{"cells":[{"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 matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\nmerchants = pd.read_csv('../input/merchants.csv')\nnew_merchant_t = pd.read_csv('../input/new_merchant_transactions.csv')\nhis_trans = pd.read_csv('../input/historical_transactions.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6fb003a0e9a70a18b6d3a7896028b74af003c5ab"},"cell_type":"code","source":"merchants = pd.read_csv('../input/merchants.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"779aa534aaf3664e11ea5cbdced0f8a42fa34cf0"},"cell_type":"code","source":"print(train.shape)\nprint(test.shape)\nprint(merchants.shape)\nprint(new_merchant_t.shape)\nprint(his_trans.shape) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5f25814e6e4cf80fb0bbe8fc1efc53d2e6f122a2"},"cell_type":"code","source":"merchants['merchant_group_id'] = merchants['merchant_group_id'].astype(object)\nmerchants['merchant_category_id'] = merchants['merchant_category_id'].astype(object)\nmerchants['subsector_id'] = merchants['subsector_id'].astype(object)\nmerchants['city_id'] = merchants['city_id'].astype(object)\nmerchants['state_id'] = merchants['state_id'].astype(object)\nmerchants['category_2'] = merchants['category_2'].astype(object)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4b0134d681e2aa7e21655f06ded186555abc2128"},"cell_type":"markdown","source":""},{"metadata":{"_uuid":"8a95234d45f796379a139db099252d57dfe54e36"},"cell_type":"markdown","source":"merchant.csv\n\n* merchant_id : Unique merchant identifier\n* merchant_group_id : Merchant group (anonymized )\n* merchant_category_id : Unique identifier for merchant category (anonymized )\n* subsector_id : Merchant category group (anonymized )\n* numerical_1 : anonymized measure\n* numerical_2 : anonymized measure\n* category_1 : anonymized category\n* most_recent_sales_range : Range of revenue (monetary units) in last active month --> A > B > C > D > E\n* most_recent_purchases_range : Range of quantity of transactions in last active month --> A > B > C > D > E\n* avg_sales_lag3 : Monthly average of revenue in last 3 months divided by revenue in last active month\n* avg_purchases_lag3 : Monthly average of transactions in last 3 months divided by transactions in last active month\n* active_months_lag3 : Quantity of active months within last 3 months\n* avg_sales_lag6 : Monthly average of revenue in last 6 months divided by revenue in last active month\n* avg_purchases_lag6 : Monthly average of transactions in last 6 months divided by transactions in last active month\n* active_months_lag6 : Quantity of active months within last 6 months\n* avg_sales_lag12 : Monthly average of revenue in last 12 months divided by revenue in last active month\n* avg_purchases_lag12 : Monthly average of transactions in last 12 months divided by transactions in last active month\n* active_months_lag12 : Quantity of active months within last 12 months\n* category_4 : anonymized category\n* city_id : City identifier (anonymized )\n* state_id : State identifier (anonymized )\ncategory_2 : anonymized category"},{"metadata":{"trusted":true,"_uuid":"35136f021c77405acd11cb53c2977aece6a09965"},"cell_type":"code","source":"merchants.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d1b6708eb3da98de40c208f3d9d838a3af9d8c19"},"cell_type":"code","source":"merchants.head(10)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ab48386fc5b60a80d10e6ea6013df7047a948e9a"},"cell_type":"markdown","source":"먼저 numerical_1 과 numerical_2 변수에 대해서 살펴보자"},{"metadata":{"trusted":true,"_uuid":"101361d9f4238b2dd76ff0670cd95e97348a92de"},"cell_type":"code","source":"merchants['numerical_1'].describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"77ec1ead1ca92da1273a550b053d3cc6147b1692"},"cell_type":"code","source":"f, ax = plt.subplots(figsize=(10, 8))\nsns.distplot(merchants['numerical_1'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5406e9361b261baf4b9446559f3c01dd3ca233a7"},"cell_type":"code","source":"merchants['numerical_2'].describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"658876af0788b68fe128468389ee8eb99133182e"},"cell_type":"code","source":"f, ax = plt.subplots(figsize=(10, 8))\nsns.distplot(merchants['numerical_2'])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cde5a8abd0ef26acc7c9892a67dfae905815de98"},"cell_type":"markdown","source":"numerical_1,2 모두 0.057471 이라는 값을 매우 많이 가지고 있다.\n해당 값의 의미를 살펴보기 위해 특정한 값을 가지는 행들만 하나씩 꺼내어 보았다.\n\n실패\n\nanonymized measure 이라는 데 무슨 의미를 가지고 있는지.."},{"metadata":{"trusted":true,"_uuid":"e847b1e61026857ccecb748e7690deab2bcd2b8b"},"cell_type":"code","source":"fig, ax = plt.subplots(1, 3, figsize = (16, 6));\nmerchants['category_1'].value_counts().sort_index().plot(kind='bar', ax=ax[0], color='teal', title='Anonymized_Category_1')\nmerchants['category_4'].value_counts().sort_index().plot(kind='bar', ax=ax[1], color='blue', title='Anonymized_Category_4')\nmerchants['category_2'].value_counts().sort_index().plot(kind='bar', ax=ax[2], color='red', title='Anonymized_Category_2')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0766bd3ff3c0dabc3fd8c004be74a5d89beb2485"},"cell_type":"markdown","source":"category_4는 merchants.csv에만 존재하므로 제외하고 category_1부터 살펴보기로 한다."},{"metadata":{"trusted":true,"_uuid":"af19ab650f24c4a866fbf211c07fcc310052e827"},"cell_type":"code","source":"merchants[merchants['category_1']=='Y'].head(30)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a1f98763feae65838ac2d1f47ba027db36996e46"},"cell_type":"code","source":"merchants[merchants['category_1']=='Y'].state_id.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f5959d8f6c2b95435f8a5c855588d9d66e5218d9"},"cell_type":"code","source":"merchants[merchants['category_1']=='Y'].category_2.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7520e9119798d7adbb90675a4eb3c5b33bc557ed"},"cell_type":"code","source":"merchants[merchants['category_1']=='Y'].city_id.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"497c943de3972af2159f852a08bee035ef98bb0b"},"cell_type":"code","source":"merchants[merchants['state_id']== -1].city_id.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"26d710541bd5b1c600d5458044893e34376270cd"},"cell_type":"code","source":"merchants[merchants['city_id']== -1].state_id.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3e5730c55b94679d4c9eb30d61344867d733d45e"},"cell_type":"code","source":"merchants[merchants['category_2'].isnull()].state_id.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8c0182cad5e635ecd002ea8ed1d94b6cdd032fe0"},"cell_type":"markdown","source":"category_1 의 경우, Y라고 나와 있는 것은 state_id, city_id 가 모두 -1이며 category_2 가 NaN임을 확인할 수 있었다.\n\n확인 결과, category_2를 모르는 경우, state_id 및 city_id는 모두 -1 이다.\nstate_id가 -1인 경우에는 category_2는 nan이 아닐 수 있으나 city_id는 무조건 -1이다.\n\ncity_id 와 state_id, 그리고 category_2는 위치와 관련된 카테고리 인데, category_2는 state_id의 상위 개념이라고 볼 수 있다.\n\n즉 -1은 위치를 모르는 것을 의미하며, category_1과 category_2는 위치와 관련된 카테고리 임을 확인할 수 있었다.\n\n또한 category_2는 국가를 의미하는 것으로 가정한다.\n\n국가 별로 최근 수익 또는 지난 lag 3 6 12의 차이를 가지고 있는지 보도록 한다."},{"metadata":{"trusted":true,"_uuid":"0199b10cb3c612a1fceae519e0a8b97fb4023685"},"cell_type":"code","source":"data1 = merchants[merchants['category_2']==1]\ndata2 = merchants[merchants['category_2']==2]\ndata3 = merchants[merchants['category_2']==3]\ndata4 = merchants[merchants['category_2']==4]\ndata5 = merchants[merchants['category_2']==5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"aa5d101376c10e87d4d38ada071fbd8d23ea15b6"},"cell_type":"code","source":"fig, ax = plt.subplots(5, 3, figsize = (16, 21));\ndata1['avg_sales_lag3'].value_counts().sort_index().plot(kind='hist', ax=ax[0][0], color='teal', title='3_Month');\ndata1['avg_sales_lag6'].value_counts().sort_index().plot(kind='hist', ax=ax[0][1], color='brown', title='6_Month');\ndata1['avg_sales_lag12'].value_counts().sort_index().plot(kind='hist', ax=ax[0][2], color='blue', title='12_Month');\ndata2['avg_sales_lag3'].value_counts().sort_index().plot(kind='hist', ax=ax[1][0], color='teal', title='3_Month');\ndata2['avg_sales_lag6'].value_counts().sort_index().plot(kind='hist', ax=ax[1][1], color='brown', title='6_Month');\ndata2['avg_sales_lag12'].value_counts().sort_index().plot(kind='hist', ax=ax[1][2], color='blue', title='12_Month');\ndata3['avg_sales_lag3'].value_counts().sort_index().plot(kind='hist', ax=ax[2][0], color='teal', title='3_Month');\ndata3['avg_sales_lag6'].value_counts().sort_index().plot(kind='hist', ax=ax[2][1], color='brown', title='6_Month');\ndata3['avg_sales_lag12'].value_counts().sort_index().plot(kind='hist', ax=ax[2][2], color='blue', title='12_Month');\ndata4['avg_sales_lag3'].value_counts().sort_index().plot(kind='hist', ax=ax[3][0], color='teal', title='3_Month');\ndata4['avg_sales_lag6'].value_counts().sort_index().plot(kind='hist', ax=ax[3][1], color='brown', title='6_Month');\ndata4['avg_sales_lag12'].value_counts().sort_index().plot(kind='hist', ax=ax[3][2], color='blue', title='12_Month');\ndata5['avg_sales_lag3'].value_counts().sort_index().plot(kind='hist', ax=ax[4][0], color='teal', title='3_Month');\ndata5['avg_sales_lag6'].value_counts().sort_index().plot(kind='hist', ax=ax[4][1], color='brown', title='6_Month');\ndata5['avg_sales_lag12'].value_counts().sort_index().plot(kind='hist', ax=ax[4][2], color='blue', title='12_Month');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"757ed314847bf8f8f664ecd96d8772bedee13616"},"cell_type":"code","source":"fig, ax = plt.subplots(5, 2, figsize = (16, 21));\ndata1['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][0], color='teal', title='most_recent_sales_range');\ndata1['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][1], color='teal', title='most_recent_purchases_range');\ndata2['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][0], color='teal', title='most_recent_sales_range');\ndata2['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][1], color='teal', title='most_recent_purchases_range');\ndata3['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][0], color='teal', title='most_recent_sales_range');\ndata3['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][1], color='teal', title='most_recent_purchases_range');\ndata4['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[3][0], color='teal', title='most_recent_sales_range');\ndata4['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[3][1], color='teal', title='most_recent_purchases_range');\ndata5['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[4][0], color='teal', title='most_recent_sales_range');\ndata5['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[4][1], color='teal', title='most_recent_purchases_range');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ba0611b07e8ad69e5b81a8ffdc2658cac3764971"},"cell_type":"code","source":"fig, ax = plt.subplots(1, 3, figsize = (16, 6));\ndata1['avg_sales_lag3'].value_counts().sort_index().plot(kind='hist', ax=ax[0], color='teal', title='3_Month');\ndata1['avg_sales_lag6'].value_counts().sort_index().plot(kind='hist', ax=ax[1], color='brown', title='6_Month');\ndata1['avg_sales_lag12'].value_counts().sort_index().plot(kind='hist', ax=ax[2], color='blue', title='12_Month');","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"90c47d2ce4f8616960c7e062db1e75597882ddbe"},"cell_type":"markdown","source":"국가별로 최근 수익 및 lag 3 6 12 를 살펴본 결과, category_2가 1 > 5 > 3 > 4 > 2 순으로 상인들이 존재한다...\nlag 3 6 12는 유의미한 차이를 보이지는 않는 것으로 보인다.\n\ncategory_2와 city_id, state_id를 활용한 위치 변수를 만들어서 활용할 수는 있겠지만, 이 것이 소비자의 loyalty를 계산하는 데에 있어서 유의미한 결과를 가져올 것으로 보이지는 않는다.\n\n그래도 한번 활용해 본다면"},{"metadata":{"trusted":true,"_uuid":"9a5e6bb048d656c6a5452ed97f76fb134468b8ab"},"cell_type":"code","source":"merchants['location'] = merchants['category_1'].astype(str) + '_' + merchants['category_2'].astype(str) + '_' + merchants['state_id'].astype(str) + '_' + merchants['city_id'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"eb57fd59cc273b243835436e9c914f6cc02875a9"},"cell_type":"markdown","source":""},{"metadata":{"trusted":true,"_uuid":"35d2f325a37c3a2c3f5a465e5cdddc4cfbbe0662"},"cell_type":"code","source":"merchants.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"05067067275252d4a1257ce5954e6e37fcb46156"},"cell_type":"markdown","source":"merchant_id에 한꺼번에 붙여서 merchant_id로 사용하는 것도 나쁘지 않아 보인다.\n큰 의미는 없어 보임."},{"metadata":{"_uuid":"306fafe2feded439be9edab6e8edefc6c43dd67c"},"cell_type":"markdown","source":"주영이의 커널을 받아서 변수를 생성해본다."},{"metadata":{"_uuid":"9e1ec156852673124acac19d26bcece5a9e34b6c"},"cell_type":"markdown","source":"먼저 성실도에 대한 변수를 생성한다."},{"metadata":{"trusted":true,"_uuid":"38529af283dee097bf1612ade9021c54f982f8f4"},"cell_type":"code","source":"fig, ax = plt.subplots(1, 3, figsize = (16, 6));\nmerchants['active_months_lag3'].value_counts().sort_index().plot(kind='bar', ax=ax[0], color='teal', title='3_Month');\nmerchants['active_months_lag6'].value_counts().sort_index().plot(kind='bar', ax=ax[1], color='brown', title='6_Month');\nmerchants['active_months_lag12'].value_counts().sort_index().plot(kind='bar', ax=ax[2], color='blue', title='12_Month');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"79e6f7369167a66644dafe5cdef2b8a4d978a1df"},"cell_type":"code","source":"y1 = merchants.loc[merchants['active_months_lag3']==3]\ny2 = merchants.loc[merchants['active_months_lag6']==6]\ny3 = merchants.loc[merchants['active_months_lag12']==12]\nx1 = merchants.loc[merchants['active_months_lag3']!=3]\nx2 = merchants.loc[merchants['active_months_lag6']!=6]\nx3 = merchants.loc[merchants['active_months_lag12']!=12]","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4263a93f2274897f151d23d7fff10c70e5d3a271"},"cell_type":"markdown","source":"x1, x2, x3은 타 상인들에 비해 성실도가 낮은 것이고 y1, y2, y3은 타 상인들에 비해 성실도가 높은 것들이다.\n\n해당 상점들의 최근 수익 및 거래량의 등급을 비교해본다."},{"metadata":{"trusted":true,"_uuid":"cc28dc6c6623bbf23071a1b451225aa5c74b1cce"},"cell_type":"code","source":"fig, ax = plt.subplots(3, 4, figsize = (16, 21));\ny1['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][0], color='teal', title='most_recent_sales_range');\ny1['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][1], color='teal', title='most_recent_purchases_range');\nx1['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][2], color='teal', title='most_recent_sales_range');\nx1['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][3], color='teal', title='most_recent_purchases_range');\n\ny2['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][0], color='teal', title='most_recent_sales_range');\ny2['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][1], color='teal', title='most_recent_purchases_range');\nx2['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][2], color='teal', title='most_recent_sales_range');\nx2['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][3], color='teal', title='most_recent_purchases_range');\n\ny3['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][0], color='teal', title='most_recent_sales_range');\ny3['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][1], color='teal', title='most_recent_purchases_range');\nx3['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][2], color='teal', title='most_recent_sales_range');\nx3['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][3], color='teal', title='most_recent_purchases_range');","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"211103dcd5ea592da53cbc0809aa917bd21bc9f2"},"cell_type":"markdown","source":"꽤나 유의한 차이를 보인다.\n\n12개월 이내 한번이라도 쉬었던 상인과 같은 경우에 A가 거의 없다.\n\n특히, 최근 3개월 내 성실하지 못했던 경우, A B가 거의 없다. B, C 또한 매우 낮은 것을 볼 수 있다.\n\n어느정도 유의미한 변수가 될 수 있을 것이라고 보인다.\n\n조금 더 자세하게 점수를 부여하기 위해서 x3내의 11가지의 경우를 모두 비교해본다.\n\nx1과 x2의 경우를 살펴보지 않는 이유는 active변수가 0인 경우가 없기 때문이다.\n예를 들어 12개월 동안 1개월을 일을 한 상인은, 무조건 3개월 이내에 해당 1개월이 존재해야만 한다.\n같은 논리로 12개월에 5개월을 일한 상인 또한 6개월간 5개월을 일했어야 한다.\n\n따라서, 아래의 x3_6~x3_11은 6개월 동안은 일을 연속적으로 한 상인이라는 결론이 도출 된다.\n\n결국 active_month 변수는 최근 3개월, 6개월, 12개월 동안 연속적으로 일을 한 상점을 구분하는 변수라고도 이해할 수 있다."},{"metadata":{"trusted":true,"_uuid":"9d5683bd9477c29511eb522ee144fb1e6ca04c9e"},"cell_type":"code","source":"x3_1 = merchants.loc[merchants['active_months_lag12']==1]\nx3_2 = merchants.loc[merchants['active_months_lag12']==2]\nx3_3 = merchants.loc[merchants['active_months_lag12']==3]\nx3_4 = merchants.loc[merchants['active_months_lag12']==4]\nx3_5 = merchants.loc[merchants['active_months_lag12']==5]\nx3_6 = merchants.loc[merchants['active_months_lag12']==6]\nx3_7 = merchants.loc[merchants['active_months_lag12']==7]\nx3_8 = merchants.loc[merchants['active_months_lag12']==8]\nx3_9 = merchants.loc[merchants['active_months_lag12']==9]\nx3_10 = merchants.loc[merchants['active_months_lag12']==10]\nx3_11 = merchants.loc[merchants['active_months_lag12']==11]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"95642c65cecf94e76385ccb4c1e7a4ad01553fad"},"cell_type":"code","source":"fig, ax = plt.subplots(11, 2, figsize = (16, 40));\nx3_1['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][0], color='teal', title='most_recent_sales_range');\nx3_1['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][1], color='teal', title='most_recent_purchases_range');\nx3_2['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][0], color='teal', title='most_recent_sales_range');\nx3_2['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][1], color='teal', title='most_recent_purchases_range');\nx3_3['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][0], color='teal', title='most_recent_sales_range');\nx3_3['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[2][1], color='teal', title='most_recent_purchases_range');\nx3_4['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[3][0], color='teal', title='most_recent_sales_range');\nx3_4['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[3][1], color='teal', title='most_recent_purchases_range');\nx3_5['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[4][0], color='teal', title='most_recent_sales_range');\nx3_5['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[4][1], color='teal', title='most_recent_purchases_range');\nx3_6['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[5][0], color='teal', title='most_recent_sales_range');\nx3_6['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[5][1], color='teal', title='most_recent_purchases_range');\nx3_7['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[6][0], color='teal', title='most_recent_sales_range');\nx3_7['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[6][1], color='teal', title='most_recent_purchases_range');\nx3_8['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[7][0], color='teal', title='most_recent_sales_range');\nx3_8['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[7][1], color='teal', title='most_recent_purchases_range');\nx3_9['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[8][0], color='teal', title='most_recent_sales_range');\nx3_9['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[8][1], color='teal', title='most_recent_purchases_range');\nx3_10['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[9][0], color='teal', title='most_recent_sales_range');\nx3_10['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[9][1], color='teal', title='most_recent_purchases_range');\nx3_11['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[10][0], color='teal', title='most_recent_sales_range');\nx3_11['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[10][1], color='teal', title='most_recent_purchases_range');","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e67c74bb77d78b32755a3d49fb229e1fa5e90c67"},"cell_type":"markdown","source":"개월 수 별로 보았을 때에는 11개월을 일한 상인 또한 A를 받지 못한 것으로 보아 큰 의미가 없다.\n\n따라서 지난 12개월 연속으로 일한 상점 \n\n6개월만을 연속적으로 일한 상점(12개월 연속 제외)\n\n3개월만을 연속적으로 일한 상점(6, 12개월 연속 제외)\n\n그리고 지난 3개월동안 한번이라도 쉬었던 상점을 비교해본다."},{"metadata":{"trusted":true,"_uuid":"713f2851c707f48c528bf3be72e65eb2867b2316"},"cell_type":"code","source":"x4_1 = merchants.loc[merchants['active_months_lag12']==12]\nx4_2 = merchants.loc[merchants['active_months_lag6']==6]\nx4_2 = x4_2.loc[merchants['active_months_lag12']!=12]\nx4_3 = merchants.loc[merchants['active_months_lag3']==3]\nx4_3 = x4_3.loc[merchants['active_months_lag6']!=6]\nx4_4 = merchants.loc[merchants['active_months_lag3']!=3]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"25b65d9116c75bac90ec95ec44e8637162d5d180"},"cell_type":"code","source":"fig, ax = plt.subplots(2, 4, figsize = (16, 16));\nx4_1['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][0], color='teal', title='most_recent_sales_range');\nx4_1['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][0], color='teal', title='most_recent_purchases_range');\nx4_2['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][1], color='teal', title='most_recent_sales_range');\nx4_2['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][1], color='teal', title='most_recent_purchases_range');\nx4_3['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][2], color='teal', title='most_recent_sales_range');\nx4_3['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][2], color='teal', title='most_recent_purchases_range');\nx4_4['most_recent_sales_range'].value_counts().sort_index().plot(kind='bar', ax=ax[0][3], color='teal', title='most_recent_sales_range');\nx4_4['most_recent_purchases_range'].value_counts().sort_index().plot(kind='bar', ax=ax[1][3], color='teal', title='most_recent_purchases_range');","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"db6232c1a509ef8ea1a8ec0e8d9881f85473edf5"},"cell_type":"markdown","source":"성실도 변수 부분에서는 12개월동안 단 한번이라도 쉰 경우, 12개월 연속으로 일한 상인에 비해 낮은 점수를 받는다는 것을 알 수 있다.\n\n일하지 않았던 개월 수에는 크게 영향을 받지 않았고,\n\n최근 3개월 내에 쉰 경험이 있는 경우 조금 더 낮은 등급을 받는다는 것을 알 수 있었다.\n\n변수를 생성하자면, 연속적으로 일한 상인과, 아닌 상인을 분류하는 것이 가장 유의미할 것으로 보인다.\n\n주영이의 도움으로 코드 완성.\n\nY는 12개월 동안 열심히 일한 상인들이며, N은 12개월 중 한번이라도 쉰 상인들이다.\n\n그래프를 눈대중으로 보고 의미를 파악하여 변수를 생성한 것으로, 논의가 필요해 보인다."},{"metadata":{"trusted":true,"_uuid":"43310cde99ad9cb3e9c2d4b3367df1859ec539f9"},"cell_type":"code","source":"merchants[\"consistency\"] = \"Y\"\nmerchants.loc[merchants[\"active_months_lag12\"]!=12,\"consistency\"]= \"N\"\n\nmerchants.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4cb303b103cf63ea5a31a1d00f5270fdc5a877b8"},"cell_type":"markdown","source":""},{"metadata":{"_uuid":"4568c674f651cc0ca2dd593133fccbc4fcbdf7f9"},"cell_type":"markdown","source":"다음은 avg 변수들에 대해 살펴본다.\n\n주영이것을 참조했다.\n\n지난 3, 6 12 개월간의 평균 수입을 가장 최근 달로 나눈 값이다.\n\n*이것은 즉 과거 n 개월 대비 최근의 성과가 어떠한지를 나타내는 변수라고 할 수 있다. 양수이고, 값이 낮으면 낮을 수록 과거에 비해 최근 성과가 좋은 것을 의미한다.\n\n일반적으로는 지난 평균기간 동안의 수입들의 변화가 크지 않다면 1에 가까울 것이다.\n\n실제로 3, 6, 12 개월 모두 중위값이 1에 가까운 것을 위에서 확인할 수 있다. 하지만 최대 8000에 해당하는 아웃라이어 종종 존재하는데 이러한 변수들에 대한 처리가 필요해 보인다."},{"metadata":{"trusted":true,"_uuid":"8a90d2766c07cb02a1fc76c7a786c41f27f75ea9"},"cell_type":"code","source":"print(merchants[merchants.avg_sales_lag3>10].shape[0])\nprint(merchants[merchants.avg_sales_lag6>10].shape[0])\nprint(merchants[merchants.avg_sales_lag12>10].shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"092b082a454ecc271a64925e098ceb8063ec458b"},"cell_type":"code","source":"# 최근\nprint((merchants[(merchants.avg_sales_lag3>10)&(merchants.most_recent_sales_range!=\"E\")].shape)[0])\nprint((merchants[(merchants.avg_sales_lag6>10)&(merchants.most_recent_sales_range!=\"E\")].shape)[0])\nprint((merchants[(merchants.avg_sales_lag12>10)&(merchants.most_recent_sales_range!=\"E\")].shape)[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"eaec8eb43274c2c16f71a51babbc19013bd32826"},"cell_type":"code","source":"f, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_sales_range', y=\"avg_sales_lag3\", data=merchants)\nplt.xlabel(\"most_recent_sales_range\")\nplt.ylabel(\"avg_sales_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"459098d34609515f9c47b46cf080ff0270cd105a"},"cell_type":"code","source":"f, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_sales_range', y=\"avg_sales_lag6\", data=merchants)\nplt.xlabel(\"most_recent_sales_range\")\nplt.ylabel(\"avg_sales_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f7c8a98bd987db80946c771010501c8c6bb85bfb"},"cell_type":"markdown","source":"위의 그래프를 보면 알 수 있듯이 비정상적으로 높은 수치를 갖고 있는 \"avg_sales_lag\"변수들은 지난달의 판매량이 낮은 분위에 속해있는 경우에만 해당되는 것을 확인할 수 있다. 지난달 판매액이 A,B,C,D 분위에 해당하는 관측값의 경우에는 크게 오버슈팅하지 않는 것을 확인할 수 있다."},{"metadata":{"_uuid":"3511c36a2bee80818ac3728626c12d4f8cdce8ed"},"cell_type":"markdown","source":"*즉, 이 변수의 이상치들은 '과거에 비해 최근에 실적이 매우 부진해진 merchant'를 의미한다고 할 수 있다.\n\n**일정 분위수 이상의 값들에 winsorizing 처리를 하는 것이 효과적일 것으로 보인다."},{"metadata":{"_uuid":"0f18c12e29d2d8675e76755baf0a7c74e4f89411"},"cell_type":"markdown","source":"오버슈팅 하는 것들을 제외하고 그래프를 한번 그려본다."},{"metadata":{"trusted":true,"_uuid":"43b71be131b914c74fad29967805a0fcdb7845e1"},"cell_type":"code","source":"merchants_no = merchants.loc[merchants['avg_sales_lag3']<100]\n\nf, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_sales_range', y=\"avg_sales_lag3\", data=merchants_no)\nplt.xlabel(\"most_recent_sales_range\")\nplt.ylabel(\"avg_sales_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9acd6b250f24f80eab4e8a281760ae7aa6ee19f5"},"cell_type":"code","source":"merchants[merchants['avg_sales_lag3']<0]","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c831848ead9a9a84809045d328fe80081df2be5d"},"cell_type":"markdown","source":"avg_sales_lag3이 음수가 되는 3개의 상인을 발견할 수 있었다.\n\n빚을 진 게 아닌가 싶다.\n\n\navg_sales_lag3은 3개월간의 수익의 평균을 지난 달의 수익으로 나눈 것이다.\n\n지난 3개월에 비해 성장했다고 한다면, 1보다 작을 것이고, 지난 3개월에 비해 수익이 적다고 하면 1보다 클 것이다."},{"metadata":{"trusted":true,"_uuid":"06c3a0208562e7cc0dea34b8826f36b68d2e0a21"},"cell_type":"code","source":"merchants_no = merchants.loc[merchants['avg_sales_lag3']<1]\nmerchants_no = merchants_no.loc[merchants_no['avg_sales_lag3']>=0]\n\nf, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_sales_range', y=\"avg_sales_lag3\", data=merchants_no)\nplt.xlabel(\"most_recent_sales_range\")\nplt.ylabel(\"avg_sales_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"aaa2db6b003b7b8e166232317726e8b2a853f50c"},"cell_type":"code","source":"merchants_no = merchants.loc[merchants['avg_sales_lag3']>1]\nmerchants_no = merchants_no.loc[merchants_no['avg_sales_lag3']<12.5]\n\nf, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_sales_range', y=\"avg_sales_lag3\", data=merchants_no)\nplt.xlabel(\"most_recent_sales_range\")\nplt.ylabel(\"avg_sales_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6b2a3a5e40ba2aa2646a038a17783908353be7f8"},"cell_type":"markdown","source":"첫번째 그래프와 두번째 그래프를 결합하여본다면, A, B, C, D, E 가 부여되는 기준은 꽤나 종합적인 점수라고 보인다.\n\nA로 갈 수록 그래프의 모습이 1에 수렴하는 것을 볼 수 있다. 하지만 단계적으로 부여되어 있지는 않다.\n\n즉, A로 갈 수록 타 등급에 비해 훨씬 안정적인 상인들의 집합이라는 것을 알 수 있었다.\n\n하지만 B C D E에도 A 와 같은 점수를 가지고 있는 것들이 존재한다. (단계적으로 부여된 것이 아니다.)\n\n그렇다면, 등급이 안정성으로만 부여된 것이 아니라, 수익 총량이나 다른 것들까지 고려하여 부여된 것으로 보인다."},{"metadata":{"_uuid":"b4c4b91277a64fcf9e6b5482b7a08261ddb3f791"},"cell_type":"markdown","source":""},{"metadata":{"trusted":true,"_uuid":"5962ec94bce4e34c9c51faa93311ca580204d15e"},"cell_type":"code","source":"merchants[merchants==np.inf].count()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4ed2cf141c4cfa08329e81245c2c6220a55701e8"},"cell_type":"code","source":"#data2 : not infinite variables in avg_purchases_lag\ndata2 = merchants.loc[merchants[\"avg_purchases_lag3\"]!=np.inf,]\nprint(data2['avg_purchases_lag3'].describe())\nprint(data2['avg_purchases_lag6'].describe())\nprint(data2['avg_purchases_lag12'].describe())        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bdaa864d3c9f466e670d44c3a345e330e5eed266"},"cell_type":"code","source":"f, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_purchases_range', y=\"avg_purchases_lag3\", data=data2)\nplt.xlabel(\"most_recent_purchases_range\")\nplt.ylabel(\"avg_purchases_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d78f66965b04d110dc8661a53f0ed7bceabd12d6"},"cell_type":"markdown","source":"주영이의 분석과 같이 특별한 이상치가 많이 존재하는 것은 아니지만, 저기 저 보이는 불편한 점이 하나 있다. 이번 달에 스캔들이라도 터졌나보다. 확인 후 바로 제외한다."},{"metadata":{"trusted":true,"_uuid":"d8872a3f02d552001b2600c314655e07e8048573"},"cell_type":"code","source":"merchants[merchants['avg_purchases_lag3']>50000]","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6572b3ff0d04f29c7e5a658192aeee36078bff08"},"cell_type":"markdown","source":"해당 값이 purchases 3 6 12 의 max를 모두 차지하고 있다."},{"metadata":{"trusted":true,"_uuid":"134ebe76968d73244e35cc0922e9c70df0584478"},"cell_type":"code","source":"data2 = merchants.loc[merchants[\"avg_purchases_lag3\"]<10000]\nprint(data2['avg_purchases_lag3'].describe())\nprint(data2['avg_purchases_lag6'].describe())\nprint(data2['avg_purchases_lag12'].describe())        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a9e1c10e5bbfd20de03d076b70cdb693c8c4c7f2"},"cell_type":"code","source":"f, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_purchases_range', y=\"avg_purchases_lag3\", data=data2)\nplt.xlabel(\"most_recent_purchases_range\")\nplt.ylabel(\"avg_purchases_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3aa8059b3626f06cb650cb4b743f3e9995131704"},"cell_type":"markdown","source":"편...안..\npurchases 에서는 음수가 존재하지 않는다. 위에서 확인했던 음수였던 것들도 팔긴 팔았나보다."},{"metadata":{"trusted":true,"_uuid":"ad2154b36b5b2dad2ae4f7dadd2e14904bacbe89"},"cell_type":"code","source":"data2_no = data2.loc[merchants['avg_purchases_lag3']<1]\n\nf, ax = plt.subplots(figsize=(8, 6))\nplt.scatter(x='most_recent_purchases_range', y=\"avg_purchases_lag3\", data=data2_no)\nplt.xlabel(\"most_recent_purchases_range\")\nplt.ylabel(\"avg_purchases_lag3\")\nplt.show","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"056f87e9d9a38c437d4ea0ed902a544ae0666331"},"cell_type":"markdown","source":"해당 값 또한 1에 수렴하고 있다. 이는 most_recent_purchases_range 와 most_recent_sales_range의 두 변수 모두 안정성을 포함한 점수를 부여한다는 것을 알 수 있다."},{"metadata":{"_uuid":"45e2b5761627b07e067fc54768074a0fa6abff98"},"cell_type":"markdown","source":"Merchants.csv를 train에 결합시키기에는 확실한 근거가 존재해보이지는 않는다.\n\nsales와 purchases 변수들과 같은 경우, 명확하게 등급이 부여된 근거를 찾기에는 데이터의 종류가 부족하다.\n\ncatgory 1, 2 그리고 city_id state_id와 같은 경우, 위치를 나타내는 변수들인데, 위치에 관련하여 큰 차이를 보이고 있지 않아, target에 많은 영향을 끼칠 것으로 보이지는 않는다.\n\n개인적으로 가장 유의미해 보이는 변수는 성실도와 관련한 부분으로 조금만 더 깊게 변수를 생성할 수 있다면, 유의미한 결과가 나타날 것으로 보인다."},{"metadata":{"_uuid":"1911c0baeb7ee3cedd20ddc116d44d968c1bcf60"},"cell_type":"markdown","source":"주영이와 토의 결과.\n\navg와 most는 다른 의미로서 작성된 변수일 가능성이 존재한다.\n\n따라서 다른 의미를 가지고 있다고 생각하여, 이 둘의 변수를 섞어서 변수를 생성하는 방안에 대해 생각해 볼 수 있을 것이다.\n\n예를 들어, most에서 A를 받고, avg에서 낮은 점수 ( 이번 달에 잘했다. ) 를 category 별로 변수를 생성하여 등급을 조금 더 자세하게 쪼개는 것이다.\nE를 받고, avg에서 낮은 점수 또는 높은 점수를 받은 상인 또한 이런 식으로 등급을 부여할 수 있을 것이다.\n\n이 변수를 category로 부여할 것인지 또는 점수로 환산해서 ( 예를 들어, most의 등급을 숫자로 환산하는 식 ? )\n\n어떤 방식이 나을 지 고민"}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}