hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
sequence
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
sequence
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
sequence
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
sequence
cell_types
sequence
cell_type_groups
sequence
ecf9a08de31ff66ffa0afbffb3d4ec4d60ff86cf
14,392
ipynb
Jupyter Notebook
rule/Apriori.ipynb
HermitSun/ML_for_learner
501634b35fb5bad2576d5a0c3b144603ba61336c
[ "Apache-2.0" ]
81
2019-03-07T03:19:53.000Z
2022-03-12T14:19:22.000Z
rule/Apriori.ipynb
a910773203/ML_for_learner
3014c641800c1408668ff243395bde752c45ec43
[ "Apache-2.0" ]
null
null
null
rule/Apriori.ipynb
a910773203/ML_for_learner
3014c641800c1408668ff243395bde752c45ec43
[ "Apache-2.0" ]
50
2019-08-17T06:44:59.000Z
2021-12-30T05:39:44.000Z
34.348449
148
0.519872
[ [ [ "## 数据准备", "_____no_output_____" ] ], [ [ "import numpy as np\ndataset = np.array([[1, 3, 4],\n [2, 3, 5],\n [1, 2, 3, 5],\n [2, 5]])", "_____no_output_____" ] ], [ [ "## 频繁项集", "_____no_output_____" ] ], [ [ "def create_1st_itemset(dataset):\n '''\n 根据初始数据集创建单个物品的项集\n '''\n# tmp=dataset.flatten(dataset) # 当输入数据规整时可使用numpy\n# return list(map(frozenset,np.unique(tmp)))\n\n tmp = list()\n for itemset in dataset:\n for item in itemset:\n if [item] not in tmp:\n tmp.append([item])\n tmp.sort()\n return list(map(frozenset, tmp)) # frozenset可用作字典key", "_____no_output_____" ], [ "def itemset_filter(dataset, itemsets, min_sup=0.5):\n '''\n 过滤小于支持度阈值的项集,返回频繁项集与支持度\n itemsets: 项集列表\n '''\n sup_dict = dict() # 支持度字典\n\n # 先计数\n for sample in dataset: # 原数据中的项集\n for itemset in itemsets: # 项集列表中的所有项集\n if itemset.issubset(sample):\n sup_dict[itemset] = sup_dict.get(itemset, 0)+1\n\n len_data = len(dataset) # 计数/总数=支持度\n freq_sets = list() # 频繁项集列表\n\n # 计算支持度并过滤掉不合格的项集\n for itemset in sup_dict:\n sup = sup_dict[itemset]/len_data\n\n if sup >= min_sup:\n freq_sets.append(itemset)\n sup_dict[itemset] = sup\n\n return freq_sets, sup_dict", "_____no_output_____" ], [ "def extend_itemset(freq_sets):\n '''\n 根据已有的k阶频繁项集生成k+1阶项集\n freq_sets: k阶频繁项集的列表\n '''\n res = list()\n raw_size = len(freq_sets)\n\n for i in range(raw_size):\n for j in range(i+1, raw_size): # 两两组合\n # 当两项集头部都相等时,才进行合并\n head_1 = list(freq_sets[i])[:-1]\n head_2 = list(freq_sets[j])[:-1]\n if head_1 == head_2:\n res.append(freq_sets[i] | freq_sets[j])\n return res\n\n\n# itemsets_1st= create_1st_itemset(dataset)\n# freq_sets_1st,_=itemset_filter(dataset, itemsets_1st, 0.5)\n# itemsets_2nd = extend_itemset(freq_sets_1st)\n# freq_sets_2nd, _ = itemset_filter(dataset, itemsets_2nd, 0.5)\n# itemsets_3th = extend_itemset(freq_sets_2nd)\n# freq_sets_3th, _ = itemset_filter(dataset, itemsets_3th, 0.5)\n# freq_sets_3th", "_____no_output_____" ], [ "def apriori(dataset, min_sup=0.5):\n itemsets_1st = create_1st_itemset(dataset) # 构建1阶项集列表\n freq_sets_1st, sup_dict = itemset_filter(dataset, itemsets_1st, min_sup)\n\n all_freq_sets = [freq_sets_1st] # 所有的频繁项集,以阶数为分隔\n\n while len(all_freq_sets[-1]) > 0: # 不断寻找高阶频繁集,直到产生空集\n cur_itemsets = extend_itemset(all_freq_sets[-1]) # 对最后一阶频繁集升阶,产生高阶项集\n cur_freq_sets, cur_sup_dict = itemset_filter(\n dataset, cur_itemsets, min_sup)\n sup_dict.update(cur_sup_dict)\n all_freq_sets.append(cur_freq_sets)\n\n return all_freq_sets, sup_dict\n\n\n# all_freq_sets, sup_dict = apriori(dataset)", "_____no_output_____" ], [ "# all_freq_sets", "_____no_output_____" ], [ "# sup_dict", "_____no_output_____" ] ], [ [ "## 关联规则\n有了能计算频繁项集的方法,接下来就是在频繁项集中找到关联规则。为简单起见,首先计算$2$阶频繁项集可能产生的所有规则。", "_____no_output_____" ] ], [ [ "def compute_conf(freq_set, conseqs, sup_dict, min_conf=0.5):\n '''\n 计算频繁项集中所有单后果规则的置信度\n freq_set: 单个频繁项集\n conseqs: 可能的后果列表\n '''\n strong_conseqs = list() # 强后果列表,返回用于扩展高阶后果\n strong_rules = list() # 规则列表\n\n for cons in conseqs: # 计算所有可能后果的规则强度\n cur_conf = sup_dict[freq_set]/sup_dict[freq_set-cons] # 共同置信度除以前因置信度\n\n if cur_conf >= min_conf:\n # 追加(前因,后果,置信度)三元组\n strong_rules.append((freq_set-cons, cons, cur_conf))\n strong_conseqs.append(cons)\n\n return strong_rules, strong_conseqs\n\n\n# freq_set = all_freq_sets[1][0] # 2阶频繁项集列表中的首个项集\n# single_conseqs = [frozenset([item])\n# for item in freq_set] # 所有可能的1阶后果,用于查询支持度\n# compute_conf(freq_set, single_conseqs, sup_dict)", "_____no_output_____" ] ], [ [ "同频繁项集的发现一样,规则也需要扩充,并且是从后果的角度来扩充。由上述函数可以得到所有$1$阶后果的强规则,那么如何得到$2$阶后果甚至更高阶后果的强规则?需要利用```extend_itemset```函数来对已有的后果列表进行升阶,然后在高阶后果列表中取出可能的后果加入已有后果。", "_____no_output_____" ] ], [ [ "# 因为这里使用递归手段,所以有些参数和变量需要从函数中独立出来\n\n\ndef extend_rules(freq_set, conseqs, sup_dict, tol_rules, min_conf=0.5):\n conseq_dim = len(conseqs[0]) # 后果的阶数\n\n if len(freq_set) > conseq_dim+1: # 只有2阶以上的频繁项集才有可能有高阶后果\n high_level_conseqs = extend_itemset(conseqs) # 后果升阶\n cur_rules, high_level_conseqs = compute_conf(\n freq_set, high_level_conseqs, sup_dict, min_conf)\n tol_rules.extend(cur_rules)\n\n if len(high_level_conseqs) > 1:\n extend_rules(freq_set, high_level_conseqs, sup_dict,tol_rules, min_conf)\n\n\n# tol_rules = list() # 记录所有规则的列表\n# freq_set = all_freq_sets[2][0] # 3阶频繁项集列表中的首个项集\n# single_conseqs = [frozenset([item])\n# for item in freq_set]\n# extend_rules(freq_set, single_conseqs, sup_dict, tol_rules)", "_____no_output_____" ], [ "# tol_rules", "_____no_output_____" ] ], [ [ "接下来的任务就是由低阶往高阶遍历所有频繁项集列表,并发掘强规则。", "_____no_output_____" ] ], [ [ "def find_rules(all_freq_sets, sup_dict, min_conf=0.5):\n tol_rules = list()\n for i in range(1, len(all_freq_sets)): # 跳过1阶频繁项集,因为1阶项集无法产生规则\n for freq_set in all_freq_sets[i]:\n conseqs = [frozenset([item]) for item in freq_set] # 初始可能的1阶后果列表\n if i > 1:\n extend_rules(freq_set, conseqs, sup_dict, tol_rules, min_conf)\n else:\n cur_rules, _ = compute_conf(\n freq_set, conseqs, sup_dict, min_conf)\n tol_rules.extend(cur_rules)\n\n return tol_rules\n\n# find_rules(all_freq_sets,sup_dict,min_conf=0.6)", "_____no_output_____" ], [ "# all_freq_sets, sup_dict = apriori(dataset,min_sup=0.5)\n# find_rules(all_freq_sets,sup_dict,min_conf=0.5)", "_____no_output_____" ] ], [ [ "## Toydataset", "_____no_output_____" ] ], [ [ "data=[line.split() for line in open('datasets/mushroom/agaricus-lepiota.data').readlines()]\nall_freq_sets, sup_dict = apriori(data,min_sup=0.8)\nfind_rules(all_freq_sets,sup_dict,min_conf=0.8)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
ecf9a4fef0e1e5f11c3d897c50d0f4ccfcd06836
127,744
ipynb
Jupyter Notebook
SII/1-pandas-intro.ipynb
vafaei-ar/alzahra-workshop-2019
ebcc293e53de5a81379c97fff95fe24f7c67ba39
[ "MIT" ]
3
2019-11-24T13:55:16.000Z
2021-01-08T20:09:55.000Z
SII/1-pandas-intro.ipynb
vafaei-ar/alzahra-workshop-2019
ebcc293e53de5a81379c97fff95fe24f7c67ba39
[ "MIT" ]
null
null
null
SII/1-pandas-intro.ipynb
vafaei-ar/alzahra-workshop-2019
ebcc293e53de5a81379c97fff95fe24f7c67ba39
[ "MIT" ]
null
null
null
25.310878
178
0.329197
[ [ [ "# Pandas introduction", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "indices = ['a','b','c']\nmy_list = [10,20, 11]\n\ndictionry_list = {'a':10,'b':20,'c':11}", "_____no_output_____" ], [ "pd.Series(data = my_list)", "_____no_output_____" ], [ "x = pd.Series(data = my_list, index = indices)\nx['a']", "_____no_output_____" ], [ "pd.Series(dictionry_list)", "_____no_output_____" ], [ "# operation", "_____no_output_____" ], [ "ser1 = pd.Series([1,2,3,4],index = ['USA', 'Germany','USSR', 'Japan'])\nser2 = pd.Series([1,2,5,4],index = ['USA', 'Germany','Italy', 'Japan'])", "_____no_output_____" ], [ "print(type(ser1))", "<class 'pandas.core.series.Series'>\n" ], [ "ser1 + ser2", "_____no_output_____" ], [ "'A B C D E'.split()", "_____no_output_____" ], [ "'W X Y Z'.split()", "_____no_output_____" ], [ "from numpy.random import uniform", "_____no_output_____" ], [ "a = uniform(0,1,(5,4))\nb = uniform(0,1,(5,4))", "_____no_output_____" ], [ "type(a)", "_____no_output_____" ], [ "a.shape", "_____no_output_____" ], [ "a+b", "_____no_output_____" ], [ "'A B C D E'.split()", "_____no_output_____" ], [ "'W X Y Z'.split()", "_____no_output_____" ], [ "data = uniform(0,1,(5,4)).astype(np.float32)", "_____no_output_____" ], [ "data.shape", "_____no_output_____" ], [ "data.dtype", "_____no_output_____" ], [ "data = data*1", "_____no_output_____" ], [ "df = pd.DataFrame(data = data,\n index = ['A', 'B', 'C', 'D', 'E'],\n columns=['W', 'X', 'Y', 'Z'])", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "tex_form = df.to_latex()", "_____no_output_____" ], [ "df['W']", "_____no_output_____" ], [ "df.W", "_____no_output_____" ], [ "type(df['W'])", "_____no_output_____" ], [ "df[['W','Z']]", "_____no_output_____" ], [ "df['NEW'] = df['W'] + df['Y']\ndf", "_____no_output_____" ], [ "df['W'] = df['W']/np.sum(df['W'])", "_____no_output_____" ], [ "df.drop('A',axis=0)", "_____no_output_____" ], [ "df.drop('NEW',axis=1)", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df.loc['A']", "_____no_output_____" ], [ "df.iloc[2]", "_____no_output_____" ], [ "df.loc['B','Y']", "_____no_output_____" ], [ "df.loc[['A','B'],['W','Y']]", "_____no_output_____" ], [ "df.loc[:,'Y']", "_____no_output_____" ], [ "df>0.5", "_____no_output_____" ], [ "df[df>0.5]", "_____no_output_____" ], [ "df[df['W']>df['Y']]", "_____no_output_____" ], [ "df[(df['W']>0.1) & (df['Y'] > 0.7)]", "_____no_output_____" ], [ "df.reset_index()", "_____no_output_____" ], [ "newind = 'CA NY WY OR CO'.split()\nnewind", "_____no_output_____" ], [ "df['States'] = newind\ndf", "_____no_output_____" ], [ "df.set_index('States')", "_____no_output_____" ], [ "df = pd.DataFrame({'col1':[1,2,3,4],'col2':[444,555,666,444],'col3':['abc','def','ghi','xyz']})\ndf", "_____no_output_____" ], [ "df['col2'].unique()", "_____no_output_____" ], [ "df['col2'].nunique()", "_____no_output_____" ], [ "df['col2'].value_counts()", "_____no_output_____" ], [ "def times2(x):\n return 2*x", "_____no_output_____" ], [ "df['col2'] = df['col2'].apply(times2)\ndf", "_____no_output_____" ], [ "fun = lambda x:x*2", "_____no_output_____" ], [ "fun(3)", "_____no_output_____" ], [ "df['col2'] = df['col2'].apply(lambda x:x*2)\ndf", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "df.index", "_____no_output_____" ], [ "df.sort_values(by='col2') #inplace=False by default", "_____no_output_____" ], [ "df.isnull()", "_____no_output_____" ], [ "df = pd.DataFrame({'col1':[1,2,3,np.nan],\n 'col2':[np.nan,555,666,444],\n 'col3':['abc','def','ghi','xyz']})\ndf.head(2)", "_____no_output_____" ], [ "df.isnull()", "_____no_output_____" ], [ "df.dropna()", "_____no_output_____" ], [ "df.fillna('100')", "_____no_output_____" ], [ "help(df.fillna)", "Help on method fillna in module pandas.core.frame:\n\nfillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs) method of pandas.core.frame.DataFrame instance\n Fill NA/NaN values using the specified method.\n \n Parameters\n ----------\n value : scalar, dict, Series, or DataFrame\n Value to use to fill holes (e.g. 0), alternately a\n dict/Series/DataFrame of values specifying which value to use for\n each index (for a Series) or column (for a DataFrame). (values not\n in the dict/Series/DataFrame will not be filled). This value cannot\n be a list.\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed Series\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use NEXT valid observation to fill gap\n axis : {0 or 'index', 1 or 'columns'}\n inplace : boolean, default False\n If True, fill in place. Note: this will modify any\n other views on this object, (e.g. a no-copy slice for a column in a\n DataFrame).\n limit : int, default None\n If method is specified, this is the maximum number of consecutive\n NaN values to forward/backward fill. In other words, if there is\n a gap with more than this number of consecutive NaNs, it will only\n be partially filled. If method is not specified, this is the\n maximum number of entries along the entire axis where NaNs will be\n filled. Must be greater than 0 if not None.\n downcast : dict, default is None\n a dict of item->dtype of what to downcast if possible,\n or the string 'infer' which will try to downcast to an appropriate\n equal type (e.g. float64 to int64 if possible)\n \n Returns\n -------\n filled : DataFrame\n \n See Also\n --------\n interpolate : Fill NaN values using interpolation.\n reindex, asfreq\n \n Examples\n --------\n >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0],\n ... [3, 4, np.nan, 1],\n ... [np.nan, np.nan, np.nan, 5],\n ... [np.nan, 3, np.nan, 4]],\n ... columns=list('ABCD'))\n >>> df\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 NaN NaN NaN 5\n 3 NaN 3.0 NaN 4\n \n Replace all NaN elements with 0s.\n \n >>> df.fillna(0)\n A B C D\n 0 0.0 2.0 0.0 0\n 1 3.0 4.0 0.0 1\n 2 0.0 0.0 0.0 5\n 3 0.0 3.0 0.0 4\n \n We can also propagate non-null values forward or backward.\n \n >>> df.fillna(method='ffill')\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 3.0 4.0 NaN 5\n 3 3.0 3.0 NaN 4\n \n Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,\n 2, and 3 respectively.\n \n >>> values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}\n >>> df.fillna(value=values)\n A B C D\n 0 0.0 2.0 2.0 0\n 1 3.0 4.0 2.0 1\n 2 0.0 1.0 2.0 5\n 3 0.0 3.0 2.0 4\n \n Only replace the first NaN element.\n \n >>> df.fillna(value=values, limit=1)\n A B C D\n 0 0.0 2.0 2.0 0\n 1 3.0 4.0 NaN 1\n 2 NaN 1.0 NaN 5\n 3 NaN 3.0 NaN 4\n\n" ], [ "df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']},\n index=[0, 1, 2, 3])\n\ndf2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],\n 'B': ['B4', 'B5', 'B6', 'B7'],\n 'C': ['C4', 'C5', 'C6', 'C7'],\n 'D': ['D4', 'D5', 'D6', 'D7']},\n index=[4, 5, 6, 7]) \n", "_____no_output_____" ], [ "df1", "_____no_output_____" ], [ "df2", "_____no_output_____" ], [ "pd.concat([df1,df2],axis=0)", "_____no_output_____" ], [ "pd.concat([df1,df2],axis=1)", "_____no_output_____" ], [ "df3 = pd.DataFrame({'E': ['E0', 'E1', 'E2', 'E3'],\n 'F': ['F0', 'F1', 'F2', 'F3'],\n 'G': ['G0', 'G1', 'G2', 'G3'],\n 'H': ['H0', 'H1', 'H2', 'H3']},\n index=[0, 1, 2, 3])\ndf3", "_____no_output_____" ], [ "pd.concat([df1,df3],axis=1)", "_____no_output_____" ], [ "left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],\n 'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3']})\n \nright = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K4'],\n 'C': ['C0', 'C1', 'C2', 'C4'],\n 'D': ['D0', 'D1', 'D2', 'D4']}) ", "_____no_output_____" ], [ "left", "_____no_output_____" ], [ "right", "_____no_output_____" ], [ "pd.merge(left,right,how='inner',on='key')", "_____no_output_____" ], [ "pd.merge(left, right,how='outer', on=['key'])", "_____no_output_____" ], [ "pd.merge(left, right, how='right', on=['key'])", "_____no_output_____" ], [ "pd.merge(left, right, how='left', on=['key'])", "_____no_output_____" ], [ "left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],\n 'key2': ['L0', 'L1', 'L0', 'L1'],\n 'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3']})\n \nright = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],\n 'key2': ['L0', 'L1', 'L0', 'L1'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']})", "_____no_output_____" ], [ "left", "_____no_output_____" ], [ "right", "_____no_output_____" ], [ "pd.merge(left, right,how='inner', on=['key1', 'key2'])", "_____no_output_____" ], [ "pd.concat([left, right])", "/home/gf/packages/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version\nof pandas will change to not sort by default.\n\nTo accept the future behavior, pass 'sort=False'.\n\nTo retain the current behavior and silence the warning, pass 'sort=True'.\n\n \"\"\"Entry point for launching an IPython kernel.\n" ], [ "data = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'],\n 'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'],\n 'Sales':[200,120,340,124,243,350]}", "_____no_output_____" ], [ "df = pd.DataFrame(data)\ndf", "_____no_output_____" ], [ "by_comp = df.groupby(\"Company\")", "_____no_output_____" ], [ "by_comp", "_____no_output_____" ], [ "by_comp.mean()", "_____no_output_____" ], [ "by_comp.std()", "_____no_output_____" ], [ "by_comp.min()", "_____no_output_____" ], [ "by_comp.count()", "_____no_output_____" ], [ "by_comp.describe()", "_____no_output_____" ], [ "# Save and load", "_____no_output_____" ], [ "df = pd.DataFrame({'col1':[1,2,3,4],'col2':[444,555,666,444],'col3':['abc','def','ghi','xyz']})\ndf", "_____no_output_____" ], [ "df.to_csv('example.csv',index=False)", "_____no_output_____" ], [ "df = pd.read_csv('example.csv')", "_____no_output_____" ], [ "df", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecf9a99e13e1189af8350a63629da394673131d1
89,908
ipynb
Jupyter Notebook
intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb
natashk/Udacity-PyTorch-Challenge
c614da84b85ba4b4072e688ea4ff78a5d17a67fe
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb
natashk/Udacity-PyTorch-Challenge
c614da84b85ba4b4072e688ea4ff78a5d17a67fe
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb
natashk/Udacity-PyTorch-Challenge
c614da84b85ba4b4072e688ea4ff78a5d17a67fe
[ "MIT" ]
null
null
null
81.071235
17,366
0.734295
[ [ [ "<a href=\"https://colab.research.google.com/github/natashk/Udacity-PyTorch-Challenge/blob/master/intro-to-pytorch/Part%202%20-%20Neural%20Networks%20in%20PyTorch%20(Exercises).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Neural networks with PyTorch\n\nDeep learning networks tend to be massive with dozens or hundreds of layers, that's where the term \"deep\" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. PyTorch has a nice module `nn` that provides a nice way to efficiently build large neural networks.", "_____no_output_____" ] ], [ [ "# http://pytorch.org/\nfrom os.path import exists\nfrom wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag\nplatform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())\ncuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\\.\\([0-9]*\\)\\.\\([0-9]*\\)$/cu\\1\\2/'\naccelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu'\n\n!pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.1-{platform}-linux_x86_64.whl torchvision", "_____no_output_____" ], [ "!wget https://raw.githubusercontent.com/udacity/deep-learning-v2-pytorch/master/intro-to-pytorch/helper.py\n", "--2018-12-17 03:15:51-- https://raw.githubusercontent.com/udacity/deep-learning-v2-pytorch/master/intro-to-pytorch/helper.py\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 2813 (2.7K) [text/plain]\nSaving to: ‘helper.py.4’\n\n\rhelper.py.4 0%[ ] 0 --.-KB/s \rhelper.py.4 100%[===================>] 2.75K --.-KB/s in 0s \n\n2018-12-17 03:15:51 (49.3 MB/s) - ‘helper.py.4’ saved [2813/2813]\n\n" ], [ "# Import necessary packages\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport torch\n\n!wget https://raw.githubusercontent.com/udacity/deep-learning-v2-pytorch/master/intro-to-pytorch/helper.py\nimport helper\n\nimport matplotlib.pyplot as plt", "--2018-12-17 03:15:54-- https://raw.githubusercontent.com/udacity/deep-learning-v2-pytorch/master/intro-to-pytorch/helper.py\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 2813 (2.7K) [text/plain]\nSaving to: ‘helper.py.5’\n\n\rhelper.py.5 0%[ ] 0 --.-KB/s \rhelper.py.5 100%[===================>] 2.75K --.-KB/s in 0s \n\n2018-12-17 03:15:54 (50.0 MB/s) - ‘helper.py.5’ saved [2813/2813]\n\n" ] ], [ [ "\nNow we're going to build a larger network that can solve a (formerly) difficult problem, identifying text in an image. Here we'll use the MNIST dataset which consists of greyscale handwritten digits. Each image is 28x28 pixels, you can see a sample below\n\n<img src='https://github.com/natashk/Udacity-PyTorch-Challenge/blob/master/intro-to-pytorch/assets/mnist.png?raw=1'>\n\nOur goal is to build a neural network that can take one of these images and predict the digit in the image.\n\nFirst up, we need to get our dataset. This is provided through the `torchvision` package. The code below will download the MNIST dataset, then create training and test datasets for us. Don't worry too much about the details here, you'll learn more about this later.", "_____no_output_____" ] ], [ [ "### Run this cell\n\nfrom torchvision import datasets, transforms\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,)),\n ])\n\n# Download and load the training data\ntrainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)", "_____no_output_____" ] ], [ [ "We have the training data loaded into `trainloader` and we make that an iterator with `iter(trainloader)`. Later, we'll use this to loop through the dataset for training, like\n\n```python\nfor image, label in trainloader:\n ## do things with images and labels\n```\n\nYou'll notice I created the `trainloader` with a batch size of 64, and `shuffle=True`. The batch size is the number of images we get in one iteration from the data loader and pass through our network, often called a *batch*. And `shuffle=True` tells it to shuffle the dataset every time we start going through the data loader again. But here I'm just grabbing the first batch so we can check out the data. We can see below that `images` is just a tensor with size `(64, 1, 28, 28)`. So, 64 images per batch, 1 color channel, and 28x28 images.", "_____no_output_____" ] ], [ [ "dataiter = iter(trainloader)\nimages, labels = dataiter.next()\nprint(type(images))\nprint(images.shape)\nprint(labels.shape)", "<class 'torch.Tensor'>\ntorch.Size([64, 1, 28, 28])\ntorch.Size([64])\n" ] ], [ [ "This is what one of the images looks like. ", "_____no_output_____" ] ], [ [ "plt.imshow(images[1].numpy().squeeze(), cmap='Greys_r');", "_____no_output_____" ] ], [ [ "First, let's try to build a simple network for this dataset using weight matrices and matrix multiplications. Then, we'll see how to do it using PyTorch's `nn` module which provides a much more convenient and powerful method for defining network architectures.\n\nThe networks you've seen so far are called *fully-connected* or *dense* networks. Each unit in one layer is connected to each unit in the next layer. In fully-connected networks, the input to each layer must be a one-dimensional vector (which can be stacked into a 2D tensor as a batch of multiple examples). However, our images are 28x28 2D tensors, so we need to convert them into 1D vectors. Thinking about sizes, we need to convert the batch of images with shape `(64, 1, 28, 28)` to a have a shape of `(64, 784)`, 784 is 28 times 28. This is typically called *flattening*, we flattened the 2D images into 1D vectors.\n\nPreviously you built a network with one output unit. Here we need 10 output units, one for each digit. We want our network to predict the digit shown in an image, so what we'll do is calculate probabilities that the image is of any one digit or class. This ends up being a discrete probability distribution over the classes (digits) that tells us the most likely class for the image. That means we need 10 output units for the 10 classes (digits). We'll see how to convert the network output into a probability distribution next.\n\n> **Exercise:** Flatten the batch of images `images`. Then build a multi-layer network with 784 input units, 256 hidden units, and 10 output units using random tensors for the weights and biases. For now, use a sigmoid activation for the hidden layer. Leave the output layer without an activation, we'll add one that gives us a probability distribution next.", "_____no_output_____" ] ], [ [ "## Your solution\ndef activation(x):\n return 1/(1+torch.exp(-x))\n\n# Flatten the input images\ninputs = images.view(images.shape[0], -1)\n\n# Create parameters\nw1 = torch.randn(784, 256)\nb1 = torch.randn(256)\n\nw2 = torch.randn(256, 10)\nb2 = torch.randn(10)\n\nh = activation(torch.mm(inputs, w1) + b1)\n\n# output of your network, should have shape (64,10)\nout = torch.mm(h, w2) + b2\n", "_____no_output_____" ] ], [ [ "Now we have 10 outputs for our network. We want to pass in an image to our network and get out a probability distribution over the classes that tells us the likely class(es) the image belongs to. Something that looks like this:\n<img src='https://github.com/natashk/Udacity-PyTorch-Challenge/blob/master/intro-to-pytorch/assets/image_distribution.png?raw=1' width=500px>\n\nHere we see that the probability for each class is roughly the same. This is representing an untrained network, it hasn't seen any data yet so it just returns a uniform distribution with equal probabilities for each class.\n\nTo calculate this probability distribution, we often use the [**softmax** function](https://en.wikipedia.org/wiki/Softmax_function). Mathematically this looks like\n\n$$\n\\Large \\sigma(x_i) = \\cfrac{e^{x_i}}{\\sum_k^K{e^{x_k}}}\n$$\n\nWhat this does is squish each input $x_i$ between 0 and 1 and normalizes the values to give you a proper probability distribution where the probabilites sum up to one.\n\n> **Exercise:** Implement a function `softmax` that performs the softmax calculation and returns probability distributions for each example in the batch. Note that you'll need to pay attention to the shapes when doing this. If you have a tensor `a` with shape `(64, 10)` and a tensor `b` with shape `(64,)`, doing `a/b` will give you an error because PyTorch will try to do the division across the columns (called broadcasting) but you'll get a size mismatch. The way to think about this is for each of the 64 examples, you only want to divide by one value, the sum in the denominator. So you need `b` to have a shape of `(64, 1)`. This way PyTorch will divide the 10 values in each row of `a` by the one value in each row of `b`. Pay attention to how you take the sum as well. You'll need to define the `dim` keyword in `torch.sum`. Setting `dim=0` takes the sum across the rows while `dim=1` takes the sum across the columns.", "_____no_output_____" ] ], [ [ "def softmax(x):\n ## TODO: Implement the softmax function here\n return torch.exp(x)/torch.sum(torch.exp(x), dim=1).view(-1, 1)\n\n# Here, out should be the output of the network in the previous excercise with shape (64,10)\nprobabilities = softmax(out)\n\n# Does it have the right shape? Should be (64, 10)\nprint(probabilities.shape)\n# Does it sum to 1?\nprint(probabilities.sum(dim=1))\n", "torch.Size([64, 10])\ntensor([1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000])\n" ] ], [ [ "## Building networks with PyTorch\n\nPyTorch provides a module `nn` that makes building networks much simpler. Here I'll show you how to build the same one as above with 784 inputs, 256 hidden units, 10 output units and a softmax output.", "_____no_output_____" ] ], [ [ "from torch import nn", "_____no_output_____" ], [ "class Network(nn.Module):\n def __init__(self):\n super().__init__()\n \n # Inputs to hidden layer linear transformation\n self.hidden = nn.Linear(784, 256)\n # Output layer, 10 units - one for each digit\n self.output = nn.Linear(256, 10)\n \n # Define sigmoid activation and softmax output \n self.sigmoid = nn.Sigmoid()\n self.softmax = nn.Softmax(dim=1)\n \n def forward(self, x):\n # Pass the input tensor through each of our operations\n x = self.hidden(x)\n x = self.sigmoid(x)\n x = self.output(x)\n x = self.softmax(x)\n \n return x", "_____no_output_____" ] ], [ [ "Let's go through this bit by bit.\n\n```python\nclass Network(nn.Module):\n```\n\nHere we're inheriting from `nn.Module`. Combined with `super().__init__()` this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from `nn.Module` when you're creating a class for your network. The name of the class itself can be anything.\n\n```python\nself.hidden = nn.Linear(784, 256)\n```\n\nThis line creates a module for a linear transformation, $x\\mathbf{W} + b$, with 784 inputs and 256 outputs and assigns it to `self.hidden`. The module automatically creates the weight and bias tensors which we'll use in the `forward` method. You can access the weight and bias tensors once the network (`net`) is created with `net.hidden.weight` and `net.hidden.bias`.\n\n```python\nself.output = nn.Linear(256, 10)\n```\n\nSimilarly, this creates another linear transformation with 256 inputs and 10 outputs.\n\n```python\nself.sigmoid = nn.Sigmoid()\nself.softmax = nn.Softmax(dim=1)\n```\n\nHere I defined operations for the sigmoid activation and softmax output. Setting `dim=1` in `nn.Softmax(dim=1)` calculates softmax across the columns.\n\n```python\ndef forward(self, x):\n```\n\nPyTorch networks created with `nn.Module` must have a `forward` method defined. It takes in a tensor `x` and passes it through the operations you defined in the `__init__` method.\n\n```python\nx = self.hidden(x)\nx = self.sigmoid(x)\nx = self.output(x)\nx = self.softmax(x)\n```\n\nHere the input tensor `x` is passed through each operation and reassigned to `x`. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the `__init__` method doesn't matter, but you'll need to sequence the operations correctly in the `forward` method.\n\nNow we can create a `Network` object.", "_____no_output_____" ] ], [ [ "# Create the network and look at it's text representation\nmodel = Network()\nmodel", "_____no_output_____" ] ], [ [ "You can define the network somewhat more concisely and clearly using the `torch.nn.functional` module. This is the most common way you'll see networks defined as many operations are simple element-wise functions. We normally import this module as `F`, `import torch.nn.functional as F`.", "_____no_output_____" ] ], [ [ "import torch.nn.functional as F\n\nclass Network(nn.Module):\n def __init__(self):\n super().__init__()\n # Inputs to hidden layer linear transformation\n self.hidden = nn.Linear(784, 256)\n # Output layer, 10 units - one for each digit\n self.output = nn.Linear(256, 10)\n \n def forward(self, x):\n # Hidden layer with sigmoid activation\n x = F.sigmoid(self.hidden(x))\n # Output layer with softmax activation\n x = F.softmax(self.output(x), dim=1)\n \n return x", "_____no_output_____" ] ], [ [ "### Activation functions\n\nSo far we've only been looking at the softmax activation, but in general any function can be used as an activation function. The only requirement is that for a network to approximate a non-linear function, the activation functions must be non-linear. Here are a few more examples of common activation functions: Tanh (hyperbolic tangent), and ReLU (rectified linear unit).\n\n<img src=\"https://github.com/natashk/Udacity-PyTorch-Challenge/blob/master/intro-to-pytorch/assets/activation.png?raw=1\" width=700px>\n\nIn practice, the ReLU function is used almost exclusively as the activation function for hidden layers.", "_____no_output_____" ], [ "### Your Turn to Build a Network\n\n<img src=\"https://github.com/natashk/Udacity-PyTorch-Challenge/blob/master/intro-to-pytorch/assets/mlp_mnist.png?raw=1\" width=600px>\n\n> **Exercise:** Create a network with 784 input units, a hidden layer with 128 units and a ReLU activation, then a hidden layer with 64 units and a ReLU activation, and finally an output layer with a softmax activation as shown above. You can use a ReLU activation with the `nn.ReLU` module or `F.relu` function.\n\nIt's good practice to name your layers by their type of network, for instance 'fc' to represent a fully-connected layer. As you code your solution, use `fc1`, `fc2`, and `fc3` as your layer names.", "_____no_output_____" ] ], [ [ "## Your solution here\nclass Network(nn.Module):\n def __init__(self):\n super().__init__()\n \n # Inputs to hidden layer linear transformation\n self.fc1 = nn.Linear(784, 128)\n self.fc2 = nn.Linear(128, 64)\n self.fc3 = nn.Linear(64, 10)\n \n def forward(self, x):\n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n x = F.relu(x)\n x = self.fc3(x)\n x = F.softmax(x, dim=1)\n \n return x\n\nmodel = Network()\nmodel", "_____no_output_____" ] ], [ [ "### Initializing weights and biases\n\nThe weights and such are automatically initialized for you, but it's possible to customize how they are initialized. The weights and biases are tensors attached to the layer you defined, you can get them with `model.fc1.weight` for instance.", "_____no_output_____" ] ], [ [ "print(model.fc1.weight)\nprint(model.fc1.bias)", "Parameter containing:\ntensor([[ 0.0264, 0.0185, 0.0194, ..., -0.0073, 0.0179, -0.0024],\n [-0.0117, 0.0335, 0.0102, ..., 0.0102, 0.0321, 0.0127],\n [ 0.0021, 0.0308, 0.0072, ..., -0.0183, 0.0139, 0.0330],\n ...,\n [-0.0030, 0.0187, 0.0151, ..., 0.0161, 0.0338, 0.0054],\n [ 0.0176, 0.0054, -0.0256, ..., -0.0133, -0.0080, 0.0195],\n [ 0.0132, 0.0060, -0.0066, ..., -0.0192, -0.0137, -0.0124]],\n requires_grad=True)\nParameter containing:\ntensor([-0.0351, -0.0324, -0.0055, 0.0179, -0.0038, -0.0255, 0.0053, -0.0190,\n -0.0152, -0.0011, -0.0343, 0.0351, -0.0018, -0.0122, 0.0326, -0.0246,\n -0.0279, 0.0257, -0.0205, -0.0302, 0.0061, -0.0123, 0.0282, 0.0009,\n -0.0279, 0.0192, -0.0233, 0.0308, -0.0353, -0.0130, -0.0104, 0.0038,\n -0.0055, 0.0273, -0.0238, -0.0011, -0.0032, 0.0081, -0.0249, 0.0066,\n -0.0264, 0.0180, 0.0067, 0.0140, -0.0165, 0.0034, -0.0323, 0.0126,\n 0.0001, -0.0242, -0.0308, -0.0320, 0.0025, 0.0182, -0.0119, 0.0238,\n -0.0036, 0.0136, -0.0127, 0.0306, -0.0076, 0.0324, -0.0162, 0.0205,\n 0.0223, 0.0131, 0.0306, -0.0344, -0.0299, -0.0076, -0.0023, 0.0119,\n 0.0050, 0.0353, 0.0290, 0.0017, -0.0222, 0.0160, -0.0059, 0.0346,\n -0.0165, -0.0187, -0.0236, 0.0357, 0.0341, 0.0308, -0.0168, -0.0051,\n 0.0094, -0.0288, -0.0207, 0.0337, -0.0297, 0.0249, -0.0298, -0.0044,\n 0.0275, -0.0312, -0.0249, 0.0253, 0.0151, 0.0342, -0.0105, 0.0312,\n 0.0251, -0.0280, 0.0262, -0.0257, -0.0250, 0.0043, 0.0357, -0.0343,\n -0.0329, -0.0217, 0.0069, -0.0258, 0.0227, -0.0182, 0.0088, -0.0237,\n -0.0137, -0.0051, 0.0192, -0.0249, 0.0351, 0.0313, 0.0277, -0.0235],\n requires_grad=True)\n" ] ], [ [ "For custom initialization, we want to modify these tensors in place. These are actually autograd *Variables*, so we need to get back the actual tensors with `model.fc1.weight.data`. Once we have the tensors, we can fill them with zeros (for biases) or random normal values.", "_____no_output_____" ] ], [ [ "# Set biases to all zeros\nmodel.fc1.bias.data.fill_(0)", "_____no_output_____" ], [ "# sample from random normal with standard dev = 0.01\nmodel.fc1.weight.data.normal_(std=0.01)", "_____no_output_____" ] ], [ [ "### Forward pass\n\nNow that we have a network, let's see what happens when we pass in an image.", "_____no_output_____" ] ], [ [ "# Grab some data \ndataiter = iter(trainloader)\nimages, labels = dataiter.next()\n\n# Resize images into a 1D vector, new shape is (batch size, color channels, image pixels) \nimages.resize_(64, 1, 784)\n# or images.resize_(images.shape[0], 1, 784) to automatically get batch size\n\n# Forward pass through the network\nimg_idx = 0\nps = model.forward(images[img_idx,:])\n\nimg = images[img_idx]\nhelper.view_classify(img.view(1, 28, 28), ps)", "_____no_output_____" ] ], [ [ "As you can see above, our network has basically no idea what this digit is. It's because we haven't trained it yet, all the weights are random!\n\n### Using `nn.Sequential`\n\nPyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, `nn.Sequential` ([documentation](https://pytorch.org/docs/master/nn.html#torch.nn.Sequential)). Using this to build the equivalent network:", "_____no_output_____" ] ], [ [ "# Hyperparameters for our network\ninput_size = 784\nhidden_sizes = [128, 64]\noutput_size = 10\n\n# Build a feed-forward network\nmodel = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),\n nn.ReLU(),\n nn.Linear(hidden_sizes[0], hidden_sizes[1]),\n nn.ReLU(),\n nn.Linear(hidden_sizes[1], output_size),\n nn.Softmax(dim=1))\nprint(model)\n\n# Forward pass through the network and display output\nimages, labels = next(iter(trainloader))\nimages.resize_(images.shape[0], 1, 784)\nps = model.forward(images[0,:])\nhelper.view_classify(images[0].view(1, 28, 28), ps)", "Sequential(\n (0): Linear(in_features=784, out_features=128, bias=True)\n (1): ReLU()\n (2): Linear(in_features=128, out_features=64, bias=True)\n (3): ReLU()\n (4): Linear(in_features=64, out_features=10, bias=True)\n (5): Softmax()\n)\n" ] ], [ [ "Here our model is the same as before: 784 input units, a hidden layer with 128 units, ReLU activation, 64 unit hidden layer, another ReLU, then the output layer with 10 units, and the softmax output.\n\nThe operations are available by passing in the appropriate index. For example, if you want to get first Linear operation and look at the weights, you'd use `model[0]`.", "_____no_output_____" ] ], [ [ "print(model[0])\nmodel[0].weight", "Linear(in_features=784, out_features=128, bias=True)\n" ] ], [ [ "You can also pass in an `OrderedDict` to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so _each operation must have a different name_.", "_____no_output_____" ] ], [ [ "from collections import OrderedDict\nmodel = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(input_size, hidden_sizes[0])),\n ('relu1', nn.ReLU()),\n ('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])),\n ('relu2', nn.ReLU()),\n ('output', nn.Linear(hidden_sizes[1], output_size)),\n ('softmax', nn.Softmax(dim=1))]))\nmodel", "_____no_output_____" ] ], [ [ "Now you can access layers either by integer or the name", "_____no_output_____" ] ], [ [ "print(model[0])\nprint(model.fc1)", "Linear(in_features=784, out_features=128, bias=True)\nLinear(in_features=784, out_features=128, bias=True)\n" ] ], [ [ "In the next notebook, we'll see how we can train a neural network to accuractly predict the numbers appearing in the MNIST images.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecf9a9a7c592249956f46e4971ed71928ac2216a
15,120
ipynb
Jupyter Notebook
1_Regression/Week2_Multiple Regression/numpy-tutorial.ipynb
Breezen/Machine-Learning
77267e106cb865a5f95d37093d4219b3458aea27
[ "MIT" ]
null
null
null
1_Regression/Week2_Multiple Regression/numpy-tutorial.ipynb
Breezen/Machine-Learning
77267e106cb865a5f95d37093d4219b3458aea27
[ "MIT" ]
null
null
null
1_Regression/Week2_Multiple Regression/numpy-tutorial.ipynb
Breezen/Machine-Learning
77267e106cb865a5f95d37093d4219b3458aea27
[ "MIT" ]
null
null
null
20.295302
404
0.521693
[ [ [ "# Numpy Tutorial", "_____no_output_____" ], [ "Numpy is a computational library for Python that is optimized for operations on multi-dimensional arrays. In this notebook we will use numpy to work with 1-d arrays (often called vectors) and 2-d arrays (often called matrices).\n\nFor a the full user guide and reference for numpy see: http://docs.scipy.org/doc/numpy/", "_____no_output_____" ] ], [ [ "import numpy as np # importing this way allows us to refer to numpy as np", "_____no_output_____" ] ], [ [ "# Creating Numpy Arrays", "_____no_output_____" ], [ "New arrays can be made in several ways. We can take an existing list and convert it to a numpy array:", "_____no_output_____" ] ], [ [ "mylist = [1., 2., 3., 4.]\nmynparray = np.array(mylist)\nmynparray", "_____no_output_____" ] ], [ [ "You can initialize an array (of any dimension) of all ones or all zeroes with the ones() and zeros() functions:", "_____no_output_____" ] ], [ [ "one_vector = np.ones(4)\nprint one_vector # using print removes the array() portion", "[ 1. 1. 1. 1.]\n" ], [ "one2Darray = np.ones((2, 4)) # an 2D array with 2 \"rows\" and 4 \"columns\"\nprint one2Darray", "[[ 1. 1. 1. 1.]\n [ 1. 1. 1. 1.]]\n" ], [ "zero_vector = np.zeros(4)\nprint zero_vector", "[ 0. 0. 0. 0.]\n" ] ], [ [ "You can also initialize an empty array which will be filled with values. This is the fastest way to initialize a fixed-size numpy array however you must ensure that you replace all of the values.", "_____no_output_____" ] ], [ [ "empty_vector = np.empty(5)\nprint empty_vector", "[ 0.00000000e+000 0.00000000e+000 2.13646924e-314 2.12357414e-314\n 2.15689220e-314]\n" ] ], [ [ "#Accessing array elements", "_____no_output_____" ], [ "Accessing an array is straight forward. For vectors you access the index by referring to it inside square brackets. Recall that indices in Python start with 0.", "_____no_output_____" ] ], [ [ "mynparray[2]", "_____no_output_____" ] ], [ [ "2D arrays are accessed similarly by referring to the row and column index separated by a comma:", "_____no_output_____" ] ], [ [ "my_matrix = np.array([[1, 2, 3], [4, 5, 6]])\nprint my_matrix", "[[1 2 3]\n [4 5 6]]\n" ], [ "print my_matrix[1, 2]", "6\n" ] ], [ [ "Sequences of indices can be accessed using ':' for example", "_____no_output_____" ] ], [ [ "print my_matrix[0:2, 2] # recall 0:2 = [0, 1]", "[3 6]\n" ], [ "print my_matrix[0, 0:3]", "[1 2 3]\n" ] ], [ [ "You can also pass a list of indices. ", "_____no_output_____" ] ], [ [ "fib_indices = np.array([1, 1, 2, 3])\nrandom_vector = np.random.random(10) # 10 random numbers between 0 and 1\nprint random_vector", "[ 0.08085806 0.82612441 0.02317605 0.70411537 0.14001416 0.32688241\n 0.68432394 0.02795512 0.48254072 0.82167965]\n" ], [ "print random_vector[fib_indices]", "[ 0.82612441 0.82612441 0.02317605 0.70411537]\n" ] ], [ [ "You can also use true/false values to select values", "_____no_output_____" ] ], [ [ "my_vector = np.array([1, 2, 3, 4])\nselect_index = np.array([True, False, True, False])\nprint my_vector[select_index]", "[1 3]\n" ] ], [ [ "For 2D arrays you can select specific columns and specific rows. Passing ':' selects all rows/columns", "_____no_output_____" ] ], [ [ "select_cols = np.array([True, False, True]) # 1st and 3rd column\nselect_rows = np.array([False, True]) # 2nd row", "_____no_output_____" ], [ "print my_matrix[select_rows, :] # just 2nd row but all columns", "_____no_output_____" ], [ "print my_matrix[:, select_cols] # all rows and just the 1st and 3rd column", "_____no_output_____" ] ], [ [ "#Operations on Arrays", "_____no_output_____" ], [ "You can use the operations '\\*', '\\*\\*', '\\\\', '+' and '-' on numpy arrays and they operate elementwise.", "_____no_output_____" ] ], [ [ "my_array = np.array([1., 2., 3., 4.])\nprint my_array*my_array", "_____no_output_____" ], [ "print my_array**2", "_____no_output_____" ], [ "print my_array - np.ones(4)", "_____no_output_____" ], [ "print my_array + np.ones(4)", "_____no_output_____" ], [ "print my_array / 3", "_____no_output_____" ], [ "print my_array / np.array([2., 3., 4., 5.]) # = [1.0/2.0, 2.0/3.0, 3.0/4.0, 4.0/5.0]", "_____no_output_____" ] ], [ [ "You can compute the sum with np.sum() and the average with np.average()", "_____no_output_____" ] ], [ [ "print np.sum(my_array)", "_____no_output_____" ], [ "print np.average(my_array)", "_____no_output_____" ], [ "print np.sum(my_array)/len(my_array)", "_____no_output_____" ] ], [ [ "#The dot product", "_____no_output_____" ], [ "An important mathematical operation in linear algebra is the dot product. \n\nWhen we compute the dot product between two vectors we are simply multiplying them elementwise and adding them up. In numpy you can do this with np.dot()", "_____no_output_____" ] ], [ [ "array1 = np.array([1., 2., 3., 4.])\narray2 = np.array([2., 3., 4., 5.])\nprint np.dot(array1, array2)", "_____no_output_____" ], [ "print np.sum(array1*array2)", "_____no_output_____" ] ], [ [ "Recall that the Euclidean length (or magnitude) of a vector is the squareroot of the sum of the squares of the components. This is just the squareroot of the dot product of the vector with itself:", "_____no_output_____" ] ], [ [ "array1_mag = np.sqrt(np.dot(array1, array1))\nprint array1_mag", "_____no_output_____" ], [ "print np.sqrt(np.sum(array1*array1))", "_____no_output_____" ] ], [ [ "We can also use the dot product when we have a 2D array (or matrix). When you have an vector with the same number of elements as the matrix (2D array) has columns you can right-multiply the matrix by the vector to get another vector with the same number of elements as the matrix has rows. For example this is how you compute the predicted values given a matrix of features and an array of weights.", "_____no_output_____" ] ], [ [ "my_features = np.array([[1., 2.], [3., 4.], [5., 6.], [7., 8.]])\nprint my_features", "_____no_output_____" ], [ "my_weights = np.array([0.4, 0.5])\nprint my_weights", "_____no_output_____" ], [ "my_predictions = np.dot(my_features, my_weights) # note that the weights are on the right\nprint my_predictions # which has 4 elements since my_features has 4 rows", "_____no_output_____" ] ], [ [ "Similarly if you have a vector with the same number of elements as the matrix has *rows* you can left multiply them.", "_____no_output_____" ] ], [ [ "my_matrix = my_features\nmy_array = np.array([0.3, 0.4, 0.5, 0.6])", "_____no_output_____" ], [ "print np.dot(my_array, my_matrix) # which has 2 elements because my_matrix has 2 columns", "_____no_output_____" ] ], [ [ "#Multiplying Matrices", "_____no_output_____" ], [ "If we have two 2D arrays (matrices) matrix_1 and matrix_2 where the number of columns of matrix_1 is the same as the number of rows of matrix_2 then we can use np.dot() to perform matrix multiplication.", "_____no_output_____" ] ], [ [ "matrix_1 = np.array([[1., 2., 3.],[4., 5., 6.]])\nprint matrix_1", "_____no_output_____" ], [ "matrix_2 = np.array([[1., 2.], [3., 4.], [5., 6.]])\nprint matrix_2", "_____no_output_____" ], [ "print np.dot(matrix_1, matrix_2)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
ecf9b77c98995a866b5dcd1f7f355434a34eb183
5,096
ipynb
Jupyter Notebook
ipynb/Germany-Nordrhein-Westfalen-LK-Viersen.ipynb
oscovida/oscovida.github.io
c74d6da79feda1b5ccce107ad3acd48cf0e74c1c
[ "CC-BY-4.0" ]
2
2020-06-19T09:16:14.000Z
2021-01-24T17:47:56.000Z
ipynb/Germany-Nordrhein-Westfalen-LK-Viersen.ipynb
oscovida/oscovida.github.io
c74d6da79feda1b5ccce107ad3acd48cf0e74c1c
[ "CC-BY-4.0" ]
8
2020-04-20T16:49:49.000Z
2021-12-25T16:54:19.000Z
ipynb/Germany-Nordrhein-Westfalen-LK-Viersen.ipynb
oscovida/oscovida.github.io
c74d6da79feda1b5ccce107ad3acd48cf0e74c1c
[ "CC-BY-4.0" ]
4
2020-04-20T13:24:45.000Z
2021-01-29T11:12:12.000Z
30.51497
192
0.524529
[ [ [ "# Germany: LK Viersen (Nordrhein-Westfalen)\n\n* Homepage of project: https://oscovida.github.io\n* Plots are explained at http://oscovida.github.io/plots.html\n* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Nordrhein-Westfalen-LK-Viersen.ipynb)", "_____no_output_____" ] ], [ [ "import datetime\nimport time\n\nstart = datetime.datetime.now()\nprint(f\"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}\")", "_____no_output_____" ], [ "%config InlineBackend.figure_formats = ['svg']\nfrom oscovida import *", "_____no_output_____" ], [ "overview(country=\"Germany\", subregion=\"LK Viersen\", weeks=5);", "_____no_output_____" ], [ "overview(country=\"Germany\", subregion=\"LK Viersen\");", "_____no_output_____" ], [ "compare_plot(country=\"Germany\", subregion=\"LK Viersen\", dates=\"2020-03-15:\");\n", "_____no_output_____" ], [ "# load the data\ncases, deaths = germany_get_region(landkreis=\"LK Viersen\")\n\n# get population of the region for future normalisation:\ninhabitants = population(country=\"Germany\", subregion=\"LK Viersen\")\nprint(f'Population of country=\"Germany\", subregion=\"LK Viersen\": {inhabitants} people')\n\n# compose into one table\ntable = compose_dataframe_summary(cases, deaths)\n\n# show tables with up to 1000 rows\npd.set_option(\"max_rows\", 1000)\n\n# display the table\ntable", "_____no_output_____" ] ], [ [ "# Explore the data in your web browser\n\n- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Nordrhein-Westfalen-LK-Viersen.ipynb)\n- and wait (~1 to 2 minutes)\n- Then press SHIFT+RETURN to advance code cell to code cell\n- See http://jupyter.org for more details on how to use Jupyter Notebook", "_____no_output_____" ], [ "# Acknowledgements:\n\n- Johns Hopkins University provides data for countries\n- Robert Koch Institute provides data for within Germany\n- Atlo Team for gathering and providing data from Hungary (https://atlo.team/koronamonitor/)\n- Open source and scientific computing community for the data tools\n- Github for hosting repository and html files\n- Project Jupyter for the Notebook and binder service\n- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))\n\n--------------------", "_____no_output_____" ] ], [ [ "print(f\"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and \"\n f\"deaths at {fetch_deaths_last_execution()}.\")", "_____no_output_____" ], [ "# to force a fresh download of data, run \"clear_cache()\"", "_____no_output_____" ], [ "print(f\"Notebook execution took: {datetime.datetime.now()-start}\")\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
ecf9b88e42e484e92aaee29fb042e11db5bde093
10,199
ipynb
Jupyter Notebook
models/clustering/experimental.ipynb
Zarand3r/corona_light
96482cfb6fff8959772ccd48c10ce0588b191f18
[ "MIT" ]
1
2020-09-27T08:55:32.000Z
2020-09-27T08:55:32.000Z
models/clustering/experimental.ipynb
Zarand3r/corona_light
96482cfb6fff8959772ccd48c10ce0588b191f18
[ "MIT" ]
null
null
null
models/clustering/experimental.ipynb
Zarand3r/corona_light
96482cfb6fff8959772ccd48c10ce0588b191f18
[ "MIT" ]
null
null
null
58.953757
1,823
0.608589
[ [ [ "# Following the tutorial from exploratory/alexcui_colored_county_maps.ipynb. Hoping thats alright\nfrom urllib.request import urlopen\nimport json\nimport plotly.express as px\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "def fix_fips(Data):\n index = 0\n for row in Data.iterrows():\n row = row[1]\n fips_val = int(row[0])\n if fips_val < 10000:\n new_fips = '0' + row[0]\n Data['FIPS'][index] = new_fips\n index += 1\n return Data", "_____no_output_____" ], [ "with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:\n counties = json.load(response)\n\nData = pd.read_csv('raw_data.csv', dtype = {'FIPS': str})\nData = Data.drop(columns = ['Unnamed: 0'])", "_____no_output_____" ], [ "Data = fix_fips(Data)", "C:\\Users\\spar1\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:8: SettingWithCopyWarning:\n\n\nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n\n" ], [ "print(Data['Pop'])", "0 55036.000\n1 203360.000\n2 26201.000\n3 22580.000\n4 57667.000\n ... \n3138 8253.000\n3139 7117.000\n3140 19480.149\n3141 41956.000\n3142 60950.305\nName: Pop, Length: 3143, dtype: float64\n" ], [ "def get_column(column, Data):\n if column != 'FIPS':\n row = np.array(Data[column])\n max_val = max(row)\n min_val = min(row)\n df = pd.DataFrame([np.array(Data['FIPS']), row]).transpose()\n df.columns = ['FIPS', column]\n return (max_val, min_val, df)", "_____no_output_____" ], [ "vals = get_column('Pop', Data)\nfig = px.choropleth_mapbox(vals[2], geojson=counties, locations='FIPS', color='Pop',\n color_continuous_scale=\"Viridis\",\n range_color=(vals[1], vals[0]),\n mapbox_style=\"carto-positron\",\n zoom=3, center = {\"lat\": 37.0902, \"lon\": -95.7129},\n opacity=0.5,\n labels={'FIPS':'Pop'}\n )\nfig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
ecf9be1ecda02e50db2080862695014a6b9d5228
103,005
ipynb
Jupyter Notebook
gan_mnist/Intro_to_GANs_Exercises.ipynb
kwidmann137/Udacity-Deep-Learning
02db4f3d3963e0519084daf6ad1e4af314024054
[ "MIT" ]
null
null
null
gan_mnist/Intro_to_GANs_Exercises.ipynb
kwidmann137/Udacity-Deep-Learning
02db4f3d3963e0519084daf6ad1e4af314024054
[ "MIT" ]
null
null
null
gan_mnist/Intro_to_GANs_Exercises.ipynb
kwidmann137/Udacity-Deep-Learning
02db4f3d3963e0519084daf6ad1e4af314024054
[ "MIT" ]
null
null
null
135.890501
36,724
0.83762
[ [ [ "# Generative Adversarial Network\n\nIn this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten digits!\n\nGANs were [first reported on](https://arxiv.org/abs/1406.2661) in 2014 from Ian Goodfellow and others in Yoshua Bengio's lab. Since then, GANs have exploded in popularity. Here are a few examples to check out:\n\n* [Pix2Pix](https://affinelayer.com/pixsrv/) \n* [CycleGAN](https://github.com/junyanz/CycleGAN)\n* [A whole list](https://github.com/wiseodd/generative-models)\n\nThe idea behind GANs is that you have two networks, a generator $G$ and a discriminator $D$, competing against each other. The generator makes fake data to pass to the discriminator. The discriminator also sees real data and predicts if the data it's received is real or fake. The generator is trained to fool the discriminator, it wants to output data that looks _as close as possible_ to real data. And the discriminator is trained to figure out which data is real and which is fake. What ends up happening is that the generator learns to make data that is indistiguishable from real data to the discriminator.\n\n![GAN diagram](assets/gan_diagram.png)\n\nThe general structure of a GAN is shown in the diagram above, using MNIST images as data. The latent sample is a random vector the generator uses to contruct it's fake images. As the generator learns through training, it figures out how to map these random vectors to recognizable images that can fool the discriminator.\n\nThe output of the discriminator is a sigmoid function, where 0 indicates a fake image and 1 indicates an real image. If you're interested only in generating new images, you can throw out the discriminator after training. Now, let's see how we build this thing in TensorFlow.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport pickle as pkl\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data')", "WARNING:tensorflow:From <ipython-input-9-a37a59f11b0d>:2: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use alternatives such as official/mnist/dataset.py from tensorflow/models.\nWARNING:tensorflow:From /home/kyle/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease write your own downloading logic.\nWARNING:tensorflow:From /home/kyle/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use tf.data to implement this functionality.\nExtracting MNIST_data/train-images-idx3-ubyte.gz\nWARNING:tensorflow:From /home/kyle/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use tf.data to implement this functionality.\nExtracting MNIST_data/train-labels-idx1-ubyte.gz\nExtracting MNIST_data/t10k-images-idx3-ubyte.gz\nExtracting MNIST_data/t10k-labels-idx1-ubyte.gz\nWARNING:tensorflow:From /home/kyle/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use alternatives such as official/mnist/dataset.py from tensorflow/models.\n" ] ], [ [ "## Model Inputs\n\nFirst we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input `inputs_real` and the generator input `inputs_z`. We'll assign them the appropriate sizes for each of the networks.\n\n>**Exercise:** Finish the `model_inputs` function below. Create the placeholders for `inputs_real` and `inputs_z` using the input sizes `real_dim` and `z_dim` respectively.", "_____no_output_____" ] ], [ [ "def model_inputs(real_dim, z_dim):\n inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real')\n inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')\n \n return inputs_real, inputs_z", "_____no_output_____" ] ], [ [ "## Generator network\n\n![GAN Network](assets/gan_network.png)\n\nHere we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values.\n\n#### Variable Scope\nHere we need to use `tf.variable_scope` for two reasons. Firstly, we're going to make sure all the variable names start with `generator`. Similarly, we'll prepend `discriminator` to the discriminator variables. This will help out later when we're training the separate networks.\n\nWe could just use `tf.name_scope` to set the names, but we also want to reuse these networks with different inputs. For the generator, we're going to train it, but also _sample from it_ as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the `reuse` keyword for `tf.variable_scope` to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again.\n\nTo use `tf.variable_scope`, you use a `with` statement:\n```python\nwith tf.variable_scope('scope_name', reuse=False):\n # code here\n```\n\nHere's more from [the TensorFlow documentation](https://www.tensorflow.org/programmers_guide/variable_scope#the_problem) to get another look at using `tf.variable_scope`.\n\n#### Leaky ReLU\nTensorFlow doesn't provide an operation for leaky ReLUs, so we'll need to make one . For this you can just take the outputs from a linear fully connected layer and pass them to `tf.maximum`. Typically, a parameter `alpha` sets the magnitude of the output for negative values. So, the output for negative input (`x`) values is `alpha*x`, and the output for positive `x` is `x`:\n$$\nf(x) = max(\\alpha * x, x)\n$$\n\n#### Tanh Output\nThe generator has been found to perform the best with $tanh$ for the generator output. This means that we'll have to rescale the MNIST images to be between -1 and 1, instead of 0 and 1.\n\n>**Exercise:** Implement the generator network in the function below. You'll need to return the tanh output. Make sure to wrap your code in a variable scope, with 'generator' as the scope name, and pass the `reuse` keyword argument from the function to `tf.variable_scope`.", "_____no_output_____" ] ], [ [ "def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):\n ''' Build the generator network.\n \n Arguments\n ---------\n z : Input tensor for the generator\"\n out_dim : Shape of the generator output\n n_units : Number of units in hidden layer\n reuse : Reuse the variables with tf.variable_scope\n alpha : leak parameter for leaky ReLU\n \n Returns\n -------\n out: \n '''\n with tf.variable_scope('generator_scope', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(z, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum(alpha * h1, h1)\n \n # Logits and tanh output\n logits = tf.layers.dense(h1, out_dim)\n out = tf.tanh(logits)\n \n return out, logits", "_____no_output_____" ] ], [ [ "## Discriminator\n\nThe discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer.\n\n>**Exercise:** Implement the discriminator network in the function below. Same as above, you'll need to return both the logits and the sigmoid output. Make sure to wrap your code in a variable scope, with 'discriminator' as the scope name, and pass the `reuse` keyword argument from the function arguments to `tf.variable_scope`.", "_____no_output_____" ] ], [ [ "def discriminator(x, n_units=128, reuse=False, alpha=0.01):\n ''' Build the discriminator network.\n \n Arguments\n ---------\n x : Input tensor for the discriminator\n n_units: Number of units in hidden layer\n reuse : Reuse the variables with tf.variable_scope\n alpha : leak parameter for leaky ReLU\n \n Returns\n -------\n out, logits: \n '''\n with tf.variable_scope('discriminator_scope', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(x, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum( alpha * h1, h1)\n \n logits = tf.layers.dense(h1, 1, activation=None)\n out = tf.sigmoid(logits)\n \n return out, logits", "_____no_output_____" ] ], [ [ "## Hyperparameters", "_____no_output_____" ] ], [ [ "# Size of input image to discriminator\ninput_size = 784 # 28x28 MNIST images flattened\n# Size of latent vector to generator\nz_size = 100\n# Sizes of hidden layers in generator and discriminator\ng_hidden_size = 128\nd_hidden_size = 128\n# Leak factor for leaky ReLU\nalpha = 0.01\n# Label smoothing \nsmooth = 0.1", "_____no_output_____" ] ], [ [ "## Build network\n\nNow we're building the network from the functions defined above.\n\nFirst is to get our inputs, `input_real, input_z` from `model_inputs` using the sizes of the input and z.\n\nThen, we'll create the generator, `generator(input_z, input_size)`. This builds the generator with the appropriate input and output sizes.\n\nThen the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as `g_model`. So the real data discriminator is `discriminator(input_real)` while the fake discriminator is `discriminator(g_model, reuse=True)`.\n\n>**Exercise:** Build the network from the functions you defined earlier.", "_____no_output_____" ] ], [ [ "tf.reset_default_graph()\n# Create our input placeholders\ninput_real, input_z = model_inputs(input_size, z_size)\n\n# Generator network here\ng_model, g_logits = generator(input_z, input_size)\n# g_model is the generator output\n\n# Disriminator network here\nd_model_real, d_logits_real = discriminator(input_real)\nd_model_fake, d_logits_fake = discriminator(g_model, reuse=True)", "_____no_output_____" ] ], [ [ "## Discriminator and Generator Losses\n\nNow we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, `d_loss = d_loss_real + d_loss_fake`. The losses will be sigmoid cross-entropies, which we can get with `tf.nn.sigmoid_cross_entropy_with_logits`. We'll also wrap that in `tf.reduce_mean` to get the mean for all the images in the batch. So the losses will look something like \n\n```python\ntf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))\n```\n\nFor the real image logits, we'll use `d_logits_real` which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example, using the parameter `smooth`. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like `labels = tf.ones_like(tensor) * (1 - smooth)`\n\nThe discriminator loss for the fake data is similar. The logits are `d_logits_fake`, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.\n\nFinally, the generator losses are using `d_logits_fake`, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images.\n\n>**Exercise:** Calculate the losses for the discriminator and the generator. There are two discriminator losses, one for real images and one for fake images. For the real image loss, use the real logits and (smoothed) labels of ones. For the fake image loss, use the fake logits with labels of all zeros. The total discriminator loss is the sum of those two losses. Finally, the generator loss again uses the fake logits from the discriminator, but this time the labels are all ones because the generator wants to fool the discriminator.", "_____no_output_____" ] ], [ [ "# Calculate losses\nd_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits = d_logits_real,\n labels=tf.ones_like(d_logits_real) * (1-smooth)))\n\nd_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits = d_logits_fake,\n labels=tf.zeros_like(d_logits_real)))\n\nd_loss = d_loss_real + d_loss_fake\n\ng_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits = d_logits_fake,\n labels=tf.ones_like(d_logits_fake)))", "_____no_output_____" ] ], [ [ "## Optimizers\n\nWe want to update the generator and discriminator variables separately. So we need to get the variables for each part and build optimizers for the two parts. To get all the trainable variables, we use `tf.trainable_variables()`. This creates a list of all the variables we've defined in our graph.\n\nFor the generator optimizer, we only want to generator variables. Our past selves were nice and used a variable scope to start all of our generator variable names with `generator`. So, we just need to iterate through the list from `tf.trainable_variables()` and keep variables that start with `generator`. Each variable object has an attribute `name` which holds the name of the variable as a string (`var.name == 'weights_0'` for instance). \n\nWe can do something similar with the discriminator. All the variables in the discriminator start with `discriminator`.\n\nThen, in the optimizer we pass the variable lists to the `var_list` keyword argument of the `minimize` method. This tells the optimizer to only update the listed variables. Something like `tf.train.AdamOptimizer().minimize(loss, var_list=var_list)` will only train the variables in `var_list`.\n\n>**Exercise: ** Below, implement the optimizers for the generator and discriminator. First you'll need to get a list of trainable variables, then split that list into two lists, one for the generator variables and another for the discriminator variables. Finally, using `AdamOptimizer`, create an optimizer for each network that update the network variables separately.", "_____no_output_____" ] ], [ [ "# Optimizers\nlearning_rate = 0.002\n\n# Get the trainable_variables, split into G and D parts\nt_vars = tf.trainable_variables()\ng_vars = [var for var in t_vars if var.name.startswith('generator')]\nd_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n\nd_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars)\ng_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars)", "_____no_output_____" ] ], [ [ "## Training", "_____no_output_____" ] ], [ [ "batch_size = 100\nepochs = 100\nsamples = []\nlosses = []\nsaver = tf.train.Saver(var_list = g_vars)\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for e in range(epochs):\n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n \n # Get images, reshape and rescale to pass to D\n batch_images = batch[0].reshape((batch_size, 784))\n batch_images = batch_images*2 - 1\n \n # Sample random noise for G\n batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n \n # Run optimizers\n _ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z})\n _ = sess.run(g_train_opt, feed_dict={input_z: batch_z})\n \n # At the end of each epoch, get the losses and print them out\n train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images})\n train_loss_g = g_loss.eval({input_z: batch_z})\n \n print(\"Epoch {}/{}...\".format(e+1, epochs),\n \"Discriminator Loss: {:.4f}...\".format(train_loss_d),\n \"Generator Loss: {:.4f}\".format(train_loss_g)) \n # Save losses to view after training\n losses.append((train_loss_d, train_loss_g))\n \n # Sample from generator as we're training for viewing afterwards\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, n_units=g_hidden_size, reuse=True, alpha=alpha),\n feed_dict={input_z: sample_z})\n samples.append(gen_samples)\n saver.save(sess, './checkpoints/generator.ckpt')\n\n# Save training generator samples\nwith open('train_samples.pkl', 'wb') as f:\n pkl.dump(samples, f)", "Epoch 1/100... Discriminator Loss: 0.3461... Generator Loss: 4.3579\nEpoch 2/100... Discriminator Loss: 0.4355... Generator Loss: 3.8049\nEpoch 3/100... Discriminator Loss: 0.4626... Generator Loss: 4.3027\nEpoch 4/100... Discriminator Loss: 0.5875... Generator Loss: 3.6213\nEpoch 5/100... Discriminator Loss: 1.3889... Generator Loss: 4.1793\nEpoch 6/100... Discriminator Loss: 0.8333... Generator Loss: 4.1618\nEpoch 7/100... Discriminator Loss: 1.8047... Generator Loss: 2.3321\nEpoch 8/100... Discriminator Loss: 1.1160... Generator Loss: 2.9631\nEpoch 9/100... Discriminator Loss: 0.9227... Generator Loss: 2.3497\nEpoch 10/100... Discriminator Loss: 1.3120... Generator Loss: 2.9380\nEpoch 11/100... Discriminator Loss: 0.7329... Generator Loss: 2.8539\nEpoch 12/100... Discriminator Loss: 1.1364... Generator Loss: 2.5426\nEpoch 13/100... Discriminator Loss: 1.0392... Generator Loss: 3.2323\nEpoch 14/100... Discriminator Loss: 0.8952... Generator Loss: 1.8161\nEpoch 15/100... Discriminator Loss: 0.8717... Generator Loss: 1.8423\nEpoch 16/100... Discriminator Loss: 1.0604... Generator Loss: 1.6060\nEpoch 17/100... Discriminator Loss: 1.1618... Generator Loss: 2.3957\nEpoch 18/100... Discriminator Loss: 0.9915... Generator Loss: 2.3191\nEpoch 19/100... Discriminator Loss: 0.7599... Generator Loss: 2.7040\nEpoch 20/100... Discriminator Loss: 1.2446... Generator Loss: 2.1178\nEpoch 21/100... Discriminator Loss: 0.7742... Generator Loss: 2.4775\nEpoch 22/100... Discriminator Loss: 0.8089... Generator Loss: 3.2820\nEpoch 23/100... Discriminator Loss: 1.0854... Generator Loss: 2.1174\nEpoch 24/100... Discriminator Loss: 1.1173... Generator Loss: 2.5588\nEpoch 25/100... Discriminator Loss: 1.1260... Generator Loss: 2.1118\nEpoch 26/100... Discriminator Loss: 0.9904... Generator Loss: 2.3600\nEpoch 27/100... Discriminator Loss: 0.9426... Generator Loss: 2.0668\nEpoch 28/100... Discriminator Loss: 0.9316... Generator Loss: 2.1135\nEpoch 29/100... Discriminator Loss: 0.8543... Generator Loss: 2.2653\nEpoch 30/100... Discriminator Loss: 1.0869... Generator Loss: 1.8889\nEpoch 31/100... Discriminator Loss: 0.7654... Generator Loss: 2.5814\nEpoch 32/100... Discriminator Loss: 0.6920... Generator Loss: 2.8554\nEpoch 33/100... Discriminator Loss: 1.0809... Generator Loss: 1.2462\nEpoch 34/100... Discriminator Loss: 0.9422... Generator Loss: 1.5173\nEpoch 35/100... Discriminator Loss: 0.8204... Generator Loss: 2.6954\nEpoch 36/100... Discriminator Loss: 0.8729... Generator Loss: 2.2865\nEpoch 37/100... Discriminator Loss: 0.8181... Generator Loss: 2.4516\nEpoch 38/100... Discriminator Loss: 0.9311... Generator Loss: 2.0473\nEpoch 39/100... Discriminator Loss: 1.0327... Generator Loss: 1.5652\nEpoch 40/100... Discriminator Loss: 0.8301... Generator Loss: 2.0411\nEpoch 41/100... Discriminator Loss: 0.7795... Generator Loss: 2.1841\nEpoch 42/100... Discriminator Loss: 0.9040... Generator Loss: 2.1737\nEpoch 43/100... Discriminator Loss: 0.8392... Generator Loss: 2.4014\nEpoch 44/100... Discriminator Loss: 1.0186... Generator Loss: 1.9242\nEpoch 45/100... Discriminator Loss: 0.8764... Generator Loss: 1.9522\nEpoch 46/100... Discriminator Loss: 0.9453... Generator Loss: 2.1546\nEpoch 47/100... Discriminator Loss: 0.7211... Generator Loss: 2.5337\nEpoch 48/100... Discriminator Loss: 0.9272... Generator Loss: 2.2453\nEpoch 49/100... Discriminator Loss: 0.8850... Generator Loss: 2.4347\nEpoch 50/100... Discriminator Loss: 0.9238... Generator Loss: 2.5056\nEpoch 51/100... Discriminator Loss: 0.9646... Generator Loss: 2.1953\nEpoch 52/100... Discriminator Loss: 1.0122... Generator Loss: 1.5862\nEpoch 53/100... Discriminator Loss: 1.0739... Generator Loss: 1.8533\nEpoch 54/100... Discriminator Loss: 1.0778... Generator Loss: 1.5303\nEpoch 55/100... Discriminator Loss: 0.8475... Generator Loss: 1.8632\nEpoch 56/100... Discriminator Loss: 0.9253... Generator Loss: 1.9829\nEpoch 57/100... Discriminator Loss: 1.0153... Generator Loss: 1.6882\nEpoch 58/100... Discriminator Loss: 0.8303... Generator Loss: 1.9950\nEpoch 59/100... Discriminator Loss: 1.0152... Generator Loss: 2.6456\nEpoch 60/100... Discriminator Loss: 0.9813... Generator Loss: 1.8391\nEpoch 61/100... Discriminator Loss: 1.1682... Generator Loss: 1.8840\nEpoch 62/100... Discriminator Loss: 0.9663... Generator Loss: 1.5623\nEpoch 63/100... Discriminator Loss: 0.9190... Generator Loss: 1.8654\nEpoch 64/100... Discriminator Loss: 1.0840... Generator Loss: 2.2078\nEpoch 65/100... Discriminator Loss: 1.1358... Generator Loss: 1.7393\nEpoch 66/100... Discriminator Loss: 0.9838... Generator Loss: 1.8375\nEpoch 67/100... Discriminator Loss: 1.0800... Generator Loss: 1.8675\nEpoch 68/100... Discriminator Loss: 0.8570... Generator Loss: 2.2470\nEpoch 69/100... Discriminator Loss: 0.7937... Generator Loss: 2.4699\nEpoch 70/100... Discriminator Loss: 0.9011... Generator Loss: 1.6207\nEpoch 71/100... Discriminator Loss: 0.9911... Generator Loss: 1.7961\nEpoch 72/100... Discriminator Loss: 1.1621... Generator Loss: 1.6099\nEpoch 73/100... Discriminator Loss: 1.0010... Generator Loss: 2.0243\nEpoch 74/100... Discriminator Loss: 1.1576... Generator Loss: 1.3836\nEpoch 75/100... Discriminator Loss: 0.9690... Generator Loss: 1.5541\nEpoch 76/100... Discriminator Loss: 1.1048... Generator Loss: 1.8881\nEpoch 77/100... Discriminator Loss: 0.9246... Generator Loss: 2.3993\nEpoch 78/100... Discriminator Loss: 0.8992... Generator Loss: 2.1767\nEpoch 79/100... Discriminator Loss: 0.9884... Generator Loss: 2.0888\nEpoch 80/100... Discriminator Loss: 0.8688... Generator Loss: 1.6902\nEpoch 81/100... Discriminator Loss: 0.9019... Generator Loss: 2.1423\nEpoch 82/100... Discriminator Loss: 1.0783... Generator Loss: 2.6045\nEpoch 83/100... Discriminator Loss: 0.9570... Generator Loss: 1.8313\nEpoch 84/100... Discriminator Loss: 1.0798... Generator Loss: 1.4993\nEpoch 85/100... Discriminator Loss: 1.0948... Generator Loss: 2.0663\nEpoch 86/100... Discriminator Loss: 1.1997... Generator Loss: 1.9464\nEpoch 87/100... Discriminator Loss: 0.8064... Generator Loss: 2.1125\nEpoch 88/100... Discriminator Loss: 1.0408... Generator Loss: 1.4917\nEpoch 89/100... Discriminator Loss: 1.0058... Generator Loss: 1.6690\nEpoch 90/100... Discriminator Loss: 0.9585... Generator Loss: 1.6885\nEpoch 91/100... Discriminator Loss: 0.8646... Generator Loss: 2.0248\nEpoch 92/100... Discriminator Loss: 0.9342... Generator Loss: 1.7063\nEpoch 93/100... Discriminator Loss: 1.1911... Generator Loss: 1.4487\nEpoch 94/100... Discriminator Loss: 1.1013... Generator Loss: 1.4278\nEpoch 95/100... Discriminator Loss: 1.1815... Generator Loss: 1.6715\nEpoch 96/100... Discriminator Loss: 1.1513... Generator Loss: 1.4364\nEpoch 97/100... Discriminator Loss: 1.0455... Generator Loss: 1.5213\nEpoch 98/100... Discriminator Loss: 1.0629... Generator Loss: 1.7066\nEpoch 99/100... Discriminator Loss: 1.1133... Generator Loss: 1.8021\nEpoch 100/100... Discriminator Loss: 1.0635... Generator Loss: 1.9274\n" ] ], [ [ "## Training loss\n\nHere we'll check out the training losses for the generator and discriminator.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nlosses = np.array(losses)\nplt.plot(losses.T[0], label='Discriminator')\nplt.plot(losses.T[1], label='Generator')\nplt.title(\"Training Losses\")\nplt.legend()", "_____no_output_____" ] ], [ [ "## Generator samples from training\n\nHere we can view samples of images from the generator. First we'll look at images taken while training.", "_____no_output_____" ] ], [ [ "def view_samples(epoch, samples):\n fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True)\n for ax, img in zip(axes.flatten(), samples[epoch]):\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n im = ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n \n return fig, axes", "_____no_output_____" ], [ "# Load samples from generator taken while training\nwith open('train_samples.pkl', 'rb') as f:\n samples = pkl.load(f)", "_____no_output_____" ] ], [ [ "These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 5, 7, 3, 0, 9. Since this is just a sample, it isn't representative of the full range of images this generator can make.", "_____no_output_____" ] ], [ [ "_ = view_samples(-1, samples)", "_____no_output_____" ] ], [ [ "Below I'm showing the generated images as the network was training, every 10 epochs. With bonus optical illusion!", "_____no_output_____" ] ], [ [ "rows, cols = 10, 6\nfig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True)\n\nfor sample, ax_row in zip(samples[::int(len(samples)/rows)], axes):\n for img, ax in zip(sample[::int(len(sample)/cols)], ax_row):\n ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)", "_____no_output_____" ] ], [ [ "It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise. Looks like 1, 9, and 8 show up first. Then, it learns 5 and 3.", "_____no_output_____" ], [ "## Sampling from the generator\n\nWe can also get completely new images from the generator by using the checkpoint we saved after training. We just need to pass in a new latent vector $z$ and we'll get new samples!", "_____no_output_____" ] ], [ [ "saver = tf.train.Saver(var_list=g_vars)\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, n_units=g_hidden_size, reuse=True, alpha=alpha),\n feed_dict={input_z: sample_z})\nview_samples(0, [gen_samples])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
ecf9c5b1f8417ec86ea0db53147376bd34d4d448
103,143
ipynb
Jupyter Notebook
0-Introduction.ipynb
duncanmmacleod/iss-2021-tutorial
89295b146e1045438155b62a434e0da73cfd620f
[ "MIT" ]
1
2021-07-14T13:38:50.000Z
2021-07-14T13:38:50.000Z
0-Introduction.ipynb
duncanmmacleod/iss-2021-tutorial
89295b146e1045438155b62a434e0da73cfd620f
[ "MIT" ]
null
null
null
0-Introduction.ipynb
duncanmmacleod/iss-2021-tutorial
89295b146e1045438155b62a434e0da73cfd620f
[ "MIT" ]
null
null
null
420.991837
50,217
0.940723
[ [ [ "# Gravitational Waves", "_____no_output_____" ], [ "## Introduction\n\nWelcome to this introductory workshop on Gravitational Waves and gravitational-wave data analysis.\nIn this notebook, and the others that follow it, we will cover the following concepts and techniques:\n\n- what are gravitational waves? [this notebook]\n- how can I investigate gravitational-wave data?\n- how are gravitational-waves detected in noisy data?\n\n### Who am I?\n\nMy name is Duncan Macleod, Senior Research Software Engineer at Cardiff University.\nI am chair of the LIGO Scientific Collaboration's (LSC) Computing and Software Group, tasked with coordinating the various computing support activities that enable the research programme of the collaboration and its partners (KAGRA, and Virgo).\n\nI am the creator and principal maintainer of some widely used software packages that enable easy access to and study of GW detector data, which we will use later in the workshop.\n\n### About this tutorial\n\nThis tutorial is a streamlined version of tutorials that were previously prepared and delivered as part of the [Gravitational-Wave Open Data Workshop series](https://www.gw-openscience.org/workshops/); that series includes hours of introductory talks that describe the science behind gravitational waves and the detectors, as well as the methods we use to study detector data to clean noise and extract signals.\n\nEach tutorial here is written as a [Jupyter notebook](https://jupyter.org/), an interactive document that combines text content alonside code that can be executed using a web browser interface. In all examples here the programming language is [Python](https://python.org).\n\n[Python](https://python.org) is a high-level programming language that has a very intuitive syntax, meaning its easy to learn and use, but also can communicate with low-level languages like C to create high-performance code.\nIn the LSC almost every science working group uses Python to develop user interfaces and pre- and post-processing libraries, while the expensive calculations are written in C.\nWe rely heavily on open-source commnunity-developed software at every level, and (almost all of) our code is also open-source, meaning you can freely access it, use it, and modify it (within reason).\n\n### How to follow along interactively\n\nYou can follow along with the material live on Google Colaboratory by visiting this link:\n\n<https://colab.research.google.com/github/duncanmmacleod/iss-2021-tutorial/>\n\nOr on Binder:\n\n[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gl/duncanmmacleod%2Fiss-2021-tutorial/main)\n\nOr by cloning the git repository onto your own machine and running `jupyter-notebook` manually:\n\n```bash\ngit clone https://github.com/duncanmmacleod/iss-2021-tutorial.git\ncd iss-2021-tutorial\njupyter-notebook\n```\n\n<div class=\"alert alert-warning\">\n Visitors from China might not be able to see the content on github.com, you can replace <code>github.com</code> with <code>gitlab.com</code> when cloning the git repository\n</div>", "_____no_output_____" ], [ "## What are gravitational waves\n\nThis video produced in Cardiff in 2016 explains the basics:", "_____no_output_____" ] ], [ [ "from IPython.display import YouTubeVideo\nYouTubeVideo(\"Lcxt097G4Ps\", width=560, height=315)", "_____no_output_____" ] ], [ [ "In summary:\n\n- gravitational waves are emitted by massive objects moving around\n- we need _really_ massive objects doing crazy things to get enough radiation to be detectable from the Earth\n- the LIGO detectors in the USA, KAGRA in Japan, and Virgo in Italy have been detecting gravitational waves since 2015", "_____no_output_____" ], [ "## What does a gravitational-wave signal look like?", "_____no_output_____" ] ], [ [ "YouTubeVideo(\"1agm33iEAuo\", width=560, height=315)", "_____no_output_____" ] ], [ [ "## How does a gravitational wave detector work?", "_____no_output_____" ] ], [ [ "YouTubeVideo(\"UA1qG7Fjc2A\", width=560, height=315)", "_____no_output_____" ] ], [ [ "## Recap\n\nWhat have we learned:\n\n- gravitational waves are emitted by accelerating massive objects, but have tiny amplitudes\n- the LIGO detectors detected the first GW signal from a binary black hole merger in 2015, and have detected dozens more signals with KAGRA and Virgo since then\n- GW signals from binary mergers have a distinctive oscillatory signature that can be modelled accurately (sort of)\n- GW detectors use lasers to measure relative displacement in long arms of an interferometer to detect disturbances caused by passing GW signals\n\nNow that we know everything there is to know about gravitational waves, lets start playing with data!\n\n<a class=\"btn btn-primary\" href=\"./1-OpenData.ipynb\" target=\"_blank\" role=\"button\">Click here</a> to open the next notebook.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecf9d595d09c2efd613c79362e0d2c73b67bf93c
392,643
ipynb
Jupyter Notebook
deeplearning1/nbs/lesson1-redux-3.ipynb
klazuka/courses
69f0d2f5c12963bec9b1d5dabb1c320caaacb444
[ "Apache-2.0" ]
null
null
null
deeplearning1/nbs/lesson1-redux-3.ipynb
klazuka/courses
69f0d2f5c12963bec9b1d5dabb1c320caaacb444
[ "Apache-2.0" ]
null
null
null
deeplearning1/nbs/lesson1-redux-3.ipynb
klazuka/courses
69f0d2f5c12963bec9b1d5dabb1c320caaacb444
[ "Apache-2.0" ]
null
null
null
713.896364
176,336
0.951465
[ [ [ "# Dogs V Cats (data augmentation edition)", "_____no_output_____" ], [ "Applies data augmentation to the input images and runs for several epochs", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "Define path to data: (It's a good idea to put it in a subdirectory of your notebooks folder, and then exclude that directory from git control by adding it to .gitignore.)", "_____no_output_____" ] ], [ [ "root_path = \"data/dogscats-redux/\"\nweights_path = root_path + 'keith_weights_1.h5'\n\npath = root_path\n#path = root_path + \"sample/\"", "_____no_output_____" ] ], [ [ "A few basic libraries that we'll need for the initial exercises:", "_____no_output_____" ] ], [ [ "from __future__ import division,print_function\n\nimport os, json, shutil, random, math\nfrom glob import glob\nimport numpy as np\nnp.set_printoptions(precision=4, linewidth=100)\nfrom matplotlib import pyplot as plt", "_____no_output_____" ] ], [ [ "We have created a file most imaginatively called 'utils.py' to store any little convenience functions we'll want to use. We will discuss these as we use them.", "_____no_output_____" ] ], [ [ "import utils; reload(utils)\nfrom utils import plots", "Using cuDNN version 5103 on context None\nMapped name None to device cuda: Tesla K80 (9F07:00:00.0)\nUsing Theano backend.\n" ], [ "def predict_and_show(batches):\n imgs, labels = next(batches)\n preds, indexes, predicted_labels = vgg.predict(imgs)\n true_labels = [vgg.classes[idx] for idx in np.argmax(labels, axis=1)]\n plots(imgs, titles=['ok' if a == b else 'wrong' for (a,b) in zip(true_labels, predicted_labels)])", "_____no_output_____" ], [ "from keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator()", "_____no_output_____" ] ], [ [ "## Use our Vgg16 class to finetune a Dogs vs Cats model\n\nTo change our model so that it outputs \"cat\" vs \"dog\", instead of one of 1,000 very specific categories, we need to use a process called \"finetuning\". Finetuning looks from the outside to be identical to normal machine learning training - we provide a training set with data and labels to learn from, and a validation set to test against. The model learns a set of parameters based on the data provided.\n\nHowever, the difference is that we start with a model that is already trained to solve a similar problem. The idea is that many of the parameters should be very similar, or the same, between the existing model, and the model we wish to create. Therefore, we only select a subset of parameters to train, and leave the rest untouched. This happens automatically when we call *fit()* after calling *finetune()*.\n\nWe create our batches just like before, and making the validation set available as well. A 'batch' (or *mini-batch* as it is commonly known) is simply a subset of the training data - we use a subset at a time when training or predicting, in order to speed up training, and to avoid running out of memory.", "_____no_output_____" ] ], [ [ "batch_size=64", "_____no_output_____" ], [ "import vgg16; reload(vgg16)", "_____no_output_____" ], [ "vgg = vgg16.Vgg16()\nbatches = vgg.get_batches(path+'train', gen=train_datagen, batch_size=batch_size)\nvalidation_batches = vgg.get_batches(path+'validation', gen=test_datagen, batch_size=batch_size)", "using vgg16 weights & architecture\nFound 20000 images belonging to 2 classes.\nFound 5000 images belonging to 2 classes.\n" ] ], [ [ "Calling *finetune()* modifies the model such that it will be trained based on the data in the batches provided - in this case, to predict either 'dog' or 'cat'.", "_____no_output_____" ] ], [ [ "vgg.finetune(batches)", "_____no_output_____" ] ], [ [ "Finally, we *fit()* the parameters of the model using the training data, reporting the accuracy on the validation set after every epoch. (An *epoch* is one full pass through the training data.)", "_____no_output_____" ] ], [ [ "hist = vgg.fit(batches, validation_batches, nb_epoch=3)", "Epoch 1/3\n20000/20000 [==============================] - 1100s - loss: 0.1492 - acc: 0.9602 - val_loss: 0.0574 - val_acc: 0.9832\nEpoch 2/3\n20000/20000 [==============================] - 499s - loss: 0.1220 - acc: 0.9718 - val_loss: 0.0717 - val_acc: 0.9816\nEpoch 3/3\n20000/20000 [==============================] - 507s - loss: 0.1129 - acc: 0.9748 - val_loss: 0.0563 - val_acc: 0.9892\n" ], [ "def plot_train_validation_curves(title, training_series, validation_series):\n num_epochs = len(training_series)\n epochs = range(1, num_epochs + 1)\n plt.plot(epochs, validation_series, label='validation')\n plt.plot(epochs, training_series, label='train')\n plt.xlabel('Epochs')\n plt.ylabel(title)\n plt.title(title)\n plt.legend()\n plt.grid(True)\n plt.show()", "_____no_output_____" ], [ "plot_train_validation_curves('Accuracy', hist.history['acc'], hist.history['val_acc'])\nplot_train_validation_curves('Loss', hist.history['loss'], hist.history['val_loss'])", "_____no_output_____" ] ], [ [ "# Try it out", "_____no_output_____" ] ], [ [ "dummy_batches = vgg.get_batches(path+'train', batch_size=6)", "Found 20000 images belonging to 2 classes.\n" ], [ "imgs, labels = next(dummy_batches)\nplots(imgs, titles=labels)", "_____no_output_____" ], [ "vgg.predict(imgs)", "_____no_output_____" ], [ "predict_and_show(dummy_batches)", "_____no_output_____" ] ], [ [ "# Kaggle Submission", "_____no_output_____" ] ], [ [ "test_batches = vgg.get_batches(path + 'test', gen=test_datagen, batch_size=32, class_mode=None, shuffle=False)", "Found 12500 images belonging to 1 classes.\n" ], [ "dog_predictions = vgg.model.predict_generator(test_batches, test_batches.nb_sample)[:,1]\ndog_predictions[:5]", "_____no_output_____" ] ], [ [ "Extract the id of each image in the test batch because Keras ImageDataGenerator will enumerate them in lexical order", "_____no_output_____" ] ], [ [ "ids = [int(x.split(\"/\")[1].split(\".\")[0]) for x in test_batches.filenames]\nids[:5]", "_____no_output_____" ] ], [ [ "fill out the submission table", "_____no_output_____" ] ], [ [ "with open(root_path + 'keith_submission_3.csv', 'w') as f:\n f.write('id,label\\n')\n for i in range(len(ids)):\n f.write('{},{}\\n'.format(ids[i], dog_predictions[i]))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecf9ddb1f20ccaa9bd8e868a8f1d58ac4ec01a5c
50,637
ipynb
Jupyter Notebook
machine_learning/ML_coverage_provided.ipynb
ArtTucker/mental_health_and_economics
4112d769df4efb6405665efd8fe02b0c2e3fa5dd
[ "MIT" ]
1
2021-05-09T23:19:55.000Z
2021-05-09T23:19:55.000Z
machine_learning/ML_coverage_provided.ipynb
ArtTucker/mental_health_and_economics
4112d769df4efb6405665efd8fe02b0c2e3fa5dd
[ "MIT" ]
17
2021-04-19T10:48:53.000Z
2022-02-08T18:39:15.000Z
machine_learning/ML_coverage_provided.ipynb
ArtTucker/mental_health_and_economics
4112d769df4efb6405665efd8fe02b0c2e3fa5dd
[ "MIT" ]
1
2021-04-26T04:48:14.000Z
2021-04-26T04:48:14.000Z
41.539787
8,104
0.461816
[ [ [ "import pandas as pd\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Dependencies for interaction with database:\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\n\n\n# Machine Learning dependencies:\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\n# Validation libraries\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score, mean_squared_error, precision_recall_curve\nfrom sklearn.model_selection import cross_val_score\n\nfrom collections import Counter\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom imblearn.metrics import classification_report_imbalanced", "_____no_output_____" ], [ "# Create engine and link to local postgres database:\nengine = create_engine('postgresql://postgres:[email protected]:5432/postgres')\nconnect = engine.connect()", "_____no_output_____" ], [ "# Create session:\nsession = Session(engine)\n", "_____no_output_____" ], [ "# Import clean_dataset_2016 table:\nclean_2016_df = pd.read_sql(sql = 'SELECT * FROM \"survey_2016\"',con=connect)", "_____no_output_____" ], [ "clean_2016_df.head()", "_____no_output_____" ], [ "# Check data for insights:\nprint(clean_2016_df.shape)\nprint(clean_2016_df.columns.tolist())\nprint(clean_2016_df.value_counts)", "(1004, 55)\n['SurveyID', 'new_id', 'self_employed', 'company_size', 'tech_company', 'mh_coverage', 'mh_coverage_awareness', 'mh_employer_discussion', 'mh_resources_provided', 'mh_anonimity', 'mh_medical_leave', 'mh_discussion_negative_impact', 'ph_discussion_negative_impact', 'mh_discussion_coworkers', 'mh_discussion_supervisors', 'mh_equal_ph', 'mh_observed_consequences_coworkers', 'prev_employers', 'prev_mh_benefits', 'prev_mh_benefits_awareness', 'prev_mh_discussion', 'prev_mh_resources', 'prev_mh_anonimity', 'prev_mh_discuss_negative_consequences', 'prev_ph_discuss_negative_consequences', 'prev_mh_discussion_coworkers', 'prev_mh_discussion_supervisors', 'prev_mh_importance_employer', 'prev_mh_consequences_coworkers', 'future_ph_specification', 'future_mh_specification', 'mh_hurt_on_career', 'mh_neg_view_coworkers', 'mh_sharing_friends_family', 'mh_bad_response_workplace', 'mh_for_others_bad_response_workplace', 'mh_family_history', 'mh_dx_past', 'mh_dx_current', 'yes_what_dx?', 'mh_dx_pro', 'yes_condition_dx', 'mh_sought_pro_tx', 'mh_eff_tx_impact_on_work', 'mh_not_eff_tx_impact_on_work', 'age', 'gender', 'country_live', 'live_us_state', 'country_work', 'work_us_state', 'work_position', 'remote', 'quantile_age_1', 'quantile_age_2']\n<bound method DataFrame.value_counts of SurveyID new_id self_employed company_size tech_company \\\n0 2016 1 0 26-100 1 \n1 2016 2 0 25-Jun 1 \n2 2016 3 0 25-Jun 1 \n3 2016 4 0 25-Jun 0 \n4 2016 5 0 More than 1000 1 \n... ... ... ... ... ... \n999 2016 1003 0 100-500 1 \n1000 2016 1004 0 500-1000 1 \n1001 2016 1005 0 100-500 1 \n1002 2016 1006 0 100-500 0 \n1003 2016 1007 0 100-500 1 \n\n mh_coverage mh_coverage_awareness \\\n0 Not eligible for coverage / N/A I am not sure \n1 No Yes \n2 No I am not sure \n3 Yes Yes \n4 Yes I am not sure \n... ... ... \n999 I don't know I am not sure \n1000 Yes No \n1001 Yes Yes \n1002 I don't know I am not sure \n1003 Yes No \n\n mh_employer_discussion mh_resources_provided mh_anonimity ... age \\\n0 No No I don't know ... 39 \n1 Yes Yes Yes ... 29 \n2 No No I don't know ... 38 \n3 No No No ... 43 \n4 No Yes Yes ... 42 \n... ... ... ... ... .. \n999 No I don't know I don't know ... 26 \n1000 No No Yes ... 38 \n1001 Yes Yes I don't know ... 52 \n1002 No Yes I don't know ... 30 \n1003 No No I don't know ... 25 \n\n gender country_live live_us_state \\\n0 male United Kingdom none \n1 male United States of America Illinois \n2 male United Kingdom none \n3 female United States of America Illinois \n4 male United Kingdom none \n... ... ... ... \n999 female Canada none \n1000 female United States of America Illinois \n1001 male United States of America Georgia \n1002 female United States of America Nebraska \n1003 nonbinary Canada none \n\n country_work work_us_state \\\n0 United Kingdom none \n1 United States of America Illinois \n2 United Kingdom none \n3 United States of America Illinois \n4 United Kingdom none \n... ... ... \n999 Canada none \n1000 United States of America Illinois \n1001 United States of America Georgia \n1002 United States of America Nebraska \n1003 Canada none \n\n work_position remote \\\n0 Back-end Developer Sometimes \n1 Back-end Developer|Front-end Developer Never \n2 Back-end Developer Always \n3 Executive Leadership|Supervisor/Team Lead|Dev ... Sometimes \n4 DevOps/SysAdmin|Support|Back-end Developer|Fro... Sometimes \n... ... ... \n999 Other Sometimes \n1000 Support Always \n1001 Back-end Developer Sometimes \n1002 DevOps/SysAdmin Sometimes \n1003 Other Sometimes \n\n quantile_age_1 quantile_age_2 \n0 (38.0, 99.0] (37.0, 39.0] \n1 (28.0, 32.0] (27.0, 29.0] \n2 (32.0, 38.0] (37.0, 39.0] \n3 (38.0, 99.0] (39.0, 44.0] \n4 (38.0, 99.0] (39.0, 44.0] \n... ... ... \n999 (19.999, 28.0] (25.0, 27.0] \n1000 (32.0, 38.0] (37.0, 39.0] \n1001 (38.0, 99.0] (44.0, 99.0] \n1002 (28.0, 32.0] (29.0, 30.0] \n1003 (19.999, 28.0] (19.0, 25.0] \n\n[1004 rows x 55 columns]>\n" ], [ "##Test:\n#Dataset filtered on tech_company = \"yes\"\n#Target: \n#Features: company_size, age, gender, country_live, identified_with_mh, mh_employer, employer_discus_mh, employer_provide_mh_coverage,treatment_mh_from_professional, employers_options_help, protected_anonymity_mh", "_____no_output_____" ], [ "# Filter tech_or_not columns:\nclean_2016_df[\"tech_company\"].head()", "_____no_output_____" ], [ "tech_df = pd.read_sql('SELECT * FROM \"survey_2016\" WHERE \"tech_company\" = 1', connect)\ntech_df.shape", "_____no_output_____" ], [ "ml_df = tech_df[[\"mh_sought_pro_tx\",\"company_size\",\"mh_coverage\",\"mh_coverage_awareness\",\"mh_resources_provided\",\"mh_anonimity\",\"age\",\"gender\"]]\nml_df", "_____no_output_____" ], [ "# Encode dataset:\n\n# Create label encoder instance:\nle = LabelEncoder()\n\n# Make a copy of desire data:\nencoded_df = ml_df.copy()\n\n# Apply encoder:\n#encoded_df[\"age\"] = le.fit_transform(encoded_df[\"age\"] )\n#encoded_df[\"company_size\"] = le.fit_transform(encoded_df[\"company_size\"])\n#encoded_df[\"gender\"] = le.fit_transform(encoded_df[\"gender\"])\n#encoded_df[\"country_live\"] = le.fit_transform(encoded_df[\"country_live\"])\n#encoded_df[\"identified_with_mh\"] = le.fit_transform(encoded_df[\"identified_with_mh\"])\n#encoded_df[\"dx_mh_disorder\"] = le.fit_transform(encoded_df[\"dx_mh_disorder\"])\n#encoded_df[\"employer_discus_mh\"] = le.fit_transform(encoded_df[\"employer_discus_mh\"])\n#encoded_df[\"mh_employer\"] = le.fit_transform(encoded_df[\"mh_employer\"])\n#encoded_df[\"treatment_mh_from_professional\"] = le.fit_transform(encoded_df[\"treatment_mh_from_professional\"])\n#encoded_df[\"employer_provide_mh_coverage\"] = le.fit_transform(encoded_df[\"employer_provide_mh_coverage\"])\n#encoded_df[\"employers_options_help\"] = le.fit_transform(encoded_df[\"employers_options_help\"])\n#encoded_df[\"protected_anonymity_mh\"] = le.fit_transform(encoded_df[\"protected_anonymity_mh\"])\n\nfeatures = encoded_df.columns.tolist()\nfor feature in features:\n encoded_df[feature] = le.fit_transform(encoded_df[feature])\n \n# Check:\nencoded_df.head()", "_____no_output_____" ], [ "from sklearn.preprocessing import OneHotEncoder\nencoder = OneHotEncoder(sparse = False)\n\nencoded_df1 = ml_df.copy()\n\n# Apply encoder:\nencoded_df1 = encoder.fit_transform(encoded_df1)\nencoded_df1", "_____no_output_____" ], [ "# Create our target:\ny = encoded_df[\"mh_sought_pro_tx\"]\n\n# Create our features:\nX = encoded_df.drop(columns = \"mh_sought_pro_tx\", axis =1)", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, \n y, \n random_state=1, \n stratify=y)\nX_train.shape", "_____no_output_____" ], [ "from sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(solver='lbfgs',\n max_iter=200,\n random_state=1)", "_____no_output_____" ], [ "classifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = classifier.predict(X_test)\nresults = pd.DataFrame({\"Prediction\": y_pred, \"Actual\": y_test}).reset_index(drop=True)\nresults.head(20)\n", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test, y_pred))", "0.59375\n" ], [ "from sklearn.metrics import confusion_matrix, classification_report\nmatrix = confusion_matrix(y_test,y_pred)\nprint(matrix)", "[[27 49]\n [29 87]]\n" ], [ "report = classification_report(y_test, y_pred)\nprint(report)", " precision recall f1-score support\n\n 0 0.48 0.36 0.41 76\n 1 0.64 0.75 0.69 116\n\n accuracy 0.59 192\n macro avg 0.56 0.55 0.55 192\nweighted avg 0.58 0.59 0.58 192\n\n" ], [ "#confusion matrix visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nf, ax=plt.subplots(figsize=(5,5))\nsns.heatmap(matrix,annot=True,linewidths=0.5,linecolor=\"red\",fmt=\".0f\",ax=ax)\nplt.xlabel(\"y_pred\")\nplt.ylabel(\"y_true\")\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecf9e46b565058f460ff66d3e6d7cfb1a2de6237
47,212
ipynb
Jupyter Notebook
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
christinac22/sqlalchemy-challenge
c19c89900ae8542dc0e9b97957c2d0bf7be4a707
[ "ADSL" ]
null
null
null
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
christinac22/sqlalchemy-challenge
c19c89900ae8542dc0e9b97957c2d0bf7be4a707
[ "ADSL" ]
null
null
null
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
christinac22/sqlalchemy-challenge
c19c89900ae8542dc0e9b97957c2d0bf7be4a707
[ "ADSL" ]
null
null
null
58.941323
14,396
0.750614
[ [ [ "%matplotlib inline\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport datetime as dt", "_____no_output_____" ] ], [ [ "# Reflect Tables into SQLAlchemy ORM", "_____no_output_____" ] ], [ [ "# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func, inspect", "_____no_output_____" ], [ "# create engine to hawaii.sqlite\nengine = create_engine(\"sqlite:///hawaii.sqlite\")", "_____no_output_____" ], [ "# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)", "_____no_output_____" ], [ "# View all of the classes that automap found\nBase.classes.keys()", "_____no_output_____" ], [ "# Save references to each table\nMeasurement= Base.classes.measurement\nStation = Base.classes.station", "_____no_output_____" ], [ "inspector= inspect(engine)\ninspector.get_table_names()", "_____no_output_____" ], [ "columns = inspector.get_columns('measurement')\nfor m in columns:\n print(m['name'], m[\"type\"])", "id INTEGER\nstation TEXT\ndate TEXT\nprcp FLOAT\ntobs FLOAT\n" ], [ "columns = inspector.get_columns('station')\nfor s in columns:\n print(s['name'], s[\"type\"])", "id INTEGER\nstation TEXT\nname TEXT\nlatitude FLOAT\nlongitude FLOAT\nelevation FLOAT\n" ], [ "# Create our session (link) from Python to the DB\nsession = Session(engine)", "_____no_output_____" ] ], [ [ "# Exploratory Precipitation Analysis", "_____no_output_____" ] ], [ [ "# Find the most recent date in the data set.\nrecent_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\nrecent_date", "_____no_output_____" ], [ "# Design a query to retrieve the last 12 months of precipitation data and plot the results. \n# Starting from the most recent data point in the database. \n# Reference 10-Adv-Dta-Storage-Stu_Chinook-Day 3\n\n# Calculate the date one year from the last date in data set.\none_yr_ago = dt.date(2017,8,23) - dt.timedelta(days=365)\none_yr_ago", "_____no_output_____" ], [ "# Perform a query to retrieve the data and precipitation scores\nprcp_info = session.query(Measurement.prcp, Measurement.date).\\\n filter(Measurement.date > one_yr_ago).order_by(Measurement.date).all()\nprcp_info\n\n# Save the query results as a Pandas DataFrame and set the index to the date column\nprcp_info_df = pd.DataFrame(prcp_info, columns = ['Precipitation', 'Date'])\nprcp_info_df\n\nprcp_info_df.set_index('Date').head()\n\n# Sort the dataframe by date\nprcp_by_date = prcp_info_df.sort_values(['Date'], ascending=True)\nprcp_by_date", "_____no_output_____" ], [ "# Use Pandas Plotting with Matplotlib to plot the data\n# Act 05 MAtplotlib- Day 2 - Stu Act 4\n\nprcp_data = prcp_by_date.plot(kind='bar')\nprcp_data.set_xlabel(\"Date\")\nprcp_data.set_ylabel(\"Inches\")\n\nplt.show()\nplt.tight_layout()", "_____no_output_____" ], [ "# Use Pandas to calculate the summary statistics for the precipitation data\nprcp_by_date.describe()", "_____no_output_____" ] ], [ [ "# Exploratory Station Analysis", "_____no_output_____" ] ], [ [ "# Design a query to calculate the total number stations in the dataset\ntotal_station = session.query(func.count(Measurement.station)).all()\ntotal_station", "_____no_output_____" ], [ "# Design a query to find the most active stations (i.e. what stations have the most rows?)\n# List the stations and the counts in descending order.\nmost_active_stations = session.query(Measurement.station, func.count(Measurement.station)).group_by(Measurement.station).\\\n order_by(func.count(Measurement.station).desc()).all()\nmost_active_stations", "_____no_output_____" ], [ "# Using the most active station id from the previous query, calculate the lowest, highest, and average temperature.\n# Day 3 - Activity 3\n\ntemp = [func.min(Measurement.tobs), \n func.max(Measurement.tobs), \n func.avg(Measurement.tobs)]\n\nactive_temp = session.query(*temp).\\\nfilter(Measurement.station == 'USC00519281').all()\nactive_temp\n\n# may_averages = session.query(*sel).\\\n# filter(func.strftime(\"%m\", Dow.date) == \"05\").\\\n# group_by(Dow.stock).\\\n# order_by(Dow.stock).all()\n# may_averages\n", "_____no_output_____" ], [ "# Using the most active station id\n# Query the last 12 months of temperature observation data for this station and plot the results as a histogram\nactive_station_id = session.query(Measurement.tobs).\\\n filter(Measurement.station == 'USC00519281').\\\n filter(Measurement.date > one_yr_ago).\\\n order_by(Measurement.date).all()\nactive_station_id\n\ndf = pd.DataFrame(active_station_id, columns= ['tobs'])\ndf", "_____no_output_____" ], [ "#histogram\n\nplt.hist(df)\nplt.xlabel('Temperature (°F)')\nplt.ylabel('Frequency')\nplt.show()", "_____no_output_____" ] ], [ [ "# Close session", "_____no_output_____" ] ], [ [ "# Close Session\nsession.close()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
ecf9e9f004b926e866989e1aaab4bde169700ac7
1,796
ipynb
Jupyter Notebook
bear_classifier_app.ipynb
giancarlovq/bear_sorter
f024819cf4d17cdf3aec5ae6faa3ac404ea7a893
[ "Apache-2.0" ]
null
null
null
bear_classifier_app.ipynb
giancarlovq/bear_sorter
f024819cf4d17cdf3aec5ae6faa3ac404ea7a893
[ "Apache-2.0" ]
null
null
null
bear_classifier_app.ipynb
giancarlovq/bear_sorter
f024819cf4d17cdf3aec5ae6faa3ac404ea7a893
[ "Apache-2.0" ]
null
null
null
22.734177
95
0.554009
[ [ [ "from fastai.vision.all import *\nfrom fastai.vision.widgets import *", "_____no_output_____" ], [ "path = Path()\nlearn_inf = load_learner(path/'export.pkl', cpu=True)\n\nbtn_upload = widgets.FileUpload()\nout_pl = widgets.Output()\nlbl_pred = widgets.Label()\nbtn_run = widgets.Button(description='Classify')", "_____no_output_____" ], [ "def on_click_classify(change):\n img = PILImage.create(btn_upload.data[-1])\n out_pl.clear_output()\n with out_pl: display(img.to_thumb(128, 128))\n pred, pred_idx, probs = learn_inf.predict(img)\n lbl_pred.value = f'Predicction: {pred}; Probability: {probs[pred_idx]:.04f}'\n \nbtn_run.on_click(on_click_classify)", "_____no_output_____" ], [ "widgets.VBox([widgets.Label('Select your bear!'), btn_upload, out_pl, lbl_pred, btn_run])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
ecf9eb00b4ea59ad5f1b221aa3490b7d90b6f3a8
16,520
ipynb
Jupyter Notebook
max-spacing-k-clustering/max-spacing-k-clustering.ipynb
jazracherif/algorithms
625d79250405df77d57aaacb85759b76654ea36f
[ "MIT" ]
null
null
null
max-spacing-k-clustering/max-spacing-k-clustering.ipynb
jazracherif/algorithms
625d79250405df77d57aaacb85759b76654ea36f
[ "MIT" ]
null
null
null
max-spacing-k-clustering/max-spacing-k-clustering.ipynb
jazracherif/algorithms
625d79250405df77d57aaacb85759b76654ea36f
[ "MIT" ]
3
2020-12-21T23:22:10.000Z
2022-03-18T00:09:27.000Z
33.783231
364
0.492312
[ [ [ "# max-spacing k-clustering.\n\n## Question 1\n\nIn this programming problem and the next you'll code up the clustering algorithm from lecture for computing a max-spacing k-clustering.\n\nThe file clustering1.txt describes a distance function (equivalently, a complete graph with edge costs). It has the following format:\n\n[number_of_nodes]\n\n[edge 1 node 1] [edge 1 node 2] [edge 1 cost]\n\n[edge 2 node 1] [edge 2 node 2] [edge 2 cost]\n\n...\n\nThere is one edge (i,j) for each choice of 1≤i<j≤n, where n is the number of nodes.\n\nFor example, the third line of the file is \"1 3 5250\", indicating that the distance between nodes 1 and 3 (equivalently, the cost of the edge (1,3)) is 5250. You can assume that distances are positive, but you should NOT assume that they are distinct.\n\nYour task in this problem is to run the clustering algorithm from lecture on this data set, where the target number k of clusters is set to 4. What is the maximum spacing of a 4-clustering?\n\nADVICE: If you're not getting the correct answer, try debugging your algorithm using some small test cases. And then post them to the discussion forum!\n\n", "_____no_output_____" ], [ "# Union Find\nImplement the union find data structure with path compression", "_____no_output_____" ] ], [ [ "import random\nimport numpy as np\n\nclass union_find_pc(object): \n def __init__(self, nodes):\n self.leader = [i for i in range(len(nodes))]\n self.rank = [0 for i in range(len(nodes))]\n self.clusters = set([i for i in range(len(nodes))])\n \n def FIND(self, x): \n n = x\n \n while self.leader[n] != n:\n n = self.leader[n]\n \n self.leader[x] = n \n return n\n \n def UNION(self, a, b): \n \n a = self.FIND(a)\n b = self.FIND(b)\n# print (\"parent of a {} - parent of b {}\".format(a,b))\n if (a == b):\n return \n \n if (self.rank[a] == self.rank[b]):\n # make a the leader of b and all its object \n flip = random.random() > 0.5\n# print (\"flip\", flip)\n if flip==1:\n self.leader[b] = a \n self.rank[a] += 1\n else:\n self.leader[a] = b \n self.rank[b] += 1\n \n elif (self.rank[a] > self.rank[b]):\n # make a the leader of b and all its object\n self.leader[b] = a \n else:\n self.leader[a] = b \n \n def getClusters(self): \n n_clusters = []\n for i in range(len(self.leader)):\n if self.leader[i] == i:\n n_clusters.append(i)\n return n_clusters", "_____no_output_____" ] ], [ [ "Test the Union-Find data structure on a simple test case", "_____no_output_____" ] ], [ [ "obj = union_find_pc([0,1,2,3,4])\n\nprint (\"=UNION(0,1)\")\nobj.UNION(0,1)\nprint (obj.FIND(1))\nprint (obj.FIND(2))\nprint (\"leaders\", obj.leader)\nprint (\"rank\", obj.rank)\nprint (\"clusters\", obj.getClusters())\n\nprint (\"=UNION(2,3)\")\nobj.UNION(2,3)\nprint (\"leaders\", obj.leader)\nprint (\"rank\", obj.rank)\nprint (\"clusters\", obj.getClusters())\n\nprint (\"=UNION(0,2)\")\n\nobj.UNION(0,2)\nprint (\"leaders\", obj.leader)\nprint (\"rank\", obj.rank)\nprint (\"clusters\", obj.getClusters())\n\nprint (\"=UNION(0,4)\")\nobj.UNION(0,4)\nprint (\"leaders\", obj.leader)\nprint (\"rank\", obj.rank)\n\nprint (\"clusters\", obj.getClusters())", "=UNION(0,1)\n0\n2\nleaders [0, 0, 2, 3, 4]\nrank [1, 0, 0, 0, 0]\nclusters [0, 2, 3, 4]\n=UNION(2,3)\nleaders [0, 0, 3, 3, 4]\nrank [1, 0, 0, 1, 0]\nclusters [0, 3, 4]\n=UNION(0,2)\nleaders [3, 0, 3, 3, 4]\nrank [1, 0, 0, 2, 0]\nclusters [3, 4]\n=UNION(0,4)\nleaders [3, 0, 3, 3, 3]\nrank [1, 0, 0, 2, 0]\nclusters [3]\n" ] ], [ [ "## Problem 1 Solution", "_____no_output_____" ] ], [ [ "FILE = \"./clustering1.txt\"\n# FILE = \"./clustering1-example-500-solution-2639.txt\"\nK = 4 \nfp = open(FILE, 'r')\n\nn_nodes = int(fp.readline())\n\nedges = []\nvertices = set()\nMAX_WEIGHT = 0\n\nfor row in fp.readlines():\n r = row.strip().split(\" \")\n \n vertices.add(int(r[0]))\n vertices.add(int(r[1]))\n weight = int(r[2])\n if weight > MAX_WEIGHT:\n MAX_WEIGHT = weight\n \n edges.append([int(r[0]),int(r[1]), int(r[2])])\n \nsortedEdges = sorted(edges, key=lambda x: x[2])\n# print (sortedEdges)\n\nvertices = list(vertices)\nv_to_idx = {vertices[i]:i for i in range(len(vertices))}\n\nobj = union_find_pc([i for i in range(n_nodes)])\n\nfor i, edge in enumerate(sortedEdges): \n v1 = v_to_idx[edge[0]]\n v2 = v_to_idx[edge[1]]\n w = edge[2]\n \n obj.UNION(v1, v2)\n \n if len(obj.getClusters()) == 4:\n print (\"final Clusters\", obj.getClusters())\n break\n \nminW = MAX_WEIGHT\nfor i, edge in enumerate(sortedEdges): \n v1 = v_to_idx[edge[0]]\n v2 = v_to_idx[edge[1]]\n w = edge[2]\n \n if obj.FIND(v1) != obj.FIND(v2):\n if w < minW:\n minW = w\nprint (\"maximum spacing\", minW) ", "final Clusters [125, 383, 413, 461]\nmaximum spacing 106\n" ] ], [ [ "## Question 2\n\nin this question your task is again to run the clustering algorithm from lecture, but on a MUCH bigger graph. So big, in fact, that the distances (i.e., edge costs) are only defined implicitly, rather than being provided as an explicit list.\n\nThe data set is below. clustering_big.txt\n\nThe format is:\n\n[# of nodes] [# of bits for each node's label]\n\n[first bit of node 1] ... [last bit of node 1]\n\n[first bit of node 2] ... [last bit of node 2]\n\n...\n\nFor example, the third line of the file \"0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1\" denotes the 24 bits associated with node #2.\n\nThe distance between two nodes u and v in this problem is defined as the Hamming distance--- the number of differing bits --- between the two nodes' labels. For example, the Hamming distance between the 24-bit label of node #2 above and the label \"0 1 0 0 0 1 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 0 1\" is 3 (since they differ in the 3rd, 7th, and 21st bits).\n\nThe question is: what is the largest value of k such that there is a k-clustering with spacing at least 3? That is, how many clusters are needed to ensure that no pair of nodes with all but 2 bits in common get split into different clusters?\n\nNOTE: The graph implicitly defined by the data file is so big that you probably can't write it out explicitly, let alone sort the edges by cost. So you will have to be a little creative to complete this part of the question. For example, is there some way you can identify the smallest distances without explicitly looking at every pair of nodes?", "_____no_output_____" ] ], [ [ "from itertools import combinations\n\ndef distance_0_items(data):\n dist0_present = collections.defaultdict(list)\n dist0_keys = collections.defaultdict(list)\n dist0_list = []\n for i, d in enumerate(data):\n if d in dist0_keys:\n dist0_present[d].append(i)\n else:\n dist0_keys[d] = i\n\n for d in dist0_present:\n dist0_present[d].append(dist0_keys[d])\n\n for k, d in dist0_present.items(): \n # create all combinations of 2 items which match the key\n out = combinations(d, 2)\n for c in out:\n dist0_list.append([c[0], c[1]])\n\n return dist0_list\n\ndef distance_1_items(data, n_bits):\n \n def dist_1(a, n_bits, out, index=None):\n for i in range(n_bits):\n dist_1 = int(a,2) ^ (1 << i) \n # many nodes will generate similar other nodes of distance 1 from themselves\n out[dist_1].append(index) \n \n dist1_present = collections.defaultdict(list)\n dist1_keys = collections.defaultdict(list)\n dist1_list = []\n \n # For each node, generate all other nodes with distance 1 and their idx in a hash table list\n # If a later node is found in the list, then add it to the dist1_present\n for i, d in enumerate(data):\n d_val = int(d,2)\n if d_val in dist1_keys:\n # nodes of distance 1 to d exists, store it in dist1_present\n dist1_present[d_val].append(i)\n dist_1(d, n_bits, dist1_keys, i)\n\n for key, val in dist1_present.items():\n # create all combinations of 2 items which match the key\n for d in val:\n for c in dist1_keys[key]:\n dist1_list.append([d, c])\n\n return dist1_list\n\n\ndef distance_2_items(data, n_bits):\n def dist_2(a, n_bits, out, index=None):\n for i in range(0,n_bits-1):\n for j in range(i+1, n_bits):\n dist_2 = int(a,2) ^ (1 << i) \n dist_2 = dist_2 ^ (1 << j) \n # many nodes will generate similar other nodes of distance 2 from themselves\n out[dist_2].append(index) \n \n dist2_present = collections.defaultdict(list)\n dist2_keys = collections.defaultdict(list)\n dist2_list = []\n \n # For each node, generate all other nodes with distance 1 and their idx in a hash table list\n # If a later node is found in the list, then add it to the dist1_present\n for i, d in enumerate(data):\n d_val = int(d,2)\n if d_val in dist2_keys:\n # nodes of distance 1 to d exists, store it in dist1_present\n dist2_present[d_val].append(i)\n dist_2(d, n_bits, dist2_keys, i)\n\n for key, val in dist2_present.items():\n # create all combinations of 2 items which match the key\n for d in val:\n for c in dist2_keys[key]:\n dist2_list.append([d, c])\n\n return dist2_list\n \ndef solve_p2(data, n_bits, n_nodes):\n dist0_list = distance_0_items(data)\n dist1_list = distance_1_items(data, n_bits)\n dist2_list = distance_2_items(data, n_bits)\n\n obj = union_find_pc([i for i in range(n_nodes)])\n for i, edge in enumerate(dist0_list): \n v1 = edge[0]\n v2 = edge[1] \n obj.UNION(v1, v2)\n\n for i, edge in enumerate(dist1_list): \n v1 = edge[0]\n v2 = edge[1] \n obj.UNION(v1, v2)\n\n for i, edge in enumerate(dist2_list): \n v1 = edge[0]\n v2 = edge[1] \n obj.UNION(v1, v2)\n\n # After clustering together all points of 0, 1, and 2 distance, we get all those points together and all\n # remaining one are further away. Each other point being its own cluster, \n # this is the max number of clusters total\n return len(obj.getClusters())", "_____no_output_____" ], [ "TEST_CASES = [ \n [\"./clustering2-example-200-12-solution-4.txt\", 4],\n [\"./clustering2-example-200-12-solution-6.txt\", 6],\n [\"clustering2-example-2000-24-solution-1575.txt\", 1575]\n ]\n\nfor test in TEST_CASES:\n file = test[0]\n solution = test[1]\n \n fp = open(file, 'r')\n n_nodes, n_bits = fp.readline().strip().split(\" \")\n n_nodes, n_bits = int(n_nodes), int(n_bits)\n\n data = []\n for row in fp.readlines():\n a = \"\".join(row.strip().split(\" \"))\n data.append(a)\n\n solved = solve_p2(data, n_bits, n_nodes)\n\n assert (solved == solution), (\"Expected {}, got {}, file {}\").format(solution, solved, file)\n \nprint (\"PASSED ALL TESTS!\")", "PASSED ALL TESTS!\n" ] ], [ [ "## Problem 2 Solution", "_____no_output_____" ] ], [ [ "FILE = \"./clustering_big.txt\"\n\nfp = open(FILE, 'r')\nn_nodes, n_bits = fp.readline().strip().split(\" \")\nn_nodes, n_bits = int(n_nodes), int(n_bits)\n\ndata = []\nfor row in fp.readlines():\n a = \"\".join(row.strip().split(\" \"))\n data.append(a)\n\nsolved = solve_p2(data, n_bits, n_nodes)\n\nprint (\"P2 Solution\", solved)\n", "P2 Solution 6118\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
ecf9ee53b2c09e3fca063a0abc05ea87cb485216
47,816
ipynb
Jupyter Notebook
Nbs/00_ModelConstructor.ipynb
ayasyrev/model_constructor
3759a02dd9f7aa1ca3e6a4a5aefe72380886207e
[ "Apache-2.0" ]
3
2020-08-02T09:18:27.000Z
2021-12-22T07:43:37.000Z
Nbs/00_ModelConstructor.ipynb
ayasyrev/model_constructor
3759a02dd9f7aa1ca3e6a4a5aefe72380886207e
[ "Apache-2.0" ]
16
2020-11-09T11:35:13.000Z
2021-12-23T13:04:54.000Z
Nbs/00_ModelConstructor.ipynb
ayasyrev/model_constructor
3759a02dd9f7aa1ca3e6a4a5aefe72380886207e
[ "Apache-2.0" ]
2
2020-04-08T20:56:48.000Z
2021-01-20T13:37:52.000Z
29.922403
949
0.502133
[ [ [ "# Model constructor.\n\n> Create and tune pytorch model.", "_____no_output_____" ] ], [ [ "#hide", "_____no_output_____" ], [ "#hide\nimport torch\nimport torch.nn as nn\n\nfrom nbdev.showdoc import show_doc\nfrom IPython.display import Markdown, display", "_____no_output_____" ], [ "# hide\ndef print_doc(func_name):\n doc = show_doc(func_name, title_level=4, disp=False)\n display(Markdown(doc))", "_____no_output_____" ] ], [ [ "## ResBlock", "_____no_output_____" ] ], [ [ "#hide\nfrom model_constructor.model_constructor import ResBlock", "_____no_output_____" ], [ "#hide_input\nprint_doc(ResBlock)", "_____no_output_____" ], [ "block = ResBlock(1,64,64,sa=True)\nblock", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 64, 32, 32)\ny = block(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 64, 32, 32]), f\"size\"", "torch.Size([16, 64, 32, 32])\n" ], [ "block = ResBlock(4,64,64,sa=True, dw=True)\nblock", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 256, 32, 32)\ny = block(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 256, 32, 32]), f\"size\"", "torch.Size([16, 256, 32, 32])\n" ], [ "block = ResBlock(4,64,64,sa=True, groups=4)\nblock", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 256, 32, 32)\ny = block(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 256, 32, 32]), f\"size\"", "torch.Size([16, 256, 32, 32])\n" ], [ "block = ResBlock(2,64,64,act_fn=nn.LeakyReLU(), bn_1st=False)\nblock", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 128, 32, 32)\ny = block(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 128, 32, 32]), f\"size\"", "torch.Size([16, 128, 32, 32])\n" ], [ "block = ResBlock(2, 64, 64, sa=True, se=True)\nblock", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 128, 32, 32)\ny = block(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 128, 32, 32]), f\"size\"", "torch.Size([16, 128, 32, 32])\n" ] ], [ [ "## Stem, Body, Head", "_____no_output_____" ] ], [ [ "#hide\nfrom model_constructor.model_constructor import _make_body, _make_head, _make_layer, _make_stem", "_____no_output_____" ], [ "#hide_input\nprint_doc(_make_layer)", "_____no_output_____" ], [ "#hide_input\nprint_doc(_make_stem)", "_____no_output_____" ], [ "#hide_input\nprint_doc(_make_body)", "_____no_output_____" ], [ "#hide_input\nprint_doc(_make_head)", "_____no_output_____" ] ], [ [ "## Model Constructor.", "_____no_output_____" ] ], [ [ "#hide\nfrom model_constructor import ModelConstructor", "_____no_output_____" ], [ "#hide_input\nprint_doc(ModelConstructor)", "_____no_output_____" ], [ "mc = ModelConstructor()\nmc", "_____no_output_____" ], [ "mc._block_sizes", "_____no_output_____" ], [ "mc.block_sizes", "_____no_output_____" ], [ "mc._block_sizes = [128, 256, 512, 1024]\nmc", "_____no_output_____" ], [ "mc.block_sizes", "_____no_output_____" ], [ "#hide\nmc = ModelConstructor(stem_sizes=[3,32,32,64])\nmc", "_____no_output_____" ], [ "mc.block_sizes", "_____no_output_____" ], [ "model = ModelConstructor()", "_____no_output_____" ], [ "#hide\n# model.block_sizes = [64, 128, 256, 512] # wrong way --> use _block_sizes\n# model", "_____no_output_____" ], [ "#collapse_output\nmc.stem", "_____no_output_____" ], [ "#collapse_output\nmc.stem_stride_on = 1\nmc.stem", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 3, 128, 128)\ny = mc.stem(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 64, 32, 32]), f\"size\"", "torch.Size([16, 64, 32, 32])\n" ], [ "mc.bn_1st = False", "_____no_output_____" ], [ "mc.act_fn =nn.LeakyReLU(inplace=True)", "_____no_output_____" ], [ "mc.sa = True\nmc.se = True", "_____no_output_____" ], [ "#collapse_output\nmc.body.l_1", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 64, 32, 32)\ny = mc.body.l_0(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 64, 32, 32]), f\"size\"", "torch.Size([16, 64, 32, 32])\n" ], [ "#hide\nmc.body.l_0", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 64, 32, 32)\ny = mc.body.l_0(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 64, 32, 32]), f\"size\"", "torch.Size([16, 64, 32, 32])\n" ], [ "#hide\nmc.groups = 4\nmc.expansion = 4\nmc.body.l_0", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 64, 32, 32)\ny = mc.body.l_0(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 256, 32, 32]), f\"size\"", "torch.Size([16, 256, 32, 32])\n" ], [ "#hide\nmc.groups = 1\nmc.dw = True\nmc.expansion = 4\nmc.body.l_0", "_____no_output_____" ], [ "#hide\nbs_test = 16\nxb = torch.randn(bs_test, 64, 32, 32)\ny = mc.body.l_0(xb)\nprint(y.shape)\nassert y.shape == torch.Size([bs_test, 256, 32, 32]), f\"size\"", "torch.Size([16, 256, 32, 32])\n" ], [ "#hide\nmc.groups = 1\nmc.dw = 0\nmc.expansion = 1", "_____no_output_____" ] ], [ [ "## end\nmodel_constructor\nby ayasyrev", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
ecf9fe1f305aadcf2ae5dce74823c5abdadb3a70
91,031
ipynb
Jupyter Notebook
Advanced_DL_with_TensorFlow_2 ~ Book/Chapter_1.ipynb
kushagras71/understanding_ML
092b545274756bf350df46dbff3b6b22492567ff
[ "Apache-2.0" ]
null
null
null
Advanced_DL_with_TensorFlow_2 ~ Book/Chapter_1.ipynb
kushagras71/understanding_ML
092b545274756bf350df46dbff3b6b22492567ff
[ "Apache-2.0" ]
null
null
null
Advanced_DL_with_TensorFlow_2 ~ Book/Chapter_1.ipynb
kushagras71/understanding_ML
092b545274756bf350df46dbff3b6b22492567ff
[ "Apache-2.0" ]
null
null
null
189.253638
47,708
0.823708
[ [ [ "### Artficial Neural Network for MNIST", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom tensorflow.keras.datasets import mnist\nimport matplotlib.pyplot as plt\n\n(x_train,y_train),(x_test,y_test) = mnist.load_data()\nunique, counts = np.unique(y_train,return_counts=True)\nprint(\"Train labels: \", dict(zip(unique,counts)))\nprint(\"Test labesl: \",dict(zip(unique,counts)))\nindexes = np.random.randint(0,x_train.shape[0],size=25)\nimages = x_train[indexes]\nlabels = x_train[indexes]\n\nplt.figure(figsize=(5,5))\nfor i in range(len(indexes)):\n plt.subplot(5,5,i+1)\n image = images[i]\n plt.imshow(image,cmap='gray')\n plt.axis(\"off\")\nplt.show()", "Train labels: {0: 5923, 1: 6742, 2: 5958, 3: 6131, 4: 5842, 5: 5421, 6: 5918, 7: 6265, 8: 5851, 9: 5949}\nTest labesl: {0: 5923, 1: 6742, 2: 5958, 3: 6131, 4: 5842, 5: 5421, 6: 5918, 7: 6265, 8: 5851, 9: 5949}\n" ], [ "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.utils import to_categorical, plot_model\nimport pydot\n\n(x_train,y_train),(x_test,y_test) = mnist.load_data()\n\nnum_labels = len(np.unique(y_train))\n\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\nimage_size = x_train.shape[1]\ninput_size = image_size * image_size\n\nx_train = np.reshape(x_train,[-1,input_size])\nx_train = x_train.astype('float32') / 255\n\nx_test = np.reshape(x_test,[-1,input_size])\nx_test = x_test.astype('float32')/255\n\nbatch_size = 128\n\nmodel = Sequential()\nmodel.add(Dense(units=2056,activation='relu',input_dim=input_size))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(units=1024,activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(units=10,activation='softmax'))\nmodel.summary()\n# plot_model(model,show_shapes=True)", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 2056) 1613960 \n_________________________________________________________________\ndropout (Dropout) (None, 2056) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1024) 2106368 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 10250 \n=================================================================\nTotal params: 3,730,578\nTrainable params: 3,730,578\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(loss='categorical_crossentropy',\n optimizer = 'adam',\n metrics=['accuracy'])\n\nmodel.fit(x_train,y_train,epochs=20,batch_size=batch_size)\n", "Epoch 1/20\n469/469 [==============================] - 4s 7ms/step - loss: 0.3802 - accuracy: 0.8820\nEpoch 2/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0984 - accuracy: 0.9692\nEpoch 3/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0700 - accuracy: 0.9787\nEpoch 4/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0561 - accuracy: 0.9826\nEpoch 5/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0454 - accuracy: 0.9850\nEpoch 6/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0462 - accuracy: 0.9850\nEpoch 7/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0424 - accuracy: 0.9865\nEpoch 8/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0440 - accuracy: 0.9864\nEpoch 9/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0324 - accuracy: 0.9899\nEpoch 10/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0328 - accuracy: 0.9901\nEpoch 11/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0336 - accuracy: 0.9897\nEpoch 12/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0301 - accuracy: 0.9903\nEpoch 13/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0274 - accuracy: 0.9920\nEpoch 14/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0312 - accuracy: 0.9910\nEpoch 15/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0303 - accuracy: 0.9919\nEpoch 16/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0283 - accuracy: 0.9922\nEpoch 17/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0331 - accuracy: 0.9915\nEpoch 18/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0288 - accuracy: 0.9925\nEpoch 19/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0340 - accuracy: 0.9926\nEpoch 20/20\n469/469 [==============================] - 3s 7ms/step - loss: 0.0283 - accuracy: 0.9931\n" ], [ "_,acc = model.evaluate(x_test,y_test,batch_size=batch_size,\n verbose=1)\nprint(\"\\nThe test accuracy: %.1f%%\" % (100.0*acc))\nprint(_)", "79/79 [==============================] - 0s 2ms/step - loss: 0.1367 - accuracy: 0.9814\n\nThe test accuracy: 98.1%\n0.1366506814956665\n" ] ], [ [ "### Convolutional Neural Network for MNIST", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Activation, Dense, Dropout\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten\nfrom tensorflow.keras.utils import to_categorical, plot_model\nfrom tensorflow.keras.datasets import mnist\n\n(x_train,y_train),(x_test,y_test) = mnist.load_data()\n\nnum_labels = len(np.unique(y_train))\n\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\nimage_size = x_train.shape[1]\nx_train = np.reshape(x_train,[-1,image_size,image_size,1])\nx_test = np.reshape(x_test,[-1,image_size,image_size,1])\n\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255\n\ninput_shape = (image_size,image_size,1)\nbatch_size = 128\n\nmodel = Sequential()\nmodel.add(Conv2D(filters=128,activation='relu',kernel_size=(3,3),input_shape=input_shape))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(filters=64,activation='relu',kernel_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(filters=32,activation=\"relu\",kernel_size=(2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(units = 128,activation='relu'))\nmodel.add(Dense(units = 10,activation='softmax'))\nmodel.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])", "_____no_output_____" ], [ "model.fit(x_train,y_train,validation_data=(x_test,y_test),\n batch_size=batch_size)", "469/469 [==============================] - 47s 100ms/step - loss: 0.3572 - accuracy: 0.8923 - val_loss: 0.0507 - val_accuracy: 0.9824\n" ], [ "loss,acc = model.evaluate(x_test,y_test,batch_size=batch_size)", "79/79 [==============================] - 3s 32ms/step - loss: 0.0507 - accuracy: 0.9824\n" ], [ "print(\"Test Accuracy for the model is %.1f%%\"%(100.0*acc))", "Test Accuracy for the model is 98.2%\n" ] ], [ [ "### Recurrent Neural Network for MNIST", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation, LSTM\nfrom tensorflow.keras.utils import to_categorical, plot_model\nfrom tensorflow.keras.datasets import mnist", "_____no_output_____" ], [ "(x_train,y_train),(x_test,y_test) = mnist.load_data()", "_____no_output_____" ], [ "num_labels = len(np.unique(y_train))", "_____no_output_____" ], [ "y_train = to_categorical(y_train)\ny_test = to_categorical(y_test)", "_____no_output_____" ], [ "image_size = x_train.shape[1]\nx_train = np.reshape(x_train,[-1,image_size, image_size])\nx_test = np.reshape(x_test,[-1,image_size, image_size])\n\nx_train = x_train.astype('float32') / 255\nx_test = x_test.astype('float32') / 255", "_____no_output_____" ], [ "input_shape = (image_size,image_size)\nbatch_size = 128\nunits = 256\ndropout = 0.25", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(LSTM(units=256,\n dropout=dropout,\n input_shape=input_shape))\nmodel.add(Dense(num_labels))\nmodel.add(Activation('softmax'))\nmodel.summary()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
ecfa02f415b8300445daa69f10feb5079c0127a7
244,644
ipynb
Jupyter Notebook
epidemioptim/analysis/Visualization EpidemiOptim.ipynb
goodhamgupta/EpidemiOptim
a4fe3fcfc2d82a10db16a168526982c03ca2c8d3
[ "MIT" ]
null
null
null
epidemioptim/analysis/Visualization EpidemiOptim.ipynb
goodhamgupta/EpidemiOptim
a4fe3fcfc2d82a10db16a168526982c03ca2c8d3
[ "MIT" ]
null
null
null
epidemioptim/analysis/Visualization EpidemiOptim.ipynb
goodhamgupta/EpidemiOptim
a4fe3fcfc2d82a10db16a168526982c03ca2c8d3
[ "MIT" ]
null
null
null
224.444037
198,259
0.869848
[ [ [ "# Visualization Notebook\n\n\nIn this notebook, the user can interact with trained models from the paper EpidemiOptim: A Toolbox for the Optimization of Control Policies in Epidemiological Models.\n", "_____no_output_____" ] ], [ [ "%matplotlib notebook\nimport sys\nsys.path.append('../../')\nfrom epidemioptim.analysis.notebook_utils import setup_visualization\nfrom epidemioptim.utils import get_repo_path", "_____no_output_____" ] ], [ [ "Pick your parameters: seed, algorithm and epidemiological model determinism. Currently implemented:\n\n### DQN\n\nThe user can control the mixing parameter $\\beta$ that tunes the balance between economic $(C_e)$ and health $(C_h)$ costs: $C=(1-\\beta)~C_h + \\beta~C_e$. When it does so, the corresponding DQN policy is loaded and run in the model for one year. The user can then visualize the evolution of costs over a year. Lockdown enforcement are marked by red dots.\n\n\n### GOAL_DQN\n\nThe user can control the mixing parameter $\\beta$. There is only one policy. For each $\\beta$, the optimal actions are selected according to the corresponding balance between Q-functions: $a^* = \\text{argmax}_a (1-\\beta)~Q_h + \\beta~Q_e$. Each time $\\beta$ is changed, the model is run over a year.\n\n\n### GOAL_DQN_CONSTRAINTS\n\nThe user can control $\\beta$ and the values of constraints on the maximum values of cumulative costs ($M_e$, $M_h$). Each time new parameters are selected, the resulting policy is run in the model over a year. \n\n\n### NSGA\n\nThe user can observe the Pareto front produced by a run of the NSGA-II algorithm. When clicking on a solution from the Pareto front, the corresponding policy is loaded and run in the model over a year. \n\n\n", "_____no_output_____" ] ], [ [ "seed = None # None picks a random seed\nalgorithm = 'GOAL_DQN' # Pick from ['DQN', 'GOAL_DQN_CONSTRAINTS', 'GOAL_DQN', 'NSGA']\ndeterministic_model = False # whether the model is deterministic or not", "_____no_output_____" ] ], [ [ "The cell below launches the visualization.", "_____no_output_____" ] ], [ [ "valid_algorithms = ['DQN', 'GOAL_DQN_CONSTRAINTS', 'GOAL_DQN', 'NSGA']\nassert algorithm in valid_algorithms, \"Pick an algorithm from\" + str(valid_algorithms)\n\nif algorithm == 'DQN':\n folder = get_repo_path() + \"/data/data_for_visualization/DQN/\"\nelif algorithm == 'GOAL_DQN':\n folder = get_repo_path() + \"/data/data_for_visualization/GOAL_DQN/1/\"\nelif algorithm == 'GOAL_DQN_CONSTRAINTS':\n folder = get_repo_path() + \"/data/data_for_visualization/GOAL_DQN_CONST/1/\"\nelif algorithm == 'NSGA':\n folder = get_repo_path() + \"/data/data_for_visualization/NSGA/1/\"\nelse:\n raise NotImplementedError\n \nsetup_visualization(folder, algorithm, seed, deterministic_model)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfa03b8e913ca1cd9a61f25162a28bba72ee51d
8,314
ipynb
Jupyter Notebook
Data-Visualization/3-Dashboard-Sales.ipynb
tahmidbintaslim/Data-Analysis-Online-Retail-Transactions
2b45113a6b2cff88372a092863cd02668b60e137
[ "MIT" ]
13
2019-09-06T03:10:59.000Z
2021-11-13T20:58:48.000Z
Data-Visualization/3-Dashboard-Sales.ipynb
Fatemeh-oss/Data-Analysis-Online-Retail-Transactions
2b45113a6b2cff88372a092863cd02668b60e137
[ "MIT" ]
null
null
null
Data-Visualization/3-Dashboard-Sales.ipynb
Fatemeh-oss/Data-Analysis-Online-Retail-Transactions
2b45113a6b2cff88372a092863cd02668b60e137
[ "MIT" ]
11
2019-12-10T14:12:27.000Z
2022-01-20T16:48:55.000Z
42.635897
280
0.515396
[ [ [ "<h1> A Dashboard to Show Trends in Products Using Dash </h1>\n<hr>\n<h3>Here we will create a dashboard to be able to quickly track, display and then analyze the sales of the products.</h3>\n<br><br>\nFirst, for this demonstration we would like to see the dashboard in the jupyter notebook inline. This is the purpose of the function below:\n\n[(Source Link)](https://github.com/4QuantOSS/DashIntro)", "_____no_output_____" ] ], [ [ "# A function to run the dash a app in jupyter (in an iframe)\nfrom IPython import display\ndef show_app(app,\n port=9999,\n width=1150,\n height=500,\n offline=True,\n style=True,\n **dash_flask_kwargs):\n \n url = 'http://localhost:%d' % port\n iframe = '<iframe src=\"{url}\" width={width} height={height}></iframe>'.format(url=url,\n width=width,\n height=height)\n display.display_html(iframe, raw=True)\n if offline:\n app.css.config.serve_locally = True\n app.scripts.config.serve_locally = True\n if style:\n external_css = [\"https://fonts.googleapis.com/css?family=Raleway:400,300,600\",\n \"https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\",\n \"http://getbootstrap.com/dist/css/bootstrap.min.css\", ]\n\n for css in external_css:\n app.css.append_css({\"external_url\": css})\n\n external_js = [\"https://code.jquery.com/jquery-3.2.1.min.js\",\n \"https://cdn.rawgit.com/plotly/dash-app-stylesheets/a3401de132a6d0b652ba11548736b1d1e80aa10d/dash-goldman-sachs-report-js.js\",\n \"http://getbootstrap.com/dist/js/bootstrap.min.js\"]\n\n for js in external_js:\n app.scripts.append_script({\"external_url\": js})\n\n return app.run_server(debug=False, port=port, **dash_flask_kwargs)", "_____no_output_____" ] ], [ [ "Now we can start building our dashboard. In this dashboard, we will have a scatter plot of all the products with respect to their 'UnitPrice' and 'Quantity' and if the user hovers on each of the products, the time series plot for that product will be created on the side.\n\nFirst, we have to make the layout of the dashboard and specify the objects we want there. For the time series plot, we will retrieve the hover data from the scatterplot and pass it as input and then create the plot based on this data.", "_____no_output_____" ] ], [ [ "#importing necessary libraries\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.graph_objs as go\n\n#importing the dataset and creating the instance\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets = external_stylesheets)\n\nCleanDataset = r'../Cleaned-Dataset/OnlineRetail_Cleaned.csv'\nData_Cleaned = pd.read_csv(CleanDataset, index_col = 'InvoiceDate')\nData_Cleaned.index = pd.to_datetime(Data_Cleaned.index, format = '%Y-%m-%d %H:%M', box = False)\n\n#dash layout\napp.layout = html.Div(\n[\n html.Div([dcc.Graph(id='crossfilter-description-scatter',hoverData={'points':[{'customdata':'HEARTS STICKERS'}]}\n ,figure={\n 'data' : [go.Scatter(x=Data_Cleaned.groupby('Description')['UnitPrice'].mean()\n , y=Data_Cleaned.groupby('Description')['Quantity'].sum()\n , text=Data_Cleaned.groupby('Description').sum().index\n , customdata=Data_Cleaned.groupby('Description').sum().index\n ,mode='markers'\n , marker={'size': 15, 'opacity': 0.5, 'line': {'width': 0.5, 'color': 'white'}}\n )],\n 'layout': go.Layout( xaxis={'title':'UnitPrice'}, yaxis={'title':'Quantity'},\n margin={'l': 40, 'b': 30, 't': 60, 'r': 0}, height=450, hovermode='closest',\n annotations=[{\n 'x': 0, 'y': 1.06, 'xanchor': 'left', 'yanchor': 'bottom',\n 'xref': 'paper', 'yref': 'paper', 'showarrow': False,\n 'align': 'left', 'bgcolor': 'rgba(255, 255, 255, 0.5)',\n 'text': '<b>Quantity Vs UnitPrice Among Items</b><br>hover over a point to see time series data'\n }]\n )\n }\n )]\n , style={'width': '45%', 'display': 'inline-block', 'padding': '0 20'}),\n \n html.Div([dcc.Graph(id='time-series')], style={'display': 'inline-block', 'width': '40%'})\n]\n)\n\n#a function to get the data and create the time series\ndef create_time_series(dff, title):\n return {\n 'data': [go.Scatter(\n x=dff.index,\n y=dff.values,\n mode='lines+markers'\n )],\n 'layout': {\n 'height': 400,\n 'margin': {'l': 40, 'b': 65, 'r': 35, 't': 40},\n 'annotations': [{\n 'x': 0, 'y': 1, 'xanchor': 'left', 'yanchor': 'bottom',\n 'xref': 'paper', 'yref': 'paper', 'showarrow': False,\n 'align': 'left', 'bgcolor': 'rgba(255, 255, 255, 0.5)',\n 'text': title\n }],\n 'xaxis': {'showgrid': False}\n }\n }\n\n#passing the hoverdata as input and creating the times series plot\[email protected](\n dash.dependencies.Output('time-series','figure'),\n [ dash.dependencies.Input('crossfilter-description-scatter','hoverData')]\n)\ndef time_series(hoverData):\n item_name = hoverData['points'][0]['customdata']\n dff = Data_Cleaned[Data_Cleaned['Description'] == item_name]\n dff = dff.groupby('InvoiceMonth', sort=False)['FinalPrice'].sum()\n title = '<b>{}</b><br>{}'.format(item_name, 'Monthly Sales, Pounds')\n return create_time_series(dff, title)\n\nshow_app(app)", "_____no_output_____" ] ], [ [ "\n<h3> Unfortunately due to limitations, it's not possible to render dash's interactive dashboards on github, so here is an example of what happens and what the resulting dashboard will look like after running the script: <h3>\n<br>\n \n![Dashboard](Dashboard.gif)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecfa048780dd2b159946004aff911935d3e45da3
31,804
ipynb
Jupyter Notebook
2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROGR/31_ESTRD_ejercicios_sol.ipynb
AlejandroSantorum/Apuntes_Mat_IngInf
68ee7851769c27a7d04203a35b14449d7f80eb73
[ "Apache-2.0" ]
18
2019-10-03T13:07:35.000Z
2022-03-29T12:58:34.000Z
2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROGR/31_ESTRD_ejercicios_sol.ipynb
AlejandroSantorum/Apuntes_Mat_IngInf
68ee7851769c27a7d04203a35b14449d7f80eb73
[ "Apache-2.0" ]
null
null
null
2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROGR/31_ESTRD_ejercicios_sol.ipynb
AlejandroSantorum/Apuntes_Mat_IngInf
68ee7851769c27a7d04203a35b14449d7f80eb73
[ "Apache-2.0" ]
7
2020-01-23T09:59:08.000Z
2021-10-04T18:03:03.000Z
25.793998
1,506
0.523896
[ [ [ "<h2>Ejercicio 1</h2>\n<p>Dada la lista $L=[3,5,6,8,10,12]$, se pide:</p>\n<ol style=\"list-style-type: lower-alpha;\">\n<li>averiguar la posición del número $8$;</li>\n<li>cambiar el valor $8$ por $9$, sin reescribir toda la lista;</li>\n<li>intercambiar $5$ y $9$;</li>\n<li>intercambiar cada valor por el que ocupa su posición <em>simétrica</em>, es decir, el primero con el último, el segundo con el penúltimo, ...</li>\n<li>crear la lista resultante de concatenar a la original, el resultado del apartado anterior.</li>\n</ol>", "_____no_output_____" ] ], [ [ "L=[3,5,6,8,10,12]\nL_copia=list(L) ### Interesa guardar una copia para el apartado e.\n#a\nj=L.index(8)\nj", "_____no_output_____" ], [ "#b\nL[j]=9\nL", "_____no_output_____" ], [ "#c\nj,k=L.index(5),L.index(9)\nL[j],L[k]=9,5\nL", "_____no_output_____" ], [ "#d\nL.reverse()\nL", "_____no_output_____" ], [ "#e\nLL2=L_copia+L\nLL2", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 2</h2>\n<p>La orden prime_range(100,1001) genera la lista de los números primos entre 100 y 1000. Se pide, siendo<br />primos=prime_range(100,1001):</p>\n<ol style=\"list-style-type: lower-alpha;\">\n<li>averiguar el primo que ocupa la posición central en primos;</li>\n<li>averiguar la posición, en primos, de 331 y 631;</li>\n<li>extraer, conociendo las posiciones anteriores, la sublista de primos entre 331 y 631 (ambos incluidos);</li>\n<li>extraer una sublista de primos que olvide los dos centrales de cada cuatro;</li>\n<li>(**) extraer una sublista de primos que olvide el tercero de cada tres.<br /><br /></li>\n</ol>", "_____no_output_____" ] ], [ [ "primos=prime_range(100,1001)", "_____no_output_____" ], [ "#2.a\nL=len(primos)\na=primos[L//2]\na, len(primos[:L//2])==len(primos[L//2+1:])", "_____no_output_____" ], [ "#2.b\np1,p2=331,631\na1,a2=primos.index(p1),primos.index(p2)\na1,a2", "_____no_output_____" ], [ "#2.c\nprimos[a1+1:a2] ### Si se entiende sin los extremos", "_____no_output_____" ] ], [ [ "<p>Para el apartado d podemos entender que se pide:</p>\n<ul style=\"list-style-type: circle;\">\n<li>recorrer la lista y decidir conforme al criterio SíNONOSíNONOSíNONO..., o con 0's (para el NO) y 1's (para el Sí): 1001001001... En este caso basta saltar de 3 en 3 y la notación slice nos resuelve.</li>\n<li>o dividir en bloques de 4 y quitar los dos centrales;  el dibujo es distinto 1001 1001 1001 .... En este caso, basta tomar los restos de la división de cada índice por 4, y quedarnos con los que dan resto 0 o 4.</li>\n</ul>", "_____no_output_____" ] ], [ [ "#2.d 100100100100...\nprint 'Una muestra: ', primos[:8:3], primos[:8]\nprint 'Todos:'; primos[::3]", "_____no_output_____" ], [ "#2.d 1001 1001 1001 ...\n[primos[j] for j in range(len(primos)) if (j%4==0) or (j%4==3)]", "_____no_output_____" ] ], [ [ "<p>Para olvidar el tercero de cada tres, hay que trabajar algo más, pues hemos de quedarnos con dos de cada tres. Se pueden pegar todas las sublistas que nos interesan, lo que conlleva un bucle for. A estas alturas es mejor quedarse con los índices múltiplos  congruentes con 0 o 1 módulo 3:</p>", "_____no_output_____" ] ], [ [ "#2.e\n[primos[j] for j in range(len(primos)) if j%3!=2]", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 3</h2>\n<p>Considérese el n úmero $1000!$ (factorial(1000)):</p>\n<ol style=\"list-style-type: lower-alpha;\">\n<li>¿en cuántos ceros acaba?</li>\n<li>¿Se encuentra el número 666 entre sus subcadenas? En caso afirmativo, localizar (encontrar los  índices de) todas las apariciones.</li>\n<li>Encontrar la subcadena má larga de doses consecutivos. Mostrarla con los dos dígitos que la rodean.</li>\n</ol>", "_____no_output_____" ], [ "<p>El primer apartado se puede resolver numéricamente localizando los múltiplos de $5$, $5^2$, $5^3$, ... que hay en los números del $2$ al $1000$. La potencia máxima es la parte entera del logaritmo en base $5$ de $1000$. Así, el siguiente cuadro nos calcula el número de ceros.</p>", "_____no_output_____" ] ], [ [ "%%time\n#3.a\nk=floor(log(10^3,base=5)) ### floor(x) devuelve la parte entera de x\nsum([floor(10^3/5^j) for j in [1..k]])", "_____no_output_____" ] ], [ [ "<p>Pero vamos a resolverlo de otras maneras, menos eficientes, pero que ayudan a ilustrar los métodos y funciones visitados en este capítulo.</p>", "_____no_output_____" ] ], [ [ "%%time\n#3.a Factorizando un entero (tremendo)\n[q for p,q in factor(factorial(10^3)) if p==5]", "_____no_output_____" ], [ "%%time\n#3.a Utilizando una cadena de caracteres\nnumeraco=str(factorial(10^3))\nm=5 ### Probamos buscar m ceros\nceros='0'*m ### m=5 ceros \nj=numeraco.index(ceros)\nprint numeraco[j-1:j+m+1]\nlen(numeraco[j:])", "_____no_output_____" ] ], [ [ "<p>Una última opción es tomar la lista de dígitos y localizar el último dígito no cero. Para utilizar .index(), damos la vuelta a la lista.</p>", "_____no_output_____" ] ], [ [ "%%time\n#3.a Buscando en la lista de dígitos el último no cero\na=list(str(factorial(10^3)))\na.reverse()\nmin([a.index(j) for j in list('123456789')])", "_____no_output_____" ], [ "#3.b\nnumeraco.count('666')", "_____no_output_____" ], [ "a1=numeraco.index('666')\na2=numeraco[a1+1:].index('666')\nnumeraco[a1:a1+3]; numeraco[a1+1+a2:a1+1+a2+3]", "_____no_output_____" ], [ "#3.c\na=[numeraco.find('2'*j) for j in [1..10]]\nprint a\nnumdoses=a.index(-1)\nprint numdoses\ncomienzo=a[numdoses-1]\nfinal=comienzo+numdoses-1\nprint comienzo,final\nprint numeraco[comienzo-1:final+2]", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 4</h2>\n<p>Si se aplica la función sum() a una lista numérica, nos devuelve la suma de todos sus elementos. En particular, la composición sum(k.digits()), para k un variable entera, nos devuelve la suma de sus dígitos (en base 10).</p>\n<ol style=\"list-style-type: lower-alpha;\">\n<li>Calcular, con la composición sum(k.digits()), la suma de los dígitos del número k=factorial(1000).</li>\n<li>Calcular la misma suma sin utilizar el método .digits().<br />Sugerencia: considerar la cadena digitos='0123456789', en la que digitos[0]='0', digitos[1]='1', ..., digitos[9]='9'.<br />Sumar los elementos de la lista<br />$$[j ∗ (\\text{ veces que aparece $j$ en $1000!$}) :\\text{ con }j = 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\\,.$$<br /><br /></li>\n</ol>", "_____no_output_____" ] ], [ [ "#4.a\nk=factorial(1000)\nsum(k.digits())", "_____no_output_____" ], [ "#4.b\nnumeraco=str(k)\ndigitos='0123456789'\n### Recorriendo índices\nsum([j*numeraco.count(digitos[j]) for j in range(len(digitos))])", "_____no_output_____" ], [ "## Recorriendo caracteres\nsum([digitos.index(j)*numeraco.count(j) for j in digitos])", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 5</h2>\n<p>A partir de la cadena de caracteres</p>", "_____no_output_____" ] ], [ [ "texto='Omnes homines, qui sese student praestare ceteris animalibus, summa ope niti decet ne uitam silentio transeant ueluti pecora, quae natura prona atque uentri oboedientia finxit.'", "_____no_output_____" ] ], [ [ "<p><br />extraer la lista de los caracteres del alfabeto utilizados, sin repeticiones, sin distinguir mayúsculas de minúsculas y ordenada alfabéticamente.</p>\n<p><br />Sugerencia: La composición list(set()) aplicada a una lista, genera una lista con los elementos de la original sin repeticiones, ¿por qué?<br /><br /><br /></p>", "_____no_output_____" ] ], [ [ "letras=set(texto.lower())\nsignos=' ,.'\nletras=list(letras.difference(signos))\nletras.sort()\nletras", "_____no_output_____" ], [ "frecuencias=dict([(letra,texto.count(letra)) for letra in letras])", "_____no_output_____" ], [ "#Ejemplo-> contabilidad de vocales\n[(vocal,frecuencias[vocal]) for vocal in 'aeiou']", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 6. Máximo común divisor</h2>\n<p>Sin utilizar los métodos .divisors() ni la función max(), elabora código que, a partir de dos números a y b, calcule:</p>\n<ul style=\"list-style-type: circle;\">\n<li>El conjunto $\\text{Div}_a = \\{k\\in\\mathbb N : k|a\\}$</li>\n<li>El conjunto $\\text{Div}_b = \\{k\\in\\mathbb N : k|b\\}$</li>\n<li>El conjunto $\\text{Div}_{a,b} = \\{k \\in\\mathbb N : k|a \\text{ y } k|b\\}$.</li>\n</ul>\n<p>Una vez se tenga el conjunto de los divisores comunes, encontrar el mayor de ellos.</p>", "_____no_output_____" ] ], [ [ "a,b=2^3*5^3*7^2,7^3*2^4 ###Números para probar\nDiv_a=set([k for k in srange(1,a+1) if a%k==0])\nDiv_b=set([k for k in srange(1,b+1) if b%k==0])\nDiv_ab=Div_a.intersection(Div_b)\nlDiv_ab=list(Div_ab) ### Pasado a lista...\nlDiv_ab.sort() ### ...y ordenados (por defecto es de menor a mayor), interesa el último.\nlDiv_ab[-1]", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 7. Mínimo común múltiplo</h2>\n<p>El mínimo comú múltiplo, $m$, de dos números, $a$ y $b$, es menor o igual que su producto: $m \\le a \\cdot b$. Sin utilizar la función min(), elabora código que, a partir de dos números $a$ y $b$, calcule:</p>\n<ul style=\"list-style-type: circle;\">\n<li>El conjunto $\\text{Mult}_{a(b)} = \\{k \\in\\mathbb N : a\\vert k \\text{ y } k \\le a · b\\}$</li>\n<li>El conjunto $\\text{Mult}_{b(a)} = \\{k \\in\\mathbb N : b\\vert k \\text{ y } k \\le a · b\\}$</li>\n<li>El conjunto $\\text{Mult}_{a,b} = \\{k \\in\\mathbb N : a\\vert k,\\,b\\vert k \\text{ y } k \\le a · b\\}$</li>\n</ul>\n<p>Una vez se tenga este subconjunto de los múltiplos comunes, encontrar el menor de ellos.</p>", "_____no_output_____" ] ], [ [ "a,b=2^3*5^3*7^2,7^3*2^4 ###Números para probar\nMult_a=set([a*j for j in range(1,b+1)])\nMult_b=set([b*j for j in range(1,a+1)])\nMult_ab=Mult_a.intersection(Mult_b)\nlMult_ab=list(Mult_ab)\nlMult_ab.sort()\nlMult_ab[0]", "_____no_output_____" ], [ "##Comprobación sencilla\nlMult_ab[0]*lDiv_ab[-1]==a*b", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 8</h2>\n<p>Dada una lista de números enteros, construye un conjunto con los factores primos de todos los números de la lista.</p>\n<p><br />Indicación: Usa list(k.factor()) para obtener los factores primos.</p>\n<p><strong>Nota:</strong> Mejor que la indicación propuesta, usamos la versión con la función factor(): list(factor(k)). El único problema con la propuesta es que los números $k$ a los que aplicar el método .factor() deberían ser enteros de sage, pero los que generamos con randint() no lo son. Bastaría multiplicarlos por $1$.<br /><br /></p>", "_____no_output_____" ] ], [ [ "nums=[randint(1,100) for j in xrange(8)] ### Una lista de enteros al azar entre 1 y 100\nfactores=set()\nfor k in nums:\n factores.update([p for p,q in list(factor(k))]) ##como no son enteros de sage, usamos factor() y no .factor()\nfactores", "_____no_output_____" ], [ "##Utilizando la indicación del enunciado. Obsérvese la multiplicación en randint(1,100)*1\nnums=[randint(1,100)*1 for j in xrange(8)] ### Una lista de enteros al azar entre 1 y 100\nfactores=set()\nfor k in nums:\n factores.update([p for p,q in list(k.factor())]) ##como no son enteros de sage, usamos factor() y no .factor()\nfactores", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 9</h2>\n<p>Almacena en un diccionario los pares letra:frecuencia resultantes de hacer el análisis de frecuencias de la cadena del siguiente texto.</p>\n<p>Utilizar el diccionario para averiguar la frecuencia de cada una de las cinco vocales.</p>", "_____no_output_____" ] ], [ [ "Hamlet='''To be, or not to be: that is the question: Whether ’tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? To die: to sleep; No more; and by a sleep to say we end The heartache and the thousand natural shocks That flesh is heir to, ’tis a consummation Devoutly to be wish’d. To die, to sleep; To sleep: perchance to dream: ay, there’s the rub; For in that sleep of death what dreams may come When we have shuffled off this mortal coil, Must give us pause: there’s the respect That makes calamity of so long life; For who would bear the whips and scorns of time, The oppressor’s wrong, the proud man’s contumely, The pangs of despised love, the law’s delay, The insolence of office and the spurns That patient merit of the unworthy takes, When he himself might his quietus make With a bare bodkin? who would fardels bear, To grunt and sweat under a weary life, But that the dread of something after death, The undiscover’d country from whose bourn No traveller returns, puzzles the will And makes us rather bear those ills we have Than fly to others that we know not of? Thus conscience does make cowards of us all; And thus the native hue of resolution Is sicklied o’er with the pale cast of thought, And enterprises of great pith and moment With this regard their currents turn awry, And lose the name of action. –Soft you now! The fair Ophelia! Nymph, in thy orisons Be all my sins remember’d.'''", "_____no_output_____" ], [ "caracteres=list(set(Hamlet))\ncaracteres", "_____no_output_____" ], [ "veces=[(j,Hamlet.count(j)) for j in caracteres]\nfrecuencias=dict(veces)\n[(vocal,frecuencias[vocal]) for vocal in 'aeiou']", "_____no_output_____" ] ], [ [ "<h2>Ejercicio 10</h2>\n<p>A partir del diccionario de frecuencias del ejercicio anterior, construir una lista de pares (frecuencia,letra) y ordenarla, en orden creciente de frecuencias.<br /><br /></p>", "_____no_output_____" ] ], [ [ "lfrecs=[(frecuencias[letra],letra) for letra in caracteres]\nlfrecs.sort()\nlfrecs", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
ecfa09e64566422406223f8807be5d117790a3de
6,161
ipynb
Jupyter Notebook
HackerEarth/Monk and nice strings.ipynb
deepaksood619/Python-Competitive-Programming
c8353d732a372c2bc62f5f12169acc421e802d0c
[ "MIT" ]
null
null
null
HackerEarth/Monk and nice strings.ipynb
deepaksood619/Python-Competitive-Programming
c8353d732a372c2bc62f5f12169acc421e802d0c
[ "MIT" ]
null
null
null
HackerEarth/Monk and nice strings.ipynb
deepaksood619/Python-Competitive-Programming
c8353d732a372c2bc62f5f12169acc421e802d0c
[ "MIT" ]
null
null
null
21.693662
1,048
0.43889
[ [ [ "https://www.hackerearth.com/practice/algorithms/sorting/insertion-sort/practice-problems/algorithm/monk-and-nice-strings-3/", "_____no_output_____" ], [ "4\na\nc\nd\nb\n\n0\n1\n2\n1", "_____no_output_____" ], [ "n = int(input())\n\nlst = []\nfor i in range(n):\n val = input()\n count = 0\n j = 0\n while j < i:\n if lst[j] < val:\n count += 1\n j += 1\n else:\n break\n print(count)\n lst.insert(j, val)", " 4\n a\n" ], [ "n = 5\n\ns = \"\"\"sr\nr\nsmepihwlob\nspmkewqmnb\nhplsjeoct\"\"\"\n\nlst = []\n\nfor i, val in enumerate(s.split()):\n count = 0\n j = 0\n while j < i:\n if lst[j] < val:\n count += 1\n j += 1\n else:\n print(count)\n break\n lst.insert(j, val)\n\n# for i, val in enumerate(s.split()):\n# lst.append((val, i))\n\n# lst.sort(key = lambda x: x[0])\n\nlst", "0\n1\n2\n0\n" ], [ "n = int(input())\n\nlst = [0]*26\n\nfor _ in range(n):\n x=ord(input().strip())-97\n lst[x] += 1\n \n count = 0\n for i in range(0, x):\n count += lst[i]\n print(count)", " 4\n a \n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
ecfa0f05dd2195a48ae1b3f4cb6656b98bd69a71
6,500
ipynb
Jupyter Notebook
_notebooks/2020-05-05-firstnotebook.ipynb
der0pa/machine-learning
6c0a681b9d22bd7cd2996532efa9a67f3f49d2a5
[ "Apache-2.0" ]
null
null
null
_notebooks/2020-05-05-firstnotebook.ipynb
der0pa/machine-learning
6c0a681b9d22bd7cd2996532efa9a67f3f49d2a5
[ "Apache-2.0" ]
18
2020-05-05T18:43:18.000Z
2022-02-26T07:40:34.000Z
_notebooks/2020-05-05-firstnotebook.ipynb
der0pa/machine-learning
6c0a681b9d22bd7cd2996532efa9a67f3f49d2a5
[ "Apache-2.0" ]
null
null
null
20.504732
100
0.486308
[ [ [ "# \"FirstNoteBook\"\n> \"Awesome summary\"\n\n- toc: false\n- branch: master\n- badges: true\n- comments: true\n- categories: [fastpages, jupyter]\n- image: images/some_folder/your_image.png\n- hide: false\n- search_exclude: true\n- metadata_key1: metadata_value1\n- metadata_key2: metadata_value2", "_____no_output_____" ] ], [ [ "!python3 --version", "Python 3.6.9\r\n" ], [ "from keras.datasets import mnist", "_____no_output_____" ], [ "(train_images, train_labels), (test_images, test_labels) = mnist.load_data()", "_____no_output_____" ], [ "train_images.shape", "_____no_output_____" ], [ "len(train_labels)", "_____no_output_____" ], [ "train_labels", "_____no_output_____" ], [ "test_images.shape", "_____no_output_____" ], [ "len(test_labels)", "_____no_output_____" ], [ "test_labels", "_____no_output_____" ] ], [ [ "Listing 2.2 the network architecture", "_____no_output_____" ] ], [ [ "#collapse\nfrom keras import models\nfrom keras import layers\nnetwork = models.Sequential()\nnetwork.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))\nnetwork.add(layers.Dense(10, activation='softmax'))", "_____no_output_____" ], [ "network.compile(optimizer='rmsprop',\nloss='categorical_crossentropy',\nmetrics=['accuracy'])", "_____no_output_____" ], [ "train_images = train_images.reshape((60000, 28 * 28))\ntrain_images = train_images.astype('float32') / 255\ntest_images = test_images.reshape((10000, 28 * 28))\ntest_images = test_images.astype('float32') / 255", "_____no_output_____" ], [ "from keras.utils import to_categorical\ntrain_labels = to_categorical(train_labels)\ntest_labels = to_categorical(test_labels)", "_____no_output_____" ], [ ">>> network.fit(train_images, train_labels, epochs=5, batch_size=128)", "Epoch 1/5\n469/469 [==============================] - 8s 16ms/step - loss: 0.2561 - accuracy: 0.9256\nEpoch 2/5\n469/469 [==============================] - 6s 13ms/step - loss: 0.1041 - accuracy: 0.9691\nEpoch 3/5\n469/469 [==============================] - 6s 12ms/step - loss: 0.0692 - accuracy: 0.9798\nEpoch 4/5\n469/469 [==============================] - 6s 12ms/step - loss: 0.0502 - accuracy: 0.9847\nEpoch 5/5\n469/469 [==============================] - 6s 13ms/step - loss: 0.0379 - accuracy: 0.9887\n" ], [ "test_loss, test_acc = network.evaluate(test_images, test_labels)\nprint('test_acc:', test_acc)", "313/313 [==============================] - 2s 7ms/step - loss: 0.0675 - accuracy: 0.9796\ntest_acc: 0.9796000123023987\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
ecfa255f3c0caca24a346461ea800f2eff8043d0
111,094
ipynb
Jupyter Notebook
Tasks.ipynb
danielmccallion/Fundamentals_of_Data_Analysis-Tasks
450f7203bc6d2f4cfc3f479e738e061194ce7c4b
[ "MIT" ]
null
null
null
Tasks.ipynb
danielmccallion/Fundamentals_of_Data_Analysis-Tasks
450f7203bc6d2f4cfc3f479e738e061194ce7c4b
[ "MIT" ]
null
null
null
Tasks.ipynb
danielmccallion/Fundamentals_of_Data_Analysis-Tasks
450f7203bc6d2f4cfc3f479e738e061194ce7c4b
[ "MIT" ]
null
null
null
86.11938
22,904
0.787009
[ [ [ "# Task 1", "_____no_output_____" ], [ "## Counts", "_____no_output_____" ], [ "A python function called **counts** that takes a list as its input and returns a dictionary of unique items in the list as keys and the number of times each item appears as values.", "_____no_output_____" ], [ "#### For example\n\nInput: \\['A', 'A', 'B', 'C', 'A'\\]\n\nOutput: {'A': 3, 'B': 1, 'C': 1}", "_____no_output_____" ] ], [ [ "def counts(list_input):\n \n # Dictionary to return with the lists items as keys\n dict_output = {} \n \n # Iterate items in the list to add to the dictionary\n for item in list_input:\n \n # Check if the item is already in the dictionary\n if item in dict_output:\n # Increment count for existing item\n dict_output[item] += 1\n else:\n # Create key and set count to 1 as item is unique to dict \n dict_output[item] = 1\n \n return dict_output\n ", "_____no_output_____" ] ], [ [ "#### Test counts function with example list input from tasks question\nSimple list of strings 1 character long: \\['A', 'A', 'B', 'C', 'A'\\]", "_____no_output_____" ] ], [ [ "task_example_input = ['A', 'A', 'B', 'C', 'A']", "_____no_output_____" ] ], [ [ "Print output of function", "_____no_output_____" ] ], [ [ "print(counts(task_example_input))", "{'A': 3, 'B': 1, 'C': 1}\n" ] ], [ [ "## Other inputs and expected issues", "_____no_output_____" ], [ "While the function counts works with the example use case from the task given and produces the desired output there is a few issues to note that may produce unexpected results. Below a few other inputs and their outputs will be described as well as what cannot be used as keys [1]. For example objects of type list or dict cannot be used as keys. This is because dictionary keys must be immutable and not mutable [2] as mutable objects are not hashable [3].", "_____no_output_____" ], [ "#### Strings as keys\nA list with string input works with each unique sting being counted. Keys are the full string for strings with multiple characters and strings with the same characters but different cases are treated as different keys. Special characters are treated just as a string and spaces within, before and after a string make the string and so key unique. Integers and floats saved as strings create keys which are strings.", "_____no_output_____" ] ], [ [ "string_input = ['A', 'A', 'B', 'C', 'A', 'AA', 'a', 'bA', 'AB', 'AA ', 'a', 'bA', 'AB.', \" AB\",\n 'A2', '5553', '-7737.99', 'hello world', '\\\\', '\\r', '\\r', '\\'', '\\\"', 'helloworld',\n 'A2', '5553', '-7737.99', 'hello world', '\\\\', '\\r', '\\r', '\\'', '\\\"', \" \"]", "_____no_output_____" ], [ "print(counts(string_input))", "{'A': 3, 'B': 1, 'C': 1, 'AA': 1, 'a': 2, 'bA': 2, 'AB': 1, 'AA ': 1, 'AB.': 1, ' AB': 1, 'A2': 2, '5553': 2, '-7737.99': 2, 'hello world': 2, '\\\\': 2, '\\r': 4, \"'\": 2, '\"': 2, 'helloworld': 1, ' ': 1}\n" ] ], [ [ "#### Integers as keys\nIntegers as a key works as expected with each unique number being a unique key.", "_____no_output_____" ] ], [ [ "int_input = [1, 2, 728299, 838, 2, 1, 2, 5553, 5553]", "_____no_output_____" ], [ "print(counts(int_input))", "{1: 2, 2: 3, 728299: 1, 838: 1, 5553: 2}\n" ] ], [ [ "#### Floats as keys\nFloats are immutable and so can be used as keys to a dictionary. This is shown below:", "_____no_output_____" ] ], [ [ "float_input = [1.24, 2.55, 728299.877, -838.23, 2.55, 1.241, 2.55, 5553.9, -5553.9, 1.0, 1.0]", "_____no_output_____" ], [ "print(counts(float_input))", "{1.24: 1, 2.55: 3, 728299.877: 1, -838.23: 1, 1.241: 1, 5553.9: 1, -5553.9: 1, 1.0: 2}\n" ] ], [ [ "There is a couple of things to note with floats though so not to get unexpected results from the counts formula. \n \nWhen mixing floats with integers and there is two values that evaluate to the same thing eg. the float 2.0 and the int 2 counts will treat these as the same key even though they are different objects. This is because the interpreter evaluates these to be the same. \n \nWhere a user may expect input \\[1.0, 1\\] to produce {1.0: 1, 1: 1} it will produce {1.0: 2} \n2 by 1.0 as 1.0 occurs in the list first.", "_____no_output_____" ] ], [ [ "mix_float_int_input = [1, 1.0, 1.000, 2.00, 2.0, 2]", "_____no_output_____" ], [ "print(counts(mix_float_int_input))", "{1: 3, 2.0: 3}\n" ] ], [ [ "Difference's in floating point precison could also cause an unexpected result. Two floating point numbers that a user may expect to be equal may not be after an arithmetic operation [4].\n\nThis is demoed below:", "_____no_output_____" ] ], [ [ "a = 0.123456\nb = 0.987654\n \nmath_floats_input = [a, b, (a/b)*b, (b/a)*a]", "_____no_output_____" ], [ "print(counts(math_floats_input))", "{0.123456: 2, 0.987654: 1, 0.9876540000000001: 1}\n" ] ], [ [ "As you can see the precision of the 2nd arithmetic operation doesnt make the value equal b as could be expected. The first operation ends up equaling a but this shows that using floats as keys could be unpredictable. The list math_floats_input though actaually shows that these floats arent equal so in that sense where a list of different floats getting turned into keys with the value being occurances then the function counts is working as expected ", "_____no_output_____" ] ], [ [ "print(math_floats_input)", "[0.123456, 0.987654, 0.123456, 0.9876540000000001]\n" ] ], [ [ "#### Boolean as keys\nA boolean object can also be used as a dictionary key as they are immutable.", "_____no_output_____" ] ], [ [ "bool_input = [True, False, True, True, False]", "_____no_output_____" ], [ "print(counts(bool_input))", "{True: 3, False: 2}\n" ] ], [ [ "As Python evaluates True and 1 as the same aswell as False and 0 this can cause an issue when a mixed list containing them is given to counts similar to the float 1.0 and int 1 issue [5]. Where input \\[True, 1, 1.0\\] could be expected to produce the output {True: 1, 1: 1, 1.0: 1} it actually produces {True: 3} and this is something to consider when using counts.", "_____no_output_____" ] ], [ [ "mixed_bool_int_float_input = [True, 1, 1.0, 0.0, False, 0]", "_____no_output_____" ], [ "print(counts(mixed_bool_int_float_input))", "{True: 3, 0.0: 3}\n" ] ], [ [ "#### Lists cant be keys\n\nA list object cannot be a key due to it being mutable and not so not hashable [6]. Mutable means they can be altered and immutable means they cannot. For example a list can be added to changing its value while a int's value can be updated but a new object is returned. If a mutable object like a list is attempted to be used as a key it will provide a TypeError and with the error because the list is unhashable. This is shown below:", "_____no_output_____" ] ], [ [ "list_input = [[1,2], ['2', 'hello'], 5, 'hello', True]", "_____no_output_____" ], [ "print(counts(list_input))", "_____no_output_____" ] ], [ [ "## An updated counts function\n\nThe function counts below has been updated to work with the mutable types list, dict and set. If the object type that is to be checked to be used as a key is an instance of the class or subclass of any of these three it will be skipped and the next item in the list will be checked instead (if any). isinstance is used here instead of type to catch any subclasses [7].\n\nA check to make sure the input to the function is an instance of list was added as a list of items is expected. If the input is not a list then a blank dictionary will be returned by the function. ", "_____no_output_____" ] ], [ [ "def counts(list_input):\n \n # Dictionary to return with the lists items as keys\n dict_output = {} \n \n # If the input to the function is from the list class then the function will run as expected\n # If not an empty dict will be returned\n if isinstance(list_input, list):\n \n # Iterate items in the list to add to the dictionary\n for item in list_input:\n \n # Check if object is an instance of the list, dict or set class and skip it if so\n if isinstance(item, list) or isinstance(item, dict) or isinstance(item, set):\n continue\n \n # Check if the item is already in the dictionary \n if item in dict_output:\n # Increment count for existing item\n dict_output[item] += 1\n else:\n # Create key and set count to 1 as item is unique to dict \n dict_output[item] = 1\n \n return dict_output", "_____no_output_____" ] ], [ [ "The below is an example of how the function now handles a list which objects of type list, set and dict aswell as immutable objects:", "_____no_output_____" ] ], [ [ "mixed_input = [[1,2], ['2', 'hello'], 5, 5, 5, 'hello', True, (2,7), {3: 4}, {'a', 'b', 'c'}]", "_____no_output_____" ], [ "print(counts(mixed_input))", "{5: 3, 'hello': 1, True: 1, (2, 7): 1}\n" ] ], [ [ "If the input is not a list as below the output will be an empty dict:", "_____no_output_____" ] ], [ [ "non_list_input = 5", "_____no_output_____" ], [ "print(counts(non_list_input))", "{}\n" ] ], [ [ "# Task 2", "_____no_output_____" ], [ "## Task brief\nWrite a Python function called dicerolls that simulates\nrolling dice. Your function should take two parameters: the number of dice k and\nthe number of times to roll the dice n. The function should simulate randomly\nrolling k dice n times, keeping track of each total face value. It should then return\na dictionary with the number of times each possible total face value occurred. So,\ncalling the function as diceroll(k=2, n=1000) should return a dictionary like: \n{2:19,3:50,4:82,5:112,6:135,7:174,8:133,9:114,10:75,11:70,12:36} \n\n\nYou can use any module from the Python standard library you wish and you should\ninclude a description with references of your algorithm in the notebook.", "_____no_output_____" ], [ "## The Code\n\nPython's random will be used to get the random value for the dice [8]. The randint function from it can be used to return a random integer within a range (eg. 1-6 for a 6 sided die) [9]. ", "_____no_output_____" ] ], [ [ "# Bring in the random libary for generating the random dice values\nimport random", "_____no_output_____" ], [ "# An example of randint returning a die roll\nprint(random.randint(1,6))", "1\n" ] ], [ [ "#### Reusing the counts function from task 1\nThe counts function from task 1 will come in handy here with the expected dictionary output required.", "_____no_output_____" ], [ "### The dicerolls function\nThis is the function that was required for the task. It takes two values k and n. k is the number of dice and n is the number of times to roll them.\n\nThe output of the function is a dictionary with the number of times each possible total face value occurred. This dictionary has been sorted by its key values to match the output in the task assignment. This limits the function for to Python version 3.7 and above [10].", "_____no_output_____" ] ], [ [ "# The diceroll function with default values for k and n as they were in example\ndef dicerolls(k=2, n=1000):\n \n # Check that both k and n are valid inputs\n for letter, input_to_check in ((\"k\", k), (\"n\", n)):\n \n # Raise an error with feedback if an input is not an integer\n if not isinstance(input_to_check, int):\n raise TypeError(f\"Only integers are allowed for {letter}, type entered:{type(input_to_check)}\")\n \n # Raise an error with feedback if an input is less than 1\n if input_to_check < 1:\n raise ValueError(f\"{letter} was {input_to_check} and cannot be less than 1. Please enter a number that is 1 or greater\")\n \n # List to save all dice totals\n dice_totals_list = []\n \n # Repeat the rolling of the dice for as many times as n requires from the input\n for interation in range(0, n):\n # Interger to hold the total of dice rolled each time \n dice_total = 0\n \n # Loop to roll as many dice as the input k\n for die in range(0, k):\n \n # Use randint to simulate the roll of a six sided die\n die_value = random.randint(1,6)\n \n # Increment the total with the new die's value\n dice_total += die_value\n\n # Append the dice total to the list so it can be used with the counts function\n dice_totals_list.append(dice_total)\n \n # Use the counts function to return with the number of times each possible total face value occurred\n dict_output = counts(dice_totals_list)\n \n # sort the dictionary keys for a better view of the output and to\n # look more like the example output from the task.\n dict_output = dict(sorted(dict_output.items()))\n \n # Return the dictionary of each total face value combo\n return dict_output", "_____no_output_____" ], [ "dicerolls(2, 1000)", "_____no_output_____" ] ], [ [ "#### Error handling\nThe function dicerolls is designed to raise a TypeError or ValueError if either of its inputs are not desired. For example both inputs have to be of type integer. This is because a fraction of a dice is not a thing and an each interation with n must be a full iteration. For this a TypeError is raised [11]. \n\nn and k must also be 1 or greater. This is because there must be at least 1 iteration and at least 1 die. A ValueError is raised if this is not the case for either input [12].", "_____no_output_____" ], [ "An example where k is less than 1:", "_____no_output_____" ] ], [ [ "dicerolls(0, 1000)", "_____no_output_____" ] ], [ [ "An example where n is less than 1:", "_____no_output_____" ] ], [ [ "dicerolls(5, -1000)", "_____no_output_____" ] ], [ [ "An example where k is a float:", "_____no_output_____" ] ], [ [ "dicerolls(90.0, 1000)", "_____no_output_____" ] ], [ [ "An example where n is a string:", "_____no_output_____" ] ], [ [ "dicerolls(9, \"2\")", "_____no_output_____" ] ], [ [ "The output of dicerolls can be graphed as below showing the highest frequency in the middle of the range.", "_____no_output_____" ] ], [ [ "dice_to_graph = dicerolls(2, 1000)\n\n# Plot dictionary as graph using zip [14]\nplt.bar(*zip(*dice_to_graph .items()))\n# Set Labels [15]\nplt.title('Dice Rolls')\nplt.xlabel('Total Value of Dice')\nplt.ylabel('Freq of Total')\nplt.show()", "_____no_output_____" ] ], [ [ "# Task 3", "_____no_output_____" ], [ "The numpy.random.binomial function can be used to\nsimulate flipping a coin with a 50/50 chance of heads or tails. Interestingly, if a\ncoin is flipped many times then the number of heads is well approximated by a\nbell-shaped curve. For instance, if we flip a coin 100 times in a row the chance of\ngetting 50 heads is relatively high, the chances of getting 0 or 100 heads is relatively\nlow, and the chances of getting any other number of heads decreases as you move\naway from 50 in either direction towards 0 or 100. Write some python code that\nsimulates flipping a coin 100 times. Then run this code 1,000 times, keeping track\nof the number of heads in each of the 1,000 simulations. Select an appropriate\nplot to depict the resulting list of 1,000 numbers, showing that it roughly follows\na bell-shaped curve. You should explain your work in a Markdown cell above the\ncode.", "_____no_output_____" ], [ "Generating 1000 simulations for 100 values with 2 possible outcomes could be done very quickly with the binomial function from the Numpy library [13]", "_____no_output_____" ] ], [ [ "# Bring in the numpy libary for generating a binomial distribution \nimport numpy as np", "_____no_output_____" ], [ "# Number of times to flip the coin \nn = 100\n# Probability of each coin flip being heads\np = .5\n\n# Create array representing the probability of 100 coin flips ran 1000 times \ncoin_flip_array = np.random.binomial(n, p, 1000)", "_____no_output_____" ], [ "coin_flip_array", "_____no_output_____" ] ], [ [ "This array can be converted to a list and used in the counts funtion from task 1 to produce a dictionary with the number of occurrences of each heads total between 0 and 100.", "_____no_output_____" ] ], [ [ "coin_flip_frequency = counts(list(coin_flip_array))", "_____no_output_____" ], [ "# Sort dictionary by keys for easier viewing\ncoin_flip_frequency = dict(sorted(coin_flip_frequency.items()))", "_____no_output_____" ], [ "coin_flip_frequency", "_____no_output_____" ], [ "# Bring in the matplotlib libary for graphing\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "As you can see below the frequency of the values around 50 is alot higher and shows the chance of the total heads reduces as it goes to either 0 or 100. The data forms a bell shaped curve on the graph showing this", "_____no_output_____" ] ], [ [ "# Plot dictionary as graph using zip [14]\nplt.bar(*zip(*coin_flip_frequency.items()))\n# Set Labels [15]\nplt.title('Coin Flip')\nplt.xlabel('Total Heads out of 100')\nplt.ylabel('Freq of Total in 1000 runs')\nplt.show()", "_____no_output_____" ] ], [ [ "The function dicerolls can also be adapted for the coin flip as below where the min and max die values can be input", "_____no_output_____" ] ], [ [ "# The diceroll function with default values for k and n as they were in example for task 2\n# Modified the function from above to accept a quantity for number of die sides with a default value of 6\ndef dicerolls(k=2, n=1000, min_die_value=1, max_die_value=6):\n \n # Check that k, n, max die value and min die value are valid inputs\n for letter, input_to_check in ((\"k\", k), (\"n\", n), (\"Min Die Value\", min_die_value), (\"Max Die Value\", max_die_value)):\n \n # Raise an error with feedback if an input is not an integer\n if not isinstance(input_to_check, int):\n raise TypeError(f\"Only integers are allowed for {letter}, type entered:{type(input_to_check)}\")\n \n # Raise an error with feedback if an input is less than 1 (or 0 for min die value)\n if input_to_check < 1:\n # Minimum die value can be 0 so a seperate check and raise message applies\n if letter == \"Min Die Value\":\n if input_to_check != 0:\n raise ValueError(f\"{letter} was {input_to_check} and cannot be less than 0. Please enter a number that is 0 or greater\")\n # Dont raise below Value error as min die value is 0\n continue\n raise ValueError(f\"{letter} was {input_to_check} and cannot be less than 1. Please enter a number that is 1 or greater\")\n \n # Check that the minimum die value is less than the maximum die value\n if min_die_value >= max_die_value:\n raise ValueError(f\"Min die value must be less than maximum die value. min:{min_die_value}, max:{max_die_value}\")\n \n # List to save all dice totals\n dice_totals_list = []\n \n # Repeat the rolling of the dice for as many times as n requires from the input\n for interation in range(0, n):\n # Interger to hold the total of dice rolled each time \n dice_total = 0\n \n # Loop to roll as many dice as the input k\n for die in range(0, k):\n \n # Use randint to simulate the roll of a die with using max and min values for the die sides\n die_value = random.randint(min_die_value, max_die_value)\n \n # Increment the total with the new die's value\n dice_total += die_value\n\n # Append the dice total to the list so it can be used with the counts function\n dice_totals_list.append(dice_total)\n \n # Use the counts function to return with the number of times each possible total face value occurred\n dict_output = counts(dice_totals_list)\n \n # sort the dictionary keys for a better view of the output and to\n # look more like the example output from the task.\n dict_output = dict(sorted(dict_output.items()))\n \n # Return the dictionary of each total face value combo\n return dict_output", "_____no_output_____" ], [ "coin_flip_via_dicerolls = dicerolls(k=100, n=1000, min_die_value=0, max_die_value=1)", "_____no_output_____" ], [ "# Plot dictionary as graph using zip [14]\nplt.bar(*zip(*coin_flip_via_dicerolls.items()))\n# Set Labels [15]\nplt.title('Coin Flip using dicerolls')\nplt.xlabel('Total Heads out of 100')\nplt.ylabel('Freq of Total in 1000 runs')\nplt.show()", "_____no_output_____" ] ], [ [ "### References\n[1] Restrictions on Dictionary Keys \nhttps://realpython.com/python-dicts/\n\n[2] Mutable and Immutable Data Types in Python \nhttps://towardsdatascience.com/https-towardsdatascience-com-python-basics-mutable-vs-immutable-objects-829a0cb1530a\n\n[3] Mutable, Immutable and Hashable \nhttps://medium.com/@mitali.s.auger/python3-sometimes-immutable-is-mutable-and-everything-is-an-object-22cd8012cabc\n\n[4] Floats as dict keys issue \nhttps://diego.assencio.com/?index=67e5393c40a627818513f9bcacd6a70d\n\n[5] Mixing boolean with int/float for a pythons dict's keys \nhttps://dbader.org/blog/python-mystery-dict-expression\n\n[6] Lists as dictionary keys \nhttps://wiki.python.org/moin/DictionaryKeys#:~:text=The%20builtin%20list%20type%20should,thus%20usable%20as%20dictionary%20keys.\n\n[7] Difference between isinstance and type \nhttps://switowski.com/blog/type-vs-isinstance#:~:text=Difference%20between%20isinstance%20and%20type&text=type%20only%20returns%20the%20type,specified%20as%20a%20second%20parameter.\n\n[8] The random library \nhttps://docs.python.org/3/library/random.html\n\n[9] Using random to simulate a dice roll \nhttps://www.geeksforgeeks.org/dice-rolling-simulator-using-python-random/\n\n[10] Sorting a dictionary by its keys Python 3.7 > \nhttps://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key\n\n[11] Raising a TypeError \nhttps://www.w3schools.com/python/ref_keyword_raise.asp\n\n[12] Raising a ValueError \nhttps://www.journaldev.com/33500/python-valueerror-exception-handling-examples#:~:text=Here%20is%20a%20simple%20example\n\n[13] Numpy.random.binomial function \nhttps://numpy.org/doc/stable/reference/random/generated/numpy.random.binomial.html\n\n[14] Plotting a dictionary using ImportanceOfBeingErnest's answer as guide \nhttps://stackoverflow.com/questions/16010869/plot-a-bar-using-matplotlib-using-a-dictionary\n\n[15] Setting labels with matplotlib \nhttps://matplotlib.org/3.1.1/gallery/pyplots/pyplot_text.html#sphx-glr-gallery-pyplots-pyplot-text-py", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
ecfa344679a0ed6d32efc378211d8868ad82123d
1,662
ipynb
Jupyter Notebook
docs/contents/tools/classes/openff_Molecule/to_molsysmt_Trajectory.ipynb
dprada/molsysmt
83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d
[ "MIT" ]
null
null
null
docs/contents/tools/classes/openff_Molecule/to_molsysmt_Trajectory.ipynb
dprada/molsysmt
83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d
[ "MIT" ]
null
null
null
docs/contents/tools/classes/openff_Molecule/to_molsysmt_Trajectory.ipynb
dprada/molsysmt
83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d
[ "MIT" ]
null
null
null
20.268293
84
0.544525
[ [ [ "# To molsysmt.Trajectory", "_____no_output_____" ] ], [ [ "from molsysmt.tools import openff_Molecule", "Warning: importing 'simtk.openmm' is deprecated. Import 'openmm' instead.\n" ], [ "#openff_Molecule.to_molsysmt_Trajectory(item)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
ecfa3582abff82a8da577c19358bec0ddec91a2f
3,160
ipynb
Jupyter Notebook
add_remove_users.ipynb
PepijnBoers/dash-flask-login
a9b672bcaa873f0898cf03d3bb88d2d74ef8e3e7
[ "MIT" ]
null
null
null
add_remove_users.ipynb
PepijnBoers/dash-flask-login
a9b672bcaa873f0898cf03d3bb88d2d74ef8e3e7
[ "MIT" ]
null
null
null
add_remove_users.ipynb
PepijnBoers/dash-flask-login
a9b672bcaa873f0898cf03d3bb88d2d74ef8e3e7
[ "MIT" ]
null
null
null
34.725275
1,124
0.606962
[ [ [ "import users_mgt as um", "_____no_output_____" ], [ "um.create_user_table()", "_____no_output_____" ], [ "um.add_user('test','test1','[email protected]')", "_____no_output_____" ], [ "um.show_users()", "_____no_output_____" ], [ "um.del_user('test')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
ecfa3833764f074df33ee5acf09ada33bc08e964
39,435
ipynb
Jupyter Notebook
project_pointcloud_into_camera.ipynb
carloradice/kitti360Scripts
3b5bfde63eb98e5a05b06e20d051059e470305ba
[ "MIT" ]
null
null
null
project_pointcloud_into_camera.ipynb
carloradice/kitti360Scripts
3b5bfde63eb98e5a05b06e20d051059e470305ba
[ "MIT" ]
null
null
null
project_pointcloud_into_camera.ipynb
carloradice/kitti360Scripts
3b5bfde63eb98e5a05b06e20d051059e470305ba
[ "MIT" ]
null
null
null
107.160326
29,972
0.860707
[ [ [ "import numpy as np\nimport open3d as o3d", "_____no_output_____" ], [ "FILE = '/home/carlo/Documents/datasets/kitti-360//2013_05_28_drive_0000_sync_000386_000450/lidar_points_all.dat'\nIMMAGINE = '/home/carlo/Documents/datasets/kitti-360/data_2d_raw/2013_05_28_drive_0000_sync/image_00/data_rect/0000000386.png'", "_____no_output_____" ], [ "sed = np.loadtxt(FILE, unpack = True)", "_____no_output_____" ], [ "sed.shape", "_____no_output_____" ], [ "pcl = o3d.PointCloud()", "_____no_output_____" ], [ "p = sed[:3, :]\np.shape", "_____no_output_____" ], [ "pose = np.array([0.6337552899, 0.7735143891, -0.0054518216, 977.5746237, \n 0.7734979431, -0.6337780079, -0.0051350568, 3802.045638,\n -0.007427285, -0.0009626034, -0.999971954, 115.0822819,\n 0,0,0,1])\npose = pose.reshape((4, 4))\npcl_origin = o3d.PointCloud()", "_____no_output_____" ], [ "pose2 = np.array([])", "_____no_output_____" ], [ "calib = np.array([0.0371783278, -0.0986182135, 0.9944306009, 1.5752681039,\n 0.9992675562, -0.0053553387, -0.0378902567, 0.0043914093,\n 0.0090621821, 0.9951109327, 0.0983468786, -0.6500000000,\n 0,0,0,1])\ncalib = calib.reshape((4,4))\npoints_num = p.shape[1]\nnew_pts = np.vstack((p, np.ones((1, points_num))))", "_____no_output_____" ], [ "new_pts = np.dot(np.linalg.inv(pose), new_pts)\npcl_origin.points = o3d.Vector3dVector(new_pts[:3, :].T)\nmasd = o3d.geometry.create_mesh_coordinate_frame(\n size=5, origin=[0., 0., 0.])\n# pointcloud nel sistema di coordinate velodyne del primo frame considerato, guardare quella pose (386)\no3d.visualization.draw_geometries([pcl_origin, masd])", "_____no_output_____" ], [ "camera_pts = np.dot(np.linalg.inv(calib), new_pts)\ncamera_pts = camera_pts[:3, :].T\npcl2 = o3d.PointCloud()\npcl2.points = o3d.Vector3dVector(camera_pts)\nmesh_frame = o3d.geometry.create_mesh_coordinate_frame(\n size=10, origin=[0., 0., 0.])", "_____no_output_____" ], [ "# pointcloud nel sistema di coordianate camera per la pose (386)\no3d.visualization.draw_geometries([pcl2, mesh_frame])", "_____no_output_____" ], [ "print(camera_pts.shape)", "(362377, 3)\n" ], [ "# proiezione nel frame immagine Camera 0 prect0\nk = np.array([552.554261, 0.000000, 682.049453, 0.000000, \n 0.000000, 552.554261, 238.769549, 0.000000, \n 0.000000, 0.000000, 1.000000, 0.000000])\nk = k.reshape((3,4))\nk", "_____no_output_____" ], [ "in_camera_pts = np.expand_dims(camera_pts.T, 0)\nin_camera_pts.shape", "_____no_output_____" ], [ "k[:3,:3].reshape([1,3,3])", "_____no_output_____" ], [ "points_proj = np.matmul(k[:3,:3].reshape([1,3,3]), in_camera_pts)\ndepth = points_proj[:,2,:]\ndepth[depth==0] = -1e-6\nu = np.round(points_proj[:,0,:]/np.abs(depth)).astype(np.int)\nv = np.round(points_proj[:,1,:]/np.abs(depth)).astype(np.int)\n\nu = u[0]\nv = v[0]\ndepth = depth[0]", "/home/carlo/anaconda3/envs/jupyter/lib/python3.7/site-packages/ipykernel_launcher.py:4: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n after removing the cwd from sys.path.\n/home/carlo/anaconda3/envs/jupyter/lib/python3.7/site-packages/ipykernel_launcher.py:5: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.\nDeprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n \"\"\"\n" ], [ "depthMap = np.zeros((376, 1408))\ndepthImage = np.zeros((376, 1408, 3))\n# valore della dimensione\nmask = np.logical_and(np.logical_and(np.logical_and(u>=0, u<1408), v>=0), v<376)\n# valore di profondita\nmask = np.logical_and(np.logical_and(mask, depth>0), depth<35)\ndepthMap[v[mask],u[mask]] = depth[mask]\n\ndepthMap.shape", "_____no_output_____" ], [ "plt.imshow(depthMap, interpolation='nearest')\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfa3cfde5faf75e8b55ad4264553e6eaee35a1d
672,238
ipynb
Jupyter Notebook
245_Project_Code.ipynb
jrgosalvez/validatingSkinCancerImageClassificationModels
6c8bc80114fcde70c9a7b43d16d8bc662484de01
[ "MIT" ]
null
null
null
245_Project_Code.ipynb
jrgosalvez/validatingSkinCancerImageClassificationModels
6c8bc80114fcde70c9a7b43d16d8bc662484de01
[ "MIT" ]
null
null
null
245_Project_Code.ipynb
jrgosalvez/validatingSkinCancerImageClassificationModels
6c8bc80114fcde70c9a7b43d16d8bc662484de01
[ "MIT" ]
1
2021-11-27T20:06:47.000Z
2021-11-27T20:06:47.000Z
715.146809
526,612
0.947682
[ [ [ "## DATA 245 Fall 2021 Project\nGroup 2: Canaan Law, Chitra Priyaa Sathya Moorthy, Haotong Qiu, Jie Dong, Lianglei Zhang, Rick Gosalvez", "_____no_output_____" ] ], [ [ "from mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.preprocessing import StandardScaler\nimport skimage\nfrom skimage import transform\nimport cv2\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nfrom glob import glob\nimport seaborn as sns\nfrom PIL import Image\nfrom tqdm import tqdm", "_____no_output_____" ] ], [ [ "### Import Data", "_____no_output_____" ] ], [ [ "# endpoints (Canaan)\nfolder_benign_train = '../245 Project Testin/dataset1/train/benign'\nfolder_malignant_train = '../245 Project Testin/dataset1/train/malignant'\n\nfolder_benign_test = '../245 Project Testin/dataset1/test/benign'\nfolder_malignant_test = '../245 Project Testin/dataset1/test/malignant'", "_____no_output_____" ] ], [ [ "# endpoints (Rick)\nfolder_benign_train = 'data/train/benign'\nfolder_malignant_train = 'data/train/malignant'\n\nfolder_benign_test = 'data/test/benign'\nfolder_malignant_test = 'data/test/malignant'", "_____no_output_____" ], [ "img_size = 200\nread = lambda imname: np.asarray(Image.open(imname).convert(\"RGB\"))\n\n# Load in training pictures \nims_benign = [read(os.path.join(folder_benign_train, filename)) for filename in os.listdir(folder_benign_train)]\nX_benign = np.array(ims_benign, dtype='uint8')\nims_malignant = [read(os.path.join(folder_malignant_train, filename)) for filename in os.listdir(folder_malignant_train)]\nX_malignant = np.array(ims_malignant, dtype='uint8')\n\n# Load in testing pictures\nims_benign = [read(os.path.join(folder_benign_test, filename)) for filename in os.listdir(folder_benign_test)]\nX_benign_test = np.array(ims_benign, dtype='uint8')\nims_malignant = [read(os.path.join(folder_malignant_test, filename)) for filename in os.listdir(folder_malignant_test)]\nX_malignant_test = np.array(ims_malignant, dtype='uint8')\n", "_____no_output_____" ] ], [ [ "### Preprocess Images", "_____no_output_____" ] ], [ [ "img_size = (200, 200)\n\n## Resize function\ndef _resize_image(image, target):\n return cv2.resize(image, dsize=(target[0], target[1]), interpolation=cv2.INTER_LINEAR)\n\nimage = [_resize_image(image=i, target=img_size) for i in X_benign]\nX_benign = np.stack(image, axis=0)\n\nimage = [_resize_image(image=i, target=img_size) for i in X_malignant]\nX_malignant = np.stack(image, axis=0)\n\nimage = [_resize_image(image=i, target=img_size) for i in X_benign_test]\nX_benign_test = np.stack(image, axis=0)\n\nimage = [_resize_image(image=i, target=img_size) for i in X_malignant_test]\nX_malignant_test = np.stack(image, axis=0)", "_____no_output_____" ], [ "X_benign.shape", "_____no_output_____" ] ], [ [ "### Split into Train and Test", "_____no_output_____" ] ], [ [ "# Create labels\ny_benign = np.zeros(X_benign.shape[0])\ny_malignant = np.ones(X_malignant.shape[0])\n\ny_benign_test = np.zeros(X_benign_test.shape[0])\ny_malignant_test = np.ones(X_malignant_test.shape[0])\n\n\n# Merge data \nX_train = np.concatenate((X_benign, X_malignant), axis = 0)\ny_train = np.concatenate((y_benign, y_malignant), axis = 0)\n\nX_test = np.concatenate((X_benign_test, X_malignant_test), axis = 0)\ny_test = np.concatenate((y_benign_test, y_malignant_test), axis = 0)", "_____no_output_____" ] ], [ [ "### Explore Data", "_____no_output_____" ] ], [ [ "# Shuffle data\ns = np.arange(X_train.shape[0])\nnp.random.shuffle(s)\nX_train = X_train[s]\ny_train = y_train[s]\n\ns = np.arange(X_test.shape[0])\nnp.random.shuffle(s)\nX_test = X_test[s]\ny_test = y_test[s]\n\n# Display first 15 images of moles, and how they are classified\nw=40\nh=30\nfig=plt.figure(figsize=(12, 8))\ncolumns = 5\nrows = 3\n\nfor i in range(1, columns*rows +1):\n ax = fig.add_subplot(rows, columns, i)\n if y_train[i] == 0:\n ax.title.set_text('Benign')\n else:\n ax.title.set_text('Malignant')\n plt.imshow(X_train[i], interpolation='nearest')\nplt.show()\n\n\nplt.bar(0, y_train[np.where(y_train == 0)].shape[0], label = 'benign')\nplt.bar(1, y_train[np.where(y_train == 1)].shape[0], label = 'malignant')\nplt.legend()\nplt.title(\"Training Data\")\nplt.show()\n\nplt.bar(0, y_test[np.where(y_test == 0)].shape[0], label = 'benign')\nplt.bar(1, y_test[np.where(y_test == 1)].shape[0], label = 'malignant')\nplt.legend()\nplt.title(\"Test Data\")\nplt.show()\n\n\nX_train = X_train/255.\nX_test = X_test/255.", "_____no_output_____" ] ], [ [ "### SVM", "_____no_output_____" ] ], [ [ "# support vector machine classifier\n#This is only a simple demostration if we apply any models on the training dataset\nfrom sklearn.svm import SVC\nmodel = SVC()\nmodel.fit(X_train.reshape(X_train.shape[0],-1), y_train)\n\nfrom sklearn.metrics import accuracy_score, classification_report\ny_pred = model.predict(X_test.reshape(X_test.shape[0],-1))\nsvm = accuracy_score(y_test, y_pred)\nprint(f'Accuracy Score: {svm:.3f}')\nprint()\nprint(classification_report(y_test, y_pred))", "Accuracy Score: 0.835\n\n precision recall f1-score support\n\n 0.0 0.87 0.82 0.84 360\n 1.0 0.80 0.86 0.83 300\n\n accuracy 0.83 660\n macro avg 0.83 0.84 0.83 660\nweighted avg 0.84 0.83 0.84 660\n\n" ] ], [ [ "### KNN", "_____no_output_____" ] ], [ [ "# KNN classifier\nfrom sklearn.neighbors import KNeighborsClassifier\nknn_model = KNeighborsClassifier(n_neighbors=3) \nknn_model.fit(X_train.reshape(X_train.shape[0],-1), y_train)\nfrom sklearn.metrics import accuracy_score\ny_pred = knn_model.predict(X_test.reshape(X_test.shape[0],-1))\nknn = accuracy_score(y_test, y_pred)\nprint(f'Accuracy Score: {knn:.3f}')", "Accuracy Score: 0.761\n" ], [ "## tune best k \naccus = []\nks = list(range(2,20))\nfor k in ks:\n knn_model = KNeighborsClassifier(n_neighbors=k)\n knn_model.fit(X_train.reshape(X_train.shape[0],-1), y_train)\n y_pred = knn_model.predict(X_test.reshape(X_test.shape[0],-1))\n accus.append(accuracy_score(y_test, y_pred))\nfig = plt.figure()\nplt.plot(ks, accus)\nplt.xlabel('k in kNN')\nplt.ylabel('Accuracy')\nfig.suptitle('kNN hyperparameter (k) tuning', fontsize=20)", "_____no_output_____" ] ], [ [ "### Import Metrics Libraries", "_____no_output_____" ] ], [ [ "from sklearn.metrics import confusion_matrix, classification_report \nfrom sklearn.metrics import accuracy_score, recall_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import plot_confusion_matrix", "_____no_output_____" ] ], [ [ "### Confusion Matrix", "_____no_output_____" ] ], [ [ "confmat = pd.DataFrame(confusion_matrix(y_test, y_pred),\n index =['True[0]','True[1]'],\n columns=['Predict[0]','Predict[1]'])\nconfmat", "_____no_output_____" ], [ "plot_confusion_matrix(knn_model, X_test.reshape(X_test.shape[0],-1), y_test, cmap=plt.cm.Blues)\nplt.title('Confustion Matrix')\nplt.show()", "_____no_output_____" ] ], [ [ "### ROC Curve", "_____no_output_____" ] ], [ [ "import scikitplot as skplt\nskplt.metrics.plot_roc(y_test, knn_model.predict_proba(X_test.reshape(X_test.shape[0],-1)), plot_micro=False)\nplt.show()", "_____no_output_____" ], [ "target_names = ['benign', 'malignant']\nprint(classification_report(y_test, y_pred, target_names=target_names))", " precision recall f1-score support\n\n benign 0.72 0.88 0.79 360\n malignant 0.80 0.60 0.69 300\n\n accuracy 0.75 660\n macro avg 0.76 0.74 0.74 660\nweighted avg 0.76 0.75 0.75 660\n\n" ] ], [ [ "### Decision Tree / Random Forest", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nforest = RandomForestClassifier(n_estimators=100, random_state=0)\nforest.fit(X_train.reshape(X_train.shape[0],-1), y_train)\ny_pred_rf = forest.predict(X_test.reshape(X_test.shape[0],-1))\nrf = accuracy_score(y_test, y_pred_rf)\nprint('Accuracy on the test set:{:.3f}'.format(rf))", "Accuracy on the test set:0.830\n" ], [ "from sklearn.tree import DecisionTreeClassifier\ndt = DecisionTreeClassifier(random_state=0)\ndt.fit(X_train.reshape(X_train.shape[0],-1), y_train)\ny_pred_dt = dt.predict(X_test.reshape(X_test.shape[0],-1))\ntree = accuracy_score(y_test, y_pred_dt)\nprint('Accuracy on the test set:{:.3f}'.format(tree))", "Accuracy on the test set:0.752\n" ] ], [ [ "### Side-by-Side", "_____no_output_____" ] ], [ [ "# manual import of CNN value (see Data245ProjCNN.ipynb)\ncnn = 0.870", "_____no_output_____" ], [ "print(f'SVM Accuracy : {svm:.3f}')\nprint(f'KNN Accuracy : {knn:.3f}')\nprint(f'Decision Tree Accuracy : {tree:.3f}')\nprint(f'Random Forest Accuracy : {rf:.3f}')\nprint(f'CNN (19 epoch) Accuracy : {cnn:.3f}')", "SVM Accuracy : 0.835\nKNN Accuracy : 0.761\nDecision Tree Accuracy : 0.752\nRandom Forest Accuracy : 0.830\nCNN (19 epoch) Accuracy : 0.870\n" ], [ "accuracy = [cnn, svm, rf, knn, tree]\nacc_name = [\"Convolution Neural Network Accuracy\", \"SVM Accuracy\", \n \"Random Forest Accuracy\", \"KNN Accuracy\", \"Decision Tree Accuracy\"]\nf, ax = plt.subplots(figsize=(10,6))\nax = plt.bar(acc_name, accuracy, width=0.6, color=\"#FF5733\", edgecolor=\"black\")\nplt.grid(True)\nplt.axis(ymin=0.5, ymax=1)\nplt.tick_params(axis='x', labelrotation=45)\nplt.ylabel(\"Accuracy\")\nplt.show()", "_____no_output_____" ] ], [ [ "### Save ML Models", "_____no_output_____" ] ], [ [ "# Import pickle Package\nimport pickle", "_____no_output_____" ], [ "# Save the Modle to file in the current working directory\nPkl_Filename_SVM = \"Pickle_SVM_Model.pkl\" # model (SVM)\n\nwith open(Pkl_Filename_SVM, 'wb') as file: \n pickle.dump(model, file)", "_____no_output_____" ], [ "# knn_model (KNN)\nPkl_Filename_KNN = \"Pickle_KNN_Model.pkl\" \n\nwith open(Pkl_Filename_KNN, 'wb') as file: \n pickle.dump(knn_model, file)", "_____no_output_____" ], [ "# forest (Random Forest)\nPkl_Filename_RF = \"Pickle_FOREST_Model.pkl\" \n\nwith open(Pkl_Filename_RF, 'wb') as file: \n pickle.dump(forest, file)", "_____no_output_____" ], [ "# dt (Decision Tree)\nPkl_Filename_DT = \"Pickle_TREE_Model.pkl\" \n\nwith open(Pkl_Filename_DT, 'wb') as file: \n pickle.dump(dt, file)", "_____no_output_____" ] ], [ [ "### Check pickle file on a model", "_____no_output_____" ] ], [ [ "# Load the Model back from file\nwith open(Pkl_Filename_SVM, 'rb') as file: \n Pickled_SVM_Model = pickle.load(file)\n\nPickled_SVM_Model", "_____no_output_____" ], [ "# Use the Reloaded Model to \n# Calculate the accuracy score and predict target values\n\n# Calculate the Score \nscore = Pickled_SVM_Model.score(X_test.reshape(X_test.shape[0],-1), y_test) \n# Print the Score\nprint(\"Test score: {0:.2f} %\".format(100 * score)) ", "Test score: 83.48 %\n" ], [ "# Predict the Labels using the reloaded Model\nYpredict = Pickled_SVM_Model.predict(X_test.reshape(X_test.shape[0],-1)) \n\nYpredict", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "raw", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "raw" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ecfa3e9826610e603c8ff5b3509a5b7cf6752956
12,287
ipynb
Jupyter Notebook
algoExpert/merge_sorted_arrays/solution.ipynb
maple1eaf/learning_algorithm
a9296c083ba9b79af1be10f56365ee8c95d3aac6
[ "MIT" ]
null
null
null
algoExpert/merge_sorted_arrays/solution.ipynb
maple1eaf/learning_algorithm
a9296c083ba9b79af1be10f56365ee8c95d3aac6
[ "MIT" ]
null
null
null
algoExpert/merge_sorted_arrays/solution.ipynb
maple1eaf/learning_algorithm
a9296c083ba9b79af1be10f56365ee8c95d3aac6
[ "MIT" ]
null
null
null
30.413366
132
0.46301
[ [ [ "# Merge Sorted Arrays\n[link](https://www.algoexpert.io/questions/Merge%20Sorted%20Arrays)", "_____no_output_____" ], [ "## My Solution", "_____no_output_____" ] ], [ [ "# O(nlog(k) + k) time | O(n + k) space\ndef mergeSortedArrays(arrays):\n # Write your code here.\n heap = MinHeap([ModifiedList(l) for l in arrays])\n \n result = []\n while not heap.isEmpty():\n ml = heap.remove()\n result.append(ml.getCurrentValue())\n ml.i += 1\n if ml.isNotBeyondRange():\n heap.insert(ml)\n return result\n\n\nclass ModifiedList:\n def __init__(self, l):\n self.l = l\n self.i = 0\n \n def getCurrentValue(self):\n return self.l[self.i]\n \n def isNotBeyondRange(self):\n return self.i < len(self.l)\n \n def __lt__(self, other):\n return self.getCurrentValue() < other.getCurrentValue()\n \n def __le__(self, other):\n return self.getCurrentValue() <= other.getCurrentValue()\n \nclass MinHeap:\n def __init__(self, array):\n # Do not edit the line below.\n self.heap = self.buildHeap(array)\n\n def buildHeap(self, array):\n # Write your code here.\n self.heap = [x for x in array]\n finalIdx = len(self.heap) - 1\n finalParentIdx = (finalIdx - 1) // 2\n for i in reversed(range(finalParentIdx + 1)):\n self.heapifyDown(i)\n return self.heap\n \n def heapifyDown(self, idx):\n while idx < len(self.heap):\n if 2 * idx + 1 >= len(self.heap):\n break\n elif 2 * idx + 1 < len(self.heap) and 2 * idx + 2 >= len(self.heap):\n if self.heap[idx] > self.heap[2 * idx + 1]:\n self.switch(idx, 2 * idx + 1)\n idx = 2 * idx + 1\n else:\n break\n elif 2 * idx + 2 < len(self.heap):\n smallerIdx = 2 * idx + 1 if self.heap[2 * idx + 1] <= self.heap[2 * idx + 2] else 2 * idx + 2\n if self.heap[idx] > self.heap[smallerIdx]:\n self.switch(idx, smallerIdx)\n idx = smallerIdx\n else:\n break\n \n def switch(self, i, j):\n self.heap[i], self.heap[j] = self.heap[j], self.heap[i]\n\n def siftDown(self):\n # Write your code here.\n self.heapifyDown(0)\n\n def siftUp(self):\n # Write your code here.\n idx = len(self.heap) - 1\n while idx > 0:\n parentIdx = (idx - 1) // 2\n if self.heap[parentIdx] > self.heap[idx]:\n self.switch(parentIdx, idx)\n idx = parentIdx\n else:\n break\n\n def peek(self):\n # Write your code here.\n return self.heap[0]\n\n def remove(self):\n # Write your code here.\n self.switch(0, len(self.heap) - 1)\n top = self.heap.pop()\n self.siftDown()\n return top\n\n def insert(self, obj):\n # Write your code here.\n self.heap.append(obj)\n self.siftUp()\n \n def isEmpty(self):\n return len(self.heap) == 0", "_____no_output_____" ], [ "import heapq\n\n# O(nlog(k) + k) time | O(n + k) space\ndef mergeSortedArrays(arrays):\n # Write your code here.\n heap = [ModifiedList(l) for l in arrays]\n heapq.heapify(heap)\n \n result = []\n while len(heap) != 0:\n ml = heapq.heappop(heap)\n result.append(ml.getCurrentValue())\n ml.i += 1\n if ml.isNotBeyondRange():\n heapq.heappush(heap, ml)\n return result\n\n\nclass ModifiedList:\n def __init__(self, l):\n self.l = l\n self.i = 0\n \n def getCurrentValue(self):\n return self.l[self.i]\n \n def isNotBeyondRange(self):\n return self.i < len(self.l)\n \n def __lt__(self, other):\n return self.getCurrentValue() < other.getCurrentValue()\n \n def __le__(self, other):\n return self.getCurrentValue() <= other.getCurrentValue()", "_____no_output_____" ], [ "import heapq\n\n# O(nlog(k) + k) time | O(n + k) space\ndef mergeSortedArrays(arrays):\n # Write your code here.\n return list(heapq.merge(*arrays))", "_____no_output_____" ] ], [ [ "## Expert Solution", "_____no_output_____" ] ], [ [ "# O(nk) time | O(n + k) space - where n is the total\n# number of array elements and k is the number of arrays\ndef mergeSortedArrays(arrays):\n sortedList = []\n elementIdxs = [0 for array in arrays]\n while True:\n smallestItems = []\n for arrayIdx in range(len(arrays)):\n relevantArray = arrays[arrayIdx]\n elementIdx = elementIdxs[arrayIdx]\n if elementIdx == len(relevantArray):\n continue\n smallestItems.append({\"arrayIdx\": arrayIdx, \"num\": relevantArray[elementIdx]})\n if len(smallestItems) == 0:\n break\n nextItem = getMinValue(smallestItems)\n sortedList.append(nextItem[\"num\"])\n elementIdxs[nextItem[\"arrayIdx\"]] += 1\n return sortedList\n\ndef getMinValue(items):\n minValueIdx = 0\n for i in range(1, len(items)):\n if items[i][\"num\"] < items[minValueIdx][\"num\"]:\n minValueIdx = i\n return items[minValueIdx]", "_____no_output_____" ], [ "# O(nlog(k) + k) time | O(n + k) space - where n is the total\n# number of array elements and k is the number of arrays\ndef mergeSortedArrays(arrays):\n sortedList = []\n smallestItems = []\n for arrayIdx in range(len(arrays)):\n smallestItems.append({\"arrayIdx\": arrayIdx, \"elementIdx\": 0, \"num\": arrays[arrayIdx][0]})\n minHeap = MinHeap(smallestItems)\n while not minHeap.isEmpty():\n smallestItem = minHeap.remove()\n arrayIdx, elementIdx, num = smallestItem[\"arrayIdx\"], smallestItem[\"elementIdx\"], smallestItem[\"num\"]\n sortedList.append(num)\n if elementIdx == len(arrays[arrayIdx]) - 1:\n continue\n minHeap.insert({\"arrayIdx\": arrayIdx, \"elementIdx\": elementIdx + 1, \"num\": arrays[arrayIdx][elementIdx + 1]})\n return sortedList\n\nclass MinHeap:\n def __init__(self, array):\n self.heap = self.buildHeap(array)\n \n def isEmpty(self):\n return len(self.heap) == 0\n\n def buildHeap(self, array):\n firstParentIdx = (len(array) - 2) // 2\n for currentIdx in reversed(range(firstParentIdx + 1)):\n self.siftDown(currentIdx, len(array) - 1, array)\n return array\n \n def siftDown(self, currentIdx, endIdx, heap):\n childOneIdx = currentIdx * 2 + 1\n while childOneIdx <= endIdx:\n childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1\n if childTwoIdx != -1 and heap[childTwoIdx][\"num\"] < heap[childOneIdx][\"num\"]:\n idxToSwap = childTwoIdx\n else:\n idxToSwap = childOneIdx\n if heap[idxToSwap][\"num\"] < heap[currentIdx][\"num\"]:\n self.swap(currentIdx, idxToSwap, heap)\n currentIdx = idxToSwap\n childOneIdx = currentIdx * 2 + 1\n else:\n return\n\n def siftUp(self, currentIdx, heap):\n parentIdx = (currentIdx - 1) // 2\n while currentIdx > 0 and heap[currentIdx][\"num\"] < heap[parentIdx][\"num\"]:\n self.swap(currentIdx, parentIdx, heap)\n currentIdx = parentIdx\n parentIdx = (currentIdx - 1)// 2\n\n def remove(self):\n self.swap(0, len(self.heap) - 1, self.heap)\n valueToRemove = self.heap.pop()\n self.siftDown(0, len(self.heap) - 1, self.heap)\n return valueToRemove\n\n def insert(self, value):\n self.heap.append(value)\n self.siftUp(len(self.heap) - 1, self.heap)\n \n def swap(self, i, j, heap):\n heap[i], heap[j] = heap[j], heap[i]\n", "_____no_output_____" ] ], [ [ "## Thoughts", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
ecfa4400d5df6d2cd34e96e77e33d30b6f1987e6
1,382
ipynb
Jupyter Notebook
21_google_cloud_run.ipynb
Cloudevel/cd601
56b07fa3c63c139f13dd7ec9bdfc7064b6f96ab1
[ "MIT" ]
6
2021-10-13T23:21:44.000Z
2022-03-31T06:03:17.000Z
21_google_cloud_run.ipynb
Cloudevel/cd601
56b07fa3c63c139f13dd7ec9bdfc7064b6f96ab1
[ "MIT" ]
null
null
null
21_google_cloud_run.ipynb
Cloudevel/cd601
56b07fa3c63c139f13dd7ec9bdfc7064b6f96ab1
[ "MIT" ]
2
2021-11-23T20:43:33.000Z
2022-01-08T07:32:55.000Z
23.423729
405
0.552098
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ecfa474eb1ea0c789d7d1faa9c23353a9b75a1c5
168,448
ipynb
Jupyter Notebook
morning_tutorial/01_introduction-dsl.ipynb
georgebisbas/OGHPC2020
e77a3839a9c6b36f35a3d7a818fd0bed423b0c13
[ "MIT" ]
3
2020-02-05T07:17:24.000Z
2020-04-23T17:28:48.000Z
morning_tutorial/01_introduction-dsl.ipynb
georgebisbas/OGHPC2020
e77a3839a9c6b36f35a3d7a818fd0bed423b0c13
[ "MIT" ]
null
null
null
morning_tutorial/01_introduction-dsl.ipynb
georgebisbas/OGHPC2020
e77a3839a9c6b36f35a3d7a818fd0bed423b0c13
[ "MIT" ]
3
2020-02-25T19:07:54.000Z
2020-03-04T18:59:49.000Z
161.813641
133,260
0.877202
[ [ [ "# Introduction (part 1): The Devito domain specific language\n\nThis notebook presents an overview of the Devito symbolic language, used to express and discretise operators, in particular partial differential equations (PDEs).\n\nFor convenience, we import all Devito modules:", "_____no_output_____" ] ], [ [ "from devito import *", "_____no_output_____" ] ], [ [ "## From equations to code in a few lines of Python\n\nThe main objective of this tutorial is to demonstrate how Devito and its [SymPy](http://www.sympy.org/en/index.html)-powered symbolic API can be used to solve partial differential equations using the finite difference method with highly optimized stencils in a few lines of Python. We demonstrate how computational stencils can be derived directly from the equation in an automated fashion and how Devito can be used to generate and execute, at runtime, the desired numerical scheme in the form of optimized C code.\n\n\n## Defining the physical domain\n\nBefore we can begin creating finite-difference (FD) stencils we will need to give Devito a few details regarding the computational domain within which we wish to solve our problem. For this purpose we create a `Grid` object that stores the physical `extent` (the size) of our domain and knows how many points we want to use in each dimension to discretise our data.\n\n<img src=\"figures/grid.png\" style=\"width: 220px;\"/>", "_____no_output_____" ] ], [ [ "grid = Grid(shape=(5, 6), extent=(1., 1.))\ngrid", "_____no_output_____" ] ], [ [ "## Functions and data\n\nTo express our equation in symbolic form and discretise it using finite differences, Devito provides a set of `Function` types. A `Function` object:\n\n1. Behaves like a `sympy.Function` symbol\n2. Manages data associated with the symbol\n\nTo get more information on how to create and use a `Function` object, or any type provided by Devito, we can take a look at the documentation.", "_____no_output_____" ] ], [ [ "print(Function.__doc__)", "\n Tensor symbol representing a discrete function in symbolic equations.\n\n A Function carries multi-dimensional data and provides operations to create\n finite-differences approximations.\n\n A Function encapsulates space-varying data; for data that also varies in time,\n use TimeFunction instead.\n\n Parameters\n ----------\n name : str\n Name of the symbol.\n grid : Grid, optional\n Carries shape, dimensions, and dtype of the Function. When grid is not\n provided, shape and dimensions must be given. For MPI execution, a\n Grid is compulsory.\n space_order : int or 3-tuple of ints, optional\n Discretisation order for space derivatives. Defaults to 1. ``space_order`` also\n impacts the number of points available around a generic point of interest. By\n default, ``space_order`` points are available on both sides of a generic point of\n interest, including those nearby the grid boundary. Sometimes, fewer points\n suffice; in other scenarios, more points are necessary. In such cases, instead of\n an integer, one can pass a 3-tuple ``(o, lp, rp)`` indicating the discretization\n order (``o``) as well as the number of points on the left (``lp``) and right\n (``rp``) sides of a generic point of interest.\n shape : tuple of ints, optional\n Shape of the domain region in grid points. Only necessary if ``grid`` isn't given.\n dimensions : tuple of Dimension, optional\n Dimensions associated with the object. Only necessary if ``grid`` isn't given.\n dtype : data-type, optional\n Any object that can be interpreted as a numpy data type. Defaults\n to ``np.float32``.\n staggered : Dimension or tuple of Dimension or Stagger, optional\n Define how the Function is staggered.\n initializer : callable or any object exposing the buffer interface, optional\n Data initializer. If a callable is provided, data is allocated lazily.\n allocator : MemoryAllocator, optional\n Controller for memory allocation. To be used, for example, when one wants\n to take advantage of the memory hierarchy in a NUMA architecture. Refer to\n `default_allocator.__doc__` for more information.\n padding : int or tuple of ints, optional\n .. deprecated:: shouldn't be used; padding is now automatically inserted.\n\n Allocate extra grid points to maximize data access alignment. When a tuple\n of ints, one int per Dimension should be provided.\n\n Examples\n --------\n Creation\n\n >>> from devito import Grid, Function\n >>> grid = Grid(shape=(4, 4))\n >>> f = Function(name='f', grid=grid)\n >>> f\n f(x, y)\n >>> g = Function(name='g', grid=grid, space_order=2)\n >>> g\n g(x, y)\n\n First-order derivatives through centered finite-difference approximations\n\n >>> f.dx\n Derivative(f(x, y), x)\n >>> f.dy\n Derivative(f(x, y), y)\n >>> g.dx\n Derivative(g(x, y), x)\n >>> (f + g).dx\n Derivative(f(x, y) + g(x, y), x)\n\n First-order derivatives through left/right finite-difference approximations\n\n >>> f.dxl\n Derivative(f(x, y), x)\n\n Note that the fact that it's a left-derivative isn't captured in the representation.\n However, upon derivative expansion, this becomes clear\n\n >>> f.dxl.evaluate\n f(x, y)/h_x - f(x - h_x, y)/h_x\n >>> f.dxr\n Derivative(f(x, y), x)\n\n Second-order derivative through centered finite-difference approximation\n\n >>> g.dx2\n Derivative(g(x, y), (x, 2))\n\n Notes\n -----\n The parameters must always be given as keyword arguments, since SymPy\n uses ``*args`` to (re-)create the dimension arguments of the symbolic object.\n \n" ] ], [ [ "Ok, let's create a function $f(x, y)$ and look at the data Devito has associated with it. Please note that it is important to use explicit keywords, such as `name` or `grid` when creating `Function` objects.", "_____no_output_____" ] ], [ [ "f = Function(name='f', grid=grid)\nf", "_____no_output_____" ], [ "f.data", "_____no_output_____" ] ], [ [ "By default, Devito `Function` objects use the spatial dimensions `(x, y)` for 2D grids and `(x, y, z)` for 3D grids. To solve a PDE over several timesteps a time dimension is also required by our symbolic function. For this Devito provides an additional function type, the `TimeFunction`, which incorporates the correct dimension along with some other intricacies needed to create a time stepping scheme.", "_____no_output_____" ] ], [ [ "g = TimeFunction(name='g', grid=grid)\ng", "_____no_output_____" ] ], [ [ "Since the default time order of a `TimeFunction` is `1`, the shape of `f` is `(2, 5, 6)`, i.e. Devito has allocated two buffers to represent `g(t, x, y)` and `g(t + dt, x, y)`:", "_____no_output_____" ] ], [ [ "g.shape", "_____no_output_____" ] ], [ [ "## Derivatives of symbolic functions\n\nThe functions we have created so far all act as `sympy.Function` objects, which means that we can form symbolic derivative expressions from them. Devito provides a set of shorthand expressions (implemented as Python properties) that allow us to generate finite differences in symbolic form. For example, the property `f.dx` denotes $\\frac{\\partial}{\\partial x} f(x, y)$ - only that Devito has already discretised it with a finite difference expression. There are also a set of shorthand expressions for left (backward) and right (forward) derivatives:\n\n| Derivative | Shorthand | Discretised | Stencil |\n| ---------- |:---------:|:-----------:|:-------:|\n| $\\frac{\\partial}{\\partial x}f(x, y)$ (right) | `f.dxr` | $\\frac{f(x+h_x,y)}{h_x} - \\frac{f(x,y)}{h_x}$ | <img src=\"figures/stencil_forward.png\" style=\"width: 180px;\"/> |\n| $\\frac{\\partial}{\\partial x}f(x, y)$ (left) | `f.dxl` | $\\frac{f(x,y)}{h_x} - \\frac{f(x-h_x,y)}{h_x}$ | <img src=\"figures/stencil_backward.png\" style=\"width: 180px;\"/> |\n\nA similar set of expressions exist for each spatial dimension defined on our grid, for example `f.dy` and `f.dyl`. Obviously, one can also take derivatives in time of `TimeFunction` objects. For example, to take the first derivative in time of `g` you can simply write:", "_____no_output_____" ] ], [ [ "g.dt", "_____no_output_____" ] ], [ [ "We may also want to take a look at the stencil Devito will generate based on the chosen discretisation:", "_____no_output_____" ] ], [ [ "g.dt.evaluate", "_____no_output_____" ] ], [ [ "There also exist convenient shortcuts to express the forward and backward stencil points, `g(t+dt, x, y)` and `g(t-dt, x, y)`.", "_____no_output_____" ] ], [ [ "g.forward", "_____no_output_____" ], [ "g.backward", "_____no_output_____" ] ], [ [ "And of course, there's nothing to stop us taking derivatives on these objects:", "_____no_output_____" ] ], [ [ "g.forward.dt", "_____no_output_____" ], [ "g.forward.dy", "_____no_output_____" ] ], [ [ "## A linear convection operator\n\n**Note:** The following example is derived from [step 5](http://nbviewer.ipython.org/github/barbagroup/CFDPython/blob/master/lessons/07_Step_5.ipynb) in the excellent tutorial series [CFD Python: 12 steps to Navier-Stokes](http://lorenabarba.com/blog/cfd-python-12-steps-to-navier-stokes/).\n\nIn this simple example we will show how to derive a very simple convection operator from a high-level description of the governing equation. We will go through the process of deriving a discretised finite difference formulation of the state update for the field variable $u$, before creating a callable `Operator` object. Luckily, the automation provided by SymPy makes the derivation very nice and easy.\n\nThe governing equation we want to implement is the linear convection equation:\n$$\\frac{\\partial u}{\\partial t}+c\\frac{\\partial u}{\\partial x} + c\\frac{\\partial u}{\\partial y} = 0.$$\n\nBefore we begin, we must define some parameters including the grid, the number of timesteps and the timestep size. We will also initialize our velocity `u` with a smooth field:", "_____no_output_____" ] ], [ [ "from examples.cfd import init_smooth, plot_field\n\nnt = 100 # Number of timesteps\ndt = 0.2 * 2. / 80 # Timestep size (sigma=0.2)\nc = 1 # Value for c\n\n# Then we create a grid and our function\ngrid = Grid(shape=(81, 81), extent=(2., 2.))\nu = TimeFunction(name='u', grid=grid)\n\n# We can now set the initial condition and plot it\ninit_smooth(field=u.data[0], dx=grid.spacing[0], dy=grid.spacing[1])\ninit_smooth(field=u.data[1], dx=grid.spacing[0], dy=grid.spacing[1])\n\nplot_field(u.data[0])", "_____no_output_____" ] ], [ [ "Next, we wish to discretise our governing equation so that a functional `Operator` can be created from it. We begin by simply writing out the equation as a symbolic expression, while using shorthand expressions for the derivatives provided by the `Function` object. This will create a symbolic object of the dicretised equation.\n\nUsing the Devito shorthand notation, we can express the governing equations as:", "_____no_output_____" ] ], [ [ "eq = Eq(u.dt + c * u.dxl + c * u.dyl)\neq", "_____no_output_____" ] ], [ [ "We now need to rearrange our equation so that the term $u(t+dt, x, y)$ is on the left-hand side, since it represents the next point in time for our state variable $u$. Devito provides a utility called `solve`, built on top of SymPy's `solve`, to rearrange our equation so that it represents a valid state update for $u$. Here, we use `solve` to create a valid stencil for our update to `u(t+dt, x, y)`:", "_____no_output_____" ] ], [ [ "stencil = solve(eq, u.forward)\nupdate = Eq(u.forward, stencil)\nupdate", "_____no_output_____" ] ], [ [ "The right-hand side of the 'update' equation should be a stencil of the shape\n<img src=\"figures/stencil_convection.png\" style=\"width: 160px;\"/>\n\nOnce we have created this 'update' expression, we can create a Devito `Operator`. This `Operator` will basically behave like a Python function that we can call to apply the created stencil over our associated data, as long as we provide all necessary unknowns. In this case we need to provide the number of timesteps to compute via the keyword `time` and the timestep size via `dt` (both have been defined above):", "_____no_output_____" ] ], [ [ "op = Operator(update)\nop(time=nt+1, dt=dt)\n\nplot_field(u.data[0])", "Operator `Kernel` run in 0.01 s\n" ] ], [ [ "Note that the real power of Devito is hidden within `Operator`, it will automatically generate and compile the optimized C code. We can look at this code (noting that this is not a requirement of executing it) via:", "_____no_output_____" ] ], [ [ "print(op.ccode)", "#define _POSIX_C_SOURCE 200809L\n#include \"stdlib.h\"\n#include \"math.h\"\n#include \"sys/time.h\"\n#include \"xmmintrin.h\"\n#include \"pmmintrin.h\"\n\nstruct dataobj\n{\n void *restrict data;\n int * size;\n int * npsize;\n int * dsize;\n int * hsize;\n int * hofs;\n int * oofs;\n} ;\n\nstruct profiler\n{\n double section0;\n} ;\n\n\nint Kernel(const float dt, const float h_x, const float h_y, struct dataobj *restrict u_vec, const int time_M, const int time_m, struct profiler * timers, const int x_M, const int x_m, const int y_M, const int y_m)\n{\n float (*restrict u)[u_vec->size[1]][u_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]]) u_vec->data;\n /* Flush denormal numbers to zero in hardware */\n _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);\n _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n for (int time = time_m, t0 = (time)%(2), t1 = (time + 1)%(2); time <= time_M; time += 1, t0 = (time)%(2), t1 = (time + 1)%(2))\n {\n struct timeval start_section0, end_section0;\n gettimeofday(&start_section0, NULL);\n /* Begin section0 */\n for (int x = x_m; x <= x_M; x += 1)\n {\n #pragma omp simd aligned(u:32)\n for (int y = y_m; y <= y_M; y += 1)\n {\n u[t1][x + 1][y + 1] = (dt*h_x*u[t0][x + 1][y] + dt*h_y*u[t0][x][y + 1] + h_x*h_y*u[t0][x + 1][y + 1] - (dt*h_x*u[t0][x + 1][y + 1] + dt*h_y*u[t0][x + 1][y + 1]))/(h_x*h_y);\n }\n }\n /* End section0 */\n gettimeofday(&end_section0, NULL);\n timers->section0 += (double)(end_section0.tv_sec-start_section0.tv_sec)+(double)(end_section0.tv_usec-start_section0.tv_usec)/1000000;\n }\n return 0;\n}\n\n" ] ], [ [ "## Second derivatives and high-order stencils\n\nIn the above example only a combination of first derivatives was present in the governing equation. However, second (or higher) order derivatives are often present in scientific problems of interest, notably any PDE modeling diffusion. To generate second order derivatives we must give the `devito.Function` object another piece of information: the desired discretisation of the stencil(s).\n\nFirst, lets define a simple second derivative in `x`, for which we need to give $u$ a `space_order` of (at least) `2`. The shorthand for this second derivative is `u.dx2`. ", "_____no_output_____" ] ], [ [ "u = TimeFunction(name='u', grid=grid, space_order=2)\nu.dx2", "_____no_output_____" ], [ "u.dx2.evaluate", "_____no_output_____" ] ], [ [ "We can increase the discretisation arbitrarily if we wish to specify higher order FD stencils:", "_____no_output_____" ] ], [ [ "u = TimeFunction(name='u', grid=grid, space_order=4)\nu.dx2", "_____no_output_____" ], [ "u.dx2.evaluate", "_____no_output_____" ] ], [ [ "To implement the diffusion or wave equations, we must take the Laplacian $\\nabla^2 u$, which is the sum of the second derivatives in all spatial dimensions. For this, Devito also provides a shorthand expression, which means we do not have to hard-code the problem dimension (2D or 3D) in the code. To change the problem dimension we can create another `Grid` object and use this to re-define our `Function`'s:", "_____no_output_____" ] ], [ [ "grid_3d = Grid(shape=(5, 6, 7), extent=(1., 1., 1.))\n\nu = TimeFunction(name='u', grid=grid_3d, space_order=2)\nu", "_____no_output_____" ] ], [ [ "We can re-define our function `u` with a different `space_order` argument to change the discretisation order of the stencil expression created. For example, we can derive an expression of the 12th-order Laplacian $\\nabla^2 u$:", "_____no_output_____" ] ], [ [ "u = TimeFunction(name='u', grid=grid_3d, space_order=12)\nu.laplace", "_____no_output_____" ] ], [ [ "The same expression could also have been generated explicitly via:", "_____no_output_____" ] ], [ [ "u.dx2 + u.dy2 + u.dz2", "_____no_output_____" ] ], [ [ "## Derivatives of composite expressions\n\nDerivatives of any arbitrary expression can easily be generated:", "_____no_output_____" ] ], [ [ "u = TimeFunction(name='u', grid=grid, space_order=2)\nv = TimeFunction(name='v', grid=grid, space_order=2, time_order=2)", "_____no_output_____" ], [ "v.dt2 + u.laplace", "_____no_output_____" ], [ "(v.dt2 + u.laplace).dx2", "_____no_output_____" ] ], [ [ "Which can, depending on the chosen discretisation, lead to fairly complex stencils: ", "_____no_output_____" ] ], [ [ "(v.dt2 + u.laplace).dx2.evaluate", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
ecfa53f8c561f2c2236c429365f6d6af6213a861
5,370
ipynb
Jupyter Notebook
Machine Learning With Python/jupyter/starter/04 - Lesson - Reinforcement Learning.ipynb
shreejitverma/Data-Scientist
03c06936e957f93182bb18362b01383e5775ffb1
[ "MIT" ]
2
2022-03-12T04:53:03.000Z
2022-03-27T12:39:21.000Z
Machine Learning With Python/jupyter/starter/04 - Lesson - Reinforcement Learning.ipynb
shreejitverma/Data-Scientist
03c06936e957f93182bb18362b01383e5775ffb1
[ "MIT" ]
null
null
null
Machine Learning With Python/jupyter/starter/04 - Lesson - Reinforcement Learning.ipynb
shreejitverma/Data-Scientist
03c06936e957f93182bb18362b01383e5775ffb1
[ "MIT" ]
2
2022-03-12T04:52:21.000Z
2022-03-27T12:45:32.000Z
23.246753
146
0.528305
[ [ [ "# Reinforcement Learning\n### Goal of lesson\n- Understand how Reinforcement Learning works\n- Learn about Agent and Environment\n- How it iterates and gets rewards based on action\n- How to continuously learn new things\n- Create own Reinforcement Learning from scratch", "_____no_output_____" ], [ "### Reinforcement Learning simply explained\n- Given a set of rewards or punishments, learn what actions to take in the future\n- The second large group of Machine Learning\n\n### Environment\n<img src='img/reinforcement-learning.png' width=600 align='left'>", "_____no_output_____" ], [ "### Agent\n- The environment gives the agent a state\n- The agent action\n- The environment gives a state and reward (or punishment)", "_____no_output_____" ], [ "This is how robots are taught how to walk", "_____no_output_____" ], [ "### Markov Decision Process\n- Model for decision-making, representing states, actions, and their rewards\n- Set of states $S$\n- Set of actions $Actions(s)$\n- Transition model $P(s'|s, a)$\n- Reward function $R(s, a, s')$", "_____no_output_____" ], [ "### Q-learning (one model)\n- Method for learning a function $Q(s, a)$, estimate of the value of performing action $a$ in state $s$", "_____no_output_____" ], [ "### Q-learning\n- Start with $Q(s, a) = 0$ for all $s, a$\n- Update $Q$ when we take an action\n- $Q(s, a) = Q(s, a) + \\alpha($reward$ + \\gamma\\max(s', a') - Q(s, a)) = (1 - \\alpha)Q(s, a) + \\alpha($reward$ + \\gamma\\max(s', a'))$", "_____no_output_____" ], [ "### $\\epsilon$-Greedy Decision Making\n**Explore vs Exploit**\n- With propability $\\epsilon$ take a random move\n- Otherwise, take action $a$ with maximum $Q(s, a)$", "_____no_output_____" ], [ "### Simple task\n<img src='img/field.png' width=600 align='left'>\n", "_____no_output_____" ], [ "- Starts at a random point\n- Move left or right\n- Avoid the red box\n- Find the green box", "_____no_output_____" ], [ "![Field](img/field-3.png)", "_____no_output_____" ], [ "> #### Programming Notes:\n> - Libraries used\n> - [**numpy**](http://numpy.org) - scientific computing with Python ([Lecture on NumPy](https://youtu.be/BpzpU8_j0-c))\n> - [**random**](https://docs.python.org/3/library/random.html) - pseudo-random generators\n> - Functionality and concepts used\n> - **Object-Oriented Programming (OOP)**: [Lecture on Object Oriented Programming](https://youtu.be/hbO9xo6RfDM)", "_____no_output_____" ], [ "> ### Resources\n> #### What if there are more states?\n> - [Reinforcement Learning from Scratch](https://youtu.be/y4LEVVE2mV8)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ecfa581e8190a0bfb8e5ea43bbff6781142374f6
146,835
ipynb
Jupyter Notebook
notebooks/archives_spectacle/import_performance_info.ipynb
eliselavy/ada-oxford
3b00c31c53dba658e7d886e833b7181adae5d7c0
[ "MIT" ]
null
null
null
notebooks/archives_spectacle/import_performance_info.ipynb
eliselavy/ada-oxford
3b00c31c53dba658e7d886e833b7181adae5d7c0
[ "MIT" ]
null
null
null
notebooks/archives_spectacle/import_performance_info.ipynb
eliselavy/ada-oxford
3b00c31c53dba658e7d886e833b7181adae5d7c0
[ "MIT" ]
null
null
null
37.343591
12,288
0.471046
[ [ [ "# Récupération des données", "_____no_output_____" ], [ "## Pour un spectacle donné", "_____no_output_____" ] ], [ [ "import urllib.request\nimport re\nimport pandas as pd\nimport os\n# import the BeautifulSoup library so we can parse HTML and XML documents\nfrom bs4 import BeautifulSoup\n#spectacleId=\"37982\"\n\n#here id example with inside <p> <span class=\"n\"> spectacleId=\"60720\"\nspectacleId=\"723\"\n#spectacleId=\"60720\"\n#spectacleId=\"36956\"\n#spectacleId=\"20185\"\n# specify which URL/web page we are going to be scraping\nurl = \"https://www.lesarchivesduspectacle.net/?IDX_Spectacle=\" + spectacleId\n# open the url using urllib.request and put the HTML into the page variable\npage = urllib.request.urlopen(url)\n# parse the HTML from our URL into the BeautifulSoup parse tree format\nsoup = BeautifulSoup(page, \"lxml\")\n#the div where the information is\n#the div where the information is\ndiv_interested = soup.find('div', class_='fiche__footer') \ncolumn_label=[]\ncolumn_value=[]\nfor row in div_interested.find_all('table')[0].findAll('tr'):\n th = row.findAll('th')[0].contents[0]\n td = row.findAll('td')[0].contents[0]\n column_label.append(th)\n column_value.append(td)\nnew_table = pd.DataFrame(columns=column_label, index= [0]) # I know the size\nnew_table[\"spectacleId\"]=int(spectacleId)\nfor row in div_interested.find_all('table')[0].findAll('tr'):\n th = row.findAll('th')[0].contents[0]\n td = row.findAll('td')[0].contents[0].strip()\n new_table.at[0,th] = td\n#Recuperer creation_date - organism_creation \n#the div where the information is\ndiv_spectacle = soup.find('div', id='div_Spectacle')\np_spectacle = div_spectacle.find_all('p')[0]\nif(p_spectacle) != None :\n for time in p_spectacle.findAll('time'):\n if time.has_attr('datetime'):\n new_table[\"typeDate\"]=time.previousSibling\n new_table[\"date\"]=time['datetime']\n for organism in p_spectacle.findAll('a',class_ ='c_Organisme'):\n if organism.has_attr('href'):\n new_table[\"organismeId\"]=organism['href']\n new_table[\"organismeName\"]=organism.contents[0].strip()\n if p_spectacle.find_all('span'):\n first = next(p_spectacle.stripped_strings)\n new_table[\"to_analyse\"]=first\n else:\n new_table[\"to_analyse\"]=p_spectacle.contents[0].string.strip()\n#partie sur la taille des équipes\npossible_job=['Danse','Circassien']\nnb_equipe=len(soup.find_all('table', class_='f-spectacle__equipe'))\nnb_danseurs=0\njob_rowid = {}\nid_row_dance_start=0\nif nb_equipe > 1:\n nb_reprise=nb_equipe-1\n new_table[\"nombre reprise\"]=nb_reprise\n #on regarde si reprise\n reprise_div=soup.find_all('div', id='onglets-reprise')\n if reprise_div:\n rows=soup.find_all('table',class_='f-spectacle__equipe')[1].findAll('tr')\n for i in range(len(rows)):\n th_all = rows[i].findAll('th')\n #on récupère le nombre de row par métiers et la ligne danse\n for th in th_all:\n job_rowid[i] = th.getText()\n #find the row for the possible_job\n if any(x in th.getText() for x in possible_job):\n id_row_dance_start=i \n keys = list(job_rowid) \n if len(keys)>1:\n id_row_dance_end = keys[keys.index(id_row_dance_start) + 1] \n rows=soup.find_all('table', class_='f-spectacle__equipe')[1].findAll('tr')\n for j in range(len(rows)):\n if j>=id_row_dance_start and j<id_row_dance_end:\n #parfois <span class=\"c_Commentaire\">24 danseurs</span>\n span=rows[j].find('span',class_ ='c_Commentaire')\n if span:\n new_table[\"commentaire\"]=span.getText()\n anchor=rows[j].find('a',class_ ='c_Personne b')\n if anchor:\n nb_danseurs += 1\n else:\n new_table[\"commentaire\"]=\"problem qu'un élément métier\" \nif nb_equipe == 1:\n rows=soup.find_all('table')[0].findAll('tr')\n for i in range(len(rows)):\n th_all = rows[i].findAll('th')\n #on récupère le nombre de row par métiers et la ligne danse\n for th in th_all:\n job_rowid[i] = th.getText()\n #find the row for the possible_job\n if any(x in th.getText() for x in possible_job):\n id_row_dance_start=i\n if id_row_dance_start!=0:\n keys = list(job_rowid) \n id_row_dance_end = keys[keys.index(id_row_dance_start) + 1] \n rows=soup.find_all('table')[0].findAll('tr')\n for j in range(len(rows)):\n if j>=id_row_dance_start and j<id_row_dance_end:\n #parfois <span class=\"c_Commentaire\">24 danseurs</span>\n span=rows[j].find('span',class_ ='c_Commentaire')\n if span:\n new_table[\"commentaire\"]=span.getText()\n anchor=rows[j].find('a',class_ ='c_Personne b')\n if anchor:\n nb_danseurs += 1\n else:\n new_table[\"commentaire\"]=\"pas de job danse\" \nnew_table[\"nb danseur\"]=nb_danseurs \nnew_table\n\n", "_____no_output_____" ] ], [ [ "## Fonction pour récupérer les informations liées à un spectacle\n", "_____no_output_____" ] ], [ [ "import urllib.request\nimport re\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport socket, errno\nimport sys\n\ndef import_df_type_spectacle(spectacleId):\n # specify which URL/web page we are going to be scraping\n url = \"https://www.lesarchivesduspectacle.net/?IDX_Spectacle=\" + str(spectacleId) \n try:\n if spectacleId != 0:\n # open the url using urllib.request and put the HTML into the page variable\n page = urllib.request.urlopen(url)\n # parse the HTML from our URL into the BeautifulSoup parse tree format\n soup = BeautifulSoup(page, \"lxml\")\n div_interested = soup.find('div', class_='fiche__footer') \n column_label=[]\n column_value=[]\n for row in div_interested.find_all('table')[0].findAll('tr'):\n th = row.findAll('th')[0].contents[0]\n td = row.findAll('td')[0].contents[0]\n column_label.append(th)\n column_value.append(td)\n new_table = pd.DataFrame(columns=column_label, index= [0]) # I know the size\n new_table[\"spectacleId\"]=int(spectacleId)\n for row in div_interested.find_all('table')[0].findAll('tr'):\n th = row.findAll('th')[0].contents[0]\n td = row.findAll('td')[0].contents[0].strip()\n new_table.at[0,th] = td\n #Recuperer creation_date - organism_creation \n #the div where the information is\n div_spectacle = soup.find('div', id='div_Spectacle')\n p_spectacle = div_spectacle.find_all('p')[0]\n if(p_spectacle) != None :\n for time in p_spectacle.findAll('time'):\n if time.has_attr('datetime'):\n new_table[\"typeDate\"]=time.previousSibling\n new_table[\"date\"]=time['datetime']\n for organism in p_spectacle.findAll('a',class_ ='c_Organisme'):\n if organism.has_attr('href'):\n new_table[\"organismeId\"]=organism['href']\n new_table[\"organismeName\"]=organism.contents[0].strip()\n if p_spectacle.find_all('span'):\n first = next(p_spectacle.stripped_strings)\n new_table[\"to_analyse\"]=first\n else:\n new_table[\"to_analyse\"]=p_spectacle.contents[0].string.strip()\n return new_table\n except urllib.error.URLError as e:\n print(e.reason + \"for spectacleId \" + str(spectacleId))\n except socket.timeout as e: # <-------- this block here\n print(\"We timed out\")\n except Exception as e:\n print(\"Unexpected error for \" + str(spectacleId) + \" spectacle id \"+ str(e))\n raise \n\n\n\n", "_____no_output_____" ] ], [ [ "## Récupération des informations spectacles pour un organisme", "_____no_output_____" ] ], [ [ "import urllib.request\nimport re\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport time\nfrom datetime import datetime\nimport pandas as pd\nimport os\nimport socket, errno\nimport numpy as np\n# 439 Arsenal\n# 699 CCAM\n# 383 grand theatre \n# 1914 CARREAU\n\norganismId=\"1914\"\nprint(\"start\",datetime.now()) \npath=os.getcwd() + \"/data/\"\ncsv_file_path = path + \"all_10_years_organism_\" + organismId + \"_clean.csv\"\n\ndf = pd.read_csv(csv_file_path)\n#in case of several representation for a same performence 53079\nt_array = np.unique(df[\"performanceId\"].to_numpy())\n\nframes = [ import_df_type_spectacle(f) for f in t_array ]\nresult = pd.concat(frames)\nresult.set_index(['spectacleId'], drop=True, inplace=True)\nresult.to_csv(os.path.join(path,'all_10_years_organism_' + organismId + '_unique_clean_type_spectacle.csv'))\nprint(\"finish\",datetime.now())\n\n", "start 2020-08-23 16:57:41.373082\nfinish 2020-08-23 16:59:31.553471\n" ] ], [ [ "# Filtre sur les spectacles de danse\n\n", "_____no_output_____" ], [ "## Répartition par genre\n\nLa base de données référencent les spectacles théâtre - danse - danse jeune public\nA voir pour une évolution des spectacles jeune public", "_____no_output_____" ], [ "### Arsenal", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\norganismId=\"439\"\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_type_spectacle.csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\n#df_spectacle.groupby(\"Genre\")[\"spectacleId\"].count().sort_values(ascending=False)", "_____no_output_____" ] ], [ [ "Le jeune public", "_____no_output_____" ] ], [ [ "df_spectacle_arsenal", "_____no_output_____" ], [ "import re\n#Filtre sur le genre - string contains danse\ndf_danse_arsenal=df_spectacle_arsenal[df_spectacle_arsenal['Genre'].astype(str).str.contains(\"Danse\",flags=re.IGNORECASE, regex=True)]\nlen(df_danse_arsenal)", "_____no_output_____" ], [ "#Sur la danse - compte spectacle jeune public \nimport re\ndf_danse_arsenal_jeune=df_danse_arsenal[df_danse_arsenal['Genre'].astype(str).str.contains(\"Jeune public|à partir\",flags=re.IGNORECASE, regex=True)]\n# 51 spectacles len(df_danse_arsenal_jeune)\npart_jeune_arsenal=len(df_danse_arsenal_jeune)*100/len(df_danse_arsenal)\npart_jeune_arsenal", "_____no_output_____" ] ], [ [ "### Grand théâtre", "_____no_output_____" ] ], [ [ "import time\nimport os\nfrom datetime import datetime\nimport pandas as pd\norganismId=\"383\"\n\n\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_type_spectacle.csv\"\ndf_spectacle_lux = pd.read_csv(csv_file_path)\n#Filtre sur le genre - string contains danse\n\ndf_danse_lux=df_spectacle_lux[df_spectacle_lux['Genre'].astype(str).str.contains(\"Danse\")]\nlen(df_danse_lux)", "_____no_output_____" ], [ "#Sur la danse - compte spectacle jeune public \nimport re\ndf_danse_lux_jeune=df_danse_lux[df_danse_lux['Genre'].astype(str).str.contains(\"Jeune public|à partir\",flags=re.IGNORECASE, regex=True)]\npart_jeune_lux=len(df_danse_lux_jeune)*100/len(df_danse_lux)\npart_jeune_lux\n", "_____no_output_____" ] ], [ [ "### CCAM", "_____no_output_____" ] ], [ [ "import time\nimport os\nfrom datetime import datetime\nimport pandas as pd\norganismId=\"699\"\n\n\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_type_spectacle.csv\"\ndf_spectacle_ccam = pd.read_csv(csv_file_path)\n#Filtre sur le genre - string contains danse\n\ndf_danse_ccam=df_spectacle_ccam[df_spectacle_ccam['Genre'].astype(str).str.contains(\"Danse\")]\ndf_danse_ccam", "_____no_output_____" ], [ "#Sur la danse - compte spectacle jeune public \nimport re\ndf_danse_ccam_jeune=df_danse_ccam[df_danse_ccam['Genre'].astype(str).str.contains(\"Jeune public|à partir\",flags=re.IGNORECASE, regex=True)]\npart_jeune_ccam=len(df_danse_ccam_jeune)*100/len(df_danse_ccam)\npart_jeune_ccam", "_____no_output_____" ] ], [ [ "### Carreau", "_____no_output_____" ] ], [ [ "import time\nimport os\nfrom datetime import datetime\nimport pandas as pd\norganismId=\"1914\"\n\n\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_type_spectacle.csv\"\ndf_spectacle_carreau = pd.read_csv(csv_file_path)\n#Filtre sur le genre - string contains danse\n\ndf_danse_carreau=df_spectacle_carreau[df_spectacle_carreau['Genre'].astype(str).str.contains(\"Danse\")]\ndf_danse_carreau", "_____no_output_____" ], [ "#Sur la danse - compte spectacle jeune public \nimport re\ndf_danse_carreau_jeune=df_danse_carreau[df_danse_carreau['Genre'].astype(str).str.contains(\"Jeune public|à partir\",flags=re.IGNORECASE, regex=True)]\npart_jeune_carreau=len(df_danse_carreau_jeune)*100/len(df_danse_carreau)\npart_jeune_carreau", "_____no_output_____" ] ], [ [ "### Résumé part de la programmation jeunesse danse dans la programmation", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nplt.figure(figsize = (8, 8))\nsizes = [part_jeune_arsenal, part_jeune_lux, part_jeune_ccam, part_jeune_carreau]\nlabels = 'Arsenal', 'Grand théâtre', 'CCAM', 'Carreau'\nexplode = (0, 0.1, 0, 0) # only \"explode\" the 2nd slice (i.e. 'Hogs')\n\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, explode=explode, labels=labels,\n startangle=90)\nax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n\nplt.show()\n", "_____no_output_____" ], [ "sizes = [part_jeune_arsenal, part_jeune_lux, part_jeune_ccam, part_jeune_carreau]\nsizes", "_____no_output_____" ] ], [ [ "## Répartition par pays", "_____no_output_____" ], [ "### Arsenal", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfig, ax = plt.subplots(figsize=(6,6))\nax.set_title('Répartition des chorégraphes')\nax=df_danse_arsenal.groupby(\"Pays\")[\"spectacleId\"].count().sort_values(ascending=False).head(5).plot.pie(autopct='%1.1f%%')\n\n\n\nfig = ax.get_figure()\nfig.savefig(os.getcwd() + \"/data/arsenal_pays.png\")\nplt.clf()\n", "_____no_output_____" ] ], [ [ "### Luxembourg", "_____no_output_____" ] ], [ [ "#df_danse.Pays.value_counts().head(5)\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfig, ax = plt.subplots(figsize=(6,6))\nax.set_title('Répartition des chorégraphes')\nax=df_danse_lux.groupby(\"Pays\")[\"spectacleId\"].count().sort_values(ascending=False).head(5).plot.pie(autopct='%1.1f%%')\n\n\n\nfig = ax.get_figure()\nfig.savefig(os.getcwd() + \"/data/lux_pays.png\")\nplt.clf()\n", "_____no_output_____" ] ], [ [ "### CCAM", "_____no_output_____" ] ], [ [ "#df_danse.Pays.value_counts().head(5)\n\n#df_danse.Pays.value_counts().head(5)\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfig, ax = plt.subplots(figsize=(6,6))\nax.set_title('Répartition des chorégraphes')\nax=df_danse_ccam.groupby(\"Pays\")[\"spectacleId\"].count().sort_values(ascending=False).head(5).plot.pie(autopct='%1.1f%%')\n\n\nfig = ax.get_figure()\nfig.savefig(os.getcwd() + \"/data/ccam_pays.png\")\nplt.clf()\n\n", "_____no_output_____" ] ], [ [ "### Carreau", "_____no_output_____" ] ], [ [ "\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfig, ax = plt.subplots(figsize=(6,6))\nax.set_title('Répartition des chorégraphes')\nax=df_danse_carreau.groupby(\"Pays\")[\"spectacleId\"].count().sort_values(ascending=False).head(5).plot.pie(autopct='%1.1f%%')\n\nfig = ax.get_figure()\nfig.savefig(os.getcwd() + \"/data/carreau_pays.png\")\nplt.clf()\n\n", "_____no_output_____" ] ], [ [ "## Part de création faite\n\nregarder dans la colonne organismeId", "_____no_output_____" ], [ "### Arsenal", "_____no_output_____" ] ], [ [ "import re\n#Filtre sur le genre - string contains danse\ndf_danse_cree_arsenal=df_danse_arsenal[df_danse_arsenal['organismeId'].astype(str).str.contains(\"439\",flags=re.IGNORECASE, regex=True)]\ndf_danse_cree_arsenal", "_____no_output_____" ] ], [ [ "### Luxembourg", "_____no_output_____" ] ], [ [ "import re\n#Filtre sur le genre - string contains danse\ndf_danse_cree_lux=df_danse_lux[df_danse_lux['organismeId'].astype(str).str.contains(\"383\",flags=re.IGNORECASE, regex=True)]\nlen(df_danse_cree_lux)", "_____no_output_____" ] ], [ [ "### CCAM", "_____no_output_____" ] ], [ [ "import re\n#Filtre sur le genre - string contains danse\ndf_danse_cree_ccam=df_danse_ccam[df_danse_ccam['organismeId'].astype(str).str.contains(\"699\",flags=re.IGNORECASE, regex=True)]\nlen(df_danse_cree_ccam)", "_____no_output_____" ] ], [ [ "### Carreau", "_____no_output_____" ] ], [ [ "import re\n#Filtre sur le genre - string contains danse\ndf_danse_cree_carreau=df_danse_carreau[df_danse_carreau['organismeId'].astype(str).str.contains(\"1914\",flags=re.IGNORECASE, regex=True)]\nlen(df_danse_cree_carreau)", "_____no_output_____" ] ], [ [ "### Organismes qui font le plus de création\n\nAttention nous sommes sur les spectacles diffusés par Arsenal / Grand théâtre / CCAM / Carreau", "_____no_output_____" ], [ "# Décalage entre création et diffusion\n\nvoir si conforme à l'étude onda \n\n- garder spectacleId / typeDate / date / to_analyse\n- si typeDate et date vide - alors to_analyse\n", "_____no_output_____" ], [ "## Date de création", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\nimport re\norganismId=\"1914\"\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_type_spectacle.csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\n#Filtre sur le genre - string contains danse\ndf_danse_arsenal=df_spectacle_arsenal[df_spectacle_arsenal['Genre'].astype(str).str.contains(\"Danse\",flags=re.IGNORECASE, regex=True)]\ndf_danse_arsenal= df_danse_arsenal[['spectacleId', 'typeDate', 'date','to_analyse']]\n#on enlève les performances sans date\ndf_danse_arsenal.dropna(subset=['typeDate','date','to_analyse'], how='all', inplace=True)\n#on transforme le champ date en datetime\ndf_danse_arsenal['date']= pd.to_datetime(df_danse_arsenal['date'], format='%Y-%m-%d', errors='coerce')\n# on garde que l'année \ndf_danse_arsenal['date']=df_danse_arsenal.date.dt.year\n# on ne garde que l'année dans la colonne to_analyse\n#df_danse_arsenal['to_analyse']=df_danse_arsenal['to_analyse'].replace(\"Création le\",\"\")\n#df_danse_arsenal['to_analyse'] = df_danse_arsenal['to_analyse'].str[-4:]\n#df_danse_arsenal.loc[df_danse_arsenal['to_analyse'] !='','year_creation'] = df_danse_arsenal['to_analyse'] \n#df_danse_arsenal.loc[pd.isna(df_danse_arsenal['year_creation']),'year_creation'] = df_danse_arsenal['date'] \n#df_danse_arsenal= df_danse_arsenal[['spectacleId', 'year_creation']]\n#df_danse_arsenal = df_danse_arsenal.astype(int)\n\n#df_danse_arsenal\n\n#################\n#df_danse_arsenal = df_danse_arsenal[df_danse_arsenal['spectacleId'] == 63852]\n####ici cas Luxembourg \ndf_danse_arsenal.loc[pd.notna(df_danse_arsenal['date']),'year_creation'] = df_danse_arsenal['date'] \ndf_danse_arsenal['to_analyse']=df_danse_arsenal['to_analyse'].replace(\"Création le\",\"\")\ndf_danse_arsenal['to_analyse'] = df_danse_arsenal['to_analyse'].str[-4:]\ndf_danse_arsenal.loc[pd.isna(df_danse_arsenal['year_creation']),'year_creation'] = df_danse_arsenal['to_analyse']\ndf_danse_arsenal= df_danse_arsenal[['spectacleId', 'year_creation']]\ndf_danse_arsenal = df_danse_arsenal.astype(int)\ndf_danse_arsenal\n################\n\n#path=os.getcwd() + \"/data/\"\n#df_danse_arsenal.to_csv(os.path.join(path,'all_creation_luxembourg.csv'))\n\n#créer une nouvelle colonne date_year si date NaN alors on prend to_analyse\n#fn = lambda row: row.a + row.b # define a function for the new column\n#col = df_danse_arsenal.apply(fn, axis=1) # get column data with an index\n#df_danse_arsenal = df_danse_arsenal.assign(c=col.values) # assign values to column 'c'df['C'] = df['C'].apply(np.int64)", "_____no_output_____" ] ], [ [ "## Date de diffusion", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\n\norganismId=\"1914\"\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_arsenal_diffusion = pd.read_csv(csv_file_path)\n#on enlève les lignes où les performanceId sont nulles\n#df_arsenal_diffusion.dropna(subset=['performanceId'], how='all', inplace=True)\ndf_arsenal_diffusion = df_arsenal_diffusion[~(df_arsenal_diffusion['performanceId']==0)]\ndf_arsenal_diffusion= df_arsenal_diffusion[['performanceId', 'year','performance','author']]\ndf_arsenal_diffusion.rename(columns = {'performanceId':'spectacleId'}, inplace = True)\ndf_arsenal_diffusion.rename(columns = {'year':'year_diffusion'}, inplace = True)\ndf_arsenal_diffusion", "_____no_output_____" ], [ "#spectacleId\n#43869 4\n#59854 4\n#87796 4", "_____no_output_____" ] ], [ [ "## Comparaison date de création et date de diffusion", "_____no_output_____" ] ], [ [ "#join df_arsenal_diffusion et df_danse_arsenal\ndf_creation_diffusion = df_danse_arsenal.join(df_arsenal_diffusion.set_index('spectacleId'), on='spectacleId')\n#path=os.getcwd() + \"/data/\"\n#df_creation_diffusion.to_csv(os.path.join(path,'all_creation_diffusion.csv'))\ndf_creation_diffusion", "_____no_output_____" ], [ "df_creation_diffusion.groupby(\"spectacleId\")[\"spectacleId\"].count().sort_values(ascending=False).head(5)", "_____no_output_____" ], [ "#créer une nouvelle colonne (date de diffusion - date de création)\nfn = lambda row: row.year_diffusion - row.year_creation # define a function for the new column\ncol = df_creation_diffusion.apply(fn, axis=1) # get column data with an index\ndf_creation_diffusion = df_creation_diffusion.assign(gap_crea_diffu=col.values) # assign values to column 'c'df['C'] = df['C'].apply(np.int64)\ndf_creation_diffusion.gap_crea_diffu.mean()", "_____no_output_____" ], [ "df_creation_diffusion = df_creation_diffusion[df_creation_diffusion['gap_crea_diffu'] > 5]\ndf_creation_diffusion", "_____no_output_____" ] ], [ [ "# Taille de l'équipe", "_____no_output_____" ] ], [ [ "## Fonction pour récupérer le nombre de danseurs", "_____no_output_____" ], [ "import urllib.request\nimport re\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport socket, errno\nimport sys\n\n \n\n#fallait juste boucler sur les th et prendre tous les td et si nouveau th stop\ndef import_dancers(spectacleId):\n # specify which URL/web page we are going to be scraping\n url = \"https://www.lesarchivesduspectacle.net/?IDX_Spectacle=\" + str(spectacleId) \n try:\n if spectacleId != 0:\n # open the url using urllib.request and put the HTML into the page variable\n page = urllib.request.urlopen(url)\n # parse the HTML from our URL into the BeautifulSoup parse tree format\n soup = BeautifulSoup(page, \"lxml\")\n #partie sur la taille des équipes\n possible_job=['Danse','Performance']\n #restriction to class == 'f-spectacle__equipe' for case like 74343\n nb_equipe=len(soup.find_all(lambda tag: tag.name == 'table' and tag.get('class') == ['f-spectacle__equipe']))\n #nb_equipe=len(soup.find_all('table', class_='f-spectacle__equipe'))\n #print(soup.find_all('table',class_='f-spectacle__equipe')[1])\n nb_danseurs=0\n job_rowid = {}\n name_rowid = {}\n id_row_dance_start=0\n id_row_dance_end=0\n commentaire=\"\"\n nb_reprise=0\n index_after_dance=0\n new_table= pd.DataFrame(columns=[\"spectacleId\",\"nombre reprise\",\"commentaire\",\"nb danseur\"])\n if nb_equipe > 2:\n nb_reprise=nb_equipe-1\n num_array=1\n if nb_equipe == 1:\n nb_reprise=0\n num_array=0\n if nb_equipe == 2:\n nb_reprise=1\n num_array=0\n if nb_equipe >=1: \n rows=soup.find_all(lambda tag: tag.name == 'table' and tag.get('class') == ['f-spectacle__equipe'])[num_array].findAll('tr')\n #rows=soup.find_all('table',class_='f-spectacle__equipe')[num_array].findAll('tr')\n for i in range(len(rows)):\n th_all = rows[i].findAll('th')\n #on récupère le nombre de row par métiers et la ligne danse\n for th in th_all:\n job_rowid[i] = th.getText()\n if any(x in job_rowid[i] for x in possible_job):\n id_row_dance_start=i\n \n #ok on n'a maintenant un tableau avec le numéro de ligne du job + le job\n #faut récupérer les td après ces numéros de lignes\n for i in range(len(rows)):\n td_all = rows[i].findAll('td')\n #on récupère le nombre de row par métiers et la ligne danse\n for td in td_all:\n name_rowid[i] = td.getText()\n #faut récupérer l'id du job qui suit la danse mais parfois les id ne se suivent pas car il ya des lignes vides\n for index, item in enumerate(job_rowid):\n #print(index,item)\n if (item==id_row_dance_start):\n #on récupère l'id de la danse\n index_dance=index\n index_after_dance=index_dance + 1\n #dans le cas où l'élément danse n'est pas le dernier élément\n if(index==index_after_dance):\n id_row_dance_end=item\n #cas ou il n'y a pas de danse index_dance=0\n if index_dance ==0 and id_row_dance_start==0 : \n commentaire=\"pas de danseurs\"\n else:\n #si danse alors on va récupérer les danseurs de id_row_dance_start à id_row_dance_end\n #rows=soup.find_all('table',class_='f-spectacle__equipe')[num_array].findAll('tr')\n #print(rows)\n for j in range(len(rows)):\n #si danse pas le dernier job\n if id_row_dance_end!=0: \n if j>=id_row_dance_start and j<id_row_dance_end:\n span=rows[j].find('span',class_ ='c_Commentaire')\n if span:\n commentaire=span.getText()\n anchor=rows[j].find('a',class_ ='c_Personne b')\n if anchor:\n nb_danseurs += 1\n #que danse https://www.lesarchivesduspectacle.net/?IDX_Spectacle=41661\n else:\n span=rows[j].find('span',class_ ='c_Commentaire')\n if span:\n commentaire=span.getText()\n anchor=rows[j].find('a',class_ ='c_Personne b')\n if anchor:\n nb_danseurs += 1 \n new_table = new_table.append({\"spectacleId\":spectacleId,\"nombre reprise\":nb_reprise,\"commentaire\":commentaire,\"nb danseur\":nb_danseurs},ignore_index=True)\n nb_danseurs=0\n commentaire=\"\"\n nb_reprise=0\n return new_table\n except urllib.error.URLError as e:\n print(e.reason + \"for spectacleId \" + str(spectacleId))\n except socket.timeout as e: # <-------- this block here\n print(\"We timed out\")\n except Exception as e:\n print(\"Unexpected error for \" + str(spectacleId) + \" spectacle id \"+ str(e))\n raise \n", "_____no_output_____" ], [ "#un danseur\n#import_dancers(55490)\n\n#une reprise\n#import_dancers(59854)\n#import_dancers(90517)\n\n#import_dancers(74343)\n#pas de la danse\n#import_dancers(50625)\n\n#erreur\nimport_dancers(80888)\n\n#import_dancers(41661)\n\n#Spectacle avec reprise\n#3 reprises\n#import_dancers(24948)\n# 1 reprise\n#import_dancers(723)", "_____no_output_____" ], [ "#fallait juste boucler sur les th et prendre tous les td et si nouveau th stop", "_____no_output_____" ], [ "#Problème si un danseur\n#55490\t\n#90517\n\n#Pas de danse\n#67807 Sous la neige \n#83396 Mon théâtre, techniques de pointe expliquées à mes voisins\n#86085 Alain Platel\n# 20985 reprise pas de danse définie\n\n\n\n# c'est un organisme id. 31575\n\n#20985\tSatchie Noro en alternance avec Marie Tassin\n\n\n#41661 que danse", "_____no_output_____" ] ], [ [ "## Récupérer le nombre de danseurs pour un organisme", "_____no_output_____" ] ], [ [ "import urllib.request\nimport re\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport time\nfrom datetime import datetime\nimport pandas as pd\nimport os\nimport socket, errno\n# 439 Arsenal\n# 699 CCAM\n# 383 grand theatre \n# 1914 CARREAU\n\norganismId=\"1914\"\nprint(\"start\",datetime.now()) \npath=os.getcwd() + \"/data/\"\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_danse.csv\"\ndf = pd.read_csv(csv_file_path)\n#Filtre sur le genre - string contains danse\ndf=df[df['Genre'].astype(str).str.contains(\"Danse\",flags=re.IGNORECASE, regex=True)]\nt_array = df[\"performanceId\"].to_numpy()\n\nframes = [ import_dancers(f) for f in t_array ]\nresult = pd.concat(frames)\nresult.set_index(['spectacleId'], drop=True, inplace=True)\nresult.to_csv(os.path.join(path,'all_10_years_organism_' + organismId + '_danse_nb_danseurs.csv'))\nprint(\"finish\",datetime.now())\n\n", "start 2020-08-30 06:25:18.775234\nfinish 2020-08-30 06:25:50.322672\n" ], [ "## Analyse du nombre \n\norganismId=\"439\"\npath=os.getcwd() + \"/data/\"\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_danse_nb_danseurs.csv\"\ndf = pd.read_csv(csv_file_path)\ndf = df[df['nb danseur'] < 1]\ndf", "_____no_output_____" ] ], [ [ "# Esthétique", "_____no_output_____" ], [ "D'après la liste des 30 chorégraphes définies dans Philippe Noisette, *Danse Contemporaine, mode d’emploi*, Paris, Flammarion, 2010", "_____no_output_____" ] ], [ [ "\n", "_____no_output_____" ] ], [ [ "## Arsenal", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\norganismId=\"439\"\nfilterChoregraphNoisette=[20588,4367,48218,47910,9113,6591,4676,10350,4182,7824,913,36997,504,10635,4786,6500,11280,4674,53732,2265,2227,7788,434,2412,2413,269,2260,14757,4040,14746,4654,9113]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nchoregraph_zoom_df.authordId.nunique()\n\n\n", "_____no_output_____" ], [ "#Antonia Baehr\nimport os\nimport pandas as pd\norganismId=\"439\"\nfilterChoregraphNoisette=[42962]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nchoregraph_zoom_df", "_____no_output_____" ], [ "#François Chaignaud / Cecilia Bengolea\nimport os\nimport pandas as pd\norganismId=\"439\"\nfilterChoregraphNoisette=[18144,11289]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_danse.csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nzoom_df =choregraph_zoom_df[[\"performanceId\",\"performance\",\"author\",\"place\",\"year\",\"occurency\"]]\nzoom_df", "_____no_output_____" ], [ "#ballet de lorrraine\n#148826 peter jacobson\nimport os\nimport pandas as pd\norganismId=\"439\"\nfilterChoregraphNoisette=[148826]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \"_danse.csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nchoregraph_zoom_df", "_____no_output_____" ] ], [ [ "## Grand théâtre", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\norganismId=\"383\"\nfilterChoregraphNoisette=[20588,4367,48218,47910,9113,6591,4676,10350,4182,7824,913,36997,504,10635,4786,6500,11280,4674,53732,2265,2227,7788,434,2412,2413,269,2260,14757,4040,14746,4654,9113]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nchoregraph_zoom_df.authordId.nunique()", "_____no_output_____" ], [ "import os\nimport pandas as pd\norganismId=\"383\"\nfilterChoregraphNoisette=[161754]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nchoregraph_zoom_df", "_____no_output_____" ] ], [ [ "## Anne Teresa De Keersmaeker\n\nLien spécifique \n- Red Bridge project\nhttps://theatres.lu/ARCHIVES/SAISON+2017-2018/RED+BRIDGE+PROJECT.html\n\nid personne 913\n", "_____no_output_____" ] ], [ [ "csv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin([913])]\nlen(choregraph_zoom_df)", "_____no_output_____" ], [ "choregraph_zoom_df", "_____no_output_____" ] ], [ [ "## CCAM", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\norganismId=\"699\"\nfilterChoregraphNoisette=[20588,4367,48218,47910,9113,6591,4676,10350,4182,7824,913,36997,504,10635,4786,6500,11280,4674,53732,2265,2227,7788,434,2412,2413,269,2260,14757,4040,14746,4654,9113]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nchoregraph_zoom_df.authordId.nunique()", "_____no_output_____" ] ], [ [ "## Carreau", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\norganismId=\"1914\"\nfilterChoregraphNoisette=[20588,4367,48218,47910,9113,6591,4676,10350,4182,7824,913,36997,504,10635,4786,6500,11280,4674,53732,2265,2227,7788,434,2412,2413,269,2260,14757,4040,14746,4654,9113]\ncsv_file_path = os.getcwd() + \"/data/all_10_years_organism_\" + organismId + \".csv\"\ndf_spectacle_arsenal = pd.read_csv(csv_file_path)\nchoregraph_zoom_df = df_spectacle_arsenal[df_spectacle_arsenal.authordId.isin(filterChoregraphNoisette)]\nchoregraph_zoom_df.authordId.nunique()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfa5835df8b513c25d6eb9158ed8669a4989838
11,383
ipynb
Jupyter Notebook
examples/big_grid.ipynb
andrewm4894/am4894plots
e72933543fe4fbcede5ef4a45a506203590d99be
[ "MIT" ]
1
2021-01-14T17:11:39.000Z
2021-01-14T17:11:39.000Z
examples/big_grid.ipynb
andrewm4894/am4894plots
e72933543fe4fbcede5ef4a45a506203590d99be
[ "MIT" ]
1
2021-05-08T07:15:20.000Z
2021-05-08T21:57:44.000Z
examples/big_grid.ipynb
andrewm4894/am4894plots
e72933543fe4fbcede5ef4a45a506203590d99be
[ "MIT" ]
1
2020-08-15T22:00:15.000Z
2020-08-15T22:00:15.000Z
34.704268
173
0.393306
[ [ [ "from am4894pd.utils import df_dummy_ts # used to generate some dummy data\nfrom am4894plots.plots import plot_lines, plot_lines_grid\nfrom am4894plots.lines.bokeh import plot_lines as plot_lines_bokeh\nfrom am4894plots.lines.bokeh import plot_lines_grid as plot_lines_grid_bk\n\n# generate some dummy time series data\ndf = df_dummy_ts(n_cols=100, freq='1min')\nprint(df.shape)\ndisplay(df.head())", "(1342, 100)\n" ], [ "# make shaded region\nshade_regions = [\n (df.index[-300:].min(), df.index[-101], 'lightblue'),\n (df.index[-100:].min(), df.index.max(), 'yellow')\n]\nprint(shade_regions)", "[(Timestamp('2019-01-01 19:01:00'), Timestamp('2019-01-01 22:20:00'), 'lightblue'), (Timestamp('2019-01-01 22:21:00'), Timestamp('2019-01-02 00:00:00'), 'yellow')]\n" ], [ "subplot_titles = [f'blah blah blah blah blah blah - {col}' for col in df.columns]", "_____no_output_____" ], [ "# plot each time series on single plot as a line\nplot_lines_grid(\n df, subplot_titles=subplot_titles, return_p=False, show_p=False, out_path='example_plots/big_grid.html', h_each=100, w=1200, \n legend=False, yaxes_visible=False, shade_regions=shade_regions, text_position='bottom right', xaxes_visible=False\n)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
ecfa693f3e7d07ff4046121fe9729f39f865e14f
157,311
ipynb
Jupyter Notebook
notebooks/01CPI_EDA.ipynb
NeilBardhan/economics
50230551c2d2d99fdcb7259fe2881860b8ca70d3
[ "MIT" ]
null
null
null
notebooks/01CPI_EDA.ipynb
NeilBardhan/economics
50230551c2d2d99fdcb7259fe2881860b8ca70d3
[ "MIT" ]
null
null
null
notebooks/01CPI_EDA.ipynb
NeilBardhan/economics
50230551c2d2d99fdcb7259fe2881860b8ca70d3
[ "MIT" ]
null
null
null
823.617801
153,192
0.954765
[ [ [ "# Examining the Consumer Price Index", "_____no_output_____" ] ], [ [ "import os\nimport sys\nimport json\nimport requests\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "os.chdir('..')\nsys.path.append(os.getcwd() + '/src/')", "_____no_output_____" ] ], [ [ "## Reading in the CPI", "_____no_output_____" ] ], [ [ "cpi_df = pd.read_csv(os.getcwd() + '/data/CPI.csv', header='infer')\ncpi_df.head()", "_____no_output_____" ] ], [ [ "## Filtering the CPI on `date`", "_____no_output_____" ] ], [ [ "cpi_df['date'] = pd.to_datetime(cpi_df['date'], format='%Y-%m-%d')\ncpi_5y = cpi_df[cpi_df['date'] >= '2016-01-01']", "_____no_output_____" ] ], [ [ "## Plotting the CPI", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(16, 9), dpi=300)\nplt.plot(cpi_5y['date'], cpi_5y['CPIAUCSL'], color='red');", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfa725edf04539c70eea90be9705f56e59de818
172,732
ipynb
Jupyter Notebook
Multinomial-Naive-Bayes-Main.ipynb
Prakhar-Bhartiya/SentimentAnalysis
8fa2664a57b01e7303ef26d1226a81c0e25be4b7
[ "MIT" ]
null
null
null
Multinomial-Naive-Bayes-Main.ipynb
Prakhar-Bhartiya/SentimentAnalysis
8fa2664a57b01e7303ef26d1226a81c0e25be4b7
[ "MIT" ]
null
null
null
Multinomial-Naive-Bayes-Main.ipynb
Prakhar-Bhartiya/SentimentAnalysis
8fa2664a57b01e7303ef26d1226a81c0e25be4b7
[ "MIT" ]
null
null
null
68.300514
12,012
0.625263
[ [ [ "# DATA DESCRIPTION\n\n**Sentiment140 dataset. It contains 1,600,000 tweets extracted using the twitter api.**<br>\n\nIt contains the following 6 fields:<br>\n\n1. target: the polarity of the tweet (0 = negative, 2 = neutral, 4 = positive)<br>\n2. ids: The id of the tweet ( 2087)<br>\n3. date: the date of the tweet (Sat May 16 23:58:44 UTC 2009) <br>\n4. flag: The query (lyx). If there is no query, then this value is NO_QUERY.<br>\n5. user: the user that tweeted (robotickilldozr)<br>\n6. text: the text of the tweet (Lyx is cool)<br>\n\n", "_____no_output_____" ] ], [ [ "#Imports\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport re\nfrom tqdm import tqdm", "_____no_output_____" ], [ "tweets_df=pd.read_csv('data/training.1600000.processed.noemoticon.csv', encoding = 'latin', header=None)\ntweets_df = tweets_df.sample(frac=1)\n#Data including total available\nprint(\"Total Data\")\nprint(len(tweets_df))\ntweets_df = tweets_df[0:1600000]\nprint(\"Used Data\")\nprint(len(tweets_df))\ntweets_df = tweets_df.rename(columns={0: 'target', 1: 'id', 2: 'TimeStamp', 3: 'query', 4: 'username', 5: 'content'})\ntweets_df.drop(['id','TimeStamp','query','username'], axis=1, inplace=True)", "Total Data\n1600000\nUsed Data\n1600000\n" ], [ "tweets_df", "_____no_output_____" ], [ "tweets_df.info()\n", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 1600000 entries, 241728 to 987352\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 target 1600000 non-null int64 \n 1 content 1600000 non-null object\ndtypes: int64(1), object(1)\nmemory usage: 36.6+ MB\n" ], [ "#Distribution Histogram\ntweets_df.hist(bins=30,figsize=(13,5),color='r')", "_____no_output_____" ], [ "tweets_df['length']=tweets_df['content'].apply(len)\ntweets_df", "_____no_output_____" ], [ "tweets_df['length'].plot(bins=100, kind='hist')", "_____no_output_____" ], [ "positive=tweets_df[tweets_df['target']==4]\nnegative=tweets_df[tweets_df['target']==0]", "_____no_output_____" ], [ "positive", "_____no_output_____" ], [ "negative", "_____no_output_____" ], [ "sentences=tweets_df['content'].tolist()\nsentences", "_____no_output_____" ], [ "print(\"Total Data :\",len(sentences))\n\nprint(\"Total Positive :\",len(positive))\n\nprint(\"Total Negative :\",len(negative))\n", "Total Data : 1600000\nTotal Positive : 800000\nTotal Negative : 800000\n" ] ], [ [ "**Cleaning Data**\n\nReplacing handwritten emojis with their feeling associated. <br>\nConvert to lowercase.<br>\nReplace contractions.<br>\nReplace abbrevations.<br>\nReplace unicode emojis with their feeling associated.<br>\nRemove all other unicoded emojis.<br>\nRemove NON- ASCII characters.<br>\nRemove numbers.<br>\nRemove \"#\". <br>\nRemove \"@\". <br>\nRemove usernames.<br>\nRemove 'RT'. <br>\nReplace all URLs and Links with word 'URL'.<br>\nRemove all punctuations.<br>\nRemoves single letter words.<br>\nRemoves double and quad backslashes.<br>\nRemoves Stop Words.<br>\nRemoves Links or Mentions.<br>\nApply Stemming.<br>\n\nPS : Stemming - [Running, Runned, Runner] all can reduce to the stem Run. <br>\n\n![Emojis code](img/emoji_data_1.png)", "_____no_output_____" ] ], [ [ "abbreviations = {\n \"$\" : \" dollar \",\n \"€\" : \" euro \",\n \"4ao\" : \"for adults only\",\n \"a.m\" : \"before midday\",\n \"a3\" : \"anytime anywhere anyplace\",\n \"aamof\" : \"as a matter of fact\",\n \"acct\" : \"account\",\n \"adih\" : \"another day in hell\",\n \"afaic\" : \"as far as i am concerned\",\n \"afaict\" : \"as far as i can tell\",\n \"afaik\" : \"as far as i know\",\n \"afair\" : \"as far as i remember\",\n \"afk\" : \"away from keyboard\",\n \"app\" : \"application\",\n \"approx\" : \"approximately\",\n \"apps\" : \"applications\",\n \"asap\" : \"as soon as possible\",\n \"asl\" : \"age, sex, location\",\n \"atk\" : \"at the keyboard\",\n \"ave.\" : \"avenue\",\n \"aymm\" : \"are you my mother\",\n \"ayor\" : \"at your own risk\", \n \"b&b\" : \"bed and breakfast\",\n \"b+b\" : \"bed and breakfast\",\n \"b.c\" : \"before christ\",\n \"b2b\" : \"business to business\",\n \"b2c\" : \"business to customer\",\n \"b4\" : \"before\",\n \"b4n\" : \"bye for now\",\n \"b@u\" : \"back at you\",\n \"bae\" : \"before anyone else\",\n \"bak\" : \"back at keyboard\",\n \"bbbg\" : \"bye bye be good\",\n \"bbc\" : \"british broadcasting corporation\",\n \"bbias\" : \"be back in a second\",\n \"bbl\" : \"be back later\",\n \"bbs\" : \"be back soon\",\n \"be4\" : \"before\",\n \"bfn\" : \"bye for now\",\n \"blvd\" : \"boulevard\",\n \"bout\" : \"about\",\n \"brb\" : \"be right back\",\n \"bros\" : \"brothers\",\n \"brt\" : \"be right there\",\n \"bsaaw\" : \"big smile and a wink\",\n \"btw\" : \"by the way\",\n \"bwl\" : \"bursting with laughter\",\n \"c/o\" : \"care of\",\n \"cet\" : \"central european time\",\n \"cf\" : \"compare\",\n \"cia\" : \"central intelligence agency\",\n \"csl\" : \"can not stop laughing\",\n \"cu\" : \"see you\",\n \"cul8r\" : \"see you later\",\n \"cv\" : \"curriculum vitae\",\n \"cwot\" : \"complete waste of time\",\n \"cya\" : \"see you\",\n \"cyt\" : \"see you tomorrow\",\n \"dae\" : \"does anyone else\",\n \"dbmib\" : \"do not bother me i am busy\",\n \"diy\" : \"do it yourself\",\n \"dm\" : \"direct message\",\n \"dwh\" : \"during work hours\",\n \"e123\" : \"easy as one two three\",\n \"eet\" : \"eastern european time\",\n \"eg\" : \"example\",\n \"embm\" : \"early morning business meeting\",\n \"encl\" : \"enclosed\",\n \"encl.\" : \"enclosed\",\n \"etc\" : \"and so on\",\n \"faq\" : \"frequently asked questions\",\n \"fawc\" : \"for anyone who cares\",\n \"fb\" : \"facebook\",\n \"fc\" : \"fingers crossed\",\n \"fig\" : \"figure\",\n \"fimh\" : \"forever in my heart\", \n \"ft.\" : \"feet\",\n \"ft\" : \"featuring\",\n \"ftl\" : \"for the loss\",\n \"ftw\" : \"for the win\",\n \"fwiw\" : \"for what it is worth\",\n \"fyi\" : \"for your information\",\n \"g9\" : \"genius\",\n \"gahoy\" : \"get a hold of yourself\",\n \"gal\" : \"get a life\",\n \"gcse\" : \"general certificate of secondary education\",\n \"gfn\" : \"gone for now\",\n \"gg\" : \"good game\",\n \"gl\" : \"good luck\",\n \"glhf\" : \"good luck have fun\",\n \"gmt\" : \"greenwich mean time\",\n \"gmta\" : \"great minds think alike\",\n \"gn\" : \"good night\",\n \"g.o.a.t\" : \"greatest of all time\",\n \"goat\" : \"greatest of all time\",\n \"goi\" : \"get over it\",\n \"gps\" : \"global positioning system\",\n \"gr8\" : \"great\",\n \"gratz\" : \"congratulations\",\n \"gyal\" : \"girl\",\n \"h&c\" : \"hot and cold\",\n \"hp\" : \"horsepower\",\n \"hr\" : \"hour\",\n \"hrh\" : \"his royal highness\",\n \"ht\" : \"height\",\n \"ibrb\" : \"i will be right back\",\n \"ic\" : \"i see\",\n \"icq\" : \"i seek you\",\n \"icymi\" : \"in case you missed it\",\n \"idc\" : \"i do not care\",\n \"idgadf\" : \"i do not give a damn fuck\",\n \"idgaf\" : \"i do not give a fuck\",\n \"idk\" : \"i do not know\",\n \"ie\" : \"that is\",\n \"i.e\" : \"that is\",\n \"ifyp\" : \"i feel your pain\",\n \"IG\" : \"instagram\",\n \"iirc\" : \"if i remember correctly\",\n \"ilu\" : \"i love you\",\n \"ily\" : \"i love you\",\n \"imho\" : \"in my humble opinion\",\n \"imo\" : \"in my opinion\",\n \"imu\" : \"i miss you\",\n \"iow\" : \"in other words\",\n \"irl\" : \"in real life\",\n \"j4f\" : \"just for fun\",\n \"jic\" : \"just in case\",\n \"jk\" : \"just kidding\",\n \"jsyk\" : \"just so you know\",\n \"l8r\" : \"later\",\n \"lb\" : \"pound\",\n \"lbs\" : \"pounds\",\n \"ldr\" : \"long distance relationship\",\n \"lmao\" : \"laugh my ass off\",\n \"lmfao\" : \"laugh my fucking ass off\",\n \"lol\" : \"laughing out loud\",\n \"ltd\" : \"limited\",\n \"ltns\" : \"long time no see\",\n \"m8\" : \"mate\",\n \"mf\" : \"motherfucker\",\n \"mfs\" : \"motherfuckers\",\n \"mfw\" : \"my face when\",\n \"mofo\" : \"motherfucker\",\n \"mph\" : \"miles per hour\",\n \"mr\" : \"mister\",\n \"mrw\" : \"my reaction when\",\n \"ms\" : \"miss\",\n \"mte\" : \"my thoughts exactly\",\n \"nagi\" : \"not a good idea\",\n \"nbc\" : \"national broadcasting company\",\n \"nbd\" : \"not big deal\",\n \"nfs\" : \"not for sale\",\n \"ngl\" : \"not going to lie\",\n \"nhs\" : \"national health service\",\n \"nrn\" : \"no reply necessary\",\n \"nsfl\" : \"not safe for life\",\n \"nsfw\" : \"not safe for work\",\n \"nth\" : \"nice to have\",\n \"nvr\" : \"never\",\n \"nyc\" : \"new york city\",\n \"oc\" : \"original content\",\n \"og\" : \"original\",\n \"ohp\" : \"overhead projector\",\n \"oic\" : \"oh i see\",\n \"omdb\" : \"over my dead body\",\n \"omg\" : \"oh my god\",\n \"omw\" : \"on my way\",\n \"p.a\" : \"per annum\",\n \"p.m\" : \"after midday\",\n \"pm\" : \"prime minister\",\n \"poc\" : \"people of color\",\n \"pov\" : \"point of view\",\n \"pp\" : \"pages\",\n \"ppl\" : \"people\",\n \"prw\" : \"parents are watching\",\n \"ps\" : \"postscript\",\n \"pt\" : \"point\",\n \"ptb\" : \"please text back\",\n \"pto\" : \"please turn over\",\n \"qpsa\" : \"what happens\", \n \"ratchet\" : \"rude\",\n \"rbtl\" : \"read between the lines\",\n \"rlrt\" : \"real life retweet\", \n \"rofl\" : \"rolling on the floor laughing\",\n \"roflol\" : \"rolling on the floor laughing out loud\",\n \"rotflmao\" : \"rolling on the floor laughing my ass off\",\n \"rt\" : \"retweet\",\n \"ruok\" : \"are you ok\",\n \"sfw\" : \"safe for work\",\n \"sk8\" : \"skate\",\n \"smh\" : \"shake my head\",\n \"sq\" : \"square\",\n \"srsly\" : \"seriously\", \n \"ssdd\" : \"same stuff different day\",\n \"tbh\" : \"to be honest\",\n \"tbs\" : \"tablespooful\",\n \"tbsp\" : \"tablespooful\",\n \"tfw\" : \"that feeling when\",\n \"thks\" : \"thank you\",\n \"tho\" : \"though\",\n \"thx\" : \"thank you\",\n \"tia\" : \"thanks in advance\",\n \"til\" : \"today i learned\",\n \"tl;dr\" : \"too long i did not read\",\n \"tldr\" : \"too long i did not read\",\n \"tmb\" : \"tweet me back\",\n \"tntl\" : \"trying not to laugh\",\n \"ttyl\" : \"talk to you later\",\n \"u\" : \"you\",\n \"u2\" : \"you too\",\n \"u4e\" : \"yours for ever\",\n \"utc\" : \"coordinated universal time\",\n \"w/\" : \"with\",\n \"w/o\" : \"without\",\n \"w8\" : \"wait\",\n \"wassup\" : \"what is up\",\n \"wb\" : \"welcome back\",\n \"wtf\" : \"what the fuck\",\n \"wtg\" : \"way to go\",\n \"wtpa\" : \"where the party at\",\n \"wuf\" : \"where are you from\",\n \"wuzup\" : \"what is up\",\n \"wywh\" : \"wish you were here\",\n \"yd\" : \"yard\",\n \"ygtr\" : \"you got that right\",\n \"ynk\" : \"you never know\",\n \"zzz\" : \"sleeping bored and tired\"\n}", "_____no_output_____" ], [ "from string import punctuation\n\nprint(\"DATA CLEANING -- \\n\")\n\n# emojis defined\nemoji_pattern = re.compile(\"[\"\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\n\n#This function replaces happy unicode emojis with \"happy\" and sad unicode emojis with \"sad\".\ndef replace_emojis(t):\n\n emoji_happy = [\"\\U0001F600\", \"\\U0001F601\", \"\\U0001F602\",\"\\U0001F603\",\"\\U0001F604\",\"\\U0001F605\", \"\\U0001F606\", \"\\U0001F607\", \"\\U0001F609\", \n \"\\U0001F60A\", \"\\U0001F642\",\"\\U0001F643\",\"\\U0001F923\",r\"\\U0001F970\",\"\\U0001F60D\", r\"\\U0001F929\",\"\\U0001F618\",\"\\U0001F617\",\n r\"\\U000263A\", \"\\U0001F61A\", \"\\U0001F619\", r\"\\U0001F972\", \"\\U0001F60B\", \"\\U0001F61B\", \"\\U0001F61C\", r\"\\U0001F92A\",\n \"\\U0001F61D\", \"\\U0001F911\", \"\\U0001F917\", r\"\\U0001F92D\", r\"\\U0001F92B\",\"\\U0001F914\",\"\\U0001F910\", r\"\\U0001F928\", \"\\U0001F610\", \"\\U0001F611\",\n \"\\U0001F636\", \"\\U0001F60F\",\"\\U0001F612\", \"\\U0001F644\",\"\\U0001F62C\",\"\\U0001F925\",\"\\U0001F60C\",\"\\U0001F614\",\"\\U0001F62A\",\n \"\\U0001F924\",\"\\U0001F634\", \"\\U0001F920\", r\"\\U0001F973\", r\"\\U0001F978\",\"\\U0001F60E\",\"\\U0001F913\", r\"\\U0001F9D0\"]\n\n emoji_sad = [\"\\U0001F637\",\"\\U0001F912\",\"\\U0001F915\",\"\\U0001F922\", r\"\\U0001F92E\",\"\\U0001F927\", r\"\\U0001F975\", r\"\\U0001F976\", r\"\\U0001F974\",\n \"\\U0001F635\", r\"\\U0001F92F\", \"\\U0001F615\",\"\\U0001F61F\",\"\\U0001F641\", r\"\\U0002639\",\"\\U0001F62E\",\"\\U0001F62F\",\"\\U0001F632\",\n \"\\U0001F633\", r\"\\U0001F97A\",\"\\U0001F626\",\"\\U0001F627\",\"\\U0001F628\",\"\\U0001F630\",\"\\U0001F625\",\"\\U0001F622\",\"\\U0001F62D\",\n \"\\U0001F631\",\"\\U0001F616\",\"\\U0001F623\"\t,\"\\U0001F61E\",\"\\U0001F613\",\"\\U0001F629\",\"\\U0001F62B\", r\"\\U0001F971\",\n \"\\U0001F624\",\"\\U0001F621\",\"\\U0001F620\", r\"\\U0001F92C\",\"\\U0001F608\",\"\\U0001F47F\",\"\\U0001F480\", r\"\\U0002620\"]\n\n words = t.split()\n reformed = []\n for w in words:\n if w in emoji_happy:\n reformed.append(\"happy\")\n elif w in emoji_sad:\n reformed.append(\"sad\") \n else:\n reformed.append(w)\n t = \" \".join(reformed)\n return t\n\n\n\n#This function replaces happy smileys with \"happy\" and sad smileys with \"sad.\ndef replace_smileys(t):\n \n emoticons_happy = set([':-)', ':)', ';)', ':o)', ':]', ':3', ':c)', ':>', '=]', '8)', '=)', ':}', ':D',\n ':^)', ':-D', ':D', '8-D', '8D', 'x-D', 'xD', 'X-D', 'XD', '=-D', '=D',\n '=-3', '=3', ':-))', \":'-)\", \":')\", ':*', ':^*', '>:P', ':-P', ':P', 'X-P',\n 'x-p', 'xp', 'XP', ':-p', ':p', '=p', ':-b', ':b', '>:)', '>;)', '>:-)', '<3'])\n\n emoticons_sad = set([':L', ':-/', '>:/', ':S', '>:[', ':@', ':-(', ':[', ':-||', '=L', ':<',\n ':-[', ':-<', '=\\\\', '=/', '>:(', ':(', '>.<', \":'-(\", \":'(\", ':\\\\', ':-c',\n ':c', ':{', '>:\\\\', ';(']) \n\n words = t.split()\n reformed = []\n for w in words:\n if w in emoticons_happy:\n reformed.append(\"happy\")\n elif w in emoticons_sad:\n reformed.append(\"sad\") \n else:\n reformed.append(w)\n t = \" \".join(reformed)\n return t\n\n#This function replaces common abbrevation into full form\ndef convert_abbrev_in_text(tweet):\n t=[]\n words=tweet.split()\n t = [abbreviations[w.lower()] if w.lower() in abbreviations.keys() else w for w in words]\n return ' '.join(t) \n\n#This function replaces english lanuage contractions like \"shouldn't\" with \"should not\"\ndef replace_contractions(t):\n\n cont = {\"aren't\" : 'are not', \"can't\" : 'cannot', \"couln't\": 'could not', \"didn't\": 'did not', \"doesn't\" : 'does not',\n \"hadn't\": 'had not', \"haven't\": 'have not', \"he's\" : 'he is', \"she's\" : 'she is', \"he'll\" : \"he will\", \n \"she'll\" : 'she will',\"he'd\": \"he would\", \"she'd\":\"she would\", \"here's\" : \"here is\", \n \"i'm\" : 'i am', \"i've\"\t: \"i have\", \"i'll\" : \"i will\", \"i'd\" : \"i would\", \"isn't\": \"is not\", \n \"it's\" : \"it is\", \"it'll\": \"it will\", \"mustn't\" : \"must not\", \"shouldn't\" : \"should not\", \"that's\" : \"that is\", \n \"there's\" : \"there is\", \"they're\" : \"they are\", \"they've\" : \"they have\", \"they'll\" : \"they will\",\n \"they'd\" : \"they would\", \"wasn't\" : \"was not\", \"we're\": \"we are\", \"we've\":\"we have\", \"we'll\": \"we will\", \n \"we'd\" : \"we would\", \"weren't\" : \"were not\", \"what's\" : \"what is\", \"where's\" : \"where is\", \"who's\": \"who is\",\n \"who'll\" :\"who will\", \"won't\":\"will not\", \"wouldn't\" : \"would not\", \"you're\": \"you are\", \"you've\":\"you have\",\n \"you'll\" : \"you will\", \"you'd\" : \"you would\", \"mayn't\" : \"may not\"}\n words = t.split()\n reformed = []\n for w in words:\n if w in cont:\n reformed.append(cont[w])\n else:\n reformed.append(w)\n t = \" \".join(reformed)\n return t \n\n\n#This function removes words that are single characters\ndef remove_single_letter_words(t):\n words = t.split()\n reformed = []\n for w in words:\n if len(w) > 1:\n reformed.append(w)\n t = \" \".join(reformed)\n return t \n\n\nprint(\"Cleaning the tweets from the data.\\n\")\nprint(\"Replacing handwritten emojis with their feeling associated.\")\nprint(\"Convert to lowercase.\")\nprint(\"Replace contractions.\")\nprint(\"Replace abbrevations.\")\nprint(\"Replace unicode emojis with their feeling associated.\")\nprint(\"Remove all other unicoded emojis.\")\nprint(\"Remove NON- ASCII characters.\")\nprint(\"Remove numbers.\")\nprint(\"Remove \\\"#\\\". \")\nprint(\"Remove \\\"@\\\". \")\nprint(\"Remove usernames.\")\nprint(\"Remove \\'RT\\'. \")\nprint(\"Replace all URLs and Links with word \\'URL\\'.\")\nprint(\"Remove all punctuations.\")\nprint(\"Removes single letter words.\\n\")\n\n#This function cleans the tweets. (Main Function)\ndef dataclean(t):\n\n t = replace_smileys(t) # replace handwritten emojis with their feeling associated\n t = t.lower() # convert to lowercase\n t = replace_contractions(t) # replace short forms used in english with their actual words\n t = convert_abbrev_in_text(t) #replace abbrevations with real full form\n t = replace_emojis(t) # replace unicode emojis with their feeling associated\n t = emoji_pattern.sub(r'', t) # remove emojis other than smiley emojis\n t = re.sub('\\\\\\\\u[0-9A-Fa-f]{4}','', t) # remove NON- ASCII characters\n t = re.sub(\"[0-9]\", \"\", t) # remove numbers # re.sub(\"\\d+\", \"\", t)\n t = re.sub('#', '', t) # remove '#'\n t = re.sub('@[A-Za-z0–9]+', '', t) # remove '@'\n t = re.sub('@[^\\s]+', '', t) # remove usernames\n t = re.sub('RT[\\s]+', '', t) # remove retweet 'RT'\n t = re.sub('((www\\.[^\\s]+)|(https?://[^\\s]+))', '', t) # remove links (URLs/ links)\n t = re.sub('[!\"$%&\\'()*+,-./:@;<=>?[\\\\]^_`{|}~]', '', t) # remove punctuations\n t = t.replace('\\\\\\\\', '')#remove backslashes\n t = t.replace('\\\\', '')\n t = remove_single_letter_words(t) # removes single letter words\n \n return t\n\ntqdm.pandas(desc=\"Data Cleaning Process :\")\ntweets_df['content'] = tweets_df['content'].progress_apply(dataclean)\nprint(\"Tweets have been cleaned.\")\n", "\rData Cleaning Process :: 0%| | 0/1600000 [00:00<?, ?it/s]" ], [ "import nltk \nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem import SnowballStemmer", "[nltk_data] Downloading package stopwords to\n[nltk_data] /Users/prakharbhartiya/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "#NLTK\n#Removing [stopwords + Links] \n#Stemming e.g connection, connected .... = connect\n\nenglish_stopwords = stopwords.words('english')\nprint(\"Stopwords\")\nprint(english_stopwords)\n\n#base of english stopwords\nstemmer = SnowballStemmer('english')\n#stemming algorithm\nregex = \"@\\S+|https?:\\S+|http?:\\S|[^A-Za-z0-9]+\"\n#regex for mentions and links in tweets\n\ndef preprocess(content, stem=False):\n content = re.sub(regex, ' ', str(content).lower()).strip()\n tokens = []\n for token in content.split():\n if token not in english_stopwords:\n tokens.append(stemmer.stem(token))\n return \" \".join(tokens)\n\ntqdm.pandas(desc=\"StopWord Removal and Stemming :\")\ntweets_df.content = tweets_df.content.progress_apply(lambda x: preprocess(x))", "StopWord Removal and Stemming :: 0%| | 845/1600000 [00:00<03:09, 8442.38it/s]" ], [ "from sklearn.feature_extraction.text import CountVectorizer\nvectorizer = CountVectorizer()\ntweets_countvectorizer = vectorizer.fit_transform(tweets_df['content'])", "_____no_output_____" ], [ "X=tweets_countvectorizer\ny=tweets_df['target']", "_____no_output_____" ], [ "tweets_countvectorizer.shape", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ], [ "y.shape", "_____no_output_____" ], [ "from 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)", "_____no_output_____" ], [ "from sklearn.naive_bayes import MultinomialNB\nNB_classifier = MultinomialNB()\nNB_classifier.fit(X_train, y_train)", "_____no_output_____" ], [ "from sklearn.metrics import classification_report, confusion_matrix\ny_predict_test=NB_classifier.predict(X_test)\ncm=confusion_matrix(y_test,y_predict_test)\nsns.heatmap(cm, annot=True)", "_____no_output_____" ], [ "print(classification_report(y_test,y_predict_test))", " precision recall f1-score support\n\n 0 0.76 0.78 0.77 159996\n 4 0.77 0.75 0.76 160004\n\n accuracy 0.76 320000\n macro avg 0.76 0.76 0.76 320000\nweighted avg 0.76 0.76 0.76 320000\n\n" ], [ "#Testing Custom Input\n\"\"\"\ninput_tweet = \"I am happy today :D 😁\"\ninput_tweet = dataclean(input_tweet)\ninput_tweet = preprocess(input_tweet)\ninput_tweet_list = list()\ninput_tweet_list.append(input_tweet)\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nvectorizer = CountVectorizer()\n\ntwe = vectorizer.fit_transform(input_tweet_list).toarray()\n\nprint(NB_classifier.predict_proba(twe))\n\n\"\"\"", "_____no_output_____" ], [ "#try ann or logitic reg", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfa77022beace8c221ed28a61326b9aae096a8a
102,967
ipynb
Jupyter Notebook
notebooks/Dataset Generation.ipynb
teomores/Oracle_HPC_contest
f2a358ac71416c032d8bd9fcffeaa7098ddaa7b4
[ "Apache-2.0" ]
4
2020-01-22T13:42:24.000Z
2022-03-21T15:43:59.000Z
notebooks/Dataset Generation.ipynb
russointroitoa/Oracle_HPC_contest
6be9a097abc6d4b45f7c80e7095f536a38b13161
[ "Apache-2.0" ]
8
2020-09-25T19:19:26.000Z
2022-02-10T02:37:32.000Z
notebooks/Dataset Generation.ipynb
russointroitoa/Oracle_HPC_contest
6be9a097abc6d4b45f7c80e7095f536a38b13161
[ "Apache-2.0" ]
1
2020-01-30T08:27:35.000Z
2020-01-30T08:27:35.000Z
38.121807
133
0.400157
[ [ [ "import pandas as pd\nimport numpy as np\nfrom tqdm.auto import tqdm\nfrom scipy import *\nfrom scipy.sparse import *", "_____no_output_____" ] ], [ [ "# Get top10 from test set ", "_____no_output_____" ] ], [ [ "sim_name = load_npz('../similarity_cosine_complete_name.npz')\nsim_email = load_npz('../similarity_cosine_complete_email.npz')\nhybrid = sim_name + 0.3*sim_email", "_____no_output_____" ], [ "df_train = pd.read_csv('../dataset/original/train.csv', escapechar=\"\\\\\")\ndf_test = pd.read_csv('../dataset/original/test.csv', escapechar=\"\\\\\")", "_____no_output_____" ], [ "df_train = df_train.sort_values(by=['record_id']).reset_index(drop=True)\ndf_test = df_test.sort_values(by=['record_id']).reset_index(drop=True)", "_____no_output_____" ], [ "# Takes both linked_id and the corresponding record_id index to get the cosine similarity value from sim\nlinid_ = []\nlinid_idx = []\nlinid_score = []\nfor x in tqdm(range(df_test.shape[0])):\n#for x in tqdm(range(10)):\n if x == 0:\n df = df_train.loc[hybrid[x].nonzero()[1][hybrid[x].data[1:].argsort()[::-1]],:].drop_duplicates(['linked_id'])[:10]\n linid_.append(df['linked_id'].values)\n linid_idx.append(list(df.index))\n linid_score.append([hybrid[x, t] for t in df.index])\n else:\n df = df_train.loc[hybrid[x].nonzero()[1][hybrid[x].data.argsort()[::-1]],:].drop_duplicates(['linked_id'])[:10]\n linid_.append(df['linked_id'].values)\n linid_idx.append(list(df.index))\n linid_score.append([hybrid[x, t] for t in df.index])", "_____no_output_____" ], [ "linid_ = []\nlinid_idx = []\nlinid_score = []\nfor x in tqdm(range(df_test.shape[0])):\n#for x in tqdm(range(10)):\n df = df_train.loc[hybrid[x].nonzero()[1][hybrid[x].data.argsort()[::-1]],:].drop_duplicates(['linked_id'])[:10]\n linid_.append(df['linked_id'].values)\n linid_idx.append(list(df.index))\n linid_score.append([hybrid[x, t] for t in df.index])", "_____no_output_____" ], [ "df = pd.DataFrame()\ndf['queried_record_id'] = df_test.record_id", "_____no_output_____" ], [ "df['predicted_record_id'] = linid_\ndf['cosine_score'] = linid_score\ndf['linked_id_idx'] = linid_idx", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df_list = []\nfor (q, pred, score, idx) in tqdm(zip(df.queried_record_id, df.predicted_record_id, df.cosine_score, df.linked_id_idx)):\n for x in range(len(pred)):\n df_list.append((q, pred[x], score[x], idx[x]))\n#df_list", "_____no_output_____" ], [ "df_new = pd.DataFrame(df_list, columns=['queried_record_id', 'predicted_record_id', 'cosine_score', 'linked_id_idx'])\ndf_new", "_____no_output_____" ], [ "df_new.to_csv('test_xgb.csv', index=False)", "_____no_output_____" ] ], [ [ "# Get top10 from validation set", "_____no_output_____" ] ], [ [ "sim_name = load_npz('../similarity_cosine_complete_name_X_val.npz')\nsim_email = load_npz('../similarity_cosine_complete_email_X_val.npz')\nhybrid = sim_name + 0.3*sim_email\ndf_train = pd.read_csv('../dataset/validation/train.csv', escapechar=\"\\\\\", index_col=0)\ndf_test = pd.read_csv('../dataset/validation/test.csv', escapechar=\"\\\\\", index_col=0)\ndf_train = df_train.sort_values(by=['record_id']).reset_index(drop=True)\ndf_test = df_test.sort_values(by=['record_id']).reset_index(drop=True)", "_____no_output_____" ], [ "# Non usare questa con l'ibrido\n# Takes both linked_id and the corresponding record_id index to get the cosine similarity value from sim\nlinid_ = []\nlinid_idx = []\nlinid_score = []\nfor x in tqdm(range(df_test.shape[0])):\n#for x in tqdm(range(10)):\n #if x == 0:\n # df = df_train.loc[hybrid[x].nonzero()[1][hybrid[x].data[1:].argsort()[::-1]],:].drop_duplicates(['linked_id'])[:10]\n # linid_.append(df['linked_id'].values)\n # linid_idx.append(list(df.index))\n # linid_score.append([hybrid[x, t] for t in df.index])\n else:\n df = df_train.loc[hybrid[x].nonzero()[1][hybrid[x].data.argsort()[::-1]],:].drop_duplicates(['linked_id'])[:10]\n linid_.append(df['linked_id'].values)\n linid_idx.append(list(df.index))\n linid_score.append([hybrid[x, t] for t in df.index])", "_____no_output_____" ], [ "linid_ = []\nlinid_idx = []\nlinid_score = []\nfor x in tqdm(range(df_test.shape[0])):\n#for x in tqdm(range(10)):\n df = df_train.loc[hybrid[x].nonzero()[1][hybrid[x].data.argsort()[::-1]],:].drop_duplicates(['linked_id'])[:100]\n linid_.append(df['linked_id'].values)\n linid_idx.append(list(df.index))\n linid_score.append([hybrid[x, t] for t in df.index])", "_____no_output_____" ], [ "df = pd.DataFrame()\ndf['queried_record_id'] = df_test.record_id\ndf['predicted_record_id'] = linid_\ndf['cosine_score'] = linid_score\ndf['linked_id_idx'] = linid_idx", "_____no_output_____" ], [ "df_list = []\nfor (q, pred, score, idx) in tqdm(zip(df.queried_record_id, df.predicted_record_id, df.cosine_score, df.linked_id_idx)):\n for x in range(len(pred)):\n df_list.append((q, pred[x], score[x], idx[x]))", "_____no_output_____" ], [ "df_new = pd.DataFrame(df_list, columns=['queried_record_id', 'predicted_record_id', 'cosine_score', 'linked_id_idx'])\ndf_new", "_____no_output_____" ], [ "df_new.to_csv('train_xgb.csv', index=False)", "_____no_output_____" ], [ "train = pd.read_csv(\"../dataset/original/train.csv\", escapechar=\"\\\\\")", "_____no_output_____" ], [ "group = train.groupby('linked_id').size().reset_index().rename(columns= {0:'size'})", "_____no_output_____" ], [ "len(group)", "_____no_output_____" ], [ "group[group['size'] > 1]", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfa85440708d25f2cd54f5767e0d41bca2340e7
348,673
ipynb
Jupyter Notebook
notebooks/Module1_unit4/3_Analyse_WaPOR_data.ipynb
LaurenZ-IHE/WAPOROCW
7e1357f23a142ea4394404f4462ed7ceb1f47009
[ "CC0-1.0" ]
7
2020-10-08T21:09:06.000Z
2022-02-08T08:48:31.000Z
notebooks/Module1_unit4/3_Analyse_WaPOR_data.ipynb
LaurenZ-IHE/WAPOROCW
7e1357f23a142ea4394404f4462ed7ceb1f47009
[ "CC0-1.0" ]
9
2020-10-03T04:26:57.000Z
2022-03-01T10:56:01.000Z
notebooks/Module1_unit4/3_Analyse_WaPOR_data.ipynb
LaurenZ-IHE/WAPOROCW
7e1357f23a142ea4394404f4462ed7ceb1f47009
[ "CC0-1.0" ]
5
2020-09-30T05:45:21.000Z
2022-02-08T08:48:38.000Z
236.870245
67,644
0.899499
[ [ [ "# Analysing WaPOR data\n\nThis notebook contains code example to analyse WaPOR data, including:\n- [1. Calculate the average value of ROI](#1.-Calculate-the-average-value-of-ROI)\n- [2. Working with timeseries (pandas library)](#2.-Working-with-timeseries-(pandas-library))\n- [3. Raster calculation](#3.-Raster-calculation)\n- [4. Land-use analysis](#4.-Land-use-analysis)\n\nAfter the examples, there will be some coding exercises for you to practice.", "_____no_output_____" ], [ "### Import libraries and functions\nFor this exercise, we can make use of the user-defined functions we made in the previous exercise to read can write raster data. \n\n*First, run the code cell below to import all of them.*", "_____no_output_____" ] ], [ [ "import numpy as np\nimport gdal\nimport osr\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport glob\nimport ogr\nimport datetime\n\ndef GetGeoInfo(fh, subdataset = 0):\n \"\"\"\n Substract metadata from a geotiff, HDF4 or netCDF file.\n \n Parameters\n ----------\n fh : str\n Filehandle to file to be scrutinized.\n subdataset : int, optional\n Layer to be used in case of HDF4 or netCDF format, default is 0.\n \n Returns\n -------\n driver : str\n Driver of the fh.\n NDV : float\n No-data-value of the fh.\n xsize : int\n Amount of pixels in x direction.\n ysize : int\n Amount of pixels in y direction.\n GeoT : list\n List with geotransform values.\n Projection : str\n Projection of fh.\n \"\"\"\n SourceDS = gdal.Open(fh, gdal.GA_ReadOnly)\n Type = SourceDS.GetDriver().ShortName\n if Type == 'HDF4' or Type == 'netCDF':\n SourceDS = gdal.Open(SourceDS.GetSubDatasets()[subdataset][0])\n NDV = SourceDS.GetRasterBand(1).GetNoDataValue()\n xsize = SourceDS.RasterXSize\n ysize = SourceDS.RasterYSize\n GeoT = SourceDS.GetGeoTransform()\n Projection = osr.SpatialReference()\n Projection.ImportFromWkt(SourceDS.GetProjectionRef())\n driver = gdal.GetDriverByName(Type)\n return driver, NDV, xsize, ysize, GeoT, Projection\n\ndef OpenAsArray(fh, bandnumber = 1, dtype = 'float32', nan_values = False):\n \"\"\"\n Open a map as an numpy array. \n \n Parameters\n ----------\n fh: str\n Filehandle to map to open.\n bandnumber : int, optional \n Band or layer to open as array, default is 1.\n dtype : str, optional\n Datatype of output array, default is 'float32'.\n nan_values : boolean, optional\n Convert he no-data-values into np.nan values, note that dtype needs to\n be a float if True. Default is False.\n \n Returns\n -------\n Array : ndarray\n Array with the pixel values.\n \"\"\"\n datatypes = {\"uint8\": np.uint8, \"int8\": np.int8, \"uint16\": np.uint16,\n \"int16\": np.int16, \"Int16\": np.int16, \"uint32\": np.uint32,\n \"int32\": np.int32, \"float32\": np.float32, \"float64\": np.float64, \n \"complex64\": np.complex64, \"complex128\": np.complex128,\n \"Int32\": np.int32, \"Float32\": np.float32, \"Float64\": np.float64, \n \"Complex64\": np.complex64, \"Complex128\": np.complex128,}\n DataSet = gdal.Open(fh, gdal.GA_ReadOnly)\n Type = DataSet.GetDriver().ShortName\n if Type == 'HDF4':\n Subdataset = gdal.Open(DataSet.GetSubDatasets()[bandnumber][0])\n NDV = int(Subdataset.GetMetadata()['_FillValue'])\n else:\n Subdataset = DataSet.GetRasterBand(bandnumber)\n NDV = Subdataset.GetNoDataValue()\n Array = Subdataset.ReadAsArray().astype(datatypes[dtype])\n if nan_values:\n Array[Array == NDV] = np.nan\n return Array\n\ndef CreateGeoTiff(fh, Array, driver, NDV, xsize, ysize, GeoT, Projection, explicit = True, compress = None):\n \"\"\"\n Creates a geotiff from a numpy array.\n \n Parameters\n ----------\n fh : str\n Filehandle for output.\n Array: ndarray\n Array to convert to geotiff.\n driver : str\n Driver of the fh.\n NDV : float\n No-data-value of the fh.\n xsize : int\n Amount of pixels in x direction.\n ysize : int\n Amount of pixels in y direction.\n GeoT : list\n List with geotransform values.\n Projection : str\n Projection of fh. \n \"\"\"\n datatypes = {\"uint8\": 1, \"int8\": 1, \"uint16\": 2, \"int16\": 3, \"Int16\": 3, \"uint32\": 4,\n \"int32\": 5, \"float32\": 6, \"float64\": 7, \"complex64\": 10, \"complex128\": 11,\n \"Int32\": 5, \"Float32\": 6, \"Float64\": 7, \"Complex64\": 10, \"Complex128\": 11,}\n if compress != None:\n DataSet = driver.Create(fh,xsize,ysize,1,datatypes[Array.dtype.name], ['COMPRESS={0}'.format(compress)])\n else:\n DataSet = driver.Create(fh,xsize,ysize,1,datatypes[Array.dtype.name])\n if NDV is None:\n NDV = -9999\n if explicit:\n Array[np.isnan(Array)] = NDV\n DataSet.GetRasterBand(1).SetNoDataValue(NDV)\n DataSet.SetGeoTransform(GeoT)\n DataSet.SetProjection(Projection.ExportToWkt())\n DataSet.GetRasterBand(1).WriteArray(Array)\n DataSet = None\n if \"nt\" not in Array.dtype.name:\n Array[Array == NDV] = np.nan\n\n\ndef MatchProjResNDV(target_file, source_fhs, output_dir, resample = 'near', \n dtype = 'float32', scale = None, ndv_to_zero = False):\n \"\"\"\n Matches the projection, resolution and no-data-value of a list of target-files\n with a source-file and saves the new maps in output_dir.\n \n Parameters\n ----------\n target_file : str\n The file to match the projection, resolution and ndv with.\n source_fhs : list\n The files to be reprojected.\n output_dir : str\n Folder to store the output.\n resample : str, optional\n Resampling method to use, default is 'near' (nearest neighbour).\n dtype : str, optional\n Datatype of output, default is 'float32'.\n scale : int, optional\n Multiple all maps with this value, default is None.\n \n Returns\n -------\n output_files : ndarray \n Filehandles of the created files.\n \"\"\"\n dst_info=gdal.Info(gdal.Open(target_file),format='json')\n output_files = np.array([])\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n for source_file in source_fhs:\n folder, fn = os.path.split(source_file)\n src_info=gdal.Info(gdal.Open(source_file),format='json')\n output_file = os.path.join(output_dir, fn)\n gdal.Warp(output_file,source_file,format='GTiff',\n srcSRS=src_info['coordinateSystem']['wkt'],\n dstSRS=dst_info['coordinateSystem']['wkt'],\n srcNodata=src_info['bands'][0]['noDataValue'],\n dstNodata=dst_info['bands'][0]['noDataValue'],\n width=dst_info['size'][0],\n height=dst_info['size'][1],\n outputBounds=(dst_info['cornerCoordinates']['lowerLeft'][0],\n dst_info['cornerCoordinates']['lowerLeft'][1],\n dst_info['cornerCoordinates']['upperRight'][0],\n dst_info['cornerCoordinates']['upperRight'][1]),\n outputBoundsSRS=dst_info['coordinateSystem']['wkt'],\n resampleAlg=resample)\n output_files = np.append(output_files, output_file)\n if not np.any([scale == 1.0, scale == None, scale == 1]):\n driver, NDV, xsize, ysize, GeoT, Projection = GetGeoInfo(output_file)\n DATA = OpenAsArray(output_file, nan_values = True) * scale\n CreateGeoTiff(output_file, DATA, driver, NDV, xsize, ysize, GeoT, Projection)\n if ndv_to_zero:\n driver, NDV, xsize, ysize, GeoT, Projection = GetGeoInfo(output_file)\n DATA = OpenAsArray(output_file, nan_values = False)\n DATA[DATA == NDV] = 0.0\n CreateGeoTiff(output_file, DATA, driver, NDV, xsize, ysize, GeoT, Projection)\n return output_files\n\ndef CliptoShp(input_fhs,output_folder,shp_fh,NDV=-9999):\n \"\"\"\n Clip raster to boundary line of a shapefile\n \n Parameters\n ----------\n input_fhs : list\n The list of input raster files\n output_folder : str\n The path to folder where to save output rasters\n shp_fh : str\n Folder to store the output.\n NDV : float or int, optional\n No Data Value of output raster\n \n Returns\n -------\n output_fhs : list \n Filehandles of the created files.\n \"\"\"\n inDriver = ogr.GetDriverByName(\"ESRI Shapefile\")\n inDataSource = inDriver.Open(shp_fh, 1)\n inLayer = inDataSource.GetLayer() \n options = gdal.WarpOptions(cutlineDSName = shp_fh,\n cutlineLayer = inLayer.GetName(),\n cropToCutline = True, \n dstNodata=NDV\n )\n output_fhs=[]\n for input_fh in input_fhs:\n output_fh=os.path.join(output_folder,os.path.basename(input_fh))\n sourceds = gdal.Warp(output_fh, input_fh, options = options)\n output_fhs.append(output_fh)\n return output_fhs", "_____no_output_____" ] ], [ [ "## 1. Calculate the average value of ROI\n### Example\nIn order to calculate average precipitation in a Region of Interest (ROI) from a raster map (mm/month), we need to clip the raster map to cutline of the ROI shapefile. By doing this, we exclude all the pixels outside of the ROI. In this example, we will use the resulted rasters in exercise 3 of the previous [notebook](2_Preprocess_WaPOR_data.ipynb), which are precipitation maps clipped with Awash River Basin shapefile, which is our ROI.\n\nFirst, we will get the list of clipped precipitation raster files", "_____no_output_____" ] ], [ [ "P_folder=r\".\\data\\L1_PCP_M_clipped\" #input folder\n# Get list of files in folder:\nP_fhs=sorted(glob.glob(os.path.join(P_folder,'*.tif')))\nP_fhs", "_____no_output_____" ] ], [ [ "Now, we will first calculate the average precipitation in Awash River Basin of the first raster file in the list as an example. We can get the average Precipitation of the whole area by *numpy.nanmean* which means calculate the average excluding pixels with nan values.", "_____no_output_____" ] ], [ [ "in_fh=P_fhs[0] #get the first raster file in the list\nP=OpenAsArray(in_fh,nan_values=True) #open the raster as array\nplt.imshow(P)\nplt.show()\nAverage_P=np.nanmean(P) #get the mean values\nprint('Average Precipitation (mm/month): {0}'.format(Average_P))", "_____no_output_____" ] ], [ [ "To get values of all monthly Precipitation (P) maps and save the value in a Python *list* and plot average precipitation against time, we will loop over all the monthly P rasters and calculate average P and the date.\n\nWe can make use of the file name to get *datetime* index. Look at example below.", "_____no_output_____" ] ], [ [ "dates=[] \nmonths=[]\nyears=[]\nP_values=[]\nfor P_fh in P_fhs:\n filename=os.path.basename(P_fh) # get file name from filehandler string\n datestr=filename.split('.')[0].split('_')[-1] #get date string from file name\n dyear=int('20'+datestr[0:2]) #get year number from date string\n dmonth=int(datestr[2:4]) #get month number from date string\n dates.append(datetime.date(dyear,dmonth,1)) # create datetime object from year and month number\n months.append(dmonth) #append to months list\n years.append(dyear) # append to years list\n #Calculate value\n P=OpenAsArray(P_fh,nan_values=True) #open raster as numpy array \n Average_P=np.nanmean(P) # calculate average P\n P_values.append(Average_P) #append to P_values list", "_____no_output_____" ] ], [ [ "After extract monthly average value of the rasters, we can plot the **P_values** to see the results", "_____no_output_____" ] ], [ [ "plt.plot(P_values)\nplt.show()", "_____no_output_____" ] ], [ [ "We can decorate our graph with some extra code. For example, run the code below and see the output graph. You can try to customize the graph.", "_____no_output_____" ] ], [ [ "output_dir=r'.\\data'\nfig = plt.figure(figsize = (10,5))\nplt.clf() #clear plot\nplt.grid(b=True, which='Major', color='0.65',linestyle='--', zorder = 0) # Add Grid line\nax = plt.subplot(111)\nax.plot(dates, P_values, '-k') #Plot data as black line\nax.fill_between(dates, P_values, color = '#6bb8cc') #Fill line area with blue color\nax.set_xlabel('Time') #Add X axis title\nax.set_ylabel('Precipitation [mm/month]') #Add Y axis title\nax.set_title('Precipitation, Awash Basin') #Add Figure title\nfig.autofmt_xdate() #auto-format dates axis\nplt.savefig(os.path.join(output_dir, 'Precipitation_Awash_ts.png')) #save figure to output\nplt.show()", "C:\\Users\\ntr002\\Anaconda3\\envs\\waporocw\\lib\\site-packages\\ipykernel_launcher.py:5: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.\n \"\"\"\n" ] ], [ [ "## 2. Working with timeseries (pandas library)\n### Example\nThe lists created (*dates*, *months*, *years*, *P_values*) can be combined in a DataFrame object using *pandas.DataFrame*. This structure makes cleaning, transforming, manipulating and analyzing data easier. For example, the code below create a DataFrame from the list of dates and average Precipitation values.", "_____no_output_____" ] ], [ [ "P_df=pd.DataFrame({'date':dates,'month':months,'year':years,'value': P_values})\nP_df", "_____no_output_____" ] ], [ [ "For example, we can easily sum up precipitation of the monthly values into the yearly total precipitation using *groupby* of column *year* with method *sum*.", "_____no_output_____" ] ], [ [ "Year_total=P_df.groupby(['year']).sum()\nYear_total['value']", "_____no_output_____" ] ], [ [ "DataFrame columns can be converted to array and plotted easily. Below is the code to plot the total yearly precipitation. ", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize = (10,5))\nax2 = plt.subplot(111)\nax2.grid(b=True, which='Major', color='0.65',linestyle='--', zorder = 0) #Grid line\nax2.bar(Year_total.index, Year_total['value'].values, 0.8, color = '#6bb8cc')\nax2.set_xlabel('Time [Year]')\nax2.set_xticks(Year_total.index)\nax2.set_ylabel('Precipitation [mm/year]')\nax2.set_title('Yearly Total Precipitation, Awash')\nplt.savefig(os.path.join(output_dir, 'Precipitation_Awash_year.png'))\nplt.show()\nplt.close(fig)", "_____no_output_____" ] ], [ [ "To calculate and plot the mean Precipitation of the calendar months, we can *groupby* method, and use *mean* instead of *sum*: **P_df.groupby(['month']).mean()**", "_____no_output_____" ] ], [ [ "Month_avg=P_df.groupby(['month']).mean()\nMonth_avg['value']\nfig = plt.figure(figsize = (10,5))\n#subplot 1\nax1 = plt.subplot(111)\nax1.grid(b=True, which='Major', color='0.65',linestyle='--', zorder = 0) #Grid line\nax1.bar(Month_avg.index, Month_avg['value'].values, 0.8, color = '#6bb8cc')\nax1.set_xlabel('Time [month]')\nmonthname={1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}\nmonthslabel=monthname.values()\nax1.set_xticks(Month_avg.index)\nax1.set_xticklabels(monthslabel)\nax1.set_ylabel('Precipitation [mm/month]')\nax1.set_title('Monthly average Precipitation, Awash')\nplt.savefig(os.path.join(output_dir, 'Precipitation_Awash_month.png'))\nplt.show()\nplt.close(fig)", "_____no_output_____" ] ], [ [ "We can also save our dataframe as csv file using pandas.DataFrame method *to_csv* for later use in other analysis. ", "_____no_output_____" ] ], [ [ "Month_max=P_df.groupby(['month']).max()\nMonth_min=P_df.groupby(['month']).min()\nMonth_med=P_df.groupby(['month']).median()\nMonth_std=P_df.groupby(['month']).std()\n\nMonth_stat=pd.DataFrame({'month': Month_avg.index,'Mean':Month_avg['value'].values,\n 'Max':Month_max['value'].values, 'Min':Month_min['value'].values,\n 'Median':Month_med['value'].values,'Std':Month_std['value'].values})\nprint(Month_stat)\nMonth_stat.to_csv(r'.\\data\\P_month_stats.csv',sep=';')", " month Mean Max Min Median Std\n0 1 16.115124 25.643679 6.586569 16.115124 13.475411\n1 2 27.138358 46.456440 7.820275 27.138358 27.319894\n2 3 54.050253 75.082008 33.018497 54.050253 29.743394\n3 4 51.782978 67.536217 36.029739 51.782978 22.278444\n4 5 40.590412 60.426426 20.754398 40.590412 28.052360\n5 6 27.875678 30.349817 25.401539 27.875678 3.498961\n6 7 126.365967 141.499390 111.232544 126.365967 21.401892\n7 8 147.474548 171.910889 123.038208 147.474548 34.558204\n8 9 54.071995 69.839439 38.304550 54.071995 22.298534\n9 10 23.540389 42.717953 4.362825 23.540389 27.121171\n10 11 10.420251 12.142183 8.698319 10.420251 2.435179\n11 12 7.193530 10.138801 4.248259 7.193530 4.165242\n" ] ], [ [ "## 3. Raster calculation\n### Example: P - ET\nFirst, we need to get the file handler of the P and ET rasters of the same date that have been matched projection, size and resolution. We can make use of the time format in file name as below.", "_____no_output_____" ] ], [ [ "start_date='2009-01-01'\nend_date='2010-12-31'\ndates=pd.date_range(start_date,end_date,freq='M') #create a date range from start_date and end_date\n\nP_path=r'.\\data\\L1_PCP_M_clipped\\L1_PCP_{:2}{:02d}M.tif' #template string to format\nET_path=r'.\\data\\L1_AETI_M_clipped\\L1_AETI_{:2}{:02d}M.tif' #template string to format\n\ndate=dates[0] #get the first date in the date range\nprint(date)\nP_fh=P_path.format(str(date.year)[2:],date.month) #format filename using the selected date\nET_fh=ET_path.format(str(date.year)[2:],date.month) #format filename using the selected date\nprint(P_fh)\nprint(ET_fh)", "2009-01-31 00:00:00\n.\\data\\L1_PCP_M_clipped\\L1_PCP_0901M.tif\n.\\data\\L1_AETI_M_clipped\\L1_AETI_0901M.tif\n" ] ], [ [ "The difference between Precipitation and Total EvapoTranspiration (P-ET) of the pixel can indicate whether the pixel is sink or source of water. When P-ET>0, water is generated in the pixel area. When P-ET< 0, water is more depleted in the pixel area. For example, below is how we can calculate P-ET for one month (January 2009). Notice where P-ET is negative and positive.", "_____no_output_____" ] ], [ [ "P=OpenAsArray(P_fh,nan_values=True)\nET=OpenAsArray(ET_fh,nan_values=True)\nP_ET=P-ET\nplt.imshow(P_ET)\nplt.colorbar()\nplt.show()", "_____no_output_____" ] ], [ [ "We can use a for-loop to calculate P-ET maps for the month in 2009. The output files will be save in the folder [P-ET_M](data/P-ET_M)", "_____no_output_____" ] ], [ [ "output_folder=r'.\\data\\P-ET_M'\nif not os.path.exists(output_folder):\n os.makedirs(output_folder)\nfor date in dates:\n print(date)\n P_fh=P_path.format(str(date.year)[2:],date.month) #format filename using the selected date\n ET_fh=ET_path.format(str(date.year)[2:],date.month) #format filename using the selected date \n driver, NDV, xsize, ysize, GeoT, Projection=GetGeoInfo(P_fh)\n P=OpenAsArray(P_fh,nan_values=True)\n ET=OpenAsArray(ET_fh,nan_values=True)\n P_ET=P-ET\n filename='P-ET_{:2}{:02d}M.tif'.format(str(date.year)[2:],date.month)\n output_fh=os.path.join(output_folder,filename)\n print(output_fh)\n CreateGeoTiff(output_fh, P_ET, driver, NDV, xsize, ysize, GeoT, Projection)", "2009-01-31 00:00:00\n.\\data\\P-ET_M\\P-ET_0901M.tif\n2009-02-28 00:00:00\n.\\data\\P-ET_M\\P-ET_0902M.tif\n2009-03-31 00:00:00\n.\\data\\P-ET_M\\P-ET_0903M.tif\n2009-04-30 00:00:00\n.\\data\\P-ET_M\\P-ET_0904M.tif\n2009-05-31 00:00:00\n.\\data\\P-ET_M\\P-ET_0905M.tif\n2009-06-30 00:00:00\n.\\data\\P-ET_M\\P-ET_0906M.tif\n2009-07-31 00:00:00\n.\\data\\P-ET_M\\P-ET_0907M.tif\n2009-08-31 00:00:00\n.\\data\\P-ET_M\\P-ET_0908M.tif\n2009-09-30 00:00:00\n.\\data\\P-ET_M\\P-ET_0909M.tif\n2009-10-31 00:00:00\n.\\data\\P-ET_M\\P-ET_0910M.tif\n2009-11-30 00:00:00\n.\\data\\P-ET_M\\P-ET_0911M.tif\n2009-12-31 00:00:00\n.\\data\\P-ET_M\\P-ET_0912M.tif\n2010-01-31 00:00:00\n.\\data\\P-ET_M\\P-ET_1001M.tif\n2010-02-28 00:00:00\n.\\data\\P-ET_M\\P-ET_1002M.tif\n2010-03-31 00:00:00\n.\\data\\P-ET_M\\P-ET_1003M.tif\n2010-04-30 00:00:00\n.\\data\\P-ET_M\\P-ET_1004M.tif\n2010-05-31 00:00:00\n.\\data\\P-ET_M\\P-ET_1005M.tif\n2010-06-30 00:00:00\n.\\data\\P-ET_M\\P-ET_1006M.tif\n2010-07-31 00:00:00\n.\\data\\P-ET_M\\P-ET_1007M.tif\n2010-08-31 00:00:00\n.\\data\\P-ET_M\\P-ET_1008M.tif\n2010-09-30 00:00:00\n.\\data\\P-ET_M\\P-ET_1009M.tif\n2010-10-31 00:00:00\n.\\data\\P-ET_M\\P-ET_1010M.tif\n2010-11-30 00:00:00\n.\\data\\P-ET_M\\P-ET_1011M.tif\n2010-12-31 00:00:00\n.\\data\\P-ET_M\\P-ET_1012M.tif\n" ] ], [ [ "## Exercise 1\nFollow the example of how monthly average Precipitation was calculated in the examples, calculate and plot monthly P - ET of the year 2009 and 2010 in Awash Basin. ", "_____no_output_____" ] ], [ [ "'''Write your code here'''", "_____no_output_____" ] ], [ [ "## 4. Land-use analysis\n### Example:\nWe will first clip the WaPOR LCC rasters downloaded from [3 Bulk download WaPOR data](3_Bulk_download_WaPOR_data.ipynb) then get the list of unique Land Cover classes from WaPOR Land Cover Classification rasters.", "_____no_output_____" ] ], [ [ "shp_fh=r\".\\data\\Awash_shapefile.shp\"\nLCC_folder=r'.\\data\\WAPOR.v2_yearly_L1_LCC_A'\nLCC_fhs=sorted(glob.glob(os.path.join(LCC_folder,'*.tif'))) #get list of LCC rasters\noutput_folder=r'.\\data\\WAPOR.v2_yearly_L1_LCC_A_clipped' # New LCC folder\nif not os.path.exists(output_folder):\n os.makedirs(output_folder) #create new P folder\nLCC_fhs=CliptoShp(LCC_fhs,output_folder,shp_fh) #clip all LCC rasters to shapefile", "_____no_output_____" ] ], [ [ "We will open 1 LCC map as numpy array to get the unique values in map. These are the Land Cover Classification codes. For the description of these LCC codes, see the Land Cover Classification metadata on WaPOR catalog https://wapor.apps.fao.org/catalog/WAPOR_2/1/L1_LCC_A\n\n| code | Name | \n| :---------: |:-------------:| \n| 20 | Shrubland | \n| 30 | Grassland | \n| 41 | Cropland, rainfed | \n| 42 | Cropland, irrigated or under water management |\n| 43 | Cropland, fallow | \n| 50 | Built-up | \n| 60 | Bare / sparse vegetation | \n| 80 | Water bodies | \n| 112 | Tree cover: closed, evergreen broadleaved | \n| 114 | Tree cover: closed, deciduous broadleaved | \n| 116 | Tree cover: closed, unknown type | \n| 124 | Tree cover: open, deciduous broadleaved | \n| 126 | Tree cover: open, unknown type | ", "_____no_output_____" ] ], [ [ "LCC_fh=r\".\\data\\WAPOR.v2_yearly_L1_LCC_A_clipped\\L1_LCC_09.tif\"\nLCC=OpenAsArray(LCC_fh,nan_values=True)\nLCC_values=np.unique(LCC[~np.isnan(LCC)])\nLCC_codes=list(LCC_values)\nprint(LCC_codes)", "[20.0, 30.0, 41.0, 42.0, 43.0, 50.0, 60.0, 80.0, 90.0, 112.0, 114.0, 116.0, 124.0, 126.0]\n" ] ], [ [ "To calculate average ET of each land cover, we can mask the ET map where the LCC map values equal to each LCC code, then calculate **np.nanmean** of the masked array.\nFor example, to get ET value of water bodies (the LCC code is 80), we can use the steps below", "_____no_output_____" ] ], [ [ "code=80 #Water bodies\n\nmask=np.where(LCC==code,0,1)\nin_fh=r\".\\data\\L1_AETI_M_clipped\\L1_AETI_0901M.tif\"\nvar=OpenAsArray(in_fh,nan_values=True)\n\nimport numpy.ma as ma #import mask array module\nmasked_map=ma.masked_array(var,mask)\nplt.imshow(masked_map)\nplt.colorbar()\nplt.show()", "_____no_output_____" ] ], [ [ "After that, we can calculate average ET of a the water bodies land-use class using the masked array", "_____no_output_____" ] ], [ [ "average=np.nanmean(masked_map)\nprint('Landuse class {0} Average: {1}'.format(code,average))", "Landuse class 80 Average: 104.69696044921875\n" ] ], [ [ "Now, we can use a for-loop over the unique LCC codes to calculate average ET value of each LCC code.", "_____no_output_____" ] ], [ [ "averages=[]\nfor code in LCC_codes:\n mask=np.where(LCC==code,0,1)\n masked_map=ma.masked_array(var,mask)\n averages.append(np.nanmean(masked_map))\nLCC_avg=pd.DataFrame({'LCC code':LCC_codes,'Average Value': averages})\nLCC_avg", "_____no_output_____" ] ], [ [ "## Exercise 2:\n\nCalculate a table of average annual P-ET in Awash basin of all land-use class for the year 2009. \n\n**Hint**: The first step is to sum all the monthly P-ET rasters in the year 2009.", "_____no_output_____" ] ], [ [ "start_date='2009-01-01'\nend_date='2009-12-31'\ndates=pd.date_range(start_date,end_date,freq='M') #create a date range from start_date and end_date\nPmET_path=r'.\\data\\P-ET_M\\P-ET_{:2}{:02d}M.tif'\nsameple_file=PmET_path.format(str(dates[0].year)[2:],dates[0].month)\ndriver, NDV, xsize, ysize, GeoT, Projection=GetGeoInfo(sameple_file)\n\nSumArray=np.zeros((ysize,xsize)) #creates an array of zeros\nfor date in dates:\n print(date)\n PmET_fh=PmET_path.format(str(date.year)[2:],date.month) #format filename using the selected date\n SumArray+=OpenAsArray(PmET_fh,nan_values=True) #cumulatively saves each array of monthly averages to the array of zeros\n\noutput_fh=os.path.join('.\\data\\P-ET_2009.tif') #name of the output file\nCreateGeoTiff(output_fh, SumArray, driver, NDV, xsize, ysize, GeoT, Projection) #creates a geotiff from SumArray\nplt.imshow(SumArray)\nplt.colorbar()\nplt.show()", "2009-01-31 00:00:00\n2009-02-28 00:00:00\n2009-03-31 00:00:00\n2009-04-30 00:00:00\n2009-05-31 00:00:00\n2009-06-30 00:00:00\n2009-07-31 00:00:00\n2009-08-31 00:00:00\n2009-09-30 00:00:00\n2009-10-31 00:00:00\n2009-11-30 00:00:00\n2009-12-31 00:00:00\n" ] ], [ [ "**Hint**: Then, using the similar steps that were used to calculate average ET of each land cover class, calculate average P -ET per land cover class.\n\nCompare Evaporation in the main classes: Forest, Shrubland, Grassland, Water bodies, Bare land, Rainfed crops, Irrigated crops.", "_____no_output_____" ] ], [ [ "'''Write your code here'''", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfa95d3e5a7861100819b6e51995830013c0f03
65,241
ipynb
Jupyter Notebook
1_Data_Cleaning.ipynb
giumanto/Disaster-Detection
cd9d2424a4b93ea7ac254e84dccc61fab1a6f6ed
[ "MIT" ]
null
null
null
1_Data_Cleaning.ipynb
giumanto/Disaster-Detection
cd9d2424a4b93ea7ac254e84dccc61fab1a6f6ed
[ "MIT" ]
null
null
null
1_Data_Cleaning.ipynb
giumanto/Disaster-Detection
cd9d2424a4b93ea7ac254e84dccc61fab1a6f6ed
[ "MIT" ]
null
null
null
59.635283
210
0.537637
[ [ [ "### Import libraries", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport pickle\nimport re", "_____no_output_____" ] ], [ [ "### User settings", "_____no_output_____" ] ], [ [ "PATH = \"C:/Users/giuma/Dropbox/Web and Social media Analytics Project/\"\n\ndo_clean = False # flag for Text Cleaning process (set False when .pkl file can be imported)", "_____no_output_____" ] ], [ [ "### Import Kaggle Dataset\nSource: https://www.kaggle.com/c/nlp-getting-started", "_____no_output_____" ] ], [ [ "df_train = pd.read_csv(PATH + \"train.csv\")\ndf_test = pd.read_csv(PATH + \"test.csv\")\n\nprint(f\"Train: {df_train.shape}, memory usage: {df_train.memory_usage().sum() / 1024**2:0.3f} MB\")\nprint(f\"Test: {df_test.shape}, memory usage: {df_test.memory_usage().sum() / 1024**2:0.3f} MB\")", "Train: (7613, 5), memory usage: 0.291 MB\nTest: (3263, 4), memory usage: 0.100 MB\n" ] ], [ [ "### Mislabeled Tweets", "_____no_output_____" ] ], [ [ "df_mislabeled = df_train.groupby(['text']).nunique().sort_values(by='target', ascending=False)\ndf_mislabeled = df_mislabeled[df_mislabeled['target'] > 1]['target']\n\nprint(f\"There are {df_mislabeled.shape[0]} mislabeled tweets!!!\")", "There are 18 mislabeled tweets!!!\n" ], [ "# Visualize mislabeled tweets\n\ndf_mislabeled.index.tolist()", "_____no_output_____" ], [ "# Relabeling\n\ndf_train['target_relabeled'] = df_train['target'].copy() \n\ndf_train.loc[df_train['text'] == 'like for the music video I want some real action shit like burning buildings and police chases not some weak ben winston shit', 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == 'Hellfire is surrounded by desires so be careful and don‰Ûªt let your desires control you! #Afterlife', 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == 'To fight bioterrorism sir.', 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == '.POTUS #StrategicPatience is a strategy for #Genocide; refugees; IDP Internally displaced people; horror; etc. https://t.co/rqWuoy1fm4', 'target_relabeled'] = 1\ndf_train.loc[df_train['text'] == 'CLEARED:incident with injury:I-495 inner loop Exit 31 - MD 97/Georgia Ave Silver Spring', 'target_relabeled'] = 1\ndf_train.loc[df_train['text'] == '#foodscare #offers2go #NestleIndia slips into loss after #Magginoodle #ban unsafe and hazardous for #humanconsumption', 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == 'In #islam saving a person is equal in reward to saving all humans! Islam is the opposite of terrorism!', 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == 'Who is bringing the tornadoes and floods. Who is bringing the climate change. God is after America He is plaguing her\\n \\n#FARRAKHAN #QUOTE', 'target_relabeled'] = 1\ndf_train.loc[df_train['text'] == 'RT NotExplained: The only known image of infamous hijacker D.B. Cooper. http://t.co/JlzK2HdeTG', 'target_relabeled'] = 1\ndf_train.loc[df_train['text'] == \"Mmmmmm I'm burning.... I'm burning buildings I'm building.... Oooooohhhh oooh ooh...\", 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == \"wowo--=== 12000 Nigerian refugees repatriated from Cameroon\", 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == \"He came to a land which was engulfed in tribal war and turned it into a land of peace i.e. Madinah. #ProphetMuhammad #islam\", 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == \"Hellfire! We don‰Ûªt even want to think about it or mention it so let‰Ûªs not do anything that leads to it #islam!\", 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == \"The Prophet (peace be upon him) said 'Save yourself from Hellfire even if it is by giving half a date in charity.'\", 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == \"Caution: breathing may be hazardous to your health.\", 'target_relabeled'] = 1\ndf_train.loc[df_train['text'] == \"I Pledge Allegiance To The P.O.P.E. And The Burning Buildings of Epic City. ??????\", 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == \"#Allah describes piling up #wealth thinking it would last #forever as the description of the people of #Hellfire in Surah Humaza. #Reflect\", 'target_relabeled'] = 0\ndf_train.loc[df_train['text'] == \"that horrible sinking feeling when you‰Ûªve been at home on your phone for a while and you realise its been on 3G this whole time\", 'target_relabeled'] = 0", "_____no_output_____" ] ], [ [ "### Text cleaning", "_____no_output_____" ] ], [ [ "def text_cleaning(tweet): \n \n # Special characters\n tweet = re.sub(r\"\\x89Û_\", \"\", tweet)\n tweet = re.sub(r\"\\x89ÛÒ\", \"\", tweet)\n tweet = re.sub(r\"\\x89ÛÓ\", \"\", tweet)\n tweet = re.sub(r\"\\x89ÛÏWhen\", \"When\", tweet)\n tweet = re.sub(r\"\\x89ÛÏ\", \"\", tweet)\n tweet = re.sub(r\"China\\x89Ûªs\", \"China's\", tweet)\n tweet = re.sub(r\"let\\x89Ûªs\", \"let's\", tweet)\n tweet = re.sub(r\"\\x89Û÷\", \"\", tweet)\n tweet = re.sub(r\"\\x89Ûª\", \"\", tweet)\n tweet = re.sub(r\"\\x89Û\\x9d\", \"\", tweet)\n tweet = re.sub(r\"å_\", \"\", tweet)\n tweet = re.sub(r\"\\x89Û¢\", \"\", tweet)\n tweet = re.sub(r\"\\x89Û¢åÊ\", \"\", tweet)\n tweet = re.sub(r\"fromåÊwounds\", \"from wounds\", tweet)\n tweet = re.sub(r\"åÊ\", \"\", tweet)\n tweet = re.sub(r\"åÈ\", \"\", tweet)\n tweet = re.sub(r\"JapÌ_n\", \"Japan\", tweet) \n tweet = re.sub(r\"Ì©\", \"e\", tweet)\n tweet = re.sub(r\"å¨\", \"\", tweet)\n tweet = re.sub(r\"Surṳ\", \"Suruc\", tweet)\n tweet = re.sub(r\"åÇ\", \"\", tweet)\n tweet = re.sub(r\"å£3million\", \"3 million\", tweet)\n tweet = re.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Ûªt\", \"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Ûªm\", \"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Ûªve\", \"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Ûªs\", \"it is\", tweet)\n tweet = re.sub(r\"doesn\\x89Ûªt\", \"does not\", tweet)\n tweet = re.sub(r\"It\\x89Ûªs\", \"It is\", tweet)\n tweet = re.sub(r\"Here\\x89Ûªs\", \"Here is\", tweet)\n tweet = re.sub(r\"who's\", \"who is\", tweet)\n tweet = re.sub(r\"I\\x89Ûªve\", \"I have\", tweet)\n tweet = re.sub(r\"y'all\", \"you all\", tweet)\n tweet = re.sub(r\"can\\x89Ûªt\", \"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Ûªt\", \"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Ûªs\", \"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Ûªre\", \"You are\", tweet)\n tweet = re.sub(r\"where's\", \"where is\", tweet)\n tweet = re.sub(r\"Don\\x89Ûªt\", \"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Ûªt\", \"Cannot\", tweet)\n tweet = re.sub(r\"you\\x89Ûªll\", \"you will\", tweet)\n tweet = re.sub(r\"I\\x89Ûªd\", \"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å«t\", \"do not\", tweet) \n \n # Character entity references\n tweet = re.sub(r\"&gt;\", \">\", tweet)\n tweet = re.sub(r\"&lt;\", \"<\", tweet)\n tweet = re.sub(r\"&amp;\", \"&\", tweet)\n \n # Typos, slang and informal abbreviations\n tweet = re.sub(r\"w/e\", \"whatever\", tweet)\n tweet = re.sub(r\"w/\", \"with\", tweet)\n tweet = re.sub(r\"USAgov\", \"USA government\", tweet)\n tweet = re.sub(r\"recentlu\", \"recently\", tweet)\n tweet = re.sub(r\"Ph0tos\", \"Photos\", tweet)\n tweet = re.sub(r\"amirite\", \"am I right\", tweet)\n tweet = re.sub(r\"exp0sed\", \"exposed\", tweet)\n tweet = re.sub(r\"<3\", \"love\", tweet)\n tweet = re.sub(r\"amageddon\", \"armageddon\", tweet)\n tweet = re.sub(r\"Trfc\", \"Traffic\", tweet)\n tweet = re.sub(r\"8/5/2015\", \"2015-08-05\", tweet)\n tweet = re.sub(r\"WindStorm\", \"Wind Storm\", tweet)\n tweet = re.sub(r\"8/6/2015\", \"2015-08-06\", tweet)\n tweet = re.sub(r\"10:38PM\", \"10:38 PM\", tweet)\n tweet = re.sub(r\"10:30pm\", \"10:30 PM\", tweet)\n tweet = re.sub(r\"16yr\", \"16 year\", tweet)\n tweet = re.sub(r\"lmao\", \"laughing my ass off\", tweet) \n tweet = re.sub(r\"TRAUMATISED\", \"traumatized\", tweet)\n \n # Hashtags and usernames\n tweet = re.sub(r\"IranDeal\", \"Iran Deal\", tweet)\n tweet = re.sub(r\"ArianaGrande\", \"Ariana Grande\", tweet)\n tweet = re.sub(r\"camilacabello97\", \"camila cabello\", tweet) \n tweet = re.sub(r\"RondaRousey\", \"Ronda Rousey\", tweet) \n tweet = re.sub(r\"MTVHottest\", \"MTV Hottest\", tweet)\n tweet = re.sub(r\"TrapMusic\", \"Trap Music\", tweet)\n tweet = re.sub(r\"ProphetMuhammad\", \"Prophet Muhammad\", tweet)\n tweet = re.sub(r\"PantherAttack\", \"Panther Attack\", tweet)\n tweet = re.sub(r\"StrategicPatience\", \"Strategic Patience\", tweet)\n tweet = re.sub(r\"socialnews\", \"social news\", tweet)\n tweet = re.sub(r\"NASAHurricane\", \"NASA Hurricane\", tweet)\n tweet = re.sub(r\"onlinecommunities\", \"online communities\", tweet)\n tweet = re.sub(r\"humanconsumption\", \"human consumption\", tweet)\n tweet = re.sub(r\"Typhoon-Devastated\", \"Typhoon Devastated\", tweet)\n tweet = re.sub(r\"Meat-Loving\", \"Meat Loving\", tweet)\n tweet = re.sub(r\"facialabuse\", \"facial abuse\", tweet)\n tweet = re.sub(r\"LakeCounty\", \"Lake County\", tweet)\n tweet = re.sub(r\"BeingAuthor\", \"Being Author\", tweet)\n tweet = re.sub(r\"withheavenly\", \"with heavenly\", tweet)\n tweet = re.sub(r\"thankU\", \"thank you\", tweet)\n tweet = re.sub(r\"iTunesMusic\", \"iTunes Music\", tweet)\n tweet = re.sub(r\"OffensiveContent\", \"Offensive Content\", tweet)\n tweet = re.sub(r\"WorstSummerJob\", \"Worst Summer Job\", tweet)\n tweet = re.sub(r\"HarryBeCareful\", \"Harry Be Careful\", tweet)\n tweet = re.sub(r\"NASASolarSystem\", \"NASA Solar System\", tweet)\n tweet = re.sub(r\"animalrescue\", \"animal rescue\", tweet)\n tweet = re.sub(r\"KurtSchlichter\", \"Kurt Schlichter\", tweet)\n tweet = re.sub(r\"aRmageddon\", \"armageddon\", tweet)\n tweet = re.sub(r\"Throwingknifes\", \"Throwing knives\", tweet)\n tweet = re.sub(r\"GodsLove\", \"God's Love\", tweet)\n tweet = re.sub(r\"bookboost\", \"book boost\", tweet)\n tweet = re.sub(r\"ibooklove\", \"I book love\", tweet)\n tweet = re.sub(r\"NestleIndia\", \"Nestle India\", tweet)\n tweet = re.sub(r\"realDonaldTrump\", \"Donald Trump\", tweet)\n tweet = re.sub(r\"DavidVonderhaar\", \"David Vonderhaar\", tweet)\n tweet = re.sub(r\"CecilTheLion\", \"Cecil The Lion\", tweet)\n tweet = re.sub(r\"weathernetwork\", \"weather network\", tweet)\n tweet = re.sub(r\"withBioterrorism&use\", \"with Bioterrorism & use\", tweet)\n tweet = re.sub(r\"Hostage&2\", \"Hostage & 2\", tweet)\n tweet = re.sub(r\"GOPDebate\", \"GOP Debate\", tweet)\n tweet = re.sub(r\"RickPerry\", \"Rick Perry\", tweet)\n tweet = re.sub(r\"frontpage\", \"front page\", tweet)\n tweet = re.sub(r\"NewsInTweets\", \"News In Tweets\", tweet)\n tweet = re.sub(r\"ViralSpell\", \"Viral Spell\", tweet)\n tweet = re.sub(r\"til_now\", \"until now\", tweet)\n tweet = re.sub(r\"volcanoinRussia\", \"volcano in Russia\", tweet)\n tweet = re.sub(r\"ZippedNews\", \"Zipped News\", tweet)\n tweet = re.sub(r\"MicheleBachman\", \"Michele Bachman\", tweet)\n tweet = re.sub(r\"53inch\", \"53 inch\", tweet)\n tweet = re.sub(r\"KerrickTrial\", \"Kerrick Trial\", tweet)\n tweet = re.sub(r\"abstorm\", \"Alberta Storm\", tweet)\n tweet = re.sub(r\"Beyhive\", \"Beyonce hive\", tweet)\n tweet = re.sub(r\"IDFire\", \"Idaho Fire\", tweet)\n tweet = re.sub(r\"DETECTADO\", \"Detected\", tweet)\n tweet = re.sub(r\"RockyFire\", \"Rocky Fire\", tweet)\n tweet = re.sub(r\"Listen/Buy\", \"Listen / Buy\", tweet)\n tweet = re.sub(r\"NickCannon\", \"Nick Cannon\", tweet)\n tweet = re.sub(r\"FaroeIslands\", \"Faroe Islands\", tweet)\n tweet = re.sub(r\"yycstorm\", \"Calgary Storm\", tweet)\n tweet = re.sub(r\"IDPs:\", \"Internally Displaced People :\", tweet)\n tweet = re.sub(r\"ArtistsUnited\", \"Artists United\", tweet)\n tweet = re.sub(r\"ClaytonBryant\", \"Clayton Bryant\", tweet)\n tweet = re.sub(r\"jimmyfallon\", \"jimmy fallon\", tweet)\n tweet = re.sub(r\"justinbieber\", \"justin bieber\", tweet) \n tweet = re.sub(r\"UTC2015\", \"UTC 2015\", tweet)\n tweet = re.sub(r\"Time2015\", \"Time 2015\", tweet)\n tweet = re.sub(r\"djicemoon\", \"dj icemoon\", tweet)\n tweet = re.sub(r\"LivingSafely\", \"Living Safely\", tweet)\n tweet = re.sub(r\"FIFA16\", \"Fifa 2016\", tweet)\n tweet = re.sub(r\"thisiswhywecanthavenicethings\", \"this is why we cannot have nice things\", tweet)\n tweet = re.sub(r\"bbcnews\", \"bbc news\", tweet)\n tweet = re.sub(r\"UndergroundRailraod\", \"Underground Railraod\", tweet)\n tweet = re.sub(r\"c4news\", \"c4 news\", tweet)\n tweet = re.sub(r\"OBLITERATION\", \"obliteration\", tweet)\n tweet = re.sub(r\"MUDSLIDE\", \"mudslide\", tweet)\n tweet = re.sub(r\"NoSurrender\", \"No Surrender\", tweet)\n tweet = re.sub(r\"NotExplained\", \"Not Explained\", tweet)\n tweet = re.sub(r\"greatbritishbakeoff\", \"great british bake off\", tweet)\n tweet = re.sub(r\"LondonFire\", \"London Fire\", tweet)\n tweet = re.sub(r\"KOTAWeather\", \"KOTA Weather\", tweet)\n tweet = re.sub(r\"LuchaUnderground\", \"Lucha Underground\", tweet)\n tweet = re.sub(r\"KOIN6News\", \"KOIN 6 News\", tweet)\n tweet = re.sub(r\"LiveOnK2\", \"Live On K2\", tweet)\n tweet = re.sub(r\"9NewsGoldCoast\", \"9 News Gold Coast\", tweet)\n tweet = re.sub(r\"nikeplus\", \"nike plus\", tweet)\n tweet = re.sub(r\"david_cameron\", \"David Cameron\", tweet)\n tweet = re.sub(r\"peterjukes\", \"Peter Jukes\", tweet)\n tweet = re.sub(r\"JamesMelville\", \"James Melville\", tweet)\n tweet = re.sub(r\"megynkelly\", \"Megyn Kelly\", tweet)\n tweet = re.sub(r\"cnewslive\", \"C News Live\", tweet)\n tweet = re.sub(r\"JamaicaObserver\", \"Jamaica Observer\", tweet)\n tweet = re.sub(r\"TweetLikeItsSeptember11th2001\", \"Tweet like it is september 11th 2001\", tweet)\n tweet = re.sub(r\"cbplawyers\", \"cbp lawyers\", tweet)\n tweet = re.sub(r\"fewmoretweets\", \"few more tweets\", tweet)\n tweet = re.sub(r\"BlackLivesMatter\", \"Black Lives Matter\", tweet)\n tweet = re.sub(r\"cjoyner\", \"Chris Joyner\", tweet)\n tweet = re.sub(r\"ENGvAUS\", \"England vs Australia\", tweet)\n tweet = re.sub(r\"ScottWalker\", \"Scott Walker\", tweet)\n tweet = re.sub(r\"MikeParrActor\", \"Michael Parr\", tweet)\n tweet = re.sub(r\"4PlayThursdays\", \"Foreplay Thursdays\", tweet)\n tweet = re.sub(r\"TGF2015\", \"Tontitown Grape Festival\", tweet)\n tweet = re.sub(r\"realmandyrain\", \"Mandy Rain\", tweet)\n tweet = re.sub(r\"GraysonDolan\", \"Grayson Dolan\", tweet)\n tweet = re.sub(r\"ApolloBrown\", \"Apollo Brown\", tweet)\n tweet = re.sub(r\"saddlebrooke\", \"Saddlebrooke\", tweet)\n tweet = re.sub(r\"TontitownGrape\", \"Tontitown Grape\", tweet)\n tweet = re.sub(r\"AbbsWinston\", \"Abbs Winston\", tweet)\n tweet = re.sub(r\"ShaunKing\", \"Shaun King\", tweet)\n tweet = re.sub(r\"MeekMill\", \"Meek Mill\", tweet)\n tweet = re.sub(r\"TornadoGiveaway\", \"Tornado Giveaway\", tweet)\n tweet = re.sub(r\"GRupdates\", \"GR updates\", tweet)\n tweet = re.sub(r\"SouthDowns\", \"South Downs\", tweet)\n tweet = re.sub(r\"braininjury\", \"brain injury\", tweet)\n tweet = re.sub(r\"auspol\", \"Australian politics\", tweet)\n tweet = re.sub(r\"PlannedParenthood\", \"Planned Parenthood\", tweet)\n tweet = re.sub(r\"calgaryweather\", \"Calgary Weather\", tweet)\n tweet = re.sub(r\"weallheartonedirection\", \"we all heart one direction\", tweet)\n tweet = re.sub(r\"edsheeran\", \"Ed Sheeran\", tweet)\n tweet = re.sub(r\"TrueHeroes\", \"True Heroes\", tweet)\n tweet = re.sub(r\"S3XLEAK\", \"sex leak\", tweet)\n tweet = re.sub(r\"ComplexMag\", \"Complex Magazine\", tweet)\n tweet = re.sub(r\"TheAdvocateMag\", \"The Advocate Magazine\", tweet)\n tweet = re.sub(r\"CityofCalgary\", \"City of Calgary\", tweet)\n tweet = re.sub(r\"EbolaOutbreak\", \"Ebola Outbreak\", tweet)\n tweet = re.sub(r\"SummerFate\", \"Summer Fate\", tweet)\n tweet = re.sub(r\"RAmag\", \"Royal Academy Magazine\", tweet)\n tweet = re.sub(r\"offers2go\", \"offers to go\", tweet)\n tweet = re.sub(r\"foodscare\", \"food scare\", tweet)\n tweet = re.sub(r\"MNPDNashville\", \"Metropolitan Nashville Police Department\", tweet)\n tweet = re.sub(r\"TfLBusAlerts\", \"TfL Bus Alerts\", tweet)\n tweet = re.sub(r\"GamerGate\", \"Gamer Gate\", tweet)\n tweet = re.sub(r\"IHHen\", \"Humanitarian Relief\", tweet)\n tweet = re.sub(r\"spinningbot\", \"spinning bot\", tweet)\n tweet = re.sub(r\"ModiMinistry\", \"Modi Ministry\", tweet)\n tweet = re.sub(r\"TAXIWAYS\", \"taxi ways\", tweet)\n tweet = re.sub(r\"Calum5SOS\", \"Calum Hood\", tweet)\n tweet = re.sub(r\"po_st\", \"po.st\", tweet)\n tweet = re.sub(r\"scoopit\", \"scoop.it\", tweet)\n tweet = re.sub(r\"UltimaLucha\", \"Ultima Lucha\", tweet)\n tweet = re.sub(r\"JonathanFerrell\", \"Jonathan Ferrell\", tweet)\n tweet = re.sub(r\"aria_ahrary\", \"Aria Ahrary\", tweet)\n tweet = re.sub(r\"rapidcity\", \"Rapid City\", tweet)\n tweet = re.sub(r\"OutBid\", \"outbid\", tweet)\n tweet = re.sub(r\"lavenderpoetrycafe\", \"lavender poetry cafe\", tweet)\n tweet = re.sub(r\"EudryLantiqua\", \"Eudry Lantiqua\", tweet)\n tweet = re.sub(r\"15PM\", \"15 PM\", tweet)\n tweet = re.sub(r\"OriginalFunko\", \"Funko\", tweet)\n tweet = re.sub(r\"rightwaystan\", \"Richard Tan\", tweet)\n tweet = re.sub(r\"CindyNoonan\", \"Cindy Noonan\", tweet)\n tweet = re.sub(r\"RT_America\", \"RT America\", tweet)\n tweet = re.sub(r\"narendramodi\", \"Narendra Modi\", tweet)\n tweet = re.sub(r\"BakeOffFriends\", \"Bake Off Friends\", tweet)\n tweet = re.sub(r\"TeamHendrick\", \"Hendrick Motorsports\", tweet)\n tweet = re.sub(r\"alexbelloli\", \"Alex Belloli\", tweet)\n tweet = re.sub(r\"itsjustinstuart\", \"Justin Stuart\", tweet)\n tweet = re.sub(r\"gunsense\", \"gun sense\", tweet)\n tweet = re.sub(r\"DebateQuestionsWeWantToHear\", \"debate questions we want to hear\", tweet)\n tweet = re.sub(r\"RoyalCarribean\", \"Royal Carribean\", tweet)\n tweet = re.sub(r\"samanthaturne19\", \"Samantha Turner\", tweet)\n tweet = re.sub(r\"JonVoyage\", \"Jon Stewart\", tweet)\n tweet = re.sub(r\"renew911health\", \"renew 911 health\", tweet)\n tweet = re.sub(r\"SuryaRay\", \"Surya Ray\", tweet)\n tweet = re.sub(r\"pattonoswalt\", \"Patton Oswalt\", tweet)\n tweet = re.sub(r\"minhazmerchant\", \"Minhaz Merchant\", tweet)\n tweet = re.sub(r\"TLVFaces\", \"Israel Diaspora Coalition\", tweet)\n tweet = re.sub(r\"pmarca\", \"Marc Andreessen\", tweet)\n tweet = re.sub(r\"pdx911\", \"Portland Police\", tweet)\n tweet = re.sub(r\"jamaicaplain\", \"Jamaica Plain\", tweet)\n tweet = re.sub(r\"Japton\", \"Arkansas\", tweet)\n tweet = re.sub(r\"RouteComplex\", \"Route Complex\", tweet)\n tweet = re.sub(r\"INSubcontinent\", \"Indian Subcontinent\", tweet)\n tweet = re.sub(r\"NJTurnpike\", \"New Jersey Turnpike\", tweet)\n tweet = re.sub(r\"Politifiact\", \"PolitiFact\", tweet)\n tweet = re.sub(r\"Hiroshima70\", \"Hiroshima\", tweet)\n tweet = re.sub(r\"GMMBC\", \"Greater Mt Moriah Baptist Church\", tweet)\n tweet = re.sub(r\"versethe\", \"verse the\", tweet)\n tweet = re.sub(r\"TubeStrike\", \"Tube Strike\", tweet)\n tweet = re.sub(r\"MissionHills\", \"Mission Hills\", tweet)\n tweet = re.sub(r\"ProtectDenaliWolves\", \"Protect Denali Wolves\", tweet)\n tweet = re.sub(r\"NANKANA\", \"Nankana\", tweet)\n tweet = re.sub(r\"SAHIB\", \"Sahib\", tweet)\n tweet = re.sub(r\"PAKPATTAN\", \"Pakpattan\", tweet)\n tweet = re.sub(r\"Newz_Sacramento\", \"News Sacramento\", tweet)\n tweet = re.sub(r\"gofundme\", \"go fund me\", tweet)\n tweet = re.sub(r\"pmharper\", \"Stephen Harper\", tweet)\n tweet = re.sub(r\"IvanBerroa\", \"Ivan Berroa\", tweet)\n tweet = re.sub(r\"LosDelSonido\", \"Los Del Sonido\", tweet)\n tweet = re.sub(r\"bancodeseries\", \"banco de series\", tweet)\n tweet = re.sub(r\"timkaine\", \"Tim Kaine\", tweet)\n tweet = re.sub(r\"IdentityTheft\", \"Identity Theft\", tweet)\n tweet = re.sub(r\"AllLivesMatter\", \"All Lives Matter\", tweet)\n tweet = re.sub(r\"mishacollins\", \"Misha Collins\", tweet)\n tweet = re.sub(r\"BillNeelyNBC\", \"Bill Neely\", tweet)\n tweet = re.sub(r\"BeClearOnCancer\", \"be clear on cancer\", tweet)\n tweet = re.sub(r\"Kowing\", \"Knowing\", tweet)\n tweet = re.sub(r\"ScreamQueens\", \"Scream Queens\", tweet)\n tweet = re.sub(r\"AskCharley\", \"Ask Charley\", tweet)\n tweet = re.sub(r\"BlizzHeroes\", \"Heroes of the Storm\", tweet)\n tweet = re.sub(r\"BradleyBrad47\", \"Bradley Brad\", tweet)\n tweet = re.sub(r\"HannaPH\", \"Typhoon Hanna\", tweet)\n tweet = re.sub(r\"meinlcymbals\", \"MEINL Cymbals\", tweet)\n tweet = re.sub(r\"Ptbo\", \"Peterborough\", tweet)\n tweet = re.sub(r\"cnnbrk\", \"CNN Breaking News\", tweet)\n tweet = re.sub(r\"IndianNews\", \"Indian News\", tweet)\n tweet = re.sub(r\"savebees\", \"save bees\", tweet)\n tweet = re.sub(r\"GreenHarvard\", \"Green Harvard\", tweet)\n tweet = re.sub(r\"StandwithPP\", \"Stand with planned parenthood\", tweet)\n tweet = re.sub(r\"hermancranston\", \"Herman Cranston\", tweet)\n tweet = re.sub(r\"WMUR9\", \"WMUR-TV\", tweet)\n tweet = re.sub(r\"RockBottomRadFM\", \"Rock Bottom Radio\", tweet)\n tweet = re.sub(r\"ameenshaikh3\", \"Ameen Shaikh\", tweet)\n tweet = re.sub(r\"ProSyn\", \"Project Syndicate\", tweet)\n tweet = re.sub(r\"Daesh\", \"ISIS\", tweet)\n tweet = re.sub(r\"s2g\", \"swear to god\", tweet)\n tweet = re.sub(r\"listenlive\", \"listen live\", tweet)\n tweet = re.sub(r\"CDCgov\", \"Centers for Disease Control and Prevention\", tweet)\n tweet = re.sub(r\"FoxNew\", \"Fox News\", tweet)\n tweet = re.sub(r\"CBSBigBrother\", \"Big Brother\", tweet)\n tweet = re.sub(r\"JulieDiCaro\", \"Julie DiCaro\", tweet)\n tweet = re.sub(r\"theadvocatemag\", \"The Advocate Magazine\", tweet)\n tweet = re.sub(r\"RohnertParkDPS\", \"Rohnert Park Police Department\", tweet)\n tweet = re.sub(r\"THISIZBWRIGHT\", \"Bonnie Wright\", tweet)\n tweet = re.sub(r\"Popularmmos\", \"Popular MMOs\", tweet)\n tweet = re.sub(r\"WildHorses\", \"Wild Horses\", tweet)\n tweet = re.sub(r\"FantasticFour\", \"Fantastic Four\", tweet)\n tweet = re.sub(r\"HORNDALE\", \"Horndale\", tweet)\n tweet = re.sub(r\"PINER\", \"Piner\", tweet)\n tweet = re.sub(r\"BathAndNorthEastSomerset\", \"Bath and North East Somerset\", tweet)\n tweet = re.sub(r\"thatswhatfriendsarefor\", \"that is what friends are for\", tweet)\n tweet = re.sub(r\"residualincome\", \"residual income\", tweet)\n tweet = re.sub(r\"YahooNewsDigest\", \"Yahoo News Digest\", tweet)\n tweet = re.sub(r\"MalaysiaAirlines\", \"Malaysia Airlines\", tweet)\n tweet = re.sub(r\"AmazonDeals\", \"Amazon Deals\", tweet)\n tweet = re.sub(r\"MissCharleyWebb\", \"Charley Webb\", tweet)\n tweet = re.sub(r\"shoalstraffic\", \"shoals traffic\", tweet)\n tweet = re.sub(r\"GeorgeFoster72\", \"George Foster\", tweet)\n tweet = re.sub(r\"pop2015\", \"pop 2015\", tweet)\n tweet = re.sub(r\"_PokemonCards_\", \"Pokemon Cards\", tweet)\n tweet = re.sub(r\"DianneG\", \"Dianne Gallagher\", tweet)\n tweet = re.sub(r\"KashmirConflict\", \"Kashmir Conflict\", tweet)\n tweet = re.sub(r\"BritishBakeOff\", \"British Bake Off\", tweet)\n tweet = re.sub(r\"FreeKashmir\", \"Free Kashmir\", tweet)\n tweet = re.sub(r\"mattmosley\", \"Matt Mosley\", tweet)\n tweet = re.sub(r\"BishopFred\", \"Bishop Fred\", tweet)\n tweet = re.sub(r\"EndConflict\", \"End Conflict\", tweet)\n tweet = re.sub(r\"EndOccupation\", \"End Occupation\", tweet)\n tweet = re.sub(r\"UNHEALED\", \"unhealed\", tweet)\n tweet = re.sub(r\"CharlesDagnall\", \"Charles Dagnall\", tweet)\n tweet = re.sub(r\"Latestnews\", \"Latest news\", tweet)\n tweet = re.sub(r\"KindleCountdown\", \"Kindle Countdown\", tweet)\n tweet = re.sub(r\"NoMoreHandouts\", \"No More Handouts\", tweet)\n tweet = re.sub(r\"datingtips\", \"dating tips\", tweet)\n tweet = re.sub(r\"charlesadler\", \"Charles Adler\", tweet)\n tweet = re.sub(r\"twia\", \"Texas Windstorm Insurance Association\", tweet)\n tweet = re.sub(r\"txlege\", \"Texas Legislature\", tweet)\n tweet = re.sub(r\"WindstormInsurer\", \"Windstorm Insurer\", tweet)\n tweet = re.sub(r\"Newss\", \"News\", tweet)\n tweet = re.sub(r\"hempoil\", \"hemp oil\", tweet)\n tweet = re.sub(r\"CommoditiesAre\", \"Commodities are\", tweet)\n tweet = re.sub(r\"tubestrike\", \"tube strike\", tweet)\n tweet = re.sub(r\"JoeNBC\", \"Joe Scarborough\", tweet)\n tweet = re.sub(r\"LiteraryCakes\", \"Literary Cakes\", tweet)\n tweet = re.sub(r\"TI5\", \"The International 5\", tweet)\n tweet = re.sub(r\"thehill\", \"the hill\", tweet)\n tweet = re.sub(r\"3others\", \"3 others\", tweet)\n tweet = re.sub(r\"stighefootball\", \"Sam Tighe\", tweet)\n tweet = re.sub(r\"whatstheimportantvideo\", \"what is the important video\", tweet)\n tweet = re.sub(r\"ClaudioMeloni\", \"Claudio Meloni\", tweet)\n tweet = re.sub(r\"DukeSkywalker\", \"Duke Skywalker\", tweet)\n tweet = re.sub(r\"carsonmwr\", \"Fort Carson\", tweet)\n tweet = re.sub(r\"offdishduty\", \"off dish duty\", tweet)\n tweet = re.sub(r\"andword\", \"and word\", tweet)\n tweet = re.sub(r\"rhodeisland\", \"Rhode Island\", tweet)\n tweet = re.sub(r\"easternoregon\", \"Eastern Oregon\", tweet)\n tweet = re.sub(r\"WAwildfire\", \"Washington Wildfire\", tweet)\n tweet = re.sub(r\"fingerrockfire\", \"Finger Rock Fire\", tweet)\n tweet = re.sub(r\"57am\", \"57 am\", tweet)\n tweet = re.sub(r\"fingerrockfire\", \"Finger Rock Fire\", tweet)\n tweet = re.sub(r\"JacobHoggard\", \"Jacob Hoggard\", tweet)\n tweet = re.sub(r\"newnewnew\", \"new new new\", tweet)\n tweet = re.sub(r\"under50\", \"under 50\", tweet)\n tweet = re.sub(r\"getitbeforeitsgone\", \"get it before it is gone\", tweet)\n tweet = re.sub(r\"freshoutofthebox\", \"fresh out of the box\", tweet)\n tweet = re.sub(r\"amwriting\", \"am writing\", tweet)\n tweet = re.sub(r\"Bokoharm\", \"Boko Haram\", tweet)\n tweet = re.sub(r\"Nowlike\", \"Now like\", tweet)\n tweet = re.sub(r\"seasonfrom\", \"season from\", tweet)\n tweet = re.sub(r\"epicente\", \"epicenter\", tweet)\n tweet = re.sub(r\"epicenterr\", \"epicenter\", tweet)\n tweet = re.sub(r\"sicklife\", \"sick life\", tweet)\n tweet = re.sub(r\"yycweather\", \"Calgary Weather\", tweet)\n tweet = re.sub(r\"calgarysun\", \"Calgary Sun\", tweet)\n tweet = re.sub(r\"approachng\", \"approaching\", tweet)\n tweet = re.sub(r\"evng\", \"evening\", tweet)\n tweet = re.sub(r\"Sumthng\", \"something\", tweet)\n tweet = re.sub(r\"EllenPompeo\", \"Ellen Pompeo\", tweet)\n tweet = re.sub(r\"shondarhimes\", \"Shonda Rhimes\", tweet)\n tweet = re.sub(r\"ABCNetwork\", \"ABC Network\", tweet)\n tweet = re.sub(r\"SushmaSwaraj\", \"Sushma Swaraj\", tweet)\n tweet = re.sub(r\"pray4japan\", \"Pray for Japan\", tweet)\n tweet = re.sub(r\"hope4japan\", \"Hope for Japan\", tweet)\n tweet = re.sub(r\"Illusionimagess\", \"Illusion images\", tweet)\n tweet = re.sub(r\"SummerUnderTheStars\", \"Summer Under The Stars\", tweet)\n tweet = re.sub(r\"ShallWeDance\", \"Shall We Dance\", tweet)\n tweet = re.sub(r\"TCMParty\", \"TCM Party\", tweet)\n tweet = re.sub(r\"marijuananews\", \"marijuana news\", tweet)\n tweet = re.sub(r\"onbeingwithKristaTippett\", \"on being with Krista Tippett\", tweet)\n tweet = re.sub(r\"Beingtweets\", \"Being tweets\", tweet)\n tweet = re.sub(r\"newauthors\", \"new authors\", tweet)\n tweet = re.sub(r\"remedyyyy\", \"remedy\", tweet)\n tweet = re.sub(r\"44PM\", \"44 PM\", tweet)\n tweet = re.sub(r\"HeadlinesApp\", \"Headlines App\", tweet)\n tweet = re.sub(r\"40PM\", \"40 PM\", tweet)\n tweet = re.sub(r\"myswc\", \"Severe Weather Center\", tweet)\n tweet = re.sub(r\"ithats\", \"that is\", tweet)\n tweet = re.sub(r\"icouldsitinthismomentforever\", \"I could sit in this moment forever\", tweet)\n tweet = re.sub(r\"FatLoss\", \"Fat Loss\", tweet)\n tweet = re.sub(r\"02PM\", \"02 PM\", tweet)\n tweet = re.sub(r\"MetroFmTalk\", \"Metro Fm Talk\", tweet)\n tweet = re.sub(r\"Bstrd\", \"bastard\", tweet)\n tweet = re.sub(r\"bldy\", \"bloody\", tweet)\n tweet = re.sub(r\"MetrofmTalk\", \"Metro Fm Talk\", tweet)\n tweet = re.sub(r\"terrorismturn\", \"terrorism turn\", tweet)\n tweet = re.sub(r\"BBCNewsAsia\", \"BBC News Asia\", tweet)\n tweet = re.sub(r\"BehindTheScenes\", \"Behind The Scenes\", tweet)\n tweet = re.sub(r\"GeorgeTakei\", \"George Takei\", tweet)\n tweet = re.sub(r\"WomensWeeklyMag\", \"Womens Weekly Magazine\", tweet)\n tweet = re.sub(r\"SurvivorsGuidetoEarth\", \"Survivors Guide to Earth\", tweet)\n tweet = re.sub(r\"incubusband\", \"incubus band\", tweet)\n tweet = re.sub(r\"Babypicturethis\", \"Baby picture this\", tweet)\n tweet = re.sub(r\"BombEffects\", \"Bomb Effects\", tweet)\n tweet = re.sub(r\"win10\", \"Windows 10\", tweet)\n tweet = re.sub(r\"idkidk\", \"I do not know I do not know\", tweet)\n tweet = re.sub(r\"TheWalkingDead\", \"The Walking Dead\", tweet)\n tweet = re.sub(r\"amyschumer\", \"Amy Schumer\", tweet)\n tweet = re.sub(r\"crewlist\", \"crew list\", tweet)\n tweet = re.sub(r\"Erdogans\", \"Erdogan\", tweet)\n tweet = re.sub(r\"BBCLive\", \"BBC Live\", tweet)\n tweet = re.sub(r\"TonyAbbottMHR\", \"Tony Abbott\", tweet)\n tweet = re.sub(r\"paulmyerscough\", \"Paul Myerscough\", tweet)\n tweet = re.sub(r\"georgegallagher\", \"George Gallagher\", tweet)\n tweet = re.sub(r\"JimmieJohnson\", \"Jimmie Johnson\", tweet)\n tweet = re.sub(r\"pctool\", \"pc tool\", tweet)\n tweet = re.sub(r\"DoingHashtagsRight\", \"Doing Hashtags Right\", tweet)\n tweet = re.sub(r\"ThrowbackThursday\", \"Throwback Thursday\", tweet)\n tweet = re.sub(r\"SnowBackSunday\", \"Snowback Sunday\", tweet)\n tweet = re.sub(r\"LakeEffect\", \"Lake Effect\", tweet)\n tweet = re.sub(r\"RTphotographyUK\", \"Richard Thomas Photography UK\", tweet)\n tweet = re.sub(r\"BigBang_CBS\", \"Big Bang CBS\", tweet)\n tweet = re.sub(r\"writerslife\", \"writers life\", tweet)\n tweet = re.sub(r\"NaturalBirth\", \"Natural Birth\", tweet)\n tweet = re.sub(r\"UnusualWords\", \"Unusual Words\", tweet)\n tweet = re.sub(r\"wizkhalifa\", \"Wiz Khalifa\", tweet)\n tweet = re.sub(r\"acreativedc\", \"a creative DC\", tweet)\n tweet = re.sub(r\"vscodc\", \"vsco DC\", tweet)\n tweet = re.sub(r\"VSCOcam\", \"vsco camera\", tweet)\n tweet = re.sub(r\"TheBEACHDC\", \"The beach DC\", tweet)\n tweet = re.sub(r\"buildingmuseum\", \"building museum\", tweet)\n tweet = re.sub(r\"WorldOil\", \"World Oil\", tweet)\n tweet = re.sub(r\"redwedding\", \"red wedding\", tweet)\n tweet = re.sub(r\"AmazingRaceCanada\", \"Amazing Race Canada\", tweet)\n tweet = re.sub(r\"WakeUpAmerica\", \"Wake Up America\", tweet)\n tweet = re.sub(r\"\\\\Allahuakbar\\\\\", \"Allahu Akbar\", tweet)\n tweet = re.sub(r\"bleased\", \"blessed\", tweet)\n tweet = re.sub(r\"nigeriantribune\", \"Nigerian Tribune\", tweet)\n tweet = re.sub(r\"HIDEO_KOJIMA_EN\", \"Hideo Kojima\", tweet)\n tweet = re.sub(r\"FusionFestival\", \"Fusion Festival\", tweet)\n tweet = re.sub(r\"50Mixed\", \"50 Mixed\", tweet)\n tweet = re.sub(r\"NoAgenda\", \"No Agenda\", tweet)\n tweet = re.sub(r\"WhiteGenocide\", \"White Genocide\", tweet)\n tweet = re.sub(r\"dirtylying\", \"dirty lying\", tweet)\n tweet = re.sub(r\"SyrianRefugees\", \"Syrian Refugees\", tweet)\n tweet = re.sub(r\"changetheworld\", \"change the world\", tweet)\n tweet = re.sub(r\"Ebolacase\", \"Ebola case\", tweet)\n tweet = re.sub(r\"mcgtech\", \"mcg technologies\", tweet)\n tweet = re.sub(r\"withweapons\", \"with weapons\", tweet)\n tweet = re.sub(r\"advancedwarfare\", \"advanced warfare\", tweet)\n tweet = re.sub(r\"letsFootball\", \"let us Football\", tweet)\n tweet = re.sub(r\"LateNiteMix\", \"late night mix\", tweet)\n tweet = re.sub(r\"PhilCollinsFeed\", \"Phil Collins\", tweet)\n tweet = re.sub(r\"RudyHavenstein\", \"Rudy Havenstein\", tweet)\n tweet = re.sub(r\"22PM\", \"22 PM\", tweet)\n tweet = re.sub(r\"54am\", \"54 AM\", tweet)\n tweet = re.sub(r\"38am\", \"38 AM\", tweet)\n tweet = re.sub(r\"OldFolkExplainStuff\", \"Old Folk Explain Stuff\", tweet)\n tweet = re.sub(r\"BlacklivesMatter\", \"Black Lives Matter\", tweet)\n tweet = re.sub(r\"InsaneLimits\", \"Insane Limits\", tweet)\n tweet = re.sub(r\"youcantsitwithus\", \"you cannot sit with us\", tweet)\n tweet = re.sub(r\"2k15\", \"2015\", tweet)\n tweet = re.sub(r\"TheIran\", \"Iran\", tweet)\n tweet = re.sub(r\"JimmyFallon\", \"Jimmy Fallon\", tweet)\n tweet = re.sub(r\"AlbertBrooks\", \"Albert Brooks\", tweet)\n tweet = re.sub(r\"defense_news\", \"defense news\", tweet)\n tweet = re.sub(r\"nuclearrcSA\", \"Nuclear Risk Control Self Assessment\", tweet)\n tweet = re.sub(r\"Auspol\", \"Australia Politics\", tweet)\n tweet = re.sub(r\"NuclearPower\", \"Nuclear Power\", tweet)\n tweet = re.sub(r\"WhiteTerrorism\", \"White Terrorism\", tweet)\n tweet = re.sub(r\"truthfrequencyradio\", \"Truth Frequency Radio\", tweet)\n tweet = re.sub(r\"ErasureIsNotEquality\", \"Erasure is not equality\", tweet)\n tweet = re.sub(r\"ProBonoNews\", \"Pro Bono News\", tweet)\n tweet = re.sub(r\"JakartaPost\", \"Jakarta Post\", tweet)\n tweet = re.sub(r\"toopainful\", \"too painful\", tweet)\n tweet = re.sub(r\"melindahaunton\", \"Melinda Haunton\", tweet)\n tweet = re.sub(r\"NoNukes\", \"No Nukes\", tweet)\n tweet = re.sub(r\"curryspcworld\", \"Currys PC World\", tweet)\n tweet = re.sub(r\"ineedcake\", \"I need cake\", tweet)\n tweet = re.sub(r\"blackforestgateau\", \"black forest gateau\", tweet)\n tweet = re.sub(r\"BBCOne\", \"BBC One\", tweet)\n tweet = re.sub(r\"AlexxPage\", \"Alex Page\", tweet)\n tweet = re.sub(r\"jonathanserrie\", \"Jonathan Serrie\", tweet)\n tweet = re.sub(r\"SocialJerkBlog\", \"Social Jerk Blog\", tweet)\n tweet = re.sub(r\"ChelseaVPeretti\", \"Chelsea Peretti\", tweet)\n tweet = re.sub(r\"irongiant\", \"iron giant\", tweet)\n tweet = re.sub(r\"RonFunches\", \"Ron Funches\", tweet)\n tweet = re.sub(r\"TimCook\", \"Tim Cook\", tweet)\n tweet = re.sub(r\"sebastianstanisaliveandwell\", \"Sebastian Stan is alive and well\", tweet)\n tweet = re.sub(r\"Madsummer\", \"Mad summer\", tweet)\n tweet = re.sub(r\"NowYouKnow\", \"Now you know\", tweet)\n tweet = re.sub(r\"concertphotography\", \"concert photography\", tweet)\n tweet = re.sub(r\"TomLandry\", \"Tom Landry\", tweet)\n tweet = re.sub(r\"showgirldayoff\", \"show girl day off\", tweet)\n tweet = re.sub(r\"Yougslavia\", \"Yugoslavia\", tweet)\n tweet = re.sub(r\"QuantumDataInformatics\", \"Quantum Data Informatics\", tweet)\n tweet = re.sub(r\"FromTheDesk\", \"From The Desk\", tweet)\n tweet = re.sub(r\"TheaterTrial\", \"Theater Trial\", tweet)\n tweet = re.sub(r\"CatoInstitute\", \"Cato Institute\", tweet)\n tweet = re.sub(r\"EmekaGift\", \"Emeka Gift\", tweet)\n tweet = re.sub(r\"LetsBe_Rational\", \"Let us be rational\", tweet)\n tweet = re.sub(r\"Cynicalreality\", \"Cynical reality\", tweet)\n tweet = re.sub(r\"FredOlsenCruise\", \"Fred Olsen Cruise\", tweet)\n tweet = re.sub(r\"NotSorry\", \"not sorry\", tweet)\n tweet = re.sub(r\"UseYourWords\", \"use your words\", tweet)\n tweet = re.sub(r\"WordoftheDay\", \"word of the day\", tweet)\n tweet = re.sub(r\"Dictionarycom\", \"Dictionary.com\", tweet)\n tweet = re.sub(r\"TheBrooklynLife\", \"The Brooklyn Life\", tweet)\n tweet = re.sub(r\"jokethey\", \"joke they\", tweet)\n tweet = re.sub(r\"nflweek1picks\", \"NFL week 1 picks\", tweet)\n tweet = re.sub(r\"uiseful\", \"useful\", tweet)\n tweet = re.sub(r\"JusticeDotOrg\", \"The American Association for Justice\", tweet)\n tweet = re.sub(r\"autoaccidents\", \"auto accidents\", tweet)\n tweet = re.sub(r\"SteveGursten\", \"Steve Gursten\", tweet)\n tweet = re.sub(r\"MichiganAutoLaw\", \"Michigan Auto Law\", tweet)\n tweet = re.sub(r\"birdgang\", \"bird gang\", tweet)\n tweet = re.sub(r\"nflnetwork\", \"NFL Network\", tweet)\n tweet = re.sub(r\"NYDNSports\", \"NY Daily News Sports\", tweet)\n tweet = re.sub(r\"RVacchianoNYDN\", \"Ralph Vacchiano NY Daily News\", tweet)\n tweet = re.sub(r\"EdmontonEsks\", \"Edmonton Eskimos\", tweet)\n tweet = re.sub(r\"david_brelsford\", \"David Brelsford\", tweet)\n tweet = re.sub(r\"TOI_India\", \"The Times of India\", tweet)\n tweet = re.sub(r\"hegot\", \"he got\", tweet)\n tweet = re.sub(r\"SkinsOn9\", \"Skins on 9\", tweet)\n tweet = re.sub(r\"sothathappened\", \"so that happened\", tweet)\n tweet = re.sub(r\"LCOutOfDoors\", \"LC Out Of Doors\", tweet)\n tweet = re.sub(r\"NationFirst\", \"Nation First\", tweet)\n tweet = re.sub(r\"IndiaToday\", \"India Today\", tweet)\n tweet = re.sub(r\"HLPS\", \"helps\", tweet)\n tweet = re.sub(r\"HOSTAGESTHROSW\", \"hostages throw\", tweet)\n tweet = re.sub(r\"SNCTIONS\", \"sanctions\", tweet)\n tweet = re.sub(r\"BidTime\", \"Bid Time\", tweet)\n tweet = re.sub(r\"crunchysensible\", \"crunchy sensible\", tweet)\n tweet = re.sub(r\"RandomActsOfRomance\", \"Random acts of romance\", tweet)\n tweet = re.sub(r\"MomentsAtHill\", \"Moments at hill\", tweet)\n tweet = re.sub(r\"eatshit\", \"eat shit\", tweet)\n tweet = re.sub(r\"liveleakfun\", \"live leak fun\", tweet)\n tweet = re.sub(r\"SahelNews\", \"Sahel News\", tweet)\n tweet = re.sub(r\"abc7newsbayarea\", \"ABC 7 News Bay Area\", tweet)\n tweet = re.sub(r\"facilitiesmanagement\", \"facilities management\", tweet)\n tweet = re.sub(r\"facilitydude\", \"facility dude\", tweet)\n tweet = re.sub(r\"CampLogistics\", \"Camp logistics\", tweet)\n tweet = re.sub(r\"alaskapublic\", \"Alaska public\", tweet)\n tweet = re.sub(r\"MarketResearch\", \"Market Research\", tweet)\n tweet = re.sub(r\"AccuracyEsports\", \"Accuracy Esports\", tweet)\n tweet = re.sub(r\"TheBodyShopAust\", \"The Body Shop Australia\", tweet)\n tweet = re.sub(r\"yychail\", \"Calgary hail\", tweet)\n tweet = re.sub(r\"yyctraffic\", \"Calgary traffic\", tweet)\n tweet = re.sub(r\"eliotschool\", \"eliot school\", tweet)\n tweet = re.sub(r\"TheBrokenCity\", \"The Broken City\", tweet)\n tweet = re.sub(r\"OldsFireDept\", \"Olds Fire Department\", tweet)\n tweet = re.sub(r\"RiverComplex\", \"River Complex\", tweet)\n tweet = re.sub(r\"fieldworksmells\", \"field work smells\", tweet)\n tweet = re.sub(r\"IranElection\", \"Iran Election\", tweet)\n tweet = re.sub(r\"glowng\", \"glowing\", tweet)\n tweet = re.sub(r\"kindlng\", \"kindling\", tweet)\n tweet = re.sub(r\"riggd\", \"rigged\", tweet)\n tweet = re.sub(r\"slownewsday\", \"slow news day\", tweet)\n tweet = re.sub(r\"MyanmarFlood\", \"Myanmar Flood\", tweet)\n tweet = re.sub(r\"abc7chicago\", \"ABC 7 Chicago\", tweet)\n tweet = re.sub(r\"copolitics\", \"Colorado Politics\", tweet)\n tweet = re.sub(r\"AdilGhumro\", \"Adil Ghumro\", tweet)\n tweet = re.sub(r\"netbots\", \"net bots\", tweet)\n tweet = re.sub(r\"byebyeroad\", \"bye bye road\", tweet)\n tweet = re.sub(r\"massiveflooding\", \"massive flooding\", tweet)\n tweet = re.sub(r\"EndofUS\", \"End of United States\", tweet)\n tweet = re.sub(r\"35PM\", \"35 PM\", tweet)\n tweet = re.sub(r\"greektheatrela\", \"Greek Theatre Los Angeles\", tweet)\n tweet = re.sub(r\"76mins\", \"76 minutes\", tweet)\n tweet = re.sub(r\"publicsafetyfirst\", \"public safety first\", tweet)\n tweet = re.sub(r\"livesmatter\", \"lives matter\", tweet)\n tweet = re.sub(r\"myhometown\", \"my hometown\", tweet)\n tweet = re.sub(r\"tankerfire\", \"tanker fire\", tweet)\n tweet = re.sub(r\"MEMORIALDAY\", \"memorial day\", tweet)\n tweet = re.sub(r\"MEMORIAL_DAY\", \"memorial day\", tweet)\n tweet = re.sub(r\"instaxbooty\", \"instagram booty\", tweet)\n tweet = re.sub(r\"Jerusalem_Post\", \"Jerusalem Post\", tweet)\n tweet = re.sub(r\"WayneRooney_INA\", \"Wayne Rooney\", tweet)\n tweet = re.sub(r\"VirtualReality\", \"Virtual Reality\", tweet)\n tweet = re.sub(r\"OculusRift\", \"Oculus Rift\", tweet)\n tweet = re.sub(r\"OwenJones84\", \"Owen Jones\", tweet)\n tweet = re.sub(r\"jeremycorbyn\", \"Jeremy Corbyn\", tweet)\n tweet = re.sub(r\"paulrogers002\", \"Paul Rogers\", tweet)\n tweet = re.sub(r\"mortalkombatx\", \"Mortal Kombat X\", tweet)\n tweet = re.sub(r\"mortalkombat\", \"Mortal Kombat\", tweet)\n tweet = re.sub(r\"FilipeCoelho92\", \"Filipe Coelho\", tweet)\n tweet = re.sub(r\"OnlyQuakeNews\", \"Only Quake News\", tweet)\n tweet = re.sub(r\"kostumes\", \"costumes\", tweet)\n tweet = re.sub(r\"YEEESSSS\", \"yes\", tweet)\n tweet = re.sub(r\"ToshikazuKatayama\", \"Toshikazu Katayama\", tweet)\n tweet = re.sub(r\"IntlDevelopment\", \"Intl Development\", tweet)\n tweet = re.sub(r\"ExtremeWeather\", \"Extreme Weather\", tweet)\n tweet = re.sub(r\"WereNotGruberVoters\", \"We are not gruber voters\", tweet)\n tweet = re.sub(r\"NewsThousands\", \"News Thousands\", tweet)\n tweet = re.sub(r\"EdmundAdamus\", \"Edmund Adamus\", tweet)\n tweet = re.sub(r\"EyewitnessWV\", \"Eye witness WV\", tweet)\n tweet = re.sub(r\"PhiladelphiaMuseu\", \"Philadelphia Museum\", tweet)\n tweet = re.sub(r\"DublinComicCon\", \"Dublin Comic Con\", tweet)\n tweet = re.sub(r\"NicholasBrendon\", \"Nicholas Brendon\", tweet)\n tweet = re.sub(r\"Alltheway80s\", \"All the way 80s\", tweet)\n tweet = re.sub(r\"FromTheField\", \"From the field\", tweet)\n tweet = re.sub(r\"NorthIowa\", \"North Iowa\", tweet)\n tweet = re.sub(r\"WillowFire\", \"Willow Fire\", tweet)\n tweet = re.sub(r\"MadRiverComplex\", \"Mad River Complex\", tweet)\n tweet = re.sub(r\"feelingmanly\", \"feeling manly\", tweet)\n tweet = re.sub(r\"stillnotoverit\", \"still not over it\", tweet)\n tweet = re.sub(r\"FortitudeValley\", \"Fortitude Valley\", tweet)\n tweet = re.sub(r\"CoastpowerlineTramTr\", \"Coast powerline\", tweet)\n tweet = re.sub(r\"ServicesGold\", \"Services Gold\", tweet)\n tweet = re.sub(r\"NewsbrokenEmergency\", \"News broken emergency\", tweet)\n tweet = re.sub(r\"Evaucation\", \"evacuation\", tweet)\n tweet = re.sub(r\"leaveevacuateexitbe\", \"leave evacuate exit be\", tweet)\n tweet = re.sub(r\"P_EOPLE\", \"PEOPLE\", tweet)\n tweet = re.sub(r\"Tubestrike\", \"tube strike\", tweet)\n tweet = re.sub(r\"CLASS_SICK\", \"CLASS SICK\", tweet)\n tweet = re.sub(r\"localplumber\", \"local plumber\", tweet)\n tweet = re.sub(r\"awesomejobsiri\", \"awesome job siri\", tweet)\n tweet = re.sub(r\"PayForItHow\", \"Pay for it how\", tweet)\n tweet = re.sub(r\"ThisIsAfrica\", \"This is Africa\", tweet)\n tweet = re.sub(r\"crimeairnetwork\", \"crime air network\", tweet)\n tweet = re.sub(r\"KimAcheson\", \"Kim Acheson\", tweet)\n tweet = re.sub(r\"cityofcalgary\", \"City of Calgary\", tweet)\n tweet = re.sub(r\"prosyndicate\", \"pro syndicate\", tweet)\n tweet = re.sub(r\"660NEWS\", \"660 NEWS\", tweet)\n tweet = re.sub(r\"BusInsMagazine\", \"Business Insurance Magazine\", tweet)\n tweet = re.sub(r\"wfocus\", \"focus\", tweet)\n tweet = re.sub(r\"ShastaDam\", \"Shasta Dam\", tweet)\n tweet = re.sub(r\"go2MarkFranco\", \"Mark Franco\", tweet)\n tweet = re.sub(r\"StephGHinojosa\", \"Steph Hinojosa\", tweet)\n tweet = re.sub(r\"Nashgrier\", \"Nash Grier\", tweet)\n tweet = re.sub(r\"NashNewVideo\", \"Nash new video\", tweet)\n tweet = re.sub(r\"IWouldntGetElectedBecause\", \"I would not get elected because\", tweet)\n tweet = re.sub(r\"SHGames\", \"Sledgehammer Games\", tweet)\n tweet = re.sub(r\"bedhair\", \"bed hair\", tweet)\n tweet = re.sub(r\"JoelHeyman\", \"Joel Heyman\", tweet)\n tweet = re.sub(r\"viaYouTube\", \"via YouTube\", tweet)\n \n # Urls\n tweet = re.sub(r\"https?:\\/\\/t.co\\/[A-Za-z0-9]+\", \"\", tweet)\n \n # Words with punctuations and special characters\n punctuations = '@#!?+&*[]-%.:/();$=><|{}^' + \"'`\"\n for p in punctuations:\n tweet = tweet.replace(p, f' {p} ')\n \n # ... and ..\n tweet = tweet.replace('...', ' ... ')\n if '...' not in tweet:\n tweet = tweet.replace('..', ' ... ') \n \n # Acronyms\n tweet = re.sub(r\"MH370\", \"Malaysia Airlines Flight 370\", tweet)\n tweet = re.sub(r\"m̼sica\", \"music\", tweet)\n tweet = re.sub(r\"okwx\", \"Oklahoma City Weather\", tweet)\n tweet = re.sub(r\"arwx\", \"Arkansas Weather\", tweet) \n tweet = re.sub(r\"gawx\", \"Georgia Weather\", tweet) \n tweet = re.sub(r\"scwx\", \"South Carolina Weather\", tweet) \n tweet = re.sub(r\"cawx\", \"California Weather\", tweet)\n tweet = re.sub(r\"tnwx\", \"Tennessee Weather\", tweet)\n tweet = re.sub(r\"azwx\", \"Arizona Weather\", tweet) \n tweet = re.sub(r\"alwx\", \"Alabama Weather\", tweet)\n tweet = re.sub(r\"wordpressdotcom\", \"wordpress\", tweet) \n tweet = re.sub(r\"usNWSgov\", \"United States National Weather Service\", tweet)\n tweet = re.sub(r\"Suruc\", \"Sanliurfa\", tweet) \n \n # Grouping same words without embeddings\n tweet = re.sub(r\"Bestnaijamade\", \"bestnaijamade\", tweet)\n tweet = re.sub(r\"SOUDELOR\", \"Soudelor\", tweet)\n \n return tweet", "_____no_output_____" ], [ "%%time\n\nif do_clean: \n # Clean tweets' text through custom function 'text_cleaning', defined in the above cell (very long operation)\n df_train['text_cleaned'] = df_train['text'].apply(lambda s : text_cleaning(s))\n df_test['text_cleaned'] = df_test['text'].apply(lambda s : text_cleaning(s))\n \n # Save to pickle\n df_train.to_pickle('train_nlp_disaster.pkl', protocol = 4)\n df_test.to_pickle('test_nlp_disaster.pkl', protocol = 4)\n \nelse:\n df_train = pd.read_pickle(\"train_nlp_disaster.pkl\")\n df_test = pd.read_pickle(\"test_nlp_disaster.pkl\")", "Wall time: 14 ms\n" ], [ "df_train.head()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ecfaa67604047be0bebf9a4a3beae83656a84af3
220,129
ipynb
Jupyter Notebook
data-analysis.ipynb
rconan/dos-actors
356228a3fbe4430671ec1225952789d620914ec9
[ "MIT" ]
null
null
null
data-analysis.ipynb
rconan/dos-actors
356228a3fbe4430671ec1225952789d620914ec9
[ "MIT" ]
null
null
null
data-analysis.ipynb
rconan/dos-actors
356228a3fbe4430671ec1225952789d620914ec9
[ "MIT" ]
1
2022-01-19T11:07:07.000Z
2022-01-19T11:07:07.000Z
936.719149
102,626
0.953296
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "data = pd.read_parquet(\"setpoint-mount-m1-m2-tt-lom.parquet\")\ndata.columns", "_____no_output_____" ], [ "plt.style.use(\"dark_background\")\nfig,axs = plt.subplots(nrows=2,sharex=True,figsize=(10,10))\nax = axs[0]\nax.plot(np.vstack(data[\"OSSM1Lcl\"]));\nax.grid()\nax = axs[1]\nax.plot(np.vstack(data[\"MCM2Lcl6D\"]))\nax.grid()\n", "_____no_output_____" ], [ "data = pd.read_parquet(\"setpoint-mount-m1-m2-tt.parquet\")\ndata.columns\n", "_____no_output_____" ], [ "plt.style.use(\"dark_background\")\nfig, axs = plt.subplots(nrows=2, sharex=True, figsize=(10, 10))\nax = axs[0]\nax.plot(np.vstack(data[\"OSSM1Lcl\"]))\nax.grid()\nax = axs[1]\nax.plot(np.vstack(data[\"MCM2Lcl6D\"]))\nax.grid()\n", "_____no_output_____" ], [ "data = pd.read_parquet(\"tt_feedback.parquet\")\ndata.columns\n", "_____no_output_____" ], [ "plt.plot(np.vstack(data[\"TTFB\"]))\nplt.grid()", "_____no_output_____" ], [ "poke = np.load(\"poke_mat.pkl\",allow_pickle=True)", "_____no_output_____" ], [ "np.asarray(poke[0]).sum()", "_____no_output_____" ], [ "np.asarray(poke[1]).sum()\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfaae659812cbcac58af3afb0a89db742e8d2b4
13,069
ipynb
Jupyter Notebook
Smart_CCTVs_Social_Distance_Detection.ipynb
tushar-amrit-6/Minor-Project
24711f89b9c18f1b796c199edb01cf96b08a7524
[ "MIT" ]
null
null
null
Smart_CCTVs_Social_Distance_Detection.ipynb
tushar-amrit-6/Minor-Project
24711f89b9c18f1b796c199edb01cf96b08a7524
[ "MIT" ]
null
null
null
Smart_CCTVs_Social_Distance_Detection.ipynb
tushar-amrit-6/Minor-Project
24711f89b9c18f1b796c199edb01cf96b08a7524
[ "MIT" ]
null
null
null
40.212308
262
0.531487
[ [ [ "<a href=\"https://colab.research.google.com/github/tushar-amrit-6/Minor-Project/blob/main/Smart_CCTVs_Social_Distance_Detection.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# **Setting up the variable values**", "_____no_output_____" ] ], [ [ "# define the minimum safe distance (in pixels) that two people can be\n# from each other\nMIN_DISTANCE = 50\n\n# initialize minimum probability to filter weak detections along with\n# the threshold when applying non-maxima suppression\nMIN_CONF = 0.3\nNMS_THRESH = 0.3", "_____no_output_____" ] ], [ [ "# **Creating the People Detection Function**", "_____no_output_____" ] ], [ [ "# import the necessary packages\n\nimport numpy as np\nimport cv2\n\ndef detect_people(frame, net, ln, personIdx=0):\n\t# grab the dimensions of the frame and initialize the list of\n\t# results\n\t(H, W) = frame.shape[:2]\n\tresults = []\n\n\t# construct a blob from the input frame and then perform a forward\n\t# pass of the YOLO object detector, giving us our bounding boxes\n\t# and associated probabilities\n\tblob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),\n\t\tswapRB=True, crop=False)\n\tnet.setInput(blob)\n\tlayerOutputs = net.forward(ln)\n\n\t# initialize our lists of detected bounding boxes, centroids, and\n\t# confidences, respectively\n\tboxes = []\n\tcentroids = []\n\tconfidences = []\n\n\t# loop over each of the layer outputs\n\tfor output in layerOutputs:\n\t\t# loop over each of the detections\n\t\tfor detection in output:\n\t\t\t# extract the class ID and confidence (i.e., probability)\n\t\t\t# of the current object detection\n\t\t\tscores = detection[5:]\n\t\t\tclassID = np.argmax(scores)\n\t\t\tconfidence = scores[classID]\n\n\t\t\t# filter detections by (1) ensuring that the object\n\t\t\t# detected was a person and (2) that the minimum\n\t\t\t# confidence is met\n\t\t\tif classID == personIdx and confidence > MIN_CONF:\n\t\t\t\t# scale the bounding box coordinates back relative to\n\t\t\t\t# the size of the image, keeping in mind that YOLO\n\t\t\t\t# actually returns the center (x, y)-coordinates of\n\t\t\t\t# the bounding box followed by the boxes' width and\n\t\t\t\t# height\n\t\t\t\tbox = detection[0:4] * np.array([W, H, W, H])\n\t\t\t\t(centerX, centerY, width, height) = box.astype(\"int\")\n\n\t\t\t\t# use the center (x, y)-coordinates to derive the top\n\t\t\t\t# and and left corner of the bounding box\n\t\t\t\tx = int(centerX - (width / 2))\n\t\t\t\ty = int(centerY - (height / 2))\n\n\t\t\t\t# update our list of bounding box coordinates,\n\t\t\t\t# centroids, and confidences\n\t\t\t\tboxes.append([x, y, int(width), int(height)])\n\t\t\t\tcentroids.append((centerX, centerY))\n\t\t\t\tconfidences.append(float(confidence))\n\n\t# apply non-maxima suppression to suppress weak, overlapping\n\t# bounding boxes\n\tidxs = cv2.dnn.NMSBoxes(boxes, confidences, MIN_CONF, NMS_THRESH)\n\n\n\n\t# ensure at least one detection exists\n\tif len(idxs) > 0:\n\t\t# loop over the indexes we are keeping\n\t\tfor i in idxs.flatten():\n\t\t\t# extract the bounding box coordinates\n\t\t\t(x, y) = (boxes[i][0], boxes[i][1])\n\t\t\t(w, h) = (boxes[i][2], boxes[i][3])\n\n\t\t\t# update our results list to consist of the person\n\t\t\t# prediction probability, bounding box coordinates,\n\t\t\t# and the centroid\n\t\t\tr = (confidences[i], (x, y, x + w, y + h), centroids[i])\n\t\t\tresults.append(r)\n\n\t# return the list of results\n\treturn results", "_____no_output_____" ] ], [ [ "#**Mounting Google Drive**", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "_____no_output_____" ] ], [ [ "# **Grab frames from video and make prediction measuring distances of detected people**", "_____no_output_____" ] ], [ [ "# USAGE\n# python social_distance_detector.py --input pedestrians.mp4\n# python social_distance_detector.py --input pedestrians.mp4 --output output.avi\n\n# import the necessary packages\nfrom google.colab.patches import cv2_imshow\nfrom scipy.spatial import distance as dist\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\nimport os\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--input\", type=str, default=\"\",\n\thelp=\"path to (optional) input video file\")\nap.add_argument(\"-o\", \"--output\", type=str, default=\"\",\n\thelp=\"path to (optional) output video file\")\nap.add_argument(\"-d\", \"--display\", type=int, default=1,\n\thelp=\"whether or not output frame should be displayed\")\nargs = vars(ap.parse_args([\"--input\",\"/content/drive/MyDrive/social-distance-detection/pedestrians.mp4\",\"--output\",\"my_output.avi\",\"--display\",\"1\"]))\n\n# load the COCO class labels our YOLO model was trained on\nlabelsPath = os.path.sep.join([\"/content/drive/MyDrive/social-distance-detection/yolo-coco/coco.names\"])\nLABELS = open(labelsPath).read().strip().split(\"\\n\")\n\n# derive the paths to the YOLO weights and model configuration\nweightsPath = os.path.sep.join([\"/content/drive/MyDrive/social-distance-detection/yolo-coco/yolov3.weights\"])\nconfigPath = os.path.sep.join([\"/content/drive/MyDrive/social-distance-detection/yolo-coco/yolov3.cfg\"])\n\n# load our YOLO object detector trained on COCO dataset (80 classes)\nprint(\"[INFO] loading YOLO from disk...\")\nnet = cv2.dnn.readNetFromDarknet(configPath, weightsPath)\n\n# determine only the *output* layer names that we need from YOLO\nln = net.getLayerNames()\nln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\n# initialize the video stream and pointer to output video file\nprint(\"[INFO] accessing video stream...\")\nvs = cv2.VideoCapture(args[\"input\"] if args[\"input\"] else 0)\nwriter = None\n\n# loop over the frames from the video stream\nwhile True:\n\t# read the next frame from the file\n\t(grabbed, frame) = vs.read()\n\n\t# if the frame was not grabbed, then we have reached the end\n\t# of the stream\n\tif not grabbed:\n\t\tbreak\n\n\t# resize the frame and then detect people (and only people) in it\n\tframe = imutils.resize(frame, width=700)\n\tresults = detect_people(frame, net, ln,\n\t\tpersonIdx=LABELS.index(\"person\"))\n\n\t# initialize the set of indexes that violate the minimum social\n\t# distance\n\tviolate = set()\n\n\t# ensure there are *at least* two people detections (required in\n\t# order to compute our pairwise distance maps)\n\tif len(results) >= 2:\n\t\t# extract all centroids from the results and compute the\n\t\t# Euclidean distances between all pairs of the centroids\n\t\tcentroids = np.array([r[2] for r in results])\n\t\tD = dist.cdist(centroids, centroids, metric=\"euclidean\")\n\n\t\t# loop over the upper triangular of the distance matrix\n\t\tfor i in range(0, D.shape[0]):\n\t\t\tfor j in range(i + 1, D.shape[1]):\n\t\t\t\t# check to see if the distance between any two\n\t\t\t\t# centroid pairs is less than the configured number\n\t\t\t\t# of pixels\n\t\t\t\tif D[i, j] < MIN_DISTANCE:\n\t\t\t\t\t# update our violation set with the indexes of\n\t\t\t\t\t# the centroid pairs\n\t\t\t\t\tviolate.add(i)\n\t\t\t\t\tviolate.add(j)\n\n\t# loop over the results\n\tfor (i, (prob, bbox, centroid)) in enumerate(results):\n\t\t# extract the bounding box and centroid coordinates, then\n\t\t# initialize the color of the annotation\n\t\t(startX, startY, endX, endY) = bbox\n\t\t(cX, cY) = centroid\n\t\tcolor = (0, 255, 0)\n\n\t\t# if the index pair exists within the violation set, then\n\t\t# update the color\n\t\tif i in violate:\n\t\t\tcolor = (0, 0, 255)\n\n\t\t# draw (1) a bounding box around the person and (2) the\n\t\t# centroid coordinates of the person,\n\t\tcv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\n\t\tcv2.circle(frame, (cX, cY), 5, color, 1)\n\n\t# draw the total number of social distancing violations on the\n\t# output frame\n\ttext = \"Social Distancing Violations: {}\".format(len(violate))\n\tcv2.putText(frame, text, (10, frame.shape[0] - 25),\n\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.85, (0, 0, 255), 3)\n\n\t# check to see if the output frame should be displayed to our\n\t# screen\n\tif args[\"display\"] > 0:\n\t\t# show the output frame\n\t\tcv2_imshow(frame)\n\t\tkey = cv2.waitKey(1) & 0xFF\n\n\t\t# if the `q` key was pressed, break from the loop\n\t\tif key == ord(\"q\"):\n\t\t\tbreak\n\n\t# if an output video file path has been supplied and the video\n\t# writer has not been initialized, do so now\n\tif args[\"output\"] != \"\" and writer is None:\n\t\t# initialize our video writer\n\t\tfourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n\t\twriter = cv2.VideoWriter(args[\"output\"], fourcc, 25,\n\t\t\t(frame.shape[1], frame.shape[0]), True)\n\n\t# if the video writer is not None, write the frame to the output\n\t# video file\n\tif writer is not None:\n\t\twriter.write(frame)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfabf0eadfaf473148427f19995cd56c5ab40fb
31,774
ipynb
Jupyter Notebook
clustering_with_preprocessing.ipynb
aktivkohle/cluster-sparse-vectors
427c090dc5b3d6b933c2fb751c95f02fa2a80ab9
[ "MIT" ]
null
null
null
clustering_with_preprocessing.ipynb
aktivkohle/cluster-sparse-vectors
427c090dc5b3d6b933c2fb751c95f02fa2a80ab9
[ "MIT" ]
null
null
null
clustering_with_preprocessing.ipynb
aktivkohle/cluster-sparse-vectors
427c090dc5b3d6b933c2fb751c95f02fa2a80ab9
[ "MIT" ]
null
null
null
34.128894
139
0.445333
[ [ [ "%%time\n%run prepare_variables.py", "CPU times: user 9.18 s, sys: 404 ms, total: 9.58 s\nWall time: 9.64 s\n" ], [ "p.shape", "_____no_output_____" ], [ "p", "_____no_output_____" ] ], [ [ "#### That is very sparse - only 0.05% of the matrix has anything in it.", "_____no_output_____" ], [ "#### http://scikit-learn.org/stable/auto_examples/text/document_clustering.html#sphx-glr-auto-examples-text-document-clustering-py\n\n#### http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer", "_____no_output_____" ] ], [ [ "from sklearn.pipeline import make_pipeline\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.preprocessing import Normalizer\nnormalizer = Normalizer(copy=False)\nfrom sklearn.cluster import KMeans\nfrom numpy.random import random", "_____no_output_____" ], [ "%%time\nsvd = TruncatedSVD(n_components=1000, n_iter=7, random_state=42)\npipeline = make_pipeline(svd, normalizer)\np_new1 = pipeline.fit_transform(p)\np_new1.shape", "CPU times: user 10min 11s, sys: 1min 31s, total: 11min 43s\nWall time: 5min 8s\n" ], [ "%%time\nsvd = TruncatedSVD(n_components=2000, n_iter=7, random_state=42)\npipeline = make_pipeline(svd, normalizer)\np_new2 = pipeline.fit_transform(p)", "CPU times: user 30min 52s, sys: 1min 35s, total: 32min 28s\nWall time: 12min 24s\n" ], [ "%%time\nsvd = TruncatedSVD(n_components=150, n_iter=100, random_state=42)\npipeline = make_pipeline(svd, normalizer)\np_new3 = pipeline.fit_transform(p)", "CPU times: user 8min, sys: 3min 17s, total: 11min 18s\nWall time: 6min 9s\n" ], [ "%%time\np_new4 = normalizer.fit_transform(p)", "CPU times: user 364 ms, sys: 16 ms, total: 380 ms\nWall time: 379 ms\n" ], [ "# p_new = normalizer.fit_transform(p)", "_____no_output_____" ], [ "print (p_new1.shape, p_new2.shape, p_new3.shape, p_new4.shape)", "(7364, 1000) (7364, 2000) (7364, 150) (7364, 429429)\n" ], [ "%%time\nkmeans1 = KMeans(n_clusters=5, n_jobs=-1).fit(p_new1) ", "CPU times: user 1.05 s, sys: 80 ms, total: 1.13 s\nWall time: 3.79 s\n" ], [ "%%time\nkmeans2 = KMeans(n_clusters=5, n_jobs=-1).fit(p_new2) ", "CPU times: user 2.03 s, sys: 100 ms, total: 2.13 s\nWall time: 6.65 s\n" ], [ "%%time\nkmeans3 = KMeans(n_clusters=5, n_jobs=-1).fit(p_new3) ", "CPU times: user 196 ms, sys: 44 ms, total: 240 ms\nWall time: 800 ms\n" ], [ "%%time\nkmeans4 = KMeans(n_clusters=5, n_jobs=-1).fit(p_new4)", "CPU times: user 604 ms, sys: 152 ms, total: 756 ms\nWall time: 5min 28s\n" ], [ "type(p_new1)", "_____no_output_____" ], [ "type(kmeans1)", "_____no_output_____" ], [ "np.save('p_new1', p_new1)\nnp.save('p_new2', p_new2)\nnp.save('p_new3', p_new3)\nnp.save('p_new4', p_new4)\nnp.save('kmeans1', kmeans1)\nnp.save('kmeans2', kmeans2)\nnp.save('kmeans3', kmeans3)\nnp.save('kmeans4', kmeans4)", "_____no_output_____" ] ], [ [ "## How many videos has it found in each cluster?", "_____no_output_____" ] ], [ [ "kmeans = kmeans2", "_____no_output_____" ], [ "videos_df['cluster_labels'] = kmeans.labels_\nvideos_df.groupby('cluster_labels').count()[['videoTitle']]", "_____no_output_____" ] ], [ [ "## Sample ten videos randomly from each of those groups:", "_____no_output_____" ] ], [ [ "pd.set_option('display.max_rows', 120)\n\n# https://stackoverflow.com/questions/22472213/python-random-selection-per-group\n\nsize = 10 # sample size\nreplace = False # with replacement\nfn = lambda obj: obj.loc[np.random.choice(obj.index, size, replace),:]\nclustered_sample = videos_df.groupby('cluster_labels', as_index=False).apply(fn)\nclustered_sample[['videoTitle','cluster_labels', 'link']]", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
ecfac21d385b1c69b86d5a32f7cf1be91f567bcf
18,889
ipynb
Jupyter Notebook
np_slice.ipynb
ftconan/numpy_tutorial
0cca229357e975e3a30fe099f2d1a3158b1712ca
[ "MIT" ]
null
null
null
np_slice.ipynb
ftconan/numpy_tutorial
0cca229357e975e3a30fe099f2d1a3158b1712ca
[ "MIT" ]
null
null
null
np_slice.ipynb
ftconan/numpy_tutorial
0cca229357e975e3a30fe099f2d1a3158b1712ca
[ "MIT" ]
null
null
null
20.180556
749
0.417174
[ [ [ "import numpy as np ", "_____no_output_____" ], [ "x = np.arange(10)\nx[2]", "_____no_output_____" ], [ "x[-2]", "_____no_output_____" ], [ "x.shape = (2,5)\nx[1,3]", "_____no_output_____" ], [ "x[1,-1]", "_____no_output_____" ], [ "x[0]", "_____no_output_____" ], [ "x[0][2]", "_____no_output_____" ], [ "x = np.arange(10)\nx[2:5]", "_____no_output_____" ], [ "x[:-7]", "_____no_output_____" ], [ "x[1:7:2]", "_____no_output_____" ], [ "y = np.arange(35).reshape(5,7)\ny[1:5:2,::3]", "_____no_output_____" ], [ "x = np.arange(10,1,-1)\nx", "_____no_output_____" ], [ "x[np.array([3,3,1,8])]", "_____no_output_____" ], [ "x[np.array([3,3,20,8])]", "_____no_output_____" ], [ "x[np.array([[1,1],[2,3]])]", "_____no_output_____" ], [ "y[np.array([0,2,4]), np.array([0,1,2])]", "_____no_output_____" ], [ "y[np.array([0,2,4]), np.array([0,1])]", "_____no_output_____" ], [ "y[np.array([0,2,4]), 1]", "_____no_output_____" ], [ "y[np.array([0,2,4])]", "_____no_output_____" ], [ "b = y > 20\ny[b]", "_____no_output_____" ], [ "b[:,5]", "_____no_output_____" ], [ "y[b[:,5]]", "_____no_output_____" ], [ "x = np.arange(30).reshape(2,3,5)\nx", "_____no_output_____" ], [ "# b = np.array([[True, True, False], [False, True, True]])\n# x[b]", "_____no_output_____" ], [ "y[np.array([0,2,4]),1:3]", "_____no_output_____" ], [ "y[b[:,5],1:3]", "_____no_output_____" ], [ " y.shape", "_____no_output_____" ], [ "y[:,np.newaxis,:].shape", "_____no_output_____" ], [ "x = np.arange(5)\nx[:,np.newaxis] + x[np.newaxis,:]", "_____no_output_____" ], [ "z = np.arange(81).reshape(3,3,3,3)\nz[1,...,2]", "_____no_output_____" ], [ "z[1,:,:,2]", "_____no_output_____" ], [ "x = np.arange(10)\nx[2:7] = 1", "_____no_output_____" ], [ "x[2:7] = np.arange(5)", "_____no_output_____" ], [ "x[1] = 1.2\nx[1]", "_____no_output_____" ], [ "x[1] = 1.2j", "_____no_output_____" ], [ "x = np.arange(0, 50, 10)\nx", "_____no_output_____" ], [ "x[np.array([1,1,3,1])] += 1\nx", "_____no_output_____" ], [ "indices = (1,1,1,1)\nz[indices]", "_____no_output_____" ], [ "indices = (1,1,1,slice(0,2))\nz[indices]", "_____no_output_____" ], [ "indices = (1, Ellipsis, 1)\nz[indices]", "_____no_output_____" ], [ "z[[1,1,1,1]]", "_____no_output_____" ], [ "z[(1,1,1,1)]", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfae95e25931613771effe00bcc4e35424f40f4
20,179
ipynb
Jupyter Notebook
notebooks/cross_validation_train_test.ipynb
parmentelat/scikit-learn-mooc
5b2db41e131fe69f9c0cd8cf5e42828afa13cd30
[ "CC-BY-4.0" ]
1
2022-02-17T13:13:52.000Z
2022-02-17T13:13:52.000Z
notebooks/cross_validation_train_test.ipynb
parmentelat/scikit-learn-mooc
5b2db41e131fe69f9c0cd8cf5e42828afa13cd30
[ "CC-BY-4.0" ]
null
null
null
notebooks/cross_validation_train_test.ipynb
parmentelat/scikit-learn-mooc
5b2db41e131fe69f9c0cd8cf5e42828afa13cd30
[ "CC-BY-4.0" ]
null
null
null
33.189145
153
0.622033
[ [ [ "# Cross-validation framework\n\nIn the previous notebooks, we introduce some concepts regarding the\nevaluation of predictive models. While this section could be slightly\nredundant, we intend to go into details into the cross-validation framework.\n\nBefore we dive in, let's linger on the reasons for always having training and\ntesting sets. Let's first look at the limitation of using a dataset without\nkeeping any samples out.\n\nTo illustrate the different concepts, we will use the California housing\ndataset.", "_____no_output_____" ] ], [ [ "from sklearn.datasets import fetch_california_housing\n\nhousing = fetch_california_housing(as_frame=True)\ndata, target = housing.data, housing.target", "_____no_output_____" ] ], [ [ "In this dataset, the aim is to predict the median value of houses in an area\nin California. The features collected are based on general real-estate and\ngeographical information.\n\nTherefore, the task to solve is different from the one shown in the previous\nnotebook. The target to be predicted is a continuous variable and not anymore\ndiscrete. This task is called regression.\n\nThis, we will use a predictive model specific to regression and not to\nclassification.", "_____no_output_____" ] ], [ [ "print(housing.DESCR)", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ] ], [ [ "To simplify future visualization, let's transform the prices from the\n100 (k\\\\$) range to the thousand dollars (k\\\\$) range.", "_____no_output_____" ] ], [ [ "target *= 100\ntarget.head()", "_____no_output_____" ] ], [ [ "<div class=\"admonition note alert alert-info\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Note</p>\n<p class=\"last\">If you want a deeper overview regarding this dataset, you can refer to the\nAppendix - Datasets description section at the end of this MOOC.</p>\n</div>", "_____no_output_____" ], [ "## Training error vs testing error\n\nTo solve this regression task, we will use a decision tree regressor.", "_____no_output_____" ] ], [ [ "from sklearn.tree import DecisionTreeRegressor\n\nregressor = DecisionTreeRegressor(random_state=0)\nregressor.fit(data, target)", "_____no_output_____" ] ], [ [ "After training the regressor, we would like to know its potential generalization\nperformance once deployed in production. For this purpose, we use the mean\nabsolute error, which gives us an error in the native unit, i.e. k\\\\$.", "_____no_output_____" ] ], [ [ "from sklearn.metrics import mean_absolute_error\n\ntarget_predicted = regressor.predict(data)\nscore = mean_absolute_error(target, target_predicted)\nprint(f\"On average, our regressor makes an error of {score:.2f} k$\")", "_____no_output_____" ] ], [ [ "We get perfect prediction with no error. It is too optimistic and almost\nalways revealing a methodological problem when doing machine learning.\n\nIndeed, we trained and predicted on the same dataset. Since our decision tree\nwas fully grown, every sample in the dataset is stored in a leaf node.\nTherefore, our decision tree fully memorized the dataset given during `fit`\nand therefore made no error when predicting.\n\nThis error computed above is called the **empirical error** or **training\nerror**.\n\n<div class=\"admonition note alert alert-info\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Note</p>\n<p class=\"last\">In this MOOC, we will consistently use the term \"training error\".</p>\n</div>\n\nWe trained a predictive model to minimize the training error but our aim is\nto minimize the error on data that has not been seen during training.\n\nThis error is also called the **generalization error** or the \"true\"\n**testing error**.\n\n<div class=\"admonition note alert alert-info\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Note</p>\n<p class=\"last\">In this MOOC, we will consistently use the term \"testing error\".</p>\n</div>\n\nThus, the most basic evaluation involves:\n\n* splitting our dataset into two subsets: a training set and a testing set;\n* fitting the model on the training set;\n* estimating the training error on the training set;\n* estimating the testing error on the testing set.\n\nSo let's split our dataset.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\n\ndata_train, data_test, target_train, target_test = train_test_split(\n data, target, random_state=0)", "_____no_output_____" ] ], [ [ "Then, let's train our model.", "_____no_output_____" ] ], [ [ "regressor.fit(data_train, target_train)", "_____no_output_____" ] ], [ [ "Finally, we estimate the different types of errors. Let's start by computing\nthe training error.", "_____no_output_____" ] ], [ [ "target_predicted = regressor.predict(data_train)\nscore = mean_absolute_error(target_train, target_predicted)\nprint(f\"The training error of our model is {score:.2f} k$\")", "_____no_output_____" ] ], [ [ "We observe the same phenomena as in the previous experiment: our model\nmemorized the training set. However, we now compute the testing error.", "_____no_output_____" ] ], [ [ "target_predicted = regressor.predict(data_test)\nscore = mean_absolute_error(target_test, target_predicted)\nprint(f\"The testing error of our model is {score:.2f} k$\")", "_____no_output_____" ] ], [ [ "This testing error is actually about what we would expect from our model if\nit was used in a production environment.", "_____no_output_____" ], [ "## Stability of the cross-validation estimates\n\nWhen doing a single train-test split we don't give any indication regarding\nthe robustness of the evaluation of our predictive model: in particular, if\nthe test set is small, this estimate of the testing error will be unstable and\nwouldn't reflect the \"true error rate\" we would have observed with the same\nmodel on an unlimited amount of test data.\n\nFor instance, we could have been lucky when we did our random split of our\nlimited dataset and isolated some of the easiest cases to predict in the\ntesting set just by chance: the estimation of the testing error would be\noverly optimistic, in this case.\n\n**Cross-validation** allows estimating the robustness of a predictive model by\nrepeating the splitting procedure. It will give several training and testing\nerrors and thus some **estimate of the variability of the model generalization\nperformance**.\n\nThere are [different cross-validation\nstrategies](https://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-iterators),\nfor now we are going to focus on one called \"shuffle-split\". At each iteration\nof this strategy we:\n\n- randomly shuffle the order of the samples of a copy of the full dataset;\n- split the shuffled dataset into a train and a test set;\n- train a new model on the train set;\n- evaluate the testing error on the test set.\n\nWe repeat this procedure `n_splits` times. Keep in mind that the computational\ncost increases with `n_splits`.\n\n![Cross-validation diagram](../figures/shufflesplit_diagram.png)\n\n<div class=\"admonition note alert alert-info\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Note</p>\n<p class=\"last\">This figure shows the particular case of <strong>shuffle-split</strong> cross-validation\nstrategy using <tt class=\"docutils literal\">n_splits=5</tt>.\nFor each cross-validation split, the procedure trains a model on all the red\nsamples and evaluate the score of the model on the blue samples.</p>\n</div>\n\nIn this case we will set `n_splits=40`, meaning that we will train 40 models\nin total and all of them will be discarded: we just record their\ngeneralization performance on each variant of the test set.\n\nTo evaluate the generalization performance of our regressor, we can use\n[`sklearn.model_selection.cross_validate`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_validate.html)\nwith a\n[`sklearn.model_selection.ShuffleSplit`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.ShuffleSplit.html)\nobject:", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import cross_validate\nfrom sklearn.model_selection import ShuffleSplit\n\ncv = ShuffleSplit(n_splits=40, test_size=0.3, random_state=0)\ncv_results = cross_validate(\n regressor, data, target, cv=cv, scoring=\"neg_mean_absolute_error\")", "_____no_output_____" ] ], [ [ "The results `cv_results` are stored into a Python dictionary. We will convert\nit into a pandas dataframe to ease visualization and manipulation.", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ncv_results = pd.DataFrame(cv_results)\ncv_results.head()", "_____no_output_____" ] ], [ [ "<div class=\"admonition tip alert alert-warning\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Tip</p>\n<p>A score is a metric for which higher values mean better results. On the\ncontrary, an error is a metric for which lower values mean better results.\nThe parameter <tt class=\"docutils literal\">scoring</tt> in <tt class=\"docutils literal\">cross_validate</tt> always expect a function that is\na score.</p>\n<p class=\"last\">To make it easy, all error metrics in scikit-learn, like\n<tt class=\"docutils literal\">mean_absolute_error</tt>, can be transformed into a score to be used in\n<tt class=\"docutils literal\">cross_validate</tt>. To do so, you need to pass a string of the error metric\nwith an additional <tt class=\"docutils literal\">neg_</tt> string at the front to the parameter <tt class=\"docutils literal\">scoring</tt>;\nfor instance <tt class=\"docutils literal\"><span class=\"pre\">scoring=\"neg_mean_absolute_error\"</span></tt>. In this case, the negative\nof the mean absolute error will be computed which would be equivalent to a\nscore.</p>\n</div>\n\nLet us revert the negation to get the actual error:", "_____no_output_____" ] ], [ [ "cv_results[\"test_error\"] = -cv_results[\"test_score\"]", "_____no_output_____" ] ], [ [ "Let's check the results reported by the cross-validation.", "_____no_output_____" ] ], [ [ "cv_results.head(10)", "_____no_output_____" ] ], [ [ "We get timing information to fit and predict at each cross-validation\niteration. Also, we get the test score, which corresponds to the testing error\non each of the splits.", "_____no_output_____" ] ], [ [ "len(cv_results)", "_____no_output_____" ] ], [ [ "We get 40 entries in our resulting dataframe because we performed 40 splits.\nTherefore, we can show the testing error distribution and thus, have an\nestimate of its variability.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\ncv_results[\"test_error\"].plot.hist(bins=10, edgecolor=\"black\")\nplt.xlabel(\"Mean absolute error (k$)\")\n_ = plt.title(\"Test error distribution\")", "_____no_output_____" ] ], [ [ "We observe that the testing error is clustered around 47 k\\\\$ and ranges from\n43 k\\\\$ to 50 k\\\\$.", "_____no_output_____" ] ], [ [ "print(f\"The mean cross-validated testing error is: \"\n f\"{cv_results['test_error'].mean():.2f} k$\")", "_____no_output_____" ], [ "print(f\"The standard deviation of the testing error is: \"\n f\"{cv_results['test_error'].std():.2f} k$\")", "_____no_output_____" ] ], [ [ "Note that the standard deviation is much smaller than the mean: we could\nsummarize that our cross-validation estimate of the testing error is 46.36 +/-\n1.17 k\\\\$.\n\nIf we were to train a single model on the full dataset (without\ncross-validation) and then later had access to an unlimited amount of test\ndata, we would expect its true testing error to fall close to that region.\n\nWhile this information is interesting in itself, it should be contrasted to\nthe scale of the natural variability of the vector `target` in our dataset.\n\nLet us plot the distribution of the target variable:", "_____no_output_____" ] ], [ [ "target.plot.hist(bins=20, edgecolor=\"black\")\nplt.xlabel(\"Median House Value (k$)\")\n_ = plt.title(\"Target distribution\")", "_____no_output_____" ], [ "print(f\"The standard deviation of the target is: {target.std():.2f} k$\")", "_____no_output_____" ] ], [ [ "The target variable ranges from close to 0 k\\\\$ up to 500 k\\\\$ and, with a\nstandard deviation around 115 k\\\\$.\n\nWe notice that the mean estimate of the testing error obtained by\ncross-validation is a bit smaller than the natural scale of variation of the\ntarget variable. Furthermore, the standard deviation of the cross validation\nestimate of the testing error is even smaller.\n\nThis is a good start, but not necessarily enough to decide whether the\ngeneralization performance is good enough to make our prediction useful in\npractice.\n\nWe recall that our model makes, on average, an error around 47 k\\\\$. With this\ninformation and looking at the target distribution, such an error might be\nacceptable when predicting houses with a 500 k\\\\$. However, it would be an\nissue with a house with a value of 50 k\\\\$. Thus, this indicates that our\nmetric (Mean Absolute Error) is not ideal.\n\nWe might instead choose a metric relative to the target value to predict: the\nmean absolute percentage error would have been a much better choice.\n\nBut in all cases, an error of 47 k\\\\$ might be too large to automatically use\nour model to tag house values without expert supervision.\n\n## More detail regarding `cross_validate`\n\nDuring cross-validation, many models are trained and evaluated. Indeed, the\nnumber of elements in each array of the output of `cross_validate` is a\nresult from one of these `fit`/`score` procedures. To make it explicit, it is\npossible to retrieve these fitted models for each of the splits/folds by\npassing the option `return_estimator=True` in `cross_validate`.", "_____no_output_____" ] ], [ [ "cv_results = cross_validate(regressor, data, target, return_estimator=True)\ncv_results", "_____no_output_____" ], [ "cv_results[\"estimator\"]", "_____no_output_____" ] ], [ [ "The five decision tree regressors corresponds to the five fitted decision\ntrees on the different folds. Having access to these regressors is handy\nbecause it allows to inspect the internal fitted parameters of these\nregressors.\n\nIn the case where you only are interested in the test score, scikit-learn\nprovide a `cross_val_score` function. It is identical to calling the\n`cross_validate` function and to select the `test_score` only (as we\nextensively did in the previous notebooks).", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import cross_val_score\n\nscores = cross_val_score(regressor, data, target)\nscores", "_____no_output_____" ] ], [ [ "## Summary\n\nIn this notebook, we saw:\n\n* the necessity of splitting the data into a train and test set;\n* the meaning of the training and testing errors;\n* the overall cross-validation framework with the possibility to study\n generalization performance variations.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecfb1d4a4ede3c8afe7d6fa9e264d5d90f3496fd
1,037
ipynb
Jupyter Notebook
Tensorflow_official/cnn/.ipynb_checkpoints/basic_classfication-checkpoint.ipynb
starkidstory/OmegaTensor
2a80d38236a7ce6d6460be59528b33227d98b93b
[ "MIT" ]
2
2020-04-07T03:01:03.000Z
2020-04-16T14:33:21.000Z
Tensorflow_official/cnn/.ipynb_checkpoints/basic_classfication-checkpoint.ipynb
starkidstory/OmegaTensor
2a80d38236a7ce6d6460be59528b33227d98b93b
[ "MIT" ]
null
null
null
Tensorflow_official/cnn/.ipynb_checkpoints/basic_classfication-checkpoint.ipynb
starkidstory/OmegaTensor
2a80d38236a7ce6d6460be59528b33227d98b93b
[ "MIT" ]
null
null
null
17.283333
53
0.48216
[ [ [ "print(\"aaa\")\nimport tensorflow as tf\nname=tf.constant(\"hello\")\nprint(name)", "aaa\ntf.Tensor(b'hello', shape=(), dtype=string)\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
ecfb225462fb56dbfc32b67a740c32058647dd8f
15,226
ipynb
Jupyter Notebook
[Spring 2021] Advanced Information retrieval/Week 1/2021S-01 Crawler.ipynb
RomulusGwelt/Innopolis
a8bf20e8b13f144581b4b8236f421024c5a1dbb6
[ "MIT" ]
null
null
null
[Spring 2021] Advanced Information retrieval/Week 1/2021S-01 Crawler.ipynb
RomulusGwelt/Innopolis
a8bf20e8b13f144581b4b8236f421024c5a1dbb6
[ "MIT" ]
null
null
null
[Spring 2021] Advanced Information retrieval/Week 1/2021S-01 Crawler.ipynb
RomulusGwelt/Innopolis
a8bf20e8b13f144581b4b8236f421024c5a1dbb6
[ "MIT" ]
null
null
null
36.513189
331
0.546959
[ [ [ "# Crawler\n## 1. Download and persist #\nPlease complete a code for `load()`, `download()` and `persist()` methods of `Document` class. What they do:\n- for a given URL `download()` method downloads binary data and stores in `self.content`. It returns `True` for success, else `False`.\n- `persist()` method saves `self.content` somewhere in file system. We do it to avoid multiple downloads (for caching in other words).\n- `load()` method loads data from hard drive. Returns `True` for success.\n\nTests checks that your code somehow works.", "_____no_output_____" ] ], [ [ "import requests\nfrom urllib.parse import quote\n\nclass Document:\n \n def __init__(self, url):\n self.url = url\n \n def get(self):\n if not self.load():\n if not self.download():\n raise FileNotFoundError(self.url)\n else:\n self.persist()\n \n def download(self):\n response = requests.get(self.url)\n if response.status_code == 200:\n self.content = response.content\n return True; \n return False\n \n def persist(self):\n with open(quote(self.url).replace('/', '_'), 'wb') as file:\n file.write(self.content)\n \n def load(self):\n try:\n with open(quote(self.url).replace('/', '_'), 'rb') as file:\n self.content = file.read() \n return True\n except:\n return False", "_____no_output_____" ] ], [ [ "### 1.1. Tests ###", "_____no_output_____" ] ], [ [ "doc = Document('http://sprotasov.ru/data/iu.txt')\n\ndoc.get()\nassert doc.content, \"Document download failed\"\nassert \"Code snippets, demos and labs for the course\" in str(doc.content), \"Document content error\"\n\ndoc.get()\nassert doc.load(), \"Load should return true for saved document\"\nassert \"Code snippets, demos and labs for the course\" in str(doc.content), \"Document load from disk error\"", "_____no_output_____" ] ], [ [ "## 2. Parse HTML ##\n`BeautifulSoap` library is a de facto standard to parse XML and HTML documents in python. Use it to complete `parse()` method that extracts document contents. You should initialize:\n- `self.anchors` list of tuples `('text', 'url')` met in a document. Be aware, there exist relative links (e.g. `../content/pic.jpg`). Use `urllib.parse.urljoin()` to fix this issue.\n- `self.images` list of images met in a document. Again, links can be relative to current page.\n- `self.text` should keep plain text of the document without scripts, tags, comments and so on. You can refer to [this stackoverflow answer](https://stackoverflow.com/a/1983219) for details.", "_____no_output_____" ] ], [ [ "from bs4 import BeautifulSoup\nfrom bs4.element import Comment\nimport urllib.parse\n\n\nclass HtmlDocument(Document):\n \n def parse(self):\n soup = BeautifulSoup(self.content, 'lxml')\n \n self.anchors = []\n self.images = []\n self.text = \"\"\n \n links = soup.find_all('a')\n for link in links:\n self.anchors.append((link.text, link.get('href')))\n \n imgs = soup.find_all('img')\n for img in imgs:\n img = urllib.parse.urljoin(self.url, img.get('src'))\n self.images.append(img)\n \n \n self.text = self.text_from_html(self.content)\n \n def tag_visible(self, element):\n if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:\n return False\n if isinstance(element, Comment):\n return False\n return True\n\n\n def text_from_html(self, body):\n soup = BeautifulSoup(body, 'html.parser')\n texts = soup.findAll(text=True)\n visible_texts = filter(self.tag_visible, texts) \n return u\" \".join(t.strip() for t in visible_texts)\n ", "_____no_output_____" ] ], [ [ "### 2.1. Tests ###", "_____no_output_____" ] ], [ [ "doc = HtmlDocument(\"http://sprotasov.ru\")\ndoc.get()\ndoc.parse()\n\nassert \"тестирующий сервер codetest\" in doc.text, \"Error parsing text\"\nassert \"http://sprotasov.ru/images/phone.png\" in doc.images, \"Error parsing images\"\nassert any(p[1] == \"http://university.innopolis.ru/\" for p in doc.anchors), \"Error parsing links\"", "_____no_output_____" ] ], [ [ "## 3. Document analysis ##\nComplete the code for `HtmlDocumentTextData` class. Implement word and sentence splitting (use any method you can propose). Your `get_word_stats()` method should return `Counter` object. Don't forget to lowercase your words.", "_____no_output_____" ] ], [ [ "from collections import Counter\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import sent_tokenize, word_tokenize, RegexpTokenizer\nnltk.download('punkt')\nnltk.download('stopwords')\nstopwords = stopwords.words(\"russian\")\n\nclass HtmlDocumentTextData:\n \n def __init__(self, url):\n self.doc = HtmlDocument(url)\n self.doc.get()\n self.doc.parse()\n \n def get_sentences(self):\n #TODO*: implement sentence parser\n result = sent_tokenize(self.doc.text, language = \"russian\")\n return result\n \n def get_word_stats(self):\n #TODO return Counter object of the document, containing mapping {`word` -> count_in_doc}\n result = RegexpTokenizer(r'\\w+').tokenize(self.doc.text.lower())\n result_withouth_sw = [word for word in result if not word in stopwords]\n\n return Counter(result_withouth_sw)\n ", "[nltk_data] Downloading package punkt to\n[nltk_data] C:\\Users\\Romulus\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\Romulus\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ] ], [ [ "### 3.1. Tests ###", "_____no_output_____" ] ], [ [ "doc = HtmlDocumentTextData(\"https://innopolis.university/\")\n\nprint(doc.get_word_stats().most_common(10))\nassert [x for x in doc.get_word_stats().most_common(10) if x[0] == 'иннополис'], 'иннополис sould be among most common'", "[('иннополис', 21), ('университета', 10), ('университет', 10), ('лаборатория', 10), ('университете', 7), ('области', 7), ('технологий', 7), ('робототехники', 7), ('12', 7), ('2020', 7)]\n" ] ], [ [ "## 4. Crawling ##\n\nMethod `crawl_generator()` is given starting url (`source`) and max depth of search. It should return a **generator** of `HtmlDocumentTextData` objects (return a document as soon as it is downloaded and parsed). You can benefit from `yield obj_name` python construction. Use `HtmlDocumentTextData.anchors` field to go deeper.", "_____no_output_____" ] ], [ [ "from queue import Queue\n\nclass Crawler:\n \n def crawl_generator(self, source, depth=1):\n queue = []\n queue.append((source, 1))\n visited = [source]\n while(len(queue) > 0):\n cur_url, cur_depth = queue.pop(0)\n if(cur_depth > depth):\n return\n try:\n HtmlDocument = HtmlDocumentTextData(cur_url)\n for node in HtmlDocument.doc.anchors:\n node_url = node[1] \n if (node_url not in visited):\n visited.append(node_url)\n queue.append((node_url, cur_depth+1))\n yield HtmlDocument\n except: \n continue", "_____no_output_____" ] ], [ [ "### 4.1. Tests ###", "_____no_output_____" ] ], [ [ "crawler = Crawler()\ncounter = Counter()\n\nfor c in crawler.crawl_generator(\"https://innopolis.university/en/\", 2):\n print(c.doc.url)\n if c.doc.url[-4:] in ('.pdf', '.mp3', '.avi', '.mp4', '.txt'):\n print(\"Skipping\", c.doc.url)\n continue\n counter.update(c.get_word_stats())\n print(len(counter), \"distinct word(s) so far\")\n \nprint(\"Done\")\n\nprint(counter.most_common(20))\nassert [x for x in counter.most_common(20) if x[0] == 'innopolis'], 'innopolis sould be among most common'", "https://innopolis.university/en/\n312 distinct word(s) so far\nhttp://old.innopolis.university/en/\n564 distinct word(s) so far\nhttps://media.innopolis.university/en/\n637 distinct word(s) so far\nhttps://www.facebook.com/InnopolisU\n701 distinct word(s) so far\nhttps://vk.com/innopolisu\n928 distinct word(s) so far\nhttps://www.youtube.com/user/InnopolisU\n952 distinct word(s) so far\nhttps://habr.com/ru/users/t-fazullin/posts/\n1653 distinct word(s) so far\nhttps://apply.innopolis.university/en/\n2369 distinct word(s) so far\nhttps://corporate.innopolis.university/\n2636 distinct word(s) so far\nhttps://media.innopolis.university/\n2883 distinct word(s) so far\nhttps://innopolis.university/lk/\n3014 distinct word(s) so far\nhttps://career.innopolis.university/en/job/\n3139 distinct word(s) so far\nhttps://career.innopolis.university/en/\n3468 distinct word(s) so far\nhttps://apply.innopolis.university/en/postgraduate-study/\n3631 distinct word(s) so far\nhttps://apply.innopolis.university/en/bachelor/\n3707 distinct word(s) so far\nhttps://apply.innopolis.university/en/master/\n3729 distinct word(s) so far\nhttps://apply.innopolis.university/en/grant/\n3731 distinct word(s) so far\nhttps://apply.innopolis.university/en/stud-life/\n3813 distinct word(s) so far\nhttps://innopolis.university/en/international-relations-office/\n4502 distinct word(s) so far\nhttps://innopolis.university/en/incomingstudents/\n4584 distinct word(s) so far\nhttps://innopolis.university/en/outgoingstudents/\n4619 distinct word(s) so far\nhttps://university.innopolis.ru/en/about/\n4685 distinct word(s) so far\nhttp://www.campuslife.innopolis.ru\n4773 distinct word(s) so far\nhttps://innopolis.university/en/research/\n4803 distinct word(s) so far\nhttps://media.innopolis.university/en/news/webinar-interstudents-eng/\n4822 distinct word(s) so far\nhttps://media.innopolis.university/en/news/devops-summer-school/\n4874 distinct word(s) so far\nhttps://media.innopolis.university/en/news/webinar-for-international-candidates-/\n4880 distinct word(s) so far\nhttps://media.innopolis.university/en/news/registration-innopolis-open-2020/\n4892 distinct word(s) so far\nhttps://media.innopolis.university/en/news/cyber-resilience-petrenko/\n4940 distinct word(s) so far\nhttps://media.innopolis.university/en/news/innopolis-university-extends-international-application-deadline-/\n4944 distinct word(s) so far\nhttps://media.innopolis.university/en/news/self-driven-school/\n4955 distinct word(s) so far\nhttps://apply.innopolis.ru/en/index.php\n5002 distinct word(s) so far\nhttps://media.innopolis.university/en/news/\n5002 distinct word(s) so far\nhttps://media.innopolis.university/en/events/\n5004 distinct word(s) so far\nhttp://www.minsvyaz.ru/en/\n5072 distinct word(s) so far\nDone\n[('the', 1337), ('of', 1212), ('and', 1196), ('in', 665), ('university', 647), ('to', 584), ('innopolis', 493), ('for', 456), ('a', 432), ('it', 262), ('is', 249), ('at', 220), ('i', 216), ('you', 200), ('with', 176), ('research', 175), ('on', 168), ('education', 164), ('students', 164), ('are', 157)]\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfb3022d9478c3cdecd4a97051873297bd089f9
927
ipynb
Jupyter Notebook
HelloGithub.ipynb
Marcela1093/dw_matrix
859482245c9e237ad2396656115c8d942b93ac20
[ "MIT" ]
null
null
null
HelloGithub.ipynb
Marcela1093/dw_matrix
859482245c9e237ad2396656115c8d942b93ac20
[ "MIT" ]
null
null
null
HelloGithub.ipynb
Marcela1093/dw_matrix
859482245c9e237ad2396656115c8d942b93ac20
[ "MIT" ]
null
null
null
927
927
0.707659
[ [ [ "print('Hello Github')", "Hello Github\n" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
ecfb455a0ecde781384a752a63d638dcd9f99796
53,141
ipynb
Jupyter Notebook
docs/memo/notebooks/data/quandl.fred_usdontd156n/notebook.ipynb
hebpmo/zipline
396469b29e7e0daea4fe1e8a1c18f6c7eeb92780
[ "Apache-2.0" ]
4
2018-11-17T20:04:53.000Z
2021-12-10T14:47:30.000Z
docs/memo/notebooks/data/quandl.fred_usdontd156n/notebook.ipynb
t330883522/zipline
396469b29e7e0daea4fe1e8a1c18f6c7eeb92780
[ "Apache-2.0" ]
null
null
null
docs/memo/notebooks/data/quandl.fred_usdontd156n/notebook.ipynb
t330883522/zipline
396469b29e7e0daea4fe1e8a1c18f6c7eeb92780
[ "Apache-2.0" ]
3
2018-11-17T20:04:50.000Z
2020-03-01T11:11:41.000Z
216.902041
45,908
0.886227
[ [ [ "# Quandl: Overnight LIBOR\n\nIn this notebook, we'll take a look at data set available on [Quantopian](https://www.quantopian.com/data). This dataset spans from 2001 through the current day. It contains the value for the London Interbank Borrowing Rate (LIBOR). We access this data via the API provided by [Quandl](https://www.quandl.com). [More details](https://www.quandl.com/data/FRED/USDONTD156N) on this dataset can be found on Quandl's website.\n\n### Blaze\nBefore we dig into the data, we want to tell you about how you generally access Quantopian partner data sets. These datasets are available using the [Blaze](http://blaze.pydata.org) library. Blaze provides the Quantopian user with a convenient interface to access very large datasets.\n\nSome of these sets (though not this one) are many millions of records. Bringing that data directly into Quantopian Research directly just is not viable. So Blaze allows us to provide a simple querying interface and shift the burden over to the server side.\n\nTo learn more about using Blaze and generally accessing Quantopian partner data, clone [this tutorial notebook](https://www.quantopian.com/clone_notebook?id=561827d21777f45c97000054).\n\nWith preamble in place, let's get started:", "_____no_output_____" ] ], [ [ "# import the dataset\nfrom quantopian.interactive.data.quandl import fred_usdontd156n as libor\n# Since this data is public domain and provided by Quandl for free, there is no _free version of this\n# data set, as found in the premium sets. This import gets you the entirety of this data set.\n\n# import data operations\nfrom odo import odo\n# import other libraries we will use\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "libor.sort('asof_date')", "_____no_output_____" ] ], [ [ "The data goes all the way back to 2001 and is updated daily.\n\nBlaze provides us with the first 10 rows of the data for display. Just to confirm, let's just count the number of rows in the Blaze expression:", "_____no_output_____" ] ], [ [ "libor.count()", "_____no_output_____" ] ], [ [ "Let's go plot it for fun. This data set is definitely small enough to just put right into a Pandas DataFrame", "_____no_output_____" ] ], [ [ "libor_df = odo(libor, pd.DataFrame)\n\nlibor_df.plot(x='asof_date', y='value')\nplt.xlabel(\"As Of Date (asof_date)\")\nplt.ylabel(\"LIBOR\")\nplt.title(\"London Interbank Offered Rate\")\nplt.legend().set_visible(False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfb4ca562e4c88176c2bb05c4d20cf70d8bf049
5,797
ipynb
Jupyter Notebook
Deep_Learning/NLP/Seminar.ipynb
GarikAdamyan/ISTC_ML_course
ea81284a54ea086b3d94408ddcea2a275736672c
[ "MIT" ]
2
2019-07-11T14:39:47.000Z
2019-07-11T20:20:17.000Z
Deep_Learning/NLP/Seminar.ipynb
GarikAdamyan/ISTC_ML_course
ea81284a54ea086b3d94408ddcea2a275736672c
[ "MIT" ]
null
null
null
Deep_Learning/NLP/Seminar.ipynb
GarikAdamyan/ISTC_ML_course
ea81284a54ea086b3d94408ddcea2a275736672c
[ "MIT" ]
null
null
null
27.473934
155
0.527169
[ [ [ "# Language Modeling", "_____no_output_____" ], [ "**Language Modeling** is the task of predicting\twhat word comes next.\n\n<img src=\"img/predict_next.png\" style=\"height: 150px;\"/>\nMore formally: given a sequence o words $x^{(1)}, x^{(2)}, \\dots, x^{(t)}$, compute the probability distribution of the next word $x^{(t+1)}$:\n$$P(x^{(t+1)})=P(w_j\\;|\\;x^{(t)}, \\dots, x^{(1)})$$\nwhere $w_j$ is a word in the vocabulary $V = \\{w_1, \\dots, w_{|V|}\\}$ ", "_____no_output_____" ], [ "# Everyday use of Language Models", "_____no_output_____" ], [ "<tr>\n<td> <img src=\"img/use1.png\" style=\"height: 250px;\"/> </td>\n<td> <img src=\"img/use2.png\" style=\"height: 250px;\"/> </td>\n</tr>", "_____no_output_____" ], [ "# n-gram Language Models\nFirst we make a simplifying assumption: $\\large x^{(t+1)}$ depends only on the preceding $ (n-1)$ words\n$$\\large P(x^{(t+1)}\\;|\\;x^{(t)}, \\dots, x^{(1)}) = P(x^{(t+1)}\\;|\\;x^{(t)}, \\dots, x^{(t-n+2)})=$$\n$$\\large = \\frac{P(x^{(t+1)}, x^{(t)}, \\dots, x^{(t-n+2)})}{P(x^{(t)}, \\dots, x^{(t-n+2)})} \\approx$$\n$$\\large \\approx \\frac{count(x^{(t+1)}, x^{(t)}, \\dots, x^{(t-n+2)})}{count(x^{(t)}, \\dots, x^{(t-n+2)})}$$", "_____no_output_____" ], [ "# Generating text\nYou can also use a Language Model to **generate text**.", "_____no_output_____" ], [ "<tr>\n<td> <img src=\"img/generate.png\" style=\"height: 300px;\"/> </td>\n<td> <img src=\"img/generate2.png\" style=\"height:300px;\"/> </td>\n</tr>", "_____no_output_____" ], [ "# A fixed-window neural Language Model", "_____no_output_____" ], [ "![neural language model](img/fixed_window_example.png)\n![neural language model](img/nlm_network.png)", "_____no_output_____" ], [ "**Improvements over** n-gram LM:\n* No sparsity problem\n* Model size is $O(n)$ not $O(exp(n))$\n\nRemaining **problems**:\n* Fixed window is *too small*\n* Enlarging window enlarges $W$ \n* Window can never be large enough!\n* Each $x^{(i)}$ uses different rows of. We *don’t share weights* across the window.", "_____no_output_____" ], [ "# Recurent Neural Networks (RNN)\n![rnn](img/rnn.png)", "_____no_output_____" ], [ "# RNN Language Model\n![RNNLM](img/rnn_lm.png)", "_____no_output_____" ], [ "RNN **Advantages**:\n* Can process any length input\n* Model size doesn’t increase for longer input\n* Computation for step t can (in theory) use information from many steps back\n* Weights are shared across timesteps: representations are shared \n\nRNN **Disadvantages**:\n* Recurrent computation is slow\n* In practice, difficult to access information from many steps back", "_____no_output_____" ], [ "# Training a RNN Language Model", "_____no_output_____" ], [ "True next word: $\\large y^{(t)} = x^{(t+1)}$ (one-hot ecoded vector)\n<br>\nPredicted Probability distribtion: $\\large \\hat{y}^{(t)}$ (sum to one)\n<br>\nLoss function on step t is usual **cross-entropy** between $y^{(t)}$ and $\\hat{y}^{(t)}$:\n\n$$\\large J^{(t)}(\\theta) = - \\sum_j y_j^{(t)} ln(\\hat{y}_j^{(t)})$$\n$$\\large \\mathcal L(\\theta) = \\frac{1}{T}\\sum_{t=1}^T J^{(t)}(\\theta)$$", "_____no_output_____" ], [ "# RNNs can be used for tagging\ne.g. part-of-speech tagging\n![tagging](img/rnn_tagging.png)\n\n# RNNs can be used for sentence classification\ne.g. sentiment classification\n![classification](img/rnn_encode.png)\n\n# RNNs can be used to generate text\ne.g. speech recognition, machine translation, summarization, image captioning\n![speech](img/rnn_speech.png)", "_____no_output_____" ], [ "### Composition of CNN and RNN\n![arcitecture](img/convplusrnn.png)\n<br>\n<br>\n![results](img/captioning.jpg)", "_____no_output_____" ], [ "## More reading\n[The Unreasonable Effectiveness of Recurrent Neural Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness/)\n<br>\n[Recurrent Neural Networks Tutorial](http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns/)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ecfb5374e55d8b68342796a222ce6df62844a377
25,969
ipynb
Jupyter Notebook
playground.ipynb
ekiuled/pairwise-similarities
db2f909a74ed2d9296b1a3814facb3e5a0efe28d
[ "Apache-2.0" ]
null
null
null
playground.ipynb
ekiuled/pairwise-similarities
db2f909a74ed2d9296b1a3814facb3e5a0efe28d
[ "Apache-2.0" ]
null
null
null
playground.ipynb
ekiuled/pairwise-similarities
db2f909a74ed2d9296b1a3814facb3e5a0efe28d
[ "Apache-2.0" ]
null
null
null
70.376694
4,746
0.473757
[ [ [ "from helpers import dataset_parser, dataset_filter\ndataset_parser.parse('data/source/junit4.md', 'data/pairs/junit4.csv', skip_untagged=False)\ndataset_filter.print_statistics('data/pairs/junit4.csv')", "Filename: data/pairs/junit4.csv\nDataset size: 180381\nClass sizes:\n-1 156728\n 0 23285\n 1 368\nName: label, dtype: int64\n" ], [ "from helpers import dataset_parser, dataset_filter\ndataset_parser.parse('data/source/gson.md', 'data/pairs/gson.csv', skip_untagged=False)\ndataset_filter.print_statistics('data/pairs/gson.csv')\ndataset_parser.parse('data/source/mockito.md', 'data/pairs/mockito.csv', skip_untagged=False)\ndataset_filter.print_statistics('data/pairs/mockito.csv')\ndataset_parser.parse('data/source/slf4j.md', 'data/pairs/slf4j.csv', skip_untagged=False)\ndataset_filter.print_statistics('data/pairs/slf4j.csv')", "Filename: data/pairs/gson.csv\nDataset size: 95266\nClass sizes:\n-1 92781\n 0 2303\n 1 182\nName: label, dtype: int64\nFilename: data/pairs/mockito.csv\nDataset size: 176121\nClass sizes:\n-1 167210\n 0 8499\n 1 412\nName: label, dtype: int64\nFilename: data/pairs/slf4j.csv\nDataset size: 11628\nClass sizes:\n-1 10353\n 0 1031\n 1 244\nName: label, dtype: int64\n" ], [ "from helpers import dataset_filter\nfor name in ['gson', 'junit4', 'mockito', 'slf4j']:\n dataset_filter.randomized_filter('data/pairs/'+name+'.csv', 'data/filtered/'+name+'.csv')\n dataset_filter.print_statistics('data/filtered/'+name+'.csv')", "Filename: data/filtered/gson.csv\nDataset size: 364\nClass sizes:\n1 182\n0 182\nName: label, dtype: int64\nFilename: data/filtered/junit4.csv\nDataset size: 736\nClass sizes:\n1 368\n0 368\nName: label, dtype: int64\nFilename: data/filtered/mockito.csv\nDataset size: 824\nClass sizes:\n1 412\n0 412\nName: label, dtype: int64\nFilename: data/filtered/slf4j.csv\nDataset size: 488\nClass sizes:\n1 244\n0 244\nName: label, dtype: int64\n" ], [ "from helpers import dataset_filter\nfilenames = ['data/filtered/'+name+'.csv' for name in ['gson', 'mockito', 'slf4j']]\ndataset_filter.concatenate_datasets(filenames, 'data/train.csv')\ndataset_filter.print_statistics('data/train.csv')", "Filename: data/train.csv\nDataset size: 1676\nClass sizes:\n1 838\n0 838\nName: label, dtype: int64\n" ], [ "from visualization import table\ntable.similarity_metrics()", "Using TensorFlow backend.\nThreshold = 0.5833, train accuracy = 0.9690\nThreshold = 0.7762, train accuracy = 0.9284\nThreshold = 0.4439, train accuracy = 0.9141\nThreshold = 0.0600, train accuracy = 0.9588\nThreshold = 0.8687, train accuracy = 0.9905\nThreshold = -2.1924, train accuracy = 0.9529\n+-------------+------------+--------+--------+------+------+------+------+\n| Algorithm | Accuracy | F1 | ROC | TP | TN | FP | FN |\n+=============+============+========+========+======+======+======+======+\n| LCS | 0.9497 | 0.9483 | 0.9952 | 339 | 360 | 8 | 29 |\n+-------------+------------+--------+--------+------+------+------+------+\n| COS | 0.8899 | 0.8771 | 0.9938 | 289 | 366 | 2 | 79 |\n+-------------+------------+--------+--------+------+------+------+------+\n| LEV | 0.9389 | 0.9386 | 0.9817 | 344 | 347 | 21 | 24 |\n+-------------+------------+--------+--------+------+------+------+------+\n| LSH | 0.9443 | 0.9428 | 0.9815 | 338 | 357 | 11 | 30 |\n+-------------+------------+--------+--------+------+------+------+------+\n| Siam | 0.9035 | 0.8973 | 0.9772 | 310 | 355 | 13 | 58 |\n+-------------+------------+--------+--------+------+------+------+------+\n| WMD | 0.9470 | 0.9453 | 0.9923 | 337 | 360 | 8 | 31 |\n+-------------+------------+--------+--------+------+------+------+------+\n" ], [ "from metrics import x_feature_metrics\nx_feature_metrics.siamx_evaluate('data/train.csv', 'data/test.csv', True, 'SiamX')", "Using TensorFlow backend.\nThreshold = 0.5689, train accuracy = 0.9958\n" ], [ "from visualization import table\ntable.feature_metrics()", "Using TensorFlow backend.\n+-------------+------------+--------------+-------------+---------------+--------+--------+\n| Algorithm | Accuracy | + Accuracy | Precision | + Precision | F1 | + F1 |\n+=============+============+==============+=============+===============+========+========+\n| LCS | 0.9497 | 0.9606 | 0.9769 | 0.9748 | 0.9483 | 0.9600 |\n+-------------+------------+--------------+-------------+---------------+--------+--------+\n| COS | 0.8899 | 0.9565 | 0.9931 | 0.9719 | 0.8771 | 0.9558 |\n+-------------+------------+--------------+-------------+---------------+--------+--------+\n| LEV | 0.9389 | 0.9443 | 0.9425 | 0.9225 | 0.9386 | 0.9457 |\n+-------------+------------+--------------+-------------+---------------+--------+--------+\n| LSH | 0.9443 | 0.9402 | 0.9685 | 0.9709 | 0.9428 | 0.9382 |\n+-------------+------------+--------------+-------------+---------------+--------+--------+\n| WMD | 0.9470 | 0.9579 | 0.9768 | 0.9542 | 0.9453 | 0.9581 |\n+-------------+------------+--------------+-------------+---------------+--------+--------+\n| Siam | 0.9035 | 0.9239 | 0.9598 | 0.8900 | 0.8973 | 0.9271 |\n+-------------+------------+--------------+-------------+---------------+--------+--------+\n" ], [ "import pandas as pd\nfor name in ['gson', 'junit4', 'mockito', 'slf4j']:\n df = pd.read_csv('data/pairs/'+name+'.csv', index_col=0)\n df = df[df['label'] == -1]\n df.to_csv('data/unlabeled/'+name+'.csv')", "_____no_output_____" ], [ "from metrics.unlabeled import label_unlabeled\n\nlabel_unlabeled('data/unlabeled/junit4.csv')", "Using TensorFlow backend.\n+-------------+------+\n| Algorithm | UP |\n+=============+======+\n| LCS | 110 |\n+-------------+------+\n| COS | 208 |\n+-------------+------+\n| LEV | 345 |\n+-------------+------+\n| LSH | 103 |\n+-------------+------+\n| WMD | 369 |\n+-------------+------+\n| SiamX | 4287 |\n+-------------+------+\n" ], [ "from metrics.unlabeled import label_unlabeled\n\nlabel_unlabeled('data/unlabeled/junit4.csv')", "Using TensorFlow backend.\n+-------------+------+\n| Algorithm | UP |\n+=============+======+\n| LCS | 110 |\n+-------------+------+\n| COS | 208 |\n+-------------+------+\n| LEV | 345 |\n+-------------+------+\n| LSH | 103 |\n+-------------+------+\n| WMD | 369 |\n+-------------+------+\n| SiamX | 4287 |\n+-------------+------+\n" ], [ "import pandas as pd \npd.read_csv('data/pairs/gson.csv', index_col=0)", "_____no_output_____" ], [ "from tabulate import tabulate\nheaders = ['Algorithm', 'Precision', '+ Precision', '+ Unl. Precision', '+ Full Precision', '+ Unl. TP', '+ Unl. Recall', '+ Full Recall']\ntable = [['LCS',0.9769,0.9748,99/110,(348+99)/(110+348+9),99,99/232,(348+99)/(232+368)],\n['COS',0.9931,0.9719,149/208,(346+149)/(208+346+10),149,149/232,(346+149)/(232+368)],\n['LEV',0.9425,0.9225,140/345,(357+140)/(345+357+30),140,140/232,(357+140)/(232+368)],\n['LSH',0.9685,0.9709,83/103,(334+83)/(103+334+10),83,83/232,(334+83)/(232+368)],\n['WMD',0.9768,0.9542,68/369,(354+68)/(369+354+17),68,68/232,(354+68)/(232+368)],\n['Siam',0.9598,0.8900,123/4287,(356+123)/(4287+356+44),123,123/232,(356+123)/(232+368)]]\nprint(tabulate(table, headers, tablefmt='rst', floatfmt='.4f'))\n# Всего 232 пары\n# Почему семантические алгоритмы так плохо отработали?", "=========== =========== ============= ================== ================== =========== =============== ===============\nAlgorithm Precision + Precision + Unl. Precision + Full Precision + Unl. TP + Unl. Recall + Full Recall\n=========== =========== ============= ================== ================== =========== =============== ===============\nLCS 0.9769 0.9748 0.9000 0.9572 99 0.4267 0.7450\nCOS 0.9931 0.9719 0.7163 0.8777 149 0.6422 0.8250\nLEV 0.9425 0.9225 0.4058 0.6790 140 0.6034 0.8283\nLSH 0.9685 0.9709 0.8058 0.9329 83 0.3578 0.6950\nWMD 0.9768 0.9542 0.1843 0.5703 68 0.2931 0.7033\nSiam 0.9598 0.8900 0.0287 0.1022 123 0.5302 0.7983\n=========== =========== ============= ================== ================== =========== =============== ===============\n" ], [ "from tabulate import tabulate\nheaders = ['Algorithm', 'Recall', '+ Recall']\ntable = \\\n[['LCS',339/368,348/368],\n['COS',289/368,346/368],\n['LEV',344/368,357/368],\n['LSH',338/368,334/368],\n['doc2vec',354/368,367/368],\n['WMD',337/368,354/368],\n['WMDK (new)',323/368,348/368],\n['Siam',310/368,356/368],\n['Siam (new)',0,358/368]]\nprint(tabulate(table, headers, tablefmt='rst', floatfmt='.4f'))", "=========== ======== ==========\nAlgorithm Recall + Recall\n=========== ======== ==========\nLCS 0.9212 0.9457\nCOS 0.7853 0.9402\nLEV 0.9348 0.9701\nLSH 0.9185 0.9076\ndoc2vec 0.9620 0.9973\nWMD 0.9158 0.9620\nWMDK (new) 0.8777 0.9457\nSiam 0.8424 0.9674\nSiam (new) 0.0000 0.9728\n=========== ======== ==========\n" ], [ "full_prec = [(348+99)/(110+348+9),(346+149)/(208+346+10),(357+140)/(345+357+30),(334+83)/(103+334+10),(354+68)/(369+354+17),(356+123)/(4287+356+44)]\nfull_rec = [(348+99)/(232+368),(346+149)/(232+368),(357+140)/(232+368),(334+83)/(232+368),(354+68)/(232+368),(356+123)/(232+368)]\nfull_f1 = [2*p*r/(p+r) for p, r in zip(full_prec, full_rec)]\nfull_f1", "_____no_output_____" ], [ "from tabulate import tabulate\nheaders = ['Algorithm', 'Accuracy', '+ Accuracy', 'F1', '+ F1', '+ Full F1']\ntable = [['LCS',0.9497,0.9606,0.9483,0.9600],\n['COS',0.8899,0.9565,0.8771,0.9558],\n['LEV',0.9389,0.9443,0.9386,0.9457],\n['LSH',0.9443,0.9402,0.9428,0.9382],\n['WMD',0.9470,0.9579,0.9453,0.9581],\n['Siam',0.9035,0.9239,0.8973,0.9271]]\nfor i in range(len(table)):\n table[i].append(full_f1[i])\nprint(tabulate(table, headers, tablefmt='rst', floatfmt='.4f'))", "=========== ========== ============ ====== ====== ===========\nAlgorithm Accuracy + Accuracy F1 + F1 + Full F1\n=========== ========== ============ ====== ====== ===========\nLCS 0.9497 0.9606 0.9483 0.9600 0.8379\nCOS 0.8899 0.9565 0.8771 0.9558 0.8505\nLEV 0.9389 0.9443 0.9386 0.9457 0.7462\nLSH 0.9443 0.9402 0.9428 0.9382 0.7966\nWMD 0.9470 0.9579 0.9453 0.9581 0.6299\nSiam 0.9035 0.9239 0.8973 0.9271 0.1812\n=========== ========== ============ ====== ====== ===========\n" ], [ "from metrics import metrics, x_feature_metrics\nfrom helpers.similarity_generator import all_algorithms, get_algorithm_by_name\n\nfor name, alg in all_algorithms():\n if name == 'Siam':\n x = x_feature_metrics.siamx_evaluate('data/train.csv', 'data/test.csv')\n else:\n x = x_feature_metrics.lr_evaluate('data/train.csv', 'data/test.csv', alg, name)\n print(name, x)", "LCS {'accuracy': 0.9605978260869565, 'precision': 0.9747899159663865, 'f1': 0.96, 'tp': 348, 'tn': 359, 'fp': 9, 'fn': 20}\nCOS {'accuracy': 0.9565217391304348, 'precision': 0.9719101123595506, 'f1': 0.9558011049723757, 'tp': 346, 'tn': 358, 'fp': 10, 'fn': 22}\nLEV {'accuracy': 0.9442934782608695, 'precision': 0.9224806201550387, 'f1': 0.9456953642384106, 'tp': 357, 'tn': 338, 'fp': 30, 'fn': 11}\nLSH {'accuracy': 0.9402173913043478, 'precision': 0.9709302325581395, 'f1': 0.9382022471910113, 'tp': 334, 'tn': 358, 'fp': 10, 'fn': 34}\nWMD {'accuracy': 0.9578804347826086, 'precision': 0.954177897574124, 'f1': 0.9580514208389717, 'tp': 354, 'tn': 351, 'fp': 17, 'fn': 14}\nSiam {'accuracy': 0.9239130434782609, 'f1': 0.9270833333333334, 'precision': 0.89, 'roc': 0.9700717745746692, 'tp': 356, 'tn': 324, 'fp': 44, 'fn': 12}\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfb58d71b2530dd35c4a0094808345a93ea912b
52,274
ipynb
Jupyter Notebook
Model/credit_scoring_with_logistic_regression.ipynb
CIC-DevC/cic-credit-scoring
ded3531bec203893bc33b3aa8b76ebce07f7cf0b
[ "Apache-2.0" ]
null
null
null
Model/credit_scoring_with_logistic_regression.ipynb
CIC-DevC/cic-credit-scoring
ded3531bec203893bc33b3aa8b76ebce07f7cf0b
[ "Apache-2.0" ]
null
null
null
Model/credit_scoring_with_logistic_regression.ipynb
CIC-DevC/cic-credit-scoring
ded3531bec203893bc33b3aa8b76ebce07f7cf0b
[ "Apache-2.0" ]
null
null
null
33.380587
105
0.266844
[ [ [ "## 1. Credit card applications", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import GridSearchCV\n\ncc_apps = pd.read_csv(\"cc_approvals.data\", header=None)\n\ncc_apps.head()", "_____no_output_____" ] ], [ [ "## 2. Inspecting the applications", "_____no_output_____" ] ], [ [ "cc_apps_description = cc_apps.describe()\nprint(cc_apps_description)\nprint(\"\\n\")\n\ncc_apps_info = cc_apps.info()\nprint(cc_apps_info)\nprint(\"\\n\")\n\ncc_apps.tail(17)", " 2 7 10 14\ncount 690.000000 690.000000 690.00000 690.000000\nmean 4.758725 2.223406 2.40000 1017.385507\nstd 4.978163 3.346513 4.86294 5210.102598\nmin 0.000000 0.000000 0.00000 0.000000\n25% 1.000000 0.165000 0.00000 0.000000\n50% 2.750000 1.000000 0.00000 5.000000\n75% 7.207500 2.625000 3.00000 395.500000\nmax 28.000000 28.500000 67.00000 100000.000000\n\n\n<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 690 entries, 0 to 689\nData columns (total 16 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 0 690 non-null object \n 1 1 690 non-null object \n 2 2 690 non-null float64\n 3 3 690 non-null object \n 4 4 690 non-null object \n 5 5 690 non-null object \n 6 6 690 non-null object \n 7 7 690 non-null float64\n 8 8 690 non-null object \n 9 9 690 non-null object \n 10 10 690 non-null int64 \n 11 11 690 non-null object \n 12 12 690 non-null object \n 13 13 690 non-null object \n 14 14 690 non-null int64 \n 15 15 690 non-null object \ndtypes: float64(2), int64(2), object(12)\nmemory usage: 86.4+ KB\nNone\n\n\n" ] ], [ [ "## 3. Handling the missing values", "_____no_output_____" ] ], [ [ "cc_apps = cc_apps.replace('?', np.nan)\ncc_apps.tail(17)", "_____no_output_____" ], [ "# Impute the missing values with mean imputation\ncc_apps.fillna(cc_apps.mean(), inplace=True)\nprint(cc_apps.isnull().sum())", "0 12\n1 12\n2 0\n3 6\n4 6\n5 9\n6 9\n7 0\n8 0\n9 0\n10 0\n11 0\n12 0\n13 13\n14 0\n15 0\ndtype: int64\n" ], [ "# Iterate over each column of cc_apps\nfor col in cc_apps.columns:\n if cc_apps[col].dtypes == 'object':\n cc_apps = cc_apps.fillna(cc_apps[col].value_counts().index[0])\n\n# Count the number of NaNs in the dataset and print the counts to verify\nprint(cc_apps.isnull().sum())", "0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0\n8 0\n9 0\n10 0\n11 0\n12 0\n13 0\n14 0\n15 0\ndtype: int64\n" ] ], [ [ "## 4. Preprocessing the data", "_____no_output_____" ] ], [ [ "# Instantiate LabelEncoder\nle=LabelEncoder()\n\n# Iterate over all the values of each column and extract their dtypes\nfor col in cc_apps.columns.values:\n if cc_apps[col].dtypes=='object':\n cc_apps[col]=le.fit_transform(cc_apps[col])\n\n", "_____no_output_____" ] ], [ [ "## 5. Splitting the dataset into train and test sets", "_____no_output_____" ] ], [ [ "\n# Drop the features 11 and 13 and convert the DataFrame to a NumPy array\ncc_apps = cc_apps.drop([11, 13], axis=1)\ncc_apps = cc_apps.values\n\n# Segregate features and labels into separate variables\nX,y = cc_apps[:,0:13] , cc_apps[:,13]\n\n# Split into train and test sets\nX_train, X_test, y_train, y_test = train_test_split(X\n ,\n y,\n test_size=0.33,\n random_state=42)", "_____no_output_____" ], [ "scaler = MinMaxScaler(feature_range=(0, 1))\nrescaledX_train = scaler.fit_transform(X_train)\nrescaledX_test = scaler.fit_transform(X_test)", "_____no_output_____" ] ], [ [ "## 6. Fitting a logistic regression model to the train set", "_____no_output_____" ] ], [ [ "logreg = LogisticRegression()\nlogreg.fit(rescaledX_train,y_train)", "_____no_output_____" ] ], [ [ "## 7. Making predictions and evaluating performance", "_____no_output_____" ] ], [ [ "# Use logreg to predict instances from the test set and store it\ny_pred = logreg.predict(rescaledX_test)\n\nprint(\"Accuracy of logistic regression classifier: \", logreg.score(rescaledX_test,y_test))\nconfusion_matrix(y_test,y_pred)\n\n", "Accuracy of logistic regression classifier: 0.8377192982456141\n" ] ], [ [ "## 8. Finding the best performing model", "_____no_output_____" ] ], [ [ "# Define the grid of values for tol and max_iter\ntol = [0.01, 0.001 ,0.0001]\nmax_iter = [100, 150, 200]\n\nparam_grid = dict(tol=tol, max_iter=max_iter)\ngrid_model = GridSearchCV(estimator=logreg, param_grid=param_grid, cv=5)\nrescaledX = scaler.fit_transform(X)\ngrid_model_result = grid_model.fit(rescaledX, y)\n\n# Summarize results\nbest_score, best_params = grid_model_result.best_score_, grid_model_result.best_params_\nprint(\"Best: %f using %s\" % (best_score, best_params))", "Best: 0.850725 using {'max_iter': 100, 'tol': 0.01}\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfb60857bcc09c8f88e88d350f8bfeaeca5efcf
1,801
ipynb
Jupyter Notebook
prepare-words.ipynb
ntnamazu/solve-wordle
3232521d5d904289a494a0e5a756213ffc5d165f
[ "MIT" ]
null
null
null
prepare-words.ipynb
ntnamazu/solve-wordle
3232521d5d904289a494a0e5a756213ffc5d165f
[ "MIT" ]
null
null
null
prepare-words.ipynb
ntnamazu/solve-wordle
3232521d5d904289a494a0e5a756213ffc5d165f
[ "MIT" ]
null
null
null
18.191919
77
0.510272
[ [ [ "file = open('words_alpha.txt')", "_____no_output_____" ], [ "print(file.read())", "_____no_output_____" ], [ "file.close()", "_____no_output_____" ], [ "file = read('words_alpha.txt')\nwords = file.read().split()\nprint(words)\nfile.close", "_____no_output_____" ], [ "words_5_letters = [word for word in words if len(word) == 5]", "_____no_output_____" ], [ "print(words_5_letters)", "_____no_output_____" ], [ "d = \"\\n\".join(words_5_letters)\n\nwith open('words.txt', 'w') as f:\n f.write(d)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
ecfb6652fe286abedb1293a5f3266f1d7601ad17
4,908
ipynb
Jupyter Notebook
assessments/coursework3/codes/Data Type transform.ipynb
linksdl/acs-project-data_mining_and_text_analytics
ed8f37f465632a5b3a46ab748614c6a3686f3d20
[ "Apache-2.0" ]
1
2021-09-14T11:36:38.000Z
2021-09-14T11:36:38.000Z
assessments/coursework3/codes/Data Type transform.ipynb
linksdl/acs-project-data_mining_and_text_analytics
ed8f37f465632a5b3a46ab748614c6a3686f3d20
[ "Apache-2.0" ]
null
null
null
assessments/coursework3/codes/Data Type transform.ipynb
linksdl/acs-project-data_mining_and_text_analytics
ed8f37f465632a5b3a46ab748614c6a3686f3d20
[ "Apache-2.0" ]
null
null
null
36.626866
1,578
0.559087
[ [ [ "## Data Transform", "_____no_output_____" ] ], [ [ "import re\nimport string\nimport csv\nimport codecs\nimport pandas as pd", "_____no_output_____" ], [ "file_path = './datasets_1/'\ndict_file_type = { \n 'SpanishAR.txt':'AR',\n 'SpanishCL.txt':'CL',\n 'SpanishCO.txt':'CO',\n 'SpanishCU.txt':'CU',\n 'SpanishMX.txt':'MX',\n }", "_____no_output_____" ], [ "def read_file(file_path):\n docs = []\n with open(file_path, encoding = 'utf-8') as f:\n lines = f.readlines()\n for line in lines:\n if line.startswith('<p>'):\n line = line.replace('<p>', '').replace('</p>', '')\n if len(line.split(' ')) > 8:\n docs.append(line)\n \n return docs", "_____no_output_____" ], [ "docs = read_file(file_path + 'SpanishCU.txt') ", "_____no_output_____" ], [ "print(len)", "4091\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ecfb68f41149f0cdfe73c4a047521ffce1c197a5
44,157
ipynb
Jupyter Notebook
analysis/XYKComparison.ipynb
galacticcouncil/HydraDX-simulations
9ff0e3fa509597c4e1160818a4ebe174109b27b1
[ "Apache-2.0" ]
4
2021-08-12T21:33:26.000Z
2022-03-04T22:51:33.000Z
analysis/XYKComparison.ipynb
galacticcouncil/HydraDX-simulations
9ff0e3fa509597c4e1160818a4ebe174109b27b1
[ "Apache-2.0" ]
31
2021-10-31T20:18:57.000Z
2022-03-25T16:01:41.000Z
analysis/XYKComparison.ipynb
galacticcouncil/HydraDX-simulations
9ff0e3fa509597c4e1160818a4ebe174109b27b1
[ "Apache-2.0" ]
4
2021-08-13T06:59:59.000Z
2021-12-13T17:47:57.000Z
165.382022
37,256
0.893245
[ [ [ "## Omnipool Slippage", "_____no_output_____" ], [ "If $p$ is the effective price and $p_i^j$ is the spot price, we compute effective slippage as\n$$\n\\frac{p}{p_i^j} - 1\n$$\n\nNote that $C = \\frac{Q_2}{Q_1}$, and $V = \\frac{\\Delta R_1}{R_1}$.\n\nWe get\n$$\nS = \\frac{1}{V}\\frac{C(VR_1 - f_T)(1 - f_P)}{C(R_1 + VR_1 - f_T) + (VR_1 - f_T)(1 - f_P)}(1 - f_A) - 1\n$$", "_____no_output_____" ], [ "### $f_T$ negligible compared to transaction size\n$$\nS = \\frac{1 - f_P}{1 + V + \\frac{V}{C}(1 - f_P)}(1 - f_A) - 1\n$$", "_____no_output_____" ], [ "### $f_P = f_A$\n$$\nS = \\frac{(1 - f_P)^2}{1 + V + \\frac{V}{C}(1 - f_P)} - 1\n$$", "_____no_output_____" ], [ "## Slippage for XYK pool\nWe define slippage as\n$$\nS = \\frac{p}{p_i^j} - 1\n$$", "_____no_output_____" ], [ "In an XYK pool with the fee deducted from the token leaving the pool, we have\n$$\n\\Delta R_2 = R_2\\frac{-\\Delta R_1}{R_1 + \\Delta R_1}(1 - f)\n$$", "_____no_output_____" ], [ "Thus\n$$\np = \\frac{R_2}{R_1 + \\Delta R_1}(1 - f)\\\\\np_1^2 = \\frac{R_2}{R_1}\n$$", "_____no_output_____" ], [ "So $S = \\frac{R_1}{R_1 + \\Delta R_1}(1 - f) - 1 = \\frac{-\\Delta R_1}{R_1} - f\\frac{R_1}{R_1 + \\Delta R_1}= -V_1 - f\\frac{1}{1 + V_1}$", "_____no_output_____" ], [ "## Effect of multiple tokens on XYK pool slippage\nSuppose we have a collection of xyk pools for $n$ tokens. We will denote by $R_i^j$ the amount of asset $i$ in the $i \\longleftrightarrow j$ pool.\n\nThen in an $i \\to j$ swap, we have $S_i^j = -\\frac{\\Delta R_i}{R_i^j} - f\\frac{R_i^j}{R_i^j + \\Delta R_1}$", "_____no_output_____" ], [ "We will make the simplfying assumption that $R_i^j = \\frac{R_i}{n - 1}$. In many ways this is the best case for a collection of xyk pools, since smaller liquidity pools dominate the slippage calculation, so spreading the liquidity of asset $i$ evenly throughout the pools is ideal.", "_____no_output_____" ], [ "Then\n$$\nS_i^j = -\\frac{\\Delta R_i}{R_i^j} - f\\frac{R_i^j}{R_i^j + \\Delta R_1} = -(n-1)\\frac{\\Delta R_i}{R_i} - f\\frac{R_i}{R_i + (n - 1)\\Delta R_i}\n= -(n-1)V_i - f\\frac{1}{1 + (n - 1)V_i}\n$$", "_____no_output_____" ], [ "## XYK vs Omnipool slippage", "_____no_output_____" ], [ "Compare this to the slippage calculation for Omnipool under similar assumptions:\n$$\nS_i^j = \\frac{(1 - f/2)^2}{1 + V_i + V_i(1 - f/2)} - 1\n\\approx \\frac{1 - f}{1 + V_i + V_i(1 - f/2)} - 1\n= \\frac{1}{1 + V_i + V_i(1 - f/2)} - 1 - \\frac{f}{1 + V_i + V_i(1 - f/2)}\\\\\n= \\frac{(-2 + f/2)V_i }{1 + (2-f/2)V_i} - f\\frac{1}{1 + (2-f/2)V_i}\n$$", "_____no_output_____" ], [ "### Ignore fees\nThen we get that for xyk,\n$$\nS_i^j = -(n - 1)V_i\n$$\nwhile for Omnipool\n$$\nS_i^j = \\frac{-2V_i }{1 + 2V_i}\n$$", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pylab as plt\n\n### Graph effective slippage\ndef slippage_omnipool(v):\n #return -2*v/(1 + 2*v)\n return 2*v/(1 + 2*v)\ndef slippage_xyk(v, n):\n #return -(n-1)*v\n return (n-1)*v\n\nstep_size = 0.001\nV_max = 0.1\nV = [step_size * i for i in range(1,int(V_max/step_size))]\nfig, ax = plt.subplots()\n\nOmnipool_slippage = [slippage_omnipool(v) for v in V]\nax.plot(V, Omnipool_slippage, label='Omnipool')\n\nN = 5\nfor n in range(2, N+1):\n \n xyk_slippage = [slippage_xyk(v, n) for v in V]\n\n ax.plot(V, xyk_slippage, label='n = ' + str(n))\n\n\n\nax.set(xlabel='Trade size divided by Liquidity', ylabel='Slippage', autoscale_on=True,\n title='Slippage Omnipool vs XYK')\nax.grid()\nax.legend()\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
ecfb73f1802aa57660a10683871fb4461fd8a8f5
423,366
ipynb
Jupyter Notebook
assign1ImageProcessing.ipynb
PeterHassaballah/ImageProcessingTask1
af0b8fa1376d38ae1d8cc3e30335577b4da0dc53
[ "MIT" ]
null
null
null
assign1ImageProcessing.ipynb
PeterHassaballah/ImageProcessingTask1
af0b8fa1376d38ae1d8cc3e30335577b4da0dc53
[ "MIT" ]
null
null
null
assign1ImageProcessing.ipynb
PeterHassaballah/ImageProcessingTask1
af0b8fa1376d38ae1d8cc3e30335577b4da0dc53
[ "MIT" ]
null
null
null
1,263.779104
132,386
0.940931
[ [ [ "<a href=\"https://colab.research.google.com/github/PeterHassaballah/ImageProcessingTask1/blob/master/assign1ImageProcessing.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import cv2\nimport numpy as np\nfrom math import *\nimport matplotlib.pylab as plt\nfrom PIL import Image\nfrom google.colab.patches import cv2_imshow", "_____no_output_____" ], [ "imgPath = './Moon.jpg'\nimg = cv2.imread(imgPath, cv2.IMREAD_GRAYSCALE)\ncv2_imshow(img)", "_____no_output_____" ], [ "#I impemented cv2 Discrete fourier transform then refined it using numpy Fast fourier transform\ndef get_dft(img):\n dft_A = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT|cv2.DFT_SCALE)\n dft_A = np.fft.fftshift(dft_A)\n return dft_A", "_____no_output_____" ], [ "def get_butter(dimg, order=3):\n dft4img=dimg\n h, w = dft4img.shape[0], dft4img.shape[1]\n stopband=10\n #coordinates to the center\n P = h/2\n Q = w/2\n dst = np.zeros((h, w, 2), np.float64)\n for i in range(h):\n for j in range(w):\n r2 = float((i-P)**2+(j-Q)**2)\n if r2 == 0:\n r2 = 1.0\n dst[i,j] = 1/(1+(r2/stopband)**order)\n dst = np.float64(dst)\n resol = cv2.magnitude(dst[:,:,0], dst[:,:,1])\n # cv2_imshow(dst)\n # cv2_imshow(resol)\n return dst", "_____no_output_____" ], [ "def update_butter(img,dimg):\n \n bw_filter = get_butter(dimg)\n dst_complex = bw_filter * dimg\n dst_complex = cv2.idft(np.fft.ifftshift(dst_complex))\n dst = np.uint8(cv2.magnitude(dst_complex[:,:,0], dst_complex[:,:,1]))\n tmp = dst\n fin=get_dft(tmp)\n return tmp\n # cv2_imshow( dst)\n", "_____no_output_____" ], [ "#Low Pass butter worth filter\ndef butter_filter(img):\n #max kernel size \n max_ksize = max(img.shape[0], img.shape[1])\n #Discrete fourier transform image\n dft4img = get_dft(img)\n # cv2_imshow(dft4img)\n last_img=update_butter(img,dft4img)\n print (\"Reducing high frequency noise\")\n # cv2_imshow(last_img)\n return last_img", "_____no_output_____" ], [ "# fshift = get_dft(img)\nout_img=butter_filter(img)\n#to get high pass subtract the image array from the low pass array \ncv2_imshow(out_img)\nz= np.array(img) - np.array(out_img)\ncv2_imshow(z)\n", "Reducing high frequency noise\n" ], [ "", "_____no_output_____" ], [ "def highPass(image, order, d0, constant ):\n\n fshift = np.fft.fftshift(image)\n f = np.fft.fft(fshift)\n\n rows, cols = f.shape\n\n H = np.zeros(image.shape)\n\n for i in range(-int(rows/2), int(rows/2)):\n for j in range(-int(cols/2), int(cols/2)):\n\n distance = sqrt((i*i + j*j))\n if distance == 0:\n value = 1/(1 + (d0 ** (2 * order)))\n else:\n value = 1/(1 + ((d0 / distance) ** (2 * order)))\n\n H[i, j] = (constant -1) + value\n\n resImage = np.multiply(f, H)\n\n ifo = np.fft.ifft(resImage)\n ifshift = np.fft.ifftshift(ifo.real)\n\n res = Image.fromarray(ifshift)\n res = res.convert(\"L\")\n marwan=ifshift\n cv2_imshow(marwan)\n\n \n\n\n# im = cv2.imread(\"Sphinx.png\")\n# gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n# im2 = his_equal(gray)\n# imRes = Image.fromarray(im2)\n# imRes.save(\"Eq.jpg\")\n\n", "_____no_output_____" ], [ "im = cv2.imread(\"./Moon.jpg\")\ngray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\nhighPass(gray, 1, 50, 1.5)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfb75599b288ae73854c8a3abbb9fb8d7d724ee
12,433
ipynb
Jupyter Notebook
.ipynb_checkpoints/1231Grokking the alghorithms-checkpoint.ipynb
FairlyTales/Machine_Learning_Courses
8fdbe477c05670ec1bb4832df193a1c9f1c76a7e
[ "MIT" ]
null
null
null
.ipynb_checkpoints/1231Grokking the alghorithms-checkpoint.ipynb
FairlyTales/Machine_Learning_Courses
8fdbe477c05670ec1bb4832df193a1c9f1c76a7e
[ "MIT" ]
null
null
null
.ipynb_checkpoints/1231Grokking the alghorithms-checkpoint.ipynb
FairlyTales/Machine_Learning_Courses
8fdbe477c05670ec1bb4832df193a1c9f1c76a7e
[ "MIT" ]
null
null
null
31.238693
432
0.550551
[ [ [ "# 1 Big \"O\" notation, binary search algorihtm\n\nО показывает насколько наш алгоритм быстро работает. \n\n#### Вот самые частые виды О, от самого быстрого к самому медленному:\nО(log(n)) - ex: binary search, O(n) - ex: simple search, O(n * log(n)) - ex: fast sort, O(n ** 2) - ex: slow sort, O(n!) - ex: traveling salesperson. \n\n## Binary search\n\nИдея в том, что мы каждый раз проверяем среднее значение списка на соответствие искомому значению. Если ср.знач. больше чем искомое, то мы отбрасываем все элементы больше него, включая его самого. Если ср.знач. меньше искомого, то отбрасываем все элементы меньше него, включая его самого.\n\nВажно: список должен быть УПОРЯДОЧЕННЫМ, иначе этот метод поиска работать не будет.", "_____no_output_____" ] ], [ [ "def binary_search(list, item):\n \"\"\"Returns an index of the searched item in the list\"\"\"\n \n low = 0 # initiation of the low border of the list\n high = len(list) - 1 # initiation of the high border of the list\n \n while low < high: # run until there is only 1 element left in the list\n mid = (low + high) // 2 # // - деление БЕЗ остатка, т.к. индексы списка могут быть только int\n guess = list[mid] # присваиваем guess ЗНАЧЕНИЕ среднего элемента списка\n if guess > item: # guess is too high\n high = mid - 1\n if guess < item: # guess is too low\n low = mid + 1\n else: # if guess == item\n return mid\n \n return None # in case we didn`t find the searched item in the list\n\ntest_list = [1,3,5,7,9,11]\ntest_item = 7\n\nbinary_search(test_list, test_item)", "_____no_output_____" ] ], [ [ "# 2 Selection sort algorithm, linked list vs array\n\nLinked list - ячейки памяти в каждой из которых хранится значение и адрес следующей ячейки, их легко расширять, но по ним неудобно искать элементы.\n\nArray - заранее определённый участок памяти под хранение элементов, в нём легко искать, но он занимает место даже когда пуст и нужно заранее знать сколько ячеек нам нужно.\n\nSelection sort algorithm consist of 2 \"functions\": find smallest/largest element & append it to the new array.\n\nHere is an example of this algorithm as 2 separate functions and as 1 function.", "_____no_output_____" ] ], [ [ "# task separated between 2 functions\ndef find_smallest(array):\n \"\"\"Finds the smallest element of the array\"\"\"\n \n smallest = array[0]\n smallest_index = 0\n \n for i in range(1, len(array)):\n if array[i] < smallest:\n smallest = array[i]\n smallest_index = i\n \n return smallest_index\n\n\ndef sort(array):\n \"\"\"Sorting function\"\"\"\n new_array = []\n \n for i in range(len(array)):\n smallest = find_smallest(array)\n new_array.append(array.pop(smallest))\n \n return new_array\n\nprint(sort([2,4,5,76,5,4,6,76,4,45,34528]), '\\n')\n\n\n# all in 1 function\ndef selection_sort_low_to_high(array):\n \"\"\"Sorts the array from low to high\"\"\"\n \n new_array = [] \n \n for i in range(len(array)):\n smallest = array[0]\n smallest_index = 0\n for j in range(1, len(array)):\n if array[j] < smallest:\n smallest = array[j]\n smallest_index = j\n new_array.append(array.pop(smallest_index))\n \n return new_array\n \nprint(selection_sort_low_to_high([2,4,5,76,5,4,6,76,4,45,34528]))", "[2, 4, 4, 4, 5, 5, 6, 45, 76, 76, 34528] \n\n[2, 4, 4, 4, 5, 5, 6, 45, 76, 76, 34528]\n" ] ], [ [ "# 3 Recursion\n\nRecursion - function that calls itself.\n\nAll function calls go onto the call stack.\n\nIf the stack gets way too large we can run out of RAM.", "_____no_output_____" ] ], [ [ "def recursion(i):\n \"\"\"Пример рекурсионной функции\"\"\"\n print(i) \n if i <= 0:\n return # \"break the loop\" condition\n else:\n recursion(i-1) # function calls itself\n \nrecursion(2)", "2\n1\n0\n" ] ], [ [ "Важный момент: когда мы открываем функцию в функции (во время рекурсии) функция которая вызвала функцию остаётся в состоянии \"паузы\" до завершения вызванной функции. Т.е. получается такая цепочка функций каждая из которых ждёт пока закончится вызванная ей функция.\n\nИ когда эта последняя из вызванных функций завершается и возвращает значение то функция вызвавшая её продолжает своё выполнение (что-то делает и затем тоже возвращает значение). И эта цепочка функций начинает \"уменьшаться\", пока последняя функция (которая начала рекурсию) не вернёт значение и её вызов не будет завершён.\n\nЭто означает что КАЖДАЯ из этих функций будет находиться в памяти пока идёт рекурсия.Что может быть ОЧЕНЬ затратно по ресурсам системы. Поэтому с рекурсиями нужно быть осторожным.", "_____no_output_____" ] ], [ [ "def factorial(x):\n \"\"\"Функция рассчёта факториала\"\"\"\n if x == 1:\n return x\n else:\n return (x * factorial(x-1)) # recursive\n \nfactorial(3)", "_____no_output_____" ] ], [ [ "# 4 Quicksort algorithm, divide-and-counquer principle\n\nDivide-and-counquer principle:\n\n 1. figure out a simple case of the problem (найти решение более простой версии задачи)\n\n 2. figure out how to reduce the problem and get it to the simple case (придумать как уменьшить/сократить задачу так, чтобы оставить от неё только простую версию, которую мы уже решили).\n\n#### Quicksort algorithm\n\nИдея алгоритма быстрой сортировки в том, что мы выбираем какой-то элемент массива и переносим все остальные элементы либо влево/вправо если они меньше выбранного либо вправо/влево если они больше выбранного. Затем в каждом из этих подмассивов делаем то же самое - выбираем один элемент и распределяем остальные элементы подмассива по его сторонам в зависимости от того больше они или меньше чем выбранный.\n\nВ результате мы приходим к тому, что в наших подмассивах остаётся меньше двух элементов. А массивы с числом элементов 0 и/или 1 уже отсортированны (ну, или их уже НЕ надо сортировать).\n\nВыбор элемента вокруг которого будет проводится перераспределение массива очень сильно влияет на скорость работы алгоритма.\n\nВот так выглядит один из вариантов этого алгоритма в коде:", "_____no_output_____" ] ], [ [ "import numpy as np\ndef quicksort(array):\n \n if len(array) < 2: # если массив меньше двух (равен 0 или 1) то сортировка окончена\n return array\n else:\n # выберем в качестве элемента вокруг которого будет проводится сортировка (pivot)\n # первый элемент массива (и в дальнейшем, подмассива)\n pivot = array[0]\n \n # используем генераторы для создания двух подмассивов\n smaller = [i\n for i in array[0:]\n if i < pivot]\n bigger = [i\n for i in array[0:]\n if i > pivot]\n \n return (quicksort(smaller) + [pivot] + quicksort(bigger))\n \na = quicksort([10,9,8,7,6,5,4,3,2,1])\na", "_____no_output_____" ] ], [ [ "# 5 - hash tables (dictionaries in python)\n\n# 6 - Graphs, Breadth-first search algorithm (finds the path through graph with the fewest number of segments)", "_____no_output_____" ], [ "# 7. Dijkstra algorithm (finds the fastest path through graph)\n\nBreadth search finds the $shortest$ path through graph, while Dijkstra's algorithm finds the $fastest$ (because if we add weights to the edges we will get thatshortest is not necessary the fastest). Beware that Dijkstra's algoritm works only with directed graphs (graphs without cycles and/or undirected edges) and if graph has only possitive weights. For graphs with negative weights Bellman-Ford algorithm should be used.\n\nIt consists of 4 steps:\n\n1. Find the edge with lowest edge weight (node with the cheapest path to it).\n\n2. Update the costs of the neighbors of the node on the end of this edge.\n\n3. Repeat until it`s done for every node in the graph (starting from the start again).\n\n4. Calculate final path.\n\n# 8. Greedy algorithms\n\n\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
ecfb7b747f31e065f166239503732d2babb4f6dd
100,420
ipynb
Jupyter Notebook
ADS-Summer2019/libraries.ipynb
peperaj/XBUS-507-01.Applied_Data_Science
0928b9aa000bfaabef13a3a59c0c80c68307013b
[ "MIT" ]
9
2019-06-21T21:38:46.000Z
2022-01-11T18:16:22.000Z
ADS-Summer2019/libraries.ipynb
peperaj/XBUS-507-01.Applied_Data_Science
0928b9aa000bfaabef13a3a59c0c80c68307013b
[ "MIT" ]
3
2019-08-24T18:56:27.000Z
2020-01-04T19:26:32.000Z
ADS-Summer2019/libraries.ipynb
peperaj/XBUS-507-01.Applied_Data_Science
0928b9aa000bfaabef13a3a59c0c80c68307013b
[ "MIT" ]
13
2018-09-28T21:39:41.000Z
2022-01-11T18:16:25.000Z
36.609552
202
0.3715
[ [ [ "# 1.0 Import Libraries", "_____no_output_____" ], [ "### 1.0 Import Libraries", "_____no_output_____" ] ], [ [ "# Load Pandas and Sqlite libraries\nimport pandas as pd\nimport sqlite3 as sql\nimport numpy as np\n", "_____no_output_____" ] ], [ [ "### 1.1 Create Pandas Dataframe\n", "_____no_output_____" ] ], [ [ "# df = pd.read_csv(\"USDA_Foodie.csv\")\ndf = pd.read_csv(\"Checkouts.csv\")\n\n\n", "/Users/raymond/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3049: DtypeWarning: Columns (1) have mixed types. Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n" ] ], [ [ "# 2 Data Exploration\n", "_____no_output_____" ], [ "### 2.0 View Feature Names and First Observations", "_____no_output_____" ] ], [ [ "# Show feature names and first 10 observations\ndf.head(10)", "_____no_output_____" ] ], [ [ "### 2.1 View Data Shape", "_____no_output_____" ] ], [ [ "#Show the number of rows and columns\ndf.shape", "_____no_output_____" ] ], [ [ "### 2.2 Describe Basic Stats on Data", "_____no_output_____" ] ], [ [ "#Show stats on the data\ndf.describe()", "_____no_output_____" ] ], [ [ "### 2.3 Select Number of Observations ", "_____no_output_____" ] ], [ [ "#Select Number of Observations and create new dataframe\ndf2 = df.iloc[:84617]\ndf2", "_____no_output_____" ] ], [ [ "### 2.4 Count Instances of Product ID", "_____no_output_____" ] ], [ [ "#Find all unique products and the number of times they appear (were purchased) in the dataset\ndf2['BibNumber'].value_counts()\n", "_____no_output_____" ], [ "#Check for null values in product_id feature\ndf2[df2['BibNumber'].isnull()].head(2)", "_____no_output_____" ], [ "#Drop all duplicate rows from the data\ndf2.drop_duplicates()", "_____no_output_____" ], [ "df2.dropna()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ecfb8264d27d6bcf985037a96132af3a7c892dd4
130,444
ipynb
Jupyter Notebook
Fusion_Industry_population_salary_geography.ipynb
anneschneider77/DA_Training_AS_Projet
edc66539e87a667def94dad9cc4d427620a185d2
[ "MIT" ]
null
null
null
Fusion_Industry_population_salary_geography.ipynb
anneschneider77/DA_Training_AS_Projet
edc66539e87a667def94dad9cc4d427620a185d2
[ "MIT" ]
null
null
null
Fusion_Industry_population_salary_geography.ipynb
anneschneider77/DA_Training_AS_Projet
edc66539e87a667def94dad9cc4d427620a185d2
[ "MIT" ]
null
null
null
34.711016
201
0.37715
[ [ [ "# le but de ce notebook est de fusionner les 4 datasets ensemble", "_____no_output_____" ] ], [ [ "# import des packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "# changement des datasets", "_____no_output_____" ] ], [ [ "# industry\nindustry = pd.read_csv('base_etablissement_par_tranche_effectif.csv')\nprint('shape de industry : ', industry.shape)\nindustry.head()", "shape de industry : (36681, 14)\n" ], [ "new_names = {'E14TST' : 'Total_ent',\n 'E14TS0ND' : 'ND_empl',\n 'E14TS1' : 'empl_1à5',\n 'E14TS6' : 'empl_6à9',\n 'E14TS10' : 'empl_10à19',\n 'E14TS20' : 'empl_20à49',\n 'empl_50à99' : 'empl_20à49',\n 'E14TS100' : 'empl_100à199',\n 'E14TS200' : 'empl_200à499',\n 'E14TS500' : 'empl_+500'}\nindustry = industry.rename(new_names, axis = 1)\nindustry.head()", "_____no_output_____" ], [ "industry.info() #pas de NaN", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 36681 entries, 0 to 36680\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 CODGEO 36681 non-null object\n 1 LIBGEO 36681 non-null object\n 2 REG 36681 non-null int64 \n 3 DEP 36681 non-null object\n 4 Total_ent 36681 non-null int64 \n 5 ND_empl 36681 non-null int64 \n 6 empl_1à5 36681 non-null int64 \n 7 empl_6à9 36681 non-null int64 \n 8 empl_10à19 36681 non-null int64 \n 9 empl_20à49 36681 non-null int64 \n 10 E14TS50 36681 non-null int64 \n 11 empl_100à199 36681 non-null int64 \n 12 empl_200à499 36681 non-null int64 \n 13 empl_+500 36681 non-null int64 \ndtypes: int64(11), object(3)\nmemory usage: 3.9+ MB\n" ] ], [ [ "##Chargement et nettoyage du dataset name_geographic_information", "_____no_output_____" ] ], [ [ "geography2 = pd.read_csv('name_geographic_information.csv')\nprint('Shape geography', geography2.shape)\ngeography2.head(5)", "Shape geography (36840, 14)\n" ], [ "# Ajouter les codes et libellés des 18 nouvelles Régions\n# Charger le fichier avec la nomenclature des 18 nouvelles régions\nold_to_newREG = pd.read_csv('anciennes-nouvelles-regions.csv', sep = ';')\nold_to_newREG.head()", "_____no_output_____" ], [ "# Ajout de la nouvelles taxonomie avec 18 Régions\ngeography2 = old_to_newREG.merge(geography2, left_on = \"REG\", right_on = \"code_région\", how = \"inner\")\nprint(geography2.shape)\ngeography2.head()\ngeography2.info()", "(36826, 17)\n<class 'pandas.core.frame.DataFrame'>\nInt64Index: 36826 entries, 0 to 36825\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 REG 36826 non-null int64 \n 1 new_REG 36826 non-null int64 \n 2 lib_new_REG 36826 non-null object \n 3 EU_circo 36826 non-null object \n 4 code_région 36826 non-null int64 \n 5 nom_région 36826 non-null object \n 6 chef.lieu_région 36826 non-null object \n 7 numéro_département 36826 non-null object \n 8 nom_département 36826 non-null object \n 9 préfecture 36826 non-null object \n 10 numéro_circonscription 36826 non-null int64 \n 11 nom_commune 36826 non-null object \n 12 codes_postaux 36826 non-null object \n 13 code_insee 36826 non-null int64 \n 14 latitude 33911 non-null float64\n 15 longitude 33999 non-null object \n 16 éloignement 33878 non-null float64\ndtypes: float64(2), int64(5), object(10)\nmemory usage: 5.1+ MB\n" ], [ "\n\nrename = {\"new_REG\" : \"New_code_région\",\n \"lib_new_REG\" : \"New_nom_région\"}\ngeo3 = geography2.rename(rename, axis = 1)\nprint(geo3.shape)\ngeo3.head()", "(36826, 17)\n" ], [ "# 1 - remplaçons les ',' dans longitude par '.'\n# 2 - supprimons les lignes où longitude est '-'\n\ngeo3['longitude'] = geo3['longitude'].apply(lambda x : str(x).replace(',','.'))\n\nlong_false = geo3['longitude']=='-'\ngeo3.drop(geo3[long_false].index, inplace = True)\n\ngeo3['longitude'] = geo3['longitude'].astype(float)\ngeo3.info()\n", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 36762 entries, 0 to 36825\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 REG 36762 non-null int64 \n 1 New_code_région 36762 non-null int64 \n 2 New_nom_région 36762 non-null object \n 3 EU_circo 36762 non-null object \n 4 code_région 36762 non-null int64 \n 5 nom_région 36762 non-null object \n 6 chef.lieu_région 36762 non-null object \n 7 numéro_département 36762 non-null object \n 8 nom_département 36762 non-null object \n 9 préfecture 36762 non-null object \n 10 numéro_circonscription 36762 non-null int64 \n 11 nom_commune 36762 non-null object \n 12 codes_postaux 36762 non-null object \n 13 code_insee 36762 non-null int64 \n 14 latitude 33847 non-null float64\n 15 longitude 33935 non-null float64\n 16 éloignement 33814 non-null float64\ndtypes: float64(3), int64(5), object(9)\nmemory usage: 5.0+ MB\n" ], [ "#Elimination des lines NaN\ngeographie = geo3.dropna(axis = 0, how = 'any')\ngeographie.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 33814 entries, 140 to 36825\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 REG 33814 non-null int64 \n 1 New_code_région 33814 non-null int64 \n 2 New_nom_région 33814 non-null object \n 3 EU_circo 33814 non-null object \n 4 code_région 33814 non-null int64 \n 5 nom_région 33814 non-null object \n 6 chef.lieu_région 33814 non-null object \n 7 numéro_département 33814 non-null object \n 8 nom_département 33814 non-null object \n 9 préfecture 33814 non-null object \n 10 numéro_circonscription 33814 non-null int64 \n 11 nom_commune 33814 non-null object \n 12 codes_postaux 33814 non-null object \n 13 code_insee 33814 non-null int64 \n 14 latitude 33814 non-null float64\n 15 longitude 33814 non-null float64\n 16 éloignement 33814 non-null float64\ndtypes: float64(3), int64(5), object(9)\nmemory usage: 4.6+ MB\n" ] ], [ [ "## fusion de Industry et de geography", "_____no_output_____" ] ], [ [ "# pour fusionner les deux DataFrame sur CODGEO et code_insee il faut exclure les communes en Corse des deux datasets", "_____no_output_____" ] ], [ [ "industry = industry[industry['REG']!=94]\ngeographie = geographie[geographie['code_région']!=94]\n", "_____no_output_____" ], [ "industry.head()\nindustry = industry.rename({'CODGEO': 'code_insee'}, axis =1)\nindustry['code_insee'] = industry['code_insee'].astype(int)\nindustry.info()\n", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 36321 entries, 0 to 36680\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 code_insee 36321 non-null int32 \n 1 LIBGEO 36321 non-null object\n 2 REG 36321 non-null int64 \n 3 DEP 36321 non-null object\n 4 Total_ent 36321 non-null int64 \n 5 ND_empl 36321 non-null int64 \n 6 empl_1à5 36321 non-null int64 \n 7 empl_6à9 36321 non-null int64 \n 8 empl_10à19 36321 non-null int64 \n 9 empl_20à49 36321 non-null int64 \n 10 E14TS50 36321 non-null int64 \n 11 empl_100à199 36321 non-null int64 \n 12 empl_200à499 36321 non-null int64 \n 13 empl_+500 36321 non-null int64 \ndtypes: int32(1), int64(11), object(2)\nmemory usage: 4.0+ MB\n" ], [ "geographie.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 33503 entries, 140 to 36465\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 REG 33503 non-null int64 \n 1 New_code_région 33503 non-null int64 \n 2 New_nom_région 33503 non-null object \n 3 EU_circo 33503 non-null object \n 4 code_région 33503 non-null int64 \n 5 nom_région 33503 non-null object \n 6 chef.lieu_région 33503 non-null object \n 7 numéro_département 33503 non-null object \n 8 nom_département 33503 non-null object \n 9 préfecture 33503 non-null object \n 10 numéro_circonscription 33503 non-null int64 \n 11 nom_commune 33503 non-null object \n 12 codes_postaux 33503 non-null object \n 13 code_insee 33503 non-null int64 \n 14 latitude 33503 non-null float64\n 15 longitude 33503 non-null float64\n 16 éloignement 33503 non-null float64\ndtypes: float64(3), int64(5), object(9)\nmemory usage: 4.6+ MB\n" ], [ "fusion = industry.merge(right = geographie, on = 'code_insee', how = 'left')\nprint(fusion.shape)\nfusion.head()", "(36432, 30)\n" ], [ "\nfusion = fusion.rename({'E14TS50' : 'empl_50à99'}, axis = 1)\n\n\nrename = {\"new_REG_x\" : \"New_code_région\", \"lib_new_REG_x\" : \"New_nom_région\"}\nfusion = fusion.rename(rename, axis = 1)\nfusion.info()\n", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 36432 entries, 0 to 36431\nData columns (total 30 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 code_insee 36432 non-null int32 \n 1 LIBGEO 36432 non-null object \n 2 REG_x 36432 non-null int64 \n 3 DEP 36432 non-null object \n 4 Total_ent 36432 non-null int64 \n 5 ND_empl 36432 non-null int64 \n 6 empl_1à5 36432 non-null int64 \n 7 empl_6à9 36432 non-null int64 \n 8 empl_10à19 36432 non-null int64 \n 9 empl_20à49 36432 non-null int64 \n 10 empl_50à99 36432 non-null int64 \n 11 empl_100à199 36432 non-null int64 \n 12 empl_200à499 36432 non-null int64 \n 13 empl_+500 36432 non-null int64 \n 14 REG_y 33480 non-null float64\n 15 New_code_région 33480 non-null float64\n 16 New_nom_région 33480 non-null object \n 17 EU_circo 33480 non-null object \n 18 code_région 33480 non-null float64\n 19 nom_région 33480 non-null object \n 20 chef.lieu_région 33480 non-null object \n 21 numéro_département 33480 non-null object \n 22 nom_département 33480 non-null object \n 23 préfecture 33480 non-null object \n 24 numéro_circonscription 33480 non-null float64\n 25 nom_commune 33480 non-null object \n 26 codes_postaux 33480 non-null object \n 27 latitude 33480 non-null float64\n 28 longitude 33480 non-null float64\n 29 éloignement 33480 non-null float64\ndtypes: float64(7), int32(1), int64(11), object(11)\nmemory usage: 8.5+ MB\n" ] ], [ [ "## le DataFrame fusion comporte des lignes avec des NaN.\n## Si ces lignes sont supprimées, quel est l'impact ssur les donnéesdsponibles ? ", "_____no_output_____" ] ], [ [ "\n\ndf1 = fusion[fusion.isna().any(axis=1)]\nprint(\"en supprimant les NA de fusion,\", df1.shape[0], \"lignes seront supprimées\")\ndf1_sorted = df1.sort_values(by = 'Total_ent', ascending = False)\n\n# Top 10 des villes dont les données seront supprimées lors de l'élimination des NaN de Fusion\ndf1_sorted.head(10)\ndf1.info()", "en supprimant les NA de fusion, 2952 lignes seront supprimées\n<class 'pandas.core.frame.DataFrame'>\nInt64Index: 2952 entries, 26 to 36431\nData columns (total 30 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 code_insee 2952 non-null int32 \n 1 LIBGEO 2952 non-null object \n 2 REG_x 2952 non-null int64 \n 3 DEP 2952 non-null object \n 4 Total_ent 2952 non-null int64 \n 5 ND_empl 2952 non-null int64 \n 6 empl_1à5 2952 non-null int64 \n 7 empl_6à9 2952 non-null int64 \n 8 empl_10à19 2952 non-null int64 \n 9 empl_20à49 2952 non-null int64 \n 10 empl_50à99 2952 non-null int64 \n 11 empl_100à199 2952 non-null int64 \n 12 empl_200à499 2952 non-null int64 \n 13 empl_+500 2952 non-null int64 \n 14 REG_y 0 non-null float64\n 15 New_code_région 0 non-null float64\n 16 New_nom_région 0 non-null object \n 17 EU_circo 0 non-null object \n 18 code_région 0 non-null float64\n 19 nom_région 0 non-null object \n 20 chef.lieu_région 0 non-null object \n 21 numéro_département 0 non-null object \n 22 nom_département 0 non-null object \n 23 préfecture 0 non-null object \n 24 numéro_circonscription 0 non-null float64\n 25 nom_commune 0 non-null object \n 26 codes_postaux 0 non-null object \n 27 latitude 0 non-null float64\n 28 longitude 0 non-null float64\n 29 éloignement 0 non-null float64\ndtypes: float64(7), int32(1), int64(11), object(11)\nmemory usage: 703.4+ KB\n" ] ], [ [ "# mesurons quel sera l'impact dela suppression des lignes NaN de fusion sur la représentatitivité des Régions", "_____no_output_____" ] ], [ [ "print(\"nbr d'entreprises supprimées : \", df1['Total_ent'].sum())\n\nerase_nbr_communes = df1.value_counts('REG_x').rename_axis('Numero Region').to_frame('Nbr communes erased')\n\nTotal_Nbr_communes = fusion.value_counts('REG_x').rename_axis('Numero Region').to_frame('Nbr communes total')\n\n\nresultat = Total_Nbr_communes.merge(erase_nbr_communes, how = 'left', left_index = True, right_index = True)\nresultat\n", "nbr d'entreprises supprimées : 917953\n" ], [ "print(\"lors de la suppression des NaN de fusion, toules les communes d'Outre-mer seront perdues et environ 10% des lignes par région\")\n", "lors de la suppression des NaN de fusion, toules les communes d'Outre-mer seront perdues et environ 10% des lignes par région\n" ], [ "fusion_1 = fusion.dropna(axis = 0, how = \"any\")\nfusion_1.info()\n# Fusion_1 est le résultat nettoyé de la fusion entre le dataset industry et le dataset geographie", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 33480 entries, 0 to 36302\nData columns (total 30 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 code_insee 33480 non-null int32 \n 1 LIBGEO 33480 non-null object \n 2 REG_x 33480 non-null int64 \n 3 DEP 33480 non-null object \n 4 Total_ent 33480 non-null int64 \n 5 ND_empl 33480 non-null int64 \n 6 empl_1à5 33480 non-null int64 \n 7 empl_6à9 33480 non-null int64 \n 8 empl_10à19 33480 non-null int64 \n 9 empl_20à49 33480 non-null int64 \n 10 empl_50à99 33480 non-null int64 \n 11 empl_100à199 33480 non-null int64 \n 12 empl_200à499 33480 non-null int64 \n 13 empl_+500 33480 non-null int64 \n 14 REG_y 33480 non-null float64\n 15 New_code_région 33480 non-null float64\n 16 New_nom_région 33480 non-null object \n 17 EU_circo 33480 non-null object \n 18 code_région 33480 non-null float64\n 19 nom_région 33480 non-null object \n 20 chef.lieu_région 33480 non-null object \n 21 numéro_département 33480 non-null object \n 22 nom_département 33480 non-null object \n 23 préfecture 33480 non-null object \n 24 numéro_circonscription 33480 non-null float64\n 25 nom_commune 33480 non-null object \n 26 codes_postaux 33480 non-null object \n 27 latitude 33480 non-null float64\n 28 longitude 33480 non-null float64\n 29 éloignement 33480 non-null float64\ndtypes: float64(7), int32(1), int64(11), object(11)\nmemory usage: 7.8+ MB\n" ] ], [ [ "## ajout du calcul de la distance entre la commune et le chef_lieu de région, ou n'importe qu'elle autre commune", "_____no_output_____" ] ], [ [ "import numpy as np\n\ndef spherical_dist(pos1, pos2, r=3958.75 * 1.609):\n pos1 = pos1 * np.pi / 180\n pos2 = pos2 * np.pi / 180\n cos_lat1 = np.cos(pos1[..., 0])\n cos_lat2 = np.cos(pos2[..., 0])\n cos_lat_d = np.cos(pos1[..., 0] - pos2[..., 0])\n cos_lon_d = np.cos(pos1[..., 1] - pos2[..., 1])\n return r * np.arccos(cos_lat_d - cos_lat1 * cos_lat2 * (1 - cos_lon_d))\n\n\npositions1 = fusion_1[['latitude', 'longitude']].values\npositions2 = fusion_1[fusion_1['nom_commune'] == 'Paris'][['latitude', 'longitude']].values[0, :]\n\n\ndistances_to_paris = spherical_dist(positions1, positions2)", "_____no_output_____" ] ], [ [ "## la prochaine étape ici sera de choisir les régions à étudier (en fonction du dataset salary) et les communes\n## entre lesquelles la distance devra être calculée. ", "_____no_output_____" ] ], [ [ "# chargement de population", "_____no_output_____" ], [ "print(\"il y a : \", len(population['LIBGEO'].unique()), \"communes couvertes dans le dataset population\")", "il y a : 33452 communes couvertes dans le dataset population\n" ], [ "population = pd.read_csv(\"population.csv\")\nprint(population.shape)\npopulation.head(5)\n", "C:\\Users\\A1BY3ZZ\\Anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3146: DtypeWarning: Columns (1) have mixed types.Specify dtype option on import or set low_memory=False.\n has_raised = await self.run_ast_nodes(code_ast.body, cell_name,\n" ], [ "print(\"il y a : \", len(population['LIBGEO'].unique()), \"communes couvertes dans le dataset population\")", "_____no_output_____" ], [ "population = population.rename(renommage, axis = 1).drop(\"NIVGEO\", axis = 1)\n\npopulation.head(5)", "_____no_output_____" ], [ "rename = {'situation_familiale' : 'MOCO', 'age' : 'AGEQ80_17'}\npopulation = population.rename(rename, axis = 1)\npopulation.head()", "_____no_output_____" ], [ "population[\"class_age\"] = pd.cut(population[\"AGEQ80_17\"], bins = [0, 10, 20, 30, 40, 50, 60, 70, 80])\npopulation.head()", "_____no_output_____" ], [ "# Suppression de la région Corse (les code_insee des communes contiennent2A et 2B)\npopulation = population[population['code_insee'].astype(str).apply(lambda x: ('A' not in x) and ('B' not in x))]\n", "_____no_output_____" ], [ "# renommage des colonnes\npopulation['SEXE'] = population['SEXE'].replace({1: 'homme', 2: 'femme'})\npopulation['MOCO'] = population['MOCO'].replace({v: 'moco_'+ str(v) for v in population['MOCO'].unique()})\npopulation['AGEQ80_17'] = population['AGEQ80_17'].replace({v: 'age_'+ str(v) for v in population['AGEQ80_17'].unique()})\npopulation.head()", "_____no_output_____" ], [ "\npopulation = population.replace(to_replace = ['moco_moco_11', 'moco_moco_12', 'moco_moco_21', 'moco_moco_22',\n 'moco_moco_23', 'moco_moco_31', 'moco_moco_32'], value = ['Enf av 2parents', 'Enf av 1parent', 'Coupl ss Enf', 'Coupl av Enf',\n 'Cel av Enf', 'Adulte + du foyer', 'Adulte Seul'])\n\n\n\npopulation = population.replace(to_replace = ['age_age_0', 'age_age_5', 'age_age_10', 'age_age_15', 'age_age_20',\n 'age_age_25', 'age_age_30', 'age_age_35', 'age_age_40',\n 'age_age_45', 'age_age_50', 'age_age_55', 'age_age_60',\n 'age_age_65', 'age_age_70', 'age_age_75', 'age_age_80'], \n value = ['age_0', 'age_5', 'age_10', 'age_15', 'age_20',\n 'age_25', 'age_30', 'age_35', 'age_40',\n 'age_45', 'age_50', 'age_55', 'age_60',\n 'age_65', 'age_70', 'age_75', 'age_80'])\n\npopulation['AGEQ80_17'].unique()\n", "_____no_output_____" ] ], [ [ "# Création de dfs , une liqte qui contiendra tous les DataFrame donnant le NB d'habitant pour chaque valeur\n# des variables MOCO ; AGEQ80_17 et SEXE\n# le but étant d'obtenir autant de colonnes que de valeurs unique dans les 3 variables dans dfs\n# et de le fusionner avec dans un premier temps le Nbr Total d'habitants par commune (code_insee)\n# puis de fusionner le tout avec fusion_1, résultat nettoyé de la fusion entre le dataset industry et le dataset geographie", "_____no_output_____" ] ], [ [ "dfs = []\n\n# parcours les colonnes\nfor col in ['MOCO', 'AGEQ80_17', 'SEXE']:\n \n # parcours les valeurs uniques des colonnes\n for value in population[col].unique():\n \n df_temp = population[population[col] == value].groupby('code_insee').agg({'NB': sum})\n \n df_temp[value] = df_temp['NB']\n df_temp = df_temp.drop(['NB'], axis=1)\n \n dfs.append(df_temp)", "_____no_output_____" ], [ "# pd.contact permet de concaténer plusieurs DF entre eux () tous les df dans dfs ont les mêmes indices), \n# axis 1 , en 'ligne', ignore_index = False pour garder code_insee en index\npopulation_total = pd.concat(\n dfs, \n axis=1, \n ignore_index=False\n)\npopulation_total.head()", "_____no_output_____" ], [ "Total_Hab_Communes = population.groupby('code_insee').agg({'NB' : sum})\nTotal_Hab_Communes", "_____no_output_____" ], [ "# on concat population_total et Total_Hab_Communes, en lignes, en gardant code_insee comme index\npopulation_total = pd.concat([population_total, Total_Hab_Communes],\n axis = 1, ignore_index = False)\npopulation_total.info()", "<class 'pandas.core.frame.DataFrame'>\nIndex: 35870 entries, 1001 to 28267\nData columns (total 27 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Enf av 2parents 35868 non-null float64\n 1 Enf av 1parent 35869 non-null float64\n 2 Coupl ss Enf 35868 non-null float64\n 3 Coupl av Enf 35868 non-null float64\n 4 Cel av Enf 35868 non-null float64\n 5 Adulte + du foyer 35869 non-null float64\n 6 Adulte Seul 35868 non-null float64\n 7 age_0 35870 non-null int64 \n 8 age_5 35870 non-null int64 \n 9 age_10 35870 non-null int64 \n 10 age_15 35870 non-null int64 \n 11 age_20 35870 non-null int64 \n 12 age_25 35870 non-null int64 \n 13 age_30 35870 non-null int64 \n 14 age_35 35870 non-null int64 \n 15 age_40 35870 non-null int64 \n 16 age_45 35870 non-null int64 \n 17 age_50 35870 non-null int64 \n 18 age_55 35870 non-null int64 \n 19 age_60 35870 non-null int64 \n 20 age_65 35870 non-null int64 \n 21 age_70 35870 non-null int64 \n 22 age_75 35870 non-null int64 \n 23 age_80 35870 non-null int64 \n 24 homme 35870 non-null int64 \n 25 femme 35870 non-null int64 \n 26 NB 35870 non-null int64 \ndtypes: float64(7), int64(20)\nmemory usage: 7.7+ MB\n" ], [ "# il y a des NaN dans population total. pas plus de 2 lignes\nprint(\"Nbr total d'habitants perdus lors de la suppression des NaN :\", \n population_total[population_total.isna().any(axis = 1)]['NB'].sum())\n ", "Nbr tota d'habitants perdus lors de la suppression des NaN : 597\n" ], [ "population_total = population_total.dropna()\npopulation_total.head()\n# pour fusionner sur code_index population_total et fusion, ilfaut que l'index que population_total soit une colonne\n\npopulation_total['code_insee'] = population_total.index\npopulation_total = population_total.reset_index(drop = True)\npopulation_total.head()\npopulation_total.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 35866 entries, 0 to 35865\nData columns (total 28 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Enf av 2parents 35866 non-null float64\n 1 Enf av 1parent 35866 non-null float64\n 2 Coupl ss Enf 35866 non-null float64\n 3 Coupl av Enf 35866 non-null float64\n 4 Cel av Enf 35866 non-null float64\n 5 Adulte + du foyer 35866 non-null float64\n 6 Adulte Seul 35866 non-null float64\n 7 age_0 35866 non-null int64 \n 8 age_5 35866 non-null int64 \n 9 age_10 35866 non-null int64 \n 10 age_15 35866 non-null int64 \n 11 age_20 35866 non-null int64 \n 12 age_25 35866 non-null int64 \n 13 age_30 35866 non-null int64 \n 14 age_35 35866 non-null int64 \n 15 age_40 35866 non-null int64 \n 16 age_45 35866 non-null int64 \n 17 age_50 35866 non-null int64 \n 18 age_55 35866 non-null int64 \n 19 age_60 35866 non-null int64 \n 20 age_65 35866 non-null int64 \n 21 age_70 35866 non-null int64 \n 22 age_75 35866 non-null int64 \n 23 age_80 35866 non-null int64 \n 24 homme 35866 non-null int64 \n 25 femme 35866 non-null int64 \n 26 NB 35866 non-null int64 \n 27 code_insee 35866 non-null int64 \ndtypes: float64(7), int64(21)\nmemory usage: 7.7 MB\n" ], [ "fusion_1.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 33480 entries, 0 to 36302\nData columns (total 30 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 code_insee 33480 non-null int32 \n 1 LIBGEO 33480 non-null object \n 2 REG_x 33480 non-null int64 \n 3 DEP 33480 non-null object \n 4 Total_ent 33480 non-null int64 \n 5 ND_empl 33480 non-null int64 \n 6 empl_1à5 33480 non-null int64 \n 7 empl_6à9 33480 non-null int64 \n 8 empl_10à19 33480 non-null int64 \n 9 empl_20à49 33480 non-null int64 \n 10 empl_50à99 33480 non-null int64 \n 11 empl_100à199 33480 non-null int64 \n 12 empl_200à499 33480 non-null int64 \n 13 empl_+500 33480 non-null int64 \n 14 REG_y 33480 non-null float64\n 15 New_code_région 33480 non-null float64\n 16 New_nom_région 33480 non-null object \n 17 EU_circo 33480 non-null object \n 18 code_région 33480 non-null float64\n 19 nom_région 33480 non-null object \n 20 chef.lieu_région 33480 non-null object \n 21 numéro_département 33480 non-null object \n 22 nom_département 33480 non-null object \n 23 préfecture 33480 non-null object \n 24 numéro_circonscription 33480 non-null float64\n 25 nom_commune 33480 non-null object \n 26 codes_postaux 33480 non-null object \n 27 latitude 33480 non-null float64\n 28 longitude 33480 non-null float64\n 29 éloignement 33480 non-null float64\ndtypes: float64(7), int32(1), int64(11), object(11)\nmemory usage: 7.8+ MB\n" ] ], [ [ "## Fusionner total_population avec fusion_1 sur code_insee", "_____no_output_____" ] ], [ [ "ind_pop = fusion_1.merge(right = population_total, on = 'code_insee', how = 'left')\nind_pop.info()\nind_pop.groupby('nom_région').agg({'nom_commune': 'count', 'Total_ent' : 'sum', 'NB' : 'sum' })", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 33480 entries, 0 to 33479\nData columns (total 57 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 code_insee 33480 non-null int32 \n 1 LIBGEO 33480 non-null object \n 2 REG_x 33480 non-null int64 \n 3 DEP 33480 non-null object \n 4 Total_ent 33480 non-null int64 \n 5 ND_empl 33480 non-null int64 \n 6 empl_1à5 33480 non-null int64 \n 7 empl_6à9 33480 non-null int64 \n 8 empl_10à19 33480 non-null int64 \n 9 empl_20à49 33480 non-null int64 \n 10 empl_50à99 33480 non-null int64 \n 11 empl_100à199 33480 non-null int64 \n 12 empl_200à499 33480 non-null int64 \n 13 empl_+500 33480 non-null int64 \n 14 REG_y 33480 non-null float64\n 15 New_code_région 33480 non-null float64\n 16 New_nom_région 33480 non-null object \n 17 EU_circo 33480 non-null object \n 18 code_région 33480 non-null float64\n 19 nom_région 33480 non-null object \n 20 chef.lieu_région 33480 non-null object \n 21 numéro_département 33480 non-null object \n 22 nom_département 33480 non-null object \n 23 préfecture 33480 non-null object \n 24 numéro_circonscription 33480 non-null float64\n 25 nom_commune 33480 non-null object \n 26 codes_postaux 33480 non-null object \n 27 latitude 33480 non-null float64\n 28 longitude 33480 non-null float64\n 29 éloignement 33480 non-null float64\n 30 Enf av 2parents 12660 non-null float64\n 31 Enf av 1parent 12660 non-null float64\n 32 Coupl ss Enf 12660 non-null float64\n 33 Coupl av Enf 12660 non-null float64\n 34 Cel av Enf 12660 non-null float64\n 35 Adulte + du foyer 12660 non-null float64\n 36 Adulte Seul 12660 non-null float64\n 37 age_0 12660 non-null float64\n 38 age_5 12660 non-null float64\n 39 age_10 12660 non-null float64\n 40 age_15 12660 non-null float64\n 41 age_20 12660 non-null float64\n 42 age_25 12660 non-null float64\n 43 age_30 12660 non-null float64\n 44 age_35 12660 non-null float64\n 45 age_40 12660 non-null float64\n 46 age_45 12660 non-null float64\n 47 age_50 12660 non-null float64\n 48 age_55 12660 non-null float64\n 49 age_60 12660 non-null float64\n 50 age_65 12660 non-null float64\n 51 age_70 12660 non-null float64\n 52 age_75 12660 non-null float64\n 53 age_80 12660 non-null float64\n 54 homme 12660 non-null float64\n 55 femme 12660 non-null float64\n 56 NB 12660 non-null float64\ndtypes: float64(34), int32(1), int64(11), object(11)\nmemory usage: 14.7+ MB\n" ] ], [ [ "# chargement du dataset net_salary_per_town_categories.csv", "_____no_output_____" ] ], [ [ "salary = pd.read_csv('net_salary_per_town_categories.csv')\nprint('Shape salary : ',salary.shape)\nprint(\"il y a : \", len(salary['LIBGEO'].unique()) , \"communes couvertes dans le dataset salary\")\nsalary.head(5)\n", "Shape salary : (5136, 26)\nil y a : 5085 communes couvertes dans le dataset salary\n" ], [ "salary.info() # pas de Nan", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 5136 entries, 0 to 5135\nData columns (total 26 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 CODGEO 5136 non-null object \n 1 LIBGEO 5136 non-null object \n 2 SNHM14 5136 non-null float64\n 3 SNHMC14 5136 non-null float64\n 4 SNHMP14 5136 non-null float64\n 5 SNHME14 5136 non-null float64\n 6 SNHMO14 5136 non-null float64\n 7 SNHMF14 5136 non-null float64\n 8 SNHMFC14 5136 non-null float64\n 9 SNHMFP14 5136 non-null float64\n 10 SNHMFE14 5136 non-null float64\n 11 SNHMFO14 5136 non-null float64\n 12 SNHMH14 5136 non-null float64\n 13 SNHMHC14 5136 non-null float64\n 14 SNHMHP14 5136 non-null float64\n 15 SNHMHE14 5136 non-null float64\n 16 SNHMHO14 5136 non-null float64\n 17 SNHM1814 5136 non-null float64\n 18 SNHM2614 5136 non-null float64\n 19 SNHM5014 5136 non-null float64\n 20 SNHMF1814 5136 non-null float64\n 21 SNHMF2614 5136 non-null float64\n 22 SNHMF5014 5136 non-null float64\n 23 SNHMH1814 5136 non-null float64\n 24 SNHMH2614 5136 non-null float64\n 25 SNHMH5014 5136 non-null float64\ndtypes: float64(24), object(2)\nmemory usage: 1.0+ MB\n" ], [ "# pour la fusion il faur supprimer les lignes correspondant aux communes de Corse", "_____no_output_____" ], [ "renommage = {\"CODGEO\" : \"code_insee\",\n \"LIBGEO\" : \"nom_commune\",\n \"MOCO\" : \"situation_familiale\",\n \"AGEQ80_17\" : \"age\"}\n\npopulation[\"MOCO\"] = population.MOCO.replace({11 : \"Enf av 2parents\", 12 : \"Enf av 1parent\",\n 21 : \"Coupl ss Enf\", 22 : \"Coupl av Enf\",\n 23 : \"Cel av Enf\", \n 31 : \"Adulte + du foyer\",\n 32 : \"Adulte Seul\"})\npopulation.head(5)", "_____no_output_____" ] ] ]
[ "raw", "code", "raw", "code", "markdown", "code", "markdown", "raw", "code", "markdown", "code", "raw", "code", "markdown", "code", "markdown", "code", "raw", "code", "markdown", "code", "markdown", "code" ]
[ [ "raw" ], [ "code" ], [ "raw" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "raw" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "raw" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "raw" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ecfb8a41800b45c8c1e4f6edc1c804f7f3cb37f3
6,798
ipynb
Jupyter Notebook
Panorama/opencv1-checkpoint.ipynb
Mohammed20201991/3D-Computer-vistion
1d31e1510c2342d8b8a53bcafe94d3c1487ac0c9
[ "MIT" ]
null
null
null
Panorama/opencv1-checkpoint.ipynb
Mohammed20201991/3D-Computer-vistion
1d31e1510c2342d8b8a53bcafe94d3c1487ac0c9
[ "MIT" ]
null
null
null
Panorama/opencv1-checkpoint.ipynb
Mohammed20201991/3D-Computer-vistion
1d31e1510c2342d8b8a53bcafe94d3c1487ac0c9
[ "MIT" ]
null
null
null
33
825
0.553398
[ [ [ "! pip install opencv-python", "Collecting opencv-python\n Downloading opencv_python-4.5.4.58-cp38-cp38-win_amd64.whl (35.1 MB)\nRequirement already satisfied: numpy>=1.17.3 in c:\\users\\mohammed\\anaconda3\\lib\\site-packages (from opencv-python) (1.20.1)\nInstalling collected packages: opencv-python\nSuccessfully installed opencv-python-4.5.4.58\n" ], [ "!pip install imutils", "Requirement already satisfied: imutils in c:\\users\\mohammed\\anaconda3\\lib\\site-packages (0.5.4)\n" ], [ "import numpy as np\nimport cv2\nimport glob\nimport imutils\n\nimage_paths = glob.glob('unstitchedImages/*.jpg')\nimages = []\n\n\nfor image in image_paths:\n img = cv2.imread(image)\n images.append(img)\n cv2.imshow(\"Image\", img)\n cv2.waitKey(0)\n\n\nimageStitcher = cv2.Stitcher_create()\n\nerror, stitched_img = imageStitcher.stitch(images)\n\nif not error:\n\n cv2.imwrite(\"stitchedOutput.png\", stitched_img)\n cv2.imshow(\"Stitched Img\", stitched_img)\n cv2.waitKey(0)\n\n\n\n\n stitched_img = cv2.copyMakeBorder(stitched_img, 10, 10, 10, 10, cv2.BORDER_CONSTANT, (0,0,0))\n\n gray = cv2.cvtColor(stitched_img, cv2.COLOR_BGR2GRAY)\n thresh_img = cv2.threshold(gray, 0, 255 , cv2.THRESH_BINARY)[1]\n\n cv2.imshow(\"Threshold Image\", thresh_img)\n cv2.waitKey(0)\n\n contours = cv2.findContours(thresh_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n contours = imutils.grab_contours(contours)\n areaOI = max(contours, key=cv2.contourArea)\n\n mask = np.zeros(thresh_img.shape, dtype=\"uint8\")\n x, y, w, h = cv2.boundingRect(areaOI)\n cv2.rectangle(mask, (x,y), (x + w, y + h), 255, -1)\n\n minRectangle = mask.copy()\n sub = mask.copy()\n\n while cv2.countNonZero(sub) > 0:\n minRectangle = cv2.erode(minRectangle, None)\n sub = cv2.subtract(minRectangle, thresh_img)\n\n\n contours = cv2.findContours(minRectangle.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n contours = imutils.grab_contours(contours)\n areaOI = max(contours, key=cv2.contourArea)\n\n cv2.imshow(\"minRectangle Image\", minRectangle)\n cv2.waitKey(0)\n\n x, y, w, h = cv2.boundingRect(areaOI)\n\n stitched_img = stitched_img[y:y + h, x:x + w]\n\n cv2.imwrite(\"stitchedOutputProcessed.png\", stitched_img)\n\n cv2.imshow(\"Stitched Image Processed\", stitched_img)\n\n cv2.waitKey(0)\n\n\n\nelse:\n print(\"Images could not be stitched!\")\n print(\"Likely not enough keypoints being detected!\")", "Images could not be stitched!\nLikely not enough keypoints being detected!\n" ], [ "import os \nimport cv2\nmainFolder = 'Images\\2\\first.jpg'\nmyFolders = os.listdir(mainFolder)\n\nprint(myFolders)\nfor folder in myFolders:\n path = mainFolder + '/'+ folder\n images =[]\n myList = os.listdir(path)\n print(f'Total number of image detected is : {len(myList)}')\n for imgN in myList:\n curImg = cv2.imread(f'{path}/{imgN}')\n curImg = cv2.resize(curImg,(0,0),(0.2,0.2),None)\n images.append(curImg)\n print(len(images))", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
ecfb8a4f7612aefebe68bbe8807f897bd724fe09
7,642
ipynb
Jupyter Notebook
Week 3/Python_string_part_1.ipynb
kiasar/NLP-tutorials-waterloo-MSCI-598---Winter-2022
25423b2ed3e6477e6615cb27e71db7ea11668613
[ "MIT" ]
4
2022-01-13T17:54:10.000Z
2022-01-27T21:31:32.000Z
Week 3/Python_string_part_1.ipynb
kiasar/NLP-tutorials-waterloo-MSCI-598---Winter-2022
25423b2ed3e6477e6615cb27e71db7ea11668613
[ "MIT" ]
null
null
null
Week 3/Python_string_part_1.ipynb
kiasar/NLP-tutorials-waterloo-MSCI-598---Winter-2022
25423b2ed3e6477e6615cb27e71db7ea11668613
[ "MIT" ]
2
2022-01-30T22:32:18.000Z
2022-03-06T21:51:12.000Z
23.58642
117
0.393483
[ [ [ "Hi\n\nIn this tutorial we will look into python string", "_____no_output_____" ] ], [ [ "s = \"s is a string\"\n\nprint(s, \", Type:\", type(s))", "s is a string , Type: <class 'str'>\n" ] ], [ [ "# It is somehow like a list!", "_____no_output_____" ] ], [ [ "# for getting length of a Sring use len function\n\nprint(len(s))", "13\n" ], [ "# you can loop through a String like a list\n\nfor x in \"my car\":\n print(x)", "m\ny\n \nc\na\nr\n" ], [ "# You can use \"in\" to check a string contains another string\ntxt = \"I love playing games!\"\nprint(\"love\" in txt)\nprint(\"ayin\" in txt)", "True\nTrue\n" ], [ "# tu get a sub String just do as you do in a list!\n\nb = \"ha ha look at this!\"\nprint(b[5:15])", " look at t\n" ], [ "# you can add two strings!\n\none = \"I'm 1, \"\ntwo = \"and I'm 2\"\n\nprint(one + two)", "I'm 1, and I'm 2\n" ] ], [ [ "# some cool stuff", "_____no_output_____" ] ], [ [ "a = \" This is a String! \"\n\nprint(a.upper())\nprint(a.lower())\nprint(a.strip()) # removes any whitespace from the beginning or the end\nprint(a.replace(\"String\", \"longer string\"))", " THIS IS A STRING! \n this is a string! \nThis is a String!\n This is a longer string! \n" ], [ "# You can use this function to split your string into a list\n\nsp = \"Roses are red, violets are blue, sugar is sweet, coding is too.\"\n\nprint(sp.split(\",\"))\nprint(sp.split(\" \"))\nprint(sp.split(\"are\"))", "['Roses are red', ' violets are blue', ' sugar is sweet', ' coding is too.']\n['Roses', 'are', 'red,', 'violets', 'are', 'blue,', 'sugar', 'is', 'sweet,', 'coding', 'is', 'too.']\n['Roses ', ' red, violets ', ' blue, sugar is sweet, coding is too.']\n" ], [ "a = \" This is a String! \"\n\nprint(a.count(\"i\"))\nprint(a.find(\"Str\"))\nprint(a.index(\"Str\"))", "3\n12\n12\n" ], [ "print(\" cat \".join([\"1\", \"2\", \"3\"]))", "1 cat 2 cat 3\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ecfb93f4deb38af5783ed01579e1fdb8cc4de4cc
31,683
ipynb
Jupyter Notebook
notebooks/01_EDA/20210603-msl-clean-data-for-modelling.ipynb
marclawson/grantnav_10k_predictor
fcdbda0734cb4dc332f1046c8d5ead868aeb0d8d
[ "MIT" ]
2
2021-06-25T19:42:37.000Z
2021-06-25T22:21:03.000Z
notebooks/01_EDA/20210603-msl-clean-data-for-modelling.ipynb
marclawson/grantnav_10k_predictor
fcdbda0734cb4dc332f1046c8d5ead868aeb0d8d
[ "MIT" ]
null
null
null
notebooks/01_EDA/20210603-msl-clean-data-for-modelling.ipynb
marclawson/grantnav_10k_predictor
fcdbda0734cb4dc332f1046c8d5ead868aeb0d8d
[ "MIT" ]
null
null
null
63.748491
1,759
0.659407
[ [ [ "# Final Cleaning", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\n\n#system\nimport os\nimport sys\nfrom os.path import join as pj\nmodule_path = os.path.abspath(pj('..','..'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n \n# utils\nfrom src.d00_utils import print_helper_functions as phf\n\n# ipython\nimport warnings\nwarnings.simplefilter('ignore')\n\n# executing code\nimport click\nimport logging\n\n# type annotations\nfrom typing import List, Set, Dict, Tuple, Optional\nfrom collections.abc import Iterable\n\n# configuring\nfrom pathlib import Path\nfrom dotenv import find_dotenv, load_dotenv\nimport configparser\n\n# feature extractor\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.pipeline import Pipeline, make_pipeline, make_union, FeatureUnion\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# data\nimport numpy as np\nimport re\nfrom forex_python.converter import CurrencyRates\nnp.set_printoptions(precision=4)\nfrom dateutil.relativedelta import relativedelta\nimport datetime\n\n# stats\nimport statsmodels.api as sm\n\n# viz\nfrom matplotlib import pyplot as plt\nimport matplotlib.dates as mdates\nimport seaborn as sns\nsns.set(font_scale=1.5)\nplt.style.use('bmh')\n%config InlineBackend.figure_format = 'retina'\n%matplotlib inline\n\n# file handling\nimport tempfile\nimport joblib\nimport botocore\nimport boto3\nfrom os.path import join as pj\nimport pickle as pkl", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ] ], [ [ "## 1.0 Load data", "_____no_output_____" ] ], [ [ "# not used in this stub but often useful for finding various files\nproject_dir = Path().resolve().parents[1]\nprint(project_dir)\n\n# find .env automagically by walking up directories until it's found, then\n# load up the .env entries as environment variables\n_ = load_dotenv(find_dotenv())\n\nraw_dir = pj(project_dir, 'data', os.environ.get('RAW_DIR'))\ninterim_dir = pj(project_dir, 'data', os.environ.get('INTERIM_DIR'))\nprocessed_dir = pj(project_dir, 'data', os.environ.get('PROCESSED_DIR'))", "/Users/marclawson/repositories/grantnav_10k_predictor\n" ], [ "data = pd.read_csv(pj(interim_dir,'grantnav_data_post2015.csv'), index_col=0)", "_____no_output_____" ] ], [ [ "## 2.0 Checks", "_____no_output_____" ], [ "### 2.1 Currency", "_____no_output_____" ] ], [ [ "data['currency'].value_counts()", "_____no_output_____" ], [ "# load currencies conversions for award date", "_____no_output_____" ], [ "nongbp_currencies = data[data['currency']!='GBP'].sort_values('award_date')", "_____no_output_____" ], [ "currencies_dict = dict(zip(nongbp_currencies.award_date, nongbp_currencies.currency))", "_____no_output_____" ], [ "import requests", "_____no_output_____" ], [ "api = '2c81b56d5ca58364ea22'", "_____no_output_____" ], [ "example_date = list(currencies_dict.keys())[0]\nexample_currency = list(currencies_dict.values())[0]", "_____no_output_____" ], [ "example_currency\nexample_date", "_____no_output_____" ], [ "today = datetime.datetime.now()-relativedelta(years=1)\ntoday_last_year = today.strftime('%Y-%m-%d')", "_____no_output_____" ], [ "URL = f'https://free.currconv.com/api/v7/convert?q={example_currency}_GBP,GBP_{example_currency}&compact=ultra&date={today_last_year}&apiKey={api}'\nprint(URL)\nreq_ = requests.get(URL, params=api)\njson_ = req_.json()\nprint(json_)", "https://free.currconv.com/api/v7/convert?q=USD_GBP,GBP_USD&compact=ultra&date=2020-06-03&apiKey=2c81b56d5ca58364ea22\n{'USD_GBP': {'2020-06-03': 0.795295}, 'GBP_USD': {'2020-06-03': 1.257395}}\n" ], [ "URL_usage = f'https://free.currconv.com/others/usage?apiKey={api}'\nparams = {'api_key': api} \nreq_ = requests.get(URL_usage, params=api)\njson_ = req_.json()\nprint(json_)", "{'timestamp': '2021-06-03T14:49:48.359Z', 'usage': 10}\n" ], [ "forex_dict = {}\nfor k, v in currencies_dict.items():\n URL = f'https://www.currencyconverterapi.com/api/v7/convert?q={v}_PHP,PHP_GBP&compact=ultra&date=[{k}]&apiKey={api}'\n r = requests.get(URL, 'text')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfb971403a0689318e568f876bb79459ce1cd21
6,970
ipynb
Jupyter Notebook
python/notebooks/PyPI.ipynb
chbrown/sandbox
c408ef7409bb4f27855a09264ae9f2e529c2f220
[ "MIT" ]
null
null
null
python/notebooks/PyPI.ipynb
chbrown/sandbox
c408ef7409bb4f27855a09264ae9f2e529c2f220
[ "MIT" ]
null
null
null
python/notebooks/PyPI.ipynb
chbrown/sandbox
c408ef7409bb4f27855a09264ae9f2e529c2f220
[ "MIT" ]
null
null
null
22.126984
103
0.431851
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ecfb9e00e5a3ebe9d24cb5be6d88faf0e1c4f77d
45,916
ipynb
Jupyter Notebook
m02_v01_store_sales_prediction.ipynb
tamsmchado/DataScience_Em_Producao
a84e2fd04834b4eba039a266f9e21faca8b9db7a
[ "MIT" ]
null
null
null
m02_v01_store_sales_prediction.ipynb
tamsmchado/DataScience_Em_Producao
a84e2fd04834b4eba039a266f9e21faca8b9db7a
[ "MIT" ]
null
null
null
m02_v01_store_sales_prediction.ipynb
tamsmchado/DataScience_Em_Producao
a84e2fd04834b4eba039a266f9e21faca8b9db7a
[ "MIT" ]
null
null
null
64.579466
25,180
0.735713
[ [ [ "# 0.0. IMPORTS", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport inflection\nimport math\nimport numpy as np \nimport seaborn as sns\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## 0.1. Helper Functions", "_____no_output_____" ], [ "## 0.2. Loading Data", "_____no_output_____" ] ], [ [ "df_sales_raw = pd.read_csv('data/train.csv', low_memory=False)\ndf_store_raw = pd.read_csv('data/store.csv', low_memory=False)\n\n# merge\ndf_raw = pd.merge(df_sales_raw, df_store_raw, how='left', on='Store')", "_____no_output_____" ] ], [ [ "# 1.0. DESCRIÇÃO DOS DADOS", "_____no_output_____" ] ], [ [ "df1 = df_raw.copy()", "_____no_output_____" ] ], [ [ "## 1.1. Rename Columns", "_____no_output_____" ] ], [ [ "cols_old = ['Store', 'DayOfWeek', 'Date', 'Sales', 'Customers', 'Open', 'Promo',\n 'StateHoliday', 'SchoolHoliday', 'StoreType', 'Assortment',\n 'CompetitionDistance', 'CompetitionOpenSinceMonth',\n 'CompetitionOpenSinceYear', 'Promo2', 'Promo2SinceWeek',\n 'Promo2SinceYear', 'PromoInterval']\n\nsnakecase = lambda x: inflection.underscore(x)\n\ncols_new = list(map(snakecase, cols_old))\n\n#Rename\ndf1.columns = cols_new", "_____no_output_____" ] ], [ [ "## 1.2. Data Dimensions", "_____no_output_____" ] ], [ [ "print('Numbers of rows: {}'.format(df1.shape[0]))\nprint('Numbers of columns: {}'.format(df1.shape[1]))", "Numbers of rows: 1017209\nNumbers of columns: 18\n" ] ], [ [ "## 1.3. Data Types", "_____no_output_____" ] ], [ [ "df1['date'] = pd.to_datetime(df1['date'])\ndf1.dtypes", "_____no_output_____" ] ], [ [ "## 1.4. Check NA", "_____no_output_____" ] ], [ [ "df1.isna().sum()", "_____no_output_____" ] ], [ [ "## 1.5. Fillout NA", "_____no_output_____" ] ], [ [ "# competition_distance\n## df1['competition_distance'].max() # Checking the maximun distance / ==75860.0\ndf1['competition_distance'] = df1['competition_distance'].apply(lambda x: 200000.0 if math.isnan( x ) else x)\n\n# competition_open_since_month\n## Using the month of the date column as reference if there isn't any value in competition_open_since_month column\ndf1['competition_open_since_month'] = df1.apply(lambda x: x['date'].month if math.isnan(x['competition_open_since_month']) else x['competition_open_since_month'], axis=1)\n\n# competition_open_since_year\n## Using the year inside date column as reference if there isn't any value in competition_open_since_year column\ndf1['competition_open_since_year'] = df1.apply(lambda x: x['date'].year if math.isnan(x['competition_open_since_year']) else x['competition_open_since_year'], axis=1)\n \n# promo2_since_week\n## Using the week inside date column as reference if there isn't any value in promo2_since_week column\ndf1['promo2_since_week'] = df1.apply(lambda x: x['date'].week if math.isnan(x['promo2_since_week']) else x['promo2_since_week'], axis=1)\n \n# promo2_since_year \n## Using the year inside date column as reference if there isn't any value in promo2_since_year column\ndf1['promo2_since_year'] = df1.apply(lambda x: x['date'].year if math.isnan(x['promo2_since_year']) else x['promo2_since_year'], axis=1)\n\n# promo_interval\nmonth_map = {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\ndf1['promo_interval'].fillna(0, inplace=True)\n\ndf1['month_map'] = df1['date'].dt.month.map(month_map)\n\ndf1['is_promo'] = df1[['promo_interval', 'month_map']].apply(lambda x: 0 if x['promo_interval'] == 0 else 1 if x['month_map'] in x['promo_interval'].split(',') else 0, axis=1)", "_____no_output_____" ] ], [ [ "## 1.6. Change Types", "_____no_output_____" ] ], [ [ "df1['competition_open_since_month'] = df1['competition_open_since_month'].astype(np.int64)\ndf1['competition_open_since_year'] = df1['competition_open_since_year'].astype(np.int64)\ndf1['promo2_since_week'] = df1['promo2_since_week'].astype(np.int64)\ndf1['promo2_since_year'] = df1['promo2_since_year'].astype(np.int64)", "_____no_output_____" ] ], [ [ "## 1.7. Descriptive Statistical ", "_____no_output_____" ], [ "### 1.7.1 Numerical Attributes", "_____no_output_____" ] ], [ [ "# Spliting the dataframe between numeric and categorical\nnum_attributes = df1.select_dtypes(include = ['int64', 'float64'])\ncat_attributes = df1.select_dtypes(exclude = ['int64', 'float64', 'datetime64[ns]'])", "_____no_output_____" ], [ "# Central Tendency - mean, median\nct1 = pd.DataFrame(num_attributes.apply(np.mean)).T\nct2 = pd.DataFrame(num_attributes.apply(np.median)).T\n\n# Dispersion - std, min, max, range, skew, kurtosis\nd1 = pd.DataFrame(num_attributes.apply(np.std)).T\nd2 = pd.DataFrame(num_attributes.apply(min)).T\nd3 = pd.DataFrame(num_attributes.apply(max)).T\nd4 = pd.DataFrame(num_attributes.apply(lambda x: x.max() - x.min())).T\nd5 = pd.DataFrame(num_attributes.apply(lambda x: x.skew())).T\nd6 = pd.DataFrame(num_attributes.apply(lambda x: x.kurtosis())).T\n\nm = pd.concat([d2, d3, d4, ct1, ct2, d1, d5, d6]).T.reset_index()\nm.columns = ['attributes', 'min', 'max', 'range', 'mean', 'median', 'std', 'skew', 'kurtosis']\nm", "_____no_output_____" ] ], [ [ "### 1.7.2 Categorical Attributes", "_____no_output_____" ] ], [ [ "cat_attributes.apply(lambda x: x.unique().shape[0])", "_____no_output_____" ], [ "aux1 = df1[(df1['state_holiday'] != '0') & (df1['sales'] > 0)]\n\nplt.figure(figsize=(15, 6))\n\nplt.subplot(1, 3, 1)\nsns.boxplot(x='state_holiday', y='sales', data=aux1)\n\nplt.subplot(1, 3, 2)\nsns.boxplot(x='store_type', y='sales', data=aux1)\n\nplt.subplot(1, 3, 3)\nsns.boxplot(x='assortment', y='sales', data=aux1)\n\nplt.tight_layout()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ecfba760161d05ab73edddca87bbb25cc175f4fa
64,076
ipynb
Jupyter Notebook
Marble.ipynb
miyuki-98312/MarbleChocolateStickerCollection
c48f043aae271e41ce3dd39f6cc39505b60a6ad8
[ "MIT" ]
null
null
null
Marble.ipynb
miyuki-98312/MarbleChocolateStickerCollection
c48f043aae271e41ce3dd39f6cc39505b60a6ad8
[ "MIT" ]
null
null
null
Marble.ipynb
miyuki-98312/MarbleChocolateStickerCollection
c48f043aae271e41ce3dd39f6cc39505b60a6ad8
[ "MIT" ]
null
null
null
115.66065
22,180
0.858449
[ [ [ "import numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\nfrom scipy import stats\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\n%matplotlib inline\n\n%precision 3\n\nmpl.rcParams['font.family'] = 'MS Gothic'", "_____no_output_____" ], [ "# 3種類から3回試行\n\nspecies = 3 # 種類\narray = []\n\nfor i in range(species) :\n for k in range(species) :\n for j in range(species) :\n if(i+k+j == species) :\n tmp = [i,k,j]\n array.append(tmp)\n \nprint(array)\n\n ", "[[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0]]\n" ], [ "# species種類からN回試行\n# 直積を利用して、合計がNの組だけ抽出する\n# このやり方だと、49種類の合計Nの組みあわせを探すのは不可能(数が大きすぎる)\n\nimport itertools\nimport pprint\n\nspecies = 3 # 種類\nN = 5 # 回数\narray = []\n\nfor i in range(species):\n tmp = []\n for j in range(N+1):\n tmp.append(j)\n array.append(tmp)\n\n \nprint(array)\np = itertools.product(*array)\n\n# 合計がNのものだけ抽出\nfor obj in p:\n if sum(obj) == N :\n print(obj)", "[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]\n(0, 0, 5)\n(0, 1, 4)\n(0, 2, 3)\n(0, 3, 2)\n(0, 4, 1)\n(0, 5, 0)\n(1, 0, 4)\n(1, 1, 3)\n(1, 2, 2)\n(1, 3, 1)\n(1, 4, 0)\n(2, 0, 3)\n(2, 1, 2)\n(2, 2, 1)\n(2, 3, 0)\n(3, 0, 2)\n(3, 1, 1)\n(3, 2, 0)\n(4, 0, 1)\n(4, 1, 0)\n(5, 0, 0)\n" ], [ "# species種類からN回試行\n# 0~48を入れたリストを用意する\n\nspecies = 49 # 種類\nN = 200 # 回数\narray = []\n\nfor i in range(species):\n array.append(i)\n\nprint(array)\n", "[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, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]\n" ], [ "# species種類からN回試行\n# リストからN回値を引く\n# species種類の数が何回出現したか数える\n\nimport random\n\nspecies = 49 # 種類\nN = 200 # 回数\ntrial = []\n\n\n\nfor i in range(N):\n trial.append(random.choice(array))\n\nprint(\"選んだ結果\")\nprint(trial)\n\ncounter = {}\nfor i in range(species):\n counter[i] = trial.count(i)\n\nprint(\"回数を数えると\")\nprint(counter)\n", "選んだ結果\n[3, 0, 34, 10, 11, 29, 34, 0, 36, 20, 10, 25, 44, 30, 21, 4, 16, 33, 36, 39, 32, 38, 26, 31, 17, 41, 44, 26, 3, 1, 2, 13, 27, 35, 8, 40, 20, 48, 36, 35, 24, 48, 36, 32, 12, 6, 46, 19, 7, 3, 35, 8, 46, 34, 2, 29, 13, 8, 45, 31, 8, 45, 25, 15, 1, 10, 16, 26, 10, 29, 24, 19, 7, 42, 23, 43, 38, 22, 13, 28, 10, 15, 23, 18, 35, 24, 20, 9, 35, 40, 3, 28, 27, 25, 45, 47, 27, 33, 31, 16, 21, 47, 21, 31, 31, 18, 30, 30, 1, 44, 43, 33, 4, 24, 18, 34, 0, 26, 34, 44, 33, 23, 23, 1, 14, 0, 38, 13, 19, 5, 9, 9, 4, 16, 18, 9, 26, 29, 37, 21, 5, 21, 45, 33, 16, 12, 12, 36, 7, 0, 17, 23, 18, 18, 43, 40, 42, 3, 12, 35, 6, 3, 40, 47, 26, 1, 18, 35, 1, 47, 39, 19, 16, 41, 16, 44, 15, 14, 4, 18, 47, 21, 6, 31, 33, 37, 18, 22, 16, 28, 37, 40, 27, 35, 34, 20, 19, 48, 27, 25]\n回数を数えると\n{0: 5, 1: 6, 2: 2, 3: 6, 4: 4, 5: 2, 6: 3, 7: 3, 8: 4, 9: 4, 10: 5, 11: 1, 12: 4, 13: 4, 14: 2, 15: 3, 16: 8, 17: 2, 18: 9, 19: 5, 20: 4, 21: 6, 22: 2, 23: 5, 24: 4, 25: 4, 26: 6, 27: 5, 28: 3, 29: 4, 30: 3, 31: 6, 32: 2, 33: 6, 34: 6, 35: 8, 36: 5, 37: 3, 38: 3, 39: 2, 40: 5, 41: 2, 42: 2, 43: 3, 44: 5, 45: 4, 46: 2, 47: 5, 48: 3}\n" ], [ "# 結果をヒストグラムにしてみる\n\nvalues = []\n\nmaxNum = 0\nfor val in counter.values():\n values.append(val)\n if val > maxNum:\n maxNum = val\n\n\nvalues.sort()\n\nprint(values)\nplt.hist(values, bins=maxNum, range=(1,maxNum+1))\n", "[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 8, 8, 9]\n" ], [ "# 正規分布に従うかを求める(p=0.05)\n\ndf=pd.DataFrame(values)\n\nstats.shapiro(df)", "_____no_output_____" ], [ "# species種類からN回選ぶ試行を行う関数を定義\n\nimport random\n\nspecies = 49 # 種類\n\n\ndef Trial(N):\n trial = []\n for i in range(N):\n trial.append(random.choice(array))\n counter = {}\n for i in range(species):\n counter[i] = trial.count(i)\n\n return trial\n \n \ndef CountBySpecies(lists):\n counter = {}\n values = []\n for i in range(species):\n counter[i] = lists.count(i)\n maxNum = 0\n for val in counter.values():\n values.append(val)\n if val > maxNum:\n maxNum = val\n values.sort()\n\n return values\n", "_____no_output_____" ], [ "# 関数を呼びだして使えるようにした\n\nresult = CountBySpecies(Trial(1000))\nmaxNum = max(result)\nprint(result)\nplt.hist(result, bins=maxNum, range=(1,maxNum+1))\ndf=pd.DataFrame(result)\n\nstats.shapiro(df)\n", "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 11, 12, 12, 13, 15, 16, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 21, 21, 21, 21, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 25, 26, 27, 28, 28, 30]\n" ], [ "# 49種類からN回選ぶ試行を200回やってみる\n\nN = 700 # マーブルチョコを何個買うか\nn = 200 # それを何回繰り返すか\n\ncounter_normal = 0\nfor i in range(n):\n result = CountBySpecies(Trial(N))\n df=pd.DataFrame(result)\n if stats.shapiro(df).pvalue > 0.05:\n counter_normal = counter_normal+1\n\nprint(\"正規分布に従ったのは\",n,\"回のうち\",counter_normal,\"回\")\n", "正規分布に従ったのは 200 回のうち 166 回\n" ], [ "# 上の処理を関数にする\n\ndef LoopTrial(N, n):\n counter_normal = 0\n for i in range(n):\n result = CountBySpecies(Trial(N))\n df=pd.DataFrame(result)\n if stats.shapiro(df).pvalue > 0.05:\n counter_normal = counter_normal+1\n return counter_normal\n", "_____no_output_____" ], [ "# 49種類からN回選ぶ試行をn回やって正規分布になった回数を調べる\n# n=200\n\nN_list = [100,200,300,400,500,600,700,800,900,1000]\nn = 200\nn_list = []\nresult_list = []\nlength = len(N_list)\nfor i in range(length):\n n_list.append(n)\n\nfor I, i in zip(N_list, n_list):\n counter_normal = LoopTrial(I, i)\n result_list.append(counter_normal)\n \nprint(result_list)\n\nN_list_index = []\nfor i in range(length):\n N_list_index.append(i)\n\ndf=pd.DataFrame(result_list)\nplt.figure(figsize=(8,5))\nplt.title(\"49種類からN回選ぶ試行をn回行う(n=200)\")\nplt.xticks(N_list_index, N_list)\nplt.xlabel(\"N\")\nplt.ylabel(\"正規分布になった回数\")\nplt.plot(df)", "[0, 73, 115, 142, 161, 161, 176, 168, 176, 175]\n" ], [ "# 49種類からN回選ぶ試行をn回やって正規分布になった回数を調べる\n# n=400\n\nN_list = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1500, 2000, 2500, 3000]\nn = 400\nn_list = []\nresult_list = []\nlength = len(N_list)\nfor i in range(length):\n n_list.append(n)\n\nfor I, i in zip(N_list, n_list):\n counter_normal = LoopTrial(I, i)\n result_list.append(counter_normal)\n \nprint(result_list)\n\nN_list_index = []\nfor i in range(length):\n N_list_index.append(i)\n\ndf=pd.DataFrame(result_list)\nplt.figure(figsize=(10,5))\nplt.title(\"49種類からN回選ぶ試行をn回行う(n=400)\")\nplt.xticks(N_list_index, N_list)\nplt.xlabel(\"N\")\nplt.ylabel(\"正規分布になった回数\")\nplt.plot(df)", "[0, 139, 258, 292, 313, 330, 330, 361, 350, 346, 355, 369, 371, 363]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfbb2770e0f10e4dbb12524435d1b026f21925b
10,006
ipynb
Jupyter Notebook
03_creating_two_detector_results.ipynb
ThesisSlayers/two_stage_detector
22541ce1088cb03933ea5a589def4a186f7ad6ca
[ "MIT" ]
null
null
null
03_creating_two_detector_results.ipynb
ThesisSlayers/two_stage_detector
22541ce1088cb03933ea5a589def4a186f7ad6ca
[ "MIT" ]
null
null
null
03_creating_two_detector_results.ipynb
ThesisSlayers/two_stage_detector
22541ce1088cb03933ea5a589def4a186f7ad6ca
[ "MIT" ]
null
null
null
31.765079
303
0.544873
[ [ [ "# default_exp inference", "_____no_output_____" ], [ "#export\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom pathlib import Path\nfrom PIL import Image\nimport os\nimport cv2\nimport numpy as np\nfrom tqdm.notebook import tqdm\n\nfrom xml.etree.ElementTree import Element, SubElement, tostring \nimport pprint\nfrom xml.dom.minidom import parseString\n\nfrom two_stage_detector.bbox import *\nfrom two_stage_detector.inference import *\n\nfrom fastcore.test import *", "_____no_output_____" ], [ "from matplotlib import pyplot as plt\nfrom IPython.display import clear_output", "_____no_output_____" ], [ "%config Completer.use_jedi = False", "_____no_output_____" ], [ "path_det1 = '/home/addfor/projects/smart_tray/20_5006v02-intp-detection-foodv01/det1_model/saved_model'\npath_det2 = '/home/addfor/projects/smart_tray/20_5006v02-intp-detection-foodv01/det2_model/saved_model'\ndet1 = tf.saved_model.load(path_det1)\ndet2 = tf.saved_model.load(path_det2)", "_____no_output_____" ], [ "DATASETS_LIST = [\n \"run_3_revisited_5may2021\",\n \"Sodexo_revisited_8jun\",\n \"Test_Empoli_01_06_2021\",\n \"Test_Empoli_08_06_2021\",\n \"Test_Empoli_09_06_2021\",\n \"Test_Empoli_26_05_2021\",\n \"Test_Empoli_27_05_2021\",\n \"Test_Empoli_28_05_2021\",\n \"Test_Empoli_29_04_2021\",\n \"Test_Empoli_30_04_2021\",\n \"Test_Empoli_31_05_2021\",\n \"Test_Empoli_from_10_06_2021_to_30_06_2021\",\n \"UNIMIB_revisited_7giu2021\"\n]\n\nBASE_PATH = Path('/mnt/data/smarttray/dataset_05jul2021_av3b')", "_____no_output_____" ], [ "def initialize_pascalvoc_header(img_path, W, H):\n node_root = Element('annotation')\n\n node_folder = SubElement(node_root, 'folder')\n node_folder.text = f'{BASE_PATH/img_path}'\n\n node_filename = SubElement(node_root, 'filename')\n node_filename.text = f'{img_path.name}'\n\n node_size = SubElement(node_root, 'size')\n node_width = SubElement(node_size, 'width')\n node_width.text = f'{W}'\n\n node_height = SubElement(node_size, 'height')\n node_height.text = f'{H}'\n\n node_depth = SubElement(node_size, 'depth')\n node_depth.text = '3'\n \n return node_root\n\ndef add_bb_to_xml(node_root, bb, scr, class_name, food_scr=None):\n node_object = SubElement(node_root, 'object')\n \n node_name = SubElement(node_object, 'name')\n node_name.text = f'{class_name}'\n node_difficult = SubElement(node_object, 'difficult')\n node_difficult.text = '0'\n \n node_bndbox = SubElement(node_object, 'bndbox')\n \n node_xmin = SubElement(node_bndbox, 'xmin')\n node_xmin.text = f'{bb[0]}'\n node_ymin = SubElement(node_bndbox, 'ymin')\n node_ymin.text = f'{bb[1]}'\n node_xmax = SubElement(node_bndbox, 'xmax')\n node_xmax.text = f'{bb[2]}'\n node_ymax = SubElement(node_bndbox, 'ymax')\n node_ymax.text = f'{bb[3]}'\n \n node_score = SubElement(node_bndbox, 'score')\n node_score.text = f'{scr}'\n \n if food_scr: \n node_food_scr = SubElement(node_bndbox, 'food_score')\n node_food_scr.text = f'{food_scr}'\n\n return node_root", "_____no_output_____" ], [ "def debug(img, food_bbs, rcp_bbs): \n draw_bbs(img, food_bbs, color=blue)\n draw_bbs(img, rcp_bbs, color=red)\n\n plot(img); plt.show()\n x = input(\"write 'c' to stop\")\n clear_output()\n if x=='c': raise Exception() ", "_____no_output_____" ], [ "def get_n_best_bbs(bbs, scrs, n):\n x = list(zip(bbs,scrs))\n x = sorted(x, key=lambda x: x[1], reverse=True)[:n]\n bbs, scrs = list(zip(*x))\n return bbs, scrs", "_____no_output_____" ], [ "bbs, scrs = [[1], [3], [2], [5]], [1, 3, 2, 5]\ntest_eq(get_n_best_bbs(bbs, scrs, 2), ([[5], [3]], [5, 3]))", "_____no_output_____" ], [ "def save_xml(node_root, xml_path):\n xml_path = Path(xml_path)\n xml_path.parent.mkdir(exist_ok=True)\n\n xml = tostring(node_root) #, pretty_print=True Formatted display, the newline of the newline\n dom = parseString(xml)\n\n with open(str(xml_path), 'w') as f: \n dom.writexml(f,indent=' ', addindent=' ', newl='\\n')\n \ndef create_xml_anns_of_img(img_path, do_debug, det1_th, det2_th, n_best): \n img = load_image(img_path).numpy()\n H, W, _ = img.shape \n node_root = initialize_pascalvoc_header(img_path, W, H)\n\n food_bbs, food_scrs = get_bbs(img, det1, threshold=det1_th, n_best=n_best, in_absolute_coords=True)\n for bb, scr in zip(food_bbs, food_scrs): \n node_root = add_bb_to_xml(node_root, bb, scr, \"food\")\n\n foods = get_bb_crops(img, food_bbs)\n for food, food_bb, food_scr in zip(foods, food_bbs, food_scrs):\n X, Y, w, h = food_bb.coco_coords\n if w > 700 and h > 700:\n rcp_bbs, rcp_scrs = get_bbs(food, det2, threshold=det2_th, n_best=n_best, in_absolute_coords=True)\n for bb, scr in zip(rcp_bbs, rcp_scrs): \n bb.shift(X, Y)\n node_root = add_bb_to_xml(node_root, bb, scr, \"recipe\", food_scr) \n\n if do_debug: debug(img, food_bbs, rcp_bbs)\n\n return node_root\n", "_____no_output_____" ], [ "det1_th = 0.0\ndet2_th = 0.0\nn_best = 20\n\nblue = [0,0,255]\nred = [255,0,0]\n\ndo_debug = False\n\n# for ds in tqdm(DATASETS_LIST):\n# ds_path = BASE_PATH/ds/'val/images'\n# if ds_path.exists(): img_paths = [img_path for img_path in ds_path.iterdir() if not img_path.is_dir()]\n# else: continue\n\n# for img_path in tqdm(img_paths):\n# node_root = create_xml_anns_of_img(img_path, do_debug, det1_th, det2_th, n_best)\n# xml_path = BASE_PATH/'two_detector_results'/ds/f'{img_path.stem}.xml'\n# save_xml(node_root, xml_path)\n\ndata_test_path = BASE_PATH/'data_test/images'\nimg_paths = [img_path for img_path in data_test_path.iterdir() if not img_path.is_dir()]\nfor img_path in tqdm(img_paths):\n node_root = create_xml_anns_of_img(img_path, do_debug, det1_th, det2_th, n_best)\n xml_path = BASE_PATH/'two_detector_results'/f'data_test/{img_path.stem}.xml'\n save_xml(node_root, xml_path) ", "_____no_output_____" ], [ "read_xml_anns(xml_path)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfbe0a6d03f21b8b8d78dae22de6a8f4efac8e5
3,262
ipynb
Jupyter Notebook
build_mesh.ipynb
Ericcsr/ClothFromDepth
c21bbcceac4b36223f99a3f1177637296553dce0
[ "MIT" ]
null
null
null
build_mesh.ipynb
Ericcsr/ClothFromDepth
c21bbcceac4b36223f99a3f1177637296553dce0
[ "MIT" ]
null
null
null
build_mesh.ipynb
Ericcsr/ClothFromDepth
c21bbcceac4b36223f99a3f1177637296553dce0
[ "MIT" ]
null
null
null
18.429379
81
0.495095
[ [ [ "import open3d as o3d\nimport numpy as np", "Jupyter environment detected. Enabling Open3D WebVisualizer.\n[Open3D INFO] WebRTC GUI backend enabled.\n[Open3D INFO] WebRTCWindowSystem: HTTP handshake server disabled.\n" ], [ "cloth_mesh = o3d.io.read_triangle_mesh(\"test.obj\")", "_____no_output_____" ], [ "faces = np.asarray(cloth_mesh.triangles)", "_____no_output_____" ], [ "np.asarray(cloth_mesh.vertices)[0]", "_____no_output_____" ], [ "import taichi as ti", "[Taichi] version 0.8.4, llvm 10.0.0, commit 895881b5, win, python 3.7.0\n" ], [ "ti.init(arch=ti.cpu)", "[Taichi] Starting on arch=x64\n" ], [ "x = ti.field(ti.i32, shape=(2))\ny = ti.field(ti.f64, shape=(2))", "_____no_output_____" ], [ "x[0] = 1\nx[1] = 0", "_____no_output_____" ], [ "@ti.kernel\ndef func():\n y[x[0]] = 1.0\n y[x[1]] = 2.0", "_____no_output_____" ], [ "func()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfbe2d64cb7158e33b1f0a37296263fdaa6acf3
7,756
ipynb
Jupyter Notebook
notebooks/Pendulum_ForwardEuler.ipynb
rjleveque/amath586s2019
235fb66c96dd51d98e30dc3d52285bf9273c4391
[ "BSD-3-Clause" ]
4
2019-07-04T00:16:31.000Z
2020-10-24T02:06:44.000Z
notebooks/Pendulum_ForwardEuler.ipynb
rjleveque/amath586s2019
235fb66c96dd51d98e30dc3d52285bf9273c4391
[ "BSD-3-Clause" ]
null
null
null
notebooks/Pendulum_ForwardEuler.ipynb
rjleveque/amath586s2019
235fb66c96dd51d98e30dc3d52285bf9273c4391
[ "BSD-3-Clause" ]
null
null
null
29.490494
355
0.525271
[ [ [ "# Pendulum motion with Forward Euler\n\n[AMath 586, Spring Quarter 2019](http://staff.washington.edu/rjl/classes/am586s2019/) at the University of Washington. For other notebooks, see [Index.ipynb](Index.ipynb) or the [Index of all notebooks on Github](https://github.com/rjleveque/amath586s2019/blob/master/notebooks/Index.ipynb).\n\nThis notebook illustrates how Forward Euler behaves when modeling a simple pendulum on a coarse grid.\n", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ], [ "from pylab import *\nfrom matplotlib import animation\nfrom IPython.display import HTML\nfrom scipy.integrate import solve_ivp", "_____no_output_____" ] ], [ [ "## Compute a fine grid solution for comparison:", "_____no_output_____" ] ], [ [ "def f(t,u):\n f0 = u[1]\n f1 = -sin(u[0])\n return array([f0,f1])\n\ntheta0 = pi/2.\nu0 = array([theta0, 0.])\ntf = 30.\n\nt_span = (0., tf)\nt_eval = linspace(0, tf, 1000)\nsolution = solve_ivp(f, t_span, u0, method='RK45', t_eval=t_eval, \n atol=1e-9, rtol=1e-9)\ntheta_eval = solution.y[0,:]", "_____no_output_____" ] ], [ [ "## Forward Euler implementation:", "_____no_output_____" ] ], [ [ "def ForwardEuler(nsteps):\n t0 = 0.; tfinal = 30.\n t = linspace(t0, tfinal, nsteps+1)\n dt = t[1] - t[0]\n \n # Array for computed solution\n # give it two rows so each column is solution at one time,\n \n U = empty((2,nsteps+1))\n U.fill(nan)\n U[0,0] = theta0 # initial angle theta\n U[1,0] = 0. # initial angular velocity\n for n in range(0,nsteps):\n U[0,n+1] = U[0,n] + dt * U[1,n]\n U[1,n+1] = U[1,n] - dt * sin(U[0,n])\n \n return t,U\n\nt,U = ForwardEuler(300)\n\nplot(t,U[0,:],'b',label='computed')\nplot(t_eval,theta_eval,'k',label='from solve_ivp')\nlegend()\nprint('Error at the final time = %g' % abs(U[0,-1]-theta_eval[-1]))", "_____no_output_____" ] ], [ [ "Note that the Forward Euler solution for $\\theta(t)$ grows in amplitude with time in a nonphysical manner and eventually goes over the top ($\\theta > \\pi$) and continues swinging around and around rather than osciallating about $\\theta = 0$ as it should.\n\nThis is much easier to visualize in an animation...\n", "_____no_output_____" ], [ "## Animation\n\nThe rest of this notebook shows how to make an animation of the solution. \n\nThis uses the [animation.FuncAnimation](https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html) function from matplotlib to animate the pendulum motion. See e.g. [this page](http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-as-interactive-javascript-widgets/) for a nice simple introductory example.", "_____no_output_____" ] ], [ [ "def pend_animation(nsteps, plot_interval=1):\n \"\"\"\n Solve the pendulum problem with the method defined above using nsteps time steps.\n Create an animation showing the swinging pendulum, using the solution every\n plot_interval time steps.\n \"\"\"\n \n # compute the solution with the method define above:\n t,U = ForwardEuler(nsteps)\n \n fig = plt.figure(figsize=(11,5))\n ax1 = plt.subplot(121)\n plot(t,U[0,:],'r')\n pi_ticks = pi*array([-1,0,1,2,3,4,5,6])\n pi_labels = ['$-\\pi$','0','$\\pi$','$2\\pi$','$3\\pi$','$4\\pi$','$5\\pi$','$6\\pi$']\n ax1.set_yticks(pi_ticks)\n ax1.set_yticklabels(pi_labels)\n ax1.set_xlabel('time')\n ax1.set_ylabel('theta')\n ax1.grid(True)\n \n theta = U[0,0]\n pendlength = 2.\n xpend = pendlength*sin(theta);\n ypend = -pendlength*cos(theta);\n \n ax2 = plt.subplot(122,xlim=(-2.3, 2.3), ylim=(-2.3, 2.3))\n ax2.plot([-2.3,2.3],[0,0],'k',linewidth=0.5)\n ax2.plot([0,0],[-2.3,2.3],'k',linewidth=0.5)\n axis('scaled')\n ax2.set_xlim(-2.3,2.3)\n ax2.set_ylim(-2.3,2.3)\n \n def init():\n shaft, = ax2.plot([0,xpend], [0,ypend], linestyle='-', color='lightblue', lw=2)\n bob, = ax2.plot([xpend],[ypend],'o',color='lightblue', markersize=8)\n theta_pt, = ax1.plot([t[0]], [U[0,0]], 'o',color='pink')\n return (shaft,bob,theta_pt)\n\n shaft,bob,theta_pt = init()\n \n def fplot(n):\n theta = U[0,n]\n xpend = pendlength*sin(theta);\n ypend = -pendlength*cos(theta);\n shaft.set_data([0,xpend], [0,ypend])\n shaft.set_color('b')\n bob.set_data([xpend], [ypend])\n bob.set_color('b')\n theta_pt.set_data([t[n]], [U[0,n]])\n theta_pt.set_color('k')\n return (shaft,bob,theta_pt)\n\n frames_to_plot = range(0, len(t), plot_interval)\n close(fig)\n return animation.FuncAnimation(fig, fplot, frames=frames_to_plot, interval=100,\n blit=True,init_func=init,repeat=False)\n", "_____no_output_____" ], [ "anim = pend_animation(300,3);", "_____no_output_____" ], [ "HTML(anim.to_jshtml())", "_____no_output_____" ] ], [ [ "Older versions of matplotlib lack the `to_jshtml` option, so you might want to use this instead (uncomment to use):", "_____no_output_____" ] ], [ [ "HTML(anim.to_html5_video())", "_____no_output_____" ], [ "animation.FuncAnimation?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ecfbe308fcdd83c82553ef925c020fc5e1e60493
10,322
ipynb
Jupyter Notebook
bures_weighted_flows_comparison.ipynb
cesar-claros/data-efficient-gans
29d06ebb72f9aa43a9c53804dfb9d28737c7ec1d
[ "BSD-2-Clause" ]
null
null
null
bures_weighted_flows_comparison.ipynb
cesar-claros/data-efficient-gans
29d06ebb72f9aa43a9c53804dfb9d28737c7ec1d
[ "BSD-2-Clause" ]
null
null
null
bures_weighted_flows_comparison.ipynb
cesar-claros/data-efficient-gans
29d06ebb72f9aa43a9c53804dfb9d28737c7ec1d
[ "BSD-2-Clause" ]
null
null
null
34.637584
262
0.490506
[ [ [ "<a href=\"https://colab.research.google.com/github/cesar-claros/data-efficient-gans/blob/master/bures_weighted_flows_comparison.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "! pip install POT\n! pip install celluloid", "_____no_output_____" ], [ "!git clone https://github.com/anon-author-dev/gsw\n%cd gsw/code_flow/gsw", "_____no_output_____" ], [ "import numpy as np\nfrom bures_weighted import WGSB\nfrom weighted_utils import w2_weighted\nfrom gsw_utils import w2,load_data\n\nimport torch\nfrom torch import optim\n\nfrom celluloid import Camera\nfrom tqdm import tqdm\nfrom IPython import display\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "# in ['swiss_roll','circle','8gaussians','25gaussians']:\n\ndataset_name = 'circle' \nnp.random.seed(10)\nN = 1000 # Number of samples from p_X\nX = load_data(name=dataset_name, n_samples=N)\nX -= X.mean(dim=0)[np.newaxis,:] # Normalization\nmeanX = 0\n# Show the dataset\n_, d = X.shape\nfig = plt.figure(figsize=(5,5))\nplt.scatter(X[:,0], X[:,1])\nplt.show()", "_____no_output_____" ], [ "# Use GPU if available, CPU otherwise\nif torch.cuda.is_available():\n device = torch.device('cuda')\nelse:\n device = torch.device('cpu')", "_____no_output_____" ], [ "# Number of iterations for the optimization process\nnofiterations = 250", "_____no_output_____" ], [ "# # Define the different defining functions\ntitles = ['Max Sliced W2: linear', 'RFB-2000-0.2', 'RFB-2000-0.1', 'Max Sliced Bures: linear', 'RFB-2000-0.2', 'RFB-2000-0.1']", "_____no_output_____" ], [ "# Define the initial distribution\n#Y = torch.from_numpy(np.random.normal(loc=meanX, scale=0.5, size=(N,d))).float()\nY = torch.from_numpy((np.random.rand(N,d)-0.5)*4 ).float()\ntemp = np.ones((N,))/N\n# Define the optimizers\nbeta = list()\noptimizer = list()\nwmsd = list()\n\nnew_lr = 1e-2\nnb = 2000 # number of bases in the random Fourier bases\nsigma0 = 0.2\nsigma1 = 0.1\n\n# WARNING the order of the optimizers is HARDCODED below ...\n\nbeta.append(torch.tensor(temp, dtype=torch.float, device=device, requires_grad=True))\noptimizer.append(optim.Adam([beta[-1]], lr = new_lr))\nwmsd.append([WGSB(ftype='linear')])\n\nbeta.append(torch.tensor(temp, dtype=torch.float, device=device, requires_grad=True))\noptimizer.append(optim.Adam([beta[-1]], lr = new_lr))\nwmsd.append([WGSB(ftype='kernel', nofbases = nb, sigma = sigma0)])\n\nbeta.append(torch.tensor(temp, dtype=torch.float, device=device, requires_grad=True))\noptimizer.append(optim.Adam([beta[-1]], lr = new_lr))\nwmsd.append([WGSB(ftype='kernel', nofbases = nb, sigma = sigma1)])\n\nbeta.append(torch.tensor(temp, dtype=torch.float, device=device, requires_grad=True))\noptimizer.append(optim.Adam([beta[-1]], lr = new_lr))\nwmsd.append([WGSB(ftype='linear')])\n\nbeta.append(torch.tensor(temp, dtype=torch.float, device=device, requires_grad=True))\noptimizer.append(optim.Adam([beta[-1]], lr = new_lr))\nwmsd.append([WGSB(ftype='kernel', nofbases = nb, sigma = sigma0)])\n\nbeta.append(torch.tensor(temp, dtype=torch.float, device=device, requires_grad=True))\noptimizer.append(optim.Adam([beta[-1]], lr = new_lr))\nwmsd.append([WGSB(ftype='kernel', nofbases = nb, sigma = sigma1)])", "_____no_output_____" ], [ "fig, f_axs = plt.subplots(ncols=3, nrows=3, figsize=(15, 15));\ncamera = Camera(fig)\ngs = f_axs[2, 0].get_gridspec()\n# remove the underlying axes\nfor ax in f_axs[-1, :]:\n ax.remove()\naxbig = fig.add_subplot(gs[-1, :])\naxbig.set_title('Wasserstein-2 Distance', fontsize=22)\naxbig.set_ylabel(r'$Log_{10}(W_2)$', fontsize=22)\ncolors = ['#1f77b4',\n '#ff7f0e',\n '#2ca02c',\n '#d62728',\n '#9467bd',\n '#8c564b']\n# Define the variables to store the loss (2-Wasserstein distance) for each defining function and each problem \nw2_dist = np.nan * np.zeros((nofiterations, 6))\nfig.suptitle('FLOWS COMPARISON', fontsize=44)\nfor i in range(nofiterations): \n loss = list()\n # We loop over the different defining functions for the max- GSW problem\n for k in range(6):\n # Loss computation (here, max-GSW and max-sliced Bures)\n if k is 0:\n loss_ = wmsd[k][0].max_gsw_weighted(X.to(device),Y.to(device),beta[k].to(device)) \n elif k is 1 or k is 2:\n loss_ = wmsd[k][0].max_kernel_gsw_weighted(X.to(device), Y.to(device),beta[k].to(device))\n elif k is 3:\n loss_ = wmsd[k][0].max_sliced_bures_weighted(X.to(device), Y.to(device),beta[k].to(device))\n else:\n loss_ = wmsd[k][0].max_sliced_kernel_bures_weighted(X.to(device), Y.to(device),beta[k].to(device))\n\n # Optimization step\n loss.append(loss_)\n optimizer[k].zero_grad()\n loss[k].backward()\n optimizer[k].step()\n # Should projection to simplex for nu instead beta \n\n \n nu = beta[k].detach().cpu().numpy()\n nu = np.maximum(0,nu).astype(np.float64)\n nu = nu/np.sum(nu)\n # Compute the 2-Wasserstein distance to compare the distributions\n w2_dist[i, k] = w2_weighted(X.detach().cpu().numpy(), Y.detach().cpu().numpy(), nu)\n \n nu = nu/np.max(nu)*15\n # Plot samples from the target and the current solution\n row = 0\n col = k\n if k>=3:\n col = k-3\n row = 1\n f_axs[row,col].scatter(X[:, 0], X[:, 1], c='b')\n f_axs[row,col].scatter(Y[:, 0], Y[:, 1], s=nu, c='r')\n f_axs[row,col].set_title(titles[k], fontsize=22)\n\n # Plot the 2-Wasserstein distance\n for p, color in enumerate(colors):\n axbig.plot(np.log10(w2_dist[:,p]), color = color)\n\n axbig.legend(titles, fontsize=22, bbox_to_anchor=(.1,-.55), loc=\"lower left\",\n ncol=2, fancybox=True, shadow=True)\n camera.snap()\n\nplt.close()", "_____no_output_____" ], [ "animation_full = camera.animate()\nanimation_full.save('animation_full.mp4')\nanimation_reduced = camera.animate(blit=False, interval=10)\nanimation_reduced.save('animation_reduced.mp4')", "_____no_output_____" ], [ "display.HTML(animation_full.to_html5_video())", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfbec4045ded707e08ed0e039fa2169df4ef095
5,090
ipynb
Jupyter Notebook
0.15/_downloads/plot_define_target_events.ipynb
drammock/mne-tools.github.io
5d3a104d174255644d8d5335f58036e32695e85d
[ "BSD-3-Clause" ]
null
null
null
0.15/_downloads/plot_define_target_events.ipynb
drammock/mne-tools.github.io
5d3a104d174255644d8d5335f58036e32695e85d
[ "BSD-3-Clause" ]
null
null
null
0.15/_downloads/plot_define_target_events.ipynb
drammock/mne-tools.github.io
5d3a104d174255644d8d5335f58036e32695e85d
[ "BSD-3-Clause" ]
null
null
null
47.12963
1,268
0.569155
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\n============================================================\nDefine target events based on time lag, plot evoked response\n============================================================\n\nThis script shows how to define higher order events based on\ntime lag between reference and target events. For\nillustration, we will put face stimuli presented into two\nclasses, that is 1) followed by an early button press\n(within 590 milliseconds) and followed by a late button\npress (later than 590 milliseconds). Finally, we will\nvisualize the evoked responses to both 'quickly-processed'\nand 'slowly-processed' face stimuli.\n\n\n", "_____no_output_____" ] ], [ [ "# Authors: Denis Engemann <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport mne\nfrom mne import io\nfrom mne.event import define_target_events\nfrom mne.datasets import sample\nimport matplotlib.pyplot as plt\n\nprint(__doc__)\n\ndata_path = sample.data_path()", "_____no_output_____" ] ], [ [ "Set parameters\n\n", "_____no_output_____" ] ], [ [ "raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nevent_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'\n\n# Setup for reading the raw data\nraw = io.read_raw_fif(raw_fname)\nevents = mne.read_events(event_fname)\n\n# Set up pick list: EEG + STI 014 - bad channels (modify to your needs)\ninclude = [] # or stim channels ['STI 014']\nraw.info['bads'] += ['EEG 053'] # bads\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=True,\n include=include, exclude='bads')", "_____no_output_____" ] ], [ [ "Find stimulus event followed by quick button presses\n\n", "_____no_output_____" ] ], [ [ "reference_id = 5 # presentation of a smiley face\ntarget_id = 32 # button press\nsfreq = raw.info['sfreq'] # sampling rate\ntmin = 0.1 # trials leading to very early responses will be rejected\ntmax = 0.59 # ignore face stimuli followed by button press later than 590 ms\nnew_id = 42 # the new event id for a hit. If None, reference_id is used.\nfill_na = 99 # the fill value for misses\n\nevents_, lag = define_target_events(events, reference_id, target_id,\n sfreq, tmin, tmax, new_id, fill_na)\n\nprint(events_) # The 99 indicates missing or too late button presses\n\n# besides the events also the lag between target and reference is returned\n# this could e.g. be used as parametric regressor in subsequent analyses.\n\nprint(lag[lag != fill_na]) # lag in milliseconds\n\n# #############################################################################\n# Construct epochs\n\ntmin_ = -0.2\ntmax_ = 0.4\nevent_id = dict(early=new_id, late=fill_na)\n\nepochs = mne.Epochs(raw, events_, event_id, tmin_,\n tmax_, picks=picks, baseline=(None, 0),\n reject=dict(mag=4e-12))\n\n# average epochs and get an Evoked dataset.\n\nearly, late = [epochs[k].average() for k in event_id]", "_____no_output_____" ] ], [ [ "View evoked response\n\n", "_____no_output_____" ] ], [ [ "times = 1e3 * epochs.times # time in milliseconds\ntitle = 'Evoked response followed by %s button press'\n\nplt.clf()\nax = plt.subplot(2, 1, 1)\nearly.plot(axes=ax)\nplt.title(title % 'late')\nplt.ylabel('Evoked field (fT)')\nax = plt.subplot(2, 1, 2)\nlate.plot(axes=ax)\nplt.title(title % 'early')\nplt.ylabel('Evoked field (fT)')\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfbf96946d8dcc8176b74baa9a9805a7ce92d3e
14,351
ipynb
Jupyter Notebook
python/anger.ipynb
kiote/empathy
4bab753541051cdbc09b85999c6f1dcfa354beb5
[ "MIT" ]
null
null
null
python/anger.ipynb
kiote/empathy
4bab753541051cdbc09b85999c6f1dcfa354beb5
[ "MIT" ]
null
null
null
python/anger.ipynb
kiote/empathy
4bab753541051cdbc09b85999c6f1dcfa354beb5
[ "MIT" ]
null
null
null
65.231818
7,680
0.775834
[ [ [ "import pandas as pd\nimport numpy as np\nfrom scipy.signal import find_peaks, peak_prominences, peak_widths, medfilt2d\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "folder_name = '1645186354'\nfile_nr = '1'", "_____no_output_____" ], [ "df = pd.read_csv(f'rawdata/{folder_name}/emotions{file_nr}.csv', header=None)", "/opt/conda/lib/python3.9/site-packages/IPython/core/interactiveshell.py:3444: DtypeWarning: Columns (148,149,150,151,152,153) have mixed types.Specify dtype option on import or set low_memory=False.\n exec(code_obj, self.user_global_ns, self.user_ns)\n" ], [ "# remove not needed columns (no idea what they are)\ndf = df.drop(df.columns[46:], axis=1)", "_____no_output_____" ], [ "# put names to columnst\ndf.columns =[\"Row\",\"Timestamp\",\"Combined Event Source\",\"SlideEvent\",\"StimType\",\"Duration\",\"CollectionPhase\",\"SourceStimuliName\",\"SampleNumber\",\"Anger\",\"Contempt\",\"Disgust\",\"Fear\",\"Joy\",\"Sadness\",\"Surprise\",\"Engagement\",\"Valence\",\"Attention\",\"Brow Furrow\",\"Brow Raise\",\"Cheek Raise\",\"Chin Raise\",\"Dimpler\",\"Eye Closure\",\"Eye Widen\",\"Inner Brow Raise\",\"Jaw Drop\",\"Lip Corner Depressor\",\"Lip Press\",\"Lip Pucker\",\"Lip Stretch\",\"Lip Suck\",\"Lid Tighten\",\"Mouth Open\",\"Nose Wrinkle\",\"Smile\",\"Smirk\",\"Upper Lip Raise\",\"Pitch\",\"Yaw\",\"Roll\",\"Interocular Distance\",\"SampleNumber\",\"width\",\"height\"]", "_____no_output_____" ], [ "plt.plot(df[\"Timestamp\"], df['Anger'])", "_____no_output_____" ], [ "x = df['Anger']\npeaks, _ = find_peaks(x)\nprominences = peak_prominences(x, peaks)[0]\ncontour_heights = x[peaks] - prominences", "_____no_output_____" ], [ "# peak max prominence\ncontour_heights.describe()", "_____no_output_____" ], [ "results_full = peak_widths(x, peaks, rel_height=1)\nmax(results_full[0])", "_____no_output_____" ], [ "medfilt2d(df['Contempt'])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfbfba4cda4e3976760471e14f6e36c0e59b0c6
1,146
ipynb
Jupyter Notebook
old_version/Author Data processing.ipynb
FatimaTafazzoli/CitationPredictor
bc2b502cbdde558a749766913a081c22719e69ad
[ "MIT" ]
null
null
null
old_version/Author Data processing.ipynb
FatimaTafazzoli/CitationPredictor
bc2b502cbdde558a749766913a081c22719e69ad
[ "MIT" ]
null
null
null
old_version/Author Data processing.ipynb
FatimaTafazzoli/CitationPredictor
bc2b502cbdde558a749766913a081c22719e69ad
[ "MIT" ]
null
null
null
1,146
1,146
0.693717
[ [ [ "import pandas as pd\r\nimport ast\r\nimport numpy as np\r\n\r\nfinal_papers = pd.read_csv('papers.csv')\r\nfinal_authors = pd.read_csv('authors.csv')\r\n", "_____no_output_____" ], [ "final_authors['H_index'] = final_authors['papers']\r\nfinal_authors['H_index'] = final_authors.papers.apply(lambda x: list(map(np.int64, ast.literal_eval(x))))\r\nfinal_authors['H_index'] = final_authors.H_index.apply(lambda x: [final_papers.loc[final_papers['id'] == j]['n_citation'].tolist()[0] for j in x])\r\n\r\nfinal_authors['H_index'] = final_authors.H_index.apply(lambda x: sum(j >= i + 1 for i, j in enumerate(sorted(list(x), reverse=True))))\r\n\r\n\r\nfinal_authors.to_csv('authors.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
ecfbfd58dccc7c3d100c0fece5c4b3d89ec9b20e
151,889
ipynb
Jupyter Notebook
Example_notebooks/01 Example_Discriminator Tests.ipynb
jgidi/threerra
cd6aca353d8d5a18bd6638502f8a9d87960b761c
[ "Apache-2.0" ]
3
2021-11-12T20:58:34.000Z
2022-01-13T05:33:11.000Z
Example_notebooks/01 Example_Discriminator Tests.ipynb
jgidi/threerra
cd6aca353d8d5a18bd6638502f8a9d87960b761c
[ "Apache-2.0" ]
null
null
null
Example_notebooks/01 Example_Discriminator Tests.ipynb
jgidi/threerra
cd6aca353d8d5a18bd6638502f8a9d87960b761c
[ "Apache-2.0" ]
null
null
null
233.675385
33,944
0.921278
[ [ [ "# Threerra Example", "_____no_output_____" ], [ "First, we import the necessary packages for the correct execution of our module.", "_____no_output_____" ] ], [ [ "import threerra # Load threerra\n\nimport numpy as np\nfrom qiskit.tools.visualization import plot_histogram\nfrom qiskit.tools.monitor import job_monitor", "_____no_output_____" ], [ "# Load IMB Quantum credentials\nfrom qiskit import IBMQ\nIBMQ.load_account()", "_____no_output_____" ] ], [ [ "It's important to choose a backend that's compatible with Qiskit Pulse, or else the Threerra Module won't be able to be executed. In this case, we use the open-access 1 qubit \"ibmq_armonk\" Quantum Processor, which is available for free.", "_____no_output_____" ] ], [ [ "# Choose device\nprovider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')\nbackend = provider.get_backend('ibmq_armonk')", "_____no_output_____" ] ], [ [ "# Testing different gates and drawing the pulse schedule", "_____no_output_____" ], [ "The first step is to create a quantum circuit with a given backend. This class have a series of pulses already implemented acting on both $01$ and $12$ subspaces, like $X$ gates, rotation gates $R_x(\\theta)$, and more (read Documentation for more details). For the rotation gates, the user needs to also specify a given angle. To better visualize what's beeing applied, the function draw() shows the whole pulse schedule in detail.", "_____no_output_____" ] ], [ [ "# Test QuantumCircuit3\nqc = threerra.QuantumCircuit3(backend) # Initialize the quantum circuit\nqc.rx_01(np.pi/2) # Apply rx gate with angle np.pi/2 in the subspace 01\nqc.x_01() # Apply x gate in the subspace 01\nqc.x_12() # Apply x gate in the subspace 12\nqc.rz(np.pi) # Apply rz gate with angle np.pi\nqc.rx_12(np.pi/2) # Apply rx gate with angle np.pi/2 in the subspace 12\nqc.draw() ", "_____no_output_____" ] ], [ [ "# Test calibrations", "_____no_output_____" ], [ "Before we make a real experiment, it's important to calibrate the $0\\rightarrow1$, $1\\rightarrow2$ frequencies, and also the $0\\rightarrow1$, $1\\rightarrow2$ $\\pi$ pulse amplitudes, using the following functions:", "_____no_output_____" ] ], [ [ "# Calibrate the 0 --> 1 frequency using a frecuency sweep.\n\n\n#qc.calibrate_freq_01()", "Calibrating qubit_freq_est_01...\nJob Status: job has successfully run\nqubit_freq_est_01 updated from 4.971595089951107GHz to 4.971583252011542GHz.\n" ], [ "# Calibrate the 0 --> 1 \\pi pulse with a Rabi experiment\n\n\n#qc.calibrate_pi_amp_01()", "Calibrating pi_amp_01...\nJob Status: job has successfully run\npi_amp_01 updated from 0.1556930479027419 to 0.25020339265292146.\n" ], [ "# Calibrate the 1 --> 2 frequency using a frecuency sweep and the sideband method.\n\n\n#qc.calibrate_freq_12()", "Calibrating qubit_freq_est_12...\nJob Status: job has successfully run\nqubit_freq_est_12 updated from 4.624402158468281GHz to 4.622937542467993GHz.\n" ], [ "# Calibrate the 1 --> 2 \\pi pulse with a Rabi experiment and the sideband method.\n\n\n#qc.calibrate_pi_amp_12()", "Calibrating pi_amp_12...\nJob Status: job has successfully run\npi_amp_12 updated from 0.2797548240848574 to 0.3284615055672541.\n" ] ], [ [ "# Test Measurement ", "_____no_output_____" ], [ "In the following examples, we will test the measurement function, and compare our results with the expected theoretical values. After the calibrations are ready, we import the functions necessary to recover the experiments data and both of our discriminators, the nearest centroid (default configuration) and LDA (Linear Discriminant Analysis) discriminator.", "_____no_output_____" ] ], [ [ "from threerra.tools import get_counts\n\nfrom threerra.discriminators.nearest_discriminator import discriminator as nst_disc\nfrom threerra.discriminators.LDA_discriminator import discriminator as lda_disc", "_____no_output_____" ] ], [ [ "The following circuit takes a $|0\\rangle$ state and returns a $|2\\rangle$ state after applying the gates $X_{01}$ and $X_{12}$. We then apply a measurement pulse to retrieve the data when we execute the circuit.", "_____no_output_____" ] ], [ [ "qc2 = threerra.QuantumCircuit3(backend)\nqc2.x_01()\nqc2.x_12()\nqc2.measure()\nqc2.draw()", "_____no_output_____" ] ], [ [ "Next, we execute the circuit. The job_monitor function tells us the status of the job.", "_____no_output_____" ] ], [ [ "job2 = qc2.run()\njob_monitor(job2)", "Job Status: job has successfully run\n" ] ], [ [ "After the job is done, we get the job's data using the result() function, and apply the get_counts() function with both of our discriminators, to get the number of counts per state.", "_____no_output_____" ] ], [ [ "result2 = job2.result()", "_____no_output_____" ], [ "counts_nst2 = get_counts(result2, discriminator=nst_disc)\ncounts_lda2 = get_counts(result2, discriminator=lda_disc)", "_____no_output_____" ], [ "state2_teo = {'0': 0, '1': 0, '2': 1024}", "_____no_output_____" ] ], [ [ "Finally, we compare the results using both discriminators with the theoretical value with a histogram plot.", "_____no_output_____" ] ], [ [ "comparision2 = [counts_nst2, counts_lda2, state2_teo]", "_____no_output_____" ], [ "plot_histogram(comparision2, legend=['Near','LDA', 'Theoric'])", "_____no_output_____" ] ], [ [ "Finally, we intend to obtain a superposition $\\frac{1}{\\sqrt{2}}\\left(|1\\rangle + |2\\rangle\\right)$. To achieve this, we construct ourselves a Hadamard gate $H_{12}$ that acts onto the $12$ subspace. This gate is constructed as follows:", "_____no_output_____" ] ], [ [ "qc12 = threerra.QuantumCircuit3(backend)\nqc12.x_01()\nqc12.x_12()\nqc12.ry_12(np.pi/2.0)\nqc12.measure()\nqc12.draw()", "_____no_output_____" ], [ "job12 = qc12.run()\njob_monitor(job12)", "Job Status: job has successfully run\n" ], [ "result12 = job12.result()", "_____no_output_____" ], [ "counts_lda12 = get_counts(result12, discriminator=lda_disc)\ncounts_nst12 = get_counts(result12, discriminator=nst_disc)\n", "_____no_output_____" ], [ "state12_teo = {'0': 0, '1': 512, '2': 512}", "_____no_output_____" ], [ "comparision12 = [counts_nst12, counts_lda12, state12_teo]", "_____no_output_____" ], [ "plot_histogram(comparision12, legend=['Near','LDA', 'Theoric'])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc03efba491e02c774507206b0467085a9cfb4
13,771
ipynb
Jupyter Notebook
sql-tutorial/IntroDBWorkshop.ipynb
georgetown-analytics/XBUS-502-01.Data_Sources_Storage
458fb9cc1563a17f93e221e8ea38272d07329e2d
[ "MIT" ]
11
2016-10-21T21:50:39.000Z
2021-04-22T20:19:13.000Z
sql-tutorial/IntroDBWorkshop.ipynb
georgetown-analytics/XBUS-502-01.Data_Sources_Storage
458fb9cc1563a17f93e221e8ea38272d07329e2d
[ "MIT" ]
3
2016-09-24T18:27:43.000Z
2016-10-19T23:49:22.000Z
sql-tutorial/IntroDBWorkshop.ipynb
georgetown-analytics/XBUS-502-01.Data_Sources_Storage
458fb9cc1563a17f93e221e8ea38272d07329e2d
[ "MIT" ]
30
2016-10-06T00:17:31.000Z
2022-03-05T16:42:30.000Z
38.791549
584
0.621596
[ [ [ "# Database Interaction with Python\n\n[PEP 249 - The Python Database API Specification](https://www.python.org/dev/peps/pep-0249/) gives very specific instructions for how Python developers should interact with databases. Although there are some notable differences in the database backends, what that means is that from the Python perspective, the use of different databases like SQLite, PostgreSQL, MySQL, etc. should all be very similar. In this tutorial, we will go over the use of Python with SQLite - a lightweight and simple database that will immediately make the data management in your apps more effective.", "_____no_output_____" ] ], [ [ "## Imports\n\nimport sqlite3", "_____no_output_____" ] ], [ [ "The first thing to keep in mind is that we have to import _driver_ code - that is the API for the specific database that we want to use. The most common are:\n\n- [psycopg2](http://initd.org/psycopg/)\n- [MySQL Connector/Python](http://dev.mysql.com/doc/connector-python/en/)\n- [sqlite3](https://docs.python.org/2/library/sqlite3.html)\n\nThough a host of other databases for vendors like IBM, Microsoft, and Oracle can be found at [Python Database Interfaces](https://wiki.python.org/moin/DatabaseInterfaces). \n\nIn this tutorial we will be using `sqlite3` because it ships with Python (the other drivers are third party) and because it is so simple to use. SQLite databases are the embedded backbone of many applications, though they should be kept small. \n\n## Connecting to a Database\n\nThe first thing you have to do is make a connection to a database. Often times this means you'll need the following information to connect to a database server:\n\n- hostname\n- port \n- username\n- password\n- database name\n\nSQLite is an _embedded_ database, however - which means it is stored in a file on disk, and operated on soley by a single program (not multiple programs at once). Therefore in order to create a connection to a SQLite database, we simply need to point it to a file on disk. ", "_____no_output_____" ] ], [ [ "DBPATH = 'people.db'\nconn = sqlite3.connect(DBPATH)", "_____no_output_____" ] ], [ [ "At this point, you should notice that a file called `people.db` has been created in your current working directory! \n\nThe connect method returned a connection object that we've called `conn`. With conn you can manipulate your connection to the database including the following methods:\n\n- `conn.commit()` - commit any changes back to the database\n- `conn.close()` - close our connection to the database and tidy up\n\nHowever, to execute SQL against the database to `INSERT` or `SELECT` rows, we'll need to create a cursor:", "_____no_output_____" ] ], [ [ "cursor = conn.cursor()", "_____no_output_____" ] ], [ [ "A cursor is essentially a pointer into the database. Think of it like a mouse cursor that keeps track of where you are on in the database table or tables. Cursors have the following methods:\n\n- `cursor.execute()` - executes a SQL string against the database\n- `cursor.fetchone()` - fetch a single row back from the executed query\n- `cursor.fetchall()` - fetch all results back from the executed query. \n\nTogether, connections and cursors are the basic way to interact with a SQL database. \n\n## Describing the Database\n\nThe first thing we have to do is describe the type of data that we'll be putting in the database by creating a _schema_. For this workshop, we'll be creating a very simple contacts application. Our schema is as follows:\n\n![Contacts Schema](figures/schema.png)\n\nHere we have two tables, `contacts` which keeps track of people, their email, and who they are affiliated with, and `companies` which keeps tracks of organizations. To create the companies table we would execute SQL as follows:", "_____no_output_____" ] ], [ [ "sql = (\n \"CREATE TABLE IF NOT EXISTS companies (\"\n \" id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \" name TEXT NOT NULL\"\n \")\"\n)\n\ncursor.execute(sql)", "_____no_output_____" ] ], [ [ "A note on the syntax above - since I like to write clean, well-indented SQL; I used a string concatentation method in Python, by opening up a parentheses and adding strings _without commas_ on new lines between them. If you print `sql` you'll see it's just one long string with spaces inside of it. You could also use docstrings with the three quotes `\"\"\"` to write a multiline string, or even read in the SQL from a file. \n\nNow write and execute the contacts table create statement. ", "_____no_output_____" ] ], [ [ "# Create the contacts table", "_____no_output_____" ] ], [ [ "## Inserting Records \n\nThe next thing we'll want to do is insert some records into the database. Let's add Georgetown University to the companies table.", "_____no_output_____" ] ], [ [ "sql = \"INSERT INTO companies (name) VALUES (?)\"\ncursor.execute(sql, (\"Georgetown University\",))\nconn.commit()", "_____no_output_____" ] ], [ [ "Here we've created essentially a SQL template for inserting the names of companies into the table. Note that we don't have to assign an id, since it will be automatically assigned using the AUTOINCREMENT property of that field.\n\nThe `?` is a parameter to the query, and can be used as a placeholder for any user input. Values for the parameters are then passed to the second argument of the `execute` method as a tuple. You _should not_ use string formatting methods like: \n\n```python\nsql = \"INSERT INTO companies (name) VALUES ({})\".format(\"Georgetown University\")\n```\n\nThis is potentially unsafe behavior, and the `?` parameters do a lot of work on your behalf to make sure things work correctly and securely. \n\nLet's go ahead and insert another record using the same sql statement.", "_____no_output_____" ] ], [ [ "cursor.execute(sql, (\"US Department of Commerce\",))\nconn.commit()", "_____no_output_____" ] ], [ [ "The last thing we should mention is the `commit` call. _Nothing will be written to the database until commit is called_. This gives us an interesting ability to do _transactions_ - a series of SQL queries that when completed together succesfully, we commit them. However if something goes wrong during execution, we don't commit and therefore \"rollback\". \n\n## Selecting Records\n\nBefore we go on to insert contact information, we need to know the id of the company of the contact we're inserting. However, because we inserted the data using the auto increment feature, we don't know what the company's ids are. To read them, we'll have to fetch them as follows:", "_____no_output_____" ] ], [ [ "cursor.execute(\"SELECT id FROM companies WHERE name=?\", (\"Georgetown University\",))\nprint(cursor.fetchone())", "_____no_output_____" ] ], [ [ "Using the same parameter statement in our predicate clause and passing in the tuple containing \"Georgetown University\" as an argument to `execute`, we can select the id that we need, which is returned as a `Row`. `Row`s present themselves as tuples, and since we only fetched the ID, it is the first element in the record. Note that we can use `SELECT *` to select all fields in a record if so desired. \n\nThe `fetchone` statement goes and gets the first record it finds. Note that the name of companies are not constrained uniqueness, therefore there could be multiple \"Georgetown University\" records fetched from this query. If you wanted all of them, you would use `fetchall`. \n\nNow to insert a person who works for Georgetown University you would write a statement similar to:\n\n```python\nsql = \"INSERT INTO contacts (name, email, company_id) VALUES (?,?,?)\" \ncursor.execute(sql, (\"Benjamin Bengfort\", \"[email protected]\", 1))\nconn.commit()\n```\n\nAnd at this point you should start inserting some contacts and companies.", "_____no_output_____" ] ], [ [ "# Insert some contacts and companies using the methods described above.", "_____no_output_____" ] ], [ [ "Consider the following questions while you're working with the database:\n\n- What errors have you been receiving? What would you do to prevent them (e.g. create guarentees)?\n- What happens if you pass in a name that doesn't exist in the database to our company select? \n- What happens if you run the insert statements twice in a row with the same values?\n- How would you ensure that company name, and email are unique? What other fields should be unique? \n\n## Workshop\n\nAt this point, you should be able to create a small Python application that does the following:\n\n- Inserts contacts into the database by gathering their name, email, and company name\n- Prints out a list of companies and the number of contacts associated with each \n\nUsing the following _incomplete_ code as a template to help you design your project:", "_____no_output_____" ] ], [ [ "import os\nimport sqlite3\n\nDBPATH = 'people.db'\nconn = sqlite3.connect(DBPATH)\n\n\ndef create_tables(conn):\n \"\"\"\n Write your CREATE TABLE statements in this function and execute\n them with the passed in connection. \n \"\"\"\n # TODO: fill in. \n pass\n\n\ndef connect(path=\"people.db\", syncdb=False):\n \"\"\"\n Connects to the database and ensures there are tables.\n \"\"\"\n \n # Check if the SQLite file exists, if not create it.\n if not os.path.exists(path):\n syncdb=True\n\n # Connect to the sqlite database\n conn = sqlite3.connect(path)\n if syncdb:\n create_tables(conn)\n \n return conn\n\n\ndef insert(name, email, company, conn=None):\n if not conn: conn = connect()\n\n # Attempt to select company by name first. \n \n # If not exists, insert and select new id.\n \n # Insert contact\n\n \nif __name__ == \"__main__\":\n name = input(\"Enter name: \")\n email = input(\"Enter email: \")\n company = input(\"Enter company: \")\n \n conn = connect()\n insert(name, email, company, conn)\n\n # Change below to count contacts per company! \n contacts = len(cursor.execute(\"SELECT id FROM contacts WHERE company_id=?\", (company_id,)).fetchone())\n print(\"The {0} now has {1} contacts.\".format(company, contacts))\n\n conn.close()", "_____no_output_____" ] ], [ [ "## Questions to Think about for Next Time\n\n1. Why use a database? Why not just use Pandas dataframes?\n2. Why is it easier to work with a database then with raw JSON?\n3. How is using PostgreSQL different from using SQLite?\n4. How is MongoDB different than a relational database? \n5. What would make you choose a relational database over a NoSQL database (and vice versa)?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecfc0f9e70d630aea8bbe669c94a80584954b99a
302,716
ipynb
Jupyter Notebook
_posts/python-v3/report-generation/email-reports.ipynb
arauzo/graphing-library-docs
c99f3ed921727e1dcb321e6a52c5c7f7fe74356d
[ "CC-BY-3.0" ]
43
2020-02-06T00:54:56.000Z
2022-03-24T22:29:33.000Z
_posts/python-v3/report-generation/email-reports.ipynb
arauzo/graphing-library-docs
c99f3ed921727e1dcb321e6a52c5c7f7fe74356d
[ "CC-BY-3.0" ]
92
2020-01-31T16:23:50.000Z
2022-03-21T05:31:39.000Z
_posts/python-v3/report-generation/email-reports.ipynb
arauzo/graphing-library-docs
c99f3ed921727e1dcb321e6a52c5c7f7fe74356d
[ "CC-BY-3.0" ]
63
2020-02-08T15:16:06.000Z
2022-03-29T17:24:38.000Z
715.640662
224,553
0.949804
[ [ [ "## Emailing Plotly Graphs\n\nIn the [Plotly Webapp](https://plotly.com/plot) you can share your graphs over email to your colleagues who are also Plotly members. If your making graphs periodically or automatically, e.g. [in Python with a cron job](http://moderndata.plot.ly/update-plotly-charts-with-cron-jobs-and-python/), it can be helpful to also share the graphs that you're creating in an email to your team.\n\nThis notebook is a primer on sending nice HTML emails with Plotly graphs in Python. We use:\n- [Plotly](https://plotly.com/python/) for interactive, web native graphs\n- [IPython Notebook](https://plotly.com/ipython-notebooks) to create this notebook, combining text, HTML, and Python code\n- [`smtplib` and `email`](https://docs.python.org/2/library/email-examples.html) libraries included in the Python standard library", "_____no_output_____" ], [ "### Part 1 - An email template", "_____no_output_____" ] ], [ [ "# The public plotly graphs to include in the email. These can also be generated with `py.plot(figure, filename)`\ngraphs = [\n 'https://plotly.com/~christopherp/308',\n 'https://plotly.com/~christopherp/306',\n 'https://plotly.com/~christopherp/300',\n 'https://plotly.com/~christopherp/296'\n]", "_____no_output_____" ], [ "from IPython.display import display, HTML\n\ntemplate = (''\n '<a href=\"{graph_url}\" target=\"_blank\">' # Open the interactive graph when you click on the image\n '<img src=\"{graph_url}.png\">' # Use the \".png\" magic url so that the latest, most-up-to-date image is included\n '</a>'\n '{caption}' # Optional caption to include below the graph\n '<br>' # Line break\n '<a href=\"{graph_url}\" style=\"color: rgb(190,190,190); text-decoration: none; font-weight: 200;\" target=\"_blank\">'\n 'Click to comment and see the interactive graph' # Direct readers to Plotly for commenting, interactive graph\n '</a>'\n '<br>'\n '<hr>' # horizontal line\n'')\n\nemail_body = ''\nfor graph in graphs:\n _ = template\n _ = _.format(graph_url=graph, caption='')\n email_body += _\n \ndisplay(HTML(email_body))", "_____no_output_____" ] ], [ [ "Looks pretty good!", "_____no_output_____" ], [ "## Part 2 - Sending the email\n\nEmail server settings. This example will use the common settings for `gmail`", "_____no_output_____" ] ], [ [ "me = '[email protected]'\nrecipient = '[email protected]'\nsubject = 'Graph Report'\n\nemail_server_host = 'smtp.gmail.com'\nport = 587\nemail_username = me\nemail_password = 'xxxxx'", "_____no_output_____" ] ], [ [ "Send the email", "_____no_output_____" ] ], [ [ "import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nimport os\n\nmsg = MIMEMultipart('alternative')\nmsg['From'] = me\nmsg['To'] = recipient\nmsg['Subject'] = subject\n\nmsg.attach(MIMEText(email_body, 'html'))\n\nserver = smtplib.SMTP(email_server_host, port)\nserver.ehlo()\nserver.starttls()\nserver.login(email_username, email_password)\nserver.sendmail(me, recipient, msg.as_string())\nserver.close()", "_____no_output_____" ] ], [ [ "![Screenshot of the sent email](http://i.imgur.com/mzCZUEE.png)", "_____no_output_____" ], [ "## Notes\n\n### Sharing Private Images\n\nPlotly graphs are *public* by default. This means that they will appear on your profile, the plotly feed, google search results.\n\nTo share private images in an email, make your graphs [\"secret\"](plot.ly/python/privacy). The graphs will be unlisted from your profile but will still be accessible by the email server via a direct link - no login authentication is required.\n\nSecret links have the form: [https://plotly.com/~&lt;username&gt;/&lt;id&gt;?share_key=&lt;share_key&gt;](). Secret images have \".png\" after \"id\" and before the \"?\". For example:\n\nThis graph: https://plotly.com/~chelsea_lyn/17461?share_key=3kCBg9awEny15vobuAP5Up\n\nHas the secret unlisted image url: https://plotly.com/~chelsea_lyn/17461.png?share_key=3kCBg9awEny15vobuAP5Up", "_____no_output_____" ] ], [ [ "from IPython.display import display, HTML\n\ntemplate = (''\n '<a href=\"{graph_url}\" target=\"_blank\">' # Open the interactive graph when you click on the image\n '<img src=\"{graph_url}\">' # Use the \".png\" magic url so that the latest, most-up-to-date image is included\n '</a>'\n '{caption}' # Optional caption to include below the graph\n '<br>' # Line break\n '<a href=\"{graph_url}\" style=\"color: rgb(190,190,190); text-decoration: none; font-weight: 200;\" target=\"_blank\">'\n 'Click to comment and see the interactive graph' # Direct readers to Plotly for commenting, interactive graph\n '</a>'\n '<br>'\n '<hr>' # horizontal line\n'')\n\nemail_body = ''\ngraph = 'https://plotly.com/~chelsea_lyn/17461.png?share_key=3kCBg9awEny15vobuAP5Up'\n_ = template\n_ = _.format(graph_url=graph, caption='')\nemail_body += _\n\ndisplay(HTML(email_body))", "_____no_output_____" ] ], [ [ "### The graph images\n\nThe HTML template that we used includes the images by their URL on the Plotly server. The viewers of the email must have permission on Plotly to view your graph. Graphs sent in emails by Chart Studio Enterprise users on private networks will not be able to be viewed outside of the network.\n\nThe reader of your email will always see the latest verison of the graph! This is great - if you tweak your graph or add an annotation, you don't need to resend the email out. If your graph updates regularly, e.g. every hour, the reader will see the latest, most updated version of the chart.\n\nFor some email clients, you can download the image and include it inline the email. This allows you to share the graph outside of your network with Chart Studio Enterprise, and keep the graph entirely private. [Note that this is not widely supported.](https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/) Here is the support from a few years ago: ![embedded image support in emails from 2003](http://i.imgur.com/WIRhmCz.png)\n\nHere is how to embed images inline in HTML:", "_____no_output_____" ] ], [ [ "import requests\nimport base64\n\ntemplate = (''\n '<img src=\"data:image/png;base64,{image}\">' \n '{caption}' # Optional caption to include below the graph\n '<br>'\n '<hr>'\n'')\n\nemail_body = ''\nfor graph_url in graphs:\n response = requests.get(graph_url + '.png') # request Plotly for the image\n response.raise_for_status()\n image_bytes = response.content\n image = base64.b64encode(image_bytes).decode(\"ascii\")\n _ = template\n _ = _.format(image=image, caption='')\n email_body += _\n\ndisplay(HTML(email_body))", "_____no_output_____" ] ], [ [ "Alternatively, you can create the image on the fly, without a URL using `py.image.get`. (Learn more about `py.image` by calling `help(py.image)`)", "_____no_output_____" ] ], [ [ "import plotly.plotly as py\n\n# A collection of Plotly graphs\nfigures = [\n {'data': [{'x': [1,2,3], 'y': [3,1,6]}], 'layout': {'title': 'the first graph'}},\n {'data': [{'x': [1,2,3], 'y': [3,7,6], 'type': 'bar'}], 'layout': {'title': 'the second graph'}}\n]\n\n# Generate their images using `py.image.get`\nimages = [base64.b64encode(py.image.get(figure)).decode(\"ascii\") for figure in figures]\n\nemail_body = ''\nfor image in images:\n _ = template\n _ = _.format(image=image, caption='')\n email_body += _\n \ndisplay(HTML(email_body))", "_____no_output_____" ] ], [ [ "### The graph URLs\n\nWe hard-coded the graph URLs above, but we can also generate the URLs with `py.plot`:", "_____no_output_____" ] ], [ [ "import plotly.plotly as py\n\nurl = py.plot([{'x': [1,2,3], 'y': [3,1,6], 'type': 'bar'}], auto_open=False, filename='email-report-graph-1')\nprint(url)", "https://plotly.com/~PythonPlotBot/3079\n" ] ], [ [ "### Updating graphs\n\nIf we use the same `filename`, the graph will save to the same URL. So, if we include a graph in an email by it's URL, we can update that graph by calling `py.plot` with the same filename.", "_____no_output_____" ], [ "### Learn more\n- Questions? <[email protected]>\n- [Getting started with Plotly and Python](https://plotly.com/python/getting-started)\n- [Updating Plotly graphs with Python and cron jobs](http://moderndata.plot.ly/update-plotly-charts-with-cron-jobs-and-python/)\n- [Using Plotly offline in IPython notebooks](https://plotly.com/python/offline)\n- [Generate HTML reports with Python, Pandas, and Plotly](http://moderndata.plot.ly/generate-html-reports-with-python-pandas-and-plotly/)\n- [Edit this tutorial](https://github.com/plotly/documentation/tree/gh-pages)", "_____no_output_____" ] ], [ [ "! pip install publisher --upgrade\n\nimport publisher\npublisher.publish('email-reports', '/python/email-reports', \n 'Emailing Plotly Graphs with Python', \n 'How to email Plotly graphs in HTML reports with Python.',\n uses_plotly_offline=True)", "Requirement already up-to-date: publisher in c:\\anaconda\\anaconda3\\lib\\site-packages (0.13)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
ecfc1cd749d9edc9e5c1db33f35f54bcb48e2fdc
186,327
ipynb
Jupyter Notebook
Thursday/Unit_1_Build_Week.ipynb
n8mcdunna/Traffic_stops
0a19698830d652aea738d0a333c5ce3e4ba0e4ad
[ "MIT" ]
null
null
null
Thursday/Unit_1_Build_Week.ipynb
n8mcdunna/Traffic_stops
0a19698830d652aea738d0a333c5ce3e4ba0e4ad
[ "MIT" ]
null
null
null
Thursday/Unit_1_Build_Week.ipynb
n8mcdunna/Traffic_stops
0a19698830d652aea738d0a333c5ce3e4ba0e4ad
[ "MIT" ]
null
null
null
175.284102
62,398
0.846243
[ [ [ "<a href=\"https://colab.research.google.com/github/n8mcdunna/Traffic_stops/blob/master/Thursday/Unit_1_Build_Week.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import chi2_contingency", "_____no_output_____" ], [ "df = pd.read_csv('http://users.stat.ufl.edu/~winner/data/trafficstop.csv')", "_____no_output_____" ], [ "# Description of data http://users.stat.ufl.edu/~winner/data/trafficstop.txt", "_____no_output_____" ], [ "# Changing dataframe column name and creatingn label variables\ndf.columns = ['Month', 'Reason for Stop', 'Officer Race', 'Officer Gender', 'Officer Years of Service', 'Driver Race', 'Driver Hispanic', \n 'Driver Gender', 'Driver Age', 'Search of Vehicle', 'Result of Stop']\nreason_labels = ['Checkpoint', 'DWI', 'Investigation', 'Other', 'Safe\\nMovement', 'Seatbelt', 'Speeding', 'StopLight\\nor Sign', 'Vehicle\\nMovement', 'Vehicle\\nRegistry']\nofficer_race_labels = ['Native American', 'Asian', 'African American', 'Hispanic', 'White', 'Unspecified']\ndriver_race_labels = ['Asian', 'African American', 'Native American', 'Other/Unknown', 'White']\nresult_labels = ['No Action Taken', 'Verbal Warning', 'Written Warning', 'Citation', 'Arrest']", "_____no_output_____" ], [ "df['Officer Race'] = df['Officer Race'].replace(np.nan, 6) # replacing NaNs in officer race with 6. NaN did stand for undefined", "_____no_output_____" ], [ "# Dividing variables into categorical and numerical for t-tests\ncat_variables = df.loc[:,['Month', 'Reason for Stop', 'Officer Race', 'Officer Gender', 'Driver Race', 'Driver Hispanic', 'Driver Gender', 'Search of Vehicle', 'Result of Stop']]\nnum_variables = df.loc[:,['Officer Years of Service', 'Driver Age']]", "_____no_output_____" ], [ "print(df.shape)\ndf.head()", "(79884, 11)\n" ], [ "# Putting age into categories to make cleaner looking graph\nbins = [x for x in range(10, 80, 10)]\nnames = ['Teens', '20s', '30s', '40s', '50s', '60+']\ndf['Age Group'] = pd.cut(df['Driver Age'], bins, labels= names)", "_____no_output_____" ], [ "# Getting age group totals\ndrivers_by_age_group = df['Age Group'].value_counts(ascending= True)\ndf3 = pd.crosstab(df['Age Group'], df['Reason for Stop'], margins= True, normalize= True) * 100", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nplt.style.use('fivethirtyeight')\n\n# Figure dimensions\nfig.set_figheight(5)\nfig.set_figwidth(10)\n\nbar_plot = sns.barplot(x= drivers_by_age_group, y= drivers_by_age_group.index)\n\nbar_plot.set(xlabel= \"Traffic Stops\",\n ylabel= 'Age Groups',\n title= 'Traffic Stops by Age Groups')\nplt.savefig('age_groups.png', bbox_inches= 'tight')\nplt.show();", "_____no_output_____" ], [ "# Creating dataframe using percentages of reason for stop and age group\ndf4 = pd.crosstab(df['Reason for Stop'], df['Age Group'], margins= True, normalize= True) * 100\nprint(df4.columns)\nprint(df4.index)", "Index(['Teens', '20s', '30s', '40s', '50s', '60+', 'All'], dtype='object', name='Age Group')\nIndex([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'All'], dtype='object', name='Reason for Stop')\n" ], [ "fig, ax = plt.subplots()\nplt.style.use('fivethirtyeight')\n\n# Creating colors for plotting. Used paired since it had 12 values and visually appealing\ncolor = sns.color_palette('Paired', 11)[::-1]\n\nfor name in df4.columns[:-1]: # iterating through all columns except for 'All'\n foundation = 0\n for i in df4.index[:-1]: # iterating through all rows except for 'All'\n height = (df4[name][i] / df4[name]['All'])*100 # calculating percentages for each row and column\n ax.bar(x= name, bottom= foundation, height= height, width= 0.97, color= color[i]) # setting width to give a little gap, and iterating through color palette\n foundation += height\n\nplt.title('Age Groups and Reason for Traffic Stop')\nfig.set_figheight(7)\nfig.set_figwidth(15)\n\nax.set_xlabel('Age Group')\nax.set_ylabel('Percent of Traffic Stops', fontsize= 'large')\n\nreason_labels = ['Checkpoint', 'DWI', 'Investigation', 'Other', 'Safe Movement', 'Seatbelt', 'Speeding', 'StopLight or Sign', 'Vehicle Movement', 'Vehicle Registry']\n\n# Used label spacing to reverse the order of the legend to match the graph and bbox to anchor to move legend to appropriate spot\nax.legend(labels= reason_labels, fontsize= 'large', loc='best', bbox_to_anchor=(1, .3), labelspacing= -2.5, frameon= False)\n\nax.set_xticklabels(df4.columns[:-1])\nax.set_xticks(ticks= [0, 1, 2, 3, 4, 5])\n\nplt.savefig('age_group_and_result.png', bbox_inches= 'tight')\nplt.show();", "_____no_output_____" ] ], [ [ "Performing chi square analysis on categorical variable. After performing analysis all of the categorical values are closely linked to each other due to their very small p-values.", "_____no_output_____" ] ], [ [ "# Performing statistical analysis on categorical variables\ndef chi_square(column_name):\n results = [(column, chi2_contingency(pd.crosstab(cat_variables[column], cat_variables[column_name]))[1]) for column in cat_variables.columns]\n results = pd.DataFrame(results)\n results.columns = ['Variable', 'p-value']\n results = results.sort_values(by= ['p-value'])\n return results", "_____no_output_____" ], [ "chi_square('Reason for Stop')", "_____no_output_____" ], [ "chi_square('Result of Stop')", "_____no_output_____" ], [ "chi_square('Search of Vehicle')", "_____no_output_____" ], [ "df2 = pd.crosstab(df['Result of Stop'], df['Reason for Stop'], margins= True, normalize= True)*100", "_____no_output_____" ], [ "# Sorting values smallest to largest to create cleaner graph\ndf2 = df2.sort_values(by= 'All', axis= 1)\ndf2", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nplt.style.use('fivethirtyeight')\n\ncolor = sns.color_palette('hls', 5)\n\nk = 0 # Used k to keep track of where to plt on the x-axis\nfor x in df2.columns[:-1]:\n foundation = 0\n k += 1\n for i in df2.index[:-1]:\n height = df2[x][i]\n ax.bar(x= k, bottom= foundation, height= height, width= 0.97, color= color[5-i])\n foundation += height\n\n# Adding text to highlight attributes of the data\nax.text(0.75, 0.3, s= '0.14%', fontsize= 16)\nax.text(2.75, 1.5, s= '0.79%', fontsize= 16)\n\nplt.title('Reason For and Result Of Traffic Stop')\nfig.set_figheight(7)\nfig.set_figwidth(15)\nfig.set_facecolor('lightgrey')\nax.set_xlabel('Reason for Traffic Stop')\nax.set_ylabel('Percent of Traffic Stops', fontsize= 'large')\n\n# Used bbox to anchor to move legend to appropriate spot\nax.legend(labels= result_labels, fontsize= 'large', labelspacing= -2.5, frameon= False, loc= 'upper left', bbox_to_anchor = (0, 0.72))\n\n\nreason_labels = ['DWI','Checkpoint','Seatbelt','Other','Investigation','Safe\\nMovement','Vehicle\\nMovement','StopLight\\nor Sign','Speeding','Vehicle\\nRegistry']\nax.set_xticklabels(reason_labels)\nax.set_xticks(ticks= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n\nplt.savefig('reason_and_result.png', bbox_inches= 'tight')\nplt.show();", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc2d27bb3ff0b235c0d81486b40ccd45f1632f
10,625
ipynb
Jupyter Notebook
.ipynb_checkpoints/Untitled2-checkpoint.ipynb
r33did/SkripsiEmosiRNN
0bfdb7d19850bbcd994fc4a8557a52716ae38128
[ "MIT" ]
2
2021-09-15T08:25:41.000Z
2021-11-12T06:42:31.000Z
.ipynb_checkpoints/Untitled2-checkpoint.ipynb
r33did/SkripsiEmosiRNN
0bfdb7d19850bbcd994fc4a8557a52716ae38128
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Untitled2-checkpoint.ipynb
r33did/SkripsiEmosiRNN
0bfdb7d19850bbcd994fc4a8557a52716ae38128
[ "MIT" ]
null
null
null
30.09915
312
0.456565
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport keras\nfrom keras.utils.vis_utils import plot_model\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import MinMaxScaler", "_____no_output_____" ], [ "model = keras.models.load_model('iaps_real4')\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlstm (LSTM) (None, None, 8) 480 \n_________________________________________________________________\nlstm_1 (LSTM) (None, 8) 544 \n_________________________________________________________________\ndense (Dense) (None, 4) 36 \n=================================================================\nTotal params: 1,060\nTrainable params: 1,060\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "weights = model.get_weights()\nfor i in range(0,8):\n# print('---------------------------------------------------------------------------------------')\n# print(' array '+str(i)+' ')\n# print('---------------------------------------------------------------------------------------')\n print(len(weights[i]))", "6\n8\n32\n8\n8\n32\n8\n4\n" ], [ "X = []\ny = []\nmaindirs = 'IAPS1_extract'\ndirs = os.listdir(maindirs)\nemosi = ['NH','NL','PH','PL']\ndf = pd.read_csv(maindirs+\"/\"+\"iaps2_extracted.csv\")\nd_t = df.drop('EMOSI',axis=1)\nlabel = pd.get_dummies(df['EMOSI'])\ndata_len = int(len(d_t))\nfor i in range (0,data_len):\n temp = d_t.iloc[i]\n temp_list = temp.values.tolist()\n X.append(temp_list)\nfor j in range(0,data_len):\n temp1 = label.iloc[j]\n temp1_list = temp1.values.tolist()\n y.append(temp1_list)\nX = np.array(X)\ny = np.array(y)\nlength = 760\nnum_train = 502\nindex = np.random.randint(0,length, size=length)\ntrain_X = X[index[0:num_train]]\ntrain_Y = y[index[0:num_train]]\ntest_X = X[index[num_train:]]\ntest_Y = y[index[num_train:]]\n# train_X = X[0:num_train]\n# train_Y = y[0:num_train]\n# test_X = X[num_train:]\n# test_Y = y[num_train:]\ntrain_X = np.reshape(train_X, (train_X.shape[0],1,train_X.shape[1]))\ntest_X = np.reshape(test_X, (test_X.shape[0],1,test_X.shape[1]))", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "asu = np.array([])", "_____no_output_____" ], [ "length = len(df)\nfor i in range(0,length):\n asu = np.append(asu, df.iloc[i])", "_____no_output_____" ], [ "asu = np.array(d_t.iloc[:])\nprint(asu)", "[[ 0.27423523 0.43509133 0.41107785 0.38136022 19.3708455 19.30151011]\n [ 0.20529628 0.33692731 0.38096757 0.83831343 17.40181015 17.5788737 ]\n [ 0.20590605 0.5494333 0.52039537 0.4139998 18.6453618 18.73064732]\n ...\n [ 0.18860092 0.5218596 0.50241615 38.37591242 86.91961848 83.60833966]\n [ 0.31366321 0.27836033 0.17831597 0.43181846 0.96653491 0.94095904]\n [ 0.30999524 0.35429093 0.35610547 0.22410245 0.38152829 0.29113767]]\n" ], [ "scaler = MinMaxScaler()\nscaler.fit_transform(asu)\nkmeans = KMeans(n_clusters = 5, random_state=123)\nkmeans.fit(asu)\nprint(kmeans.cluster_centers_)\ndf['EMOSI']=kmeans.labels_", "[[ 0.29335628 0.3759173 0.32083774 1.1274295 3.86348356 3.56465025]\n [ 0.24352653 0.47824451 0.43717564 7.99087656 62.82924379 66.616183 ]\n [ 0.27955576 0.40335829 0.33950346 3.23402839 16.40916435 16.13088129]\n [ 0.222435 0.46566447 0.46100099 35.86297881 76.97559987 87.38707364]\n [ 0.26442974 0.39280108 0.3778977 16.56907055 31.60515045 26.06091807]]\n" ], [ "output = plt.scatter(asu[:,0], asu[:,1], s = 100, c = df.EMOSI, marker = 'o', alpha = 1, )\ncenters = kmeans.cluster_centers_\nplt.scatter(centers[:,0], centers[:,1], c='red', s=200, alpha=1 , marker='o');\nplt.title('Hasil Klustering K-Means')\nplt.colorbar (output)\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc2dfb0baffb5b3318f65a756be63c89159036
147,855
ipynb
Jupyter Notebook
house_rent_prediction_using_deep_learning.ipynb
diptomondal007/Ai-Assignment
0bb6dafa338ca963a3a40e74f13e50a59047fcff
[ "Apache-2.0" ]
null
null
null
house_rent_prediction_using_deep_learning.ipynb
diptomondal007/Ai-Assignment
0bb6dafa338ca963a3a40e74f13e50a59047fcff
[ "Apache-2.0" ]
null
null
null
house_rent_prediction_using_deep_learning.ipynb
diptomondal007/Ai-Assignment
0bb6dafa338ca963a3a40e74f13e50a59047fcff
[ "Apache-2.0" ]
null
null
null
70.845712
27,494
0.563877
[ [ [ "<a href=\"https://colab.research.google.com/github/diptomondal007/Ai-Assignment/blob/main/house_rent_prediction_using_deep_learning.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "from google.colab import files\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n%matplotlib inline", "_____no_output_____" ], [ "data_frame = pd.read_csv(\"RentRaw.csv\")\ndata_frame.head()", "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (12) have mixed types.Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n" ], [ "data_frame = data_frame.dropna()", "_____no_output_____" ], [ "data_frame = data_frame.reset_index(drop=True)", "_____no_output_____" ], [ "data_frame.isnull().sum()", "_____no_output_____" ], [ "data_frame = data_frame.drop_duplicates()\ndata_frame = data_frame.reset_index(drop=True)", "_____no_output_____" ], [ "data_frame = data_frame[[\"BuiltUpSize\", \"NoOfBathroom\", \"NoOfBedroom\", \"NoOfParking\", \"State\", \"Furnishing\", \"PropertyType\", \"RentalPerMth\"]]\ndata_frame.head()", "_____no_output_____" ], [ "data_frame[\"State\"].value_counts()", "_____no_output_____" ], [ "data_frame[\"State\"] = data_frame[\"State\"].replace(\"Selangor\", \"selangor\")", "_____no_output_____" ], [ "data_frame[\"Furnishing\"].value_counts()", "_____no_output_____" ], [ "data_frame = data_frame[data_frame[\"Furnishing\"] != \"Unknown\"].reset_index(drop=True)", "_____no_output_____" ], [ "data_frame = data_frame[data_frame[\"BuiltUpSize\"] != 0].reset_index(drop=True)\n\ndata_frame = data_frame[data_frame[\"NoOfBedroom\"] != 0].reset_index(drop=True)\n\ndata_frame = data_frame[data_frame[\"NoOfBathroom\"] != 0].reset_index(drop=True)\n\ndata_frame = data_frame[data_frame[\"NoOfParking\"] != 0].reset_index(drop=True)\n\ndata_frame = data_frame[data_frame[\"RentalPerMth\"] != 0].reset_index(drop=True)", "_____no_output_____" ], [ "plt.subplot(121)\nsns.distplot(data_frame[\"RentalPerMth\"]);\n\nplt.subplot(122)\ndata_frame[\"RentalPerMth\"].plot.box(figsize=(16,5))\n\nplt.show()", "/usr/local/lib/python3.6/dist-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).\n warnings.warn(msg, FutureWarning)\n" ], [ "data_frame = data_frame[data_frame[\"RentalPerMth\"] <= 10000].reset_index(drop=True)", "_____no_output_____" ], [ "with pd.option_context('float_format', '{:f}'.format): print(data_frame[\"RentalPerMth\"].describe())", "count 24426.000000\nmean 2101.786211\nstd 1077.809424\nmin 110.000000\n25% 1400.000000\n50% 1800.000000\n75% 2500.000000\nmax 10000.000000\nName: RentalPerMth, dtype: float64\n" ], [ "data_frame_with_dummy = pd.get_dummies(data_frame)\ndata_frame_with_dummy.head()", "_____no_output_____" ], [ "X = data_frame_with_dummy.drop(columns=[\"RentalPerMth\"])\nY = data_frame_with_dummy[\"RentalPerMth\"]", "_____no_output_____" ], [ "from 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=101)", "_____no_output_____" ], [ "y_test", "_____no_output_____" ], [ "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras.optimizers import Adam", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(Dense(19,activation='relu'))\nmodel.add(Dense(19,activation='relu'))\nmodel.add(Dense(19,activation='relu'))\nmodel.add(Dense(19,activation='relu'))\nmodel.add(Dense(1))\nmodel.compile(optimizer='Adam',loss='mse')", "_____no_output_____" ], [ "model.fit(x=X_train,y=y_train,\n validation_data=(X_test,y_test),\n batch_size=128,epochs=400)", "Epoch 1/400\n128/128 [==============================] - 1s 4ms/step - loss: 4783342.1589 - val_loss: 1212896.8750\nEpoch 2/400\n128/128 [==============================] - 0s 2ms/step - loss: 1198776.7539 - val_loss: 1206587.7500\nEpoch 3/400\n128/128 [==============================] - 0s 2ms/step - loss: 1204613.5911 - val_loss: 1203864.8750\nEpoch 4/400\n128/128 [==============================] - 0s 2ms/step - loss: 1186487.6352 - val_loss: 1202743.8750\nEpoch 5/400\n128/128 [==============================] - 0s 2ms/step - loss: 1164902.6899 - val_loss: 1205369.7500\nEpoch 6/400\n128/128 [==============================] - 0s 2ms/step - loss: 1252822.5310 - val_loss: 1237727.5000\nEpoch 7/400\n128/128 [==============================] - 0s 2ms/step - loss: 1201620.7083 - val_loss: 1193253.0000\nEpoch 8/400\n128/128 [==============================] - 0s 4ms/step - loss: 1193126.6521 - val_loss: 1189622.0000\nEpoch 9/400\n128/128 [==============================] - 0s 2ms/step - loss: 1213131.9448 - val_loss: 1188395.5000\nEpoch 10/400\n128/128 [==============================] - 0s 2ms/step - loss: 1207930.9312 - val_loss: 1182694.1250\nEpoch 11/400\n128/128 [==============================] - 0s 2ms/step - loss: 1131334.8978 - val_loss: 1181897.3750\nEpoch 12/400\n128/128 [==============================] - 0s 2ms/step - loss: 1183467.9360 - val_loss: 1158951.5000\nEpoch 13/400\n128/128 [==============================] - 0s 2ms/step - loss: 1264049.1357 - val_loss: 1161760.8750\nEpoch 14/400\n128/128 [==============================] - 0s 2ms/step - loss: 1197695.1124 - val_loss: 1160642.0000\nEpoch 15/400\n128/128 [==============================] - 0s 2ms/step - loss: 1149443.3459 - val_loss: 1110759.3750\nEpoch 16/400\n128/128 [==============================] - 0s 2ms/step - loss: 1058590.3866 - val_loss: 1051574.6250\nEpoch 17/400\n128/128 [==============================] - 0s 2ms/step - loss: 1016979.1463 - val_loss: 988544.3125\nEpoch 18/400\n128/128 [==============================] - 0s 2ms/step - loss: 966622.2016 - val_loss: 862116.4375\nEpoch 19/400\n128/128 [==============================] - 0s 2ms/step - loss: 819921.8818 - val_loss: 723540.7500\nEpoch 20/400\n128/128 [==============================] - 0s 2ms/step - loss: 703516.0422 - val_loss: 675002.7500\nEpoch 21/400\n128/128 [==============================] - 0s 2ms/step - loss: 677984.5298 - val_loss: 654507.7500\nEpoch 22/400\n128/128 [==============================] - 0s 2ms/step - loss: 681402.8377 - val_loss: 648307.8750\nEpoch 23/400\n128/128 [==============================] - 0s 2ms/step - loss: 684528.2728 - val_loss: 682317.5625\nEpoch 24/400\n128/128 [==============================] - 0s 2ms/step - loss: 644771.2931 - val_loss: 624482.2500\nEpoch 25/400\n128/128 [==============================] - 0s 2ms/step - loss: 699940.9123 - val_loss: 626364.1250\nEpoch 26/400\n128/128 [==============================] - 0s 2ms/step - loss: 652087.2563 - val_loss: 631377.8125\nEpoch 27/400\n128/128 [==============================] - 0s 2ms/step - loss: 650204.2655 - val_loss: 614337.8750\nEpoch 28/400\n128/128 [==============================] - 0s 2ms/step - loss: 656073.5334 - val_loss: 615656.4375\nEpoch 29/400\n128/128 [==============================] - 0s 2ms/step - loss: 610633.1986 - val_loss: 645273.9375\nEpoch 30/400\n128/128 [==============================] - 0s 2ms/step - loss: 638455.9029 - val_loss: 613907.3750\nEpoch 31/400\n128/128 [==============================] - 0s 2ms/step - loss: 607674.9261 - val_loss: 624500.6875\nEpoch 32/400\n128/128 [==============================] - 0s 2ms/step - loss: 620764.6667 - val_loss: 601468.7500\nEpoch 33/400\n128/128 [==============================] - 0s 2ms/step - loss: 623237.3832 - val_loss: 599859.6875\nEpoch 34/400\n128/128 [==============================] - 0s 2ms/step - loss: 630003.9109 - val_loss: 649322.2500\nEpoch 35/400\n128/128 [==============================] - 0s 2ms/step - loss: 635123.3522 - val_loss: 639406.7500\nEpoch 36/400\n128/128 [==============================] - 0s 2ms/step - loss: 645045.2539 - val_loss: 595999.6250\nEpoch 37/400\n128/128 [==============================] - 0s 2ms/step - loss: 601487.8028 - val_loss: 594726.4375\nEpoch 38/400\n128/128 [==============================] - 0s 2ms/step - loss: 609553.2369 - val_loss: 610511.7500\nEpoch 39/400\n128/128 [==============================] - 0s 2ms/step - loss: 593787.4264 - val_loss: 656531.0625\nEpoch 40/400\n128/128 [==============================] - 0s 2ms/step - loss: 620306.3353 - val_loss: 617260.5000\nEpoch 41/400\n128/128 [==============================] - 0s 2ms/step - loss: 608210.1487 - val_loss: 594173.6875\nEpoch 42/400\n128/128 [==============================] - 0s 2ms/step - loss: 624164.3110 - val_loss: 589273.0625\nEpoch 43/400\n128/128 [==============================] - 0s 2ms/step - loss: 621196.1051 - val_loss: 589620.1875\nEpoch 44/400\n128/128 [==============================] - 0s 2ms/step - loss: 612338.6192 - val_loss: 590328.0625\nEpoch 45/400\n128/128 [==============================] - 0s 2ms/step - loss: 613903.2970 - val_loss: 604028.8750\nEpoch 46/400\n128/128 [==============================] - 0s 2ms/step - loss: 596450.5528 - val_loss: 629975.6875\nEpoch 47/400\n128/128 [==============================] - 0s 2ms/step - loss: 607812.5945 - val_loss: 603926.3125\nEpoch 48/400\n128/128 [==============================] - 0s 2ms/step - loss: 590305.6076 - val_loss: 591866.6250\nEpoch 49/400\n128/128 [==============================] - 0s 2ms/step - loss: 596996.3183 - val_loss: 617226.3125\nEpoch 50/400\n128/128 [==============================] - 0s 2ms/step - loss: 614784.9385 - val_loss: 590104.9375\nEpoch 51/400\n128/128 [==============================] - 0s 2ms/step - loss: 610198.5470 - val_loss: 596868.1250\nEpoch 52/400\n128/128 [==============================] - 0s 2ms/step - loss: 594070.6797 - val_loss: 578854.5625\nEpoch 53/400\n128/128 [==============================] - 0s 2ms/step - loss: 591098.6589 - val_loss: 582507.6875\nEpoch 54/400\n128/128 [==============================] - 0s 2ms/step - loss: 563424.7214 - val_loss: 685330.6250\nEpoch 55/400\n128/128 [==============================] - 0s 2ms/step - loss: 635228.4385 - val_loss: 596961.3125\nEpoch 56/400\n128/128 [==============================] - 0s 4ms/step - loss: 597221.9016 - val_loss: 596803.6250\nEpoch 57/400\n128/128 [==============================] - 0s 2ms/step - loss: 605742.6444 - val_loss: 578676.5000\nEpoch 58/400\n128/128 [==============================] - 0s 2ms/step - loss: 608928.8469 - val_loss: 588485.6875\nEpoch 59/400\n128/128 [==============================] - 0s 2ms/step - loss: 590448.0785 - val_loss: 600649.2500\nEpoch 60/400\n128/128 [==============================] - 0s 2ms/step - loss: 604195.5933 - val_loss: 593268.2500\nEpoch 61/400\n128/128 [==============================] - 0s 2ms/step - loss: 611485.4050 - val_loss: 580029.5000\nEpoch 62/400\n128/128 [==============================] - 0s 2ms/step - loss: 611380.3711 - val_loss: 569524.8750\nEpoch 63/400\n128/128 [==============================] - 0s 2ms/step - loss: 596960.0397 - val_loss: 570995.7500\nEpoch 64/400\n128/128 [==============================] - 0s 2ms/step - loss: 584100.2224 - val_loss: 567335.9375\nEpoch 65/400\n128/128 [==============================] - 0s 2ms/step - loss: 654111.7452 - val_loss: 574944.2500\nEpoch 66/400\n128/128 [==============================] - 0s 2ms/step - loss: 608968.3716 - val_loss: 586096.5000\nEpoch 67/400\n128/128 [==============================] - 0s 2ms/step - loss: 608988.8299 - val_loss: 569187.3750\nEpoch 68/400\n128/128 [==============================] - 0s 2ms/step - loss: 573054.0206 - val_loss: 571207.4375\nEpoch 69/400\n128/128 [==============================] - 0s 2ms/step - loss: 574678.4545 - val_loss: 564944.5000\nEpoch 70/400\n128/128 [==============================] - 0s 2ms/step - loss: 577839.7464 - val_loss: 569945.1250\nEpoch 71/400\n128/128 [==============================] - 0s 2ms/step - loss: 617165.2301 - val_loss: 571177.6875\nEpoch 72/400\n128/128 [==============================] - 0s 2ms/step - loss: 593090.9753 - val_loss: 566373.8750\nEpoch 73/400\n128/128 [==============================] - 0s 2ms/step - loss: 636802.3721 - val_loss: 566026.8125\nEpoch 74/400\n128/128 [==============================] - 0s 2ms/step - loss: 581852.5208 - val_loss: 560130.0625\nEpoch 75/400\n128/128 [==============================] - 0s 2ms/step - loss: 599611.0506 - val_loss: 561997.6250\nEpoch 76/400\n128/128 [==============================] - 0s 3ms/step - loss: 579188.2665 - val_loss: 569911.9375\nEpoch 77/400\n128/128 [==============================] - 0s 2ms/step - loss: 583862.5310 - val_loss: 558014.6875\nEpoch 78/400\n128/128 [==============================] - 0s 2ms/step - loss: 568386.9409 - val_loss: 621306.6875\nEpoch 79/400\n128/128 [==============================] - 0s 2ms/step - loss: 606945.1134 - val_loss: 560461.1250\nEpoch 80/400\n128/128 [==============================] - 0s 2ms/step - loss: 603898.0843 - val_loss: 589317.7500\nEpoch 81/400\n128/128 [==============================] - 0s 2ms/step - loss: 576747.1720 - val_loss: 569730.0000\nEpoch 82/400\n128/128 [==============================] - 0s 2ms/step - loss: 582254.0097 - val_loss: 756561.2500\nEpoch 83/400\n128/128 [==============================] - 0s 2ms/step - loss: 632288.1725 - val_loss: 562572.4375\nEpoch 84/400\n128/128 [==============================] - 0s 2ms/step - loss: 589288.3871 - val_loss: 715456.0000\nEpoch 85/400\n128/128 [==============================] - 0s 2ms/step - loss: 622787.6812 - val_loss: 575828.3125\nEpoch 86/400\n128/128 [==============================] - 0s 2ms/step - loss: 575807.1756 - val_loss: 671598.5625\nEpoch 87/400\n128/128 [==============================] - 0s 2ms/step - loss: 586590.1371 - val_loss: 655992.4375\nEpoch 88/400\n128/128 [==============================] - 0s 2ms/step - loss: 622143.5252 - val_loss: 632578.9375\nEpoch 89/400\n128/128 [==============================] - 0s 2ms/step - loss: 593479.4162 - val_loss: 547649.6250\nEpoch 90/400\n128/128 [==============================] - 0s 2ms/step - loss: 626260.4520 - val_loss: 547308.2500\nEpoch 91/400\n128/128 [==============================] - 0s 2ms/step - loss: 599887.8658 - val_loss: 553985.8750\nEpoch 92/400\n128/128 [==============================] - 0s 2ms/step - loss: 580995.0087 - val_loss: 554788.8750\nEpoch 93/400\n128/128 [==============================] - 0s 2ms/step - loss: 545475.9549 - val_loss: 681543.6875\nEpoch 94/400\n128/128 [==============================] - 0s 2ms/step - loss: 608857.2156 - val_loss: 565919.5000\nEpoch 95/400\n128/128 [==============================] - 0s 2ms/step - loss: 582608.7432 - val_loss: 547854.8750\nEpoch 96/400\n128/128 [==============================] - 0s 2ms/step - loss: 572012.3735 - val_loss: 599474.6875\nEpoch 97/400\n128/128 [==============================] - 0s 2ms/step - loss: 571017.1013 - val_loss: 543791.0000\nEpoch 98/400\n128/128 [==============================] - 0s 2ms/step - loss: 611474.9700 - val_loss: 552685.6875\nEpoch 99/400\n128/128 [==============================] - 0s 2ms/step - loss: 582505.8149 - val_loss: 539547.3125\nEpoch 100/400\n128/128 [==============================] - 0s 2ms/step - loss: 539321.8391 - val_loss: 553411.3125\nEpoch 101/400\n128/128 [==============================] - 0s 2ms/step - loss: 581377.6391 - val_loss: 539774.0000\nEpoch 102/400\n128/128 [==============================] - 0s 2ms/step - loss: 559594.4193 - val_loss: 539414.1875\nEpoch 103/400\n128/128 [==============================] - 0s 2ms/step - loss: 533468.6415 - val_loss: 549345.5000\nEpoch 104/400\n128/128 [==============================] - 0s 2ms/step - loss: 533000.2786 - val_loss: 546466.0000\nEpoch 105/400\n128/128 [==============================] - 0s 2ms/step - loss: 580753.2958 - val_loss: 534926.3125\nEpoch 106/400\n128/128 [==============================] - 0s 2ms/step - loss: 606751.3973 - val_loss: 574564.0000\nEpoch 107/400\n128/128 [==============================] - 0s 2ms/step - loss: 632641.4210 - val_loss: 549708.8125\nEpoch 108/400\n128/128 [==============================] - 0s 2ms/step - loss: 555595.9188 - val_loss: 550379.0625\nEpoch 109/400\n128/128 [==============================] - 0s 2ms/step - loss: 545884.6311 - val_loss: 542349.0625\nEpoch 110/400\n128/128 [==============================] - 0s 2ms/step - loss: 597802.2524 - val_loss: 532740.3125\nEpoch 111/400\n128/128 [==============================] - 0s 2ms/step - loss: 556328.8379 - val_loss: 532552.4375\nEpoch 112/400\n128/128 [==============================] - 0s 3ms/step - loss: 531845.1311 - val_loss: 529947.5625\nEpoch 113/400\n128/128 [==============================] - 0s 4ms/step - loss: 572627.0802 - val_loss: 535211.6250\nEpoch 114/400\n128/128 [==============================] - 0s 2ms/step - loss: 620892.6696 - val_loss: 537971.6250\nEpoch 115/400\n128/128 [==============================] - 0s 2ms/step - loss: 553855.0717 - val_loss: 561033.5000\nEpoch 116/400\n128/128 [==============================] - 0s 2ms/step - loss: 533232.8476 - val_loss: 546225.0625\nEpoch 117/400\n128/128 [==============================] - 0s 2ms/step - loss: 553789.9516 - val_loss: 532098.1875\nEpoch 118/400\n128/128 [==============================] - 0s 2ms/step - loss: 606494.6638 - val_loss: 532797.0000\nEpoch 119/400\n128/128 [==============================] - 0s 2ms/step - loss: 570175.1008 - val_loss: 530696.6250\nEpoch 120/400\n128/128 [==============================] - 0s 2ms/step - loss: 580722.0916 - val_loss: 530996.9375\nEpoch 121/400\n128/128 [==============================] - 0s 2ms/step - loss: 577385.1097 - val_loss: 532686.5000\nEpoch 122/400\n128/128 [==============================] - 0s 2ms/step - loss: 565775.8113 - val_loss: 532561.7500\nEpoch 123/400\n128/128 [==============================] - 0s 2ms/step - loss: 546655.5073 - val_loss: 531188.8125\nEpoch 124/400\n128/128 [==============================] - 0s 2ms/step - loss: 525028.0034 - val_loss: 531402.1250\nEpoch 125/400\n128/128 [==============================] - 0s 2ms/step - loss: 538242.9639 - val_loss: 535038.2500\nEpoch 126/400\n128/128 [==============================] - 0s 2ms/step - loss: 549707.6943 - val_loss: 524010.5625\nEpoch 127/400\n128/128 [==============================] - 0s 2ms/step - loss: 562812.9872 - val_loss: 517995.9688\nEpoch 128/400\n128/128 [==============================] - 0s 2ms/step - loss: 536385.1066 - val_loss: 525330.8750\nEpoch 129/400\n128/128 [==============================] - 0s 3ms/step - loss: 548555.9859 - val_loss: 537675.3125\nEpoch 130/400\n128/128 [==============================] - 0s 2ms/step - loss: 558186.9440 - val_loss: 525259.8125\nEpoch 131/400\n128/128 [==============================] - 0s 2ms/step - loss: 540122.5063 - val_loss: 539604.9375\nEpoch 132/400\n128/128 [==============================] - 0s 2ms/step - loss: 619803.4961 - val_loss: 516293.5312\nEpoch 133/400\n128/128 [==============================] - 0s 2ms/step - loss: 542533.6688 - val_loss: 611764.0000\nEpoch 134/400\n128/128 [==============================] - 0s 3ms/step - loss: 552647.9239 - val_loss: 521261.5938\nEpoch 135/400\n128/128 [==============================] - 0s 2ms/step - loss: 535995.9799 - val_loss: 568543.6250\nEpoch 136/400\n128/128 [==============================] - 0s 2ms/step - loss: 561633.6441 - val_loss: 520148.0625\nEpoch 137/400\n128/128 [==============================] - 0s 2ms/step - loss: 530327.2415 - val_loss: 521975.8750\nEpoch 138/400\n128/128 [==============================] - 0s 2ms/step - loss: 521569.7212 - val_loss: 514300.8438\nEpoch 139/400\n128/128 [==============================] - 0s 2ms/step - loss: 565756.3258 - val_loss: 524682.0625\nEpoch 140/400\n128/128 [==============================] - 0s 2ms/step - loss: 523089.6781 - val_loss: 515591.1875\nEpoch 141/400\n128/128 [==============================] - 0s 2ms/step - loss: 557947.2357 - val_loss: 531302.8125\nEpoch 142/400\n128/128 [==============================] - 0s 2ms/step - loss: 522696.0203 - val_loss: 511869.9375\nEpoch 143/400\n128/128 [==============================] - 0s 2ms/step - loss: 520062.6982 - val_loss: 540099.3125\nEpoch 144/400\n128/128 [==============================] - 0s 2ms/step - loss: 565094.6437 - val_loss: 507694.5938\nEpoch 145/400\n128/128 [==============================] - 0s 2ms/step - loss: 638180.9637 - val_loss: 507140.9688\nEpoch 146/400\n128/128 [==============================] - 0s 3ms/step - loss: 537481.0274 - val_loss: 507520.5625\nEpoch 147/400\n128/128 [==============================] - 0s 3ms/step - loss: 534495.7757 - val_loss: 582055.0625\nEpoch 148/400\n128/128 [==============================] - 0s 2ms/step - loss: 514277.7519 - val_loss: 647027.0000\nEpoch 149/400\n128/128 [==============================] - 0s 2ms/step - loss: 532981.2217 - val_loss: 507288.2812\nEpoch 150/400\n128/128 [==============================] - 0s 2ms/step - loss: 576472.7919 - val_loss: 509779.4688\nEpoch 151/400\n128/128 [==============================] - 0s 2ms/step - loss: 528437.1604 - val_loss: 541753.5000\nEpoch 152/400\n128/128 [==============================] - 0s 2ms/step - loss: 585479.8537 - val_loss: 696205.3125\nEpoch 153/400\n128/128 [==============================] - 0s 2ms/step - loss: 570397.1129 - val_loss: 519295.3438\nEpoch 154/400\n128/128 [==============================] - 0s 2ms/step - loss: 533367.6119 - val_loss: 524200.3438\nEpoch 155/400\n128/128 [==============================] - 0s 2ms/step - loss: 508589.1771 - val_loss: 521274.2812\nEpoch 156/400\n128/128 [==============================] - 0s 2ms/step - loss: 518582.6553 - val_loss: 573313.1875\nEpoch 157/400\n128/128 [==============================] - 0s 2ms/step - loss: 575929.6851 - val_loss: 502319.9375\nEpoch 158/400\n128/128 [==============================] - 0s 2ms/step - loss: 528533.3064 - val_loss: 502765.5938\nEpoch 159/400\n128/128 [==============================] - 0s 2ms/step - loss: 554476.3922 - val_loss: 519655.9062\nEpoch 160/400\n128/128 [==============================] - 0s 2ms/step - loss: 527143.1487 - val_loss: 498312.1250\nEpoch 161/400\n128/128 [==============================] - 0s 4ms/step - loss: 524060.9937 - val_loss: 498887.0938\nEpoch 162/400\n128/128 [==============================] - 0s 2ms/step - loss: 501558.0659 - val_loss: 500692.9062\nEpoch 163/400\n128/128 [==============================] - 0s 2ms/step - loss: 519100.2001 - val_loss: 504512.9062\nEpoch 164/400\n128/128 [==============================] - 0s 2ms/step - loss: 547506.6427 - val_loss: 499801.6250\nEpoch 165/400\n128/128 [==============================] - 0s 2ms/step - loss: 505007.4227 - val_loss: 518497.2500\nEpoch 166/400\n128/128 [==============================] - 0s 2ms/step - loss: 521809.9910 - val_loss: 505437.1875\nEpoch 167/400\n128/128 [==============================] - 0s 2ms/step - loss: 508996.5012 - val_loss: 507720.6250\nEpoch 168/400\n128/128 [==============================] - 0s 2ms/step - loss: 508766.7590 - val_loss: 501376.7812\nEpoch 169/400\n128/128 [==============================] - 0s 2ms/step - loss: 528036.8341 - val_loss: 497043.1562\nEpoch 170/400\n128/128 [==============================] - 0s 2ms/step - loss: 490118.0681 - val_loss: 502656.4062\nEpoch 171/400\n128/128 [==============================] - 0s 2ms/step - loss: 585155.5877 - val_loss: 494642.6250\nEpoch 172/400\n128/128 [==============================] - 0s 2ms/step - loss: 507360.0715 - val_loss: 540871.9375\nEpoch 173/400\n128/128 [==============================] - 0s 2ms/step - loss: 534796.3319 - val_loss: 537383.0000\nEpoch 174/400\n128/128 [==============================] - 0s 2ms/step - loss: 524489.3103 - val_loss: 533992.3125\nEpoch 175/400\n128/128 [==============================] - 0s 2ms/step - loss: 517261.2103 - val_loss: 503114.2188\nEpoch 176/400\n128/128 [==============================] - 0s 2ms/step - loss: 519687.5848 - val_loss: 498445.0625\nEpoch 177/400\n128/128 [==============================] - 0s 2ms/step - loss: 511218.8968 - val_loss: 501234.8125\nEpoch 178/400\n128/128 [==============================] - 0s 2ms/step - loss: 486490.2163 - val_loss: 490059.0000\nEpoch 179/400\n128/128 [==============================] - 0s 2ms/step - loss: 493717.8057 - val_loss: 489520.4062\nEpoch 180/400\n128/128 [==============================] - 0s 2ms/step - loss: 519596.8156 - val_loss: 496577.4375\nEpoch 181/400\n128/128 [==============================] - 0s 2ms/step - loss: 505032.6417 - val_loss: 501464.2500\nEpoch 182/400\n128/128 [==============================] - 0s 2ms/step - loss: 497814.4758 - val_loss: 522406.6875\nEpoch 183/400\n128/128 [==============================] - 0s 2ms/step - loss: 495055.7214 - val_loss: 530052.1250\nEpoch 184/400\n128/128 [==============================] - 0s 2ms/step - loss: 504455.2677 - val_loss: 489789.2812\nEpoch 185/400\n128/128 [==============================] - 0s 2ms/step - loss: 498720.9135 - val_loss: 509557.1562\nEpoch 186/400\n128/128 [==============================] - 0s 2ms/step - loss: 513021.5237 - val_loss: 490217.6562\nEpoch 187/400\n128/128 [==============================] - 0s 2ms/step - loss: 553182.2435 - val_loss: 486375.3125\nEpoch 188/400\n128/128 [==============================] - 0s 2ms/step - loss: 534974.5426 - val_loss: 489840.2500\nEpoch 189/400\n128/128 [==============================] - 0s 2ms/step - loss: 496672.5533 - val_loss: 483192.5938\nEpoch 190/400\n128/128 [==============================] - 0s 2ms/step - loss: 503306.0308 - val_loss: 489794.5000\nEpoch 191/400\n128/128 [==============================] - 0s 2ms/step - loss: 499788.3401 - val_loss: 490567.7500\nEpoch 192/400\n128/128 [==============================] - 0s 3ms/step - loss: 503068.3372 - val_loss: 490582.5938\nEpoch 193/400\n128/128 [==============================] - 0s 2ms/step - loss: 508902.4426 - val_loss: 497666.7812\nEpoch 194/400\n128/128 [==============================] - 0s 2ms/step - loss: 514418.6422 - val_loss: 498326.9062\nEpoch 195/400\n128/128 [==============================] - 0s 2ms/step - loss: 553599.7694 - val_loss: 487448.1875\nEpoch 196/400\n128/128 [==============================] - 0s 2ms/step - loss: 514264.9486 - val_loss: 499044.3125\nEpoch 197/400\n128/128 [==============================] - 0s 2ms/step - loss: 482595.4712 - val_loss: 499600.6562\nEpoch 198/400\n128/128 [==============================] - 0s 2ms/step - loss: 504010.3328 - val_loss: 486624.7500\nEpoch 199/400\n128/128 [==============================] - 0s 2ms/step - loss: 497181.4201 - val_loss: 482657.5312\nEpoch 200/400\n128/128 [==============================] - 0s 2ms/step - loss: 492261.4448 - val_loss: 494199.7500\nEpoch 201/400\n128/128 [==============================] - 0s 2ms/step - loss: 475611.3731 - val_loss: 551102.7500\nEpoch 202/400\n128/128 [==============================] - 0s 2ms/step - loss: 515137.1204 - val_loss: 502091.9062\nEpoch 203/400\n128/128 [==============================] - 0s 2ms/step - loss: 483274.4736 - val_loss: 483069.4375\nEpoch 204/400\n128/128 [==============================] - 0s 2ms/step - loss: 489095.6487 - val_loss: 486846.8750\nEpoch 205/400\n128/128 [==============================] - 0s 2ms/step - loss: 493007.3854 - val_loss: 479886.5938\nEpoch 206/400\n128/128 [==============================] - 0s 2ms/step - loss: 524779.3748 - val_loss: 495197.1250\nEpoch 207/400\n128/128 [==============================] - 0s 2ms/step - loss: 482126.1243 - val_loss: 483709.5000\nEpoch 208/400\n128/128 [==============================] - 0s 2ms/step - loss: 465139.2946 - val_loss: 485769.0312\nEpoch 209/400\n128/128 [==============================] - 0s 2ms/step - loss: 542014.7873 - val_loss: 473468.6562\nEpoch 210/400\n128/128 [==============================] - 0s 2ms/step - loss: 530462.2294 - val_loss: 490447.5938\nEpoch 211/400\n128/128 [==============================] - 0s 2ms/step - loss: 496539.2091 - val_loss: 485086.3125\nEpoch 212/400\n128/128 [==============================] - 0s 2ms/step - loss: 478418.8750 - val_loss: 482784.8750\nEpoch 213/400\n128/128 [==============================] - 0s 2ms/step - loss: 504498.1090 - val_loss: 509030.9688\nEpoch 214/400\n128/128 [==============================] - 0s 2ms/step - loss: 469314.9142 - val_loss: 532175.3750\nEpoch 215/400\n128/128 [==============================] - 0s 2ms/step - loss: 508782.3709 - val_loss: 472029.4375\nEpoch 216/400\n128/128 [==============================] - 0s 3ms/step - loss: 500973.8384 - val_loss: 475004.1562\nEpoch 217/400\n128/128 [==============================] - 0s 2ms/step - loss: 498872.2718 - val_loss: 486481.4688\nEpoch 218/400\n128/128 [==============================] - 0s 4ms/step - loss: 489484.6708 - val_loss: 513086.9688\nEpoch 219/400\n128/128 [==============================] - 0s 2ms/step - loss: 508604.0695 - val_loss: 472738.6250\nEpoch 220/400\n128/128 [==============================] - 0s 2ms/step - loss: 477341.9302 - val_loss: 493924.2500\nEpoch 221/400\n128/128 [==============================] - 0s 2ms/step - loss: 513293.3072 - val_loss: 475219.6250\nEpoch 222/400\n128/128 [==============================] - 0s 3ms/step - loss: 495263.1083 - val_loss: 472586.0938\nEpoch 223/400\n128/128 [==============================] - 0s 2ms/step - loss: 462867.9738 - val_loss: 475093.8438\nEpoch 224/400\n128/128 [==============================] - 0s 2ms/step - loss: 511209.8280 - val_loss: 481021.8125\nEpoch 225/400\n128/128 [==============================] - 0s 2ms/step - loss: 476159.5145 - val_loss: 531457.6875\nEpoch 226/400\n128/128 [==============================] - 0s 2ms/step - loss: 490134.5703 - val_loss: 470591.0938\nEpoch 227/400\n128/128 [==============================] - 0s 2ms/step - loss: 451466.9947 - val_loss: 475222.2500\nEpoch 228/400\n128/128 [==============================] - 0s 2ms/step - loss: 480137.1032 - val_loss: 471921.0938\nEpoch 229/400\n128/128 [==============================] - 0s 2ms/step - loss: 505173.5850 - val_loss: 499167.2812\nEpoch 230/400\n128/128 [==============================] - 0s 2ms/step - loss: 493022.4804 - val_loss: 471853.4062\nEpoch 231/400\n128/128 [==============================] - 0s 3ms/step - loss: 467374.6827 - val_loss: 561597.0000\nEpoch 232/400\n128/128 [==============================] - 0s 2ms/step - loss: 520406.5833 - val_loss: 470693.5625\nEpoch 233/400\n128/128 [==============================] - 0s 2ms/step - loss: 502440.9886 - val_loss: 482362.3750\nEpoch 234/400\n128/128 [==============================] - 0s 2ms/step - loss: 458046.0501 - val_loss: 466716.1875\nEpoch 235/400\n128/128 [==============================] - 0s 3ms/step - loss: 491062.4874 - val_loss: 472492.4375\nEpoch 236/400\n128/128 [==============================] - 0s 2ms/step - loss: 463737.4763 - val_loss: 488967.4375\nEpoch 237/400\n128/128 [==============================] - 0s 2ms/step - loss: 485518.2352 - val_loss: 506689.5938\nEpoch 238/400\n128/128 [==============================] - 0s 2ms/step - loss: 504187.8551 - val_loss: 461358.0625\nEpoch 239/400\n128/128 [==============================] - 0s 2ms/step - loss: 501574.1192 - val_loss: 472793.6562\nEpoch 240/400\n128/128 [==============================] - 0s 3ms/step - loss: 496152.7095 - val_loss: 497571.7500\nEpoch 241/400\n128/128 [==============================] - 0s 2ms/step - loss: 486017.9707 - val_loss: 462990.3125\nEpoch 242/400\n128/128 [==============================] - 0s 2ms/step - loss: 463117.4896 - val_loss: 467649.5312\nEpoch 243/400\n128/128 [==============================] - 0s 2ms/step - loss: 454652.7842 - val_loss: 576871.0625\nEpoch 244/400\n128/128 [==============================] - 0s 2ms/step - loss: 514140.6512 - val_loss: 482535.8750\nEpoch 245/400\n128/128 [==============================] - 0s 3ms/step - loss: 498111.9574 - val_loss: 464039.1875\nEpoch 246/400\n128/128 [==============================] - 0s 2ms/step - loss: 495586.1810 - val_loss: 466136.5938\nEpoch 247/400\n128/128 [==============================] - 0s 2ms/step - loss: 481801.4925 - val_loss: 690772.7500\nEpoch 248/400\n128/128 [==============================] - 0s 2ms/step - loss: 538490.8135 - val_loss: 459315.5625\nEpoch 249/400\n128/128 [==============================] - 0s 2ms/step - loss: 480550.6526 - val_loss: 475192.1562\nEpoch 250/400\n128/128 [==============================] - 0s 2ms/step - loss: 480156.2454 - val_loss: 459517.6875\nEpoch 251/400\n128/128 [==============================] - 0s 2ms/step - loss: 445213.6492 - val_loss: 460344.0000\nEpoch 252/400\n128/128 [==============================] - 0s 2ms/step - loss: 509219.8500 - val_loss: 456819.3750\nEpoch 253/400\n128/128 [==============================] - 0s 2ms/step - loss: 472932.9552 - val_loss: 471715.0312\nEpoch 254/400\n128/128 [==============================] - 0s 3ms/step - loss: 469907.5010 - val_loss: 498817.9062\nEpoch 255/400\n128/128 [==============================] - 0s 3ms/step - loss: 520621.3735 - val_loss: 467587.1875\nEpoch 256/400\n128/128 [==============================] - 0s 2ms/step - loss: 474667.2524 - val_loss: 463725.8438\nEpoch 257/400\n128/128 [==============================] - 0s 3ms/step - loss: 482338.1429 - val_loss: 465954.7500\nEpoch 258/400\n128/128 [==============================] - 0s 2ms/step - loss: 455736.4850 - val_loss: 469068.0312\nEpoch 259/400\n128/128 [==============================] - 0s 2ms/step - loss: 534803.4634 - val_loss: 477015.7812\nEpoch 260/400\n128/128 [==============================] - 0s 2ms/step - loss: 462364.4234 - val_loss: 457352.7500\nEpoch 261/400\n128/128 [==============================] - 0s 2ms/step - loss: 475042.1284 - val_loss: 454627.5312\nEpoch 262/400\n128/128 [==============================] - 0s 2ms/step - loss: 477544.5826 - val_loss: 483652.0938\nEpoch 263/400\n128/128 [==============================] - 0s 2ms/step - loss: 458871.3508 - val_loss: 452751.3438\nEpoch 264/400\n128/128 [==============================] - 0s 2ms/step - loss: 506588.3573 - val_loss: 455352.6250\nEpoch 265/400\n128/128 [==============================] - 0s 3ms/step - loss: 458118.1131 - val_loss: 459748.8438\nEpoch 266/400\n128/128 [==============================] - 1s 4ms/step - loss: 473869.0247 - val_loss: 463462.8438\nEpoch 267/400\n128/128 [==============================] - 0s 2ms/step - loss: 491933.6790 - val_loss: 468244.1875\nEpoch 268/400\n128/128 [==============================] - 0s 3ms/step - loss: 463714.0933 - val_loss: 479151.7500\nEpoch 269/400\n128/128 [==============================] - 0s 2ms/step - loss: 472899.1119 - val_loss: 456847.7500\nEpoch 270/400\n128/128 [==============================] - 0s 2ms/step - loss: 471026.2771 - val_loss: 457545.0625\nEpoch 271/400\n128/128 [==============================] - 0s 2ms/step - loss: 473179.1812 - val_loss: 453401.5938\nEpoch 272/400\n128/128 [==============================] - 0s 2ms/step - loss: 473262.3047 - val_loss: 471277.3125\nEpoch 273/400\n128/128 [==============================] - 0s 2ms/step - loss: 471035.8404 - val_loss: 458015.3438\nEpoch 274/400\n128/128 [==============================] - 0s 2ms/step - loss: 505145.5770 - val_loss: 458628.8438\nEpoch 275/400\n128/128 [==============================] - 0s 2ms/step - loss: 450209.2679 - val_loss: 574265.3750\nEpoch 276/400\n128/128 [==============================] - 0s 2ms/step - loss: 485458.7059 - val_loss: 451820.0938\nEpoch 277/400\n128/128 [==============================] - 0s 3ms/step - loss: 458275.2282 - val_loss: 490508.0938\nEpoch 278/400\n128/128 [==============================] - 0s 3ms/step - loss: 483856.2687 - val_loss: 453466.0938\nEpoch 279/400\n128/128 [==============================] - 0s 2ms/step - loss: 497772.8367 - val_loss: 450172.1875\nEpoch 280/400\n128/128 [==============================] - 0s 2ms/step - loss: 469447.0676 - val_loss: 475440.7812\nEpoch 281/400\n128/128 [==============================] - 0s 2ms/step - loss: 482739.5703 - val_loss: 459297.3750\nEpoch 282/400\n128/128 [==============================] - 0s 2ms/step - loss: 497610.4159 - val_loss: 464833.4062\nEpoch 283/400\n128/128 [==============================] - 0s 2ms/step - loss: 463924.2088 - val_loss: 452759.3438\nEpoch 284/400\n128/128 [==============================] - 0s 2ms/step - loss: 487476.7020 - val_loss: 493876.0938\nEpoch 285/400\n128/128 [==============================] - 0s 2ms/step - loss: 460772.2166 - val_loss: 467459.1250\nEpoch 286/400\n128/128 [==============================] - 0s 2ms/step - loss: 519938.4181 - val_loss: 455677.4688\nEpoch 287/400\n128/128 [==============================] - 0s 3ms/step - loss: 454714.1858 - val_loss: 452226.9062\nEpoch 288/400\n128/128 [==============================] - 0s 2ms/step - loss: 473944.2403 - val_loss: 466867.5625\nEpoch 289/400\n128/128 [==============================] - 0s 2ms/step - loss: 494498.5606 - val_loss: 498356.1250\nEpoch 290/400\n128/128 [==============================] - 0s 2ms/step - loss: 488336.4516 - val_loss: 686639.8125\nEpoch 291/400\n128/128 [==============================] - 0s 2ms/step - loss: 500855.7490 - val_loss: 460646.0312\nEpoch 292/400\n128/128 [==============================] - 0s 2ms/step - loss: 454787.9283 - val_loss: 453383.8438\nEpoch 293/400\n128/128 [==============================] - 0s 2ms/step - loss: 490244.2006 - val_loss: 463428.6562\nEpoch 294/400\n128/128 [==============================] - 0s 2ms/step - loss: 473888.2619 - val_loss: 456376.0625\nEpoch 295/400\n128/128 [==============================] - 0s 2ms/step - loss: 484515.9605 - val_loss: 498016.9375\nEpoch 296/400\n128/128 [==============================] - 0s 3ms/step - loss: 499964.7716 - val_loss: 476597.7500\nEpoch 297/400\n128/128 [==============================] - 0s 2ms/step - loss: 487140.2192 - val_loss: 454493.6250\nEpoch 298/400\n128/128 [==============================] - 0s 3ms/step - loss: 500984.6771 - val_loss: 482041.7188\nEpoch 299/400\n128/128 [==============================] - 0s 2ms/step - loss: 490213.1768 - val_loss: 449746.0938\nEpoch 300/400\n128/128 [==============================] - 0s 2ms/step - loss: 471853.9787 - val_loss: 477296.6562\nEpoch 301/400\n128/128 [==============================] - 0s 2ms/step - loss: 466384.0218 - val_loss: 472791.0625\nEpoch 302/400\n128/128 [==============================] - 0s 3ms/step - loss: 454811.1853 - val_loss: 465162.8438\nEpoch 303/400\n128/128 [==============================] - 0s 2ms/step - loss: 461939.1495 - val_loss: 447746.3438\nEpoch 304/400\n128/128 [==============================] - 0s 2ms/step - loss: 469361.0603 - val_loss: 470983.0000\nEpoch 305/400\n128/128 [==============================] - 0s 2ms/step - loss: 480795.5603 - val_loss: 457115.6562\nEpoch 306/400\n128/128 [==============================] - 0s 2ms/step - loss: 461989.6037 - val_loss: 444552.6875\nEpoch 307/400\n128/128 [==============================] - 0s 2ms/step - loss: 455779.8026 - val_loss: 478105.3125\nEpoch 308/400\n128/128 [==============================] - 0s 2ms/step - loss: 540489.2110 - val_loss: 470467.3125\nEpoch 309/400\n128/128 [==============================] - 0s 2ms/step - loss: 483304.9813 - val_loss: 461996.6250\nEpoch 310/400\n128/128 [==============================] - 0s 2ms/step - loss: 481967.0710 - val_loss: 476904.1562\nEpoch 311/400\n128/128 [==============================] - 0s 2ms/step - loss: 464841.9038 - val_loss: 471176.6250\nEpoch 312/400\n128/128 [==============================] - 0s 2ms/step - loss: 478523.6197 - val_loss: 498273.7188\nEpoch 313/400\n128/128 [==============================] - 0s 2ms/step - loss: 459095.1514 - val_loss: 453954.5312\nEpoch 314/400\n128/128 [==============================] - 0s 2ms/step - loss: 470821.9874 - val_loss: 458596.9688\nEpoch 315/400\n128/128 [==============================] - 0s 2ms/step - loss: 479988.9595 - val_loss: 456164.0312\nEpoch 316/400\n128/128 [==============================] - 0s 3ms/step - loss: 465438.1139 - val_loss: 460419.8438\nEpoch 317/400\n128/128 [==============================] - 0s 2ms/step - loss: 477803.2926 - val_loss: 500113.2188\nEpoch 318/400\n128/128 [==============================] - 0s 2ms/step - loss: 468803.7488 - val_loss: 479527.0000\nEpoch 319/400\n128/128 [==============================] - 0s 3ms/step - loss: 476304.9864 - val_loss: 463837.6875\nEpoch 320/400\n128/128 [==============================] - 0s 2ms/step - loss: 471151.8517 - val_loss: 451521.4062\nEpoch 321/400\n128/128 [==============================] - 0s 2ms/step - loss: 474572.6923 - val_loss: 459244.2812\nEpoch 322/400\n128/128 [==============================] - 0s 3ms/step - loss: 455407.3375 - val_loss: 472796.6875\nEpoch 323/400\n128/128 [==============================] - 1s 4ms/step - loss: 460911.1284 - val_loss: 454953.6875\nEpoch 324/400\n128/128 [==============================] - 0s 2ms/step - loss: 488812.1051 - val_loss: 448027.4062\nEpoch 325/400\n128/128 [==============================] - 0s 3ms/step - loss: 444399.0078 - val_loss: 448723.3438\nEpoch 326/400\n128/128 [==============================] - 0s 2ms/step - loss: 463367.1223 - val_loss: 453340.3438\nEpoch 327/400\n128/128 [==============================] - 0s 2ms/step - loss: 474991.0841 - val_loss: 456905.8438\nEpoch 328/400\n128/128 [==============================] - 0s 2ms/step - loss: 445226.5019 - val_loss: 447910.5000\nEpoch 329/400\n128/128 [==============================] - 0s 2ms/step - loss: 490929.4586 - val_loss: 446593.1875\nEpoch 330/400\n128/128 [==============================] - 0s 2ms/step - loss: 471649.1979 - val_loss: 449728.5625\nEpoch 331/400\n128/128 [==============================] - 0s 2ms/step - loss: 486113.2706 - val_loss: 454590.2500\nEpoch 332/400\n128/128 [==============================] - 0s 3ms/step - loss: 473350.8258 - val_loss: 491242.0938\nEpoch 333/400\n128/128 [==============================] - 0s 3ms/step - loss: 475574.5143 - val_loss: 445740.3438\nEpoch 334/400\n128/128 [==============================] - 0s 3ms/step - loss: 443768.6042 - val_loss: 454805.9062\nEpoch 335/400\n128/128 [==============================] - 0s 3ms/step - loss: 474081.3033 - val_loss: 454925.4688\nEpoch 336/400\n128/128 [==============================] - 0s 2ms/step - loss: 462665.5061 - val_loss: 450310.5625\nEpoch 337/400\n128/128 [==============================] - 0s 3ms/step - loss: 478913.4111 - val_loss: 485408.5312\nEpoch 338/400\n128/128 [==============================] - 0s 3ms/step - loss: 478055.4663 - val_loss: 443244.3125\nEpoch 339/400\n128/128 [==============================] - 0s 3ms/step - loss: 456111.3127 - val_loss: 449958.7812\nEpoch 340/400\n128/128 [==============================] - 0s 2ms/step - loss: 481439.0828 - val_loss: 484024.6250\nEpoch 341/400\n128/128 [==============================] - 0s 3ms/step - loss: 494435.7408 - val_loss: 451139.8750\nEpoch 342/400\n128/128 [==============================] - 0s 3ms/step - loss: 473851.1000 - val_loss: 459258.4375\nEpoch 343/400\n128/128 [==============================] - 0s 3ms/step - loss: 462404.5686 - val_loss: 443343.5000\nEpoch 344/400\n128/128 [==============================] - 0s 3ms/step - loss: 447671.8522 - val_loss: 479295.9375\nEpoch 345/400\n128/128 [==============================] - 0s 3ms/step - loss: 490858.0518 - val_loss: 450265.9688\nEpoch 346/400\n128/128 [==============================] - 0s 3ms/step - loss: 457918.9453 - val_loss: 444959.7500\nEpoch 347/400\n128/128 [==============================] - 0s 3ms/step - loss: 460316.7762 - val_loss: 581854.7500\nEpoch 348/400\n128/128 [==============================] - 0s 3ms/step - loss: 472753.5569 - val_loss: 566076.1250\nEpoch 349/400\n128/128 [==============================] - 0s 3ms/step - loss: 487071.1538 - val_loss: 456164.3750\nEpoch 350/400\n128/128 [==============================] - 0s 3ms/step - loss: 437319.0632 - val_loss: 449474.3438\nEpoch 351/400\n128/128 [==============================] - 0s 3ms/step - loss: 451975.4981 - val_loss: 454211.8750\nEpoch 352/400\n128/128 [==============================] - 0s 3ms/step - loss: 479528.2481 - val_loss: 499014.2188\nEpoch 353/400\n128/128 [==============================] - 0s 3ms/step - loss: 500263.5579 - val_loss: 461379.7500\nEpoch 354/400\n128/128 [==============================] - 0s 3ms/step - loss: 447820.7757 - val_loss: 445149.2500\nEpoch 355/400\n128/128 [==============================] - 0s 3ms/step - loss: 465681.1686 - val_loss: 459058.0312\nEpoch 356/400\n128/128 [==============================] - 0s 3ms/step - loss: 535514.4445 - val_loss: 453984.1250\nEpoch 357/400\n128/128 [==============================] - 0s 3ms/step - loss: 462445.8188 - val_loss: 463163.2188\nEpoch 358/400\n128/128 [==============================] - 0s 2ms/step - loss: 447548.0368 - val_loss: 446287.8750\nEpoch 359/400\n128/128 [==============================] - 0s 2ms/step - loss: 447569.9627 - val_loss: 448191.8750\nEpoch 360/400\n128/128 [==============================] - 0s 2ms/step - loss: 460977.0465 - val_loss: 579835.4375\nEpoch 361/400\n128/128 [==============================] - 0s 3ms/step - loss: 510368.5015 - val_loss: 448478.4375\nEpoch 362/400\n128/128 [==============================] - 0s 3ms/step - loss: 447590.4167 - val_loss: 447829.1875\nEpoch 363/400\n128/128 [==============================] - 0s 2ms/step - loss: 455571.2192 - val_loss: 492602.6250\nEpoch 364/400\n128/128 [==============================] - 0s 3ms/step - loss: 475884.9859 - val_loss: 444743.3125\nEpoch 365/400\n128/128 [==============================] - 0s 2ms/step - loss: 465877.6061 - val_loss: 444712.5000\nEpoch 366/400\n128/128 [==============================] - 0s 3ms/step - loss: 459119.1349 - val_loss: 448430.1875\nEpoch 367/400\n128/128 [==============================] - 0s 3ms/step - loss: 470529.3607 - val_loss: 453783.9375\nEpoch 368/400\n128/128 [==============================] - 0s 3ms/step - loss: 459838.0206 - val_loss: 488096.0938\nEpoch 369/400\n128/128 [==============================] - 0s 3ms/step - loss: 492559.4947 - val_loss: 477887.6562\nEpoch 370/400\n128/128 [==============================] - 0s 3ms/step - loss: 468590.7330 - val_loss: 472547.3125\nEpoch 371/400\n128/128 [==============================] - 1s 4ms/step - loss: 463291.3910 - val_loss: 469057.3750\nEpoch 372/400\n128/128 [==============================] - 0s 2ms/step - loss: 444300.8607 - val_loss: 450591.1250\nEpoch 373/400\n128/128 [==============================] - 0s 3ms/step - loss: 482367.6853 - val_loss: 468646.2812\nEpoch 374/400\n128/128 [==============================] - 0s 2ms/step - loss: 479561.2250 - val_loss: 449877.2812\nEpoch 375/400\n128/128 [==============================] - 0s 2ms/step - loss: 433303.5710 - val_loss: 449838.6562\nEpoch 376/400\n128/128 [==============================] - 0s 3ms/step - loss: 479904.5845 - val_loss: 444823.8750\nEpoch 377/400\n128/128 [==============================] - 0s 3ms/step - loss: 459071.0969 - val_loss: 444752.3750\nEpoch 378/400\n128/128 [==============================] - 0s 3ms/step - loss: 432132.3496 - val_loss: 451168.6875\nEpoch 379/400\n128/128 [==============================] - 0s 3ms/step - loss: 467815.2565 - val_loss: 446241.2188\nEpoch 380/400\n128/128 [==============================] - 0s 3ms/step - loss: 461450.8951 - val_loss: 445600.1250\nEpoch 381/400\n128/128 [==============================] - 0s 3ms/step - loss: 474344.8263 - val_loss: 458377.7188\nEpoch 382/400\n128/128 [==============================] - 0s 3ms/step - loss: 474042.0128 - val_loss: 450996.5938\nEpoch 383/400\n128/128 [==============================] - 0s 2ms/step - loss: 470866.1844 - val_loss: 541193.5000\nEpoch 384/400\n128/128 [==============================] - 0s 3ms/step - loss: 479482.8144 - val_loss: 450600.5625\nEpoch 385/400\n128/128 [==============================] - 0s 3ms/step - loss: 467212.0928 - val_loss: 447546.4062\nEpoch 386/400\n128/128 [==============================] - 0s 3ms/step - loss: 479391.0812 - val_loss: 487446.6875\nEpoch 387/400\n128/128 [==============================] - 0s 3ms/step - loss: 446155.0266 - val_loss: 453256.0000\nEpoch 388/400\n128/128 [==============================] - 0s 3ms/step - loss: 429435.9133 - val_loss: 466330.9375\nEpoch 389/400\n128/128 [==============================] - 0s 3ms/step - loss: 476348.3738 - val_loss: 442397.3438\nEpoch 390/400\n128/128 [==============================] - 0s 2ms/step - loss: 465569.7374 - val_loss: 446799.8750\nEpoch 391/400\n128/128 [==============================] - 0s 2ms/step - loss: 453758.4954 - val_loss: 618561.7500\nEpoch 392/400\n128/128 [==============================] - 0s 2ms/step - loss: 480963.7519 - val_loss: 443648.3438\nEpoch 393/400\n128/128 [==============================] - 0s 3ms/step - loss: 450927.2674 - val_loss: 454925.7812\nEpoch 394/400\n128/128 [==============================] - 0s 3ms/step - loss: 431572.2490 - val_loss: 456800.4375\nEpoch 395/400\n128/128 [==============================] - 0s 2ms/step - loss: 461386.8694 - val_loss: 476275.7500\nEpoch 396/400\n128/128 [==============================] - 0s 3ms/step - loss: 451536.6669 - val_loss: 453781.5312\nEpoch 397/400\n128/128 [==============================] - 0s 3ms/step - loss: 454535.9995 - val_loss: 442121.9688\nEpoch 398/400\n128/128 [==============================] - 0s 2ms/step - loss: 448421.2699 - val_loss: 449228.0312\nEpoch 399/400\n128/128 [==============================] - 0s 2ms/step - loss: 431275.2016 - val_loss: 446305.8125\nEpoch 400/400\n128/128 [==============================] - 0s 3ms/step - loss: 473413.7597 - val_loss: 449730.5312\n" ], [ "model.summary()", "Model: \"sequential_8\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_40 (Dense) (None, 19) 513 \n_________________________________________________________________\ndense_41 (Dense) (None, 19) 380 \n_________________________________________________________________\ndense_42 (Dense) (None, 19) 380 \n_________________________________________________________________\ndense_43 (Dense) (None, 19) 380 \n_________________________________________________________________\ndense_44 (Dense) (None, 1) 20 \n=================================================================\nTotal params: 1,673\nTrainable params: 1,673\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "y_pred = model.predict(X_test)", "_____no_output_____" ], [ "from sklearn import metrics\nimport numpy as np\n\nprint('MAE:', metrics.mean_absolute_error(y_test, y_pred)) \nprint('MSE:', metrics.mean_squared_error(y_test, y_pred)) \nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))\nprint('VarScore:',metrics.explained_variance_score(y_test,y_pred))\n# Visualizing Our predictions\nfig = plt.figure(figsize=(10,5))\nplt.scatter(y_test,y_pred)\n# Perfect predictions\nplt.plot(y_test,y_test,'r')", "MAE: 446.18126223883223\nMSE: 449730.47546398215\nRMSE: 670.6194714321842\nVarScore: 0.6057758648097856\n" ], [ "y = np.array(y_test)\ny_p = np.array(y_pred).flatten()\ndf = pd.DataFrame({\"test\": y, \"predictions\": y_p})\ndf.head(100)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc31f56ae1fff2bef1594b021fafacd5ab2dbd
767,944
ipynb
Jupyter Notebook
profiling.ipynb
rdeits/SoftRobots.jl
f73973c246951543ca3c56068ffb08cd81c6db7e
[ "MIT" ]
null
null
null
profiling.ipynb
rdeits/SoftRobots.jl
f73973c246951543ca3c56068ffb08cd81c6db7e
[ "MIT" ]
null
null
null
profiling.ipynb
rdeits/SoftRobots.jl
f73973c246951543ca3c56068ffb08cd81c6db7e
[ "MIT" ]
1
2020-02-08T11:34:07.000Z
2020-02-08T11:34:07.000Z
370.98744
334,240
0.678859
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
ecfc405da0f859c61c38831d6c7191b11038052b
7,345
ipynb
Jupyter Notebook
20190430.ipynb
yijiun0407/sss
b7f32f872c080d5d6bbcd2137a87a832437a73e8
[ "Apache-2.0" ]
null
null
null
20190430.ipynb
yijiun0407/sss
b7f32f872c080d5d6bbcd2137a87a832437a73e8
[ "Apache-2.0" ]
null
null
null
20190430.ipynb
yijiun0407/sss
b7f32f872c080d5d6bbcd2137a87a832437a73e8
[ "Apache-2.0" ]
null
null
null
17.081395
335
0.438393
[ [ [ "## 20190430", "_____no_output_____" ] ], [ [ "# int float, bool, string", "_____no_output_____" ], [ "#lst, dict, tuple", "_____no_output_____" ], [ "a=[]\nd={}\nc=()", "_____no_output_____" ], [ "print (type(a))\nprint (type(d))\nprint (type(c))", "<class 'list'>\n<class 'dict'>\n<class 'tuple'>\n" ], [ "a.append(1)", "_____no_output_____" ], [ "a.append('string')", "_____no_output_____" ], [ "a.append(True)", "_____no_output_____" ], [ "a", "_____no_output_____" ], [ "d['a']=10", "_____no_output_____" ], [ "d", "_____no_output_____" ], [ "d['b']=30", "_____no_output_____" ], [ "d", "_____no_output_____" ], [ "d.get('a')", "_____no_output_____" ], [ "e={'c':90, 'd':True}", "_____no_output_____" ], [ "e", "_____no_output_____" ], [ "e.get('e','oh no')", "_____no_output_____" ], [ "e.get('c','oh no')", "_____no_output_____" ], [ "type('c')", "_____no_output_____" ], [ "c=(1,3,5,6,1,1,1,4,6,6,6,6,)", "_____no_output_____" ], [ "type(c)", "_____no_output_____" ], [ "c.count(1)", "_____no_output_____" ], [ "c[0]", "_____no_output_____" ], [ "c[0]=\"1\" #tuple不同於list 不可任意置換", "_____no_output_____" ], [ "def add(i,j,k):\n return(i+j+k)\ndef substract(i,j,k):\n return(i-j-k)\ndef multiply(i,j,k):\n return(i*j*k)\ndef divid(i,j,k):\n return(i/j/k)", "_____no_output_____" ], [ "divid(12,2,3)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc40f37d28e14884a862563bd67ed5449d63d5
27,743
ipynb
Jupyter Notebook
notebooks/PlacesCNN_v3.1.experiment_4.ipynb
ifranco14/tf_real_estate_images_classification
a6aea3cb2b72fb88db815b0e6fcc72858a8d5f01
[ "MIT" ]
null
null
null
notebooks/PlacesCNN_v3.1.experiment_4.ipynb
ifranco14/tf_real_estate_images_classification
a6aea3cb2b72fb88db815b0e6fcc72858a8d5f01
[ "MIT" ]
null
null
null
notebooks/PlacesCNN_v3.1.experiment_4.ipynb
ifranco14/tf_real_estate_images_classification
a6aea3cb2b72fb88db815b0e6fcc72858a8d5f01
[ "MIT" ]
null
null
null
46.392977
331
0.608622
[ [ [ "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\ntf.keras.backend.clear_session()", "_____no_output_____" ], [ "from src.models import places_ontop_model\nfrom src import custom_losses, custom_metrics, optimizers\nfrom src.data import data", "Using TensorFlow backend.\n" ], [ "batch_size = 128\nn_classes = 6\nepochs = 100\nimg_size = 224\nn_channels = 3", "_____no_output_____" ], [ "model = places_ontop_model.PlacesOntop_Model(batch_size, n_classes, epochs, img_size, n_channels, version=7)", "WARNING: Logging before flag parsing goes to stderr.\nW0106 00:06:01.419593 140213472909120 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tesis_env/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:4070: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead.\n\n" ], [ "from src.data import data", "_____no_output_____" ], [ "paths = data.PATH()\ndataset_path = f'{paths.PROCESSED_DATA_PATH}/'\ndataset = 'vision_based_dataset'\ntest_dataset_path = f'{dataset_path}/{dataset}/'", "_____no_output_____" ], [ "train_generator, validation_generator, test_generator = model.get_image_data_generator(test_dataset_path, train=True, validation=True, test=True, class_mode_validation='categorical', class_mode_test='categorical')", "Found 114361 images belonging to 6 classes.\nFound 6305 images belonging to 6 classes.\nFound 6328 images belonging to 6 classes.\n" ], [ "weights = model.get_class_weights(train_generator.classes, model)\nmodel.compile(loss=custom_losses.weighted_categorical_crossentropy(weights), metrics=['categorical_accuracy'],)\n# model.model.compile(optimizer='adam', loss=custom_losses.weighted_categorical_crossentropy(weights), metrics=['categorical_accuracy'],)\n# instance_model.compile(optimizer='adam', loss=custom_losses.weighted_categorical_crossentropy(weights), metrics=['categorical_accuracy'],)", "_____no_output_____" ], [ "model.show_summary()", "##### PlacesOntop_Model #####\nModel: \"model_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) (None, 224, 224, 3) 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n_________________________________________________________________\nglobal_max_pooling2d_1 (Glob (None, 512) 0 \n_________________________________________________________________\npredictions (Dense) (None, 6) 3078 \n=================================================================\nTotal params: 14,717,766\nTrainable params: 3,078\nNon-trainable params: 14,714,688\n_________________________________________________________________\n\n" ], [ "model.fit_from_generator(path=f'{dataset_path}/{dataset}', \n train_generator=train_generator, validation_generator=validation_generator,\n test_generator=test_generator,\n evaluate_net=False, use_model_check_point=True, use_early_stop=True, weighted=True,\n show_activations=False,)", "W0106 00:06:24.504561 140213472909120 callbacks.py:875] `period` argument is deprecated. Please use `save_freq` to specify the frequency in number of samples seen.\nW0106 00:06:24.505112 140213472909120 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:354: The name tf.global_variables_initializer is deprecated. Please use tf.compat.v1.global_variables_initializer instead.\n\nW0106 00:06:24.506791 140213472909120 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:355: The name tf.local_variables_initializer is deprecated. Please use tf.compat.v1.local_variables_initializer instead.\n\nW0106 00:06:24.508421 140213472909120 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:356: The name tf.keras.backend.get_session is deprecated. Please use tf.compat.v1.keras.backend.get_session instead.\n\n" ], [ "model.fit_from_generator(path=f'{dataset_path}/{dataset}', \n train_generator=train_generator, validation_generator=validation_generator,\n test_generator=test_generator,\n evaluate_net=False, use_model_check_point=True, use_early_stop=True, weighted=True,\n show_activations=False,)", "W0105 18:55:05.993316 140515426867008 callbacks.py:875] `period` argument is deprecated. Please use `save_freq` to specify the frequency in number of samples seen.\nW0105 18:55:05.993947 140515426867008 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:354: The name tf.global_variables_initializer is deprecated. Please use tf.compat.v1.global_variables_initializer instead.\n\nW0105 18:55:05.996554 140515426867008 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:355: The name tf.local_variables_initializer is deprecated. Please use tf.compat.v1.local_variables_initializer instead.\n\nW0105 18:55:06.000074 140515426867008 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:356: The name tf.keras.backend.get_session is deprecated. Please use tf.compat.v1.keras.backend.get_session instead.\n\n" ], [ "model.model_path", "_____no_output_____" ], [ "model = model.load_model(model.model_path)", "_____no_output_____" ], [ "model.model_is_trained = True", "_____no_output_____" ], [ "model.save_model()", "weights [2.09728947 0.87794411 1.08704042 0.8524606 0.87239869 0.87343812]\n" ] ], [ [ "### Notas:\n#### - Probar configuraciones 6, 7, 8 y 9.\n#### - Comparar mejor resultado con notebook placescnn_v2.1\n#### - Probar configuraciones desfrizando bloques convolutivos de la red", "_____no_output_____" ] ], [ [ "model.fit_from_generator(path=f'{dataset_path}/{dataset}', \n train_generator=train_generator, validation_generator=validation_generator,\n test_generator=test_generator,\n evaluate_net=False, use_model_check_point=True, use_early_stop=True, weighted=True,\n show_activations=False,)", "W1215 16:28:29.501663 140671186286400 callbacks.py:875] `period` argument is deprecated. Please use `save_freq` to specify the frequency in number of samples seen.\nW1215 16:28:29.502433 140671186286400 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:352: The name tf.global_variables_initializer is deprecated. Please use tf.compat.v1.global_variables_initializer instead.\n\nW1215 16:28:29.507600 140671186286400 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:353: The name tf.local_variables_initializer is deprecated. Please use tf.compat.v1.local_variables_initializer instead.\n\nW1215 16:28:29.512035 140671186286400 deprecation_wrapper.py:119] From /home/ifranco/Documents/facultad/tesis/tf_real_estate_images_classification/src/models/base_model.py:354: The name tf.keras.backend.get_session is deprecated. Please use tf.compat.v1.keras.backend.get_session instead.\n\n" ], [ "model.model_is_trained = True", "_____no_output_____" ], [ "model.save_model()", "weights [2.09728947 0.87794411 1.08704042 0.8524606 0.87239869 0.87343812]\n" ], [ "model.predict_from_generator()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
ecfc45e539b48b43bb8f16be3fb77c87905ff7df
17,265
ipynb
Jupyter Notebook
00.ipynb
Programmer-RD-AI/Apple-Stock-Price
fff9a4dd5cd17cb8f55d4277a708dadd49641399
[ "Apache-2.0" ]
null
null
null
00.ipynb
Programmer-RD-AI/Apple-Stock-Price
fff9a4dd5cd17cb8f55d4277a708dadd49641399
[ "Apache-2.0" ]
null
null
null
00.ipynb
Programmer-RD-AI/Apple-Stock-Price
fff9a4dd5cd17cb8f55d4277a708dadd49641399
[ "Apache-2.0" ]
null
null
null
33.138196
143
0.48468
[ [ [ "import random\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nimport torch,torchvision\nfrom torch.nn import *\nfrom tqdm import tqdm\nimport cv2\nfrom torch.optim import *\n# Preproccessing\nfrom sklearn.preprocessing import (\n StandardScaler,\n RobustScaler,\n MinMaxScaler,\n MaxAbsScaler,\n OneHotEncoder,\n Normalizer,\n Binarizer\n)\n# Decomposition\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import KernelPCA\n# Feature Selection\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.feature_selection import SelectFromModel\n# Model Eval\nfrom sklearn.compose import make_column_transformer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score,train_test_split\nfrom sklearn.metrics import mean_absolute_error,mean_squared_error\n# Other\nimport pickle\nimport wandb\n\nPROJECT_NAME = 'Apple-Stock-Price'\ndevice = 'cuda:0'\nnp.random.seed(21)\nrandom.seed(21)\ntorch.manual_seed(21)", "_____no_output_____" ], [ "data = pd.read_csv('./data.csv')", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "data = data['Open']", "_____no_output_____" ], [ "data = data.tolist()", "_____no_output_____" ], [ "data = torch.from_numpy(np.array(data)).view(1,-1).to(device).to(device).float()", "_____no_output_____" ], [ "data_input = data[:1,:-1].float()\ndata_target = data[:1,1:].float()", "_____no_output_____" ], [ "class Model(Module):\n def __init__(self):\n super().__init__()\n self.hidden = 64\n self.lstm1 = LSTMCell(1,self.hidden)\n self.lstm2 = LSTMCell(self.hidden,self.hidden)\n self.lstm3 = LSTMCell(self.hidden,self.hidden)\n self.linear = Linear(self.hidden,1)\n \n def forward(self,X,future=0):\n preds = []\n batch_size = X.size(0)\n h_t1,c_t1 = torch.zeros(batch_size,self.hidden).to(device),torch.zeros(batch_size,self.hidden).to(device)\n h_t2,c_t2 = torch.zeros(batch_size,self.hidden).to(device),torch.zeros(batch_size,self.hidden).to(device)\n h_t3,c_t3 = torch.zeros(batch_size,self.hidden).to(device),torch.zeros(batch_size,self.hidden).to(device)\n for X_batch in X.split(1,dim=1):\n X_batch = X_batch.to(device)\n h_t1,c_t1 = self.lstm1(X_batch,(h_t1,c_t1))\n h_t1,c_t1 = h_t1.to(device),c_t1.to(device)\n h_t2,c_t2 = self.lstm2(h_t1,(h_t2,c_t2))\n h_t2,c_t2 = h_t2.to(device),c_t2.to(device)\n h_t3,c_t3 = self.lstm3(h_t2,(h_t3,c_t3))\n h_t3,c_t3 = h_t3.to(device),c_t3.to(device)\n pred = self.linear(h_t3)\n preds.append(pred)\n for _ in range(future):\n X_batch = X_batch.to(device)\n h_t1,c_t1 = self.lstm1(X_batch,(h_t1,c_t1))\n h_t1,c_t1 = h_t1.to(device),c_t1.to(device)\n h_t2,c_t2 = self.lstm2(h_t1,(h_t2,c_t2))\n h_t2,c_t2 = h_t2.to(device),c_t2.to(device)\n h_t3,c_t3 = self.lstm3(h_t2,(h_t3,c_t3))\n h_t3,c_t3 = h_t3.to(device),c_t3.to(device)\n pred = self.linear(h_t3)\n preds.append(pred)\n preds = torch.cat(preds,dim=1)\n return preds", "_____no_output_____" ], [ "model = Model().to(device)\ncriterion = MSELoss()", "_____no_output_____" ], [ "optimizer = Adam(model.parameters(),lr=0.001)", "_____no_output_____" ], [ "epochs = 100", "_____no_output_____" ], [ "# wandb.init(project=PROJECT_NAME,name='baseline')\n# for _ in tqdm(range(epochs)):\n# def closure():\n# optimizer.zero_grad()\n# preds = model(data_input)\n# loss = criterion(preds,data_target)\n# loss.backward()\n# wandb.log({'Loss':loss.item()})\n# return loss\n# optimizer.step(closure)\n# with torch.no_grad():\n# n = data_input.shape[1]\n# future = 100\n# preds = model(data_input,future)\n# loss = criterion(preds[:,:-future],data_target)\n# wandb.log({'Val Loss':loss.item()})\n# preds = preds[0].view(-1).cpu().detach().numpy()\n# plt.plot(figsize=(12,6))\n# plt.plot(np.arange(n),data_target.view(-1).cpu().detach().numpy())\n# plt.plot(np.arange(n,n+future),preds[n:])\n# plt.savefig('./img.png')\n# plt.close()\n# wandb.log({'Img':wandb.Image(cv2.imread('./img.png'))})\n# wandb.finish()", "Exception in thread Thread-17:\nTraceback (most recent call last):\n File \"/home/indika/anaconda3/lib/python3.7/threading.py\", line 926, in _bootstrap_inner\n self.run()\n File \"/home/indika/anaconda3/lib/python3.7/threading.py\", line 870, in run\n self._target(*self._args, **self._kwargs)\n File \"/home/indika/anaconda3/lib/python3.7/site-packages/wandb/sdk/wandb_run.py\", line 203, in check_status\n status_response = self._interface.communicate_stop_status()\n File \"/home/indika/anaconda3/lib/python3.7/site-packages/wandb/sdk/interface/interface.py\", line 737, in communicate_stop_status\n resp = self._communicate(req, timeout=timeout, local=True)\n File \"/home/indika/anaconda3/lib/python3.7/site-packages/wandb/sdk/interface/interface.py\", line 539, in _communicate\n return self._communicate_async(rec, local=local).get(timeout=timeout)\n File \"/home/indika/anaconda3/lib/python3.7/site-packages/wandb/sdk/interface/interface.py\", line 544, in _communicate_async\n raise Exception(\"The wandb backend process has shutdown\")\nException: The wandb backend process has shutdown\n\n" ], [ "torch.save(data,'./data.pt')\ntorch.save(data,'./data.pth')\ntorch.save(data_input,'data_input.pt')\ntorch.save(data_input,'data_input.pth')\ntorch.save(data_target,'data_target.pt')\ntorch.save(data_target,'data_target.pth')", "_____no_output_____" ], [ "torch.save(model,'custom-model.pt')\ntorch.save(model,'custom-model.pth')\ntorch.save(model.state_dict(),'custom-model-sd.pt')\ntorch.save(model.state_dict(),'custom-model-sd.pth')\ntorch.save(model,'model.pt')\ntorch.save(model,'model.pth')\ntorch.save(model.state_dict(),'model-sd.pt')\ntorch.save(model.state_dict(),'model-sd.pth')", "_____no_output_____" ], [ "torch.save(model,'custom-model.pt')\ntorch.save(model,'custom-model.pth')\ntorch.save(model.state_dict(),'custom-model-sd.pt')\ntorch.save(model.state_dict(),'custom-model-sd.pth')\ntorch.save(model,'model.pt')\ntorch.save(model,'model.pth')\ntorch.save(model.state_dict(),'model-sd.pt')\ntorch.save(model.state_dict(),'model-sd.pth')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc535da86fcd7545d59e52f356b8660c660d33
8,064
ipynb
Jupyter Notebook
Array/linear_regression.ipynb
jdgomezmo/gee
7016c47ee902dbf60b1aeb6319424c61c1107345
[ "MIT" ]
1
2020-11-16T22:07:42.000Z
2020-11-16T22:07:42.000Z
Array/linear_regression.ipynb
tingli3/earthengine-py-notebooks
7016c47ee902dbf60b1aeb6319424c61c1107345
[ "MIT" ]
null
null
null
Array/linear_regression.ipynb
tingli3/earthengine-py-notebooks
7016c47ee902dbf60b1aeb6319424c61c1107345
[ "MIT" ]
null
null
null
44.065574
1,031
0.576513
[ [ [ "<table class=\"ee-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Array/linear_regression.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n <td><a target=\"_blank\" href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Array/linear_regression.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Array/linear_regression.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n</table>", "_____no_output_____" ], [ "## Install Earth Engine API and geemap\nInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\nThe following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n\n**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).", "_____no_output_____" ] ], [ [ "# Installs geemap package\nimport subprocess\n\ntry:\n import geemap\nexcept ImportError:\n print('geemap package not installed. Installing ...')\n subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n\n# Checks whether this notebook is running on Google Colab\ntry:\n import google.colab\n import geemap.eefolium as geemap\nexcept:\n import geemap\n\n# Authenticates and initializes Earth Engine\nimport ee\n\ntry:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize() ", "_____no_output_____" ] ], [ [ "## Create an interactive map \nThe default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. ", "_____no_output_____" ] ], [ [ "Map = geemap.Map(center=[40,-100], zoom=4)\nMap", "_____no_output_____" ] ], [ [ "## Add Earth Engine Python script ", "_____no_output_____" ] ], [ [ "# Add Earth Engine dataset\n# Simple regression of year versus NDVI.\n\n# Define the start date and position to get images covering Montezuma Castle,\n# Arizona, from 2000-2010.\nstart = '2000-01-01'\nend = '2010-01-01'\nlng = -111.83533\nlat = 34.57499\nregion = ee.Geometry.Point(lng, lat)\n\n# Filter to Landsat 7 images in the given time and place, filter to a regular\n# time of year to avoid seasonal affects, and for each image create the bands\n# we will regress on:\n# 1. A 1, so the resulting array has a column of ones to capture the offset.\n# 2. Fractional year past 2000-01-01.\n# 3. NDVI.\n\ndef addBand(image):\n date = ee.Date(image.get('system:time_start'))\n yearOffset = date.difference(ee.Date(start), 'year')\n ndvi = image.normalizedDifference(['B4', 'B3'])\n return ee.Image(1).addBands(yearOffset).addBands(ndvi).toDouble()\n\n\nimages = ee.ImageCollection('LANDSAT/LE07/C01/T1') \\\n .filterDate(start, end) \\\n .filter(ee.Filter.dayOfYear(160, 240)) \\\n .filterBounds(region) \\\n .map(addBand) \n# date = ee.Date(image.get('system:time_start'))\n# yearOffset = date.difference(ee.Date(start), 'year')\n# ndvi = image.normalizedDifference(['B4', 'B3'])\n# return ee.Image(1).addBands(yearOffset).addBands(ndvi).toDouble()\n# })\n\n# Convert to an array. Give the axes names for more readable code.\narray = images.toArray()\nimageAxis = 0\nbandAxis = 1\n\n# Slice off the year and ndvi, and solve for the coefficients.\nx = array.arraySlice(bandAxis, 0, 2)\ny = array.arraySlice(bandAxis, 2)\nfit = x.matrixSolve(y)\n\n# Get the coefficient for the year, effectively the slope of the long-term\n# NDVI trend.\nslope = fit.arrayGet([1, 0])\n\nMap.setCenter(lng, lat, 12)\nMap.addLayer(slope, {'min': -0.03, 'max': 0.03}, 'Slope')\n\n", "_____no_output_____" ] ], [ [ "## Display Earth Engine data layers ", "_____no_output_____" ] ], [ [ "Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\nMap", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfc59923d581b0d0b37b4c0eeb1f8b66dd6e3e2
374,323
ipynb
Jupyter Notebook
Notebooks/ORF_CNN_123.ipynb
ShepherdCode/Soars2021
ab4f304eaa09e52d260152397a6c53d7a05457da
[ "MIT" ]
1
2021-08-16T14:49:04.000Z
2021-08-16T14:49:04.000Z
Notebooks/ORF_CNN_123.ipynb
ShepherdCode/Soars2021
ab4f304eaa09e52d260152397a6c53d7a05457da
[ "MIT" ]
null
null
null
Notebooks/ORF_CNN_123.ipynb
ShepherdCode/Soars2021
ab4f304eaa09e52d260152397a6c53d7a05457da
[ "MIT" ]
null
null
null
119.86007
36,522
0.634497
[ [ [ "# ORF recognition by CNN\n\nUse variable number of bases between START and STOP. Thus, ncRNA will have its STOP out-of-frame or too close to the START, and pcRNA will have its STOP in-frame and far from the START.", "_____no_output_____" ] ], [ [ "import time \nt = time.time()\ntime.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(t))", "_____no_output_____" ], [ "PC_SEQUENCES=32000 # how many protein-coding sequences\nNC_SEQUENCES=32000 # how many non-coding sequences\nPC_TESTS=1000\nNC_TESTS=1000\nRNA_LEN=32 # how long is each sequence\nCDS_LEN=16 # min CDS len to be coding\nALPHABET=4 # how many different letters are possible\nINPUT_SHAPE_2D = (RNA_LEN,ALPHABET,1) # Conv2D needs 3D inputs\nINPUT_SHAPE = (RNA_LEN,ALPHABET) # Conv1D needs 2D inputs\nFILTERS = 16 # how many different patterns the model looks for\nNEURONS = 16\nDROP_RATE = 0.4\nWIDTH = 3 # how wide each pattern is, in bases\nSTRIDE_2D = (1,1) # For Conv2D how far in each direction\nSTRIDE = 1 # For Conv1D, how far between pattern matches, in bases\nEPOCHS=400 # how many times to train on all the data\nSPLITS=3 # SPLITS=3 means train on 2/3 and validate on 1/3 \nFOLDS=3 # train the model this many times (range 1 to SPLITS)", "_____no_output_____" ], [ "import sys\nIN_COLAB = False\ntry:\n from google.colab import drive\n IN_COLAB = True\nexcept:\n pass\nif IN_COLAB:\n print(\"On Google CoLab, mount cloud-local file, get our code from GitHub.\")\n PATH='/content/drive/'\n #drive.mount(PATH,force_remount=True) # hardly ever need this\n #drive.mount(PATH) # Google will require login credentials\n DATAPATH=PATH+'My Drive/data/' # must end in \"/\"\n import requests\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/RNA_describe.py')\n with open('RNA_describe.py', 'w') as f:\n f.write(r.text) \n from RNA_describe import ORF_counter\n from RNA_describe import Random_Base_Oracle\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/RNA_prep.py')\n with open('RNA_prep.py', 'w') as f:\n f.write(r.text) \n from RNA_prep import prepare_inputs_len_x_alphabet\nelse:\n print(\"CoLab not working. On my PC, use relative paths.\")\n DATAPATH='data/' # must end in \"/\"\n sys.path.append(\"..\") # append parent dir in order to use sibling dirs\n from SimTools.RNA_describe import ORF_counter,Random_Base_Oracle\n from SimTools.RNA_prep import prepare_inputs_len_x_alphabet\n\nMODELPATH=\"BestModel\" # saved on cloud instance and lost after logout\n#MODELPATH=DATAPATH+MODELPATH # saved on Google Drive but requires login", "On Google CoLab, mount cloud-local file, get our code from GitHub.\n" ], [ "from os import listdir\nimport csv\nfrom zipfile import ZipFile\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats # mode\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Embedding,Dropout\nfrom keras.layers import Conv1D,Conv2D\nfrom keras.layers import Flatten,MaxPooling1D,MaxPooling2D\nfrom keras.losses import BinaryCrossentropy\n# tf.keras.losses.BinaryCrossentropy\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nmycmap = colors.ListedColormap(['red','blue']) # list color for label 0 then 1\nnp.set_printoptions(precision=2)\n", "_____no_output_____" ], [ "rbo=Random_Base_Oracle(RNA_LEN,True)\npc_all,nc_all = rbo.get_partitioned_sequences(CDS_LEN,10) # just testing\npc_all,nc_all = rbo.get_partitioned_sequences(CDS_LEN,PC_SEQUENCES+PC_TESTS)\nprint(\"Use\",len(pc_all),\"PC seqs\")\nprint(\"Use\",len(nc_all),\"NC seqs\")", "It took 59 trials to reach 10 per class.\nIt took 144231 trials to reach 33000 per class.\nUse 33000 PC seqs\nUse 33000 NC seqs\n" ], [ "# Describe the sequences\ndef describe_sequences(list_of_seq):\n oc = ORF_counter()\n num_seq = len(list_of_seq)\n rna_lens = np.zeros(num_seq)\n orf_lens = np.zeros(num_seq)\n for i in range(0,num_seq):\n rna_len = len(list_of_seq[i])\n rna_lens[i] = rna_len\n oc.set_sequence(list_of_seq[i])\n orf_len = oc.get_max_orf_len()\n orf_lens[i] = orf_len\n print (\"Average RNA length:\",rna_lens.mean())\n print (\"Average ORF length:\",orf_lens.mean())\n \nprint(\"Simulated sequences prior to adjustment:\")\nprint(\"PC seqs\")\ndescribe_sequences(pc_all)\nprint(\"NC seqs\")\ndescribe_sequences(nc_all)", "Simulated sequences prior to adjustment:\nPC seqs\nAverage RNA length: 32.0\nAverage ORF length: 19.688727272727274\nNC seqs\nAverage RNA length: 32.0\nAverage ORF length: 2.8624545454545456\n" ], [ "pc_train=pc_all[:PC_SEQUENCES]\nnc_train=nc_all[:NC_SEQUENCES]\npc_test=pc_all[PC_SEQUENCES:]\nnc_test=nc_all[NC_SEQUENCES:]", "_____no_output_____" ], [ "# Use code from our SimTools library.\nX,y = prepare_inputs_len_x_alphabet(pc_train,nc_train,ALPHABET) # shuffles\nprint(\"Data ready.\")", "Data ready.\n" ], [ "def make_DNN():\n print(\"make_DNN\")\n print(\"input shape:\",INPUT_SHAPE)\n dnn = Sequential()\n #dnn.add(Embedding(input_dim=INPUT_SHAPE,output_dim=INPUT_SHAPE)) \n dnn.add(Conv1D(filters=FILTERS,kernel_size=WIDTH,strides=STRIDE,padding=\"same\",\n input_shape=INPUT_SHAPE))\n dnn.add(Conv1D(filters=FILTERS,kernel_size=WIDTH,strides=STRIDE,padding=\"same\"))\n dnn.add(MaxPooling1D())\n #dnn.add(Conv1D(filters=FILTERS,kernel_size=WIDTH,strides=STRIDE,padding=\"same\"))\n #dnn.add(Conv1D(filters=FILTERS,kernel_size=WIDTH,strides=STRIDE,padding=\"same\"))\n #dnn.add(MaxPooling1D())\n dnn.add(Flatten())\n dnn.add(Dense(NEURONS,activation=\"sigmoid\",dtype=np.float32)) \n dnn.add(Dropout(DROP_RATE))\n dnn.add(Dense(1,activation=\"sigmoid\",dtype=np.float32)) \n dnn.compile(optimizer='adam',\n loss=BinaryCrossentropy(from_logits=False),\n metrics=['accuracy']) # add to default metrics=loss\n dnn.build(input_shape=INPUT_SHAPE)\n #ln_rate = tf.keras.optimizers.Adam(learning_rate = LN_RATE)\n #bc=tf.keras.losses.BinaryCrossentropy(from_logits=False)\n #model.compile(loss=bc, optimizer=ln_rate, metrics=[\"accuracy\"])\n return dnn\nmodel = make_DNN()\nprint(model.summary())", "make_DNN\ninput shape: (32, 4)\nModel: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv1d (Conv1D) (None, 32, 16) 208 \n_________________________________________________________________\nconv1d_1 (Conv1D) (None, 32, 16) 784 \n_________________________________________________________________\nmax_pooling1d (MaxPooling1D) (None, 16, 16) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 256) 0 \n_________________________________________________________________\ndense (Dense) (None, 16) 4112 \n_________________________________________________________________\ndropout (Dropout) (None, 16) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1) 17 \n=================================================================\nTotal params: 5,121\nTrainable params: 5,121\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ], [ "from keras.callbacks import ModelCheckpoint\ndef do_cross_validation(X,y):\n cv_scores = []\n fold=0\n mycallbacks = [ModelCheckpoint(\n filepath=MODELPATH, save_best_only=True, \n monitor='val_accuracy', mode='max')] \n splitter = KFold(n_splits=SPLITS) # this does not shuffle\n for train_index,valid_index in splitter.split(X):\n if fold < FOLDS:\n fold += 1\n X_train=X[train_index] # inputs for training\n y_train=y[train_index] # labels for training\n X_valid=X[valid_index] # inputs for validation\n y_valid=y[valid_index] # labels for validation\n print(\"MODEL\")\n # Call constructor on each CV. Else, continually improves the same model.\n model = model = make_DNN()\n print(\"FIT\") # model.fit() implements learning\n start_time=time.time()\n history=model.fit(X_train, y_train, \n epochs=EPOCHS, \n verbose=1, # ascii art while learning\n callbacks=mycallbacks, # called at end of each epoch\n validation_data=(X_valid,y_valid))\n end_time=time.time()\n elapsed_time=(end_time-start_time) \n print(\"Fold %d, %d epochs, %d sec\"%(fold,EPOCHS,elapsed_time))\n # print(history.history.keys()) # all these keys will be shown in figure\n pd.DataFrame(history.history).plot(figsize=(8,5))\n plt.grid(True)\n plt.gca().set_ylim(0,1) # any losses > 1 will be off the scale\n plt.show()\n", "_____no_output_____" ], [ "do_cross_validation(X,y)", "MODEL\nmake_DNN\ninput shape: (32, 4)\nFIT\nEpoch 1/400\n1334/1334 [==============================] - 48s 4ms/step - loss: 0.6391 - accuracy: 0.6246 - val_loss: 0.4810 - val_accuracy: 0.7701\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 2/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.4872 - accuracy: 0.7668 - val_loss: 0.4255 - val_accuracy: 0.8007\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 3/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.4401 - accuracy: 0.7944 - val_loss: 0.3941 - val_accuracy: 0.8147\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 4/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.4224 - accuracy: 0.7999 - val_loss: 0.3772 - val_accuracy: 0.8255\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 5/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.4002 - accuracy: 0.8129 - val_loss: 0.3603 - val_accuracy: 0.8294\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 6/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3856 - accuracy: 0.8205 - val_loss: 0.3514 - val_accuracy: 0.8356\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 7/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3838 - accuracy: 0.8183 - val_loss: 0.3494 - val_accuracy: 0.8325\nEpoch 8/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3775 - accuracy: 0.8181 - val_loss: 0.3396 - val_accuracy: 0.8397\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 9/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3690 - accuracy: 0.8203 - val_loss: 0.3471 - val_accuracy: 0.8374\nEpoch 10/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3706 - accuracy: 0.8192 - val_loss: 0.3260 - val_accuracy: 0.8450\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 11/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3544 - accuracy: 0.8288 - val_loss: 0.3184 - val_accuracy: 0.8451\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 12/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3500 - accuracy: 0.8284 - val_loss: 0.3160 - val_accuracy: 0.8456\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 13/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3505 - accuracy: 0.8270 - val_loss: 0.3117 - val_accuracy: 0.8493\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 14/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3460 - accuracy: 0.8320 - val_loss: 0.3105 - val_accuracy: 0.8497\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 15/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3395 - accuracy: 0.8331 - val_loss: 0.3102 - val_accuracy: 0.8531\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 16/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3396 - accuracy: 0.8320 - val_loss: 0.3031 - val_accuracy: 0.8509\nEpoch 17/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3359 - accuracy: 0.8348 - val_loss: 0.3026 - val_accuracy: 0.8495\nEpoch 18/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3343 - accuracy: 0.8378 - val_loss: 0.3013 - val_accuracy: 0.8522\nEpoch 19/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3332 - accuracy: 0.8379 - val_loss: 0.2966 - val_accuracy: 0.8577\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 20/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3328 - accuracy: 0.8393 - val_loss: 0.2931 - val_accuracy: 0.8579\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 21/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3314 - accuracy: 0.8387 - val_loss: 0.2984 - val_accuracy: 0.8586\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 22/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3261 - accuracy: 0.8445 - val_loss: 0.2913 - val_accuracy: 0.8593\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 23/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3235 - accuracy: 0.8433 - val_loss: 0.2854 - val_accuracy: 0.8617\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 24/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3292 - accuracy: 0.8399 - val_loss: 0.2865 - val_accuracy: 0.8614\nEpoch 25/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3221 - accuracy: 0.8415 - val_loss: 0.2885 - val_accuracy: 0.8639\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 26/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3214 - accuracy: 0.8405 - val_loss: 0.2833 - val_accuracy: 0.8652\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 27/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3165 - accuracy: 0.8445 - val_loss: 0.2803 - val_accuracy: 0.8648\nEpoch 28/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3151 - accuracy: 0.8450 - val_loss: 0.2850 - val_accuracy: 0.8661\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 29/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3127 - accuracy: 0.8445 - val_loss: 0.2838 - val_accuracy: 0.8649\nEpoch 30/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3063 - accuracy: 0.8472 - val_loss: 0.2837 - val_accuracy: 0.8667\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 31/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3134 - accuracy: 0.8443 - val_loss: 0.2827 - val_accuracy: 0.8643\nEpoch 32/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3098 - accuracy: 0.8503 - val_loss: 0.2761 - val_accuracy: 0.8693\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 33/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3162 - accuracy: 0.8454 - val_loss: 0.2792 - val_accuracy: 0.8622\nEpoch 34/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3074 - accuracy: 0.8488 - val_loss: 0.2761 - val_accuracy: 0.8701\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 35/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3066 - accuracy: 0.8483 - val_loss: 0.2731 - val_accuracy: 0.8722\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 36/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3094 - accuracy: 0.8475 - val_loss: 0.2756 - val_accuracy: 0.8709\nEpoch 37/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3054 - accuracy: 0.8495 - val_loss: 0.2686 - val_accuracy: 0.8721\nEpoch 38/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3011 - accuracy: 0.8491 - val_loss: 0.2681 - val_accuracy: 0.8747\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 39/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3060 - accuracy: 0.8489 - val_loss: 0.2727 - val_accuracy: 0.8703\nEpoch 40/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3060 - accuracy: 0.8498 - val_loss: 0.2821 - val_accuracy: 0.8714\nEpoch 41/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3046 - accuracy: 0.8494 - val_loss: 0.2742 - val_accuracy: 0.8694\nEpoch 42/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3030 - accuracy: 0.8518 - val_loss: 0.2748 - val_accuracy: 0.8720\nEpoch 43/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2985 - accuracy: 0.8522 - val_loss: 0.2626 - val_accuracy: 0.8717\nEpoch 44/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3044 - accuracy: 0.8513 - val_loss: 0.2687 - val_accuracy: 0.8727\nEpoch 45/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.3045 - accuracy: 0.8526 - val_loss: 0.2607 - val_accuracy: 0.8726\nEpoch 46/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2973 - accuracy: 0.8560 - val_loss: 0.2650 - val_accuracy: 0.8757\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 47/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2894 - accuracy: 0.8559 - val_loss: 0.2634 - val_accuracy: 0.8719\nEpoch 48/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2938 - accuracy: 0.8535 - val_loss: 0.2648 - val_accuracy: 0.8763\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 49/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2950 - accuracy: 0.8527 - val_loss: 0.2610 - val_accuracy: 0.8739\nEpoch 50/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2978 - accuracy: 0.8539 - val_loss: 0.2550 - val_accuracy: 0.8766\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 51/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2923 - accuracy: 0.8545 - val_loss: 0.2662 - val_accuracy: 0.8762\nEpoch 52/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2908 - accuracy: 0.8578 - val_loss: 0.2552 - val_accuracy: 0.8755\nEpoch 53/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2921 - accuracy: 0.8540 - val_loss: 0.2548 - val_accuracy: 0.8789\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 54/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2920 - accuracy: 0.8558 - val_loss: 0.2579 - val_accuracy: 0.8772\nEpoch 55/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2929 - accuracy: 0.8533 - val_loss: 0.2592 - val_accuracy: 0.8781\nEpoch 56/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2919 - accuracy: 0.8557 - val_loss: 0.2629 - val_accuracy: 0.8758\nEpoch 57/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2959 - accuracy: 0.8546 - val_loss: 0.2571 - val_accuracy: 0.8792\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 58/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2902 - accuracy: 0.8565 - val_loss: 0.2529 - val_accuracy: 0.8794\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 59/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2910 - accuracy: 0.8549 - val_loss: 0.2568 - val_accuracy: 0.8798\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 60/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2907 - accuracy: 0.8550 - val_loss: 0.2574 - val_accuracy: 0.8784\nEpoch 61/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2898 - accuracy: 0.8569 - val_loss: 0.2642 - val_accuracy: 0.8775\nEpoch 62/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2873 - accuracy: 0.8572 - val_loss: 0.2506 - val_accuracy: 0.8810\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 63/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2886 - accuracy: 0.8534 - val_loss: 0.2515 - val_accuracy: 0.8774\nEpoch 64/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2904 - accuracy: 0.8563 - val_loss: 0.2576 - val_accuracy: 0.8714\nEpoch 65/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2859 - accuracy: 0.8569 - val_loss: 0.2532 - val_accuracy: 0.8809\nEpoch 66/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2872 - accuracy: 0.8594 - val_loss: 0.2562 - val_accuracy: 0.8768\nEpoch 67/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2839 - accuracy: 0.8574 - val_loss: 0.2539 - val_accuracy: 0.8790\nEpoch 68/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2803 - accuracy: 0.8587 - val_loss: 0.2537 - val_accuracy: 0.8795\nEpoch 69/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2880 - accuracy: 0.8554 - val_loss: 0.2587 - val_accuracy: 0.8780\nEpoch 70/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2848 - accuracy: 0.8584 - val_loss: 0.2495 - val_accuracy: 0.8793\nEpoch 71/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2843 - accuracy: 0.8585 - val_loss: 0.2509 - val_accuracy: 0.8754\nEpoch 72/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2867 - accuracy: 0.8576 - val_loss: 0.2461 - val_accuracy: 0.8805\nEpoch 73/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2807 - accuracy: 0.8581 - val_loss: 0.2504 - val_accuracy: 0.8773\nEpoch 74/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2799 - accuracy: 0.8590 - val_loss: 0.2517 - val_accuracy: 0.8754\nEpoch 75/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2869 - accuracy: 0.8569 - val_loss: 0.2480 - val_accuracy: 0.8802\nEpoch 76/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2871 - accuracy: 0.8533 - val_loss: 0.2557 - val_accuracy: 0.8792\nEpoch 77/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2793 - accuracy: 0.8602 - val_loss: 0.2480 - val_accuracy: 0.8832\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 78/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2874 - accuracy: 0.8579 - val_loss: 0.2498 - val_accuracy: 0.8797\nEpoch 79/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2778 - accuracy: 0.8600 - val_loss: 0.2489 - val_accuracy: 0.8779\nEpoch 80/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2830 - accuracy: 0.8590 - val_loss: 0.2545 - val_accuracy: 0.8813\nEpoch 81/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2802 - accuracy: 0.8572 - val_loss: 0.2455 - val_accuracy: 0.8790\nEpoch 82/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2828 - accuracy: 0.8581 - val_loss: 0.2480 - val_accuracy: 0.8807\nEpoch 83/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2772 - accuracy: 0.8603 - val_loss: 0.2483 - val_accuracy: 0.8761\nEpoch 84/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2740 - accuracy: 0.8609 - val_loss: 0.2507 - val_accuracy: 0.8747\nEpoch 85/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2773 - accuracy: 0.8625 - val_loss: 0.2478 - val_accuracy: 0.8814\nEpoch 86/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2743 - accuracy: 0.8600 - val_loss: 0.2490 - val_accuracy: 0.8801\nEpoch 87/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2734 - accuracy: 0.8631 - val_loss: 0.2464 - val_accuracy: 0.8786\nEpoch 88/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2754 - accuracy: 0.8619 - val_loss: 0.2464 - val_accuracy: 0.8802\nEpoch 89/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2793 - accuracy: 0.8613 - val_loss: 0.2469 - val_accuracy: 0.8838\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 90/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2782 - accuracy: 0.8592 - val_loss: 0.2416 - val_accuracy: 0.8836\nEpoch 91/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2767 - accuracy: 0.8618 - val_loss: 0.2418 - val_accuracy: 0.8823\nEpoch 92/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2736 - accuracy: 0.8620 - val_loss: 0.2398 - val_accuracy: 0.8827\nEpoch 93/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2739 - accuracy: 0.8644 - val_loss: 0.2453 - val_accuracy: 0.8802\nEpoch 94/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2770 - accuracy: 0.8600 - val_loss: 0.2474 - val_accuracy: 0.8827\nEpoch 95/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2757 - accuracy: 0.8608 - val_loss: 0.2416 - val_accuracy: 0.8831\nEpoch 96/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2736 - accuracy: 0.8616 - val_loss: 0.2438 - val_accuracy: 0.8790\nEpoch 97/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2714 - accuracy: 0.8628 - val_loss: 0.2511 - val_accuracy: 0.8821\nEpoch 98/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2734 - accuracy: 0.8629 - val_loss: 0.2426 - val_accuracy: 0.8831\nEpoch 99/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2742 - accuracy: 0.8628 - val_loss: 0.2430 - val_accuracy: 0.8838\nEpoch 100/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2823 - accuracy: 0.8578 - val_loss: 0.2457 - val_accuracy: 0.8815\nEpoch 101/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2702 - accuracy: 0.8652 - val_loss: 0.2427 - val_accuracy: 0.8841\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 102/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2738 - accuracy: 0.8607 - val_loss: 0.2461 - val_accuracy: 0.8822\nEpoch 103/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2760 - accuracy: 0.8618 - val_loss: 0.2380 - val_accuracy: 0.8841\nEpoch 104/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2758 - accuracy: 0.8597 - val_loss: 0.2463 - val_accuracy: 0.8817\nEpoch 105/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2714 - accuracy: 0.8628 - val_loss: 0.2436 - val_accuracy: 0.8843\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 106/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2712 - accuracy: 0.8625 - val_loss: 0.2401 - val_accuracy: 0.8855\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 107/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2689 - accuracy: 0.8640 - val_loss: 0.2436 - val_accuracy: 0.8791\nEpoch 108/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2660 - accuracy: 0.8632 - val_loss: 0.2459 - val_accuracy: 0.8839\nEpoch 109/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2717 - accuracy: 0.8625 - val_loss: 0.2458 - val_accuracy: 0.8816\nEpoch 110/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2752 - accuracy: 0.8611 - val_loss: 0.2496 - val_accuracy: 0.8817\nEpoch 111/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2729 - accuracy: 0.8645 - val_loss: 0.2384 - val_accuracy: 0.8833\nEpoch 112/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2708 - accuracy: 0.8609 - val_loss: 0.2422 - val_accuracy: 0.8854\nEpoch 113/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2736 - accuracy: 0.8610 - val_loss: 0.2422 - val_accuracy: 0.8794\nEpoch 114/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2720 - accuracy: 0.8601 - val_loss: 0.2359 - val_accuracy: 0.8848\nEpoch 115/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2654 - accuracy: 0.8650 - val_loss: 0.2381 - val_accuracy: 0.8845\nEpoch 116/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2768 - accuracy: 0.8623 - val_loss: 0.2429 - val_accuracy: 0.8840\nEpoch 117/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2684 - accuracy: 0.8669 - val_loss: 0.2448 - val_accuracy: 0.8784\nEpoch 118/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2688 - accuracy: 0.8624 - val_loss: 0.2412 - val_accuracy: 0.8870\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 119/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2676 - accuracy: 0.8615 - val_loss: 0.2442 - val_accuracy: 0.8828\nEpoch 120/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2735 - accuracy: 0.8626 - val_loss: 0.2388 - val_accuracy: 0.8845\nEpoch 121/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2722 - accuracy: 0.8582 - val_loss: 0.2444 - val_accuracy: 0.8833\nEpoch 122/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2741 - accuracy: 0.8644 - val_loss: 0.2407 - val_accuracy: 0.8845\nEpoch 123/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2756 - accuracy: 0.8630 - val_loss: 0.2451 - val_accuracy: 0.8826\nEpoch 124/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2678 - accuracy: 0.8671 - val_loss: 0.2426 - val_accuracy: 0.8803\nEpoch 125/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2737 - accuracy: 0.8577 - val_loss: 0.2398 - val_accuracy: 0.8828\nEpoch 126/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2787 - accuracy: 0.8613 - val_loss: 0.2403 - val_accuracy: 0.8805\nEpoch 127/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2746 - accuracy: 0.8598 - val_loss: 0.2406 - val_accuracy: 0.8817\nEpoch 128/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2657 - accuracy: 0.8647 - val_loss: 0.2413 - val_accuracy: 0.8850\nEpoch 129/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2607 - accuracy: 0.8679 - val_loss: 0.2392 - val_accuracy: 0.8848\nEpoch 130/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2655 - accuracy: 0.8653 - val_loss: 0.2371 - val_accuracy: 0.8869\nEpoch 131/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2686 - accuracy: 0.8622 - val_loss: 0.2419 - val_accuracy: 0.8816\nEpoch 132/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2694 - accuracy: 0.8617 - val_loss: 0.2429 - val_accuracy: 0.8840\nEpoch 133/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2658 - accuracy: 0.8629 - val_loss: 0.2427 - val_accuracy: 0.8851\nEpoch 134/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2622 - accuracy: 0.8627 - val_loss: 0.2409 - val_accuracy: 0.8822\nEpoch 135/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2662 - accuracy: 0.8660 - val_loss: 0.2406 - val_accuracy: 0.8865\nEpoch 136/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2682 - accuracy: 0.8616 - val_loss: 0.2433 - val_accuracy: 0.8864\nEpoch 137/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2638 - accuracy: 0.8643 - val_loss: 0.2425 - val_accuracy: 0.8862\nEpoch 138/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2664 - accuracy: 0.8640 - val_loss: 0.2420 - val_accuracy: 0.8839\nEpoch 139/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2650 - accuracy: 0.8649 - val_loss: 0.2395 - val_accuracy: 0.8865\nEpoch 140/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2659 - accuracy: 0.8657 - val_loss: 0.2409 - val_accuracy: 0.8842\nEpoch 141/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2596 - accuracy: 0.8694 - val_loss: 0.2366 - val_accuracy: 0.8868\nEpoch 142/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2628 - accuracy: 0.8660 - val_loss: 0.2384 - val_accuracy: 0.8823\nEpoch 143/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2647 - accuracy: 0.8652 - val_loss: 0.2386 - val_accuracy: 0.8854\nEpoch 144/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2664 - accuracy: 0.8647 - val_loss: 0.2380 - val_accuracy: 0.8851\nEpoch 145/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2621 - accuracy: 0.8675 - val_loss: 0.2375 - val_accuracy: 0.8772\nEpoch 146/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2675 - accuracy: 0.8601 - val_loss: 0.2503 - val_accuracy: 0.8863\nEpoch 147/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2640 - accuracy: 0.8636 - val_loss: 0.2413 - val_accuracy: 0.8816\nEpoch 148/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2637 - accuracy: 0.8680 - val_loss: 0.2371 - val_accuracy: 0.8811\nEpoch 149/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2653 - accuracy: 0.8655 - val_loss: 0.2380 - val_accuracy: 0.8840\nEpoch 150/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2650 - accuracy: 0.8644 - val_loss: 0.2466 - val_accuracy: 0.8862\nEpoch 151/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2675 - accuracy: 0.8659 - val_loss: 0.2399 - val_accuracy: 0.8838\nEpoch 152/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2710 - accuracy: 0.8618 - val_loss: 0.2417 - val_accuracy: 0.8875\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 153/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2632 - accuracy: 0.8665 - val_loss: 0.2399 - val_accuracy: 0.8797\nEpoch 154/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2740 - accuracy: 0.8596 - val_loss: 0.2390 - val_accuracy: 0.8856\nEpoch 155/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2550 - accuracy: 0.8724 - val_loss: 0.2344 - val_accuracy: 0.8839\nEpoch 156/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2642 - accuracy: 0.8667 - val_loss: 0.2397 - val_accuracy: 0.8804\nEpoch 157/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2604 - accuracy: 0.8656 - val_loss: 0.2393 - val_accuracy: 0.8829\nEpoch 158/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2611 - accuracy: 0.8665 - val_loss: 0.2372 - val_accuracy: 0.8850\nEpoch 159/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2631 - accuracy: 0.8673 - val_loss: 0.2435 - val_accuracy: 0.8839\nEpoch 160/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2648 - accuracy: 0.8631 - val_loss: 0.2360 - val_accuracy: 0.8877\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 161/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2678 - accuracy: 0.8669 - val_loss: 0.2364 - val_accuracy: 0.8833\nEpoch 162/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2623 - accuracy: 0.8653 - val_loss: 0.2357 - val_accuracy: 0.8854\nEpoch 163/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2632 - accuracy: 0.8662 - val_loss: 0.2362 - val_accuracy: 0.8860\nEpoch 164/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2677 - accuracy: 0.8638 - val_loss: 0.2379 - val_accuracy: 0.8839\nEpoch 165/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2649 - accuracy: 0.8616 - val_loss: 0.2473 - val_accuracy: 0.8868\nEpoch 166/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2622 - accuracy: 0.8687 - val_loss: 0.2448 - val_accuracy: 0.8865\nEpoch 167/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2634 - accuracy: 0.8651 - val_loss: 0.2363 - val_accuracy: 0.8847\nEpoch 168/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2569 - accuracy: 0.8695 - val_loss: 0.2373 - val_accuracy: 0.8856\nEpoch 169/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2610 - accuracy: 0.8648 - val_loss: 0.2416 - val_accuracy: 0.8869\nEpoch 170/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2612 - accuracy: 0.8651 - val_loss: 0.2403 - val_accuracy: 0.8831\nEpoch 171/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2593 - accuracy: 0.8673 - val_loss: 0.2349 - val_accuracy: 0.8875\nEpoch 172/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2634 - accuracy: 0.8666 - val_loss: 0.2367 - val_accuracy: 0.8857\nEpoch 173/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2621 - accuracy: 0.8654 - val_loss: 0.2354 - val_accuracy: 0.8844\nEpoch 174/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2636 - accuracy: 0.8650 - val_loss: 0.2424 - val_accuracy: 0.8881\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 175/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2636 - accuracy: 0.8679 - val_loss: 0.2366 - val_accuracy: 0.8827\nEpoch 176/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2606 - accuracy: 0.8675 - val_loss: 0.2355 - val_accuracy: 0.8863\nEpoch 177/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2629 - accuracy: 0.8670 - val_loss: 0.2357 - val_accuracy: 0.8847\nEpoch 178/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2602 - accuracy: 0.8669 - val_loss: 0.2372 - val_accuracy: 0.8853\nEpoch 179/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2637 - accuracy: 0.8657 - val_loss: 0.2363 - val_accuracy: 0.8886\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 180/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2626 - accuracy: 0.8650 - val_loss: 0.2354 - val_accuracy: 0.8891\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 181/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2616 - accuracy: 0.8635 - val_loss: 0.2407 - val_accuracy: 0.8872\nEpoch 182/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2608 - accuracy: 0.8655 - val_loss: 0.2358 - val_accuracy: 0.8878\nEpoch 183/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2646 - accuracy: 0.8652 - val_loss: 0.2349 - val_accuracy: 0.8872\nEpoch 184/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2635 - accuracy: 0.8637 - val_loss: 0.2375 - val_accuracy: 0.8887\nEpoch 185/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2680 - accuracy: 0.8645 - val_loss: 0.2350 - val_accuracy: 0.8853\nEpoch 186/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2642 - accuracy: 0.8629 - val_loss: 0.2404 - val_accuracy: 0.8871\nEpoch 187/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2576 - accuracy: 0.8672 - val_loss: 0.2348 - val_accuracy: 0.8853\nEpoch 188/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2590 - accuracy: 0.8683 - val_loss: 0.2382 - val_accuracy: 0.8885\nEpoch 189/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2620 - accuracy: 0.8652 - val_loss: 0.2429 - val_accuracy: 0.8751\nEpoch 190/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2649 - accuracy: 0.8629 - val_loss: 0.2410 - val_accuracy: 0.8883\nEpoch 191/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2591 - accuracy: 0.8661 - val_loss: 0.2354 - val_accuracy: 0.8897\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 192/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2594 - accuracy: 0.8669 - val_loss: 0.2340 - val_accuracy: 0.8852\nEpoch 193/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2616 - accuracy: 0.8657 - val_loss: 0.2403 - val_accuracy: 0.8879\nEpoch 194/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2583 - accuracy: 0.8675 - val_loss: 0.2378 - val_accuracy: 0.8844\nEpoch 195/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2612 - accuracy: 0.8657 - val_loss: 0.2381 - val_accuracy: 0.8858\nEpoch 196/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2619 - accuracy: 0.8664 - val_loss: 0.2338 - val_accuracy: 0.8872\nEpoch 197/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2608 - accuracy: 0.8680 - val_loss: 0.2357 - val_accuracy: 0.8866\nEpoch 198/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2614 - accuracy: 0.8685 - val_loss: 0.2342 - val_accuracy: 0.8892\nEpoch 199/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2581 - accuracy: 0.8662 - val_loss: 0.2370 - val_accuracy: 0.8806\nEpoch 200/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2629 - accuracy: 0.8672 - val_loss: 0.2348 - val_accuracy: 0.8899\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 201/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2597 - accuracy: 0.8673 - val_loss: 0.2358 - val_accuracy: 0.8869\nEpoch 202/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2559 - accuracy: 0.8680 - val_loss: 0.2315 - val_accuracy: 0.8859\nEpoch 203/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2587 - accuracy: 0.8652 - val_loss: 0.2331 - val_accuracy: 0.8881\nEpoch 204/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2636 - accuracy: 0.8671 - val_loss: 0.2374 - val_accuracy: 0.8859\nEpoch 205/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2580 - accuracy: 0.8686 - val_loss: 0.2347 - val_accuracy: 0.8884\nEpoch 206/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2628 - accuracy: 0.8664 - val_loss: 0.2388 - val_accuracy: 0.8850\nEpoch 207/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2598 - accuracy: 0.8631 - val_loss: 0.2400 - val_accuracy: 0.8868\nEpoch 208/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2566 - accuracy: 0.8681 - val_loss: 0.2339 - val_accuracy: 0.8866\nEpoch 209/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2585 - accuracy: 0.8683 - val_loss: 0.2420 - val_accuracy: 0.8859\nEpoch 210/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2594 - accuracy: 0.8674 - val_loss: 0.2325 - val_accuracy: 0.8827\nEpoch 211/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2577 - accuracy: 0.8682 - val_loss: 0.2319 - val_accuracy: 0.8858\nEpoch 212/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2592 - accuracy: 0.8641 - val_loss: 0.2375 - val_accuracy: 0.8900\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 213/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2612 - accuracy: 0.8676 - val_loss: 0.2365 - val_accuracy: 0.8895\nEpoch 214/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2540 - accuracy: 0.8720 - val_loss: 0.2359 - val_accuracy: 0.8863\nEpoch 215/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2592 - accuracy: 0.8677 - val_loss: 0.2366 - val_accuracy: 0.8881\nEpoch 216/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2592 - accuracy: 0.8671 - val_loss: 0.2309 - val_accuracy: 0.8834\nEpoch 217/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2589 - accuracy: 0.8672 - val_loss: 0.2362 - val_accuracy: 0.8897\nEpoch 218/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2570 - accuracy: 0.8674 - val_loss: 0.2359 - val_accuracy: 0.8882\nEpoch 219/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2616 - accuracy: 0.8675 - val_loss: 0.2383 - val_accuracy: 0.8875\nEpoch 220/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2582 - accuracy: 0.8686 - val_loss: 0.2341 - val_accuracy: 0.8854\nEpoch 221/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2586 - accuracy: 0.8683 - val_loss: 0.2330 - val_accuracy: 0.8864\nEpoch 222/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2567 - accuracy: 0.8685 - val_loss: 0.2363 - val_accuracy: 0.8824\nEpoch 223/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2575 - accuracy: 0.8691 - val_loss: 0.2373 - val_accuracy: 0.8816\nEpoch 224/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2591 - accuracy: 0.8661 - val_loss: 0.2330 - val_accuracy: 0.8880\nEpoch 225/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2543 - accuracy: 0.8687 - val_loss: 0.2380 - val_accuracy: 0.8896\nEpoch 226/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2597 - accuracy: 0.8684 - val_loss: 0.2351 - val_accuracy: 0.8842\nEpoch 227/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2531 - accuracy: 0.8719 - val_loss: 0.2348 - val_accuracy: 0.8885\nEpoch 228/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2564 - accuracy: 0.8715 - val_loss: 0.2378 - val_accuracy: 0.8814\nEpoch 229/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2597 - accuracy: 0.8676 - val_loss: 0.2352 - val_accuracy: 0.8866\nEpoch 230/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2586 - accuracy: 0.8667 - val_loss: 0.2364 - val_accuracy: 0.8859\nEpoch 231/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2576 - accuracy: 0.8701 - val_loss: 0.2286 - val_accuracy: 0.8883\nEpoch 232/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2588 - accuracy: 0.8676 - val_loss: 0.2375 - val_accuracy: 0.8854\nEpoch 233/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2598 - accuracy: 0.8649 - val_loss: 0.2327 - val_accuracy: 0.8891\nEpoch 234/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2524 - accuracy: 0.8711 - val_loss: 0.2363 - val_accuracy: 0.8820\nEpoch 235/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2538 - accuracy: 0.8682 - val_loss: 0.2358 - val_accuracy: 0.8887\nEpoch 236/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2575 - accuracy: 0.8672 - val_loss: 0.2350 - val_accuracy: 0.8867\nEpoch 237/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2528 - accuracy: 0.8665 - val_loss: 0.2316 - val_accuracy: 0.8855\nEpoch 238/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2574 - accuracy: 0.8690 - val_loss: 0.2383 - val_accuracy: 0.8903\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 239/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2547 - accuracy: 0.8697 - val_loss: 0.2303 - val_accuracy: 0.8889\nEpoch 240/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2573 - accuracy: 0.8679 - val_loss: 0.2385 - val_accuracy: 0.8864\nEpoch 241/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2548 - accuracy: 0.8694 - val_loss: 0.2320 - val_accuracy: 0.8868\nEpoch 242/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2597 - accuracy: 0.8662 - val_loss: 0.2330 - val_accuracy: 0.8883\nEpoch 243/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2537 - accuracy: 0.8696 - val_loss: 0.2334 - val_accuracy: 0.8878\nEpoch 244/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2580 - accuracy: 0.8692 - val_loss: 0.2308 - val_accuracy: 0.8884\nEpoch 245/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2603 - accuracy: 0.8688 - val_loss: 0.2313 - val_accuracy: 0.8881\nEpoch 246/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2579 - accuracy: 0.8672 - val_loss: 0.2336 - val_accuracy: 0.8877\nEpoch 247/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2566 - accuracy: 0.8693 - val_loss: 0.2343 - val_accuracy: 0.8859\nEpoch 248/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2600 - accuracy: 0.8702 - val_loss: 0.2350 - val_accuracy: 0.8877\nEpoch 249/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2521 - accuracy: 0.8684 - val_loss: 0.2337 - val_accuracy: 0.8853\nEpoch 250/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2577 - accuracy: 0.8687 - val_loss: 0.2340 - val_accuracy: 0.8899\nEpoch 251/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2590 - accuracy: 0.8685 - val_loss: 0.2300 - val_accuracy: 0.8895\nEpoch 252/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2537 - accuracy: 0.8703 - val_loss: 0.2376 - val_accuracy: 0.8900\nEpoch 253/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2605 - accuracy: 0.8685 - val_loss: 0.2390 - val_accuracy: 0.8870\nEpoch 254/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2561 - accuracy: 0.8697 - val_loss: 0.2377 - val_accuracy: 0.8895\nEpoch 255/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2550 - accuracy: 0.8672 - val_loss: 0.2357 - val_accuracy: 0.8870\nEpoch 256/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2555 - accuracy: 0.8679 - val_loss: 0.2333 - val_accuracy: 0.8904\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 257/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2530 - accuracy: 0.8733 - val_loss: 0.2357 - val_accuracy: 0.8910\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 258/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2576 - accuracy: 0.8674 - val_loss: 0.2418 - val_accuracy: 0.8883\nEpoch 259/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2574 - accuracy: 0.8692 - val_loss: 0.2356 - val_accuracy: 0.8898\nEpoch 260/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2520 - accuracy: 0.8694 - val_loss: 0.2321 - val_accuracy: 0.8890\nEpoch 261/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2528 - accuracy: 0.8669 - val_loss: 0.2306 - val_accuracy: 0.8902\nEpoch 262/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2564 - accuracy: 0.8674 - val_loss: 0.2321 - val_accuracy: 0.8906\nEpoch 263/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2499 - accuracy: 0.8696 - val_loss: 0.2341 - val_accuracy: 0.8900\nEpoch 264/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2588 - accuracy: 0.8666 - val_loss: 0.2379 - val_accuracy: 0.8871\nEpoch 265/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2539 - accuracy: 0.8674 - val_loss: 0.2336 - val_accuracy: 0.8865\nEpoch 266/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2508 - accuracy: 0.8725 - val_loss: 0.2283 - val_accuracy: 0.8877\nEpoch 267/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2601 - accuracy: 0.8655 - val_loss: 0.2268 - val_accuracy: 0.8891\nEpoch 268/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2564 - accuracy: 0.8682 - val_loss: 0.2440 - val_accuracy: 0.8905\nEpoch 269/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2526 - accuracy: 0.8708 - val_loss: 0.2335 - val_accuracy: 0.8856\nEpoch 270/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2534 - accuracy: 0.8713 - val_loss: 0.2321 - val_accuracy: 0.8840\nEpoch 271/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2530 - accuracy: 0.8697 - val_loss: 0.2330 - val_accuracy: 0.8868\nEpoch 272/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2614 - accuracy: 0.8679 - val_loss: 0.2426 - val_accuracy: 0.8897\nEpoch 273/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2593 - accuracy: 0.8656 - val_loss: 0.2305 - val_accuracy: 0.8874\nEpoch 274/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2559 - accuracy: 0.8706 - val_loss: 0.2359 - val_accuracy: 0.8846\nEpoch 275/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2542 - accuracy: 0.8726 - val_loss: 0.2297 - val_accuracy: 0.8891\nEpoch 276/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2555 - accuracy: 0.8666 - val_loss: 0.2330 - val_accuracy: 0.8914\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 277/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2555 - accuracy: 0.8697 - val_loss: 0.2354 - val_accuracy: 0.8885\nEpoch 278/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2544 - accuracy: 0.8726 - val_loss: 0.2383 - val_accuracy: 0.8882\nEpoch 279/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2507 - accuracy: 0.8699 - val_loss: 0.2322 - val_accuracy: 0.8894\nEpoch 280/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2586 - accuracy: 0.8662 - val_loss: 0.2288 - val_accuracy: 0.8913\nEpoch 281/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2610 - accuracy: 0.8649 - val_loss: 0.2317 - val_accuracy: 0.8875\nEpoch 282/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2613 - accuracy: 0.8667 - val_loss: 0.2345 - val_accuracy: 0.8917\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 283/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2534 - accuracy: 0.8704 - val_loss: 0.2305 - val_accuracy: 0.8877\nEpoch 284/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2584 - accuracy: 0.8678 - val_loss: 0.2311 - val_accuracy: 0.8871\nEpoch 285/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2544 - accuracy: 0.8694 - val_loss: 0.2283 - val_accuracy: 0.8883\nEpoch 286/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2551 - accuracy: 0.8670 - val_loss: 0.2318 - val_accuracy: 0.8855\nEpoch 287/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2572 - accuracy: 0.8685 - val_loss: 0.2336 - val_accuracy: 0.8907\nEpoch 288/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2549 - accuracy: 0.8673 - val_loss: 0.2265 - val_accuracy: 0.8918\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 289/400\n1334/1334 [==============================] - 6s 5ms/step - loss: 0.2564 - accuracy: 0.8677 - val_loss: 0.2298 - val_accuracy: 0.8928\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 290/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2553 - accuracy: 0.8704 - val_loss: 0.2305 - val_accuracy: 0.8907\nEpoch 291/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2514 - accuracy: 0.8699 - val_loss: 0.2268 - val_accuracy: 0.8904\nEpoch 292/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2513 - accuracy: 0.8695 - val_loss: 0.2284 - val_accuracy: 0.8875\nEpoch 293/400\n1334/1334 [==============================] - 6s 5ms/step - loss: 0.2559 - accuracy: 0.8662 - val_loss: 0.2307 - val_accuracy: 0.8877\nEpoch 294/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2544 - accuracy: 0.8692 - val_loss: 0.2325 - val_accuracy: 0.8894\nEpoch 295/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2582 - accuracy: 0.8663 - val_loss: 0.2304 - val_accuracy: 0.8895\nEpoch 296/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2539 - accuracy: 0.8711 - val_loss: 0.2363 - val_accuracy: 0.8808\nEpoch 297/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2575 - accuracy: 0.8679 - val_loss: 0.2302 - val_accuracy: 0.8880\nEpoch 298/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2539 - accuracy: 0.8688 - val_loss: 0.2281 - val_accuracy: 0.8901\nEpoch 299/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2611 - accuracy: 0.8672 - val_loss: 0.2291 - val_accuracy: 0.8867\nEpoch 300/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2545 - accuracy: 0.8700 - val_loss: 0.2316 - val_accuracy: 0.8898\nEpoch 301/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2533 - accuracy: 0.8689 - val_loss: 0.2290 - val_accuracy: 0.8890\nEpoch 302/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2546 - accuracy: 0.8685 - val_loss: 0.2317 - val_accuracy: 0.8883\nEpoch 303/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2489 - accuracy: 0.8726 - val_loss: 0.2322 - val_accuracy: 0.8870\nEpoch 304/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2534 - accuracy: 0.8688 - val_loss: 0.2329 - val_accuracy: 0.8883\nEpoch 305/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2548 - accuracy: 0.8705 - val_loss: 0.2311 - val_accuracy: 0.8907\nEpoch 306/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2564 - accuracy: 0.8688 - val_loss: 0.2270 - val_accuracy: 0.8873\nEpoch 307/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2540 - accuracy: 0.8704 - val_loss: 0.2300 - val_accuracy: 0.8903\nEpoch 308/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2506 - accuracy: 0.8709 - val_loss: 0.2329 - val_accuracy: 0.8890\nEpoch 309/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2559 - accuracy: 0.8654 - val_loss: 0.2275 - val_accuracy: 0.8897\nEpoch 310/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2563 - accuracy: 0.8702 - val_loss: 0.2308 - val_accuracy: 0.8849\nEpoch 311/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2513 - accuracy: 0.8681 - val_loss: 0.2300 - val_accuracy: 0.8870\nEpoch 312/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2542 - accuracy: 0.8681 - val_loss: 0.2315 - val_accuracy: 0.8874\nEpoch 313/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2493 - accuracy: 0.8728 - val_loss: 0.2319 - val_accuracy: 0.8867\nEpoch 314/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2563 - accuracy: 0.8678 - val_loss: 0.2303 - val_accuracy: 0.8885\nEpoch 315/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2531 - accuracy: 0.8702 - val_loss: 0.2345 - val_accuracy: 0.8908\nEpoch 316/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2533 - accuracy: 0.8708 - val_loss: 0.2296 - val_accuracy: 0.8898\nEpoch 317/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2553 - accuracy: 0.8692 - val_loss: 0.2280 - val_accuracy: 0.8879\nEpoch 318/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2566 - accuracy: 0.8693 - val_loss: 0.2304 - val_accuracy: 0.8886\nEpoch 319/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2524 - accuracy: 0.8695 - val_loss: 0.2350 - val_accuracy: 0.8905\nEpoch 320/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2498 - accuracy: 0.8705 - val_loss: 0.2295 - val_accuracy: 0.8855\nEpoch 321/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2509 - accuracy: 0.8695 - val_loss: 0.2321 - val_accuracy: 0.8873\nEpoch 322/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2531 - accuracy: 0.8678 - val_loss: 0.2294 - val_accuracy: 0.8904\nEpoch 323/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2523 - accuracy: 0.8709 - val_loss: 0.2259 - val_accuracy: 0.8900\nEpoch 324/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2498 - accuracy: 0.8728 - val_loss: 0.2306 - val_accuracy: 0.8886\nEpoch 325/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2565 - accuracy: 0.8685 - val_loss: 0.2313 - val_accuracy: 0.8868\nEpoch 326/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2517 - accuracy: 0.8723 - val_loss: 0.2323 - val_accuracy: 0.8913\nEpoch 327/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2537 - accuracy: 0.8705 - val_loss: 0.2279 - val_accuracy: 0.8915\nEpoch 328/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2520 - accuracy: 0.8691 - val_loss: 0.2261 - val_accuracy: 0.8891\nEpoch 329/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2488 - accuracy: 0.8708 - val_loss: 0.2357 - val_accuracy: 0.8881\nEpoch 330/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2525 - accuracy: 0.8722 - val_loss: 0.2290 - val_accuracy: 0.8906\nEpoch 331/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2561 - accuracy: 0.8708 - val_loss: 0.2281 - val_accuracy: 0.8896\nEpoch 332/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2561 - accuracy: 0.8673 - val_loss: 0.2280 - val_accuracy: 0.8891\nEpoch 333/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2507 - accuracy: 0.8718 - val_loss: 0.2276 - val_accuracy: 0.8894\nEpoch 334/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2527 - accuracy: 0.8699 - val_loss: 0.2296 - val_accuracy: 0.8885\nEpoch 335/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2548 - accuracy: 0.8688 - val_loss: 0.2332 - val_accuracy: 0.8891\nEpoch 336/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2530 - accuracy: 0.8679 - val_loss: 0.2347 - val_accuracy: 0.8892\nEpoch 337/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2561 - accuracy: 0.8698 - val_loss: 0.2267 - val_accuracy: 0.8897\nEpoch 338/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2532 - accuracy: 0.8694 - val_loss: 0.2264 - val_accuracy: 0.8871\nEpoch 339/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2501 - accuracy: 0.8737 - val_loss: 0.2312 - val_accuracy: 0.8892\nEpoch 340/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2538 - accuracy: 0.8692 - val_loss: 0.2324 - val_accuracy: 0.8882\nEpoch 341/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2522 - accuracy: 0.8704 - val_loss: 0.2305 - val_accuracy: 0.8902\nEpoch 342/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2504 - accuracy: 0.8708 - val_loss: 0.2312 - val_accuracy: 0.8909\nEpoch 343/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2521 - accuracy: 0.8714 - val_loss: 0.2371 - val_accuracy: 0.8891\nEpoch 344/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2537 - accuracy: 0.8705 - val_loss: 0.2290 - val_accuracy: 0.8903\nEpoch 345/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2529 - accuracy: 0.8695 - val_loss: 0.2311 - val_accuracy: 0.8832\nEpoch 346/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2501 - accuracy: 0.8730 - val_loss: 0.2268 - val_accuracy: 0.8901\nEpoch 347/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2515 - accuracy: 0.8695 - val_loss: 0.2280 - val_accuracy: 0.8892\nEpoch 348/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2532 - accuracy: 0.8692 - val_loss: 0.2269 - val_accuracy: 0.8880\nEpoch 349/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2460 - accuracy: 0.8732 - val_loss: 0.2305 - val_accuracy: 0.8873\nEpoch 350/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2498 - accuracy: 0.8725 - val_loss: 0.2400 - val_accuracy: 0.8898\nEpoch 351/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2478 - accuracy: 0.8718 - val_loss: 0.2268 - val_accuracy: 0.8912\nEpoch 352/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2552 - accuracy: 0.8692 - val_loss: 0.2260 - val_accuracy: 0.8912\nEpoch 353/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2570 - accuracy: 0.8677 - val_loss: 0.2288 - val_accuracy: 0.8903\nEpoch 354/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2545 - accuracy: 0.8687 - val_loss: 0.2310 - val_accuracy: 0.8887\nEpoch 355/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2560 - accuracy: 0.8694 - val_loss: 0.2292 - val_accuracy: 0.8881\nEpoch 356/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2496 - accuracy: 0.8712 - val_loss: 0.2299 - val_accuracy: 0.8869\nEpoch 357/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2507 - accuracy: 0.8724 - val_loss: 0.2292 - val_accuracy: 0.8895\nEpoch 358/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2536 - accuracy: 0.8707 - val_loss: 0.2296 - val_accuracy: 0.8900\nEpoch 359/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2566 - accuracy: 0.8672 - val_loss: 0.2334 - val_accuracy: 0.8867\nEpoch 360/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2548 - accuracy: 0.8703 - val_loss: 0.2281 - val_accuracy: 0.8891\nEpoch 361/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2550 - accuracy: 0.8692 - val_loss: 0.2346 - val_accuracy: 0.8924\nEpoch 362/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2529 - accuracy: 0.8695 - val_loss: 0.2362 - val_accuracy: 0.8919\nEpoch 363/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2510 - accuracy: 0.8706 - val_loss: 0.2378 - val_accuracy: 0.8917\nEpoch 364/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2536 - accuracy: 0.8692 - val_loss: 0.2344 - val_accuracy: 0.8908\nEpoch 365/400\n1334/1334 [==============================] - 6s 5ms/step - loss: 0.2550 - accuracy: 0.8687 - val_loss: 0.2296 - val_accuracy: 0.8902\nEpoch 366/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2494 - accuracy: 0.8704 - val_loss: 0.2316 - val_accuracy: 0.8892\nEpoch 367/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2533 - accuracy: 0.8690 - val_loss: 0.2313 - val_accuracy: 0.8920\nEpoch 368/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2512 - accuracy: 0.8723 - val_loss: 0.2308 - val_accuracy: 0.8878\nEpoch 369/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2467 - accuracy: 0.8722 - val_loss: 0.2281 - val_accuracy: 0.8904\nEpoch 370/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2531 - accuracy: 0.8704 - val_loss: 0.2308 - val_accuracy: 0.8891\nEpoch 371/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2485 - accuracy: 0.8720 - val_loss: 0.2361 - val_accuracy: 0.8907\nEpoch 372/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2517 - accuracy: 0.8706 - val_loss: 0.2336 - val_accuracy: 0.8909\nEpoch 373/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2556 - accuracy: 0.8700 - val_loss: 0.2281 - val_accuracy: 0.8906\nEpoch 374/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2555 - accuracy: 0.8694 - val_loss: 0.2301 - val_accuracy: 0.8873\nEpoch 375/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2489 - accuracy: 0.8701 - val_loss: 0.2256 - val_accuracy: 0.8910\nEpoch 376/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2548 - accuracy: 0.8685 - val_loss: 0.2289 - val_accuracy: 0.8907\nEpoch 377/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2501 - accuracy: 0.8712 - val_loss: 0.2354 - val_accuracy: 0.8916\nEpoch 378/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2489 - accuracy: 0.8718 - val_loss: 0.2289 - val_accuracy: 0.8891\nEpoch 379/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2505 - accuracy: 0.8717 - val_loss: 0.2267 - val_accuracy: 0.8898\nEpoch 380/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2542 - accuracy: 0.8679 - val_loss: 0.2326 - val_accuracy: 0.8920\nEpoch 381/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2467 - accuracy: 0.8736 - val_loss: 0.2276 - val_accuracy: 0.8868\nEpoch 382/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2514 - accuracy: 0.8686 - val_loss: 0.2338 - val_accuracy: 0.8857\nEpoch 383/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2505 - accuracy: 0.8728 - val_loss: 0.2282 - val_accuracy: 0.8900\nEpoch 384/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2491 - accuracy: 0.8710 - val_loss: 0.2274 - val_accuracy: 0.8887\nEpoch 385/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2532 - accuracy: 0.8715 - val_loss: 0.2247 - val_accuracy: 0.8905\nEpoch 386/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2501 - accuracy: 0.8682 - val_loss: 0.2292 - val_accuracy: 0.8898\nEpoch 387/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2469 - accuracy: 0.8720 - val_loss: 0.2276 - val_accuracy: 0.8872\nEpoch 388/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2451 - accuracy: 0.8736 - val_loss: 0.2286 - val_accuracy: 0.8922\nEpoch 389/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2518 - accuracy: 0.8682 - val_loss: 0.2285 - val_accuracy: 0.8900\nEpoch 390/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2477 - accuracy: 0.8744 - val_loss: 0.2299 - val_accuracy: 0.8918\nEpoch 391/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2528 - accuracy: 0.8688 - val_loss: 0.2298 - val_accuracy: 0.8887\nEpoch 392/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2455 - accuracy: 0.8726 - val_loss: 0.2326 - val_accuracy: 0.8932\nINFO:tensorflow:Assets written to: BestModel/assets\nEpoch 393/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2462 - accuracy: 0.8722 - val_loss: 0.2382 - val_accuracy: 0.8912\nEpoch 394/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2513 - accuracy: 0.8724 - val_loss: 0.2305 - val_accuracy: 0.8888\nEpoch 395/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2484 - accuracy: 0.8717 - val_loss: 0.2274 - val_accuracy: 0.8877\nEpoch 396/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2468 - accuracy: 0.8742 - val_loss: 0.2271 - val_accuracy: 0.8905\nEpoch 397/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2517 - accuracy: 0.8702 - val_loss: 0.2273 - val_accuracy: 0.8890\nEpoch 398/400\n1334/1334 [==============================] - 5s 4ms/step - loss: 0.2487 - accuracy: 0.8712 - val_loss: 0.2307 - val_accuracy: 0.8899\nEpoch 399/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2482 - accuracy: 0.8737 - val_loss: 0.2302 - val_accuracy: 0.8896\nEpoch 400/400\n1334/1334 [==============================] - 6s 4ms/step - loss: 0.2454 - accuracy: 0.8718 - val_loss: 0.2272 - val_accuracy: 0.8894\nFold 1, 400 epochs, 2235 sec\n" ], [ "from keras.models import load_model\nX,y = prepare_inputs_len_x_alphabet(pc_test,nc_test,ALPHABET)\nbest_model=load_model(MODELPATH)\nscores = best_model.evaluate(X, y, verbose=0)\nprint(\"The best model parameters were saved during cross-validation.\")\nprint(\"Best was defined as maximum validation accuracy at end of any epoch.\")\nprint(\"Now re-load the best model and test it on previously unseen data.\")\nprint(\"Test on\",len(pc_test),\"PC seqs\")\nprint(\"Test on\",len(nc_test),\"NC seqs\")\nprint(\"%s: %.2f%%\" % (best_model.metrics_names[1], scores[1]*100))\n", "The best model parameters were saved during cross-validation.\nBest was defined as maximum validation accuracy at end of any epoch.\nNow re-load the best model and test it on previously unseen data.\nTest on 1000 PC seqs\nTest on 1000 NC seqs\naccuracy: 90.30%\n" ], [ "from sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\nns_probs = [0 for _ in range(len(y))]\nbm_probs = best_model.predict(X)\nns_auc = roc_auc_score(y, ns_probs)\nbm_auc = roc_auc_score(y, bm_probs)\nns_fpr, ns_tpr, _ = roc_curve(y, ns_probs)\nbm_fpr, bm_tpr, _ = roc_curve(y, bm_probs)\nplt.plot(ns_fpr, ns_tpr, linestyle='--', label='Guess, auc=%.4f'%ns_auc)\nplt.plot(bm_fpr, bm_tpr, marker='.', label='Model, auc=%.4f'%bm_auc)\nplt.title('ROC')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.legend()\nplt.show()\nprint(\"%s: %.2f%%\" %('AUC',bm_auc*100.0))\n", "_____no_output_____" ], [ "t = time.time()\ntime.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(t))", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc60a3d661503bfb8d4279cb2a229a92935ec9
1,460
ipynb
Jupyter Notebook
aoc_2021/day10.ipynb
ckuenzi/AoC
3dd243ec02b7f2dff42aa7c67e2dcddefb0fef64
[ "Unlicense" ]
2
2020-12-11T18:07:11.000Z
2020-12-11T18:08:04.000Z
aoc_2021/day10.ipynb
ckuenzi/AoC
3dd243ec02b7f2dff42aa7c67e2dcddefb0fef64
[ "Unlicense" ]
null
null
null
aoc_2021/day10.ipynb
ckuenzi/AoC
3dd243ec02b7f2dff42aa7c67e2dcddefb0fef64
[ "Unlicense" ]
null
null
null
22.8125
88
0.434932
[ [ [ "from functools import reduce\nmatch = {']':'[',')':'(','}':'{','>':'<'}\npoints = {'(': 1, '[':2, '{':3, '<':4, ')': 3, ']':57, '}':1197, '>':25137}\n\np1 = 0\np2 = []\nfor line in open('day10.txt').read().splitlines():\n to_close = []\n add_p2 = True\n for c in line:\n if c in match.values():\n to_close.append(c)\n elif match[c] == to_close[-1]:\n to_close.pop()\n else:\n p1 += points[c]\n break\n else:\n p2.append(reduce(lambda a,b: a * 5 + points[b], reversed(to_close), 0))\nprint(p1)\nprint(sorted(p2)[len(p2)//2])", "216297\n2165057169\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
ecfc77e11fa3d1ee9b68c7061a4a85b291b501f6
17,141
ipynb
Jupyter Notebook
intro-to-pytorch/Part 1 - Tensors in PyTorch (Solution).ipynb
r-keller/pytorch-udacity-fb
f45f51074106c554d7096138477ccca76f702211
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 1 - Tensors in PyTorch (Solution).ipynb
r-keller/pytorch-udacity-fb
f45f51074106c554d7096138477ccca76f702211
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 1 - Tensors in PyTorch (Solution).ipynb
r-keller/pytorch-udacity-fb
f45f51074106c554d7096138477ccca76f702211
[ "MIT" ]
null
null
null
38.605856
674
0.59874
[ [ [ "# Introduction to Deep Learning with PyTorch\n\nIn this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation!) and another module specifically for building neural networks. All together, PyTorch ends up being more coherent with Python and the Numpy/Scipy stack compared to TensorFlow and other frameworks.\n\n", "_____no_output_____" ], [ "## Neural Networks\n\nDeep Learning is based on artificial neural networks which have been around in some form since the late 1950s. The networks are built from individual parts approximating neurons, typically called units or simply \"neurons.\" Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit's output.\n\n<img src=\"assets/simple_neuron.png\" width=400px>\n\nMathematically this looks like: \n\n$$\n\\begin{align}\ny &= f(w_1 x_1 + w_2 x_2 + b) \\\\\ny &= f\\left(\\sum_i w_i x_i +b \\right)\n\\end{align}\n$$\n\nWith vectors this is the dot/inner product of two vectors:\n\n$$\nh = \\begin{bmatrix}\nx_1 \\, x_2 \\cdots x_n\n\\end{bmatrix}\n\\cdot \n\\begin{bmatrix}\n w_1 \\\\\n w_2 \\\\\n \\vdots \\\\\n w_n\n\\end{bmatrix}\n$$", "_____no_output_____" ], [ "## Tensors\n\nIt turns out neural network computations are just a bunch of linear algebra operations on *tensors*, a generalization of matrices. A vector is a 1-dimensional tensor, a matrix is a 2-dimensional tensor, an array with three indices is a 3-dimensional tensor (RGB color images for example). The fundamental data structure for neural networks are tensors and PyTorch (as well as pretty much every other deep learning framework) is built around tensors.\n\n<img src=\"assets/tensor_examples.svg\" width=600px>\n\nWith the basics covered, it's time to explore how we can use PyTorch to build a simple neural network.", "_____no_output_____" ] ], [ [ "# First, import PyTorch\nimport torch", "_____no_output_____" ], [ "def activation(x):\n \"\"\" Sigmoid activation function \n \n Arguments\n ---------\n x: torch.Tensor\n \"\"\"\n return 1/(1+torch.exp(-x))", "_____no_output_____" ], [ "### Generate some data\ntorch.manual_seed(7) # Set the random seed so things are predictable\n\n# Features are 3 random normal variables\nfeatures = torch.randn((1, 5))\n# True weights for our data, random normal variables again\nweights = torch.randn_like(features)\n# and a true bias term\nbias = torch.randn((1, 1))", "_____no_output_____" ] ], [ [ "Above I generated data we can use to get the output of our simple network. This is all just random for now, going forward we'll start using normal data. Going through each relevant line:\n\n`features = torch.randn((1, 5))` creates a tensor with shape `(1, 5)`, one row and five columns, that contains values randomly distributed according to the normal distribution with a mean of zero and standard deviation of one. \n\n`weights = torch.randn_like(features)` creates another tensor with the same shape as `features`, again containing values from a normal distribution.\n\nFinally, `bias = torch.randn((1, 1))` creates a single value from a normal distribution.\n\nPyTorch tensors can be added, multiplied, subtracted, etc, just like Numpy arrays. In general, you'll use PyTorch tensors pretty much the same way you'd use Numpy arrays. They come with some nice benefits though such as GPU acceleration which we'll get to later. For now, use the generated data to calculate the output of this simple single layer network. \n> **Exercise**: Calculate the output of the network with input features `features`, weights `weights`, and bias `bias`. Similar to Numpy, PyTorch has a [`torch.sum()`](https://pytorch.org/docs/stable/torch.html#torch.sum) function, as well as a `.sum()` method on tensors, for taking sums. Use the function `activation` defined above as the activation function.", "_____no_output_____" ] ], [ [ "### Solution\n\n# Now, make our labels from our data and true weights\n\ny = activation(torch.sum(features * weights) + bias)\ny = activation((features * weights).sum() + bias)", "_____no_output_____" ] ], [ [ ">> understand the implementation of torch matmul\nis mm ", "_____no_output_____" ], [ "You can do the multiplication and sum in the same operation using a matrix multiplication. In general, you'll want to use matrix multiplications since they are more efficient and accelerated using modern libraries and high-performance computing on GPUs.\n\nHere, we want to do a matrix multiplication of the features and the weights. For this we can use [`torch.mm()`](https://pytorch.org/docs/stable/torch.html#torch.mm) or [`torch.matmul()`](https://pytorch.org/docs/stable/torch.html#torch.matmul) which is somewhat more complicated and supports broadcasting. If we try to do it with `features` and `weights` as they are, we'll get an error\n\n```python\n>> torch.mm(features, weights)\n\n---------------------------------------------------------------------------\nRuntimeError Traceback (most recent call last)\n<ipython-input-13-15d592eb5279> in <module>()\n----> 1 torch.mm(features, weights)\n\nRuntimeError: size mismatch, m1: [1 x 5], m2: [1 x 5] at /Users/soumith/minicondabuild3/conda-bld/pytorch_1524590658547/work/aten/src/TH/generic/THTensorMath.c:2033\n```\n\nAs you're building neural networks in any framework, you'll see this often. Really often. What's happening here is our tensors aren't the correct shapes to perform a matrix multiplication. Remember that for matrix multiplications, the number of columns in the first tensor must equal to the number of rows in the second column. Both `features` and `weights` have the same shape, `(1, 5)`. This means we need to change the shape of `weights` to get the matrix multiplication to work.\n\n**Note: To see the shape of a tensor called `tensor`, use `tensor.shape`. If you're building neural networks, you'll be using this method often.**\n\nThere are a few options here: [`weights.reshape()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.reshape), [`weights.resize_()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.resize_), and [`weights.view()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.view).\n\n* `weights.reshape(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)` sometimes, and sometimes a clone, **as in it copies the data to another part of memory.**\n* `weights.resize_(a, b)`**possibly truncates** returns the same tensor with a different shape. However, if the new shape results in fewer elements than the original tensor, some elements will be removed from the tensor (but not from memory). If the new shape results in more elements than the original tensor, new elements will be uninitialized in memory. Here I should note that the underscore at the end of the method denotes that this method is performed **in-place**. Here is a great forum thread to [read more about in-place operations](https://discuss.pytorch.org/t/what-is-in-place-operation/16244) in PyTorch.\n* `weights.view(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)`.\n\nI usually use `.view()`, but any of the three methods will work for this. So, now we can reshape `weights` to have five rows and one column with something like `weights.view(5, 1)`.\n\n> **Exercise**: Calculate the output of our little network using matrix multiplication.", "_____no_output_____" ] ], [ [ "## Solution\n\ny = activation(torch.mm(features, weights.view(5,1)) + bias)", "_____no_output_____" ] ], [ [ "### Stack them up!\n\nThat's how you can calculate the output for a single neuron. The real power of this algorithm happens when you start stacking these individual units into layers and stacks of layers, into a network of neurons. The output of one layer of neurons becomes the input for the next layer. With multiple input units and output units, we now need to express the weights as a matrix.\n\n<img src='assets/multilayer_diagram_weights.png' width=450px>\n\nThe first layer shown on the bottom here are the inputs, understandably called the **input layer**. The middle layer is called the **hidden layer**, and the final layer (on the right) is the **output layer**. We can express this network mathematically with matrices again and use matrix multiplication to get linear combinations for each unit in one operation. For example, the hidden layer ($h_1$ and $h_2$ here) can be calculated \n\n$$\n\\vec{h} = [h_1 \\, h_2] = \n\\begin{bmatrix}\nx_1 \\, x_2 \\cdots \\, x_n\n\\end{bmatrix}\n\\cdot \n\\begin{bmatrix}\n w_{11} & w_{12} \\\\\n w_{21} &w_{22} \\\\\n \\vdots &\\vdots \\\\\n w_{n1} &w_{n2}\n\\end{bmatrix}\n$$\n\nThe output for this small network is found by treating the hidden layer as inputs for the output unit. The network output is expressed simply\n\n$$\ny = f_2 \\! \\left(\\, f_1 \\! \\left(\\vec{x} \\, \\mathbf{W_1}\\right) \\mathbf{W_2} \\right)\n$$", "_____no_output_____" ] ], [ [ "### Generate some data\ntorch.manual_seed(7) # Set the random seed so things are predictable\n\n# Features are 3 random normal variables\nfeatures = torch.randn((1, 3))\n\n# Define the size of each layer in our network\nn_input = features.shape[1] # Number of input units, must match number of input features\nn_hidden = 2 # Number of hidden units \nn_output = 1 # Number of output units\n\n# Weights for inputs to hidden layer\nW1 = torch.randn(n_input, n_hidden)\n# Weights for hidden layer to output layer\nW2 = torch.randn(n_hidden, n_output)\n\n# and bias terms for hidden and output layers\nB1 = torch.randn((1, n_hidden))\nB2 = torch.randn((1, n_output))", "_____no_output_____" ] ], [ [ "> **Exercise:** Calculate the output for this multi-layer network using the weights `W1` & `W2`, and the biases, `B1` & `B2`. ", "_____no_output_____" ] ], [ [ "### Solution\n\nh = activation(torch.mm(features, W1) + B1)\noutput = activation(torch.mm(h, W2) + B2)\nprint(output)", "tensor([[0.3171]])\n" ] ], [ [ "If you did this correctly, you should see the output `tensor([[ 0.3171]])`.\n\nThe number of hidden units a parameter of the network, often called a **hyperparameter** to differentiate it from the weights and biases parameters. As you'll see later when we discuss training a neural network, the more hidden units a network has, and the more layers, the better able it is to learn from data and make accurate predictions.", "_____no_output_____" ], [ "## Numpy to Torch and back\n\nSpecial bonus section! PyTorch has a great feature for converting between Numpy arrays and Torch tensors. To create a tensor from a Numpy array, use `torch.from_numpy()`. To convert a tensor to a Numpy array, use the `.numpy()` method.", "_____no_output_____" ] ], [ [ "import numpy as np\na = np.random.rand(4,3)\na", "_____no_output_____" ], [ "b = torch.from_numpy(a)\nb", "_____no_output_____" ], [ "b.numpy()", "_____no_output_____" ] ], [ [ "The memory is shared between the Numpy array and Torch tensor, so if you change the values in-place of one object, the other will change as well.", "_____no_output_____" ] ], [ [ "# Multiply PyTorch Tensor by 2, in place\nb.mul_(2)", "_____no_output_____" ], [ "# Numpy array matches new values from Tensor\na", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ecfc83cd6e9bca53a7f2f85a0a2f5ae1efe9ea81
4,037
ipynb
Jupyter Notebook
tasks/isolation-forest-clustering/Deployment.ipynb
platiagro/tasks
a6103cb101eeed26381cdb170a11d0e1dc53d3ad
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
2
2021-02-16T12:39:57.000Z
2021-07-21T11:36:39.000Z
tasks/isolation-forest-clustering/Deployment.ipynb
platiagro/tasks
a6103cb101eeed26381cdb170a11d0e1dc53d3ad
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
20
2020-10-26T18:05:27.000Z
2021-11-30T19:05:22.000Z
tasks/isolation-forest-clustering/Deployment.ipynb
platiagro/tasks
a6103cb101eeed26381cdb170a11d0e1dc53d3ad
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
7
2020-10-13T18:12:22.000Z
2021-08-13T19:16:21.000Z
35.725664
276
0.577409
[ [ [ "# Agrupamento Isolation Forest - Implantação\n\nEste é um componente que treina um modelo Isolation Forest usando [Scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html). <br>\nScikit-learn é uma biblioteca open source de machine learning que suporta apredizado supervisionado e não supervisionado. Também provê várias ferramentas para montagem de modelo, pré-processamento de dados, seleção e avaliação de modelos, e muitos outros utilitários.\n\nEste notebook apresenta:\n- como carregar modelos e outros resultados do treinamento.\n- como utilizar um modelo para fornecer predições em tempo real.", "_____no_output_____" ], [ "## Declaração de Classe para Predições em Tempo Real\n\nA tarefa de implantação cria um serviço REST para predições em tempo real.<br>\nPara isso você deve criar uma classe `Model` que implementa o método `predict`.", "_____no_output_____" ] ], [ [ "%%writefile Model.py\nimport logging\nfrom typing import List, Iterable, Dict, Union\n\nimport joblib\nimport numpy as np\nimport pandas as pd\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model(object):\n def __init__(self):\n self.loaded = False\n\n def load(self):\n # Following links explain why to use load() method insted of __init__()\n\n # Issue associated with seldon on __init__\n # https://github.com/SeldonIO/seldon-core/issues/2616\n\n # Solution for the case\n # https://docs.seldon.io/projects/seldon-core/en/latest/python/python_component.html#gunicorn-and-load\n # Carrega artefatos: estimador, etc\n artifacts = joblib.load(\"/tmp/data/isolation-forest-clustering.joblib\")\n self.pipeline = artifacts[\"pipeline\"]\n self.columns = artifacts[\"columns\"]\n self.columns_to_filter = artifacts[\"columns_to_filter\"]\n self.new_columns = artifacts[\"new_columns\"]\n self.features_after_pipeline = artifacts[\"features_after_pipeline\"]\n self.loaded = True\n\n\n def class_names(self):\n column_names = np.concatenate((self.columns_to_filter,self.new_columns))\n return column_names.tolist()\n\n def predict(self, X, feature_names, meta=None):\n # First time load model\n if not self.loaded:\n self.load()\n \n df = pd.DataFrame(X)\n \n if feature_names:\n # Antes de utilizar o conjunto de dados X no modelo, reordena suas features de acordo com a ordem utilizada no treinamento\n df = pd.DataFrame(X, columns=feature_names)\n df = df[self.columns_to_filter]\n \n # Realiza classificação \n y_pred = self.pipeline.predict(df)\n \n # Adicionando classificação ao banco de dados \n df[self.new_columns[0]] = y_pred\n\n return df.to_numpy()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ] ]
ecfc8ee0bc3fe51824a5e668d59589379d356a0d
139,946
ipynb
Jupyter Notebook
riddler538_2020_May22/python/puzzle-solution.ipynb
tjburch/puzzles
b48294a852af7f29457a5c429c794fa7eef559e2
[ "MIT" ]
3
2020-07-28T15:30:03.000Z
2020-08-30T21:50:56.000Z
riddler538_2020_May22/python/puzzle-solution.ipynb
tjburch/puzzles
b48294a852af7f29457a5c429c794fa7eef559e2
[ "MIT" ]
null
null
null
riddler538_2020_May22/python/puzzle-solution.ipynb
tjburch/puzzles
b48294a852af7f29457a5c429c794fa7eef559e2
[ "MIT" ]
null
null
null
120.125322
48,360
0.841217
[ [ [ "# Riddler Classic - May 22, 2020\n\nhttps://fivethirtyeight.com/features/somethings-fishy-in-the-state-of-the-riddler/\n\nOhio is the only state whose name doesn’t share any letters with the word “mackerel.” It’s strange, but it’s true.\n\nBut that isn’t the only pairing of a state and a word you can say that about — it’s not even the only fish! Kentucky has “goldfish” to itself, Montana has “jellyfish” and Delaware has “monkfish,” just to name a few.\n\nWhat is the longest “mackerel?” That is, what is the longest word that doesn’t share any letters with exactly one state? (If multiple “mackerels” are tied for being the longest, can you find them all?)\n\nExtra credit: Which state has the most “mackerels?” That is, which state has the most words for which it is the only state without any letters in common with those words?", "_____no_output_____" ], [ "### Load data", "_____no_output_____" ] ], [ [ "import pickle\nwordlist = pickle.load(open(\"../data/word-list.pkl\",\"rb\"))\nwordlist = [w.decode(\"utf-8\") for w in wordlist]\nstatelist = pickle.load(open(\"../data/state-list.pkl\",\"rb\"))\nstatelist = [state.lower() for state in statelist]", "_____no_output_____" ], [ "print(f\"There are {len(wordlist)} total words\")\nprint(f\"There are {len(statelist)} total states\")", "There are 263533 total words\nThere are 50 total states\n" ] ], [ [ "### Do some quick dataset checks", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nplt.style.use(\"tjb\")\nimport numpy as np", "\nBad key \"axes.color_cycle\" on line 26 in\n/Users/tburch/.matplotlib/stylelib/tjb.mplstyle.\nYou probably need to get an updated matplotlibrc file from\nhttp://github.com/matplotlib/matplotlib/blob/master/matplotlibrc.template\nor from the matplotlib source distribution\n" ], [ "mylen = np.vectorize(len)\nlongest = wordlist[np.argmax(mylen(wordlist))]\nprint(f\"The longest word is {longest}\")\nlength_sorted_words = list(reversed([x for _,x in sorted(zip(mylen(wordlist),wordlist))]))\nprint(f\"The 5 longest words are {length_sorted_words[0:5]} of lengths {[len(x) for x in length_sorted_words[0:5]]}\")", "The longest word is pneumonoultramicroscopicsilicovolcanoconiosis\nThe 5 longest words are ['pneumonoultramicroscopicsilicovolcanoconiosis', 'dichlorodiphenyltrichloroethanes', 'dichlorodiphenyltrichloroethane', 'floccinaucinihilipilifications', 'floccinaucinihilipilification'] of lengths [45, 32, 31, 30, 29]\n" ] ], [ [ "#### Important quantity is not necessarily word legnth, but number of unique characters in each word\n\nWill help with computation time and problem context, so look at those", "_____no_output_____" ] ], [ [ "# Get Alphabetically sorted unique letters\nset_length_sorted_words = { w : \"\".join(sorted(set(w))) for w in length_sorted_words}\nunique_substrings = list(set(set_length_sorted_words.values()))", "_____no_output_____" ], [ "print(f\"There are {len(unique_substrings)} unique substrings\")", "There are 101137 unique substrings\n" ], [ "length_sorted_unique_substrings = list(reversed([x for _,x in sorted(zip(mylen(unique_substrings),unique_substrings))]))", "_____no_output_____" ], [ "print(length_sorted_unique_substrings[0])\nprint(length_sorted_unique_substrings[1])\n", "abcdehilmnoprsty\nceghilmnoprstuy\n" ], [ "for key, v in set_length_sorted_words.items():\n if v == length_sorted_unique_substrings[0]: \n print(f\"The most unique characters are {key}, with {len(key)} unique characters\")", "The most unique characters are phenylthiocarbamides, with 20 unique characters\n" ], [ "fig, ax_enum = plt.subplots(1,2, figsize=(15,5))\nplt.sca(ax_enum[0])\nword_lengths = mylen(wordlist)\nplt.hist(word_lengths, bins=np.arange(min(word_lengths), max(word_lengths)), alpha=0.8)\nplt.ylabel(\"Count\",fontsize=16)\nplt.xlabel(\"Word Length\",fontsize=16)\nplt.tick_params(labelsize=12)\n\nplt.sca(ax_enum[1])\nunique_char_counts = mylen(length_sorted_unique_substrings)\nplt.hist(unique_char_counts, bins=np.arange(min(unique_char_counts), max(unique_char_counts)),\n color=\"#DB7093\", alpha=0.8)\nplt.xlabel(\"Unique Characters\",fontsize=16)\nplt.tick_params(labelsize=12)\n\n\n\nplt.savefig(\"../plots/count_distribution\",bbox_inches=\"tight\")", "_____no_output_____" ], [ "print(\"--- Mean ---\")\nprint(f\"All: {np.mean(word_lengths):.2f}\")\nprint(f\"Unique: {np.mean(unique_char_counts):.2f}\")\n\nprint(\"--- Median ---\")\nprint(f\"All: {np.median(word_lengths):.2f}\")\nprint(f\"Unique: {np.median(unique_char_counts):.2f}\")\n\nprint(\"--- Standard Deviation ---\")\nprint(f\"All: {np.std(word_lengths):.2f}\")\nprint(f\"Unique: {np.std(unique_char_counts):.2f}\")", "--- Mean ---\nAll: 9.31\nUnique: 7.71\n--- Median ---\nAll: 9.00\nUnique: 8.00\n--- Standard Deviation ---\nAll: 2.84\nUnique: 1.91\n" ] ], [ [ "### Define checking function", "_____no_output_____" ] ], [ [ "def check_word_against_states(word):\n \"\"\" Checks word against all states to see if it passes the question criteria, sharing letters with exactly one\n word (str) : word to evaluate\n returns (str) : None if fails criteria, the one orthogonally spelled state if meets criteria\n \n Note : This could be sped up if we only looked at unique characters, but it's not slow as-is.\n \"\"\"\n word = word.lower()\n theword = None\n thestate = None\n unshared_char_states = 0\n for state in statelist:\n state= state.lower()\n i = set(state)\n j = set(word)\n matching = i&j\n if len(matching) == 0:\n unshared_char_states += 1\n theword = word\n thestate = state\n if unshared_char_states > 1:\n return None\n if unshared_char_states == 1:\n return thestate\n else:\n return None", "_____no_output_____" ], [ "# Test\ndef test_checking_function(word):\n state = check_word_against_states(word)\n if state is None:\n print(f\"{word} failed\")\n else:\n print(f\"Word: {word} State: {state}\")\n \nprint(\"-----Should Pass-----\")\ntest_checking_function(\"monkfish\")\ntest_checking_function(\"jellyfish\")\ntest_checking_function(\"mackerel\")\ntest_checking_function(\"unwatched\")\ntest_checking_function(\"elephant\")\ntest_checking_function(\"james\")\n\nprint(\"-----Should Fail-----\")\ntest_checking_function(\"tyler\")\ntest_checking_function(\"physics\")\ntest_checking_function(\"four\")", "-----Should Pass-----\nWord: monkfish State: delaware\nWord: jellyfish State: montana\nWord: mackerel State: ohio\nWord: unwatched State: mississippi\nWord: elephant State: missouri\nWord: james State: ohio\n-----Should Fail-----\ntyler failed\nphysics failed\nfour failed\n" ] ], [ [ "### Run solution\n\nWe'll start with the longest word and continue down the sorted list until we find the length of the longest word that meets the criteria", "_____no_output_____" ] ], [ [ "%%time\nfor word in length_sorted_words:\n state = check_word_against_states(word)\n if state is not None:\n print(f\"Word: {word} State: {state}\")\n print(f\"length of longest word {len(word)} \")\n maximum_matching_length = len(word)\n break", "Word: hydrochlorofluorocarbon State: mississippi\nlength of longest word 23 \nCPU times: user 7.3 ms, sys: 1.96 ms, total: 9.26 ms\nWall time: 13.6 ms\n" ] ], [ [ "Next, we need to find all the words of the same length that meet the criteria", "_____no_output_____" ] ], [ [ "correct_length_words = np.array(wordlist)[mylen(wordlist) == maximum_matching_length]\nfor word in correct_length_words:\n state = check_word_against_states(word)\n if state is not None:\n print(f\"Word: {word} State: {state}\")", "Word: counterproductivenesses State: alabama\nWord: hydrochlorofluorocarbon State: mississippi\n" ] ], [ [ "### Solution:\n\nThere are **2** words of length **23** who don't share letters with _exactly_ one state. The two words are:\n\n- **counterproductivenesses** which doesn't share letters with **Alabama**\n- **hydrochlorofluorocarbon** which doesn't share letters with **Mississippi**", "_____no_output_____" ], [ "## Exhaustive solution\n\nSince the computation time is working well, how many words of each length meet the solution criteria?", "_____no_output_____" ] ], [ [ "%%time\nlen_match_criteria = []\nsuccessful_words = []\nstate_list = []\nfor word in length_sorted_words:\n state = check_word_against_states(word)\n if state is not None:\n len_match_criteria.append(len(word))\n successful_words.append(word)\n state_list.append(state)", "CPU times: user 17 s, sys: 125 ms, total: 17.1 s\nWall time: 17.6 s\n" ], [ "plt.figure(figsize=(10,5))\nplt.hist(len_match_criteria, bins=np.arange(min(len_match_criteria), max(len_match_criteria)), color=\"firebrick\", alpha=0.8)\nplt.ylabel(\"Count\",fontsize=16)\nplt.xlabel(\"Word Length (Meet Criteria)\",fontsize=16)\nplt.xticks(np.arange(0,25,5))\nplt.tick_params(labelsize=12)\nplt.savefig(\"../plots/passing_distribution\",bbox_inches=\"tight\")", "_____no_output_____" ], [ "print(\"--- Count ---\")\nprint(f\"All: {len(word_lengths)}\")\nprint(f\"Passing: {len(len_match_criteria)}\")\n\nprint(\"--- Mean ---\")\nprint(f\"All: {np.mean(word_lengths):.2f}\")\nprint(f\"Passing: {np.mean(len_match_criteria):.2f}\")\n\nprint(\"--- Median ---\")\nprint(f\"All: {np.median(word_lengths):.2f}\")\nprint(f\"Passing: {np.median(len_match_criteria):.2f}\")\n\nprint(\"--- Standard Deviation ---\")\nprint(f\"All: {np.std(word_lengths):.2f}\")\nprint(f\"Passing: {np.std(len_match_criteria):.2f}\")", "--- Count ---\nAll: 263533\nPassing: 45385\n--- Mean ---\nAll: 9.31\nPassing: 9.37\n--- Median ---\nAll: 9.00\nPassing: 9.00\n--- Standard Deviation ---\nAll: 2.84\nPassing: 2.33\n" ] ], [ [ "## Extra Credit\n\nExtra credit: Which state has the most “mackerels?” That is, which state has the most words for which it is the only state without any letters in common with those words?", "_____no_output_____" ] ], [ [ "import pandas as pd\nstate_list_cap = [s.title() for s in state_list]\ndf = pd.DataFrame({'states': state_list_cap})\ndf['num'] = 1 # placeholder for summing\ndf = df.groupby('states').sum().sort_values('num', ascending=False)\n\nplt.figure(figsize=(14,7))\nplt.bar(df.index, df.num, width=0.5, color='forestgreen', alpha=0.8)\n#plt.hist(state_list, bins=np.arange(min(len_match_criteria), max(len_match_criteria)), color=\"forestgreen\", alpha=0.8)\nplt.ylabel(\"\\\"Mackerel\\\" Count\",fontsize=16)\nplt.xticks(rotation=75, fontsize=12)\nplt.tick_params(labelsize=12)\nplt.savefig(\"../plots/states_distribution\",bbox_inches=\"tight\")", "_____no_output_____" ] ], [ [ "### Full list\n\nJust to check the raw counts", "_____no_output_____" ] ], [ [ "df", "_____no_output_____" ] ], [ [ "### Plot number of unique characters in a state v number of \"mackerels\"", "_____no_output_____" ] ], [ [ "df[\"lower_state\"] = df.index.str.lower()\ndf[\"unique_chars\"] = df[\"lower_state\"].apply(list).apply(set).apply(len)", "_____no_output_____" ], [ "plt.figure(figsize=(10,5))\nplt.scatter(df[\"unique_chars\"], df[\"num\"])\ncorrelation = np.corrcoef(df[\"unique_chars\"], df[\"num\"])[0,1]\nplt.annotate(f\"Correlation {correlation:.3f}\", xy=(0.95,0.9), xycoords=\"axes fraction\", ha=\"right\", fontsize=16)\n\nplt.xlabel(\"Unique Characters in State Name\",fontsize=16)\nplt.ylabel(\"Number of \\\"Mackerels\\\"\",fontsize=16)\nplt.tick_params(labelsize=14)\nplt.savefig(\"../plots/scatter_state\",bbox_inches=\"tight\")", "_____no_output_____" ], [ "df", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
ecfc9235d6b1f98c83b709d406ccbb3e4eb89717
22,638
ipynb
Jupyter Notebook
src/Chapter-2/07-mini_project_minist.ipynb
TaehoLi/Basic-Pytorch
547d1171ca80870756ee4b2fe65e0d5dd61b7f34
[ "MIT" ]
null
null
null
src/Chapter-2/07-mini_project_minist.ipynb
TaehoLi/Basic-Pytorch
547d1171ca80870756ee4b2fe65e0d5dd61b7f34
[ "MIT" ]
null
null
null
src/Chapter-2/07-mini_project_minist.ipynb
TaehoLi/Basic-Pytorch
547d1171ca80870756ee4b2fe65e0d5dd61b7f34
[ "MIT" ]
null
null
null
46.2
4,540
0.638396
[ [ [ "# Mini-Project: 나만의 딥러닝 모델로 Mnist Dataset 학습하기\n\n> 2.2.8 장에 해당하는 코드", "_____no_output_____" ], [ "## 패키기 불러오기 및 GUI 프로그램 작성", "_____no_output_____" ] ], [ [ "# 코드 2-22\n\nimport os\n# matplotlib 패키지 결과물을 노트북을 실행한 브라우저 안에 보일 수 있도록 하는 명령어다. \n%matplotlib inline\n# numpy 와 pytorch 패키지 불러오기 \nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n# 데이터로더 및 mnist 가 내장 되어있는 torchvision 패키지에서 데이터셋 불러오기\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\n\n# 손글씨를 써볼 수 있는 GUI 프로그램\nfrom drawing import Drawing\n# 그림 시각화 처리를 위한 패키지\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\ndef drawing_custom_number(preprocess, filepath=\"./figs\", return_img=True):\n \"\"\"손글씨 입력 GUI 미니 프로그램\"\"\"\n if (not os.path.isdir(\"figs\")) and (filepath == \"./figs\"):\n os.mkdir(\"figs\")\n draw = Drawing()\n draw.main(preprocess=preprocess, filepath=filepath)\n img = Image.open(draw.file)\n plt.imshow(img, cmap=\"gray\")\n plt.show()\n if return_img:\n return img", "_____no_output_____" ] ], [ [ "## 데이터 살펴보기", "_____no_output_____" ] ], [ [ "# 코드 2-23\n\ntorch.manual_seed(70)\n\n# 데이터셋 정의하기\ntrain_dataset = datasets.MNIST(root='./data', # 데이터 경로\n train=True, # 훈련데이터의 여부\n download=True, # 기존에 없다면 root 경로에 다운로드를 받게 된다.\n transform=transforms.ToTensor()) # 텐서로 바꾸는 전처리를 한다.\ntest_dataset = datasets.MNIST(root='./data', # 데이터 경로\n train=False, # 훈련데이터의 여부\n transform=transforms.ToTensor()) # 텐서로 바꾸는 전처리를 한다.\n\n# 데이터 살펴보기: 훈련데이터 중 임의의 데이터를 골라서 보여준다\nidx = torch.randint(0, len(train_dataset), (1,)).item()\nrandom_image = train_dataset[idx][0].squeeze().numpy()\ntarget_num = train_dataset[idx][1]\nprint(\"Target: {}\".format(target_num))\nprint(\"Size of Image: {}\".format(random_image.shape))\nplt.imshow(random_image, cmap=\"gray\")\nplt.axis(\"off\")\nplt.show()", "Target: 0\nSize of Image: (28, 28)\n" ], [ "# 코드 2-24\n\n# 미니배치크기\nBATCH = 64\n# 디바이스 설정: cuda 사용할지 cpu 사용할지\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\n# 총 스텝 크기\nSTEP = 10\n\n# 훈련 데이터로더 선언\ntrain_loader = DataLoader(dataset=train_dataset, \n batch_size=BATCH, \n shuffle=True)\n# 테스트 데이터 로더 설정\ntest_loader = DataLoader(dataset=test_dataset, \n batch_size=BATCH, \n shuffle=True)", "_____no_output_____" ], [ "for (data, target) in train_loader:\n print(data.size(), target.size())\n break", "torch.Size([64, 1, 28, 28]) torch.Size([64])\n" ], [ "# 코드 2-30\n\nclass Net(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(Net, self).__init__()\n self.flatten = lambda x: x.view(x.size(0), -1)\n self.linear1 = nn.Linear(input_size, hidden_size)\n self.linear2 = nn.Linear(hidden_size, hidden_size)\n self.linear3 = nn.Linear(hidden_size, output_size)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n x = self.flatten(x)\n x = self.linear1(x)\n x = self.relu(x)\n x = self.linear2(x)\n x = self.relu(x)\n x = self.linear3(x)\n return x", "_____no_output_____" ], [ "# 코드 2-25\n\n# 모델 선언\nmodel = Net(input_size=28*28, hidden_size=100, output_size=10).to(DEVICE)", "_____no_output_____" ], [ "# 코드 2-26\n\n# 손실함수와 옵티마이저 선언\nloss_function = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters())\n\n# 매개변수 개수 확인하기\nnum_params = 0\nfor params in model.parameters():\n num_params += params.view(-1).size(0)\nprint(\"Total number of parameters: {}\".format(num_params))", "Total number of parameters: 89610\n" ], [ "# 코드 2-27\n\ndef train(model, train_loader, loss_func, optimizer, step, device, print_step=200):\n \"\"\"train function: 1 스텝 동안 발생하는 학습과정\"\"\"\n # 모델에게 훈련단계이라고 선언함\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n # 입력과 타겟 텐서에 GPU 를 사용여부 전달\n data, target = data.to(device), target.to(device)\n # 경사 초기화\n model.zero_grad()\n # 순방향 전파\n output = model(data)\n # 손실값 계산\n loss = loss_func(output, target)\n # 역방향 전파\n loss.backward()\n # 매개변수 업데이트\n optimizer.step()\n # 중간 과정 print\n if batch_idx % print_step == 0:\n print('Train Step: {} ({:05.2f}%) \\tLoss: {:.4f}'.format(\n step, 100.*(batch_idx*train_loader.batch_size)/len(train_loader.dataset), \n loss.item()))\n \ndef test(model, test_loader, loss_func, device):\n \"\"\"test function\"\"\"\n # 모델에게 평가단계이라고 선언함\n model.eval()\n test_loss = 0\n correct = 0\n\n with torch.no_grad():\n for data, target in test_loader:\n # 입력과 타겟 텐서에 GPU 를 사용여부 전달\n data, target = data.to(device), target.to(device)\n # 순방향전파\n output = model(data)\n # 손실값 계산(합)\n test_loss += loss_func(output, target, reduction=\"sum\").item()\n # 예측 값에 해당하는 클래스 번호 반환\n pred = output.softmax(1).argmax(dim=1, keepdim=True)\n # 정확하게 예측한 개수를 기록한다\n correct += pred.eq(target.view_as(pred)).sum().item()\n \n test_loss /= len(test_loader.dataset)\n test_acc = correct / len(test_loader.dataset)\n print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:05.2f}%)'.format(\n test_loss, correct, len(test_loader.dataset), 100. * test_acc))\n return test_loss, test_acc\n\ndef main(model, train_loader, test_loader, loss_func, optimizer, n_step, device, save_path=None, print_step=200):\n \"\"\"메인 학습 함수\"\"\"\n test_accs = []\n best_acc = 0.0\n\n for step in range(1, n_step+1):\n # 훈련 단계\n train(model, train_loader, loss_func, optimizer, \n step=step, device=device, print_step=print_step)\n # 평가 단계\n test_loss, test_acc = test(model, test_loader, \n loss_func=F.cross_entropy, \n device=device)\n # 테스트 정확도 기록\n test_accs.append(test_acc)\n # 모델 최적의 매개변수값을 저장할지 결정하고 기록한다.\n if len(test_accs) >= 2:\n if test_acc >= best_acc:\n best_acc = test_acc\n best_state_dict = model.state_dict()\n print(\"discard previous state, best model state saved!\")\n print(\"\")\n\n # 매개변수 값 저장하기\n if save_path is not None:\n torch.save(best_state_dict, save_path)", "_____no_output_____" ], [ "# 코드 2-28\n\nmain(model=model, \n train_loader=train_loader, \n test_loader=test_loader, \n loss_func=loss_function, \n optimizer=optimizer, \n n_step=STEP,\n device=DEVICE,\n save_path=\"mnist_model.pt\", \n print_step=200)", "Train Step: 1 (00.00%) \tLoss: 2.3176\nTrain Step: 1 (21.33%) \tLoss: 0.2704\nTrain Step: 1 (42.67%) \tLoss: 0.3944\nTrain Step: 1 (64.00%) \tLoss: 0.1376\nTrain Step: 1 (85.33%) \tLoss: 0.2473\nTest set: Average loss: 0.1566, Accuracy: 9543/10000 (95.43%)\n\nTrain Step: 2 (00.00%) \tLoss: 0.2037\nTrain Step: 2 (21.33%) \tLoss: 0.1473\nTrain Step: 2 (42.67%) \tLoss: 0.1313\nTrain Step: 2 (64.00%) \tLoss: 0.1170\nTrain Step: 2 (85.33%) \tLoss: 0.0972\nTest set: Average loss: 0.1198, Accuracy: 9610/10000 (96.10%)\ndiscard previous state, best model state saved!\n\nTrain Step: 3 (00.00%) \tLoss: 0.0749\nTrain Step: 3 (21.33%) \tLoss: 0.1048\nTrain Step: 3 (42.67%) \tLoss: 0.0381\nTrain Step: 3 (64.00%) \tLoss: 0.0404\nTrain Step: 3 (85.33%) \tLoss: 0.0462\nTest set: Average loss: 0.1066, Accuracy: 9662/10000 (96.62%)\ndiscard previous state, best model state saved!\n\nTrain Step: 4 (00.00%) \tLoss: 0.0631\nTrain Step: 4 (21.33%) \tLoss: 0.0844\nTrain Step: 4 (42.67%) \tLoss: 0.0425\nTrain Step: 4 (64.00%) \tLoss: 0.0341\nTrain Step: 4 (85.33%) \tLoss: 0.0798\nTest set: Average loss: 0.0888, Accuracy: 9721/10000 (97.21%)\ndiscard previous state, best model state saved!\n\nTrain Step: 5 (00.00%) \tLoss: 0.0155\nTrain Step: 5 (21.33%) \tLoss: 0.1525\nTrain Step: 5 (42.67%) \tLoss: 0.0196\nTrain Step: 5 (64.00%) \tLoss: 0.0421\nTrain Step: 5 (85.33%) \tLoss: 0.0361\nTest set: Average loss: 0.0906, Accuracy: 9718/10000 (97.18%)\n\nTrain Step: 6 (00.00%) \tLoss: 0.0214\nTrain Step: 6 (21.33%) \tLoss: 0.0265\nTrain Step: 6 (42.67%) \tLoss: 0.0912\nTrain Step: 6 (64.00%) \tLoss: 0.0678\nTrain Step: 6 (85.33%) \tLoss: 0.0150\nTest set: Average loss: 0.0797, Accuracy: 9767/10000 (97.67%)\ndiscard previous state, best model state saved!\n\nTrain Step: 7 (00.00%) \tLoss: 0.0510\nTrain Step: 7 (21.33%) \tLoss: 0.0306\nTrain Step: 7 (42.67%) \tLoss: 0.0495\nTrain Step: 7 (64.00%) \tLoss: 0.0219\nTrain Step: 7 (85.33%) \tLoss: 0.0104\nTest set: Average loss: 0.0896, Accuracy: 9742/10000 (97.42%)\n\nTrain Step: 8 (00.00%) \tLoss: 0.0198\nTrain Step: 8 (21.33%) \tLoss: 0.0558\nTrain Step: 8 (42.67%) \tLoss: 0.0046\nTrain Step: 8 (64.00%) \tLoss: 0.0162\nTrain Step: 8 (85.33%) \tLoss: 0.0485\nTest set: Average loss: 0.0845, Accuracy: 9755/10000 (97.55%)\n\nTrain Step: 9 (00.00%) \tLoss: 0.0835\nTrain Step: 9 (21.33%) \tLoss: 0.0571\nTrain Step: 9 (42.67%) \tLoss: 0.0281\nTrain Step: 9 (64.00%) \tLoss: 0.0133\nTrain Step: 9 (85.33%) \tLoss: 0.1205\nTest set: Average loss: 0.0839, Accuracy: 9761/10000 (97.61%)\n\nTrain Step: 10 (00.00%) \tLoss: 0.0048\nTrain Step: 10 (21.33%) \tLoss: 0.0023\nTrain Step: 10 (42.67%) \tLoss: 0.0027\nTrain Step: 10 (64.00%) \tLoss: 0.0094\nTrain Step: 10 (85.33%) \tLoss: 0.0429\nTest set: Average loss: 0.0909, Accuracy: 9765/10000 (97.65%)\n\n" ], [ "# 만약에 해당 프로그램이 계속 실행안되고 재시작을 한다면 ssh 접속시\n# $ ssh -Y [host 이름]\n# 으로 실행해주시면 됩니다.\nimg = drawing_custom_number(preprocess=True, return_img=True)", "file saved ./figs/img.png\n" ], [ "# 코드 2-29\n\n# 내가 그린 이미지 테스트\n# 이미지를 (1, 28, 28) 크기의 텐서로 바꿔준다\ntest_input = torch.Tensor(np.array(img)).unsqueeze(0).to(DEVICE)\npred = model(test_input)\nprint(\"Predicted number is {}.\".format(pred.softmax(1).argmax().item()))", "Predicted number is 7.\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfc94abcc60d8994cd8b6667881c278182dfbc3
68,673
ipynb
Jupyter Notebook
python/two_phase_1D_fipy_seq.ipynb
simulkade/peteng
470baf49db56e8e4055fac5a14d7272cf333a6a6
[ "MIT" ]
2
2020-04-25T20:11:24.000Z
2021-06-09T07:27:38.000Z
python/two_phase_1D_fipy_seq.ipynb
simulkade/peteng
470baf49db56e8e4055fac5a14d7272cf333a6a6
[ "MIT" ]
null
null
null
python/two_phase_1D_fipy_seq.ipynb
simulkade/peteng
470baf49db56e8e4055fac5a14d7272cf333a6a6
[ "MIT" ]
4
2017-09-03T09:00:17.000Z
2020-09-07T21:51:41.000Z
143.367432
14,168
0.822812
[ [ [ "## FiPy 1D two-phase flow in porous mediaq, 11 October, 2019\nDifferent approaches:\n * Coupled\n * Sequential\n * ...", "_____no_output_____" ] ], [ [ "from fipy import Grid2D, CellVariable, FaceVariable\nimport numpy as np\n\n\ndef upwindValues(mesh, field, velocity):\n \"\"\"Calculate the upwind face values for a field variable\n\n Note that the mesh.faceNormals point from `id1` to `id2` so if velocity is in the same\n direction as the `faceNormal`s then we take the value from `id1`s and visa-versa.\n\n Args:\n mesh: a fipy mesh\n field: a fipy cell variable or equivalent numpy array\n velocity: a fipy face variable (rank 1) or equivalent numpy array\n \n Returns:\n numpy array shaped as a fipy face variable\n \"\"\"\n # direction is over faces (rank 0)\n direction = np.sum(np.array(mesh.faceNormals * velocity), axis=0)\n # id1, id2 are shaped as faces but contains cell index values\n id1, id2 = mesh._adjacentCellIDs\n return np.where(direction >= 0, field[id1], field[id2])\n\n\n# mesh = Grid2D(nx=3, ny=3)\n# print(\n# upwindValues(\n# mesh,\n# np.arange(mesh.numberOfCells),\n# 2 * np.random.random(size=(2, mesh.numberOfFaces)) - 1\n# )\n# )\n", "_____no_output_____" ], [ "from fipy import *\n\n# relperm parameters\nswc = 0.0\nsor = 0.0\nkrw0 = 0.3\nkro0 = 1.0\nnw = 2.0\nno = 2.0\n\n# domain and boundaries\nk = 1e-12 # m^2\nphi = 0.4\nu = 1.e-5\np0 = 100e5 # Pa\nLx = 100.\nLy = 10.\nnx = 100\nny = 10\ndx = Lx/nx\ndy = Ly/ny\n\n# fluid properties\nmuo = 0.002\nmuw = 0.001\n\n# define the fractional flow functions\ndef krw(sw):\n res = krw0*((sw-swc)/(1-swc-sor))**nw\n return res\n\ndef dkrw(sw):\n res = krw0*nw/(1-swc-sor)*((sw-swc)/(1-swc-sor))**(nw-1)\n return res\n\n\ndef kro(sw):\n res = kro0*((1-sw-sor)/(1-swc-sor))**no\n return res\n\ndef dkro(sw):\n res = -kro0*no/(1-swc-sor)*((1-sw-sor)/(1-swc-sor))**(no-1)\n return res\n\ndef fw(sw):\n res = krw(sw)/muw/(krw(sw)/muw+kro(sw)/muo)\n return res\n\ndef dfw(sw):\n res = (dkrw(sw)/muw*kro(sw)/muo-krw(sw)/muw*dkro(sw)/muo)/(krw(sw)/muw+kro(sw)/muo)**2\n return res\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nsw_plot = np.linspace(swc, 1-sor, 50)", "_____no_output_____" ] ], [ [ "## Visualize the relative permeability and fractional flow curves", "_____no_output_____" ] ], [ [ "krw_plot = [krw(sw) for sw in sw_plot]\nkro_plot = [kro(sw) for sw in sw_plot]\nfw_plot = [fw(sw) for sw in sw_plot]\n\nplt.figure(1)\nplt.plot(sw_plot, krw_plot, sw_plot, kro_plot)\nplt.show()\n\nplt.figure(2)\nplt.plot(sw_plot, fw_plot)\nplt.show()", "_____no_output_____" ], [ "# create the grid\nmesh = Grid1D(dx = Lx/nx, nx = nx)\nx = mesh.cellCenters\n\n# create the cell variables and boundary conditions\nsw = CellVariable(mesh=mesh, name=\"saturation\", hasOld=True, value = swc)\np = CellVariable(mesh=mesh, name=\"pressure\", hasOld=True, value = p0)\n# sw.setValue(1-sor,where = x<=dx)\n\nsw.constrain(1.0,mesh.facesLeft)\n#sw.constrain(0., mesh.facesRight)\nsw.faceGrad.constrain([0], mesh.facesRight)\np.faceGrad.constrain([-u/(krw(1-sor)*k/muw)], mesh.facesLeft)\np.constrain(p0, mesh.facesRight)\n# p.constrain(3.0*p0, mesh.facesLeft)\nu/(krw(1-sor)*k/muw)", "_____no_output_____" ] ], [ [ "## Equations\n$$\\nabla.\\left(\\left(-\\frac{k_{rw} k}{\\mu_w}-\\frac{k_{ro} k}{\\mu_o} \\right)\\nabla p \\right)=0$$ or\n$$\\varphi \\frac{\\partial S_w}{\\partial t}+\\nabla.\\left(-\\frac{k_{rw} k}{\\mu_w} \\nabla p \\right)=0$$", "_____no_output_____" ] ], [ [ "# eq_p = DiffusionTerm(var=p, coeff=-k*(krw(sw.faceValue)/muw+kro(sw.faceValue)/muo))- \\\n# UpwindConvectionTerm(var=sw, coeff=-k*(dkrw(sw.faceValue)/muw+dkro(sw.faceValue)/muo)*p.faceGrad)- \\\n# (k*(dkrw(sw.faceValue)/muw+dkro(sw.faceValue)/muo)*sw.faceValue*p.faceGrad).divergence == 0\n\n# eq_sw = TransientTerm(coeff=phi, var=sw) + \\\n# DiffusionTerm(var=p, coeff=-k*krw(sw.faceValue)/muw)+ \\\n# UpwindConvectionTerm(var=sw, coeff=-k*dkrw(sw.faceValue)/muw*p.faceGrad)- \\\n# (-k*dkrw(sw.faceValue)/muw*p.faceGrad*sw.faceValue).divergence == 0\n\neq_p = DiffusionTerm(var=p, coeff=-k*(krw(sw.faceValue)/muw+kro(sw.faceValue)/muo)) == 0\n\neq_sw = TransientTerm(coeff=phi, var=sw) + \\\n(-k*krw(sw.faceValue)/muw*p.faceGrad).divergence == 0\n\nsw_face = sw.faceValue\n\n# eq = eq_p & eq_sw\nsteps = 100\ndt0 = 5000.\ndt = dt0\nt_end = steps*dt0\nt = 0.0\nviewer = Viewer(vars = sw, datamax=1.1, datamin=-0.1)\nwhile t<t_end:\n eq_p.solve(var=p)\n eq_sw.solve(var=sw, dt=dt0)\n sw.value[sw.value>1-sor]=1-sor\n sw.value[sw.value<swc]=swc\n p.updateOld()\n sw.updateOld()\n u_w = -k*krw(sw_face)/muw*p.faceGrad\n sw_face = FaceVariable(mesh, upwindValues(mesh, sw, u_w))\n sw_face.value[0] = 1.0\n eq_p = DiffusionTerm(var=p, coeff=-k*(krw(sw_face)/muw+kro(sw_face)/muo)) == 0\n eq_sw = TransientTerm(coeff=phi, var=sw) + (-k*krw(sw_face)/muw*p.faceGrad).divergence == 0\n t=t+dt0\n \n# Note: try to use the Appleyard method; the overflow is a result of wrong rel-perm values \nviewer.plot()", "_____no_output_____" ], [ "sw_face.value[0] =1.0\nsw_face.value", "_____no_output_____" ], [ "0.5>1-0.6", "_____no_output_____" ], [ "upwindValues(mesh, sw, u_w)", "_____no_output_____" ] ], [ [ "## Analytical solution", "_____no_output_____" ] ], [ [ "import fractional_flow as ff\nxt_shock, sw_shock, xt_prf, sw_prf, t, p_inj, R_oil = ff.frac_flow_wf(muw=muw, muo=muo, ut=u, phi=1.0, \\\n k=1e-12, swc=swc, sor=sor, kro0=kro0, no=no, krw0=krw0, \\\n nw=nw, sw0=swc, sw_inj=1.0, L=Lx, pv_inj=5.0)", "/home/ali/projects/peteng/python/relative_permeability.py:39: RuntimeWarning: invalid value encountered in true_divide\n +((sw<swc) | (sw>=1.0))*0.0\n" ], [ "plt.figure()\nplt.plot(xt_prf, sw_prf)\nplt.plot(x.value.squeeze()/(steps*dt), sw.value)\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ecfc98626be6cd7e32e53ba1fd5ccf26c5fefe42
125,882
ipynb
Jupyter Notebook
docs/tutorial/Getting_started.ipynb
EVBiotechBV/biosteam
c31c5998c6f6a52f9e06daba0ddc73bdee78a07a
[ "MIT" ]
null
null
null
docs/tutorial/Getting_started.ipynb
EVBiotechBV/biosteam
c31c5998c6f6a52f9e06daba0ddc73bdee78a07a
[ "MIT" ]
null
null
null
docs/tutorial/Getting_started.ipynb
EVBiotechBV/biosteam
c31c5998c6f6a52f9e06daba0ddc73bdee78a07a
[ "MIT" ]
null
null
null
102.509772
52,608
0.82687
[ [ [ "# Getting started", "_____no_output_____" ], [ "### Initialize streams", "_____no_output_____" ], [ "[Stream](https://thermosteam.readthedocs.io/en/latest/Stream.html) objects define material flow rates along with its thermodynamic state. Before creating streams, a [Thermo](https://thermosteam.readthedocs.io/en/latest/Thermo.html) property package must be defined. Alternatively, we can just pass chemical names and BioSTEAM will automatically create a property package based on ideal mixing rules and UNIFAC activity coefficients for thermodynamic equilibrium. More complex packages can be defined through Thermosteam, BioSTEAM's premier thermodynamic engine. Please visit [Thermosteam's documentation](https://thermosteam.readthedocs.io/en/latest/index.html) for a complete tutorial on [Stream](https://thermosteam.readthedocs.io/en/latest/Stream.html) objects and how to create a property package. In this example, a simple feed stream with a few common chemicals will be initialized:", "_____no_output_____" ] ], [ [ "import biosteam as bst\nbst.settings.set_thermo(['Water', 'Methanol'])\nfeed = bst.Stream(Water=50, Methanol=20)\nfeed.show()", "Stream: s1\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Water 50\n Methanol 20\n" ] ], [ [ "Set prices for performing techno-economic analysis later:", "_____no_output_____" ] ], [ [ "feed.price = 0.15 # USD/kg\nfeed.cost # USD/hr", "_____no_output_____" ] ], [ [ "### Process settings", "_____no_output_____" ], [ "Process settings include price of feeds and products, conditions of utilities, and the chemical engineering plant cost index. These should be set before simulating a system.", "_____no_output_____" ], [ "Set the chemical engineering plant cost index:", "_____no_output_____" ] ], [ [ "bst.CE # Default year is 2017", "_____no_output_____" ], [ "bst.CE = 603.1 # To year 2018", "_____no_output_____" ] ], [ [ "Set [PowerUtility](../PowerUtility.txt) options:", "_____no_output_____" ] ], [ [ "bst.PowerUtility.price # Default price (USD/kJ)", "_____no_output_____" ], [ "bst.PowerUtility.price = 0.065 # Adjust price", "_____no_output_____" ] ], [ [ "Set [HeatUtility](../HeatUtility.txt) options via [UtilityAgent](../UtilityAgent.txt) objects, which are [Stream](https://thermosteam.readthedocs.io/en/latest/Stream.html) objects with additional attributes to describe a utility agent:", "_____no_output_____" ] ], [ [ "bst.HeatUtility.cooling_agents # All available cooling agents", "_____no_output_____" ], [ "cooling_water = bst.HeatUtility.get_cooling_agent('cooling_water')\ncooling_water.show() # A UtilityAgent", "UtilityAgent: cooling_water\n heat_transfer_efficiency: 1.000\n heat_transfer_price: 0 USD/kJ\n regeneration_price: 0.000488 USD/kmol\n T_limit: 325 K\n phase: 'l'\n T: 305.37 K\n P: 101325 Pa\n flow (kmol/hr): Water 1\n" ], [ "# Price of regenerating the utility in USD/kmol\ncooling_water.regeneration_price", "_____no_output_____" ], [ "# Other utilities may be priced for amount of heat transfered in USD/kJ\nchilled_water = bst.HeatUtility.get_cooling_agent('chilled_water')\nchilled_water.heat_transfer_price", "_____no_output_____" ], [ "cooling_water.T = 302 # Change the temperature of cooling water (K)", "_____no_output_____" ], [ "bst.HeatUtility.heating_agents # All available heating agents", "_____no_output_____" ], [ "lps = bst.HeatUtility.get_heating_agent('low_pressure_steam') # A UtilityAgent\nlps.show() # Note that because utility changes phase, T_limit is None", "UtilityAgent: low_pressure_steam\n heat_transfer_efficiency: 0.950\n heat_transfer_price: 0 USD/kJ\n regeneration_price: 0.238 USD/kmol\n T_limit: None\n phase: 'g'\n T: 412.19 K\n P: 344738 Pa\n flow (kmol/hr): Water 1\n" ], [ "lps.regeneration_price = 0.20 # Adjust price (USD/kmol)", "_____no_output_____" ] ], [ [ "### Find design requirements and cost with Unit objects", "_____no_output_____" ], [ "[Creating a Unit](./Creating_a_Unit.ipynb) can be flexible. But in summary, a [Unit](../Unit.txt) object is initialized with an ID, and unit-specific arguments. BioSTEAM includes [essential unit operations](../units/units.txt) with rigorous modeling and design algorithms. Here we create a [Flash](../units/Flash.txt) object as an example:", "_____no_output_____" ] ], [ [ "from biosteam import units\n\n# Specify vapor fraction and isobaric conditions\nF1 = units.Flash('F1', V=0.5, P=101325)\nF1.show()", "Flash: F1\nins...\n[0] missing stream\nouts...\n[0] s2\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow: 0\n[1] s3\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow: 0\n" ] ], [ [ "Note that, by default, Missing Stream objects are given to inputs, `ins`, and empty streams to outputs, `outs`:", "_____no_output_____" ] ], [ [ "F1.ins", "_____no_output_____" ], [ "F1.outs", "_____no_output_____" ] ], [ [ "You can connect streams by setting the `ins` and `outs`:", "_____no_output_____" ] ], [ [ "F1.ins[0] = feed\nF1.show()", "Flash: F1\nins...\n[0] s1\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Water 50\n Methanol 20\nouts...\n[0] s2\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow: 0\n[1] s3\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow: 0\n" ] ], [ [ "To simulate the flash, use the `simulate` method:", "_____no_output_____" ] ], [ [ "F1.simulate()\nF1.show()", "Flash: F1\nins...\n[0] s1\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Water 50\n Methanol 20\nouts...\n[0] s2\n phase: 'g', T: 359.63 K, P: 101325 Pa\n flow (kmol/hr): Water 19\n Methanol 16\n[1] s3\n phase: 'l', T: 359.63 K, P: 101325 Pa\n flow (kmol/hr): Water 31\n Methanol 4\n" ] ], [ [ "Note that warnings notify you whether purchase cost correlations are out of range for the given design. This is ok for the example, but its important to make sure that the process is well designed and cost correlations are suitable for the domain.", "_____no_output_____" ], [ "The `results` method returns simulation results:", "_____no_output_____" ] ], [ [ "F1.results() # Default returns DataFrame object with units", "_____no_output_____" ], [ "F1.results(with_units=False) # Returns Series object without units", "_____no_output_____" ] ], [ [ "Although BioSTEAM includes a large set of essential unit operations, many process specific unit operations are not yet available. In this case, you can create new [Unit subclasses](./Inheriting_from_Unit.ipynb) to model unit operations not yet available in BioSTEAM.", "_____no_output_____" ], [ "### Solve recycle loops and process specifications with System objects", "_____no_output_____" ], [ "Designing a chemical process is no easy task. A simple recycle process consisting of a flash with a partial liquid recycle is presented here.", "_____no_output_____" ], [ "Create a [Mixer](../units/mixing.txt) object and a [Splitter](../units/splitting.txt) object:", "_____no_output_____" ] ], [ [ "M1 = units.Mixer('M1')\nS1 = units.Splitter('S1', outs=('liquid_recycle', 'liquid_product'),\n split=0.5) # Split to 0th output stream\nF1.outs[0].ID = 'vapor_product'\nF1.outs[1].ID = 'liquid'", "_____no_output_____" ] ], [ [ "You can [find unit operations and manage flowsheets](./Managing_flowsheets.ipynb) with the `main_flowsheet`:", "_____no_output_____" ] ], [ [ "bst.main_flowsheet.diagram()", "_____no_output_____" ] ], [ [ "Connect streams and make a recycle loop using [-pipe- notation](./-pipe-_notation.ipynb):", "_____no_output_____" ] ], [ [ "feed = bst.Stream('feed', Methanol=100, Water=450)\n\n# Broken down -pipe- notation\n[S1-0, feed]-M1 # M1.ins[:] = [S1.outs[0], feed]\nM1-F1 # F1.ins[:] = M1.outs\nF1-1-S1 # S1.ins[:] = [F1.outs[1]]\n\n# All together\n[S1-0, feed]-M1-F1-1-S1;", "_____no_output_____" ] ], [ [ "Now lets check the diagram again:", "_____no_output_____" ] ], [ [ "bst.main_flowsheet.diagram(format='png')", "_____no_output_____" ] ], [ [ "[System](../System.txt) objects take care of solving recycle loops and simulating all unit operations.\nAlthough there are many ways of [creating a system](./Creating_a_system.ipynb), the most recommended way is to use the flowsheet:", "_____no_output_____" ] ], [ [ "flowsheet_sys = bst.main_flowsheet.create_system('flowsheet_sys')\nflowsheet_sys.show()", "System: flowsheet_sys\nHighest convergence error among components in recycle\nstream S1-0 after 0 loops:\n- flow rate 0.00e+00 kmol/hr (0%)\n- temperature 0.00e+00 K (0%)\nins...\n[0] feed\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Water 450\n Methanol 100\nouts...\n[0] vapor_product\n phase: 'g', T: 359.63 K, P: 101325 Pa\n flow (kmol/hr): Water 19\n Methanol 16\n[1] liquid_product\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow: 0\n" ] ], [ [ "Although not recommened due to the likelyhood of human error, a [System](../System.txt) object may also be created by specifying an ID, a `recycle` stream and a `path` of units to run element by element:", "_____no_output_____" ] ], [ [ "sys = bst.System('sys', path=(M1, F1, S1), recycle=S1-0) # recycle=S1.outs[0]\nsys.show()", "System: sys\nHighest convergence error among components in recycle\nstream S1-0 after 0 loops:\n- flow rate 0.00e+00 kmol/hr (0%)\n- temperature 0.00e+00 K (0%)\nins...\n[0] feed\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Water 450\n Methanol 100\nouts...\n[0] vapor_product\n phase: 'g', T: 359.63 K, P: 101325 Pa\n flow (kmol/hr): Water 19\n Methanol 16\n[1] liquid_product\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow: 0\n" ] ], [ [ "Simulate the System object:", "_____no_output_____" ] ], [ [ "sys.simulate()\nsys.show()", "System: sys\nHighest convergence error among components in recycle\nstream S1-0 after 4 loops:\n- flow rate 1.38e-01 kmol/hr (0.16%)\n- temperature 4.43e-03 K (0.0012%)\nins...\n[0] feed\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Water 450\n Methanol 100\nouts...\n[0] vapor_product\n phase: 'g', T: 366.37 K, P: 101325 Pa\n flow (kmol/hr): Water 275\n Methanol 92.1\n[1] liquid_product\n phase: 'l', T: 366.37 K, P: 101325 Pa\n flow (kmol/hr): Water 175\n Methanol 7.9\n" ] ], [ [ "Note how the recycle stream converged and all unit operations (including the flash vessel) were simulated:", "_____no_output_____" ] ], [ [ "F1.results()", "_____no_output_____" ] ], [ [ "You can retrieve summarized power and heat utilities from the system as well:", "_____no_output_____" ] ], [ [ "sys.power_utility.show()", "PowerUtility:\n consumption: 0 kW\n production: 0 kW\n rate: 0 kW\n cost: 0 USD/hr\n" ], [ "for i in sys.heat_utilities: i.show()", "HeatUtility: low_pressure_steam\n duty: 1.82e+07 kJ/hr\n flow: 470 kmol/hr\n cost: 94 USD/hr\n" ] ], [ [ "Once your system has been simulated, you can save a system report to view all results in an excel spreadsheet:", "_____no_output_____" ] ], [ [ "# Try this on your computer and open excel\n# sys.save_report('Example.xlsx') ", "_____no_output_____" ] ], [ [ "Note that the cash flow analysis did not appear in the report because it requires a [TEA](../TEA.txt) object with all the necessary parameters (e.g., depreciation schedule, plant lifetime, construction schedule) to perform the analysis. A [TEA](../TEA.txt) object may also solve for economic indicators such as internal rate of return, minimum product selling price (MPSP), and maximum feedstock purchase price (MFPP). [Techno-economic analysis](./Techno-economic_analysis.ipynb) is discussed in detail later in the tutorial due to the extensive nature of the cash flow analysis.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecfca3a885e86b4f79120e9c46e29f57d7f9447f
207,663
ipynb
Jupyter Notebook
Untitled.ipynb
microamp/pitchfork-analysis
3e3930940837bb24a22bac9d475f77109b5fad8e
[ "Apache-2.0" ]
null
null
null
Untitled.ipynb
microamp/pitchfork-analysis
3e3930940837bb24a22bac9d475f77109b5fad8e
[ "Apache-2.0" ]
null
null
null
Untitled.ipynb
microamp/pitchfork-analysis
3e3930940837bb24a22bac9d475f77109b5fad8e
[ "Apache-2.0" ]
null
null
null
128.98323
78,758
0.815528
[ [ [ "from pyspark.sql import SQLContext\nfrom pyspark.sql import functions as sqlfns\nfrom pyspark.sql import types as sqltypes\n\nsqlContext = SQLContext(sc)", "_____no_output_____" ], [ "# Read a directory of JSON files using Spark SQL DataFrame\n\nimport os\n\npath = \"%s/src/github.com/microamp/pitchfork-dl/reviews\" % os.environ.get(\"GOPATH\")\nreviews = sqlContext.read.json(path)", "_____no_output_____" ], [ "# Check schema\n\nreviews.printSchema()", "root\n |-- albums: array (nullable = true)\n | |-- element: struct (containsNull = true)\n | | |-- artists: array (nullable = true)\n | | | |-- element: string (containsNull = true)\n | | |-- labels: array (nullable = true)\n | | | |-- element: string (containsNull = true)\n | | |-- score: string (nullable = true)\n | | |-- title: string (nullable = true)\n | | |-- year: string (nullable = true)\n |-- article: string (nullable = true)\n |-- authors: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- genres: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- id: string (nullable = true)\n\n" ], [ "# Show the first 5 rows\n\nreviews.select(\"id\", \"authors\", \"genres\").show(5)", "+--------------------+------------------+--------------------+\n| id| authors| genres|\n+--------------------+------------------+--------------------+\n| 22044-dangerous| [Jeff Weiss]| [Pop/R&B]|\n|19860-sleater-kin...| [Jenn Pelly]| [Rock]|\n|16108-throbbing-g...| [Drew Daniel]|[Rock, Experiment...|\n| 22045-mamas-gun|[Daphne A. Brooks]| [Pop/R&B]|\n|17269-the-studio-...| [Jessica Hopper]| [Rock]|\n+--------------------+------------------+--------------------+\nonly showing top 5 rows\n\n" ], [ "# Without data truncated\n\nreviews.select(\"id\", \"albums\", \"authors\", \"genres\", \n sqlfns.substring(sqlfns.col(\"article\"), 0, 20).alias(\"article_starts_with\")).\\\n first()", "_____no_output_____" ], [ "# List pyspark functions\n\nlist(filter(lambda attr: not attr.startswith(\"_\"), dir(sqlfns)))", "_____no_output_____" ], [ "# List reviews with multiple albums\n\nwith_multiple_albums = reviews.filter(sqlfns.size(sqlfns.col(\"albums\")) > 1)\nwith_multiple_albums.cache()\n\n\"Reviews with multiple albums: %d\" % with_multiple_albums.count()", "_____no_output_____" ], [ "# Check how many albums in total are included in reviews with multiple albums\n\nhelp(with_multiple_albums.withColumn)\n\nwith_multiple_albums.withColumn(\"album_count\", sqlfns.size(\"albums\")).\\\n select(sqlfns.sum(\"album_count\")).show()", "Help on method withColumn in module pyspark.sql.dataframe:\n\nwithColumn(colName, col) method of pyspark.sql.dataframe.DataFrame instance\n Returns a new :class:`DataFrame` by adding a column or replacing the\n existing column that has the same name.\n \n :param colName: string, name of the new column.\n :param col: a :class:`Column` expression for the new column.\n \n >>> df.withColumn('age2', df.age + 2).collect()\n [Row(age=2, name='Alice', age2=4), Row(age=5, name='Bob', age2=7)]\n \n .. versionadded:: 1.3\n\n+----------------+\n|sum(album_count)|\n+----------------+\n| 1280|\n+----------------+\n\n" ], [ "# Each review to have only one album using `explode`\n\nhelp(sqlfns.explode)\n\nwith_single_album = with_multiple_albums.withColumn(\"album\", sqlfns.explode(\"albums\"))\nwith_single_album.cache()\n\nwith_single_album.printSchema()\n\n\"%d multi-album reviews expanded to %d single-album reviews\" % (with_multiple_albums.count(), \n with_single_album.count(),)", "Help on function explode in module pyspark.sql.functions:\n\nexplode(col)\n Returns a new row for each element in the given array or map.\n \n >>> from pyspark.sql import Row\n >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={\"a\": \"b\"})])\n >>> eDF.select(explode(eDF.intlist).alias(\"anInt\")).collect()\n [Row(anInt=1), Row(anInt=2), Row(anInt=3)]\n \n >>> eDF.select(explode(eDF.mapfield).alias(\"key\", \"value\")).show()\n +---+-----+\n |key|value|\n +---+-----+\n | a| b|\n +---+-----+\n \n .. versionadded:: 1.4\n\nroot\n |-- albums: array (nullable = true)\n | |-- element: struct (containsNull = true)\n | | |-- artists: array (nullable = true)\n | | | |-- element: string (containsNull = true)\n | | |-- labels: array (nullable = true)\n | | | |-- element: string (containsNull = true)\n | | |-- score: string (nullable = true)\n | | |-- title: string (nullable = true)\n | | |-- year: string (nullable = true)\n |-- article: string (nullable = true)\n |-- authors: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- genres: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- id: string (nullable = true)\n |-- album: struct (nullable = true)\n | |-- artists: array (nullable = true)\n | | |-- element: string (containsNull = true)\n | |-- labels: array (nullable = true)\n | | |-- element: string (containsNull = true)\n | |-- score: string (nullable = true)\n | |-- title: string (nullable = true)\n | |-- year: string (nullable = true)\n\n" ], [ "# Apply the technique above to all reviews, with or without multiple albums\n\nalbum_reviews = reviews.withColumn(\"album\", sqlfns.explode(\"albums\")).drop(\"albums\")\nalbum_reviews.cache()\n\nalbum_reviews.printSchema()\n\n\"%d single/multi-album reviews expanded to %d single-album reviews\" % (reviews.count(),\n album_reviews.count(),)", "root\n |-- article: string (nullable = true)\n |-- authors: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- genres: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- id: string (nullable = true)\n |-- album: struct (nullable = true)\n | |-- artists: array (nullable = true)\n | | |-- element: string (containsNull = true)\n | |-- labels: array (nullable = true)\n | | |-- element: string (containsNull = true)\n | |-- score: string (nullable = true)\n | |-- title: string (nullable = true)\n | |-- year: string (nullable = true)\n\n" ], [ "# Check scores!\n\nhelp(album_reviews.describe)\n\ndef to_float(score):\n try:\n return float(score)\n except ValueError:\n return None\n\nudf_score_float = sqlfns.udf(to_float, sqltypes.FloatType())\n\n# Scores to be integers\nalbum_reviews = album_reviews.withColumn(\"score\", udf_score_float(album_reviews.album.score))\n\nalbum_reviews.describe(\"score\").show()", "Help on method describe in module pyspark.sql.dataframe:\n\ndescribe(*cols) method of pyspark.sql.dataframe.DataFrame instance\n Computes statistics for numeric columns.\n \n This include count, mean, stddev, min, and max. If no columns are\n given, this function computes statistics for all numerical columns.\n \n .. note:: This function is meant for exploratory data analysis, as we make no guarantee about the backward compatibility of the schema of the resulting DataFrame.\n \n >>> df.describe().show()\n +-------+------------------+\n |summary| age|\n +-------+------------------+\n | count| 2|\n | mean| 3.5|\n | stddev|2.1213203435596424|\n | min| 2|\n | max| 5|\n +-------+------------------+\n >>> df.describe(['age', 'name']).show()\n +-------+------------------+-----+\n |summary| age| name|\n +-------+------------------+-----+\n | count| 2| 2|\n | mean| 3.5| null|\n | stddev|2.1213203435596424| null|\n | min| 2|Alice|\n | max| 5| Bob|\n +-------+------------------+-----+\n \n .. versionadded:: 1.3.1\n\n+-------+-----------------+\n|summary| score|\n+-------+-----------------+\n| count| 18582|\n| mean|7.029749231418419|\n| stddev|1.301369680072018|\n| min| 0.0|\n| max| 10.0|\n+-------+-----------------+\n\n" ], [ "# Reviews with 0.0 score\n\nwith_zero_score = album_reviews.filter(album_reviews.score == 0.0)\nwith_zero_score.select(\"album.artists\", \"album.title\", \"authors\", \"album.year\", \"album.score\").\\\n sort(\"album.year\").show()", "+-----------------+--------------------+-------------------+----+-----+\n| artists| title| authors|year|score|\n+-----------------+--------------------+-------------------+----+-----+\n| [Sonic Youth]|NYC Ghosts & Flowers|[Brent DiCrescenzo]|2000| 0.0|\n| [Liz Phair]| Liz Phair| [Matt LeMay]|2003| 0.0|\n|[Travis Morrison]| Travistan| [Chris Dahlen]|2004| 0.0|\n| [Robert Pollard]|Relaxation of the...| [Eric Carr]|2005| 0.0|\n| [Jet]| Shine On| [Ray Suzuki]|2006| 0.0|\n+-----------------+--------------------+-------------------+----+-----+\n\n" ], [ "# Reviews with the perfect score, 10.0\n\nwith_perfect_score = album_reviews.filter(album_reviews.score == 10.0)\nwith_perfect_score.cache()\n\nprint(\"%d album reviews with the perfect score, 10!\" % with_perfect_score.count())\nwith_perfect_score.select(\"album.artists\", \"album.title\", \"authors\", \"album.year\", \"score\").\\\n sort(\"album.year\").show()", "105 album reviews with the perfect score, 10!\n+--------------------+--------------------+--------------------+---------+-----+\n| artists| title| authors| year|score|\n+--------------------+--------------------+--------------------+---------+-----+\n| [Pink Floyd]| Animals| [James P. Wisdom]| | 10.0|\n| [James Brown]|Live at the Apoll...| [Dominique Leone]|1963/2004| 10.0|\n| [Nina Simone]| In Concert| [Carvell Wallace]|1964/2016| 10.0|\n| [Otis Redding]|Otis Blue: Otis R...| [Nate Patrin]|1965/2008| 10.0|\n| [The Beatles]| Rubber Soul| [Scott Plagenhoef]|1965/2009| 10.0|\n| [The Beatles]| Revolver| [Scott Plagenhoef]|1966/2009| 10.0|\n| [The Beatles]|Sgt. Pepper's Lon...| [Scott Plagenhoef]|1967/2009| 10.0|\n| [The Beatles]|Magical Mystery Tour| [Scott Plagenhoef]|1967/2009| 10.0|\n| [The Beatles]| The Beatles| [Mark Richardson]|1968/2009| 10.0|\n|[The Velvet Under...|White Light/White...| [Douglas Wolk]|1968/2013| 10.0|\n| [Van Morrison]| Astral Weeks|[Stephen Thomas E...|1968/2015| 10.0|\n| [The Beatles]| Abbey Road| [Mark Richardson]|1969/2009| 10.0|\n| [Neil Young]|Everybody Knows T...| [Mark Richardson]|1969/2009| 10.0|\n|[The Velvet Under...|The Velvet Underg...| [Stuart Berman]|1969/2014| 10.0|\n| [Led Zeppelin]| Led Zeppelin II| [Mark Richardson]|1969/2014| 10.0|\n| [Neil Young]| After the Gold Rush| [Mark Richardson]|1970/2009| 10.0|\n|[The Velvet Under...|Loaded: Re-Loaded...| [Stuart Berman]|1970/2015| 10.0|\n| [Serge Gainsbourg]|Histoire de Melod...| [Tom Ewing]|1971/2009| 10.0|\n| [Can]|Tago Mago [40th A...| [Douglas Wolk]|1971/2011| 10.0|\n| [Joni Mitchell]| Blue| [Jessica Hopper]|1971/2012| 10.0|\n+--------------------+--------------------+--------------------+---------+-----+\nonly showing top 20 rows\n\n" ], [ "# With original/remastered years\n\ndef with_original_year(album_years):\n years = album_years.split(\"/\")\n return int(years[0]) if years[0] else None\n\ndef with_remastered_year(album_years):\n return int(album_years.split(\"/\")[1]) if \"/\" in album_years else None\n\nudf_original_year = sqlfns.udf(with_original_year, sqltypes.IntegerType())\nudf_remastered_year = sqlfns.udf(with_remastered_year, sqltypes.IntegerType())\n\nalbum_reviews = album_reviews.\\\n withColumn(\"original_year\", udf_original_year(album_reviews.album.year)).\\\n withColumn(\"remastered_year\", udf_remastered_year(album_reviews.album.year))\nalbum_reviews.cache()\n\nalbum_reviews.printSchema()\nalbum_reviews.select(\"album.title\", \"album.artists\", \"score\").show(5)", "root\n |-- article: string (nullable = true)\n |-- authors: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- genres: array (nullable = true)\n | |-- element: string (containsNull = true)\n |-- id: string (nullable = true)\n |-- album: struct (nullable = true)\n | |-- artists: array (nullable = true)\n | | |-- element: string (containsNull = true)\n | |-- labels: array (nullable = true)\n | | |-- element: string (containsNull = true)\n | |-- score: string (nullable = true)\n | |-- title: string (nullable = true)\n | |-- year: string (nullable = true)\n |-- score: float (nullable = true)\n |-- original_year: integer (nullable = true)\n |-- remastered_year: integer (nullable = true)\n\n+---------------+-----------------+-----+\n| title| artists|score|\n+---------------+-----------------+-----+\n| Dangerous|[Michael Jackson]| 8.6|\n| Start Together| [Sleater-Kinney]| 9.2|\n| Sleater-Kinney| [Sleater-Kinney]| 7.8|\n|Call the Doctor| [Sleater-Kinney]| 8.6|\n| Dig Me Out| [Sleater-Kinney]| 9.3|\n+---------------+-----------------+-----+\nonly showing top 5 rows\n\n" ], [ "# Plot\n%matplotlib inline\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nyears_and_scores = album_reviews.\\\n filter(~sqlfns.isnull(\"original_year\")).\\\n select(\"original_year\", \"score\").collect()\n\nyears = [r[0] for r in years_and_scores]\nscores = [r[1] for r in years_and_scores]\n\n#print(min(years))\n\nfig = plt.figure(figsize=(12, 15))\nplt.title(\"Album Review Scores\")\nplt.axis([min(years) - 1, max(years) + 1,\n -0.1, 10 + 0.1])\nplt.xlabel(\"Year\")\nplt.ylabel(\"Score\")\n\nplt.scatter(years, scores)", "_____no_output_____" ], [ "# By year\n\n# No year\nwith_no_year = album_reviews.filter(sqlfns.isnull(\"original_year\"))\nprint(\"Album reviews with no year specified: %d\" % with_no_year.count())\n\n# Average by year (post-2000)\nby_year = album_reviews.\\\n filter(~sqlfns.isnull(\"original_year\")).\\\n groupby(\"original_year\").\\\n agg(sqlfns.avg(\"score\").alias(\"score_avg\"),\n sqlfns.count(\"*\").alias(\"reviewed\")).\\\n sort(\"original_year\")\n \nby_year.cache()\n\npost_2000 = by_year.\\\n filter(by_year.original_year >= 2000)\n\npost_2000.show()", "Album reviews with no year specified: 407\n+-------------+------------------+--------+\n|original_year| score_avg|reviewed|\n+-------------+------------------+--------+\n| 2000| 7.092951576221357| 227|\n| 2001| 7.009090919771403| 561|\n| 2002| 6.813844268287363| 809|\n| 2003|6.9799212683138885| 1016|\n| 2004| 7.170926846062264| 1025|\n| 2005| 7.009256214075838| 1210|\n| 2006| 6.957142859953816| 1162|\n| 2007| 6.817819155594136| 1128|\n| 2008| 6.83056732337168| 1181|\n| 2009| 6.841766734232113| 1166|\n| 2010|6.9883537715245465| 1142|\n| 2011| 7.053970977549468| 1171|\n| 2012|6.9876511302842585| 1158|\n| 2013| 7.004306646793901| 1161|\n| 2014| 6.994578909666241| 1033|\n| 2015| 7.045711415567022| 991|\n| 2016| 7.12047246192384| 1016|\n+-------------+------------------+--------+\n\n" ], [ "temp = post_2000.collect()\nyears = [r[0] for r in temp]\nreviewed = [r[2] for r in temp]\n\nfig = plt.figure(figsize=(12, 7))\nplt.title(\"Albums Reviewed By Year (post-2000)\")\nplt.axis([min(years), max(years),\n 0, max(reviewed) + 50])\nplt.xlabel(\"Year\")\nplt.ylabel(\"Albums Reviewed\")\n\nplt.bar(years, reviewed)", "_____no_output_____" ], [ "temp = by_year.collect()\nyears = [r[0] for r in temp]\navgs = [r[1] for r in temp]\n\nfig = plt.figure(figsize=(12, 7))\nplt.title(\"Score Avg by Year\")\nplt.axis([min(years), max(years),\n 0, 10])\nplt.xlabel(\"Year\")\nplt.ylabel(\"Albums Reviewed\")\n\nplt.bar(years, avgs)", "_____no_output_____" ], [ "# Reviews with the perfect score, 10 (non-remasters ONLY)\n\nwith_perfect_score_non_remasters_only = album_reviews.\\\n filter(album_reviews.score == 10.0).\\\n filter(sqlfns.isnull(\"remastered_year\"))\nwith_perfect_score_non_remasters_only.cache()\n \nwith_perfect_score_non_remasters_only.\\\n select(\"album.title\", \"album.artists\", \"album.year\", \"original_year\", \"score\").\\\n sort(\"original_year\").\\\n show()", "+--------------------+--------------------+----+-------------+-----+\n| title| artists|year|original_year|score|\n+--------------------+--------------------+----+-------------+-----+\n| Animals| [Pink Floyd]| | null| 10.0|\n| Tonight's the Night| [Neil Young]|1975| 1975| 10.0|\n| Another Green World| [Brian Eno]|1975| 1975| 10.0|\n| Blood on the Tracks| [Bob Dylan]|1975| 1975| 10.0|\n|Songs in the Key ...| [Stevie Wonder]|1976| 1976| 10.0|\n| Pink Flag| [Wire]|1977| 1977| 10.0|\n| Marquee Moon| [Television]|1977| 1977| 10.0|\n| Low| [David Bowie]|1977| 1977| 10.0|\n| \"Heroes\"| [David Bowie]|1977| 1977| 10.0|\n| Chairs Missing| [Wire]|1978| 1978| 10.0|\n| Dirty Mind| [Prince]|1980| 1980| 10.0|\n| 1999| [Prince]|1982| 1982| 10.0|\n| Purple Rain|[Prince, The Revo...|1984| 1984| 10.0|\n| Hounds of Love| [Kate Bush]|1985| 1985| 10.0|\n| Sign \"O\" the Times| [Prince]|1987| 1987| 10.0|\n| Surfer Rosa| [Pixies]|1988| 1988| 10.0|\n| Doolittle| [Pixies]|1989| 1989| 10.0|\n| I See a Darkness|[Bonnie “Prince” ...|1999| 1999| 10.0|\n| Kid A| [Radiohead]|2000| 2000| 10.0|\n|The Olatunji Conc...| [John Coltrane]|2001| 2001| 10.0|\n+--------------------+--------------------+----+-------------+-----+\nonly showing top 20 rows\n\n" ], [ "# Reviews with the perfect score, 10 (non-remasters ONLY), in 2000s\n\nwith_perfect_score_non_remasters_only.\\\n select(\"album.title\", \"album.artists\", \"original_year\", \"score\").\\\n filter(with_perfect_score_non_remasters_only.original_year >= 2000).\\\n sort(\"original_year\", ascending=False).\\\n show()", "+--------------------+--------------------+-------------+-----+\n| title| artists|original_year|score|\n+--------------------+--------------------+-------------+-----+\n|A Love Supreme: T...| [John Coltrane]| 2015| 10.0|\n|The Disintegratio...| [William Basinski]| 2012| 10.0|\n| Laughing Stock| [Talk Talk]| 2011| 10.0|\n| The Smile Sessions| [The Beach Boys]| 2011| 10.0|\n|Nevermind [20th A...| [Nirvana]| 2011| 10.0|\n|Siamese Dream [De...|[The Smashing Pum...| 2011| 10.0|\n|Emergency & I [Vi...|[The Dismembermen...| 2011| 10.0|\n| The Queen Is Dead| [The Smiths]| 2011| 10.0|\n| Hatful of Hollow| [The Smiths]| 2011| 10.0|\n| Quarantine the Past| [Pavement]| 2010| 10.0|\n|My Beautiful Dark...| [Kanye West]| 2010| 10.0|\n| On Fire| [Galaxie 500]| 2010| 10.0|\n|Pinkerton [Deluxe...| [Weezer]| 2010| 10.0|\n|Disintegration [D...| [The Cure]| 2010| 10.0|\n|Exile on Main St....|[The Rolling Stones]| 2010| 10.0|\n| In Mono| [The Beatles]| 2009| 10.0|\n|Ladies and Gentle...| [Spiritualized]| 2009| 10.0|\n|The Bends: Collec...| [Radiohead]| 2009| 10.0|\n| Stereo Box| [The Beatles]| 2009| 10.0|\n|OK Computer: Coll...| [Radiohead]| 2009| 10.0|\n+--------------------+--------------------+-------------+-----+\nonly showing top 20 rows\n\n" ], [ "# Album reviews with multiple authors\n\nalbum_reviews.filter(sqlfns.size(album_reviews.authors) > 1).count()", "_____no_output_____" ], [ "# With comma-separated authors\n\ndef with_csv_authors(authors):\n return \", \".join(authors)\n\nudf_with_author = sqlfns.udf(with_csv_authors, sqltypes.StringType())\n\nalbum_reviews = album_reviews.withColumn(\"author\", udf_with_author(album_reviews.authors))\n\nalbum_reviews.select(\"album.title\", \"album.artists\", \"author\").show(5)", "+---------------+-----------------+----------+\n| title| artists| author|\n+---------------+-----------------+----------+\n| Dangerous|[Michael Jackson]|Jeff Weiss|\n| Start Together| [Sleater-Kinney]|Jenn Pelly|\n| Sleater-Kinney| [Sleater-Kinney]|Jenn Pelly|\n|Call the Doctor| [Sleater-Kinney]|Jenn Pelly|\n| Dig Me Out| [Sleater-Kinney]|Jenn Pelly|\n+---------------+-----------------+----------+\nonly showing top 5 rows\n\n" ], [ "# Best rated collabo albums\n\ndef csv_artists(artists):\n return \", \".join(artists)\n\nudf_csv_artists = sqlfns.udf(csv_artists, sqltypes.StringType())\n\nalbum_reviews.filter(sqlfns.size(\"album.artists\") > 1).\\\n select(\"album.title\", \n udf_csv_artists(\"album.artists\").alias(\"artists\"),\n \"author\", \"album.year\", \"score\").\\\n sort(\"score\", ascending=False).\\\n show(10)", "+--------------------+--------------------+---------------+---------+-----+\n| title| artists| author| year|score|\n+--------------------+--------------------+---------------+---------+-----+\n| Purple Rain|Prince, The Revol...|Carvell Wallace| 1984| 10.0|\n| String Quartet II|Morton Feldman, I...| Chris Dahlen| 2001| 9.5|\n| Black Messiah|D'Angelo, The Van...| Craig Jenkins| 2014| 9.4|\n| After the Heat|Brian Eno, Dieter...|Mark Richardson|1978/2005| 9.3|\n| Ram|Paul McCartney, L...| Jayson Greene|1971/2012| 9.2|\n| Parade|Prince, The Revol...| Douglas Wolk| 1986| 9.1|\n|Outside the Dream...| Tony Conrad, Faust|Brent S. Sirota|1972/2002| 9.0|\n| After the Heat|Brian Eno, Dieter...| Andy Beta|1978/2005| 9.0|\n| Open, Coma|Tim Berne, Herb R...| Chris Dahlen| 2002| 8.9|\n|Around the World ...|Prince, The Revol...| Alan Light| 1985| 8.8|\n+--------------------+--------------------+---------------+---------+-----+\nonly showing top 10 rows\n\n" ], [ "# Album reviews with multiple genres\n\nwith_multiple_genres = album_reviews.filter(sqlfns.size(album_reviews.genres) > 1)\nprint(\"%d reviews with multiple genres\" % with_multiple_genres.count())\n\nalbum_reviews.withColumn(\"genre\", sqlfns.explode(\"genres\")).\\\n filter(with_multiple_genres.album.title == \"HOPELESSNESS\").\\\n select(\"album.title\", \"album.artists\", \"genre\").\\\n show()", "4143 reviews with multiple genres\n+------------+--------+------------+\n| title| artists| genre|\n+------------+--------+------------+\n|HOPELESSNESS|[ANOHNI]| Pop/R&B|\n|HOPELESSNESS|[ANOHNI]|Experimental|\n+------------+--------+------------+\n\n" ], [ "# Which genres gets loved the most?\n\nhelp(album_reviews.groupby)\n\ngrouped_by_genre = album_reviews.withColumn(\"genre\", sqlfns.explode(\"genres\")).groupby(\"genre\")\n\nagg_by_genre = grouped_by_genre.agg(sqlfns.avg(\"score\").alias(\"score_avg\"),\n sqlfns.max(\"score\").alias(\"score_max\"),\n sqlfns.min(\"score\").alias(\"score_min\"),\n sqlfns.count(\"*\").alias(\"reviewed\"))\nagg_by_genre.sort(\"score_avg\", ascending=False).show()", "Help on method groupBy in module pyspark.sql.dataframe:\n\ngroupBy(*cols) method of pyspark.sql.dataframe.DataFrame instance\n :func:`groupby` is an alias for :func:`groupBy`.\n \n .. versionadded:: 1.4\n\n+------------+-----------------+---------+---------+--------+\n| genre| score_avg|score_max|score_min|reviewed|\n+------------+-----------------+---------+---------+--------+\n| Global|7.522943757829212| 9.7| 2.2| 231|\n|Experimental|7.350647254894209| 10.0| 0.3| 1854|\n| Jazz|7.318636365370317| 10.0| 1.0| 440|\n|Folk/Country|7.215306127036626| 10.0| 2.2| 686|\n| Rock|6.980606763876109| 10.0| 0.0| 9658|\n| Metal| 6.95941375773883| 10.0| 0.2| 887|\n| Electronic|6.955307972594595| 10.0| 0.0| 3994|\n| Pop/R&B|6.902234270053897| 10.0| 0.0| 1477|\n| Rap|6.901079632452464| 10.0| 0.8| 1482|\n+------------+-----------------+---------+---------+--------+\n\n" ], [ "fig = plt.figure(figsize=(7, 7))\nplt.title(\"Albums by Genre\")\n\ntemp = agg_by_genre.collect()\ngenres = [r[0] for r in temp]\nreviewed = [r[4] for r in temp]\n\nplt.pie(reviewed, labels=genres)", "_____no_output_____" ], [ "temp = agg_by_genre.sort(\"score_avg\").collect()\ngenres = [r[0] for r in temp]\navgs = [r[1] for r in temp]\n\nnums = list(range(len(genres)))\n\nfig = plt.figure(figsize=(15, 7))\nplt.title(\"Score Avg by Genre\")\n\nplt.bar(nums, avgs, align=\"center\")\nplt.xticks(nums, genres)", "_____no_output_____" ], [ "# Which author rates lowest?\n\ngrouped_by_author = album_reviews.withColumn(\"author\", sqlfns.explode(\"authors\")).groupby(\"author\")\n\nscore_avg_by_author = grouped_by_author.agg(sqlfns.avg(\"score\").alias(\"score_avg\"),\n sqlfns.max(\"score\").alias(\"score_max\"),\n sqlfns.min(\"score\").alias(\"score_min\"),\n sqlfns.count(\"*\").alias(\"reviewed\"))\n\n# Only those who have reviewed 100 or more albums\nscore_avg_by_author.filter(score_avg_by_author.reviewed >= 100).\\\n sort(score_avg_by_author.score_avg).\\\n show()\n \n# The highest rated review by Adam Moerder (8.5)\nalbum_reviews.\\\n filter(album_reviews.author == \"Adam Moerder\").\\\n filter(album_reviews.score == 8.5).\\\n select(\"album.title\", \"album.artists\", \"score\", \"author\").\\\n collect()", "+--------------+------------------+---------+---------+--------+\n| author| score_avg|score_max|score_min|reviewed|\n+--------------+------------------+---------+---------+--------+\n| Adam Moerder| 6.164077675458297| 8.5| 1.5| 206|\n| Joshua Love| 6.342056102841814| 9.1| 2.0| 107|\n| Ian Cohen| 6.348471622952034| 10.0| 0.2| 687|\n| Rob Mitchum| 6.396511617210484| 10.0| 0.4| 258|\n| David Raposa| 6.523125015199184| 9.6| 2.5| 160|\n| Eric Harvey| 6.597777795791626| 9.0| 1.5| 135|\n| Zach Kelly| 6.598684196409426| 8.5| 3.7| 152|\n| Eric Carr| 6.600000026516425| 10.0| 0.0| 117|\n| Marc Hogan| 6.613348420389098| 9.2| 0.9| 442|\n|Nick Sylvester| 6.682031279429793| 9.0| 0.5| 128|\n| Paul Thompson| 6.710267869489534| 10.0| 2.8| 224|\n| Joshua Klein| 6.730875563511651| 10.0| 2.7| 217|\n| Tom Breihan| 6.757547177796094| 9.5| 1.6| 212|\n| Douglas Wolk| 6.795424837692111| 10.0| 1.3| 153|\n| Nick Neyland| 6.840654199368486| 9.2| 4.6| 214|\n| Jason Crock| 6.870522403894966| 9.3| 2.0| 268|\n| Paul Cooper| 6.888695633929709| 9.5| 2.2| 115|\n| Sam Ubl| 6.897402613193957| 8.7| 2.0| 154|\n| Andrew Gaerig|6.8992700916137135| 9.0| 2.9| 274|\n| Joe Colly| 6.933027513530276| 9.0| 1.4| 109|\n+--------------+------------------+---------+---------+--------+\nonly showing top 20 rows\n\n" ], [ "# By artist\n\nsingle_artist = sqlfns.udf(lambda artists: artists[0], sqlfns.StringType())\n\nby_artist = album_reviews.\\\n filter(sqlfns.size(album_reviews.album.artists) == 1).\\\n withColumn(\"artist\", single_artist(\"album.artists\")).\\\n groupby(\"artist\").\\\n agg(sqlfns.avg(\"score\").alias(\"score_avg\"),\n sqlfns.count(\"*\").alias(\"albums\"))\n \ngte_five_albums = by_artist.filter(by_artist.albums >= 5)\n\ngte_five_albums.cache()\n\n# Most/least loved artists\ntop_ten = gte_five_albums.sort(\"score_avg\", ascending=False).limit(10)\nbottom_ten = gte_five_albums.sort(\"score_avg\", ascending=True).limit(10)\n\nprint(\"10 most loved artists (with 5 or more albums reviewed):\")\ntop_ten.show()\n\nprint(\"10 least loved artists (with 5 or more albums reviewed):\")\nbottom_ten.show()", "10 most loved artists (with 5 or more albums reviewed):\n+--------------------+-----------------+------+\n| artist| score_avg|albums|\n+--------------------+-----------------+------+\n|The Velvet Underg...|9.524999976158142| 8|\n| Funkadelic|9.020000076293945| 5|\n| Pavement| 9.0| 5|\n| This Heat|8.980000114440918| 5|\n| The Beatles|8.940909082239324| 22|\n| Caetano Veloso|8.839999961853028| 5|\n| Sleater-Kinney|8.800000095367432| 10|\n| Joanna Newsom|8.759999847412109| 5|\n| Miles Davis|8.730769194089449| 13|\n| Galaxie 500|8.679999923706054| 5|\n+--------------------+-----------------+------+\n\n10 least loved artists (with 5 or more albums reviewed):\n+--------------------+------------------+------+\n| artist| score_avg|albums|\n+--------------------+------------------+------+\n| The Dandy Warhols|3.6199999809265138| 5|\n| Joan of Arc|3.6833333373069763| 6|\n| The Get Up Kids|3.7799999713897705| 5|\n| N.E.R.D.| 4.359999942779541| 5|\n| Gomez|4.3599999904632565| 5|\n| The Mars Volta| 4.457142898014614| 7|\n| Moby| 4.471428564616612| 7|\n| Tricky| 4.614285741533552| 7|\n|Black Rebel Motor...| 4.650000000993411| 6|\n| Kings of Leon| 4.785714251654489| 7|\n+--------------------+------------------+------+\n\n" ], [ "# The Beatles\n\nprint(\"The Beatles albums:\")\nalbum_reviews.\\\n filter(sqlfns.array_contains(\"album.artists\", \"The Beatles\")).\\\n select(\"original_year\", sqlfns.lit(\"The Beatles\"), \"album.title\", \"score\").\\\n sort(\"original_year\").\\\n show(22)\n \n# Radiohead\nprint(\"Radiohead albums:\")\nalbum_reviews.\\\n filter(sqlfns.array_contains(\"album.artists\", \"Radiohead\")).\\\n select(\"original_year\", sqlfns.lit(\"Radiohead\"), \"album.title\", \"score\").\\\n sort(\"original_year\").\\\n show()", "The Beatles albums:\n+-------------+-----------+--------------------+-----+\n|original_year|The Beatles| title|score|\n+-------------+-----------+--------------------+-----+\n| 1963|The Beatles| Please Please Me| 9.5|\n| 1963|The Beatles| With the Beatles| 8.8|\n| 1964|The Beatles| A Hard Day's Night| 9.7|\n| 1964|The Beatles| Beatles For Sale| 9.3|\n| 1965|The Beatles| Rubber Soul| 10.0|\n| 1965|The Beatles| Help!| 9.2|\n| 1966|The Beatles| Revolver| 10.0|\n| 1967|The Beatles|Magical Mystery Tour| 10.0|\n| 1967|The Beatles|Sgt. Pepper's Lon...| 10.0|\n| 1968|The Beatles| The Beatles| 10.0|\n| 1969|The Beatles| Abbey Road| 10.0|\n| 1969|The Beatles| Yellow Submarine| 6.2|\n| 1970|The Beatles| Let It Be| 9.1|\n| 1988|The Beatles| Past Masters| 9.2|\n| 2003|The Beatles| Let It Be... Naked| 7.0|\n| 2004|The Beatles|The Capitol Album...| 6.0|\n| 2006|The Beatles| Love| 8.5|\n| 2006|The Beatles|The Capitol Album...| 7.5|\n| 2009|The Beatles| Stereo Box| 10.0|\n| 2009|The Beatles| Rock Band| 9.5|\n| 2009|The Beatles| In Mono| 10.0|\n| 2013|The Beatles|On Air - Live at ...| 7.2|\n+-------------+-----------+--------------------+-----+\n\nRadiohead albums:\n+-------------+---------+--------------------+-----+\n|original_year|Radiohead| title|score|\n+-------------+---------+--------------------+-----+\n| 2000|Radiohead| Kid A| 10.0|\n| 2001|Radiohead| Amnesiac| 9.0|\n| 2001|Radiohead|I Might Be Wrong:...| 8.0|\n| 2007|Radiohead| In Rainbows [CD 2]| 6.2|\n| 2007|Radiohead| In Rainbows| 9.3|\n| 2008|Radiohead| The Best Of| 4.0|\n| 2008|Radiohead|The Best Of [Spec...| 2.0|\n| 2009|Radiohead|Pablo Honey: Coll...| 5.4|\n| 2009|Radiohead|Hail to the Thief...| 8.6|\n| 2009|Radiohead|Kid A: Special Co...| 10.0|\n| 2009|Radiohead|The Bends: Collec...| 10.0|\n| 2009|Radiohead|OK Computer: Coll...| 10.0|\n| 2009|Radiohead|Amnesiac: Special...| 9.5|\n| 2011|Radiohead| TKOL RMX 1234567| 6.0|\n| 2011|Radiohead| The King of Limbs| 7.9|\n| 2016|Radiohead| A Moon Shaped Pool| 9.1|\n+-------------+---------+--------------------+-----+\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfcab743e364803cb353b22f1974c994a5e9bf0
8,753
ipynb
Jupyter Notebook
docs/tutorials/cga/clustering.ipynb
corcoted/clifford
8077fa71e97292b7076435daae40ca3badc7819d
[ "BSD-3-Clause" ]
642
2017-11-17T09:49:48.000Z
2022-03-21T22:02:25.000Z
docs/tutorials/cga/clustering.ipynb
corcoted/clifford
8077fa71e97292b7076435daae40ca3badc7819d
[ "BSD-3-Clause" ]
347
2017-11-17T13:57:43.000Z
2022-01-20T09:40:15.000Z
docs/tutorials/cga/clustering.ipynb
corcoted/clifford
8077fa71e97292b7076435daae40ca3badc7819d
[ "BSD-3-Clause" ]
61
2017-11-19T17:15:26.000Z
2022-01-15T05:18:27.000Z
34.87251
287
0.544042
[ [ [ "This notebook is part of the `clifford` documentation: https://clifford.readthedocs.io/.", "_____no_output_____" ], [ "# Example 2 Clustering Geometric Objects", "_____no_output_____" ], [ "In this example we will look at a few of the tools provided by the clifford package for (4,1) conformal geometric algebra (CGA) and see how we can use them in a practical setting to cluster geometric objects via the simple K-means clustering algorithm provided in clifford.tools\n\nAs before the first step in using the package for CGA is to generate and import the algebra:", "_____no_output_____" ] ], [ [ "from clifford.g3c import *\nprint('e1*e1 ', e1*e1)\nprint('e2*e2 ', e2*e2)\nprint('e3*e3 ', e3*e3)\nprint('e4*e4 ', e4*e4)\nprint('e5*e5 ', e5*e5)", "_____no_output_____" ] ], [ [ "The tools submodule of the clifford package contains a wide array of algorithms and tools that can be useful for manipulating objects in CGA. In this case we will be generating a large number of objects and then segmenting them into clusters.\n\nWe first need an algorithm for generating a cluster of objects in space. We will construct this cluster by generating a random object and then repeatedly disturbing this object by some small fixed amount and storing the result:", "_____no_output_____" ] ], [ [ "from clifford.tools.g3c import *\nimport numpy as np\n\ndef generate_random_object_cluster(n_objects, object_generator, max_cluster_trans=1.0, max_cluster_rot=np.pi/8):\n \"\"\" Creates a cluster of random objects \"\"\"\n ref_obj = object_generator()\n cluster_objects = []\n for i in range(n_objects):\n r = random_rotation_translation_rotor(maximum_translation=max_cluster_trans, maximum_angle=max_cluster_rot)\n new_obj = apply_rotor(ref_obj, r)\n cluster_objects.append(new_obj)\n return cluster_objects", "_____no_output_____" ] ], [ [ "We can use this function to create a cluster and then we can visualise this cluster with [pyganja](https://github.com/pygae/pyganja).", "_____no_output_____" ] ], [ [ "from pyganja import *\nclustered_circles = generate_random_object_cluster(10, random_circle)\nsc = GanjaScene()\nfor c in clustered_circles:\n sc.add_object(c, rgb2hex([255,0,0]))\ndraw(sc, scale=0.05)", "_____no_output_____" ] ], [ [ "This cluster generation function appears in clifford tools by default and it can be imported as follows:", "_____no_output_____" ] ], [ [ "from clifford.tools.g3c import generate_random_object_cluster", "_____no_output_____" ] ], [ [ "Now that we can generate individual clusters we would like to generate many:", "_____no_output_____" ] ], [ [ "def generate_n_clusters( object_generator, n_clusters, n_objects_per_cluster ):\n object_clusters = []\n for i in range(n_clusters):\n cluster_objects = generate_random_object_cluster(n_objects_per_cluster, object_generator,\n max_cluster_trans=0.5, max_cluster_rot=np.pi / 16)\n object_clusters.append(cluster_objects)\n all_objects = [item for sublist in object_clusters for item in sublist]\n return all_objects, object_clusters", "_____no_output_____" ] ], [ [ "Again this function appears by default in clifford tools and we can easily visualise the result:", "_____no_output_____" ] ], [ [ "from clifford.tools.g3c import generate_n_clusters\n\nall_objects, object_clusters = generate_n_clusters(random_circle, 2, 5)\nsc = GanjaScene()\nfor c in all_objects:\n sc.add_object(c, rgb2hex([255,0,0]))\ndraw(sc, scale=0.05)", "_____no_output_____" ] ], [ [ "Given that we can now generate multiple clusters of objects we can test algorithms for segmenting them.\n\nThe function run_n_clusters below generates a lot of objects distributed into n clusters and then attempts to segment the objects to recover the clusters. ", "_____no_output_____" ] ], [ [ "from clifford.tools.g3c.object_clustering import n_clusters_objects\nimport time\n\ndef run_n_clusters( object_generator, n_clusters, n_objects_per_cluster, n_shotgunning):\n all_objects, object_clusters = generate_n_clusters( object_generator, n_clusters, n_objects_per_cluster ) \n [new_labels, centroids, start_labels, start_centroids] = n_clusters_objects(n_clusters, all_objects, \n initial_centroids=None, \n n_shotgunning=n_shotgunning, \n averaging_method='unweighted') \n return all_objects, new_labels, centroids ", "_____no_output_____" ] ], [ [ "Lets try it!", "_____no_output_____" ] ], [ [ "def visualise_n_clusters(all_objects, centroids, labels,\n color_1=np.array([255, 0, 0]), \n color_2=np.array([0, 255, 0])):\n \"\"\"\n Utility method for visualising several clusters and their respective centroids\n using pyganja\n \"\"\"\n alpha_list = np.linspace(0, 1, num=len(centroids))\n sc = GanjaScene()\n for ind, this_obj in enumerate(all_objects):\n alpha = alpha_list[labels[ind]]\n cluster_color = (alpha * color_1 + (1 - alpha) * color_2).astype(np.int)\n sc.add_object(this_obj, rgb2hex(cluster_color))\n\n for c in centroids:\n sc.add_object(c, Color.BLACK)\n\n return sc\n\n \n\nobject_generator = random_circle \n\nn_clusters = 3 \nn_objects_per_cluster = 10 \nn_shotgunning = 60 \nall_objects, labels, centroids = run_n_clusters(object_generator, n_clusters, \n n_objects_per_cluster, n_shotgunning)\n \nsc = visualise_n_clusters(all_objects, centroids, labels, \n color_1=np.array([255, 0, 0]), \n color_2=np.array([0, 255, 0])) \ndraw(sc, scale=0.05) ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
ecfcb9dec4c3bfbbde07d09c9bd57fae7480d3ce
8,303
ipynb
Jupyter Notebook
GrommetChallenge.ipynb
Didier-Lalli/GrommetChallenge
af8df50a23a0b71a4270f836da86af021bcb7c31
[ "Apache-2.0" ]
null
null
null
GrommetChallenge.ipynb
Didier-Lalli/GrommetChallenge
af8df50a23a0b71a4270f836da86af021bcb7c31
[ "Apache-2.0" ]
null
null
null
GrommetChallenge.ipynb
Didier-Lalli/GrommetChallenge
af8df50a23a0b71a4270f836da86af021bcb7c31
[ "Apache-2.0" ]
null
null
null
51.571429
723
0.682043
[ [ [ "![hpedev.io](https://developer.hpe.com/img/hpe-dev-logo-mark-anim.svg?1580730675069 \"HPE DEV Hack Shack\")\n\n\n# Welcome to the DISCOVER Hack Shack Grommet Challenge\n\n## Challenge prerequisites\n\nWe recommend you attend the following Discover Hack Shack workshops before attempting this challenge:\n\n1. [Hack Shack Workshop: Git 101](../../WKSHP-GIT101/0-ReadmeFirst.ipynb)\n2. [Hack Shack Workshop: Streamline app development with open source Grommet](../../WKSHP-Grommet/0-ReadmeFirst.ipynb)\n\nAlso, make sure you leverage the notebooks provided in your Jupyter account environment as reference material.\n\n> Please note, your account session will only be allocated for a 4-hour time slot, so make sure you register only when you have enough time available to take the challenge.\n\n# Challenge description\n\nA new mission awaits! In this challenge, you will take on a UX designer persona and show your creative side using Grommet to design your own little web app UI. You will start with the Grommet Designer, generate code from your design, push that code to GitHub, and finally deploy the app on Netlify. Beginner through expert designers and developers are all welcome. This challenge is all about unleashing your creativity!\n\n# Step 1: Build a sample front-end application\n\nThe first step to accomplish this challenge is to create a web front-end application, and for this we would like you to use Grommet Designer. Keep it simple yet slick, show your design prowess. The [Hack Shack Workshop: Streamline app development with open source Grommet](../WKSHP-Grommet/1-WKSHP-Introduction.ipynb) is your best point of reference for this step, if you need help.\n\n## Quiz question 1:\n\nWhat is the URL of the Grommet Designer?", "_____no_output_____" ] ], [ [ "Https://designer.grommet.io", "_____no_output_____" ] ], [ [ "\n# Step 2: Run your web application locally\n\nThe next step of the challenge is to make this application work locally on your laptop. The Grommet Designer online instructions and the [Lab 3 of the Grommet Workshop](../WKSHP-Grommet/3-WKSHP-PrepareEnvironment.ipynb) are your best source of information for accomplishing this. \n\n# Step 3: Share your application in GitHub\n\nIn this step, you will use the local version of your application to create a local git repo and then upload it into your GitHub account. The [Hack Shack Workshop: Git 101](../WKSHP-GIT101/1-WKSHP-GIT-Basics.ipynb) and [the last part of Lab 3 of the Grommet Workshop](../WKSHP-Grommet/3-WKSHP-PrepareEnvironment.ipynb) are your best sources of information for accomplishing this.\n \n## Quiz question 2:\n\nWhat is the URL of your application source code repo on GitHub?", "_____no_output_____" ] ], [ [ "# Your response goes here", "_____no_output_____" ] ], [ [ "# Step 4: Set up CI/CD pipeline for your application\n\nThis is the final step of your challenge. We will ask you to use [Netlifly](https://netlifly.com) to host your application so we can judge it. For this you will need to setup an account on [Netlifly](https://netlifly.com) (this is free) and a CI/CD configuration so that [Netlifly](https://netlifly.com) automatically builds your web site from your GitHub repo created in Step 3. Use [Lab4 of the Grommet Workshop](../WKSHP-Grommet/4-WKSHP-DeploytoNetlify.ipynb) for details on how to accomplish this. Once this is all in place, not only will your application be up and running (try changing the domain name to obtain a friendly URL), but it will automatically update everytime you commit changes to it in GitHub. \n\n> Note: You can use this feature as an opportunity to continue improve your design until the \"judgment day\", since the URL you have submitted will not change ;-)\n\n## Quiz question 3:\n\nWhat is the URL of your application on Netlifly?", "_____no_output_____" ] ], [ [ "# Your response goes here", "_____no_output_____" ] ], [ [ "Finished? Well done! It's now time to submit your reponse.\n\n# Submitting your response \n\nIn order to hand in your response to this challenge, we will ask you to use GitHub to submit the modified version of the Jupyter Notebook.\nFollow instructions from the [Hack Shack Workshop: Git 101](../WKSHP-GIT101/1-WKSHP-GIT-Basics.ipynb) notebook if you need help.\n\nSubmitting your response to the challenge will be done by submitting your edited challenge notebook (in some cases there might be additional edited files in the repo). When you are ready, we will ask you to leverage GitHub again and do the following:\n\n- Step 1: Commit changes in your Jupyter environment (again using your Launcher terminal window)\n- Step 2: Push changes to your repo (still using your Launcher terminal window)\n- Step 3: Open a Pull Request (PR) on our original repo. Make sure you provide an email in the description of the PR so we can contact you if your submission has been chosen. (This step is done from your GitHub account).\n\n![Open PR](Pictures/NewPullRequest.png)\n\nYou should submit your response within the 4-hour time slot. We will reset all the Jupyter accounts right after the time is up, so make sure you have at least committed and pushed your changes back to your repo prior to that. You will then have more time to submit your PR.\n\n> Note: Use the [GIT101 notebook](./WKSHP-GIT101/1-WKSHP-GIT-Basics.ipynb) if you need assistance with these steps\n\n# Looking for help?\n\nDon't hesitate to refer back to the notebooks in your Jupyter accounts for help in answering questions that come up in the challenge. We have set up a Slack channel in the HPE DEV Slack Workspace. Feel free to [join the workspace](https://slack.hpedev.io/) then [start asking questions there](https://hpedev.slack.com/archives/C015CLE2QTT). We will be around to help you.\n\nFinally, in case of a real emergency, you can contact the [HPEDEV Team](mailto:[email protected]).\n\nPlease note that during the period of June 30th, until July 17th the Slack channel will be opened 24x7, with monitoring from the HPE DEV Team from 9AM-6PM CET.\n\n# Providing feedback\n\nWe would love to get feedback about your experience with the Hack Shack Challenges, so please take a moment to fill out that [short survey](https://forms.office.com/Pages/ResponsePage.aspx?id=YSBbEGm2MUuSrCTTBNGV3KHzFdd987lBoQATWJq45DdUNEVQTzdQV1NZM1MxNVVDMDRPRlFGUTlaQi4u) for us:\n\n# Challenge rewards\n\nWe will select and reward the best response per challenge subject at the end of the HPE Discover Virtual Experience Challenges period. In addition to this, we will have a drawing amongst all the challengers who participated in all four challenges and also reward this super-challenger. \n\n[Review the terms & conditions](https://hackshack.hpedev.io/challengetermsconditions)\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecfcbcdecd7bf37265452e191933496249d55d01
309,713
ipynb
Jupyter Notebook
Custom_metric.ipynb
jvishnuvardhan/Keras_Examples
333f601837d9744cea5d429c50670895cc72f665
[ "Apache-2.0" ]
3
2019-10-08T12:52:23.000Z
2020-02-17T12:12:47.000Z
Custom_metric.ipynb
jvishnuvardhan/Keras_Examples
333f601837d9744cea5d429c50670895cc72f665
[ "Apache-2.0" ]
7
2020-02-12T00:48:19.000Z
2020-02-12T01:06:27.000Z
Custom_metric.ipynb
jvishnuvardhan/Keras_Examples
333f601837d9744cea5d429c50670895cc72f665
[ "Apache-2.0" ]
1
2020-02-11T10:50:20.000Z
2020-02-11T10:50:20.000Z
1,518.20098
300,123
0.017377
[ [ [ "<a href=\"https://colab.research.google.com/github/jvishnuvardhan/Keras_Examples/blob/master/Custom_metric.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!pip install tensorflow==2.0.0rc1", "Collecting tensorflow==2.0.0rc1\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/40/d0/7359227ccfb6e2ae2a8fe345db1d513f010282022a7a6a899530cc63c41f/tensorflow-2.0.0rc1-cp36-cp36m-manylinux2010_x86_64.whl (86.3MB)\n\u001b[K |████████████████████████████████| 86.3MB 1.6MB/s \n\u001b[?25hRequirement already satisfied: gast>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (0.2.2)\nRequirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (3.7.1)\nRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (1.1.0)\nRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (1.15.0)\nRequirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (0.8.0)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (1.12.0)\nRequirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (1.11.2)\nRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (0.8.0)\nRequirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (1.1.0)\nRequirement already satisfied: keras-applications>=1.0.8 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (1.0.8)\nRequirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (1.16.5)\nCollecting tb-nightly<1.15.0a20190807,>=1.15.0a20190806 (from tensorflow==2.0.0rc1)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/bc/88/24b5fb7280e74c7cf65bde47c171547fd02afb3840cff41bcbe9270650f5/tb_nightly-1.15.0a20190806-py3-none-any.whl (4.3MB)\n\u001b[K |████████████████████████████████| 4.3MB 39.1MB/s \n\u001b[?25hCollecting tf-estimator-nightly<1.14.0.dev2019080602,>=1.14.0.dev2019080601 (from tensorflow==2.0.0rc1)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/21/28/f2a27a62943d5f041e4a6fd404b2d21cb7c59b2242a4e73b03d9ba166552/tf_estimator_nightly-1.14.0.dev2019080601-py2.py3-none-any.whl (501kB)\n\u001b[K |████████████████████████████████| 501kB 38.1MB/s \n\u001b[?25hRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (0.33.6)\nRequirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (0.1.7)\nRequirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0rc1) (3.0.1)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tensorflow==2.0.0rc1) (41.2.0)\nRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.8->tensorflow==2.0.0rc1) (2.8.0)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.15.0a20190807,>=1.15.0a20190806->tensorflow==2.0.0rc1) (3.1.1)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.15.0a20190807,>=1.15.0a20190806->tensorflow==2.0.0rc1) (0.15.6)\nInstalling collected packages: tb-nightly, tf-estimator-nightly, tensorflow\n Found existing installation: tensorflow 1.14.0\n Uninstalling tensorflow-1.14.0:\n Successfully uninstalled tensorflow-1.14.0\nSuccessfully installed tb-nightly-1.15.0a20190806 tensorflow-2.0.0rc1 tf-estimator-nightly-1.14.0.dev2019080601\n" ], [ "import tensorflow as tf\nfrom tensorflow import keras\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\n# Custom Loss1 (for example) \[email protected]() \ndef customLoss1(yTrue,yPred):\n return tf.reduce_mean(yTrue-yPred) \n\n# Custom Loss2 (for example) \[email protected]() \ndef customLoss2(yTrue, yPred):\n return tf.reduce_mean(tf.square(tf.subtract(yTrue,yPred))) \n \ndef create_model():\n model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(512, activation=tf.nn.relu), \n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n ])\n model.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy', customLoss1, customLoss2])\n return model", "_____no_output_____" ], [ "# Create a basic model instance\nmodel=create_model()\n\n# Fit and evaluate model \nmodel.fit(x_train, y_train, epochs=5)\nloss, acc,loss1, loss2 = model.evaluate(x_test, y_test,verbose=1)\nprint(\"Original model, accuracy: {:5.2f}%\".format(100*acc))", "Train on 60000 samples\nEpoch 1/5\n60000/60000 [==============================] - 11s 180us/sample - loss: 0.2205 - accuracy: 0.9357 - customLoss1: 4.3539 - customLoss2: 27.3819\nEpoch 2/5\n60000/60000 [==============================] - 11s 176us/sample - loss: 0.0967 - accuracy: 0.9701 - customLoss1: 4.3539 - customLoss2: 27.3892\nEpoch 3/5\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.0686 - accuracy: 0.9782 - customLoss1: 4.3539 - customLoss2: 27.3908\nEpoch 4/5\n60000/60000 [==============================] - 11s 178us/sample - loss: 0.0522 - accuracy: 0.9832 - customLoss1: 4.3539 - customLoss2: 27.3916\nEpoch 5/5\n60000/60000 [==============================] - 11s 180us/sample - loss: 0.0439 - accuracy: 0.9855 - customLoss1: 4.3539 - customLoss2: 27.3921\n10000/1 [================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================] - 1s 86us/sample - loss: 0.0310 - accuracy: 0.9815 - customLoss1: 4.3429 - customLoss2: 27.3310\nOriginal model, accuracy: 98.15%\n" ], [ "print(loss)", "0.10193580744992942\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
ecfcc5fa7d18593364e08aa0cb27039777622033
116,996
ipynb
Jupyter Notebook
08-02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb
tuhinsharma121/aws-sagemaker-quickstart
20183417d9b56f54c74cebc2e0475b9d70a993ea
[ "Apache-2.0" ]
null
null
null
08-02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb
tuhinsharma121/aws-sagemaker-quickstart
20183417d9b56f54c74cebc2e0475b9d70a993ea
[ "Apache-2.0" ]
null
null
null
08-02_Prepare_Dataset_BERT_Scikit_ScriptMode_FeatureStore.ipynb
tuhinsharma121/aws-sagemaker-quickstart
20183417d9b56f54c74cebc2e0475b9d70a993ea
[ "Apache-2.0" ]
null
null
null
49.013825
3,323
0.590294
[ [ [ "# Feature Transformation with Amazon a SageMaker Processing Job and Scikit-Learn\n\nIn this notebook, we convert raw text into BERT embeddings. This will allow us to perform natural language processing tasks such as text classification.\n\nTypically a machine learning (ML) process consists of few steps. First, gathering data with various ETL jobs, then pre-processing the data, featurizing the dataset by incorporating standard techniques or prior knowledge, and finally training an ML model using an algorithm.\n\nOften, distributed data processing frameworks such as Scikit-Learn are used to pre-process data sets in order to prepare them for training. In this notebook we'll use Amazon SageMaker Processing, and leverage the power of Scikit-Learn in a managed SageMaker environment to run our processing workload.", "_____no_output_____" ], [ "# NOTE: THIS NOTEBOOK WILL TAKE A 5-10 MINUTES TO COMPLETE.\n\n# PLEASE BE PATIENT.", "_____no_output_____" ], [ "## Contents\n\n1. Setup Environment\n1. Setup Input Data\n1. Setup Output Data\n1. Build a Scikit-Learn container for running the processing job\n1. Run the Processing Job using Amazon SageMaker\n1. Inspect the Processed Output Data", "_____no_output_____" ], [ "# Setup Environment\n\nLet's start by specifying:\n* The S3 bucket and prefixes that you use for training and model data. Use the default bucket specified by the Amazon SageMaker session.\n* The IAM role ARN used to give processing and training access to the dataset.", "_____no_output_____" ] ], [ [ "import sagemaker\nimport boto3\n\nsess = sagemaker.Session()\nrole = sagemaker.get_execution_role()\nbucket = sess.default_bucket()\nregion = boto3.Session().region_name\n\nsm = boto3.Session().client(service_name=\"sagemaker\", region_name=region)\ns3 = boto3.Session().client(service_name=\"s3\", region_name=region)", "_____no_output_____" ] ], [ [ "# Setup Input Data", "_____no_output_____" ] ], [ [ "%store -r s3_public_path_tsv", "_____no_output_____" ], [ "print(s3_public_path_tsv)", "s3://amazon-reviews-pds/tsv\n" ], [ "%store -r s3_private_path_tsv", "_____no_output_____" ], [ "print(s3_private_path_tsv)", "s3://sagemaker-us-east-1-117859797117/amazon-reviews-pds/tsv\n" ], [ "raw_input_data_s3_uri = \"s3://{}/amazon-reviews-pds/tsv/\".format(bucket)\nprint(raw_input_data_s3_uri)", "s3://sagemaker-us-east-1-117859797117/amazon-reviews-pds/tsv/\n" ], [ "!aws s3 ls $raw_input_data_s3_uri", "2021-04-12 14:57:24 18997559 amazon_reviews_us_Digital_Software_v1_00.tsv.gz\n2021-04-12 14:57:25 27442648 amazon_reviews_us_Digital_Video_Games_v1_00.tsv.gz\n2021-04-12 14:57:27 12134676 amazon_reviews_us_Gift_Card_v1_00.tsv.gz\n" ] ], [ [ "# Run the Processing Job using Amazon SageMaker\n\nNext, use the Amazon SageMaker Python SDK to submit a processing job using our custom python script.", "_____no_output_____" ], [ "# Review the Processing Script", "_____no_output_____" ] ], [ [ "!pygmentize preprocess-scikit-text-to-bert-feature-store.py", "\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36msklearn\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mmodel_selection\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m train_test_split\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36msklearn\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mutils\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m resample\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mfunctools\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mmultiprocessing\u001b[39;49;00m\n\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mdatetime\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m datetime\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mtime\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m gmtime, strftime, sleep\n\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msys\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mre\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mcollections\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36margparse\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mjson\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mos\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mcsv\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mglob\u001b[39;49;00m\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mpathlib\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m Path\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtime\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mboto3\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msubprocess\u001b[39;49;00m\n\n\u001b[37m## PIP INSTALLS ##\u001b[39;49;00m\n\u001b[37m# This is 2.3.0 (vs. 2.3.1 everywhere else) because we need to\u001b[39;49;00m\n\u001b[37m# use anaconda and anaconda only supports 2.3.0 at this time\u001b[39;49;00m\nsubprocess.check_call([sys.executable, \u001b[33m\"\u001b[39;49;00m\u001b[33m-m\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mconda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33minstall\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33m-c\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33manaconda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mtensorflow==2.3.0\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33m-y\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m])\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtensorflow\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mtf\u001b[39;49;00m\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mtensorflow\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m keras\n\nsubprocess.check_call([sys.executable, \u001b[33m\"\u001b[39;49;00m\u001b[33m-m\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mconda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33minstall\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33m-c\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mconda-forge\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mtransformers==3.5.1\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33m-y\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m])\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mtransformers\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m DistilBertTokenizer\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mtransformers\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m DistilBertConfig\n\nsubprocess.check_call([sys.executable, \u001b[33m\"\u001b[39;49;00m\u001b[33m-m\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mpip\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33minstall\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mmatplotlib==3.2.1\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m])\nsubprocess.check_call([sys.executable, \u001b[33m\"\u001b[39;49;00m\u001b[33m-m\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mpip\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33minstall\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33msagemaker==2.24.1\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m])\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpandas\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mpd\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mre\u001b[39;49;00m\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msagemaker\u001b[39;49;00m\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36msagemaker\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36msession\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m Session\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36msagemaker\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mfeature_store\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mfeature_group\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m FeatureGroup\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36msagemaker\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mfeature_store\u001b[39;49;00m\u001b[04m\u001b[36m.\u001b[39;49;00m\u001b[04m\u001b[36mfeature_definition\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m (\n FeatureDefinition,\n FeatureTypeEnum,\n)\n\nregion = os.environ[\u001b[33m\"\u001b[39;49;00m\u001b[33mAWS_DEFAULT_REGION\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]\n\u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mRegion: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(region))\n\n\u001b[37m#############################\u001b[39;49;00m\n\u001b[37m## We may need to get the Role and Bucket before setting sm, featurestore_runtime, etc.\u001b[39;49;00m\n\u001b[37m## Role and Bucket are malformed if we do this later.\u001b[39;49;00m\nsts = boto3.Session(region_name=region).client(service_name=\u001b[33m\"\u001b[39;49;00m\u001b[33msts\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, region_name=region)\n\ncaller_identity = sts.get_caller_identity()\n\u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mcaller_identity: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(caller_identity))\n\nassumed_role_arn = caller_identity[\u001b[33m\"\u001b[39;49;00m\u001b[33mArn\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]\n\u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33m(assumed_role) caller_identity_arn: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(assumed_role_arn))\n\nassumed_role_name = assumed_role_arn.split(\u001b[33m\"\u001b[39;49;00m\u001b[33m/\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)[-\u001b[34m2\u001b[39;49;00m]\n\niam = boto3.Session(region_name=region).client(service_name=\u001b[33m\"\u001b[39;49;00m\u001b[33miam\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, region_name=region)\nget_role_response = iam.get_role(RoleName=assumed_role_name)\n\u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mget_role_response \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(get_role_response))\nrole = get_role_response[\u001b[33m\"\u001b[39;49;00m\u001b[33mRole\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m][\u001b[33m\"\u001b[39;49;00m\u001b[33mArn\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]\n\u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mrole \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(role))\n\nbucket = sagemaker.Session().default_bucket()\n\u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mThe DEFAULT BUCKET is \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(bucket))\n\u001b[37m#############################\u001b[39;49;00m\n\nsm = boto3.Session(region_name=region).client(service_name=\u001b[33m\"\u001b[39;49;00m\u001b[33msagemaker\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, region_name=region)\n\nfeaturestore_runtime = boto3.Session(region_name=region).client(\n service_name=\u001b[33m\"\u001b[39;49;00m\u001b[33msagemaker-featurestore-runtime\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, region_name=region\n)\n\ns3 = boto3.Session(region_name=region).client(service_name=\u001b[33m\"\u001b[39;49;00m\u001b[33ms3\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, region_name=region)\n\nsagemaker_session = sagemaker.Session(\n boto_session=boto3.Session(region_name=region),\n sagemaker_client=sm,\n sagemaker_featurestore_runtime_client=featurestore_runtime,\n)\n\ntokenizer = DistilBertTokenizer.from_pretrained(\u001b[33m\"\u001b[39;49;00m\u001b[33mdistilbert-base-uncased\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\nREVIEW_BODY_COLUMN = \u001b[33m\"\u001b[39;49;00m\u001b[33mreview_body\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\nREVIEW_ID_COLUMN = \u001b[33m\"\u001b[39;49;00m\u001b[33mreview_id\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n\u001b[37m# DATE_COLUMN = 'date'\u001b[39;49;00m\n\nLABEL_COLUMN = \u001b[33m\"\u001b[39;49;00m\u001b[33mstar_rating\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\nLABEL_VALUES = [\u001b[34m1\u001b[39;49;00m, \u001b[34m2\u001b[39;49;00m, \u001b[34m3\u001b[39;49;00m, \u001b[34m4\u001b[39;49;00m, \u001b[34m5\u001b[39;49;00m]\n\nlabel_map = {}\n\u001b[34mfor\u001b[39;49;00m (i, label) \u001b[35min\u001b[39;49;00m \u001b[36menumerate\u001b[39;49;00m(LABEL_VALUES):\n label_map[label] = i\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mcast_object_to_string\u001b[39;49;00m(data_frame):\n \u001b[34mfor\u001b[39;49;00m label \u001b[35min\u001b[39;49;00m data_frame.columns:\n \u001b[34mif\u001b[39;49;00m data_frame.dtypes[label] == \u001b[33m\"\u001b[39;49;00m\u001b[33mobject\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m:\n data_frame[label] = data_frame[label].astype(\u001b[33m\"\u001b[39;49;00m\u001b[33mstr\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m).astype(\u001b[33m\"\u001b[39;49;00m\u001b[33mstring\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[34mreturn\u001b[39;49;00m data_frame\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mwait_for_feature_group_creation_complete\u001b[39;49;00m(feature_group):\n \u001b[34mtry\u001b[39;49;00m:\n status = feature_group.describe().get(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeatureGroupStatus\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeature Group status: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(status))\n \u001b[34mwhile\u001b[39;49;00m status == \u001b[33m\"\u001b[39;49;00m\u001b[33mCreating\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mWaiting for Feature Group Creation\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n time.sleep(\u001b[34m5\u001b[39;49;00m)\n status = feature_group.describe().get(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeatureGroupStatus\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeature Group status: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(status))\n \u001b[34mif\u001b[39;49;00m status != \u001b[33m\"\u001b[39;49;00m\u001b[33mCreated\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeature Group status: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(status))\n \u001b[34mraise\u001b[39;49;00m \u001b[36mRuntimeError\u001b[39;49;00m(\u001b[33mf\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\u001b[33mFailed to create feature group \u001b[39;49;00m\u001b[33m{feature_group.name}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(\u001b[33mf\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\u001b[33mFeatureGroup \u001b[39;49;00m\u001b[33m{feature_group.name}\u001b[39;49;00m\u001b[33m successfully created.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[34mexcept\u001b[39;49;00m:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mNo feature group created yet.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mcreate_or_load_feature_group\u001b[39;49;00m(prefix, feature_group_name):\n\n \u001b[37m# Feature Definitions for our records\u001b[39;49;00m\n feature_definitions = [\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33minput_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33minput_mask\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33msegment_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33mlabel_id\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.INTEGRAL),\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33mreview_id\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33mdate\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33mlabel\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.INTEGRAL),\n \u001b[37m# FeatureDefinition(feature_name='review_body', feature_type=FeatureTypeEnum.STRING),\u001b[39;49;00m\n FeatureDefinition(feature_name=\u001b[33m\"\u001b[39;49;00m\u001b[33msplit_type\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, feature_type=FeatureTypeEnum.STRING),\n ]\n\n feature_group = FeatureGroup(\n name=feature_group_name, feature_definitions=feature_definitions, sagemaker_session=sagemaker_session\n )\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeature Group: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(feature_group))\n\n \u001b[34mtry\u001b[39;49;00m:\n \u001b[36mprint\u001b[39;49;00m(\n \u001b[33m\"\u001b[39;49;00m\u001b[33mWaiting for existing Feature Group to become available if it is being created by another instance in our cluster...\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n )\n wait_for_feature_group_creation_complete(feature_group)\n \u001b[34mexcept\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m e:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mBefore CREATE FG wait exeption: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(e))\n \u001b[37m# pass\u001b[39;49;00m\n\n \u001b[34mtry\u001b[39;49;00m:\n record_identifier_feature_name = \u001b[33m\"\u001b[39;49;00m\u001b[33mreview_id\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n event_time_feature_name = \u001b[33m\"\u001b[39;49;00m\u001b[33mdate\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mCreating Feature Group with role \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m...\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(role))\n feature_group.create(\n s3_uri=\u001b[33mf\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\u001b[33ms3://\u001b[39;49;00m\u001b[33m{bucket}\u001b[39;49;00m\u001b[33m/\u001b[39;49;00m\u001b[33m{prefix}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n record_identifier_name=record_identifier_feature_name,\n event_time_feature_name=event_time_feature_name,\n role_arn=role,\n enable_online_store=\u001b[34mTrue\u001b[39;49;00m,\n )\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mCreating Feature Group. Completed.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mWaiting for new Feature Group to become available...\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n wait_for_feature_group_creation_complete(feature_group)\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeature Group available.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n feature_group.describe()\n\n \u001b[34mexcept\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m e:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mException: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(e))\n\n \u001b[34mreturn\u001b[39;49;00m feature_group\n\n\n\u001b[34mclass\u001b[39;49;00m \u001b[04m\u001b[32mInputFeatures\u001b[39;49;00m(\u001b[36mobject\u001b[39;49;00m):\n \u001b[33m\"\"\"BERT feature vectors.\"\"\"\u001b[39;49;00m\n\n \u001b[34mdef\u001b[39;49;00m \u001b[32m__init__\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, input_ids, input_mask, segment_ids, label_id, review_id, date, label):\n \u001b[37m# review_body):\u001b[39;49;00m\n \u001b[36mself\u001b[39;49;00m.input_ids = input_ids\n \u001b[36mself\u001b[39;49;00m.input_mask = input_mask\n \u001b[36mself\u001b[39;49;00m.segment_ids = segment_ids\n \u001b[36mself\u001b[39;49;00m.label_id = label_id\n \u001b[36mself\u001b[39;49;00m.review_id = review_id\n \u001b[36mself\u001b[39;49;00m.date = date\n \u001b[36mself\u001b[39;49;00m.label = label\n\n\n\u001b[37m# self.review_body = review_body\u001b[39;49;00m\n\n\n\u001b[34mclass\u001b[39;49;00m \u001b[04m\u001b[32mInput\u001b[39;49;00m(\u001b[36mobject\u001b[39;49;00m):\n \u001b[33m\"\"\"A single training/test input for sequence classification.\"\"\"\u001b[39;49;00m\n\n \u001b[34mdef\u001b[39;49;00m \u001b[32m__init__\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, text, review_id, date, label=\u001b[34mNone\u001b[39;49;00m):\n \u001b[33m\"\"\"Constructs an Input.\u001b[39;49;00m\n\u001b[33m Args:\u001b[39;49;00m\n\u001b[33m text: string. The untokenized text of the first sequence. For single\u001b[39;49;00m\n\u001b[33m sequence tasks, only this sequence must be specified.\u001b[39;49;00m\n\u001b[33m label: (Optional) string. The label of the example. This should be\u001b[39;49;00m\n\u001b[33m specified for train and dev examples, but not for test examples.\u001b[39;49;00m\n\u001b[33m \"\"\"\u001b[39;49;00m\n \u001b[36mself\u001b[39;49;00m.text = text\n \u001b[36mself\u001b[39;49;00m.review_id = review_id\n \u001b[36mself\u001b[39;49;00m.date = date\n \u001b[36mself\u001b[39;49;00m.label = label\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mconvert_input\u001b[39;49;00m(the_input, max_seq_length):\n \u001b[37m# First, we need to preprocess our data so that it matches the data BERT was trained on:\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n \u001b[37m# 1. Lowercase our text (if we're using a BERT lowercase model)\u001b[39;49;00m\n \u001b[37m# 2. Tokenize it (i.e. \"sally says hi\" -> [\"sally\", \"says\", \"hi\"])\u001b[39;49;00m\n \u001b[37m# 3. Break words into WordPieces (i.e. \"calling\" -> [\"call\", \"##ing\"])\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n \u001b[37m# Fortunately, the Transformers tokenizer does this for us!\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n tokens = tokenizer.tokenize(the_input.text)\n\n \u001b[37m# Next, we need to do the following:\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n \u001b[37m# 4. Map our words to indexes using a vocab file that BERT provides\u001b[39;49;00m\n \u001b[37m# 5. Add special \"CLS\" and \"SEP\" tokens (see the [readme](https://github.com/google-research/bert))\u001b[39;49;00m\n \u001b[37m# 6. Append \"index\" and \"segment\" tokens to each input (see the [BERT paper](https://arxiv.org/pdf/1810.04805.pdf))\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n \u001b[37m# Again, the Transformers tokenizer does this for us!\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n encode_plus_tokens = tokenizer.encode_plus(\n the_input.text,\n pad_to_max_length=\u001b[34mTrue\u001b[39;49;00m,\n max_length=max_seq_length,\n \u001b[37m# truncation=True\u001b[39;49;00m\n )\n\n \u001b[37m# The id from the pre-trained BERT vocabulary that represents the token. (Padding of 0 will be used if the # of tokens is less than `max_seq_length`)\u001b[39;49;00m\n input_ids = encode_plus_tokens[\u001b[33m\"\u001b[39;49;00m\u001b[33minput_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]\n\n \u001b[37m# Specifies which tokens BERT should pay attention to (0 or 1). Padded `input_ids` will have 0 in each of these vector elements.\u001b[39;49;00m\n input_mask = encode_plus_tokens[\u001b[33m\"\u001b[39;49;00m\u001b[33mattention_mask\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]\n\n \u001b[37m# Segment ids are always 0 for single-sequence tasks such as text classification. 1 is used for two-sequence tasks such as question/answer and next sentence prediction.\u001b[39;49;00m\n segment_ids = [\u001b[34m0\u001b[39;49;00m] * max_seq_length\n\n \u001b[37m# Label for each training row (`star_rating` 1 through 5)\u001b[39;49;00m\n label_id = label_map[the_input.label]\n\n features = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id,\n review_id=the_input.review_id,\n date=the_input.date,\n label=the_input.label,\n )\n \u001b[37m# review_body=the_input.text)\u001b[39;49;00m\n\n \u001b[37m# print('**input_ids**\\n{}\\n'.format(features.input_ids))\u001b[39;49;00m\n \u001b[37m# print('**input_mask**\\n{}\\n'.format(features.input_mask))\u001b[39;49;00m\n \u001b[37m# print('**segment_ids**\\n{}\\n'.format(features.segment_ids))\u001b[39;49;00m\n \u001b[37m# print('**label_id**\\n{}\\n'.format(features.label_id))\u001b[39;49;00m\n \u001b[37m# print('**review_id**\\n{}\\n'.format(features.review_id))\u001b[39;49;00m\n \u001b[37m# print('**date**\\n{}\\n'.format(features.date))\u001b[39;49;00m\n \u001b[37m# print('**label**\\n{}\\n'.format(features.label))\u001b[39;49;00m\n \u001b[37m# print('**review_body**\\n{}\\n'.format(features.review_body))\u001b[39;49;00m\n\n \u001b[34mreturn\u001b[39;49;00m features\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mtransform_inputs_to_tfrecord\u001b[39;49;00m(inputs, output_file, max_seq_length):\n \u001b[33m\"\"\"Convert a set of `Input`s to a TFRecord file.\"\"\"\u001b[39;49;00m\n\n records = []\n\n tf_record_writer = tf.io.TFRecordWriter(output_file)\n\n \u001b[34mfor\u001b[39;49;00m (input_idx, the_input) \u001b[35min\u001b[39;49;00m \u001b[36menumerate\u001b[39;49;00m(inputs):\n \u001b[34mif\u001b[39;49;00m input_idx % \u001b[34m10000\u001b[39;49;00m == \u001b[34m0\u001b[39;49;00m:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mWriting input \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m of \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\\n\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(input_idx, \u001b[36mlen\u001b[39;49;00m(inputs)))\n\n features = convert_input(the_input, max_seq_length)\n\n all_features = collections.OrderedDict()\n all_features[\u001b[33m\"\u001b[39;49;00m\u001b[33minput_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m] = tf.train.Feature(int64_list=tf.train.Int64List(value=features.input_ids))\n all_features[\u001b[33m\"\u001b[39;49;00m\u001b[33minput_mask\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m] = tf.train.Feature(int64_list=tf.train.Int64List(value=features.input_mask))\n all_features[\u001b[33m\"\u001b[39;49;00m\u001b[33msegment_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m] = tf.train.Feature(int64_list=tf.train.Int64List(value=features.segment_ids))\n all_features[\u001b[33m\"\u001b[39;49;00m\u001b[33mlabel_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m] = tf.train.Feature(int64_list=tf.train.Int64List(value=[features.label_id]))\n\n tf_record = tf.train.Example(features=tf.train.Features(feature=all_features))\n tf_record_writer.write(tf_record.SerializeToString())\n\n records.append(\n { \u001b[37m#'tf_record': tf_record.SerializeToString(),\u001b[39;49;00m\n \u001b[33m\"\u001b[39;49;00m\u001b[33minput_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: features.input_ids,\n \u001b[33m\"\u001b[39;49;00m\u001b[33minput_mask\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: features.input_mask,\n \u001b[33m\"\u001b[39;49;00m\u001b[33msegment_ids\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: features.segment_ids,\n \u001b[33m\"\u001b[39;49;00m\u001b[33mlabel_id\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: features.label_id,\n \u001b[33m\"\u001b[39;49;00m\u001b[33mreview_id\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: the_input.review_id,\n \u001b[33m\"\u001b[39;49;00m\u001b[33mdate\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: the_input.date,\n \u001b[33m\"\u001b[39;49;00m\u001b[33mlabel\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m: features.label,\n \u001b[37m# 'review_body': features.review_body\u001b[39;49;00m\n }\n )\n\n \u001b[37m#####################################\u001b[39;49;00m\n \u001b[37m####### TODO: REMOVE THIS BREAK #######\u001b[39;49;00m\n \u001b[37m#####################################\u001b[39;49;00m\n \u001b[37m# break\u001b[39;49;00m\n\n tf_record_writer.close()\n\n \u001b[34mreturn\u001b[39;49;00m records\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mlist_arg\u001b[39;49;00m(raw_value):\n \u001b[33m\"\"\"argparse type for a list of strings\"\"\"\u001b[39;49;00m\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mstr\u001b[39;49;00m(raw_value).split(\u001b[33m\"\u001b[39;49;00m\u001b[33m,\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mparse_args\u001b[39;49;00m():\n \u001b[37m# Unlike SageMaker training jobs (which have `SM_HOSTS` and `SM_CURRENT_HOST` env vars), processing jobs to need to parse the resource config file directly\u001b[39;49;00m\n resconfig = {}\n \u001b[34mtry\u001b[39;49;00m:\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33m/opt/ml/config/resourceconfig.json\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33mr\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m cfgfile:\n resconfig = json.load(cfgfile)\n \u001b[34mexcept\u001b[39;49;00m \u001b[36mFileNotFoundError\u001b[39;49;00m:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33m/opt/ml/config/resourceconfig.json not found. current_host is unknown.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[34mpass\u001b[39;49;00m \u001b[37m# Ignore\u001b[39;49;00m\n\n \u001b[37m# Local testing with CLI args\u001b[39;49;00m\n parser = argparse.ArgumentParser(description=\u001b[33m\"\u001b[39;49;00m\u001b[33mProcess\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--hosts\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=list_arg,\n default=resconfig.get(\u001b[33m\"\u001b[39;49;00m\u001b[33mhosts\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, [\u001b[33m\"\u001b[39;49;00m\u001b[33munknown\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]),\n help=\u001b[33m\"\u001b[39;49;00m\u001b[33mComma-separated list of host names running the job\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--current-host\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mstr\u001b[39;49;00m,\n default=resconfig.get(\u001b[33m\"\u001b[39;49;00m\u001b[33mcurrent_host\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[33m\"\u001b[39;49;00m\u001b[33munknown\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m),\n help=\u001b[33m\"\u001b[39;49;00m\u001b[33mName of this host running the job\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--input-data\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mstr\u001b[39;49;00m,\n default=\u001b[33m\"\u001b[39;49;00m\u001b[33m/opt/ml/processing/input/data\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--output-data\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mstr\u001b[39;49;00m,\n default=\u001b[33m\"\u001b[39;49;00m\u001b[33m/opt/ml/processing/output\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--train-split-percentage\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mfloat\u001b[39;49;00m,\n default=\u001b[34m0.90\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--validation-split-percentage\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mfloat\u001b[39;49;00m,\n default=\u001b[34m0.05\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--test-split-percentage\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mfloat\u001b[39;49;00m,\n default=\u001b[34m0.05\u001b[39;49;00m,\n )\n parser.add_argument(\u001b[33m\"\u001b[39;49;00m\u001b[33m--balance-dataset\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, \u001b[36mtype\u001b[39;49;00m=\u001b[36meval\u001b[39;49;00m, default=\u001b[34mTrue\u001b[39;49;00m)\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--max-seq-length\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mint\u001b[39;49;00m,\n default=\u001b[34m64\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--feature-store-offline-prefix\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mstr\u001b[39;49;00m,\n default=\u001b[34mNone\u001b[39;49;00m,\n )\n parser.add_argument(\n \u001b[33m\"\u001b[39;49;00m\u001b[33m--feature-group-name\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m,\n \u001b[36mtype\u001b[39;49;00m=\u001b[36mstr\u001b[39;49;00m,\n default=\u001b[34mNone\u001b[39;49;00m,\n )\n\n \u001b[34mreturn\u001b[39;49;00m parser.parse_args()\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32m_transform_tsv_to_tfrecord\u001b[39;49;00m(file, max_seq_length, balance_dataset, prefix, feature_group_name):\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mfile \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(file))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mmax_seq_length \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(max_seq_length))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mbalance_dataset \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(balance_dataset))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mprefix \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(prefix))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mfeature_group_name \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(feature_group_name))\n\n \u001b[37m# need to re-load since we can't pass feature_group object in _partial functions for some reason\u001b[39;49;00m\n feature_group = create_or_load_feature_group(prefix, feature_group_name)\n\n filename_without_extension = Path(Path(file).stem).stem\n\n df = pd.read_csv(file, delimiter=\u001b[33m\"\u001b[39;49;00m\u001b[33m\\t\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m, quoting=csv.QUOTE_NONE, compression=\u001b[33m\"\u001b[39;49;00m\u001b[33mgzip\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n df.isna().values.any()\n df = df.dropna()\n df = df.reset_index(drop=\u001b[34mTrue\u001b[39;49;00m)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mShape of dataframe \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(df.shape))\n\n \u001b[34mif\u001b[39;49;00m balance_dataset:\n \u001b[37m# Balance the dataset down to the minority class\u001b[39;49;00m\n df_grouped_by = df.groupby([\u001b[33m\"\u001b[39;49;00m\u001b[33mstar_rating\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]) \n df_balanced = df_grouped_by.apply(\u001b[34mlambda\u001b[39;49;00m x: x.sample(df_grouped_by.size().min()).reset_index(drop=\u001b[34mTrue\u001b[39;49;00m))\n\n df_balanced = df_balanced.reset_index(drop=\u001b[34mTrue\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mShape of balanced dataframe \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(df_balanced.shape))\n \n \u001b[36mprint\u001b[39;49;00m(df_balanced[\u001b[33m\"\u001b[39;49;00m\u001b[33mstar_rating\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m].head(\u001b[34m100\u001b[39;49;00m))\n\n df = df_balanced\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mShape of dataframe before splitting \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(df.shape))\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mtrain split percentage \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.train_split_percentage))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mvalidation split percentage \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.validation_split_percentage))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mtest split percentage \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.test_split_percentage))\n\n holdout_percentage = \u001b[34m1.00\u001b[39;49;00m - args.train_split_percentage\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mholdout percentage \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(holdout_percentage))\n \n df_train, df_holdout = train_test_split(df, test_size=holdout_percentage, stratify=df[\u001b[33m\"\u001b[39;49;00m\u001b[33mstar_rating\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m])\n\n test_holdout_percentage = args.test_split_percentage / holdout_percentage\n \n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mtest holdout percentage \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(test_holdout_percentage))\n \n df_validation, df_test = train_test_split(\n df_holdout, test_size=test_holdout_percentage, stratify=df_holdout[\u001b[33m\"\u001b[39;49;00m\u001b[33mstar_rating\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m])\n\n df_train = df_train.reset_index(drop=\u001b[34mTrue\u001b[39;49;00m)\n df_validation = df_validation.reset_index(drop=\u001b[34mTrue\u001b[39;49;00m)\n df_test = df_test.reset_index(drop=\u001b[34mTrue\u001b[39;49;00m)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mShape of train dataframe \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(df_train.shape))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mShape of validation dataframe \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(df_validation.shape))\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mShape of test dataframe \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(df_test.shape))\n\n timestamp = datetime.now().strftime(\u001b[33m\"\u001b[39;49;00m\u001b[33m%\u001b[39;49;00m\u001b[33mY-\u001b[39;49;00m\u001b[33m%\u001b[39;49;00m\u001b[33mm-\u001b[39;49;00m\u001b[33m%d\u001b[39;49;00m\u001b[33mT\u001b[39;49;00m\u001b[33m%\u001b[39;49;00m\u001b[33mH:\u001b[39;49;00m\u001b[33m%\u001b[39;49;00m\u001b[33mM:\u001b[39;49;00m\u001b[33m%\u001b[39;49;00m\u001b[33mSZ\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(timestamp)\n\n train_inputs = df_train.apply(\n \u001b[34mlambda\u001b[39;49;00m x: Input(\n label=x[LABEL_COLUMN], text=x[REVIEW_BODY_COLUMN], review_id=x[REVIEW_ID_COLUMN], date=timestamp\n ),\n axis=\u001b[34m1\u001b[39;49;00m,\n )\n\n validation_inputs = df_validation.apply(\n \u001b[34mlambda\u001b[39;49;00m x: Input(\n label=x[LABEL_COLUMN], text=x[REVIEW_BODY_COLUMN], review_id=x[REVIEW_ID_COLUMN], date=timestamp\n ),\n axis=\u001b[34m1\u001b[39;49;00m,\n )\n\n test_inputs = df_test.apply(\n \u001b[34mlambda\u001b[39;49;00m x: Input(\n label=x[LABEL_COLUMN], text=x[REVIEW_BODY_COLUMN], review_id=x[REVIEW_ID_COLUMN], date=timestamp\n ),\n axis=\u001b[34m1\u001b[39;49;00m,\n )\n\n \u001b[37m# Next, we need to preprocess our data so that it matches the data BERT was trained on. For this, we'll need to do a couple of things (but don't worry--this is also included in the Python library):\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n \u001b[37m# 1. Lowercase our text (if we're using a BERT lowercase model)\u001b[39;49;00m\n \u001b[37m# 2. Tokenize it (i.e. \"sally says hi\" -> [\"sally\", \"says\", \"hi\"])\u001b[39;49;00m\n \u001b[37m# 3. Break words into WordPieces (i.e. \"calling\" -> [\"call\", \"##ing\"])\u001b[39;49;00m\n \u001b[37m# 4. Map our words to indexes using a vocab file that BERT provides\u001b[39;49;00m\n \u001b[37m# 5. Add special \"CLS\" and \"SEP\" tokens (see the [readme](https://github.com/google-research/bert))\u001b[39;49;00m\n \u001b[37m# 6. Append \"index\" and \"segment\" tokens to each input (see the [BERT paper](https://arxiv.org/pdf/1810.04805.pdf))\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n \u001b[37m# We don't have to worry about these details. The Transformers tokenizer does this for us.\u001b[39;49;00m\n \u001b[37m#\u001b[39;49;00m\n train_data = \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/bert/train\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.output_data)\n validation_data = \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/bert/validation\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.output_data)\n test_data = \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/bert/test\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.output_data)\n\n \u001b[37m# Convert our train and validation features to InputFeatures (.tfrecord protobuf) that works with BERT and TensorFlow.\u001b[39;49;00m\n train_records = transform_inputs_to_tfrecord(\n train_inputs,\n \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/part-\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m-\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m.tfrecord\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(train_data, args.current_host, filename_without_extension),\n max_seq_length,\n )\n\n validation_records = transform_inputs_to_tfrecord(\n validation_inputs,\n \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/part-\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m-\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m.tfrecord\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(validation_data, args.current_host, filename_without_extension),\n max_seq_length,\n )\n\n test_records = transform_inputs_to_tfrecord(\n test_inputs,\n \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/part-\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m-\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m.tfrecord\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(test_data, args.current_host, filename_without_extension),\n max_seq_length,\n )\n\n df_train_records = pd.DataFrame.from_dict(train_records)\n df_train_records[\u001b[33m\"\u001b[39;49;00m\u001b[33msplit_type\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m] = \u001b[33m\"\u001b[39;49;00m\u001b[33mtrain\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n df_train_records.head()\n\n df_validation_records = pd.DataFrame.from_dict(validation_records)\n df_validation_records[\u001b[33m\"\u001b[39;49;00m\u001b[33msplit_type\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m] = \u001b[33m\"\u001b[39;49;00m\u001b[33mvalidation\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n df_validation_records.head()\n\n df_test_records = pd.DataFrame.from_dict(test_records)\n df_test_records[\u001b[33m\"\u001b[39;49;00m\u001b[33msplit_type\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m] = \u001b[33m\"\u001b[39;49;00m\u001b[33mtest\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m\n df_test_records.head()\n\n \u001b[37m# Add record to feature store\u001b[39;49;00m\n df_fs_train_records = cast_object_to_string(df_train_records)\n df_fs_validation_records = cast_object_to_string(df_validation_records)\n df_fs_test_records = cast_object_to_string(df_test_records)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mIngesting Features...\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n feature_group.ingest(data_frame=df_fs_train_records, max_workers=\u001b[34m3\u001b[39;49;00m, wait=\u001b[34mTrue\u001b[39;49;00m)\n feature_group.ingest(data_frame=df_fs_validation_records, max_workers=\u001b[34m3\u001b[39;49;00m, wait=\u001b[34mTrue\u001b[39;49;00m)\n feature_group.ingest(data_frame=df_fs_test_records, max_workers=\u001b[34m3\u001b[39;49;00m, wait=\u001b[34mTrue\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mFeature ingest completed.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n\n\u001b[34mdef\u001b[39;49;00m \u001b[32mprocess\u001b[39;49;00m(args):\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mCurrent host: \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.current_host))\n\n feature_group = create_or_load_feature_group(\n prefix=args.feature_store_offline_prefix, feature_group_name=args.feature_group_name\n )\n\n feature_group.describe()\n\n \u001b[36mprint\u001b[39;49;00m(feature_group.as_hive_ddl())\n\n train_data = \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/bert/train\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.output_data)\n validation_data = \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/bert/validation\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.output_data)\n test_data = \u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/bert/test\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.output_data)\n\n transform_tsv_to_tfrecord = functools.partial(\n _transform_tsv_to_tfrecord,\n max_seq_length=args.max_seq_length,\n balance_dataset=args.balance_dataset,\n prefix=args.feature_store_offline_prefix,\n feature_group_name=args.feature_group_name,\n )\n\n input_files = glob.glob(\u001b[33m\"\u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m/*.tsv.gz\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.input_data))\n\n num_cpus = multiprocessing.cpu_count()\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mnum_cpus \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(num_cpus))\n\n p = multiprocessing.Pool(num_cpus)\n p.map(transform_tsv_to_tfrecord, input_files)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mListing contents of \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(args.output_data))\n dirs_output = os.listdir(args.output_data)\n \u001b[34mfor\u001b[39;49;00m file \u001b[35min\u001b[39;49;00m dirs_output:\n \u001b[36mprint\u001b[39;49;00m(file)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mListing contents of \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(train_data))\n dirs_output = os.listdir(train_data)\n \u001b[34mfor\u001b[39;49;00m file \u001b[35min\u001b[39;49;00m dirs_output:\n \u001b[36mprint\u001b[39;49;00m(file)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mListing contents of \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(validation_data))\n dirs_output = os.listdir(validation_data)\n \u001b[34mfor\u001b[39;49;00m file \u001b[35min\u001b[39;49;00m dirs_output:\n \u001b[36mprint\u001b[39;49;00m(file)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mListing contents of \u001b[39;49;00m\u001b[33m{}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(test_data))\n dirs_output = os.listdir(test_data)\n \u001b[34mfor\u001b[39;49;00m file \u001b[35min\u001b[39;49;00m dirs_output:\n \u001b[36mprint\u001b[39;49;00m(file)\n\n offline_store_contents = \u001b[34mNone\u001b[39;49;00m\n \u001b[34mwhile\u001b[39;49;00m offline_store_contents \u001b[35mis\u001b[39;49;00m \u001b[34mNone\u001b[39;49;00m:\n objects_in_bucket = s3.list_objects(Bucket=bucket, Prefix=args.feature_store_offline_prefix)\n \u001b[34mif\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mContents\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[35min\u001b[39;49;00m objects_in_bucket \u001b[35mand\u001b[39;49;00m \u001b[36mlen\u001b[39;49;00m(objects_in_bucket[\u001b[33m\"\u001b[39;49;00m\u001b[33mContents\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]) > \u001b[34m1\u001b[39;49;00m:\n offline_store_contents = objects_in_bucket[\u001b[33m\"\u001b[39;49;00m\u001b[33mContents\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m]\n \u001b[34melse\u001b[39;49;00m:\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mWaiting for data in offline store...\u001b[39;49;00m\u001b[33m\\n\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n sleep(\u001b[34m60\u001b[39;49;00m)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mData available.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mComplete\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n\n\n\u001b[34mif\u001b[39;49;00m \u001b[31m__name__\u001b[39;49;00m == \u001b[33m\"\u001b[39;49;00m\u001b[33m__main__\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m:\n args = parse_args()\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mLoaded arguments:\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(args)\n\n \u001b[36mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mEnvironment variables:\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\n \u001b[36mprint\u001b[39;49;00m(os.environ)\n\n process(args)\n" ] ], [ [ "Run this script as a processing job. You also need to specify one `ProcessingInput` with the `source` argument of the Amazon S3 bucket and `destination` is where the script reads this data from `/opt/ml/processing/input` (inside the Docker container.) All local paths inside the processing container must begin with `/opt/ml/processing/`.\n\nAlso give the `run()` method a `ProcessingOutput`, where the `source` is the path the script writes output data to. For outputs, the `destination` defaults to an S3 bucket that the Amazon SageMaker Python SDK creates for you, following the format `s3://sagemaker-<region>-<account_id>/<processing_job_name>/output/<output_name>/`. You also give the `ProcessingOutput` value for `output_name`, to make it easier to retrieve these output artifacts after the job is run.\n\nThe arguments parameter in the `run()` method are command-line arguments in our `preprocess-scikit-text-to-bert-feature-store.py` script.\n\nNote that we sharding the data using `ShardedByS3Key` to spread the transformations across all worker nodes in the cluster.", "_____no_output_____" ], [ "# Track the `Experiment`\nWe will track every step of this experiment throughout the `prepare`, `train`, `optimize`, and `deploy`.", "_____no_output_____" ], [ "# Concepts\n\n**Experiment**: A collection of related Trials. Add Trials to an Experiment that you wish to compare together.\n\n**Trial**: A description of a multi-step machine learning workflow. Each step in the workflow is described by a Trial Component. There is no relationship between Trial Components such as ordering.\n\n**Trial Component**: A description of a single step in a machine learning workflow. For example data cleaning, feature extraction, model training, model evaluation, etc.\n\n**Tracker**: A logger of information about a single TrialComponent.\n", "_____no_output_____" ], [ "# Create the `Experiment`", "_____no_output_____" ] ], [ [ "import time\nfrom smexperiments.experiment import Experiment\n\ntimestamp = int(time.time())\n\nexperiment = Experiment.create(\n experiment_name=\"Amazon-Customer-Reviews-BERT-Experiment-{}\".format(timestamp),\n description=\"Amazon Customer Reviews BERT Experiment\",\n sagemaker_boto_client=sm,\n)\n\nexperiment_name = experiment.experiment_name\nprint(\"Experiment name: {}\".format(experiment_name))", "Experiment name: Amazon-Customer-Reviews-BERT-Experiment-1618387082\n" ] ], [ [ "# Create the `Trial`", "_____no_output_____" ] ], [ [ "import time\nfrom smexperiments.trial import Trial\n\ntimestamp = int(time.time())\n\ntrial = Trial.create(\n trial_name=\"trial-{}\".format(timestamp), experiment_name=experiment_name, sagemaker_boto_client=sm\n)\n\ntrial_name = trial.trial_name\nprint(\"Trial name: {}\".format(trial_name))", "Trial name: trial-1618387082\n" ] ], [ [ "# Create the `Experiment Config`", "_____no_output_____" ] ], [ [ "experiment_config = {\n \"ExperimentName\": experiment_name,\n \"TrialName\": trial_name,\n \"TrialComponentDisplayName\": \"prepare\",\n}", "_____no_output_____" ], [ "print(experiment_name)", "Amazon-Customer-Reviews-BERT-Experiment-1618387082\n" ], [ "%store experiment_name", "Stored 'experiment_name' (str)\n" ], [ "print(trial_name)", "trial-1618387082\n" ], [ "%store trial_name", "Stored 'trial_name' (str)\n" ] ], [ [ "# Create Feature Store and Feature Group", "_____no_output_____" ] ], [ [ "featurestore_runtime = boto3.Session().client(service_name=\"sagemaker-featurestore-runtime\", region_name=region)", "_____no_output_____" ], [ "timestamp = int(time.time())\n\nfeature_store_offline_prefix = \"reviews-feature-store-\" + str(timestamp)\n\nprint(feature_store_offline_prefix)", "reviews-feature-store-1618387082\n" ], [ "feature_group_name = \"reviews-feature-group-\" + str(timestamp)\n\nprint(feature_group_name)", "reviews-feature-group-1618387082\n" ], [ "from sagemaker.feature_store.feature_definition import (\n FeatureDefinition,\n FeatureTypeEnum,\n)\n\nfeature_definitions = [\n FeatureDefinition(feature_name=\"input_ids\", feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\"input_mask\", feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\"segment_ids\", feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\"label_id\", feature_type=FeatureTypeEnum.INTEGRAL),\n FeatureDefinition(feature_name=\"review_id\", feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\"date\", feature_type=FeatureTypeEnum.STRING),\n FeatureDefinition(feature_name=\"label\", feature_type=FeatureTypeEnum.INTEGRAL),\n # FeatureDefinition(feature_name='review_body', feature_type=FeatureTypeEnum.STRING)\n]", "_____no_output_____" ], [ "from sagemaker.feature_store.feature_group import FeatureGroup\n\nfeature_group = FeatureGroup(name=feature_group_name, feature_definitions=feature_definitions, sagemaker_session=sess)\n\nprint(feature_group)", "FeatureGroup(name='reviews-feature-group-1618387082', sagemaker_session=<sagemaker.session.Session object at 0x7f325c027890>, feature_definitions=[FeatureDefinition(feature_name='input_ids', feature_type=<FeatureTypeEnum.STRING: 'String'>), FeatureDefinition(feature_name='input_mask', feature_type=<FeatureTypeEnum.STRING: 'String'>), FeatureDefinition(feature_name='segment_ids', feature_type=<FeatureTypeEnum.STRING: 'String'>), FeatureDefinition(feature_name='label_id', feature_type=<FeatureTypeEnum.INTEGRAL: 'Integral'>), FeatureDefinition(feature_name='review_id', feature_type=<FeatureTypeEnum.STRING: 'String'>), FeatureDefinition(feature_name='date', feature_type=<FeatureTypeEnum.STRING: 'String'>), FeatureDefinition(feature_name='label', feature_type=<FeatureTypeEnum.INTEGRAL: 'Integral'>)])\n" ] ], [ [ "# Set the Processing Job Hyper-Parameters ", "_____no_output_____" ] ], [ [ "processing_instance_type = \"ml.c5.2xlarge\"\nprocessing_instance_count = 2\ntrain_split_percentage = 0.90\nvalidation_split_percentage = 0.05\ntest_split_percentage = 0.05\nbalance_dataset = True\nmax_seq_length = 64", "_____no_output_____" ] ], [ [ "# Choosing a `max_seq_length` for BERT\nSince a smaller `max_seq_length` leads to faster training and lower resource utilization, we want to find the smallest review length that captures `80%` of our reviews.\n\nRemember our distribution of review lengths from a previous section?\n\n```\nmean 51.683405\nstd 107.030844\nmin 1.000000\n10% 2.000000\n20% 7.000000\n30% 19.000000\n40% 22.000000\n50% 26.000000\n60% 32.000000\n70% 43.000000\n80% 63.000000\n90% 110.000000\n100% 5347.000000\nmax 5347.000000\n```\n\n\nReview length `63` represents the `80th` percentile for this dataset. However, it's best to stick with powers-of-2 when using BERT. So let's choose `64` as this is the smallest power-of-2 greater than `63`. Reviews with length > `64` will be truncated to `64`.", "_____no_output_____" ] ], [ [ "from sagemaker.sklearn.processing import SKLearnProcessor\n\nprocessor = SKLearnProcessor(\n framework_version=\"0.23-1\",\n role=role,\n instance_type=processing_instance_type,\n instance_count=processing_instance_count,\n env={\"AWS_DEFAULT_REGION\": region},\n max_runtime_in_seconds=7200,\n)", "INFO:sagemaker.image_uris:Same images used for training and inference. Defaulting to image scope: inference.\nINFO:sagemaker.image_uris:Defaulting to only available Python version: py3\n" ], [ "from sagemaker.processing import ProcessingInput, ProcessingOutput\n\nprocessor.run(\n code=\"preprocess-scikit-text-to-bert-feature-store.py\",\n inputs=[\n ProcessingInput(\n input_name=\"raw-input-data\",\n source=raw_input_data_s3_uri,\n destination=\"/opt/ml/processing/input/data/\",\n s3_data_distribution_type=\"ShardedByS3Key\",\n )\n ],\n outputs=[\n ProcessingOutput(\n output_name=\"bert-train\", s3_upload_mode=\"EndOfJob\", source=\"/opt/ml/processing/output/bert/train\"\n ),\n ProcessingOutput(\n output_name=\"bert-validation\",\n s3_upload_mode=\"EndOfJob\",\n source=\"/opt/ml/processing/output/bert/validation\",\n ),\n ProcessingOutput(\n output_name=\"bert-test\", s3_upload_mode=\"EndOfJob\", source=\"/opt/ml/processing/output/bert/test\"\n ),\n ],\n arguments=[\n \"--train-split-percentage\",\n str(train_split_percentage),\n \"--validation-split-percentage\",\n str(validation_split_percentage),\n \"--test-split-percentage\",\n str(test_split_percentage),\n \"--max-seq-length\",\n str(max_seq_length),\n \"--balance-dataset\",\n str(balance_dataset),\n \"--feature-store-offline-prefix\",\n str(feature_store_offline_prefix),\n \"--feature-group-name\",\n str(feature_group_name),\n ],\n experiment_config=experiment_config,\n logs=True,\n wait=False,\n)", "INFO:sagemaker:Creating processing-job with name sagemaker-scikit-learn-2021-04-14-07-58-05-034\n" ], [ "scikit_processing_job_name = processor.jobs[-1].describe()[\"ProcessingJobName\"]\nprint(scikit_processing_job_name)", "sagemaker-scikit-learn-2021-04-14-07-58-05-034\n" ], [ "from IPython.core.display import display, HTML\n\ndisplay(\n HTML(\n '<b>Review <a target=\"blank\" href=\"https://console.aws.amazon.com/sagemaker/home?region={}#/processing-jobs/{}\">Processing Job</a></b>'.format(\n region, scikit_processing_job_name\n )\n )\n)", "_____no_output_____" ], [ "from IPython.core.display import display, HTML\n\ndisplay(\n HTML(\n '<b>Review <a target=\"blank\" href=\"https://console.aws.amazon.com/cloudwatch/home?region={}#logStream:group=/aws/sagemaker/ProcessingJobs;prefix={};streamFilter=typeLogStreamPrefix\">CloudWatch Logs</a> After About 5 Minutes</b>'.format(\n region, scikit_processing_job_name\n )\n )\n)", "_____no_output_____" ], [ "from IPython.core.display import display, HTML\n\ndisplay(\n HTML(\n '<b>Review <a target=\"blank\" href=\"https://s3.console.aws.amazon.com/s3/buckets/{}/{}/?region={}&tab=overview\">S3 Output Data</a> After The Processing Job Has Completed</b>'.format(\n bucket, scikit_processing_job_name, region\n )\n )\n)", "_____no_output_____" ] ], [ [ "# Monitor the Processing Job", "_____no_output_____" ] ], [ [ "running_processor = sagemaker.processing.ProcessingJob.from_processing_name(\n processing_job_name=scikit_processing_job_name, sagemaker_session=sess\n)\n\nprocessing_job_description = running_processor.describe()\n\nprint(processing_job_description)", "{'ProcessingInputs': [{'InputName': 'raw-input-data', 'AppManaged': False, 'S3Input': {'S3Uri': 's3://sagemaker-us-east-1-117859797117/amazon-reviews-pds/tsv/', 'LocalPath': '/opt/ml/processing/input/data/', 'S3DataType': 'S3Prefix', 'S3InputMode': 'File', 'S3DataDistributionType': 'ShardedByS3Key', 'S3CompressionType': 'None'}}, {'InputName': 'code', 'AppManaged': False, 'S3Input': {'S3Uri': 's3://sagemaker-us-east-1-117859797117/sagemaker-scikit-learn-2021-04-14-07-58-05-034/input/code/preprocess-scikit-text-to-bert-feature-store.py', 'LocalPath': '/opt/ml/processing/input/code', 'S3DataType': 'S3Prefix', 'S3InputMode': 'File', 'S3DataDistributionType': 'FullyReplicated', 'S3CompressionType': 'None'}}], 'ProcessingOutputConfig': {'Outputs': [{'OutputName': 'bert-train', 'S3Output': {'S3Uri': 's3://sagemaker-us-east-1-117859797117/sagemaker-scikit-learn-2021-04-14-07-58-05-034/output/bert-train', 'LocalPath': '/opt/ml/processing/output/bert/train', 'S3UploadMode': 'EndOfJob'}, 'AppManaged': False}, {'OutputName': 'bert-validation', 'S3Output': {'S3Uri': 's3://sagemaker-us-east-1-117859797117/sagemaker-scikit-learn-2021-04-14-07-58-05-034/output/bert-validation', 'LocalPath': '/opt/ml/processing/output/bert/validation', 'S3UploadMode': 'EndOfJob'}, 'AppManaged': False}, {'OutputName': 'bert-test', 'S3Output': {'S3Uri': 's3://sagemaker-us-east-1-117859797117/sagemaker-scikit-learn-2021-04-14-07-58-05-034/output/bert-test', 'LocalPath': '/opt/ml/processing/output/bert/test', 'S3UploadMode': 'EndOfJob'}, 'AppManaged': False}]}, 'ProcessingJobName': 'sagemaker-scikit-learn-2021-04-14-07-58-05-034', 'ProcessingResources': {'ClusterConfig': {'InstanceCount': 2, 'InstanceType': 'ml.c5.2xlarge', 'VolumeSizeInGB': 30}}, 'StoppingCondition': {'MaxRuntimeInSeconds': 7200}, 'AppSpecification': {'ImageUri': '683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-scikit-learn:0.23-1-cpu-py3', 'ContainerEntrypoint': ['python3', '/opt/ml/processing/input/code/preprocess-scikit-text-to-bert-feature-store.py'], 'ContainerArguments': ['--train-split-percentage', '0.9', '--validation-split-percentage', '0.05', '--test-split-percentage', '0.05', '--max-seq-length', '64', '--balance-dataset', 'True', '--feature-store-offline-prefix', 'reviews-feature-store-1618387082', '--feature-group-name', 'reviews-feature-group-1618387082']}, 'Environment': {'AWS_DEFAULT_REGION': 'us-east-1'}, 'RoleArn': 'arn:aws:iam::117859797117:role/service-role/AmazonSageMakerServiceCatalogProductsUseRole', 'ExperimentConfig': {'ExperimentName': 'Amazon-Customer-Reviews-BERT-Experiment-1618387082', 'TrialName': 'trial-1618387082', 'TrialComponentDisplayName': 'prepare'}, 'ProcessingJobArn': 'arn:aws:sagemaker:us-east-1:117859797117:processing-job/sagemaker-scikit-learn-2021-04-14-07-58-05-034', 'ProcessingJobStatus': 'InProgress', 'LastModifiedTime': datetime.datetime(2021, 4, 14, 7, 58, 6, 21000, tzinfo=tzlocal()), 'CreationTime': datetime.datetime(2021, 4, 14, 7, 58, 5, 526000, tzinfo=tzlocal()), 'ResponseMetadata': {'RequestId': '11ef795f-a801-4810-b6eb-153ae9f3506d', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '11ef795f-a801-4810-b6eb-153ae9f3506d', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2979', 'date': 'Wed, 14 Apr 2021 07:58:06 GMT'}, 'RetryAttempts': 0}}\n" ], [ "running_processor.wait(logs=False)", "........................................................................................................................................!" ] ], [ [ "# _Please Wait Until the ^^ Processing Job ^^ Completes Above._", "_____no_output_____" ], [ "# Inspect the Processed Output Data\n\nTake a look at a few rows of the transformed dataset to make sure the processing was successful.", "_____no_output_____" ] ], [ [ "processing_job_description = running_processor.describe()\n\noutput_config = processing_job_description[\"ProcessingOutputConfig\"]\nfor output in output_config[\"Outputs\"]:\n if output[\"OutputName\"] == \"bert-train\":\n processed_train_data_s3_uri = output[\"S3Output\"][\"S3Uri\"]\n if output[\"OutputName\"] == \"bert-validation\":\n processed_validation_data_s3_uri = output[\"S3Output\"][\"S3Uri\"]\n if output[\"OutputName\"] == \"bert-test\":\n processed_test_data_s3_uri = output[\"S3Output\"][\"S3Uri\"]\n\nprint(processed_train_data_s3_uri)\nprint(processed_validation_data_s3_uri)\nprint(processed_test_data_s3_uri)", "s3://sagemaker-us-east-1-117859797117/sagemaker-scikit-learn-2021-04-14-07-58-05-034/output/bert-train\ns3://sagemaker-us-east-1-117859797117/sagemaker-scikit-learn-2021-04-14-07-58-05-034/output/bert-validation\ns3://sagemaker-us-east-1-117859797117/sagemaker-scikit-learn-2021-04-14-07-58-05-034/output/bert-test\n" ], [ "!aws s3 ls $processed_train_data_s3_uri/", "2021-04-14 08:08:56 10482080 part-algo-1-amazon_reviews_us_Digital_Software_v1_00.tfrecord\n2021-04-14 08:08:56 2315998 part-algo-1-amazon_reviews_us_Gift_Card_v1_00.tfrecord\n2021-04-14 08:09:21 11711725 part-algo-2-amazon_reviews_us_Digital_Video_Games_v1_00.tfrecord\n" ], [ "!aws s3 ls $processed_validation_data_s3_uri/", "2021-04-14 08:08:56 582264 part-algo-1-amazon_reviews_us_Digital_Software_v1_00.tfrecord\n2021-04-14 08:08:56 128660 part-algo-1-amazon_reviews_us_Gift_Card_v1_00.tfrecord\n2021-04-14 08:09:21 650265 part-algo-2-amazon_reviews_us_Digital_Video_Games_v1_00.tfrecord\n" ], [ "!aws s3 ls $processed_test_data_s3_uri/", "2021-04-14 08:08:56 582706 part-algo-1-amazon_reviews_us_Digital_Software_v1_00.tfrecord\n2021-04-14 08:08:56 129538 part-algo-1-amazon_reviews_us_Gift_Card_v1_00.tfrecord\n2021-04-14 08:09:21 650953 part-algo-2-amazon_reviews_us_Digital_Video_Games_v1_00.tfrecord\n" ] ], [ [ "# Pass Variables to the Next Notebook(s)", "_____no_output_____" ] ], [ [ "%store raw_input_data_s3_uri", "Stored 'raw_input_data_s3_uri' (str)\n" ], [ "%store max_seq_length", "Stored 'max_seq_length' (int)\n" ], [ "%store train_split_percentage", "Stored 'train_split_percentage' (float)\n" ], [ "%store validation_split_percentage", "Stored 'validation_split_percentage' (float)\n" ], [ "%store test_split_percentage", "Stored 'test_split_percentage' (float)\n" ], [ "%store balance_dataset", "Stored 'balance_dataset' (bool)\n" ], [ "%store feature_store_offline_prefix", "Stored 'feature_store_offline_prefix' (str)\n" ], [ "%store feature_group_name", "Stored 'feature_group_name' (str)\n" ], [ "%store processed_train_data_s3_uri", "Stored 'processed_train_data_s3_uri' (str)\n" ], [ "%store processed_validation_data_s3_uri", "Stored 'processed_validation_data_s3_uri' (str)\n" ], [ "%store processed_test_data_s3_uri", "Stored 'processed_test_data_s3_uri' (str)\n" ], [ "%store", "Stored variables and their in-db values:\nbalance_dataset -> True\nbalanced_bias_data_jsonlines_s3_uri -> 's3://sagemaker-us-east-1-117859797117/bias-detect\nbalanced_bias_data_s3_uri -> 's3://sagemaker-us-east-1-117859797117/bias-detect\nbias_data_s3_uri -> 's3://sagemaker-us-east-1-117859797117/bias-detect\nexperiment_name -> 'Amazon-Customer-Reviews-BERT-Experiment-161838708\nfeature_group_name -> 'reviews-feature-group-1618387082'\nfeature_store_offline_prefix -> 'reviews-feature-store-1618387082'\ningest_create_athena_db_passed -> True\ningest_create_athena_table_parquet_passed -> True\ningest_create_athena_table_tsv_passed -> True\nmax_seq_length -> 64\nmodel_ab_endpoint_name -> 'tensorflow-training-2021-04-05-11-23-57-968-abtes\nprocessed_metrics_s3_uri -> 's3://sagemaker-us-east-1-117859797117/sagemaker-s\nprocessed_test_data_s3_uri -> 's3://sagemaker-us-east-1-117859797117/sagemaker-s\nprocessed_train_data_s3_uri -> 's3://sagemaker-us-east-1-117859797117/sagemaker-s\nprocessed_validation_data_s3_uri -> 's3://sagemaker-us-east-1-117859797117/sagemaker-s\nprocessing_evaluation_metrics_job_name -> 'sagemaker-scikit-learn-2021-04-05-13-42-30-315'\nraw_input_data_s3_uri -> 's3://sagemaker-us-east-1-117859797117/amazon-revi\ns3_private_path_tsv -> 's3://sagemaker-us-east-1-117859797117/amazon-revi\ns3_public_path_tsv -> 's3://amazon-reviews-pds/tsv'\nsetup_dependencies_passed -> True\ntensorflow_endpoint_arn -> 'arn:aws:sagemaker:us-east-1:117859797117:endpoint\ntensorflow_endpoint_name -> 'tensorflow-training-2021-04-05-11-23-57-968-tf-16\ntensorflow_model_name -> 'tensorflow-training-2021-04-05-11-23-57-968-tf-16\ntest_data_bias_s3_uri -> 's3://sagemaker-us-east-1-117859797117/bias/test_d\ntest_data_explainablity_s3_uri -> 's3://sagemaker-us-east-1-117859797117/bias/test_d\ntest_split_percentage -> 0.05\ntrain_split_percentage -> 0.9\ntraining_job_name -> 'tensorflow-training-2021-04-12-21-49-31-083'\ntrial_name -> 'trial-1618387082'\nvalidation_split_percentage -> 0.05\n" ] ], [ [ "# Query The Feature Store", "_____no_output_____" ] ], [ [ "feature_store_query = feature_group.athena_query()", "_____no_output_____" ], [ "feature_store_table = feature_store_query.table_name", "_____no_output_____" ], [ "query_string = \"\"\"\nSELECT input_ids, input_mask, segment_ids, label_id, split_type FROM \"{}\" WHERE split_type='train' LIMIT 5\n\"\"\".format(\n feature_store_table\n)\n\nprint(\"Running \" + query_string)", "Running \nSELECT input_ids, input_mask, segment_ids, label_id, split_type FROM \"reviews-feature-group-1618387082-1618387492\" WHERE split_type='train' LIMIT 5\n\n" ], [ "feature_store_query.run(\n query_string=query_string,\n output_location=\"s3://\" + bucket + \"/\" + feature_store_offline_prefix + \"/query_results/\",\n)\n\nfeature_store_query.wait()", "INFO:sagemaker:Query 65d6e636-9eca-451f-b7b9-8b0a114c54dd is being executed.\nINFO:sagemaker:Query 65d6e636-9eca-451f-b7b9-8b0a114c54dd successfully executed.\n" ], [ "feature_store_query.as_dataframe()", "_____no_output_____" ] ], [ [ "# Show the Experiment Tracking Lineage", "_____no_output_____" ] ], [ [ "from sagemaker.analytics import ExperimentAnalytics\n\nimport pandas as pd\n\npd.set_option(\"max_colwidth\", 500)\n# pd.set_option(\"max_rows\", 100)\n\nexperiment_analytics = ExperimentAnalytics(\n sagemaker_session=sess, experiment_name=experiment_name, sort_by=\"CreationTime\", sort_order=\"Descending\"\n)\n\nexperiment_analytics_df = experiment_analytics.dataframe()\nexperiment_analytics_df", "_____no_output_____" ], [ "trial_component_name = experiment_analytics_df.TrialComponentName[0]\nprint(trial_component_name)", "sagemaker-scikit-learn-2021-04-14-07-58-05-034-aws-processing-job\n" ], [ "trial_component_description = sm.describe_trial_component(TrialComponentName=trial_component_name)\ntrial_component_description", "_____no_output_____" ] ], [ [ "# Show SageMaker ML Lineage Tracking \n\nAmazon SageMaker ML Lineage Tracking creates and stores information about the steps of a machine learning (ML) workflow from data preparation to model deployment. \n\nAmazon SageMaker Lineage enables events that happen within SageMaker to be traced via a graph structure. The data simplifies generating reports, making comparisons, or discovering relationships between events. For example easily trace both how a model was generated and where the model was deployed.\n\nThe lineage graph is created automatically by SageMaker and you can directly create or modify your own graphs.\n\n## Key Concepts\n\n* **Lineage Graph** - A connected graph tracing your machine learning workflow end to end.\n\n* **Artifacts** - Represents a URI addressable object or data. Artifacts are typically inputs or outputs to Actions.\n\n* **Actions** - Represents an action taken such as a computation, transformation, or job.\n\n* **Contexts** - Provides a method to logically group other entities.\n\n* **Associations** - A directed edge in the lineage graph that links two entities.\n\n* **Lineage Traversal** - Starting from an arbitrary point trace the lineage graph to discover and analyze relationships between steps in your workflow.\n\n* **Experiments** - Experiment entites (Experiments, Trials, and Trial Components) are also part of the lineage graph and can be associated wtih Artifacts, Actions, or Contexts.", "_____no_output_____" ], [ "## Show Lineage Artifacts For Our Processing Job", "_____no_output_____" ] ], [ [ "from sagemaker.lineage.visualizer import LineageTableVisualizer\n\nlineage_table_viz = LineageTableVisualizer(sess)\nlineage_table_viz_df = lineage_table_viz.show(processing_job_name=scikit_processing_job_name)\nlineage_table_viz_df", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
ecfcd52af574bfb34843c44f0508e18e9b0f58d1
3,452
ipynb
Jupyter Notebook
TF/GPU_Test.ipynb
krishnakesari/Tensorflow-Methods-2.0
a1eac068edcfc17ac52dc4e2070099b3a381350a
[ "MIT" ]
null
null
null
TF/GPU_Test.ipynb
krishnakesari/Tensorflow-Methods-2.0
a1eac068edcfc17ac52dc4e2070099b3a381350a
[ "MIT" ]
null
null
null
TF/GPU_Test.ipynb
krishnakesari/Tensorflow-Methods-2.0
a1eac068edcfc17ac52dc4e2070099b3a381350a
[ "MIT" ]
null
null
null
23.972222
288
0.543743
[ [ [ "import tensorflow as tf\ndevices = tf.config.list_physical_devices()\nprint(devices)", "[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'), PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]\n" ], [ "import tensorflow as tf\nprint(\"TensorFlow version:\", tf.__version__)", "TensorFlow version: 2.7.0\n" ], [ "mnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0", "_____no_output_____" ], [ "model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10)\n])\n\npredictions = model(x_train[:1]).numpy()\npredictions", "Metal device set to: Apple M1\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
ecfcde2a1994bdb9413f0b79655134f031588a9e
114,579
ipynb
Jupyter Notebook
Cleaning_EDA/sql_over_under.ipynb
lucy-allen/Project_3
5fb9c790ba18187f2a90fc32bbe856b409080ba5
[ "FTL" ]
null
null
null
Cleaning_EDA/sql_over_under.ipynb
lucy-allen/Project_3
5fb9c790ba18187f2a90fc32bbe856b409080ba5
[ "FTL" ]
null
null
null
Cleaning_EDA/sql_over_under.ipynb
lucy-allen/Project_3
5fb9c790ba18187f2a90fc32bbe856b409080ba5
[ "FTL" ]
null
null
null
38.501008
151
0.339512
[ [ [ "# More feature engineering with SQL (For predicting if a game is high scoring)", "_____no_output_____" ] ], [ [ "from sqlalchemy import create_engine\nimport pandas as pd", "_____no_output_____" ], [ "# cnx = create_engine('postgresql://username:password@ip_address:port/database')\ncnx = create_engine('postgresql://lucyallen@localhost:5432/nhl_new')", "_____no_output_____" ], [ "df = pd.read_sql_query('''select *, (hometenwinpct - awaytenwinpct) as tenwinpctdiff, (hometengoalsfor-awaytengoalsfor) as tengamegoalfordiff,\n(homefivegoalsfor-awayfivegoalsfor) as fivegamegoalfordiff, (hometengoalsagainst-awaytengoalsagainst) as tengamegoalagainstdiff,\n(homefivegoalsagainst-awayfivegoalsagainst) as fivegamegoalagainstdiff, (homefivegoalsfor-homefivegoalsagainst) as homefivegoaldiff, \n(hometengoalsfor-hometengoalsagainst) as hometengoaldiff, (awayfivegoalsfor-awayfivegoalsagainst) as awayfivegoaldiff,\n(awaytengoalsfor-awaytengoalsagainst) as awaytengoaldiff,\ncase when homedivision = awaydivision then 1 else 0 end as samedivision,\ncase when homeresult = 'Win' then 1 else 0 end as win\nfrom \n(select * \nfrom nhl_home_new nh \nleft join nhl_away_new na \non nh.hometeam = na.hometeam and na.date = nh.date\n) as tablehome''', cnx)", "_____no_output_____" ] ], [ [ "###### Removing Duplicate Rows", "_____no_output_____" ] ], [ [ "nhl = df.loc[:,~df.columns.duplicated()]", "_____no_output_____" ], [ "nhl", "_____no_output_____" ], [ "nhl.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 954 entries, 0 to 953\nData columns (total 71 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 index 954 non-null int64 \n 1 homedivision 954 non-null object \n 2 hometeam 954 non-null object \n 3 date 954 non-null object \n 4 awayteam 954 non-null object \n 5 homegoals 954 non-null int64 \n 6 awaygoals 954 non-null int64 \n 7 homeresult 954 non-null object \n 8 datetime 954 non-null object \n 9 totalpoints 954 non-null int64 \n 10 homeprevpct 938 non-null float64\n 11 homeprevwins 938 non-null float64\n 12 homeprevloss 938 non-null float64\n 13 homeprevties 938 non-null float64\n 14 homefivepct 862 non-null float64\n 15 homefivewins 862 non-null float64\n 16 homefiveloss 862 non-null float64\n 17 homefiveties 862 non-null float64\n 18 hometenpct 781 non-null float64\n 19 hometenwins 781 non-null float64\n 20 hometenloss 781 non-null float64\n 21 hometenties 781 non-null float64\n 22 homefivegoalsfor 876 non-null float64\n 23 homefivegoalsagainst 876 non-null float64\n 24 hometengoalsfor 799 non-null float64\n 25 hometengoalsagainst 799 non-null float64\n 26 homelastfivewins 862 non-null float64\n 27 homelastfiveloss 862 non-null float64\n 28 homelastfiveties 862 non-null float64\n 29 homelasttenwins 781 non-null float64\n 30 homelasttenloss 781 non-null float64\n 31 homelasttenties 781 non-null float64\n 32 homefivewinpct 862 non-null float64\n 33 hometenwinpct 781 non-null float64\n 34 awaydivision 954 non-null object \n 35 awayresult 954 non-null object \n 36 awayprevpct 939 non-null float64\n 37 awayprevwins 939 non-null float64\n 38 awayprevloss 939 non-null float64\n 39 awayprevties 939 non-null float64\n 40 awayfivepct 860 non-null float64\n 41 awayfivewins 860 non-null float64\n 42 awayfiveloss 860 non-null float64\n 43 awayfiveties 860 non-null float64\n 44 awaytenpct 786 non-null float64\n 45 awaytenwins 786 non-null float64\n 46 awaytenloss 786 non-null float64\n 47 awaytenties 786 non-null float64\n 48 awayfivegoalsfor 877 non-null float64\n 49 awayfivegoalsagainst 877 non-null float64\n 50 awaytengoalsfor 799 non-null float64\n 51 awaytengoalsagainst 799 non-null float64\n 52 awaylastfivewins 860 non-null float64\n 53 awaylastfiveloss 860 non-null float64\n 54 awaylastfiveties 860 non-null float64\n 55 awaylasttenwins 786 non-null float64\n 56 awaylasttenloss 786 non-null float64\n 57 awaylasttenties 786 non-null float64\n 58 awayfivewinpct 860 non-null float64\n 59 awaytenwinpct 786 non-null float64\n 60 tenwinpctdiff 776 non-null float64\n 61 tengamegoalfordiff 792 non-null float64\n 62 fivegamegoalfordiff 872 non-null float64\n 63 tengamegoalagainstdiff 792 non-null float64\n 64 fivegamegoalagainstdiff 872 non-null float64\n 65 homefivegoaldiff 876 non-null float64\n 66 hometengoaldiff 799 non-null float64\n 67 awayfivegoaldiff 877 non-null float64\n 68 awaytengoaldiff 799 non-null float64\n 69 samedivision 954 non-null int64 \n 70 win 954 non-null int64 \ndtypes: float64(57), int64(6), object(8)\nmemory usage: 529.3+ KB\n" ], [ "nhl", "_____no_output_____" ], [ "nhl.columns", "_____no_output_____" ] ], [ [ "###### Dropping Null Values", "_____no_output_____" ] ], [ [ "nhl.dropna(inplace=True)", "<ipython-input-12-727fdd3092e6>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n nhl.dropna(inplace=True)\n" ], [ "nhl.reset_index(inplace=True)", "_____no_output_____" ], [ "nhl.columns", "_____no_output_____" ] ], [ [ "###### Dropping some unnecessary columns", "_____no_output_____" ] ], [ [ "nhl.drop(['level_0', 'index', 'homegoals', 'awaygoals', 'homefivepct', 'homefivewins', 'homefiveloss', 'homefiveties', \n 'hometenpct', 'hometenwins', 'hometenloss', 'hometenties', 'awayfivepct', 'awayfivewins', 'awayfiveloss', 'awayfiveties', \n 'awaytenpct', 'awaytenwins', 'awaytenloss', 'awaytenties'], axis=1, inplace=True)", "/Users/lucyallen/opt/anaconda3/envs/metis/lib/python3.8/site-packages/pandas/core/frame.py:3990: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return super().drop(\n" ], [ "nhl.describe()", "_____no_output_____" ], [ "nhl.drop(['homeprevpct', 'homeprevwins', 'homeprevloss', 'homeprevties'], axis=1, inplace=True)", "/Users/lucyallen/opt/anaconda3/envs/metis/lib/python3.8/site-packages/pandas/core/frame.py:3990: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return super().drop(\n" ], [ "nhl", "_____no_output_____" ], [ "nhl.drop(['awayprevpct', 'awayprevwins', 'awayprevloss', 'awayprevties'], axis=1, inplace=True)", "/Users/lucyallen/opt/anaconda3/envs/metis/lib/python3.8/site-packages/pandas/core/frame.py:3990: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n return super().drop(\n" ], [ "nhl.columns", "_____no_output_____" ] ], [ [ "###### Creating some new columns for total goals in the games since that will probably be more important with the high goal game prediction", "_____no_output_____" ] ], [ [ "nhl['homefivetotalgoals'] = nhl['homefivegoalsfor'] + nhl['homefivegoalsagainst']", "<ipython-input-21-97964718779b>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n nhl['homefivetotalgoals'] = nhl['homefivegoalsfor'] + nhl['homefivegoalsagainst']\n" ], [ "nhl['hometentotalgoals'] = nhl['hometengoalsfor'] + nhl['hometengoalsagainst']", "<ipython-input-22-59baf65a1e3d>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n nhl['hometentotalgoals'] = nhl['hometengoalsfor'] + nhl['hometengoalsagainst']\n" ], [ "nhl['awayfivetotalgoals'] = nhl['awayfivegoalsfor'] + nhl['awayfivegoalsagainst']", "<ipython-input-23-c20beb4a6193>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n nhl['awayfivetotalgoals'] = nhl['awayfivegoalsfor'] + nhl['awayfivegoalsagainst']\n" ], [ "nhl['awaytentotalgoals'] = nhl['awaytengoalsfor'] + nhl['awaytengoalsagainst']", "<ipython-input-24-ad24db3d7ba7>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n nhl['awaytentotalgoals'] = nhl['awaytengoalsfor'] + nhl['awaytengoalsagainst']\n" ], [ "nhl.columns", "_____no_output_____" ], [ "nhl", "_____no_output_____" ] ], [ [ "###### Creating a target variable `over` to use, using > 7 total points since it is the 75th percentile", "_____no_output_____" ] ], [ [ "nhl['over'] = 0\nfor i in range(776):\n if nhl.loc[i, 'totalpoints'] > 7:\n nhl.loc[i,'over'] = 1", "<ipython-input-28-7e796e3d0d6d>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n nhl['over'] = 0\n/Users/lucyallen/opt/anaconda3/envs/metis/lib/python3.8/site-packages/pandas/core/indexing.py:966: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self.obj[item] = s\n" ], [ "nhl", "_____no_output_____" ] ], [ [ "### Saving this table to import into a new notebook for modeling", "_____no_output_____" ] ], [ [ "nhl.to_csv('nhl_over_under_table.csv')", "_____no_output_____" ], [ "nhl.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 776 entries, 0 to 775\nData columns (total 49 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 homedivision 776 non-null object \n 1 hometeam 776 non-null object \n 2 date 776 non-null object \n 3 awayteam 776 non-null object \n 4 homeresult 776 non-null object \n 5 datetime 776 non-null object \n 6 totalpoints 776 non-null int64 \n 7 homefivegoalsfor 776 non-null float64\n 8 homefivegoalsagainst 776 non-null float64\n 9 hometengoalsfor 776 non-null float64\n 10 hometengoalsagainst 776 non-null float64\n 11 homelastfivewins 776 non-null float64\n 12 homelastfiveloss 776 non-null float64\n 13 homelastfiveties 776 non-null float64\n 14 homelasttenwins 776 non-null float64\n 15 homelasttenloss 776 non-null float64\n 16 homelasttenties 776 non-null float64\n 17 homefivewinpct 776 non-null float64\n 18 hometenwinpct 776 non-null float64\n 19 awaydivision 776 non-null object \n 20 awayresult 776 non-null object \n 21 awayfivegoalsfor 776 non-null float64\n 22 awayfivegoalsagainst 776 non-null float64\n 23 awaytengoalsfor 776 non-null float64\n 24 awaytengoalsagainst 776 non-null float64\n 25 awaylastfivewins 776 non-null float64\n 26 awaylastfiveloss 776 non-null float64\n 27 awaylastfiveties 776 non-null float64\n 28 awaylasttenwins 776 non-null float64\n 29 awaylasttenloss 776 non-null float64\n 30 awaylasttenties 776 non-null float64\n 31 awayfivewinpct 776 non-null float64\n 32 awaytenwinpct 776 non-null float64\n 33 tenwinpctdiff 776 non-null float64\n 34 tengamegoalfordiff 776 non-null float64\n 35 fivegamegoalfordiff 776 non-null float64\n 36 tengamegoalagainstdiff 776 non-null float64\n 37 fivegamegoalagainstdiff 776 non-null float64\n 38 homefivegoaldiff 776 non-null float64\n 39 hometengoaldiff 776 non-null float64\n 40 awayfivegoaldiff 776 non-null float64\n 41 awaytengoaldiff 776 non-null float64\n 42 samedivision 776 non-null int64 \n 43 win 776 non-null int64 \n 44 homefivetotalgoals 776 non-null float64\n 45 hometentotalgoals 776 non-null float64\n 46 awayfivetotalgoals 776 non-null float64\n 47 awaytentotalgoals 776 non-null float64\n 48 over 776 non-null int64 \ndtypes: float64(37), int64(4), object(8)\nmemory usage: 297.2+ KB\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ecfce1280fd86775f524d819608605b26c864253
520,041
ipynb
Jupyter Notebook
sign_model_colab.ipynb
TanweerulHaque/Signature-Verification
ee30b99d8ca8bc4a51494734791cc7b3c43002e5
[ "MIT" ]
null
null
null
sign_model_colab.ipynb
TanweerulHaque/Signature-Verification
ee30b99d8ca8bc4a51494734791cc7b3c43002e5
[ "MIT" ]
null
null
null
sign_model_colab.ipynb
TanweerulHaque/Signature-Verification
ee30b99d8ca8bc4a51494734791cc7b3c43002e5
[ "MIT" ]
null
null
null
95.367871
67,850
0.724639
[ [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "# place the zip file in this path of google drive, which is the home page of google drive, change if path is different\r\n# No need to change any other code hereafter\r\n\r\n!unzip /content/drive/MyDrive/sign_data.zip", "Archive: /content/drive/MyDrive/sign_data.zip\n creating: sign_data/\n creating: sign_data/sign_data/\n creating: sign_data/sign_data/test/\n creating: sign_data/sign_data/test/049/\n extracting: sign_data/sign_data/test/049/01_049.png \n extracting: sign_data/sign_data/test/049/02_049.png \n extracting: sign_data/sign_data/test/049/03_049.png \n extracting: sign_data/sign_data/test/049/04_049.png \n extracting: sign_data/sign_data/test/049/05_049.png \n extracting: sign_data/sign_data/test/049/06_049.png \n extracting: sign_data/sign_data/test/049/07_049.png \n extracting: sign_data/sign_data/test/049/08_049.png \n extracting: sign_data/sign_data/test/049/09_049.png \n extracting: sign_data/sign_data/test/049/10_049.png \n extracting: sign_data/sign_data/test/049/11_049.png \n extracting: sign_data/sign_data/test/049/12_049.png \n creating: sign_data/sign_data/test/049_forg/\n extracting: sign_data/sign_data/test/049_forg/01_0114049.PNG \n extracting: sign_data/sign_data/test/049_forg/01_0206049.PNG \n extracting: sign_data/sign_data/test/049_forg/01_0210049.PNG \n extracting: sign_data/sign_data/test/049_forg/02_0114049.PNG \n extracting: sign_data/sign_data/test/049_forg/02_0206049.PNG \n extracting: sign_data/sign_data/test/049_forg/02_0210049.PNG \n extracting: sign_data/sign_data/test/049_forg/03_0114049.PNG \n extracting: sign_data/sign_data/test/049_forg/03_0206049.PNG \n extracting: sign_data/sign_data/test/049_forg/03_0210049.PNG \n extracting: sign_data/sign_data/test/049_forg/04_0114049.PNG \n extracting: sign_data/sign_data/test/049_forg/04_0206049.PNG \n extracting: sign_data/sign_data/test/049_forg/04_0210049.PNG \n creating: sign_data/sign_data/test/050/\n extracting: sign_data/sign_data/test/050/01_050.png \n extracting: sign_data/sign_data/test/050/02_050.png \n extracting: sign_data/sign_data/test/050/03_050.png \n extracting: sign_data/sign_data/test/050/04_050.png \n extracting: sign_data/sign_data/test/050/05_050.png \n extracting: sign_data/sign_data/test/050/06_050.png \n extracting: sign_data/sign_data/test/050/07_050.png \n extracting: sign_data/sign_data/test/050/08_050.png \n extracting: sign_data/sign_data/test/050/09_050.png \n extracting: sign_data/sign_data/test/050/10_050.png \n extracting: sign_data/sign_data/test/050/11_050.png \n extracting: sign_data/sign_data/test/050/12_050.png \n creating: sign_data/sign_data/test/050_forg/\n extracting: sign_data/sign_data/test/050_forg/01_0125050.PNG \n extracting: sign_data/sign_data/test/050_forg/01_0126050.PNG \n extracting: sign_data/sign_data/test/050_forg/01_0204050.PNG \n extracting: sign_data/sign_data/test/050_forg/02_0125050.PNG \n extracting: sign_data/sign_data/test/050_forg/02_0126050.PNG \n extracting: sign_data/sign_data/test/050_forg/02_0204050.PNG \n extracting: sign_data/sign_data/test/050_forg/03_0125050.PNG \n extracting: sign_data/sign_data/test/050_forg/03_0126050.PNG \n extracting: sign_data/sign_data/test/050_forg/03_0204050.PNG \n extracting: sign_data/sign_data/test/050_forg/04_0125050.PNG \n extracting: sign_data/sign_data/test/050_forg/04_0126050.PNG \n extracting: sign_data/sign_data/test/050_forg/04_0204050.PNG \n creating: sign_data/sign_data/test/051/\n extracting: sign_data/sign_data/test/051/01_051.png \n extracting: sign_data/sign_data/test/051/02_051.png \n extracting: sign_data/sign_data/test/051/03_051.png \n extracting: sign_data/sign_data/test/051/04_051.png \n extracting: sign_data/sign_data/test/051/05_051.png \n extracting: sign_data/sign_data/test/051/06_051.png \n extracting: sign_data/sign_data/test/051/07_051.png \n extracting: sign_data/sign_data/test/051/08_051.png \n extracting: sign_data/sign_data/test/051/09_051.png \n extracting: sign_data/sign_data/test/051/10_051.png \n extracting: sign_data/sign_data/test/051/11_051.png \n extracting: sign_data/sign_data/test/051/12_051.png \n creating: sign_data/sign_data/test/051_forg/\n extracting: sign_data/sign_data/test/051_forg/01_0104051.PNG \n extracting: sign_data/sign_data/test/051_forg/01_0120051.PNG \n extracting: sign_data/sign_data/test/051_forg/02_0104051.PNG \n extracting: sign_data/sign_data/test/051_forg/02_0120051.PNG \n extracting: sign_data/sign_data/test/051_forg/03_0104051.PNG \n extracting: sign_data/sign_data/test/051_forg/03_0120051.PNG \n extracting: sign_data/sign_data/test/051_forg/04_0104051.PNG \n extracting: sign_data/sign_data/test/051_forg/04_0120051.PNG \n creating: sign_data/sign_data/test/052/\n extracting: sign_data/sign_data/test/052/01_052.png \n extracting: sign_data/sign_data/test/052/02_052.png \n extracting: sign_data/sign_data/test/052/03_052.png \n extracting: sign_data/sign_data/test/052/04_052.png \n extracting: sign_data/sign_data/test/052/05_052.png \n extracting: sign_data/sign_data/test/052/06_052.png \n extracting: sign_data/sign_data/test/052/07_052.png \n extracting: sign_data/sign_data/test/052/08_052.png \n extracting: sign_data/sign_data/test/052/09_052.png \n extracting: sign_data/sign_data/test/052/10_052.png \n extracting: sign_data/sign_data/test/052/11_052.png \n extracting: sign_data/sign_data/test/052/12_052.png \n creating: sign_data/sign_data/test/052_forg/\n extracting: sign_data/sign_data/test/052_forg/01_0106052.PNG \n extracting: sign_data/sign_data/test/052_forg/01_0109052.PNG \n extracting: sign_data/sign_data/test/052_forg/01_0207052.PNG \n extracting: sign_data/sign_data/test/052_forg/01_0210052.PNG \n extracting: sign_data/sign_data/test/052_forg/02_0106052.PNG \n extracting: sign_data/sign_data/test/052_forg/02_0109052.PNG \n extracting: sign_data/sign_data/test/052_forg/02_0207052.PNG \n extracting: sign_data/sign_data/test/052_forg/02_0210052.PNG \n extracting: sign_data/sign_data/test/052_forg/03_0106052.PNG \n extracting: sign_data/sign_data/test/052_forg/03_0109052.PNG \n extracting: sign_data/sign_data/test/052_forg/03_0207052.PNG \n extracting: sign_data/sign_data/test/052_forg/03_0210052.PNG \n extracting: sign_data/sign_data/test/052_forg/04_0106052.PNG \n extracting: sign_data/sign_data/test/052_forg/04_0109052.PNG \n extracting: sign_data/sign_data/test/052_forg/04_0207052.PNG \n extracting: sign_data/sign_data/test/052_forg/04_0210052.PNG \n creating: sign_data/sign_data/test/053/\n extracting: sign_data/sign_data/test/053/01_053.png \n extracting: sign_data/sign_data/test/053/02_053.png \n extracting: sign_data/sign_data/test/053/03_053.png \n extracting: sign_data/sign_data/test/053/04_053.png \n extracting: sign_data/sign_data/test/053/05_053.png \n extracting: sign_data/sign_data/test/053/06_053.png \n extracting: sign_data/sign_data/test/053/07_053.png \n extracting: sign_data/sign_data/test/053/08_053.png \n extracting: sign_data/sign_data/test/053/09_053.png \n extracting: sign_data/sign_data/test/053/10_053.png \n extracting: sign_data/sign_data/test/053/11_053.png \n extracting: sign_data/sign_data/test/053/12_053.png \n creating: sign_data/sign_data/test/053_forg/\n extracting: sign_data/sign_data/test/053_forg/01_0107053.PNG \n extracting: sign_data/sign_data/test/053_forg/01_0115053.PNG \n extracting: sign_data/sign_data/test/053_forg/01_0202053.PNG \n extracting: sign_data/sign_data/test/053_forg/01_0207053.PNG \n extracting: sign_data/sign_data/test/053_forg/02_0107053.PNG \n extracting: sign_data/sign_data/test/053_forg/02_0115053.PNG \n extracting: sign_data/sign_data/test/053_forg/02_0202053.PNG \n extracting: sign_data/sign_data/test/053_forg/02_0207053.PNG \n extracting: sign_data/sign_data/test/053_forg/03_0107053.PNG \n extracting: sign_data/sign_data/test/053_forg/03_0115053.PNG \n extracting: sign_data/sign_data/test/053_forg/03_0202053.PNG \n extracting: sign_data/sign_data/test/053_forg/03_0207053.PNG \n extracting: sign_data/sign_data/test/053_forg/04_0107053.PNG \n extracting: sign_data/sign_data/test/053_forg/04_0115053.PNG \n extracting: sign_data/sign_data/test/053_forg/04_0202053.PNG \n extracting: sign_data/sign_data/test/053_forg/04_0207053.PNG \n creating: sign_data/sign_data/test/054/\n extracting: sign_data/sign_data/test/054/01_054.png \n extracting: sign_data/sign_data/test/054/02_054.png \n extracting: sign_data/sign_data/test/054/03_054.png \n extracting: sign_data/sign_data/test/054/04_054.png \n extracting: sign_data/sign_data/test/054/05_054.png \n extracting: sign_data/sign_data/test/054/06_054.png \n extracting: sign_data/sign_data/test/054/07_054.png \n extracting: sign_data/sign_data/test/054/08_054.png \n extracting: sign_data/sign_data/test/054/09_054.png \n extracting: sign_data/sign_data/test/054/10_054.png \n extracting: sign_data/sign_data/test/054/11_054.png \n extracting: sign_data/sign_data/test/054/12_054.png \n creating: sign_data/sign_data/test/054_forg/\n extracting: sign_data/sign_data/test/054_forg/01_0102054.PNG \n extracting: sign_data/sign_data/test/054_forg/01_0124054.PNG \n extracting: sign_data/sign_data/test/054_forg/01_0207054.PNG \n extracting: sign_data/sign_data/test/054_forg/01_0208054.PNG \n extracting: sign_data/sign_data/test/054_forg/01_0214054.PNG \n extracting: sign_data/sign_data/test/054_forg/02_0102054.PNG \n extracting: sign_data/sign_data/test/054_forg/02_0124054.PNG \n extracting: sign_data/sign_data/test/054_forg/02_0207054.PNG \n extracting: sign_data/sign_data/test/054_forg/02_0208054.PNG \n extracting: sign_data/sign_data/test/054_forg/02_0214054.PNG \n extracting: sign_data/sign_data/test/054_forg/03_0102054.PNG \n extracting: sign_data/sign_data/test/054_forg/03_0124054.PNG \n extracting: sign_data/sign_data/test/054_forg/03_0207054.PNG \n extracting: sign_data/sign_data/test/054_forg/03_0208054.PNG \n extracting: sign_data/sign_data/test/054_forg/03_0214054.PNG \n extracting: sign_data/sign_data/test/054_forg/04_0102054.PNG \n extracting: sign_data/sign_data/test/054_forg/04_0124054.PNG \n extracting: sign_data/sign_data/test/054_forg/04_0207054.PNG \n extracting: sign_data/sign_data/test/054_forg/04_0208054.PNG \n extracting: sign_data/sign_data/test/054_forg/04_0214054.PNG \n creating: sign_data/sign_data/test/055/\n extracting: sign_data/sign_data/test/055/01_055.png \n extracting: sign_data/sign_data/test/055/02_055.png \n extracting: sign_data/sign_data/test/055/03_055.png \n extracting: sign_data/sign_data/test/055/04_055.png \n extracting: sign_data/sign_data/test/055/05_055.png \n extracting: sign_data/sign_data/test/055/06_055.png \n extracting: sign_data/sign_data/test/055/07_055.png \n extracting: sign_data/sign_data/test/055/08_055.png \n extracting: sign_data/sign_data/test/055/09_055.png \n extracting: sign_data/sign_data/test/055/10_055.png \n extracting: sign_data/sign_data/test/055/11_055.png \n extracting: sign_data/sign_data/test/055/12_055.png \n creating: sign_data/sign_data/test/055_forg/\n extracting: sign_data/sign_data/test/055_forg/01_0118055.PNG \n extracting: sign_data/sign_data/test/055_forg/01_0120055.PNG \n extracting: sign_data/sign_data/test/055_forg/01_0202055.PNG \n extracting: sign_data/sign_data/test/055_forg/02_0118055.PNG \n extracting: sign_data/sign_data/test/055_forg/02_0120055.PNG \n extracting: sign_data/sign_data/test/055_forg/02_0202055.PNG \n extracting: sign_data/sign_data/test/055_forg/03_0118055.PNG \n extracting: sign_data/sign_data/test/055_forg/03_0120055.PNG \n extracting: sign_data/sign_data/test/055_forg/03_0202055.PNG \n extracting: sign_data/sign_data/test/055_forg/04_0118055.PNG \n extracting: sign_data/sign_data/test/055_forg/04_0120055.PNG \n extracting: sign_data/sign_data/test/055_forg/04_0202055.PNG \n creating: sign_data/sign_data/test/056/\n extracting: sign_data/sign_data/test/056/01_056.png \n extracting: sign_data/sign_data/test/056/02_056.png \n extracting: sign_data/sign_data/test/056/03_056.png \n extracting: sign_data/sign_data/test/056/04_056.png \n extracting: sign_data/sign_data/test/056/05_056.png \n extracting: sign_data/sign_data/test/056/06_056.png \n extracting: sign_data/sign_data/test/056/07_056.png \n extracting: sign_data/sign_data/test/056/08_056.png \n extracting: sign_data/sign_data/test/056/09_056.png \n extracting: sign_data/sign_data/test/056/10_056.png \n extracting: sign_data/sign_data/test/056/11_056.png \n extracting: sign_data/sign_data/test/056/12_056.png \n creating: sign_data/sign_data/test/056_forg/\n extracting: sign_data/sign_data/test/056_forg/01_0105056.PNG \n extracting: sign_data/sign_data/test/056_forg/01_0115056.PNG \n extracting: sign_data/sign_data/test/056_forg/02_0105056.PNG \n extracting: sign_data/sign_data/test/056_forg/02_0115056.PNG \n extracting: sign_data/sign_data/test/056_forg/03_0105056.PNG \n extracting: sign_data/sign_data/test/056_forg/03_0115056.PNG \n extracting: sign_data/sign_data/test/056_forg/04_0105056.PNG \n extracting: sign_data/sign_data/test/056_forg/04_0115056.PNG \n creating: sign_data/sign_data/test/057/\n extracting: sign_data/sign_data/test/057/01_057.png \n extracting: sign_data/sign_data/test/057/02_057.png \n extracting: sign_data/sign_data/test/057/03_057.png \n extracting: sign_data/sign_data/test/057/04_057.png \n extracting: sign_data/sign_data/test/057/05_057.png \n extracting: sign_data/sign_data/test/057/06_057.png \n extracting: sign_data/sign_data/test/057/07_057.png \n extracting: sign_data/sign_data/test/057/08_057.png \n extracting: sign_data/sign_data/test/057/09_057.png \n extracting: sign_data/sign_data/test/057/10_057.png \n extracting: sign_data/sign_data/test/057/11_057.png \n extracting: sign_data/sign_data/test/057/12_057.png \n creating: sign_data/sign_data/test/057_forg/\n extracting: sign_data/sign_data/test/057_forg/01_0117057.PNG \n extracting: sign_data/sign_data/test/057_forg/01_0208057.PNG \n extracting: sign_data/sign_data/test/057_forg/01_0210057.PNG \n extracting: sign_data/sign_data/test/057_forg/02_0117057.PNG \n extracting: sign_data/sign_data/test/057_forg/02_0208057.PNG \n extracting: sign_data/sign_data/test/057_forg/02_0210057.PNG \n extracting: sign_data/sign_data/test/057_forg/03_0117057.PNG \n extracting: sign_data/sign_data/test/057_forg/03_0208057.PNG \n extracting: sign_data/sign_data/test/057_forg/03_0210057.PNG \n extracting: sign_data/sign_data/test/057_forg/04_0117057.PNG \n extracting: sign_data/sign_data/test/057_forg/04_0208057.PNG \n extracting: sign_data/sign_data/test/057_forg/04_0210057.PNG \n creating: sign_data/sign_data/test/058/\n extracting: sign_data/sign_data/test/058/01_058.png \n extracting: sign_data/sign_data/test/058/02_058.png \n extracting: sign_data/sign_data/test/058/03_058.png \n extracting: sign_data/sign_data/test/058/04_058.png \n extracting: sign_data/sign_data/test/058/05_058.png \n extracting: sign_data/sign_data/test/058/06_058.png \n extracting: sign_data/sign_data/test/058/07_058.png \n extracting: sign_data/sign_data/test/058/08_058.png \n extracting: sign_data/sign_data/test/058/09_058.png \n extracting: sign_data/sign_data/test/058/10_058.png \n extracting: sign_data/sign_data/test/058/11_058.png \n extracting: sign_data/sign_data/test/058/12_058.png \n creating: sign_data/sign_data/test/058_forg/\n extracting: sign_data/sign_data/test/058_forg/01_0109058.PNG \n extracting: sign_data/sign_data/test/058_forg/01_0110058.PNG \n extracting: sign_data/sign_data/test/058_forg/01_0125058.PNG \n extracting: sign_data/sign_data/test/058_forg/01_0127058.PNG \n extracting: sign_data/sign_data/test/058_forg/02_0109058.PNG \n extracting: sign_data/sign_data/test/058_forg/02_0110058.PNG \n extracting: sign_data/sign_data/test/058_forg/02_0125058.PNG \n extracting: sign_data/sign_data/test/058_forg/02_0127058.PNG \n extracting: sign_data/sign_data/test/058_forg/03_0109058.PNG \n extracting: sign_data/sign_data/test/058_forg/03_0110058.PNG \n extracting: sign_data/sign_data/test/058_forg/03_0125058.PNG \n extracting: sign_data/sign_data/test/058_forg/03_0127058.PNG \n extracting: sign_data/sign_data/test/058_forg/04_0109058.PNG \n extracting: sign_data/sign_data/test/058_forg/04_0110058.PNG \n extracting: sign_data/sign_data/test/058_forg/04_0125058.PNG \n extracting: sign_data/sign_data/test/058_forg/04_0127058.PNG \n creating: sign_data/sign_data/test/059/\n extracting: sign_data/sign_data/test/059/01_059.png \n extracting: sign_data/sign_data/test/059/02_059.png \n extracting: sign_data/sign_data/test/059/03_059.png \n extracting: sign_data/sign_data/test/059/04_059.png \n extracting: sign_data/sign_data/test/059/05_059.png \n extracting: sign_data/sign_data/test/059/06_059.png \n extracting: sign_data/sign_data/test/059/07_059.png \n extracting: sign_data/sign_data/test/059/08_059.png \n extracting: sign_data/sign_data/test/059/09_059.png \n extracting: sign_data/sign_data/test/059/10_059.png \n extracting: sign_data/sign_data/test/059/11_059.png \n extracting: sign_data/sign_data/test/059/12_059.png \n creating: sign_data/sign_data/test/059_forg/\n extracting: sign_data/sign_data/test/059_forg/01_0104059.PNG \n extracting: sign_data/sign_data/test/059_forg/01_0125059.PNG \n extracting: sign_data/sign_data/test/059_forg/02_0104059.PNG \n extracting: sign_data/sign_data/test/059_forg/02_0125059.PNG \n extracting: sign_data/sign_data/test/059_forg/03_0104059.PNG \n extracting: sign_data/sign_data/test/059_forg/03_0125059.PNG \n extracting: sign_data/sign_data/test/059_forg/04_0104059.PNG \n extracting: sign_data/sign_data/test/059_forg/04_0125059.PNG \n creating: sign_data/sign_data/test/060/\n extracting: sign_data/sign_data/test/060/01_060.png \n extracting: sign_data/sign_data/test/060/02_060.png \n extracting: sign_data/sign_data/test/060/03_060.png \n extracting: sign_data/sign_data/test/060/04_060.png \n extracting: sign_data/sign_data/test/060/05_060.png \n extracting: sign_data/sign_data/test/060/06_060.png \n extracting: sign_data/sign_data/test/060/07_060.png \n extracting: sign_data/sign_data/test/060/08_060.png \n extracting: sign_data/sign_data/test/060/09_060.png \n extracting: sign_data/sign_data/test/060/10_060.png \n extracting: sign_data/sign_data/test/060/11_060.png \n extracting: sign_data/sign_data/test/060/12_060.png \n creating: sign_data/sign_data/test/060_forg/\n extracting: sign_data/sign_data/test/060_forg/01_0111060.PNG \n extracting: sign_data/sign_data/test/060_forg/01_0121060.PNG \n extracting: sign_data/sign_data/test/060_forg/01_0126060.PNG \n extracting: sign_data/sign_data/test/060_forg/02_0111060.PNG \n extracting: sign_data/sign_data/test/060_forg/02_0121060.PNG \n extracting: sign_data/sign_data/test/060_forg/02_0126060.PNG \n extracting: sign_data/sign_data/test/060_forg/03_0111060.PNG \n extracting: sign_data/sign_data/test/060_forg/03_0121060.PNG \n extracting: sign_data/sign_data/test/060_forg/03_0126060.PNG \n extracting: sign_data/sign_data/test/060_forg/04_0111060.PNG \n extracting: sign_data/sign_data/test/060_forg/04_0121060.PNG \n extracting: sign_data/sign_data/test/060_forg/04_0126060.PNG \n creating: sign_data/sign_data/test/061/\n extracting: sign_data/sign_data/test/061/01_061.png \n extracting: sign_data/sign_data/test/061/02_061.png \n extracting: sign_data/sign_data/test/061/03_061.png \n extracting: sign_data/sign_data/test/061/04_061.png \n extracting: sign_data/sign_data/test/061/05_061.png \n extracting: sign_data/sign_data/test/061/06_061.png \n extracting: sign_data/sign_data/test/061/07_061.png \n extracting: sign_data/sign_data/test/061/08_061.png \n extracting: sign_data/sign_data/test/061/09_061.png \n extracting: sign_data/sign_data/test/061/10_061.png \n extracting: sign_data/sign_data/test/061/11_061.png \n extracting: sign_data/sign_data/test/061/12_061.png \n creating: sign_data/sign_data/test/061_forg/\n extracting: sign_data/sign_data/test/061_forg/01_0102061.PNG \n extracting: sign_data/sign_data/test/061_forg/01_0112061.PNG \n extracting: sign_data/sign_data/test/061_forg/01_0206061.PNG \n extracting: sign_data/sign_data/test/061_forg/02_0102061.PNG \n extracting: sign_data/sign_data/test/061_forg/02_0112061.PNG \n extracting: sign_data/sign_data/test/061_forg/02_0206061.PNG \n extracting: sign_data/sign_data/test/061_forg/03_0102061.PNG \n extracting: sign_data/sign_data/test/061_forg/03_0112061.PNG \n extracting: sign_data/sign_data/test/061_forg/03_0206061.PNG \n extracting: sign_data/sign_data/test/061_forg/04_0102061.PNG \n extracting: sign_data/sign_data/test/061_forg/04_0112061.PNG \n extracting: sign_data/sign_data/test/061_forg/04_0206061.PNG \n creating: sign_data/sign_data/test/062/\n extracting: sign_data/sign_data/test/062/01_062.png \n extracting: sign_data/sign_data/test/062/02_062.png \n extracting: sign_data/sign_data/test/062/03_062.png \n extracting: sign_data/sign_data/test/062/04_062.png \n extracting: sign_data/sign_data/test/062/05_062.png \n inflating: sign_data/sign_data/test/062/06_062.png \n extracting: sign_data/sign_data/test/062/07_062.png \n extracting: sign_data/sign_data/test/062/08_062.png \n extracting: sign_data/sign_data/test/062/09_062.png \n extracting: sign_data/sign_data/test/062/10_062.png \n extracting: sign_data/sign_data/test/062/11_062.png \n extracting: sign_data/sign_data/test/062/12_062.png \n creating: sign_data/sign_data/test/062_forg/\n extracting: sign_data/sign_data/test/062_forg/01_0109062.PNG \n extracting: sign_data/sign_data/test/062_forg/01_0116062.PNG \n extracting: sign_data/sign_data/test/062_forg/01_0201062.PNG \n extracting: sign_data/sign_data/test/062_forg/02_0109062.PNG \n extracting: sign_data/sign_data/test/062_forg/02_0116062.PNG \n extracting: sign_data/sign_data/test/062_forg/02_0201062.PNG \n extracting: sign_data/sign_data/test/062_forg/03_0109062.PNG \n extracting: sign_data/sign_data/test/062_forg/03_0116062.PNG \n extracting: sign_data/sign_data/test/062_forg/03_0201062.PNG \n extracting: sign_data/sign_data/test/062_forg/04_0109062.PNG \n extracting: sign_data/sign_data/test/062_forg/04_0116062.PNG \n extracting: sign_data/sign_data/test/062_forg/04_0201062.PNG \n creating: sign_data/sign_data/test/063/\n extracting: sign_data/sign_data/test/063/01_063.png \n extracting: sign_data/sign_data/test/063/02_063.png \n extracting: sign_data/sign_data/test/063/03_063.png \n extracting: sign_data/sign_data/test/063/04_063.png \n extracting: sign_data/sign_data/test/063/05_063.png \n extracting: sign_data/sign_data/test/063/06_063.png \n extracting: sign_data/sign_data/test/063/07_063.png \n extracting: sign_data/sign_data/test/063/08_063.png \n extracting: sign_data/sign_data/test/063/09_063.png \n extracting: sign_data/sign_data/test/063/10_063.png \n extracting: sign_data/sign_data/test/063/11_063.png \n extracting: sign_data/sign_data/test/063/12_063.png \n creating: sign_data/sign_data/test/063_forg/\n extracting: sign_data/sign_data/test/063_forg/01_0104063.PNG \n extracting: sign_data/sign_data/test/063_forg/01_0108063.PNG \n extracting: sign_data/sign_data/test/063_forg/01_0119063.PNG \n extracting: sign_data/sign_data/test/063_forg/02_0104063.PNG \n extracting: sign_data/sign_data/test/063_forg/02_0108063.PNG \n extracting: sign_data/sign_data/test/063_forg/02_0119063.PNG \n extracting: sign_data/sign_data/test/063_forg/03_0104063.PNG \n extracting: sign_data/sign_data/test/063_forg/03_0108063.PNG \n extracting: sign_data/sign_data/test/063_forg/03_0119063.PNG \n extracting: sign_data/sign_data/test/063_forg/04_0104063.PNG \n extracting: sign_data/sign_data/test/063_forg/04_0108063.PNG \n extracting: sign_data/sign_data/test/063_forg/04_0119063.PNG \n creating: sign_data/sign_data/test/064/\n extracting: sign_data/sign_data/test/064/01_064.png \n extracting: sign_data/sign_data/test/064/02_064.png \n extracting: sign_data/sign_data/test/064/03_064.png \n extracting: sign_data/sign_data/test/064/04_064.png \n extracting: sign_data/sign_data/test/064/05_064.png \n extracting: sign_data/sign_data/test/064/06_064.png \n extracting: sign_data/sign_data/test/064/07_064.png \n extracting: sign_data/sign_data/test/064/08_064.png \n extracting: sign_data/sign_data/test/064/09_064.png \n extracting: sign_data/sign_data/test/064/10_064.png \n extracting: sign_data/sign_data/test/064/11_064.png \n extracting: sign_data/sign_data/test/064/12_064.png \n creating: sign_data/sign_data/test/064_forg/\n extracting: sign_data/sign_data/test/064_forg/01_0105064.PNG \n extracting: sign_data/sign_data/test/064_forg/01_0203064.PNG \n extracting: sign_data/sign_data/test/064_forg/02_0105064.PNG \n extracting: sign_data/sign_data/test/064_forg/02_0203064.PNG \n extracting: sign_data/sign_data/test/064_forg/03_0105064.PNG \n extracting: sign_data/sign_data/test/064_forg/03_0203064.PNG \n extracting: sign_data/sign_data/test/064_forg/04_0105064.PNG \n extracting: sign_data/sign_data/test/064_forg/04_0203064.PNG \n creating: sign_data/sign_data/test/065/\n extracting: sign_data/sign_data/test/065/01_065.png \n extracting: sign_data/sign_data/test/065/02_065.png \n extracting: sign_data/sign_data/test/065/03_065.png \n extracting: sign_data/sign_data/test/065/04_065.png \n extracting: sign_data/sign_data/test/065/05_065.png \n extracting: sign_data/sign_data/test/065/06_065.png \n extracting: sign_data/sign_data/test/065/07_065.png \n extracting: sign_data/sign_data/test/065/08_065.png \n extracting: sign_data/sign_data/test/065/09_065.png \n extracting: sign_data/sign_data/test/065/10_065.png \n extracting: sign_data/sign_data/test/065/11_065.png \n extracting: sign_data/sign_data/test/065/12_065.png \n creating: sign_data/sign_data/test/065_forg/\n extracting: sign_data/sign_data/test/065_forg/01_0118065.PNG \n extracting: sign_data/sign_data/test/065_forg/01_0206065.PNG \n extracting: sign_data/sign_data/test/065_forg/02_0118065.PNG \n extracting: sign_data/sign_data/test/065_forg/02_0206065.PNG \n extracting: sign_data/sign_data/test/065_forg/03_0118065.PNG \n extracting: sign_data/sign_data/test/065_forg/03_0206065.PNG \n extracting: sign_data/sign_data/test/065_forg/04_0118065.PNG \n extracting: sign_data/sign_data/test/065_forg/04_0206065.PNG \n creating: sign_data/sign_data/test/066/\n extracting: sign_data/sign_data/test/066/01_066.png \n extracting: sign_data/sign_data/test/066/02_066.png \n extracting: sign_data/sign_data/test/066/03_066.png \n extracting: sign_data/sign_data/test/066/04_066.png \n extracting: sign_data/sign_data/test/066/05_066.png \n extracting: sign_data/sign_data/test/066/06_066.png \n extracting: sign_data/sign_data/test/066/07_066.png \n extracting: sign_data/sign_data/test/066/08_066.png \n extracting: sign_data/sign_data/test/066/09_066.png \n extracting: sign_data/sign_data/test/066/10_066.png \n extracting: sign_data/sign_data/test/066/11_066.png \n extracting: sign_data/sign_data/test/066/12_066.png \n creating: sign_data/sign_data/test/066_forg/\n extracting: sign_data/sign_data/test/066_forg/01_0101066.PNG \n extracting: sign_data/sign_data/test/066_forg/01_0127066.PNG \n extracting: sign_data/sign_data/test/066_forg/01_0211066.PNG \n extracting: sign_data/sign_data/test/066_forg/01_0212066.PNG \n extracting: sign_data/sign_data/test/066_forg/02_0101066.PNG \n extracting: sign_data/sign_data/test/066_forg/02_0127066.PNG \n extracting: sign_data/sign_data/test/066_forg/02_0211066.PNG \n extracting: sign_data/sign_data/test/066_forg/02_0212066.PNG \n extracting: sign_data/sign_data/test/066_forg/03_0101066.PNG \n extracting: sign_data/sign_data/test/066_forg/03_0127066.PNG \n extracting: sign_data/sign_data/test/066_forg/03_0211066.PNG \n extracting: sign_data/sign_data/test/066_forg/03_0212066.PNG \n extracting: sign_data/sign_data/test/066_forg/04_0101066.PNG \n extracting: sign_data/sign_data/test/066_forg/04_0127066.PNG \n extracting: sign_data/sign_data/test/066_forg/04_0211066.PNG \n extracting: sign_data/sign_data/test/066_forg/04_0212066.PNG \n creating: sign_data/sign_data/test/067/\n extracting: sign_data/sign_data/test/067/01_067.png \n extracting: sign_data/sign_data/test/067/02_067.png \n extracting: sign_data/sign_data/test/067/03_067.png \n extracting: sign_data/sign_data/test/067/04_067.png \n extracting: sign_data/sign_data/test/067/05_067.png \n extracting: sign_data/sign_data/test/067/06_067.png \n extracting: sign_data/sign_data/test/067/07_067.png \n extracting: sign_data/sign_data/test/067/08_067.png \n extracting: sign_data/sign_data/test/067/09_067.png \n extracting: sign_data/sign_data/test/067/10_067.png \n extracting: sign_data/sign_data/test/067/11_067.png \n extracting: sign_data/sign_data/test/067/12_067.png \n creating: sign_data/sign_data/test/067_forg/\n extracting: sign_data/sign_data/test/067_forg/01_0205067.PNG \n extracting: sign_data/sign_data/test/067_forg/01_0212067.PNG \n extracting: sign_data/sign_data/test/067_forg/02_0205067.PNG \n extracting: sign_data/sign_data/test/067_forg/02_0212067.PNG \n extracting: sign_data/sign_data/test/067_forg/03_0205067.PNG \n extracting: sign_data/sign_data/test/067_forg/03_0212067.PNG \n extracting: sign_data/sign_data/test/067_forg/04_0205067.PNG \n extracting: sign_data/sign_data/test/067_forg/04_0212067.PNG \n creating: sign_data/sign_data/test/068/\n extracting: sign_data/sign_data/test/068/01_068.png \n extracting: sign_data/sign_data/test/068/02_068.png \n extracting: sign_data/sign_data/test/068/03_068.png \n extracting: sign_data/sign_data/test/068/04_068.png \n extracting: sign_data/sign_data/test/068/05_068.png \n extracting: sign_data/sign_data/test/068/06_068.png \n extracting: sign_data/sign_data/test/068/07_068.png \n extracting: sign_data/sign_data/test/068/08_068.png \n extracting: sign_data/sign_data/test/068/09_068.png \n extracting: sign_data/sign_data/test/068/10_068.png \n extracting: sign_data/sign_data/test/068/11_068.png \n extracting: sign_data/sign_data/test/068/12_068.png \n creating: sign_data/sign_data/test/068_forg/\n extracting: sign_data/sign_data/test/068_forg/01_0113068.PNG \n extracting: sign_data/sign_data/test/068_forg/01_0124068.PNG \n extracting: sign_data/sign_data/test/068_forg/02_0113068.PNG \n extracting: sign_data/sign_data/test/068_forg/02_0124068.PNG \n extracting: sign_data/sign_data/test/068_forg/03_0113068.PNG \n extracting: sign_data/sign_data/test/068_forg/03_0124068.PNG \n extracting: sign_data/sign_data/test/068_forg/04_0113068.PNG \n extracting: sign_data/sign_data/test/068_forg/04_0124068.PNG \n creating: sign_data/sign_data/test/069/\n extracting: sign_data/sign_data/test/069/01_069.png \n extracting: sign_data/sign_data/test/069/02_069.png \n extracting: sign_data/sign_data/test/069/03_069.png \n extracting: sign_data/sign_data/test/069/04_069.png \n extracting: sign_data/sign_data/test/069/05_069.png \n extracting: sign_data/sign_data/test/069/06_069.png \n extracting: sign_data/sign_data/test/069/07_069.png \n extracting: sign_data/sign_data/test/069/08_069.png \n extracting: sign_data/sign_data/test/069/09_069.png \n extracting: sign_data/sign_data/test/069/10_069.png \n extracting: sign_data/sign_data/test/069/11_069.png \n extracting: sign_data/sign_data/test/069/12_069.png \n creating: sign_data/sign_data/test/069_forg/\n extracting: sign_data/sign_data/test/069_forg/01_0106069.PNG \n extracting: sign_data/sign_data/test/069_forg/01_0108069.PNG \n extracting: sign_data/sign_data/test/069_forg/01_0111069.PNG \n extracting: sign_data/sign_data/test/069_forg/02_0106069.PNG \n extracting: sign_data/sign_data/test/069_forg/02_0108069.PNG \n extracting: sign_data/sign_data/test/069_forg/02_0111069.PNG \n extracting: sign_data/sign_data/test/069_forg/03_0106069.PNG \n extracting: sign_data/sign_data/test/069_forg/03_0108069.PNG \n extracting: sign_data/sign_data/test/069_forg/03_0111069.PNG \n extracting: sign_data/sign_data/test/069_forg/04_0106069.PNG \n extracting: sign_data/sign_data/test/069_forg/04_0108069.PNG \n extracting: sign_data/sign_data/test/069_forg/04_0111069.PNG \n inflating: sign_data/sign_data/test_data.csv \n creating: sign_data/sign_data/train/\n creating: sign_data/sign_data/train/001/\n extracting: sign_data/sign_data/train/001/001_01.PNG \n extracting: sign_data/sign_data/train/001/001_02.PNG \n extracting: sign_data/sign_data/train/001/001_03.PNG \n extracting: sign_data/sign_data/train/001/001_04.PNG \n extracting: sign_data/sign_data/train/001/001_05.PNG \n extracting: sign_data/sign_data/train/001/001_06.PNG \n extracting: sign_data/sign_data/train/001/001_07.PNG \n extracting: sign_data/sign_data/train/001/001_08.PNG \n extracting: sign_data/sign_data/train/001/001_09.PNG \n extracting: sign_data/sign_data/train/001/001_10.PNG \n extracting: sign_data/sign_data/train/001/001_11.PNG \n extracting: sign_data/sign_data/train/001/001_12.PNG \n extracting: sign_data/sign_data/train/001/001_13.PNG \n extracting: sign_data/sign_data/train/001/001_14.PNG \n extracting: sign_data/sign_data/train/001/001_15.PNG \n extracting: sign_data/sign_data/train/001/001_16.PNG \n extracting: sign_data/sign_data/train/001/001_17.PNG \n extracting: sign_data/sign_data/train/001/001_18.PNG \n extracting: sign_data/sign_data/train/001/001_19.PNG \n extracting: sign_data/sign_data/train/001/001_20.PNG \n extracting: sign_data/sign_data/train/001/001_21.PNG \n extracting: sign_data/sign_data/train/001/001_22.PNG \n extracting: sign_data/sign_data/train/001/001_23.PNG \n extracting: sign_data/sign_data/train/001/001_24.PNG \n creating: sign_data/sign_data/train/001_forg/\n extracting: sign_data/sign_data/train/001_forg/0119001_01.png \n extracting: sign_data/sign_data/train/001_forg/0119001_02.png \n extracting: sign_data/sign_data/train/001_forg/0119001_03.png \n extracting: sign_data/sign_data/train/001_forg/0119001_04.png \n extracting: sign_data/sign_data/train/001_forg/0201001_01.png \n extracting: sign_data/sign_data/train/001_forg/0201001_02.png \n extracting: sign_data/sign_data/train/001_forg/0201001_03.png \n extracting: sign_data/sign_data/train/001_forg/0201001_04.png \n creating: sign_data/sign_data/train/002/\n extracting: sign_data/sign_data/train/002/002_01.PNG \n extracting: sign_data/sign_data/train/002/002_02.PNG \n extracting: sign_data/sign_data/train/002/002_03.PNG \n extracting: sign_data/sign_data/train/002/002_04.PNG \n extracting: sign_data/sign_data/train/002/002_05.PNG \n extracting: sign_data/sign_data/train/002/002_06.PNG \n extracting: sign_data/sign_data/train/002/002_07.PNG \n extracting: sign_data/sign_data/train/002/002_08.PNG \n extracting: sign_data/sign_data/train/002/002_09.PNG \n extracting: sign_data/sign_data/train/002/002_10.PNG \n extracting: sign_data/sign_data/train/002/002_11.PNG \n extracting: sign_data/sign_data/train/002/002_12.PNG \n extracting: sign_data/sign_data/train/002/002_13.PNG \n extracting: sign_data/sign_data/train/002/002_14.PNG \n extracting: sign_data/sign_data/train/002/002_15.PNG \n extracting: sign_data/sign_data/train/002/002_16.PNG \n extracting: sign_data/sign_data/train/002/002_17.PNG \n extracting: sign_data/sign_data/train/002/002_18.PNG \n extracting: sign_data/sign_data/train/002/002_19.PNG \n extracting: sign_data/sign_data/train/002/002_20.PNG \n extracting: sign_data/sign_data/train/002/002_21.PNG \n extracting: sign_data/sign_data/train/002/002_22.PNG \n extracting: sign_data/sign_data/train/002/002_23.PNG \n extracting: sign_data/sign_data/train/002/002_24.PNG \n creating: sign_data/sign_data/train/002_forg/\n extracting: sign_data/sign_data/train/002_forg/0108002_01.png \n extracting: sign_data/sign_data/train/002_forg/0108002_02.png \n extracting: sign_data/sign_data/train/002_forg/0108002_03.png \n extracting: sign_data/sign_data/train/002_forg/0108002_04.png \n extracting: sign_data/sign_data/train/002_forg/0110002_01.png \n extracting: sign_data/sign_data/train/002_forg/0110002_02.png \n extracting: sign_data/sign_data/train/002_forg/0110002_03.png \n extracting: sign_data/sign_data/train/002_forg/0110002_04.png \n extracting: sign_data/sign_data/train/002_forg/0118002_01.png \n extracting: sign_data/sign_data/train/002_forg/0118002_02.png \n extracting: sign_data/sign_data/train/002_forg/0118002_03.png \n extracting: sign_data/sign_data/train/002_forg/0118002_04.png \n creating: sign_data/sign_data/train/003/\n extracting: sign_data/sign_data/train/003/003_01.PNG \n extracting: sign_data/sign_data/train/003/003_02.PNG \n extracting: sign_data/sign_data/train/003/003_03.PNG \n extracting: sign_data/sign_data/train/003/003_04.PNG \n extracting: sign_data/sign_data/train/003/003_05.PNG \n extracting: sign_data/sign_data/train/003/003_06.PNG \n extracting: sign_data/sign_data/train/003/003_07.PNG \n extracting: sign_data/sign_data/train/003/003_08.PNG \n extracting: sign_data/sign_data/train/003/003_09.PNG \n extracting: sign_data/sign_data/train/003/003_10.PNG \n extracting: sign_data/sign_data/train/003/003_11.PNG \n extracting: sign_data/sign_data/train/003/003_12.PNG \n extracting: sign_data/sign_data/train/003/003_13.PNG \n extracting: sign_data/sign_data/train/003/003_14.PNG \n extracting: sign_data/sign_data/train/003/003_15.PNG \n extracting: sign_data/sign_data/train/003/003_16.PNG \n extracting: sign_data/sign_data/train/003/003_17.PNG \n extracting: sign_data/sign_data/train/003/003_18.PNG \n extracting: sign_data/sign_data/train/003/003_19.PNG \n extracting: sign_data/sign_data/train/003/003_20.PNG \n extracting: sign_data/sign_data/train/003/003_21.PNG \n extracting: sign_data/sign_data/train/003/003_22.PNG \n extracting: sign_data/sign_data/train/003/003_23.PNG \n extracting: sign_data/sign_data/train/003/003_24.PNG \n creating: sign_data/sign_data/train/003_forg/\n extracting: sign_data/sign_data/train/003_forg/0121003_01.png \n extracting: sign_data/sign_data/train/003_forg/0121003_02.png \n extracting: sign_data/sign_data/train/003_forg/0121003_03.png \n extracting: sign_data/sign_data/train/003_forg/0121003_04.png \n extracting: sign_data/sign_data/train/003_forg/0126003_01.png \n extracting: sign_data/sign_data/train/003_forg/0126003_02.png \n extracting: sign_data/sign_data/train/003_forg/0126003_03.png \n extracting: sign_data/sign_data/train/003_forg/0126003_04.png \n extracting: sign_data/sign_data/train/003_forg/0206003_01.png \n extracting: sign_data/sign_data/train/003_forg/0206003_02.png \n extracting: sign_data/sign_data/train/003_forg/0206003_03.png \n extracting: sign_data/sign_data/train/003_forg/0206003_04.png \n creating: sign_data/sign_data/train/004/\n extracting: sign_data/sign_data/train/004/004_01.PNG \n extracting: sign_data/sign_data/train/004/004_02.PNG \n extracting: sign_data/sign_data/train/004/004_03.PNG \n extracting: sign_data/sign_data/train/004/004_04.PNG \n extracting: sign_data/sign_data/train/004/004_05.PNG \n extracting: sign_data/sign_data/train/004/004_06.PNG \n extracting: sign_data/sign_data/train/004/004_07.PNG \n extracting: sign_data/sign_data/train/004/004_08.PNG \n extracting: sign_data/sign_data/train/004/004_09.PNG \n extracting: sign_data/sign_data/train/004/004_10.PNG \n extracting: sign_data/sign_data/train/004/004_11.PNG \n extracting: sign_data/sign_data/train/004/004_12.PNG \n extracting: sign_data/sign_data/train/004/004_13.PNG \n extracting: sign_data/sign_data/train/004/004_14.PNG \n extracting: sign_data/sign_data/train/004/004_15.PNG \n extracting: sign_data/sign_data/train/004/004_16.PNG \n extracting: sign_data/sign_data/train/004/004_17.PNG \n extracting: sign_data/sign_data/train/004/004_18.PNG \n extracting: sign_data/sign_data/train/004/004_19.PNG \n extracting: sign_data/sign_data/train/004/004_20.PNG \n extracting: sign_data/sign_data/train/004/004_21.PNG \n extracting: sign_data/sign_data/train/004/004_22.PNG \n extracting: sign_data/sign_data/train/004/004_23.PNG \n extracting: sign_data/sign_data/train/004/004_24.PNG \n creating: sign_data/sign_data/train/004_forg/\n extracting: sign_data/sign_data/train/004_forg/0103004_02.png \n extracting: sign_data/sign_data/train/004_forg/0103004_03.png \n extracting: sign_data/sign_data/train/004_forg/0103004_04.png \n extracting: sign_data/sign_data/train/004_forg/0105004_01.png \n extracting: sign_data/sign_data/train/004_forg/0105004_02.png \n extracting: sign_data/sign_data/train/004_forg/0105004_03.png \n extracting: sign_data/sign_data/train/004_forg/0105004_04.png \n extracting: sign_data/sign_data/train/004_forg/0124004_01.png \n extracting: sign_data/sign_data/train/004_forg/0124004_02.png \n extracting: sign_data/sign_data/train/004_forg/0124004_03.png \n extracting: sign_data/sign_data/train/004_forg/0124004_04.png \n creating: sign_data/sign_data/train/006/\n extracting: sign_data/sign_data/train/006/006_01.PNG \n extracting: sign_data/sign_data/train/006/006_02.PNG \n extracting: sign_data/sign_data/train/006/006_03.PNG \n extracting: sign_data/sign_data/train/006/006_04.PNG \n extracting: sign_data/sign_data/train/006/006_05.PNG \n extracting: sign_data/sign_data/train/006/006_06.PNG \n extracting: sign_data/sign_data/train/006/006_07.PNG \n extracting: sign_data/sign_data/train/006/006_08.PNG \n extracting: sign_data/sign_data/train/006/006_09.PNG \n extracting: sign_data/sign_data/train/006/006_10.PNG \n extracting: sign_data/sign_data/train/006/006_11.PNG \n extracting: sign_data/sign_data/train/006/006_12.PNG \n extracting: sign_data/sign_data/train/006/006_13.PNG \n extracting: sign_data/sign_data/train/006/006_14.PNG \n extracting: sign_data/sign_data/train/006/006_15.PNG \n extracting: sign_data/sign_data/train/006/006_16.PNG \n extracting: sign_data/sign_data/train/006/006_17.PNG \n extracting: sign_data/sign_data/train/006/006_18.PNG \n extracting: sign_data/sign_data/train/006/006_19.PNG \n extracting: sign_data/sign_data/train/006/006_20.PNG \n extracting: sign_data/sign_data/train/006/006_21.PNG \n extracting: sign_data/sign_data/train/006/006_22.PNG \n extracting: sign_data/sign_data/train/006/006_23.PNG \n extracting: sign_data/sign_data/train/006/006_24.PNG \n creating: sign_data/sign_data/train/006_forg/\n extracting: sign_data/sign_data/train/006_forg/0111006_01.png \n extracting: sign_data/sign_data/train/006_forg/0111006_02.png \n extracting: sign_data/sign_data/train/006_forg/0111006_03.png \n extracting: sign_data/sign_data/train/006_forg/0111006_04.png \n extracting: sign_data/sign_data/train/006_forg/0202006_01.png \n extracting: sign_data/sign_data/train/006_forg/0202006_02.png \n extracting: sign_data/sign_data/train/006_forg/0202006_03.png \n extracting: sign_data/sign_data/train/006_forg/0202006_04.png \n extracting: sign_data/sign_data/train/006_forg/0205006_01.png \n extracting: sign_data/sign_data/train/006_forg/0205006_02.png \n extracting: sign_data/sign_data/train/006_forg/0205006_03.png \n extracting: sign_data/sign_data/train/006_forg/0205006_04.png \n creating: sign_data/sign_data/train/009/\n extracting: sign_data/sign_data/train/009/009_01.PNG \n extracting: sign_data/sign_data/train/009/009_02.PNG \n extracting: sign_data/sign_data/train/009/009_03.PNG \n extracting: sign_data/sign_data/train/009/009_04.PNG \n extracting: sign_data/sign_data/train/009/009_05.PNG \n extracting: sign_data/sign_data/train/009/009_06.PNG \n extracting: sign_data/sign_data/train/009/009_07.PNG \n extracting: sign_data/sign_data/train/009/009_08.PNG \n extracting: sign_data/sign_data/train/009/009_09.PNG \n extracting: sign_data/sign_data/train/009/009_10.PNG \n extracting: sign_data/sign_data/train/009/009_11.PNG \n extracting: sign_data/sign_data/train/009/009_12.PNG \n extracting: sign_data/sign_data/train/009/009_13.PNG \n extracting: sign_data/sign_data/train/009/009_14.PNG \n extracting: sign_data/sign_data/train/009/009_15.PNG \n extracting: sign_data/sign_data/train/009/009_16.PNG \n extracting: sign_data/sign_data/train/009/009_17.PNG \n extracting: sign_data/sign_data/train/009/009_18.PNG \n extracting: sign_data/sign_data/train/009/009_19.PNG \n extracting: sign_data/sign_data/train/009/009_20.PNG \n extracting: sign_data/sign_data/train/009/009_21.PNG \n extracting: sign_data/sign_data/train/009/009_22.PNG \n extracting: sign_data/sign_data/train/009/009_23.PNG \n extracting: sign_data/sign_data/train/009/009_24.PNG \n creating: sign_data/sign_data/train/009_forg/\n extracting: sign_data/sign_data/train/009_forg/0117009_01.png \n extracting: sign_data/sign_data/train/009_forg/0117009_02.png \n extracting: sign_data/sign_data/train/009_forg/0117009_03.png \n extracting: sign_data/sign_data/train/009_forg/0117009_04.png \n extracting: sign_data/sign_data/train/009_forg/0123009_01.png \n extracting: sign_data/sign_data/train/009_forg/0123009_02.png \n extracting: sign_data/sign_data/train/009_forg/0123009_03.png \n extracting: sign_data/sign_data/train/009_forg/0123009_04.png \n extracting: sign_data/sign_data/train/009_forg/0201009_01.png \n extracting: sign_data/sign_data/train/009_forg/0201009_02.png \n extracting: sign_data/sign_data/train/009_forg/0201009_03.png \n extracting: sign_data/sign_data/train/009_forg/0201009_04.png \n creating: sign_data/sign_data/train/012/\n extracting: sign_data/sign_data/train/012/012_01.PNG \n extracting: sign_data/sign_data/train/012/012_02.PNG \n extracting: sign_data/sign_data/train/012/012_03.PNG \n extracting: sign_data/sign_data/train/012/012_04.PNG \n extracting: sign_data/sign_data/train/012/012_05.PNG \n extracting: sign_data/sign_data/train/012/012_06.PNG \n extracting: sign_data/sign_data/train/012/012_07.PNG \n extracting: sign_data/sign_data/train/012/012_08.PNG \n extracting: sign_data/sign_data/train/012/012_09.PNG \n extracting: sign_data/sign_data/train/012/012_10.PNG \n extracting: sign_data/sign_data/train/012/012_11.PNG \n extracting: sign_data/sign_data/train/012/012_12.PNG \n extracting: sign_data/sign_data/train/012/012_13.PNG \n extracting: sign_data/sign_data/train/012/012_14.PNG \n extracting: sign_data/sign_data/train/012/012_15.PNG \n extracting: sign_data/sign_data/train/012/012_16.PNG \n extracting: sign_data/sign_data/train/012/012_17.PNG \n extracting: sign_data/sign_data/train/012/012_18.PNG \n extracting: sign_data/sign_data/train/012/012_19.PNG \n extracting: sign_data/sign_data/train/012/012_20.PNG \n extracting: sign_data/sign_data/train/012/012_21.PNG \n extracting: sign_data/sign_data/train/012/012_22.PNG \n extracting: sign_data/sign_data/train/012/012_23.PNG \n extracting: sign_data/sign_data/train/012/012_24.PNG \n creating: sign_data/sign_data/train/012_forg/\n extracting: sign_data/sign_data/train/012_forg/0113012_01.png \n extracting: sign_data/sign_data/train/012_forg/0113012_02.png \n extracting: sign_data/sign_data/train/012_forg/0113012_03.png \n extracting: sign_data/sign_data/train/012_forg/0113012_04.png \n extracting: sign_data/sign_data/train/012_forg/0206012_01.png \n extracting: sign_data/sign_data/train/012_forg/0206012_02.png \n extracting: sign_data/sign_data/train/012_forg/0206012_03.png \n extracting: sign_data/sign_data/train/012_forg/0206012_04.png \n extracting: sign_data/sign_data/train/012_forg/0210012_01.png \n extracting: sign_data/sign_data/train/012_forg/0210012_02.png \n extracting: sign_data/sign_data/train/012_forg/0210012_03.png \n extracting: sign_data/sign_data/train/012_forg/0210012_04.png \n creating: sign_data/sign_data/train/013/\n extracting: sign_data/sign_data/train/013/01_013.png \n extracting: sign_data/sign_data/train/013/02_013.png \n extracting: sign_data/sign_data/train/013/03_013.png \n extracting: sign_data/sign_data/train/013/04_013.png \n extracting: sign_data/sign_data/train/013/05_013.png \n extracting: sign_data/sign_data/train/013/06_013.png \n extracting: sign_data/sign_data/train/013/07_013.png \n extracting: sign_data/sign_data/train/013/08_013.png \n extracting: sign_data/sign_data/train/013/09_013.png \n extracting: sign_data/sign_data/train/013/10_013.png \n extracting: sign_data/sign_data/train/013/11_013.png \n extracting: sign_data/sign_data/train/013/12_013.png \n creating: sign_data/sign_data/train/013_forg/\n extracting: sign_data/sign_data/train/013_forg/01_0113013.PNG \n extracting: sign_data/sign_data/train/013_forg/01_0203013.PNG \n extracting: sign_data/sign_data/train/013_forg/01_0204013.PNG \n extracting: sign_data/sign_data/train/013_forg/02_0113013.PNG \n extracting: sign_data/sign_data/train/013_forg/02_0203013.PNG \n extracting: sign_data/sign_data/train/013_forg/02_0204013.PNG \n extracting: sign_data/sign_data/train/013_forg/03_0113013.PNG \n extracting: sign_data/sign_data/train/013_forg/03_0203013.PNG \n extracting: sign_data/sign_data/train/013_forg/03_0204013.PNG \n extracting: sign_data/sign_data/train/013_forg/04_0113013.PNG \n extracting: sign_data/sign_data/train/013_forg/04_0203013.PNG \n extracting: sign_data/sign_data/train/013_forg/04_0204013.PNG \n creating: sign_data/sign_data/train/014/\n extracting: sign_data/sign_data/train/014/014_01.PNG \n extracting: sign_data/sign_data/train/014/014_02.PNG \n extracting: sign_data/sign_data/train/014/014_03.PNG \n extracting: sign_data/sign_data/train/014/014_04.PNG \n extracting: sign_data/sign_data/train/014/014_05.PNG \n extracting: sign_data/sign_data/train/014/014_06.PNG \n extracting: sign_data/sign_data/train/014/014_07.PNG \n extracting: sign_data/sign_data/train/014/014_08.PNG \n extracting: sign_data/sign_data/train/014/014_09.PNG \n extracting: sign_data/sign_data/train/014/014_10.PNG \n extracting: sign_data/sign_data/train/014/014_11.PNG \n extracting: sign_data/sign_data/train/014/014_12.PNG \n extracting: sign_data/sign_data/train/014/014_13.PNG \n extracting: sign_data/sign_data/train/014/014_14.PNG \n extracting: sign_data/sign_data/train/014/014_15.PNG \n extracting: sign_data/sign_data/train/014/014_16.PNG \n extracting: sign_data/sign_data/train/014/014_17.PNG \n extracting: sign_data/sign_data/train/014/014_18.PNG \n extracting: sign_data/sign_data/train/014/014_19.PNG \n extracting: sign_data/sign_data/train/014/014_20.PNG \n extracting: sign_data/sign_data/train/014/014_21.PNG \n extracting: sign_data/sign_data/train/014/014_22.PNG \n extracting: sign_data/sign_data/train/014/014_23.PNG \n extracting: sign_data/sign_data/train/014/014_24.PNG \n creating: sign_data/sign_data/train/014_forg/\n extracting: sign_data/sign_data/train/014_forg/0102014_01.png \n extracting: sign_data/sign_data/train/014_forg/0102014_02.png \n extracting: sign_data/sign_data/train/014_forg/0102014_03.png \n extracting: sign_data/sign_data/train/014_forg/0102014_04.png \n extracting: sign_data/sign_data/train/014_forg/0104014_01.png \n extracting: sign_data/sign_data/train/014_forg/0104014_02.png \n extracting: sign_data/sign_data/train/014_forg/0104014_03.png \n extracting: sign_data/sign_data/train/014_forg/0104014_04.png \n extracting: sign_data/sign_data/train/014_forg/0208014_01.png \n extracting: sign_data/sign_data/train/014_forg/0208014_02.png \n extracting: sign_data/sign_data/train/014_forg/0208014_03.png \n extracting: sign_data/sign_data/train/014_forg/0208014_04.png \n extracting: sign_data/sign_data/train/014_forg/0214014_01.png \n extracting: sign_data/sign_data/train/014_forg/0214014_02.png \n extracting: sign_data/sign_data/train/014_forg/0214014_03.png \n extracting: sign_data/sign_data/train/014_forg/0214014_04.png \n creating: sign_data/sign_data/train/015/\n extracting: sign_data/sign_data/train/015/015_01.PNG \n extracting: sign_data/sign_data/train/015/015_02.PNG \n extracting: sign_data/sign_data/train/015/015_03.PNG \n extracting: sign_data/sign_data/train/015/015_04.PNG \n extracting: sign_data/sign_data/train/015/015_05.PNG \n extracting: sign_data/sign_data/train/015/015_06.PNG \n extracting: sign_data/sign_data/train/015/015_07.PNG \n extracting: sign_data/sign_data/train/015/015_08.PNG \n extracting: sign_data/sign_data/train/015/015_09.PNG \n extracting: sign_data/sign_data/train/015/015_10.PNG \n extracting: sign_data/sign_data/train/015/015_11.PNG \n extracting: sign_data/sign_data/train/015/015_12.PNG \n extracting: sign_data/sign_data/train/015/015_13.PNG \n extracting: sign_data/sign_data/train/015/015_14.PNG \n extracting: sign_data/sign_data/train/015/015_15.PNG \n extracting: sign_data/sign_data/train/015/015_16.PNG \n extracting: sign_data/sign_data/train/015/015_17.PNG \n extracting: sign_data/sign_data/train/015/015_18.PNG \n extracting: sign_data/sign_data/train/015/015_19.PNG \n extracting: sign_data/sign_data/train/015/015_20.PNG \n extracting: sign_data/sign_data/train/015/015_21.PNG \n extracting: sign_data/sign_data/train/015/015_22.PNG \n extracting: sign_data/sign_data/train/015/015_23.PNG \n extracting: sign_data/sign_data/train/015/015_24.PNG \n creating: sign_data/sign_data/train/015_forg/\n extracting: sign_data/sign_data/train/015_forg/0106015_01.png \n extracting: sign_data/sign_data/train/015_forg/0106015_02.png \n extracting: sign_data/sign_data/train/015_forg/0106015_03.png \n extracting: sign_data/sign_data/train/015_forg/0106015_04.png \n extracting: sign_data/sign_data/train/015_forg/0210015_01.png \n extracting: sign_data/sign_data/train/015_forg/0210015_02.png \n extracting: sign_data/sign_data/train/015_forg/0210015_03.png \n extracting: sign_data/sign_data/train/015_forg/0210015_04.png \n extracting: sign_data/sign_data/train/015_forg/0213015_01.png \n extracting: sign_data/sign_data/train/015_forg/0213015_02.png \n extracting: sign_data/sign_data/train/015_forg/0213015_03.png \n extracting: sign_data/sign_data/train/015_forg/0213015_04.png \n creating: sign_data/sign_data/train/016/\n extracting: sign_data/sign_data/train/016/016_01.PNG \n extracting: sign_data/sign_data/train/016/016_02.PNG \n extracting: sign_data/sign_data/train/016/016_03.PNG \n extracting: sign_data/sign_data/train/016/016_04.PNG \n extracting: sign_data/sign_data/train/016/016_05.PNG \n extracting: sign_data/sign_data/train/016/016_06.PNG \n extracting: sign_data/sign_data/train/016/016_07.PNG \n extracting: sign_data/sign_data/train/016/016_08.PNG \n extracting: sign_data/sign_data/train/016/016_09.PNG \n extracting: sign_data/sign_data/train/016/016_10.PNG \n extracting: sign_data/sign_data/train/016/016_11.PNG \n extracting: sign_data/sign_data/train/016/016_12.PNG \n extracting: sign_data/sign_data/train/016/016_13.PNG \n extracting: sign_data/sign_data/train/016/016_14.PNG \n extracting: sign_data/sign_data/train/016/016_15.PNG \n extracting: sign_data/sign_data/train/016/016_16.PNG \n extracting: sign_data/sign_data/train/016/016_17.PNG \n extracting: sign_data/sign_data/train/016/016_18.PNG \n extracting: sign_data/sign_data/train/016/016_20.PNG \n extracting: sign_data/sign_data/train/016/016_21.PNG \n extracting: sign_data/sign_data/train/016/016_22.PNG \n extracting: sign_data/sign_data/train/016/016_23.PNG \n extracting: sign_data/sign_data/train/016/016_24.PNG \n creating: sign_data/sign_data/train/016_forg/\n extracting: sign_data/sign_data/train/016_forg/0107016_01.png \n extracting: sign_data/sign_data/train/016_forg/0107016_02.png \n extracting: sign_data/sign_data/train/016_forg/0107016_03.png \n extracting: sign_data/sign_data/train/016_forg/0107016_04.png \n extracting: sign_data/sign_data/train/016_forg/0110016_01.png \n extracting: sign_data/sign_data/train/016_forg/0110016_02.png \n extracting: sign_data/sign_data/train/016_forg/0110016_03.png \n extracting: sign_data/sign_data/train/016_forg/0110016_04.png \n extracting: sign_data/sign_data/train/016_forg/0127016_01.png \n extracting: sign_data/sign_data/train/016_forg/0127016_02.png \n extracting: sign_data/sign_data/train/016_forg/0127016_03.png \n extracting: sign_data/sign_data/train/016_forg/0127016_04.png \n extracting: sign_data/sign_data/train/016_forg/0202016_01.png \n extracting: sign_data/sign_data/train/016_forg/0202016_02.png \n extracting: sign_data/sign_data/train/016_forg/0202016_03.png \n extracting: sign_data/sign_data/train/016_forg/0202016_04.png \n creating: sign_data/sign_data/train/017/\n extracting: sign_data/sign_data/train/017/01_017.png \n extracting: sign_data/sign_data/train/017/02_017.png \n extracting: sign_data/sign_data/train/017/03_017.png \n extracting: sign_data/sign_data/train/017/04_017.png \n extracting: sign_data/sign_data/train/017/05_017.png \n extracting: sign_data/sign_data/train/017/06_017.png \n extracting: sign_data/sign_data/train/017/07_017.png \n extracting: sign_data/sign_data/train/017/08_017.png \n extracting: sign_data/sign_data/train/017/09_017.png \n extracting: sign_data/sign_data/train/017/10_017.png \n extracting: sign_data/sign_data/train/017/11_017.png \n extracting: sign_data/sign_data/train/017/12_017.png \n creating: sign_data/sign_data/train/017_forg/\n extracting: sign_data/sign_data/train/017_forg/01_0107017.PNG \n extracting: sign_data/sign_data/train/017_forg/01_0124017.PNG \n extracting: sign_data/sign_data/train/017_forg/01_0211017.PNG \n extracting: sign_data/sign_data/train/017_forg/02_0107017.PNG \n extracting: sign_data/sign_data/train/017_forg/02_0124017.PNG \n extracting: sign_data/sign_data/train/017_forg/02_0211017.PNG \n extracting: sign_data/sign_data/train/017_forg/03_0107017.PNG \n extracting: sign_data/sign_data/train/017_forg/03_0124017.PNG \n extracting: sign_data/sign_data/train/017_forg/03_0211017.PNG \n extracting: sign_data/sign_data/train/017_forg/04_0107017.PNG \n extracting: sign_data/sign_data/train/017_forg/04_0124017.PNG \n extracting: sign_data/sign_data/train/017_forg/04_0211017.PNG \n creating: sign_data/sign_data/train/018/\n extracting: sign_data/sign_data/train/018/01_018.png \n extracting: sign_data/sign_data/train/018/02_018.png \n extracting: sign_data/sign_data/train/018/03_018.png \n extracting: sign_data/sign_data/train/018/04_018.png \n extracting: sign_data/sign_data/train/018/05_018.png \n extracting: sign_data/sign_data/train/018/06_018.png \n extracting: sign_data/sign_data/train/018/07_018.png \n extracting: sign_data/sign_data/train/018/08_018.png \n extracting: sign_data/sign_data/train/018/09_018.png \n extracting: sign_data/sign_data/train/018/10_018.png \n extracting: sign_data/sign_data/train/018/11_018.png \n extracting: sign_data/sign_data/train/018/12_018.png \n creating: sign_data/sign_data/train/018_forg/\n extracting: sign_data/sign_data/train/018_forg/01_0106018.PNG \n extracting: sign_data/sign_data/train/018_forg/01_0112018.PNG \n extracting: sign_data/sign_data/train/018_forg/01_0202018.PNG \n extracting: sign_data/sign_data/train/018_forg/02_0106018.PNG \n extracting: sign_data/sign_data/train/018_forg/02_0112018.PNG \n extracting: sign_data/sign_data/train/018_forg/02_0202018.PNG \n extracting: sign_data/sign_data/train/018_forg/03_0106018.PNG \n extracting: sign_data/sign_data/train/018_forg/03_0112018.PNG \n extracting: sign_data/sign_data/train/018_forg/03_0202018.PNG \n extracting: sign_data/sign_data/train/018_forg/04_0106018.PNG \n extracting: sign_data/sign_data/train/018_forg/04_0112018.PNG \n extracting: sign_data/sign_data/train/018_forg/04_0202018.PNG \n creating: sign_data/sign_data/train/019/\n extracting: sign_data/sign_data/train/019/01_019.png \n extracting: sign_data/sign_data/train/019/02_019.png \n extracting: sign_data/sign_data/train/019/03_019.png \n extracting: sign_data/sign_data/train/019/04_019.png \n extracting: sign_data/sign_data/train/019/05_019.png \n extracting: sign_data/sign_data/train/019/06_019.png \n extracting: sign_data/sign_data/train/019/07_019.png \n extracting: sign_data/sign_data/train/019/08_019.png \n extracting: sign_data/sign_data/train/019/09_019.png \n extracting: sign_data/sign_data/train/019/10_019.png \n extracting: sign_data/sign_data/train/019/11_019.png \n extracting: sign_data/sign_data/train/019/12_019.png \n creating: sign_data/sign_data/train/019_forg/\n extracting: sign_data/sign_data/train/019_forg/01_0115019.PNG \n extracting: sign_data/sign_data/train/019_forg/01_0116019.PNG \n extracting: sign_data/sign_data/train/019_forg/01_0119019.PNG \n extracting: sign_data/sign_data/train/019_forg/02_0115019.PNG \n extracting: sign_data/sign_data/train/019_forg/02_0116019.PNG \n extracting: sign_data/sign_data/train/019_forg/02_0119019.PNG \n extracting: sign_data/sign_data/train/019_forg/03_0115019.PNG \n extracting: sign_data/sign_data/train/019_forg/03_0116019.PNG \n extracting: sign_data/sign_data/train/019_forg/03_0119019.PNG \n extracting: sign_data/sign_data/train/019_forg/04_0115019.PNG \n extracting: sign_data/sign_data/train/019_forg/04_0116019.PNG \n extracting: sign_data/sign_data/train/019_forg/04_0119019.PNG \n creating: sign_data/sign_data/train/020/\n extracting: sign_data/sign_data/train/020/01_020.png \n extracting: sign_data/sign_data/train/020/02_020.png \n extracting: sign_data/sign_data/train/020/03_020.png \n extracting: sign_data/sign_data/train/020/04_020.png \n extracting: sign_data/sign_data/train/020/05_020.png \n extracting: sign_data/sign_data/train/020/06_020.png \n extracting: sign_data/sign_data/train/020/07_020.png \n extracting: sign_data/sign_data/train/020/08_020.png \n extracting: sign_data/sign_data/train/020/09_020.png \n extracting: sign_data/sign_data/train/020/10_020.png \n extracting: sign_data/sign_data/train/020/11_020.png \n extracting: sign_data/sign_data/train/020/12_020.png \n creating: sign_data/sign_data/train/020_forg/\n extracting: sign_data/sign_data/train/020_forg/01_0105020.PNG \n extracting: sign_data/sign_data/train/020_forg/01_0117020.PNG \n extracting: sign_data/sign_data/train/020_forg/01_0127020.PNG \n extracting: sign_data/sign_data/train/020_forg/01_0213020.PNG \n extracting: sign_data/sign_data/train/020_forg/02_0101020.PNG \n extracting: sign_data/sign_data/train/020_forg/02_0105020.PNG \n extracting: sign_data/sign_data/train/020_forg/02_0117020.PNG \n extracting: sign_data/sign_data/train/020_forg/02_0127020.PNG \n extracting: sign_data/sign_data/train/020_forg/02_0213020.PNG \n extracting: sign_data/sign_data/train/020_forg/03_0101020.PNG \n extracting: sign_data/sign_data/train/020_forg/03_0105020.PNG \n extracting: sign_data/sign_data/train/020_forg/03_0117020.PNG \n extracting: sign_data/sign_data/train/020_forg/03_0127020.PNG \n extracting: sign_data/sign_data/train/020_forg/03_0213020.PNG \n extracting: sign_data/sign_data/train/020_forg/04_0101020.PNG \n extracting: sign_data/sign_data/train/020_forg/04_0105020.PNG \n extracting: sign_data/sign_data/train/020_forg/04_0117020.PNG \n extracting: sign_data/sign_data/train/020_forg/04_0127020.PNG \n extracting: sign_data/sign_data/train/020_forg/04_0213020.PNG \n creating: sign_data/sign_data/train/021/\n extracting: sign_data/sign_data/train/021/01_021.png \n extracting: sign_data/sign_data/train/021/02_021.png \n extracting: sign_data/sign_data/train/021/03_021.png \n extracting: sign_data/sign_data/train/021/04_021.png \n extracting: sign_data/sign_data/train/021/05_021.png \n extracting: sign_data/sign_data/train/021/06_021.png \n extracting: sign_data/sign_data/train/021/07_021.png \n extracting: sign_data/sign_data/train/021/08_021.png \n extracting: sign_data/sign_data/train/021/09_021.png \n extracting: sign_data/sign_data/train/021/10_021.png \n extracting: sign_data/sign_data/train/021/11_021.png \n extracting: sign_data/sign_data/train/021/12_021.png \n creating: sign_data/sign_data/train/021_forg/\n extracting: sign_data/sign_data/train/021_forg/01_0110021.PNG \n extracting: sign_data/sign_data/train/021_forg/01_0204021.PNG \n extracting: sign_data/sign_data/train/021_forg/01_0211021.PNG \n extracting: sign_data/sign_data/train/021_forg/02_0110021.PNG \n extracting: sign_data/sign_data/train/021_forg/02_0204021.PNG \n extracting: sign_data/sign_data/train/021_forg/02_0211021.PNG \n extracting: sign_data/sign_data/train/021_forg/03_0110021.PNG \n extracting: sign_data/sign_data/train/021_forg/03_0204021.PNG \n extracting: sign_data/sign_data/train/021_forg/03_0211021.PNG \n extracting: sign_data/sign_data/train/021_forg/04_0110021.PNG \n extracting: sign_data/sign_data/train/021_forg/04_0204021.PNG \n extracting: sign_data/sign_data/train/021_forg/04_0211021.PNG \n creating: sign_data/sign_data/train/022/\n extracting: sign_data/sign_data/train/022/01_022.png \n extracting: sign_data/sign_data/train/022/02_022.png \n extracting: sign_data/sign_data/train/022/03_022.png \n extracting: sign_data/sign_data/train/022/04_022.png \n extracting: sign_data/sign_data/train/022/05_022.png \n extracting: sign_data/sign_data/train/022/06_022.png \n extracting: sign_data/sign_data/train/022/07_022.png \n extracting: sign_data/sign_data/train/022/08_022.png \n extracting: sign_data/sign_data/train/022/09_022.png \n extracting: sign_data/sign_data/train/022/10_022.png \n extracting: sign_data/sign_data/train/022/11_022.png \n extracting: sign_data/sign_data/train/022/12_022.png \n creating: sign_data/sign_data/train/022_forg/\n extracting: sign_data/sign_data/train/022_forg/01_0125022.PNG \n extracting: sign_data/sign_data/train/022_forg/01_0127022.PNG \n extracting: sign_data/sign_data/train/022_forg/01_0208022.PNG \n extracting: sign_data/sign_data/train/022_forg/01_0214022.PNG \n extracting: sign_data/sign_data/train/022_forg/02_0125022.PNG \n extracting: sign_data/sign_data/train/022_forg/02_0127022.PNG \n extracting: sign_data/sign_data/train/022_forg/02_0208022.PNG \n extracting: sign_data/sign_data/train/022_forg/02_0214022.PNG \n extracting: sign_data/sign_data/train/022_forg/03_0125022.PNG \n extracting: sign_data/sign_data/train/022_forg/03_0127022.PNG \n extracting: sign_data/sign_data/train/022_forg/03_0208022.PNG \n extracting: sign_data/sign_data/train/022_forg/03_0214022.PNG \n extracting: sign_data/sign_data/train/022_forg/04_0125022.PNG \n extracting: sign_data/sign_data/train/022_forg/04_0127022.PNG \n extracting: sign_data/sign_data/train/022_forg/04_0208022.PNG \n extracting: sign_data/sign_data/train/022_forg/04_0214022.PNG \n creating: sign_data/sign_data/train/023/\n extracting: sign_data/sign_data/train/023/01_023.png \n extracting: sign_data/sign_data/train/023/02_023.png \n extracting: sign_data/sign_data/train/023/03_023.png \n extracting: sign_data/sign_data/train/023/04_023.png \n extracting: sign_data/sign_data/train/023/05_023.png \n extracting: sign_data/sign_data/train/023/06_023.png \n extracting: sign_data/sign_data/train/023/07_023.png \n extracting: sign_data/sign_data/train/023/08_023.png \n extracting: sign_data/sign_data/train/023/09_023.png \n extracting: sign_data/sign_data/train/023/10_023.png \n extracting: sign_data/sign_data/train/023/11_023.png \n extracting: sign_data/sign_data/train/023/12_023.png \n creating: sign_data/sign_data/train/023_forg/\n extracting: sign_data/sign_data/train/023_forg/01_0126023.PNG \n extracting: sign_data/sign_data/train/023_forg/01_0203023.PNG \n extracting: sign_data/sign_data/train/023_forg/02_0126023.PNG \n extracting: sign_data/sign_data/train/023_forg/02_0203023.PNG \n extracting: sign_data/sign_data/train/023_forg/03_0126023.PNG \n extracting: sign_data/sign_data/train/023_forg/03_0203023.PNG \n extracting: sign_data/sign_data/train/023_forg/04_0126023.PNG \n extracting: sign_data/sign_data/train/023_forg/04_0203023.PNG \n creating: sign_data/sign_data/train/024/\n extracting: sign_data/sign_data/train/024/01_024.png \n extracting: sign_data/sign_data/train/024/02_024.png \n extracting: sign_data/sign_data/train/024/03_024.png \n extracting: sign_data/sign_data/train/024/04_024.png \n extracting: sign_data/sign_data/train/024/05_024.png \n extracting: sign_data/sign_data/train/024/06_024.png \n extracting: sign_data/sign_data/train/024/07_024.png \n extracting: sign_data/sign_data/train/024/08_024.png \n extracting: sign_data/sign_data/train/024/09_024.png \n extracting: sign_data/sign_data/train/024/10_024.png \n extracting: sign_data/sign_data/train/024/11_024.png \n extracting: sign_data/sign_data/train/024/12_024.png \n creating: sign_data/sign_data/train/024_forg/\n extracting: sign_data/sign_data/train/024_forg/01_0102024.PNG \n extracting: sign_data/sign_data/train/024_forg/01_0119024.PNG \n extracting: sign_data/sign_data/train/024_forg/01_0120024.PNG \n extracting: sign_data/sign_data/train/024_forg/02_0102024.PNG \n extracting: sign_data/sign_data/train/024_forg/02_0119024.PNG \n extracting: sign_data/sign_data/train/024_forg/02_0120024.PNG \n extracting: sign_data/sign_data/train/024_forg/03_0102024.PNG \n extracting: sign_data/sign_data/train/024_forg/03_0119024.PNG \n extracting: sign_data/sign_data/train/024_forg/03_0120024.PNG \n extracting: sign_data/sign_data/train/024_forg/04_0102024.PNG \n extracting: sign_data/sign_data/train/024_forg/04_0119024.PNG \n extracting: sign_data/sign_data/train/024_forg/04_0120024.PNG \n creating: sign_data/sign_data/train/025/\n extracting: sign_data/sign_data/train/025/01_025.png \n extracting: sign_data/sign_data/train/025/02_025.png \n extracting: sign_data/sign_data/train/025/03_025.png \n extracting: sign_data/sign_data/train/025/04_025.png \n extracting: sign_data/sign_data/train/025/05_025.png \n extracting: sign_data/sign_data/train/025/06_025.png \n extracting: sign_data/sign_data/train/025/07_025.png \n extracting: sign_data/sign_data/train/025/08_025.png \n extracting: sign_data/sign_data/train/025/09_025.png \n extracting: sign_data/sign_data/train/025/10_025.png \n extracting: sign_data/sign_data/train/025/11_025.png \n extracting: sign_data/sign_data/train/025/12_025.png \n creating: sign_data/sign_data/train/025_forg/\n extracting: sign_data/sign_data/train/025_forg/01_0116025.PNG \n extracting: sign_data/sign_data/train/025_forg/01_0121025.PNG \n extracting: sign_data/sign_data/train/025_forg/02_0116025.PNG \n extracting: sign_data/sign_data/train/025_forg/02_0121025.PNG \n extracting: sign_data/sign_data/train/025_forg/03_0116025.PNG \n extracting: sign_data/sign_data/train/025_forg/03_0121025.PNG \n extracting: sign_data/sign_data/train/025_forg/04_0116025.PNG \n extracting: sign_data/sign_data/train/025_forg/04_0121025.PNG \n creating: sign_data/sign_data/train/026/\n extracting: sign_data/sign_data/train/026/01_026.png \n extracting: sign_data/sign_data/train/026/02_026.png \n extracting: sign_data/sign_data/train/026/03_026.png \n extracting: sign_data/sign_data/train/026/04_026.png \n extracting: sign_data/sign_data/train/026/05_026.png \n extracting: sign_data/sign_data/train/026/06_026.png \n extracting: sign_data/sign_data/train/026/07_026.png \n extracting: sign_data/sign_data/train/026/08_026.png \n extracting: sign_data/sign_data/train/026/09_026.png \n extracting: sign_data/sign_data/train/026/10_026.png \n extracting: sign_data/sign_data/train/026/11_026.png \n extracting: sign_data/sign_data/train/026/12_026.png \n creating: sign_data/sign_data/train/026_forg/\n extracting: sign_data/sign_data/train/026_forg/01_0119026.PNG \n extracting: sign_data/sign_data/train/026_forg/01_0123026.PNG \n extracting: sign_data/sign_data/train/026_forg/01_0125026.PNG \n extracting: sign_data/sign_data/train/026_forg/02_0119026.PNG \n extracting: sign_data/sign_data/train/026_forg/02_0123026.PNG \n extracting: sign_data/sign_data/train/026_forg/02_0125026.PNG \n extracting: sign_data/sign_data/train/026_forg/03_0119026.PNG \n extracting: sign_data/sign_data/train/026_forg/03_0123026.PNG \n extracting: sign_data/sign_data/train/026_forg/03_0125026.PNG \n extracting: sign_data/sign_data/train/026_forg/04_0119026.PNG \n extracting: sign_data/sign_data/train/026_forg/04_0123026.PNG \n extracting: sign_data/sign_data/train/026_forg/04_0125026.PNG \n creating: sign_data/sign_data/train/027/\n extracting: sign_data/sign_data/train/027/01_027.png \n extracting: sign_data/sign_data/train/027/02_027.png \n extracting: sign_data/sign_data/train/027/03_027.png \n extracting: sign_data/sign_data/train/027/04_027.png \n extracting: sign_data/sign_data/train/027/05_027.png \n extracting: sign_data/sign_data/train/027/06_027.png \n extracting: sign_data/sign_data/train/027/07_027.png \n extracting: sign_data/sign_data/train/027/08_027.png \n extracting: sign_data/sign_data/train/027/09_027.png \n extracting: sign_data/sign_data/train/027/10_027.png \n extracting: sign_data/sign_data/train/027/11_027.png \n extracting: sign_data/sign_data/train/027/12_027.png \n creating: sign_data/sign_data/train/027_forg/\n extracting: sign_data/sign_data/train/027_forg/01_0101027.PNG \n extracting: sign_data/sign_data/train/027_forg/01_0212027.PNG \n extracting: sign_data/sign_data/train/027_forg/02_0101027.PNG \n extracting: sign_data/sign_data/train/027_forg/02_0212027.PNG \n extracting: sign_data/sign_data/train/027_forg/03_0101027.PNG \n extracting: sign_data/sign_data/train/027_forg/03_0212027.PNG \n extracting: sign_data/sign_data/train/027_forg/04_0101027.PNG \n extracting: sign_data/sign_data/train/027_forg/04_0212027.PNG \n creating: sign_data/sign_data/train/028/\n extracting: sign_data/sign_data/train/028/01_028.png \n extracting: sign_data/sign_data/train/028/02_028.png \n extracting: sign_data/sign_data/train/028/03_028.png \n extracting: sign_data/sign_data/train/028/04_028.png \n extracting: sign_data/sign_data/train/028/05_028.png \n extracting: sign_data/sign_data/train/028/06_028.png \n extracting: sign_data/sign_data/train/028/07_028.png \n extracting: sign_data/sign_data/train/028/08_028.png \n extracting: sign_data/sign_data/train/028/09_028.png \n extracting: sign_data/sign_data/train/028/10_028.png \n extracting: sign_data/sign_data/train/028/11_028.png \n extracting: sign_data/sign_data/train/028/12_028.png \n creating: sign_data/sign_data/train/028_forg/\n extracting: sign_data/sign_data/train/028_forg/01_0126028.PNG \n extracting: sign_data/sign_data/train/028_forg/01_0205028.PNG \n extracting: sign_data/sign_data/train/028_forg/01_0212028.PNG \n extracting: sign_data/sign_data/train/028_forg/02_0126028.PNG \n extracting: sign_data/sign_data/train/028_forg/02_0205028.PNG \n extracting: sign_data/sign_data/train/028_forg/02_0212028.PNG \n extracting: sign_data/sign_data/train/028_forg/03_0126028.PNG \n extracting: sign_data/sign_data/train/028_forg/03_0205028.PNG \n extracting: sign_data/sign_data/train/028_forg/03_0212028.PNG \n extracting: sign_data/sign_data/train/028_forg/04_0126028.PNG \n extracting: sign_data/sign_data/train/028_forg/04_0205028.PNG \n extracting: sign_data/sign_data/train/028_forg/04_0212028.PNG \n creating: sign_data/sign_data/train/029/\n extracting: sign_data/sign_data/train/029/01_029.png \n extracting: sign_data/sign_data/train/029/02_029.png \n extracting: sign_data/sign_data/train/029/03_029.png \n extracting: sign_data/sign_data/train/029/04_029.png \n extracting: sign_data/sign_data/train/029/05_029.png \n extracting: sign_data/sign_data/train/029/06_029.png \n extracting: sign_data/sign_data/train/029/07_029.png \n extracting: sign_data/sign_data/train/029/08_029.png \n extracting: sign_data/sign_data/train/029/09_029.png \n extracting: sign_data/sign_data/train/029/10_029.png \n extracting: sign_data/sign_data/train/029/11_029.png \n extracting: sign_data/sign_data/train/029/12_029.png \n creating: sign_data/sign_data/train/029_forg/\n extracting: sign_data/sign_data/train/029_forg/01_0104029.PNG \n extracting: sign_data/sign_data/train/029_forg/01_0115029.PNG \n extracting: sign_data/sign_data/train/029_forg/01_0203029.PNG \n extracting: sign_data/sign_data/train/029_forg/02_0104029.PNG \n extracting: sign_data/sign_data/train/029_forg/02_0115029.PNG \n extracting: sign_data/sign_data/train/029_forg/02_0203029.PNG \n extracting: sign_data/sign_data/train/029_forg/03_0104029.PNG \n extracting: sign_data/sign_data/train/029_forg/03_0115029.PNG \n extracting: sign_data/sign_data/train/029_forg/03_0203029.PNG \n extracting: sign_data/sign_data/train/029_forg/04_0104029.PNG \n extracting: sign_data/sign_data/train/029_forg/04_0115029.PNG \n extracting: sign_data/sign_data/train/029_forg/04_0203029.PNG \n creating: sign_data/sign_data/train/030/\n extracting: sign_data/sign_data/train/030/01_030.png \n extracting: sign_data/sign_data/train/030/02_030.png \n extracting: sign_data/sign_data/train/030/03_030.png \n extracting: sign_data/sign_data/train/030/04_030.png \n extracting: sign_data/sign_data/train/030/05_030.png \n extracting: sign_data/sign_data/train/030/06_030.png \n extracting: sign_data/sign_data/train/030/07_030.png \n extracting: sign_data/sign_data/train/030/08_030.png \n extracting: sign_data/sign_data/train/030/09_030.png \n extracting: sign_data/sign_data/train/030/10_030.png \n extracting: sign_data/sign_data/train/030/11_030.png \n extracting: sign_data/sign_data/train/030/12_030.png \n creating: sign_data/sign_data/train/030_forg/\n extracting: sign_data/sign_data/train/030_forg/01_0109030.PNG \n extracting: sign_data/sign_data/train/030_forg/01_0114030.PNG \n extracting: sign_data/sign_data/train/030_forg/01_0213030.PNG \n extracting: sign_data/sign_data/train/030_forg/02_0109030.PNG \n extracting: sign_data/sign_data/train/030_forg/02_0114030.PNG \n extracting: sign_data/sign_data/train/030_forg/02_0213030.PNG \n extracting: sign_data/sign_data/train/030_forg/03_0109030.PNG \n extracting: sign_data/sign_data/train/030_forg/03_0114030.PNG \n extracting: sign_data/sign_data/train/030_forg/03_0213030.PNG \n extracting: sign_data/sign_data/train/030_forg/04_0109030.PNG \n extracting: sign_data/sign_data/train/030_forg/04_0114030.PNG \n extracting: sign_data/sign_data/train/030_forg/04_0213030.PNG \n creating: sign_data/sign_data/train/031/\n extracting: sign_data/sign_data/train/031/01_031.png \n extracting: sign_data/sign_data/train/031/02_031.png \n extracting: sign_data/sign_data/train/031/03_031.png \n extracting: sign_data/sign_data/train/031/04_031.png \n extracting: sign_data/sign_data/train/031/05_031.png \n extracting: sign_data/sign_data/train/031/06_031.png \n extracting: sign_data/sign_data/train/031/07_031.png \n extracting: sign_data/sign_data/train/031/08_031.png \n extracting: sign_data/sign_data/train/031/09_031.png \n extracting: sign_data/sign_data/train/031/10_031.png \n extracting: sign_data/sign_data/train/031/11_031.png \n extracting: sign_data/sign_data/train/031/12_031.png \n creating: sign_data/sign_data/train/031_forg/\n extracting: sign_data/sign_data/train/031_forg/01_0103031.PNG \n extracting: sign_data/sign_data/train/031_forg/01_0121031.PNG \n extracting: sign_data/sign_data/train/031_forg/02_0103031.PNG \n extracting: sign_data/sign_data/train/031_forg/02_0121031.PNG \n extracting: sign_data/sign_data/train/031_forg/03_0103031.PNG \n extracting: sign_data/sign_data/train/031_forg/03_0121031.PNG \n extracting: sign_data/sign_data/train/031_forg/04_0103031.PNG \n extracting: sign_data/sign_data/train/031_forg/04_0121031.PNG \n creating: sign_data/sign_data/train/032/\n extracting: sign_data/sign_data/train/032/01_032.png \n extracting: sign_data/sign_data/train/032/02_032.png \n extracting: sign_data/sign_data/train/032/03_032.png \n extracting: sign_data/sign_data/train/032/04_032.png \n extracting: sign_data/sign_data/train/032/05_032.png \n extracting: sign_data/sign_data/train/032/06_032.png \n extracting: sign_data/sign_data/train/032/07_032.png \n extracting: sign_data/sign_data/train/032/08_032.png \n extracting: sign_data/sign_data/train/032/09_032.png \n extracting: sign_data/sign_data/train/032/10_032.png \n extracting: sign_data/sign_data/train/032/11_032.png \n extracting: sign_data/sign_data/train/032/12_032.png \n creating: sign_data/sign_data/train/032_forg/\n extracting: sign_data/sign_data/train/032_forg/01_0112032.PNG \n extracting: sign_data/sign_data/train/032_forg/01_0117032.PNG \n extracting: sign_data/sign_data/train/032_forg/01_0120032.PNG \n extracting: sign_data/sign_data/train/032_forg/02_0112032.PNG \n extracting: sign_data/sign_data/train/032_forg/02_0117032.PNG \n extracting: sign_data/sign_data/train/032_forg/02_0120032.PNG \n extracting: sign_data/sign_data/train/032_forg/03_0112032.PNG \n extracting: sign_data/sign_data/train/032_forg/03_0117032.PNG \n extracting: sign_data/sign_data/train/032_forg/03_0120032.PNG \n extracting: sign_data/sign_data/train/032_forg/04_0112032.PNG \n extracting: sign_data/sign_data/train/032_forg/04_0117032.PNG \n extracting: sign_data/sign_data/train/032_forg/04_0120032.PNG \n creating: sign_data/sign_data/train/033/\n extracting: sign_data/sign_data/train/033/01_033.png \n extracting: sign_data/sign_data/train/033/02_033.png \n extracting: sign_data/sign_data/train/033/03_033.png \n extracting: sign_data/sign_data/train/033/04_033.png \n extracting: sign_data/sign_data/train/033/05_033.png \n extracting: sign_data/sign_data/train/033/06_033.png \n extracting: sign_data/sign_data/train/033/07_033.png \n extracting: sign_data/sign_data/train/033/08_033.png \n extracting: sign_data/sign_data/train/033/09_033.png \n extracting: sign_data/sign_data/train/033/10_033.png \n extracting: sign_data/sign_data/train/033/11_033.png \n extracting: sign_data/sign_data/train/033/12_033.png \n creating: sign_data/sign_data/train/033_forg/\n extracting: sign_data/sign_data/train/033_forg/01_0112033.PNG \n extracting: sign_data/sign_data/train/033_forg/01_0203033.PNG \n extracting: sign_data/sign_data/train/033_forg/01_0205033.PNG \n extracting: sign_data/sign_data/train/033_forg/01_0213033.PNG \n extracting: sign_data/sign_data/train/033_forg/02_0112033.PNG \n extracting: sign_data/sign_data/train/033_forg/02_0203033.PNG \n extracting: sign_data/sign_data/train/033_forg/02_0205033.PNG \n extracting: sign_data/sign_data/train/033_forg/02_0213033.PNG \n extracting: sign_data/sign_data/train/033_forg/03_0112033.PNG \n extracting: sign_data/sign_data/train/033_forg/03_0203033.PNG \n extracting: sign_data/sign_data/train/033_forg/03_0205033.PNG \n extracting: sign_data/sign_data/train/033_forg/03_0213033.PNG \n extracting: sign_data/sign_data/train/033_forg/04_0112033.PNG \n extracting: sign_data/sign_data/train/033_forg/04_0203033.PNG \n extracting: sign_data/sign_data/train/033_forg/04_0205033.PNG \n extracting: sign_data/sign_data/train/033_forg/04_0213033.PNG \n creating: sign_data/sign_data/train/034/\n extracting: sign_data/sign_data/train/034/01_034.png \n extracting: sign_data/sign_data/train/034/02_034.png \n extracting: sign_data/sign_data/train/034/03_034.png \n extracting: sign_data/sign_data/train/034/04_034.png \n extracting: sign_data/sign_data/train/034/05_034.png \n extracting: sign_data/sign_data/train/034/06_034.png \n extracting: sign_data/sign_data/train/034/07_034.png \n extracting: sign_data/sign_data/train/034/08_034.png \n extracting: sign_data/sign_data/train/034/09_034.png \n extracting: sign_data/sign_data/train/034/10_034.png \n extracting: sign_data/sign_data/train/034/11_034.png \n extracting: sign_data/sign_data/train/034/12_034.png \n creating: sign_data/sign_data/train/034_forg/\n extracting: sign_data/sign_data/train/034_forg/01_0103034.PNG \n extracting: sign_data/sign_data/train/034_forg/01_0110034.PNG \n extracting: sign_data/sign_data/train/034_forg/01_0120034.PNG \n extracting: sign_data/sign_data/train/034_forg/02_0103034.PNG \n extracting: sign_data/sign_data/train/034_forg/02_0110034.PNG \n extracting: sign_data/sign_data/train/034_forg/02_0120034.PNG \n extracting: sign_data/sign_data/train/034_forg/03_0103034.PNG \n extracting: sign_data/sign_data/train/034_forg/03_0110034.PNG \n extracting: sign_data/sign_data/train/034_forg/03_0120034.PNG \n extracting: sign_data/sign_data/train/034_forg/04_0103034.PNG \n extracting: sign_data/sign_data/train/034_forg/04_0110034.PNG \n extracting: sign_data/sign_data/train/034_forg/04_0120034.PNG \n creating: sign_data/sign_data/train/035/\n extracting: sign_data/sign_data/train/035/01_035.png \n extracting: sign_data/sign_data/train/035/02_035.png \n extracting: sign_data/sign_data/train/035/03_035.png \n extracting: sign_data/sign_data/train/035/04_035.png \n extracting: sign_data/sign_data/train/035/05_035.png \n extracting: sign_data/sign_data/train/035/06_035.png \n extracting: sign_data/sign_data/train/035/07_035.png \n extracting: sign_data/sign_data/train/035/08_035.png \n extracting: sign_data/sign_data/train/035/09_035.png \n extracting: sign_data/sign_data/train/035/10_035.png \n extracting: sign_data/sign_data/train/035/11_035.png \n extracting: sign_data/sign_data/train/035/12_035.png \n creating: sign_data/sign_data/train/035_forg/\n extracting: sign_data/sign_data/train/035_forg/01_0103035.PNG \n extracting: sign_data/sign_data/train/035_forg/01_0115035.PNG \n extracting: sign_data/sign_data/train/035_forg/01_0201035.PNG \n extracting: sign_data/sign_data/train/035_forg/02_0103035.PNG \n extracting: sign_data/sign_data/train/035_forg/02_0115035.PNG \n extracting: sign_data/sign_data/train/035_forg/02_0201035.PNG \n extracting: sign_data/sign_data/train/035_forg/03_0103035.PNG \n extracting: sign_data/sign_data/train/035_forg/03_0115035.PNG \n extracting: sign_data/sign_data/train/035_forg/03_0201035.PNG \n extracting: sign_data/sign_data/train/035_forg/04_0103035.PNG \n extracting: sign_data/sign_data/train/035_forg/04_0115035.PNG \n extracting: sign_data/sign_data/train/035_forg/04_0201035.PNG \n creating: sign_data/sign_data/train/036/\n extracting: sign_data/sign_data/train/036/01_036.png \n extracting: sign_data/sign_data/train/036/02_036.png \n extracting: sign_data/sign_data/train/036/03_036.png \n extracting: sign_data/sign_data/train/036/04_036.png \n extracting: sign_data/sign_data/train/036/05_036.png \n extracting: sign_data/sign_data/train/036/06_036.png \n extracting: sign_data/sign_data/train/036/07_036.png \n extracting: sign_data/sign_data/train/036/08_036.png \n extracting: sign_data/sign_data/train/036/09_036.png \n extracting: sign_data/sign_data/train/036/10_036.png \n extracting: sign_data/sign_data/train/036/11_036.png \n extracting: sign_data/sign_data/train/036/12_036.png \n creating: sign_data/sign_data/train/036_forg/\n extracting: sign_data/sign_data/train/036_forg/01_0109036.PNG \n extracting: sign_data/sign_data/train/036_forg/01_0118036.PNG \n extracting: sign_data/sign_data/train/036_forg/01_0123036.PNG \n extracting: sign_data/sign_data/train/036_forg/02_0109036.PNG \n extracting: sign_data/sign_data/train/036_forg/02_0118036.PNG \n extracting: sign_data/sign_data/train/036_forg/02_0123036.PNG \n extracting: sign_data/sign_data/train/036_forg/03_0109036.PNG \n extracting: sign_data/sign_data/train/036_forg/03_0118036.PNG \n extracting: sign_data/sign_data/train/036_forg/03_0123036.PNG \n extracting: sign_data/sign_data/train/036_forg/04_0109036.PNG \n extracting: sign_data/sign_data/train/036_forg/04_0118036.PNG \n extracting: sign_data/sign_data/train/036_forg/04_0123036.PNG \n creating: sign_data/sign_data/train/037/\n extracting: sign_data/sign_data/train/037/01_037.png \n extracting: sign_data/sign_data/train/037/02_037.png \n extracting: sign_data/sign_data/train/037/03_037.png \n extracting: sign_data/sign_data/train/037/04_037.png \n extracting: sign_data/sign_data/train/037/05_037.png \n extracting: sign_data/sign_data/train/037/06_037.png \n extracting: sign_data/sign_data/train/037/07_037.png \n extracting: sign_data/sign_data/train/037/08_037.png \n extracting: sign_data/sign_data/train/037/09_037.png \n extracting: sign_data/sign_data/train/037/10_037.png \n extracting: sign_data/sign_data/train/037/11_037.png \n extracting: sign_data/sign_data/train/037/12_037.png \n creating: sign_data/sign_data/train/037_forg/\n extracting: sign_data/sign_data/train/037_forg/01_0114037.PNG \n extracting: sign_data/sign_data/train/037_forg/01_0123037.PNG \n extracting: sign_data/sign_data/train/037_forg/01_0208037.PNG \n extracting: sign_data/sign_data/train/037_forg/01_0214037.PNG \n extracting: sign_data/sign_data/train/037_forg/02_0114037.PNG \n extracting: sign_data/sign_data/train/037_forg/02_0123037.PNG \n extracting: sign_data/sign_data/train/037_forg/02_0208037.PNG \n extracting: sign_data/sign_data/train/037_forg/02_0214037.PNG \n extracting: sign_data/sign_data/train/037_forg/03_0114037.PNG \n extracting: sign_data/sign_data/train/037_forg/03_0123037.PNG \n extracting: sign_data/sign_data/train/037_forg/03_0208037.PNG \n extracting: sign_data/sign_data/train/037_forg/03_0214037.PNG \n extracting: sign_data/sign_data/train/037_forg/04_0114037.PNG \n extracting: sign_data/sign_data/train/037_forg/04_0123037.PNG \n extracting: sign_data/sign_data/train/037_forg/04_0208037.PNG \n extracting: sign_data/sign_data/train/037_forg/04_0214037.PNG \n creating: sign_data/sign_data/train/038/\n extracting: sign_data/sign_data/train/038/01_038.png \n extracting: sign_data/sign_data/train/038/02_038.png \n extracting: sign_data/sign_data/train/038/03_038.png \n extracting: sign_data/sign_data/train/038/04_038.png \n extracting: sign_data/sign_data/train/038/05_038.png \n extracting: sign_data/sign_data/train/038/06_038.png \n extracting: sign_data/sign_data/train/038/07_038.png \n extracting: sign_data/sign_data/train/038/08_038.png \n extracting: sign_data/sign_data/train/038/09_038.png \n extracting: sign_data/sign_data/train/038/10_038.png \n extracting: sign_data/sign_data/train/038/11_038.png \n extracting: sign_data/sign_data/train/038/12_038.png \n creating: sign_data/sign_data/train/038_forg/\n extracting: sign_data/sign_data/train/038_forg/01_0101038.PNG \n extracting: sign_data/sign_data/train/038_forg/01_0124038.PNG \n extracting: sign_data/sign_data/train/038_forg/01_0213038.PNG \n extracting: sign_data/sign_data/train/038_forg/02_0101038.PNG \n extracting: sign_data/sign_data/train/038_forg/02_0124038.PNG \n extracting: sign_data/sign_data/train/038_forg/02_0213038.PNG \n extracting: sign_data/sign_data/train/038_forg/03_0101038.PNG \n extracting: sign_data/sign_data/train/038_forg/03_0124038.PNG \n extracting: sign_data/sign_data/train/038_forg/03_0213038.PNG \n extracting: sign_data/sign_data/train/038_forg/04_0101038.PNG \n extracting: sign_data/sign_data/train/038_forg/04_0124038.PNG \n extracting: sign_data/sign_data/train/038_forg/04_0213038.PNG \n creating: sign_data/sign_data/train/039/\n extracting: sign_data/sign_data/train/039/01_039.png \n extracting: sign_data/sign_data/train/039/02_039.png \n extracting: sign_data/sign_data/train/039/03_039.png \n extracting: sign_data/sign_data/train/039/04_039.png \n extracting: sign_data/sign_data/train/039/05_039.png \n extracting: sign_data/sign_data/train/039/06_039.png \n extracting: sign_data/sign_data/train/039/07_039.png \n extracting: sign_data/sign_data/train/039/08_039.png \n extracting: sign_data/sign_data/train/039/09_039.png \n extracting: sign_data/sign_data/train/039/10_039.png \n extracting: sign_data/sign_data/train/039/11_039.png \n extracting: sign_data/sign_data/train/039/12_039.png \n creating: sign_data/sign_data/train/039_forg/\n extracting: sign_data/sign_data/train/039_forg/01_0102039.PNG \n extracting: sign_data/sign_data/train/039_forg/01_0108039.PNG \n extracting: sign_data/sign_data/train/039_forg/01_0113039.PNG \n extracting: sign_data/sign_data/train/039_forg/02_0102039.PNG \n extracting: sign_data/sign_data/train/039_forg/02_0108039.PNG \n extracting: sign_data/sign_data/train/039_forg/02_0113039.PNG \n extracting: sign_data/sign_data/train/039_forg/03_0102039.PNG \n extracting: sign_data/sign_data/train/039_forg/03_0108039.PNG \n extracting: sign_data/sign_data/train/039_forg/03_0113039.PNG \n extracting: sign_data/sign_data/train/039_forg/04_0102039.PNG \n extracting: sign_data/sign_data/train/039_forg/04_0108039.PNG \n extracting: sign_data/sign_data/train/039_forg/04_0113039.PNG \n creating: sign_data/sign_data/train/040/\n extracting: sign_data/sign_data/train/040/01_040.png \n extracting: sign_data/sign_data/train/040/02_040.png \n extracting: sign_data/sign_data/train/040/03_040.png \n extracting: sign_data/sign_data/train/040/04_040.png \n extracting: sign_data/sign_data/train/040/05_040.png \n extracting: sign_data/sign_data/train/040/06_040.png \n extracting: sign_data/sign_data/train/040/07_040.png \n extracting: sign_data/sign_data/train/040/08_040.png \n extracting: sign_data/sign_data/train/040/09_040.png \n extracting: sign_data/sign_data/train/040/10_040.png \n extracting: sign_data/sign_data/train/040/11_040.png \n extracting: sign_data/sign_data/train/040/12_040.png \n creating: sign_data/sign_data/train/040_forg/\n extracting: sign_data/sign_data/train/040_forg/01_0114040.PNG \n extracting: sign_data/sign_data/train/040_forg/01_0121040.PNG \n extracting: sign_data/sign_data/train/040_forg/02_0114040.PNG \n extracting: sign_data/sign_data/train/040_forg/02_0121040.PNG \n extracting: sign_data/sign_data/train/040_forg/03_0114040.PNG \n extracting: sign_data/sign_data/train/040_forg/03_0121040.PNG \n extracting: sign_data/sign_data/train/040_forg/04_0114040.PNG \n extracting: sign_data/sign_data/train/040_forg/04_0121040.PNG \n creating: sign_data/sign_data/train/041/\n extracting: sign_data/sign_data/train/041/01_041.png \n extracting: sign_data/sign_data/train/041/02_041.png \n extracting: sign_data/sign_data/train/041/03_041.png \n extracting: sign_data/sign_data/train/041/04_041.png \n extracting: sign_data/sign_data/train/041/05_041.png \n extracting: sign_data/sign_data/train/041/06_041.png \n extracting: sign_data/sign_data/train/041/07_041.png \n extracting: sign_data/sign_data/train/041/08_041.png \n extracting: sign_data/sign_data/train/041/09_041.png \n extracting: sign_data/sign_data/train/041/10_041.png \n extracting: sign_data/sign_data/train/041/11_041.png \n extracting: sign_data/sign_data/train/041/12_041.png \n creating: sign_data/sign_data/train/041_forg/\n extracting: sign_data/sign_data/train/041_forg/01_0105041.PNG \n extracting: sign_data/sign_data/train/041_forg/01_0116041.PNG \n extracting: sign_data/sign_data/train/041_forg/01_0117041.PNG \n extracting: sign_data/sign_data/train/041_forg/02_0105041.PNG \n extracting: sign_data/sign_data/train/041_forg/02_0116041.PNG \n extracting: sign_data/sign_data/train/041_forg/02_0117041.PNG \n extracting: sign_data/sign_data/train/041_forg/03_0105041.PNG \n extracting: sign_data/sign_data/train/041_forg/03_0116041.PNG \n extracting: sign_data/sign_data/train/041_forg/03_0117041.PNG \n extracting: sign_data/sign_data/train/041_forg/04_0105041.PNG \n extracting: sign_data/sign_data/train/041_forg/04_0116041.PNG \n extracting: sign_data/sign_data/train/041_forg/04_0117041.PNG \n creating: sign_data/sign_data/train/042/\n extracting: sign_data/sign_data/train/042/01_042.png \n extracting: sign_data/sign_data/train/042/02_042.png \n extracting: sign_data/sign_data/train/042/03_042.png \n extracting: sign_data/sign_data/train/042/04_042.png \n extracting: sign_data/sign_data/train/042/05_042.png \n extracting: sign_data/sign_data/train/042/06_042.png \n extracting: sign_data/sign_data/train/042/07_042.png \n extracting: sign_data/sign_data/train/042/08_042.png \n extracting: sign_data/sign_data/train/042/09_042.png \n extracting: sign_data/sign_data/train/042/10_042.png \n extracting: sign_data/sign_data/train/042/11_042.png \n extracting: sign_data/sign_data/train/042/12_042.png \n creating: sign_data/sign_data/train/042_forg/\n extracting: sign_data/sign_data/train/042_forg/01_0107042.PNG \n extracting: sign_data/sign_data/train/042_forg/01_0118042.PNG \n extracting: sign_data/sign_data/train/042_forg/01_0204042.PNG \n extracting: sign_data/sign_data/train/042_forg/02_0107042.PNG \n extracting: sign_data/sign_data/train/042_forg/02_0118042.PNG \n extracting: sign_data/sign_data/train/042_forg/02_0204042.PNG \n extracting: sign_data/sign_data/train/042_forg/03_0107042.PNG \n extracting: sign_data/sign_data/train/042_forg/03_0118042.PNG \n extracting: sign_data/sign_data/train/042_forg/03_0204042.PNG \n extracting: sign_data/sign_data/train/042_forg/04_0107042.PNG \n extracting: sign_data/sign_data/train/042_forg/04_0118042.PNG \n extracting: sign_data/sign_data/train/042_forg/04_0204042.PNG \n creating: sign_data/sign_data/train/043/\n extracting: sign_data/sign_data/train/043/01_043.png \n extracting: sign_data/sign_data/train/043/02_043.png \n extracting: sign_data/sign_data/train/043/03_043.png \n extracting: sign_data/sign_data/train/043/04_043.png \n extracting: sign_data/sign_data/train/043/05_043.png \n extracting: sign_data/sign_data/train/043/06_043.png \n extracting: sign_data/sign_data/train/043/07_043.png \n extracting: sign_data/sign_data/train/043/08_043.png \n extracting: sign_data/sign_data/train/043/09_043.png \n extracting: sign_data/sign_data/train/043/10_043.png \n extracting: sign_data/sign_data/train/043/11_043.png \n extracting: sign_data/sign_data/train/043/12_043.png \n creating: sign_data/sign_data/train/043_forg/\n extracting: sign_data/sign_data/train/043_forg/01_0111043.PNG \n extracting: sign_data/sign_data/train/043_forg/01_0201043.PNG \n extracting: sign_data/sign_data/train/043_forg/01_0211043.PNG \n extracting: sign_data/sign_data/train/043_forg/02_0111043.PNG \n extracting: sign_data/sign_data/train/043_forg/02_0201043.PNG \n extracting: sign_data/sign_data/train/043_forg/02_0211043.PNG \n extracting: sign_data/sign_data/train/043_forg/03_0111043.PNG \n extracting: sign_data/sign_data/train/043_forg/03_0201043.PNG \n extracting: sign_data/sign_data/train/043_forg/03_0211043.PNG \n extracting: sign_data/sign_data/train/043_forg/04_0111043.PNG \n extracting: sign_data/sign_data/train/043_forg/04_0201043.PNG \n extracting: sign_data/sign_data/train/043_forg/04_0211043.PNG \n creating: sign_data/sign_data/train/044/\n extracting: sign_data/sign_data/train/044/01_044.png \n extracting: sign_data/sign_data/train/044/02_044.png \n extracting: sign_data/sign_data/train/044/03_044.png \n extracting: sign_data/sign_data/train/044/04_044.png \n extracting: sign_data/sign_data/train/044/05_044.png \n extracting: sign_data/sign_data/train/044/06_044.png \n extracting: sign_data/sign_data/train/044/07_044.png \n extracting: sign_data/sign_data/train/044/08_044.png \n extracting: sign_data/sign_data/train/044/09_044.png \n extracting: sign_data/sign_data/train/044/10_044.png \n extracting: sign_data/sign_data/train/044/11_044.png \n extracting: sign_data/sign_data/train/044/12_044.png \n creating: sign_data/sign_data/train/044_forg/\n extracting: sign_data/sign_data/train/044_forg/01_0103044.PNG \n extracting: sign_data/sign_data/train/044_forg/01_0112044.PNG \n extracting: sign_data/sign_data/train/044_forg/01_0211044.PNG \n extracting: sign_data/sign_data/train/044_forg/02_0103044.PNG \n extracting: sign_data/sign_data/train/044_forg/02_0112044.PNG \n extracting: sign_data/sign_data/train/044_forg/02_0211044.PNG \n extracting: sign_data/sign_data/train/044_forg/03_0103044.PNG \n extracting: sign_data/sign_data/train/044_forg/03_0112044.PNG \n extracting: sign_data/sign_data/train/044_forg/03_0211044.PNG \n extracting: sign_data/sign_data/train/044_forg/04_0103044.PNG \n extracting: sign_data/sign_data/train/044_forg/04_0112044.PNG \n extracting: sign_data/sign_data/train/044_forg/04_0211044.PNG \n creating: sign_data/sign_data/train/045/\n extracting: sign_data/sign_data/train/045/01_045.png \n extracting: sign_data/sign_data/train/045/02_045.png \n extracting: sign_data/sign_data/train/045/03_045.png \n extracting: sign_data/sign_data/train/045/04_045.png \n extracting: sign_data/sign_data/train/045/05_045.png \n extracting: sign_data/sign_data/train/045/06_045.png \n extracting: sign_data/sign_data/train/045/07_045.png \n extracting: sign_data/sign_data/train/045/08_045.png \n extracting: sign_data/sign_data/train/045/09_045.png \n extracting: sign_data/sign_data/train/045/10_045.png \n extracting: sign_data/sign_data/train/045/11_045.png \n extracting: sign_data/sign_data/train/045/12_045.png \n creating: sign_data/sign_data/train/045_forg/\n extracting: sign_data/sign_data/train/045_forg/01_0111045.PNG \n extracting: sign_data/sign_data/train/045_forg/01_0116045.PNG \n extracting: sign_data/sign_data/train/045_forg/01_0205045.PNG \n extracting: sign_data/sign_data/train/045_forg/02_0111045.PNG \n extracting: sign_data/sign_data/train/045_forg/02_0116045.PNG \n extracting: sign_data/sign_data/train/045_forg/02_0205045.PNG \n extracting: sign_data/sign_data/train/045_forg/03_0111045.PNG \n extracting: sign_data/sign_data/train/045_forg/03_0116045.PNG \n extracting: sign_data/sign_data/train/045_forg/03_0205045.PNG \n extracting: sign_data/sign_data/train/045_forg/04_0111045.PNG \n extracting: sign_data/sign_data/train/045_forg/04_0116045.PNG \n extracting: sign_data/sign_data/train/045_forg/04_0205045.PNG \n creating: sign_data/sign_data/train/046/\n extracting: sign_data/sign_data/train/046/01_046.png \n extracting: sign_data/sign_data/train/046/02_046.png \n extracting: sign_data/sign_data/train/046/03_046.png \n extracting: sign_data/sign_data/train/046/04_046.png \n extracting: sign_data/sign_data/train/046/05_046.png \n extracting: sign_data/sign_data/train/046/06_046.png \n extracting: sign_data/sign_data/train/046/07_046.png \n extracting: sign_data/sign_data/train/046/08_046.png \n extracting: sign_data/sign_data/train/046/09_046.png \n extracting: sign_data/sign_data/train/046/10_046.png \n extracting: sign_data/sign_data/train/046/11_046.png \n extracting: sign_data/sign_data/train/046/12_046.png \n creating: sign_data/sign_data/train/046_forg/\n extracting: sign_data/sign_data/train/046_forg/01_0107046.PNG \n extracting: sign_data/sign_data/train/046_forg/01_0108046.PNG \n extracting: sign_data/sign_data/train/046_forg/01_0123046.PNG \n extracting: sign_data/sign_data/train/046_forg/02_0107046.PNG \n extracting: sign_data/sign_data/train/046_forg/02_0108046.PNG \n extracting: sign_data/sign_data/train/046_forg/02_0123046.PNG \n extracting: sign_data/sign_data/train/046_forg/03_0107046.PNG \n extracting: sign_data/sign_data/train/046_forg/03_0108046.PNG \n extracting: sign_data/sign_data/train/046_forg/03_0123046.PNG \n extracting: sign_data/sign_data/train/046_forg/04_0107046.PNG \n extracting: sign_data/sign_data/train/046_forg/04_0108046.PNG \n extracting: sign_data/sign_data/train/046_forg/04_0123046.PNG \n creating: sign_data/sign_data/train/047/\n extracting: sign_data/sign_data/train/047/01_047.png \n extracting: sign_data/sign_data/train/047/02_047.png \n extracting: sign_data/sign_data/train/047/03_047.png \n extracting: sign_data/sign_data/train/047/04_047.png \n extracting: sign_data/sign_data/train/047/05_047.png \n inflating: sign_data/sign_data/train/047/06_047.png \n extracting: sign_data/sign_data/train/047/07_047.png \n extracting: sign_data/sign_data/train/047/08_047.png \n extracting: sign_data/sign_data/train/047/09_047.png \n extracting: sign_data/sign_data/train/047/10_047.png \n extracting: sign_data/sign_data/train/047/11_047.png \n extracting: sign_data/sign_data/train/047/12_047.png \n creating: sign_data/sign_data/train/047_forg/\n extracting: sign_data/sign_data/train/047_forg/01_0113047.PNG \n extracting: sign_data/sign_data/train/047_forg/01_0114047.PNG \n extracting: sign_data/sign_data/train/047_forg/01_0212047.PNG \n extracting: sign_data/sign_data/train/047_forg/02_0113047.PNG \n extracting: sign_data/sign_data/train/047_forg/02_0114047.PNG \n extracting: sign_data/sign_data/train/047_forg/02_0212047.PNG \n extracting: sign_data/sign_data/train/047_forg/03_0113047.PNG \n extracting: sign_data/sign_data/train/047_forg/03_0114047.PNG \n extracting: sign_data/sign_data/train/047_forg/03_0212047.PNG \n extracting: sign_data/sign_data/train/047_forg/04_0113047.PNG \n extracting: sign_data/sign_data/train/047_forg/04_0114047.PNG \n extracting: sign_data/sign_data/train/047_forg/04_0212047.PNG \n creating: sign_data/sign_data/train/048/\n extracting: sign_data/sign_data/train/048/01_048.png \n extracting: sign_data/sign_data/train/048/02_048.png \n extracting: sign_data/sign_data/train/048/03_048.png \n extracting: sign_data/sign_data/train/048/04_048.png \n extracting: sign_data/sign_data/train/048/05_048.png \n extracting: sign_data/sign_data/train/048/06_048.png \n extracting: sign_data/sign_data/train/048/07_048.png \n extracting: sign_data/sign_data/train/048/08_048.png \n extracting: sign_data/sign_data/train/048/09_048.png \n extracting: sign_data/sign_data/train/048/10_048.png \n extracting: sign_data/sign_data/train/048/11_048.png \n extracting: sign_data/sign_data/train/048/12_048.png \n creating: sign_data/sign_data/train/048_forg/\n extracting: sign_data/sign_data/train/048_forg/01_0106048.PNG \n extracting: sign_data/sign_data/train/048_forg/01_0204048.PNG \n extracting: sign_data/sign_data/train/048_forg/02_0106048.PNG \n extracting: sign_data/sign_data/train/048_forg/02_0204048.PNG \n extracting: sign_data/sign_data/train/048_forg/03_0106048.PNG \n extracting: sign_data/sign_data/train/048_forg/03_0204048.PNG \n extracting: sign_data/sign_data/train/048_forg/04_0106048.PNG \n extracting: sign_data/sign_data/train/048_forg/04_0204048.PNG \n creating: sign_data/sign_data/train/049/\n extracting: sign_data/sign_data/train/049/01_049.png \n extracting: sign_data/sign_data/train/049/02_049.png \n extracting: sign_data/sign_data/train/049/03_049.png \n extracting: sign_data/sign_data/train/049/04_049.png \n extracting: sign_data/sign_data/train/049/05_049.png \n extracting: sign_data/sign_data/train/049/06_049.png \n extracting: sign_data/sign_data/train/049/07_049.png \n extracting: sign_data/sign_data/train/049/08_049.png \n extracting: sign_data/sign_data/train/049/09_049.png \n extracting: sign_data/sign_data/train/049/10_049.png \n extracting: sign_data/sign_data/train/049/11_049.png \n extracting: sign_data/sign_data/train/049/12_049.png \n creating: sign_data/sign_data/train/049_forg/\n extracting: sign_data/sign_data/train/049_forg/01_0114049.PNG \n extracting: sign_data/sign_data/train/049_forg/01_0206049.PNG \n extracting: sign_data/sign_data/train/049_forg/01_0210049.PNG \n extracting: sign_data/sign_data/train/049_forg/02_0114049.PNG \n extracting: sign_data/sign_data/train/049_forg/02_0206049.PNG \n extracting: sign_data/sign_data/train/049_forg/02_0210049.PNG \n extracting: sign_data/sign_data/train/049_forg/03_0114049.PNG \n extracting: sign_data/sign_data/train/049_forg/03_0206049.PNG \n extracting: sign_data/sign_data/train/049_forg/03_0210049.PNG \n extracting: sign_data/sign_data/train/049_forg/04_0114049.PNG \n extracting: sign_data/sign_data/train/049_forg/04_0206049.PNG \n extracting: sign_data/sign_data/train/049_forg/04_0210049.PNG \n creating: sign_data/sign_data/train/050/\n extracting: sign_data/sign_data/train/050/01_050.png \n extracting: sign_data/sign_data/train/050/02_050.png \n extracting: sign_data/sign_data/train/050/03_050.png \n extracting: sign_data/sign_data/train/050/04_050.png \n extracting: sign_data/sign_data/train/050/05_050.png \n extracting: sign_data/sign_data/train/050/06_050.png \n extracting: sign_data/sign_data/train/050/07_050.png \n extracting: sign_data/sign_data/train/050/08_050.png \n extracting: sign_data/sign_data/train/050/09_050.png \n extracting: sign_data/sign_data/train/050/10_050.png \n extracting: sign_data/sign_data/train/050/11_050.png \n extracting: sign_data/sign_data/train/050/12_050.png \n creating: sign_data/sign_data/train/050_forg/\n extracting: sign_data/sign_data/train/050_forg/01_0125050.PNG \n extracting: sign_data/sign_data/train/050_forg/01_0126050.PNG \n extracting: sign_data/sign_data/train/050_forg/01_0204050.PNG \n extracting: sign_data/sign_data/train/050_forg/02_0125050.PNG \n extracting: sign_data/sign_data/train/050_forg/02_0126050.PNG \n extracting: sign_data/sign_data/train/050_forg/02_0204050.PNG \n extracting: sign_data/sign_data/train/050_forg/03_0125050.PNG \n extracting: sign_data/sign_data/train/050_forg/03_0126050.PNG \n extracting: sign_data/sign_data/train/050_forg/03_0204050.PNG \n extracting: sign_data/sign_data/train/050_forg/04_0125050.PNG \n extracting: sign_data/sign_data/train/050_forg/04_0126050.PNG \n extracting: sign_data/sign_data/train/050_forg/04_0204050.PNG \n creating: sign_data/sign_data/train/051/\n extracting: sign_data/sign_data/train/051/01_051.png \n extracting: sign_data/sign_data/train/051/02_051.png \n extracting: sign_data/sign_data/train/051/03_051.png \n extracting: sign_data/sign_data/train/051/04_051.png \n extracting: sign_data/sign_data/train/051/05_051.png \n extracting: sign_data/sign_data/train/051/06_051.png \n extracting: sign_data/sign_data/train/051/07_051.png \n extracting: sign_data/sign_data/train/051/08_051.png \n extracting: sign_data/sign_data/train/051/09_051.png \n extracting: sign_data/sign_data/train/051/10_051.png \n extracting: sign_data/sign_data/train/051/11_051.png \n extracting: sign_data/sign_data/train/051/12_051.png \n creating: sign_data/sign_data/train/051_forg/\n extracting: sign_data/sign_data/train/051_forg/01_0104051.PNG \n extracting: sign_data/sign_data/train/051_forg/01_0120051.PNG \n extracting: sign_data/sign_data/train/051_forg/02_0104051.PNG \n extracting: sign_data/sign_data/train/051_forg/02_0120051.PNG \n extracting: sign_data/sign_data/train/051_forg/03_0104051.PNG \n extracting: sign_data/sign_data/train/051_forg/03_0120051.PNG \n extracting: sign_data/sign_data/train/051_forg/04_0104051.PNG \n extracting: sign_data/sign_data/train/051_forg/04_0120051.PNG \n creating: sign_data/sign_data/train/052/\n extracting: sign_data/sign_data/train/052/01_052.png \n extracting: sign_data/sign_data/train/052/02_052.png \n extracting: sign_data/sign_data/train/052/03_052.png \n extracting: sign_data/sign_data/train/052/04_052.png \n extracting: sign_data/sign_data/train/052/05_052.png \n extracting: sign_data/sign_data/train/052/06_052.png \n extracting: sign_data/sign_data/train/052/07_052.png \n extracting: sign_data/sign_data/train/052/08_052.png \n extracting: sign_data/sign_data/train/052/09_052.png \n extracting: sign_data/sign_data/train/052/10_052.png \n extracting: sign_data/sign_data/train/052/11_052.png \n extracting: sign_data/sign_data/train/052/12_052.png \n creating: sign_data/sign_data/train/052_forg/\n extracting: sign_data/sign_data/train/052_forg/01_0106052.PNG \n extracting: sign_data/sign_data/train/052_forg/01_0109052.PNG \n extracting: sign_data/sign_data/train/052_forg/01_0207052.PNG \n extracting: sign_data/sign_data/train/052_forg/01_0210052.PNG \n extracting: sign_data/sign_data/train/052_forg/02_0106052.PNG \n extracting: sign_data/sign_data/train/052_forg/02_0109052.PNG \n extracting: sign_data/sign_data/train/052_forg/02_0207052.PNG \n extracting: sign_data/sign_data/train/052_forg/02_0210052.PNG \n extracting: sign_data/sign_data/train/052_forg/03_0106052.PNG \n extracting: sign_data/sign_data/train/052_forg/03_0109052.PNG \n extracting: sign_data/sign_data/train/052_forg/03_0207052.PNG \n extracting: sign_data/sign_data/train/052_forg/03_0210052.PNG \n extracting: sign_data/sign_data/train/052_forg/04_0106052.PNG \n extracting: sign_data/sign_data/train/052_forg/04_0109052.PNG \n extracting: sign_data/sign_data/train/052_forg/04_0207052.PNG \n extracting: sign_data/sign_data/train/052_forg/04_0210052.PNG \n creating: sign_data/sign_data/train/053/\n extracting: sign_data/sign_data/train/053/01_053.png \n extracting: sign_data/sign_data/train/053/02_053.png \n extracting: sign_data/sign_data/train/053/03_053.png \n extracting: sign_data/sign_data/train/053/04_053.png \n extracting: sign_data/sign_data/train/053/05_053.png \n extracting: sign_data/sign_data/train/053/06_053.png \n extracting: sign_data/sign_data/train/053/07_053.png \n extracting: sign_data/sign_data/train/053/08_053.png \n extracting: sign_data/sign_data/train/053/09_053.png \n extracting: sign_data/sign_data/train/053/10_053.png \n extracting: sign_data/sign_data/train/053/11_053.png \n extracting: sign_data/sign_data/train/053/12_053.png \n creating: sign_data/sign_data/train/053_forg/\n extracting: sign_data/sign_data/train/053_forg/01_0107053.PNG \n extracting: sign_data/sign_data/train/053_forg/01_0115053.PNG \n extracting: sign_data/sign_data/train/053_forg/01_0202053.PNG \n extracting: sign_data/sign_data/train/053_forg/01_0207053.PNG \n extracting: sign_data/sign_data/train/053_forg/02_0107053.PNG \n extracting: sign_data/sign_data/train/053_forg/02_0115053.PNG \n extracting: sign_data/sign_data/train/053_forg/02_0202053.PNG \n extracting: sign_data/sign_data/train/053_forg/02_0207053.PNG \n extracting: sign_data/sign_data/train/053_forg/03_0107053.PNG \n extracting: sign_data/sign_data/train/053_forg/03_0115053.PNG \n extracting: sign_data/sign_data/train/053_forg/03_0202053.PNG \n extracting: sign_data/sign_data/train/053_forg/03_0207053.PNG \n extracting: sign_data/sign_data/train/053_forg/04_0107053.PNG \n extracting: sign_data/sign_data/train/053_forg/04_0115053.PNG \n extracting: sign_data/sign_data/train/053_forg/04_0202053.PNG \n extracting: sign_data/sign_data/train/053_forg/04_0207053.PNG \n creating: sign_data/sign_data/train/054/\n extracting: sign_data/sign_data/train/054/01_054.png \n extracting: sign_data/sign_data/train/054/02_054.png \n extracting: sign_data/sign_data/train/054/03_054.png \n extracting: sign_data/sign_data/train/054/04_054.png \n extracting: sign_data/sign_data/train/054/05_054.png \n extracting: sign_data/sign_data/train/054/06_054.png \n extracting: sign_data/sign_data/train/054/07_054.png \n extracting: sign_data/sign_data/train/054/08_054.png \n extracting: sign_data/sign_data/train/054/09_054.png \n extracting: sign_data/sign_data/train/054/10_054.png \n extracting: sign_data/sign_data/train/054/11_054.png \n extracting: sign_data/sign_data/train/054/12_054.png \n creating: sign_data/sign_data/train/054_forg/\n extracting: sign_data/sign_data/train/054_forg/01_0102054.PNG \n extracting: sign_data/sign_data/train/054_forg/01_0124054.PNG \n extracting: sign_data/sign_data/train/054_forg/01_0207054.PNG \n extracting: sign_data/sign_data/train/054_forg/01_0208054.PNG \n extracting: sign_data/sign_data/train/054_forg/01_0214054.PNG \n extracting: sign_data/sign_data/train/054_forg/02_0102054.PNG \n extracting: sign_data/sign_data/train/054_forg/02_0124054.PNG \n extracting: sign_data/sign_data/train/054_forg/02_0207054.PNG \n extracting: sign_data/sign_data/train/054_forg/02_0208054.PNG \n extracting: sign_data/sign_data/train/054_forg/02_0214054.PNG \n extracting: sign_data/sign_data/train/054_forg/03_0102054.PNG \n extracting: sign_data/sign_data/train/054_forg/03_0124054.PNG \n extracting: sign_data/sign_data/train/054_forg/03_0207054.PNG \n extracting: sign_data/sign_data/train/054_forg/03_0208054.PNG \n extracting: sign_data/sign_data/train/054_forg/03_0214054.PNG \n extracting: sign_data/sign_data/train/054_forg/04_0102054.PNG \n extracting: sign_data/sign_data/train/054_forg/04_0124054.PNG \n extracting: sign_data/sign_data/train/054_forg/04_0207054.PNG \n extracting: sign_data/sign_data/train/054_forg/04_0208054.PNG \n extracting: sign_data/sign_data/train/054_forg/04_0214054.PNG \n creating: sign_data/sign_data/train/055/\n extracting: sign_data/sign_data/train/055/01_055.png \n extracting: sign_data/sign_data/train/055/02_055.png \n extracting: sign_data/sign_data/train/055/03_055.png \n extracting: sign_data/sign_data/train/055/04_055.png \n extracting: sign_data/sign_data/train/055/05_055.png \n extracting: sign_data/sign_data/train/055/06_055.png \n extracting: sign_data/sign_data/train/055/07_055.png \n extracting: sign_data/sign_data/train/055/08_055.png \n extracting: sign_data/sign_data/train/055/09_055.png \n extracting: sign_data/sign_data/train/055/10_055.png \n extracting: sign_data/sign_data/train/055/11_055.png \n extracting: sign_data/sign_data/train/055/12_055.png \n creating: sign_data/sign_data/train/055_forg/\n extracting: sign_data/sign_data/train/055_forg/01_0118055.PNG \n extracting: sign_data/sign_data/train/055_forg/01_0120055.PNG \n extracting: sign_data/sign_data/train/055_forg/01_0202055.PNG \n extracting: sign_data/sign_data/train/055_forg/02_0118055.PNG \n extracting: sign_data/sign_data/train/055_forg/02_0120055.PNG \n extracting: sign_data/sign_data/train/055_forg/02_0202055.PNG \n extracting: sign_data/sign_data/train/055_forg/03_0118055.PNG \n extracting: sign_data/sign_data/train/055_forg/03_0120055.PNG \n extracting: sign_data/sign_data/train/055_forg/03_0202055.PNG \n extracting: sign_data/sign_data/train/055_forg/04_0118055.PNG \n extracting: sign_data/sign_data/train/055_forg/04_0120055.PNG \n extracting: sign_data/sign_data/train/055_forg/04_0202055.PNG \n creating: sign_data/sign_data/train/056/\n extracting: sign_data/sign_data/train/056/01_056.png \n extracting: sign_data/sign_data/train/056/02_056.png \n extracting: sign_data/sign_data/train/056/03_056.png \n extracting: sign_data/sign_data/train/056/04_056.png \n extracting: sign_data/sign_data/train/056/05_056.png \n extracting: sign_data/sign_data/train/056/06_056.png \n extracting: sign_data/sign_data/train/056/07_056.png \n extracting: sign_data/sign_data/train/056/08_056.png \n extracting: sign_data/sign_data/train/056/09_056.png \n extracting: sign_data/sign_data/train/056/10_056.png \n extracting: sign_data/sign_data/train/056/11_056.png \n extracting: sign_data/sign_data/train/056/12_056.png \n creating: sign_data/sign_data/train/056_forg/\n extracting: sign_data/sign_data/train/056_forg/01_0105056.PNG \n extracting: sign_data/sign_data/train/056_forg/01_0115056.PNG \n extracting: sign_data/sign_data/train/056_forg/02_0105056.PNG \n extracting: sign_data/sign_data/train/056_forg/02_0115056.PNG \n extracting: sign_data/sign_data/train/056_forg/03_0105056.PNG \n extracting: sign_data/sign_data/train/056_forg/03_0115056.PNG \n extracting: sign_data/sign_data/train/056_forg/04_0105056.PNG \n extracting: sign_data/sign_data/train/056_forg/04_0115056.PNG \n creating: sign_data/sign_data/train/057/\n extracting: sign_data/sign_data/train/057/01_057.png \n extracting: sign_data/sign_data/train/057/02_057.png \n extracting: sign_data/sign_data/train/057/03_057.png \n extracting: sign_data/sign_data/train/057/04_057.png \n extracting: sign_data/sign_data/train/057/05_057.png \n extracting: sign_data/sign_data/train/057/06_057.png \n extracting: sign_data/sign_data/train/057/07_057.png \n extracting: sign_data/sign_data/train/057/08_057.png \n extracting: sign_data/sign_data/train/057/09_057.png \n extracting: sign_data/sign_data/train/057/10_057.png \n extracting: sign_data/sign_data/train/057/11_057.png \n extracting: sign_data/sign_data/train/057/12_057.png \n creating: sign_data/sign_data/train/057_forg/\n extracting: sign_data/sign_data/train/057_forg/01_0117057.PNG \n extracting: sign_data/sign_data/train/057_forg/01_0208057.PNG \n extracting: sign_data/sign_data/train/057_forg/01_0210057.PNG \n extracting: sign_data/sign_data/train/057_forg/02_0117057.PNG \n extracting: sign_data/sign_data/train/057_forg/02_0208057.PNG \n extracting: sign_data/sign_data/train/057_forg/02_0210057.PNG \n extracting: sign_data/sign_data/train/057_forg/03_0117057.PNG \n extracting: sign_data/sign_data/train/057_forg/03_0208057.PNG \n extracting: sign_data/sign_data/train/057_forg/03_0210057.PNG \n extracting: sign_data/sign_data/train/057_forg/04_0117057.PNG \n extracting: sign_data/sign_data/train/057_forg/04_0208057.PNG \n extracting: sign_data/sign_data/train/057_forg/04_0210057.PNG \n creating: sign_data/sign_data/train/058/\n extracting: sign_data/sign_data/train/058/01_058.png \n extracting: sign_data/sign_data/train/058/02_058.png \n extracting: sign_data/sign_data/train/058/03_058.png \n extracting: sign_data/sign_data/train/058/04_058.png \n extracting: sign_data/sign_data/train/058/05_058.png \n extracting: sign_data/sign_data/train/058/06_058.png \n extracting: sign_data/sign_data/train/058/07_058.png \n extracting: sign_data/sign_data/train/058/08_058.png \n extracting: sign_data/sign_data/train/058/09_058.png \n extracting: sign_data/sign_data/train/058/10_058.png \n extracting: sign_data/sign_data/train/058/11_058.png \n extracting: sign_data/sign_data/train/058/12_058.png \n creating: sign_data/sign_data/train/058_forg/\n extracting: sign_data/sign_data/train/058_forg/01_0109058.PNG \n extracting: sign_data/sign_data/train/058_forg/01_0110058.PNG \n extracting: sign_data/sign_data/train/058_forg/01_0125058.PNG \n extracting: sign_data/sign_data/train/058_forg/01_0127058.PNG \n extracting: sign_data/sign_data/train/058_forg/02_0109058.PNG \n extracting: sign_data/sign_data/train/058_forg/02_0110058.PNG \n extracting: sign_data/sign_data/train/058_forg/02_0125058.PNG \n extracting: sign_data/sign_data/train/058_forg/02_0127058.PNG \n extracting: sign_data/sign_data/train/058_forg/03_0109058.PNG \n extracting: sign_data/sign_data/train/058_forg/03_0110058.PNG \n extracting: sign_data/sign_data/train/058_forg/03_0125058.PNG \n extracting: sign_data/sign_data/train/058_forg/03_0127058.PNG \n extracting: sign_data/sign_data/train/058_forg/04_0109058.PNG \n extracting: sign_data/sign_data/train/058_forg/04_0110058.PNG \n extracting: sign_data/sign_data/train/058_forg/04_0125058.PNG \n extracting: sign_data/sign_data/train/058_forg/04_0127058.PNG \n creating: sign_data/sign_data/train/059/\n extracting: sign_data/sign_data/train/059/01_059.png \n extracting: sign_data/sign_data/train/059/02_059.png \n extracting: sign_data/sign_data/train/059/03_059.png \n extracting: sign_data/sign_data/train/059/04_059.png \n extracting: sign_data/sign_data/train/059/05_059.png \n extracting: sign_data/sign_data/train/059/06_059.png \n extracting: sign_data/sign_data/train/059/07_059.png \n extracting: sign_data/sign_data/train/059/08_059.png \n extracting: sign_data/sign_data/train/059/09_059.png \n extracting: sign_data/sign_data/train/059/10_059.png \n extracting: sign_data/sign_data/train/059/11_059.png \n extracting: sign_data/sign_data/train/059/12_059.png \n creating: sign_data/sign_data/train/059_forg/\n extracting: sign_data/sign_data/train/059_forg/01_0104059.PNG \n extracting: sign_data/sign_data/train/059_forg/01_0125059.PNG \n extracting: sign_data/sign_data/train/059_forg/02_0104059.PNG \n extracting: sign_data/sign_data/train/059_forg/02_0125059.PNG \n extracting: sign_data/sign_data/train/059_forg/03_0104059.PNG \n extracting: sign_data/sign_data/train/059_forg/03_0125059.PNG \n extracting: sign_data/sign_data/train/059_forg/04_0104059.PNG \n extracting: sign_data/sign_data/train/059_forg/04_0125059.PNG \n creating: sign_data/sign_data/train/060/\n extracting: sign_data/sign_data/train/060/01_060.png \n extracting: sign_data/sign_data/train/060/02_060.png \n extracting: sign_data/sign_data/train/060/03_060.png \n extracting: sign_data/sign_data/train/060/04_060.png \n extracting: sign_data/sign_data/train/060/05_060.png \n extracting: sign_data/sign_data/train/060/06_060.png \n extracting: sign_data/sign_data/train/060/07_060.png \n extracting: sign_data/sign_data/train/060/08_060.png \n extracting: sign_data/sign_data/train/060/09_060.png \n extracting: sign_data/sign_data/train/060/10_060.png \n extracting: sign_data/sign_data/train/060/11_060.png \n extracting: sign_data/sign_data/train/060/12_060.png \n creating: sign_data/sign_data/train/060_forg/\n extracting: sign_data/sign_data/train/060_forg/01_0111060.PNG \n extracting: sign_data/sign_data/train/060_forg/01_0121060.PNG \n extracting: sign_data/sign_data/train/060_forg/01_0126060.PNG \n extracting: sign_data/sign_data/train/060_forg/02_0111060.PNG \n extracting: sign_data/sign_data/train/060_forg/02_0121060.PNG \n extracting: sign_data/sign_data/train/060_forg/02_0126060.PNG \n extracting: sign_data/sign_data/train/060_forg/03_0111060.PNG \n extracting: sign_data/sign_data/train/060_forg/03_0121060.PNG \n extracting: sign_data/sign_data/train/060_forg/03_0126060.PNG \n extracting: sign_data/sign_data/train/060_forg/04_0111060.PNG \n extracting: sign_data/sign_data/train/060_forg/04_0121060.PNG \n extracting: sign_data/sign_data/train/060_forg/04_0126060.PNG \n creating: sign_data/sign_data/train/061/\n extracting: sign_data/sign_data/train/061/01_061.png \n extracting: sign_data/sign_data/train/061/02_061.png \n extracting: sign_data/sign_data/train/061/03_061.png \n extracting: sign_data/sign_data/train/061/04_061.png \n extracting: sign_data/sign_data/train/061/05_061.png \n extracting: sign_data/sign_data/train/061/06_061.png \n extracting: sign_data/sign_data/train/061/07_061.png \n extracting: sign_data/sign_data/train/061/08_061.png \n extracting: sign_data/sign_data/train/061/09_061.png \n extracting: sign_data/sign_data/train/061/10_061.png \n extracting: sign_data/sign_data/train/061/11_061.png \n extracting: sign_data/sign_data/train/061/12_061.png \n creating: sign_data/sign_data/train/061_forg/\n extracting: sign_data/sign_data/train/061_forg/01_0102061.PNG \n extracting: sign_data/sign_data/train/061_forg/01_0112061.PNG \n extracting: sign_data/sign_data/train/061_forg/01_0206061.PNG \n extracting: sign_data/sign_data/train/061_forg/02_0102061.PNG \n extracting: sign_data/sign_data/train/061_forg/02_0112061.PNG \n extracting: sign_data/sign_data/train/061_forg/02_0206061.PNG \n extracting: sign_data/sign_data/train/061_forg/03_0102061.PNG \n extracting: sign_data/sign_data/train/061_forg/03_0112061.PNG \n extracting: sign_data/sign_data/train/061_forg/03_0206061.PNG \n extracting: sign_data/sign_data/train/061_forg/04_0102061.PNG \n extracting: sign_data/sign_data/train/061_forg/04_0112061.PNG \n extracting: sign_data/sign_data/train/061_forg/04_0206061.PNG \n creating: sign_data/sign_data/train/062/\n extracting: sign_data/sign_data/train/062/01_062.png \n extracting: sign_data/sign_data/train/062/02_062.png \n extracting: sign_data/sign_data/train/062/03_062.png \n extracting: sign_data/sign_data/train/062/04_062.png \n extracting: sign_data/sign_data/train/062/05_062.png \n inflating: sign_data/sign_data/train/062/06_062.png \n extracting: sign_data/sign_data/train/062/07_062.png \n extracting: sign_data/sign_data/train/062/08_062.png \n extracting: sign_data/sign_data/train/062/09_062.png \n extracting: sign_data/sign_data/train/062/10_062.png \n extracting: sign_data/sign_data/train/062/11_062.png \n extracting: sign_data/sign_data/train/062/12_062.png \n creating: sign_data/sign_data/train/062_forg/\n extracting: sign_data/sign_data/train/062_forg/01_0109062.PNG \n extracting: sign_data/sign_data/train/062_forg/01_0116062.PNG \n extracting: sign_data/sign_data/train/062_forg/01_0201062.PNG \n extracting: sign_data/sign_data/train/062_forg/02_0109062.PNG \n extracting: sign_data/sign_data/train/062_forg/02_0116062.PNG \n extracting: sign_data/sign_data/train/062_forg/02_0201062.PNG \n extracting: sign_data/sign_data/train/062_forg/03_0109062.PNG \n extracting: sign_data/sign_data/train/062_forg/03_0116062.PNG \n extracting: sign_data/sign_data/train/062_forg/03_0201062.PNG \n extracting: sign_data/sign_data/train/062_forg/04_0109062.PNG \n extracting: sign_data/sign_data/train/062_forg/04_0116062.PNG \n extracting: sign_data/sign_data/train/062_forg/04_0201062.PNG \n creating: sign_data/sign_data/train/063/\n extracting: sign_data/sign_data/train/063/01_063.png \n extracting: sign_data/sign_data/train/063/02_063.png \n extracting: sign_data/sign_data/train/063/03_063.png \n extracting: sign_data/sign_data/train/063/04_063.png \n extracting: sign_data/sign_data/train/063/05_063.png \n extracting: sign_data/sign_data/train/063/06_063.png \n extracting: sign_data/sign_data/train/063/07_063.png \n extracting: sign_data/sign_data/train/063/08_063.png \n extracting: sign_data/sign_data/train/063/09_063.png \n extracting: sign_data/sign_data/train/063/10_063.png \n extracting: sign_data/sign_data/train/063/11_063.png \n extracting: sign_data/sign_data/train/063/12_063.png \n creating: sign_data/sign_data/train/063_forg/\n extracting: sign_data/sign_data/train/063_forg/01_0104063.PNG \n extracting: sign_data/sign_data/train/063_forg/01_0108063.PNG \n extracting: sign_data/sign_data/train/063_forg/01_0119063.PNG \n extracting: sign_data/sign_data/train/063_forg/02_0104063.PNG \n extracting: sign_data/sign_data/train/063_forg/02_0108063.PNG \n extracting: sign_data/sign_data/train/063_forg/02_0119063.PNG \n extracting: sign_data/sign_data/train/063_forg/03_0104063.PNG \n extracting: sign_data/sign_data/train/063_forg/03_0108063.PNG \n extracting: sign_data/sign_data/train/063_forg/03_0119063.PNG \n extracting: sign_data/sign_data/train/063_forg/04_0104063.PNG \n extracting: sign_data/sign_data/train/063_forg/04_0108063.PNG \n extracting: sign_data/sign_data/train/063_forg/04_0119063.PNG \n creating: sign_data/sign_data/train/064/\n extracting: sign_data/sign_data/train/064/01_064.png \n extracting: sign_data/sign_data/train/064/02_064.png \n extracting: sign_data/sign_data/train/064/03_064.png \n extracting: sign_data/sign_data/train/064/04_064.png \n extracting: sign_data/sign_data/train/064/05_064.png \n extracting: sign_data/sign_data/train/064/06_064.png \n extracting: sign_data/sign_data/train/064/07_064.png \n extracting: sign_data/sign_data/train/064/08_064.png \n extracting: sign_data/sign_data/train/064/09_064.png \n extracting: sign_data/sign_data/train/064/10_064.png \n extracting: sign_data/sign_data/train/064/11_064.png \n extracting: sign_data/sign_data/train/064/12_064.png \n creating: sign_data/sign_data/train/064_forg/\n extracting: sign_data/sign_data/train/064_forg/01_0105064.PNG \n extracting: sign_data/sign_data/train/064_forg/01_0203064.PNG \n extracting: sign_data/sign_data/train/064_forg/02_0105064.PNG \n extracting: sign_data/sign_data/train/064_forg/02_0203064.PNG \n extracting: sign_data/sign_data/train/064_forg/03_0105064.PNG \n extracting: sign_data/sign_data/train/064_forg/03_0203064.PNG \n extracting: sign_data/sign_data/train/064_forg/04_0105064.PNG \n extracting: sign_data/sign_data/train/064_forg/04_0203064.PNG \n creating: sign_data/sign_data/train/065/\n extracting: sign_data/sign_data/train/065/01_065.png \n extracting: sign_data/sign_data/train/065/02_065.png \n extracting: sign_data/sign_data/train/065/03_065.png \n extracting: sign_data/sign_data/train/065/04_065.png \n extracting: sign_data/sign_data/train/065/05_065.png \n extracting: sign_data/sign_data/train/065/06_065.png \n extracting: sign_data/sign_data/train/065/07_065.png \n extracting: sign_data/sign_data/train/065/08_065.png \n extracting: sign_data/sign_data/train/065/09_065.png \n extracting: sign_data/sign_data/train/065/10_065.png \n extracting: sign_data/sign_data/train/065/11_065.png \n extracting: sign_data/sign_data/train/065/12_065.png \n creating: sign_data/sign_data/train/065_forg/\n extracting: sign_data/sign_data/train/065_forg/01_0118065.PNG \n extracting: sign_data/sign_data/train/065_forg/01_0206065.PNG \n extracting: sign_data/sign_data/train/065_forg/02_0118065.PNG \n extracting: sign_data/sign_data/train/065_forg/02_0206065.PNG \n extracting: sign_data/sign_data/train/065_forg/03_0118065.PNG \n extracting: sign_data/sign_data/train/065_forg/03_0206065.PNG \n extracting: sign_data/sign_data/train/065_forg/04_0118065.PNG \n extracting: sign_data/sign_data/train/065_forg/04_0206065.PNG \n creating: sign_data/sign_data/train/066/\n extracting: sign_data/sign_data/train/066/01_066.png \n extracting: sign_data/sign_data/train/066/02_066.png \n extracting: sign_data/sign_data/train/066/03_066.png \n extracting: sign_data/sign_data/train/066/04_066.png \n extracting: sign_data/sign_data/train/066/05_066.png \n extracting: sign_data/sign_data/train/066/06_066.png \n extracting: sign_data/sign_data/train/066/07_066.png \n extracting: sign_data/sign_data/train/066/08_066.png \n extracting: sign_data/sign_data/train/066/09_066.png \n extracting: sign_data/sign_data/train/066/10_066.png \n extracting: sign_data/sign_data/train/066/11_066.png \n extracting: sign_data/sign_data/train/066/12_066.png \n creating: sign_data/sign_data/train/066_forg/\n extracting: sign_data/sign_data/train/066_forg/01_0101066.PNG \n extracting: sign_data/sign_data/train/066_forg/01_0127066.PNG \n extracting: sign_data/sign_data/train/066_forg/01_0211066.PNG \n extracting: sign_data/sign_data/train/066_forg/01_0212066.PNG \n extracting: sign_data/sign_data/train/066_forg/02_0101066.PNG \n extracting: sign_data/sign_data/train/066_forg/02_0127066.PNG \n extracting: sign_data/sign_data/train/066_forg/02_0211066.PNG \n extracting: sign_data/sign_data/train/066_forg/02_0212066.PNG \n extracting: sign_data/sign_data/train/066_forg/03_0101066.PNG \n extracting: sign_data/sign_data/train/066_forg/03_0127066.PNG \n extracting: sign_data/sign_data/train/066_forg/03_0211066.PNG \n extracting: sign_data/sign_data/train/066_forg/03_0212066.PNG \n extracting: sign_data/sign_data/train/066_forg/04_0101066.PNG \n extracting: sign_data/sign_data/train/066_forg/04_0127066.PNG \n extracting: sign_data/sign_data/train/066_forg/04_0211066.PNG \n extracting: sign_data/sign_data/train/066_forg/04_0212066.PNG \n creating: sign_data/sign_data/train/067/\n extracting: sign_data/sign_data/train/067/01_067.png \n extracting: sign_data/sign_data/train/067/02_067.png \n extracting: sign_data/sign_data/train/067/03_067.png \n extracting: sign_data/sign_data/train/067/04_067.png \n extracting: sign_data/sign_data/train/067/05_067.png \n extracting: sign_data/sign_data/train/067/06_067.png \n extracting: sign_data/sign_data/train/067/07_067.png \n extracting: sign_data/sign_data/train/067/08_067.png \n extracting: sign_data/sign_data/train/067/09_067.png \n extracting: sign_data/sign_data/train/067/10_067.png \n extracting: sign_data/sign_data/train/067/11_067.png \n extracting: sign_data/sign_data/train/067/12_067.png \n creating: sign_data/sign_data/train/067_forg/\n extracting: sign_data/sign_data/train/067_forg/01_0205067.PNG \n extracting: sign_data/sign_data/train/067_forg/01_0212067.PNG \n extracting: sign_data/sign_data/train/067_forg/02_0205067.PNG \n extracting: sign_data/sign_data/train/067_forg/02_0212067.PNG \n extracting: sign_data/sign_data/train/067_forg/03_0205067.PNG \n extracting: sign_data/sign_data/train/067_forg/03_0212067.PNG \n extracting: sign_data/sign_data/train/067_forg/04_0205067.PNG \n extracting: sign_data/sign_data/train/067_forg/04_0212067.PNG \n creating: sign_data/sign_data/train/068/\n extracting: sign_data/sign_data/train/068/01_068.png \n extracting: sign_data/sign_data/train/068/02_068.png \n extracting: sign_data/sign_data/train/068/03_068.png \n extracting: sign_data/sign_data/train/068/04_068.png \n extracting: sign_data/sign_data/train/068/05_068.png \n extracting: sign_data/sign_data/train/068/06_068.png \n extracting: sign_data/sign_data/train/068/07_068.png \n extracting: sign_data/sign_data/train/068/08_068.png \n extracting: sign_data/sign_data/train/068/09_068.png \n extracting: sign_data/sign_data/train/068/10_068.png \n extracting: sign_data/sign_data/train/068/11_068.png \n extracting: sign_data/sign_data/train/068/12_068.png \n creating: sign_data/sign_data/train/068_forg/\n extracting: sign_data/sign_data/train/068_forg/01_0113068.PNG \n extracting: sign_data/sign_data/train/068_forg/01_0124068.PNG \n extracting: sign_data/sign_data/train/068_forg/02_0113068.PNG \n extracting: sign_data/sign_data/train/068_forg/02_0124068.PNG \n extracting: sign_data/sign_data/train/068_forg/03_0113068.PNG \n extracting: sign_data/sign_data/train/068_forg/03_0124068.PNG \n extracting: sign_data/sign_data/train/068_forg/04_0113068.PNG \n extracting: sign_data/sign_data/train/068_forg/04_0124068.PNG \n creating: sign_data/sign_data/train/069/\n extracting: sign_data/sign_data/train/069/01_069.png \n extracting: sign_data/sign_data/train/069/02_069.png \n extracting: sign_data/sign_data/train/069/03_069.png \n extracting: sign_data/sign_data/train/069/04_069.png \n extracting: sign_data/sign_data/train/069/05_069.png \n extracting: sign_data/sign_data/train/069/06_069.png \n extracting: sign_data/sign_data/train/069/07_069.png \n extracting: sign_data/sign_data/train/069/08_069.png \n extracting: sign_data/sign_data/train/069/09_069.png \n extracting: sign_data/sign_data/train/069/10_069.png \n extracting: sign_data/sign_data/train/069/11_069.png \n extracting: sign_data/sign_data/train/069/12_069.png \n creating: sign_data/sign_data/train/069_forg/\n extracting: sign_data/sign_data/train/069_forg/01_0106069.PNG \n extracting: sign_data/sign_data/train/069_forg/01_0108069.PNG \n extracting: sign_data/sign_data/train/069_forg/01_0111069.PNG \n extracting: sign_data/sign_data/train/069_forg/02_0106069.PNG \n extracting: sign_data/sign_data/train/069_forg/02_0108069.PNG \n extracting: sign_data/sign_data/train/069_forg/02_0111069.PNG \n extracting: sign_data/sign_data/train/069_forg/03_0106069.PNG \n extracting: sign_data/sign_data/train/069_forg/03_0108069.PNG \n extracting: sign_data/sign_data/train/069_forg/03_0111069.PNG \n extracting: sign_data/sign_data/train/069_forg/04_0106069.PNG \n extracting: sign_data/sign_data/train/069_forg/04_0108069.PNG \n extracting: sign_data/sign_data/train/069_forg/04_0111069.PNG \n inflating: sign_data/sign_data/train_data.csv \n creating: sign_data/test/\n creating: sign_data/test/049/\n extracting: sign_data/test/049/01_049.png \n extracting: sign_data/test/049/02_049.png \n extracting: sign_data/test/049/03_049.png \n extracting: sign_data/test/049/04_049.png \n extracting: sign_data/test/049/05_049.png \n extracting: sign_data/test/049/06_049.png \n extracting: sign_data/test/049/07_049.png \n extracting: sign_data/test/049/08_049.png \n extracting: sign_data/test/049/09_049.png \n extracting: sign_data/test/049/10_049.png \n extracting: sign_data/test/049/11_049.png \n extracting: sign_data/test/049/12_049.png \n creating: sign_data/test/049_forg/\n extracting: sign_data/test/049_forg/01_0114049.PNG \n extracting: sign_data/test/049_forg/01_0206049.PNG \n extracting: sign_data/test/049_forg/01_0210049.PNG \n extracting: sign_data/test/049_forg/02_0114049.PNG \n extracting: sign_data/test/049_forg/02_0206049.PNG \n extracting: sign_data/test/049_forg/02_0210049.PNG \n extracting: sign_data/test/049_forg/03_0114049.PNG \n extracting: sign_data/test/049_forg/03_0206049.PNG \n extracting: sign_data/test/049_forg/03_0210049.PNG \n extracting: sign_data/test/049_forg/04_0114049.PNG \n extracting: sign_data/test/049_forg/04_0206049.PNG \n extracting: sign_data/test/049_forg/04_0210049.PNG \n creating: sign_data/test/050/\n extracting: sign_data/test/050/01_050.png \n extracting: sign_data/test/050/02_050.png \n extracting: sign_data/test/050/03_050.png \n extracting: sign_data/test/050/04_050.png \n extracting: sign_data/test/050/05_050.png \n extracting: sign_data/test/050/06_050.png \n extracting: sign_data/test/050/07_050.png \n extracting: sign_data/test/050/08_050.png \n extracting: sign_data/test/050/09_050.png \n extracting: sign_data/test/050/10_050.png \n extracting: sign_data/test/050/11_050.png \n extracting: sign_data/test/050/12_050.png \n creating: sign_data/test/050_forg/\n extracting: sign_data/test/050_forg/01_0125050.PNG \n extracting: sign_data/test/050_forg/01_0126050.PNG \n extracting: sign_data/test/050_forg/01_0204050.PNG \n extracting: sign_data/test/050_forg/02_0125050.PNG \n extracting: sign_data/test/050_forg/02_0126050.PNG \n extracting: sign_data/test/050_forg/02_0204050.PNG \n extracting: sign_data/test/050_forg/03_0125050.PNG \n extracting: sign_data/test/050_forg/03_0126050.PNG \n extracting: sign_data/test/050_forg/03_0204050.PNG \n extracting: sign_data/test/050_forg/04_0125050.PNG \n extracting: sign_data/test/050_forg/04_0126050.PNG \n extracting: sign_data/test/050_forg/04_0204050.PNG \n creating: sign_data/test/051/\n extracting: sign_data/test/051/01_051.png \n extracting: sign_data/test/051/02_051.png \n extracting: sign_data/test/051/03_051.png \n extracting: sign_data/test/051/04_051.png \n extracting: sign_data/test/051/05_051.png \n extracting: sign_data/test/051/06_051.png \n extracting: sign_data/test/051/07_051.png \n extracting: sign_data/test/051/08_051.png \n extracting: sign_data/test/051/09_051.png \n extracting: sign_data/test/051/10_051.png \n extracting: sign_data/test/051/11_051.png \n extracting: sign_data/test/051/12_051.png \n creating: sign_data/test/051_forg/\n extracting: sign_data/test/051_forg/01_0104051.PNG \n extracting: sign_data/test/051_forg/01_0120051.PNG \n extracting: sign_data/test/051_forg/02_0104051.PNG \n extracting: sign_data/test/051_forg/02_0120051.PNG \n extracting: sign_data/test/051_forg/03_0104051.PNG \n extracting: sign_data/test/051_forg/03_0120051.PNG \n extracting: sign_data/test/051_forg/04_0104051.PNG \n extracting: sign_data/test/051_forg/04_0120051.PNG \n creating: sign_data/test/052/\n extracting: sign_data/test/052/01_052.png \n extracting: sign_data/test/052/02_052.png \n extracting: sign_data/test/052/03_052.png \n extracting: sign_data/test/052/04_052.png \n extracting: sign_data/test/052/05_052.png \n extracting: sign_data/test/052/06_052.png \n extracting: sign_data/test/052/07_052.png \n extracting: sign_data/test/052/08_052.png \n extracting: sign_data/test/052/09_052.png \n extracting: sign_data/test/052/10_052.png \n extracting: sign_data/test/052/11_052.png \n extracting: sign_data/test/052/12_052.png \n creating: sign_data/test/052_forg/\n extracting: sign_data/test/052_forg/01_0106052.PNG \n extracting: sign_data/test/052_forg/01_0109052.PNG \n extracting: sign_data/test/052_forg/01_0207052.PNG \n extracting: sign_data/test/052_forg/01_0210052.PNG \n extracting: sign_data/test/052_forg/02_0106052.PNG \n extracting: sign_data/test/052_forg/02_0109052.PNG \n extracting: sign_data/test/052_forg/02_0207052.PNG \n extracting: sign_data/test/052_forg/02_0210052.PNG \n extracting: sign_data/test/052_forg/03_0106052.PNG \n extracting: sign_data/test/052_forg/03_0109052.PNG \n extracting: sign_data/test/052_forg/03_0207052.PNG \n extracting: sign_data/test/052_forg/03_0210052.PNG \n extracting: sign_data/test/052_forg/04_0106052.PNG \n extracting: sign_data/test/052_forg/04_0109052.PNG \n extracting: sign_data/test/052_forg/04_0207052.PNG \n extracting: sign_data/test/052_forg/04_0210052.PNG \n creating: sign_data/test/053/\n extracting: sign_data/test/053/01_053.png \n extracting: sign_data/test/053/02_053.png \n extracting: sign_data/test/053/03_053.png \n extracting: sign_data/test/053/04_053.png \n extracting: sign_data/test/053/05_053.png \n extracting: sign_data/test/053/06_053.png \n extracting: sign_data/test/053/07_053.png \n extracting: sign_data/test/053/08_053.png \n extracting: sign_data/test/053/09_053.png \n extracting: sign_data/test/053/10_053.png \n extracting: sign_data/test/053/11_053.png \n extracting: sign_data/test/053/12_053.png \n creating: sign_data/test/053_forg/\n extracting: sign_data/test/053_forg/01_0107053.PNG \n extracting: sign_data/test/053_forg/01_0115053.PNG \n extracting: sign_data/test/053_forg/01_0202053.PNG \n extracting: sign_data/test/053_forg/01_0207053.PNG \n extracting: sign_data/test/053_forg/02_0107053.PNG \n extracting: sign_data/test/053_forg/02_0115053.PNG \n extracting: sign_data/test/053_forg/02_0202053.PNG \n extracting: sign_data/test/053_forg/02_0207053.PNG \n extracting: sign_data/test/053_forg/03_0107053.PNG \n extracting: sign_data/test/053_forg/03_0115053.PNG \n extracting: sign_data/test/053_forg/03_0202053.PNG \n extracting: sign_data/test/053_forg/03_0207053.PNG \n extracting: sign_data/test/053_forg/04_0107053.PNG \n extracting: sign_data/test/053_forg/04_0115053.PNG \n extracting: sign_data/test/053_forg/04_0202053.PNG \n extracting: sign_data/test/053_forg/04_0207053.PNG \n creating: sign_data/test/054/\n extracting: sign_data/test/054/01_054.png \n extracting: sign_data/test/054/02_054.png \n extracting: sign_data/test/054/03_054.png \n extracting: sign_data/test/054/04_054.png \n extracting: sign_data/test/054/05_054.png \n extracting: sign_data/test/054/06_054.png \n extracting: sign_data/test/054/07_054.png \n extracting: sign_data/test/054/08_054.png \n extracting: sign_data/test/054/09_054.png \n extracting: sign_data/test/054/10_054.png \n extracting: sign_data/test/054/11_054.png \n extracting: sign_data/test/054/12_054.png \n creating: sign_data/test/054_forg/\n extracting: sign_data/test/054_forg/01_0102054.PNG \n extracting: sign_data/test/054_forg/01_0124054.PNG \n extracting: sign_data/test/054_forg/01_0207054.PNG \n extracting: sign_data/test/054_forg/01_0208054.PNG \n extracting: sign_data/test/054_forg/01_0214054.PNG \n extracting: sign_data/test/054_forg/02_0102054.PNG \n extracting: sign_data/test/054_forg/02_0124054.PNG \n extracting: sign_data/test/054_forg/02_0207054.PNG \n extracting: sign_data/test/054_forg/02_0208054.PNG \n extracting: sign_data/test/054_forg/02_0214054.PNG \n extracting: sign_data/test/054_forg/03_0102054.PNG \n extracting: sign_data/test/054_forg/03_0124054.PNG \n extracting: sign_data/test/054_forg/03_0207054.PNG \n extracting: sign_data/test/054_forg/03_0208054.PNG \n extracting: sign_data/test/054_forg/03_0214054.PNG \n extracting: sign_data/test/054_forg/04_0102054.PNG \n extracting: sign_data/test/054_forg/04_0124054.PNG \n extracting: sign_data/test/054_forg/04_0207054.PNG \n extracting: sign_data/test/054_forg/04_0208054.PNG \n extracting: sign_data/test/054_forg/04_0214054.PNG \n creating: sign_data/test/055/\n extracting: sign_data/test/055/01_055.png \n extracting: sign_data/test/055/02_055.png \n extracting: sign_data/test/055/03_055.png \n extracting: sign_data/test/055/04_055.png \n extracting: sign_data/test/055/05_055.png \n extracting: sign_data/test/055/06_055.png \n extracting: sign_data/test/055/07_055.png \n extracting: sign_data/test/055/08_055.png \n extracting: sign_data/test/055/09_055.png \n extracting: sign_data/test/055/10_055.png \n extracting: sign_data/test/055/11_055.png \n extracting: sign_data/test/055/12_055.png \n creating: sign_data/test/055_forg/\n extracting: sign_data/test/055_forg/01_0118055.PNG \n extracting: sign_data/test/055_forg/01_0120055.PNG \n extracting: sign_data/test/055_forg/01_0202055.PNG \n extracting: sign_data/test/055_forg/02_0118055.PNG \n extracting: sign_data/test/055_forg/02_0120055.PNG \n extracting: sign_data/test/055_forg/02_0202055.PNG \n extracting: sign_data/test/055_forg/03_0118055.PNG \n extracting: sign_data/test/055_forg/03_0120055.PNG \n extracting: sign_data/test/055_forg/03_0202055.PNG \n extracting: sign_data/test/055_forg/04_0118055.PNG \n extracting: sign_data/test/055_forg/04_0120055.PNG \n extracting: sign_data/test/055_forg/04_0202055.PNG \n creating: sign_data/test/056/\n extracting: sign_data/test/056/01_056.png \n extracting: sign_data/test/056/02_056.png \n extracting: sign_data/test/056/03_056.png \n extracting: sign_data/test/056/04_056.png \n extracting: sign_data/test/056/05_056.png \n extracting: sign_data/test/056/06_056.png \n extracting: sign_data/test/056/07_056.png \n extracting: sign_data/test/056/08_056.png \n extracting: sign_data/test/056/09_056.png \n extracting: sign_data/test/056/10_056.png \n extracting: sign_data/test/056/11_056.png \n extracting: sign_data/test/056/12_056.png \n creating: sign_data/test/056_forg/\n extracting: sign_data/test/056_forg/01_0105056.PNG \n extracting: sign_data/test/056_forg/01_0115056.PNG \n extracting: sign_data/test/056_forg/02_0105056.PNG \n extracting: sign_data/test/056_forg/02_0115056.PNG \n extracting: sign_data/test/056_forg/03_0105056.PNG \n extracting: sign_data/test/056_forg/03_0115056.PNG \n extracting: sign_data/test/056_forg/04_0105056.PNG \n extracting: sign_data/test/056_forg/04_0115056.PNG \n creating: sign_data/test/057/\n extracting: sign_data/test/057/01_057.png \n extracting: sign_data/test/057/02_057.png \n extracting: sign_data/test/057/03_057.png \n extracting: sign_data/test/057/04_057.png \n extracting: sign_data/test/057/05_057.png \n extracting: sign_data/test/057/06_057.png \n extracting: sign_data/test/057/07_057.png \n extracting: sign_data/test/057/08_057.png \n extracting: sign_data/test/057/09_057.png \n extracting: sign_data/test/057/10_057.png \n extracting: sign_data/test/057/11_057.png \n extracting: sign_data/test/057/12_057.png \n creating: sign_data/test/057_forg/\n extracting: sign_data/test/057_forg/01_0117057.PNG \n extracting: sign_data/test/057_forg/01_0208057.PNG \n extracting: sign_data/test/057_forg/01_0210057.PNG \n extracting: sign_data/test/057_forg/02_0117057.PNG \n extracting: sign_data/test/057_forg/02_0208057.PNG \n extracting: sign_data/test/057_forg/02_0210057.PNG \n extracting: sign_data/test/057_forg/03_0117057.PNG \n extracting: sign_data/test/057_forg/03_0208057.PNG \n extracting: sign_data/test/057_forg/03_0210057.PNG \n extracting: sign_data/test/057_forg/04_0117057.PNG \n extracting: sign_data/test/057_forg/04_0208057.PNG \n extracting: sign_data/test/057_forg/04_0210057.PNG \n creating: sign_data/test/058/\n extracting: sign_data/test/058/01_058.png \n extracting: sign_data/test/058/02_058.png \n extracting: sign_data/test/058/03_058.png \n extracting: sign_data/test/058/04_058.png \n extracting: sign_data/test/058/05_058.png \n extracting: sign_data/test/058/06_058.png \n extracting: sign_data/test/058/07_058.png \n extracting: sign_data/test/058/08_058.png \n extracting: sign_data/test/058/09_058.png \n extracting: sign_data/test/058/10_058.png \n extracting: sign_data/test/058/11_058.png \n extracting: sign_data/test/058/12_058.png \n creating: sign_data/test/058_forg/\n extracting: sign_data/test/058_forg/01_0109058.PNG \n extracting: sign_data/test/058_forg/01_0110058.PNG \n extracting: sign_data/test/058_forg/01_0125058.PNG \n extracting: sign_data/test/058_forg/01_0127058.PNG \n extracting: sign_data/test/058_forg/02_0109058.PNG \n extracting: sign_data/test/058_forg/02_0110058.PNG \n extracting: sign_data/test/058_forg/02_0125058.PNG \n extracting: sign_data/test/058_forg/02_0127058.PNG \n extracting: sign_data/test/058_forg/03_0109058.PNG \n extracting: sign_data/test/058_forg/03_0110058.PNG \n extracting: sign_data/test/058_forg/03_0125058.PNG \n extracting: sign_data/test/058_forg/03_0127058.PNG \n extracting: sign_data/test/058_forg/04_0109058.PNG \n extracting: sign_data/test/058_forg/04_0110058.PNG \n extracting: sign_data/test/058_forg/04_0125058.PNG \n extracting: sign_data/test/058_forg/04_0127058.PNG \n creating: sign_data/test/059/\n extracting: sign_data/test/059/01_059.png \n extracting: sign_data/test/059/02_059.png \n extracting: sign_data/test/059/03_059.png \n extracting: sign_data/test/059/04_059.png \n extracting: sign_data/test/059/05_059.png \n extracting: sign_data/test/059/06_059.png \n extracting: sign_data/test/059/07_059.png \n extracting: sign_data/test/059/08_059.png \n extracting: sign_data/test/059/09_059.png \n extracting: sign_data/test/059/10_059.png \n extracting: sign_data/test/059/11_059.png \n extracting: sign_data/test/059/12_059.png \n creating: sign_data/test/059_forg/\n extracting: sign_data/test/059_forg/01_0104059.PNG \n extracting: sign_data/test/059_forg/01_0125059.PNG \n extracting: sign_data/test/059_forg/02_0104059.PNG \n extracting: sign_data/test/059_forg/02_0125059.PNG \n extracting: sign_data/test/059_forg/03_0104059.PNG \n extracting: sign_data/test/059_forg/03_0125059.PNG \n extracting: sign_data/test/059_forg/04_0104059.PNG \n extracting: sign_data/test/059_forg/04_0125059.PNG \n creating: sign_data/test/060/\n extracting: sign_data/test/060/01_060.png \n extracting: sign_data/test/060/02_060.png \n extracting: sign_data/test/060/03_060.png \n extracting: sign_data/test/060/04_060.png \n extracting: sign_data/test/060/05_060.png \n extracting: sign_data/test/060/06_060.png \n extracting: sign_data/test/060/07_060.png \n extracting: sign_data/test/060/08_060.png \n extracting: sign_data/test/060/09_060.png \n extracting: sign_data/test/060/10_060.png \n extracting: sign_data/test/060/11_060.png \n extracting: sign_data/test/060/12_060.png \n creating: sign_data/test/060_forg/\n extracting: sign_data/test/060_forg/01_0111060.PNG \n extracting: sign_data/test/060_forg/01_0121060.PNG \n extracting: sign_data/test/060_forg/01_0126060.PNG \n extracting: sign_data/test/060_forg/02_0111060.PNG \n extracting: sign_data/test/060_forg/02_0121060.PNG \n extracting: sign_data/test/060_forg/02_0126060.PNG \n extracting: sign_data/test/060_forg/03_0111060.PNG \n extracting: sign_data/test/060_forg/03_0121060.PNG \n extracting: sign_data/test/060_forg/03_0126060.PNG \n extracting: sign_data/test/060_forg/04_0111060.PNG \n extracting: sign_data/test/060_forg/04_0121060.PNG \n extracting: sign_data/test/060_forg/04_0126060.PNG \n creating: sign_data/test/061/\n extracting: sign_data/test/061/01_061.png \n extracting: sign_data/test/061/02_061.png \n extracting: sign_data/test/061/03_061.png \n extracting: sign_data/test/061/04_061.png \n extracting: sign_data/test/061/05_061.png \n extracting: sign_data/test/061/06_061.png \n extracting: sign_data/test/061/07_061.png \n extracting: sign_data/test/061/08_061.png \n extracting: sign_data/test/061/09_061.png \n extracting: sign_data/test/061/10_061.png \n extracting: sign_data/test/061/11_061.png \n extracting: sign_data/test/061/12_061.png \n creating: sign_data/test/061_forg/\n extracting: sign_data/test/061_forg/01_0102061.PNG \n extracting: sign_data/test/061_forg/01_0112061.PNG \n extracting: sign_data/test/061_forg/01_0206061.PNG \n extracting: sign_data/test/061_forg/02_0102061.PNG \n extracting: sign_data/test/061_forg/02_0112061.PNG \n extracting: sign_data/test/061_forg/02_0206061.PNG \n extracting: sign_data/test/061_forg/03_0102061.PNG \n extracting: sign_data/test/061_forg/03_0112061.PNG \n extracting: sign_data/test/061_forg/03_0206061.PNG \n extracting: sign_data/test/061_forg/04_0102061.PNG \n extracting: sign_data/test/061_forg/04_0112061.PNG \n extracting: sign_data/test/061_forg/04_0206061.PNG \n creating: sign_data/test/062/\n extracting: sign_data/test/062/01_062.png \n extracting: sign_data/test/062/02_062.png \n extracting: sign_data/test/062/03_062.png \n extracting: sign_data/test/062/04_062.png \n extracting: sign_data/test/062/05_062.png \n inflating: sign_data/test/062/06_062.png \n extracting: sign_data/test/062/07_062.png \n extracting: sign_data/test/062/08_062.png \n extracting: sign_data/test/062/09_062.png \n extracting: sign_data/test/062/10_062.png \n extracting: sign_data/test/062/11_062.png \n extracting: sign_data/test/062/12_062.png \n creating: sign_data/test/062_forg/\n extracting: sign_data/test/062_forg/01_0109062.PNG \n extracting: sign_data/test/062_forg/01_0116062.PNG \n extracting: sign_data/test/062_forg/01_0201062.PNG \n extracting: sign_data/test/062_forg/02_0109062.PNG \n extracting: sign_data/test/062_forg/02_0116062.PNG \n extracting: sign_data/test/062_forg/02_0201062.PNG \n extracting: sign_data/test/062_forg/03_0109062.PNG \n extracting: sign_data/test/062_forg/03_0116062.PNG \n extracting: sign_data/test/062_forg/03_0201062.PNG \n extracting: sign_data/test/062_forg/04_0109062.PNG \n extracting: sign_data/test/062_forg/04_0116062.PNG \n extracting: sign_data/test/062_forg/04_0201062.PNG \n creating: sign_data/test/063/\n extracting: sign_data/test/063/01_063.png \n extracting: sign_data/test/063/02_063.png \n extracting: sign_data/test/063/03_063.png \n extracting: sign_data/test/063/04_063.png \n extracting: sign_data/test/063/05_063.png \n extracting: sign_data/test/063/06_063.png \n extracting: sign_data/test/063/07_063.png \n extracting: sign_data/test/063/08_063.png \n extracting: sign_data/test/063/09_063.png \n extracting: sign_data/test/063/10_063.png \n extracting: sign_data/test/063/11_063.png \n extracting: sign_data/test/063/12_063.png \n creating: sign_data/test/063_forg/\n extracting: sign_data/test/063_forg/01_0104063.PNG \n extracting: sign_data/test/063_forg/01_0108063.PNG \n extracting: sign_data/test/063_forg/01_0119063.PNG \n extracting: sign_data/test/063_forg/02_0104063.PNG \n extracting: sign_data/test/063_forg/02_0108063.PNG \n extracting: sign_data/test/063_forg/02_0119063.PNG \n extracting: sign_data/test/063_forg/03_0104063.PNG \n extracting: sign_data/test/063_forg/03_0108063.PNG \n extracting: sign_data/test/063_forg/03_0119063.PNG \n extracting: sign_data/test/063_forg/04_0104063.PNG \n extracting: sign_data/test/063_forg/04_0108063.PNG \n extracting: sign_data/test/063_forg/04_0119063.PNG \n creating: sign_data/test/064/\n extracting: sign_data/test/064/01_064.png \n extracting: sign_data/test/064/02_064.png \n extracting: sign_data/test/064/03_064.png \n extracting: sign_data/test/064/04_064.png \n extracting: sign_data/test/064/05_064.png \n extracting: sign_data/test/064/06_064.png \n extracting: sign_data/test/064/07_064.png \n extracting: sign_data/test/064/08_064.png \n extracting: sign_data/test/064/09_064.png \n extracting: sign_data/test/064/10_064.png \n extracting: sign_data/test/064/11_064.png \n extracting: sign_data/test/064/12_064.png \n creating: sign_data/test/064_forg/\n extracting: sign_data/test/064_forg/01_0105064.PNG \n extracting: sign_data/test/064_forg/01_0203064.PNG \n extracting: sign_data/test/064_forg/02_0105064.PNG \n extracting: sign_data/test/064_forg/02_0203064.PNG \n extracting: sign_data/test/064_forg/03_0105064.PNG \n extracting: sign_data/test/064_forg/03_0203064.PNG \n extracting: sign_data/test/064_forg/04_0105064.PNG \n extracting: sign_data/test/064_forg/04_0203064.PNG \n creating: sign_data/test/065/\n extracting: sign_data/test/065/01_065.png \n extracting: sign_data/test/065/02_065.png \n extracting: sign_data/test/065/03_065.png \n extracting: sign_data/test/065/04_065.png \n extracting: sign_data/test/065/05_065.png \n extracting: sign_data/test/065/06_065.png \n extracting: sign_data/test/065/07_065.png \n extracting: sign_data/test/065/08_065.png \n extracting: sign_data/test/065/09_065.png \n extracting: sign_data/test/065/10_065.png \n extracting: sign_data/test/065/11_065.png \n extracting: sign_data/test/065/12_065.png \n creating: sign_data/test/065_forg/\n extracting: sign_data/test/065_forg/01_0118065.PNG \n extracting: sign_data/test/065_forg/01_0206065.PNG \n extracting: sign_data/test/065_forg/02_0118065.PNG \n extracting: sign_data/test/065_forg/02_0206065.PNG \n extracting: sign_data/test/065_forg/03_0118065.PNG \n extracting: sign_data/test/065_forg/03_0206065.PNG \n extracting: sign_data/test/065_forg/04_0118065.PNG \n extracting: sign_data/test/065_forg/04_0206065.PNG \n creating: sign_data/test/066/\n extracting: sign_data/test/066/01_066.png \n extracting: sign_data/test/066/02_066.png \n extracting: sign_data/test/066/03_066.png \n extracting: sign_data/test/066/04_066.png \n extracting: sign_data/test/066/05_066.png \n extracting: sign_data/test/066/06_066.png \n extracting: sign_data/test/066/07_066.png \n extracting: sign_data/test/066/08_066.png \n extracting: sign_data/test/066/09_066.png \n extracting: sign_data/test/066/10_066.png \n extracting: sign_data/test/066/11_066.png \n extracting: sign_data/test/066/12_066.png \n creating: sign_data/test/066_forg/\n extracting: sign_data/test/066_forg/01_0101066.PNG \n extracting: sign_data/test/066_forg/01_0127066.PNG \n extracting: sign_data/test/066_forg/01_0211066.PNG \n extracting: sign_data/test/066_forg/01_0212066.PNG \n extracting: sign_data/test/066_forg/02_0101066.PNG \n extracting: sign_data/test/066_forg/02_0127066.PNG \n extracting: sign_data/test/066_forg/02_0211066.PNG \n extracting: sign_data/test/066_forg/02_0212066.PNG \n extracting: sign_data/test/066_forg/03_0101066.PNG \n extracting: sign_data/test/066_forg/03_0127066.PNG \n extracting: sign_data/test/066_forg/03_0211066.PNG \n extracting: sign_data/test/066_forg/03_0212066.PNG \n extracting: sign_data/test/066_forg/04_0101066.PNG \n extracting: sign_data/test/066_forg/04_0127066.PNG \n extracting: sign_data/test/066_forg/04_0211066.PNG \n extracting: sign_data/test/066_forg/04_0212066.PNG \n creating: sign_data/test/067/\n extracting: sign_data/test/067/01_067.png \n extracting: sign_data/test/067/02_067.png \n extracting: sign_data/test/067/03_067.png \n extracting: sign_data/test/067/04_067.png \n extracting: sign_data/test/067/05_067.png \n extracting: sign_data/test/067/06_067.png \n extracting: sign_data/test/067/07_067.png \n extracting: sign_data/test/067/08_067.png \n extracting: sign_data/test/067/09_067.png \n extracting: sign_data/test/067/10_067.png \n extracting: sign_data/test/067/11_067.png \n extracting: sign_data/test/067/12_067.png \n creating: sign_data/test/067_forg/\n extracting: sign_data/test/067_forg/01_0205067.PNG \n extracting: sign_data/test/067_forg/01_0212067.PNG \n extracting: sign_data/test/067_forg/02_0205067.PNG \n extracting: sign_data/test/067_forg/02_0212067.PNG \n extracting: sign_data/test/067_forg/03_0205067.PNG \n extracting: sign_data/test/067_forg/03_0212067.PNG \n extracting: sign_data/test/067_forg/04_0205067.PNG \n extracting: sign_data/test/067_forg/04_0212067.PNG \n creating: sign_data/test/068/\n extracting: sign_data/test/068/01_068.png \n extracting: sign_data/test/068/02_068.png \n extracting: sign_data/test/068/03_068.png \n extracting: sign_data/test/068/04_068.png \n extracting: sign_data/test/068/05_068.png \n extracting: sign_data/test/068/06_068.png \n extracting: sign_data/test/068/07_068.png \n extracting: sign_data/test/068/08_068.png \n extracting: sign_data/test/068/09_068.png \n extracting: sign_data/test/068/10_068.png \n extracting: sign_data/test/068/11_068.png \n extracting: sign_data/test/068/12_068.png \n creating: sign_data/test/068_forg/\n extracting: sign_data/test/068_forg/01_0113068.PNG \n extracting: sign_data/test/068_forg/01_0124068.PNG \n extracting: sign_data/test/068_forg/02_0113068.PNG \n extracting: sign_data/test/068_forg/02_0124068.PNG \n extracting: sign_data/test/068_forg/03_0113068.PNG \n extracting: sign_data/test/068_forg/03_0124068.PNG \n extracting: sign_data/test/068_forg/04_0113068.PNG \n extracting: sign_data/test/068_forg/04_0124068.PNG \n creating: sign_data/test/069/\n extracting: sign_data/test/069/01_069.png \n extracting: sign_data/test/069/02_069.png \n extracting: sign_data/test/069/03_069.png \n extracting: sign_data/test/069/04_069.png \n extracting: sign_data/test/069/05_069.png \n extracting: sign_data/test/069/06_069.png \n extracting: sign_data/test/069/07_069.png \n extracting: sign_data/test/069/08_069.png \n extracting: sign_data/test/069/09_069.png \n extracting: sign_data/test/069/10_069.png \n extracting: sign_data/test/069/11_069.png \n extracting: sign_data/test/069/12_069.png \n creating: sign_data/test/069_forg/\n extracting: sign_data/test/069_forg/01_0106069.PNG \n extracting: sign_data/test/069_forg/01_0108069.PNG \n extracting: sign_data/test/069_forg/01_0111069.PNG \n extracting: sign_data/test/069_forg/02_0106069.PNG \n extracting: sign_data/test/069_forg/02_0108069.PNG \n extracting: sign_data/test/069_forg/02_0111069.PNG \n extracting: sign_data/test/069_forg/03_0106069.PNG \n extracting: sign_data/test/069_forg/03_0108069.PNG \n extracting: sign_data/test/069_forg/03_0111069.PNG \n extracting: sign_data/test/069_forg/04_0106069.PNG \n extracting: sign_data/test/069_forg/04_0108069.PNG \n extracting: sign_data/test/069_forg/04_0111069.PNG \n inflating: sign_data/test_data.csv \n creating: sign_data/train/\n creating: sign_data/train/001/\n extracting: sign_data/train/001/001_01.PNG \n extracting: sign_data/train/001/001_02.PNG \n extracting: sign_data/train/001/001_03.PNG \n extracting: sign_data/train/001/001_04.PNG \n extracting: sign_data/train/001/001_05.PNG \n extracting: sign_data/train/001/001_06.PNG \n extracting: sign_data/train/001/001_07.PNG \n extracting: sign_data/train/001/001_08.PNG \n extracting: sign_data/train/001/001_09.PNG \n extracting: sign_data/train/001/001_10.PNG \n extracting: sign_data/train/001/001_11.PNG \n extracting: sign_data/train/001/001_12.PNG \n extracting: sign_data/train/001/001_13.PNG \n extracting: sign_data/train/001/001_14.PNG \n extracting: sign_data/train/001/001_15.PNG \n extracting: sign_data/train/001/001_16.PNG \n extracting: sign_data/train/001/001_17.PNG \n extracting: sign_data/train/001/001_18.PNG \n extracting: sign_data/train/001/001_19.PNG \n extracting: sign_data/train/001/001_20.PNG \n extracting: sign_data/train/001/001_21.PNG \n extracting: sign_data/train/001/001_22.PNG \n extracting: sign_data/train/001/001_23.PNG \n extracting: sign_data/train/001/001_24.PNG \n creating: sign_data/train/001_forg/\n extracting: sign_data/train/001_forg/0119001_01.png \n extracting: sign_data/train/001_forg/0119001_02.png \n extracting: sign_data/train/001_forg/0119001_03.png \n extracting: sign_data/train/001_forg/0119001_04.png \n extracting: sign_data/train/001_forg/0201001_01.png \n extracting: sign_data/train/001_forg/0201001_02.png \n extracting: sign_data/train/001_forg/0201001_03.png \n extracting: sign_data/train/001_forg/0201001_04.png \n creating: sign_data/train/002/\n extracting: sign_data/train/002/002_01.PNG \n extracting: sign_data/train/002/002_02.PNG \n extracting: sign_data/train/002/002_03.PNG \n extracting: sign_data/train/002/002_04.PNG \n extracting: sign_data/train/002/002_05.PNG \n extracting: sign_data/train/002/002_06.PNG \n extracting: sign_data/train/002/002_07.PNG \n extracting: sign_data/train/002/002_08.PNG \n extracting: sign_data/train/002/002_09.PNG \n extracting: sign_data/train/002/002_10.PNG \n extracting: sign_data/train/002/002_11.PNG \n extracting: sign_data/train/002/002_12.PNG \n extracting: sign_data/train/002/002_13.PNG \n extracting: sign_data/train/002/002_14.PNG \n extracting: sign_data/train/002/002_15.PNG \n extracting: sign_data/train/002/002_16.PNG \n extracting: sign_data/train/002/002_17.PNG \n extracting: sign_data/train/002/002_18.PNG \n extracting: sign_data/train/002/002_19.PNG \n extracting: sign_data/train/002/002_20.PNG \n extracting: sign_data/train/002/002_21.PNG \n extracting: sign_data/train/002/002_22.PNG \n extracting: sign_data/train/002/002_23.PNG \n extracting: sign_data/train/002/002_24.PNG \n creating: sign_data/train/002_forg/\n extracting: sign_data/train/002_forg/0108002_01.png \n extracting: sign_data/train/002_forg/0108002_02.png \n extracting: sign_data/train/002_forg/0108002_03.png \n extracting: sign_data/train/002_forg/0108002_04.png \n extracting: sign_data/train/002_forg/0110002_01.png \n extracting: sign_data/train/002_forg/0110002_02.png \n extracting: sign_data/train/002_forg/0110002_03.png \n extracting: sign_data/train/002_forg/0110002_04.png \n extracting: sign_data/train/002_forg/0118002_01.png \n extracting: sign_data/train/002_forg/0118002_02.png \n extracting: sign_data/train/002_forg/0118002_03.png \n extracting: sign_data/train/002_forg/0118002_04.png \n creating: sign_data/train/003/\n extracting: sign_data/train/003/003_01.PNG \n extracting: sign_data/train/003/003_02.PNG \n extracting: sign_data/train/003/003_03.PNG \n extracting: sign_data/train/003/003_04.PNG \n extracting: sign_data/train/003/003_05.PNG \n extracting: sign_data/train/003/003_06.PNG \n extracting: sign_data/train/003/003_07.PNG \n extracting: sign_data/train/003/003_08.PNG \n extracting: sign_data/train/003/003_09.PNG \n extracting: sign_data/train/003/003_10.PNG \n extracting: sign_data/train/003/003_11.PNG \n extracting: sign_data/train/003/003_12.PNG \n extracting: sign_data/train/003/003_13.PNG \n extracting: sign_data/train/003/003_14.PNG \n extracting: sign_data/train/003/003_15.PNG \n extracting: sign_data/train/003/003_16.PNG \n extracting: sign_data/train/003/003_17.PNG \n extracting: sign_data/train/003/003_18.PNG \n extracting: sign_data/train/003/003_19.PNG \n extracting: sign_data/train/003/003_20.PNG \n extracting: sign_data/train/003/003_21.PNG \n extracting: sign_data/train/003/003_22.PNG \n extracting: sign_data/train/003/003_23.PNG \n extracting: sign_data/train/003/003_24.PNG \n creating: sign_data/train/003_forg/\n extracting: sign_data/train/003_forg/0121003_01.png \n extracting: sign_data/train/003_forg/0121003_02.png \n extracting: sign_data/train/003_forg/0121003_03.png \n extracting: sign_data/train/003_forg/0121003_04.png \n extracting: sign_data/train/003_forg/0126003_01.png \n extracting: sign_data/train/003_forg/0126003_02.png \n extracting: sign_data/train/003_forg/0126003_03.png \n extracting: sign_data/train/003_forg/0126003_04.png \n extracting: sign_data/train/003_forg/0206003_01.png \n extracting: sign_data/train/003_forg/0206003_02.png \n extracting: sign_data/train/003_forg/0206003_03.png \n extracting: sign_data/train/003_forg/0206003_04.png \n creating: sign_data/train/004/\n extracting: sign_data/train/004/004_01.PNG \n extracting: sign_data/train/004/004_02.PNG \n extracting: sign_data/train/004/004_03.PNG \n extracting: sign_data/train/004/004_04.PNG \n extracting: sign_data/train/004/004_05.PNG \n extracting: sign_data/train/004/004_06.PNG \n extracting: sign_data/train/004/004_07.PNG \n extracting: sign_data/train/004/004_08.PNG \n extracting: sign_data/train/004/004_09.PNG \n extracting: sign_data/train/004/004_10.PNG \n extracting: sign_data/train/004/004_11.PNG \n extracting: sign_data/train/004/004_12.PNG \n extracting: sign_data/train/004/004_13.PNG \n extracting: sign_data/train/004/004_14.PNG \n extracting: sign_data/train/004/004_15.PNG \n extracting: sign_data/train/004/004_16.PNG \n extracting: sign_data/train/004/004_17.PNG \n extracting: sign_data/train/004/004_18.PNG \n extracting: sign_data/train/004/004_19.PNG \n extracting: sign_data/train/004/004_20.PNG \n extracting: sign_data/train/004/004_21.PNG \n extracting: sign_data/train/004/004_22.PNG \n extracting: sign_data/train/004/004_23.PNG \n extracting: sign_data/train/004/004_24.PNG \n creating: sign_data/train/004_forg/\n extracting: sign_data/train/004_forg/0103004_02.png \n extracting: sign_data/train/004_forg/0103004_03.png \n extracting: sign_data/train/004_forg/0103004_04.png \n extracting: sign_data/train/004_forg/0105004_01.png \n extracting: sign_data/train/004_forg/0105004_02.png \n extracting: sign_data/train/004_forg/0105004_03.png \n extracting: sign_data/train/004_forg/0105004_04.png \n extracting: sign_data/train/004_forg/0124004_01.png \n extracting: sign_data/train/004_forg/0124004_02.png \n extracting: sign_data/train/004_forg/0124004_03.png \n extracting: sign_data/train/004_forg/0124004_04.png \n creating: sign_data/train/006/\n extracting: sign_data/train/006/006_01.PNG \n extracting: sign_data/train/006/006_02.PNG \n extracting: sign_data/train/006/006_03.PNG \n extracting: sign_data/train/006/006_04.PNG \n extracting: sign_data/train/006/006_05.PNG \n extracting: sign_data/train/006/006_06.PNG \n extracting: sign_data/train/006/006_07.PNG \n extracting: sign_data/train/006/006_08.PNG \n extracting: sign_data/train/006/006_09.PNG \n extracting: sign_data/train/006/006_10.PNG \n extracting: sign_data/train/006/006_11.PNG \n extracting: sign_data/train/006/006_12.PNG \n extracting: sign_data/train/006/006_13.PNG \n extracting: sign_data/train/006/006_14.PNG \n extracting: sign_data/train/006/006_15.PNG \n extracting: sign_data/train/006/006_16.PNG \n extracting: sign_data/train/006/006_17.PNG \n extracting: sign_data/train/006/006_18.PNG \n extracting: sign_data/train/006/006_19.PNG \n extracting: sign_data/train/006/006_20.PNG \n extracting: sign_data/train/006/006_21.PNG \n extracting: sign_data/train/006/006_22.PNG \n extracting: sign_data/train/006/006_23.PNG \n extracting: sign_data/train/006/006_24.PNG \n creating: sign_data/train/006_forg/\n extracting: sign_data/train/006_forg/0111006_01.png \n extracting: sign_data/train/006_forg/0111006_02.png \n extracting: sign_data/train/006_forg/0111006_03.png \n extracting: sign_data/train/006_forg/0111006_04.png \n extracting: sign_data/train/006_forg/0202006_01.png \n extracting: sign_data/train/006_forg/0202006_02.png \n extracting: sign_data/train/006_forg/0202006_03.png \n extracting: sign_data/train/006_forg/0202006_04.png \n extracting: sign_data/train/006_forg/0205006_01.png \n extracting: sign_data/train/006_forg/0205006_02.png \n extracting: sign_data/train/006_forg/0205006_03.png \n extracting: sign_data/train/006_forg/0205006_04.png \n creating: sign_data/train/009/\n extracting: sign_data/train/009/009_01.PNG \n extracting: sign_data/train/009/009_02.PNG \n extracting: sign_data/train/009/009_03.PNG \n extracting: sign_data/train/009/009_04.PNG \n extracting: sign_data/train/009/009_05.PNG \n extracting: sign_data/train/009/009_06.PNG \n extracting: sign_data/train/009/009_07.PNG \n extracting: sign_data/train/009/009_08.PNG \n extracting: sign_data/train/009/009_09.PNG \n extracting: sign_data/train/009/009_10.PNG \n extracting: sign_data/train/009/009_11.PNG \n extracting: sign_data/train/009/009_12.PNG \n extracting: sign_data/train/009/009_13.PNG \n extracting: sign_data/train/009/009_14.PNG \n extracting: sign_data/train/009/009_15.PNG \n extracting: sign_data/train/009/009_16.PNG \n extracting: sign_data/train/009/009_17.PNG \n extracting: sign_data/train/009/009_18.PNG \n extracting: sign_data/train/009/009_19.PNG \n extracting: sign_data/train/009/009_20.PNG \n extracting: sign_data/train/009/009_21.PNG \n extracting: sign_data/train/009/009_22.PNG \n extracting: sign_data/train/009/009_23.PNG \n extracting: sign_data/train/009/009_24.PNG \n creating: sign_data/train/009_forg/\n extracting: sign_data/train/009_forg/0117009_01.png \n extracting: sign_data/train/009_forg/0117009_02.png \n extracting: sign_data/train/009_forg/0117009_03.png \n extracting: sign_data/train/009_forg/0117009_04.png \n extracting: sign_data/train/009_forg/0123009_01.png \n extracting: sign_data/train/009_forg/0123009_02.png \n extracting: sign_data/train/009_forg/0123009_03.png \n extracting: sign_data/train/009_forg/0123009_04.png \n extracting: sign_data/train/009_forg/0201009_01.png \n extracting: sign_data/train/009_forg/0201009_02.png \n extracting: sign_data/train/009_forg/0201009_03.png \n extracting: sign_data/train/009_forg/0201009_04.png \n creating: sign_data/train/012/\n extracting: sign_data/train/012/012_01.PNG \n extracting: sign_data/train/012/012_02.PNG \n extracting: sign_data/train/012/012_03.PNG \n extracting: sign_data/train/012/012_04.PNG \n extracting: sign_data/train/012/012_05.PNG \n extracting: sign_data/train/012/012_06.PNG \n extracting: sign_data/train/012/012_07.PNG \n extracting: sign_data/train/012/012_08.PNG \n extracting: sign_data/train/012/012_09.PNG \n extracting: sign_data/train/012/012_10.PNG \n extracting: sign_data/train/012/012_11.PNG \n extracting: sign_data/train/012/012_12.PNG \n extracting: sign_data/train/012/012_13.PNG \n extracting: sign_data/train/012/012_14.PNG \n extracting: sign_data/train/012/012_15.PNG \n extracting: sign_data/train/012/012_16.PNG \n extracting: sign_data/train/012/012_17.PNG \n extracting: sign_data/train/012/012_18.PNG \n extracting: sign_data/train/012/012_19.PNG \n extracting: sign_data/train/012/012_20.PNG \n extracting: sign_data/train/012/012_21.PNG \n extracting: sign_data/train/012/012_22.PNG \n extracting: sign_data/train/012/012_23.PNG \n extracting: sign_data/train/012/012_24.PNG \n creating: sign_data/train/012_forg/\n extracting: sign_data/train/012_forg/0113012_01.png \n extracting: sign_data/train/012_forg/0113012_02.png \n extracting: sign_data/train/012_forg/0113012_03.png \n extracting: sign_data/train/012_forg/0113012_04.png \n extracting: sign_data/train/012_forg/0206012_01.png \n extracting: sign_data/train/012_forg/0206012_02.png \n extracting: sign_data/train/012_forg/0206012_03.png \n extracting: sign_data/train/012_forg/0206012_04.png \n extracting: sign_data/train/012_forg/0210012_01.png \n extracting: sign_data/train/012_forg/0210012_02.png \n extracting: sign_data/train/012_forg/0210012_03.png \n extracting: sign_data/train/012_forg/0210012_04.png \n creating: sign_data/train/013/\n extracting: sign_data/train/013/01_013.png \n extracting: sign_data/train/013/02_013.png \n extracting: sign_data/train/013/03_013.png \n extracting: sign_data/train/013/04_013.png \n extracting: sign_data/train/013/05_013.png \n extracting: sign_data/train/013/06_013.png \n extracting: sign_data/train/013/07_013.png \n extracting: sign_data/train/013/08_013.png \n extracting: sign_data/train/013/09_013.png \n extracting: sign_data/train/013/10_013.png \n extracting: sign_data/train/013/11_013.png \n extracting: sign_data/train/013/12_013.png \n creating: sign_data/train/013_forg/\n extracting: sign_data/train/013_forg/01_0113013.PNG \n extracting: sign_data/train/013_forg/01_0203013.PNG \n extracting: sign_data/train/013_forg/01_0204013.PNG \n extracting: sign_data/train/013_forg/02_0113013.PNG \n extracting: sign_data/train/013_forg/02_0203013.PNG \n extracting: sign_data/train/013_forg/02_0204013.PNG \n extracting: sign_data/train/013_forg/03_0113013.PNG \n extracting: sign_data/train/013_forg/03_0203013.PNG \n extracting: sign_data/train/013_forg/03_0204013.PNG \n extracting: sign_data/train/013_forg/04_0113013.PNG \n extracting: sign_data/train/013_forg/04_0203013.PNG \n extracting: sign_data/train/013_forg/04_0204013.PNG \n creating: sign_data/train/014/\n extracting: sign_data/train/014/014_01.PNG \n extracting: sign_data/train/014/014_02.PNG \n extracting: sign_data/train/014/014_03.PNG \n extracting: sign_data/train/014/014_04.PNG \n extracting: sign_data/train/014/014_05.PNG \n extracting: sign_data/train/014/014_06.PNG \n extracting: sign_data/train/014/014_07.PNG \n extracting: sign_data/train/014/014_08.PNG \n extracting: sign_data/train/014/014_09.PNG \n extracting: sign_data/train/014/014_10.PNG \n extracting: sign_data/train/014/014_11.PNG \n extracting: sign_data/train/014/014_12.PNG \n extracting: sign_data/train/014/014_13.PNG \n extracting: sign_data/train/014/014_14.PNG \n extracting: sign_data/train/014/014_15.PNG \n extracting: sign_data/train/014/014_16.PNG \n extracting: sign_data/train/014/014_17.PNG \n extracting: sign_data/train/014/014_18.PNG \n extracting: sign_data/train/014/014_19.PNG \n extracting: sign_data/train/014/014_20.PNG \n extracting: sign_data/train/014/014_21.PNG \n extracting: sign_data/train/014/014_22.PNG \n extracting: sign_data/train/014/014_23.PNG \n extracting: sign_data/train/014/014_24.PNG \n creating: sign_data/train/014_forg/\n extracting: sign_data/train/014_forg/0102014_01.png \n extracting: sign_data/train/014_forg/0102014_02.png \n extracting: sign_data/train/014_forg/0102014_03.png \n extracting: sign_data/train/014_forg/0102014_04.png \n extracting: sign_data/train/014_forg/0104014_01.png \n extracting: sign_data/train/014_forg/0104014_02.png \n extracting: sign_data/train/014_forg/0104014_03.png \n extracting: sign_data/train/014_forg/0104014_04.png \n extracting: sign_data/train/014_forg/0208014_01.png \n extracting: sign_data/train/014_forg/0208014_02.png \n extracting: sign_data/train/014_forg/0208014_03.png \n extracting: sign_data/train/014_forg/0208014_04.png \n extracting: sign_data/train/014_forg/0214014_01.png \n extracting: sign_data/train/014_forg/0214014_02.png \n extracting: sign_data/train/014_forg/0214014_03.png \n extracting: sign_data/train/014_forg/0214014_04.png \n creating: sign_data/train/015/\n extracting: sign_data/train/015/015_01.PNG \n extracting: sign_data/train/015/015_02.PNG \n extracting: sign_data/train/015/015_03.PNG \n extracting: sign_data/train/015/015_04.PNG \n extracting: sign_data/train/015/015_05.PNG \n extracting: sign_data/train/015/015_06.PNG \n extracting: sign_data/train/015/015_07.PNG \n extracting: sign_data/train/015/015_08.PNG \n extracting: sign_data/train/015/015_09.PNG \n extracting: sign_data/train/015/015_10.PNG \n extracting: sign_data/train/015/015_11.PNG \n extracting: sign_data/train/015/015_12.PNG \n extracting: sign_data/train/015/015_13.PNG \n extracting: sign_data/train/015/015_14.PNG \n extracting: sign_data/train/015/015_15.PNG \n extracting: sign_data/train/015/015_16.PNG \n extracting: sign_data/train/015/015_17.PNG \n extracting: sign_data/train/015/015_18.PNG \n extracting: sign_data/train/015/015_19.PNG \n extracting: sign_data/train/015/015_20.PNG \n extracting: sign_data/train/015/015_21.PNG \n extracting: sign_data/train/015/015_22.PNG \n extracting: sign_data/train/015/015_23.PNG \n extracting: sign_data/train/015/015_24.PNG \n creating: sign_data/train/015_forg/\n extracting: sign_data/train/015_forg/0106015_01.png \n extracting: sign_data/train/015_forg/0106015_02.png \n extracting: sign_data/train/015_forg/0106015_03.png \n extracting: sign_data/train/015_forg/0106015_04.png \n extracting: sign_data/train/015_forg/0210015_01.png \n extracting: sign_data/train/015_forg/0210015_02.png \n extracting: sign_data/train/015_forg/0210015_03.png \n extracting: sign_data/train/015_forg/0210015_04.png \n extracting: sign_data/train/015_forg/0213015_01.png \n extracting: sign_data/train/015_forg/0213015_02.png \n extracting: sign_data/train/015_forg/0213015_03.png \n extracting: sign_data/train/015_forg/0213015_04.png \n creating: sign_data/train/016/\n extracting: sign_data/train/016/016_01.PNG \n extracting: sign_data/train/016/016_02.PNG \n extracting: sign_data/train/016/016_03.PNG \n extracting: sign_data/train/016/016_04.PNG \n extracting: sign_data/train/016/016_05.PNG \n extracting: sign_data/train/016/016_06.PNG \n extracting: sign_data/train/016/016_07.PNG \n extracting: sign_data/train/016/016_08.PNG \n extracting: sign_data/train/016/016_09.PNG \n extracting: sign_data/train/016/016_10.PNG \n extracting: sign_data/train/016/016_11.PNG \n extracting: sign_data/train/016/016_12.PNG \n extracting: sign_data/train/016/016_13.PNG \n extracting: sign_data/train/016/016_14.PNG \n extracting: sign_data/train/016/016_15.PNG \n extracting: sign_data/train/016/016_16.PNG \n extracting: sign_data/train/016/016_17.PNG \n extracting: sign_data/train/016/016_18.PNG \n extracting: sign_data/train/016/016_20.PNG \n extracting: sign_data/train/016/016_21.PNG \n extracting: sign_data/train/016/016_22.PNG \n extracting: sign_data/train/016/016_23.PNG \n extracting: sign_data/train/016/016_24.PNG \n creating: sign_data/train/016_forg/\n extracting: sign_data/train/016_forg/0107016_01.png \n extracting: sign_data/train/016_forg/0107016_02.png \n extracting: sign_data/train/016_forg/0107016_03.png \n extracting: sign_data/train/016_forg/0107016_04.png \n extracting: sign_data/train/016_forg/0110016_01.png \n extracting: sign_data/train/016_forg/0110016_02.png \n extracting: sign_data/train/016_forg/0110016_03.png \n extracting: sign_data/train/016_forg/0110016_04.png \n extracting: sign_data/train/016_forg/0127016_01.png \n extracting: sign_data/train/016_forg/0127016_02.png \n extracting: sign_data/train/016_forg/0127016_03.png \n extracting: sign_data/train/016_forg/0127016_04.png \n extracting: sign_data/train/016_forg/0202016_01.png \n extracting: sign_data/train/016_forg/0202016_02.png \n extracting: sign_data/train/016_forg/0202016_03.png \n extracting: sign_data/train/016_forg/0202016_04.png \n creating: sign_data/train/017/\n extracting: sign_data/train/017/01_017.png \n extracting: sign_data/train/017/02_017.png \n extracting: sign_data/train/017/03_017.png \n extracting: sign_data/train/017/04_017.png \n extracting: sign_data/train/017/05_017.png \n extracting: sign_data/train/017/06_017.png \n extracting: sign_data/train/017/07_017.png \n extracting: sign_data/train/017/08_017.png \n extracting: sign_data/train/017/09_017.png \n extracting: sign_data/train/017/10_017.png \n extracting: sign_data/train/017/11_017.png \n extracting: sign_data/train/017/12_017.png \n creating: sign_data/train/017_forg/\n extracting: sign_data/train/017_forg/01_0107017.PNG \n extracting: sign_data/train/017_forg/01_0124017.PNG \n extracting: sign_data/train/017_forg/01_0211017.PNG \n extracting: sign_data/train/017_forg/02_0107017.PNG \n extracting: sign_data/train/017_forg/02_0124017.PNG \n extracting: sign_data/train/017_forg/02_0211017.PNG \n extracting: sign_data/train/017_forg/03_0107017.PNG \n extracting: sign_data/train/017_forg/03_0124017.PNG \n extracting: sign_data/train/017_forg/03_0211017.PNG \n extracting: sign_data/train/017_forg/04_0107017.PNG \n extracting: sign_data/train/017_forg/04_0124017.PNG \n extracting: sign_data/train/017_forg/04_0211017.PNG \n creating: sign_data/train/018/\n extracting: sign_data/train/018/01_018.png \n extracting: sign_data/train/018/02_018.png \n extracting: sign_data/train/018/03_018.png \n extracting: sign_data/train/018/04_018.png \n extracting: sign_data/train/018/05_018.png \n extracting: sign_data/train/018/06_018.png \n extracting: sign_data/train/018/07_018.png \n extracting: sign_data/train/018/08_018.png \n extracting: sign_data/train/018/09_018.png \n extracting: sign_data/train/018/10_018.png \n extracting: sign_data/train/018/11_018.png \n extracting: sign_data/train/018/12_018.png \n creating: sign_data/train/018_forg/\n extracting: sign_data/train/018_forg/01_0106018.PNG \n extracting: sign_data/train/018_forg/01_0112018.PNG \n extracting: sign_data/train/018_forg/01_0202018.PNG \n extracting: sign_data/train/018_forg/02_0106018.PNG \n extracting: sign_data/train/018_forg/02_0112018.PNG \n extracting: sign_data/train/018_forg/02_0202018.PNG \n extracting: sign_data/train/018_forg/03_0106018.PNG \n extracting: sign_data/train/018_forg/03_0112018.PNG \n extracting: sign_data/train/018_forg/03_0202018.PNG \n extracting: sign_data/train/018_forg/04_0106018.PNG \n extracting: sign_data/train/018_forg/04_0112018.PNG \n extracting: sign_data/train/018_forg/04_0202018.PNG \n creating: sign_data/train/019/\n extracting: sign_data/train/019/01_019.png \n extracting: sign_data/train/019/02_019.png \n extracting: sign_data/train/019/03_019.png \n extracting: sign_data/train/019/04_019.png \n extracting: sign_data/train/019/05_019.png \n extracting: sign_data/train/019/06_019.png \n extracting: sign_data/train/019/07_019.png \n extracting: sign_data/train/019/08_019.png \n extracting: sign_data/train/019/09_019.png \n extracting: sign_data/train/019/10_019.png \n extracting: sign_data/train/019/11_019.png \n extracting: sign_data/train/019/12_019.png \n creating: sign_data/train/019_forg/\n extracting: sign_data/train/019_forg/01_0115019.PNG \n extracting: sign_data/train/019_forg/01_0116019.PNG \n extracting: sign_data/train/019_forg/01_0119019.PNG \n extracting: sign_data/train/019_forg/02_0115019.PNG \n extracting: sign_data/train/019_forg/02_0116019.PNG \n extracting: sign_data/train/019_forg/02_0119019.PNG \n extracting: sign_data/train/019_forg/03_0115019.PNG \n extracting: sign_data/train/019_forg/03_0116019.PNG \n extracting: sign_data/train/019_forg/03_0119019.PNG \n extracting: sign_data/train/019_forg/04_0115019.PNG \n extracting: sign_data/train/019_forg/04_0116019.PNG \n extracting: sign_data/train/019_forg/04_0119019.PNG \n creating: sign_data/train/020/\n extracting: sign_data/train/020/01_020.png \n extracting: sign_data/train/020/02_020.png \n extracting: sign_data/train/020/03_020.png \n extracting: sign_data/train/020/04_020.png \n extracting: sign_data/train/020/05_020.png \n extracting: sign_data/train/020/06_020.png \n extracting: sign_data/train/020/07_020.png \n extracting: sign_data/train/020/08_020.png \n extracting: sign_data/train/020/09_020.png \n extracting: sign_data/train/020/10_020.png \n extracting: sign_data/train/020/11_020.png \n extracting: sign_data/train/020/12_020.png \n creating: sign_data/train/020_forg/\n extracting: sign_data/train/020_forg/01_0105020.PNG \n extracting: sign_data/train/020_forg/01_0117020.PNG \n extracting: sign_data/train/020_forg/01_0127020.PNG \n extracting: sign_data/train/020_forg/01_0213020.PNG \n extracting: sign_data/train/020_forg/02_0101020.PNG \n extracting: sign_data/train/020_forg/02_0105020.PNG \n extracting: sign_data/train/020_forg/02_0117020.PNG \n extracting: sign_data/train/020_forg/02_0127020.PNG \n extracting: sign_data/train/020_forg/02_0213020.PNG \n extracting: sign_data/train/020_forg/03_0101020.PNG \n extracting: sign_data/train/020_forg/03_0105020.PNG \n extracting: sign_data/train/020_forg/03_0117020.PNG \n extracting: sign_data/train/020_forg/03_0127020.PNG \n extracting: sign_data/train/020_forg/03_0213020.PNG \n extracting: sign_data/train/020_forg/04_0101020.PNG \n extracting: sign_data/train/020_forg/04_0105020.PNG \n extracting: sign_data/train/020_forg/04_0117020.PNG \n extracting: sign_data/train/020_forg/04_0127020.PNG \n extracting: sign_data/train/020_forg/04_0213020.PNG \n creating: sign_data/train/021/\n extracting: sign_data/train/021/01_021.png \n extracting: sign_data/train/021/02_021.png \n extracting: sign_data/train/021/03_021.png \n extracting: sign_data/train/021/04_021.png \n extracting: sign_data/train/021/05_021.png \n extracting: sign_data/train/021/06_021.png \n extracting: sign_data/train/021/07_021.png \n extracting: sign_data/train/021/08_021.png \n extracting: sign_data/train/021/09_021.png \n extracting: sign_data/train/021/10_021.png \n extracting: sign_data/train/021/11_021.png \n extracting: sign_data/train/021/12_021.png \n creating: sign_data/train/021_forg/\n extracting: sign_data/train/021_forg/01_0110021.PNG \n extracting: sign_data/train/021_forg/01_0204021.PNG \n extracting: sign_data/train/021_forg/01_0211021.PNG \n extracting: sign_data/train/021_forg/02_0110021.PNG \n extracting: sign_data/train/021_forg/02_0204021.PNG \n extracting: sign_data/train/021_forg/02_0211021.PNG \n extracting: sign_data/train/021_forg/03_0110021.PNG \n extracting: sign_data/train/021_forg/03_0204021.PNG \n extracting: sign_data/train/021_forg/03_0211021.PNG \n extracting: sign_data/train/021_forg/04_0110021.PNG \n extracting: sign_data/train/021_forg/04_0204021.PNG \n extracting: sign_data/train/021_forg/04_0211021.PNG \n creating: sign_data/train/022/\n extracting: sign_data/train/022/01_022.png \n extracting: sign_data/train/022/02_022.png \n extracting: sign_data/train/022/03_022.png \n extracting: sign_data/train/022/04_022.png \n extracting: sign_data/train/022/05_022.png \n extracting: sign_data/train/022/06_022.png \n extracting: sign_data/train/022/07_022.png \n extracting: sign_data/train/022/08_022.png \n extracting: sign_data/train/022/09_022.png \n extracting: sign_data/train/022/10_022.png \n extracting: sign_data/train/022/11_022.png \n extracting: sign_data/train/022/12_022.png \n creating: sign_data/train/022_forg/\n extracting: sign_data/train/022_forg/01_0125022.PNG \n extracting: sign_data/train/022_forg/01_0127022.PNG \n extracting: sign_data/train/022_forg/01_0208022.PNG \n extracting: sign_data/train/022_forg/01_0214022.PNG \n extracting: sign_data/train/022_forg/02_0125022.PNG \n extracting: sign_data/train/022_forg/02_0127022.PNG \n extracting: sign_data/train/022_forg/02_0208022.PNG \n extracting: sign_data/train/022_forg/02_0214022.PNG \n extracting: sign_data/train/022_forg/03_0125022.PNG \n extracting: sign_data/train/022_forg/03_0127022.PNG \n extracting: sign_data/train/022_forg/03_0208022.PNG \n extracting: sign_data/train/022_forg/03_0214022.PNG \n extracting: sign_data/train/022_forg/04_0125022.PNG \n extracting: sign_data/train/022_forg/04_0127022.PNG \n extracting: sign_data/train/022_forg/04_0208022.PNG \n extracting: sign_data/train/022_forg/04_0214022.PNG \n creating: sign_data/train/023/\n extracting: sign_data/train/023/01_023.png \n extracting: sign_data/train/023/02_023.png \n extracting: sign_data/train/023/03_023.png \n extracting: sign_data/train/023/04_023.png \n extracting: sign_data/train/023/05_023.png \n extracting: sign_data/train/023/06_023.png \n extracting: sign_data/train/023/07_023.png \n extracting: sign_data/train/023/08_023.png \n extracting: sign_data/train/023/09_023.png \n extracting: sign_data/train/023/10_023.png \n extracting: sign_data/train/023/11_023.png \n extracting: sign_data/train/023/12_023.png \n creating: sign_data/train/023_forg/\n extracting: sign_data/train/023_forg/01_0126023.PNG \n extracting: sign_data/train/023_forg/01_0203023.PNG \n extracting: sign_data/train/023_forg/02_0126023.PNG \n extracting: sign_data/train/023_forg/02_0203023.PNG \n extracting: sign_data/train/023_forg/03_0126023.PNG \n extracting: sign_data/train/023_forg/03_0203023.PNG \n extracting: sign_data/train/023_forg/04_0126023.PNG \n extracting: sign_data/train/023_forg/04_0203023.PNG \n creating: sign_data/train/024/\n extracting: sign_data/train/024/01_024.png \n extracting: sign_data/train/024/02_024.png \n extracting: sign_data/train/024/03_024.png \n extracting: sign_data/train/024/04_024.png \n extracting: sign_data/train/024/05_024.png \n extracting: sign_data/train/024/06_024.png \n extracting: sign_data/train/024/07_024.png \n extracting: sign_data/train/024/08_024.png \n extracting: sign_data/train/024/09_024.png \n extracting: sign_data/train/024/10_024.png \n extracting: sign_data/train/024/11_024.png \n extracting: sign_data/train/024/12_024.png \n creating: sign_data/train/024_forg/\n extracting: sign_data/train/024_forg/01_0102024.PNG \n extracting: sign_data/train/024_forg/01_0119024.PNG \n extracting: sign_data/train/024_forg/01_0120024.PNG \n extracting: sign_data/train/024_forg/02_0102024.PNG \n extracting: sign_data/train/024_forg/02_0119024.PNG \n extracting: sign_data/train/024_forg/02_0120024.PNG \n extracting: sign_data/train/024_forg/03_0102024.PNG \n extracting: sign_data/train/024_forg/03_0119024.PNG \n extracting: sign_data/train/024_forg/03_0120024.PNG \n extracting: sign_data/train/024_forg/04_0102024.PNG \n extracting: sign_data/train/024_forg/04_0119024.PNG \n extracting: sign_data/train/024_forg/04_0120024.PNG \n creating: sign_data/train/025/\n extracting: sign_data/train/025/01_025.png \n extracting: sign_data/train/025/02_025.png \n extracting: sign_data/train/025/03_025.png \n extracting: sign_data/train/025/04_025.png \n extracting: sign_data/train/025/05_025.png \n extracting: sign_data/train/025/06_025.png \n extracting: sign_data/train/025/07_025.png \n extracting: sign_data/train/025/08_025.png \n extracting: sign_data/train/025/09_025.png \n extracting: sign_data/train/025/10_025.png \n extracting: sign_data/train/025/11_025.png \n extracting: sign_data/train/025/12_025.png \n creating: sign_data/train/025_forg/\n extracting: sign_data/train/025_forg/01_0116025.PNG \n extracting: sign_data/train/025_forg/01_0121025.PNG \n extracting: sign_data/train/025_forg/02_0116025.PNG \n extracting: sign_data/train/025_forg/02_0121025.PNG \n extracting: sign_data/train/025_forg/03_0116025.PNG \n extracting: sign_data/train/025_forg/03_0121025.PNG \n extracting: sign_data/train/025_forg/04_0116025.PNG \n extracting: sign_data/train/025_forg/04_0121025.PNG \n creating: sign_data/train/026/\n extracting: sign_data/train/026/01_026.png \n extracting: sign_data/train/026/02_026.png \n extracting: sign_data/train/026/03_026.png \n extracting: sign_data/train/026/04_026.png \n extracting: sign_data/train/026/05_026.png \n extracting: sign_data/train/026/06_026.png \n extracting: sign_data/train/026/07_026.png \n extracting: sign_data/train/026/08_026.png \n extracting: sign_data/train/026/09_026.png \n extracting: sign_data/train/026/10_026.png \n extracting: sign_data/train/026/11_026.png \n extracting: sign_data/train/026/12_026.png \n creating: sign_data/train/026_forg/\n extracting: sign_data/train/026_forg/01_0119026.PNG \n extracting: sign_data/train/026_forg/01_0123026.PNG \n extracting: sign_data/train/026_forg/01_0125026.PNG \n extracting: sign_data/train/026_forg/02_0119026.PNG \n extracting: sign_data/train/026_forg/02_0123026.PNG \n extracting: sign_data/train/026_forg/02_0125026.PNG \n extracting: sign_data/train/026_forg/03_0119026.PNG \n extracting: sign_data/train/026_forg/03_0123026.PNG \n extracting: sign_data/train/026_forg/03_0125026.PNG \n extracting: sign_data/train/026_forg/04_0119026.PNG \n extracting: sign_data/train/026_forg/04_0123026.PNG \n extracting: sign_data/train/026_forg/04_0125026.PNG \n creating: sign_data/train/027/\n extracting: sign_data/train/027/01_027.png \n extracting: sign_data/train/027/02_027.png \n extracting: sign_data/train/027/03_027.png \n extracting: sign_data/train/027/04_027.png \n extracting: sign_data/train/027/05_027.png \n extracting: sign_data/train/027/06_027.png \n extracting: sign_data/train/027/07_027.png \n extracting: sign_data/train/027/08_027.png \n extracting: sign_data/train/027/09_027.png \n extracting: sign_data/train/027/10_027.png \n extracting: sign_data/train/027/11_027.png \n extracting: sign_data/train/027/12_027.png \n creating: sign_data/train/027_forg/\n extracting: sign_data/train/027_forg/01_0101027.PNG \n extracting: sign_data/train/027_forg/01_0212027.PNG \n extracting: sign_data/train/027_forg/02_0101027.PNG \n extracting: sign_data/train/027_forg/02_0212027.PNG \n extracting: sign_data/train/027_forg/03_0101027.PNG \n extracting: sign_data/train/027_forg/03_0212027.PNG \n extracting: sign_data/train/027_forg/04_0101027.PNG \n extracting: sign_data/train/027_forg/04_0212027.PNG \n creating: sign_data/train/028/\n extracting: sign_data/train/028/01_028.png \n extracting: sign_data/train/028/02_028.png \n extracting: sign_data/train/028/03_028.png \n extracting: sign_data/train/028/04_028.png \n extracting: sign_data/train/028/05_028.png \n extracting: sign_data/train/028/06_028.png \n extracting: sign_data/train/028/07_028.png \n extracting: sign_data/train/028/08_028.png \n extracting: sign_data/train/028/09_028.png \n extracting: sign_data/train/028/10_028.png \n extracting: sign_data/train/028/11_028.png \n extracting: sign_data/train/028/12_028.png \n creating: sign_data/train/028_forg/\n extracting: sign_data/train/028_forg/01_0126028.PNG \n extracting: sign_data/train/028_forg/01_0205028.PNG \n extracting: sign_data/train/028_forg/01_0212028.PNG \n extracting: sign_data/train/028_forg/02_0126028.PNG \n extracting: sign_data/train/028_forg/02_0205028.PNG \n extracting: sign_data/train/028_forg/02_0212028.PNG \n extracting: sign_data/train/028_forg/03_0126028.PNG \n extracting: sign_data/train/028_forg/03_0205028.PNG \n extracting: sign_data/train/028_forg/03_0212028.PNG \n extracting: sign_data/train/028_forg/04_0126028.PNG \n extracting: sign_data/train/028_forg/04_0205028.PNG \n extracting: sign_data/train/028_forg/04_0212028.PNG \n creating: sign_data/train/029/\n extracting: sign_data/train/029/01_029.png \n extracting: sign_data/train/029/02_029.png \n extracting: sign_data/train/029/03_029.png \n extracting: sign_data/train/029/04_029.png \n extracting: sign_data/train/029/05_029.png \n extracting: sign_data/train/029/06_029.png \n extracting: sign_data/train/029/07_029.png \n extracting: sign_data/train/029/08_029.png \n extracting: sign_data/train/029/09_029.png \n extracting: sign_data/train/029/10_029.png \n extracting: sign_data/train/029/11_029.png \n extracting: sign_data/train/029/12_029.png \n creating: sign_data/train/029_forg/\n extracting: sign_data/train/029_forg/01_0104029.PNG \n extracting: sign_data/train/029_forg/01_0115029.PNG \n extracting: sign_data/train/029_forg/01_0203029.PNG \n extracting: sign_data/train/029_forg/02_0104029.PNG \n extracting: sign_data/train/029_forg/02_0115029.PNG \n extracting: sign_data/train/029_forg/02_0203029.PNG \n extracting: sign_data/train/029_forg/03_0104029.PNG \n extracting: sign_data/train/029_forg/03_0115029.PNG \n extracting: sign_data/train/029_forg/03_0203029.PNG \n extracting: sign_data/train/029_forg/04_0104029.PNG \n extracting: sign_data/train/029_forg/04_0115029.PNG \n extracting: sign_data/train/029_forg/04_0203029.PNG \n creating: sign_data/train/030/\n extracting: sign_data/train/030/01_030.png \n extracting: sign_data/train/030/02_030.png \n extracting: sign_data/train/030/03_030.png \n extracting: sign_data/train/030/04_030.png \n extracting: sign_data/train/030/05_030.png \n extracting: sign_data/train/030/06_030.png \n extracting: sign_data/train/030/07_030.png \n extracting: sign_data/train/030/08_030.png \n extracting: sign_data/train/030/09_030.png \n extracting: sign_data/train/030/10_030.png \n extracting: sign_data/train/030/11_030.png \n extracting: sign_data/train/030/12_030.png \n creating: sign_data/train/030_forg/\n extracting: sign_data/train/030_forg/01_0109030.PNG \n extracting: sign_data/train/030_forg/01_0114030.PNG \n extracting: sign_data/train/030_forg/01_0213030.PNG \n extracting: sign_data/train/030_forg/02_0109030.PNG \n extracting: sign_data/train/030_forg/02_0114030.PNG \n extracting: sign_data/train/030_forg/02_0213030.PNG \n extracting: sign_data/train/030_forg/03_0109030.PNG \n extracting: sign_data/train/030_forg/03_0114030.PNG \n extracting: sign_data/train/030_forg/03_0213030.PNG \n extracting: sign_data/train/030_forg/04_0109030.PNG \n extracting: sign_data/train/030_forg/04_0114030.PNG \n extracting: sign_data/train/030_forg/04_0213030.PNG \n creating: sign_data/train/031/\n extracting: sign_data/train/031/01_031.png \n extracting: sign_data/train/031/02_031.png \n extracting: sign_data/train/031/03_031.png \n extracting: sign_data/train/031/04_031.png \n extracting: sign_data/train/031/05_031.png \n extracting: sign_data/train/031/06_031.png \n extracting: sign_data/train/031/07_031.png \n extracting: sign_data/train/031/08_031.png \n extracting: sign_data/train/031/09_031.png \n extracting: sign_data/train/031/10_031.png \n extracting: sign_data/train/031/11_031.png \n extracting: sign_data/train/031/12_031.png \n creating: sign_data/train/031_forg/\n extracting: sign_data/train/031_forg/01_0103031.PNG \n extracting: sign_data/train/031_forg/01_0121031.PNG \n extracting: sign_data/train/031_forg/02_0103031.PNG \n extracting: sign_data/train/031_forg/02_0121031.PNG \n extracting: sign_data/train/031_forg/03_0103031.PNG \n extracting: sign_data/train/031_forg/03_0121031.PNG \n extracting: sign_data/train/031_forg/04_0103031.PNG \n extracting: sign_data/train/031_forg/04_0121031.PNG \n creating: sign_data/train/032/\n extracting: sign_data/train/032/01_032.png \n extracting: sign_data/train/032/02_032.png \n extracting: sign_data/train/032/03_032.png \n extracting: sign_data/train/032/04_032.png \n extracting: sign_data/train/032/05_032.png \n extracting: sign_data/train/032/06_032.png \n extracting: sign_data/train/032/07_032.png \n extracting: sign_data/train/032/08_032.png \n extracting: sign_data/train/032/09_032.png \n extracting: sign_data/train/032/10_032.png \n extracting: sign_data/train/032/11_032.png \n extracting: sign_data/train/032/12_032.png \n creating: sign_data/train/032_forg/\n extracting: sign_data/train/032_forg/01_0112032.PNG \n extracting: sign_data/train/032_forg/01_0117032.PNG \n extracting: sign_data/train/032_forg/01_0120032.PNG \n extracting: sign_data/train/032_forg/02_0112032.PNG \n extracting: sign_data/train/032_forg/02_0117032.PNG \n extracting: sign_data/train/032_forg/02_0120032.PNG \n extracting: sign_data/train/032_forg/03_0112032.PNG \n extracting: sign_data/train/032_forg/03_0117032.PNG \n extracting: sign_data/train/032_forg/03_0120032.PNG \n extracting: sign_data/train/032_forg/04_0112032.PNG \n extracting: sign_data/train/032_forg/04_0117032.PNG \n extracting: sign_data/train/032_forg/04_0120032.PNG \n creating: sign_data/train/033/\n extracting: sign_data/train/033/01_033.png \n extracting: sign_data/train/033/02_033.png \n extracting: sign_data/train/033/03_033.png \n extracting: sign_data/train/033/04_033.png \n extracting: sign_data/train/033/05_033.png \n extracting: sign_data/train/033/06_033.png \n extracting: sign_data/train/033/07_033.png \n extracting: sign_data/train/033/08_033.png \n extracting: sign_data/train/033/09_033.png \n extracting: sign_data/train/033/10_033.png \n extracting: sign_data/train/033/11_033.png \n extracting: sign_data/train/033/12_033.png \n creating: sign_data/train/033_forg/\n extracting: sign_data/train/033_forg/01_0112033.PNG \n extracting: sign_data/train/033_forg/01_0203033.PNG \n extracting: sign_data/train/033_forg/01_0205033.PNG \n extracting: sign_data/train/033_forg/01_0213033.PNG \n extracting: sign_data/train/033_forg/02_0112033.PNG \n extracting: sign_data/train/033_forg/02_0203033.PNG \n extracting: sign_data/train/033_forg/02_0205033.PNG \n extracting: sign_data/train/033_forg/02_0213033.PNG \n extracting: sign_data/train/033_forg/03_0112033.PNG \n extracting: sign_data/train/033_forg/03_0203033.PNG \n extracting: sign_data/train/033_forg/03_0205033.PNG \n extracting: sign_data/train/033_forg/03_0213033.PNG \n extracting: sign_data/train/033_forg/04_0112033.PNG \n extracting: sign_data/train/033_forg/04_0203033.PNG \n extracting: sign_data/train/033_forg/04_0205033.PNG \n extracting: sign_data/train/033_forg/04_0213033.PNG \n creating: sign_data/train/034/\n extracting: sign_data/train/034/01_034.png \n extracting: sign_data/train/034/02_034.png \n extracting: sign_data/train/034/03_034.png \n extracting: sign_data/train/034/04_034.png \n extracting: sign_data/train/034/05_034.png \n extracting: sign_data/train/034/06_034.png \n extracting: sign_data/train/034/07_034.png \n extracting: sign_data/train/034/08_034.png \n extracting: sign_data/train/034/09_034.png \n extracting: sign_data/train/034/10_034.png \n extracting: sign_data/train/034/11_034.png \n extracting: sign_data/train/034/12_034.png \n creating: sign_data/train/034_forg/\n extracting: sign_data/train/034_forg/01_0103034.PNG \n extracting: sign_data/train/034_forg/01_0110034.PNG \n extracting: sign_data/train/034_forg/01_0120034.PNG \n extracting: sign_data/train/034_forg/02_0103034.PNG \n extracting: sign_data/train/034_forg/02_0110034.PNG \n extracting: sign_data/train/034_forg/02_0120034.PNG \n extracting: sign_data/train/034_forg/03_0103034.PNG \n extracting: sign_data/train/034_forg/03_0110034.PNG \n extracting: sign_data/train/034_forg/03_0120034.PNG \n extracting: sign_data/train/034_forg/04_0103034.PNG \n extracting: sign_data/train/034_forg/04_0110034.PNG \n extracting: sign_data/train/034_forg/04_0120034.PNG \n creating: sign_data/train/035/\n extracting: sign_data/train/035/01_035.png \n extracting: sign_data/train/035/02_035.png \n extracting: sign_data/train/035/03_035.png \n extracting: sign_data/train/035/04_035.png \n extracting: sign_data/train/035/05_035.png \n extracting: sign_data/train/035/06_035.png \n extracting: sign_data/train/035/07_035.png \n extracting: sign_data/train/035/08_035.png \n extracting: sign_data/train/035/09_035.png \n extracting: sign_data/train/035/10_035.png \n extracting: sign_data/train/035/11_035.png \n extracting: sign_data/train/035/12_035.png \n creating: sign_data/train/035_forg/\n extracting: sign_data/train/035_forg/01_0103035.PNG \n extracting: sign_data/train/035_forg/01_0115035.PNG \n extracting: sign_data/train/035_forg/01_0201035.PNG \n extracting: sign_data/train/035_forg/02_0103035.PNG \n extracting: sign_data/train/035_forg/02_0115035.PNG \n extracting: sign_data/train/035_forg/02_0201035.PNG \n extracting: sign_data/train/035_forg/03_0103035.PNG \n extracting: sign_data/train/035_forg/03_0115035.PNG \n extracting: sign_data/train/035_forg/03_0201035.PNG \n extracting: sign_data/train/035_forg/04_0103035.PNG \n extracting: sign_data/train/035_forg/04_0115035.PNG \n extracting: sign_data/train/035_forg/04_0201035.PNG \n creating: sign_data/train/036/\n extracting: sign_data/train/036/01_036.png \n extracting: sign_data/train/036/02_036.png \n extracting: sign_data/train/036/03_036.png \n extracting: sign_data/train/036/04_036.png \n extracting: sign_data/train/036/05_036.png \n extracting: sign_data/train/036/06_036.png \n extracting: sign_data/train/036/07_036.png \n extracting: sign_data/train/036/08_036.png \n extracting: sign_data/train/036/09_036.png \n extracting: sign_data/train/036/10_036.png \n extracting: sign_data/train/036/11_036.png \n extracting: sign_data/train/036/12_036.png \n creating: sign_data/train/036_forg/\n extracting: sign_data/train/036_forg/01_0109036.PNG \n extracting: sign_data/train/036_forg/01_0118036.PNG \n extracting: sign_data/train/036_forg/01_0123036.PNG \n extracting: sign_data/train/036_forg/02_0109036.PNG \n extracting: sign_data/train/036_forg/02_0118036.PNG \n extracting: sign_data/train/036_forg/02_0123036.PNG \n extracting: sign_data/train/036_forg/03_0109036.PNG \n extracting: sign_data/train/036_forg/03_0118036.PNG \n extracting: sign_data/train/036_forg/03_0123036.PNG \n extracting: sign_data/train/036_forg/04_0109036.PNG \n extracting: sign_data/train/036_forg/04_0118036.PNG \n extracting: sign_data/train/036_forg/04_0123036.PNG \n creating: sign_data/train/037/\n extracting: sign_data/train/037/01_037.png \n extracting: sign_data/train/037/02_037.png \n extracting: sign_data/train/037/03_037.png \n extracting: sign_data/train/037/04_037.png \n extracting: sign_data/train/037/05_037.png \n extracting: sign_data/train/037/06_037.png \n extracting: sign_data/train/037/07_037.png \n extracting: sign_data/train/037/08_037.png \n extracting: sign_data/train/037/09_037.png \n extracting: sign_data/train/037/10_037.png \n extracting: sign_data/train/037/11_037.png \n extracting: sign_data/train/037/12_037.png \n creating: sign_data/train/037_forg/\n extracting: sign_data/train/037_forg/01_0114037.PNG \n extracting: sign_data/train/037_forg/01_0123037.PNG \n extracting: sign_data/train/037_forg/01_0208037.PNG \n extracting: sign_data/train/037_forg/01_0214037.PNG \n extracting: sign_data/train/037_forg/02_0114037.PNG \n extracting: sign_data/train/037_forg/02_0123037.PNG \n extracting: sign_data/train/037_forg/02_0208037.PNG \n extracting: sign_data/train/037_forg/02_0214037.PNG \n extracting: sign_data/train/037_forg/03_0114037.PNG \n extracting: sign_data/train/037_forg/03_0123037.PNG \n extracting: sign_data/train/037_forg/03_0208037.PNG \n extracting: sign_data/train/037_forg/03_0214037.PNG \n extracting: sign_data/train/037_forg/04_0114037.PNG \n extracting: sign_data/train/037_forg/04_0123037.PNG \n extracting: sign_data/train/037_forg/04_0208037.PNG \n extracting: sign_data/train/037_forg/04_0214037.PNG \n creating: sign_data/train/038/\n extracting: sign_data/train/038/01_038.png \n extracting: sign_data/train/038/02_038.png \n extracting: sign_data/train/038/03_038.png \n extracting: sign_data/train/038/04_038.png \n extracting: sign_data/train/038/05_038.png \n extracting: sign_data/train/038/06_038.png \n extracting: sign_data/train/038/07_038.png \n extracting: sign_data/train/038/08_038.png \n extracting: sign_data/train/038/09_038.png \n extracting: sign_data/train/038/10_038.png \n extracting: sign_data/train/038/11_038.png \n extracting: sign_data/train/038/12_038.png \n creating: sign_data/train/038_forg/\n extracting: sign_data/train/038_forg/01_0101038.PNG \n extracting: sign_data/train/038_forg/01_0124038.PNG \n extracting: sign_data/train/038_forg/01_0213038.PNG \n extracting: sign_data/train/038_forg/02_0101038.PNG \n extracting: sign_data/train/038_forg/02_0124038.PNG \n extracting: sign_data/train/038_forg/02_0213038.PNG \n extracting: sign_data/train/038_forg/03_0101038.PNG \n extracting: sign_data/train/038_forg/03_0124038.PNG \n extracting: sign_data/train/038_forg/03_0213038.PNG \n extracting: sign_data/train/038_forg/04_0101038.PNG \n extracting: sign_data/train/038_forg/04_0124038.PNG \n extracting: sign_data/train/038_forg/04_0213038.PNG \n creating: sign_data/train/039/\n extracting: sign_data/train/039/01_039.png \n extracting: sign_data/train/039/02_039.png \n extracting: sign_data/train/039/03_039.png \n extracting: sign_data/train/039/04_039.png \n extracting: sign_data/train/039/05_039.png \n extracting: sign_data/train/039/06_039.png \n extracting: sign_data/train/039/07_039.png \n extracting: sign_data/train/039/08_039.png \n extracting: sign_data/train/039/09_039.png \n extracting: sign_data/train/039/10_039.png \n extracting: sign_data/train/039/11_039.png \n extracting: sign_data/train/039/12_039.png \n creating: sign_data/train/039_forg/\n extracting: sign_data/train/039_forg/01_0102039.PNG \n extracting: sign_data/train/039_forg/01_0108039.PNG \n extracting: sign_data/train/039_forg/01_0113039.PNG \n extracting: sign_data/train/039_forg/02_0102039.PNG \n extracting: sign_data/train/039_forg/02_0108039.PNG \n extracting: sign_data/train/039_forg/02_0113039.PNG \n extracting: sign_data/train/039_forg/03_0102039.PNG \n extracting: sign_data/train/039_forg/03_0108039.PNG \n extracting: sign_data/train/039_forg/03_0113039.PNG \n extracting: sign_data/train/039_forg/04_0102039.PNG \n extracting: sign_data/train/039_forg/04_0108039.PNG \n extracting: sign_data/train/039_forg/04_0113039.PNG \n creating: sign_data/train/040/\n extracting: sign_data/train/040/01_040.png \n extracting: sign_data/train/040/02_040.png \n extracting: sign_data/train/040/03_040.png \n extracting: sign_data/train/040/04_040.png \n extracting: sign_data/train/040/05_040.png \n extracting: sign_data/train/040/06_040.png \n extracting: sign_data/train/040/07_040.png \n extracting: sign_data/train/040/08_040.png \n extracting: sign_data/train/040/09_040.png \n extracting: sign_data/train/040/10_040.png \n extracting: sign_data/train/040/11_040.png \n extracting: sign_data/train/040/12_040.png \n creating: sign_data/train/040_forg/\n extracting: sign_data/train/040_forg/01_0114040.PNG \n extracting: sign_data/train/040_forg/01_0121040.PNG \n extracting: sign_data/train/040_forg/02_0114040.PNG \n extracting: sign_data/train/040_forg/02_0121040.PNG \n extracting: sign_data/train/040_forg/03_0114040.PNG \n extracting: sign_data/train/040_forg/03_0121040.PNG \n extracting: sign_data/train/040_forg/04_0114040.PNG \n extracting: sign_data/train/040_forg/04_0121040.PNG \n creating: sign_data/train/041/\n extracting: sign_data/train/041/01_041.png \n extracting: sign_data/train/041/02_041.png \n extracting: sign_data/train/041/03_041.png \n extracting: sign_data/train/041/04_041.png \n extracting: sign_data/train/041/05_041.png \n extracting: sign_data/train/041/06_041.png \n extracting: sign_data/train/041/07_041.png \n extracting: sign_data/train/041/08_041.png \n extracting: sign_data/train/041/09_041.png \n extracting: sign_data/train/041/10_041.png \n extracting: sign_data/train/041/11_041.png \n extracting: sign_data/train/041/12_041.png \n creating: sign_data/train/041_forg/\n extracting: sign_data/train/041_forg/01_0105041.PNG \n extracting: sign_data/train/041_forg/01_0116041.PNG \n extracting: sign_data/train/041_forg/01_0117041.PNG \n extracting: sign_data/train/041_forg/02_0105041.PNG \n extracting: sign_data/train/041_forg/02_0116041.PNG \n extracting: sign_data/train/041_forg/02_0117041.PNG \n extracting: sign_data/train/041_forg/03_0105041.PNG \n extracting: sign_data/train/041_forg/03_0116041.PNG \n extracting: sign_data/train/041_forg/03_0117041.PNG \n extracting: sign_data/train/041_forg/04_0105041.PNG \n extracting: sign_data/train/041_forg/04_0116041.PNG \n extracting: sign_data/train/041_forg/04_0117041.PNG \n creating: sign_data/train/042/\n extracting: sign_data/train/042/01_042.png \n extracting: sign_data/train/042/02_042.png \n extracting: sign_data/train/042/03_042.png \n extracting: sign_data/train/042/04_042.png \n extracting: sign_data/train/042/05_042.png \n extracting: sign_data/train/042/06_042.png \n extracting: sign_data/train/042/07_042.png \n extracting: sign_data/train/042/08_042.png \n extracting: sign_data/train/042/09_042.png \n extracting: sign_data/train/042/10_042.png \n extracting: sign_data/train/042/11_042.png \n extracting: sign_data/train/042/12_042.png \n creating: sign_data/train/042_forg/\n extracting: sign_data/train/042_forg/01_0107042.PNG \n extracting: sign_data/train/042_forg/01_0118042.PNG \n extracting: sign_data/train/042_forg/01_0204042.PNG \n extracting: sign_data/train/042_forg/02_0107042.PNG \n extracting: sign_data/train/042_forg/02_0118042.PNG \n extracting: sign_data/train/042_forg/02_0204042.PNG \n extracting: sign_data/train/042_forg/03_0107042.PNG \n extracting: sign_data/train/042_forg/03_0118042.PNG \n extracting: sign_data/train/042_forg/03_0204042.PNG \n extracting: sign_data/train/042_forg/04_0107042.PNG \n extracting: sign_data/train/042_forg/04_0118042.PNG \n extracting: sign_data/train/042_forg/04_0204042.PNG \n creating: sign_data/train/043/\n extracting: sign_data/train/043/01_043.png \n extracting: sign_data/train/043/02_043.png \n extracting: sign_data/train/043/03_043.png \n extracting: sign_data/train/043/04_043.png \n extracting: sign_data/train/043/05_043.png \n extracting: sign_data/train/043/06_043.png \n extracting: sign_data/train/043/07_043.png \n extracting: sign_data/train/043/08_043.png \n extracting: sign_data/train/043/09_043.png \n extracting: sign_data/train/043/10_043.png \n extracting: sign_data/train/043/11_043.png \n extracting: sign_data/train/043/12_043.png \n creating: sign_data/train/043_forg/\n extracting: sign_data/train/043_forg/01_0111043.PNG \n extracting: sign_data/train/043_forg/01_0201043.PNG \n extracting: sign_data/train/043_forg/01_0211043.PNG \n extracting: sign_data/train/043_forg/02_0111043.PNG \n extracting: sign_data/train/043_forg/02_0201043.PNG \n extracting: sign_data/train/043_forg/02_0211043.PNG \n extracting: sign_data/train/043_forg/03_0111043.PNG \n extracting: sign_data/train/043_forg/03_0201043.PNG \n extracting: sign_data/train/043_forg/03_0211043.PNG \n extracting: sign_data/train/043_forg/04_0111043.PNG \n extracting: sign_data/train/043_forg/04_0201043.PNG \n extracting: sign_data/train/043_forg/04_0211043.PNG \n creating: sign_data/train/044/\n extracting: sign_data/train/044/01_044.png \n extracting: sign_data/train/044/02_044.png \n extracting: sign_data/train/044/03_044.png \n extracting: sign_data/train/044/04_044.png \n extracting: sign_data/train/044/05_044.png \n extracting: sign_data/train/044/06_044.png \n extracting: sign_data/train/044/07_044.png \n extracting: sign_data/train/044/08_044.png \n extracting: sign_data/train/044/09_044.png \n extracting: sign_data/train/044/10_044.png \n extracting: sign_data/train/044/11_044.png \n extracting: sign_data/train/044/12_044.png \n creating: sign_data/train/044_forg/\n extracting: sign_data/train/044_forg/01_0103044.PNG \n extracting: sign_data/train/044_forg/01_0112044.PNG \n extracting: sign_data/train/044_forg/01_0211044.PNG \n extracting: sign_data/train/044_forg/02_0103044.PNG \n extracting: sign_data/train/044_forg/02_0112044.PNG \n extracting: sign_data/train/044_forg/02_0211044.PNG \n extracting: sign_data/train/044_forg/03_0103044.PNG \n extracting: sign_data/train/044_forg/03_0112044.PNG \n extracting: sign_data/train/044_forg/03_0211044.PNG \n extracting: sign_data/train/044_forg/04_0103044.PNG \n extracting: sign_data/train/044_forg/04_0112044.PNG \n extracting: sign_data/train/044_forg/04_0211044.PNG \n creating: sign_data/train/045/\n extracting: sign_data/train/045/01_045.png \n extracting: sign_data/train/045/02_045.png \n extracting: sign_data/train/045/03_045.png \n extracting: sign_data/train/045/04_045.png \n extracting: sign_data/train/045/05_045.png \n extracting: sign_data/train/045/06_045.png \n extracting: sign_data/train/045/07_045.png \n extracting: sign_data/train/045/08_045.png \n extracting: sign_data/train/045/09_045.png \n extracting: sign_data/train/045/10_045.png \n extracting: sign_data/train/045/11_045.png \n extracting: sign_data/train/045/12_045.png \n creating: sign_data/train/045_forg/\n extracting: sign_data/train/045_forg/01_0111045.PNG \n extracting: sign_data/train/045_forg/01_0116045.PNG \n extracting: sign_data/train/045_forg/01_0205045.PNG \n extracting: sign_data/train/045_forg/02_0111045.PNG \n extracting: sign_data/train/045_forg/02_0116045.PNG \n extracting: sign_data/train/045_forg/02_0205045.PNG \n extracting: sign_data/train/045_forg/03_0111045.PNG \n extracting: sign_data/train/045_forg/03_0116045.PNG \n extracting: sign_data/train/045_forg/03_0205045.PNG \n extracting: sign_data/train/045_forg/04_0111045.PNG \n extracting: sign_data/train/045_forg/04_0116045.PNG \n extracting: sign_data/train/045_forg/04_0205045.PNG \n creating: sign_data/train/046/\n extracting: sign_data/train/046/01_046.png \n extracting: sign_data/train/046/02_046.png \n extracting: sign_data/train/046/03_046.png \n extracting: sign_data/train/046/04_046.png \n extracting: sign_data/train/046/05_046.png \n extracting: sign_data/train/046/06_046.png \n extracting: sign_data/train/046/07_046.png \n extracting: sign_data/train/046/08_046.png \n extracting: sign_data/train/046/09_046.png \n extracting: sign_data/train/046/10_046.png \n extracting: sign_data/train/046/11_046.png \n extracting: sign_data/train/046/12_046.png \n creating: sign_data/train/046_forg/\n extracting: sign_data/train/046_forg/01_0107046.PNG \n extracting: sign_data/train/046_forg/01_0108046.PNG \n extracting: sign_data/train/046_forg/01_0123046.PNG \n extracting: sign_data/train/046_forg/02_0107046.PNG \n extracting: sign_data/train/046_forg/02_0108046.PNG \n extracting: sign_data/train/046_forg/02_0123046.PNG \n extracting: sign_data/train/046_forg/03_0107046.PNG \n extracting: sign_data/train/046_forg/03_0108046.PNG \n extracting: sign_data/train/046_forg/03_0123046.PNG \n extracting: sign_data/train/046_forg/04_0107046.PNG \n extracting: sign_data/train/046_forg/04_0108046.PNG \n extracting: sign_data/train/046_forg/04_0123046.PNG \n creating: sign_data/train/047/\n extracting: sign_data/train/047/01_047.png \n extracting: sign_data/train/047/02_047.png \n extracting: sign_data/train/047/03_047.png \n extracting: sign_data/train/047/04_047.png \n extracting: sign_data/train/047/05_047.png \n inflating: sign_data/train/047/06_047.png \n extracting: sign_data/train/047/07_047.png \n extracting: sign_data/train/047/08_047.png \n extracting: sign_data/train/047/09_047.png \n extracting: sign_data/train/047/10_047.png \n extracting: sign_data/train/047/11_047.png \n extracting: sign_data/train/047/12_047.png \n creating: sign_data/train/047_forg/\n extracting: sign_data/train/047_forg/01_0113047.PNG \n extracting: sign_data/train/047_forg/01_0114047.PNG \n extracting: sign_data/train/047_forg/01_0212047.PNG \n extracting: sign_data/train/047_forg/02_0113047.PNG \n extracting: sign_data/train/047_forg/02_0114047.PNG \n extracting: sign_data/train/047_forg/02_0212047.PNG \n extracting: sign_data/train/047_forg/03_0113047.PNG \n extracting: sign_data/train/047_forg/03_0114047.PNG \n extracting: sign_data/train/047_forg/03_0212047.PNG \n extracting: sign_data/train/047_forg/04_0113047.PNG \n extracting: sign_data/train/047_forg/04_0114047.PNG \n extracting: sign_data/train/047_forg/04_0212047.PNG \n creating: sign_data/train/048/\n extracting: sign_data/train/048/01_048.png \n extracting: sign_data/train/048/02_048.png \n extracting: sign_data/train/048/03_048.png \n extracting: sign_data/train/048/04_048.png \n extracting: sign_data/train/048/05_048.png \n extracting: sign_data/train/048/06_048.png \n extracting: sign_data/train/048/07_048.png \n extracting: sign_data/train/048/08_048.png \n extracting: sign_data/train/048/09_048.png \n extracting: sign_data/train/048/10_048.png \n extracting: sign_data/train/048/11_048.png \n extracting: sign_data/train/048/12_048.png \n creating: sign_data/train/048_forg/\n extracting: sign_data/train/048_forg/01_0106048.PNG \n extracting: sign_data/train/048_forg/01_0204048.PNG \n extracting: sign_data/train/048_forg/02_0106048.PNG \n extracting: sign_data/train/048_forg/02_0204048.PNG \n extracting: sign_data/train/048_forg/03_0106048.PNG \n extracting: sign_data/train/048_forg/03_0204048.PNG \n extracting: sign_data/train/048_forg/04_0106048.PNG \n extracting: sign_data/train/048_forg/04_0204048.PNG \n creating: sign_data/train/049/\n extracting: sign_data/train/049/01_049.png \n extracting: sign_data/train/049/02_049.png \n extracting: sign_data/train/049/03_049.png \n extracting: sign_data/train/049/04_049.png \n extracting: sign_data/train/049/05_049.png \n extracting: sign_data/train/049/06_049.png \n extracting: sign_data/train/049/07_049.png \n extracting: sign_data/train/049/08_049.png \n extracting: sign_data/train/049/09_049.png \n extracting: sign_data/train/049/10_049.png \n extracting: sign_data/train/049/11_049.png \n extracting: sign_data/train/049/12_049.png \n creating: sign_data/train/049_forg/\n extracting: sign_data/train/049_forg/01_0114049.PNG \n extracting: sign_data/train/049_forg/01_0206049.PNG \n extracting: sign_data/train/049_forg/01_0210049.PNG \n extracting: sign_data/train/049_forg/02_0114049.PNG \n extracting: sign_data/train/049_forg/02_0206049.PNG \n extracting: sign_data/train/049_forg/02_0210049.PNG \n extracting: sign_data/train/049_forg/03_0114049.PNG \n extracting: sign_data/train/049_forg/03_0206049.PNG \n extracting: sign_data/train/049_forg/03_0210049.PNG \n extracting: sign_data/train/049_forg/04_0114049.PNG \n extracting: sign_data/train/049_forg/04_0206049.PNG \n extracting: sign_data/train/049_forg/04_0210049.PNG \n creating: sign_data/train/050/\n extracting: sign_data/train/050/01_050.png \n extracting: sign_data/train/050/02_050.png \n extracting: sign_data/train/050/03_050.png \n extracting: sign_data/train/050/04_050.png \n extracting: sign_data/train/050/05_050.png \n extracting: sign_data/train/050/06_050.png \n extracting: sign_data/train/050/07_050.png \n extracting: sign_data/train/050/08_050.png \n extracting: sign_data/train/050/09_050.png \n extracting: sign_data/train/050/10_050.png \n extracting: sign_data/train/050/11_050.png \n extracting: sign_data/train/050/12_050.png \n creating: sign_data/train/050_forg/\n extracting: sign_data/train/050_forg/01_0125050.PNG \n extracting: sign_data/train/050_forg/01_0126050.PNG \n extracting: sign_data/train/050_forg/01_0204050.PNG \n extracting: sign_data/train/050_forg/02_0125050.PNG \n extracting: sign_data/train/050_forg/02_0126050.PNG \n extracting: sign_data/train/050_forg/02_0204050.PNG \n extracting: sign_data/train/050_forg/03_0125050.PNG \n extracting: sign_data/train/050_forg/03_0126050.PNG \n extracting: sign_data/train/050_forg/03_0204050.PNG \n extracting: sign_data/train/050_forg/04_0125050.PNG \n extracting: sign_data/train/050_forg/04_0126050.PNG \n extracting: sign_data/train/050_forg/04_0204050.PNG \n creating: sign_data/train/051/\n extracting: sign_data/train/051/01_051.png \n extracting: sign_data/train/051/02_051.png \n extracting: sign_data/train/051/03_051.png \n extracting: sign_data/train/051/04_051.png \n extracting: sign_data/train/051/05_051.png \n extracting: sign_data/train/051/06_051.png \n extracting: sign_data/train/051/07_051.png \n extracting: sign_data/train/051/08_051.png \n extracting: sign_data/train/051/09_051.png \n extracting: sign_data/train/051/10_051.png \n extracting: sign_data/train/051/11_051.png \n extracting: sign_data/train/051/12_051.png \n creating: sign_data/train/051_forg/\n extracting: sign_data/train/051_forg/01_0104051.PNG \n extracting: sign_data/train/051_forg/01_0120051.PNG \n extracting: sign_data/train/051_forg/02_0104051.PNG \n extracting: sign_data/train/051_forg/02_0120051.PNG \n extracting: sign_data/train/051_forg/03_0104051.PNG \n extracting: sign_data/train/051_forg/03_0120051.PNG \n extracting: sign_data/train/051_forg/04_0104051.PNG \n extracting: sign_data/train/051_forg/04_0120051.PNG \n creating: sign_data/train/052/\n extracting: sign_data/train/052/01_052.png \n extracting: sign_data/train/052/02_052.png \n extracting: sign_data/train/052/03_052.png \n extracting: sign_data/train/052/04_052.png \n extracting: sign_data/train/052/05_052.png \n extracting: sign_data/train/052/06_052.png \n extracting: sign_data/train/052/07_052.png \n extracting: sign_data/train/052/08_052.png \n extracting: sign_data/train/052/09_052.png \n extracting: sign_data/train/052/10_052.png \n extracting: sign_data/train/052/11_052.png \n extracting: sign_data/train/052/12_052.png \n creating: sign_data/train/052_forg/\n extracting: sign_data/train/052_forg/01_0106052.PNG \n extracting: sign_data/train/052_forg/01_0109052.PNG \n extracting: sign_data/train/052_forg/01_0207052.PNG \n extracting: sign_data/train/052_forg/01_0210052.PNG \n extracting: sign_data/train/052_forg/02_0106052.PNG \n extracting: sign_data/train/052_forg/02_0109052.PNG \n extracting: sign_data/train/052_forg/02_0207052.PNG \n extracting: sign_data/train/052_forg/02_0210052.PNG \n extracting: sign_data/train/052_forg/03_0106052.PNG \n extracting: sign_data/train/052_forg/03_0109052.PNG \n extracting: sign_data/train/052_forg/03_0207052.PNG \n extracting: sign_data/train/052_forg/03_0210052.PNG \n extracting: sign_data/train/052_forg/04_0106052.PNG \n extracting: sign_data/train/052_forg/04_0109052.PNG \n extracting: sign_data/train/052_forg/04_0207052.PNG \n extracting: sign_data/train/052_forg/04_0210052.PNG \n creating: sign_data/train/053/\n extracting: sign_data/train/053/01_053.png \n extracting: sign_data/train/053/02_053.png \n extracting: sign_data/train/053/03_053.png \n extracting: sign_data/train/053/04_053.png \n extracting: sign_data/train/053/05_053.png \n extracting: sign_data/train/053/06_053.png \n extracting: sign_data/train/053/07_053.png \n extracting: sign_data/train/053/08_053.png \n extracting: sign_data/train/053/09_053.png \n extracting: sign_data/train/053/10_053.png \n extracting: sign_data/train/053/11_053.png \n extracting: sign_data/train/053/12_053.png \n creating: sign_data/train/053_forg/\n extracting: sign_data/train/053_forg/01_0107053.PNG \n extracting: sign_data/train/053_forg/01_0115053.PNG \n extracting: sign_data/train/053_forg/01_0202053.PNG \n extracting: sign_data/train/053_forg/01_0207053.PNG \n extracting: sign_data/train/053_forg/02_0107053.PNG \n extracting: sign_data/train/053_forg/02_0115053.PNG \n extracting: sign_data/train/053_forg/02_0202053.PNG \n extracting: sign_data/train/053_forg/02_0207053.PNG \n extracting: sign_data/train/053_forg/03_0107053.PNG \n extracting: sign_data/train/053_forg/03_0115053.PNG \n extracting: sign_data/train/053_forg/03_0202053.PNG \n extracting: sign_data/train/053_forg/03_0207053.PNG \n extracting: sign_data/train/053_forg/04_0107053.PNG \n extracting: sign_data/train/053_forg/04_0115053.PNG \n extracting: sign_data/train/053_forg/04_0202053.PNG \n extracting: sign_data/train/053_forg/04_0207053.PNG \n creating: sign_data/train/054/\n extracting: sign_data/train/054/01_054.png \n extracting: sign_data/train/054/02_054.png \n extracting: sign_data/train/054/03_054.png \n extracting: sign_data/train/054/04_054.png \n extracting: sign_data/train/054/05_054.png \n extracting: sign_data/train/054/06_054.png \n extracting: sign_data/train/054/07_054.png \n extracting: sign_data/train/054/08_054.png \n extracting: sign_data/train/054/09_054.png \n extracting: sign_data/train/054/10_054.png \n extracting: sign_data/train/054/11_054.png \n extracting: sign_data/train/054/12_054.png \n creating: sign_data/train/054_forg/\n extracting: sign_data/train/054_forg/01_0102054.PNG \n extracting: sign_data/train/054_forg/01_0124054.PNG \n extracting: sign_data/train/054_forg/01_0207054.PNG \n extracting: sign_data/train/054_forg/01_0208054.PNG \n extracting: sign_data/train/054_forg/01_0214054.PNG \n extracting: sign_data/train/054_forg/02_0102054.PNG \n extracting: sign_data/train/054_forg/02_0124054.PNG \n extracting: sign_data/train/054_forg/02_0207054.PNG \n extracting: sign_data/train/054_forg/02_0208054.PNG \n extracting: sign_data/train/054_forg/02_0214054.PNG \n extracting: sign_data/train/054_forg/03_0102054.PNG \n extracting: sign_data/train/054_forg/03_0124054.PNG \n extracting: sign_data/train/054_forg/03_0207054.PNG \n extracting: sign_data/train/054_forg/03_0208054.PNG \n extracting: sign_data/train/054_forg/03_0214054.PNG \n extracting: sign_data/train/054_forg/04_0102054.PNG \n extracting: sign_data/train/054_forg/04_0124054.PNG \n extracting: sign_data/train/054_forg/04_0207054.PNG \n extracting: sign_data/train/054_forg/04_0208054.PNG \n extracting: sign_data/train/054_forg/04_0214054.PNG \n creating: sign_data/train/055/\n extracting: sign_data/train/055/01_055.png \n extracting: sign_data/train/055/02_055.png \n extracting: sign_data/train/055/03_055.png \n extracting: sign_data/train/055/04_055.png \n extracting: sign_data/train/055/05_055.png \n extracting: sign_data/train/055/06_055.png \n extracting: sign_data/train/055/07_055.png \n extracting: sign_data/train/055/08_055.png \n extracting: sign_data/train/055/09_055.png \n extracting: sign_data/train/055/10_055.png \n extracting: sign_data/train/055/11_055.png \n extracting: sign_data/train/055/12_055.png \n creating: sign_data/train/055_forg/\n extracting: sign_data/train/055_forg/01_0118055.PNG \n extracting: sign_data/train/055_forg/01_0120055.PNG \n extracting: sign_data/train/055_forg/01_0202055.PNG \n extracting: sign_data/train/055_forg/02_0118055.PNG \n extracting: sign_data/train/055_forg/02_0120055.PNG \n extracting: sign_data/train/055_forg/02_0202055.PNG \n extracting: sign_data/train/055_forg/03_0118055.PNG \n extracting: sign_data/train/055_forg/03_0120055.PNG \n extracting: sign_data/train/055_forg/03_0202055.PNG \n extracting: sign_data/train/055_forg/04_0118055.PNG \n extracting: sign_data/train/055_forg/04_0120055.PNG \n extracting: sign_data/train/055_forg/04_0202055.PNG \n creating: sign_data/train/056/\n extracting: sign_data/train/056/01_056.png \n extracting: sign_data/train/056/02_056.png \n extracting: sign_data/train/056/03_056.png \n extracting: sign_data/train/056/04_056.png \n extracting: sign_data/train/056/05_056.png \n extracting: sign_data/train/056/06_056.png \n extracting: sign_data/train/056/07_056.png \n extracting: sign_data/train/056/08_056.png \n extracting: sign_data/train/056/09_056.png \n extracting: sign_data/train/056/10_056.png \n extracting: sign_data/train/056/11_056.png \n extracting: sign_data/train/056/12_056.png \n creating: sign_data/train/056_forg/\n extracting: sign_data/train/056_forg/01_0105056.PNG \n extracting: sign_data/train/056_forg/01_0115056.PNG \n extracting: sign_data/train/056_forg/02_0105056.PNG \n extracting: sign_data/train/056_forg/02_0115056.PNG \n extracting: sign_data/train/056_forg/03_0105056.PNG \n extracting: sign_data/train/056_forg/03_0115056.PNG \n extracting: sign_data/train/056_forg/04_0105056.PNG \n extracting: sign_data/train/056_forg/04_0115056.PNG \n creating: sign_data/train/057/\n extracting: sign_data/train/057/01_057.png \n extracting: sign_data/train/057/02_057.png \n extracting: sign_data/train/057/03_057.png \n extracting: sign_data/train/057/04_057.png \n extracting: sign_data/train/057/05_057.png \n extracting: sign_data/train/057/06_057.png \n extracting: sign_data/train/057/07_057.png \n extracting: sign_data/train/057/08_057.png \n extracting: sign_data/train/057/09_057.png \n extracting: sign_data/train/057/10_057.png \n extracting: sign_data/train/057/11_057.png \n extracting: sign_data/train/057/12_057.png \n creating: sign_data/train/057_forg/\n extracting: sign_data/train/057_forg/01_0117057.PNG \n extracting: sign_data/train/057_forg/01_0208057.PNG \n extracting: sign_data/train/057_forg/01_0210057.PNG \n extracting: sign_data/train/057_forg/02_0117057.PNG \n extracting: sign_data/train/057_forg/02_0208057.PNG \n extracting: sign_data/train/057_forg/02_0210057.PNG \n extracting: sign_data/train/057_forg/03_0117057.PNG \n extracting: sign_data/train/057_forg/03_0208057.PNG \n extracting: sign_data/train/057_forg/03_0210057.PNG \n extracting: sign_data/train/057_forg/04_0117057.PNG \n extracting: sign_data/train/057_forg/04_0208057.PNG \n extracting: sign_data/train/057_forg/04_0210057.PNG \n creating: sign_data/train/058/\n extracting: sign_data/train/058/01_058.png \n extracting: sign_data/train/058/02_058.png \n extracting: sign_data/train/058/03_058.png \n extracting: sign_data/train/058/04_058.png \n extracting: sign_data/train/058/05_058.png \n extracting: sign_data/train/058/06_058.png \n extracting: sign_data/train/058/07_058.png \n extracting: sign_data/train/058/08_058.png \n extracting: sign_data/train/058/09_058.png \n extracting: sign_data/train/058/10_058.png \n extracting: sign_data/train/058/11_058.png \n extracting: sign_data/train/058/12_058.png \n creating: sign_data/train/058_forg/\n extracting: sign_data/train/058_forg/01_0109058.PNG \n extracting: sign_data/train/058_forg/01_0110058.PNG \n extracting: sign_data/train/058_forg/01_0125058.PNG \n extracting: sign_data/train/058_forg/01_0127058.PNG \n extracting: sign_data/train/058_forg/02_0109058.PNG \n extracting: sign_data/train/058_forg/02_0110058.PNG \n extracting: sign_data/train/058_forg/02_0125058.PNG \n extracting: sign_data/train/058_forg/02_0127058.PNG \n extracting: sign_data/train/058_forg/03_0109058.PNG \n extracting: sign_data/train/058_forg/03_0110058.PNG \n extracting: sign_data/train/058_forg/03_0125058.PNG \n extracting: sign_data/train/058_forg/03_0127058.PNG \n extracting: sign_data/train/058_forg/04_0109058.PNG \n extracting: sign_data/train/058_forg/04_0110058.PNG \n extracting: sign_data/train/058_forg/04_0125058.PNG \n extracting: sign_data/train/058_forg/04_0127058.PNG \n creating: sign_data/train/059/\n extracting: sign_data/train/059/01_059.png \n extracting: sign_data/train/059/02_059.png \n extracting: sign_data/train/059/03_059.png \n extracting: sign_data/train/059/04_059.png \n extracting: sign_data/train/059/05_059.png \n extracting: sign_data/train/059/06_059.png \n extracting: sign_data/train/059/07_059.png \n extracting: sign_data/train/059/08_059.png \n extracting: sign_data/train/059/09_059.png \n extracting: sign_data/train/059/10_059.png \n extracting: sign_data/train/059/11_059.png \n extracting: sign_data/train/059/12_059.png \n creating: sign_data/train/059_forg/\n extracting: sign_data/train/059_forg/01_0104059.PNG \n extracting: sign_data/train/059_forg/01_0125059.PNG \n extracting: sign_data/train/059_forg/02_0104059.PNG \n extracting: sign_data/train/059_forg/02_0125059.PNG \n extracting: sign_data/train/059_forg/03_0104059.PNG \n extracting: sign_data/train/059_forg/03_0125059.PNG \n extracting: sign_data/train/059_forg/04_0104059.PNG \n extracting: sign_data/train/059_forg/04_0125059.PNG \n creating: sign_data/train/060/\n extracting: sign_data/train/060/01_060.png \n extracting: sign_data/train/060/02_060.png \n extracting: sign_data/train/060/03_060.png \n extracting: sign_data/train/060/04_060.png \n extracting: sign_data/train/060/05_060.png \n extracting: sign_data/train/060/06_060.png \n extracting: sign_data/train/060/07_060.png \n extracting: sign_data/train/060/08_060.png \n extracting: sign_data/train/060/09_060.png \n extracting: sign_data/train/060/10_060.png \n extracting: sign_data/train/060/11_060.png \n extracting: sign_data/train/060/12_060.png \n creating: sign_data/train/060_forg/\n extracting: sign_data/train/060_forg/01_0111060.PNG \n extracting: sign_data/train/060_forg/01_0121060.PNG \n extracting: sign_data/train/060_forg/01_0126060.PNG \n extracting: sign_data/train/060_forg/02_0111060.PNG \n extracting: sign_data/train/060_forg/02_0121060.PNG \n extracting: sign_data/train/060_forg/02_0126060.PNG \n extracting: sign_data/train/060_forg/03_0111060.PNG \n extracting: sign_data/train/060_forg/03_0121060.PNG \n extracting: sign_data/train/060_forg/03_0126060.PNG \n extracting: sign_data/train/060_forg/04_0111060.PNG \n extracting: sign_data/train/060_forg/04_0121060.PNG \n extracting: sign_data/train/060_forg/04_0126060.PNG \n creating: sign_data/train/061/\n extracting: sign_data/train/061/01_061.png \n extracting: sign_data/train/061/02_061.png \n extracting: sign_data/train/061/03_061.png \n extracting: sign_data/train/061/04_061.png \n extracting: sign_data/train/061/05_061.png \n extracting: sign_data/train/061/06_061.png \n extracting: sign_data/train/061/07_061.png \n extracting: sign_data/train/061/08_061.png \n extracting: sign_data/train/061/09_061.png \n extracting: sign_data/train/061/10_061.png \n extracting: sign_data/train/061/11_061.png \n extracting: sign_data/train/061/12_061.png \n creating: sign_data/train/061_forg/\n extracting: sign_data/train/061_forg/01_0102061.PNG \n extracting: sign_data/train/061_forg/01_0112061.PNG \n extracting: sign_data/train/061_forg/01_0206061.PNG \n extracting: sign_data/train/061_forg/02_0102061.PNG \n extracting: sign_data/train/061_forg/02_0112061.PNG \n extracting: sign_data/train/061_forg/02_0206061.PNG \n extracting: sign_data/train/061_forg/03_0102061.PNG \n extracting: sign_data/train/061_forg/03_0112061.PNG \n extracting: sign_data/train/061_forg/03_0206061.PNG \n extracting: sign_data/train/061_forg/04_0102061.PNG \n extracting: sign_data/train/061_forg/04_0112061.PNG \n extracting: sign_data/train/061_forg/04_0206061.PNG \n creating: sign_data/train/062/\n extracting: sign_data/train/062/01_062.png \n extracting: sign_data/train/062/02_062.png \n extracting: sign_data/train/062/03_062.png \n extracting: sign_data/train/062/04_062.png \n extracting: sign_data/train/062/05_062.png \n inflating: sign_data/train/062/06_062.png \n extracting: sign_data/train/062/07_062.png \n extracting: sign_data/train/062/08_062.png \n extracting: sign_data/train/062/09_062.png \n extracting: sign_data/train/062/10_062.png \n extracting: sign_data/train/062/11_062.png \n extracting: sign_data/train/062/12_062.png \n creating: sign_data/train/062_forg/\n extracting: sign_data/train/062_forg/01_0109062.PNG \n extracting: sign_data/train/062_forg/01_0116062.PNG \n extracting: sign_data/train/062_forg/01_0201062.PNG \n extracting: sign_data/train/062_forg/02_0109062.PNG \n extracting: sign_data/train/062_forg/02_0116062.PNG \n extracting: sign_data/train/062_forg/02_0201062.PNG \n extracting: sign_data/train/062_forg/03_0109062.PNG \n extracting: sign_data/train/062_forg/03_0116062.PNG \n extracting: sign_data/train/062_forg/03_0201062.PNG \n extracting: sign_data/train/062_forg/04_0109062.PNG \n extracting: sign_data/train/062_forg/04_0116062.PNG \n extracting: sign_data/train/062_forg/04_0201062.PNG \n creating: sign_data/train/063/\n extracting: sign_data/train/063/01_063.png \n extracting: sign_data/train/063/02_063.png \n extracting: sign_data/train/063/03_063.png \n extracting: sign_data/train/063/04_063.png \n extracting: sign_data/train/063/05_063.png \n extracting: sign_data/train/063/06_063.png \n extracting: sign_data/train/063/07_063.png \n extracting: sign_data/train/063/08_063.png \n extracting: sign_data/train/063/09_063.png \n extracting: sign_data/train/063/10_063.png \n extracting: sign_data/train/063/11_063.png \n extracting: sign_data/train/063/12_063.png \n creating: sign_data/train/063_forg/\n extracting: sign_data/train/063_forg/01_0104063.PNG \n extracting: sign_data/train/063_forg/01_0108063.PNG \n extracting: sign_data/train/063_forg/01_0119063.PNG \n extracting: sign_data/train/063_forg/02_0104063.PNG \n extracting: sign_data/train/063_forg/02_0108063.PNG \n extracting: sign_data/train/063_forg/02_0119063.PNG \n extracting: sign_data/train/063_forg/03_0104063.PNG \n extracting: sign_data/train/063_forg/03_0108063.PNG \n extracting: sign_data/train/063_forg/03_0119063.PNG \n extracting: sign_data/train/063_forg/04_0104063.PNG \n extracting: sign_data/train/063_forg/04_0108063.PNG \n extracting: sign_data/train/063_forg/04_0119063.PNG \n creating: sign_data/train/064/\n extracting: sign_data/train/064/01_064.png \n extracting: sign_data/train/064/02_064.png \n extracting: sign_data/train/064/03_064.png \n extracting: sign_data/train/064/04_064.png \n extracting: sign_data/train/064/05_064.png \n extracting: sign_data/train/064/06_064.png \n extracting: sign_data/train/064/07_064.png \n extracting: sign_data/train/064/08_064.png \n extracting: sign_data/train/064/09_064.png \n extracting: sign_data/train/064/10_064.png \n extracting: sign_data/train/064/11_064.png \n extracting: sign_data/train/064/12_064.png \n creating: sign_data/train/064_forg/\n extracting: sign_data/train/064_forg/01_0105064.PNG \n extracting: sign_data/train/064_forg/01_0203064.PNG \n extracting: sign_data/train/064_forg/02_0105064.PNG \n extracting: sign_data/train/064_forg/02_0203064.PNG \n extracting: sign_data/train/064_forg/03_0105064.PNG \n extracting: sign_data/train/064_forg/03_0203064.PNG \n extracting: sign_data/train/064_forg/04_0105064.PNG \n extracting: sign_data/train/064_forg/04_0203064.PNG \n creating: sign_data/train/065/\n extracting: sign_data/train/065/01_065.png \n extracting: sign_data/train/065/02_065.png \n extracting: sign_data/train/065/03_065.png \n extracting: sign_data/train/065/04_065.png \n extracting: sign_data/train/065/05_065.png \n extracting: sign_data/train/065/06_065.png \n extracting: sign_data/train/065/07_065.png \n extracting: sign_data/train/065/08_065.png \n extracting: sign_data/train/065/09_065.png \n extracting: sign_data/train/065/10_065.png \n extracting: sign_data/train/065/11_065.png \n extracting: sign_data/train/065/12_065.png \n creating: sign_data/train/065_forg/\n extracting: sign_data/train/065_forg/01_0118065.PNG \n extracting: sign_data/train/065_forg/01_0206065.PNG \n extracting: sign_data/train/065_forg/02_0118065.PNG \n extracting: sign_data/train/065_forg/02_0206065.PNG \n extracting: sign_data/train/065_forg/03_0118065.PNG \n extracting: sign_data/train/065_forg/03_0206065.PNG \n extracting: sign_data/train/065_forg/04_0118065.PNG \n extracting: sign_data/train/065_forg/04_0206065.PNG \n creating: sign_data/train/066/\n extracting: sign_data/train/066/01_066.png \n extracting: sign_data/train/066/02_066.png \n extracting: sign_data/train/066/03_066.png \n extracting: sign_data/train/066/04_066.png \n extracting: sign_data/train/066/05_066.png \n extracting: sign_data/train/066/06_066.png \n extracting: sign_data/train/066/07_066.png \n extracting: sign_data/train/066/08_066.png \n extracting: sign_data/train/066/09_066.png \n extracting: sign_data/train/066/10_066.png \n extracting: sign_data/train/066/11_066.png \n extracting: sign_data/train/066/12_066.png \n creating: sign_data/train/066_forg/\n extracting: sign_data/train/066_forg/01_0101066.PNG \n extracting: sign_data/train/066_forg/01_0127066.PNG \n extracting: sign_data/train/066_forg/01_0211066.PNG \n extracting: sign_data/train/066_forg/01_0212066.PNG \n extracting: sign_data/train/066_forg/02_0101066.PNG \n extracting: sign_data/train/066_forg/02_0127066.PNG \n extracting: sign_data/train/066_forg/02_0211066.PNG \n extracting: sign_data/train/066_forg/02_0212066.PNG \n extracting: sign_data/train/066_forg/03_0101066.PNG \n extracting: sign_data/train/066_forg/03_0127066.PNG \n extracting: sign_data/train/066_forg/03_0211066.PNG \n extracting: sign_data/train/066_forg/03_0212066.PNG \n extracting: sign_data/train/066_forg/04_0101066.PNG \n extracting: sign_data/train/066_forg/04_0127066.PNG \n extracting: sign_data/train/066_forg/04_0211066.PNG \n extracting: sign_data/train/066_forg/04_0212066.PNG \n creating: sign_data/train/067/\n extracting: sign_data/train/067/01_067.png \n extracting: sign_data/train/067/02_067.png \n extracting: sign_data/train/067/03_067.png \n extracting: sign_data/train/067/04_067.png \n extracting: sign_data/train/067/05_067.png \n extracting: sign_data/train/067/06_067.png \n extracting: sign_data/train/067/07_067.png \n extracting: sign_data/train/067/08_067.png \n extracting: sign_data/train/067/09_067.png \n extracting: sign_data/train/067/10_067.png \n extracting: sign_data/train/067/11_067.png \n extracting: sign_data/train/067/12_067.png \n creating: sign_data/train/067_forg/\n extracting: sign_data/train/067_forg/01_0205067.PNG \n extracting: sign_data/train/067_forg/01_0212067.PNG \n extracting: sign_data/train/067_forg/02_0205067.PNG \n extracting: sign_data/train/067_forg/02_0212067.PNG \n extracting: sign_data/train/067_forg/03_0205067.PNG \n extracting: sign_data/train/067_forg/03_0212067.PNG \n extracting: sign_data/train/067_forg/04_0205067.PNG \n extracting: sign_data/train/067_forg/04_0212067.PNG \n creating: sign_data/train/068/\n extracting: sign_data/train/068/01_068.png \n extracting: sign_data/train/068/02_068.png \n extracting: sign_data/train/068/03_068.png \n extracting: sign_data/train/068/04_068.png \n extracting: sign_data/train/068/05_068.png \n extracting: sign_data/train/068/06_068.png \n extracting: sign_data/train/068/07_068.png \n extracting: sign_data/train/068/08_068.png \n extracting: sign_data/train/068/09_068.png \n extracting: sign_data/train/068/10_068.png \n extracting: sign_data/train/068/11_068.png \n extracting: sign_data/train/068/12_068.png \n creating: sign_data/train/068_forg/\n extracting: sign_data/train/068_forg/01_0113068.PNG \n extracting: sign_data/train/068_forg/01_0124068.PNG \n extracting: sign_data/train/068_forg/02_0113068.PNG \n extracting: sign_data/train/068_forg/02_0124068.PNG \n extracting: sign_data/train/068_forg/03_0113068.PNG \n extracting: sign_data/train/068_forg/03_0124068.PNG \n extracting: sign_data/train/068_forg/04_0113068.PNG \n extracting: sign_data/train/068_forg/04_0124068.PNG \n creating: sign_data/train/069/\n extracting: sign_data/train/069/01_069.png \n extracting: sign_data/train/069/02_069.png \n extracting: sign_data/train/069/03_069.png \n extracting: sign_data/train/069/04_069.png \n extracting: sign_data/train/069/05_069.png \n extracting: sign_data/train/069/06_069.png \n extracting: sign_data/train/069/07_069.png \n extracting: sign_data/train/069/08_069.png \n extracting: sign_data/train/069/09_069.png \n extracting: sign_data/train/069/10_069.png \n extracting: sign_data/train/069/11_069.png \n extracting: sign_data/train/069/12_069.png \n creating: sign_data/train/069_forg/\n extracting: sign_data/train/069_forg/01_0106069.PNG \n extracting: sign_data/train/069_forg/01_0108069.PNG \n extracting: sign_data/train/069_forg/01_0111069.PNG \n extracting: sign_data/train/069_forg/02_0106069.PNG \n extracting: sign_data/train/069_forg/02_0108069.PNG \n extracting: sign_data/train/069_forg/02_0111069.PNG \n extracting: sign_data/train/069_forg/03_0106069.PNG \n extracting: sign_data/train/069_forg/03_0108069.PNG \n extracting: sign_data/train/069_forg/03_0111069.PNG \n extracting: sign_data/train/069_forg/04_0106069.PNG \n extracting: sign_data/train/069_forg/04_0108069.PNG \n extracting: sign_data/train/069_forg/04_0111069.PNG \n inflating: sign_data/train_data.csv \n" ], [ "import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport keras ", "_____no_output_____" ], [ "pwd", "_____no_output_____" ], [ "train_dir=\"/content/sign_data/train\"\ntrain_csv=\"/content/sign_data/train_data.csv\"\ntest_csv=\"/content/sign_data/test_data.csv\"\ntest_dir=\"/content/sign_data/test\"", "_____no_output_____" ], [ "df_train=pd.read_csv(train_csv)\ndf_train.head()", "_____no_output_____" ], [ "df_test = pd.read_csv(test_csv)\ndf_test.head()", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimg = plt.imread(train_dir+\"/\"+(df_train.iat[1,0]))#.replace(\"/\", \"\\\\\"))\nplt.imshow(img)", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimg = plt.imread(train_dir+\"/\"+df_train.iat[1,1])#.replace(\"/\", \"\\\\\"))\nplt.imshow(img)", "_____no_output_____" ], [ "import cv2\ntest_images1 = []\ntest_images2 = []\nfor j in range(0,len(df_test)):\n img1 = cv2.imread(test_dir+\"/\"+df_test.iat[j,0])\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n img1 = cv2.resize(img1, (100, 100))\n test_images1.append(img1)\n \n img2 = cv2.imread(test_dir+\"/\"+df_test.iat[j,1])\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n img2 = cv2.resize(img2, (100, 100))\n test_images2.append(img2)\n\ntest_images1 = np.array(test_images1)/255.0\ntest_images2 = np.array(test_images2)/255.0", "_____no_output_____" ], [ "import cv2\n\ntrain_images1 = []\ntrain_images2 = []\ntrain_labels = []\n\nfor i in range(len(df_train)):\n img1 = cv2.imread(train_dir+\"/\"+df_train.iat[i,0])\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n img1 = cv2.resize(img1, (100, 100))\n train_images1.append(img1)\n \n img2 = cv2.imread(train_dir+\"/\"+df_train.iat[i,1])\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n img2 = cv2.resize(img2, (100, 100))\n train_images2.append(img2)\n \n train_labels.append(df_train.iat[i,2])\n \ntrain_images1 = np.array(train_images1)/255.0\ntrain_images2 = np.array(train_images2)/255.0\ntrain_labels = np.array(train_labels)", "_____no_output_____" ], [ "train_images1 = np.expand_dims(train_images1, -1)\ntrain_images2 = np.expand_dims(train_images2, -1)\ntest_images1 = np.expand_dims(test_images1, -1)\ntest_images2 = np.expand_dims(test_images2, -1)", "_____no_output_____" ], [ "from keras import backend as K\ndef euclidean_distance(vects):\n x, y = vects\n return K.sqrt(K.sum(K.square(x - y), axis=1, keepdims=True))\n\ndef eucl_dist_output_shape(shapes):\n shape1, shape2 = shapes\n return (shape1[0], 1)\n\n# def contrastive_loss(y_true, y_pred):\n# margin = 1\n# return K.mean(y_true * K.square(y_pred) + (1 - y_true) * K.square(K.maximum(margin - y_pred, 0)))\n\n# def accuracy(y_true, y_pred):\n# '''Compute classification accuracy with a fixed threshold on distances.\n# '''\n# return K.mean(K.equal(y_true, K.cast(y_pred < 0.5, y_true.dtype)))", "_____no_output_____" ], [ "input_dim = (100,100,1)", "_____no_output_____" ], [ "from keras import backend as K\nfrom keras.layers import Activation\nfrom keras.layers import Input, Lambda, Dense, Dropout, Convolution2D, MaxPooling2D, Flatten\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import RMSprop\nfrom keras import optimizers\n\nfrom keras import callbacks\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping, ReduceLROnPlateau, TensorBoard\nimport os\nfrom keras.models import Model,load_model\nimport json\nfrom keras.models import model_from_json, load_model\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "def build_base_network(input_shape):\n \n seq = Sequential()\n \n kernel_size = 3\n \n #convolutional layer 1\n seq.add(Convolution2D(64, (kernel_size, kernel_size), input_shape=input_shape))\n seq.add(Activation('relu'))\n seq.add(MaxPooling2D(pool_size=(2, 2))) \n seq.add(Dropout(.25))\n \n seq.add(Convolution2D(32, (kernel_size, kernel_size)))\n seq.add(Activation('relu'))\n seq.add(MaxPooling2D(pool_size=(2, 2))) \n seq.add(Dropout(.25))\n \n #convolutional layer 2\n seq.add(Convolution2D(32, (kernel_size, kernel_size)))\n seq.add(Activation('relu'))\n seq.add(MaxPooling2D(pool_size=(2, 2))) \n seq.add(Dropout(.25))\n\n #flatten \n seq.add(Flatten())\n seq.add(Dense(128, activation='relu'))\n seq.add(Dropout(0.1))\n seq.add(Dense(50, activation='relu'))\n return seq\n\nbase_network = build_base_network(input_dim)\n\nimg_a = Input(shape=input_dim)\nimg_b = Input(shape=input_dim)\n\nfeat_vecs_a = base_network(img_a)\nfeat_vecs_b = base_network(img_b)\n\ndistance = Lambda(euclidean_distance, output_shape=eucl_dist_output_shape)([feat_vecs_a, feat_vecs_b])\n\nprediction = Dense(1,activation='sigmoid')(distance)", "_____no_output_____" ], [ "earlyStopping = EarlyStopping(monitor='val_loss',\n min_delta=0,\n patience=3,\n verbose=1)\n\ncallback_early_stop_reduceLROnPlateau=[earlyStopping]", "_____no_output_____" ], [ "model = Model([img_a, img_b],prediction)\nmodel.summary()", "Model: \"model\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) [(None, 100, 100, 1) 0 \n__________________________________________________________________________________________________\ninput_2 (InputLayer) [(None, 100, 100, 1) 0 \n__________________________________________________________________________________________________\nsequential (Sequential) (None, 50) 444530 input_1[0][0] \n input_2[0][0] \n__________________________________________________________________________________________________\nlambda (Lambda) (None, 1) 0 sequential[0][0] \n sequential[1][0] \n__________________________________________________________________________________________________\ndense_2 (Dense) (None, 1) 2 lambda[0][0] \n==================================================================================================\nTotal params: 444,532\nTrainable params: 444,532\nNon-trainable params: 0\n__________________________________________________________________________________________________\n" ], [ "from keras.utils.vis_utils import plot_model\nplot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)", "_____no_output_____" ], [ "model.compile(loss=\"binary_crossentropy\", optimizer=optimizers.Adam(lr=0.0001), metrics=[\"accuracy\"])", "_____no_output_____" ], [ "model_hist = model.fit([train_images1,train_images2], train_labels, validation_split=.10,\n batch_size= 32, verbose=1, epochs=5, callbacks=callback_early_stop_reduceLROnPlateau)", "Epoch 1/5\n653/653 [==============================] - 19s 18ms/step - loss: 0.7070 - accuracy: 0.4782 - val_loss: 0.6929 - val_accuracy: 0.5118\nEpoch 2/5\n653/653 [==============================] - 11s 17ms/step - loss: 0.6918 - accuracy: 0.5410 - val_loss: 0.6929 - val_accuracy: 0.5118\nEpoch 3/5\n653/653 [==============================] - 11s 17ms/step - loss: 0.6911 - accuracy: 0.5416 - val_loss: 0.6930 - val_accuracy: 0.5118\nEpoch 4/5\n653/653 [==============================] - 11s 17ms/step - loss: 0.6900 - accuracy: 0.5498 - val_loss: 0.6931 - val_accuracy: 0.5118\nEpoch 5/5\n653/653 [==============================] - 11s 17ms/step - loss: 0.6909 - accuracy: 0.5357 - val_loss: 0.6933 - val_accuracy: 0.5118\nEpoch 00005: early stopping\n" ], [ "pred_y = model.predict([test_images1,test_images2])", "_____no_output_____" ], [ "test_labels = np.array(df_test['1'])", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(pred_y.argmax(axis=1), test_labels)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfce2acd5b62bc473ee9d1f97173e210e77fe9c
198,725
ipynb
Jupyter Notebook
lab2/Part1_MNIST.ipynb
sramirezh/introtodeeplearning
93e6a3986375a997b51f977e2ee596f227b424d0
[ "MIT" ]
null
null
null
lab2/Part1_MNIST.ipynb
sramirezh/introtodeeplearning
93e6a3986375a997b51f977e2ee596f227b424d0
[ "MIT" ]
null
null
null
lab2/Part1_MNIST.ipynb
sramirezh/introtodeeplearning
93e6a3986375a997b51f977e2ee596f227b424d0
[ "MIT" ]
null
null
null
222.287472
145,098
0.840518
[ [ [ "<table align=\"center\">\n <td align=\"center\"><a target=\"_blank\" href=\"http://introtodeeplearning.com\">\n <img src=\"https://i.ibb.co/Jr88sn2/mit.png\" style=\"padding-bottom:5px;\" />\n Visit MIT Deep Learning</a></td>\n <td align=\"center\"><a target=\"_blank\" href=\"https://colab.research.google.com/github/aamini/introtodeeplearning/blob/master/lab2/Part1_MNIST.ipynb\">\n <img src=\"https://i.ibb.co/2P3SLwK/colab.png\" style=\"padding-bottom:5px;\" />Run in Google Colab</a></td>\n <td align=\"center\"><a target=\"_blank\" href=\"https://github.com/aamini/introtodeeplearning/blob/master/lab2/Part1_MNIST.ipynb\">\n <img src=\"https://i.ibb.co/xfJbPmL/github.png\" height=\"70px\" style=\"padding-bottom:5px;\" />View Source on GitHub</a></td>\n</table>\n\n# Copyright Information", "_____no_output_____" ] ], [ [ "# Copyright 2021 MIT 6.S191 Introduction to Deep Learning. All Rights Reserved.\n# \n# Licensed under the MIT License. You may not use this file except in compliance\n# with the License. Use and/or modification of this code outside of 6.S191 must\n# reference:\n#\n# © MIT 6.S191: Introduction to Deep Learning\n# http://introtodeeplearning.com\n#", "_____no_output_____" ] ], [ [ "# Laboratory 2: Computer Vision\n\n# Part 1: MNIST Digit Classification\n\nIn the first portion of this lab, we will build and train a convolutional neural network (CNN) for classification of handwritten digits from the famous [MNIST](http://yann.lecun.com/exdb/mnist/) dataset. The MNIST dataset consists of 60,000 training images and 10,000 test images. Our classes are the digits 0-9.\n\nFirst, let's download the course repository, install dependencies, and import the relevant packages we'll need for this lab.", "_____no_output_____" ] ], [ [ "# Import Tensorflow 2.0\n%tensorflow_version 2.x\nimport tensorflow as tf \n\n!pip install mitdeeplearning\nimport mitdeeplearning as mdl\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nfrom tqdm import tqdm\n\n# Check that we are using a GPU, if not switch runtimes\n# using Runtime > Change Runtime Type > GPU\nassert len(tf.config.list_physical_devices('GPU')) > 0", "Collecting mitdeeplearning\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/9d/ad/650eb53c0d9d1213536fe94bc150f89b564ff5ee784bd662272584bb091b/mitdeeplearning-0.2.0.tar.gz (2.1MB)\n\r\u001b[K |▏ | 10kB 22.6MB/s eta 0:00:01\r\u001b[K |▎ | 20kB 29.7MB/s eta 0:00:01\r\u001b[K |▌ | 30kB 24.9MB/s eta 0:00:01\r\u001b[K |▋ | 40kB 21.2MB/s eta 0:00:01\r\u001b[K |▉ | 51kB 22.5MB/s eta 0:00:01\r\u001b[K |█ | 61kB 15.5MB/s eta 0:00:01\r\u001b[K |█ | 71kB 16.9MB/s eta 0:00:01\r\u001b[K |█▎ | 81kB 15.9MB/s eta 0:00:01\r\u001b[K |█▍ | 92kB 15.9MB/s eta 0:00:01\r\u001b[K |█▋ | 102kB 16.5MB/s eta 0:00:01\r\u001b[K |█▊ | 112kB 16.5MB/s eta 0:00:01\r\u001b[K |█▉ | 122kB 16.5MB/s eta 0:00:01\r\u001b[K |██ | 133kB 16.5MB/s eta 0:00:01\r\u001b[K |██▏ | 143kB 16.5MB/s eta 0:00:01\r\u001b[K |██▍ | 153kB 16.5MB/s eta 0:00:01\r\u001b[K |██▌ | 163kB 16.5MB/s eta 0:00:01\r\u001b[K |██▋ | 174kB 16.5MB/s eta 0:00:01\r\u001b[K |██▉ | 184kB 16.5MB/s eta 0:00:01\r\u001b[K |███ | 194kB 16.5MB/s eta 0:00:01\r\u001b[K |███▏ | 204kB 16.5MB/s eta 0:00:01\r\u001b[K |███▎ | 215kB 16.5MB/s eta 0:00:01\r\u001b[K |███▌ | 225kB 16.5MB/s eta 0:00:01\r\u001b[K |███▋ | 235kB 16.5MB/s eta 0:00:01\r\u001b[K |███▊ | 245kB 16.5MB/s eta 0:00:01\r\u001b[K |████ | 256kB 16.5MB/s eta 0:00:01\r\u001b[K |████ | 266kB 16.5MB/s eta 0:00:01\r\u001b[K |████▎ | 276kB 16.5MB/s eta 0:00:01\r\u001b[K |████▍ | 286kB 16.5MB/s eta 0:00:01\r\u001b[K |████▌ | 296kB 16.5MB/s eta 0:00:01\r\u001b[K |████▊ | 307kB 16.5MB/s eta 0:00:01\r\u001b[K |████▉ | 317kB 16.5MB/s eta 0:00:01\r\u001b[K |█████ | 327kB 16.5MB/s eta 0:00:01\r\u001b[K |█████▏ | 337kB 16.5MB/s eta 0:00:01\r\u001b[K |█████▎ | 348kB 16.5MB/s eta 0:00:01\r\u001b[K |█████▌ | 358kB 16.5MB/s eta 0:00:01\r\u001b[K |█████▋ | 368kB 16.5MB/s eta 0:00:01\r\u001b[K |█████▉ | 378kB 16.5MB/s eta 0:00:01\r\u001b[K |██████ | 389kB 16.5MB/s eta 0:00:01\r\u001b[K |██████▏ | 399kB 16.5MB/s eta 0:00:01\r\u001b[K |██████▎ | 409kB 16.5MB/s eta 0:00:01\r\u001b[K |██████▍ | 419kB 16.5MB/s eta 0:00:01\r\u001b[K |██████▋ | 430kB 16.5MB/s eta 0:00:01\r\u001b[K |██████▊ | 440kB 16.5MB/s eta 0:00:01\r\u001b[K |███████ | 450kB 16.5MB/s eta 0:00:01\r\u001b[K |███████ | 460kB 16.5MB/s eta 0:00:01\r\u001b[K |███████▏ | 471kB 16.5MB/s eta 0:00:01\r\u001b[K |███████▍ | 481kB 16.5MB/s eta 0:00:01\r\u001b[K |███████▌ | 491kB 16.5MB/s eta 0:00:01\r\u001b[K |███████▊ | 501kB 16.5MB/s eta 0:00:01\r\u001b[K |███████▉ | 512kB 16.5MB/s eta 0:00:01\r\u001b[K |████████ | 522kB 16.5MB/s eta 0:00:01\r\u001b[K |████████▏ | 532kB 16.5MB/s eta 0:00:01\r\u001b[K |████████▎ | 542kB 16.5MB/s eta 0:00:01\r\u001b[K |████████▌ | 552kB 16.5MB/s eta 0:00:01\r\u001b[K |████████▋ | 563kB 16.5MB/s eta 0:00:01\r\u001b[K |████████▉ | 573kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████ | 583kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████ | 593kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████▎ | 604kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████▍ | 614kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████▋ | 624kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████▊ | 634kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████▉ | 645kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████ | 655kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████▏ | 665kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████▍ | 675kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████▌ | 686kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████▋ | 696kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████▉ | 706kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████ | 716kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████▏ | 727kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████▎ | 737kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████▍ | 747kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████▋ | 757kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████▊ | 768kB 16.5MB/s eta 0:00:01\r\u001b[K |████████████ | 778kB 16.5MB/s eta 0:00:01\r\u001b[K |████████████ | 788kB 16.5MB/s eta 0:00:01\r\u001b[K |████████████▎ | 798kB 16.5MB/s eta 0:00:01\r\u001b[K |████████████▍ | 808kB 16.5MB/s eta 0:00:01\r\u001b[K |████████████▌ | 819kB 16.5MB/s eta 0:00:01\r\u001b[K |████████████▊ | 829kB 16.5MB/s eta 0:00:01\r\u001b[K |████████████▉ | 839kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████ | 849kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████▏ | 860kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████▎ | 870kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████▌ | 880kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████▋ | 890kB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████▉ | 901kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████ | 911kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████ | 921kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████▎ | 931kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████▍ | 942kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████▋ | 952kB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████▊ | 962kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████ | 972kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████ | 983kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████▏ | 993kB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████▍ | 1.0MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████▌ | 1.0MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████▊ | 1.0MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████▉ | 1.0MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████ | 1.0MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████▏ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████▎ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████▌ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████▋ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████▊ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████▎ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████▍ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████▋ | 1.1MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████▊ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████▉ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████▏ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████▍ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████▌ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████▋ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████▉ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████▏ | 1.2MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████▎ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████▍ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████▋ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████▊ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████▎ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████▍ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████▌ | 1.3MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████▊ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████▉ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▏ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▎ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▌ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▋ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████▉ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████ | 1.4MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▎ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▍ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▋ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▊ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████▉ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▏ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▍ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▌ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▊ | 1.5MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████▉ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▏ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▎ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▌ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▋ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████▊ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▎ | 1.6MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▍ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▌ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▊ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████▉ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▏ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▍ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▌ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▋ | 1.7MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████▉ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▏ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▎ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▍ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▋ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████▊ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▏ | 1.8MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▍ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▌ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▊ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████▉ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▏ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▎ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▌ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▋ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▉ | 1.9MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▎ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▍ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▋ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▊ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▉ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████ | 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▏| 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▍| 2.0MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▌| 2.1MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▊| 2.1MB 16.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▉| 2.1MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 2.1MB 16.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 2.1MB 16.5MB/s \n\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from mitdeeplearning) (1.19.5)\nRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from mitdeeplearning) (2019.12.20)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from mitdeeplearning) (4.41.1)\nRequirement already satisfied: gym in /usr/local/lib/python3.7/dist-packages (from mitdeeplearning) (0.17.3)\nRequirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from gym->mitdeeplearning) (1.3.0)\nRequirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym->mitdeeplearning) (1.5.0)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from gym->mitdeeplearning) (1.4.1)\nRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym->mitdeeplearning) (0.16.0)\nBuilding wheels for collected packages: mitdeeplearning\n Building wheel for mitdeeplearning (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for mitdeeplearning: filename=mitdeeplearning-0.2.0-cp37-none-any.whl size=2115442 sha256=b6c91ccafe91a17b330997976cd9d04434694bbc005924d4d4f1d2d72a8b0447\n Stored in directory: /root/.cache/pip/wheels/af/dc/2a/5c3633135e7e4ef4fd31463cfa1942cb1bae7486ab94e7a2ad\nSuccessfully built mitdeeplearning\nInstalling collected packages: mitdeeplearning\nSuccessfully installed mitdeeplearning-0.2.0\n" ] ], [ [ "## 1.1 MNIST dataset \n\nLet's download and load the dataset and display a few random samples from it:", "_____no_output_____" ] ], [ [ "mnist = tf.keras.datasets.mnist\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\ntrain_images = (np.expand_dims(train_images, axis=-1)/255.).astype(np.float32)\ntrain_labels = (train_labels).astype(np.int64)\ntest_images = (np.expand_dims(test_images, axis=-1)/255.).astype(np.float32)\ntest_labels = (test_labels).astype(np.int64)", "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n11493376/11490434 [==============================] - 0s 0us/step\n" ] ], [ [ "Our training set is made up of 28x28 grayscale images of handwritten digits. \n\nLet's visualize what some of these images and their corresponding training labels look like.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,10))\nrandom_inds = np.random.choice(60000,36)\nfor i in range(36):\n plt.subplot(6,6,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n image_ind = random_inds[i]\n plt.imshow(np.squeeze(train_images[image_ind]), cmap=plt.cm.binary)\n plt.xlabel(train_labels[image_ind])", "_____no_output_____" ] ], [ [ "## 1.2 Neural Network for Handwritten Digit Classification\n\nWe'll first build a simple neural network consisting of two fully connected layers and apply this to the digit classification task. Our network will ultimately output a probability distribution over the 10 digit classes (0-9). This first architecture we will be building is depicted below:\n\n![alt_text](https://raw.githubusercontent.com/aamini/introtodeeplearning/master/lab2/img/mnist_2layers_arch.png \"CNN Architecture for MNIST Classification\")\n", "_____no_output_____" ], [ "### Fully connected neural network architecture\nTo define the architecture of this first fully connected neural network, we'll once again use the Keras API and define the model using the [`Sequential`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential) class. Note how we first use a [`Flatten`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Flatten) layer, which flattens the input so that it can be fed into the model. \n\nIn this next block, you'll define the fully connected layers of this simple work.", "_____no_output_____" ] ], [ [ "def build_fc_model():\n fc_model = tf.keras.Sequential([\n # First define a Flatten layer\n tf.keras.layers.Flatten(),\n\n # '''TODO: Define the activation function for the first fully connected (Dense) layer.'''\n tf.keras.layers.Dense(128, activation= tf.nn.relu),\n\n # '''TODO: Define the second Dense layer to output the classification probabilities'''\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n\n \n ])\n return fc_model\n\nmodel = build_fc_model()", "_____no_output_____" ] ], [ [ "As we progress through this next portion, you may find that you'll want to make changes to the architecture defined above. **Note that in order to update the model later on, you'll need to re-run the above cell to re-initialize the model.**", "_____no_output_____" ], [ "Let's take a step back and think about the network we've just created. The first layer in this network, `tf.keras.layers.Flatten`, transforms the format of the images from a 2d-array (28 x 28 pixels), to a 1d-array of 28 * 28 = 784 pixels. You can think of this layer as unstacking rows of pixels in the image and lining them up. There are no learned parameters in this layer; it only reformats the data.\n\nAfter the pixels are flattened, the network consists of a sequence of two `tf.keras.layers.Dense` layers. These are fully-connected neural layers. The first `Dense` layer has 128 nodes (or neurons). The second (and last) layer (which you've defined!) should return an array of probability scores that sum to 1. Each node contains a score that indicates the probability that the current image belongs to one of the handwritten digit classes.\n\nThat defines our fully connected model! ", "_____no_output_____" ], [ "\n\n### Compile the model\n\nBefore training the model, we need to define a few more settings. These are added during the model's [`compile`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential#compile) step:\n\n* *Loss function* — This defines how we measure how accurate the model is during training. As was covered in lecture, during training we want to minimize this function, which will \"steer\" the model in the right direction.\n* *Optimizer* — This defines how the model is updated based on the data it sees and its loss function.\n* *Metrics* — Here we can define metrics used to monitor the training and testing steps. In this example, we'll look at the *accuracy*, the fraction of the images that are correctly classified.\n\nWe'll start out by using a stochastic gradient descent (SGD) optimizer initialized with a learning rate of 0.1. Since we are performing a categorical classification task, we'll want to use the [cross entropy loss](https://www.tensorflow.org/api_docs/python/tf/keras/metrics/sparse_categorical_crossentropy).\n\nYou'll want to experiment with both the choice of optimizer and learning rate and evaluate how these affect the accuracy of the trained model. ", "_____no_output_____" ] ], [ [ "'''TODO: Experiment with different optimizers and learning rates. How do these affect\n the accuracy of the trained model? Which optimizers and/or learning rates yield\n the best performance?'''\nmodel.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=1e-1), \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])", "_____no_output_____" ] ], [ [ "### Train the model\n\nWe're now ready to train our model, which will involve feeding the training data (`train_images` and `train_labels`) into the model, and then asking it to learn the associations between images and labels. We'll also need to define the batch size and the number of epochs, or iterations over the MNIST dataset, to use during training. \n\nIn Lab 1, we saw how we can use `GradientTape` to optimize losses and train models with stochastic gradient descent. After defining the model settings in the `compile` step, we can also accomplish training by calling the [`fit`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential#fit) method on an instance of the `Model` class. We will use this to train our fully connected model\n", "_____no_output_____" ] ], [ [ "# Define the batch size and the number of epochs to use during training\nBATCH_SIZE = 64\nEPOCHS = 5\n\nmodel.fit(train_images, train_labels, batch_size=BATCH_SIZE, epochs=EPOCHS)", "Epoch 1/5\n938/938 [==============================] - 2s 2ms/step - loss: 0.5787 - accuracy: 0.8419\nEpoch 2/5\n938/938 [==============================] - 2s 2ms/step - loss: 0.2138 - accuracy: 0.9404\nEpoch 3/5\n938/938 [==============================] - 2s 2ms/step - loss: 0.1586 - accuracy: 0.9549\nEpoch 4/5\n938/938 [==============================] - 2s 2ms/step - loss: 0.1215 - accuracy: 0.9663\nEpoch 5/5\n938/938 [==============================] - 2s 2ms/step - loss: 0.1039 - accuracy: 0.9716\n" ] ], [ [ "As the model trains, the loss and accuracy metrics are displayed. With five epochs and a learning rate of 0.01, this fully connected model should achieve an accuracy of approximatley 0.97 (or 97%) on the training data.", "_____no_output_____" ], [ "### Evaluate accuracy on the test dataset\n\nNow that we've trained the model, we can ask it to make predictions about a test set that it hasn't seen before. In this example, the `test_images` array comprises our test dataset. To evaluate accuracy, we can check to see if the model's predictions match the labels from the `test_labels` array. \n\nUse the [`evaluate`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential#evaluate) method to evaluate the model on the test dataset!", "_____no_output_____" ] ], [ [ "'''TODO: Use the evaluate method to test the model!'''\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\n\nprint('Test accuracy:', test_acc)", "313/313 [==============================] - 1s 2ms/step - loss: 0.1016 - accuracy: 0.9700\nTest accuracy: 0.9700000286102295\n" ] ], [ [ "You may observe that the accuracy on the test dataset is a little lower than the accuracy on the training dataset. ** This gap between training accuracy and test accuracy is an example of *overfitting* ** , when a machine learning model performs worse on new data than on its training data. \n\nWhat is the highest accuracy you can achieve with this first fully connected model? Since the handwritten digit classification task is pretty straightforward, you may be wondering how we can do better...\n\n![Deeper...](https://i.kym-cdn.com/photos/images/newsfeed/000/534/153/f87.jpg)", "_____no_output_____" ], [ "## 1.3 Convolutional Neural Network (CNN) for handwritten digit classification", "_____no_output_____" ], [ "As we saw in lecture, convolutional neural networks (CNNs) are particularly well-suited for a variety of tasks in computer vision, and have achieved near-perfect accuracies on the MNIST dataset. We will now build a CNN composed of two convolutional layers and pooling layers, followed by two fully connected layers, and ultimately output a probability distribution over the 10 digit classes (0-9). The CNN we will be building is depicted below:\n\n![alt_text](https://raw.githubusercontent.com/aamini/introtodeeplearning/master/lab2/img/convnet_fig.png \"CNN Architecture for MNIST Classification\")", "_____no_output_____" ], [ "### Define the CNN model\n\nWe'll use the same training and test datasets as before, and proceed similarly as our fully connected network to define and train our new CNN model. To do this we will explore two layers we have not encountered before: you can use [`keras.layers.Conv2D` ](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) to define convolutional layers and [`keras.layers.MaxPool2D`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D) to define the pooling layers. Use the parameters shown in the network architecture above to define these layers and build the CNN model.", "_____no_output_____" ] ], [ [ "def build_cnn_model():\n cnn_model = tf.keras.Sequential([\n\n # TODO: Define the first convolutional layer\n tf.keras.layers.Conv2D(filters=24, kernel_size=(3,3), activation=tf.nn.relu), \n\n # TODO: Define the first max pooling layer\n tf.keras.layers.MaxPool2D(pool_size=(2,2)),\n\n # TODO: Define the second convolutional layer\n tf.keras.layers.Conv2D(filters=24, kernel_size=(3,3), activation=tf.nn.relu),\n\n # TODO: Define the second max pooling layer\n tf.keras.layers.MaxPool2D(pool_size=(2,2)),\n\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation=tf.nn.relu), #Notice the 128 is the ouput size\n\n # TODO: Define the last Dense layer to output the classification \n # probabilities. Pay attention to the activation needed a probability\n # output\n tf.keras.layers.Dense(10, activation=tf.nn.softmax) #Notice that it has to have the number of output channels\n ])\n \n return cnn_model\n \ncnn_model = build_cnn_model()\n# Initialize the model by passing some data through\ncnn_model.predict(train_images[[0]])\n# Print the summary of the layers in the model.\nprint(cnn_model.summary())", "Model: \"sequential_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 26, 26, 24) 240 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 13, 13, 24) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 11, 11, 24) 5208 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 5, 5, 24) 0 \n_________________________________________________________________\nflatten_5 (Flatten) (None, 600) 0 \n_________________________________________________________________\ndense_6 (Dense) (None, 128) 76928 \n_________________________________________________________________\ndense_7 (Dense) (None, 10) 1290 \n=================================================================\nTotal params: 83,666\nTrainable params: 83,666\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ] ], [ [ "### Train and test the CNN model\n\nNow, as before, we can define the loss function, optimizer, and metrics through the `compile` method. Compile the CNN model with an optimizer and learning rate of choice:", "_____no_output_____" ] ], [ [ "'''TODO: Define the compile operation with your optimizer and learning rate of choice'''\ncnn_model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=1e-1), loss='sparse_categorical_crossentropy', metrics=['accuracy']) # TODO\n", "_____no_output_____" ] ], [ [ "As was the case with the fully connected model, we can train our CNN using the `fit` method via the Keras API.", "_____no_output_____" ] ], [ [ "'''TODO: Use model.fit to train the CNN model, with the same batch_size and number of epochs previously used.'''\nBATCH_SIZE = 64\nEPOCHS = 5\n\ncnn_model.fit(train_images, train_labels, batch_size=BATCH_SIZE, epochs=EPOCHS)", "Epoch 1/5\n938/938 [==============================] - 3s 3ms/step - loss: 0.5692 - accuracy: 0.8222\nEpoch 2/5\n938/938 [==============================] - 2s 3ms/step - loss: 0.0788 - accuracy: 0.9764\nEpoch 3/5\n938/938 [==============================] - 3s 3ms/step - loss: 0.0530 - accuracy: 0.9835\nEpoch 4/5\n938/938 [==============================] - 3s 3ms/step - loss: 0.0413 - accuracy: 0.9876\nEpoch 5/5\n938/938 [==============================] - 3s 3ms/step - loss: 0.0357 - accuracy: 0.9894\n" ] ], [ [ "Great! Now that we've trained the model, let's evaluate it on the test dataset using the [`evaluate`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential#evaluate) method:", "_____no_output_____" ] ], [ [ "'''TODO: Use the evaluate method to test the model!'''\ntest_loss, test_acc = cnn_model.evaluate(test_images, test_labels)\n\nprint('Test accuracy:', test_acc)", "313/313 [==============================] - 1s 2ms/step - loss: 0.0388 - accuracy: 0.9864\nTest accuracy: 0.9864000082015991\n" ] ], [ [ "What is the highest accuracy you're able to achieve using the CNN model, and how does the accuracy of the CNN model compare to the accuracy of the simple fully connected network? What optimizers and learning rates seem to be optimal for training the CNN model? \n\n## Do this with WB from spacetp", "_____no_output_____" ], [ "### Make predictions with the CNN model\n\nWith the model trained, we can use it to make predictions about some images. The [`predict`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential#predict) function call generates the output predictions given a set of input samples.\n", "_____no_output_____" ] ], [ [ "predictions = cnn_model.predict(test_images)", "_____no_output_____" ] ], [ [ "With this function call, the model has predicted the label for each image in the testing set. Let's take a look at the prediction for the first image in the test dataset:", "_____no_output_____" ] ], [ [ "predictions[0]", "_____no_output_____" ] ], [ [ "As you can see, a prediction is an array of 10 numbers. Recall that the output of our model is a probability distribution over the 10 digit classes. Thus, these numbers describe the model's \"confidence\" that the image corresponds to each of the 10 different digits. \n\nLet's look at the digit that has the highest confidence for the first image in the test dataset:", "_____no_output_____" ] ], [ [ "'''TODO: identify the digit with the highest confidence prediction for the first\n image in the test dataset. '''\nprediction = # TODO\n\nprint(prediction)", "_____no_output_____" ] ], [ [ "So, the model is most confident that this image is a \"???\". We can check the test label (remember, this is the true identity of the digit) to see if this prediction is correct:", "_____no_output_____" ] ], [ [ "print(\"Label of this digit is:\", test_labels[0])\nplt.imshow(test_images[0,:,:,0], cmap=plt.cm.binary)", "_____no_output_____" ] ], [ [ "It is! Let's visualize the classification results on the MNIST dataset. We will plot images from the test dataset along with their predicted label, as well as a histogram that provides the prediction probabilities for each of the digits:", "_____no_output_____" ] ], [ [ "#@title Change the slider to look at the model's predictions! { run: \"auto\" }\n\nimage_index = 79 #@param {type:\"slider\", min:0, max:100, step:1}\nplt.subplot(1,2,1)\nmdl.lab2.plot_image_prediction(image_index, predictions, test_labels, test_images)\nplt.subplot(1,2,2)\nmdl.lab2.plot_value_prediction(image_index, predictions, test_labels)", "_____no_output_____" ] ], [ [ "We can also plot several images along with their predictions, where correct prediction labels are blue and incorrect prediction labels are grey. The number gives the percent confidence (out of 100) for the predicted label. Note the model can be very confident in an incorrect prediction!", "_____no_output_____" ] ], [ [ "# Plots the first X test images, their predicted label, and the true label\n# Color correct predictions in blue, incorrect predictions in red\nnum_rows = 5\nnum_cols = 4\nnum_images = num_rows*num_cols\nplt.figure(figsize=(2*2*num_cols, 2*num_rows))\nfor i in range(num_images):\n plt.subplot(num_rows, 2*num_cols, 2*i+1)\n mdl.lab2.plot_image_prediction(i, predictions, test_labels, test_images)\n plt.subplot(num_rows, 2*num_cols, 2*i+2)\n mdl.lab2.plot_value_prediction(i, predictions, test_labels)\n", "_____no_output_____" ] ], [ [ "## 1.4 Training the model 2.0\n\nEarlier in the lab, we used the [`fit`](https://www.tensorflow.org/api_docs/python/tf/keras/models/Sequential#fit) function call to train the model. This function is quite high-level and intuitive, which is really useful for simpler models. As you may be able to tell, this function abstracts away many details in the training call, and we have less control over training model, which could be useful in other contexts. \n\nAs an alternative to this, we can use the [`tf.GradientTape`](https://www.tensorflow.org/api_docs/python/tf/GradientTape) class to record differentiation operations during training, and then call the [`tf.GradientTape.gradient`](https://www.tensorflow.org/api_docs/python/tf/GradientTape#gradient) function to actually compute the gradients. You may recall seeing this in Lab 1 Part 1, but let's take another look at this here.\n\nWe'll use this framework to train our `cnn_model` using stochastic gradient descent.", "_____no_output_____" ] ], [ [ "# Rebuild the CNN model\ncnn_model = build_cnn_model()\n\nbatch_size = 12\nloss_history = mdl.util.LossHistory(smoothing_factor=0.95) # to record the evolution of the loss\nplotter = mdl.util.PeriodicPlotter(sec=2, xlabel='Iterations', ylabel='Loss', scale='semilogy')\noptimizer = tf.keras.optimizers.SGD(learning_rate=1e-2) # define our optimizer\n\nif hasattr(tqdm, '_instances'): tqdm._instances.clear() # clear if it exists\n\nfor idx in tqdm(range(0, train_images.shape[0], batch_size)):\n # First grab a batch of training data and convert the input images to tensors\n (images, labels) = (train_images[idx:idx+batch_size], train_labels[idx:idx+batch_size])\n images = tf.convert_to_tensor(images, dtype=tf.float32)\n\n # GradientTape to record differentiation operations\n with tf.GradientTape() as tape:\n #'''TODO: feed the images into the model and obtain the predictions'''\n logits = # TODO\n\n #'''TODO: compute the categorical cross entropy loss\n loss_value = tf.keras.backend.sparse_categorical_crossentropy() # TODO\n\n loss_history.append(loss_value.numpy().mean()) # append the loss to the loss_history record\n plotter.plot(loss_history.get())\n\n # Backpropagation\n '''TODO: Use the tape to compute the gradient against all parameters in the CNN model.\n Use cnn_model.trainable_variables to access these parameters.''' \n grads = # TODO\n optimizer.apply_gradients(zip(grads, cnn_model.trainable_variables))\n", "_____no_output_____" ] ], [ [ "## 1.5 Conclusion\nIn this part of the lab, you had the chance to play with different MNIST classifiers with different architectures (fully-connected layers only, CNN), and experiment with how different hyperparameters affect accuracy (learning rate, etc.). The next part of the lab explores another application of CNNs, facial detection, and some drawbacks of AI systems in real world applications, like issues of bias. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
ecfce67bdb6e710f8c911be0a7327e857782ffc6
66,792
ipynb
Jupyter Notebook
OCRTesseract.ipynb
rahul8c/Generative-Adversarial-Networks-Projects
55a69fe1cb08fb47cec597246bd4be0729060a3a
[ "MIT" ]
null
null
null
OCRTesseract.ipynb
rahul8c/Generative-Adversarial-Networks-Projects
55a69fe1cb08fb47cec597246bd4be0729060a3a
[ "MIT" ]
null
null
null
OCRTesseract.ipynb
rahul8c/Generative-Adversarial-Networks-Projects
55a69fe1cb08fb47cec597246bd4be0729060a3a
[ "MIT" ]
null
null
null
231.114187
49,527
0.895422
[ [ [ "<a href=\"https://colab.research.google.com/github/rahul8c/Generative-Adversarial-Networks-Projects/blob/master/OCRTesseract.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!sudo apt install tesseract-ocr", "Reading package lists... Done\nBuilding dependency tree \nReading state information... Done\nThe following package was automatically installed and is no longer required:\n libnvidia-common-430\nUse 'sudo apt autoremove' to remove it.\nThe following additional packages will be installed:\n tesseract-ocr-eng tesseract-ocr-osd\nThe following NEW packages will be installed:\n tesseract-ocr tesseract-ocr-eng tesseract-ocr-osd\n0 upgraded, 3 newly installed, 0 to remove and 25 not upgraded.\nNeed to get 4,795 kB of archives.\nAfter this operation, 15.8 MB of additional disk space will be used.\nGet:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 tesseract-ocr-eng all 4.00~git24-0e00fe6-1.2 [1,588 kB]\nGet:2 http://archive.ubuntu.com/ubuntu bionic/universe amd64 tesseract-ocr-osd all 4.00~git24-0e00fe6-1.2 [2,989 kB]\nGet:3 http://archive.ubuntu.com/ubuntu bionic/universe amd64 tesseract-ocr amd64 4.00~git2288-10f4998a-2 [218 kB]\nFetched 4,795 kB in 1s (4,616 kB/s)\ndebconf: unable to initialize frontend: Dialog\ndebconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76, <> line 3.)\ndebconf: falling back to frontend: Readline\ndebconf: unable to initialize frontend: Readline\ndebconf: (This frontend requires a controlling tty.)\ndebconf: falling back to frontend: Teletype\ndpkg-preconfigure: unable to re-open stdin: \nSelecting previously unselected package tesseract-ocr-eng.\n(Reading database ... 134443 files and directories currently installed.)\nPreparing to unpack .../tesseract-ocr-eng_4.00~git24-0e00fe6-1.2_all.deb ...\nUnpacking tesseract-ocr-eng (4.00~git24-0e00fe6-1.2) ...\nSelecting previously unselected package tesseract-ocr-osd.\nPreparing to unpack .../tesseract-ocr-osd_4.00~git24-0e00fe6-1.2_all.deb ...\nUnpacking tesseract-ocr-osd (4.00~git24-0e00fe6-1.2) ...\nSelecting previously unselected package tesseract-ocr.\nPreparing to unpack .../tesseract-ocr_4.00~git2288-10f4998a-2_amd64.deb ...\nUnpacking tesseract-ocr (4.00~git2288-10f4998a-2) ...\nSetting up tesseract-ocr-osd (4.00~git24-0e00fe6-1.2) ...\nSetting up tesseract-ocr-eng (4.00~git24-0e00fe6-1.2) ...\nSetting up tesseract-ocr (4.00~git2288-10f4998a-2) ...\nProcessing triggers for man-db (2.8.3-2ubuntu0.1) ...\n" ], [ "!pip install pytesseract", "Collecting pytesseract\n Downloading https://files.pythonhosted.org/packages/df/4e/42c54b4344cbcb392d949ffb0b1c1e95f03ceaa6a354c8d3aafcd470592e/pytesseract-0.3.2.tar.gz\nRequirement already satisfied: Pillow in /usr/local/lib/python2.7/dist-packages (from pytesseract) (4.3.0)\nRequirement already satisfied: olefile in /usr/local/lib/python2.7/dist-packages (from Pillow->pytesseract) (0.46)\nBuilding wheels for collected packages: pytesseract\n Building wheel for pytesseract (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for pytesseract: filename=pytesseract-0.3.2-py2.py3-none-any.whl size=13373 sha256=c90812aa7b750aaf4c244b17a0576a09d18a1a48fbe58f1443bb29dd3a89456c\n Stored in directory: /root/.cache/pip/wheels/c2/60/55/ec507bce8e8ccb516954accf661ee60c8b34198fafdfb81872\nSuccessfully built pytesseract\nInstalling collected packages: pytesseract\nSuccessfully installed pytesseract-0.3.2\n" ], [ "import pytesseract\nimport shutil\nimport os\nimport random\ntry:\n from PIL import Image\nexcept ImportError:\n import Image", "_____no_output_____" ], [ "from IPython.display import Image\nImage('car2.jpg')", "_____no_output_____" ], [ "from google.colab import files\n\nuploaded = files.upload()", "_____no_output_____" ], [ "extractedInformation = pytesseract.image_to_string(Image.open('car2.jpg'))", "_____no_output_____" ], [ "print(extractedInformation)", "APO9 BN 7886\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
ecfcf399d49359ce4d2d00d9fe589a8682f652bb
188,513
ipynb
Jupyter Notebook
Python_Stock/Portfolio_Analysis.ipynb
chunsj/Stock_Analysis_For_Quant
5f28ef9537885a695245d26f3010592a29d45a34
[ "MIT" ]
962
2019-07-17T09:57:41.000Z
2022-03-29T01:55:20.000Z
Python_Stock/Portfolio_Analysis.ipynb
chunsj/Stock_Analysis_For_Quant
5f28ef9537885a695245d26f3010592a29d45a34
[ "MIT" ]
5
2020-04-29T16:54:30.000Z
2022-02-10T02:57:30.000Z
Python_Stock/Portfolio_Analysis.ipynb
chunsj/Stock_Analysis_For_Quant
5f28ef9537885a695245d26f3010592a29d45a34
[ "MIT" ]
286
2019-08-04T10:37:58.000Z
2022-03-28T06:31:56.000Z
211.100784
136,486
0.885859
[ [ [ "# Portfolio Analysis", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# fix_yahoo_finance is used to fetch data \nimport fix_yahoo_finance as yf\nyf.pdr_override()", "_____no_output_____" ], [ "# input\nsymbols = ['AAPL','MSFT','AMD','NVDA']\nstart = '2012-01-01'\nend = '2019-09-11'\n\n# Read data \ndataset = yf.download(symbols,start,end)['Adj Close']\n\n# View Columns\ndataset.head()", "[*********************100%***********************] 4 of 4 downloaded\n" ], [ "# Calculate Daily Returns\nreturns = dataset.pct_change()", "_____no_output_____" ], [ "returns = returns.dropna()", "_____no_output_____" ], [ "returns.head()", "_____no_output_____" ], [ "# Calculate mean returns\nmeanDailyReturns = returns.mean()\nprint(meanDailyReturns)", "AAPL 0.000878\nAMD 0.001575\nMSFT 0.001044\nNVDA 0.001652\ndtype: float64\n" ], [ "# Calculate std returns\nstdDailyReturns = returns.std()\nprint(stdDailyReturns)", "AAPL 0.016245\nAMD 0.037615\nMSFT 0.014470\nNVDA 0.023808\ndtype: float64\n" ], [ "# Define weights for the portfolio\nweights = np.array([0.5, 0.2, 0.2, 0.1])", "_____no_output_____" ], [ "# Calculate the covariance matrix on daily returns\ncov_matrix = (returns.cov())*250\nprint (cov_matrix)", " AAPL AMD MSFT NVDA\nAAPL 0.065974 0.038292 0.025152 0.034493\nAMD 0.038292 0.353730 0.036180 0.094201\nMSFT 0.025152 0.036180 0.052348 0.037223\nNVDA 0.034493 0.094201 0.037223 0.141710\n" ], [ "# Calculate expected portfolio performance\nportReturn = np.sum(meanDailyReturns*weights)", "_____no_output_____" ], [ "# Print the portfolio return\nprint(portReturn)", "0.00112807303295\n" ], [ "# Create portfolio returns column\nreturns['Portfolio'] = returns.dot(weights)", "_____no_output_____" ], [ "returns.head()", "_____no_output_____" ], [ "# Calculate cumulative returns\ndaily_cum_ret=(1+returns).cumprod()\nprint(daily_cum_ret.tail())", " AAPL AMD MSFT NVDA Portfolio\nDate \n2019-09-04 4.080211 5.647810 6.211842 13.042339 6.920307\n2019-09-05 4.159985 5.748175 6.321067 13.890912 7.081916\n2019-09-06 4.159595 5.576642 6.278189 13.806672 7.025415\n2019-09-09 4.177344 5.565693 6.206877 13.949646 7.028960\n2019-09-10 4.226692 5.516423 6.141883 14.156765 7.053748\n" ], [ "returns['Portfolio'].hist()\nplt.show()", "_____no_output_____" ], [ "import matplotlib.dates\n\n# Plot the portfolio cumulative returns only\nfig, ax = plt.subplots()\nax.plot(daily_cum_ret.index, daily_cum_ret.Portfolio, color='purple', label=\"portfolio\")\nax.xaxis.set_major_locator(matplotlib.dates.YearLocator())\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "# Print the mean\nprint(\"mean : \", returns['Portfolio'].mean()*100)\n\n# Print the standard deviation\nprint(\"Std. dev: \", returns['Portfolio'].std()*100)\n\n# Print the skewness\nprint(\"skew: \", returns['Portfolio'].skew())\n\n# Print the kurtosis\nprint(\"kurt: \", returns['Portfolio'].kurtosis())", "mean : 0.11280730329520924\nStd. dev: 1.5289593176510718\nskew: -0.133433702248\nkurt: 2.96049017087\n" ], [ "# Calculate the standard deviation by taking the square root\nport_standard_dev = np.sqrt(np.dot(weights.T, np.dot(weights, cov_matrix)))\n\n# Print the results \nprint(str(np.round(port_standard_dev, 4) * 100) + '%')", "24.17%\n" ], [ "# Calculate the portfolio variance\nport_variance = np.dot(weights.T, np.dot(cov_matrix, weights))\n\n# Print the result\nprint(str(np.round(port_variance, 4) * 100) + '%')", "5.84%\n" ], [ "# Calculate total return and annualized return from price data \ntotal_return = (returns['Portfolio'][-1] - returns['Portfolio'][0]) / returns['Portfolio'][0]\n\n# Annualize the total return over 6 year \nannualized_return = ((total_return + 1)**(1/6))-1", "_____no_output_____" ], [ "# Calculate annualized volatility from the standard deviation\nvol_port = returns['Portfolio'].std() * np.sqrt(250)", "_____no_output_____" ], [ "# Calculate the Sharpe ratio \nrf = 0.01\nsharpe_ratio = ((annualized_return - rf) / vol_port)\nprint (sharpe_ratio)", "-0.554238786819\n" ] ], [ [ "If the analysis results in a negative Sharpe ratio, it either means the risk-free rate is greater than the portfolio's return, or the portfolio's return is expected to be negative. ", "_____no_output_____" ] ], [ [ "# Create a downside return column with the negative returns only\ntarget = 0\ndownside_returns = returns.loc[returns['Portfolio'] < target]\n\n# Calculate expected return and std dev of downside\nexpected_return = returns['Portfolio'].mean()\ndown_stdev = downside_returns.std()\n\n# Calculate the sortino ratio\nrf = 0.01\nsortino_ratio = (expected_return - rf)/down_stdev\n\n# Print the results\nprint(\"Expected return: \", expected_return*100)\nprint('-' * 50)\nprint(\"Downside risk:\")\nprint(down_stdev*100)\nprint('-' * 50)\nprint(\"Sortino ratio:\")\nprint(sortino_ratio)", "Expected return: 0.11280730329520924\n--------------------------------------------------\nDownside risk:\nAAPL 1.363155\nAMD 2.957687\nMSFT 1.292771\nNVDA 2.036317\nPortfolio 1.087610\ndtype: float64\n--------------------------------------------------\nSortino ratio:\nAAPL -0.650838\nAMD -0.299962\nMSFT -0.686272\nNVDA -0.435685\nPortfolio -0.815727\ndtype: float64\n" ], [ "# Calculate the max value \nroll_max = returns['Portfolio'].rolling(center=False,min_periods=1,window=252).max()\n\n# Calculate the daily draw-down relative to the max\ndaily_draw_down = returns['Portfolio']/roll_max - 1.0\n\n# Calculate the minimum (negative) daily draw-down\nmax_daily_draw_down = daily_draw_down.rolling(center=False,min_periods=1,window=252).min()\n\n# Plot the results\nplt.figure(figsize=(15,15))\nplt.plot(returns.index, daily_draw_down, label='Daily drawdown')\nplt.plot(returns.index, max_daily_draw_down, label='Maximum daily drawdown in time-window')\nplt.legend()\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
ecfd1310313c86ac7912b97954a8f9c8233277d4
44,004
ipynb
Jupyter Notebook
code/09_variance_swaps.ipynb
pvkraju80/leo
f6ed6f4ee6eb34c47581d40d4d3fea69f42140f3
[ "CNRI-Python" ]
99
2016-11-02T14:29:41.000Z
2022-03-02T23:53:02.000Z
code/09_variance_swaps.ipynb
pvkraju80/leo
f6ed6f4ee6eb34c47581d40d4d3fea69f42140f3
[ "CNRI-Python" ]
null
null
null
code/09_variance_swaps.ipynb
pvkraju80/leo
f6ed6f4ee6eb34c47581d40d4d3fea69f42140f3
[ "CNRI-Python" ]
86
2016-11-05T15:39:08.000Z
2022-03-14T04:37:17.000Z
26.333932
763
0.557972
[ [ [ "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br><br><br>", "_____no_output_____" ], [ "# Listed Volatility and Variance Derivatives\n\n**Wiley Finance (2017)**\n\nDr. Yves J. Hilpisch | The Python Quants GmbH\n\nhttp://tpq.io | [@dyjh](http://twitter.com/dyjh) | http://books.tpq.io\n\n<img src=\"http://hilpisch.com/../images/lvvd_cover.png\" alt=\"Derivatives Analytics with Python\" width=\"30%\" align=\"left\" border=\"0\">", "_____no_output_____" ], [ "# Realized Variance and Variance Swaps", "_____no_output_____" ], [ "## Introdution", "_____no_output_____" ], [ "This chapter discusses basic notions and concepts needed in the context of variance swaps and futures. It covers among others the following topics:\n\n* **realized variance**: the basic measure on which variance swaps and variance futures are defined\n* **variance swap**: the definition of a variance swap and some numerical examples\n* **mark-to-market**: the mark-to-market valuation approach for a variance swap\n* **variance swap on EURO STOXX 50**: simple re-calculation of a variance swap given historical data\n* **variance vs. volatility**: major differences between the two measures", "_____no_output_____" ], [ "## Realized Variance", "_____no_output_____" ], [ "Historical or realized variance $\\sigma^2$ generally is defined as", "_____no_output_____" ], [ "$$\\sigma^2 \\equiv \\frac{252}{N} \\cdot \\sum^{N}_{n=1}R_n^2$$\n\nwhere, for a time series $S_n, n=0, 1, ..., N$, the log returns are given by\n\n$$R_n \\equiv \\log \\frac{S_{n}}{S_{n-1}}$$\n\nHere, it is assumed that there are 252 trading days per year and that the average daily return is zero. The simple application of these definitions yields values as decimals. Scaling by a factor of $100^2=10000$ gives values in percent.\n\n$$\\sigma^2 \\equiv 10000 \\cdot \\frac{252}{N} \\cdot \\sum^{N}_{n=1}R_n^2$$\n\nTo simplify notation, we use the notation $\\sigma^2$ instead of $\\hat{\\sigma}^2$ for the realized variance from here on.", "_____no_output_____" ], [ "The concept of realized variance is easily illustrated by the use of historical data for the EURO STOXX 50 stock index. To this end, we read data from the index provider's Web site http://www.stoxx.com with Python and the pandas library. For details on using the pandas library for interactive financial analytics see chapter _Python Introduction_ or refer to Hilpisch (2018): _Python for Finance_. As usual, we start with some Python library imports.", "_____no_output_____" ] ], [ [ "import math\nimport numpy as np\nimport pandas as pd", "_____no_output_____" ] ], [ [ "First, we need the complete URL of the data set.", "_____no_output_____" ] ], [ [ "url = 'https://hilpisch.com/lvvd_eikon_eod_data.csv'", "_____no_output_____" ] ], [ [ "Second, we read the data with the pandas library from that source.", "_____no_output_____" ] ], [ [ "es = pd.read_csv(url, index_col=0, parse_dates=True)", "_____no_output_____" ] ], [ [ "Let us inspect the most final five data rows.", "_____no_output_____" ] ], [ [ "es.tail()", "_____no_output_____" ] ], [ [ "Third, we select the EURO STOXX 50 index data from the just downloaded and imported data set, i.e. the data sub-set for the symbol SX5E. Using this sub-set, we generate a new pandas ``DataFrame`` object to store the data. The historical time series of daily closing levels of the EURO STOXX 50 can then easily be inspected by a call of the ``plot`` method. The following figure shows the graphical output.", "_____no_output_____" ] ], [ [ "from pylab import mpl, plt\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\ndata = pd.DataFrame({'SX5E': es['.STOXX50E']})\ndata.plot(figsize=(10, 6));", "_____no_output_____" ] ], [ [ "<p style=\"font-family: monospace;\">Historical index levels of EURO STOXX 50 index.", "_____no_output_____" ], [ "Fourth, the log returns are calculated (in vectorized fashion, i.e. simultaneously over the whole time series) and stored as a new column in the pandas ``DataFrame`` object.", "_____no_output_____" ] ], [ [ "data['R_n'] = np.log(data['SX5E'] / data['SX5E'].shift(1))", "_____no_output_____" ] ], [ [ "Let us inspect the last five data rows of this new DataFrame object.", "_____no_output_____" ] ], [ [ "data.tail()", "_____no_output_____" ] ], [ [ "In the fifth step, we calculate the realized variance, again in vectorized fashion. With the following code we calculate the realized variance for every single date of the time series.", "_____no_output_____" ] ], [ [ "## np.cumsum calculates the element-wise cumulative sum of an array/time series\n## np.arange(N) gives an array of the form [0, 1, ..., N-1]\ndata['sigma**2'] = 10000 * 252 * (np.cumsum(data['R_n'] ** 2) \n / np.arange(len(data)))", "_____no_output_____" ] ], [ [ "The third column of the ``DataFrame`` object now contains the realized variance.", "_____no_output_____" ] ], [ [ "data.tail()", "_____no_output_____" ] ], [ [ "In the sixth and final step, one can now compare the index level time series with the realized variance over time graphically &mdash; see the following figure.", "_____no_output_____" ] ], [ [ "data[['SX5E', 'sigma**2']].plot(subplots=True,\n figsize=(10, 8),\n grid=True);", "_____no_output_____" ] ], [ [ "<p style=\"font-family: monospace;\">Historical index levels of EURO STOXX 50 index and realized variance (long-term).", "_____no_output_____" ], [ "Now let us implement the same approach for a shorter, recent period of time, i.e. the second half of the year 2015. The realized variance has to be re-calculated since there is now a new starting date.", "_____no_output_____" ] ], [ [ "## select time series data with date later/earlier than given dates\nshort = data[['SX5E', 'R_n']][(data.index > '2015-7-1')\n & (data.index <= '2015-12-31')]\n\n## calculate the realized variance in percent values\nshort['sigma**2'] = 10000 * 252 * (np.cumsum(short['R_n'] ** 2)\n / np.arange(len(short)))\n", "_____no_output_____" ] ], [ [ "The first five rows of the new ``DataFrame`` object:", "_____no_output_____" ] ], [ [ "short.head()", "_____no_output_____" ] ], [ [ "A graphical comparison of the EUROS STOXX 50 time series data with its realized variance for the shorter time frame is displayed in the following figure.", "_____no_output_____" ] ], [ [ "short[['SX5E', 'sigma**2']].plot(subplots=True,\n figsize=(10, 8),\n grid=True);", "_____no_output_____" ] ], [ [ "<p style=\"font-family: monospace;\">Historical index levels of EURO STOXX 50 index and realized variance (short-term).", "_____no_output_____" ], [ "## Variance Swaps", "_____no_output_____" ], [ "Nowadays, variance swaps are popular financial instruments for volatility/variance trading and hedging purposes. See, for instance, the paper Bossu et al. (2005) for an overview of the features and characteristics of variance swaps.", "_____no_output_____" ], [ "### Definition of a Variance Swap", "_____no_output_____" ], [ "A variance swap is a financial instrument that allows investors to trade future realized variance against current implied volatility (the \"strike\"). The characteristics and payoff of a variance swap are more like those of a forward contract than those of a typical swap on interest rates, currencies, equities, etc.\n\nThe payoff $h_T$ of a variance swap maturing at some future date $T$ is\n\n$$h_T = \\sigma_{0,T}^2 - \\sigma_K^2$$\n\nwith $\\sigma_K^2$ being the variance strike and $\\sigma_K$ the volatility strike.", "_____no_output_____" ], [ "At inception, i.e. at $t=0$, the volatility strike is set such that the value of the variance swap is zero. This implies that the volatility strike is set equal to the implied volatility $\\sigma_i(0,T)$ for the maturity $T$.", "_____no_output_____" ], [ "### Numerical Example", "_____no_output_____" ], [ "Consider a Black-Scholes-Merton (1973) world with a geometric Brownian motion driving uncertainty for the index level of relevance (cf. Black and Scholes (1973) and Merton (1973)). The risk-neutral stochastic differential equation (SDE) in this model (without dividends) is given by:", "_____no_output_____" ], [ "$$\ndS_t = r S_t dt + \\sigma S_t dZ_t\n$$\n\n$S_t$ is the index level at time $t$, $r$ the constant risk-less short rate, $\\sigma$ the instantaneous volatility and $Z_t$ a standard Brownian motion. For a comprehensive treatment of this and other continuous time financial models refer, for example, to Björk (2009).", "_____no_output_____" ], [ "Instantaneous volatility (and variance) in this model world is constant which makes implied volatility also constant, say $\\sigma_t =\\sigma_i = \\sigma = 0.2$. Given, for example, a Monte Carlo simulation of this model, realized variance might deviate from $\\sigma^2 = 0.2^2 = 0.04$. Let us implement such a Monte Carlo simulation for the model. An Euler discretization scheme for the above SDE is given for $t \\geq \\Delta t$ by:\n\n$$\nS_t = S_{t-\\Delta t} \\exp \\left( \\left( r -\\frac{\\sigma^2}{2}\\right) \\Delta t + \\sigma \\sqrt{\\Delta t} z_t \\right)\n$$\n\nwith $\\Delta t$ being the fixed time interval used for the discretization and $z_t$ a standard normally distributed random variable.", "_____no_output_____" ], [ "A Python implementation might look like follows (refer to Hilpisch (2018) for details on Monte Carlo simulation with Python) .", "_____no_output_____" ] ], [ [ "import sys\nsys.path.append('./scripts')", "_____no_output_____" ], [ "import variance_swaps", "_____no_output_____" ], [ "variance_swaps.generate_path??", "_____no_output_____" ] ], [ [ "Using this function and providing numerical parameters returns a pandas ``DataFrame`` with a single simulated path for the model. A sample path is shown in the following figure.", "_____no_output_____" ] ], [ [ "S0 = 100 # initial index level\nr = 0.005 # risk-less short rate\nsigma = 0.2 # instantaneous volatility\nT = 1.0 # maturity date\nM = 50 # number of time intervals\n\ndata = variance_swaps.generate_path(S0, r, sigma, T, M, seed=100000)\ndata.plot(figsize=(10, 5));", "_____no_output_____" ] ], [ [ "<p style=\"font-family: monospace;\">Sample path based on geometric Brownian motion.", "_____no_output_____" ], [ "Given such a simulated path, one can calculate realized variance over time in the same fashion as above for the EURO STOXX 50 index.", "_____no_output_____" ] ], [ [ "data['R_t'] = np.log(data['index'] / data['index'].shift(1))\n## scaling now by M / T since returns are not necessarily daily returns\ndata['sigma**2'] = 10000 * M / T * (np.cumsum(data['R_t'] ** 2)\n / np.arange(len(data)))\ndata.tail()", "_____no_output_____" ] ], [ [ "The following figure shows the results graphically.", "_____no_output_____" ] ], [ [ "data[['index', 'sigma**2']].plot(subplots=True,\n figsize=(10, 8),\n grid=True);", "_____no_output_____" ] ], [ [ "<p style=\"font-family: monospace;\">Geometric Brownian motion sample path with realized variance.", "_____no_output_____" ], [ "In this case, the payoff $h_T$ of the variance swap at maturity is:", "_____no_output_____" ] ], [ [ "data['sigma**2'].iloc[-1] - 20 ** 2", "_____no_output_____" ] ], [ [ "In general, variance swaps have a notional that differs from a value of 1, i.e. the above value would have to be multiplied by a notional not equal to 1. It is market practice to define the variance swap notional in volatility terms:\n\n$$\nNotional = \\frac{VegaNotional}{2 \\cdot Strike}\n$$\n\nThis can be done consistently due to the following relationship for a derivative instrument $f$ depending on some underlying $S$ with volatility $\\sigma$ (and satisfying further technical assumptions):\n\n\n\\begin{eqnarray*}\n\\frac{\\partial f}{\\partial \\sigma} &=& \\frac{\\partial f}{\\partial (\\sigma^2)} \\cdot 2\\sigma \\\\\n\\Leftrightarrow \\frac{\\partial f}{\\partial (\\sigma^2)} &=& \\frac{\\frac{\\partial f}{\\partial \\sigma}}{2\\sigma}\n\\end{eqnarray*}\n", "_____no_output_____" ], [ "Say, we want a Vega notional of 100,000 currency units, i.e. we want a payoff of 100,000 currency units per volatility point difference (e.g. when realized volatility is 1 percentage point above the volatility strike). The variance notional then is:\n\n$$\nNotional = \\frac{100000}{2 \\cdot 20} = 2500\n$$", "_____no_output_____" ] ], [ [ "Notional = 100000. / (2 * 20)\nNotional", "_____no_output_____" ] ], [ [ "Given this value for the variance notional, the payoff of the variance swap in the above numerical example would be:", "_____no_output_____" ] ], [ [ "Notional * (data['sigma**2'].iloc[-1] - 20 ** 2)", "_____no_output_____" ] ], [ [ "### Mark-to-Market", "_____no_output_____" ], [ "What about the value of a variance swap over time? A major advantage of working with variance (instead of volatility) is that variance is additive over time (when a mean of about zero is assumed). This gives rise to the following present value of a variance swap at time $t$, for a constant short rate $r$.\n\n$$\nV_t = Notional \\cdot e^{-r(T-t)} \\cdot \\left( \\frac{t \\cdot \\sigma_{0,t}^2 + (T-t) \\cdot \\sigma_i^2(t,T)}{T}-\\sigma_K^2 \\right) \n$$", "_____no_output_____" ], [ "The major component of the mark-to-market value of the variance swap is the time weighted average of realized variance $\\sigma_{0,t}^2$ up until time $t$ and implied variance $\\sigma_i^2(t,T)$ for the remaining life time from $t$ onwards.\n\nIn the model economy, $\\sigma_i^2(t,T)=\\sigma_K^2=\\sigma^2=400$. Therefore:\n\n$$\nV_t = Notional \\cdot e^{-r(T-t)} \\cdot \\left( \\frac{t \\cdot \\sigma_{0,t}^2 + (T-t) \\cdot 400}{T} - 400 \\right) \n$$\n\nFor $t=0$, this obviously gives $V_t = 0$ as desired.", "_____no_output_____" ], [ "This is readily implemented in Python given that we already have realized variance in a pandas ``DataFrame`` object. We calculate it again in vectorized fashion for $t=0, \\Delta t, 2\\Delta t..., T$.", "_____no_output_____" ] ], [ [ "dt = T / M\nt = np.arange(M + 1) * dt\nt\nsigma_K = 20\ndata['V_t'] = Notional * np.exp(-r * (T - t)) * ((t * data['sigma**2']\n + (T - t) * sigma_K ** 2) / T - sigma_K ** 2) \ndata.tail()", "_____no_output_____" ] ], [ [ "Graphically, we get the result as presented in the following figure.", "_____no_output_____" ] ], [ [ "data[['index', 'sigma**2', 'V_t']].plot(subplots=True,\n figsize=(10, 8),\n grid=True);", "_____no_output_____" ] ], [ [ "<p style=\"font-family: monospace;\">Geometric Brownian motion sample path with realized variance and variance swap mark-to-market values.", "_____no_output_____" ], [ "### Vega Sensitivity", "_____no_output_____" ], [ "What is the sensitivity of the mark-to-market value of a variance swap with regard to implied volatility? Recall that the value itself is given by\n\n$$\nV_t = Notional \\cdot e^{-r(T-t)} \\cdot \\left( \\frac{t \\cdot \\sigma_{0,t}^2 + (T-t) \\cdot \\sigma_i^2(t,T)}{T}-\\sigma_K^2 \\right)\n$$\n\nDifferentiation with respect to $\\sigma_i$ gives a Vega of\n\n$$\nVega_t = \\frac{\\partial V_t}{\\partial\\sigma_i} = Notional \\cdot e^{-r(T-t)} \\cdot \\frac{T-t}{T} \\cdot2 \\sigma_i(t,T) \n$$\n\nAt inception of the variance swap, we have a Vega of \n\n\n\\begin{eqnarray*}\nVega_0 &=& \\frac{\\partial V_0}{\\partial\\sigma_i} \\\\\n &=& \\frac{VegaNotional}{2 \\cdot \\sigma_i(0,T)} \\cdot e^{-r(T-t)} \\cdot \\frac{T-t}{T} \\cdot2 \\sigma_i(0,T) \\\\\n &=& e^{-rT} \\cdot VegaNotional\n\\end{eqnarray*}\n\n\nIn this case, Vega equals the discounted Vega notional. For general $t$, we get\n\n\\begin{eqnarray*}\nVega_t &=& \\frac{\\partial V_t}{\\partial\\sigma_i} \\\\\n &=& \\frac{VegaNotional}{2 \\cdot \\sigma_i(t,T)} \\cdot e^{-r(T-t)} \\cdot \\frac{T-t}{T} \\cdot2 \\sigma_i(t,T) \\\\\n &=& e^{-r(T-t)} \\cdot VegaNotional \\cdot \\frac{T-t}{T}\n\\end{eqnarray*}\n\nThis illustrates that Vega sensitivity diminishes over time and that it is proportional to the time-to-maturity.", "_____no_output_____" ], [ "### Variance Swap on the EURO STOXX 50", "_____no_output_____" ], [ "We are now ready to do a historical re-calculation of a variance swap on the EURO STOXX 50. We will re-calculate a variance swap during June 2015. To this end we also use VSTOXX sub-index data for the shortest maturity available which provides us with a time series for the correct implied volatilities.", "_____no_output_____" ], [ "EURO STOXX 50 data is already available.", "_____no_output_____" ] ], [ [ "es.info()", "_____no_output_____" ] ], [ [ "The VSTOXX data can be read from the same source (see chapter _Data Analysis and Strategies_).", "_____no_output_____" ] ], [ [ "url = 'https://hilpisch.com/vstoxx_eikon_eod_data.csv'", "_____no_output_____" ], [ "vs = pd.read_csv(url, index_col=0, parse_dates=True)", "_____no_output_____" ], [ "vs.info()", "_____no_output_____" ] ], [ [ "The data column `.V6I1` contains the index values (= implied volatility) for the neareast option series maturity available (i.e within a maximum of one month). For example, on the 1st of June 2015, the index values represent implied volatilities for the maturity on the third Friday in June 2015, i.e. the 19th of June. Maturity $T$ then is:", "_____no_output_____" ] ], [ [ "## 15 trading days\nT = 15.", "_____no_output_____" ] ], [ [ "The variance swap we want to re-calculate should start on 1st of June 2015 and shall have a maturity until the 19th of June. It shall have a Vega notional of 100,000 EUR.", "_____no_output_____" ], [ "First, let us select and collect the data needed from the available data sets.", "_____no_output_____" ] ], [ [ "data = pd.DataFrame(es['.STOXX50E'][(es.index > '2015-5-31')\n & (es.index < '2015-6-20')])\ndata.columns = ['SX5E']", "_____no_output_____" ], [ "data['V6I1'] = vs['.V6I1'][(vs.index > '2015-5-31')\n & (vs.index < '2015-6-20')]", "_____no_output_____" ] ], [ [ "The new data set looks as follows. Note that the VSTOXX sub-index is only available up until two days before the maturity date.", "_____no_output_____" ] ], [ [ "data", "_____no_output_____" ] ], [ [ "We forward fill the `NaN` values since for the vectorized calculations to follow we want to use these data points but they will have a negligible or zero influence anyway.", "_____no_output_____" ] ], [ [ "data = data.fillna(method='ffill')", "_____no_output_____" ] ], [ [ "We save the data set for later re-use.", "_____no_output_____" ] ], [ [ "h5 = pd.HDFStore('./data/SX5E_V6I1.h5')\nh5['SX5E_V6I1'] = data\nh5.close()", "_____no_output_____" ] ], [ [ "The implied volatility on 1st of June was 25.871%. This gives rise to a variance swap strike of $\\sigma_K^2=25.871^2=669.31$. For a Vega notional of 100,000, the variance notional therefore is\n\n$$Notional=\\frac{100000}{2 \\cdot 25.871} = 1932.67$$", "_____no_output_____" ] ], [ [ "data['V6I1'][0]\nsigma_K = data['V6I1'][0]\nNotional = 100000 / (2. * sigma_K)\nNotional", "_____no_output_____" ] ], [ [ "Three time series have to be calculated now:\n\n* log returns of the EURO STOXX 50 index\n* realized variance of the EURO STOXX 50 index\n* mark-to-market values of the variance swap\n\nFirst, the log returns.", "_____no_output_____" ] ], [ [ "data['R_t'] = np.log(data['SX5E'] / data['SX5E'].shift(1))", "_____no_output_____" ] ], [ [ "Second, the realized variance which we scale by a factor of 10,000 to end up with percent values and not decimal values.", "_____no_output_____" ] ], [ [ "data['sigma**2'] = 10000 * 252 * (np.cumsum(data['R_t'] ** 2)\n / np.arange(len(data)))", "_____no_output_____" ] ], [ [ "Third, the mark-to-market values. We start with the array of elapsed days.", "_____no_output_____" ] ], [ [ "t = np.arange(1, 16)\nt", "_____no_output_____" ] ], [ [ "We assume a fixed short rate of 0.1%.", "_____no_output_____" ] ], [ [ "r = 0.001\ndata['V_t'] = np.exp(-r * (T - t) / 365.) * ((t * data['sigma**2']\n + (T - t) * data['V6I1'] ** 2) / T - sigma_K ** 2) ", "_____no_output_____" ] ], [ [ "The initial value of the variance swap is zero.", "_____no_output_____" ] ], [ [ "data['V_t'].loc['2015-06-01'] = 0.0", "_____no_output_____" ] ], [ [ "The complete results data set is given below.", "_____no_output_____" ] ], [ [ "data", "_____no_output_____" ] ], [ [ "The payoff of the variance swap at maturity given the variance notional then is:", "_____no_output_____" ] ], [ [ "Notional * data['V_t'][-1]", "_____no_output_____" ] ], [ [ "Finally, a plot of the major results is presented in the following figure.", "_____no_output_____" ] ], [ [ "data[['SX5E', 'sigma**2', 'V_t']].plot(subplots=True,\n figsize=(10, 8));", "_____no_output_____" ] ], [ [ "<p style=\"font-family: monospace;\">EURO STOXX 50 historical index levels with realized variance and futures prices.", "_____no_output_____" ], [ "We save the data for use in the next chapter.", "_____no_output_____" ] ], [ [ "h5 = pd.HDFStore('./data/var_data.h5', 'a')\nh5['var_swap'] = data\nh5.close()", "_____no_output_____" ] ], [ [ "## Variance vs. Volatility", "_____no_output_____" ], [ "Both variance and volatility are tradable asset classes. The following sub-sections discuss some differences between the two measures of variability and the two asset classes, respectively. See also Bennett and Gil (2012) on this topic.", "_____no_output_____" ], [ "### Squared Variations", "_____no_output_____" ], [ "Squared variations are in many application scenarios the better measure for variability compared to simple variations. By squaring variations, one makes sure that variations do not cancel each other out. Since volatility is generally defined as the square root of variance, both measures avoid the cancelling of positive and negative variations.", "_____no_output_____" ], [ "### Additivity in Time", "_____no_output_____" ], [ "Although both volatility and variance avoid the cancelling out of variations, there is a major difference between both when it comes to additivity. While variance is additive (linear) in time, volatility is convex (non-linear) in time.\n\nAssume we have $N$ return observations and assume $0<M<N$. We then have:", "_____no_output_____" ], [ "\n\\begin{eqnarray*}\n\\sigma^2 &\\equiv& \\frac{252}{N} \\cdot \\sum^{N}_{n=1}R_n^2 \\\\\n &=& \\frac{252}{N} \\cdot \\left( \\sum^{M}_{n=1}R_n^2 + \\sum^{N}_{n=M+1}R_n^2 \\right) \\\\\n &=& \\frac{252}{N} \\cdot \\sum^{M}_{n=1}R_n^2 + \\frac{252}{N} \\cdot \\sum^{N}_{n=M+1}R_n^2 \\\\\n &\\equiv& \\sigma_1^2 + \\sigma_2^2\n\\end{eqnarray*}\n", "_____no_output_____" ], [ "Here, $\\sigma_1^2$ is the variance for the first part and $\\sigma_2^2$ for the second part of the return observations. Note that one needs to keep the weighting factor constant at $\\frac{252}{N}$ in order to retain additivity.\n\nThis aspect can be illustrated by a simple numerical example. Consider first a function to calculate realized variance that we can re-use.", "_____no_output_____" ] ], [ [ "## function to calculate the realized variance\nrv = lambda ret_dat: 10000 * 252. / N * np.sum(ret_dat ** 2)", "_____no_output_____" ] ], [ [ "Second, a simple example data set ...", "_____no_output_____" ] ], [ [ "data = np.array([0.01, 0.02, 0.03, 0.04, 0.05])", "_____no_output_____" ] ], [ [ "... of length $N=5$.", "_____no_output_____" ] ], [ [ "N = len(data)\nN", "_____no_output_____" ] ], [ [ "Then, we easily see additivity.", "_____no_output_____" ] ], [ [ "rv(data[:2]) + rv(data[2:])", "_____no_output_____" ], [ "rv(data)", "_____no_output_____" ] ], [ [ "Next, we use the EURO STOXX 50 index data from before. Let us have a look at the year 2013 and the two halfs of the year.", "_____no_output_____" ] ], [ [ "data = pd.DataFrame(es['.STOXX50E'][(es.index > '31-12-2012')\n & (es.index < '01-01-2014')])\ndata.columns = ['SX5E']\n## we need log returns\ndata['R_t'] = np.log(data['SX5E'] / data['SX5E'].shift(1))", "_____no_output_____" ] ], [ [ "We have 256 index level observations and 255 return observations.", "_____no_output_____" ] ], [ [ "N = len(data) - 1\nN", "_____no_output_____" ], [ "var_1st = rv(data['R_t'][data.index < '2013-07-01'])\nvar_1st", "_____no_output_____" ], [ "var_2nd = rv(data['R_t'][data.index > '2013-06-30']) \nvar_2nd", "_____no_output_____" ] ], [ [ "Again, additivity is given for the realized variance.", "_____no_output_____" ] ], [ [ "var_1st + var_2nd", "_____no_output_____" ], [ "var_full = rv(data['R_t'])\nvar_full", "_____no_output_____" ] ], [ [ "Obviously, this is different when considering realized volatility instead of variance.", "_____no_output_____" ] ], [ [ "vol_1st = math.sqrt(rv(data['R_t'][data.index < '2013-07-01']))\nvol_1st", "_____no_output_____" ], [ "vol_2nd = math.sqrt(rv(data['R_t'][data.index > '2013-06-30']))\nvol_2nd", "_____no_output_____" ], [ "vol_1st + vol_2nd", "_____no_output_____" ], [ "vol_full = math.sqrt(rv(data['R_t']))\nvol_full", "_____no_output_____" ] ], [ [ "This is something to be expected due to the sub-additivity $\\sqrt{a + b} \\leq \\sqrt{a} + \\sqrt{b}$ of the square-root function.", "_____no_output_____" ], [ "### Static Hedges", "_____no_output_____" ], [ "Realized variance can be statically replicated (hedged) by positions in out-of-the money put and call options. This is a well-known result which is presented in detail in chapter _Model-Free Replication of Variance_. It is the basic idea and approach underlying volatility indexes like the VSTOXX and the VIX. This also makes it possible to statically replicate and hedge variance swaps by the use of options &mdash; something not true for volatility swaps, for example. ", "_____no_output_____" ], [ "### Broad Measure of Risk", "_____no_output_____" ], [ "Implied volatility generally is only defined for a certain maturity and a certain strike. When the spot moves, at-the-money implied volatility changes as well. By contrast, (implied) variance is a measure taking into account all strikes for a given maturity. This can be seen by the fact that the traded variance level of a variance swap is applicable independent of the spot of the underlying (index). ", "_____no_output_____" ], [ "## Conclusions", "_____no_output_____" ], [ "This chapter introduces variance swaps both theoretically as well as based on concrete numerical examples. Central notions are realized variance, variance/volatility strike and variance notional. Mark-to-market valuations of such instruments are easily accomplished due to their very nature. As a consequence, sensitivies of variance swaps, for example, with regard to vega are also easily derived. The major numerical example is based on EURO STOXX 50 index and log return data. A hypothetical variance swap with inception on 1st of June 2015 and maturity on 19th of June 2015 is valued by the mark-to-market approach using VSTOXX sub-index data with the very same maturity as a proxy for the implied volatility during the life time of the variance swap. ", "_____no_output_____" ], [ "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br>\n\n<a href=\"http://tpq.io\" target=\"_blank\">http://tpq.io</a> | <a href=\"http://twitter.com/dyjh\" target=\"_blank\">@dyjh</a> | <a href=\"mailto:[email protected]\">[email protected]</a>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "raw", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "raw" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
ecfd21b5e698df2230a3bb07d211c34d720f4ada
59,317
ipynb
Jupyter Notebook
Exercise_18_2.ipynb
nflanner/deep-learning-for-physics-research-answers
a73e8b1d486cf77d9495e84d85d329525a4edfff
[ "MIT" ]
null
null
null
Exercise_18_2.ipynb
nflanner/deep-learning-for-physics-research-answers
a73e8b1d486cf77d9495e84d85d329525a4edfff
[ "MIT" ]
null
null
null
Exercise_18_2.ipynb
nflanner/deep-learning-for-physics-research-answers
a73e8b1d486cf77d9495e84d85d329525a4edfff
[ "MIT" ]
null
null
null
68.653935
33,557
0.788138
[ [ [ "# Exercise 18.2\n## Generation of air-shower footprints using WGAN\nIn this tutorial we will learn how to implement Wasserstein GANs (WGAN) using tensorflow.keras.\n\nRecall the description of a cosmic-ray observatory in Example 11.2 and Fig. 11.2b.\nIn response to a cosmic-ray-induced air shower, a small part of the detector stations is traversed by shower particles leading to characteristic arrival patterns (dubbed footprints, see Fig. 18.13).\nThe number of triggered stations increases with the cosmic-ray energy.\nThe signal response is largest close to the center of the shower.\n\n#### Tasks\n 1. Build a generator and a critic network which allows for the generation of $9 \\times 9$ air-shower footprints.\n 2. Set up the training by implementing the Wasserstein loss using the Kantorovich-Rubinstein duality. \n 3. Implement the main loop and train the framework for 15 epochs. Check the plots of the critic loss and generated air shower footprints.\n 4. Name four general challenges of training adversarial frameworks.\n 5. Explain why approximating the Wasserstein distance in the discriminator/critic helps to reduce mode collapsing.\n\nThis approach is a simplified version of: https://link.springer.com/article/10.1007/s41781-018-0008-x\n\nTraining WGAN can be computationally demanding, thus, we recommend to use a GPU for this task.", "_____no_output_____" ], [ "### Software\nFirst we have to import our software. Used versions:", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution() # gp loss won't work with eager\nlayers = keras.layers\n\nprint(\"tensorflow version\", tf.__version__)\nprint(\"keras version\", keras.__version__)", "tensorflow version 2.4.0\nkeras version 2.4.0\n" ] ], [ [ "## Data\nTo train our generative model we need some data. In this case we want to generate cosmic-ray induced air showers. The showers were simulated using https://doi.org/10.1016/j.astropartphys.2017.10.006", "_____no_output_____" ] ], [ [ "import gdown\n\nurl = \"https://drive.google.com/u/0/uc?export=download&confirm=HgGH&id=1JfuYem6sXQSE3SYecHnNk5drtC7YKoYz\"\noutput = 'airshowers.npz'\ngdown.download(url, output, quiet=True)", "_____no_output_____" ], [ "file = np.load(output)\nshower_maps = file['shower_maps']\nnsamples = len(shower_maps)", "_____no_output_____" ] ], [ [ "Now, we can have a look at some random footprints of the data set.", "_____no_output_____" ] ], [ [ "def rectangular_array(n=9):\n \"\"\" Return x,y coordinates for rectangular array with n^2 stations. \"\"\"\n n0 = (n - 1) / 2\n return (np.mgrid[0:n, 0:n].astype(float) - n0)\n\n\nfor i,j in enumerate(np.random.choice(nsamples, 4)):\n plt.subplot(2,2,i+1)\n footprint=shower_maps[j,...,0]\n xd, yd = rectangular_array()\n mask = footprint != 0\n mask[5, 5] = True\n marker_size = 50 * footprint[mask]\n plot = plt.scatter(xd, yd, c='grey', s=10, alpha=0.3, label=\"silent\")\n circles = plt.scatter(xd[mask], yd[mask], c=footprint[mask],\n s=marker_size, alpha=1, label=\"loud\")\n cbar = plt.colorbar(circles)\n cbar.set_label('signal [a.u.]')\n plt.grid(True)\n\nplt.tight_layout()\nplt.show()", "_____no_output_____" ] ], [ [ "## Wasserstein GANs\nTo overcome the meaningless loss and vanishing gradients, [Arjovsky, Chintala and Bottou](https://arxiv.org/abs/1701.07875) proposed to use Wasserstein-1 as a metric in the discriminator.\n\nUsing the Wasserstein distance as a metric has several advantages in comparison to the old min-max loss. The crucial feature of the Wasserstein distance is a meaningful distance measure even when distributions are disjunct. But before coming to the essential difference, let us try to understand the Wasserstein distance.", "_____no_output_____" ], [ "### Generator\nFor training GANs we need to further define our generator and discriminator network. We start by defining our generator network, which should map from our noise + label space into the space of images (latent-vector size --> image size). Adding the label the input of to both the generator and discriminator should enforce the generator to produce samples from the according class.", "_____no_output_____" ], [ "#### Task\nDesign a meaningful generator model! \nRemember to check the latent and image dimensions. You can make use of the 'DCGAN guidelines' (See Sec. 18.2.3).\nUse a meaningful last activation function!", "_____no_output_____" ] ], [ [ "def generator_model(latent_size):\n \"\"\" Generator network \"\"\"\n\n\n return keras.models.Model(latent, z, name=\"generator\")", "_____no_output_____" ] ], [ [ "Now we can build and check the shapes of our generator.", "_____no_output_____" ] ], [ [ "latent_size = 128\ng = generator_model(latent_size)\ng.summary()", "_____no_output_____" ] ], [ [ "### Critic / Discriminator\nThe task of the discriminator is to measure the similarity between the fake images (output of the generator) and the real images. So, the network maps from the image space into a 1D space where we can measure the 'distance' between the distributions of the real and generated images (image size --> scalar). Also, here we add the class label to the discriminator.\n\n#### Task\nDesign a power- and meaningful critic model! Remember that you can make use of the DCGAN guidelines and check the image dimensions.\nDo we need a \"special\" last activation function in the critic?", "_____no_output_____" ] ], [ [ "def critic_model():\n \"\"\" Critic network \"\"\"\n\n return keras.models.Model(image, x, name=\"critic\")", "_____no_output_____" ] ], [ [ "Let us now build and inspect the critic.", "_____no_output_____" ] ], [ [ "critic = critic_model()\ncritic.summary()", "_____no_output_____" ] ], [ [ "## Training piplines\nBelow we have to design the pipelines for training the adversarial framework. ", "_____no_output_____" ] ], [ [ "def make_trainable(model, trainable):\n ''' Freezes/unfreezes the weights in the given model '''\n for layer in model.layers:\n # print(type(layer))\n if type(layer) is layers.BatchNormalization:\n layer.trainable = True\n else:\n layer.trainable = trainable", "_____no_output_____" ] ], [ [ "Note that after we compiled a model, calling `make_trainable` will have no effect until we compile the model again.", "_____no_output_____" ], [ "Freeze the critic during the generator training and unfreeze the generator during the generator training", "_____no_output_____" ] ], [ [ "make_trainable(critic, False) \nmake_trainable(g, True) # This is in principal not needed here", "_____no_output_____" ] ], [ [ "Now, we stack the generator on top of the critic and finalize the generator-training step.", "_____no_output_____" ] ], [ [ "gen_input = g.inputs\ngenerator_training = keras.models.Model(gen_input, critic(g(gen_input)))\ngenerator_training.summary()", "_____no_output_____" ] ], [ [ "We can further visualize this simple \"computational graph\".", "_____no_output_____" ] ], [ [ "keras.utils.plot_model(generator_training, show_shapes=True)", "_____no_output_____" ] ], [ [ "#### Task\n - implement the Wasserstein loss", "_____no_output_____" ] ], [ [ "import tensorflow.keras.backend as K\n\ndef wasserstein_loss(y_true, y_pred):\n return \n\ngenerator_training.compile(keras.optimizers.Adam(0.0001, beta_1=0.5, beta_2=0.9, decay=0.0), loss=[wasserstein_loss])", "_____no_output_____" ] ], [ [ "### Gradient penalty\nTo obtain the final Wasserstein distance, we have to use the gradient penalty to enforce the Lipschitz constraint.\n\nTherefore, we need to design a layer that samples on straight lines between reals and fakes samples ", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 128\n\nclass UniformLineSampler(tf.keras.layers.Layer):\n def __init__(self, batch_size):\n super().__init__()\n self.batch_size = batch_size\n\n def call(self, inputs, **kwargs):\n weights = K.random_uniform((self.batch_size, 1, 1, 1))\n return(weights * inputs[0]) + ((1 - weights) * inputs[1])\n\n def compute_output_shape(self, input_shape):\n return input_shape[0]", "_____no_output_____" ] ], [ [ "We design the pipeline of the critic training by inserting generated (use generator + noise directly to circumvent expensive prediction step) and real samples into the sampling layer and additionally feeding generated and real samples into the critic.", "_____no_output_____" ] ], [ [ "make_trainable(critic, True) # unfreeze the critic during the critic training\nmake_trainable(g, False) # freeze the generator during the critic training\n\ng_out = g(g.inputs)\ncritic_out_fake_samples = critic(g_out)\ncritic_out_data_samples = critic(critic.inputs)\naveraged_batch = UniformLineSampler(BATCH_SIZE)([g_out, critic.inputs[0]])\naveraged_batch_out = critic(averaged_batch)\n\ncritic_training = keras.models.Model(inputs=[g.inputs, critic.inputs], outputs=[critic_out_fake_samples, critic_out_data_samples, averaged_batch_out])", "_____no_output_____" ] ], [ [ "Let us visualize this \"computational graph\". The critic outputs will be used for the Wasserstein loss and the `UniformLineSampler` output for the gradient penalty.", "_____no_output_____" ] ], [ [ "keras.utils.plot_model(critic_training, show_shapes=True)", "_____no_output_____" ], [ "critic_training.summary()", "_____no_output_____" ] ], [ [ "We now design the gradient penalty as proposed by in https://arxiv.org/abs/1704.00028", "_____no_output_____" ] ], [ [ "from functools import partial\n\ndef gradient_penalty_loss(y_true, y_pred, averaged_batch, penalty_weight):\n \"\"\"Calculates the gradient penalty.\n The 1-Lipschitz constraint of improved WGANs is enforced by adding a term that penalizes a gradient norm in the critic unequal to 1.\"\"\"\n gradients = K.gradients(y_pred, averaged_batch)\n gradients_sqr_sum = K.sum(K.square(gradients)[0], axis=(1, 2, 3))\n gradient_penalty = penalty_weight * K.square(1 - K.sqrt(gradients_sqr_sum))\n return K.mean(gradient_penalty)\n\n\ngradient_penalty = partial(gradient_penalty_loss, averaged_batch=averaged_batch, penalty_weight=10) # construct the gradient penalty\ngradient_penalty.__name__ = 'gradient_penalty'", "_____no_output_____" ] ], [ [ "Let us compile the critic. The losses have to be given in the order as we designed the model outputs (gradient penalty connected to the output of the sampling layer).", "_____no_output_____" ] ], [ [ "critic_training.compile(keras.optimizers.Adam(0.0001, beta_1=0.5, beta_2=0.9, decay=0.0), loss=[wasserstein_loss, wasserstein_loss, gradient_penalty])", "_____no_output_____" ] ], [ [ "The labels for the training are (Remember we used as for the Wasserstein loss a simple multiplication to add a sign.)", "_____no_output_____" ] ], [ [ "positive_y = np.ones(BATCH_SIZE)\nnegative_y = -positive_y\ndummy = np.zeros(BATCH_SIZE) # keras throws an error when calculating a loss without having a label -> needed for using the gradient penalty loss", "_____no_output_____" ] ], [ [ "### Training\nWe can now start the training loop.\nIn the WGAN setup, the critic is trained several times before the generator is updated.\n\n#### Task\n - Implement the main loop.\n - Choose a reasonable number of `EPOCHS` until you see a cood convergence.\n - Choose a meaningful number of `critic_iterations`.", "_____no_output_____" ] ], [ [ "EPOCHS = 1\ncritic_iterations = 1\n\ngenerator_loss = []\ncritic_loss = []\n\niterations_per_epoch = nsamples // (critic_iterations * BATCH_SIZE)\niters = 0\n\nfor epoch in range(EPOCHS):\n print(\"epoch: \", epoch) \n \n for iteration in range(iterations_per_epoch):\n\n for j in range(critic_iterations):\n\n # complete the main loop here\n \n generated_maps = g.predict_on_batch(np.random.randn(BATCH_SIZE, latent_size))\n \n if iters % 300 == 1:\n print(\"iteration\", iters)\n print(\"critic loss:\", critic_loss[-1])\n print(\"generator loss:\", generator_loss[-1])\n\n for i in range(4):\n plt.subplot(2,2,i+1)\n footprint=generated_maps[i,...,0]\n xd, yd = rectangular_array()\n mask = footprint != 0\n mask[5, 5] = True\n marker_size = 50 * footprint[mask]\n plot = plt.scatter(xd, yd, c='grey', s=10, alpha=0.3, label=\"silent\")\n circles = plt.scatter(xd[mask], yd[mask], c=footprint[mask],\n s=marker_size, alpha=1, label=\"loud\")\n cbar = plt.colorbar(circles)\n cbar.set_label('signal [a.u.]')\n plt.grid(True)\n\n plt.suptitle(\"iteration %i\" % iters)\n plt.tight_layout(rect=[0, 0.03, 1, 0.95])\n plt.savefig(\"./fake_showers_iteration_%.6i.png\" % iters)\n plt.close(\"all\")", "_____no_output_____" ] ], [ [ "### Results\nLet us plot the critic loss.\nWe now expect to see a convergence of the total loss if the training was successful.", "_____no_output_____" ] ], [ [ "critic_loss = np.array(critic_loss)\n\nplt.subplots(1, figsize=(10, 5))\nplt.plot(np.arange(len(critic_loss)), critic_loss[:, 0], color='red', markersize=12, label=r'Total')\nplt.plot(np.arange(len(critic_loss)), critic_loss[:, 1] + critic_loss[:, 2], color='green', label=r'Wasserstein', linestyle='dashed')\nplt.plot(np.arange(len(critic_loss)), critic_loss[:, 3], color='royalblue', markersize=12, label=r'GradientPenalty', linestyle='dashed')\nplt.legend(loc='upper right')\nplt.xlabel(r'Iterations')\nplt.ylabel(r'Loss')\nplt.ylim(-6, 3)\nplt.show()", "_____no_output_____" ] ], [ [ "In addition, we can visualize the generator loss.", "_____no_output_____" ] ], [ [ "generator_loss = np.array(generator_loss)\n\nplt.subplots(1, figsize=(10, 5))\nplt.plot(np.arange(len(generator_loss)), generator_loss, color='red', markersize=12, label=r'Total')\nplt.legend(loc='upper right')\nplt.xlabel(r'Iterations')\nplt.ylabel(r'Loss')\nplt.show()", "_____no_output_____" ] ], [ [ "#### Plot generated footprints\nTo nicely see the training progress, we can create a gif of the generated samples during the training.", "_____no_output_____" ] ], [ [ "import imageio\nimport glob\n\nout_file = 'generated_shower_samples.gif'\n\nwith imageio.get_writer(out_file, mode='I', duration=0.5) as writer:\n file_names = glob.glob('fake_showers_iteration_*.png')\n file_names = sorted(file_names)\n last = -1\n\n for i, file_name in enumerate(file_names):\n animated_image = imageio.imread(file_name)\n writer.append_data(animated_image)\n\n animated_image = imageio.imread(file_name)\n writer.append_data(animated_image)\n\nfrom IPython.display import Image\nImage(open('generated_shower_samples.gif','rb').read())", "_____no_output_____" ] ], [ [ "#### Name four general challenges of training generative adversarial frameworks.", "_____no_output_____" ], [ "#### Explain why approximating the wasserstein distance in the discriminator/critic helps to reduce mode collapsing.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]