{"cells":[{"metadata":{},"cell_type":"markdown","source":"Лабораторная работа 3.\n\nОбучить и сравнить качество нескольких предсказательных моделей в задаче регрессии. В лабораторной работе рассматривается задача предсказания выручки с каждого клиента магазина Gstore. Данные и подробное описание задачи может быть найдено тут https://www.kaggle.com/c/ga-customer-revenue-prediction/data (файл train.csv). При необходимости для ускорения процесса обучения можно взять только 10% случайных (!) строк данных. \n\nЗадачи данной лабораторной работы:\n- подобрать признаки (не менее 10, в т.ч. не менее 5 расчётных, отсутсвующих в данных явно), которые могут помочь в построении модели. По каждому расчитаному признаку пояснить, почему этот признак может быть важен. \n- обучить несколько классических моделей машинного обучения для задачи регрессии, включая GBM на дереьвях решений, лес решений, SVM, линейная регрессия. Зависимая переменная – логарифм от выручки с клиента \n- настроить гиперпараметры моделей. \n- с помощью 5-fold кросс валидации посчитать среднее качество каждой из моделей. \n- с помощью 20 случайных разбиений оценить дисперсию оценки каждой из моделей. \n- визуализировать полученные распределения метрик качества каждой из модели с помощью boxplotов, также отразить посчитанное ранее среднее качество."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport json","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#Считаем файл:\ndata = pd.read_csv(\"../input/ga-customer-revenue-prediction/train.csv\", converters={'device': json.loads, 'geoNetwork': json.loads, 'totals': json.loads, 'trafficSource': json.loads}).sample(frac=0.2)\n\n#Считаем столбцы в json'e:\ndevice = pd.DataFrame(data['device'].tolist()).filter(items=['browser', 'isMobile', 'operatingSystem', 'deviceCategory'])\ngeoNetwork = pd.DataFrame(data['geoNetwork'].tolist()).filter(items=['continent', 'subContinent', 'country', 'region', 'metro', 'city', 'networkDomain'])\ntotals = pd.DataFrame(data['totals'].tolist())\ntrafficSource = pd.DataFrame(data['trafficSource'].tolist()).filter(items=['campaign', 'source', 'medium', 'keyword', 'isTrueDirect', 'referralPath', 'adContent'])\n\n#Удаляем ненужные столбцы:\ndata = data.drop(labels = ['device', 'geoNetwork', 'totals', 'trafficSource', 'sessionId', 'visitId', 'fullVisitorId'], axis='columns')\n\n#Склеим всё в один фрейм:\ndata = data.join(device).join(geoNetwork).join(totals).join(trafficSource)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Подготовка данных:\nint_cols = ['visits', 'hits', 'pageviews', 'bounces', 'newVisits', 'transactionRevenue']\nbool_cols = ['isTrueDirect']\nstring_cols = ['channelGrouping', 'deviceCategory', 'region', 'metro', 'city']\nfor col in int_cols:\n    data[col].fillna(0, inplace=True)\nfor col in bool_cols:\n    data[col].fillna(False, inplace=True)\nfor col in string_cols:\n    data[col].fillna('(not set)')\n    data.replace({ col: { 'not available in demo dataset': '(not set)'}})\n    \ndata['socialEngagementType'] = data['socialEngagementType'] == 'Engaged'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor\nfrom sklearn.svm import SVR\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split, KFold, cross_val_score\n\ny = data['transactionRevenue']\nx = data.filter(items = ['visits', 'hits', 'pageviews', 'bounces', 'newVisits'])\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"models = [GradientBoostingRegressor(), RandomForestRegressor(), LinearRegression()]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Result = pd.DataFrame()\ntmp = pd.DataFrame()\n\n#Кросс-валидация:\nfor model in models:\n    model_name = str(model)\n    scores = np.array([])\n    for i in range(10):\n        fold = KFold(n_splits=5, shuffle=True)\n        score = cross_val_score(estimator=model, X=x, y=y, cv=fold, scoring='r2')\n        scores = np.append(scores, score)\n    tmp['Оценки качества'] = pd.Series(scores)\n    tmp['Модель'] = model_name\n    Result = Result.append(tmp)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Result","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}