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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d0aae00334b64ce29cf3f99c6877c2a4cfb7ccff | 313,734 | ipynb | Jupyter Notebook | notebooks/EDA.ipynb | Gnishimura/We_Eat | bff1b112a1b0f6cb411e8b9f43792cc42412765b | [
"MIT"
] | null | null | null | notebooks/EDA.ipynb | Gnishimura/We_Eat | bff1b112a1b0f6cb411e8b9f43792cc42412765b | [
"MIT"
] | null | null | null | notebooks/EDA.ipynb | Gnishimura/We_Eat | bff1b112a1b0f6cb411e8b9f43792cc42412765b | [
"MIT"
] | 1 | 2018-12-13T01:41:46.000Z | 2018-12-13T01:41:46.000Z | 54.363888 | 1,599 | 0.408821 | [
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"from build_database import (\n load_api_key, make_request, build_database, default_params,\n retrieve_database)",
"_____no_output_____"
],
[
"api_key = load_api_key()",
"_____no_output_____"
],
[
"build_database()",
"1\n51\n101\n151\n201\n251\n301\n351\n401\n451\n501\n551\n601\n651\n701\n751\n801\n851\n901\n951\nNo businesses returned\n"
],
[
"mile_from_galvanize = retrieve_database()",
"_____no_output_____"
],
[
"mile_from_galvanize.shape",
"_____no_output_____"
],
[
"mile_from_galvanize.head()",
"_____no_output_____"
],
[
"mile_from_galvanize.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1393 entries, 0 to 1392\nData columns (total 17 columns):\n_id 1393 non-null object\nalias 1393 non-null object\ncategories 1393 non-null object\ncoordinates 1393 non-null object\ndisplay_phone 1393 non-null object\ndistance 1393 non-null float64\nid 1393 non-null object\nimage_url 1393 non-null object\nis_closed 1393 non-null bool\nlocation 1393 non-null object\nname 1393 non-null object\nphone 1393 non-null object\nprice 1234 non-null object\nrating 1393 non-null float64\nreview_count 1393 non-null int64\ntransactions 1393 non-null object\nurl 1393 non-null object\ndtypes: bool(1), float64(2), int64(1), object(13)\nmemory usage: 175.6+ KB\n"
],
[
"mile_from_galvanize[mile_from_galvanize['price'].isnull() == True]",
"_____no_output_____"
],
[
"mile_from_galvanize[mile_from_galvanize['price']=='$'].count()",
"_____no_output_____"
],
[
"mile_from_galvanize['alias'][mile_from_galvanize['distance'].argsort()]",
"_____no_output_____"
],
[
"def clean_coords(coordinates):\n \"\"\"Break coordinates feature up into strings of latitude and longitude.\"\"\"\n return [(row['latitude'], row['longitude']) for row in coordinates]",
"_____no_output_____"
],
[
"mile_from_galvanize['lats'] = mile_from_galvanize['coordinates'].apply(clean_coords)[0]\nmile_from_galvanize['longs'] = mile_from_galvanize['coordinates'].apply(clean_coords)[1]",
"_____no_output_____"
],
[
"[(row['latitude'], row['longitude']) for row in mile_from_galvanize['coordinates']][0][0]\n ",
"_____no_output_____"
],
[
"lats = mile_from_galvanize['coordinates'].apply(lambda x: ",
"_____no_output_____"
],
[
"def clean_cats(categories):\n \"\"\"Change list of categories into a string.\"\"\"\n return ','.join(cat['alias'] for cat in categories)",
"_____no_output_____"
],
[
"def clean_coords(df):\n \"\"\"Change list of categories into a string.\"\"\"\n return df['coordinates'].apply(lambda x: x['latitude']), df['coordinates'].apply(lambda x: x['longitude'])\n",
"_____no_output_____"
],
[
"mile_from_galvanize['lats'], mile_from_galvanize['longs'] = clean_coords(mile_from_galvanize)",
"_____no_output_____"
],
[
"mile_from_galvanize",
"_____no_output_____"
],
[
"mile_from_galvanize = mile_from_galvanize[mile_from_galvanize['is_closed'] == False]",
"_____no_output_____"
],
[
"mile_from_galvanize.shape",
"_____no_output_____"
],
[
"def change_price_nulls(df):\n \"\"\"Change all nulls to the mode of the price data, $$\"\"\"\n df['price'].fillna(value='$$', inplace=True)\n ",
"_____no_output_____"
],
[
"change_price_nulls(mile_from_galvanize)",
"_____no_output_____"
],
[
"def dummify_price(df):\n \"\"\"Change yelp's price categories ('$', '$$', '$$$, '$$$$') into dummy variables\"\"\"\n df['$'] = (df['price']=='$')*1\n df['$$'] = (df['price']=='$$')*1\n df['$$$'] = (df['price']=='$$$')*1\n df['$$$$'] = (df['price']=='$$$$')*1",
"_____no_output_____"
],
[
"dummify_price(mile_from_galvanize)",
"_____no_output_____"
],
[
"mile_from_galvanize.T",
"_____no_output_____"
],
[
"mile_from_galvanize['cats'].head(20)",
"1\n51\n101\n151\n201\n251\n301\n351\n401\n451\n501\n551\n601\n651\n701\n751\n801\n851\n901\n951\nNo businesses returned\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"
]
] |
d0aaea2f783c40952abdd8f368222a405218e867 | 4,432 | ipynb | Jupyter Notebook | Day01_ComputerBasics/notebooks/01 - Data Science.ipynb | LucaFoschini/UCSBDataScienceBootcamp2015 | a9d6126613a03c767fd1eb4200e6d7f9549d5bf5 | [
"CC0-1.0"
] | 6 | 2015-09-17T16:13:15.000Z | 2018-01-12T02:48:43.000Z | Day01_ComputerBasics/notebooks/01 - Data Science.ipynb | LucaFoschini/UCSBDataScienceBootcamp2015 | a9d6126613a03c767fd1eb4200e6d7f9549d5bf5 | [
"CC0-1.0"
] | 1 | 2015-09-16T18:00:43.000Z | 2015-09-16T18:00:43.000Z | Day01_ComputerBasics/notebooks/01 - Data Science.ipynb | LucaFoschini/UCSBDataScienceBootcamp2015 | a9d6126613a03c767fd1eb4200e6d7f9549d5bf5 | [
"CC0-1.0"
] | 24 | 2015-08-26T03:33:32.000Z | 2019-10-11T12:15:31.000Z | 31.211268 | 434 | 0.622067 | [
[
[
"# Data Science\n\nWhat's that?",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image\nImage(url='http://static.squarespace.com/static/5150aec6e4b0e340ec52710a/t/51525c33e4b0b3e0d10f77ab/1364352052403/Data_Science_VD.png?format=750w')\n",
"_____no_output_____"
]
],
[
[
"Read the full story:\n\nhttp://lucafoschini.com/notebooks/Agile%20Data%20Science%20Meetup.slides.html#/\n\nSource (Another feature of Notebooks: Make slides out of them!):\n\nhttps://github.com/LucaFoschini/lucafoschini.github.io/blob/master/notebooks/Agile%20Data%20Science%20Meetup.ipynb\n\n# Getting started\n\nThis section focuses on the 'Hacking Skills' part of the Venn diagram -- we're going to get you up and running on Linux, using git and GitHub, and starting to work on Jupyter notebooks. This is all stuff which will be used for future sections in this bootcamp, so take notes! \n\nFirst up: opening the terminal. Either search for a program named 'terminal' on your computer (more on that in the links below), or use 'Applications (top left corner of your screen) -> System Tools -> Terminal'\n\nThe terminal is a powerful and efficient replacement for the file explorer:\n",
"_____no_output_____"
]
],
[
[
"Image(url='https://upload.wikimedia.org/wikipedia/en/c/cb/Windows_Explorer_Windows_7.png')",
"_____no_output_____"
]
],
[
[
"\"In Unix, a word is worth a thousand clicks.\" Much like in a traditional file explorer, you will be located at a specific directory (e.g. 'Libraries' in the picture above), and can travel up and down through the directory structure, running or opening files with various programs. If you are new to the command line, or even just a little bit rusty, the following short introduction and tutorial will bring you up to speed:\n\n* Introduction: http://ryanstutorials.net/linuxtutorial/commandline.php\n\n* Tutorial: http://matt.might.net/articles/basic-unix/",
"_____no_output_____"
],
[
"# Data Science from the command line\n\nThe Unix terminal is a very powerful thing, and the comparison to a file explorer is unfair. Get a feel for how much you can do with so little by running through the following tutorial, until the 'awk' section:\n\nhttp://www.ibm.com/developerworks/aix/library/au-unixtext/\n\nUnix texutils can go a long way. Here are seven examples of powerful little tools that can be run from the terminal:\n\nhttp://jeroenjanssens.com/2013/09/19/seven-command-line-tools-for-data-science.html\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
d0aaf7f1822748497ab15194bcccbf42b04e142a | 3,231 | ipynb | Jupyter Notebook | cartoon .ipynb | Satarupa22-SD/cartoon-python3- | 687a456f16f93a178d4dc2614a52d30e00332856 | [
"MIT"
] | null | null | null | cartoon .ipynb | Satarupa22-SD/cartoon-python3- | 687a456f16f93a178d4dc2614a52d30e00332856 | [
"MIT"
] | null | null | null | cartoon .ipynb | Satarupa22-SD/cartoon-python3- | 687a456f16f93a178d4dc2614a52d30e00332856 | [
"MIT"
] | null | null | null | 21.117647 | 137 | 0.532033 | [
[
[
"pip install opencv-python",
"Requirement already satisfied: opencv-python in c:\\users\\lucy22\\anaconda3\\lib\\site-packages (4.5.3.56)\nRequirement already satisfied: numpy>=1.17.3 in c:\\users\\lucy22\\anaconda3\\lib\\site-packages (from opencv-python) (1.20.1)\nNote: you may need to restart the kernel to use updated packages.\n"
],
[
"pip install numpy",
"Requirement already satisfied: numpy in c:\\users\\lucy22\\anaconda3\\lib\\site-packages (1.20.1)\nNote: you may need to restart the kernel to use updated packages.\n"
],
[
"import cv2",
"_____no_output_____"
],
[
"import numpy as np\nfrom tkinter.filedialog import *",
"_____no_output_____"
],
[
"photo = askopenfilename()\nimg = cv2.imread(photo)",
"_____no_output_____"
],
[
"grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ngrey = cv2.medianBlur(grey, 5)\nedges = cv2.adaptiveThreshold(grey, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)",
"_____no_output_____"
],
[
"#cartoonize\ncolor = cv2.bilateralFilter(img, 9, 250, 250)\ncartoon = cv2.bitwise_and(color, color, mask = edges)\n",
"_____no_output_____"
],
[
"cv2.imshow(\"Image\", img)\ncv2.imshow(\"Cartoon\", cartoon)",
"_____no_output_____"
],
[
"#save\ncv2.imwrite(\"cartoon.jpg\", cartoon)\ncv2.waitKey(0)\ncv2.destroyAllWindows()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0aafa5414e7b90a571d79c5a77b1fb63f865bd1 | 12,196 | ipynb | Jupyter Notebook | models/.ipynb_checkpoints/GBM - Experiments 500 Best Feats 21.05-checkpoint.ipynb | susantamoh84/Kaggle-Quora | d38a87a4e9bc5786dc43f8641ce08b50ff3d1075 | [
"MIT"
] | 99 | 2017-06-11T16:39:21.000Z | 2022-03-27T15:51:59.000Z | models/.ipynb_checkpoints/GBM - Experiments 500 Best Feats 21.05-checkpoint.ipynb | susantamoh84/Kaggle-Quora | d38a87a4e9bc5786dc43f8641ce08b50ff3d1075 | [
"MIT"
] | 3 | 2018-05-24T07:13:45.000Z | 2018-06-07T06:57:28.000Z | models/.ipynb_checkpoints/GBM - Experiments 500 Best Feats 21.05-checkpoint.ipynb | susantamoh84/Kaggle-Quora | d38a87a4e9bc5786dc43f8641ce08b50ff3d1075 | [
"MIT"
] | 37 | 2017-06-11T16:47:22.000Z | 2021-08-01T22:13:39.000Z | 38.473186 | 263 | 0.621105 | [
[
[
"import nltk\nimport difflib\nimport time\nimport gc\nimport itertools\nimport multiprocessing\nimport pandas as pd\nimport numpy as np\nimport xgboost as xgb\nimport lightgbm as lgb\n\nimport warnings\nwarnings.filterwarnings('ignore')\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\n\nfrom sklearn.metrics import log_loss\nfrom sklearn.model_selection import train_test_split\n\nfrom models_utils_fe import *\nfrom models_utils_gbm import *",
"_____no_output_____"
],
[
"src = '/media/w/1c392724-ecf3-4615-8f3c-79368ec36380/DS Projects/Kaggle/Quora/scripts/features/'\nfeats_src = '/media/w/1c392724-ecf3-4615-8f3c-79368ec36380/DS Projects/Kaggle/Quora/data/features/uncleaned/'\ntrans_src = '/media/w/1c392724-ecf3-4615-8f3c-79368ec36380/DS Projects/Kaggle/Quora/data/features/lemmatized_fullclean/transformations/'\n\nwmd = pd.read_csv(src + 'train_WMD_cleaned_stemmed.csv')\nwmd = wmd.astype('float32')\nwmd.replace(np.inf, 1000, inplace = True)\n\nskip_thought = pd.read_csv(src + 'train_skipthoughts_Alex_distances.csv')\nskip_thought = skip_thought.astype('float32')\n\ncompression = pd.read_csv(src + 'train_LZMAcompression_distance.csv')\ncompression = compression.astype('float32')\n\nedit = pd.read_csv(src + 'train_EDITdistance.csv')\nedit = edit.astype('float32')\n\nmoments = pd.read_csv(src + 'train_doc2vec_moments.csv')\nmoments = moments.astype('float32')\n\nnetworks_NER = pd.read_csv(src + 'train_networkfeats_NER.csv')\nnetworks_NER = networks_NER.astype('float32')\n\nxgb_feats = pd.read_csv(feats_src + '/the_1owl/owl_train.csv')\ny_train = xgb_feats[['is_duplicate']]\n\nlsaq1 = pd.DataFrame(np.load(trans_src + 'train_lsa50_CV1gram.npy')[0])\nlsaq1.columns = ['{}_lsaCV1_q1'.format(i) for i in range(lsaq1.shape[1])]\nlsaq2 = pd.DataFrame(np.load(trans_src + 'train_lsa50_CV1gram.npy')[1])\nlsaq2.columns = ['{}_lsaCV1_q2'.format(i) for i in range(lsaq2.shape[1])]\n\nsvdq1 = pd.DataFrame(np.load(trans_src + 'train_svd50_CV1gram.npy')[0])\nsvdq1.columns = ['{}_svdCV1_q1'.format(i) for i in range(svdq1.shape[1])]\nsvdq2 = pd.DataFrame(np.load(trans_src + 'train_svd50_CV1gram.npy')[1])\nsvdq2.columns = ['{}_svdCV1_q2'.format(i) for i in range(svdq2.shape[1])]\n\n\nX_train = pd.read_pickle('Xtrain_500bestCols.pkl')\nX_train = pd.concat([X_train, wmd, skip_thought, compression, edit, moments, networks_NER, \n lsaq1, lsaq2, svdq1, svdq2], axis = 1)\n\ndel xgb_feats, wmd, skip_thought, compression, edit, moments, networks_NER, \\\n lsaq1, lsaq2, svdq1, svdq2\ngc.collect()",
"_____no_output_____"
],
[
"best_cols = [\n 'min_pagerank_sp_network_weighted',\n 'norm_wmd',\n 'word_match',\n '1wl_tfidf_l2_euclidean',\n 'm_vstack_svd_q1_q1_euclidean',\n '1wl_tfidf_cosine',\n 'sk_bi_skew_q2vec',\n 'm_q1_q2_tf_svd0',\n 'sk_bi_skew_q1vec',\n 'skew_q2vec',\n 'trigram_tfidf_cosine',\n 'sk_uni_skew_q2vec',\n 'sk_bi_canberra_distance',\n 'question1_3',\n 'sk_uni_skew_q1vec',\n 'sk_uni_kur_q2vec',\n 'min_eigenvector_centrality_np_network_weighted',\n 'avg_world_len2',\n 'z_word_match',\n 'sk_uni_kur_q1vec',\n 'skew_doc2vec_pretrained_lemmat']\n\nrescale = False\nX_bin = bin_numerical(X_train, best_cols, 0.1)\nX_grouped = group_featbyfeat(X_train, best_cols, 'mean')\nX_grouped2 = group_featbyfeat(X_train, best_cols, 'sum')\nX_combinations = feature_combinations(X_train, best_cols[:5])\n\nX_additional = pd.concat([X_bin, X_grouped, X_grouped2, X_combinations], axis = 1)\nX_additional = drop_duplicate_cols(X_additional)\nX_additional.replace(np.inf, 999, inplace = True)\nX_additional.replace(np.nan, -999, inplace = True)\nif rescale:\n colnames = X_additional.columns\n X_additional = pd.DataFrame(MinMaxScaler().fit_transform(X_additional))\n X_additional.columns = colnames\n\nX_train = pd.concat([X_train, X_additional], axis = 1)\nX_train = X_train.astype('float32')\nprint('Final training data shape:', X_train.shape)\n\ndel X_bin, X_grouped, X_grouped2, X_combinations, X_additional\ngc.collect()",
"_____no_output_____"
],
[
"src = '/media/w/1c392724-ecf3-4615-8f3c-79368ec36380/DS Projects/Kaggle/Quora/scripts/features/'\nfeats_src = '/media/w/1c392724-ecf3-4615-8f3c-79368ec36380/DS Projects/Kaggle/Quora/data/features/uncleaned/'\ntrans_src = '/media/w/1c392724-ecf3-4615-8f3c-79368ec36380/DS Projects/Kaggle/Quora/data/features/lemmatized_fullclean/transformations/'\n\nX_train = pd.read_pickle('Xtrain_814colsBest.pkl', compression = 'bz2')\nxgb_feats = pd.read_csv(feats_src + '/the_1owl/owl_train.csv')\ny_train = xgb_feats[['is_duplicate']]\n\n\ndel xgb_feats\ngc.collect()",
"_____no_output_____"
],
[
"xgb = True\n\nif xgb:\n run_xgb(X_train, y_train)\nelse:\n run_lgb(X_train, y_train)",
"Start training with parameters: {'nthread': 4, 'colsample_bytree': 0.42, 'eta': 0.02, 'max_depth': 8, 'objective': 'binary:logistic', 'subsample': 0.85, 'eval_metric': 'logloss', 'min_child_weight': 20, 'silent': 1, 'tree_method': 'hist', 'seed': 1337}\n[0]\ttrain-logloss:0.680122\tvalid-logloss:0.680223\nMultiple eval metrics have been passed: 'valid-logloss' will be used for early stopping.\n\nWill train until valid-logloss hasn't improved in 250 rounds.\n[100]\ttrain-logloss:0.274051\tvalid-logloss:0.280521\n[200]\ttrain-logloss:0.227292\tvalid-logloss:0.237365\n[300]\ttrain-logloss:0.21292\tvalid-logloss:0.226354\n[400]\ttrain-logloss:0.201778\tvalid-logloss:0.220382\n[500]\ttrain-logloss:0.192838\tvalid-logloss:0.216636\n[600]\ttrain-logloss:0.185062\tvalid-logloss:0.213893\n[700]\ttrain-logloss:0.178618\tvalid-logloss:0.211966\n[800]\ttrain-logloss:0.173117\tvalid-logloss:0.210567\n[900]\ttrain-logloss:0.167968\tvalid-logloss:0.20939\n[1000]\ttrain-logloss:0.163199\tvalid-logloss:0.208437\n[1100]\ttrain-logloss:0.158802\tvalid-logloss:0.207618\n[1200]\ttrain-logloss:0.154606\tvalid-logloss:0.206917\n[1300]\ttrain-logloss:0.150681\tvalid-logloss:0.206357\n[1400]\ttrain-logloss:0.146821\tvalid-logloss:0.205809\n[1500]\ttrain-logloss:0.143423\tvalid-logloss:0.205313\n[1600]\ttrain-logloss:0.139832\tvalid-logloss:0.204876\n[1700]\ttrain-logloss:0.136387\tvalid-logloss:0.204411\n[1800]\ttrain-logloss:0.133093\tvalid-logloss:0.204063\n[1900]\ttrain-logloss:0.129738\tvalid-logloss:0.203605\n[2000]\ttrain-logloss:0.126639\tvalid-logloss:0.203304\n[2100]\ttrain-logloss:0.123697\tvalid-logloss:0.202996\n[2200]\ttrain-logloss:0.120948\tvalid-logloss:0.202741\n[2300]\ttrain-logloss:0.118149\tvalid-logloss:0.20249\n[2400]\ttrain-logloss:0.115491\tvalid-logloss:0.202264\n[2500]\ttrain-logloss:0.112829\tvalid-logloss:0.202043\n[2600]\ttrain-logloss:0.110168\tvalid-logloss:0.201783\n[2700]\ttrain-logloss:0.107845\tvalid-logloss:0.20159\n[2800]\ttrain-logloss:0.105434\tvalid-logloss:0.201451\n[2900]\ttrain-logloss:0.103155\tvalid-logloss:0.201279\n[3000]\ttrain-logloss:0.100872\tvalid-logloss:0.20112\n[3100]\ttrain-logloss:0.09865\tvalid-logloss:0.201039\n[3200]\ttrain-logloss:0.096574\tvalid-logloss:0.200971\n[3300]\ttrain-logloss:0.094473\tvalid-logloss:0.200876\n[3400]\ttrain-logloss:0.092543\tvalid-logloss:0.200812\n[3500]\ttrain-logloss:0.09066\tvalid-logloss:0.200733\n[3600]\ttrain-logloss:0.088758\tvalid-logloss:0.200654\n[3700]\ttrain-logloss:0.086787\tvalid-logloss:0.200555\n[3800]\ttrain-logloss:0.085087\tvalid-logloss:0.200527\n[3900]\ttrain-logloss:0.083296\tvalid-logloss:0.200455\n[4000]\ttrain-logloss:0.08152\tvalid-logloss:0.200397\n[4100]\ttrain-logloss:0.079818\tvalid-logloss:0.200295\n[4200]\ttrain-logloss:0.078233\tvalid-logloss:0.200288\n[4300]\ttrain-logloss:0.076603\tvalid-logloss:0.200224\n[4400]\ttrain-logloss:0.075042\tvalid-logloss:0.20023\n[4500]\ttrain-logloss:0.073516\tvalid-logloss:0.20019\n[4600]\ttrain-logloss:0.072041\tvalid-logloss:0.200171\n[4700]\ttrain-logloss:0.070518\tvalid-logloss:0.200209\nStopping. Best iteration:\n[4515]\ttrain-logloss:0.07331\tvalid-logloss:0.200167\n\nStart predicting...\nFinal score: 0.200167422056 \n Time it took to train and predict: 5234.663367986679\n"
],
[
"gbm = xgb.Booster(model_file = 'saved_models/XGB/XGB_500cols_experiments.txt')\ndtrain = xgb.DMatrix(X_train, label = y_train)\n\nmapper = {'f{0}'.format(i): v for i, v in enumerate(dtrain.feature_names)}\nimportance = {mapper[k]: v for k, v in gbm.get_fscore().items()}\nimportance = sorted(importance.items(), key=lambda x:x[1], reverse=True)[:20]\n\ndf_importance = pd.DataFrame(importance, columns=['feature', 'fscore'])\ndf_importance['fscore'] = df_importance['fscore'] / df_importance['fscore'].sum()\n\nplt.figure()\ndf_importance.plot()\ndf_importance.plot(kind='barh', x='feature', y='fscore', legend=False, figsize=(10, 18))\nplt.title('XGBoost Feature Importance')\nplt.xlabel('relative importance')",
"_____no_output_____"
],
[
"retain_cols = df_importance['feature']\nX_train2 = X_train.loc[:, retain_cols]\nretain_cols.to_pickle('Colnames_best500features.pkl')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ab0309a2d78b06ad38cade950ef4d17e65209d | 68,096 | ipynb | Jupyter Notebook | Implementing Algo From Scratch/Simple Linear Regression.ipynb | thealphadollar/Machine-Learning-PC | 003dcdd5f27d83d03b1ffd1181c1deaedd6af7ca | [
"MIT"
] | 2 | 2020-05-21T03:51:09.000Z | 2021-02-10T11:00:33.000Z | Implementing Algo From Scratch/Simple Linear Regression.ipynb | thealphadollar/Machine-Learning-PC | 003dcdd5f27d83d03b1ffd1181c1deaedd6af7ca | [
"MIT"
] | 4 | 2020-02-24T20:43:39.000Z | 2021-08-23T20:42:10.000Z | Implementing Algo From Scratch/Simple Linear Regression.ipynb | thealphadollar/Machine-Learning-PG | 003dcdd5f27d83d03b1ffd1181c1deaedd6af7ca | [
"MIT"
] | null | null | null | 187.592287 | 29,028 | 0.898482 | [
[
[
"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"data = pd.read_csv('data/ex1data1.txt', names=['Pop', \n 'Pro'])\ndata.head()\ndata.describe()",
"_____no_output_____"
],
[
"data.plot(kind='scatter', x='Pop', y='Pro')",
"_____no_output_____"
],
[
"def comCost(X,y,theta):\n y_pred = np.power((X*theta.T - y), 2)\n return np.sum(y_pred) / (2*len(X))",
"_____no_output_____"
],
[
"data.insert(0, \"Int\", 1)\ncols = data.shape[1]\nX = data.iloc[:,0:cols-1]\ny = data.iloc[:,cols-1:cols]",
"_____no_output_____"
],
[
"X = np.matrix(X.values)",
"_____no_output_____"
],
[
"y = np.matrix(y.values)\n\n",
"_____no_output_____"
],
[
"theta = np.matrix(np.array([0,0]))",
"_____no_output_____"
],
[
"cost(X,y,theta)",
"_____no_output_____"
],
[
"def gradientDes(X,y,theta,alpha,iters):\n temp = np.matrix(np.zeros(theta.shape))\n parameters = int(theta.ravel().shape[1])\n cost = np.zeros(iters)\n \n for i in range(iters):\n error = (X*theta.T) - y\n for j in range(parameters):\n term = np.multiply(error, X[:, j])\n temp[0,j] = theta[0,j] - ((alpha/len(X)) * np.sum(term))\n theta = temp\n cost[i] = comCost(X,y,theta)\n return theta,cost",
"_____no_output_____"
],
[
"alpha = 0.01\niters = 1000\n\nsol, cost = gradientDes(X,y,theta, alpha,iters)\nsol\n\nx = np.linspace(data.Pop.min(), data.Pop.max(), 1000)\nf = sol[0,0] + (sol[0,1]*x)\nfig, ax = plt.subplots(figsize=(12,8))\nax.plot(x,f, 'r', label='Prediction')\nax.scatter(data.Pop, data.Pro, label='Training Data')\nax.legend(loc=2)\nax.set_xlabel('Population')\nax.set_ylabel('Profit')\nax.set_title('Prediction vs Data')",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(12,8))\nax.plot(np.arange(iters), cost, 'r')\nax.set_xlabel('Iterations')\nax.set_ylabel('Cost')\nax.set_title('Error vs. Training Epoch')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ab0457ddff44f0847c277d51024527e639b785 | 282,753 | ipynb | Jupyter Notebook | Chapter1/bayesian_introduction.ipynb | nathdipankar/Bayesian-Statistics | 444d0476e61e2ce61ae39bf0bb30c6d0e1b3d2c9 | [
"MIT"
] | null | null | null | Chapter1/bayesian_introduction.ipynb | nathdipankar/Bayesian-Statistics | 444d0476e61e2ce61ae39bf0bb30c6d0e1b3d2c9 | [
"MIT"
] | null | null | null | Chapter1/bayesian_introduction.ipynb | nathdipankar/Bayesian-Statistics | 444d0476e61e2ce61ae39bf0bb30c6d0e1b3d2c9 | [
"MIT"
] | null | null | null | 1,848.058824 | 125,409 | 0.704792 | [
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import stats",
"_____no_output_____"
],
[
"n_params = [1, 2, 4] # Number of trials\np_params = [0.25, 0.5, 0.75] # Probability of success\n\nx = np.arange(0, max(n_params)+1)\nf,ax = plt.subplots(len(n_params), len(p_params), sharex=True, \n sharey=True,\n figsize=(8, 7), constrained_layout=True)\n\nfor i in range(len(n_params)):\n for j in range(len(p_params)):\n n = n_params[i]\n p = p_params[j]\n\n y = stats.binom(n=n, p=p).pmf(x)\n\n ax[i,j].vlines(x, 0, y, colors='C0', lw=5)\n ax[i,j].set_ylim(0, 1)\n ax[i,j].plot(0, 0, label=\"N = {:3.2f}\\nθ = {:3.2f}\".format(n,p), alpha=0)\n ax[i,j].legend()\n\n ax[2,1].set_xlabel('y')\n ax[1,0].set_ylabel('p(y | θ, N)')\n ax[0,0].set_xticks(x)\n",
"_____no_output_____"
]
],
[
[
"### Choosing the prior\n\nAs a prior we will use a beta distribution, which is a very common distribution:\n\n\\begin{equation}\np\\left(\\theta\\right) = \\frac{\\Gamma\\left(\\alpha+\\beta\\right)}{\\Gamma\\left(\\alpha\\right)\\Gamma\\left(\\beta\\right)}\\theta^(\\alpha - 1)\\left(1-\\theta\\right)^{\\beta -1}\n\\end{equation}\n\nThe beta distribution is a common choice of prior in Bayesian statistics:",
"_____no_output_____"
]
],
[
[
"params = [0.5, 1, 2, 3]\nx = np.linspace(0, 1, 100)\nf, ax = plt.subplots(len(params), len(params), sharex=True, \n sharey=True,\n figsize=(8, 7), constrained_layout=True)\nfor i in range(4):\n for j in range(4):\n a = params[i]\n b = params[j]\n y = stats.beta(a, b).pdf(x)\n ax[i,j].plot(x, y)\n ax[i,j].plot(0, 0, label=\"α = {:2.1f}\\nβ = {:2.1f}\".format(a, \n b), alpha=0)\n ax[i,j].legend()\nax[1,0].set_yticks([])\nax[1,0].set_xticks([0, 0.5, 1])\nf.text(0.5, 0.05, 'θ', ha='center')\nf.text(0.07, 0.5, 'p(θ)', va='center', rotation=0)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ab1e9b47edefc07e0d541d85ba03cd8d9d250e | 2,248 | ipynb | Jupyter Notebook | docs/python/pandas/Create-an-Empty-DataFrame.ipynb | rakshmitha/mlnotes | 01d8b0e3b98f1990259b94ad5a815d5a12d2fd7e | [
"MIT"
] | 1 | 2020-09-30T05:45:16.000Z | 2020-09-30T05:45:16.000Z | docs/python/pandas/Dataframe/Create-an-Empty-DataFrame.ipynb | rakshmitha/mlnotes | 01d8b0e3b98f1990259b94ad5a815d5a12d2fd7e | [
"MIT"
] | null | null | null | docs/python/pandas/Dataframe/Create-an-Empty-DataFrame.ipynb | rakshmitha/mlnotes | 01d8b0e3b98f1990259b94ad5a815d5a12d2fd7e | [
"MIT"
] | null | null | null | 19.893805 | 68 | 0.439057 | [
[
[
"---\ntitle: \"CREATE AN EMPTY DATAFRAME\"\nauthor: \"Rakshmitha\"\ndate: 2020-08-13\ndescription: \"-\"\ntype: technical_note\ndraft: false\n---",
"_____no_output_____"
]
],
[
[
"## Create an Empty DataFrame\nA basic DataFrame, which can be created is an Empty Dataframe.",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"df = pd.DataFrame()\ndf",
"_____no_output_____"
]
]
] | [
"raw",
"markdown",
"code"
] | [
[
"raw"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0ab29b71fe4d42f74c08833bdc2838e0cfcde6c | 30,449 | ipynb | Jupyter Notebook | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring | eaeb92e2df1a5709a3b87f80985a0c189158901a | [
"MIT"
] | 9 | 2018-03-02T12:21:50.000Z | 2019-08-06T08:14:18.000Z | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring | eaeb92e2df1a5709a3b87f80985a0c189158901a | [
"MIT"
] | 20 | 2018-03-15T22:00:12.000Z | 2019-01-21T09:38:44.000Z | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring | eaeb92e2df1a5709a3b87f80985a0c189158901a | [
"MIT"
] | 10 | 2018-03-14T10:13:39.000Z | 2022-03-24T20:14:52.000Z | 26.136481 | 548 | 0.565306 | [
[
[
"# Homework 1\n\nThe maximum score of this homework is 100+10 points. Grading is listed in this table:\n\n| Grade | Score range |\n| --- | --- |\n| 5 | 85+ |\n| 4 | 70-84 |\n| 3 | 55-69 |\n| 2 | 40-54 |\n| 1 | 0-39 |\n\nMost exercises include tests which should pass if your solution is correct.\nHowever successful test do not guarantee that your solution is correct.\nThe homework is partially autograded using many hidden tests.\nTest cells cannot be modified and empty cells cannot be deleted.\n\nYour solution should replace placeholder lines such as:\n\n ### YOUR CODE HERE\n raise NotImplementedError()\n\nPlease do not add new cells, they will be ignored by the autograder.\n\n**VERY IMPORTANT** Before submitting your solution (pushing to the git repo),\nrun your notebook with `Kernel -> Restart & Run All` and make sure it\nruns without exceptions.\n\n## Submission\n\nGitHub Classroom will accept your last pushed version before the deadline.\nYou do not need to send the homework to the instructor.\n\n## Plagiarism\n\nWhen preparing their homework, students are reminded to pay special attention to Title 32, Sections 92-93 of Code of Studies (quoted below). Any content from external sources must be stated in the students own words AND accompanied by citations. Copying and pasting from an external source should be avoided and any text copied must be placed between quotation marks. Reports that violate these rules cannot receive a passing grade.\n\n\"**Section 92**\n\n(1) The works of another person will be used as follows: a) if a work of another person is used in whole or in part (e.g. by copying, citation, translation from another language or presentation), the source and the name of the author will be indicated if this name is included in the source or – in case of orally presented works – may be clearly identified; b) the work of another person or any part of that will be used – up to a quantity reasonably corresponding to the nature and purpose of the student work – identified as quotations.\n\n(2) Instructors are entitled to review compliance with requirements in this article with computer programmes and databases.\n\n(3) The use of works of another person and the acknowledgement of use will be governed by applicable laws and the relevant rules of the specific discipline.\n\n**Section 93**\n\n(1) If a student fails to meet rules regarding use of works of another person in whole or in part, the student work will be considered as not assessable and the student will not be allowed to obtain the credit of the concerned subject in the specific term.\n\n(2) It will be deemed a disciplinary offence if a student – in breach of the rules regarding use of works of another person – submits or presents a work of another person fully or in a significant part verbatim (word for word) or in terms of its basic concepts or the combined version of several works of another person(s) as their own work.\n\n(3) Based on subsection (1) of Section 52/A. of the Higher Education Act, compliance with the rules regarding the use of works of another person in a master thesis may be reviewed up to five years following the issue of the degree certificate. In case of violation of the above rules, section 52/A of the Higher Education Act will apply.\"\n\n(BME Code of Studies, p.50)",
"_____no_output_____"
],
[
"## 1. Modified Levenshtein distance (20 points)\n\nStandard Levenshtein distance assigns an integer edit distance to any two strings measuring how difficult it would be to turn one string into the other. See [Wikipedia](https://en.wikipedia.org/wiki/Levenshtein_distance).\n\nCreate a modify version of Levenshtein distance which discounts letters\nthat are close to each other on the English keyboard. The keyboard variable below\ncontains the English keyboard organized into a table.\nTwo letters are considered close to each other if both their row\nand column distance is at most 1. Close keys are at distance 0.5,\nothers are at distance 1.\nThis table lists a few examples:\n\n| | | distance |\n| ---- | ---- |\n| q | w | 0.5 |\n| q | e | 1 |\n| s | w | 0.5 |\n| f | t | 0.5 |\n| f | y | 1 |\n| f | f | 0 |\n\nAny letter outside the lowercase English alphabet (see the `keyboard` variable below)\nis not considered close and you do not need to discount them.",
"_____no_output_____"
]
],
[
[
"keyboard = [\n ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],\n ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'],\n ['z', 'x', 'c', 'v', 'b', 'n', 'm'],\n]\nkeyboard_mapping = {}\nfor i, row in enumerate(keyboard):\n for j, c in enumerate(row):\n keyboard_mapping[c] = (i, j)",
"_____no_output_____"
],
[
"def keyboard_edit_distance(str1, str2):\n # YOUR CODE HERE\n raise NotImplementedError()",
"_____no_output_____"
],
[
"assert keyboard_edit_distance(\"abc\", \"abc\") == 0\nassert keyboard_edit_distance(\"abc\", \"ab\") == 1",
"_____no_output_____"
],
[
"assert keyboard_edit_distance(\"a\", \"s\") == 0.5",
"_____no_output_____"
]
],
[
[
"## 2. Replace rare words (10 points)\n\nWrite a function that takes a text and a number $N$ as parameters and replaces every word other than the most common $N$ in the text with a common symbol. The symbol by default is `__RARE__` but it can be redefined.\n\nYour code should split on spaces only.\n\nYou can derive the function definition from the tests.",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE\nraise NotImplementedError()",
"_____no_output_____"
],
[
"assert replace_rare_words(\"a b a a a b b b c d d d\", 2) == \"a b a a a b b b __RARE__ __RARE__ __RARE__ __RARE__\"\nassert replace_rare_words(\"a b a b b c\", 2, rare_symbol=\"rare\") == \"a b a b b rare\"",
"_____no_output_____"
]
],
[
[
"## 3. MutableString (30 points)\n\nPython strings are immutable. Create a mutable string class. The internal representation should be mutable too.\n\nImplement the following features (see the tests below).\n\n- initialization from `str`,\n- initialization from text file (loads the file's content into the string),\n- assignment (i.e. modifying a character),\n - if the index is out of range, it should fill the blanks with spaces (see the tests below)\n- conversion to built-in `str` and `list`. The latter is a list of the characters.\n- addition with other `MutableString` instances and built-in strings,\n- multiplication with integers. Multiplying a string with 3 means repeating the string 3 times.\n- built-in `len` function,\n- comparision with strings,\n- substring containment with both built-in strings and other MutableString objects,\n- in-place upper and lowercasing,\n- shallow copying,\n- iteration.\n\nPlease read all of the tests before writing your solution.",
"_____no_output_____"
]
],
[
[
"class MutableString(object):\n # YOUR CODE HERE\n raise NotImplementedError()",
"_____no_output_____"
]
],
[
[
"### Briefly describe what internal representation you chose and why you chose it.\n\nWhat other possibilities did you think about?\n\n(double-click on the text to edit it)",
"_____no_output_____"
],
[
"YOUR ANSWER HERE",
"_____no_output_____"
],
[
"### MutableString tests",
"_____no_output_____"
]
],
[
[
"# initialization\nm = MutableString()\nassert m == \"\" and len(m) == 0",
"_____no_output_____"
],
[
"# initialization from file\nimport tempfile\nimport os\n\nwith tempfile.NamedTemporaryFile(mode=\"w+b\", delete=False) as tmpfile:\n tmpfile.write(\"abc\".encode(\"utf8\"))\nm = MutableString.from_file(tmpfile.name)\nassert m == \"abc\"",
"_____no_output_____"
],
[
"os.remove(tmpfile.name)",
"_____no_output_____"
],
[
"# iteration\nm = MutableString(\"abc\")\nfor c in m:\n print(c)",
"_____no_output_____"
],
[
"# comparison\nm1 = MutableString(\"abc\")\nassert m1 == \"abc\"\nm2 = MutableString(\"abc\")\nassert id(m1) != id(m2)\nassert m1 == m2",
"_____no_output_____"
],
[
"# item setting tests\nm1 = MutableString(\"abc\")\nassert m1[0] == \"a\" and m1[2] == \"c\"\nm1[1] = \"d\"\nassert(m1[1] == \"d\")",
"_____no_output_____"
],
[
"# slicing\nm1 = MutableString(\"abc\")\nassert m1[1:] == \"bc\"\nm1[2:4] = \"ad\"\nassert m1 == \"abad\"",
"_____no_output_____"
],
[
"# conversions\nm1 = MutableString(\"abc d\")\nassert(list(m1) == list(\"abc d\"))\nassert(str(m1) == \"abc d\")",
"_____no_output_____"
],
[
"# concatenation\nm1 = MutableString(\"abc\")\nm2 = MutableString(\"def\")\nassert m1 + m2 == \"abcdef\"\nassert m2 + m1 == \"defabc\"",
"_____no_output_____"
],
[
"# multiplication\nm1 = MutableString(\"abc\")\nm3 = m1 * 3\nassert m3 == \"abcabcabc\"",
"_____no_output_____"
],
[
"# operator=\nm1 = MutableString(\"abc\")\nm2 = m1\nm2[0] = \"A\"\nassert m1[1:] == \"bc\"",
"_____no_output_____"
],
[
"# copy\nfrom copy import copy\n\nm1 = MutableString(\"abc\")\nm2 = copy(m1)\nm2[0] = \"A\"\nassert m2 == \"Abc\"",
"_____no_output_____"
],
[
"# concatenation with strings\nm1 = MutableString(\"abc\")\nm2 = m1 + \"def\"\nassert m2 == \"abcdef\"\nm3 = \"def\" + m1\nassert m3 == \"defabc\"",
"_____no_output_____"
],
[
"# in place lowercasing and uppercasing\nm1 = MutableString(\"aBc\")\nm1.to_upper()\nassert m1 == \"ABC\"\nm1 = MutableString(\"aBc\")\nm1.to_lower()",
"_____no_output_____"
],
[
"# containment test\nm1 = MutableString(\"abcdef\")\nassert \"bcd\" in m1\nm2 = MutableString(\"bcd\")\nassert m2 in m1",
"_____no_output_____"
]
],
[
[
"# Text generation\n\n## 3.1 (Same as a laboratory exercise) Write a function that computes N-gram frequencies in a string. (0 point)",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE\nraise NotImplementedError()",
"_____no_output_____"
],
[
"assert(count_ngram_freqs(\"abcc\", 1) == {\"a\": 1, \"b\": 1, \"c\": 2})\nassert(count_ngram_freqs(\"abccab\", 2) == {\"ab\": 2, \"bc\": 1, \"cc\": 1, \"ca\": 1})",
"_____no_output_____"
]
],
[
[
"## 3.2 Define a random text generator function (20 points).\n\nThe function takes 4 arguments:\n\n1. starting text (at least $N-1$ long),\n2. target length: length of the output string,\n3. n-gram frequency dictionary,\n4. N, length of the n-grams.\n\nThe function generates one character at a time given the last $N-1$ characters.\nThe probability of `c` being generated after `ab` is defined as:\n\n$$\nP(c | a b ) = \\frac{\\text{freq}(a b c)}{\\text{freq}(a b)},\n$$\n\nwhere $\\text{freq}(a b c)$ is obtained by counting how many times `abc` occurs in the training corpus (`count_ngram_freqs` function).\n\nIf the generated text ends with a $N-1$-gram that does not occur in the training data, generate the next character from the full character or ngram distribution.",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE\nraise NotImplementedError()",
"_____no_output_____"
],
[
"toy_freqs = count_ngram_freqs(\"abcabcda\", 3)\ngen = generate_text(\"abc\", 5, toy_freqs, 3)\n\nassert(len(gen) == 5)\nassert(set(gen) <= set(\"abcd\"))",
"_____no_output_____"
]
],
[
[
"## 3.3 Test your solution on a small Wikipedia corpus (10 points).\n\nCollect a sample of at least 1 million characters from Wikipedia using the wikipedia module.",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE\nraise NotImplementedError()",
"_____no_output_____"
]
],
[
[
"## \\*3.4 Smoothing (extra exercise, 10 points)\n\nImplement one or more smoothing methods such as Jelinek-Mercer smoothing or Katz's backoff. Train it on your Wikipedia corpus and generate an example.\n\nhttps://nlp.stanford.edu/~wcmac/papers/20050421-smoothing-tutorial.pdf",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE\nraise NotImplementedError()",
"_____no_output_____"
]
],
[
[
"## Code cleanness and PEP8 (10 points)\n\nThis cell is here for technical reasons, you will receive feedback on your code quality here. You do not need to write anything here.",
"_____no_output_____"
],
[
"YOUR ANSWER HERE",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
d0ab2e86a60160e8b1d227f0d6d5c7794193cc10 | 215,664 | ipynb | Jupyter Notebook | mystic.ipynb | jingxlim/tutmom | cda5bac2a1a8c496ec31fc9c54c929e67b9726d7 | [
"BSD-3-Clause"
] | 236 | 2015-07-07T16:07:01.000Z | 2022-03-06T07:15:29.000Z | mystic.ipynb | RahulSundar/tutmom | cda5bac2a1a8c496ec31fc9c54c929e67b9726d7 | [
"BSD-3-Clause"
] | 5 | 2019-11-15T02:00:26.000Z | 2021-01-06T04:26:40.000Z | tutmom-master/mystic.ipynb | sunny2309/scipy_conf_notebooks | 30a85d5137db95e01461ad21519bc1bdf294044b | [
"MIT"
] | 118 | 2015-07-07T18:09:58.000Z | 2021-07-28T09:46:17.000Z | 119.946607 | 72,772 | 0.839213 | [
[
[
"# Optimiztion with `mystic`",
"_____no_output_____"
]
],
[
[
"%matplotlib notebook",
"_____no_output_____"
]
],
[
[
"`mystic`: approximates that `scipy.optimize` interface",
"_____no_output_____"
]
],
[
[
"\"\"\"\nExample:\n - Minimize Rosenbrock's Function with Nelder-Mead.\n - Plot of parameter convergence to function minimum.\n\nDemonstrates:\n - standard models\n - minimal solver interface\n - parameter trajectories using retall\n\"\"\"\n\n# Nelder-Mead solver\nfrom mystic.solvers import fmin\n\n# Rosenbrock function\nfrom mystic.models import rosen\n\n# tools\nimport pylab\n\n\nif __name__ == '__main__':\n\n # initial guess\n x0 = [0.8,1.2,0.7]\n\n # use Nelder-Mead to minimize the Rosenbrock function\n solution = fmin(rosen, x0, disp=0, retall=1)\n allvecs = solution[-1]\n\n # plot the parameter trajectories\n pylab.plot([i[0] for i in allvecs])\n pylab.plot([i[1] for i in allvecs])\n pylab.plot([i[2] for i in allvecs])\n\n # draw the plot\n pylab.title(\"Rosenbrock parameter convergence\")\n pylab.xlabel(\"Nelder-Mead solver iterations\")\n pylab.ylabel(\"parameter value\")\n pylab.legend([\"x\", \"y\", \"z\"])\n pylab.show()",
"_____no_output_____"
]
],
[
[
"Diagnostic tools",
"_____no_output_____"
],
[
"* Callbacks",
"_____no_output_____"
]
],
[
[
"\"\"\"\nExample:\n - Minimize Rosenbrock's Function with Nelder-Mead.\n - Dynamic plot of parameter convergence to function minimum.\n\nDemonstrates:\n - standard models\n - minimal solver interface\n - parameter trajectories using callback\n - solver interactivity\n\"\"\"\n\n# Nelder-Mead solver\nfrom mystic.solvers import fmin\n\n# Rosenbrock function\nfrom mystic.models import rosen\n\n# tools\nfrom mystic.tools import getch\nimport pylab\npylab.ion()\n \n# draw the plot\ndef plot_frame():\n pylab.title(\"Rosenbrock parameter convergence\")\n pylab.xlabel(\"Nelder-Mead solver iterations\")\n pylab.ylabel(\"parameter value\")\n pylab.draw()\n return\n\niter = 0\nstep, xval, yval, zval = [], [], [], []\n# plot the parameter trajectories\ndef plot_params(params):\n global iter, step, xval, yval, zval\n step.append(iter)\n xval.append(params[0])\n yval.append(params[1])\n zval.append(params[2])\n pylab.plot(step,xval,'b-')\n pylab.plot(step,yval,'g-')\n pylab.plot(step,zval,'r-')\n pylab.legend([\"x\", \"y\", \"z\"])\n pylab.draw()\n iter += 1\n return\n\n\nif __name__ == '__main__':\n\n # initial guess\n x0 = [0.8,1.2,0.7]\n\n # suggest that the user interacts with the solver\n print(\"NOTE: while solver is running, press 'Ctrl-C' in console window\")\n getch()\n plot_frame()\n\n # use Nelder-Mead to minimize the Rosenbrock function\n solution = fmin(rosen, x0, disp=1, callback=plot_params, handler=True)\n print(solution)\n\n # don't exit until user is ready\n getch()\n",
"NOTE: while solver is running, press 'Ctrl-C' in console window\nPress any key to continue and press enter\n\nOptimization terminated successfully.\n Current function value: 0.000000\n Iterations: 120\n Function evaluations: 215\n[ 1.00000328 1.00000565 1.00001091]\nPress any key to continue and press enter\n\n"
]
],
[
[
"**NOTE** IPython does not handle shell prompt interactive programs well, so the above should be run from a command prompt. An IPython-safe version is below.",
"_____no_output_____"
]
],
[
[
"\"\"\" \nExample:\n - Minimize Rosenbrock's Function with Powell's method.\n - Dynamic print of parameter convergence to function minimum.\n\nDemonstrates:\n - standard models\n - minimal solver interface\n - parameter trajectories using callback\n\"\"\" \n \n# Powell's Directonal solver\nfrom mystic.solvers import fmin_powell\n \n# Rosenbrock function\nfrom mystic.models import rosen\n \niter = 0\n# plot the parameter trajectories\ndef print_params(params):\n global iter\n from numpy import asarray\n print(\"Generation %d has best fit parameters: %s\" % (iter,asarray(params)))\n iter += 1\n return\n \n\nif __name__ == '__main__':\n \n # initial guess\n x0 = [0.8,1.2,0.7]\n print_params(x0)\n \n # use Powell's method to minimize the Rosenbrock function\n solution = fmin_powell(rosen, x0, disp=1, callback=print_params, handler=False)\n print(solution)",
"Generation 0 has best fit parameters: [ 0.8 1.2 0.7]\nGeneration 1 has best fit parameters: [ 0.8 1.2 0.7]\nGeneration 2 has best fit parameters: [ 1.096641 0.92316246 0.85222892]\nGeneration 3 has best fit parameters: [ 0.96098383 0.92341029 0.85268657]\nGeneration 4 has best fit parameters: [ 0.96116068 0.92362873 0.85268597]\nGeneration 5 has best fit parameters: [ 0.96139941 0.92394456 0.85319715]\nGeneration 6 has best fit parameters: [ 0.96490397 0.9293998 0.86287626]\nGeneration 7 has best fit parameters: [ 0.97283782 0.9438172 0.8900223 ]\nGeneration 8 has best fit parameters: [ 0.99282304 0.98392465 0.9676975 ]\nGeneration 9 has best fit parameters: [ 0.99599362 0.99123752 0.98220233]\nGeneration 10 has best fit parameters: [ 0.99933371 0.99875944 0.9973022 ]\nGeneration 11 has best fit parameters: [ 0.99959358 0.99924252 0.99835369]\nGeneration 12 has best fit parameters: [ 1.00000002 1.00000006 1.00000011]\nGeneration 13 has best fit parameters: [ 1. 1. 1.]\nGeneration 14 has best fit parameters: [ 1. 1. 1.]\nOptimization terminated successfully.\n Current function value: 0.000000\n Iterations: 13\n Function evaluations: 524\n[ 1. 1. 1.]\n"
]
],
[
[
"* Monitors",
"_____no_output_____"
]
],
[
[
"\"\"\"\nExample:\n - Minimize Rosenbrock's Function with Powell's method.\n\nDemonstrates:\n - standard models\n - minimal solver interface\n - customized monitors\n\"\"\"\n\n# Powell's Directonal solver\nfrom mystic.solvers import fmin_powell\n\n# Rosenbrock function\nfrom mystic.models import rosen\n\n# tools\nfrom mystic.monitors import VerboseLoggingMonitor\n\n\nif __name__ == '__main__':\n\n print(\"Powell's Method\")\n print(\"===============\")\n\n # initial guess\n x0 = [1.5, 1.5, 0.7]\n\n # configure monitor\n stepmon = VerboseLoggingMonitor(1,1)\n\n # use Powell's method to minimize the Rosenbrock function\n solution = fmin_powell(rosen, x0, itermon=stepmon)\n print(solution)",
"Powell's Method\n===============\nGeneration 0 has Chi-Squared: 297.000000\nGeneration 1 has Chi-Squared: 26.522040\nGeneration 2 has Chi-Squared: 0.002383\nGeneration 3 has Chi-Squared: 0.002378\nGeneration 4 has Chi-Squared: 0.001940\nGeneration 5 has Chi-Squared: 0.001141\nGeneration 6 has Chi-Squared: 0.000769\nGeneration 7 has Chi-Squared: 0.000125\nGeneration 8 has Chi-Squared: 0.000042\nGeneration 9 has Chi-Squared: 0.000000\nGeneration 10 has Chi-Squared: 0.000000\nGeneration 11 has Chi-Squared: 0.000000\nGeneration 12 has Chi-Squared: 0.000000\nGeneration 13 has Chi-Squared: 0.000000\nGeneration 14 has Chi-Squared: 0.000000\nOptimization terminated successfully.\n Current function value: 0.000000\n Iterations: 14\n Function evaluations: 529\nSTOP(\"NormalizedChangeOverGeneration with {'tolerance': 0.0001, 'generations': 2}\")\n[ 1. 1. 1.]\n"
],
[
"import mystic\nmystic.log_reader('log.txt')",
"_____no_output_____"
]
],
[
[
"* Solution trajectory and model plotting",
"_____no_output_____"
]
],
[
[
"import mystic\nmystic.model_plotter(mystic.models.rosen, 'log.txt', kwds='-d -x 1 -b \"-2:2:.1, -2:2:.1, 1\"')",
"_____no_output_____"
]
],
[
[
"Solver \"tuning\" and extension",
"_____no_output_____"
],
[
"* Solver class interface",
"_____no_output_____"
]
],
[
[
"\"\"\"\nExample:\n - Solve 8th-order Chebyshev polynomial coefficients with DE.\n - Callable plot of fitting to Chebyshev polynomial.\n - Monitor Chi-Squared for Chebyshev polynomial.\n\nDemonstrates:\n - standard models\n - expanded solver interface\n - built-in random initial guess\n - customized monitors and termination conditions\n - customized DE mutation strategies\n - use of monitor to retrieve results information\n\"\"\"\n\n# Differential Evolution solver\nfrom mystic.solvers import DifferentialEvolutionSolver2\n\n# Chebyshev polynomial and cost function\nfrom mystic.models.poly import chebyshev8, chebyshev8cost\nfrom mystic.models.poly import chebyshev8coeffs\n\n# tools\nfrom mystic.termination import VTR\nfrom mystic.strategy import Best1Exp\nfrom mystic.monitors import VerboseMonitor\nfrom mystic.tools import getch, random_seed\nfrom mystic.math import poly1d\nimport pylab\npylab.ion()\n\n# draw the plot\ndef plot_exact():\n pylab.title(\"fitting 8th-order Chebyshev polynomial coefficients\")\n pylab.xlabel(\"x\")\n pylab.ylabel(\"f(x)\")\n import numpy\n x = numpy.arange(-1.2, 1.2001, 0.01)\n exact = chebyshev8(x)\n pylab.plot(x,exact,'b-')\n pylab.legend([\"Exact\"])\n pylab.axis([-1.4,1.4,-2,8],'k-')\n pylab.draw()\n return\n\n# plot the polynomial\ndef plot_solution(params,style='y-'):\n import numpy\n x = numpy.arange(-1.2, 1.2001, 0.01)\n f = poly1d(params)\n y = f(x)\n pylab.plot(x,y,style)\n pylab.legend([\"Exact\",\"Fitted\"])\n pylab.axis([-1.4,1.4,-2,8],'k-')\n pylab.draw()\n return\n\n\nif __name__ == '__main__':\n\n print(\"Differential Evolution\")\n print(\"======================\")\n\n # set range for random initial guess\n ndim = 9\n x0 = [(-100,100)]*ndim\n random_seed(123)\n\n # draw frame and exact coefficients\n plot_exact()\n\n # configure monitor\n stepmon = VerboseMonitor(50)\n\n # use DE to solve 8th-order Chebyshev coefficients\n npop = 10*ndim\n solver = DifferentialEvolutionSolver2(ndim,npop)\n solver.SetRandomInitialPoints(min=[-100]*ndim, max=[100]*ndim)\n solver.SetGenerationMonitor(stepmon)\n solver.enable_signal_handler()\n solver.Solve(chebyshev8cost, termination=VTR(0.01), strategy=Best1Exp, \\\n CrossProbability=1.0, ScalingFactor=0.9, \\\n sigint_callback=plot_solution)\n solution = solver.Solution()\n\n # use monitor to retrieve results information\n iterations = len(stepmon)\n cost = stepmon.y[-1]\n print(\"Generation %d has best Chi-Squared: %f\" % (iterations, cost))\n\n # use pretty print for polynomials\n print(poly1d(solution))\n\n # compare solution with actual 8th-order Chebyshev coefficients\n print(\"\\nActual Coefficients:\\n %s\\n\" % poly1d(chebyshev8coeffs))\n\n # plot solution versus exact coefficients\n plot_solution(solution)\n",
"Differential Evolution\n======================\nGeneration 0 has Chi-Squared: 76214.552493\nGeneration 50 has Chi-Squared: 5823.804953\nGeneration 100 has Chi-Squared: 912.555273\nGeneration 150 has Chi-Squared: 73.593950\nGeneration 200 has Chi-Squared: 10.411967\nGeneration 250 has Chi-Squared: 0.350054\nGeneration 300 has Chi-Squared: 0.010559\nSTOP(\"VTR with {'tolerance': 0.01, 'target': 0.0}\")\nGeneration 312 has best Chi-Squared: 0.008604\n 8 7 6 5 4 3 2\n127.9 x - 0.3241 x - 254.6 x + 0.7937 x + 157.8 x - 0.6282 x - 30.99 x + 0.1701 x + 0.9503\n\nActual Coefficients:\n 8 6 4 2\n128 x - 256 x + 160 x - 32 x + 1\n\n"
],
[
"from mystic.solvers import DifferentialEvolutionSolver\nprint(\"\\n\".join([i for i in dir(DifferentialEvolutionSolver) if not i.startswith('_')]))",
"Collapse\nCollapsed\nFinalize\nSaveSolver\nSetConstraints\nSetEvaluationLimits\nSetEvaluationMonitor\nSetGenerationMonitor\nSetInitialPoints\nSetMultinormalInitialPoints\nSetObjective\nSetPenalty\nSetRandomInitialPoints\nSetReducer\nSetSampledInitialPoints\nSetSaveFrequency\nSetStrictRanges\nSetTermination\nSolution\nSolve\nStep\nTerminated\nUpdateGenealogyRecords\nbestEnergy\nbestSolution\ndisable_signal_handler\nenable_signal_handler\nenergy_history\nevaluations\ngenerations\nsolution_history\n"
]
],
[
[
"* Algorithm configurability",
"_____no_output_____"
],
[
"* Termination conditions",
"_____no_output_____"
]
],
[
[
"from mystic.termination import VTR, ChangeOverGeneration, And, Or\nstop = Or(And(VTR(), ChangeOverGeneration()), VTR(1e-8))\n\nfrom mystic.models import rosen\nfrom mystic.monitors import VerboseMonitor\nfrom mystic.solvers import DifferentialEvolutionSolver\n\nsolver = DifferentialEvolutionSolver(3,40)\nsolver.SetRandomInitialPoints([-10,-10,-10],[10,10,10])\nsolver.SetGenerationMonitor(VerboseMonitor(10))\nsolver.SetTermination(stop)\nsolver.SetObjective(rosen)\nsolver.SetStrictRanges([-10,-10,-10],[10,10,10])\nsolver.SetEvaluationLimits(generations=600)\nsolver.Solve()\n\nprint(solver.bestSolution)",
"Generation 0 has Chi-Squared: 587.458970\nGeneration 10 has Chi-Squared: 2.216492\nGeneration 20 has Chi-Squared: 1.626018\nGeneration 30 has Chi-Squared: 0.229984\nGeneration 40 has Chi-Squared: 0.229984\nGeneration 50 has Chi-Squared: 0.008647\nGeneration 60 has Chi-Squared: 0.000946\nGeneration 70 has Chi-Squared: 0.000109\nGeneration 80 has Chi-Squared: 0.000002\nGeneration 90 has Chi-Squared: 0.000000\nSTOP(\"VTR with {'tolerance': 1e-08, 'target': 0.0}\")\n[ 1.00001435 1.0000254 1.0000495 ]\n"
]
],
[
[
"* Solver population",
"_____no_output_____"
]
],
[
[
"from mystic.solvers import DifferentialEvolutionSolver\nfrom mystic.math import Distribution\nimport numpy as np\nimport pylab\n\n# build a mystic distribution instance\ndist = Distribution(np.random.normal, 5, 1)\n\n# use the distribution instance as the initial population\nsolver = DifferentialEvolutionSolver(3,20)\nsolver.SetSampledInitialPoints(dist)\n\n# visualize the initial population\npylab.hist(np.array(solver.population).ravel())\npylab.show()",
"_____no_output_____"
]
],
[
[
"**EXERCISE:** Use `mystic` to find the minimum for the `peaks` test function, with the bound specified by the `mystic.models.peaks` documentation.",
"_____no_output_____"
],
[
"**EXERCISE:** Use `mystic` to do a fit to the noisy data in the `scipy.optimize.curve_fit` example (the least squares fit).",
"_____no_output_____"
],
[
"Constraints \"operators\" (i.e. kernel transformations)\n\nPENALTY: $\\psi(x) = f(x) + k*p(x)$\n\nCONSTRAINT: $\\psi(x) = f(c(x)) = f(x')$",
"_____no_output_____"
]
],
[
[
"from mystic.constraints import *\nfrom mystic.penalty import quadratic_equality\nfrom mystic.coupler import inner\nfrom mystic.math import almostEqual\nfrom mystic.tools import random_seed\nrandom_seed(213)\n\ndef test_penalize():\n\n from mystic.math.measures import mean, spread\n def mean_constraint(x, target):\n return mean(x) - target\n\n def range_constraint(x, target):\n return spread(x) - target\n\n @quadratic_equality(condition=range_constraint, kwds={'target':5.0})\n @quadratic_equality(condition=mean_constraint, kwds={'target':5.0})\n def penalty(x):\n return 0.0\n\n def cost(x):\n return abs(sum(x) - 5.0)\n\n from mystic.solvers import fmin\n from numpy import array\n x = array([1,2,3,4,5])\n y = fmin(cost, x, penalty=penalty, disp=False)\n\n assert round(mean(y)) == 5.0\n assert round(spread(y)) == 5.0\n assert round(cost(y)) == 4*(5.0)\n\n\ndef test_solve():\n\n from mystic.math.measures import mean\n def mean_constraint(x, target):\n return mean(x) - target\n\n def parameter_constraint(x):\n return x[-1] - x[0]\n\n @quadratic_equality(condition=mean_constraint, kwds={'target':5.0})\n @quadratic_equality(condition=parameter_constraint)\n def penalty(x):\n return 0.0\n\n x = solve(penalty, guess=[2,3,1])\n\n assert round(mean_constraint(x, 5.0)) == 0.0\n assert round(parameter_constraint(x)) == 0.0\n assert issolution(penalty, x)\n\n\ndef test_solve_constraint():\n\n from mystic.math.measures import mean\n @with_mean(1.0)\n def constraint(x):\n x[-1] = x[0]\n return x\n\n x = solve(constraint, guess=[2,3,1])\n\n assert almostEqual(mean(x), 1.0, tol=1e-15)\n assert x[-1] == x[0]\n assert issolution(constraint, x)\n\n\ndef test_as_constraint():\n\n from mystic.math.measures import mean, spread\n def mean_constraint(x, target):\n return mean(x) - target\n\n def range_constraint(x, target):\n return spread(x) - target\n\n @quadratic_equality(condition=range_constraint, kwds={'target':5.0})\n @quadratic_equality(condition=mean_constraint, kwds={'target':5.0})\n def penalty(x):\n return 0.0\n\n ndim = 3\n constraints = as_constraint(penalty, solver='fmin')\n #XXX: this is expensive to evaluate, as there are nested optimizations\n\n from numpy import arange\n x = arange(ndim)\n _x = constraints(x)\n\n assert round(mean(_x)) == 5.0\n assert round(spread(_x)) == 5.0\n assert round(penalty(_x)) == 0.0\n\n def cost(x):\n return abs(sum(x) - 5.0)\n\n npop = ndim*3\n from mystic.solvers import diffev\n y = diffev(cost, x, npop, constraints=constraints, disp=False, gtol=10)\n\n assert round(mean(y)) == 5.0\n assert round(spread(y)) == 5.0\n assert round(cost(y)) == 5.0*(ndim-1)\n\n\ndef test_as_penalty():\n\n from mystic.math.measures import mean, spread\n @with_spread(5.0)\n @with_mean(5.0)\n def constraint(x):\n return x\n\n penalty = as_penalty(constraint)\n\n from numpy import array\n x = array([1,2,3,4,5])\n\n def cost(x):\n return abs(sum(x) - 5.0)\n\n from mystic.solvers import fmin\n y = fmin(cost, x, penalty=penalty, disp=False)\n\n assert round(mean(y)) == 5.0\n assert round(spread(y)) == 5.0\n assert round(cost(y)) == 4*(5.0)\n\n\ndef test_with_penalty():\n\n from mystic.math.measures import mean, spread\n @with_penalty(quadratic_equality, kwds={'target':5.0})\n def penalty(x, target):\n return mean(x) - target\n\n def cost(x):\n return abs(sum(x) - 5.0)\n\n from mystic.solvers import fmin\n from numpy import array\n x = array([1,2,3,4,5])\n y = fmin(cost, x, penalty=penalty, disp=False)\n\n assert round(mean(y)) == 5.0\n assert round(cost(y)) == 4*(5.0)\n\n\ndef test_with_mean():\n\n from mystic.math.measures import mean, impose_mean\n\n @with_mean(5.0)\n def mean_of_squared(x):\n return [i**2 for i in x]\n\n from numpy import array\n x = array([1,2,3,4,5])\n y = impose_mean(5, [i**2 for i in x])\n assert mean(y) == 5.0\n assert mean_of_squared(x) == y\n\n\ndef test_with_mean_spread():\n\n from mystic.math.measures import mean, spread, impose_mean, impose_spread\n\n @with_spread(50.0)\n @with_mean(5.0)\n def constrained_squared(x):\n return [i**2 for i in x]\n\n from numpy import array\n x = array([1,2,3,4,5])\n y = impose_spread(50.0, impose_mean(5.0,[i**2 for i in x]))\n assert almostEqual(mean(y), 5.0, tol=1e-15)\n assert almostEqual(spread(y), 50.0, tol=1e-15)\n assert constrained_squared(x) == y\n\n\ndef test_constrained_solve():\n\n from mystic.math.measures import mean, spread\n @with_spread(5.0)\n @with_mean(5.0)\n def constraints(x):\n return x\n\n def cost(x):\n return abs(sum(x) - 5.0)\n\n from mystic.solvers import fmin_powell\n from numpy import array\n x = array([1,2,3,4,5])\n y = fmin_powell(cost, x, constraints=constraints, disp=False)\n\n assert almostEqual(mean(y), 5.0, tol=1e-15)\n assert almostEqual(spread(y), 5.0, tol=1e-15)\n assert almostEqual(cost(y), 4*(5.0), tol=1e-6)\n\n\nif __name__ == '__main__':\n test_penalize()\n test_solve()\n test_solve_constraint()\n test_as_constraint()\n test_as_penalty()\n test_with_penalty()\n test_with_mean()\n test_with_mean_spread()\n test_constrained_solve()",
"_____no_output_____"
],
[
"from mystic.coupler import and_, or_, not_\nfrom mystic.constraints import and_ as _and, or_ as _or, not_ as _not\n\n\nif __name__ == '__main__':\n import numpy as np\n from mystic.penalty import linear_equality, quadratic_equality\n from mystic.constraints import as_constraint\n\n x = x1,x2,x3 = (5., 5., 1.)\n f = f1,f2,f3 = (np.sum, np.prod, np.average)\n\n k = 100\n solver = 'fmin_powell' #'diffev'\n ptype = quadratic_equality\n\n\n # case #1: couple penalties into a single constraint\n\n p1 = lambda x: abs(x1 - f1(x))\n p2 = lambda x: abs(x2 - f2(x))\n p3 = lambda x: abs(x3 - f3(x))\n p = (p1,p2,p3)\n p = [ptype(pi)(lambda x:0.) for pi in p]\n penalty = and_(*p, k=k)\n constraint = as_constraint(penalty, solver=solver)\n\n x = [1,2,3,4,5]\n x_ = constraint(x)\n\n assert round(f1(x_)) == round(x1)\n assert round(f2(x_)) == round(x2)\n assert round(f3(x_)) == round(x3)\n\n\n # case #2: couple constraints into a single constraint\n\n from mystic.math.measures import impose_product, impose_sum, impose_mean\n from mystic.constraints import as_penalty\n from mystic import random_seed\n random_seed(123)\n\n t = t1,t2,t3 = (impose_sum, impose_product, impose_mean)\n c1 = lambda x: t1(x1, x)\n c2 = lambda x: t2(x2, x)\n c3 = lambda x: t3(x3, x)\n c = (c1,c2,c3)\n\n k=1\n solver = 'buckshot' #'diffev'\n ptype = linear_equality #quadratic_equality\n\n p = [as_penalty(ci, ptype) for ci in c]\n penalty = and_(*p, k=k)\n constraint = as_constraint(penalty, solver=solver)\n\n x = [1,2,3,4,5]\n x_ = constraint(x)\n\n assert round(f1(x_)) == round(x1)\n assert round(f2(x_)) == round(x2)\n assert round(f3(x_)) == round(x3)\n\n\n # etc: more coupling of constraints\n from mystic.constraints import with_mean, discrete\n\n @with_mean(5.0)\n def meanie(x):\n return x\n\n @discrete(list(range(11)))\n def integers(x):\n return x\n\n c = _and(integers, meanie)\n x = c([1,2,3])\n assert x == integers(x) == meanie(x)\n x = c([9,2,3])\n assert x == integers(x) == meanie(x)\n x = c([0,-2,3])\n assert x == integers(x) == meanie(x)\n x = c([9,-200,344])\n assert x == integers(x) == meanie(x)\n\n c = _or(meanie, integers)\n x = c([1.1234, 4.23412, -9])\n assert x == meanie(x) and x != integers(x)\n x = c([7.0, 10.0, 0.0])\n assert x == integers(x) and x != meanie(x)\n x = c([6.0, 9.0, 0.0])\n assert x == integers(x) == meanie(x)\n x = c([3,4,5])\n assert x == integers(x) and x != meanie(x)\n x = c([3,4,5.5])\n assert x == meanie(x) and x != integers(x)\n\n c = _not(integers)\n x = c([1,2,3])\n assert x != integers(x) and x != [1,2,3] and x == c(x)\n x = c([1.1,2,3])\n assert x != integers(x) and x == [1.1,2,3] and x == c(x)\n c = _not(meanie)\n x = c([1,2,3])\n assert x != meanie(x) and x == [1,2,3] and x == c(x)\n x = c([4,5,6])\n assert x != meanie(x) and x != [4,5,6] and x == c(x)\n c = _not(_and(meanie, integers))\n x = c([4,5,6])\n assert x != meanie(x) and x != integers(x) and x != [4,5,6] and x == c(x)\n\n\n # etc: more coupling of penalties\n from mystic.penalty import quadratic_inequality\n\n p1 = lambda x: sum(x) - 5\n p2 = lambda x: min(i**2 for i in x)\n p = p1,p2\n\n p = [quadratic_inequality(pi)(lambda x:0.) for pi in p]\n p1,p2 = p\n penalty = and_(*p)\n\n x = [[1,2],[-2,-1],[5,-5]]\n for xi in x:\n assert p1(xi) + p2(xi) == penalty(xi)\n\n penalty = or_(*p)\n for xi in x:\n assert min(p1(xi),p2(xi)) == penalty(xi)\n\n penalty = not_(p1)\n for xi in x:\n assert bool(p1(xi)) != bool(penalty(xi))\n penalty = not_(p2)\n for xi in x:\n assert bool(p2(xi)) != bool(penalty(xi))\n",
"_____no_output_____"
]
],
[
[
"In addition to being able to generically apply information as a penalty, `mystic` provides the ability to construct constraints \"operators\" -- essentially applying kernel transformations that reduce optimizer search space to the space of solutions that satisfy the constraints. This can greatly accelerate convergence to a solution, as the space that the optimizer can explore is restricted.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nExample:\n - Minimize Rosenbrock's Function with Powell's method.\n\nDemonstrates:\n - standard models\n - minimal solver interface\n - parameter constraints solver and constraints factory decorator\n - statistical parameter constraints\n - customized monitors\n\"\"\"\n\n# Powell's Directonal solver\nfrom mystic.solvers import fmin_powell\n\n# Rosenbrock function\nfrom mystic.models import rosen\n\n# tools\nfrom mystic.monitors import VerboseMonitor\nfrom mystic.math.measures import mean, impose_mean\n\n\nif __name__ == '__main__':\n\n print(\"Powell's Method\")\n print(\"===============\")\n\n # initial guess\n x0 = [0.8,1.2,0.7]\n\n # use the mean constraints factory decorator\n from mystic.constraints import with_mean\n\n # define constraints function\n @with_mean(1.0)\n def constraints(x):\n # constrain the last x_i to be the same value as the first x_i\n x[-1] = x[0]\n return x\n\n # configure monitor\n stepmon = VerboseMonitor(1)\n\n # use Powell's method to minimize the Rosenbrock function\n solution = fmin_powell(rosen, x0, constraints=constraints, itermon=stepmon)\n print(solution)\n",
"Powell's Method\n===============\nGeneration 0 has Chi-Squared: 81.100247\nGeneration 1 has Chi-Squared: 0.000000\nGeneration 2 has Chi-Squared: 0.000000\nOptimization terminated successfully.\n Current function value: 0.000000\n Iterations: 2\n Function evaluations: 81\nSTOP(\"NormalizedChangeOverGeneration with {'tolerance': 0.0001, 'generations': 2}\")\n[ 1. 1. 1.]\n"
]
],
[
[
"* Range (i.e. 'box') constraints",
"_____no_output_____"
],
[
"Use `solver.SetStrictRange`, or the `bounds` keyword on the solver function interface.",
"_____no_output_____"
],
[
"* Symbolic constraints interface",
"_____no_output_____"
]
],
[
[
"%%file spring.py\n\"a Tension-Compression String\"\n\ndef objective(x):\n x0,x1,x2 = x\n return x0**2 * x1 * (x2 + 2)\n\nbounds = [(0,100)]*3\n# with penalty='penalty' applied, solution is:\nxs = [0.05168906, 0.35671773, 11.28896619]\nys = 0.01266523\n\nfrom mystic.symbolic import generate_constraint, generate_solvers, solve\nfrom mystic.symbolic import generate_penalty, generate_conditions\n\nequations = \"\"\"\n1.0 - (x1**3 * x2)/(71785*x0**4) <= 0.0\n(4*x1**2 - x0*x1)/(12566*x0**3 * (x1 - x0)) + 1./(5108*x0**2) - 1.0 <= 0.0\n1.0 - 140.45*x0/(x2 * x1**2) <= 0.0\n(x0 + x1)/1.5 - 1.0 <= 0.0\n\"\"\"\n\npf = generate_penalty(generate_conditions(equations), k=1e12)\n\n\nif __name__ == '__main__':\n\n from mystic.solvers import diffev2\n\n result = diffev2(objective, x0=bounds, bounds=bounds, penalty=pf, npop=40,\n gtol=500, disp=True, full_output=True)\n\n print(result[0])",
"Writing spring.py\n"
],
[
"equations = \"\"\"\n1.0 - (x1**3 * x2)/(71785*x0**4) <= 0.0\n(4*x1**2 - x0*x1)/(12566*x0**3 * (x1 - x0)) + 1./(5108*x0**2) - 1.0 <= 0.0\n1.0 - 140.45*x0/(x2 * x1**2) <= 0.0\n(x0 + x1)/1.5 - 1.0 <= 0.0\n\"\"\"\n\nfrom mystic.symbolic import generate_constraint, generate_solvers, solve\nfrom mystic.symbolic import generate_penalty, generate_conditions\n\nineql, eql = generate_conditions(equations)\n\nprint(\"CONVERTED SYMBOLIC TO SINGLE CONSTRAINTS FUNCTIONS\")\nprint(ineql)\nprint(eql)\n\nprint(\"\\nTHE INDIVIDUAL INEQUALITIES\")\nfor f in ineql:\n print(f.__doc__)\n\nprint(\"\\nGENERATED THE PENALTY FUNCTION FOR ALL CONSTRAINTS\")\npf = generate_penalty((ineql, eql))\nprint(pf.__doc__)\n\nx = [-0.1, 0.5, 11.0]\nprint(\"\\nPENALTY FOR {}: {}\".format(x, pf(x)))",
"CONVERTED SYMBOLIC TO SINGLE CONSTRAINTS FUNCTIONS\n(<function inequality_4606002448 at 0x111d18488>, <function inequality_4604414640 at 0x111d181e0>, <function inequality_4606003984 at 0x112733b70>, <function inequality_4605118704 at 0x1127331e0>)\n()\n\nTHE INDIVIDUAL INEQUALITIES\n1.0 - (x[1]**3 * x[2])/(71785*x[0]**4) - (0.0)\n(4*x[1]**2 - x[0]*x[1])/(12566*x[0]**3 * (x[1] - x[0])) + 1./(5108*x[0]**2) - 1.0 - (0.0)\n1.0 - 140.45*x[0]/(x[2] * x[1]**2) - (0.0)\n(x[0] + x[1])/1.5 - 1.0 - (0.0)\n\nGENERATED THE PENALTY FUNCTION FOR ALL CONSTRAINTS\nquadratic_inequality: 1.0 - (x[1]**3 * x[2])/(71785*x[0]**4) - (0.0)\nquadratic_inequality: (4*x[1]**2 - x[0]*x[1])/(12566*x[0]**3 * (x[1] - x[0])) + 1./(5108*x[0]**2) - 1.0 - (0.0)\nquadratic_inequality: 1.0 - 140.45*x[0]/(x[2] * x[1]**2) - (0.0)\nquadratic_inequality: (x[0] + x[1])/1.5 - 1.0 - (0.0)\n\nPENALTY FOR [-0.1, 0.5, 11.0]: 7590.476190957014\n"
]
],
[
[
"* Penatly functions",
"_____no_output_____"
]
],
[
[
"equations = \"\"\"\n1.0 - (x1**3 * x2)/(71785*x0**4) <= 0.0\n(4*x1**2 - x0*x1)/(12566*x0**3 * (x1 - x0)) + 1./(5108*x0**2) - 1.0 <= 0.0\n1.0 - 140.45*x0/(x2 * x1**2) <= 0.0\n(x0 + x1)/1.5 - 1.0 <= 0.0\n\"\"\"",
"_____no_output_____"
],
[
"\"a Tension-Compression String\"\n\nfrom spring import objective, bounds, xs, ys\n\nfrom mystic.penalty import quadratic_inequality\n\ndef penalty1(x): # <= 0.0\n return 1.0 - (x[1]**3 * x[2])/(71785*x[0]**4)\n\ndef penalty2(x): # <= 0.0\n return (4*x[1]**2 - x[0]*x[1])/(12566*x[0]**3 * (x[1] - x[0])) + 1./(5108*x[0]**2) - 1.0\n\ndef penalty3(x): # <= 0.0\n return 1.0 - 140.45*x[0]/(x[2] * x[1]**2)\n\ndef penalty4(x): # <= 0.0\n return (x[0] + x[1])/1.5 - 1.0\n\n@quadratic_inequality(penalty1, k=1e12)\n@quadratic_inequality(penalty2, k=1e12)\n@quadratic_inequality(penalty3, k=1e12)\n@quadratic_inequality(penalty4, k=1e12)\ndef penalty(x):\n return 0.0\n\n\n\nif __name__ == '__main__':\n\n from mystic.solvers import diffev2\n\n result = diffev2(objective, x0=bounds, bounds=bounds, penalty=penalty, npop=40,\n gtol=500, disp=True, full_output=True)\n print(result[0])",
"Optimization terminated successfully.\n Current function value: 0.012665\n Iterations: 540\n Function evaluations: 21640\n[ 0.05168906 0.35671772 11.28896693]\n"
]
],
[
[
"* \"Operators\" that directly constrain search space",
"_____no_output_____"
]
],
[
[
"\"\"\"\n\n Crypto problem in Google CP Solver.\n\n Prolog benchmark problem\n '''\n Name : crypto.pl\n Original Source: P. Van Hentenryck's book\n Adapted by : Daniel Diaz - INRIA France\n Date : September 1992\n '''\n\"\"\"\n\ndef objective(x):\n return 0.0\n\nnletters = 26\n\nbounds = [(1,nletters)]*nletters\n# with penalty='penalty' applied, solution is:\n# A B C D E F G H I J K L M N O P Q\nxs = [ 5, 13, 9, 16, 20, 4, 24, 21, 25, 17, 23, 2, 8, 12, 10, 19, 7, \\\n# R S T U V W X Y Z\n 11, 15, 3, 1, 26, 6, 22, 14, 18]\nys = 0.0\n\n# constraints\nequations = \"\"\"\nB + A + L + L + E + T - 45 == 0\nC + E + L + L + O - 43 == 0\nC + O + N + C + E + R + T - 74 == 0\nF + L + U + T + E - 30 == 0\nF + U + G + U + E - 50 == 0\nG + L + E + E - 66 == 0\nJ + A + Z + Z - 58 == 0\nL + Y + R + E - 47 == 0\nO + B + O + E - 53 == 0\nO + P + E + R + A - 65 == 0\nP + O + L + K + A - 59 == 0\nQ + U + A + R + T + E + T - 50 == 0\nS + A + X + O + P + H + O + N + E - 134 == 0\nS + C + A + L + E - 51 == 0\nS + O + L + O - 37 == 0\nS + O + N + G - 61 == 0\nS + O + P + R + A + N + O - 82 == 0\nT + H + E + M + E - 72 == 0\nV + I + O + L + I + N - 100 == 0\nW + A + L + T + Z - 34 == 0\n\"\"\"\nvar = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n\n# Let's say we know the vowels.\nbounds[0] = (5,5) # A\nbounds[4] = (20,20) # E\nbounds[8] = (25,25) # I\nbounds[14] = (10,10) # O\nbounds[20] = (1,1) # U\n\nfrom mystic.constraints import unique, near_integers, has_unique\nfrom mystic.symbolic import generate_penalty, generate_conditions\npf = generate_penalty(generate_conditions(equations,var),k=1)\nfrom mystic.penalty import quadratic_equality\n\n@quadratic_equality(near_integers)\n@quadratic_equality(has_unique)\ndef penalty(x):\n return pf(x)\n\nfrom numpy import round, hstack, clip\ndef constraint(x):\n x = round(x).astype(int) # force round and convert type to int\n x = clip(x, 1,nletters) #XXX: hack to impose bounds\n x = unique(x, range(1,nletters+1))\n return x\n\n\nif __name__ == '__main__':\n\n from mystic.solvers import diffev2\n from mystic.monitors import Monitor, VerboseMonitor\n mon = VerboseMonitor(50)\n\n result = diffev2(objective, x0=bounds, bounds=bounds, penalty=pf,\n constraints=constraint, npop=52, ftol=1e-8, gtol=1000,\n disp=True, full_output=True, cross=0.1, scale=0.9, itermon=mon)\n print(result[0])\n",
"Generation 0 has Chi-Squared: 1495.000000\nGeneration 50 has Chi-Squared: 469.000000\nGeneration 100 has Chi-Squared: 270.000000\nGeneration 150 has Chi-Squared: 142.000000\nGeneration 200 has Chi-Squared: 124.000000\nGeneration 250 has Chi-Squared: 106.000000\nGeneration 300 has Chi-Squared: 74.000000\nGeneration 350 has Chi-Squared: 61.000000\nGeneration 400 has Chi-Squared: 38.000000\nGeneration 450 has Chi-Squared: 32.000000\nGeneration 500 has Chi-Squared: 24.000000\nGeneration 550 has Chi-Squared: 24.000000\nGeneration 600 has Chi-Squared: 23.000000\nGeneration 650 has Chi-Squared: 23.000000\nGeneration 700 has Chi-Squared: 21.000000\nGeneration 750 has Chi-Squared: 21.000000\nGeneration 800 has Chi-Squared: 17.000000\nGeneration 850 has Chi-Squared: 13.000000\nGeneration 900 has Chi-Squared: 6.000000\nGeneration 950 has Chi-Squared: 6.000000\nGeneration 1000 has Chi-Squared: 6.000000\nGeneration 1050 has Chi-Squared: 6.000000\nGeneration 1100 has Chi-Squared: 6.000000\nGeneration 1150 has Chi-Squared: 6.000000\nGeneration 1200 has Chi-Squared: 6.000000\nGeneration 1250 has Chi-Squared: 6.000000\nGeneration 1300 has Chi-Squared: 6.000000\nGeneration 1350 has Chi-Squared: 6.000000\nGeneration 1400 has Chi-Squared: 6.000000\nGeneration 1450 has Chi-Squared: 1.000000\nGeneration 1500 has Chi-Squared: 1.000000\nGeneration 1550 has Chi-Squared: 1.000000\nGeneration 1600 has Chi-Squared: 1.000000\nGeneration 1650 has Chi-Squared: 1.000000\nGeneration 1700 has Chi-Squared: 1.000000\nGeneration 1750 has Chi-Squared: 1.000000\nGeneration 1800 has Chi-Squared: 1.000000\nGeneration 1850 has Chi-Squared: 1.000000\nGeneration 1900 has Chi-Squared: 1.000000\nGeneration 1950 has Chi-Squared: 1.000000\nGeneration 2000 has Chi-Squared: 1.000000\nGeneration 2050 has Chi-Squared: 1.000000\nGeneration 2100 has Chi-Squared: 1.000000\nGeneration 2150 has Chi-Squared: 1.000000\nGeneration 2200 has Chi-Squared: 1.000000\nGeneration 2250 has Chi-Squared: 1.000000\nGeneration 2300 has Chi-Squared: 1.000000\nGeneration 2350 has Chi-Squared: 1.000000\nGeneration 2400 has Chi-Squared: 1.000000\nSTOP(\"ChangeOverGeneration with {'tolerance': 1e-08, 'generations': 1000}\")\nOptimization terminated successfully.\n Current function value: 1.000000\n Iterations: 2428\n Function evaluations: 126308\n[ 5. 13. 9. 16. 20. 4. 24. 22. 25. 17. 23. 2. 7. 12. 10.\n 19. 8. 11. 15. 3. 1. 26. 6. 21. 14. 18.]\n"
]
],
[
[
"Special cases",
"_____no_output_____"
],
[
"* Integer and mixed integer programming",
"_____no_output_____"
]
],
[
[
"\"\"\"\n Eq 10 in Google CP Solver.\n\n Standard benchmark problem.\n\"\"\"\n\ndef objective(x):\n return 0.0\n\nbounds = [(0,10)]*7\n# with penalty='penalty' applied, solution is:\nxs = [6., 0., 8., 4., 9., 3., 9.]\nys = 0.0\n\n# constraints\nequations = \"\"\"\n98527*x0 + 34588*x1 + 5872*x2 + 59422*x4 + 65159*x6 - 1547604 - 30704*x3 - 29649*x5 == 0.0\n98957*x1 + 83634*x2 + 69966*x3 + 62038*x4 + 37164*x5 + 85413*x6 - 1823553 - 93989*x0 == 0.0\n900032 + 10949*x0 + 77761*x1 + 67052*x4 - 80197*x2 - 61944*x3 - 92964*x5 - 44550*x6 == 0.0\n73947*x0 + 84391*x2 + 81310*x4 - 1164380 - 96253*x1 - 44247*x3 - 70582*x5 - 33054*x6 == 0.0\n13057*x2 + 42253*x3 + 77527*x4 + 96552*x6 - 1185471 - 60152*x0 - 21103*x1 - 97932*x5 == 0.0\n1394152 + 66920*x0 + 55679*x3 - 64234*x1 - 65337*x2 - 45581*x4 - 67707*x5 - 98038*x6 == 0.0\n68550*x0 + 27886*x1 + 31716*x2 + 73597*x3 + 38835*x6 - 279091 - 88963*x4 - 76391*x5 == 0.0\n76132*x1 + 71860*x2 + 22770*x3 + 68211*x4 + 78587*x5 - 480923 - 48224*x0 - 82817*x6 == 0.0\n519878 + 94198*x1 + 87234*x2 + 37498*x3 - 71583*x0 - 25728*x4 - 25495*x5 - 70023*x6 == 0.0\n361921 + 78693*x0 + 38592*x4 + 38478*x5 - 94129*x1 - 43188*x2 - 82528*x3 - 69025*x6 == 0.0\n\"\"\"\n\nfrom mystic.symbolic import generate_constraint, generate_solvers, solve\ncf = generate_constraint(generate_solvers(solve(equations)))\n\n\nif __name__ == '__main__':\n\n from mystic.solvers import diffev2\n\n result = diffev2(objective, x0=bounds, bounds=bounds, constraints=cf,\n npop=4, gtol=1, disp=True, full_output=True)\n\n print(result[0])",
"Optimization terminated successfully.\n Current function value: 0.000000\n Iterations: 1\n Function evaluations: 14\n[ 6. 0. 8. 4. 9. 3. 9.]\n"
]
],
[
[
"**EXERCISE:** Solve the `chebyshev8.cost` example exactly, by applying the knowledge that the last term in the chebyshev polynomial will always be be one. Use `numpy.round` or `mystic.constraints.integers` or to constrain solutions to the set of integers. Does using `mystic.suppressed` to supress small numbers accelerate the solution?",
"_____no_output_____"
],
[
"**EXERCISE:** Replace the symbolic constraints in the following \"Pressure Vessel Design\" code with explicit penalty functions (i.e. use a compound penalty built with `mystic.penalty.quadratic_inequality`).",
"_____no_output_____"
]
],
[
[
"\"Pressure Vessel Design\"\n\ndef objective(x):\n x0,x1,x2,x3 = x\n return 0.6224*x0*x2*x3 + 1.7781*x1*x2**2 + 3.1661*x0**2*x3 + 19.84*x0**2*x2\n\nbounds = [(0,1e6)]*4\n# with penalty='penalty' applied, solution is:\nxs = [0.72759093, 0.35964857, 37.69901188, 240.0]\nys = 5804.3762083\n\nfrom mystic.symbolic import generate_constraint, generate_solvers, solve\nfrom mystic.symbolic import generate_penalty, generate_conditions\n\nequations = \"\"\"\n-x0 + 0.0193*x2 <= 0.0\n-x1 + 0.00954*x2 <= 0.0\n-pi*x2**2*x3 - (4/3.)*pi*x2**3 + 1296000.0 <= 0.0\nx3 - 240.0 <= 0.0\n\"\"\"\npf = generate_penalty(generate_conditions(equations), k=1e12)\n\n\nif __name__ == '__main__':\n\n from mystic.solvers import diffev2\n from mystic.math import almostEqual\n\n result = diffev2(objective, x0=bounds, bounds=bounds, penalty=pf, npop=40, gtol=500,\n disp=True, full_output=True)\n print(result[0])\n",
"Optimization terminated successfully.\n Current function value: 5804.376208\n Iterations: 950\n Function evaluations: 38040\n[ 0.72759093 0.35964857 37.69901188 240. ]\n"
]
],
[
[
"* Linear and quadratic constraints",
"_____no_output_____"
]
],
[
[
"\"\"\"\n Minimize: f = 2*x[0] + 1*x[1]\n\n Subject to: -1*x[0] + 1*x[1] <= 1\n 1*x[0] + 1*x[1] >= 2\n 1*x[1] >= 0\n 1*x[0] - 2*x[1] <= 4\n\n where: -inf <= x[0] <= inf\n\"\"\"\n\ndef objective(x):\n x0,x1 = x\n return 2*x0 + x1\n\nequations = \"\"\"\n-x0 + x1 - 1.0 <= 0.0\n-x0 - x1 + 2.0 <= 0.0\nx0 - 2*x1 - 4.0 <= 0.0\n\"\"\"\nbounds = [(None, None),(0.0, None)]\n\n# with penalty='penalty' applied, solution is:\nxs = [0.5, 1.5]\nys = 2.5\n\nfrom mystic.symbolic import generate_conditions, generate_penalty\npf = generate_penalty(generate_conditions(equations), k=1e3)\nfrom mystic.symbolic import generate_constraint, generate_solvers, simplify\ncf = generate_constraint(generate_solvers(simplify(equations)))\n\n\nif __name__ == '__main__':\n\n from mystic.solvers import fmin_powell\n from mystic.math import almostEqual\n\n result = fmin_powell(objective, x0=[0.0,0.0], bounds=bounds, constraint=cf,\n penalty=pf, disp=True, full_output=True, gtol=3)\n print(result[0])",
"Optimization terminated successfully.\n Current function value: 2.499688\n Iterations: 6\n Function evaluations: 277\n[ 0.49974959 1.49987526]\n"
]
],
[
[
"**EXERCISE:** Solve the `cvxopt` \"qp\" example with `mystic`. Use symbolic constaints, penalty functions, or constraints operators. If you get it quickly, do all three methods.",
"_____no_output_____"
],
[
"Let's look at how `mystic` gives improved [solver workflow](workflow.ipynb)",
"_____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"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
d0ab4ebcaa9ea2aaa61a66f0a9951f9935657948 | 173,108 | ipynb | Jupyter Notebook | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter | 4e452a135aef1de72a17b8c18910d6e0bc0fc4e9 | [
"FTL"
] | null | null | null | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter | 4e452a135aef1de72a17b8c18910d6e0bc0fc4e9 | [
"FTL"
] | 3 | 2021-09-08T02:27:42.000Z | 2022-03-12T01:10:38.000Z | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter | 4e452a135aef1de72a17b8c18910d6e0bc0fc4e9 | [
"FTL"
] | null | null | null | 217.199498 | 26,776 | 0.901414 | [
[
[
"# libraries",
"_____no_output_____"
]
],
[
[
"import sys\nimport os\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport en_core_web_sm\nfrom spacy.matcher import Matcher\n\n%matplotlib inline\n\n# to import Database class from data_collection folder\nmodule_path = os.path.abspath(os.path.join('../..')+'/data/data_collection')\nif module_path not in sys.path:\n sys.path.append(module_path)\n\n# now that the folder is in the path, ../data_collection/database.py can be imported\nfrom storage_managers.database import Database",
"_____no_output_____"
]
],
[
[
"# Import reviews data and target feature",
"_____no_output_____"
]
],
[
[
"db = Database()\n\n# get halal-reviews (reviews that include the word 'halal')\nreviews_sql = '''SELECT * FROM reviews'''\nreviews_df = db.select_df(reviews_sql)\nprint('- {} reviews containing the word halal were scraped'.format(reviews_df.shape[0]))\n\n# get target restaurants-of-interest list \nfile_path = '/Users/wesamazaizeh/Desktop/Projects/halal_o_meter/src/features/target_feature/label_target.csv'\ntarget_df = pd.read_csv(file_path, index_col=0)\ntarget_df['halal'] = target_df['halal'].str.replace('FLASE', 'FALSE')\ntarget_df['halal'] = target_df['halal'].apply(lambda x: True if x =='TRUE' else False)\nhalal_frac = target_df['halal'].sum()/target_df.shape[0]\n\nprint('- {:.0f}% of the {} restaurants-of-interest are halal'.format(halal_frac*100, target_df.shape[0]))",
"- 5092 reviews containing the word halal were scraped\n- 73% of the 838 restaurants-of-interest are halal\n"
]
],
[
[
"# Feature Engineering\n## 1. 'halal' in business name",
"_____no_output_____"
]
],
[
[
"# patch missing platform_ids and mismatch in target data\n\n# import original businesses data\nrest_sql = '''SELECT * FROM businesses WHERE url LIKE '%yelp%' '''\nrest_df = db.select_df(rest_sql)\n\n# drop Aya Kitchen\naya_id = 'y6BfLt9Gvrq2JsJvjkjdIQ'\nreviews_df.drop(reviews_df[reviews_df['restaurant_id'] == aya_id].index, inplace=True)\n\n# patch platform_id in target_df\ntarget_df = target_df.merge(rest_df[['platform_id', 'url']], how='left', on='url')\ntarget_df.drop('platform_id_x', inplace=True, axis=1)\ntarget_df = target_df.rename(columns={'platform_id_y' : 'platform_id'})",
"_____no_output_____"
],
[
"# group reviews per restaurant\ngrouped_reviews_df = reviews_df.groupby('restaurant_id').agg(lambda x: ' '.join(x)) # combine review text\ngrouped_reviews_df['review_date'] = grouped_reviews_df['review_date'].apply(lambda x: x.split()) # make dates list\ngrouped_reviews_df['review_count'] = grouped_reviews_df['review_date'].apply(lambda x: len(x)) # count reviews per restaurnat\ngrouped_reviews_df.head()\n\n# merge restaurant name \ngrouped_reviews_df = grouped_reviews_df.merge(target_df[['platform_id', 'name', 'total_review_count', 'halal']], how='left', left_index=True, right_on='platform_id')\n\ngrouped_reviews_df.index = grouped_reviews_df['platform_id']\ngrouped_reviews_df.drop('platform_id', inplace=True, axis=1)\ngrouped_reviews_df = grouped_reviews_df.rename(columns={'name': 'restaurant_name', 'review_count' : 'halal_review_count'})\n\n# add boolean column for 'halal' in rest_name\ngrouped_reviews_df['halal_in_name'] = grouped_reviews_df.apply(lambda row: True if 'halal' in row['restaurant_name'].lower() else False, axis=1)\n\nplt.figure(figsize=(14,8))\ng = sns.countplot(x='halal', hue='halal_in_name', data=grouped_reviews_df)\ng.set_title('Distribution of halal_in_name feature', size=14)\ng_labels = g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalalignment='right')\nfor p in g.patches:\n g.annotate('{:.0f}'.format(p.get_height()), (p.get_x()+0.3, p.get_height()),\n ha='center', va='bottom', color= 'black')",
"_____no_output_____"
]
],
[
[
"## 2. Percentage of reviews including the word halal out of all reviews",
"_____no_output_____"
]
],
[
[
"# calculate percentage of halal-containing reviews out of total reviews\ngrouped_reviews_df['halal_review_percent'] = grouped_reviews_df.apply(lambda row: row['halal_review_count']/row['total_review_count'], axis =1)\n\n# plot distribution for halal vs non-halal restaurants\nhalal_target = grouped_reviews_df[grouped_reviews_df['halal']]['halal_review_percent']\nnon_halal_target = grouped_reviews_df[~grouped_reviews_df['halal']]['halal_review_percent']\nfig = plt.figure(figsize=(14,8))\ng1 = sns.distplot(halal_target*100, kde=False)\ng2 = sns.distplot(non_halal_target*100, kde=False)\ng1.set_title('Distribution of the percent of halal-reviews out of all reviews for restaurant-of-interest', size=14)\ng1.set_xlabel('% of halal review', size=14)\ng1.set_ylabel('Count', size=14)\nplt.legend(labels=['Halal restaurants','Non-halal restaurants'], prop={'size': 10})\nplt.show()",
"_____no_output_____"
],
[
"grouped_reviews_df[(grouped_reviews_df['halal_review_percent'] > 0.9) & (~grouped_reviews_df['halal'])]",
"_____no_output_____"
]
],
[
[
"- The higher percentage of halal-related reviews in non-halal restaurants is probably related to food carts or restaurants with few reviews to start with and they have comparison to halal-guys or halal street cuisine ",
"_____no_output_____"
],
[
"## 3. Spacy nlp to find text patterns\n### 3.1. tokenize and match pattern [lemma=be, lower=halal]",
"_____no_output_____"
]
],
[
[
"# # run nlp of grouped review text and save Doc to dataframe\n# nlp = en_core_web_sm.load()\n# grouped_reviews_df['doc'] = grouped_reviews_df['review_text'].apply(lambda x: nlp(x))\n\n# initialize matcher\nmatcher = Matcher(nlp.vocab)\n\n# specify match pattern\npattern = [{'LEMMA': 'be'},{'LOWER': 'halal'}]\nmatcher.add('be_halal', None, pattern)\n\n# match and print the first few setences\nc=10\nfor i, doc in grouped_reviews_df['doc'].iteritems():\n match = matcher(doc)\n count = len(match)\n grouped_reviews_df.loc[i, 'be_halal_count'] = count\n grouped_reviews_df.loc[i, 'be_halal'] = True if count>0 else False\n if c>0:\n for match_id, start, end in match:\n print(doc[start:end].sent)\n c -= 1",
"Love this place and love that it's halal.\nand they happen to be halal!\nLove that it's halal and delicious.\nThe entire menu is halal and although they do not serve alcohol, you are welcome bring your own.\nThe meat are halal.\nI have asked them verbally three times if their meat is halal\n, everything is halal.\nboth times was told again yes - everything is halal.\n\n\nIf you only have a partially halal menu, then do not mislead customers by saying everything you serve is halal.\nOh and if you're a Halal foodie then you're in luck because this place is Halal.\n\n\nA definite plus being halal for the Muslim community.\n"
],
[
"# plot distribution of number of matches found for halal vs. non-halal restaurants\nhalal_target = grouped_reviews_df[grouped_reviews_df['halal']]['be_halal_count']\nnon_halal_target = grouped_reviews_df[~grouped_reviews_df['halal']]['be_halal_count']\nfig = plt.figure(figsize=(14,8))\ng1 = sns.distplot(halal_target, kde=False, norm_hist=True,)\ng2 = sns.distplot(non_halal_target, kde=False, norm_hist=True,)\ng1.set_title('Distribution of the count of is halal in reviews', size=14)\ng1.set_xlabel('Count of is_halal mention', size=14)\nplt.legend(labels=['Halal restaurants','Non-halal restaurants'], prop={'size': 10})\nplt.show()",
"_____no_output_____"
],
[
"# barplot of categorical be_halal\nplt.figure(figsize=(14,8))\ng = sns.countplot(x='halal', hue='be_halal', data=grouped_reviews_df)\ng.set_title('Distribution of is halal mention in reviews', size=14)\ng_labels = g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalalignment='right')\nfor p in g.patches:\n g.annotate('{:.0f}'.format(p.get_height()), (p.get_x()+0.3, p.get_height()),\n ha='center', va='bottom', color= 'black')",
"_____no_output_____"
]
],
[
[
"### 3.2. Match pattern 'halal guys/ truck' and count how many it occurs out of all the mentiones of halal",
"_____no_output_____"
]
],
[
[
"# initialize matcher\nmatcher = Matcher(nlp.vocab)\n\n# find all incidences of halal\npattern = [{'LOWER': 'halal'}]\nmatcher.add('halal', None, pattern)\nfor i, doc in grouped_reviews_df['doc'].iteritems():\n match = matcher(doc)\n grouped_reviews_df.loc[i, 'halal_match_count'] = len(match)\n\n# reinitialize matcher\nmatcher = Matcher(nlp.vocab)\n\n# match 'halal guys'\npattern1 = [{'LOWER': 'halal'}, {'LOWER': 'guys'}]\npattern2 = [{'LOWER': 'halal'}, {'LOWER': 'truck'}]\npattern3 = [{'LOWER': 'halal'}, {'LOWER': 'trucks'}]\nmatcher.add('halal_guys', None, pattern1)\nmatcher.add('halal_guys', None, pattern2)\nmatcher.add('halal_guys', None, pattern3)\n\n# match and print the first few setences\nc=10\nfor i, doc in grouped_reviews_df['doc'].iteritems():\n match = matcher(doc)\n grouped_reviews_df.loc[i, 'halal_guys_count'] = len(match)\n if c>0:\n for match_id, start, end in match:\n print(doc[start:end].sent)\n c -= 1\n \ngrouped_reviews_df['halal_guys_percent'] = grouped_reviews_df.apply(lambda row: row['halal_guys_count'] / row['halal_match_count'], axis=1)",
"This is he halal truck that made me fall in love with halal trucks!\nThis is he halal truck that made me fall in love with halal trucks!\nQuick, better than halal guys, and have a magical green sauce.\nThe halal guys at midtown are only good for quantity, and considering how they charge you $7, I think the price to quantity ratio is about the same. \nThis Starbucks is right in front of Halal Guys\nThis starbucks was conveniently located right next to Halal Guys, and so we decided to stop by to get some drinks after eating.\n"
],
[
"# plot distribution of 'halal guys' mention out of all 'halal' mentions for halal vs. non-halal restaurants\nhalal_target = grouped_reviews_df[grouped_reviews_df['halal']]['halal_guys_percent']\nnon_halal_target = grouped_reviews_df[~grouped_reviews_df['halal']]['halal_guys_percent']\nfig = plt.figure(figsize=(14,8))\ng1 = sns.distplot(halal_target*100, kde=False, norm_hist=True,)\ng2 = sns.distplot(non_halal_target*100, kde=False, norm_hist=True,)\ng1.set_title('Distribution of the halal guys/halal mentions out of all reviews for restaurant-of-interest', size=14)\ng1.set_xlabel('% of halal guys mentios out of all mentions of halal', size=14)\ng1.set_ylabel('Count', size=14)\nplt.legend(labels=['Halal restaurants','Non-halal restaurants'], prop={'size': 10})\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 3.3. mention of halal chicken vs. halal burger",
"_____no_output_____"
]
],
[
[
"# initialize matcher\nmatcher = Matcher(nlp.vocab)\n\n# contains halal chicken\npattern1 = [{'LOWER': 'halal'}, {'LOWER': 'chicken'}]\nmatcher.add('chicken', None, pattern1)\nfor i, doc in grouped_reviews_df['doc'].iteritems():\n match = matcher(doc)\n grouped_reviews_df.loc[i, 'chicken'] = True if len(match) else False\n\n # initialize matcher\nmatcher = Matcher(nlp.vocab)\n\n# contains halal burger\npattern2 = [{'LOWER': 'halal'}, {'LOWER': 'burger'}]\nmatcher.add('burger', None, pattern2)\nfor i, doc in grouped_reviews_df['doc'].iteritems():\n match = matcher(doc)\n grouped_reviews_df.loc[i, 'burger'] = True if len(match) else False\n\n# initialize matcher\nmatcher = Matcher(nlp.vocab)\n\n# contains CreekStone # a company with halal certified steaks and beef but these products are often cooked on the\n# grill alongside non-halal ingerdients\npattern2 = [{'LOWER': 'creekstone'}]\nmatcher.add('creekstone', None, pattern2)\nfor i, doc in grouped_reviews_df['doc'].iteritems():\n match = matcher(doc)\n grouped_reviews_df.loc[i, 'creekstone'] = True if len(match) else False",
"_____no_output_____"
],
[
"# barplot of chicken, burger and CreekStone\nfig, axes = plt.subplots(ncols=3, nrows=1, figsize=(14,10))\n\ncolumns = ['chicken', 'burger', 'creekstone']\nfor col, ax in zip(columns, axes.flat):\n g = sns.countplot(x='halal', hue=col, data=grouped_reviews_df, ax=ax)\n g_labels = g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalalignment='right')\n for p in g.patches:\n g.annotate('{:.0f}'.format(p.get_height()), (p.get_x()+0.3, p.get_height()),\n ha='center', va='bottom', color= 'black')\n ax.set_xlabel('halal', size=14)\n ax.set_xticklabels(labels=ax.get_xticks(), rotation=45, ha='right')\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"- When combined with halal chicken and burger do not provide significant information. \n- Consider trying more combinations with 'chicken', such as 'chicken over rice' or chicken as DEP=compound noun.\n- CreekStone has 2:1 chance of being mentioned in non-halal vs. halal restaurant.",
"_____no_output_____"
],
[
"### 3.4. Mention of '100% halal'",
"_____no_output_____"
]
],
[
[
"# initialize matcher\nmatcher = Matcher(nlp.vocab)\n\n# contains halal chicken\npattern3 = [{'IS_DIGIT': True, 'LOWER': '100'},\n {'IS_PUNCT': True},\n {'LOWER': 'halal'}]\nmatcher.add('100%', None, pattern3)\nfor i, doc in grouped_reviews_df['doc'].iteritems():\n match = matcher(doc)\n grouped_reviews_df.loc[i, '100%'] = True if len(match) else False\n\nplt.figure(figsize=(14,8))\ng = sns.countplot(x='halal', hue='100%', data=grouped_reviews_df)\ng.set_title('Mention of 100% halal', size=14)\ng_labels = g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalalignment='right')\nfor p in g.patches:\n g.annotate('{:.0f}'.format(p.get_height()), (p.get_x()+0.3, p.get_height()),\n ha='center', va='bottom', color= 'black')",
"_____no_output_____"
]
],
[
[
"### 3.5. Mention of non-halal terms",
"_____no_output_____"
],
[
"## 4. Examine the term frequency in the labeling notes",
"_____no_output_____"
]
],
[
[
"import spacy.attrs\n\nhalal_dicts = []\nnon_halal_dicts = []\n\n# for i, note in target_df['note_1'].iteritems():\n# if note:\n# doc = nlp(str(note))\n# counts_dict = doc.count_by(spacy.attrs.IDS['LEMMA'])\n# halal_dicts.append(counts_dict)\n\n\ndoc=nlp(target_df['note_1'].iloc[704].lower())\ncounts_dict = doc.count_by(spacy.attrs.IDS['LEMMA'])\n# Print the human readable part of speech tags\nfor lemma, count in counts_dict.items():\n human_readable_tag = doc.vocab[lemma].text\n print(human_readable_tag,lemma, count)\n \n",
"meat 10145736325826752106 1\nand 2283656566040971221 1\nchicken 11593913656828918848 1\nbe 10382539506755952630 1\nzabihah 4871322777386070092 1\n� 15133719645169837349 2\nhalal 12288342265014770467 1\n. 12646065887601541794 1\n"
],
[
"doc=nlp(target_df['note_1'].iloc[705].lower())\ncounts_dict = doc.count_by(spacy.attrs.IDS['LEMMA'])\n# Print the human readable part of speech tags\nfor lemma, count in counts_dict.items():\n human_readable_tag = doc.vocab[lemma].text\n print(human_readable_tag,lemma, count)",
"veggie 17659162195392082590 1\nraman 15907565465263018957 1\nbe 10382539506755952630 1\n� 15133719645169837349 2\nhalal 12288342265014770467 1\nand 2283656566040971221 1\nmake 9614445426764226664 1\nwith 12510949447758279278 1\nvegetable 10226061632043966089 1\nbroth 2343545011278681547 2\nfor 16037325823156266367 1\nall 13409319323822384369 1\n-PRON- 561228191312463089 1\nmuslim 123001378226201854 1\nfriend 16302678419497547123 1\n( 12638816674900267446 1\nthe 7425985699627899538 1\nother 1176656782636220709 1\none 17454115351911680600 1\nhave 14692702688101715474 1\npork 13061448519093429940 1\n) 3842344029291005339 1\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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
d0ab58206b34e616293a8e9a99631eacf70b9723 | 19,119 | ipynb | Jupyter Notebook | quetzal_germany-master/notebooks/cal21_inner-zone_estimation.ipynb | avi-shake/Flensburg_Modeling | 53ebc78813c05f1f3f9157ed0d74ef505b4e6e24 | [
"Apache-2.0"
] | null | null | null | quetzal_germany-master/notebooks/cal21_inner-zone_estimation.ipynb | avi-shake/Flensburg_Modeling | 53ebc78813c05f1f3f9157ed0d74ef505b4e6e24 | [
"Apache-2.0"
] | null | null | null | quetzal_germany-master/notebooks/cal21_inner-zone_estimation.ipynb | avi-shake/Flensburg_Modeling | 53ebc78813c05f1f3f9157ed0d74ef505b4e6e24 | [
"Apache-2.0"
] | null | null | null | 53.405028 | 2,032 | 0.631675 | [
[
[
"import pandas as pd\nimport numpy as np\nimport biogeme.database as db\nimport biogeme.biogeme as bio\nimport biogeme.models as models\nimport biogeme.messaging as message\nfrom biogeme.expressions import Beta",
"_____no_output_____"
]
],
[
[
"# Intra-zonal trips\n## Parameter estimation\nAssignment of inner-zonal trips is not possible with common methods of transport modelling. A Logit regression based on zonal attributes is required.",
"_____no_output_____"
]
],
[
[
"input_path = '../input/'\noutput_path = '../output/'\nmodel_path = '../model/'",
"_____no_output_____"
]
],
[
[
"### Model formulation\nThe Logit regression model consists of observable utility functions, one for each mode j:\n> V_ij = ASC_ij + b_ac_i * AC_j + b_pop_i * POP + b_cars_i * CARS\n\nWith explainatory variables\n* AC: accessibility as average distance to and from PT stops in km or binary for car usage\n* POP: population density\n* CARS: car ownership density\n* ROADS: road density in km/km² -- not implemented\n* INCOME: household income -- not implemented\n\nIndex i marks the demand group. I = {'commuting' (1), 'education' (2), 'shopping/medical' (3), 'official' (4), 'private' (6)}",
"_____no_output_____"
]
],
[
[
"# Load calibration data set\ndf = pd.read_csv(input_path + 'transport_demand/calibration_intra-cellular_trips_MiD2017.csv')\nprint(df.shape)",
"_____no_output_____"
],
[
"col_dict = {'mode_model': 'MODE', 'purpose_vp': 'PURPOSE', 'pop_density': 'POP',\n 'car_density': 'CARS', 'accessibility_rail': 'AC_RAIL',\n 'accessibility_bus': 'AC_BUS', 'accessibility_car': 'AC_CAR',\n 'accessibility_walk': 'AC_NM'}\ndf.rename(columns=col_dict, inplace=True)",
"_____no_output_____"
],
[
"# Remove unused columns\ndf = df[[col for _, col in col_dict.items()]]",
"_____no_output_____"
],
[
"# Remove trips where mode is car but the car availability is zero\n# because it irritates the MLE algorithm\nmask = ((df['MODE']==6) & (df['AC_CAR']==0))\nprint('Share of car trips dropped: {}. New number of observations is {}'.format(\n len(df.loc[mask])/len(df.loc[df['MODE']==6]), len(df.loc[~mask])))\ndf = df.loc[~mask]",
"_____no_output_____"
]
],
[
[
"### Build the calibration model with Biogeme",
"_____no_output_____"
]
],
[
[
"database = db.Database('MiD', df.copy())\nglobals().update(database.variables)\ndatabase.getSampleSize()",
"_____no_output_____"
],
[
"# Define Betas\nasc_rail = Beta('asc_rail', 0, None, None, 0)\nasc_bus = Beta('asc_bus', 0, None, None, 0)\nasc_car = Beta('asc_car', 0, None, None, 1)\nasc_nm = Beta('asc_nm', 0, None, None, 0)\nb_ac_rail = Beta('b_ac_rail', 0, None, None, 0)\nb_pop_rail = Beta('b_pop_rail', 0, None, None, 0)\nb_cars_rail = Beta('b_cars_rail', 0, None, None, 0)\nb_ac_bus = Beta('b_ac_bus', 0, None, None, 0)\nb_pop_bus = Beta('b_pop_bus', 0, None, None, 0)\nb_cars_bus = Beta('b_cars_bus', 0, None, None, 0)\nb_ac_car = Beta('b_ac_car', 0, None, None, 0)\nb_pop_car = Beta('b_pop_car', 0, None, None, 0)\nb_cars_car = Beta('b_cars_car', 0, None, None, 0)\nb_ac_nm = Beta('b_ac_nm', 0, None, None, 0)\nb_pop_nm = Beta('b_pop_nm', 0, None, None, 0)\nb_cars_nm = Beta('b_cars_nm', 0, None, None, 0)",
"_____no_output_____"
],
[
"# Parameter for the nested logit structure\nmu_pt = Beta('mu_pt', 1, 1, 10, 0)",
"_____no_output_____"
],
[
"# Utility functions\nV_RAIL = asc_rail + b_ac_rail * AC_RAIL + b_pop_rail * POP + b_cars_rail * CARS\nV_BUS = asc_bus + b_ac_bus * AC_BUS + b_pop_bus * POP + b_cars_bus * CARS\nV_CAR = asc_car + b_ac_car * AC_CAR + b_pop_car * POP + b_cars_car * CARS\nV_NM = asc_nm + b_ac_nm * AC_NM + b_pop_nm * POP + b_cars_nm * CARS",
"_____no_output_____"
],
[
"# Define level of verbosity\nlogger = message.bioMessage()\n#logger.setSilent()\nlogger.setWarning()\n#logger.setGeneral()\n#logger.setDetailed()",
"_____no_output_____"
],
[
"# Map modes to utility functions\nV = {1:V_RAIL,\n 2:V_RAIL,\n 4:V_BUS,\n 6:V_CAR,\n 7:V_NM}",
"_____no_output_____"
],
[
"# Map the availability of alternatives with MODE as key\n# Except for the car, it is always one\nav = {1:1,\n 2:1,\n 4:1,\n 6:AC_CAR,\n 7:1}",
"_____no_output_____"
],
[
"# Mode nests as tuples with nest name and dictionary where\n# alternative IDs are mapped to alpha values. Missing ID's alpha is zero\nnests = ((mu_pt, [1,2, 4]), # PT\n (1, [6]), # Car\n (1, [7])) # Non-motorised",
"_____no_output_____"
],
[
"# Choose the logarithmic nested logit model\nnl = models.lognested(V, av, nests, MODE)",
"_____no_output_____"
],
[
"# All purposes\nmodel_nl = bio.BIOGEME(database, nl)\nmodel_nl.modelName = 'NL'\nresults = model_nl.estimate()",
"_____no_output_____"
],
[
"# Write results to a file\nwriter = pd.ExcelWriter(input_path + 'estimation_results_inner_cell.xlsx', engine='xlsxwriter')",
"_____no_output_____"
],
[
"params = results.getEstimatedParameters()\nfor key, val in results.getGeneralStatistics().items():\n params.loc[key] = [val[0], val[1]] + ['' for i in range(len(params.columns)-2)]\nparams",
"_____no_output_____"
],
[
"params.to_excel(writer, sheet_name=model_nl.modelName)",
"_____no_output_____"
],
[
"# Run all purposes\nresults = []\nfor p in [1,2,3,4,6]:\n database = db.Database('MiD2017', df.copy())\n database.remove(PURPOSE!=p)\n print('Sample size for purpose {}: {}'.format(p, database.getSampleSize()))\n model = bio.BIOGEME(database, nl) # Choose the model formulation\n model.modelName = 'NL_Fz' + str(p) # Name it\n results.append(model.estimate()) # Estimation\n output = results[-1].getEstimatedParameters()\n # Add results to the Excel file\n for key, val in results[-1].getGeneralStatistics().items():\n output.loc[key] = [val[0], val[1]] + ['' for i in range(len(output.columns)-2)]\n output.to_excel(writer, sheet_name=model.modelName)",
"Sample size for purpose 1: 42414\n"
],
[
"writer.save()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ab617138d43ab1fdbac1b64bc2740afe4b443b | 106,634 | ipynb | Jupyter Notebook | 10 - Feature Engineering/Feature_Engineering.ipynb | algonacci/Projects | e82ea1cf6505c552e4586e77d8435a2764631eeb | [
"MIT"
] | null | null | null | 10 - Feature Engineering/Feature_Engineering.ipynb | algonacci/Projects | e82ea1cf6505c552e4586e77d8435a2764631eeb | [
"MIT"
] | null | null | null | 10 - Feature Engineering/Feature_Engineering.ipynb | algonacci/Projects | e82ea1cf6505c552e4586e77d8435a2764631eeb | [
"MIT"
] | null | null | null | 74.205985 | 18,664 | 0.705479 | [
[
[
"### Import Library and Dataset",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime",
"_____no_output_____"
],
[
"pd.set_option('display.max_columns', None)\ndata_train = pd.read_excel('Data_Train.xlsx')\ndata_test = pd.read_excel('Data_Test.xlsx')",
"_____no_output_____"
]
],
[
[
"### Combining the Dataset",
"_____no_output_____"
]
],
[
[
"price_train = data_train.Price \n# Concatenate training and test sets \ndata = pd.concat([data_train.drop(['Price'], axis=1), data_test])",
"_____no_output_____"
],
[
"data.columns",
"_____no_output_____"
]
],
[
[
"### Exploratory Data Analysis",
"_____no_output_____"
]
],
[
[
"data.head()",
"_____no_output_____"
],
[
"data.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 13354 entries, 0 to 2670\nData columns (total 10 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Airline 13354 non-null object\n 1 Date_of_Journey 13354 non-null object\n 2 Source 13354 non-null object\n 3 Destination 13354 non-null object\n 4 Route 13353 non-null object\n 5 Dep_Time 13354 non-null object\n 6 Arrival_Time 13354 non-null object\n 7 Duration 13354 non-null object\n 8 Total_Stops 13353 non-null object\n 9 Additional_Info 13354 non-null object\ndtypes: object(10)\nmemory usage: 1.1+ MB\n"
],
[
"data.describe()",
"_____no_output_____"
],
[
"data = data.drop_duplicates()",
"_____no_output_____"
],
[
"data.isnull().sum()",
"_____no_output_____"
],
[
"data = data.drop(data.loc[data['Route'].isnull()].index)",
"_____no_output_____"
]
],
[
[
"## Feature Engineering",
"_____no_output_____"
]
],
[
[
"data['Airline'].unique()",
"_____no_output_____"
],
[
"import seaborn as sns\n\nsns.countplot(x='Airline', data=data)\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"data['Airline'] = np.where(data['Airline']=='Vistara Premium economy', 'Vistara', data['Airline'])\ndata['Airline'] = np.where(data['Airline']=='Jet Airways Business', 'Jet Airways', data['Airline'])\ndata['Airline'] = np.where(data['Airline']=='Multiple carriers Premium economy', 'Multiple carriers', data['Airline'])",
"_____no_output_____"
],
[
"sns.countplot(x='Airline', data=data)\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"data['Destination'].unique()",
"_____no_output_____"
],
[
"data['Destination'] = np.where(data['Destination']=='Delhi','New Delhi', data['Destination'])",
"_____no_output_____"
],
[
"data['Date_of_Journey'] ",
"_____no_output_____"
],
[
"data['Date_of_Journey'] = pd.to_datetime(data['Date_of_Journey'])\ndata['Date_of_Journey'] ",
"_____no_output_____"
],
[
"data['day_of_week'] = data['Date_of_Journey'].dt.day_name()\ndata['day_of_week']",
"_____no_output_____"
],
[
"sns.countplot(x='day_of_week', data=data)\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"data['Journey_Month'] = pd.to_datetime(data.Date_of_Journey, format='%d/%m/%Y').dt.month_name()\nsns.countplot(x='Journey_Month', data=data)\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"data['Departure_t'] = pd.to_datetime(data.Dep_Time, format='%H:%M')\na = data.assign(dept_session=pd.cut(data.Departure_t.dt.hour,[0,6,12,18,24],labels=['Night','Morning','Afternoon','Evening']))\ndata['Departure_S'] = a['dept_session']",
"_____no_output_____"
],
[
"sns.countplot(x='dept_session', data=a)\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"data['Departure_S'].fillna(\"Night\", inplace = True)",
"_____no_output_____"
],
[
"duration = list(data['Duration'])\nfor i in range(len(duration)) :\n if len(duration[i].split()) != 2:\n if 'h' in duration[i] :\n duration[i] = duration[i].strip() + ' 0m'\n elif 'm' in duration[i] :\n duration[i] = '0h {}'.format(duration[i].strip())\ndur_hours = []\ndur_minutes = [] \n \nfor i in range(len(duration)) :\n dur_hours.append(int(duration[i].split()[0][:-1]))\n dur_minutes.append(int(duration[i].split()[1][:-1]))\n \n\ndata['Duration_hours'] = dur_hours\ndata['Duration_minutes'] =dur_minutes\ndata.loc[:,'Duration_hours'] *= 60\ndata['Duration_Total_mins']= data['Duration_hours']+data['Duration_minutes']",
"_____no_output_____"
],
[
"# Get names of indexes for which column Age has value 30\nindexNames = data[data.Duration_Total_mins < 60].index\n# Delete these row indexes from dataFrame\ndata.drop(indexNames , inplace=True)",
"_____no_output_____"
],
[
"data.drop(labels = ['Arrival_Time','Dep_Time','Date_of_Journey','Duration','Departure_t','Duration_hours','Duration_minutes'], axis=1, inplace = True)",
"_____no_output_____"
],
[
"cat_vars = ['Airline', 'Source', 'Destination', 'Route', 'Total_Stops',\n 'Additional_Info', 'day_of_week', 'Journey_Month', 'Departure_S' ]\nfor var in cat_vars:\n catList = 'var'+'_'+var\n catList = pd.get_dummies(data[var], prefix=var)\n data1 = data.join(catList)\n data = data1\n \ndata_vars = data.columns.values.tolist()\nto_keep = [i for i in data_vars if i not in cat_vars]\ndata_final=data[to_keep]",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"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"
]
] |
d0ab6f093ef136d67130ec6524bfc56d21379562 | 55,462 | ipynb | Jupyter Notebook | Notebooks/Data_Cleaning/data_cleaning.ipynb | githotirado/covid-analysis | cbe9c5e2b26b7ee4205672aecff961f8bbfe9243 | [
"Apache-2.0"
] | null | null | null | Notebooks/Data_Cleaning/data_cleaning.ipynb | githotirado/covid-analysis | cbe9c5e2b26b7ee4205672aecff961f8bbfe9243 | [
"Apache-2.0"
] | 1 | 2021-08-11T05:07:07.000Z | 2021-08-11T05:07:07.000Z | Notebooks/Data_Cleaning/data_cleaning.ipynb | githotirado/covid-analysis | cbe9c5e2b26b7ee4205672aecff961f8bbfe9243 | [
"Apache-2.0"
] | 2 | 2021-08-11T04:52:21.000Z | 2021-08-11T06:05:23.000Z | 35.484325 | 170 | 0.391908 | [
[
[
"# Import dependencies\nimport pandas as pd\nimport pathlib\n\n# Identifying CSV file path\ncsv_path = pathlib.Path('../../Resources/Raw/COVID-19_Case_Surveillance_Public_Use_Data_with_Geography.csv')",
"_____no_output_____"
],
[
"# Reading and previewing CSV file\ndata_df = pd.read_csv(csv_path, low_memory=False)\ndata_df.head()",
"_____no_output_____"
],
[
"# Filtering for only California cases\nca_data_df = data_df.loc[data_df['res_state'] == 'CA']\nca_data_df.head()",
"_____no_output_____"
],
[
"# Dropping unused columns\nca_data_df = ca_data_df.drop(columns=[\n 'state_fips_code', \n 'case_positive_specimen_interval', \n 'case_onset_interval', 'process', \n 'exposure_yn', 'symptom_status', \n 'hosp_yn', \n 'icu_yn', \n 'underlying_conditions_yn'])\nca_data_df.head()",
"_____no_output_____"
],
[
"# Extracting year and month from 'case_month'\nca_data_df['year'] = ca_data_df['case_month'].str[:4].astype(int)\nca_data_df['month'] = ca_data_df['case_month'].str[-2:].astype(int)\nca_data_df.head()",
"_____no_output_____"
],
[
"# ----------------------- Data Cleanup -----------------------",
"_____no_output_____"
],
[
"# County: dropping rows with N/A\nca_data_df = pd.DataFrame(ca_data_df[ca_data_df['res_county'].notna()])",
"_____no_output_____"
],
[
"# Age Group: removing rows with 'Missing'\nca_data_df['age_group'] = ca_data_df['age_group'].str.replace('Missing','Unknown')\nca_data_df['age_group'] = ca_data_df['age_group'].str.replace('NA','Unknown')\n\nvalue = {'age_group': 'Unknown'}\nca_data_df = ca_data_df.fillna(value=value)",
"_____no_output_____"
],
[
"# Sex: If 'Missing' then 'Unknown'\nca_data_df['sex'] = ca_data_df['sex'].str.replace('NA','Unknown')\n\nvalue = {'sex': 'Unknown'}\nca_data_df = ca_data_df.fillna(value=value)",
"_____no_output_____"
],
[
"# Current Status: removing Probable Cases\nca_data_df = ca_data_df.drop(ca_data_df[ca_data_df.current_status == 'Probable Case'].index)",
"_____no_output_____"
],
[
"# Death Y/N: removing 'Missing' or 'Unknown'\nca_data_df = ca_data_df.drop(ca_data_df[ca_data_df.death_yn == 'Missing'].index)\nca_data_df = ca_data_df.drop(ca_data_df[ca_data_df.death_yn == 'NA'].index)\nca_data_df = ca_data_df.drop(ca_data_df[ca_data_df.death_yn == 'Unknown'].index)",
"_____no_output_____"
],
[
"# Create new column for 'race/ethnicity' and set initially to the value of 'race'\nca_data_df['race/ethnicity'] = ca_data_df['race']\n\n# If 'race' equals \"Unknown\" then set 'race/ethnicity' to the value of 'ethnicity'\nca_data_df.loc[ca_data_df[\"race\"] == \"Unknown\", \"race/ethnicity\"] = ca_data_df[\"ethnicity\"]\nca_data_df.loc[ca_data_df['race'] == 'Unknown'].head()",
"_____no_output_____"
],
[
"# If 'race' equals \"Missing\" then set 'race/ethnicity' to the value of 'ethnicity'\nca_data_df.loc[ca_data_df[\"race\"] == \"Missing\", \"race/ethnicity\"] = ca_data_df[\"ethnicity\"]\nca_data_df.loc[ca_data_df[\"race\"] == \"Missing\"].head()",
"_____no_output_____"
],
[
"# If 'race/ethnicity' equals \"Missing\" then set 'race/ethnicity' to \"Unknown\"\nca_data_df.loc[ca_data_df[\"race/ethnicity\"] == \"Missing\"] = \"Unknown\"\nca_data_df['race/ethnicity'].value_counts()",
"_____no_output_____"
],
[
"# If 'race' equals \"White\" and ethnicity equals \"Hispanic/Latino\" then set 'race/ethnicity' to \"Hispanic/Latino\"\nca_data_df.loc[((ca_data_df['race'] == 'White') & (ca_data_df['ethnicity'] == 'Hispanic/Latino')), 'race/ethnicity'] = 'Hispanic/Latino'\nca_data_df.loc[((ca_data_df['race'] == 'White') & (ca_data_df['ethnicity'] == 'Hispanic/Latino'))].head()",
"_____no_output_____"
],
[
"# Replace blanks in 'race/ethnicity' with \"Unknown\"\nca_data_df['race/ethnicity'] = ca_data_df['race/ethnicity'].fillna('Unknown')",
"_____no_output_____"
],
[
"# Reviewing 'race/ethnicity' column\nca_data_df['race/ethnicity'].value_counts()",
"_____no_output_____"
],
[
"# Reorganizing columns\nca_data_df = ca_data_df[['year','month','case_month','res_county','res_state','county_fips_code','age_group','sex','race/ethnicity','current_status','death_yn']]\nca_data_df.head()",
"_____no_output_____"
],
[
"# Export to CSV for review\nca_data_df.to_csv('../../Resources/Clean/ca_data_df.csv', index=False)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ab74cfbd40b7f23ebc330045a5742ea9462ec5 | 113,024 | ipynb | Jupyter Notebook | ARIMA_monthly_rev_driver.ipynb | naomiyjchen/sales-forecast-time-series | ad183e561a15458e4f3128cf1a618f498cbcf678 | [
"MIT"
] | null | null | null | ARIMA_monthly_rev_driver.ipynb | naomiyjchen/sales-forecast-time-series | ad183e561a15458e4f3128cf1a618f498cbcf678 | [
"MIT"
] | null | null | null | ARIMA_monthly_rev_driver.ipynb | naomiyjchen/sales-forecast-time-series | ad183e561a15458e4f3128cf1a618f498cbcf678 | [
"MIT"
] | null | null | null | 355.421384 | 62,308 | 0.928555 | [
[
[
"# Import required libraries \nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport sys\n\n%load_ext autoreload\n%autoreload 2\n\n#Ignore harmless warnings \nimport warnings \nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
],
[
"#from code.arima import arima_util as arima\nfrom code.arima import arima_util as arima\nfrom code import tools as tl",
"_____no_output_____"
]
],
[
[
"#### Load and prepare data",
"_____no_output_____"
]
],
[
[
"df = tl.load_data('./data/For Naomi.csv') #read in data from file\ndf = tl.prepare_data(df,'消費日期','交易筆數') # select 'ds' and 'y'",
"_____no_output_____"
],
[
"df1 = tl.group_by_date(df, 'M','2015-01-01','2020-08-31') # group by date\ndf1.shape",
"_____no_output_____"
]
],
[
[
"#### Split data for testing and spliting",
"_____no_output_____"
]
],
[
[
"df_tr, df_tst = tl.train_test_split(df1,'2018-12-31','2019-12-31')\n",
"train shape (48, 3)\ntest shape (12, 3)\n"
]
],
[
[
"#### Set parameters for ARIMA model",
"_____no_output_____"
]
],
[
[
"params = {'start_p': 1,\n 'max_p': 16,\n \n 'd':None,\n #'max_d':2,\n \n 'start_q': 1,\n 'max_q': 3,\n \n 'start_P': 1,\n 'max_P': 5,\n \n 'D': None,\n #'max_D': 1,\n \n #'start_Q': 1,\n #'max_Q': 5,\n \n 'm': 12,\n\n #'alpha': 0.05, # default\n 'seasonal': True, \n 'stepwise': True,\n 'trace':True, \n 'error_action': 'ignore', # we don't want to know if an order does not work \n 'suppress_warnings': True # we don't want convergence warnings \n }",
"_____no_output_____"
]
],
[
[
"#### Model Training",
"_____no_output_____"
]
],
[
[
"Arima = arima.Arima_Impl(df_tr)\nArima.find_best_orders( print_summary = False, **params)\nArima.sm_train()",
"Performing stepwise search to minimize aic\n ARIMA(1,1,1)(1,0,1)[12] intercept : AIC=1076.860, Time=0.09 sec\n ARIMA(0,1,0)(0,0,0)[12] intercept : AIC=1085.102, Time=0.02 sec\n ARIMA(1,1,0)(1,0,0)[12] intercept : AIC=1074.386, Time=0.03 sec\n ARIMA(0,1,1)(0,0,1)[12] intercept : AIC=1075.752, Time=0.03 sec\n ARIMA(0,1,0)(0,0,0)[12] : AIC=1083.212, Time=0.01 sec\n ARIMA(1,1,0)(0,0,0)[12] intercept : AIC=1079.448, Time=0.01 sec\n ARIMA(1,1,0)(2,0,0)[12] intercept : AIC=1071.977, Time=0.09 sec\n ARIMA(1,1,0)(3,0,0)[12] intercept : AIC=1073.928, Time=0.19 sec\n ARIMA(1,1,0)(2,0,1)[12] intercept : AIC=1073.973, Time=0.14 sec\n ARIMA(1,1,0)(1,0,1)[12] intercept : AIC=1074.121, Time=0.05 sec\n ARIMA(1,1,0)(3,0,1)[12] intercept : AIC=1075.756, Time=0.55 sec\n ARIMA(0,1,0)(2,0,0)[12] intercept : AIC=1076.255, Time=0.06 sec\n ARIMA(2,1,0)(2,0,0)[12] intercept : AIC=1071.457, Time=0.13 sec\n ARIMA(2,1,0)(1,0,0)[12] intercept : AIC=1073.734, Time=0.04 sec\n ARIMA(2,1,0)(3,0,0)[12] intercept : AIC=1073.450, Time=0.28 sec\n ARIMA(2,1,0)(2,0,1)[12] intercept : AIC=1073.364, Time=0.19 sec\n ARIMA(2,1,0)(1,0,1)[12] intercept : AIC=1074.389, Time=0.07 sec\n ARIMA(2,1,0)(3,0,1)[12] intercept : AIC=inf, Time=0.94 sec\n ARIMA(3,1,0)(2,0,0)[12] intercept : AIC=1072.461, Time=0.17 sec\n ARIMA(2,1,1)(2,0,0)[12] intercept : AIC=1072.719, Time=0.23 sec\n ARIMA(1,1,1)(2,0,0)[12] intercept : AIC=1074.282, Time=0.13 sec\n ARIMA(3,1,1)(2,0,0)[12] intercept : AIC=1074.558, Time=0.22 sec\n ARIMA(2,1,0)(2,0,0)[12] : AIC=1069.312, Time=0.10 sec\n ARIMA(2,1,0)(1,0,0)[12] : AIC=1072.200, Time=0.04 sec\n ARIMA(2,1,0)(3,0,0)[12] : AIC=1071.265, Time=0.25 sec\n ARIMA(2,1,0)(2,0,1)[12] : AIC=1071.268, Time=0.16 sec\n ARIMA(2,1,0)(1,0,1)[12] : AIC=1070.940, Time=0.08 sec\n ARIMA(2,1,0)(3,0,1)[12] : AIC=1073.262, Time=0.28 sec\n ARIMA(1,1,0)(2,0,0)[12] : AIC=1069.853, Time=0.08 sec\n ARIMA(3,1,0)(2,0,0)[12] : AIC=1070.345, Time=0.13 sec\n ARIMA(2,1,1)(2,0,0)[12] : AIC=1070.841, Time=0.20 sec\n ARIMA(1,1,1)(2,0,0)[12] : AIC=1071.584, Time=0.12 sec\n ARIMA(3,1,1)(2,0,0)[12] : AIC=1072.470, Time=0.20 sec\n\nBest model: ARIMA(2,1,0)(2,0,0)[12] \nTotal fit time: 5.360 seconds\n"
]
],
[
[
"#### Predict the data and calculate MAPE",
"_____no_output_____"
]
],
[
[
"Arima.predict(12,'predicted_revenue')\ndf_pred = tl.make_dataframe(Arima.predictions.values, df_tst) #prepare data for plotting\n\nprint('MAPE: ', tl.mean_absolute_percentage_error(Arima.predictions, df_tst['y']))",
"MAPE: 0.059292462335839374\n"
]
],
[
[
"#### Prediction Evaluation",
"_____no_output_____"
]
],
[
[
"tl.plot_predict_and_actual(df_pred, df_tr)",
"_____no_output_____"
],
[
"tl.plot_predict_vs_actual(df_pred, df_tst, 'M', '2018-12-31','2019-12-31')",
"(12, 2) (12, 3)\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0ab75632e93e6d6aaf25281a1be6c320b3a0a1f | 18,621 | ipynb | Jupyter Notebook | C_content/biomass_C_content_estimation.ipynb | milo-lab/anthropogenic_mass | 5a0170a51d164c1cc98b232452e86feb1e4ee334 | [
"MIT"
] | 24 | 2020-12-09T19:09:52.000Z | 2022-03-26T14:04:32.000Z | C_content/biomass_C_content_estimation.ipynb | milo-lab/anthropogenic_mass | 5a0170a51d164c1cc98b232452e86feb1e4ee334 | [
"MIT"
] | null | null | null | C_content/biomass_C_content_estimation.ipynb | milo-lab/anthropogenic_mass | 5a0170a51d164c1cc98b232452e86feb1e4ee334 | [
"MIT"
] | 5 | 2020-12-10T03:40:12.000Z | 2021-06-27T11:53:48.000Z | 32.328125 | 525 | 0.429247 | [
[
[
"# Load dependencies \nimport numpy as np\nimport pandas as pd\nfrom uncertainties import ufloat\nfrom uncertainties import unumpy",
"_____no_output_____"
]
],
[
[
"# Biomass C content estimation\n\nBiomass is presented in the paper on a dry-weight basis. As part of the biomass calculation, we converted biomass in carbon-weight basis to dry-weight basis by multiplying by a conversion factor. \n\n## Conversion factor calculation \n\nThe conversion factor was calculated based on C content estimates of the different plant compartments (leaves, stems and roots) of different biomes, from [Tang et al.](https://doi.org/10.1073/pnas.1700295114) (units: (mg/g)). ",
"_____no_output_____"
]
],
[
[
"# Upload C content data from Tang et al., units [mg/g]\nc_content = pd.read_excel(\"C_content_Tang.xlsx\")\nc_content",
"_____no_output_____"
],
[
"# Save parameters to unumpy arrays \ncleaf = unumpy.uarray(list(c_content['leaf']), list(c_content['leaf std']))\ncstem = unumpy.uarray(list(c_content['stem'].fillna(0)), list(c_content['stem std'].fillna(0)))\ncroot = unumpy.uarray(list(c_content['root']), list(c_content['root std']))",
"_____no_output_____"
]
],
[
[
"For each biome, we calculate the weighted average C content according to the mass fraction of each plant compartment. Information on plants compartmental mass composition was obtained from [Poorter et al.](https://nph.onlinelibrary.wiley.com/doi/full/10.1111/j.1469-8137.2011.03952.x). ",
"_____no_output_____"
]
],
[
[
"# Upload compartmental mass composition, from Poorter et al., classified according to Tang et al. biomes \ncompart_comp = pd.read_excel(\"compartment_comp_Poorter.xlsx\")\ncompart_comp",
"_____no_output_____"
],
[
"# Save parameters to unumpy arrays \nfleaf = unumpy.uarray(list(compart_comp['leaf']), list(compart_comp['leaf std']))\nfstem = unumpy.uarray(list(compart_comp['stem'].fillna(0)), list(compart_comp['stem std'].fillna(0)))\nfroot = unumpy.uarray(list(compart_comp['root']), list(compart_comp['root std']))",
"_____no_output_____"
],
[
"# Calculate the weighted average for each biome \ncbiome = (cleaf*fleaf)+(cstem*fstem)+(croot*froot) ",
"_____no_output_____"
]
],
[
[
"Next, we calculate the plants conversion factor, according to the mass fraction of each biome, which was calculated by the corresponding mass of each of the biome categories, derived from [Erb et al.](https://doi.org/10.1038/nature25138).",
"_____no_output_____"
]
],
[
[
"# Upload biomes biomass, from Erb et al., classified according to Tang et al. biomes \nmbiome = pd.read_excel('biome_mass_Erb.xlsx')\nmbiome",
"_____no_output_____"
],
[
"# Save to unumpy array \nmbiomes = unumpy.uarray(list(mbiome['biomass [Gt C]']), list(mbiome['biomass std']))\n\n# Calculate the overall conversion factor \ncplants_factor = 1000/np.sum((cbiome* (mbiomes/np.sum(mbiomes))))",
"_____no_output_____"
]
],
[
[
"In the overall carbon-weight to dry-weight conversion factor, we also accounted the C content of non-plant biomass, which was based on estimates from [Heldal et al.](https://aem.asm.org/content/50/5/1251.short) and [von Stockar](https://www.sciencedirect.com/science/article/pii/S0005272899000651). We used the current estimate of non-plant biomass fraction - about 10% of the total biomass, according to [Bar-On et al.](https://doi.org/10.1073/pnas.1711842115) and [updates](https://doi.org/10.1038/s41561-018-0221-6).",
"_____no_output_____"
]
],
[
[
"# Upload non plant C content data, units [g/g] \ncnon_plant = pd.read_excel('C_content_non_plant.xlsx')\ncnon_plant",
"_____no_output_____"
],
[
"# Calculate conversion factors \ncnon_plant_factor = ufloat(np.average(cnon_plant['C content']) ,np.std(cnon_plant['C content'], ddof = 1))\ncfactor = (cplants_factor*0.9) +(0.1*(1/cnon_plant_factor))\ncfactor\nprint 'Our best estimate of the C content conversion factor is: ' + \"%.2f\" % (cfactor.n) + ', with uncertainty (±1 standard deviation): ' + \"%.2f\" % (cfactor.s) ",
"Our best estimate of the C content conversion factor is: 2.25, with uncertainty (±1 standard deviation): 0.13\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0aba6b55bcefa9a899e03cd80bed2b1d0431765 | 375,495 | ipynb | Jupyter Notebook | flower-classification-ensemble.ipynb | Sebastian-Koenig/Flower-Classification-with-TPUs | 00b3df7a156615e87e5f90230f1d3062512fcead | [
"Apache-2.0"
] | null | null | null | flower-classification-ensemble.ipynb | Sebastian-Koenig/Flower-Classification-with-TPUs | 00b3df7a156615e87e5f90230f1d3062512fcead | [
"Apache-2.0"
] | null | null | null | flower-classification-ensemble.ipynb | Sebastian-Koenig/Flower-Classification-with-TPUs | 00b3df7a156615e87e5f90230f1d3062512fcead | [
"Apache-2.0"
] | null | null | null | 371.409496 | 163,544 | 0.920097 | [
[
[
"!pip install -q efficientnet",
"_____no_output_____"
],
[
"import math, re, os, random\nimport tensorflow as tf, tensorflow.keras.backend as K\nimport numpy as np\nimport pandas as pd\nimport efficientnet.tfkeras as efn\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nfrom sklearn.model_selection import KFold\nprint(\"Tensorflow version \" + tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE",
"Tensorflow version 2.1.0\n"
]
],
[
[
"# TPU or GPU detection",
"_____no_output_____"
]
],
[
[
"# Detect hardware, return appropriate distribution strategy\ntry:\n tpu = tf.distribute.cluster_resolver.TPUClusterResolver() # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n print('Running on TPU ', tpu.master())\nexcept ValueError:\n tpu = None\n\nif tpu:\n tf.config.experimental_connect_to_cluster(tpu)\n tf.tpu.experimental.initialize_tpu_system(tpu)\n strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)",
"Running on TPU grpc://10.0.0.2:8470\nREPLICAS: 8\n"
]
],
[
[
"# Competition data access\nTPUs read data directly from Google Cloud Storage (GCS). This Kaggle utility will copy the dataset to a GCS bucket co-located with the TPU. If you have multiple datasets attached to the notebook, you can pass the name of a specific dataset to the get_gcs_path function. The name of the dataset is the name of the directory it is mounted in. Use `!ls /kaggle/input/` to list attached datasets.",
"_____no_output_____"
]
],
[
[
"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"",
"_____no_output_____"
]
],
[
[
"# Configuration",
"_____no_output_____"
]
],
[
[
"IMAGE_SIZE = [512, 512] # at this size, a GPU will run out of memory. Use the TPU\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nSEED = 42\nFOLDS = 3\n\nGCS_PATH_SELECT = { # available image sizes\n 192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n 224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n 331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n 512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec') + tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for the competition\n\nCLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle', # 00 - 09\n 'snapdragon', \"colt's foot\", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily', # 10 - 19\n 'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', # 20 - 29\n 'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose', # 30 - 39\n 'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion', # 40 - 49\n 'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia', # 50 - 59\n 'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy', # 60 - 69\n 'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium', # 70 - 79\n 'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily', # 80 - 89\n 'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower', # 90 - 99\n 'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose'] # 100 - 102",
"_____no_output_____"
]
],
[
[
"## Visualization utilities\ndata -> pixels, nothing of much interest for the machine learning practitioner in this section.",
"_____no_output_____"
]
],
[
[
"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n images, labels = data\n numpy_images = images.numpy()\n numpy_labels = labels.numpy()\n if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n numpy_labels = [None for _ in enumerate(numpy_images)]\n # If no labels, only image IDs, return None for labels (this is the case for test data)\n return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n if correct_label is None:\n return CLASSES[label], True\n correct = (label == correct_label)\n return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n plt.subplot(*subplot)\n plt.axis('off')\n plt.imshow(image)\n if len(title) > 0:\n plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n return (subplot[0], subplot[1], subplot[2]+1)\n \ndef display_batch_of_images(databatch, predictions=None):\n \"\"\"This will work with:\n display_batch_of_images(images)\n display_batch_of_images(images, predictions)\n display_batch_of_images((images, labels))\n display_batch_of_images((images, labels), predictions)\n \"\"\"\n # data\n images, labels = batch_to_numpy_images_and_labels(databatch)\n if labels is None:\n labels = [None for _ in enumerate(images)]\n \n # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n rows = int(math.sqrt(len(images)))\n cols = len(images)//rows\n \n # size and spacing\n FIGSIZE = 13.0\n SPACING = 0.1\n subplot=(rows,cols,1)\n if rows < cols:\n plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n else:\n plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n \n # display\n for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n title = '' if label is None else CLASSES[label]\n correct = True\n if predictions is not None:\n title, correct = title_from_label_and_target(predictions[i], label)\n dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n \n #layout\n plt.tight_layout()\n if label is None and predictions is None:\n plt.subplots_adjust(wspace=0, hspace=0)\n else:\n plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n plt.show()\n\ndef display_confusion_matrix(cmat, score, precision, recall):\n plt.figure(figsize=(15,15))\n ax = plt.gca()\n ax.matshow(cmat, cmap='Reds')\n ax.set_xticks(range(len(CLASSES)))\n ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n ax.set_yticks(range(len(CLASSES)))\n ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n titlestring = \"\"\n if score is not None:\n titlestring += 'f1 = {:.3f} '.format(score)\n if precision is not None:\n titlestring += '\\nprecision = {:.3f} '.format(precision)\n if recall is not None:\n titlestring += '\\nrecall = {:.3f} '.format(recall)\n if len(titlestring) > 0:\n ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n plt.show()\n \ndef display_training_curves(training, validation, title, subplot):\n if subplot%10==1: # set up the subplots on the first call\n plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n plt.tight_layout()\n ax = plt.subplot(subplot)\n ax.set_facecolor('#F8F8F8')\n ax.plot(training)\n ax.plot(validation)\n ax.set_title('model '+ title)\n ax.set_ylabel(title)\n #ax.set_ylim(0.28,1.05)\n ax.set_xlabel('epoch')\n ax.legend(['train', 'valid.'])",
"_____no_output_____"
]
],
[
[
"# Datasets",
"_____no_output_____"
]
],
[
[
"def decode_image(image_data):\n image = tf.image.decode_jpeg(image_data, channels=3)\n image = tf.cast(image, tf.float32) / 255.0 # convert image to floats in [0, 1] range\n image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n return image\n\ndef read_labeled_tfrecord(example):\n LABELED_TFREC_FORMAT = {\n \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n \"class\": tf.io.FixedLenFeature([], tf.int64), # shape [] means single element\n }\n example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n image = decode_image(example['image'])\n label = tf.cast(example['class'], tf.int32)\n return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n UNLABELED_TFREC_FORMAT = {\n \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n \"id\": tf.io.FixedLenFeature([], tf.string), # shape [] means single element\n # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n }\n example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n image = decode_image(example['image'])\n idnum = example['id']\n return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n # Read from TFRecords. For optimal performance, reading from multiple files at once and\n # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n ignore_order = tf.data.Options()\n if not ordered:\n ignore_order.experimental_deterministic = False # disable order, increase speed\n\n dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n return dataset\n\ndef data_augment(image, label):\n # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n # of the TPU while the TPU itself is computing gradients.\n image = tf.image.random_flip_left_right(image)\n return image, label \n\ndef get_training_dataset(dataset, do_aug=True):\n dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)\n dataset = dataset.repeat() # the training dataset must repeat for several epochs\n dataset = dataset.shuffle(2048)\n dataset = dataset.batch(BATCH_SIZE)\n dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n return dataset\n\ndef get_validation_dataset(dataset):\n dataset = dataset.batch(BATCH_SIZE)\n dataset = dataset.cache()\n dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n return dataset\n\ndef get_test_dataset(ordered=False):\n dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n dataset = dataset.batch(BATCH_SIZE)\n dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n return dataset\n\ndef count_data_items(filenames):\n # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n return np.sum(n)\n\nNUM_TRAINING_IMAGES = int( count_data_items(TRAINING_FILENAMES) * (FOLDS-1.)/FOLDS )\nNUM_VALIDATION_IMAGES = int( count_data_items(TRAINING_FILENAMES) * (1./FOLDS) )\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))",
"Dataset: 10976 training images, 5488 validation images, 7382 unlabeled test images\n"
]
],
[
[
"# Enhanced Data Augmentation",
"_____no_output_____"
]
],
[
[
"def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n # returns 3x3 transformmatrix which transforms indicies\n \n # CONVERT DEGREES TO RADIANS\n rotation = math.pi * rotation / 180.\n shear = math.pi * shear / 180.\n \n # ROTATION MATRIX\n c1 = tf.math.cos(rotation)\n s1 = tf.math.sin(rotation)\n one = tf.constant([1],dtype='float32')\n zero = tf.constant([0],dtype='float32')\n rotation_matrix = tf.reshape( tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3] )\n \n # SHEAR MATRIX\n c2 = tf.math.cos(shear)\n s2 = tf.math.sin(shear)\n shear_matrix = tf.reshape( tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3] ) \n \n # ZOOM MATRIX\n zoom_matrix = tf.reshape( tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3] )\n \n # SHIFT MATRIX\n shift_matrix = tf.reshape( tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3] )\n \n return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))",
"_____no_output_____"
],
[
"def transform(image,label):\n # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n # output - image randomly rotated, sheared, zoomed, and shifted\n DIM = IMAGE_SIZE[0]\n XDIM = DIM%2 #fix for size 331\n \n rot = 15. * tf.random.normal([1],dtype='float32')\n shr = 5. * tf.random.normal([1],dtype='float32') \n h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n h_shift = 16. * tf.random.normal([1],dtype='float32') \n w_shift = 16. * tf.random.normal([1],dtype='float32') \n \n # GET TRANSFORMATION MATRIX\n m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) \n\n # LIST DESTINATION PIXEL INDICES\n x = tf.repeat( tf.range(DIM//2,-DIM//2,-1), DIM )\n y = tf.tile( tf.range(-DIM//2,DIM//2),[DIM] )\n z = tf.ones([DIM*DIM],dtype='int32')\n idx = tf.stack( [x,y,z] )\n \n # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n idx2 = K.dot(m,tf.cast(idx,dtype='float32'))\n idx2 = K.cast(idx2,dtype='int32')\n idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)\n \n # FIND ORIGIN PIXEL VALUES \n idx3 = tf.stack( [DIM//2-idx2[0,], DIM//2-1+idx2[1,]] )\n d = tf.gather_nd(image,tf.transpose(idx3))\n \n return tf.reshape(d,[DIM,DIM,3]),label",
"_____no_output_____"
]
],
[
[
"# Model Selector",
"_____no_output_____"
]
],
[
[
"#selecting which models will be trained and used in inference. Options: Ensamble, Model No. \nMODEL_SELECT = 'Model1'\nEPOCHS = 15",
"_____no_output_____"
]
],
[
[
"# Model 1\nDenseNet201",
"_____no_output_____"
]
],
[
[
"def get_model1():\n with strategy.scope():\n dn201 = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])\n dn201.trainable = True # Full Training\n\n model1 = tf.keras.Sequential([\n dn201,\n tf.keras.layers.GlobalAveragePooling2D(),\n tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n ])\n\n model1.compile(\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),\n loss = 'sparse_categorical_crossentropy',\n metrics=['sparse_categorical_accuracy']\n )\n return model1",
"_____no_output_____"
]
],
[
[
"# Model 2\nEfficient Net B7",
"_____no_output_____"
]
],
[
[
"def get_model2():\n with strategy.scope():\n enb7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])\n enb7.trainable = True # Full Training\n\n model2 = tf.keras.Sequential([\n enb7,\n tf.keras.layers.GlobalAveragePooling2D(),\n tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n ])\n\n model2.compile(\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),\n loss = 'sparse_categorical_crossentropy',\n metrics=['sparse_categorical_accuracy']\n )\n return model2",
"_____no_output_____"
]
],
[
[
"# Callbacks",
"_____no_output_____"
]
],
[
[
"LR_START = 0.0001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 3\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n if epoch < LR_RAMPUP_EPOCHS:\n lr = np.random.random_sample() * LR_START # Using random learning rate for initial epochs.\n elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n lr = LR_MAX \n else:\n lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN # Rapid decay of learning rate to improve convergence.\n return lr\n \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)",
"_____no_output_____"
],
[
"es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=5, verbose=1, mode='auto', restore_best_weights=True)",
"_____no_output_____"
]
],
[
[
"# Custom Training Fuction",
"_____no_output_____"
]
],
[
[
"def train_cross_validate(folds = 5):\n histories = []\n models = []\n kfold = KFold(folds, shuffle = True, random_state = SEED)\n for f, (trn_ind, val_ind) in enumerate(kfold.split(TRAINING_FILENAMES)):\n print(); print('#'*25)\n print('### FOLD',f+1)\n print('#'*25)\n train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True)\n val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True)\n if MODEL_SELECT is 'Ensamble' or MODEL_SELECT is 'Model1':\n model1 = get_model1()\n history1 = model1.fit(\n get_training_dataset(train_dataset), \n steps_per_epoch = STEPS_PER_EPOCH,\n epochs = EPOCHS,\n callbacks = [lr_callback, es_callback],\n validation_data = get_validation_dataset(val_dataset),\n verbose=2\n )\n models.append(model1)\n histories.append(history1)\n if MODEL_SELECT is 'Ensamble' or MODEL_SELECT is 'Model2':\n model2 = get_model2()\n history2 = model2.fit(\n get_training_dataset(train_dataset), \n steps_per_epoch = STEPS_PER_EPOCH,\n epochs = EPOCHS,\n callbacks = [lr_callback, es_callback],\n validation_data = get_validation_dataset(val_dataset),\n verbose=2\n )\n models.append(model2)\n histories.append(history2)\n return histories, models",
"_____no_output_____"
],
[
"def train_and_predict(folds = 5):\n test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n test_images_ds = test_ds.map(lambda image, idnum: image)\n print('Start training %i folds'%folds)\n histories, models = train_cross_validate(folds = folds)\n print('Computing predictions...')\n # get the mean probability of the folds models\n probabilities = np.average([models[i].predict(test_images_ds) for i in range(len(models))], axis = 0)\n predictions = np.argmax(probabilities, axis=-1)\n print('Generating submission.csv file...')\n test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n return histories, models",
"_____no_output_____"
]
],
[
[
"# Training",
"_____no_output_____"
]
],
[
[
"histories, models = train_and_predict(folds = FOLDS)",
"Start training 3 folds\n\n#########################\n### FOLD 1\n#########################\nDownloading data from https://github.com/keras-team/keras-applications/releases/download/densenet/densenet201_weights_tf_dim_ordering_tf_kernels_notop.h5\n74842112/74836368 [==============================] - 3s 0us/step\nTrain for 85 steps\n\nEpoch 00001: LearningRateScheduler reducing learning rate to 9.1417492950938e-05.\nEpoch 1/15\n85/85 - 459s - loss: 2.4616 - sparse_categorical_accuracy: 0.4831 - val_loss: 1.5036 - val_sparse_categorical_accuracy: 0.6429\n\nEpoch 00002: LearningRateScheduler reducing learning rate to 3.4569470359511804e-05.\nEpoch 2/15\n85/85 - 73s - loss: 1.1508 - sparse_categorical_accuracy: 0.7779 - val_loss: 1.0659 - val_sparse_categorical_accuracy: 0.7466\n\nEpoch 00003: LearningRateScheduler reducing learning rate to 3.766496482417756e-05.\nEpoch 3/15\n85/85 - 71s - loss: 0.8540 - sparse_categorical_accuracy: 0.8404 - val_loss: 0.7878 - val_sparse_categorical_accuracy: 0.8261\n\nEpoch 00004: LearningRateScheduler reducing learning rate to 0.0004.\nEpoch 4/15\n85/85 - 65s - loss: 0.7031 - sparse_categorical_accuracy: 0.8507 - val_loss: 0.8503 - val_sparse_categorical_accuracy: 0.7709\n\nEpoch 00005: LearningRateScheduler reducing learning rate to 0.000322.\nEpoch 5/15\n85/85 - 77s - loss: 0.3347 - sparse_categorical_accuracy: 0.9132 - val_loss: 0.5663 - val_sparse_categorical_accuracy: 0.8612\n\nEpoch 00006: LearningRateScheduler reducing learning rate to 0.0002596000000000001.\nEpoch 6/15\n85/85 - 75s - loss: 0.1865 - sparse_categorical_accuracy: 0.9566 - val_loss: 0.3745 - val_sparse_categorical_accuracy: 0.9164\n\nEpoch 00007: LearningRateScheduler reducing learning rate to 0.00020968000000000004.\nEpoch 7/15\n85/85 - 74s - loss: 0.0959 - sparse_categorical_accuracy: 0.9757 - val_loss: 0.2790 - val_sparse_categorical_accuracy: 0.9434\n\nEpoch 00008: LearningRateScheduler reducing learning rate to 0.00016974400000000002.\nEpoch 8/15\n85/85 - 69s - loss: 0.0610 - sparse_categorical_accuracy: 0.9890 - val_loss: 0.2964 - val_sparse_categorical_accuracy: 0.9434\n\nEpoch 00009: LearningRateScheduler reducing learning rate to 0.00013779520000000003.\nEpoch 9/15\n85/85 - 72s - loss: 0.0366 - sparse_categorical_accuracy: 0.9934 - val_loss: 0.2651 - val_sparse_categorical_accuracy: 0.9420\n\nEpoch 00010: LearningRateScheduler reducing learning rate to 0.00011223616000000004.\nEpoch 10/15\n85/85 - 71s - loss: 0.0269 - sparse_categorical_accuracy: 0.9956 - val_loss: 0.2595 - val_sparse_categorical_accuracy: 0.9434\n\nEpoch 00011: LearningRateScheduler reducing learning rate to 9.178892800000003e-05.\nEpoch 11/15\n85/85 - 67s - loss: 0.0207 - sparse_categorical_accuracy: 0.9985 - val_loss: 0.2607 - val_sparse_categorical_accuracy: 0.9434\n\nEpoch 00012: LearningRateScheduler reducing learning rate to 7.543114240000003e-05.\nEpoch 12/15\n85/85 - 76s - loss: 0.0178 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.2546 - val_sparse_categorical_accuracy: 0.9474\n\nEpoch 00013: LearningRateScheduler reducing learning rate to 6.234491392000002e-05.\nEpoch 13/15\n85/85 - 75s - loss: 0.0144 - sparse_categorical_accuracy: 0.9993 - val_loss: 0.2517 - val_sparse_categorical_accuracy: 0.9461\n\nEpoch 00014: LearningRateScheduler reducing learning rate to 5.1875931136000024e-05.\nEpoch 14/15\n85/85 - 72s - loss: 0.0129 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.2483 - val_sparse_categorical_accuracy: 0.9474\n\nEpoch 00015: LearningRateScheduler reducing learning rate to 4.3500744908800015e-05.\nEpoch 15/15\n85/85 - 68s - loss: 0.0115 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.2496 - val_sparse_categorical_accuracy: 0.9474\n\n#########################\n### FOLD 2\n#########################\nTrain for 85 steps\n\nEpoch 00001: LearningRateScheduler reducing learning rate to 1.0179904476519863e-05.\nEpoch 1/15\n85/85 - 442s - loss: 4.3489 - sparse_categorical_accuracy: 0.0926 - val_loss: 4.0935 - val_sparse_categorical_accuracy: 0.1048\n\nEpoch 00002: LearningRateScheduler reducing learning rate to 6.926801424387187e-05.\nEpoch 2/15\n85/85 - 76s - loss: 2.2879 - sparse_categorical_accuracy: 0.5162 - val_loss: 1.4722 - val_sparse_categorical_accuracy: 0.6734\n\nEpoch 00003: LearningRateScheduler reducing learning rate to 2.3951788695106347e-05.\nEpoch 3/15\n85/85 - 73s - loss: 1.2806 - sparse_categorical_accuracy: 0.7426 - val_loss: 1.0411 - val_sparse_categorical_accuracy: 0.7473\n\nEpoch 00004: LearningRateScheduler reducing learning rate to 0.0004.\nEpoch 4/15\n85/85 - 68s - loss: 0.8224 - sparse_categorical_accuracy: 0.8132 - val_loss: 1.0667 - val_sparse_categorical_accuracy: 0.7070\n\nEpoch 00005: LearningRateScheduler reducing learning rate to 0.000322.\nEpoch 5/15\n85/85 - 72s - loss: 0.3827 - sparse_categorical_accuracy: 0.9110 - val_loss: 0.5111 - val_sparse_categorical_accuracy: 0.8656\n\nEpoch 00006: LearningRateScheduler reducing learning rate to 0.0002596000000000001.\nEpoch 6/15\n85/85 - 69s - loss: 0.2243 - sparse_categorical_accuracy: 0.9507 - val_loss: 0.3229 - val_sparse_categorical_accuracy: 0.9207\n\nEpoch 00007: LearningRateScheduler reducing learning rate to 0.00020968000000000004.\nEpoch 7/15\n85/85 - 71s - loss: 0.1225 - sparse_categorical_accuracy: 0.9765 - val_loss: 0.2833 - val_sparse_categorical_accuracy: 0.9247\n\nEpoch 00008: LearningRateScheduler reducing learning rate to 0.00016974400000000002.\nEpoch 8/15\n85/85 - 76s - loss: 0.0753 - sparse_categorical_accuracy: 0.9853 - val_loss: 0.2674 - val_sparse_categorical_accuracy: 0.9382\n\nEpoch 00009: LearningRateScheduler reducing learning rate to 0.00013779520000000003.\nEpoch 9/15\n85/85 - 74s - loss: 0.0498 - sparse_categorical_accuracy: 0.9919 - val_loss: 0.2465 - val_sparse_categorical_accuracy: 0.9489\n\nEpoch 00010: LearningRateScheduler reducing learning rate to 0.00011223616000000004.\nEpoch 10/15\n85/85 - 73s - loss: 0.0345 - sparse_categorical_accuracy: 0.9956 - val_loss: 0.2442 - val_sparse_categorical_accuracy: 0.9435\n\nEpoch 00011: LearningRateScheduler reducing learning rate to 9.178892800000003e-05.\nEpoch 11/15\n85/85 - 72s - loss: 0.0272 - sparse_categorical_accuracy: 0.9956 - val_loss: 0.2386 - val_sparse_categorical_accuracy: 0.9476\n\nEpoch 00012: LearningRateScheduler reducing learning rate to 7.543114240000003e-05.\nEpoch 12/15\n85/85 - 70s - loss: 0.0217 - sparse_categorical_accuracy: 0.9985 - val_loss: 0.2292 - val_sparse_categorical_accuracy: 0.9476\n\nEpoch 00013: LearningRateScheduler reducing learning rate to 6.234491392000002e-05.\nEpoch 13/15\n85/85 - 73s - loss: 0.0188 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.2267 - val_sparse_categorical_accuracy: 0.9543\n\nEpoch 00014: LearningRateScheduler reducing learning rate to 5.1875931136000024e-05.\nEpoch 14/15\n85/85 - 71s - loss: 0.0151 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.2316 - val_sparse_categorical_accuracy: 0.9489\n\nEpoch 00015: LearningRateScheduler reducing learning rate to 4.3500744908800015e-05.\nEpoch 15/15\n85/85 - 70s - loss: 0.0143 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.2319 - val_sparse_categorical_accuracy: 0.9516\n\n#########################\n### FOLD 3\n#########################\nTrain for 85 steps\n\nEpoch 00001: LearningRateScheduler reducing learning rate to 8.37399262780287e-05.\nEpoch 1/15\n85/85 - 549s - loss: 2.6060 - sparse_categorical_accuracy: 0.4603 - val_loss: 1.7585 - val_sparse_categorical_accuracy: 0.5794\n\nEpoch 00002: LearningRateScheduler reducing learning rate to 6.5591373553646414e-06.\nEpoch 2/15\n85/85 - 74s - loss: 1.3516 - sparse_categorical_accuracy: 0.7140 - val_loss: 1.3621 - val_sparse_categorical_accuracy: 0.7086\n\nEpoch 00003: LearningRateScheduler reducing learning rate to 3.095993057022272e-05.\nEpoch 3/15\n85/85 - 70s - loss: 1.1385 - sparse_categorical_accuracy: 0.7890 - val_loss: 0.9297 - val_sparse_categorical_accuracy: 0.7976\n\nEpoch 00004: LearningRateScheduler reducing learning rate to 0.0004.\nEpoch 4/15\n85/85 - 64s - loss: 0.8058 - sparse_categorical_accuracy: 0.8162 - val_loss: 1.0798 - val_sparse_categorical_accuracy: 0.7487\n\nEpoch 00005: LearningRateScheduler reducing learning rate to 0.000322.\nEpoch 5/15\n85/85 - 70s - loss: 0.4021 - sparse_categorical_accuracy: 0.9110 - val_loss: 0.5708 - val_sparse_categorical_accuracy: 0.8604\n\nEpoch 00006: LearningRateScheduler reducing learning rate to 0.0002596000000000001.\nEpoch 6/15\n85/85 - 72s - loss: 0.2265 - sparse_categorical_accuracy: 0.9551 - val_loss: 0.3362 - val_sparse_categorical_accuracy: 0.9075\n\nEpoch 00007: LearningRateScheduler reducing learning rate to 0.00020968000000000004.\nEpoch 7/15\n85/85 - 70s - loss: 0.1340 - sparse_categorical_accuracy: 0.9684 - val_loss: 0.2960 - val_sparse_categorical_accuracy: 0.9127\n\nEpoch 00008: LearningRateScheduler reducing learning rate to 0.00016974400000000002.\nEpoch 8/15\n85/85 - 68s - loss: 0.0877 - sparse_categorical_accuracy: 0.9853 - val_loss: 0.2562 - val_sparse_categorical_accuracy: 0.9284\n\nEpoch 00009: LearningRateScheduler reducing learning rate to 0.00013779520000000003.\nEpoch 9/15\n85/85 - 68s - loss: 0.0528 - sparse_categorical_accuracy: 0.9926 - val_loss: 0.2316 - val_sparse_categorical_accuracy: 0.9476\n\nEpoch 00010: LearningRateScheduler reducing learning rate to 0.00011223616000000004.\nEpoch 10/15\n85/85 - 69s - loss: 0.0414 - sparse_categorical_accuracy: 0.9912 - val_loss: 0.2360 - val_sparse_categorical_accuracy: 0.9442\n\nEpoch 00011: LearningRateScheduler reducing learning rate to 9.178892800000003e-05.\nEpoch 11/15\n85/85 - 71s - loss: 0.0299 - sparse_categorical_accuracy: 0.9971 - val_loss: 0.2212 - val_sparse_categorical_accuracy: 0.9581\n\nEpoch 00012: LearningRateScheduler reducing learning rate to 7.543114240000003e-05.\nEpoch 12/15\n85/85 - 70s - loss: 0.0237 - sparse_categorical_accuracy: 0.9985 - val_loss: 0.2115 - val_sparse_categorical_accuracy: 0.9494\n\nEpoch 00013: LearningRateScheduler reducing learning rate to 6.234491392000002e-05.\nEpoch 13/15\n85/85 - 64s - loss: 0.0192 - sparse_categorical_accuracy: 0.9985 - val_loss: 0.2135 - val_sparse_categorical_accuracy: 0.9511\n\nEpoch 00014: LearningRateScheduler reducing learning rate to 5.1875931136000024e-05.\nEpoch 14/15\n85/85 - 69s - loss: 0.0165 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.2120 - val_sparse_categorical_accuracy: 0.9511\n\nEpoch 00015: LearningRateScheduler reducing learning rate to 4.3500744908800015e-05.\nEpoch 15/15\n85/85 - 72s - loss: 0.0147 - sparse_categorical_accuracy: 0.9993 - val_loss: 0.2099 - val_sparse_categorical_accuracy: 0.9546\nComputing predictions...\nGenerating submission.csv file...\n"
],
[
"for h in range(len(histories)):\n display_training_curves(histories[h].history['loss'], histories[h].history['val_loss'], 'loss', 211)\n display_training_curves(histories[h].history['sparse_categorical_accuracy'], histories[h].history['val_sparse_categorical_accuracy'], 'accuracy', 212)",
"_____no_output_____"
]
],
[
[
"# Confusion matrix",
"_____no_output_____"
]
],
[
[
"all_labels = []; all_prob = []; all_pred = []\nkfold = KFold(FOLDS, shuffle = True, random_state = SEED)\nfor j, (trn_ind, val_ind) in enumerate( kfold.split(TRAINING_FILENAMES) ):\n print('Inferring fold',j+1,'validation images...')\n VAL_FILES = list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[val_ind]['TRAINING_FILENAMES'])\n NUM_VALIDATION_IMAGES = count_data_items(VAL_FILES)\n cmdataset = get_validation_dataset(load_dataset(VAL_FILES, labeled = True, ordered = True))\n images_ds = cmdataset.map(lambda image, label: image)\n labels_ds = cmdataset.map(lambda image, label: label).unbatch()\n all_labels.append( next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() ) # get everything as one batch\n prob = models[j].predict(images_ds)\n all_prob.append( prob )\n all_pred.append( np.argmax(prob, axis=-1) )\ncm_correct_labels = np.concatenate(all_labels)\ncm_probabilities = np.concatenate(all_prob)\ncm_predictions = np.concatenate(all_pred)\nprint(\"Correct labels: \", cm_correct_labels.shape, cm_correct_labels)\nprint(\"Predicted labels: \", cm_predictions.shape, cm_predictions)",
"Inferring fold 1 validation images...\nInferring fold 2 validation images...\nInferring fold 3 validation images...\nCorrect labels: (16465,) [57 84 15 ... 73 67 67]\nPredicted labels: (16465,) [57 84 15 ... 73 67 67]\n"
],
[
"cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\ndisplay_confusion_matrix(cmat, score, precision, recall)\nprint('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))",
"_____no_output_____"
]
]
] | [
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0ababe6ba9548e961c59e52a069dc8bf158c21a | 573,309 | ipynb | Jupyter Notebook | pyqstrat/notebooks/pair_trading_strategy.ipynb | alexanu/pyqstrat | ec62a1a7b048df05e8d1058a37bfe2cf113d2815 | [
"BSD-3-Clause"
] | null | null | null | pyqstrat/notebooks/pair_trading_strategy.ipynb | alexanu/pyqstrat | ec62a1a7b048df05e8d1058a37bfe2cf113d2815 | [
"BSD-3-Clause"
] | null | null | null | pyqstrat/notebooks/pair_trading_strategy.ipynb | alexanu/pyqstrat | ec62a1a7b048df05e8d1058a37bfe2cf113d2815 | [
"BSD-3-Clause"
] | null | null | null | 1,158.2 | 167,976 | 0.952462 | [
[
[
"## A Simple Pair Trading Strategy\n\n**_Please go through the \"building strategies\" notebook before looking at this notebook._**\n\nLet's build a aimple pair trading strategy to show how you can trade multiple symbols in a strategy. We will trade 2 stocks, Coca-Cola (KO) and Pepsi (PEP)\n\n1. We will buy KO and sell PEP when the price ratio KO / PEP is more than 1 standard deviation lower than its 5 day simple moving average. \n2. We will buy PEP and sell KO when the price ratio KO / PEP is more than 1 standard deviation higher than its 5 day simple moving average.\n3. We will exit when the price ratio is less than +/- 0.5 standard deviations away from its simple moving average\n4. We will size the trades in 1 and 2 by allocating 10% of our capital to each trade.\n\nFirst lets load some price data in fifteen minute bars.",
"_____no_output_____"
]
],
[
[
"import math\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.stats\nimport os\nfrom types import SimpleNamespace\n\nimport pyqstrat as pq\n\npq.set_defaults() # Set some display defaults to make dataframes and plots easier to look at\n\ntry:\n ko_file = os.path.dirname(os.path.realpath(__file__)) + './support/coke_15_min_prices.csv.gz'\n pep_file = os.path.dirname(os.path.realpath(__file__)) + './support/pepsi_15_min_prices.csv.gz' # If we are running from unit tests\n \nexcept:\n ko_file_path = '../notebooks/support/coke_15_min_prices.csv.gz'\n pep_file_path = '../notebooks/support/pepsi_15_min_prices.csv.gz'\n\nko_prices = pd.read_csv(ko_file_path)\npep_prices = pd.read_csv(pep_file_path)\n\nko_prices['timestamp'] = pd.to_datetime(ko_prices.date)\npep_prices['timestamp'] = pd.to_datetime(pep_prices.date)\n\ntimestamps = ko_prices.timestamp.values\n\nko_contract_group = pq.ContractGroup.create('KO')\npep_contract_group = pq.ContractGroup.create('PEP')",
"_____no_output_____"
]
],
[
[
"Lets compute the ratio of the two prices and add it to the market data. Since the two price series have the exact same timestamps, we can simply divide the two close price series",
"_____no_output_____"
]
],
[
[
"ratio = ko_prices.c / pep_prices.c",
"_____no_output_____"
]
],
[
[
"Next, lets create an indicator for the zscore, and plot it.",
"_____no_output_____"
]
],
[
[
"def zscore_indicator(symbol, timestamps, indicators, strategy_context): # simple moving average\n ratio = indicators.ratio\n r = pd.Series(ratio).rolling(window = 130)\n mean = r.mean()\n std = r.std(ddof = 0)\n zscore = (ratio - mean) / std\n zscore = np.nan_to_num(zscore)\n return zscore\n\nko_zscore = zscore_indicator(None, None, SimpleNamespace(ratio = ratio), None)\n\nratio_subplot = pq.Subplot([pq.TimeSeries('ratio', timestamps, ratio)], ylabel = 'Ratio')\nzscore_subplot = pq.Subplot([pq.TimeSeries('zscore', timestamps, ko_zscore)], ylabel = 'ZScore')\nplot = pq.Plot([ratio_subplot, zscore_subplot], title = 'KO')\nplot.draw();\n\n",
"_____no_output_____"
]
],
[
[
"Now lets create the signal that will tell us to get in when the zscore is +/-1 and get out when its less than +/- 0.5. We use a signal value of 2 to figure out when to go long, and -2 to figure out when to go short. A value of 1 means get out of a long position, and -1 means get out of a short position. We also plot the signal to check it.",
"_____no_output_____"
]
],
[
[
"def pair_strategy_signal(contract_group, timestamps, indicators, parent_signals, strategy_context):\n zscore = indicators.zscore\n signal = np.where(zscore > 1, 2, 0)\n signal = np.where(zscore < -1, -2, signal)\n signal = np.where((zscore > 0.5) & (zscore < 1), 1, signal)\n signal = np.where((zscore < -0.5) & (zscore > -1), -1, signal)\n if contract_group.name == 'PEP': signal = -1. * signal\n return signal\n\nsignal = pair_strategy_signal(ko_contract_group, timestamps, SimpleNamespace(zscore = ko_zscore), None, None)\nsignal_subplot = pq.Subplot([pq.TimeSeries('signal', timestamps, signal)], ylabel = 'Signal')\nplot = pq.Plot([signal_subplot], title = 'KO', show_date_gaps = False)\nplot.draw();",
"_____no_output_____"
]
],
[
[
"Finally we create the trading rule and market simulator functions",
"_____no_output_____"
]
],
[
[
"def pair_trading_rule(contract_group, i, timestamps, indicators, signal, account, strategy_context):\n timestamp = timestamps[i]\n curr_pos = account.position(contract_group, timestamp)\n signal_value = signal[i]\n risk_percent = 0.1\n \n orders = []\n \n symbol = contract_group.name\n \n contract = contract_group.get_contract(symbol)\n if contract is None:\n contract = pq.Contract.create(symbol, contract_group = contract_group)\n \n # if we don't already have a position, check if we should enter a trade\n if math.isclose(curr_pos, 0):\n if signal_value == 2 or signal_value == -2:\n curr_equity = account.equity(timestamp)\n order_qty = np.round(curr_equity * risk_percent / indicators.c[i] * np.sign(signal_value))\n trigger_price = indicators.c[i]\n reason_code = pq.ReasonCode.ENTER_LONG if order_qty > 0 else pq.ReasonCode.ENTER_SHORT\n orders.append(pq.MarketOrder(contract, timestamp, order_qty, reason_code = reason_code))\n \n else: # We have a current position, so check if we should exit\n if (curr_pos > 0 and signal_value == -1) or (curr_pos < 0 and signal_value == 1):\n order_qty = -curr_pos\n reason_code = pq.ReasonCode.EXIT_LONG if order_qty < 0 else pq.ReasonCode.EXIT_SHORT\n orders.append(pq.MarketOrder(contract, timestamp, order_qty, reason_code = reason_code))\n return orders\n\ndef market_simulator(orders, i, timestamps, indicators, signals, strategy_context):\n trades = []\n \n timestamp = timestamps[i]\n \n for order in orders:\n trade_price = np.nan\n \n contract_group = order.contract.contract_group\n ind = indicators[contract_group]\n \n o, h, l, c = ind.o[i], ind.h[i], ind.l[i], ind.c[i]\n \n if isinstance(order, pq.MarketOrder):\n trade_price = 0.5 * (o + h) if order.qty > 0 else 0.5 * (o + l)\n else:\n raise Exception(f'unexpected order type: {order}')\n \n if np.isnan(trade_price): continue\n \n trade = pq.Trade(order.contract, order, timestamp, order.qty, trade_price, commission = 0, fee = 0)\n order.status = 'filled'\n \n trades.append(trade)\n \n return trades\n",
"_____no_output_____"
]
],
[
[
"Lets run the strategy, plot the results and look at the returns",
"_____no_output_____"
]
],
[
[
"def get_price(contract, timestamps, i, strategy_context):\n if contract.symbol == 'KO':\n return strategy_context.ko_price[i]\n elif contract.symbol == 'PEP':\n return strategy_context.pep_price[i]\n raise Exception(f'Unknown symbol: {symbol}')\n\nstrategy_context = SimpleNamespace(ko_price = ko_prices.c.values, pep_price = pep_prices.c.values)\n\nstrategy = pq.Strategy(timestamps, [ko_contract_group, pep_contract_group], get_price, trade_lag = 1, strategy_context = strategy_context)\nfor tup in [(ko_contract_group, ko_prices), (pep_contract_group, pep_prices)]:\n for column in ['o', 'h', 'l', 'c']:\n strategy.add_indicator(column, tup[1][column].values, contract_groups = [tup[0]])\n \nstrategy.add_indicator('ratio', ratio)\nstrategy.add_indicator('zscore', zscore_indicator, depends_on = ['ratio'])\n\nstrategy.add_signal('pair_strategy_signal', pair_strategy_signal, depends_on_indicators = ['zscore'])\n\n# ask pqstrat to call our trading rule when the signal has one of the values [-2, -1, 1, 2]\nstrategy.add_rule('pair_trading_rule', pair_trading_rule, \n signal_name = 'pair_strategy_signal', sig_true_values = [-2, -1, 1, 2])\n\nstrategy.add_market_sim(market_simulator)\n\nportfolio = pq.Portfolio()\nportfolio.add_strategy('pair_strategy', strategy)\nportfolio.run()\n\nstrategy.plot(primary_indicators = ['c'], secondary_indicators = ['zscore'])",
"_____no_output_____"
],
[
"strategy.evaluate_returns();",
"_____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",
"code"
]
] |
d0abb4c2890f7b913955cc14f959d896ae41ffa6 | 32,068 | ipynb | Jupyter Notebook | NumpyNN/1010_Char_RNN_Unfolded.ipynb | marcinbogdanski/ai-sketchpad | cd97a99ab0504b845e6962de5970042acd2cb91c | [
"MIT"
] | 8 | 2019-01-04T18:54:39.000Z | 2021-06-16T22:10:44.000Z | NumpyNN/1010_Char_RNN_Unfolded.ipynb | marcinbogdanski/ai-sketchpad | cd97a99ab0504b845e6962de5970042acd2cb91c | [
"MIT"
] | null | null | null | NumpyNN/1010_Char_RNN_Unfolded.ipynb | marcinbogdanski/ai-sketchpad | cd97a99ab0504b845e6962de5970042acd2cb91c | [
"MIT"
] | 1 | 2021-04-02T02:44:40.000Z | 2021-04-02T02:44:40.000Z | 43.928767 | 13,252 | 0.620026 | [
[
[
"# Introduction",
"_____no_output_____"
],
[
"<div class=\"alert alert-info\">\n\n**Code not tidied, but should work OK**\n\n</div>",
"_____no_output_____"
],
[
"<img src=\"../Udacity_DL_Nanodegree/031%20RNN%20Super%20Basics/SimpleRNN01.png\" align=\"left\"/>",
"_____no_output_____"
],
[
"# Neural Network",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pdb",
"_____no_output_____"
]
],
[
[
"**Sigmoid**",
"_____no_output_____"
]
],
[
[
"def sigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef sigmoid_der(x):\n return sigmoid(x) * (1 - sigmoid(x))",
"_____no_output_____"
]
],
[
[
"**Hyperbolic Tangent**",
"_____no_output_____"
]
],
[
[
"def tanh(x):\n return np.tanh(x)\n\ndef tanh_der(x):\n return 1.0 - np.tanh(x)**2",
"_____no_output_____"
]
],
[
[
"**Mean Squared Error**",
"_____no_output_____"
]
],
[
[
"def mse(x, y, Wxh, Whh, Who):\n y_hat = forward(x, Wxh, Whh, Who)\n return 0.5 * np.mean((y-y_hat)**2)",
"_____no_output_____"
]
],
[
[
"**Forward Pass**",
"_____no_output_____"
]
],
[
[
"def forward(x, Wxh, Whh, Who):\n assert x.ndim==3 and x.shape[1:]==(4, 3)\n \n x_t0 = x[:,0,:]\n x_t1 = x[:,1,:]\n x_t2 = x[:,2,:]\n x_t3 = x[:,3,:]\n \n s_init = np.zeros([len(x), len(Whh)]) # [n_batch, n_hid]\n z_t0 = s_init @ Whh + x_t0 @ Wxh\n s_t0 = tanh(z_t0)\n z_t1 = s_t0 @ Whh + x_t1 @ Wxh\n s_t1 = tanh(z_t1)\n z_t2 = s_t1 @ Whh + x_t2 @ Wxh\n s_t2 = tanh(z_t2)\n z_t3 = s_t2 @ Whh + x_t3 @ Wxh\n s_t3 = tanh(z_t3)\n z_out = s_t3 @ Who\n y_hat = sigmoid( z_out )\n \n return y_hat",
"_____no_output_____"
],
[
"def forward(x, Wxh, Whh, Who):\n assert x.ndim==3 and x.shape[1:]==(4, 3)\n \n x_t = {}\n s_t = {}\n z_t = {}\n s_t[-1] = np.zeros([len(x), len(Whh)]) # [n_batch, n_hid]\n T = x.shape[1]\n \n for t in range(T):\n x_t[t] = x[:,t,:]\n z_t[t] = s_t[t-1] @ Whh + x_t[t] @ Wxh\n s_t[t] = tanh(z_t[t])\n \n z_out = s_t[t] @ Who\n y_hat = sigmoid( z_out )\n \n return y_hat",
"_____no_output_____"
]
],
[
[
"**Backpropagation**",
"_____no_output_____"
]
],
[
[
"def backward(x, y, Wxh, Whh, Who):\n assert x.ndim==3 and x.shape[1:]==(4, 3)\n assert y.ndim==2 and y.shape[1:]==(1,)\n assert len(x) == len(y)\n \n # Forward\n x_t0 = x[:,0,:]\n x_t1 = x[:,1,:]\n x_t2 = x[:,2,:]\n x_t3 = x[:,3,:]\n \n s_init = np.zeros([len(x), len(Whh)]) # [n_batch, n_hid]\n z_t0 = s_init @ Whh + x_t0 @ Wxh\n s_t0 = tanh(z_t0)\n z_t1 = s_t0 @ Whh + x_t1 @ Wxh\n s_t1 = tanh(z_t1)\n z_t2 = s_t1 @ Whh + x_t2 @ Wxh\n s_t2 = tanh(z_t2)\n z_t3 = s_t2 @ Whh + x_t3 @ Wxh\n s_t3 = tanh(z_t3)\n z_out = s_t3 @ Who\n y_hat = sigmoid( z_out )\n \n # Backward\n dWxh = np.zeros_like(Wxh)\n dWhh = np.zeros_like(Whh)\n dWho = np.zeros_like(Who)\n \n err = -(y-y_hat)/len(x) * sigmoid_der( z_out )\n dWho = s_t3.T @ err\n ro_t3 = err @ Who.T * tanh_der(z_t3)\n \n dWxh += x_t3.T @ ro_t3\n dWhh += s_t2.T @ ro_t3\n ro_t2 = ro_t3 @ Whh.T * tanh_der(z_t2)\n \n dWxh += x_t2.T @ ro_t2\n dWhh += s_t1.T @ ro_t2\n ro_t1 = ro_t2 @ Whh.T * tanh_der(z_t1)\n \n dWxh += x_t1.T @ ro_t1\n dWhh += s_t0.T @ ro_t1\n ro_t0 = ro_t1 @ Whh.T * tanh_der(z_t0)\n \n dWxh += x_t0.T @ ro_t0\n dWhh += s_init.T @ ro_t0\n \n return y_hat, dWxh, dWhh, dWho",
"_____no_output_____"
],
[
"def backward(x, y, Wxh, Whh, Who):\n assert x.ndim==3 and x.shape[1:]==(4, 3)\n assert y.ndim==2 and y.shape[1:]==(1,)\n assert len(x) == len(y)\n \n # Init\n x_t = {}\n s_t = {}\n z_t = {}\n s_t[-1] = np.zeros([len(x), len(Whh)]) # [n_batch, n_hid]\n T = x.shape[1]\n \n # Forward\n for t in range(T): # t = [0, 1, 2, 3]\n x_t[t] = x[:,t,:] # pick time-step input x_[t].shape = (n_batch, n_in)\n z_t[t] = s_t[t-1] @ Whh + x_t[t] @ Wxh\n s_t[t] = tanh(z_t[t])\n z_out = s_t[t] @ Who\n y_hat = sigmoid( z_out )\n \n # Backward\n dWxh = np.zeros_like(Wxh)\n dWhh = np.zeros_like(Whh)\n dWho = np.zeros_like(Who)\n \n ro = -(y-y_hat)/len(x) * sigmoid_der( z_out ) # Backprop through loss funt.\n dWho = s_t[t].T @ ro # \n ro = ro @ Who.T * tanh_der(z_t[t]) # Backprop into hidden state\n \n for t in reversed(range(T)): # t = [3, 2, 1, 0]\n dWxh += x_t[t].T @ ro\n dWhh += s_t[t-1].T @ ro\n if t != 0: # don't backprop into t=-1\n ro = ro @ Whh.T * tanh_der(z_t[t-1]) # Backprop into previous time step\n \n return y_hat, dWxh, dWhh, dWho",
"_____no_output_____"
]
],
[
[
"**Train Loop**",
"_____no_output_____"
]
],
[
[
"def train_rnn(x, y, nb_epochs, learning_rate, Wxh, Whh, Who):\n \n losses = []\n \n for e in range(nb_epochs):\n \n y_hat, dWxh, dWhh, dWho = backward(x, y, Wxh, Whh, Who)\n \n Wxh += -learning_rate * dWxh\n Whh += -learning_rate * dWhh\n Who += -learning_rate * dWho\n \n # Log and print\n loss_train = mse(x, y, Wxh, Whh, Who)\n losses.append(loss_train)\n if e % (nb_epochs / 10) == 0:\n print('loss ', loss_train.round(4))\n \n return losses",
"_____no_output_____"
]
],
[
[
"# Example: Count Letter 'a'",
"_____no_output_____"
],
[
"**Create Dataset**",
"_____no_output_____"
]
],
[
[
"# Encoding: 'a'=[0,0,1] 'b'=[0,1,0] 'c'=[1,0,0]\n\n# < ----- 4x time steps ----- >\nx_train = np.array([ \n [ [0, 1, 0], [0, 1, 0], [1, 0, 0], [0, 1, 0] ], # 'bbcb'\n [ [1, 0, 0], [0, 1, 0], [1, 0, 0], [0, 1, 0] ], # 'cbcb' ^\n [ [0, 1, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0] ], # 'bcbc' ^\n [ [1, 0, 0], [0, 1, 0], [0, 1, 0], [1, 0, 0] ], # 'cbbc' ^\n [ [1, 0, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0] ], # 'ccbc' ^\n \n \n [ [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0] ], # 'bacb' | 9x batch size\n [ [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1] ], # 'ccba' v\n [ [0, 0, 1], [1, 0, 0], [0, 1, 0], [1, 0, 0] ], # 'acbc' ^\n [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0] ], # 'cbac' ^\n \n [ [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 1, 0] ], # 'baab'\n [ [0, 0, 1], [0, 0, 1], [0, 1, 0], [1, 0, 0] ], # 'aabc'\n \n [ [0, 0, 1], [1, 0, 0], [0, 0, 1], [0, 0, 1] ], # 'acaa'\n ])\ny_train = np.array([ [0], # <-> no timesteps\n [0], #\n [0], #\n [0], #\n [0], #\n \n [1], # ^\n [1], # | 9x batch size\n [1], # ^\n [1], # | 9x batch size\n \n [0], # v\n [0], #\n \n [1] ]) #\nx_test = np.array([\n [ [0,1,0], [1,0,0], [1,0,0], [0,1,0] ], # 'bccb' -> 0\n [ [1,0,0], [1,0,0], [0,1,0], [1,0,0] ], # 'ccbb' -> 0\n [ [0,1,0], [1,0,0], [0,0,1], [1,0,0] ], # 'bcac' -> 1\n [ [0,1,0], [0,0,1], [1,0,0], [0,1,0] ], # 'bacb' -> 1\n ])\ny_test = np.array([ [0], # <-> no timesteps\n [0], #\n [1], #\n [1], ])",
"_____no_output_____"
],
[
"test_gradient()",
"_____no_output_____"
]
],
[
[
"#### Train",
"_____no_output_____"
]
],
[
[
"np.random.seed(0)\nW_xh = 0.1 * np.random.randn(3, 2) # Wxh.shape: [n_in, n_hid]\nW_hh = 0.1 * np.random.randn(2, 2) # Whh.shape: [n_hid, n_hid]\nW_ho = 0.1 * np.random.randn(2, 1) # Who.shape: [n_hid, n_out]",
"_____no_output_____"
],
[
"losses = train_rnn(x_train, y_train, 3000, 0.1, W_xh, W_hh, W_ho)",
"loss 0.1261\nloss 0.1247\nloss 0.1212\nloss 0.1057\nloss 0.0891\nloss 0.0766\nloss 0.0651\nloss 0.0468\nloss 0.0216\nloss 0.0092\n"
],
[
"y_hat = forward(x_train, W_xh, W_hh, W_ho).round(0)\ny_hat",
"_____no_output_____"
],
[
"y_hat == y_train",
"_____no_output_____"
],
[
"y_hat = forward(x_test, W_xh, W_hh, W_ho).round(0)\ny_hat",
"_____no_output_____"
],
[
"y_hat == y_test",
"_____no_output_____"
],
[
"plt.plot(losses)",
"_____no_output_____"
]
],
[
[
"# Gradient Check",
"_____no_output_____"
]
],
[
[
"def numerical_gradient(x, y, Wxh, Whh, Who):\n dWxh = np.zeros_like(Wxh)\n dWhh = np.zeros_like(Whh)\n dWho = np.zeros_like(Who)\n eps = 1e-4\n \n for r in range(len(Wxh)):\n for c in range(Wxh.shape[1]):\n Wxh_pls = Wxh.copy()\n Wxh_min = Wxh.copy()\n \n Wxh_pls[r, c] += eps\n Wxh_min[r, c] -= eps\n \n l_pls = mse(x, y, Wxh_pls, Whh, Who)\n l_min = mse(x, y, Wxh_min, Whh, Who)\n \n dWxh[r, c] = (l_pls - l_min) / (2*eps)\n \n for r in range(len(Whh)):\n for c in range(Whh.shape[1]):\n Whh_pls = Whh.copy()\n Whh_min = Whh.copy()\n \n Whh_pls[r, c] += eps\n Whh_min[r, c] -= eps\n \n l_pls = mse(x, y, Wxh, Whh_pls, Who)\n l_min = mse(x, y, Wxh, Whh_min, Who)\n \n dWhh[r, c] = (l_pls - l_min) / (2*eps)\n \n for r in range(len(Who)):\n for c in range(Who.shape[1]):\n Who_pls = Who.copy()\n Who_min = Who.copy()\n \n Who_pls[r, c] += eps\n Who_min[r, c] -= eps\n \n l_pls = mse(x, y, Wxh, Whh, Who_pls)\n l_min = mse(x, y, Wxh, Whh, Who_min)\n \n dWho[r, c] = (l_pls - l_min) / (2*eps)\n \n \n return dWxh, dWhh, dWho",
"_____no_output_____"
],
[
"def test_gradients():\n for i in range(100):\n W_xh = 0.1 * np.random.randn(3, 2) # Wxh.shape: [n_in, n_hid]\n W_hh = 0.1 * np.random.randn(2, 2) # Whh.shape: [n_hid, n_hid]\n W_ho = 0.1 * np.random.randn(2, 1) # Who.shape: [n_hid, n_out]\n\n xx = np.random.randn(100, 4, 3)\n yy = np.random.randint(0, 2, size=[100, 1])\n\n _, dW_xh, dW_hh, dW_ho = backward(xx, yy, W_xh, W_hh, W_ho)\n ngW_xh, ngW_hh, ngW_ho = numerical_gradient(xx, yy, W_xh, W_hh, W_ho)\n\n assert np.allclose(dW_xh, ngW_xh)\n assert np.allclose(dW_hh, ngW_hh)\n assert np.allclose(dW_ho, ngW_ho)",
"_____no_output_____"
],
[
"test_gradients()",
"_____no_output_____"
]
]
] | [
"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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
d0abbf0045eafb0662411d9448d40ed37af73d81 | 8,223 | ipynb | Jupyter Notebook | Operations_and_Expressions.ipynb | LouisFeraer/CPEN21A-ECE-2-1 | 6412d7f09c37c44e582d2c2b9b38ca3c5fe4ec13 | [
"Apache-2.0"
] | null | null | null | Operations_and_Expressions.ipynb | LouisFeraer/CPEN21A-ECE-2-1 | 6412d7f09c37c44e582d2c2b9b38ca3c5fe4ec13 | [
"Apache-2.0"
] | null | null | null | Operations_and_Expressions.ipynb | LouisFeraer/CPEN21A-ECE-2-1 | 6412d7f09c37c44e582d2c2b9b38ca3c5fe4ec13 | [
"Apache-2.0"
] | null | null | null | 21.469974 | 250 | 0.384896 | [
[
[
"<a href=\"https://colab.research.google.com/github/LouisFeraer/CPEN21A-ECE-2-1/blob/main/Operations_and_Expressions.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"##Operations and Expressions",
"_____no_output_____"
],
[
"##Boolean Operator",
"_____no_output_____"
]
],
[
[
"x=1\ny=2\nprint(x>y)\nprint(y)\nprint(10>11)\nprint(10==10)\n",
"False\n2\nFalse\nTrue\n"
],
[
"#Using bool() function\nprint(bool(\"Hello\"))\nprint(bool(15))\nprint(bool(\"false\")) \nprint(bool(0))",
"True\nTrue\nTrue\nFalse\n"
]
],
[
[
"###Function can return Boolean\n",
"_____no_output_____"
]
],
[
[
"def myFunction():return True\nprint(myFunction())",
"True\n"
]
],
[
[
"###You try",
"_____no_output_____"
]
],
[
[
"print (10>9)\na=6\nb=7\nprint(a==b)\nprint(a!=a)",
"True\nFalse\nFalse\n"
]
],
[
[
"##Arithmetic operators\n",
"_____no_output_____"
]
],
[
[
"print(10+5)\nprint(10-5)\nprint(10*5)\nprint(10/5)\nprint(10%5) #modulo division, reminder\nprint(10//5) #floor division\nprint(10//3) #floor division",
"15\n5\n50\n2.0\n0\n2\n3\n"
]
],
[
[
"##Bitwise Operators",
"_____no_output_____"
]
],
[
[
"a=60 #0011 1100\nb=13 #0000 1101\n\nprint(a&b)\nprint(a|b)\nprint(a^b)\nprint(~a)\nprint(a<<1) #0011 1100\nprint(a<<2) #0011 1100\nprint(b>>1) #0000 1101 \nprint(b>>2)",
"12\n61\n49\n-61\n120\n240\n6\n3\n"
]
],
[
[
"##Python Assignment Operators ",
"_____no_output_____"
]
],
[
[
"a++3 #Same Asa=a+3\n #Same Asa=60, a=63\nprint(a)",
"60\n"
]
],
[
[
"##Logical Operator",
"_____no_output_____"
]
],
[
[
"#and logical operator\n\na=True\nb=False\n\nprint(a and b)\nprint(a or b)\nprint(not(a or b))",
"False\nTrue\nFalse\n"
],
[
"print(a is b)\na is not b",
"False\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0abcf9c40fcc6be11f6d99c849ded84af3e4574 | 7,749 | ipynb | Jupyter Notebook | project/src/Investigate-Spark.ipynb | syenpark/Big-Data-Computing | 535dce80abd60c6a1dccc2179c51272e7c1bb846 | [
"MIT"
] | null | null | null | project/src/Investigate-Spark.ipynb | syenpark/Big-Data-Computing | 535dce80abd60c6a1dccc2179c51272e7c1bb846 | [
"MIT"
] | null | null | null | project/src/Investigate-Spark.ipynb | syenpark/Big-Data-Computing | 535dce80abd60c6a1dccc2179c51272e7c1bb846 | [
"MIT"
] | null | null | null | 21.172131 | 181 | 0.384437 | [
[
[
"df = spark.read.option('quote', '\"').option('escape', '\"').option(\"delimiter\", \",\").option(\"multiLine\", True).csv('../data/Reviews.csv', header=True, inferSchema=True)",
"_____no_output_____"
],
[
"df.printSchema()",
"root\n |-- _c0: integer (nullable = true)\n |-- Clothing ID: integer (nullable = true)\n |-- Age: integer (nullable = true)\n |-- Title: string (nullable = true)\n |-- Review Text: string (nullable = true)\n |-- Rating: integer (nullable = true)\n |-- Recommended IND: integer (nullable = true)\n |-- Positive Feedback Count: integer (nullable = true)\n |-- Division Name: string (nullable = true)\n |-- Department Name: string (nullable = true)\n |-- Class Name: string (nullable = true)\n\n"
],
[
" df.dtypes",
"_____no_output_____"
],
[
"df.groupBy(\"Age\").count().show()",
"+---+-----+\n|Age|count|\n+---+-----+\n| 31| 569|\n| 85| 6|\n| 65| 226|\n| 53| 560|\n| 78| 15|\n| 34| 804|\n| 81| 5|\n| 28| 428|\n| 76| 10|\n| 27| 344|\n| 26| 423|\n| 44| 617|\n| 91| 5|\n| 22| 146|\n| 93| 2|\n| 47| 564|\n| 52| 442|\n| 86| 2|\n| 40| 617|\n| 20| 108|\n+---+-----+\nonly showing top 20 rows\n\n"
],
[
"ages = df.select('Age')",
"_____no_output_____"
],
[
"ages.show()",
"+---+\n|Age|\n+---+\n| 33|\n| 34|\n| 60|\n| 50|\n| 47|\n| 49|\n| 39|\n| 39|\n| 24|\n| 34|\n| 53|\n| 39|\n| 53|\n| 44|\n| 50|\n| 47|\n| 34|\n| 41|\n| 32|\n| 47|\n+---+\nonly showing top 20 rows\n\n"
],
[
"ages.count()",
"_____no_output_____"
],
[
"ages.distinct().count()",
"_____no_output_____"
],
[
"ages.distinct().show()",
"+---+\n|Age|\n+---+\n| 31|\n| 85|\n| 65|\n| 53|\n| 78|\n| 34|\n| 81|\n| 28|\n| 76|\n| 27|\n| 26|\n| 44|\n| 91|\n| 22|\n| 93|\n| 47|\n| 52|\n| 86|\n| 40|\n| 20|\n+---+\nonly showing top 20 rows\n\n"
],
[
"def age_filtering(age):\n df.filter(df['Age'] == age).show()",
"_____no_output_____"
],
[
"age_filtering('1')",
"+---+-----------+---+-----+-----------+------+---------------+-----------------------+-------------+---------------+----------+\n|_c0|Clothing ID|Age|Title|Review Text|Rating|Recommended IND|Positive Feedback Count|Division Name|Department Name|Class Name|\n+---+-----------+---+-----+-----------+------+---------------+-----------------------+-------------+---------------+----------+\n+---+-----------+---+-----+-----------+------+---------------+-----------------------+-------------+---------------+----------+\n\n"
],
[
"df.select(df.Age.cast(\"int\")).show()",
"+---+\n|Age|\n+---+\n| 33|\n| 34|\n| 60|\n| 50|\n| 47|\n| 49|\n| 39|\n| 39|\n| 24|\n| 34|\n| 53|\n| 39|\n| 53|\n| 44|\n| 50|\n| 47|\n| 34|\n| 41|\n| 32|\n| 47|\n+---+\nonly showing top 20 rows\n\n"
],
[
"from pyspark.mllib.linalg import Vectors\nfrom pyspark.mllib.linalg.distributed import RowMatrix\n\nrows = sc.parallelize([\n Vectors.sparse(5, {1: 1.0, 3: 7.0}),\n Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),\n Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0)\n])\n\nmat = RowMatrix(rows)\n# Compute the top 4 principal components.\n# Principal components are stored in a local dense matrix.\npc = mat.computePrincipalComponents(4)\n\n# Project the rows to the linear space spanned by the top 4 principal components.\nprojected = mat.multiply(pc)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0abd7126d1e5b0f01deb2f991742cea33592584 | 213,993 | ipynb | Jupyter Notebook | lab/sheve_stasavage/scratch_sheve_stassavage.ipynb | ds-modules/PS-88-21-DEV | f043abe6b3a26f8778f58d547fad8ea26d683d8a | [
"MIT"
] | null | null | null | lab/sheve_stasavage/scratch_sheve_stassavage.ipynb | ds-modules/PS-88-21-DEV | f043abe6b3a26f8778f58d547fad8ea26d683d8a | [
"MIT"
] | 16 | 2021-02-01T22:47:51.000Z | 2021-06-28T02:40:46.000Z | lab/sheve_stasavage/scratch_sheve_stassavage.ipynb | ds-modules/PS-88-21-DEV | f043abe6b3a26f8778f58d547fad8ea26d683d8a | [
"MIT"
] | 3 | 2021-03-09T02:26:26.000Z | 2022-02-23T09:05:07.000Z | 73.235113 | 105,736 | 0.602842 | [
[
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (16,8)\nplt.rcParams['figure.dpi'] = 150\nsns.set()\npd.set_option('display.max_columns', None)",
"_____no_output_____"
],
[
"string1 = \"data/Scheve_Stasavage_IO_2010_CoWreplicationdata.csv\"\ndf=pd.read_csv(string1)",
"_____no_output_____"
],
[
"df_participants=df[((df[\"country\"]==\"UK\") | (df[\"country\"]==\"France\") | (df[\"country\"]==\"United States\") | (df[\"country\"]==\"Canada\")) & (~df[\"topratep\"].isna())].groupby(\"year\").mean().reset_index()[[\"year\",\"topratep\"]].query(\"year>=1900 & year<=1930\")",
"_____no_output_____"
],
[
"df_not_participants=df[((df[\"country\"]==\"Sweden\") | (df[\"country\"]==\"Netherlands\") | (df[\"country\"]==\"Japan\") | (df[\"country\"]==\"Spain\")) & (~df[\"topratep\"].isna())].groupby(\"year\").mean().reset_index()[[\"year\",\"topratep\"]].query(\"year>=1900 & year<=1930\")",
"_____no_output_____"
],
[
"sns.lineplot(x=\"year\",y=\"topratep\",data=df_participants,label=\"Word War I Participants\")\nsns.lineplot(x=\"year\",y=\"topratep\",data=df_not_participants, label=\"Nonparticipants\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Top Rate of Income Tax\")",
"_____no_output_____"
],
[
"df[((df[\"country\"]==\"UK\") | (df[\"country\"]==\"France\") | (df[\"country\"]==\"United States\") | (df[\"country\"]==\"Canada\")) & (~df[\"topratep\"].isna())].query(\"year>=1900 & year<=1914\")",
"_____no_output_____"
],
[
"df[((df[\"country\"]==\"UK\") | (df[\"country\"]==\"France\") | (df[\"country\"]==\"United States\") | (df[\"country\"]==\"Canada\")) & (~df[\"topratep\"].isna())].query(\"year>=1900 & year<=1914\")[\"topratep\"].max()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0abd7c3739082d50d91cb4b47a96c8a4b018d76 | 171,626 | ipynb | Jupyter Notebook | basics/first/Ch05 Basic plotting.ipynb | febin-varghese/Data-Science | 25f4f186019573a8355a90300bcaac2bf0e88e13 | [
"BSD-3-Clause"
] | 1 | 2021-01-09T16:53:51.000Z | 2021-01-09T16:53:51.000Z | basics/first/Ch05 Basic plotting.ipynb | febin-varghese/Data-Science | 25f4f186019573a8355a90300bcaac2bf0e88e13 | [
"BSD-3-Clause"
] | null | null | null | basics/first/Ch05 Basic plotting.ipynb | febin-varghese/Data-Science | 25f4f186019573a8355a90300bcaac2bf0e88e13 | [
"BSD-3-Clause"
] | null | null | null | 198.641204 | 19,504 | 0.905574 | [
[
[
"# Basic plotting",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"oo = pd.read_csv('data/olympics.csv',skiprows=4)\noo.head()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Plot types",
"_____no_output_____"
],
[
"### What were the different sports in the first olympics? Plot them using different graphs.",
"_____no_output_____"
]
],
[
[
"fo = oo[oo.Edition == 1896]\nfo.head()",
"_____no_output_____"
]
],
[
[
"### Line plot",
"_____no_output_____"
]
],
[
[
"fo.Sport.value_counts().plot(kind='line');",
"_____no_output_____"
]
],
[
[
"### Bar plot",
"_____no_output_____"
]
],
[
[
"fo.Sport.value_counts().plot(kind='bar');",
"_____no_output_____"
]
],
[
[
"### Horizontal bar plot",
"_____no_output_____"
]
],
[
[
"fo.Sport.value_counts().plot(kind='barh');",
"_____no_output_____"
]
],
[
[
"### Pie chart",
"_____no_output_____"
]
],
[
[
"fo.Sport.value_counts().plot(kind='pie');",
"_____no_output_____"
]
],
[
[
"## Plot colors",
"_____no_output_____"
]
],
[
[
"fo.Sport.value_counts().plot(color='plum')",
"_____no_output_____"
],
[
"fo.Sport.value_counts().plot(kind='bar',color='maroon');",
"_____no_output_____"
]
],
[
[
"## figsize()",
"_____no_output_____"
]
],
[
[
"fo.Sport.value_counts().plot(figsize=(10,3));",
"_____no_output_____"
]
],
[
[
"## Colormaps",
"_____no_output_____"
]
],
[
[
"fo.Sport.value_counts().plot(kind='pie',colormap='Paired');",
"_____no_output_____"
],
[
"fo.Sport.value_counts().plot(kind='bar',color='red');",
"_____no_output_____"
]
],
[
[
"# Seaborn basic plotting",
"_____no_output_____"
]
],
[
[
"import seaborn as sns",
"_____no_output_____"
]
],
[
[
"### How many medals have been won by men and women in the history of the Olympics. How many gold, silver and bronze medals were won for each gender?",
"_____no_output_____"
]
],
[
[
"sns.countplot(x='Medal',data=oo, hue='Gender');",
"_____no_output_____"
],
[
"mw = oo[(oo.Edition == 2008) & (oo.NOC == \"CHN\")]\nmw.Gender.value_counts().plot(kind=\"bar\")",
"_____no_output_____"
],
[
"sns.countplot(data=oo, x=\"Gender\", palette='bwr')",
"_____no_output_____"
],
[
"sns.countplot(x='Medal', data=mw, hue='Gender', palette='bwr', order=['Gold', 'Silver', 'Bronze'])",
"_____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",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0abd8cb5a1006b2e5c7db3c51a892ae806c9a78 | 6,275 | ipynb | Jupyter Notebook | jwst_validation_notebooks/dark_current/jwst_dark_current_unit_tests.ipynb | york-stsci/jwst_validation_notebooks | 1a244c927a027f89dcb01d146964fef71b5ea029 | [
"BSD-3-Clause"
] | 4 | 2019-02-28T21:21:20.000Z | 2022-01-31T04:24:12.000Z | jwst_validation_notebooks/dark_current/jwst_dark_current_unit_tests.ipynb | york-stsci/jwst_validation_notebooks | 1a244c927a027f89dcb01d146964fef71b5ea029 | [
"BSD-3-Clause"
] | 58 | 2020-02-17T14:54:30.000Z | 2022-03-10T14:53:00.000Z | jwst_validation_notebooks/dark_current/jwst_dark_current_unit_tests.ipynb | york-stsci/jwst_validation_notebooks | 1a244c927a027f89dcb01d146964fef71b5ea029 | [
"BSD-3-Clause"
] | 20 | 2019-03-11T17:24:03.000Z | 2022-01-07T20:57:13.000Z | 27.282609 | 309 | 0.568446 | [
[
[
"<a id=\"title_ID\"></a>\n# JWST Pipeline Validation Notebook: calwebb_detector1, dark_current unit tests\n\n<span style=\"color:red\"> **Instruments Affected**</span>: NIRCam, NIRISS, NIRSpec, MIRI, FGS\n\n### Table of Contents\n\n<div style=\"text-align: left\"> \n \n<br> [Introduction](#intro)\n<br> [JWST Unit Tests](#unit)\n<br> [Defining Terms](#terms)\n<br> [Test Description](#description)\n<br> [Data Description](#data_descr)\n<br> [Imports](#imports)\n<br> [Convenience Functions](#functions)\n<br> [Perform Tests](#testing) \n<br> [About This Notebook](#about)\n<br> \n\n</div>",
"_____no_output_____"
],
[
"<a id=\"intro\"></a>\n# Introduction\n\nThis is the validation notebook that displays the unit tests for the Dark Current step in calwebb_detector1. This notebook runs and displays the unit tests that are performed as a part of the normal software continuous integration process. For more information on the pipeline visit the links below. \n\n* Pipeline description: https://jwst-pipeline.readthedocs.io/en/latest/jwst/dark_current/index.html\n\n* Pipeline code: https://github.com/spacetelescope/jwst/tree/master/jwst/\n\n[Top of Page](#title_ID)",
"_____no_output_____"
],
[
"<a id=\"unit\"></a>\n# JWST Unit Tests\n\nJWST unit tests are located in the \"tests\" folder for each pipeline step within the [GitHub repository](https://github.com/spacetelescope/jwst/tree/master/jwst/), e.g., ```jwst/dark_current/tests```.\n\n* Unit test README: https://github.com/spacetelescope/jwst#unit-tests\n\n\n[Top of Page](#title_ID)",
"_____no_output_____"
],
[
"<a id=\"terms\"></a>\n# Defining Terms\n\nThese are terms or acronymns used in this notebook that may not be known a general audience.\n\n* JWST: James Webb Space Telescope\n\n* NIRCam: Near-Infrared Camera\n\n\n[Top of Page](#title_ID)",
"_____no_output_____"
],
[
"<a id=\"description\"></a>\n# Test Description\n\nUnit testing is a software testing method by which individual units of source code are tested to determine whether they are working sufficiently well. Unit tests do not require a separate data file; the test creates the necessary test data and parameters as a part of the test code. \n\n\n[Top of Page](#title_ID)",
"_____no_output_____"
],
[
"<a id=\"data_descr\"></a>\n# Data Description\n\nData used for unit tests is created on the fly within the test itself, and is typically an array in the expected format of JWST data with added metadata needed to run through the pipeline. \n\n\n[Top of Page](#title_ID)",
"_____no_output_____"
],
[
"<a id=\"imports\"></a>\n# Imports\n\n* tempfile for creating temporary output products\n* pytest for unit test functions\n* jwst for the JWST Pipeline\n* IPython.display for display pytest reports\n\n[Top of Page](#title_ID)",
"_____no_output_____"
]
],
[
[
"import tempfile\nimport pytest\nimport jwst\nfrom IPython.display import IFrame",
"_____no_output_____"
]
],
[
[
"<a id=\"functions\"></a>\n# Convenience Functions\n\nHere we define any convenience functions to help with running the unit tests. \n\n[Top of Page](#title_ID)",
"_____no_output_____"
]
],
[
[
"def display_report(fname):\n '''Convenience function to display pytest report.'''\n \n return IFrame(src=fname, width=700, height=600)",
"_____no_output_____"
]
],
[
[
"<a id=\"testing\"></a>\n# Perform Tests\n\nBelow we run the unit tests for the Dark Current step. \n\n[Top of Page](#title_ID)",
"_____no_output_____"
]
],
[
[
"with tempfile.TemporaryDirectory() as tmpdir:\n !pytest jwst/dark_current -v --ignore=jwst/associations --ignore=jwst/datamodels --ignore=jwst/stpipe --ignore=jwst/regtest --html=tmpdir/unit_report.html --self-contained-html\n report = display_report('tmpdir/unit_report.html')",
"_____no_output_____"
],
[
"report",
"_____no_output_____"
]
],
[
[
"<a id=\"about\"></a>\n## About This Notebook\n**Author:** Alicia Canipe, Staff Scientist, NIRCam\n<br>**Updated On:** 01/07/2021",
"_____no_output_____"
],
[
"[Top of Page](#title_ID)\n<img style=\"float: right;\" src=\"./stsci_pri_combo_mark_horizonal_white_bkgd.png\" alt=\"stsci_pri_combo_mark_horizonal_white_bkgd\" width=\"200px\"/> ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
d0abd93fe19fcd83e3a0f322751bfb1519e25acb | 104,512 | ipynb | Jupyter Notebook | lectures/other/Transposition.ipynb | snowdj/18S096-iap17 | 0a922819405312f4201c82828bc0fe94ef186b24 | [
"MIT"
] | 107 | 2019-02-20T01:38:18.000Z | 2022-03-21T03:01:03.000Z | lectures/other/Transposition.ipynb | snowdj/18S096-iap17 | 0a922819405312f4201c82828bc0fe94ef186b24 | [
"MIT"
] | null | null | null | lectures/other/Transposition.ipynb | snowdj/18S096-iap17 | 0a922819405312f4201c82828bc0fe94ef186b24 | [
"MIT"
] | 25 | 2019-04-16T20:43:02.000Z | 2022-03-24T22:18:06.000Z | 237.527273 | 60,226 | 0.907427 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
d0abddbefed726d5442e722fb80414cf83e9de70 | 9,449 | ipynb | Jupyter Notebook | 01_install_tensorflow_and_libs/.ipynb_checkpoints/01_install_tensorflow_and_libs-checkpoint.ipynb | mechasolution-vn/machine-learning-on-pi-with-tensorflow | 03173a45a7a63377ee1fbb4df9b4ae2e57a0ee06 | [
"MIT"
] | 1 | 2020-10-09T13:37:01.000Z | 2020-10-09T13:37:01.000Z | 01_install_tensorflow_and_libs/01_install_tensorflow_and_libs.ipynb | mechasolution-vn/machine-learning-on-pi-with-tensorflow | 03173a45a7a63377ee1fbb4df9b4ae2e57a0ee06 | [
"MIT"
] | null | null | null | 01_install_tensorflow_and_libs/01_install_tensorflow_and_libs.ipynb | mechasolution-vn/machine-learning-on-pi-with-tensorflow | 03173a45a7a63377ee1fbb4df9b4ae2e57a0ee06 | [
"MIT"
] | null | null | null | 37.496032 | 391 | 0.610223 | [
[
[
"## Dự án 01: Xây dựng Raspberry PI thành máy tính cho Data Scientist (PIDS)\n## Bài 01. Cài đặt TensorFlow và các thư viện cần thiết\n\n##### Người soạn: Dương Trần Hà Phương\n##### Website: [Mechasolution Việt Nam](https://mechasolution.vn)\n##### Email: [email protected]\n---",
"_____no_output_____"
],
[
"## 1. Mở đầu\nNếu bạn muốn chạy một Neural network model hoặc một thuật toán dự đoán nào đó trên một hệ thống nhúng thì Raspberry PI là một lựa chọn hoàn hảo cho bạn.\n\nChỉ cần lựa chọn phiên bản Raspberry phù hợp với dự án của bạn. Sau đó, cài đặt hệ điều hành mới nhất và xong. Bạn đã sẵn sàng để khám phá thế giới Raspberry kì diệu rồi đó.",
"_____no_output_____"
],
[
"## 2. Yêu cầu cần thiết\n**Hệ điều hành: Raspbian**\n* Tải xuống phiên bản mới nhất của hệ điều hành Raspbian tại [ĐÂY](https://downloads.raspberrypi.org/raspbian_latest)\n* Sử dụng [Etcher](https://etcher.io/) để copy Raspbian lên thẻ nhớ (MicroSD)\n* Tham khảo cách cài đặt và chạy Raspbian tại bài viết [**Thiết lập Raspberry PI**](https://mechasolution.vn/Blog/bai-1-thiet-lap-raspberry-pi)\n\n**Python**\n* Ở đây chúng ta sẽ dùng Python làm ngôn ngữ chính để lập trình vì nhiều lý do như: hiện thực thuật toán nhanh, đơn giản, hệ thống thư viện hỗ trợ đa dạng.\n* Phiên bản Raspbian mới nhất ([2018–04–18-raspbian-stretch](https://downloads.raspberrypi.org/raspbian_latest)) đã được cài đặt 2 phiên bản Python là Python 3.5.2 và 2.7.13. Ở đây tôi sử dụng phiên bản Python 3.5.x để demo.",
"_____no_output_____"
],
[
"## 3. Cài đặt Numpy\n\nNumpy là thư viện toán học cho ngôn ngữ lập trình Python. Numpy hỗ trợ mảng, ma trận có kích thước và số chiều lớn cùng các toán tử đa dạng để tính toán trên mảng, ma trận. Cơ sở của Machine Learning dự trên phần lớn là toán học nên Numpy là một thư viện nền tảng không thể thiếu. Số lượng Commits và Contributors trên Github cũng cực kì ấn tượng: Commits: 15980, Contributors: 522.\n\nChúng ta cài đặt Numpy với dòng lệnh sau:\n\n> `sudo apt-get install python3-numpy`",
"_____no_output_____"
],
[
"## 4. Cài đặt Scipy\n\nScipy là thư viện dành cho các nhà khoa học và kĩ sư. SciPy bao gồm các modules: linear algebra, optimization, integration, and statistics. Đây cũng là một thư viện nền tảng không thể thiếu cho các dự án Machine Learning. Scipy cũng có số lượng Commits và Contributors trên Github rất lớn: **Commits: 17213, Contributors: 489**\n\nChúng ta cài đặt Scipy và các thư viện liên quan với các dòng lệnh sau:\n\n> `sudo apt-get install libblas-dev`\n\n> `sudo apt-get install liblapack-dev`\n\n> `sudo apt-get install python3-dev # Có thể đã được cài đặt sẵn`\n\n> `sudo apt-get install libatlas-base-dev # Tuỳ chọn`\n\n> `sudo apt-get install gfortran`\n\n> `sudo apt-get install python3-setuptools # Có thể đã được cài đặt sẵn`\n\n> `sudo apt-get install python3-scipy`",
"_____no_output_____"
],
[
"## 5. Cài đặt Scikit-learn\n\nScikit-learn (Sklearn) là các gói bổ sung của SciPy Stack được thiết kế cho các chức năng cụ thể như xử lý hình ảnh và Machine learning được dễ dàng hơn, nhanh hơn và tiện dụng hơn. Lượt Commits và Contributors trên Github lần lượt là: **Commits: 21793, Contributors: 842**.\n\n> `sudo pip3 install scikit-learn`\n\n> `sudo pip3 install pillow`\n\n> `sudo apt-get install python3-h5py`",
"_____no_output_____"
],
[
"## 6. Cài đặt Matplotlib\n\nMatplotlib là một thư viện hỗ trợ trực quan hoá dữ liệu một cách đơn giản nhưng không kém phần mạnh mẽ. Với một chút nỗ lực, bạn có thể trực quan hoá bất kỳ dữ liệu nào: Line plots; Scatter plots; Bar charts and Histograms; Pie charts; Stem plots; Contour plots; Quiver plots; Spectrograms. Số lượng Commits và Contributors trên Github là: **Commits: 21754, Contributors: 588**.\n\n> `sudo apt-get install python3-matplotlib`",
"_____no_output_____"
],
[
"## 7. Upgrade pip\n\nChúng ta hãy cập nhật pip trước khi tiến hành cài đặt thư viện tiếp theo - Jupyter notebook.\n\n> `sudo pip3 install --upgrade pip`\n\n> `reboot`",
"_____no_output_____"
],
[
"## 8. Cài đặt Jupyter Notebook\n\n[Jupyter Notebook](http://jupyter.org/) là một ứng dụng web mã nguồn mở cho phép bạn tạo hoặc chia sẻ những văn bản chứa:\n* live code\n* mô phỏng\n* văn bản diễn giải\n\nSau đó, bạn chạy các lệnh dưới đây trên Terminal:\n\n> `sudo pip3 install jupyter`\n\nKhi cài đặt xong, chạy dòng lệnh dưới đây để khởi động Jupyter Notebook\n> `jupyter notebook`\n\nKết quả, bạn sẽ thấy trình duyệt web được mở lên cùng với giao diện Jupyter Notebook như sau:\n\n\n\nXem bài viết [Sử dụng Jupyter Notebook cho Python](https://mechasolution.vn/Blog/bai-3-su-dung-jupyter-notebook-cho-python) để xem thêm về cách sử dụng Jupyter Notebook",
"_____no_output_____"
],
[
"## 9. Cài đặt TensorFlow\n[**TensorFlow**](https://www.tensorflow.org/) là một hệ thống chuyên dùng để tính toán trên đồ thị (graph-based computation). Một ví dụ điển hình là sử dụng trong máy học (machine learning).\n\nỞ đây, tôi sử dụng **Python Wheel Package (*.WHL)** được cung cấp bởi [lhelontra](https://github.com/lhelontra) tại [tensorflow-on-arm](https://github.com/lhelontra/tensorflow-on-arm)\n\n### * Với Raspberry PI 2 / 3\n###### ♦ Với Python version 3.5.x\n> `wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp35-none-linux_armv7l.whl`\n\n> `sudo pip3 install tensorflow-1.8.0-cp35-none-linux_armv7l.whl`\n\n> `sudo pip3 uninstall mock`\n\n> `sudo pip3 install mock`\n\n###### ♦ Với Python version 2.7.x\n> `wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp27-none-linux_armv7l.wh`\n\n> `sudo pip3 install tensorflow-1.8.0-cp35-none-linux_armv7l.whl`\n\n> `sudo pip3 uninstall mock`\n\n> `sudo pip3 install mock`\n\n### * Với Raspberry PI One / Zero\n###### ♦ Với Python version 3.5.x\n> `wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp35-none-linux_armv6l.whl`\n\n> `sudo pip3 install tensorflow-1.8.0-cp35-none-linux_armv6l.whl`\n\n> `sudo pip3 uninstall mock`\n\n> `sudo pip3 install mock`\n\n###### ♦ Với Python version 2.7.x\n> `wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp27-none-linux_armv6l.whl`\n\n> `sudo pip3 install tensorflow-1.8.0-cp27-none-linux_armv6l.whl`\n\n> `sudo pip3 uninstall mock`\n\n> `sudo pip3 install mock`\n\nSau khi cài đặt xong, bạn có thể kiểm tra xem mình có cài đặt thành công không bằng cách import TensorFlow và in ra phiên bản hiện tại (như hình):\n\n",
"_____no_output_____"
],
[
"### Tham khảo:\n\n* https://medium.com/@abhizcc/installing-latest-tensor-flow-and-keras-on-raspberry-pi-aac7dbf95f2\n\n* https://medium.com/activewizards-machine-learning-company/top-15-python-libraries-for-data-science-in-in-2017-ab61b4f9b4a7\n\n* http://www.instructables.com/id/Installing-Keras-on-Raspberry-Pi-3/",
"_____no_output_____"
],
[
"---\nNếu có thắc mắc hoặc góp ý, các bạn hãy comment bên dưới để bài viết có thể được hoàn thiện hơn. \nXin cảm ơn,\n\nHà Phương - Mechasolution Việt Nam.",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d0abe07a82ba3897334901860125b5c8e9a33a6e | 1,263 | ipynb | Jupyter Notebook | results.ipynb | mariatippler/haven-ai | 2a6c88922b504f382d270eded34232d6ac9f0226 | [
"Apache-2.0"
] | null | null | null | results.ipynb | mariatippler/haven-ai | 2a6c88922b504f382d270eded34232d6ac9f0226 | [
"Apache-2.0"
] | null | null | null | results.ipynb | mariatippler/haven-ai | 2a6c88922b504f382d270eded34232d6ac9f0226 | [
"Apache-2.0"
] | null | null | null | 28.704545 | 82 | 0.529691 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
d0ac032193d305d7e1e448ddded39adc54b4b250 | 20,365 | ipynb | Jupyter Notebook | MatrixP.ipynb | marceljanerfont/MatrixP | 94fc881e3696f79a1ee6d8ec78535810c26f5b10 | [
"MIT"
] | null | null | null | MatrixP.ipynb | marceljanerfont/MatrixP | 94fc881e3696f79a1ee6d8ec78535810c26f5b10 | [
"MIT"
] | null | null | null | MatrixP.ipynb | marceljanerfont/MatrixP | 94fc881e3696f79a1ee6d8ec78535810c26f5b10 | [
"MIT"
] | null | null | null | 33.22186 | 335 | 0.49698 | [
[
[
"# Transform points from pitch to texture and vice-versa\n### Matrix P - Projection\nThe P matrix is a 3x4 matrix that given a 3D point in the world reference frame, it is projected into the 2D image in **texture coordinate** reference frame, i.e:\n\n\\begin{align}\n\\mathbf{pt_{world}} = (x, y, z, 1) \\\\\n\\mathbf{pt_{pitch}} = (a, b, c) = \\mathbf{P_{texture}} * \\mathbf{pt_{world}} \\\\\n\\mathbf{pt_{texture}} = (i, j) = (a/c, b/c)\n\\end{align}\n\n**Texture coordinate range** is [0.0, 1.0]\n\n<img src=\"pitch.png\" style=\"width: 400px;\">\n\n### Matrix H - Homography\nThe H matrix is a 3x3 Matrix that transforms points from one plane to another. In our case from pitch to texture and from texture to pitch which is the inverse of the first (pitch to texture homography). **Pitch is the world plane where z=0.** Hence, get matrix **H*pith2texture*** is as simple as discard 3th matrix P column:\n\n\n<img src=\"homo.png\" style=\"width: 500px;\">\n\n### How to convert from pitch (world) to texture coordinate system\n\\begin{align}\n\\mathbf{pt_{texture}} = \\mathbf{H_{pitch2texture}} * \\mathbf{pt_{pitch}}\n\\end{align}\n\n### How to convert from texture to pitch (world) coordinate system\n\\begin{align}\n\\mathbf{pt_{pitch}} = \\mathbf{H_{texture2pitch}} * \\mathbf{pt_{texture}}\n\\end{align}\n\nWhere,\n\n\\begin{align}\n\\mathbf{H_{texture2pitch}} = \\mathbf{H_{pitch2texture}^{-1}}\n\\end{align}\n\n### How to convert from texture to video image coordinate system\n\n\\begin{equation*}\n\\mathbf{P_{image}} = \\begin{vmatrix}\nWidth & 0 & 0 \\\\ 0 & Height & 0 \\\\ 0 & 0 & 1\n\\end{vmatrix} * \\mathbf{P_{texture}}\n\\end{equation*}\n\nWhere **`Width`** and **`Height`** refer to the video frame size. ",
"_____no_output_____"
]
],
[
[
"# import what we need\nimport numpy as np\nimport math",
"_____no_output_____"
],
[
"def rodrigues(r):\n '''\n Rodrigues formula\n :param r: 1x3 array of rotations about x, y, and z\n :return: the 3x3 rotation matrix\n '''\n def S(n):\n Sn = np.array([\n [0.0, -n[2], n[1]],\n [n[2], 0.0, -n[0]],\n [-n[1], n[0], 0]])\n return Sn\n theta = np.linalg.norm(r)\n if theta > 1e-30:\n n = r/theta\n Sn = S(n)\n R = np.eye(3) + np.sin(theta) * Sn + (1.0 - np.cos(theta)) * np.dot(Sn, Sn)\n else:\n Sr = S(r)\n theta2 = theta ** 2.0\n R = np.eye(3) + (1.0 - theta2 / 6.0)*Sr + (0.5 - theta2 / 24.0) * np.dot(Sr, Sr)\n return np.mat(R)",
"_____no_output_____"
],
[
"def world_to_texture(pw, P):\n \"\"\"\n Projects a world point to texture projection plane\n :param pw: world point (x, y, z)\n :param P: projection matrix P\n :return: texture point (i, j)\n \"\"\"\n pw_h = np.append(pw, 1.0)\n pp = P.dot(pw_h)\n return np.array([pp[0]/pp[2], pp[1]/pp[2]])",
"_____no_output_____"
],
[
"def homography_pitch_to_texture(P):\n \"\"\"\n Returns the homografy to transform points from the pitch (world Z=0) to texture image\n :param matrixP: Full matrix P\n :return: homography_pitch_to_texture matrix\n \"\"\"\n # delete the 3th column, the z component\n return np.delete(P, 2, axis=1) ",
"_____no_output_____"
],
[
"def pitch_to_texture(pitch, P):\n \"\"\"\n Project a point from pitch plane to texture plane\n :param pitch: pitch point (x, y)\n :param P: projection matrix P\n :return: texture point (i, j)\n \"\"\"\n pitch_h = np.append(pitch, 1.0)\n H = homography_pitch_to_texture(P)\n transformed = H.dot(pitch_h)\n #print(projected)\n return np.array([transformed[0]/transformed[2], transformed[1]/transformed[2]])\n ",
"_____no_output_____"
],
[
"def texture_to_pitch(texture, P):\n \"\"\"\n Project a point from texture plane to pitch plane\n :param texture: texture point (i, j)\n :param P: projection matrix P\n :return: pitch point (x, y)\n \"\"\"\n texture_h = np.append(texture, 1.0)\n H = homography_pitch_to_texture(P)\n Hinv = np.linalg.inv(H)\n transformed = Hinv.dot(texture_h)\n return np.array([transformed[0]/transformed[2], transformed[1]/transformed[2]])",
"_____no_output_____"
],
[
"def texture_to_image(texture, width, height):\n \"\"\"\n Converts a texture coordinate to image coordinate system\n \"\"\"\n return np.array([int(float(width)*texture[0]), int(float(height)*texture[1])])\n\ndef image_to_texture(image, width, height):\n \"\"\"\n Converts a image coordinate to texture coordinate system\n \"\"\"\n return np.array([float(image[0])/float(width), float(image[1])/float(height)])",
"_____no_output_____"
]
],
[
[
"# Projection matrix P from an individual camera\nThe funciton `camera_full_projection_matrix` is only valid for individual cameras. \n\n## How to get camera parameters: *aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz* \nYou can find camera parameters **`aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz`** in `C:\\AutomaticTV\\data\\cameras\\{id}.xml`. In XML `<modelcalibration>` tag, for instance:\n\n```\n<modelsCalibration>\n <modelCalibration computed=\"true\" sportFieldName=\"Football11\">\n <Zoom>1.2124214</Zoom>\n <AspectRatio>1.7777778</AspectRatio>\n <Skew>0</Skew>\n <Pan>-28.826538</Pan>\n <Tilt>110.37401</Tilt>\n <Roll>-10.530287</Roll>\n <Tx>34.07756</Tx>\n <Ty>-3.4855517</Ty>\n <Tz>74.498503</Tz>\n </modelCalibration>\n </modelsCalibration>\n```",
"_____no_output_____"
]
],
[
[
"def camera_full_projection_matrix(aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz):\n \"\"\"\n Creates projection matrix P from camera model parameters\n :param aspect_ratio: camera aspect ratio = image width / image height\n :param zoom: camera focal\n :param skew:\n :param pan:\n :param tilt:\n :param roll:\n :param Tx:\n :param Ty:\n :param Tz:\n :return: the projection Matrix P\n \"\"\"\n K = np.array([[zoom, skew, 0.5], [0.0, zoom * aspect_ratio, 0.5], [0.0, 0.0, 1.0]])\n\n # Rotation matrix\n Rpan = rodrigues(np.array([0.0, 0.0, pan*math.pi/180.0]))\n Rtilt = rodrigues(np.array([tilt*math.pi/180.0, 0.0, 0.0]))\n Rroll = rodrigues(np.array([0.0, 0.0, roll*math.pi/180.0]))\n Mrot = Rroll * Rtilt * Rpan\n\n # Translation vector\n t = np.array([Tx, Ty, Tz])\n KR = K * Mrot\n Kt = np.dot(K, t)\n\n # Projection Martix P\n P = np.zeros((3, 4))\n P[:, 0] = KR[:, 0].T\n P[:, 1] = KR[:, 1].T\n P[:, 2] = KR[:, 2].T\n P[:, 3] = Kt\n return P",
"_____no_output_____"
]
],
[
[
"### Individual camera matrix P Testing",
"_____no_output_____"
]
],
[
[
"# test\n# test matrixP_from_camera_model\ncamera_model = {\n \"aspect_ratio\": 5.333333333,\n \"zoom\": 0.45361389,\n \"skew\": 0.0,\n \"pan\": -2.0953152,\n \"tilt\": 108.76381,\n \"roll\": 0.0,\n \"Tx\": 0.48063888,\n \"Ty\": -0.30635475,\n \"Tz\": 87.349004}\nP = camera_full_projection_matrix(**camera_model)\nP_expected = np.array([[0.436, 0.4897, -0.1608, 43.893],\n [0.01114, -0.3046, -2.4515, 42.933],\n [-0.03462, 0.9462, -0.3217, 87.349]])\nassert(np.allclose(P, P_expected, rtol=1e-3))\n\n# ML\ncamera_model = {\n \"aspect_ratio\": 1.7777778,\n \"zoom\": 1.2124214,\n \"skew\": 0.0,\n \"pan\": -28.826538,\n \"tilt\": 110.37401,\n \"roll\": -10.530287,\n \"Tx\": 34.07756,\n \"Ty\": -3.4855517,\n \"Tz\": 74.498503}\nP = camera_full_projection_matrix(**camera_model)\nprint(P)\nP_expected = np.array([[0.8555, 0.9178, -0.3818, 78.566],\n [-0.2154, -0.4256, -2.1606, 29.736],\n [-0.452, 0.8213, -0.3481, 74.499]])\nassert(np.allclose(P, P_expected, rtol=1e-3))\n\nprint()\n# project world point\nx = -10.0\ny = 3.0\nworld = np.array([x, y, 0.0])\nprint(\"world: {}\".format(world))\ntexture = world_to_texture(world, P)\nprint(\"texture: {}\".format(texture))\n\"\"\"\nif (texture > 1.0).any() or (texture < 0.0).any():\n print(\"point is out the texture limits\")\nelse:\n print(\"point is in the texture limits\")\n\"\"\"\n\nprint()\n# transform point from pitch to texture plane\npitch = np.array([x, y])\nprint(\"pitch: {}\".format(pitch))\ntexture = pitch_to_texture(pitch, P)\nprint(\"texture: {}\".format(texture))\n\nprint()\n# transform point from texture to pitch\nprint(\"texture: {}\".format(texture))\npitch = texture_to_pitch(texture, P)\nprint(\"pitch: {}\".format(pitch))\n\n",
"[[ 0.85549003 0.91779104 -0.38178799 78.5656145 ]\n [ -0.21537938 -0.42563356 -2.16061687 29.73643812]\n [ -0.45199561 0.82127568 -0.34814685 74.498503 ]]\n\nworld: [-10. 3. 0.]\ntexture: [ 0.89300498 0.37570535]\n\npitch: [-10. 3.]\ntexture: [ 0.89300498 0.37570535]\n\ntexture: [ 0.89300498 0.37570535]\npitch: [-10. 3.]\n"
]
],
[
[
"## Matrix P for Panorama\n\n## How to get Panorama camera parameters: *src_width, src_height, zoom, skew, pan, tilt, roll, Tx, Ty, Tz* \nYou can find camera parameters **`zoom, skew, pan, tilt, roll, Tx, Ty, Tz`** in `C:\\AutomaticTV\\data\\virtual_cameras\\{id}.xml`. In XML `<CameraModel name=\"PANORAMA\">` tag, for instance:\n\n```\n <CameraModel name=\"PANORAMA\">\n <Width>5760</Width>\n <Height>1080</Height>\n <Zoom>0.45361389</Zoom>\n <AspectRatio>5.3333333</AspectRatio>\n <Skew>0</Skew>\n <Pan>-2.0953152</Pan>\n <Tilt>108.76381</Tilt>\n <Roll>10</Roll>\n <Tx>0.48063888</Tx>\n <Ty>-0.30635475</Ty>\n <Tz>87.349004</Tz>\n </CameraModel>\n```\n* **src_width** is `5760`\n* **src_height** is `1080`\n\n**NOTE: Do not use this `AspectRatio`.**\n\n## How to get Panorama camera *offset_x* and *offset_y*\nYou can find **`offset_x`** and **`offset_y`** in `C:\\AutomaticTV\\data\\virtual_cameras\\{id}.xml` file tag `<PanoramaOffsetX>` and `<PanoramaOffsetY>`\n```\n <PanoramaOffsetX>0</PanoramaOffsetX>\n <PanoramaOffsetY>0</PanoramaOffsetY>\n```\n\n## How to get Panorama camera *src_width* and *src_height*\nIt can be found in `C:\\AutomaticTV\\data\\productions\\{id}.xml`. In XML `<panorama><realization>` tag, for instance:`\n```\n <width>3840</width>\n <height>1080</height>\n```\n\n## How to get Panorama camera *aspect_ratio, state_x, state_y, state_zoom*\nIt can be found in `C:\\AutomaticTV\\data\\productions\\{id}.xml`. In XML `<panorama><realization><operators><operator name=\"panorama\"><currentState>` tag, for instance:\n\n```\n <currentState>\n <elem>0.500000</elem>\n <elem>0.500000</elem>\n <elem>1.000000</elem>\n <elem>0.453614</elem>\n <elem>3.555556</elem>\n <elem>0.000000</elem>\n <elem>-2.095315</elem>\n <elem>108.763810</elem>\n <elem>0.000000</elem>\n <elem>0.480639</elem>\n <elem>-0.306355</elem>\n <elem>87.349004</elem>\n </currentState>\n```\nwhere:\n* ***aspect_ratio*** is the 4th elem `3.555556`\n* ***state_x*** is the 1st elem `0.500000`\n* ***state_y*** is the 2nd elem `0.500000`\n* ***state_zoom*** is the 3rd elem `1.000000`",
"_____no_output_____"
]
],
[
[
"def camera_full_projection_matrix_with_crop(aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz, crop_tx, crop_ty, crop_zoom):\n \"\"\"\n Creates projection matrix P from camera model parameters\n :param aspect_ratio: camera aspect ratio = dst_width / dst_height\n :param zoom: camera focal\n :param skew:\n :param pan:\n :param tilt:\n :param roll:\n :param Tx:\n :param Ty:\n :param Tz:\n :param crop_tx:\n :param crop_ty:\n :param crop_zoom:\n :return: the projection Matrix P\n \"\"\"\n K = np.array([[crop_zoom * zoom, crop_zoom * skew, 0.5 + crop_tx], \n [0.0, crop_zoom * zoom * aspect_ratio, 0.5 + crop_ty],\n [0.0, 0.0, 1.0]])\n\n # Rotation matrix\n Rpan = rodrigues(np.array([0.0, 0.0, pan*math.pi/180.0]))\n Rtilt = rodrigues(np.array([tilt*math.pi/180.0, 0.0, 0.0]))\n Rroll = rodrigues(np.array([0.0, 0.0, roll*math.pi/180.0]))\n Mrot = Rroll * Rtilt * Rpan\n\n # Translation vector\n t = np.array([Tx, Ty, Tz])\n KR = K * Mrot\n Kt = np.dot(K, t)\n\n # Projection Martix P\n P = np.zeros((3, 4))\n P[:, 0] = KR[:, 0].T\n P[:, 1] = KR[:, 1].T\n P[:, 2] = KR[:, 2].T\n P[:, 3] = Kt\n return P\n\ndef get_crop_params(src_width, src_height, offset_x, offset_y, dst_width, dst_height, state_x, state_y, state_zoom):\n \"\"\"\n Computes crop parameters taking in account source and destination dimensions\n : return crop_tx: \n : return crop_ty:\n : return crop_zoom:\n \"\"\"\n width_ratio_inv = float(src_width) / float(dst_width)\n height_ratio_inv = float(src_height) / float(dst_height)\n crop_tx = (0.5 - state_x + offset_y) * (state_zoom * width_ratio_inv)\n crop_ty = (0.5 - state_x + offset_y) * (state_zoom * height_ratio_inv)\n crop_zoom = state_zoom * max(width_ratio_inv, height_ratio_inv)\n \n return crop_tx, crop_ty, crop_zoom",
"_____no_output_____"
]
],
[
[
"### Panorama matrix P Testing",
"_____no_output_____"
]
],
[
[
"camera_model = {\n \"aspect_ratio\": 3.5555555820465088,\n \"zoom\": 0.45361389,\n \"skew\": 0.0,\n \"pan\": -2.0953152,\n \"tilt\": 108.76381,\n \"roll\": 10.0,\n \"Tx\": 0.48063888,\n \"Ty\": -0.30635475,\n \"Tz\": 87.349004}\n\ncrop_params = {\n \"src_width\": 5760,\n \"src_height\": 1080,\n \"offset_x\": 0.0,\n \"offset_y\": 0.0,\n \"dst_width\": 3840,\n \"dst_height\": 1080,\n \"state_x\": 0.5,\n \"state_y\": 0.5,\n \"state_zoom\": 1.0}\n\n# compute crop from params\ncrop_tx, crop_ty, crop_zoom = get_crop_params(**crop_params)\nprint(\"crop: {}, {}, {}\".format(crop_tx, crop_ty, crop_zoom))\n\n# compute matrix P\nP = camera_full_projection_matrix_with_crop(**camera_model, crop_tx=crop_tx, crop_ty=crop_ty, crop_zoom=crop_zoom)\nprint(P)\nP_expected = np.array([[0.6509, 0.53559, -0.04896, 44.0015],\n [0.4305, -0.2774, -2.4167, 42.933],\n [-0.034618, 0.946219, -0.321667, 87.3490]])\nassert(np.allclose(P, P_expected, rtol=1e-3))\n\n",
"crop: 0.0, 0.0, 1.5\n[[ 6.50936689e-01 5.35590234e-01 -4.89595755e-02 4.40015387e+01]\n [ 4.30532613e-01 -2.77397706e-01 -2.41672906e+00 4.29333459e+01]\n [ -3.46188241e-02 9.46219547e-01 -3.21667695e-01 8.73490040e+01]]\n"
]
],
[
[
"## How to transform points from an image A to an image B\n\n<img src=\"imageA2imageB.png\">\n\n### How to get frames from video\n```\nffmpeg -i \"CleanFeed.mp4\" \"frames/out-%03d.jpg\"\n```",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d0ac2f326380065762b54a9f8a5bbf87cc9ae5a3 | 80,559 | ipynb | Jupyter Notebook | aquaponics-master/notebooks/Aquaponics/Plant + Bacteria.ipynb | JunwenLIU/Aquaponics_system_Simulink | 5048012730815f3e8bb5ccb254c7e1d4be8a84d4 | [
"Apache-2.0"
] | null | null | null | aquaponics-master/notebooks/Aquaponics/Plant + Bacteria.ipynb | JunwenLIU/Aquaponics_system_Simulink | 5048012730815f3e8bb5ccb254c7e1d4be8a84d4 | [
"Apache-2.0"
] | null | null | null | aquaponics-master/notebooks/Aquaponics/Plant + Bacteria.ipynb | JunwenLIU/Aquaponics_system_Simulink | 5048012730815f3e8bb5ccb254c7e1d4be8a84d4 | [
"Apache-2.0"
] | null | null | null | 601.186567 | 77,680 | 0.948994 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom time import time\n\nfrom aquaponics import Aquaponics\nimode = 7",
"_____no_output_____"
],
[
"a = Aquaponics(\n 'plant', 'bacteria', 'nitrogen', \n NH3_0=100, ppb0=30, beds=[(0,30), (30, 60), (60, 90)], kswitch=100\n)\nm = a.get_model()\n\ntf = 90\nsteps = tf * 12 + 1\nm.time = np.linspace(0,tf,steps)\n\nstart = time()\na.solve(glamdring=True, imode=imode, disp=False)\nprint('Solved in {:.2f} Seconds'.format(time() - start))",
"Solved in 14.54 Seconds\n"
],
[
"%matplotlib inline\nplt.figure(figsize=(12,12))\nax = plt.subplot(411)\nplt.plot(m.time, a.w, label='Dry Weight')\nplt.grid()\nplt.legend()\n\nplt.subplot(412, sharex=ax)\nplt.plot(m.time, a.dNup, label='dNup')\nplt.grid()\nplt.legend()\n\nplt.subplot(413, sharex=ax)\nplt.plot(m.time, a.NH3, label='NH3')\nplt.plot(m.time, a.NO2, label='N02')\nplt.plot(m.time, a.NO3, label='NO3')\nplt.grid()\nplt.legend()\nplt.ylabel('Concentration (mg/l)')\n\nplt.subplot(414, sharex=ax)\nplt.plot(m.time, a.Cm, label='Cm')\nplt.plot(m.time, a.Cb, label='Cb')\nplt.grid()\nplt.legend()\nplt.ylabel('Concentration (mg/l)')\n\nplt.xlim(0, tf)\nplt.xlabel('Time (days)')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
d0ac3819a05650d8190cc62f2a999d8a87889a92 | 30,586 | ipynb | Jupyter Notebook | notebooks/09 - Tensorflow_prediction.ipynb | UnfoldedInc/examples | 10203fbf25bc29e79cae5b12fcb835f3e6afed13 | [
"MIT"
] | 15 | 2021-04-13T20:18:44.000Z | 2022-03-12T17:52:16.000Z | notebooks/09 - Tensorflow_prediction.ipynb | UnfoldedInc/examples | 10203fbf25bc29e79cae5b12fcb835f3e6afed13 | [
"MIT"
] | 16 | 2021-04-13T18:44:18.000Z | 2022-01-31T18:39:51.000Z | notebooks/09 - Tensorflow_prediction.ipynb | UnfoldedInc/examples | 10203fbf25bc29e79cae5b12fcb835f3e6afed13 | [
"MIT"
] | 5 | 2021-07-01T07:58:26.000Z | 2022-01-20T21:58:45.000Z | 29.101808 | 313 | 0.549696 | [
[
[
"# House Price Prediction With TensorFlow\n\n[![open_in_colab][colab_badge]][colab_notebook_link]\n[![open_in_binder][binder_badge]][binder_notebook_link]\n\n[colab_badge]: https://colab.research.google.com/assets/colab-badge.svg\n[colab_notebook_link]: https://colab.research.google.com/github/UnfoldedInc/examples/blob/master/notebooks/09%20-%20Tensorflow_prediction.ipynb\n[binder_badge]: https://mybinder.org/badge_logo.svg\n[binder_notebook_link]: https://mybinder.org/v2/gh/UnfoldedInc/examples/master?urlpath=lab/tree/notebooks/09%20-%20Tensorflow_prediction.ipynb",
"_____no_output_____"
],
[
"This example demonstrates how the Unfolded Map SDK allows for more engaging exploratory data visualization, helping to simplify the process of building a machine learning model for predicting median house prices in California.",
"_____no_output_____"
],
[
"## Dependencies ",
"_____no_output_____"
],
[
"This notebook uses the following dependencies:\n\n- pandas\n- numpy\n- scikit-learn\n- scipy\n- seaborn\n- matplotlib\n- tensorflow\n\nIf running this notebook in Binder, these dependencies should already be installed. If running in Colab, the next cell will install these dependencies. In another environment, you'll need to make sure these dependencies are available by running the following `pip` command in a shell.\n\n```bash\npip install pandas numpy scikit-learn scipy seaborn matplotlib tensorflow\n```\n\nThis notebook was originally tested with the following package versions, but likely works with a broad range of versions:\n\n- pandas==1.3.2\n- numpy==1.19.5\n- scikit-learn==0.24.2\n- scipy==1.7.1\n- seaborn==0.11.2\n- matplotlib==3.4.3\n- tensorflow==2.6.0",
"_____no_output_____"
]
],
[
[
"# If in Colab, install this notebook's required dependencies\nimport sys\nif \"google.colab\" in sys.modules:\n !pip install 'unfolded.map_sdk>=0.6.3' pandas numpy scikit-learn scipy seaborn matplotlib tensorflow",
"_____no_output_____"
]
],
[
[
"## Imports",
"_____no_output_____"
],
[
"If you're running this notebook on Binder, you may see a notification like the following when running the next cell.\n```\nCould not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory\nIgnore above cudart dlerror if you do not have a GPU set up on your machine.\n```\nThis is expected behavior because the machines on which Binder is running are not equipped with GPUs. The notebook will still function fine, it will just run slightly slower than on a machine with a GPU available.",
"_____no_output_____"
]
],
[
[
"from uuid import uuid4\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.cluster import KMeans\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense\n\nfrom unfolded.map_sdk import UnfoldedMap",
"_____no_output_____"
]
],
[
[
"## Data Loading",
"_____no_output_____"
],
[
"For this example we'll use data from Kaggle's [California Housing Prices](https://www.kaggle.com/camnugent/california-housing-prices) dataset under the CC0 license. This dataset contains information about the housing in each census area in California, as of the 1990 census.",
"_____no_output_____"
]
],
[
[
"dataset_url = \"https://raw.githubusercontent.com/UnfoldedInc/examples/master/notebooks/data/housing.csv\"\nhousing = pd.read_csv(dataset_url)\nhousing.head()",
"_____no_output_____"
]
],
[
[
"## Feature Engineering",
"_____no_output_____"
],
[
"First, let's take a look at the input data and try to visualize different aspects of them in a map.",
"_____no_output_____"
],
[
"### Population Clustering",
"_____no_output_____"
],
[
"In the next cell we'll create a map that clusters rows of the dataset according to population. Note that since the clustering happens within Unfolded Studio, the clusters are re-computed as you zoom in, allowing you to explore your data at various resolutions.",
"_____no_output_____"
]
],
[
[
"population_in_CA = UnfoldedMap()\npopulation_in_CA",
"_____no_output_____"
],
[
"# Create a persistent dataset ID that we can reference in both add_dataset and add_layer\ndataset_id = uuid4()\n\npopulation_in_CA.add_dataset(\n {\"uuid\": dataset_id, \"label\": \"Population_in_CA\", \"data\": housing},\n auto_create_layers=False,\n)\n\npopulation_in_CA.add_layer(\n {\n \"id\": \"population_CA\",\n \"type\": \"cluster\",\n \"config\": {\n \"label\": \"population in CA\",\n \"data_id\": dataset_id,\n \"columns\": {\"lat\": \"latitude\", \"lng\": \"longitude\"},\n \"is_visible\": True,\n \"color_scale\": \"quantize\",\n \"color_field\": {\"name\": \"population\", \"type\": \"real\"},\n },\n }\n)\n\npopulation_in_CA.set_view_state(\n {\"longitude\": -119.417931, \"latitude\": 36.778259, \"zoom\": 5}\n)",
"_____no_output_____"
]
],
[
[
"### Distances from housing areas to largest cities",
"_____no_output_____"
],
[
"Next, we want to explore where the housing areas in our dataset are located in comparison to the largest cities in California. For example purposes, we'll take the five largest cities in California and compare our input data against these locations.",
"_____no_output_____"
]
],
[
[
"# Longitude-latitude pairs for large cities\ncities = {\n \"Los Angeles\": (-118.244, 34.052),\n \"San Diego\": (-117.165, 32.716),\n \"San Jose\": (-121.895, 37.339),\n \"San Francisco\": (-122.419, 37.775),\n \"Fresno\": (-119.772, 36.748),\n}",
"_____no_output_____"
]
],
[
[
"Next we need to find the closest city for each row in our data sample. First we'll define a couple functions to help compute the distance between cities and the city closest to a specific point. Then we'll apply these functions on our data.",
"_____no_output_____"
]
],
[
[
"def distance(lng1, lat1, lng2, lat2):\n \"\"\"Vectorized Haversine formula\n\n Computes distances between two sets of points.\n\n From: https://stackoverflow.com/a/51722117\n \"\"\"\n # approximate radius of earth in km\n R = 6371.009\n\n lat1 = lat1*np.pi/180.0\n lng1 = np.deg2rad(lng1)\n lat2 = np.deg2rad(lat2)\n lng2 = np.deg2rad(lng2)\n\n d = np.sin((lat2 - lat1)/2)**2 + np.cos(lat1)*np.cos(lat2) * np.sin((lng2 - lng1)/2)**2\n\n return 2 * R * np.arcsin(np.sqrt(d))",
"_____no_output_____"
],
[
"def closest_city(lng_array, lat_array, cities):\n \"\"\"Find the closest_city for each row in lng_array and lat_array input\n \"\"\"\n distances = []\n\n # Compute distance from each row of arrays to each of our city inputs\n for city_name, coord in cities.items():\n distances.append(distance(lng_array, lat_array, *coord))\n\n # Convert this list of numpy arrays into a 2D numpy array\n distances = np.array(distances)\n\n # Find the shortest distance value for each row\n shortest_distances = np.amin(distances, axis=0)\n\n # Find the _index_ of the shortest distance for each row. Then use this value to\n # lookup the longitude-latitude pair of the closest city\n city_index = np.argmin(distances, axis=0)\n\n # Create a 2D numpy array of location coordinates\n # Then use the indexes from above to perform a lookup against the order of cities as\n # input. (Note: this relies on the fact that in Python 3.6+ dictionaries are\n # ordered)\n input_coords = np.array(list(cities.values()))\n closest_city_coords = input_coords[city_index]\n\n # Return a 2D array with three columns:\n # - Distance to closest city\n # - Longitude of closest city\n # - Latitude of closest city\n return np.hstack((shortest_distances[:, np.newaxis], closest_city_coords))",
"_____no_output_____"
]
],
[
[
"Then use the `closest_city` function on our data to create three new columns:",
"_____no_output_____"
]
],
[
[
"housing[['closest_city_dist', 'closest_city_lng', 'closest_city_lat']] = closest_city(\n housing['longitude'], housing['latitude'], cities\n)",
"_____no_output_____"
]
],
[
[
"The map created in the next cell uses the new columns we computed above in relation to the largest cities in California:",
"_____no_output_____"
]
],
[
[
"distance_to_big_cities = UnfoldedMap()\ndistance_to_big_cities",
"_____no_output_____"
],
[
"dist_data_id = uuid4()\n\ndistance_to_big_cities.add_dataset(\n {\n \"uuid\": dist_data_id,\n \"label\": \"Distance to closest big city\",\n \"data\": housing,\n },\n auto_create_layers=False,\n)\n\ndistance_to_big_cities.add_layer(\n {\n \"id\": \"closest_distance\",\n \"type\": \"arc\",\n \"config\": {\n \"data_id\": dist_data_id,\n \"label\": \"distance to closest big city\",\n \"columns\": {\n \"lng0\": \"longitude\",\n \"lat0\": \"latitude\",\n \"lng1\": \"closest_city_lng\",\n \"lat1\": \"closest_city_lat\",\n },\n \"visConfig\": {\"opacity\": 0.8, \"thickness\": 0.3},\n \"is_visible\": True,\n },\n }\n)\n\ndistance_to_big_cities.set_view_state(\n {\"longitude\": -119.417931, \"latitude\": 36.778259, \"zoom\": 4.5}\n)",
"_____no_output_____"
]
],
[
[
"## Data Preprocessing",
"_____no_output_____"
],
[
"In this next section, we want to prepare our dataset to be used for training a TensorFlow model. First, we'll drop rows with null values, since they're quite rare in the dataset.",
"_____no_output_____"
]
],
[
[
"pct_null_rows = housing.isnull().any(axis=1).sum() / len(housing) * 100\nprint(f'{pct_null_rows:.1f}% of rows have null values')\n\nhousing = housing.dropna()",
"_____no_output_____"
]
],
[
[
"In the model we're training, we want to predict the median house value of an area. Thus we split the columns from our dataset `housing` into a dataset `y` with the column `median_house_value` and a dataset `X` with all other columns.",
"_____no_output_____"
]
],
[
[
"predicted_column = ['median_house_value']\nother_columns = housing.columns.difference(predicted_column)\n\nX = housing.loc[:, other_columns]\ny = housing.loc[:, predicted_column]",
"_____no_output_____"
]
],
[
[
"Most of the columns in `X` are numeric, but one is not. `ocean_proximity` is of type `object`, which here is a string.",
"_____no_output_____"
]
],
[
[
"X.dtypes",
"_____no_output_____"
]
],
[
[
"Looking closer, we see that `ocean_proximity` is a categorical string with only five values.",
"_____no_output_____"
]
],
[
[
"X['ocean_proximity'].value_counts()",
"_____no_output_____"
]
],
[
[
"In order to use this column in our numeric model, we call [`pandas.get_dummies`](https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html) to create five new boolean columns. Each of these columns contains a `1` if the value of `ocean_proximity` is equal to the value that's now the column name.",
"_____no_output_____"
]
],
[
[
"X = pd.get_dummies(\n data=X, columns=[\"ocean_proximity\"], prefix=[\"ocean_proximity\"], drop_first=True\n)",
"_____no_output_____"
]
],
[
[
"## Data Splitting",
"_____no_output_____"
],
[
"In line with standard machine learning practice, we split our dataset into training, validation and test sets. We first take out 20% of our full dataset to use for testing the model after training. Then of the remaining 80%, we take out 75% to use for training the model and 25% to use for validation.",
"_____no_output_____"
]
],
[
[
"# dividing training data into test, validation and train\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)\n\nX_train, X_val, y_train, y_val = train_test_split(\n X_train, y_train, test_size=0.25, random_state=1\n)\n\n# We save a copy of our test data to use after model prediction\nstart_values = X_test.copy(deep=True)",
"_____no_output_____"
]
],
[
[
"## Feature Scaling",
"_____no_output_____"
],
[
"We use standard scaling with mean and standard deviation from our training dataset to avoid data leakage.",
"_____no_output_____"
]
],
[
[
"# feature standardization\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_val = scaler.transform(X_val)\nX_test = scaler.transform(X_test)",
"_____no_output_____"
]
],
[
[
"## Price Prediction Model",
"_____no_output_____"
],
[
"Next we specify the parameters for the TensorFlow model:",
"_____no_output_____"
]
],
[
[
"# We use a Sequential model from Keras\n# https://keras.io/api/models/sequential/\nmodel = Sequential()\n\n# Each column from X is an input feature into our model.\nnumber_of_features = len(X.columns)\n\n# input Layer\nmodel.add(Dense(number_of_features, activation=\"relu\", input_dim=number_of_features))\n\n# hidden Layer\nmodel.add(Dense(512, activation=\"relu\"))\nmodel.add(Dense(512, activation=\"relu\"))\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dense(128, activation=\"relu\"))\nmodel.add(Dense(64, activation=\"relu\"))\nmodel.add(Dense(32, activation=\"relu\"))\n\n# output Layer\nmodel.add(Dense(1, activation=\"linear\"))",
"_____no_output_____"
],
[
"model.compile(loss=\"mse\", optimizer=\"adam\", metrics=[\"mse\", \"mae\"])\nmodel.summary()",
"_____no_output_____"
]
],
[
[
"### Training",
"_____no_output_____"
],
[
"Next we begin model training. Model training can take a long time; the higher the number of epochs, the better the model will be fit, but the longer training will take. Here we default to only 10 epochs because the focus of this notebook is integration with Unfolded Studio, not the machine learning itself.",
"_____no_output_____"
]
],
[
[
"EPOCHS = 10\n# Or uncomment the following line if you're happy to wait longer for a better model fit.\n# EPOCHS = 70",
"_____no_output_____"
],
[
"history = model.fit(\n X_train,\n y_train.to_numpy(),\n batch_size=10,\n epochs=EPOCHS,\n verbose=1,\n validation_data=(X_val, y_val),\n)",
"_____no_output_____"
]
],
[
[
"### Evaluation",
"_____no_output_____"
],
[
"Next we want to find out how well the model was trained:",
"_____no_output_____"
]
],
[
[
"# summarize history for loss\nloss_train = history.history[\"loss\"]\nloss_val = history.history[\"val_loss\"]\nepochs = range(1, EPOCHS + 1)\nplt.figure(figsize=(10, 8))\nplt.plot(epochs, loss_train, \"g\", label=\"Training loss\")\nplt.plot(epochs, loss_val, \"b\", label=\"Validation loss\")\nplt.title(\"Training and Validation loss\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"In the above chart we can see that the training loss and validation loss are quite close to each other.",
"_____no_output_____"
],
[
"Now we can use our trained model to predict home prices on the _test_ data, which was not used in the training process.",
"_____no_output_____"
]
],
[
[
"y_pred = model.predict(X_test)",
"_____no_output_____"
]
],
[
[
"We can see that loss function value on the test data is similar to the loss value on the training data",
"_____no_output_____"
]
],
[
[
"model.evaluate(X_test, y_test)",
"_____no_output_____"
]
],
[
[
"### Prediction",
"_____no_output_____"
],
[
"Let's now visualize our housing price predictions using Unfolded Studio. Here we create a dataframe with predicted values obtained from the model.",
"_____no_output_____"
]
],
[
[
"predict_data = start_values.loc[:, ['longitude', 'latitude']]\npredict_data[\"price\"] = y_pred",
"_____no_output_____"
]
],
[
[
"### Visualization",
"_____no_output_____"
],
[
"The map we create in the next cell depicts the prices we've predicted for houses in each census area in California.",
"_____no_output_____"
]
],
[
[
"housing_predict_prices = UnfoldedMap()\nhousing_predict_prices",
"_____no_output_____"
],
[
"price_data_id = uuid4()\n\nhousing_predict_prices.add_dataset(\n {\n \"uuid\": price_data_id,\n \"label\": \"Predict housing prices in CA\",\n \"data\": predict_data,\n },\n auto_create_layers=False,\n)\n\nhousing_predict_prices.add_layer(\n {\n \"id\": \"housing_prices\",\n \"type\": \"hexagon\",\n \"config\": {\n \"label\": \"housing prices\",\n \"data_id\": price_data_id,\n \"columns\": {\"lat\": \"latitude\", \"lng\": \"longitude\"},\n \"is_visible\": True,\n \"color_scale\": \"quantize\",\n \"color_field\": {\"name\": \"price\", \"type\": \"real\"},\n \"vis_config\": {\n \"colorRange\": {\n \"colors\": [\n \"#E6F598\",\n \"#ABDDA4\",\n \"#66C2A5\",\n \"#3288BD\",\n \"#5E4FA2\",\n \"#9E0142\",\n \"#D53E4F\",\n \"#F46D43\",\n \"#FDAE61\",\n \"#FEE08B\",\n ]\n }\n },\n },\n }\n)\n\nhousing_predict_prices.set_view_state(\n {\"longitude\": -119.417931, \"latitude\": 36.6, \"zoom\": 6}\n)",
"_____no_output_____"
]
],
[
[
"## Clustering Model",
"_____no_output_____"
],
[
"We'll now cluster the predicted data by price levels using the KMeans algorithm.",
"_____no_output_____"
]
],
[
[
"k = 5\nkm = KMeans(n_clusters=k, init=\"k-means++\")\nX = predict_data.loc[:, [\"latitude\", \"longitude\", \"price\"]]\n\n# Run clustering and add to prediction dataset dataset\npredict_data[\"cluster\"] = km.fit_predict(X)",
"_____no_output_____"
]
],
[
[
"### Visualization",
"_____no_output_____"
],
[
"Let's show the price clusters in a chart",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots()\nsns.scatterplot(\n x=\"latitude\",\n y=\"longitude\",\n data=predict_data,\n palette=sns.color_palette(\"bright\", k),\n hue=\"cluster\",\n size_order=[1, 0],\n ax=ax,\n).set_title(f\"Clustering (k={k})\")",
"_____no_output_____"
]
],
[
[
"The next map shows the same clusters in a geographic context. Here we can see that house prices are highest for areas close to the largest cities.",
"_____no_output_____"
]
],
[
[
"unfolded_map_prices = UnfoldedMap()\nunfolded_map_prices",
"_____no_output_____"
],
[
"prices_dataset_id = uuid4()\n\nunfolded_map_prices.add_dataset(\n {\"uuid\": prices_dataset_id, \"label\": \"Prices\", \"data\": predict_data},\n auto_create_layers=False,\n)\n\nunfolded_map_prices.add_layer(\n {\n \"id\": \"prices_CA\",\n \"type\": \"point\",\n \"config\": {\n \"data_id\": prices_dataset_id,\n \"label\": \"clustering of prices\",\n \"columns\": {\"lat\": \"latitude\", \"lng\": \"longitude\"},\n \"is_visible\": True,\n \"color_scale\": \"quantize\",\n \"color_field\": {\"name\": \"cluster\", \"type\": \"real\"},\n \"vis_config\": {\n \"colorRange\": {\n \"colors\": [\"#7FFFD4\", \"#8A2BE2\", \"#00008B\", \"#FF8C00\", \"#FF1493\"]\n }\n },\n },\n }\n)\n\nunfolded_map_prices.set_view_state(\n {\"longitude\": -119.417931, \"latitude\": 36.778259, \"zoom\": 4}\n)",
"_____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",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0ac3b580c3e83853a7e79029af92335289611c7 | 9,615 | ipynb | Jupyter Notebook | module3-cross-validation/LS_DS_223_assignment.ipynb | tbbcoach/DS-Unit-2-Kaggle-Challenge | e785482da6767acbd25cd1093599cbdd666d2615 | [
"MIT"
] | null | null | null | module3-cross-validation/LS_DS_223_assignment.ipynb | tbbcoach/DS-Unit-2-Kaggle-Challenge | e785482da6767acbd25cd1093599cbdd666d2615 | [
"MIT"
] | null | null | null | module3-cross-validation/LS_DS_223_assignment.ipynb | tbbcoach/DS-Unit-2-Kaggle-Challenge | e785482da6767acbd25cd1093599cbdd666d2615 | [
"MIT"
] | null | null | null | 28.446746 | 246 | 0.555798 | [
[
[
"Lambda School Data Science\n\n*Unit 2, Sprint 2, Module 3*\n\n---\n<p style=\"padding: 10px; border: 2px solid red;\">\n <b>Before you start:</b> Today is the day you should submit the dataset for your Unit 2 Build Week project. You can review the guidelines and make your submission in the Build Week course for your cohort on Canvas.</p>",
"_____no_output_____"
]
],
[
[
"%%capture\nimport sys\n\n# If you're on Colab:\nif 'google.colab' in sys.modules:\n DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/main/data/'\n !pip install category_encoders==2.*\n !pip install pandas-profiling==2.*\n\n# If you're working locally:\nelse:\n DATA_PATH = '../data/'",
"_____no_output_____"
]
],
[
[
"# Module Project: Hyperparameter Tuning\n\nThis sprint, the module projects will focus on creating and improving a model for the Tanazania Water Pump dataset. Your goal is to create a model to predict whether a water pump is functional, non-functional, or needs repair.\n\nDataset source: [DrivenData.org](https://www.drivendata.org/competitions/7/pump-it-up-data-mining-the-water-table/).\n\n## Directions\n\nThe tasks for this project are as follows:\n\n- **Task 1:** Use `wrangle` function to import training and test data.\n- **Task 2:** Split training data into feature matrix `X` and target vector `y`.\n- **Task 3:** Establish the baseline accuracy score for your dataset.\n- **Task 4:** Build `clf_dt`.\n- **Task 5:** Build `clf_rf`.\n- **Task 6:** Evaluate classifiers using k-fold cross-validation.\n- **Task 7:** Tune hyperparameters for best performing classifier.\n- **Task 8:** Print out best score and params for model.\n- **Task 9:** Create `submission.csv` and upload to Kaggle.\n\nYou should limit yourself to the following libraries for this project:\n\n- `category_encoders`\n- `matplotlib`\n- `pandas`\n- `pandas-profiling`\n- `sklearn`\n\n# I. Wrangle Data",
"_____no_output_____"
]
],
[
[
"def wrangle(fm_path, tv_path=None):\n if tv_path:\n df = pd.merge(pd.read_csv(fm_path, \n na_values=[0, -2.000000e-08]),\n pd.read_csv(tv_path)).set_index('id')\n else:\n df = pd.read_csv(fm_path, \n na_values=[0, -2.000000e-08],\n index_col='id')\n\n # Drop constant columns\n df.drop(columns=['recorded_by'], inplace=True)\n\n # Drop HCCCs\n cutoff = 100\n drop_cols = [col for col in df.select_dtypes('object').columns\n if df[col].nunique() > cutoff]\n df.drop(columns=drop_cols, inplace=True)\n\n # Drop duplicate columns\n dupe_cols = [col for col in df.head(15).T.duplicated().index\n if df.head(15).T.duplicated()[col]]\n df.drop(columns=dupe_cols, inplace=True) \n\n return df",
"_____no_output_____"
]
],
[
[
"**Task 1:** Using the above `wrangle` function to read `train_features.csv` and `train_labels.csv` into the DataFrame `df`, and `test_features.csv` into the DataFrame `X_test`.",
"_____no_output_____"
]
],
[
[
"df = ...\nX_test = ...",
"_____no_output_____"
]
],
[
[
"# II. Split Data\n\n**Task 2:** Split your DataFrame `df` into a feature matrix `X` and the target vector `y`. You want to predict `'status_group'`.\n\n**Note:** You won't need to do a train-test split because you'll use cross-validation instead.",
"_____no_output_____"
]
],
[
[
"X = ...\ny = ...",
"_____no_output_____"
]
],
[
[
"# III. Establish Baseline\n\n**Task 3:** Since this is a **classification** problem, you should establish a baseline accuracy score. Figure out what is the majority class in `y_train` and what percentage of your training observations it represents.",
"_____no_output_____"
]
],
[
[
"baseline_acc = ...\nprint('Baseline Accuracy Score:', baseline_acc)",
"_____no_output_____"
]
],
[
[
"# IV. Build Models\n\n**Task 4:** Build a `Pipeline` named `clf_dt`. Your `Pipeline` should include:\n\n- an `OrdinalEncoder` transformer for categorical features.\n- a `SimpleImputer` transformer fot missing values.\n- a `DecisionTreeClassifier` Predictor.\n\n**Note:** Do not train `clf_dt`. You'll do that in a subsequent task. ",
"_____no_output_____"
]
],
[
[
"clf_dt = ...",
"_____no_output_____"
]
],
[
[
"**Task 5:** Build a `Pipeline` named `clf_rf`. Your `Pipeline` should include:\n\n- an `OrdinalEncoder` transformer for categorical features.\n- a `SimpleImputer` transformer fot missing values.\n- a `RandomForestClassifier` predictor.\n\n**Note:** Do not train `clf_rf`. You'll do that in a subsequent task. ",
"_____no_output_____"
]
],
[
[
"clf_rf = ...",
"_____no_output_____"
]
],
[
[
"# V. Check Metrics\n\n**Task 6:** Evaluate the performance of both of your classifiers using k-fold cross-validation.",
"_____no_output_____"
]
],
[
[
"cv_scores_dt = ...\ncv_scores_rf = ...",
"_____no_output_____"
],
[
"print('CV scores DecisionTreeClassifier')\nprint(cv_scores_dt)\nprint('Mean CV accuracy score:', cv_scores_dt.mean())\nprint('STD CV accuracy score:', cv_scores_dt.std())",
"_____no_output_____"
],
[
"print('CV score RandomForestClassifier')\nprint(cv_scores_rf)\nprint('Mean CV accuracy score:', cv_scores_rf.mean())\nprint('STD CV accuracy score:', cv_scores_rf.std())",
"_____no_output_____"
]
],
[
[
"# VI. Tune Model\n\n**Task 7:** Choose the best performing of your two models and tune its hyperparameters using a `RandomizedSearchCV` named `model`. Make sure that you include cross-validation and that `n_iter` is set to at least `25`.\n\n**Note:** If you're not sure which hyperparameters to tune, check the notes from today's guided project and the `sklearn` documentation. ",
"_____no_output_____"
]
],
[
[
"model = ...",
"_____no_output_____"
]
],
[
[
"**Task 8:** Print out the best score and best params for `model`.",
"_____no_output_____"
]
],
[
[
"best_score = ...\nbest_params = ...\n\nprint('Best score for `model`:', best_score)\nprint('Best params for `model`:', best_params)",
"_____no_output_____"
]
],
[
[
"# Communicate Results",
"_____no_output_____"
],
[
"**Task 9:** Create a DataFrame `submission` whose index is the same as `X_test` and that has one column `'status_group'` with your predictions. Next, save this DataFrame as a CSV file and upload your submissions to our competition site. \n\n**Note:** Check the `sample_submission.csv` file on the competition website to make sure your submissions follows the same formatting. ",
"_____no_output_____"
]
],
[
[
"submission = ...",
"_____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",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
d0ac425b951fa656a24d703b8612fc67b638908b | 31,006 | ipynb | Jupyter Notebook | examples/vision/ipynb/semantic_image_clustering.ipynb | YassineYousfi/keras-io | a620cf365d0acb02a6cd73ca5b8e5414ebced08f | [
"Apache-2.0"
] | 2 | 2021-04-08T13:33:16.000Z | 2022-03-14T13:46:18.000Z | examples/vision/ipynb/semantic_image_clustering.ipynb | YassineYousfi/keras-io | a620cf365d0acb02a6cd73ca5b8e5414ebced08f | [
"Apache-2.0"
] | null | null | null | examples/vision/ipynb/semantic_image_clustering.ipynb | YassineYousfi/keras-io | a620cf365d0acb02a6cd73ca5b8e5414ebced08f | [
"Apache-2.0"
] | 1 | 2022-03-31T15:26:14.000Z | 2022-03-31T15:26:14.000Z | 30.608095 | 177 | 0.570406 | [
[
[
"# Semantic Image Clustering\n\n**Author:** [Khalid Salama](https://www.linkedin.com/in/khalid-salama-24403144/)<br>\n**Date created:** 2021/02/28<br>\n**Last modified:** 2021/02/28<br>\n**Description:** Semantic Clustering by Adopting Nearest neighbors (SCAN) algorithm.",
"_____no_output_____"
],
[
"## Introduction\n\nThis example demonstrates how to apply the [Semantic Clustering by Adopting Nearest neighbors\n(SCAN)](https://arxiv.org/abs/2005.12320) algorithm (Van Gansbeke et al., 2020) on the\n[CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html) dataset. The algorithm consists of\ntwo phases:\n\n1. Self-supervised visual representation learning of images, in which we use the\n[simCLR](https://arxiv.org/abs/2002.05709) technique.\n2. Clustering of the learned visual representation vectors to maximize the agreement\nbetween the cluster assignments of neighboring vectors.\n\nThe example requires [TensorFlow Addons](https://www.tensorflow.org/addons),\nwhich you can install using the following command:\n\n```python\npip install tensorflow-addons\n```",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"from collections import defaultdict\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm",
"_____no_output_____"
]
],
[
[
"## Prepare the data",
"_____no_output_____"
]
],
[
[
"num_classes = 10\ninput_shape = (32, 32, 3)\n\n(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\nx_data = np.concatenate([x_train, x_test])\ny_data = np.concatenate([y_train, y_test])\n\nprint(\"x_data shape:\", x_data.shape, \"- y_data shape:\", y_data.shape)\n\nclasses = [\n \"airplane\",\n \"automobile\",\n \"bird\",\n \"cat\",\n \"deer\",\n \"dog\",\n \"frog\",\n \"horse\",\n \"ship\",\n \"truck\",\n]",
"_____no_output_____"
]
],
[
[
"## Define hyperparameters",
"_____no_output_____"
]
],
[
[
"target_size = 32 # Resize the input images.\nrepresentation_dim = 512 # The dimensions of the features vector.\nprojection_units = 128 # The projection head of the representation learner.\nnum_clusters = 20 # Number of clusters.\nk_neighbours = 5 # Number of neighbours to consider during cluster learning.\ntune_encoder_during_clustering = False # Freeze the encoder in the cluster learning.",
"_____no_output_____"
]
],
[
[
"## Implement data preprocessing\n\nThe data preprocessing step resizes the input images to the desired `target_size` and applies\nfeature-wise normalization. Note that, when using `keras.applications.ResNet50V2` as the\nvisual encoder, resizing the images into 255 x 255 inputs would lead to more accurate results\nbut require a longer time to train.",
"_____no_output_____"
]
],
[
[
"data_preprocessing = keras.Sequential(\n [\n layers.experimental.preprocessing.Resizing(target_size, target_size),\n layers.experimental.preprocessing.Normalization(),\n ]\n)\n# Compute the mean and the variance from the data for normalization.\ndata_preprocessing.layers[-1].adapt(x_data)",
"_____no_output_____"
]
],
[
[
"## Data augmentation\n\nUnlike simCLR, which randomly picks a single data augmentation function to apply to an input\nimage, we apply a set of data augmentation functions randomly to the input image.\n(You can experiment with other image augmentation techniques by following the [data augmentation tutorial](https://www.tensorflow.org/tutorials/images/data_augmentation).)",
"_____no_output_____"
]
],
[
[
"data_augmentation = keras.Sequential(\n [\n layers.experimental.preprocessing.RandomTranslation(\n height_factor=(-0.2, 0.2), width_factor=(-0.2, 0.2), fill_mode=\"nearest\"\n ),\n layers.experimental.preprocessing.RandomFlip(mode=\"horizontal\"),\n layers.experimental.preprocessing.RandomRotation(\n factor=0.15, fill_mode=\"nearest\"\n ),\n layers.experimental.preprocessing.RandomZoom(\n height_factor=(-0.3, 0.1), width_factor=(-0.3, 0.1), fill_mode=\"nearest\"\n )\n ]\n)",
"_____no_output_____"
]
],
[
[
"Display a random image",
"_____no_output_____"
]
],
[
[
"image_idx = np.random.choice(range(x_data.shape[0]))\nimage = x_data[image_idx]\nimage_class = classes[y_data[image_idx][0]]\nplt.figure(figsize=(3, 3))\nplt.imshow(x_data[image_idx].astype(\"uint8\"))\nplt.title(image_class)\n_ = plt.axis(\"off\")",
"_____no_output_____"
]
],
[
[
"Display a sample of augmented versions of the image",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10, 10))\nfor i in range(9):\n augmented_images = data_augmentation(np.array([image]))\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(augmented_images[0].numpy().astype(\"uint8\"))\n plt.axis(\"off\")",
"_____no_output_____"
]
],
[
[
"## Self-supervised representation learning",
"_____no_output_____"
],
[
"### Implement the vision encoder",
"_____no_output_____"
]
],
[
[
"\ndef create_encoder(representation_dim):\n encoder = keras.Sequential(\n [\n keras.applications.ResNet50V2(\n include_top=False, weights=None, pooling=\"avg\"\n ),\n layers.Dense(representation_dim),\n ]\n )\n return encoder\n",
"_____no_output_____"
]
],
[
[
"### Implement the unsupervised contrastive loss",
"_____no_output_____"
]
],
[
[
"\nclass RepresentationLearner(keras.Model):\n def __init__(\n self,\n encoder,\n projection_units,\n num_augmentations,\n temperature=1.0,\n dropout_rate=0.1,\n l2_normalize=False,\n **kwargs\n ):\n super(RepresentationLearner, self).__init__(**kwargs)\n self.encoder = encoder\n # Create projection head.\n self.projector = keras.Sequential(\n [\n layers.Dropout(dropout_rate),\n layers.Dense(units=projection_units, use_bias=False),\n layers.BatchNormalization(),\n layers.ReLU(),\n ]\n )\n self.num_augmentations = num_augmentations\n self.temperature = temperature\n self.l2_normalize = l2_normalize\n self.loss_tracker = keras.metrics.Mean(name=\"loss\")\n\n @property\n def metrics(self):\n return [self.loss_tracker]\n\n def compute_contrastive_loss(self, feature_vectors, batch_size):\n num_augmentations = tf.shape(feature_vectors)[0] // batch_size\n if self.l2_normalize:\n feature_vectors = tf.math.l2_normalize(feature_vectors, -1)\n # The logits shape is [num_augmentations * batch_size, num_augmentations * batch_size].\n logits = (\n tf.linalg.matmul(feature_vectors, feature_vectors, transpose_b=True)\n / self.temperature\n )\n # Apply log-max trick for numerical stability.\n logits_max = tf.math.reduce_max(logits, axis=1)\n logits = logits - logits_max\n # The shape of targets is [num_augmentations * batch_size, num_augmentations * batch_size].\n # targets is a matrix consits of num_augmentations submatrices of shape [batch_size * batch_size].\n # Each [batch_size * batch_size] submatrix is an identity matrix (diagonal entries are ones).\n targets = tf.tile(tf.eye(batch_size), [num_augmentations, num_augmentations])\n # Compute cross entropy loss\n return keras.losses.categorical_crossentropy(\n y_true=targets, y_pred=logits, from_logits=True\n )\n\n def call(self, inputs):\n # Preprocess the input images.\n preprocessed = data_preprocessing(inputs)\n # Create augmented versions of the images.\n augmented = []\n for _ in range(self.num_augmentations):\n augmented.append(data_augmentation(preprocessed))\n augmented = layers.Concatenate(axis=0)(augmented)\n # Generate embedding representations of the images.\n features = self.encoder(augmented)\n # Apply projection head.\n return self.projector(features)\n\n def train_step(self, inputs):\n batch_size = tf.shape(inputs)[0]\n # Run the forward pass and compute the contrastive loss\n with tf.GradientTape() as tape:\n feature_vectors = self(inputs, training=True)\n loss = self.compute_contrastive_loss(feature_vectors, batch_size)\n # Compute gradients\n trainable_vars = self.trainable_variables\n gradients = tape.gradient(loss, trainable_vars)\n # Update weights\n self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n # Update loss tracker metric\n self.loss_tracker.update_state(loss)\n # Return a dict mapping metric names to current value\n return {m.name: m.result() for m in self.metrics}\n\n def test_step(self, inputs):\n batch_size = tf.shape(inputs)[0]\n feature_vectors = self(inputs, training=False)\n loss = self.compute_contrastive_loss(feature_vectors, batch_size)\n self.loss_tracker.update_state(loss)\n return {\"loss\": self.loss_tracker.result()}\n",
"_____no_output_____"
]
],
[
[
"### Train the model",
"_____no_output_____"
]
],
[
[
"# Create vision encoder.\nencoder = create_encoder(representation_dim)\n# Create representation learner.\nrepresentation_learner = RepresentationLearner(\n encoder, projection_units, num_augmentations=2, temperature=0.1\n)\n# Create a a Cosine decay learning rate scheduler.\nlr_scheduler = keras.experimental.CosineDecay(\n initial_learning_rate=0.001, decay_steps=500, alpha=0.1\n)\n# Compile the model.\nrepresentation_learner.compile(\n optimizer=tfa.optimizers.AdamW(learning_rate=lr_scheduler, weight_decay=0.0001),\n)\n# Fit the model.\nhistory = representation_learner.fit(\n x=x_data,\n batch_size=512,\n epochs=50, # for better results, increase the number of epochs to 500.\n)\n",
"_____no_output_____"
]
],
[
[
"Plot training loss",
"_____no_output_____"
]
],
[
[
"plt.plot(history.history[\"loss\"])\nplt.ylabel(\"loss\")\nplt.xlabel(\"epoch\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Compute the nearest neighbors",
"_____no_output_____"
],
[
"### Generate the embeddings for the images",
"_____no_output_____"
]
],
[
[
"batch_size = 500\n# Get the feature vector representations of the images.\nfeature_vectors = encoder.predict(x_data, batch_size=batch_size, verbose=1)\n# Normalize the feature vectores.\nfeature_vectors = tf.math.l2_normalize(feature_vectors, -1)",
"_____no_output_____"
]
],
[
[
"### Find the *k* nearest neighbours for each embedding",
"_____no_output_____"
]
],
[
[
"neighbours = []\nnum_batches = feature_vectors.shape[0] // batch_size\nfor batch_idx in tqdm(range(num_batches)):\n start_idx = batch_idx * batch_size\n end_idx = start_idx + batch_size\n current_batch = feature_vectors[start_idx:end_idx]\n # Compute the dot similarity.\n similarities = tf.linalg.matmul(current_batch, feature_vectors, transpose_b=True)\n # Get the indices of most similar vectors.\n _, indices = tf.math.top_k(similarities, k=k_neighbours + 1, sorted=True)\n # Add the indices to the neighbours.\n neighbours.append(indices[..., 1:])\n\nneighbours = np.reshape(np.array(neighbours), (-1, k_neighbours))",
"_____no_output_____"
]
],
[
[
"Let's display some neighbors on each row",
"_____no_output_____"
]
],
[
[
"nrows = 4\nncols = k_neighbours + 1\n\nplt.figure(figsize=(12, 12))\nposition = 1\nfor _ in range(nrows):\n anchor_idx = np.random.choice(range(x_data.shape[0]))\n neighbour_indicies = neighbours[anchor_idx]\n indices = [anchor_idx] + neighbour_indicies.tolist()\n for j in range(ncols):\n plt.subplot(nrows, ncols, position)\n plt.imshow(x_data[indices[j]].astype(\"uint8\"))\n plt.title(classes[y_data[indices[j]][0]])\n plt.axis(\"off\")\n position += 1",
"_____no_output_____"
]
],
[
[
"You notice that images on each row are visually similar, and belong to similar classes.",
"_____no_output_____"
],
[
"## Semantic clustering with nearest neighbours",
"_____no_output_____"
],
[
"### Implement clustering consistency loss\n\nThis loss tries to make sure that neighbours have the same clustering assignments.",
"_____no_output_____"
]
],
[
[
"\nclass ClustersConsistencyLoss(keras.losses.Loss):\n def __init__(self):\n super(ClustersConsistencyLoss, self).__init__()\n\n def __call__(self, target, similarity, sample_weight=None):\n # Set targets to be ones.\n target = tf.ones_like(similarity)\n # Compute cross entropy loss.\n loss = keras.losses.binary_crossentropy(\n y_true=target, y_pred=similarity, from_logits=True\n )\n return tf.math.reduce_mean(loss)\n",
"_____no_output_____"
]
],
[
[
"### Implement the clusters entropy loss\n\nThis loss tries to make sure that cluster distribution is roughly uniformed, to avoid\nassigning most of the instances to one cluster.",
"_____no_output_____"
]
],
[
[
"\nclass ClustersEntropyLoss(keras.losses.Loss):\n def __init__(self, entropy_loss_weight=1.0):\n super(ClustersEntropyLoss, self).__init__()\n self.entropy_loss_weight = entropy_loss_weight\n\n def __call__(self, target, cluster_probabilities, sample_weight=None):\n # Ideal entropy = log(num_clusters).\n num_clusters = tf.cast(tf.shape(cluster_probabilities)[-1], tf.dtypes.float32)\n target = tf.math.log(num_clusters)\n # Compute the overall clusters distribution.\n cluster_probabilities = tf.math.reduce_mean(cluster_probabilities, axis=0)\n # Replacing zero probabilities - if any - with a very small value.\n cluster_probabilities = tf.clip_by_value(\n cluster_probabilities, clip_value_min=1e-8, clip_value_max=1.0\n )\n # Compute the entropy over the clusters.\n entropy = -tf.math.reduce_sum(\n cluster_probabilities * tf.math.log(cluster_probabilities)\n )\n # Compute the difference between the target and the actual.\n loss = target - entropy\n return loss\n",
"_____no_output_____"
]
],
[
[
"### Implement clustering model\n\nThis model takes a raw image as an input, generated its feature vector using the trained\nencoder, and produces a probability distribution of the clusters given the feature vector\nas the cluster assignments.",
"_____no_output_____"
]
],
[
[
"\ndef create_clustering_model(encoder, num_clusters, name=None):\n inputs = keras.Input(shape=input_shape)\n # Preprocess the input images.\n preprocessed = data_preprocessing(inputs)\n # Apply data augmentation to the images.\n augmented = data_augmentation(preprocessed)\n # Generate embedding representations of the images.\n features = encoder(augmented)\n # Assign the images to clusters.\n outputs = layers.Dense(units=num_clusters, activation=\"softmax\")(features)\n # Create the model.\n model = keras.Model(inputs=inputs, outputs=outputs, name=name)\n return model\n",
"_____no_output_____"
]
],
[
[
"### Implement clustering learner\n\nThis model receives the input `anchor` image and its `neighbours`, produces the clusters\nassignments for them using the `clustering_model`, and produces two outputs:\n1. `similarity`: the similarity between the cluster assignments of the `anchor` image and\nits `neighbours`. This output is fed to the `ClustersConsistencyLoss`.\n2. `anchor_clustering`: cluster assignments of the `anchor` images. This is fed to the `ClustersEntropyLoss`.",
"_____no_output_____"
]
],
[
[
"\ndef create_clustering_learner(clustering_model):\n anchor = keras.Input(shape=input_shape, name=\"anchors\")\n neighbours = keras.Input(\n shape=tuple([k_neighbours]) + input_shape, name=\"neighbours\"\n )\n # Changes neighbours shape to [batch_size * k_neighbours, width, height, channels]\n neighbours_reshaped = tf.reshape(neighbours, shape=tuple([-1]) + input_shape)\n # anchor_clustering shape: [batch_size, num_clusters]\n anchor_clustering = clustering_model(anchor)\n # neighbours_clustering shape: [batch_size * k_neighbours, num_clusters]\n neighbours_clustering = clustering_model(neighbours_reshaped)\n # Convert neighbours_clustering shape to [batch_size, k_neighbours, num_clusters]\n neighbours_clustering = tf.reshape(\n neighbours_clustering,\n shape=(-1, k_neighbours, tf.shape(neighbours_clustering)[-1]),\n )\n # similarity shape: [batch_size, 1, k_neighbours]\n similarity = tf.linalg.einsum(\n \"bij,bkj->bik\", tf.expand_dims(anchor_clustering, axis=1), neighbours_clustering\n )\n # similarity shape: [batch_size, k_neighbours]\n similarity = layers.Lambda(lambda x: tf.squeeze(x, axis=1), name=\"similarity\")(\n similarity\n )\n # Create the model.\n model = keras.Model(\n inputs=[anchor, neighbours],\n outputs=[similarity, anchor_clustering],\n name=\"clustering_learner\",\n )\n return model\n",
"_____no_output_____"
]
],
[
[
"### Train model",
"_____no_output_____"
]
],
[
[
"# If tune_encoder_during_clustering is set to False,\n# then freeze the encoder weights.\nfor layer in encoder.layers:\n layer.trainable = tune_encoder_during_clustering\n# Create the clustering model and learner.\nclustering_model = create_clustering_model(encoder, num_clusters, name=\"clustering\")\nclustering_learner = create_clustering_learner(clustering_model)\n# Instantiate the model losses.\nlosses = [ClustersConsistencyLoss(), ClustersEntropyLoss(entropy_loss_weight=5)]\n# Create the model inputs and labels.\ninputs = {\"anchors\": x_data, \"neighbours\": tf.gather(x_data, neighbours)}\nlabels = tf.ones(shape=(x_data.shape[0]))\n# Compile the model.\nclustering_learner.compile(\n optimizer=tfa.optimizers.AdamW(learning_rate=0.0005, weight_decay=0.0001),\n loss=losses,\n)\n\n# Begin training the model.\nclustering_learner.fit(x=inputs, y=labels, batch_size=512, epochs=50)",
"_____no_output_____"
]
],
[
[
"Plot training loss",
"_____no_output_____"
]
],
[
[
"plt.plot(history.history[\"loss\"])\nplt.ylabel(\"loss\")\nplt.xlabel(\"epoch\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Cluster analysis",
"_____no_output_____"
],
[
"### Assign images to clusters",
"_____no_output_____"
]
],
[
[
"# Get the cluster probability distribution of the input images.\nclustering_probs = clustering_model.predict(x_data, batch_size=batch_size, verbose=1)\n# Get the cluster of the highest probability.\ncluster_assignments = tf.math.argmax(clustering_probs, axis=-1).numpy()\n# Store the clustering confidence.\n# Images with the highest clustering confidence are considered the 'prototypes'\n# of the clusters.\ncluster_confidence = tf.math.reduce_max(clustering_probs, axis=-1).numpy()",
"_____no_output_____"
]
],
[
[
"Let's compute the cluster sizes",
"_____no_output_____"
]
],
[
[
"clusters = defaultdict(list)\nfor idx, c in enumerate(cluster_assignments):\n clusters[c].append((idx, cluster_confidence[idx]))\n\nfor c in range(num_clusters):\n print(\"cluster\", c, \":\", len(clusters[c]))",
"_____no_output_____"
]
],
[
[
"Notice that the clusters have roughly balanced sizes.",
"_____no_output_____"
],
[
"### Visualize cluster images\n\nDisplay the *prototypes*—instances with the highest clustering confidence—of each cluster:",
"_____no_output_____"
]
],
[
[
"num_images = 8\nplt.figure(figsize=(15, 15))\nposition = 1\nfor c in range(num_clusters):\n cluster_instances = sorted(clusters[c], key=lambda kv: kv[1], reverse=True)\n\n for j in range(num_images):\n image_idx = cluster_instances[j][0]\n plt.subplot(num_clusters, num_images, position)\n plt.imshow(x_data[image_idx].astype(\"uint8\"))\n plt.title(classes[y_data[image_idx][0]])\n plt.axis(\"off\")\n position += 1",
"_____no_output_____"
]
],
[
[
"### Compute clustering accuracy\n\nFirst, we assign a label for each cluster based on the majority label of its images.\nThen, we compute the accuracy of each cluster by dividing the number of image with the\nmajority label by the size of the cluster.",
"_____no_output_____"
]
],
[
[
"cluster_label_counts = dict()\n\nfor c in range(num_clusters):\n cluster_label_counts[c] = [0] * num_classes\n instances = clusters[c]\n for i, _ in instances:\n cluster_label_counts[c][y_data[i][0]] += 1\n\n cluster_label_idx = np.argmax(cluster_label_counts[c])\n correct_count = np.max(cluster_label_counts[c])\n cluster_size = len(clusters[c])\n accuracy = (\n np.round((correct_count / cluster_size) * 100, 2) if cluster_size > 0 else 0\n )\n cluster_label = classes[cluster_label_idx]\n print(\"cluster\", c, \"label is:\", cluster_label, \" - accuracy:\", accuracy, \"%\")",
"_____no_output_____"
]
],
[
[
"## Conclusion\n\nTo improve the accuracy results, you can: 1) increase the number\nof epochs in the representation learning and the clustering phases; 2)\nallow the encoder weights to be tuned during the clustering phase; and 3) perform a final\nfine-tuning step through self-labeling, as described in the [original SCAN paper](https://arxiv.org/abs/2005.12320).\nNote that unsupervised image clustering techniques are not expected to outperform the accuracy\nof supervised image classification techniques, rather showing that they can learn the semantics\nof the images and group them into clusters that are similar to their original classes.",
"_____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"
] | [
[
"markdown",
"markdown",
"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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d0ac4e3357d0aa6faee2ed9144fa610e355a3713 | 2,013 | ipynb | Jupyter Notebook | Chapter_5/Section_5.2.2.2.ipynb | godfanmiao/ML-Kaggle-Github-2022 | 19c9fd0fe5db432f43f5844e170f952eaaaeaefd | [
"BSD-3-Clause"
] | 8 | 2021-10-15T12:27:01.000Z | 2022-02-21T13:50:04.000Z | Chapter_5/.ipynb_checkpoints/Section_5.2.2.2-checkpoint.ipynb | godfanmiao/ML-Kaggle-Github-2022 | 19c9fd0fe5db432f43f5844e170f952eaaaeaefd | [
"BSD-3-Clause"
] | null | null | null | Chapter_5/.ipynb_checkpoints/Section_5.2.2.2-checkpoint.ipynb | godfanmiao/ML-Kaggle-Github-2022 | 19c9fd0fe5db432f43f5844e170f952eaaaeaefd | [
"BSD-3-Clause"
] | 1 | 2022-02-04T07:25:34.000Z | 2022-02-04T07:25:34.000Z | 19.543689 | 100 | 0.531545 | [
[
[
"from sklearn.datasets import load_iris\n\n\n#读取iris数据集的特征与类别标签。\nfeatures, labels = load_iris(return_X_y=True)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler\n\n\n#初始化数据标准化处理器。\nss = StandardScaler()\n\n#标准化数据特征。\nfeatures = ss.fit_transform(features)",
"_____no_output_____"
],
[
"from sklearn.cluster import DBSCAN\n\n\n#初始化DBSCAN聚类算法。\ndbscan = DBSCAN()\n\n#利用iris数据特征进行聚类。\nclusters = dbscan.fit_predict(features)",
"_____no_output_____"
],
[
"from sklearn.metrics import adjusted_rand_score\n\n\nprint('Scikit-learn的DBSCAN聚类算法在iris数据集上的调整兰德系数为:%.4f。' %adjusted_rand_score(labels, clusters))",
"Scikit-learn的DBSCAN聚类算法在iris数据集上的调整兰德系数为:0.4421。\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
d0ac60b376c8b468e126ca4033f5e6a064861b50 | 135,353 | ipynb | Jupyter Notebook | model_13.ipynb | Zxavy/Genre-Classifier | f3acf2df2fd70c31436539df6a7f7b15c61ad1f5 | [
"Apache-2.0"
] | 5 | 2022-02-19T16:11:29.000Z | 2022-02-19T17:58:59.000Z | model_13.ipynb | Zxavy/Genre-Classifier | f3acf2df2fd70c31436539df6a7f7b15c61ad1f5 | [
"Apache-2.0"
] | null | null | null | model_13.ipynb | Zxavy/Genre-Classifier | f3acf2df2fd70c31436539df6a7f7b15c61ad1f5 | [
"Apache-2.0"
] | null | null | null | 130.272377 | 29,532 | 0.788509 | [
[
[
"import json\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport tensorflow.keras as keras\n\nimport matplotlib.pyplot as plt\nimport random\n\nimport librosa\nimport math",
"_____no_output_____"
],
[
"# path to json\ndata_path = \"C:\\\\Users\\\\Saad\\\\Desktop\\\\Project\\\\MGC\\\\Data\\\\data.json\"",
"_____no_output_____"
],
[
"def load_data(data_path):\n\n with open(data_path, \"r\") as f:\n data = json.load(f)\n\n # convert lists to numpy arrays\n X = np.array(data[\"mfcc\"])\n y = np.array(data[\"labels\"])\n\n print(\"No Problems, go ahead!\")\n\n return X, y",
"_____no_output_____"
],
[
"# load data\nX, y = load_data(data_path)",
"No Problems, go ahead!\n"
],
[
"X.shape",
"_____no_output_____"
]
],
[
[
"## ANN",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)",
"_____no_output_____"
],
[
"model = keras.Sequential([\n\n keras.layers.Flatten(input_shape=(X.shape[1], X.shape[2])),\n\n keras.layers.Dense(512, activation='relu'),\n\n keras.layers.Dense(256, activation='relu'),\n\n keras.layers.Dense(64, activation='relu'),\n\n keras.layers.Dense(10, activation='softmax')\n])",
"_____no_output_____"
],
[
"optimiser = keras.optimizers.Adam(learning_rate=0.0001)\nmodel.compile(optimizer=optimiser,\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nflatten (Flatten) (None, 1690) 0 \n_________________________________________________________________\ndense (Dense) (None, 512) 865792 \n_________________________________________________________________\ndense_1 (Dense) (None, 256) 131328 \n_________________________________________________________________\ndense_2 (Dense) (None, 64) 16448 \n_________________________________________________________________\ndense_3 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 1,014,218\nTrainable params: 1,014,218\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"history = model.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=50)",
"Epoch 1/50\n197/197 [==============================] - 1s 4ms/step - loss: 6.0868 - accuracy: 0.2879 - val_loss: 2.2508 - val_accuracy: 0.2616\nEpoch 2/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.9406 - accuracy: 0.3287 - val_loss: 2.0467 - val_accuracy: 0.3286\nEpoch 3/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.7567 - accuracy: 0.3837 - val_loss: 2.0365 - val_accuracy: 0.3483\nEpoch 4/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.6810 - accuracy: 0.4061 - val_loss: 2.1394 - val_accuracy: 0.3646\nEpoch 5/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.5510 - accuracy: 0.4578 - val_loss: 1.9740 - val_accuracy: 0.3735\nEpoch 6/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.4834 - accuracy: 0.4821 - val_loss: 1.9310 - val_accuracy: 0.3757\nEpoch 7/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.4108 - accuracy: 0.5074 - val_loss: 1.9275 - val_accuracy: 0.4261\nEpoch 8/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.2916 - accuracy: 0.5380 - val_loss: 1.9129 - val_accuracy: 0.4094\nEpoch 9/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.2439 - accuracy: 0.5576 - val_loss: 1.9249 - val_accuracy: 0.4450\nEpoch 10/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.1849 - accuracy: 0.5752 - val_loss: 1.9343 - val_accuracy: 0.4524\nEpoch 11/50\n197/197 [==============================] - 1s 3ms/step - loss: 1.1042 - accuracy: 0.6028 - val_loss: 1.8760 - val_accuracy: 0.4605\nEpoch 12/50\n197/197 [==============================] - 1s 4ms/step - loss: 1.0318 - accuracy: 0.6235 - val_loss: 1.9340 - val_accuracy: 0.4765\nEpoch 13/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.9560 - accuracy: 0.6497 - val_loss: 2.2505 - val_accuracy: 0.4513\nEpoch 14/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.9467 - accuracy: 0.6636 - val_loss: 1.8911 - val_accuracy: 0.4961\nEpoch 15/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.8856 - accuracy: 0.6727 - val_loss: 1.8135 - val_accuracy: 0.5209\nEpoch 16/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.8239 - accuracy: 0.6968 - val_loss: 1.7558 - val_accuracy: 0.5139\nEpoch 17/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.7574 - accuracy: 0.7207 - val_loss: 1.8310 - val_accuracy: 0.5224\nEpoch 18/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.7216 - accuracy: 0.7396 - val_loss: 1.9420 - val_accuracy: 0.5465\nEpoch 19/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.6708 - accuracy: 0.7588 - val_loss: 1.7573 - val_accuracy: 0.5320\nEpoch 20/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.6624 - accuracy: 0.7561 - val_loss: 1.7515 - val_accuracy: 0.5561\nEpoch 21/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.5981 - accuracy: 0.7788 - val_loss: 1.9278 - val_accuracy: 0.5558\nEpoch 22/50\n197/197 [==============================] - 1s 3ms/step - loss: 0.5785 - accuracy: 0.7869 - val_loss: 1.8951 - val_accuracy: 0.5609\nEpoch 23/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.5071 - accuracy: 0.8110 - val_loss: 1.7521 - val_accuracy: 0.5765\nEpoch 24/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.4696 - accuracy: 0.8282 - val_loss: 1.9835 - val_accuracy: 0.5687\nEpoch 25/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.4591 - accuracy: 0.8271 - val_loss: 1.9197 - val_accuracy: 0.5635\nEpoch 26/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.4199 - accuracy: 0.8406 - val_loss: 1.9325 - val_accuracy: 0.5728\nEpoch 27/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.3934 - accuracy: 0.8531 - val_loss: 1.9075 - val_accuracy: 0.5817\nEpoch 28/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.3787 - accuracy: 0.8663 - val_loss: 1.8717 - val_accuracy: 0.5906\nEpoch 29/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.3408 - accuracy: 0.8714 - val_loss: 1.9752 - val_accuracy: 0.5847\nEpoch 30/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.3299 - accuracy: 0.8787 - val_loss: 2.1009 - val_accuracy: 0.5980\nEpoch 31/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.3022 - accuracy: 0.8842 - val_loss: 2.2740 - val_accuracy: 0.5810\nEpoch 32/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.3214 - accuracy: 0.8830 - val_loss: 2.1291 - val_accuracy: 0.5824\nEpoch 33/50\n197/197 [==============================] - 1s 3ms/step - loss: 0.2893 - accuracy: 0.8966 - val_loss: 1.9740 - val_accuracy: 0.5869\nEpoch 34/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.2832 - accuracy: 0.8973 - val_loss: 2.2070 - val_accuracy: 0.5817\nEpoch 35/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.2816 - accuracy: 0.9006 - val_loss: 1.9782 - val_accuracy: 0.5936\nEpoch 36/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.2655 - accuracy: 0.9057 - val_loss: 2.1255 - val_accuracy: 0.5913\nEpoch 37/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.2271 - accuracy: 0.9169 - val_loss: 2.3635 - val_accuracy: 0.5880\nEpoch 38/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.2469 - accuracy: 0.9136 - val_loss: 2.1701 - val_accuracy: 0.6036\nEpoch 39/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1874 - accuracy: 0.9312 - val_loss: 2.3085 - val_accuracy: 0.5921\nEpoch 40/50\n197/197 [==============================] - 1s 3ms/step - loss: 0.2457 - accuracy: 0.9171 - val_loss: 2.1375 - val_accuracy: 0.5965\nEpoch 41/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.2033 - accuracy: 0.9265 - val_loss: 2.1285 - val_accuracy: 0.6095\nEpoch 42/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1925 - accuracy: 0.9363 - val_loss: 2.3574 - val_accuracy: 0.6010\nEpoch 43/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1881 - accuracy: 0.9338 - val_loss: 2.4684 - val_accuracy: 0.5784\nEpoch 44/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1799 - accuracy: 0.9349 - val_loss: 2.5516 - val_accuracy: 0.5961\nEpoch 45/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1781 - accuracy: 0.9377 - val_loss: 2.4310 - val_accuracy: 0.6021\nEpoch 46/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1528 - accuracy: 0.9457 - val_loss: 2.3302 - val_accuracy: 0.5798\nEpoch 47/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1800 - accuracy: 0.9370 - val_loss: 2.2150 - val_accuracy: 0.6132\nEpoch 48/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1435 - accuracy: 0.9498 - val_loss: 2.3277 - val_accuracy: 0.6047\nEpoch 49/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1618 - accuracy: 0.9436 - val_loss: 2.4277 - val_accuracy: 0.5980\nEpoch 50/50\n197/197 [==============================] - 1s 4ms/step - loss: 0.1109 - accuracy: 0.9609 - val_loss: 2.5663 - val_accuracy: 0.6150\n"
],
[
"def plot_history(history):\n\n fig, axs = plt.subplots(2)\n\n axs[0].plot(history.history[\"accuracy\"], label=\"train accuracy\")\n axs[0].plot(history.history[\"val_accuracy\"], label=\"test accuracy\")\n axs[0].set_ylabel(\"Accuracy\")\n axs[0].legend(loc=\"lower right\")\n axs[0].set_title(\"Accuracy eval\")\n\n axs[1].plot(history.history[\"loss\"], label=\"train error\")\n axs[1].plot(history.history[\"val_loss\"], label=\"test error\")\n axs[1].set_ylabel(\"Error\")\n axs[1].set_xlabel(\"Epoch\")\n axs[1].legend(loc=\"upper right\")\n axs[1].set_title(\"Error eval\")\n \n plt.show()",
"_____no_output_____"
],
[
"plot_history(history)",
"_____no_output_____"
],
[
"model_regularized = keras.Sequential([\n\n keras.layers.Flatten(input_shape=(X.shape[1], X.shape[2])),\n\n keras.layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)),\n keras.layers.Dropout(0.3),\n\n keras.layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)),\n keras.layers.Dropout(0.3),\n\n keras.layers.Dense(64, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)),\n keras.layers.Dropout(0.3),\n\n keras.layers.Dense(10, activation='softmax')\n])",
"_____no_output_____"
],
[
"optimiser = keras.optimizers.Adam(learning_rate=0.0001)\nmodel_regularized.compile(optimizer=optimiser,\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"history = model_regularized.fit(X_train, y_train, validation_data=(X_test, y_test), batch_size=32, epochs=100)",
"Epoch 1/100\n197/197 [==============================] - 1s 7ms/step - loss: 22.0044 - accuracy: 0.1853 - val_loss: 3.6561 - val_accuracy: 0.2223\nEpoch 2/100\n197/197 [==============================] - 1s 7ms/step - loss: 7.0021 - accuracy: 0.1804 - val_loss: 3.4144 - val_accuracy: 0.1660\nEpoch 3/100\n197/197 [==============================] - 1s 6ms/step - loss: 4.7614 - accuracy: 0.1729 - val_loss: 3.4492 - val_accuracy: 0.1589\nEpoch 4/100\n197/197 [==============================] - 1s 6ms/step - loss: 4.0688 - accuracy: 0.1723 - val_loss: 3.4631 - val_accuracy: 0.1423\nEpoch 5/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.7957 - accuracy: 0.1677 - val_loss: 3.4569 - val_accuracy: 0.1412\nEpoch 6/100\n197/197 [==============================] - 1s 7ms/step - loss: 3.6752 - accuracy: 0.1607 - val_loss: 3.4388 - val_accuracy: 0.1482\nEpoch 7/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.6192 - accuracy: 0.1660 - val_loss: 3.4178 - val_accuracy: 0.1597\nEpoch 8/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.5087 - accuracy: 0.1771 - val_loss: 3.3935 - val_accuracy: 0.1660\nEpoch 9/100\n197/197 [==============================] - 1s 7ms/step - loss: 3.4627 - accuracy: 0.1815 - val_loss: 3.3450 - val_accuracy: 0.1934\nEpoch 10/100\n197/197 [==============================] - 1s 7ms/step - loss: 3.4193 - accuracy: 0.1922 - val_loss: 3.3323 - val_accuracy: 0.1960\nEpoch 11/100\n197/197 [==============================] - 1s 5ms/step - loss: 3.3883 - accuracy: 0.1934 - val_loss: 3.2894 - val_accuracy: 0.2101\nEpoch 12/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.3587 - accuracy: 0.1987 - val_loss: 3.2775 - val_accuracy: 0.2123\nEpoch 13/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.3242 - accuracy: 0.2028 - val_loss: 3.2913 - val_accuracy: 0.2034\nEpoch 14/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.2878 - accuracy: 0.2072 - val_loss: 3.2419 - val_accuracy: 0.2234\nEpoch 15/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.3048 - accuracy: 0.2057 - val_loss: 3.2439 - val_accuracy: 0.2156\nEpoch 16/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.2706 - accuracy: 0.2168 - val_loss: 3.2084 - val_accuracy: 0.2230\nEpoch 17/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.2508 - accuracy: 0.2174 - val_loss: 3.2206 - val_accuracy: 0.2145\nEpoch 18/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.2239 - accuracy: 0.2287 - val_loss: 3.1684 - val_accuracy: 0.2249\nEpoch 19/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.1935 - accuracy: 0.2385 - val_loss: 3.1111 - val_accuracy: 0.2456\nEpoch 20/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.1668 - accuracy: 0.2473 - val_loss: 3.1001 - val_accuracy: 0.2460\nEpoch 21/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.1384 - accuracy: 0.2488 - val_loss: 3.0899 - val_accuracy: 0.2501\nEpoch 22/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.1083 - accuracy: 0.2563 - val_loss: 3.1202 - val_accuracy: 0.2197\nEpoch 23/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.1014 - accuracy: 0.2546 - val_loss: 3.0679 - val_accuracy: 0.2471\nEpoch 24/100\n197/197 [==============================] - 1s 6ms/step - loss: 3.0854 - accuracy: 0.2620 - val_loss: 3.0636 - val_accuracy: 0.2375\nEpoch 25/100\n197/197 [==============================] - 1s 5ms/step - loss: 3.0554 - accuracy: 0.2655 - val_loss: 2.9918 - val_accuracy: 0.2701\nEpoch 26/100\n197/197 [==============================] - 1s 5ms/step - loss: 3.0225 - accuracy: 0.2708 - val_loss: 2.9797 - val_accuracy: 0.2590\nEpoch 27/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.9825 - accuracy: 0.2789 - val_loss: 2.9713 - val_accuracy: 0.2634\nEpoch 28/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.9811 - accuracy: 0.2739 - val_loss: 2.9522 - val_accuracy: 0.2675\nEpoch 29/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.9587 - accuracy: 0.2785 - val_loss: 2.9196 - val_accuracy: 0.2871\nEpoch 30/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.9293 - accuracy: 0.2892 - val_loss: 2.9085 - val_accuracy: 0.2916\nEpoch 31/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.9110 - accuracy: 0.2903 - val_loss: 2.8793 - val_accuracy: 0.2901\nEpoch 32/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.8684 - accuracy: 0.2965 - val_loss: 2.8745 - val_accuracy: 0.2864\nEpoch 33/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.8594 - accuracy: 0.2930 - val_loss: 2.8246 - val_accuracy: 0.3031\nEpoch 34/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.8197 - accuracy: 0.2995 - val_loss: 2.8287 - val_accuracy: 0.2912\nEpoch 35/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.7980 - accuracy: 0.3020 - val_loss: 2.8059 - val_accuracy: 0.3005\nEpoch 36/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.7659 - accuracy: 0.3081 - val_loss: 2.7837 - val_accuracy: 0.2794\nEpoch 37/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.7539 - accuracy: 0.3086 - val_loss: 2.7450 - val_accuracy: 0.3012\nEpoch 38/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.7150 - accuracy: 0.3143 - val_loss: 2.7581 - val_accuracy: 0.3183\nEpoch 39/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.7045 - accuracy: 0.3221 - val_loss: 2.7168 - val_accuracy: 0.3116\nEpoch 40/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.6543 - accuracy: 0.3262 - val_loss: 2.6796 - val_accuracy: 0.3072\nEpoch 41/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.6459 - accuracy: 0.3271 - val_loss: 2.6658 - val_accuracy: 0.3109\nEpoch 42/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.6022 - accuracy: 0.3346 - val_loss: 2.6284 - val_accuracy: 0.3216\nEpoch 43/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.5713 - accuracy: 0.3389 - val_loss: 2.5801 - val_accuracy: 0.3279\nEpoch 44/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.5483 - accuracy: 0.3478 - val_loss: 2.6189 - val_accuracy: 0.3286\nEpoch 45/100\n197/197 [==============================] - 1s 5ms/step - loss: 2.5155 - accuracy: 0.3506 - val_loss: 2.5651 - val_accuracy: 0.3531\nEpoch 46/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.4946 - accuracy: 0.3510 - val_loss: 2.5399 - val_accuracy: 0.3527\nEpoch 47/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.4656 - accuracy: 0.3711 - val_loss: 2.4988 - val_accuracy: 0.3727\nEpoch 48/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.4192 - accuracy: 0.3770 - val_loss: 2.4492 - val_accuracy: 0.3724\nEpoch 49/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.3744 - accuracy: 0.3726 - val_loss: 2.3245 - val_accuracy: 0.3950\nEpoch 50/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.3001 - accuracy: 0.4000 - val_loss: 2.3167 - val_accuracy: 0.3764\nEpoch 51/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.2671 - accuracy: 0.4042 - val_loss: 2.2757 - val_accuracy: 0.4064\nEpoch 52/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.2284 - accuracy: 0.4029 - val_loss: 2.2213 - val_accuracy: 0.3979\nEpoch 53/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.1716 - accuracy: 0.4145 - val_loss: 2.2326 - val_accuracy: 0.4224\nEpoch 54/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.1436 - accuracy: 0.4219 - val_loss: 2.1840 - val_accuracy: 0.4305\nEpoch 55/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.1081 - accuracy: 0.4374 - val_loss: 2.1743 - val_accuracy: 0.4168\nEpoch 56/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.0768 - accuracy: 0.4393 - val_loss: 2.1359 - val_accuracy: 0.4457\nEpoch 57/100\n197/197 [==============================] - 1s 6ms/step - loss: 2.0363 - accuracy: 0.4555 - val_loss: 2.1497 - val_accuracy: 0.4476\n"
],
[
"plot_history(history)",
"_____no_output_____"
]
],
[
[
"## CNN",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)\nX_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size=0.2)\n\nX_train = X_train[..., np.newaxis]\nX_validation = X_validation[..., np.newaxis]\nX_test = X_test[..., np.newaxis]",
"_____no_output_____"
],
[
"X_train.shape",
"_____no_output_____"
],
[
"input_shape = (X_train.shape[1], X_train.shape[2], 1)",
"_____no_output_____"
],
[
"model_cnn = keras.Sequential()\n\nmodel_cnn.add(keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))\nmodel_cnn.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))\nmodel_cnn.add(keras.layers.BatchNormalization())\n\nmodel_cnn.add(keras.layers.Conv2D(32, (3, 3), activation='relu'))\nmodel_cnn.add(keras.layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same'))\nmodel_cnn.add(keras.layers.BatchNormalization())\n\nmodel_cnn.add(keras.layers.Conv2D(32, (2, 2), activation='relu'))\nmodel_cnn.add(keras.layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same'))\nmodel_cnn.add(keras.layers.BatchNormalization())\n\nmodel_cnn.add(keras.layers.Flatten())\nmodel_cnn.add(keras.layers.Dense(64, activation='relu'))\nmodel_cnn.add(keras.layers.Dropout(0.3))\n\nmodel_cnn.add(keras.layers.Dense(10, activation='softmax'))",
"_____no_output_____"
],
[
"optimiser = keras.optimizers.Adam(learning_rate=0.0001)\nmodel_cnn.compile(optimizer=optimiser,\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"model_cnn.summary()",
"Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 128, 11, 32) 320 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 64, 6, 32) 0 \n_________________________________________________________________\nbatch_normalization (BatchNo (None, 64, 6, 32) 128 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 62, 4, 32) 9248 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 31, 2, 32) 0 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 31, 2, 32) 128 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 30, 1, 32) 4128 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 15, 1, 32) 0 \n_________________________________________________________________\nbatch_normalization_2 (Batch (None, 15, 1, 32) 128 \n_________________________________________________________________\nflatten_2 (Flatten) (None, 480) 0 \n_________________________________________________________________\ndense_8 (Dense) (None, 64) 30784 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 64) 0 \n_________________________________________________________________\ndense_9 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 45,514\nTrainable params: 45,322\nNon-trainable params: 192\n_________________________________________________________________\n"
],
[
"history = model_cnn.fit(X_train, y_train, validation_data=(X_validation, y_validation), batch_size=32, epochs=50)",
"Epoch 1/50\n169/169 [==============================] - 3s 20ms/step - loss: 2.2365 - accuracy: 0.2752 - val_loss: 1.8050 - val_accuracy: 0.3815\nEpoch 2/50\n169/169 [==============================] - 3s 19ms/step - loss: 1.7316 - accuracy: 0.4030 - val_loss: 1.5235 - val_accuracy: 0.4607\nEpoch 3/50\n169/169 [==============================] - 3s 19ms/step - loss: 1.5584 - accuracy: 0.4515 - val_loss: 1.3930 - val_accuracy: 0.4985\nEpoch 4/50\n169/169 [==============================] - 3s 20ms/step - loss: 1.4477 - accuracy: 0.4918 - val_loss: 1.3228 - val_accuracy: 0.5126\nEpoch 5/50\n169/169 [==============================] - 4s 21ms/step - loss: 1.3591 - accuracy: 0.5114 - val_loss: 1.2467 - val_accuracy: 0.5385\nEpoch 6/50\n169/169 [==============================] - 3s 21ms/step - loss: 1.2864 - accuracy: 0.5470 - val_loss: 1.2160 - val_accuracy: 0.5504\nEpoch 7/50\n169/169 [==============================] - 4s 21ms/step - loss: 1.2384 - accuracy: 0.5542 - val_loss: 1.1497 - val_accuracy: 0.5763\nEpoch 8/50\n169/169 [==============================] - 4s 23ms/step - loss: 1.1752 - accuracy: 0.5857 - val_loss: 1.1013 - val_accuracy: 0.5874\nEpoch 9/50\n169/169 [==============================] - 4s 21ms/step - loss: 1.1345 - accuracy: 0.5976 - val_loss: 1.0703 - val_accuracy: 0.5985\nEpoch 10/50\n169/169 [==============================] - 3s 20ms/step - loss: 1.0941 - accuracy: 0.6111 - val_loss: 1.0583 - val_accuracy: 0.6052\nEpoch 11/50\n169/169 [==============================] - 3s 19ms/step - loss: 1.0605 - accuracy: 0.6276 - val_loss: 1.0024 - val_accuracy: 0.6415\nEpoch 12/50\n169/169 [==============================] - 3s 19ms/step - loss: 1.0127 - accuracy: 0.6378 - val_loss: 1.0200 - val_accuracy: 0.6281\nEpoch 13/50\n169/169 [==============================] - 3s 19ms/step - loss: 0.9713 - accuracy: 0.6515 - val_loss: 0.9654 - val_accuracy: 0.6526\nEpoch 14/50\n169/169 [==============================] - 3s 19ms/step - loss: 0.9599 - accuracy: 0.6604 - val_loss: 0.9494 - val_accuracy: 0.6622\nEpoch 15/50\n169/169 [==============================] - 3s 19ms/step - loss: 0.9342 - accuracy: 0.6648 - val_loss: 0.9354 - val_accuracy: 0.6704\nEpoch 16/50\n169/169 [==============================] - 3s 19ms/step - loss: 0.8864 - accuracy: 0.6837 - val_loss: 0.8952 - val_accuracy: 0.6837\nEpoch 17/50\n169/169 [==============================] - 3s 19ms/step - loss: 0.8787 - accuracy: 0.6893 - val_loss: 0.8923 - val_accuracy: 0.6822\nEpoch 18/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.8464 - accuracy: 0.7048 - val_loss: 0.8925 - val_accuracy: 0.6852\nEpoch 19/50\n169/169 [==============================] - 3s 19ms/step - loss: 0.8244 - accuracy: 0.7048 - val_loss: 0.8786 - val_accuracy: 0.7037\nEpoch 20/50\n169/169 [==============================] - 3s 19ms/step - loss: 0.8053 - accuracy: 0.7095 - val_loss: 0.8665 - val_accuracy: 0.7022\nEpoch 21/50\n169/169 [==============================] - 4s 22ms/step - loss: 0.7816 - accuracy: 0.7224 - val_loss: 0.8493 - val_accuracy: 0.6948\nEpoch 22/50\n169/169 [==============================] - 4s 21ms/step - loss: 0.7507 - accuracy: 0.7376 - val_loss: 0.8264 - val_accuracy: 0.7104\nEpoch 23/50\n169/169 [==============================] - 4s 21ms/step - loss: 0.7568 - accuracy: 0.7386 - val_loss: 0.8354 - val_accuracy: 0.7104\nEpoch 24/50\n169/169 [==============================] - 4s 21ms/step - loss: 0.7295 - accuracy: 0.7478 - val_loss: 0.8194 - val_accuracy: 0.7281\nEpoch 25/50\n169/169 [==============================] - 3s 21ms/step - loss: 0.7080 - accuracy: 0.7541 - val_loss: 0.8293 - val_accuracy: 0.7111\nEpoch 26/50\n169/169 [==============================] - 3s 21ms/step - loss: 0.6962 - accuracy: 0.7595 - val_loss: 0.8196 - val_accuracy: 0.7170\nEpoch 27/50\n169/169 [==============================] - 4s 22ms/step - loss: 0.6876 - accuracy: 0.7515 - val_loss: 0.7996 - val_accuracy: 0.7193\nEpoch 28/50\n169/169 [==============================] - 4s 22ms/step - loss: 0.6798 - accuracy: 0.7623 - val_loss: 0.7824 - val_accuracy: 0.7178\nEpoch 29/50\n169/169 [==============================] - 4s 23ms/step - loss: 0.6542 - accuracy: 0.7662 - val_loss: 0.7843 - val_accuracy: 0.7200\nEpoch 30/50\n169/169 [==============================] - 4s 25ms/step - loss: 0.6356 - accuracy: 0.7752 - val_loss: 0.7985 - val_accuracy: 0.7215\nEpoch 31/50\n169/169 [==============================] - 4s 23ms/step - loss: 0.6197 - accuracy: 0.7843 - val_loss: 0.7848 - val_accuracy: 0.7356\nEpoch 32/50\n169/169 [==============================] - 4s 23ms/step - loss: 0.6193 - accuracy: 0.7788 - val_loss: 0.7910 - val_accuracy: 0.7304\nEpoch 33/50\n169/169 [==============================] - 4s 21ms/step - loss: 0.6033 - accuracy: 0.7927 - val_loss: 0.7710 - val_accuracy: 0.7281\nEpoch 34/50\n169/169 [==============================] - 4s 21ms/step - loss: 0.5820 - accuracy: 0.7956 - val_loss: 0.7593 - val_accuracy: 0.7430\nEpoch 35/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.5820 - accuracy: 0.7984 - val_loss: 0.7687 - val_accuracy: 0.7385\nEpoch 36/50\n169/169 [==============================] - 4s 21ms/step - loss: 0.5703 - accuracy: 0.8042 - val_loss: 0.7440 - val_accuracy: 0.7519\nEpoch 37/50\n169/169 [==============================] - 3s 21ms/step - loss: 0.5631 - accuracy: 0.8014 - val_loss: 0.7740 - val_accuracy: 0.7319\nEpoch 38/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.5511 - accuracy: 0.8040 - val_loss: 0.7668 - val_accuracy: 0.7407\nEpoch 39/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.5439 - accuracy: 0.8060 - val_loss: 0.7415 - val_accuracy: 0.7526\nEpoch 40/50\n169/169 [==============================] - 3s 21ms/step - loss: 0.5361 - accuracy: 0.8088 - val_loss: 0.7469 - val_accuracy: 0.7489\nEpoch 41/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.5149 - accuracy: 0.8262 - val_loss: 0.7308 - val_accuracy: 0.7459\nEpoch 42/50\n169/169 [==============================] - 4s 22ms/step - loss: 0.5009 - accuracy: 0.8223 - val_loss: 0.7481 - val_accuracy: 0.7519\nEpoch 43/50\n169/169 [==============================] - 4s 23ms/step - loss: 0.4888 - accuracy: 0.8229 - val_loss: 0.7697 - val_accuracy: 0.7430\nEpoch 44/50\n169/169 [==============================] - 4s 22ms/step - loss: 0.4911 - accuracy: 0.8293 - val_loss: 0.7271 - val_accuracy: 0.7563\nEpoch 45/50\n169/169 [==============================] - 3s 21ms/step - loss: 0.4830 - accuracy: 0.8340 - val_loss: 0.7656 - val_accuracy: 0.7400\nEpoch 46/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.4560 - accuracy: 0.8477 - val_loss: 0.7840 - val_accuracy: 0.7341\nEpoch 47/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.4477 - accuracy: 0.8473 - val_loss: 0.7536 - val_accuracy: 0.7444\nEpoch 48/50\n169/169 [==============================] - 3s 21ms/step - loss: 0.4456 - accuracy: 0.8449 - val_loss: 0.7467 - val_accuracy: 0.7415\nEpoch 49/50\n169/169 [==============================] - 3s 20ms/step - loss: 0.4349 - accuracy: 0.8579 - val_loss: 0.7379 - val_accuracy: 0.7548\nEpoch 50/50\n169/169 [==============================] - 4s 21ms/step - loss: 0.4545 - accuracy: 0.8379 - val_loss: 0.7636 - val_accuracy: 0.7430\n"
],
[
"plot_history(history)",
"_____no_output_____"
],
[
"test_loss, test_acc = model_cnn.evaluate(X_test, y_test, verbose=1)\nprint('\\nTest accuracy:', test_acc)",
"71/71 [==============================] - 0s 4ms/step - loss: 0.7577 - accuracy: 0.7390\n\nTest accuracy: 0.7389951348304749\n"
],
[
"model_cnn.save(\"Genre_Classifier.h5\")",
"_____no_output_____"
],
[
"for n in range(10):\n i = random.randint(0,len(X_test))\n \n # pick a sample to predict from the test set\n X_to_predict = X_test[i]\n y_to_predict = y_test[i]\n print(\"\\nReal Genre :\", y_to_predict)\n \n X_to_predict = X_to_predict[np.newaxis, ...]\n prediction = model_cnn.predict(X_to_predict)\n \n # get index with max value\n predicted_index = np.argmax(prediction, axis=1)\n print(\"Predicted Genre:\", int(predicted_index))",
"\nReal Genre : 7\nPredicted Genre: 7\n\nReal Genre : 1\nPredicted Genre: 1\n\nReal Genre : 8\nPredicted Genre: 3\n\nReal Genre : 1\nPredicted Genre: 1\n\nReal Genre : 6\nPredicted Genre: 6\n\nReal Genre : 1\nPredicted Genre: 1\n\nReal Genre : 0\nPredicted Genre: 0\n\nReal Genre : 5\nPredicted Genre: 5\n\nReal Genre : 1\nPredicted Genre: 1\n\nReal Genre : 2\nPredicted Genre: 2\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"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"
]
] |
d0ac6ab047b60de773a0e93e9184593667dd36de | 10,225 | ipynb | Jupyter Notebook | intro_to_python/3_Advanced_Data_Structures_Incomplete.ipynb | siqitoday/mban22_software_tools | de51d2859cb9c321cedbae47b539f11731242932 | [
"MIT"
] | 2 | 2021-08-24T14:02:31.000Z | 2021-09-01T04:24:15.000Z | intro_to_python/3_Advanced_Data_Structures_Incomplete.ipynb | siqitoday/mban22_software_tools | de51d2859cb9c321cedbae47b539f11731242932 | [
"MIT"
] | null | null | null | intro_to_python/3_Advanced_Data_Structures_Incomplete.ipynb | siqitoday/mban22_software_tools | de51d2859cb9c321cedbae47b539f11731242932 | [
"MIT"
] | 6 | 2019-12-03T22:35:28.000Z | 2021-03-04T00:28:02.000Z | 24.345238 | 220 | 0.551491 | [
[
[
"# Notebook 3 - Advanced Data Structures\n\nSo far, we have seen numbers, strings, and lists. In this notebook, we will learn three more data structures, which allow us to organize data. The data structures are `tuple`, `set`, and `dict` (dictionary). ",
"_____no_output_____"
],
[
"## Tuples\nA tuple is like a list, but is immutable, meaning that it cannot be modified.",
"_____no_output_____"
]
],
[
[
"tup = (1,'a',[1,2])\ntup",
"_____no_output_____"
],
[
"print(tup[1])\nprint(tup[2][0])",
"_____no_output_____"
],
[
"tup[1] = 3",
"_____no_output_____"
],
[
"# We can turn a list into a tuple, and visa versa\nprint(list(tup))\nprint(tuple(list(tup)))",
"_____no_output_____"
],
[
"# We can have a tuple with a single item\nsingle_tup = (1,)\nprint(single_tup)",
"_____no_output_____"
]
],
[
[
"## Sets\nWe consider the `set` data structure. The `set` is thought of similarly to how it is defined in mathematics: it is unordered, and has no duplicates. Let's contrast with the data structures we have seen thus far.\n\n* A `list` is an ordered, mutable collection of items\n* A `tuple` is an ordered, immutable collection of items\n* A `str` is an ordered, immutable collection of characters\n* A `set` is an unordered, mutable collection of distinct items",
"_____no_output_____"
]
],
[
[
"some_numbers = [0,2,1,1,2]\nmy_set = set(some_numbers) # create a set out of the numbers\n\nprint(my_set)",
"_____no_output_____"
]
],
[
[
"We observed that, by turning a list into a set, we automatically removed the duplicates. This idea will work on any collection.",
"_____no_output_____"
]
],
[
[
"my_string = 'aabbccda'\nmy_set = set(my_string)\n\nprint(my_set)",
"_____no_output_____"
],
[
"'a' in my_set\n'a' in my_set and 'e' not in my_set",
"_____no_output_____"
]
],
[
[
"Suppose we wanted to remove `'a'` from `my_set`, but don't know the syntax for it. \n\nFortunately, there is built-in help features.\n\n* Typing `my_set.<tab>` lists different member functions of `my_set`.\n* The function `help(my_set)` also lists different functions, along with explanations.",
"_____no_output_____"
]
],
[
[
"my_set.",
"_____no_output_____"
],
[
"help(my_set)",
"_____no_output_____"
]
],
[
[
"## Dictionaries",
"_____no_output_____"
],
[
"These are *very* useful!\n\nGiven $n$ values, a list `l` store $n$ values, which can be accessed by `l[i]` for each $i = 0,\\ldots,n-1$. \n\nA *dictionary* is a data structure that allows us to access values by general types of keys. This is useful in designing efficient algorithms and writing simple code.",
"_____no_output_____"
]
],
[
[
"# Create a dictionary of produce and their prices\nproduct_prices = {} \n\n# Add produce and prices to the dictionary\nproduct_prices['apple'] = 2\nproduct_prices['banana'] = 2\nproduct_prices['carrot'] = 3\n\n# View the dictionary\nprint(product_prices)\n",
"_____no_output_____"
]
],
[
[
"Dictionaries behave in ways similar to a list.",
"_____no_output_____"
]
],
[
[
"# Print the price of a banana\nprint(product_prices['banana'])\n\n# Check if 'banana' is a key in the dictionary.\nprint('banana' in product_prices)\n\n# Check if `donut` is a key in the dictonary.\nprint('donut' in product_prices)",
"_____no_output_____"
]
],
[
[
"Dictionaries allow us to access their keys and values directly.",
"_____no_output_____"
]
],
[
[
"# View the keys of the dictionary\nproduce = product_prices.keys()\nprint(produce)",
"_____no_output_____"
],
[
"# The keys are a list\ntype(produce)",
"_____no_output_____"
],
[
"# Using list comprehensions, we can find all produce that\n# have 6 characters in their name.\nprint([name for name in product_prices if len(name) == 6])\n\n# Python knows that we want to iterate through the keys of product_prices.\n# Equivalently, we can use the following syntax.\nprint([name for name in produce if len(name) == 6])",
"_____no_output_____"
],
[
"# We can find all produce that have a price of 2 dollars.\nprint([name for name in product_prices if product_prices[name] == 2])",
"_____no_output_____"
],
[
"# Similarly, we can access the values of the dictionary\nprint(product_prices.values())",
"_____no_output_____"
]
],
[
[
"Dictionaries don't have to be indexed by strings. It can be indexed by numbers.",
"_____no_output_____"
]
],
[
[
"my_dict = {1: 5, 'abc': '123'}\nprint(my_dict)",
"_____no_output_____"
]
],
[
[
"Dictionaries can be created in several ways. We have seen two so far.\n\n* Creating an empty dictionary with `{}`, then adding (key,value) pairs, one at a time.\n\n* Creating an dictionary at once as `{key1:val1, key2:val2, ...}`\n\nThere are more ways to create dictionaries, that are convenient in different situations. We will see one more way.\n\n* Dictionary comprehension\n* Combining lists",
"_____no_output_____"
]
],
[
[
"# Create a dictionary, with a key of i^2 and a value of i for each i in 0,...,1000\nsquared_numbers = {i**2: i for i in range(10)}\n\nprint(81 in squared_numbers)\nprint(squared_numbers[81])",
"_____no_output_____"
],
[
"names = ['alice','bob','cindy']\nsports = [['Archery', 'Badmitton'], ['Archery', 'Curling'], ['Badmitton', 'Diving']]\n\n# Create a dictionary mapping names to sports\nprint({names[i]:sports[i] for i in range(len(names))})",
"_____no_output_____"
],
[
"# Alternative approach\nprint(dict(zip(names,sports)))",
"_____no_output_____"
]
],
[
[
"## Exercise\n### Part 1\nObtain the list of common English words from the 'english_words.txt' file. \n\n### Part 2\nCreate a dictionary called `length_to_words` that maps an integer `i` to the list of common English words that have that have `i` letters.\n\nExample: If the words were `['and','if','the']`, then the dictionary would be `{2: ['if'], 3: ['and','the']}`.\n\nQuestion: Why is a dictionary the correct choice for this data structure?\n\n### Part 3\nCreate a dictionary named `length_to_num_words` that maps each length in `length_to_words` to the number of words with that length.\n\nExample: If the words were `['and','if','the']`, then the dictionary would be `{2: 1, 3: 2}`.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
d0ac740f75c215b3aa5ae368eac0dd521bfd7e23 | 662,973 | ipynb | Jupyter Notebook | MODEST_Museum_Dataset_Statistics.ipynb | shan18/MODEST-Museum-Dataset | c6c40428fc6e3664e2061a048c3e5b066d6b1000 | [
"MIT"
] | 1 | 2020-06-16T19:54:10.000Z | 2020-06-16T19:54:10.000Z | MODEST_Museum_Dataset_Statistics.ipynb | shan18/MODEST-Museum-Dataset | c6c40428fc6e3664e2061a048c3e5b066d6b1000 | [
"MIT"
] | null | null | null | MODEST_Museum_Dataset_Statistics.ipynb | shan18/MODEST-Museum-Dataset | c6c40428fc6e3664e2061a048c3e5b066d6b1000 | [
"MIT"
] | 1 | 2020-05-11T10:53:16.000Z | 2020-05-11T10:53:16.000Z | 315.401047 | 307,194 | 0.911619 | [
[
[
"### Mount Google Drive (Works only on Google Colab)",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/gdrive')",
"Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/gdrive\n"
]
],
[
[
"# Import Packages\n\n",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np\nimport pandas as pd\n\nfrom zipfile import ZipFile\nfrom PIL import Image\nfrom tqdm.autonotebook import tqdm\nfrom IPython.display import display\nfrom IPython.display import Image as Dimage",
"/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:7: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n import sys\n"
]
],
[
[
"# Define Paths\n\nDefine paths of all the required directories",
"_____no_output_____"
]
],
[
[
"# Root path of the dataset\nROOT_DATA_DIR = '/content/gdrive/My Drive/modest_museum_dataset.zip'",
"_____no_output_____"
]
],
[
[
"# Data Visualization\n\nLet's visualize some of the foreground and background images",
"_____no_output_____"
]
],
[
[
"def make_grid(images_list, height=140, margin=8, aspect_ratio=False):\n \"\"\"Combine Images to form a grid.\n\n Args:\n images (list): List of PIL images to display in grid.\n height (int): Height to which the image will be resized.\n margin (int): Amount of padding between the images in grid.\n aspect_ratio (bool, optional): Create grid while maintaining\n the aspect ratio of the images. (default: False)\n \n Returns:\n Image grid.\n \"\"\"\n\n # Create grid template\n widths = []\n if aspect_ratio:\n for image in images_list:\n # Find width according to aspect ratio\n h_percent = height / image.size[1]\n widths.append(int(image.size[0] * h_percent))\n else:\n widths = [height] * len(images_list)\n \n start = 0\n background = Image.new(\n 'RGBA', (sum(widths) + (len(images_list) - 1) * margin, height)\n )\n \n # Add images to grid\n for idx, image in enumerate(images_list):\n image = image.resize((widths[idx], height))\n offset = (start, 0)\n start += (widths[idx] + margin)\n background.paste(image, offset)\n \n return background",
"_____no_output_____"
]
],
[
[
"# Data Statistics\n\nLet's calculate mean, standard deviation and total number of images for each type of image category.\n\n## Mean\n\nMean is calculated using the formula\n\n<center>\n <img src=\"https://www.gstatic.com/education/formulas/images_long_sheet/en/mean.svg\" height=\"50\">\n</center>\n\nwhere, `sum of the terms` represents a pixel value and `number of terms` represents the total number of pixels across all the images.\n\n## Standard Deviation\n\nStandard Deviation is calculated using the formula\n\n<center>\n <img src=\"https://www.gstatic.com/education/formulas/images_long_sheet/en/population_standard_deviation.svg\" height=\"50\">\n</center>\n\nwhere, `x` represents a pixel value, `u` represents the mean calculated above and `N` represents the total number of pixels across all the images.",
"_____no_output_____"
]
],
[
[
"def statistics(filename, channel_num, filetype):\n \"\"\"Calculates data statistics\n\n Args:\n path (str): Path of the directory for which statistics is to be calculated\n\n Returns:\n Mean, standard deviation, number of images\n \"\"\"\n\n counter = 0\n mean = []\n std = []\n images = [] # store PIL instance of the image\n\n pixel_num = 0 # store all pixel number in the dataset\n channel_sum = np.zeros(channel_num) # store channel-wise sum\n channel_sum_squared = np.zeros(channel_num) # store squared channel-wise sum\n\n with ZipFile(filename) as archive:\n img_list = [\n x for x in archive.infolist()\n if x.filename.split('/')[1] == filetype and x.filename.split('/')[2].endswith('.jpeg')\n ]\n for entry in tqdm(img_list):\n with archive.open(entry) as file:\n img = Image.open(file)\n if len(images) < 5:\n images.append(img)\n im = np.array(img)\n im = im / 255.0\n pixel_num += (im.size / channel_num)\n channel_sum += np.sum(im, axis=(0, 1))\n channel_sum_squared += np.sum(np.square(im), axis=(0, 1))\n counter += 1\n bgr_mean = channel_sum / pixel_num\n bgr_std = np.sqrt(channel_sum_squared / pixel_num - np.square(bgr_mean))\n \n # change the format from bgr to rgb\n mean = [round(x, 5) for x in list(bgr_mean)[::-1]]\n std = [round(x, 5) for x in list(bgr_std)[::-1]]\n\n return mean, std, counter, im.shape, images",
"_____no_output_____"
]
],
[
[
"# Statistics for Background images",
"_____no_output_____"
]
],
[
[
"# Background\nprint('Calculating statistics for Backgrounds...')\nbg_mean, bg_std, bg_counter, bg_dim, bg_images = statistics(ROOT_DATA_DIR, 3, 'bg')",
"Calculating statistics for Backgrounds...\n"
],
[
"# Display\nprint('Background Images:')\nmake_grid(bg_images, margin=30)",
"Background Images:\n"
],
[
"print('Data Statistics for Background images')\n\nstats = {\n 'Statistics': ['Mean', 'Standard deviation', 'Number of images', 'Dimension'],\n 'Data': [bg_mean, bg_std, bg_counter, bg_dim]\n}\n\ndata = pd.DataFrame(stats)\ndata",
"Data Statistics for Background images\n"
]
],
[
[
"# Statistics for Background-Foreground images",
"_____no_output_____"
]
],
[
[
"# Background-Foreground\nprint('Calculating statistics for Background-Foreground Images...')\nbg_fg_mean, bg_fg_std, bg_fg_counter, bg_fg_dim, bg_fg_image = statistics(ROOT_DATA_DIR, 3, 'bg_fg')",
"Calculating statistics for Background-Foreground Images...\n"
],
[
"# Display\nprint('Background-Foreground Images:')\nmake_grid(bg_fg_image, margin=30)",
"Background-Foreground Images:\n"
],
[
"print('Data Statistics for Background-Foreground images')\n\nstats = {\n 'Statistics': ['Mean', 'Standard deviation', 'Number of images', 'Dimension'],\n 'Data': [bg_fg_mean, bg_fg_std, bg_fg_counter, bg_fg_dim]\n }\n\ndata = pd.DataFrame(stats)\ndata",
"Data Statistics for Background-Foreground images\n"
]
],
[
[
"# Statistics for Background-Foreground Masks",
"_____no_output_____"
]
],
[
[
"#Foreground-Background Masks\nprint('Calculating statistics for Foreground-Background Masks...')\nbg_fg_mask_mean, bg_fg_mask_std, bg_fg_mask_counter, bg_fg_mask_dim, bg_fg_mask_images = statistics(ROOT_DATA_DIR, 1, 'bg_fg_mask')",
"Calculating statistics for Foreground-Background Masks...\n"
],
[
"# Display\nprint('Background-Foreground Masks:')\nmake_grid(bg_fg_mask_images, margin=30, aspect_ratio=True)",
"Background-Foreground Masks:\n"
],
[
"print('Data Statistics for Background-Foreground Masks images')\n\nstats = {\n 'Statistics': ['Mean', 'Standard deviation', 'Number of images', 'Dimension'],\n 'Data': [bg_fg_mask_mean, bg_fg_mask_std, bg_fg_mask_counter, bg_fg_mask_dim]\n }\n\ndata = pd.DataFrame(stats)\ndata",
"Data Statistics for Background-Foreground Masks images\n"
]
],
[
[
"# Statistics for Background-Foreground Depth Maps",
"_____no_output_____"
]
],
[
[
"#Foreground-Background Depth Map\nprint('Calculating statistics for Foreground-Background Depth Map...')\ndepth_mean, depth_std, depth_counter, depth_dim, depth_images = statistics(ROOT_DATA_DIR, 1, 'bg_fg_depth_map')",
"Calculating statistics for Foreground-Background Depth Map...\n"
],
[
"# Display\nprint('Background-Foreground Depth Maps:')\nmake_grid(depth_images, margin=30)",
"Background-Foreground Depth Maps:\n"
],
[
"print('Data Statistics for Background-Foreground Depth Map images')\n\nstats = {\n 'Statistics': ['Mean', 'Standard deviation', 'Number of images', 'Dimension'],\n 'Data': [depth_mean, depth_std, depth_counter, depth_dim]\n }\n\ndata = pd.DataFrame(stats)\ndata",
"Data Statistics for Background-Foreground Depth Map images\n"
],
[
"",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0ac7eb8013fbbd3f925b93422e8450ba8d2b12b | 32,374 | ipynb | Jupyter Notebook | tests/project/ipynb/pandas.ipynb | QuantEcon/sphinx-tojupyter | ba15167e433ef67b92d88484465c40cb9153bc3c | [
"BSD-3-Clause"
] | 1 | 2021-02-08T11:43:38.000Z | 2021-02-08T11:43:38.000Z | tests/project/ipynb/pandas.ipynb | QuantEcon/sphinx-tojupyter | ba15167e433ef67b92d88484465c40cb9153bc3c | [
"BSD-3-Clause"
] | 23 | 2020-11-10T04:42:58.000Z | 2022-02-16T07:48:53.000Z | tests/project/ipynb/pandas.ipynb | QuantEcon/sphinx-tojupyter | ba15167e433ef67b92d88484465c40cb9153bc3c | [
"BSD-3-Clause"
] | null | null | null | 25.878497 | 215 | 0.555106 | [
[
[
"\n<a id='pd'></a>\n<div id=\"qe-notebook-header\" align=\"right\" style=\"text-align:right;\">\n <a href=\"https://quantecon.org/\" title=\"quantecon.org\">\n <img style=\"width:250px;display:inline;\" width=\"250px\" src=\"https://assets.quantecon.org/img/qe-menubar-logo.svg\" alt=\"QuantEcon\">\n </a>\n</div>",
"_____no_output_____"
],
[
"# Pandas\n\n\n<a id='index-1'></a>",
"_____no_output_____"
],
[
"## Contents\n\n- [Pandas](#Pandas) \n - [Overview](#Overview) \n - [Series](#Series) \n - [DataFrames](#DataFrames) \n - [On-Line Data Sources](#On-Line-Data-Sources) \n - [Exercises](#Exercises) \n - [Solutions](#Solutions) ",
"_____no_output_____"
],
[
"In addition to what’s in Anaconda, this lecture will need the following libraries:",
"_____no_output_____"
]
],
[
[
"!pip install --upgrade pandas-datareader",
"_____no_output_____"
]
],
[
[
"## Overview\n\n[Pandas](http://pandas.pydata.org/) is a package of fast, efficient data analysis tools for Python.\n\nIts popularity has surged in recent years, coincident with the rise\nof fields such as data science and machine learning.\n\nHere’s a popularity comparison over time against STATA, SAS, and [dplyr](https://dplyr.tidyverse.org/) courtesy of Stack Overflow Trends\n\n\n\n \nJust as [NumPy](http://www.numpy.org/) provides the basic array data type plus core array operations, pandas\n\n1. defines fundamental structures for working with data and \n1. endows them with methods that facilitate operations such as \n - reading in data \n - adjusting indices \n - working with dates and time series \n - sorting, grouping, re-ordering and general data munging <sup><a href=#mung id=mung-link>[1]</a></sup> \n - dealing with missing values, etc., etc. \n\n\nMore sophisticated statistical functionality is left to other packages, such\nas [statsmodels](http://www.statsmodels.org/) and [scikit-learn](http://scikit-learn.org/), which are built on top of pandas.\n\nThis lecture will provide a basic introduction to pandas.\n\nThroughout the lecture, we will assume that the following imports have taken\nplace",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [10,8] # Set default figure size\nimport requests",
"_____no_output_____"
]
],
[
[
"## Series\n\n\n<a id='index-2'></a>\nTwo important data types defined by pandas are `Series` and `DataFrame`.\n\nYou can think of a `Series` as a “column” of data, such as a collection of observations on a single variable.\n\nA `DataFrame` is an object for storing related columns of data.\n\nLet’s start with Series",
"_____no_output_____"
]
],
[
[
"s = pd.Series(np.random.randn(4), name='daily returns')\ns",
"_____no_output_____"
]
],
[
[
"Here you can imagine the indices `0, 1, 2, 3` as indexing four listed\ncompanies, and the values being daily returns on their shares.\n\nPandas `Series` are built on top of NumPy arrays and support many similar\noperations",
"_____no_output_____"
]
],
[
[
"s * 100",
"_____no_output_____"
],
[
"np.abs(s)",
"_____no_output_____"
]
],
[
[
"But `Series` provide more than NumPy arrays.\n\nNot only do they have some additional (statistically oriented) methods",
"_____no_output_____"
]
],
[
[
"s.describe()",
"_____no_output_____"
]
],
[
[
"But their indices are more flexible",
"_____no_output_____"
]
],
[
[
"s.index = ['AMZN', 'AAPL', 'MSFT', 'GOOG']\ns",
"_____no_output_____"
]
],
[
[
"Viewed in this way, `Series` are like fast, efficient Python dictionaries\n(with the restriction that the items in the dictionary all have the same\ntype—in this case, floats).\n\nIn fact, you can use much of the same syntax as Python dictionaries",
"_____no_output_____"
]
],
[
[
"s['AMZN']",
"_____no_output_____"
],
[
"s['AMZN'] = 0\ns",
"_____no_output_____"
],
[
"'AAPL' in s",
"_____no_output_____"
]
],
[
[
"## DataFrames\n\n\n<a id='index-3'></a>\nWhile a `Series` is a single column of data, a `DataFrame` is several columns, one for each variable.\n\nIn essence, a `DataFrame` in pandas is analogous to a (highly optimized) Excel spreadsheet.\n\nThus, it is a powerful tool for representing and analyzing data that are naturally organized into rows and columns, often with descriptive indexes for individual rows and individual columns.\n\nHere’s the content of `test_pwt.csv`",
"_____no_output_____"
],
[
"```text\n\"country\",\"country isocode\",\"year\",\"POP\",\"XRAT\",\"tcgdp\",\"cc\",\"cg\"\n\"Argentina\",\"ARG\",\"2000\",\"37335.653\",\"0.9995\",\"295072.21869\",\"75.716805379\",\"5.5788042896\"\n\"Australia\",\"AUS\",\"2000\",\"19053.186\",\"1.72483\",\"541804.6521\",\"67.759025993\",\"6.7200975332\"\n\"India\",\"IND\",\"2000\",\"1006300.297\",\"44.9416\",\"1728144.3748\",\"64.575551328\",\"14.072205773\"\n\"Israel\",\"ISR\",\"2000\",\"6114.57\",\"4.07733\",\"129253.89423\",\"64.436450847\",\"10.266688415\"\n\"Malawi\",\"MWI\",\"2000\",\"11801.505\",\"59.543808333\",\"5026.2217836\",\"74.707624181\",\"11.658954494\"\n\"South Africa\",\"ZAF\",\"2000\",\"45064.098\",\"6.93983\",\"227242.36949\",\"72.718710427\",\"5.7265463933\"\n\"United States\",\"USA\",\"2000\",\"282171.957\",\"1\",\"9898700\",\"72.347054303\",\"6.0324539789\"\n\"Uruguay\",\"URY\",\"2000\",\"3219.793\",\"12.099591667\",\"25255.961693\",\"78.978740282\",\"5.108067988\"\n```\n",
"_____no_output_____"
],
[
"Supposing you have this data saved as `test_pwt.csv` in the present working directory (type `%pwd` in Jupyter to see what this is), it can be read in as follows:",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('https://raw.githubusercontent.com/QuantEcon/lecture-python-programming/master/source/_static/lecture_specific/pandas/data/test_pwt.csv')\ntype(df)",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
]
],
[
[
"We can select particular rows using standard Python array slicing notation",
"_____no_output_____"
]
],
[
[
"df[2:5]",
"_____no_output_____"
]
],
[
[
"To select columns, we can pass a list containing the names of the desired columns represented as strings",
"_____no_output_____"
]
],
[
[
"df[['country', 'tcgdp']]",
"_____no_output_____"
]
],
[
[
"To select both rows and columns using integers, the `iloc` attribute should be used with the format `.iloc[rows, columns]`",
"_____no_output_____"
]
],
[
[
"df.iloc[2:5, 0:4]",
"_____no_output_____"
]
],
[
[
"To select rows and columns using a mixture of integers and labels, the `loc` attribute can be used in a similar way",
"_____no_output_____"
]
],
[
[
"df.loc[df.index[2:5], ['country', 'tcgdp']]",
"_____no_output_____"
]
],
[
[
"Let’s imagine that we’re only interested in population (`POP`) and total GDP (`tcgdp`).\n\nOne way to strip the data frame `df` down to only these variables is to overwrite the dataframe using the selection method described above",
"_____no_output_____"
]
],
[
[
"df = df[['country', 'POP', 'tcgdp']]\ndf",
"_____no_output_____"
]
],
[
[
"Here the index `0, 1,..., 7` is redundant because we can use the country names as an index.\n\nTo do this, we set the index to be the `country` variable in the dataframe",
"_____no_output_____"
]
],
[
[
"df = df.set_index('country')\ndf",
"_____no_output_____"
]
],
[
[
"Let’s give the columns slightly better names",
"_____no_output_____"
]
],
[
[
"df.columns = 'population', 'total GDP'\ndf",
"_____no_output_____"
]
],
[
[
"Population is in thousands, let’s revert to single units",
"_____no_output_____"
]
],
[
[
"df['population'] = df['population'] * 1e3\ndf",
"_____no_output_____"
]
],
[
[
"Next, we’re going to add a column showing real GDP per capita, multiplying by 1,000,000 as we go because total GDP is in millions",
"_____no_output_____"
]
],
[
[
"df['GDP percap'] = df['total GDP'] * 1e6 / df['population']\ndf",
"_____no_output_____"
]
],
[
[
"One of the nice things about pandas `DataFrame` and `Series` objects is that they have methods for plotting and visualization that work through Matplotlib.\n\nFor example, we can easily generate a bar plot of GDP per capita",
"_____no_output_____"
]
],
[
[
"ax = df['GDP percap'].plot(kind='bar')\nax.set_xlabel('country', fontsize=12)\nax.set_ylabel('GDP per capita', fontsize=12)\nplt.show()",
"_____no_output_____"
]
],
[
[
"At the moment the data frame is ordered alphabetically on the countries—let’s change it to GDP per capita",
"_____no_output_____"
]
],
[
[
"df = df.sort_values(by='GDP percap', ascending=False)\ndf",
"_____no_output_____"
]
],
[
[
"Plotting as before now yields",
"_____no_output_____"
]
],
[
[
"ax = df['GDP percap'].plot(kind='bar')\nax.set_xlabel('country', fontsize=12)\nax.set_ylabel('GDP per capita', fontsize=12)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## On-Line Data Sources\n\n\n<a id='index-4'></a>\nPython makes it straightforward to query online databases programmatically.\n\nAn important database for economists is [FRED](https://research.stlouisfed.org/fred2/) — a vast collection of time series data maintained by the St. Louis Fed.\n\nFor example, suppose that we are interested in the [unemployment rate](https://research.stlouisfed.org/fred2/series/UNRATE).\n\nVia FRED, the entire series for the US civilian unemployment rate can be downloaded directly by entering\nthis URL into your browser (note that this requires an internet connection)",
"_____no_output_____"
],
[
"```text\nhttps://research.stlouisfed.org/fred2/series/UNRATE/downloaddata/UNRATE.csv\n```\n",
"_____no_output_____"
],
[
"(Equivalently, click here: [https://research.stlouisfed.org/fred2/series/UNRATE/downloaddata/UNRATE.csv](https://research.stlouisfed.org/fred2/series/UNRATE/downloaddata/UNRATE.csv))\n\nThis request returns a CSV file, which will be handled by your default application for this class of files.\n\nAlternatively, we can access the CSV file from within a Python program.\n\nThis can be done with a variety of methods.\n\nWe start with a relatively low-level method and then return to pandas.",
"_____no_output_____"
],
[
"### Accessing Data with requests\n\n\n<a id='index-6'></a>\nOne option is to use [requests](https://requests.readthedocs.io/en/master/), a standard Python library for requesting data over the Internet.\n\nTo begin, try the following code on your computer",
"_____no_output_____"
]
],
[
[
"r = requests.get('http://research.stlouisfed.org/fred2/series/UNRATE/downloaddata/UNRATE.csv')",
"_____no_output_____"
]
],
[
[
"If there’s no error message, then the call has succeeded.\n\nIf you do get an error, then there are two likely causes\n\n1. You are not connected to the Internet — hopefully, this isn’t the case. \n1. Your machine is accessing the Internet through a proxy server, and Python isn’t aware of this. \n\n\nIn the second case, you can either\n\n- switch to another machine \n- solve your proxy problem by reading [the documentation](https://requests.readthedocs.io/en/master/) \n\n\nAssuming that all is working, you can now proceed to use the `source` object returned by the call `requests.get('http://research.stlouisfed.org/fred2/series/UNRATE/downloaddata/UNRATE.csv')`",
"_____no_output_____"
]
],
[
[
"url = 'http://research.stlouisfed.org/fred2/series/UNRATE/downloaddata/UNRATE.csv'\nsource = requests.get(url).content.decode().split(\"\\n\")\nsource[0]",
"_____no_output_____"
],
[
"source[1]",
"_____no_output_____"
],
[
"source[2]",
"_____no_output_____"
]
],
[
[
"We could now write some additional code to parse this text and store it as an array.\n\nBut this is unnecessary — pandas’ `read_csv` function can handle the task for us.\n\nWe use `parse_dates=True` so that pandas recognizes our dates column, allowing for simple date filtering",
"_____no_output_____"
]
],
[
[
"data = pd.read_csv(url, index_col=0, parse_dates=True)",
"_____no_output_____"
]
],
[
[
"The data has been read into a pandas DataFrame called `data` that we can now manipulate in the usual way",
"_____no_output_____"
]
],
[
[
"type(data)",
"_____no_output_____"
],
[
"data.head() # A useful method to get a quick look at a data frame",
"_____no_output_____"
],
[
"pd.set_option('precision', 1)\ndata.describe() # Your output might differ slightly",
"_____no_output_____"
]
],
[
[
"We can also plot the unemployment rate from 2006 to 2012 as follows",
"_____no_output_____"
]
],
[
[
"ax = data['2006':'2012'].plot(title='US Unemployment Rate', legend=False)\nax.set_xlabel('year', fontsize=12)\nax.set_ylabel('%', fontsize=12)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Note that pandas offers many other file type alternatives.\n\nPandas has [a wide variety](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html) of top-level methods that we can use to read, excel, json, parquet or plug straight into a database server.",
"_____no_output_____"
],
[
"### Using pandas_datareader to Access Data\n\n\n<a id='index-8'></a>\nThe maker of pandas has also authored a library called pandas_datareader that gives programmatic access to many data sources straight from the Jupyter notebook.\n\nWhile some sources require an access key, many of the most important (e.g., FRED, [OECD](https://data.oecd.org/), [EUROSTAT](https://ec.europa.eu/eurostat/data/database) and the World Bank) are free to use.\n\nFor now let’s work through one example of downloading and plotting data — this\ntime from the World Bank.\n\nThe World Bank [collects and organizes data](http://data.worldbank.org/indicator) on a huge range of indicators.\n\nFor example, [here’s](http://data.worldbank.org/indicator/GC.DOD.TOTL.GD.ZS/countries) some data on government debt as a ratio to GDP.\n\nThe next code example fetches the data for you and plots time series for the US and Australia",
"_____no_output_____"
]
],
[
[
"from pandas_datareader import wb\n\ngovt_debt = wb.download(indicator='GC.DOD.TOTL.GD.ZS', country=['US', 'AU'], start=2005, end=2016).stack().unstack(0)\nind = govt_debt.index.droplevel(-1)\ngovt_debt.index = ind\nax = govt_debt.plot(lw=2)\nax.set_xlabel('year', fontsize=12)\nplt.title(\"Government Debt to GDP (%)\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"The [documentation](https://pandas-datareader.readthedocs.io/en/latest/index.html) provides more details on how to access various data sources.",
"_____no_output_____"
],
[
"## Exercises\n\n\n<a id='pd-ex1'></a>",
"_____no_output_____"
],
[
"### Exercise 1\n\nWith these imports:",
"_____no_output_____"
]
],
[
[
"import datetime as dt\nfrom pandas_datareader import data",
"_____no_output_____"
]
],
[
[
"Write a program to calculate the percentage price change over 2019 for the following shares:",
"_____no_output_____"
]
],
[
[
"ticker_list = {'INTC': 'Intel',\n 'MSFT': 'Microsoft',\n 'IBM': 'IBM',\n 'BHP': 'BHP',\n 'TM': 'Toyota',\n 'AAPL': 'Apple',\n 'AMZN': 'Amazon',\n 'BA': 'Boeing',\n 'QCOM': 'Qualcomm',\n 'KO': 'Coca-Cola',\n 'GOOG': 'Google',\n 'SNE': 'Sony',\n 'PTR': 'PetroChina'}",
"_____no_output_____"
]
],
[
[
"Here’s the first part of the program",
"_____no_output_____"
]
],
[
[
"def read_data(ticker_list,\n start=dt.datetime(2019, 1, 2),\n end=dt.datetime(2019, 12, 31)):\n \"\"\"\n This function reads in closing price data from Yahoo\n for each tick in the ticker_list.\n \"\"\"\n ticker = pd.DataFrame()\n\n for tick in ticker_list:\n prices = data.DataReader(tick, 'yahoo', start, end)\n closing_prices = prices['Close']\n ticker[tick] = closing_prices\n\n return ticker\n\nticker = read_data(ticker_list)",
"_____no_output_____"
]
],
[
[
"Complete the program to plot the result as a bar graph like this one:\n\n\n\n \n\n<a id='pd-ex2'></a>",
"_____no_output_____"
],
[
"### Exercise 2\n\nUsing the method `read_data` introduced in [Exercise 1](#pd-ex1), write a program to obtain year-on-year percentage change for the following indices:",
"_____no_output_____"
]
],
[
[
"indices_list = {'^GSPC': 'S&P 500',\n '^IXIC': 'NASDAQ',\n '^DJI': 'Dow Jones',\n '^N225': 'Nikkei'}",
"_____no_output_____"
]
],
[
[
"Complete the program to show summary statistics and plot the result as a time series graph like this one:\n\n",
"_____no_output_____"
],
[
"## Solutions",
"_____no_output_____"
],
[
"### Exercise 1\n\nThere are a few ways to approach this problem using Pandas to calculate\nthe percentage change.\n\nFirst, you can extract the data and perform the calculation such as:",
"_____no_output_____"
]
],
[
[
"p1 = ticker.iloc[0] #Get the first set of prices as a Series\np2 = ticker.iloc[-1] #Get the last set of prices as a Series\nprice_change = (p2 - p1) / p1 * 100\nprice_change",
"_____no_output_____"
]
],
[
[
"Alternatively you can use an inbuilt method `pct_change` and configure it to\nperform the correct calculation using `periods` argument.",
"_____no_output_____"
]
],
[
[
"change = ticker.pct_change(periods=len(ticker)-1, axis='rows')*100\nprice_change = change.iloc[-1]\nprice_change",
"_____no_output_____"
]
],
[
[
"Then to plot the chart",
"_____no_output_____"
]
],
[
[
"price_change.sort_values(inplace=True)\nprice_change = price_change.rename(index=ticker_list)\nfig, ax = plt.subplots(figsize=(10,8))\nax.set_xlabel('stock', fontsize=12)\nax.set_ylabel('percentage change in price', fontsize=12)\nprice_change.plot(kind='bar', ax=ax)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Exercise 2\n\nFollowing the work you did in [Exercise 1](#pd-ex1), you can query the data using `read_data` by updating the start and end dates accordingly.",
"_____no_output_____"
]
],
[
[
"indices_data = read_data(\n indices_list,\n start=dt.datetime(1928, 1, 2),\n end=dt.datetime(2020, 12, 31)\n)",
"_____no_output_____"
]
],
[
[
"Then, extract the first and last set of prices per year as DataFrames and calculate the yearly returns such as:",
"_____no_output_____"
]
],
[
[
"yearly_returns = pd.DataFrame()\n\nfor index, name in indices_list.items():\n p1 = indices_data.groupby(indices_data.index.year)[index].first() # Get the first set of returns as a DataFrame\n p2 = indices_data.groupby(indices_data.index.year)[index].last() # Get the last set of returns as a DataFrame\n returns = (p2 - p1) / p1\n yearly_returns[name] = returns\n\nyearly_returns",
"_____no_output_____"
]
],
[
[
"Next, you can obtain summary statistics by using the method `describe`.",
"_____no_output_____"
]
],
[
[
"yearly_returns.describe()",
"_____no_output_____"
]
],
[
[
"Then, to plot the chart",
"_____no_output_____"
]
],
[
[
"fig, axes = plt.subplots(2, 2, figsize=(10, 8))\n\nfor iter_, ax in enumerate(axes.flatten()): # Flatten 2-D array to 1-D array\n index_name = yearly_returns.columns[iter_] # Get index name per iteration\n ax.plot(yearly_returns[index_name]) # Plot pct change of yearly returns per index\n ax.set_ylabel(\"percent change\", fontsize = 12)\n ax.set_title(index_name)\n\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"<p><a id=mung href=#mung-link><strong>[1]</strong></a> Wikipedia defines munging as cleaning data from one raw form into a structured, purged one.",
"_____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",
"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"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d0ac81e8efcf40105687e00d8a5c932b5ab56c9a | 196,476 | ipynb | Jupyter Notebook | Old/Group_asgnt (1).ipynb | Rick-Mackenbach/DPA-Group-Assignment | 3b74fdb3902f77e4ca6aedb76f4dad2f87ee928e | [
"MIT"
] | null | null | null | Old/Group_asgnt (1).ipynb | Rick-Mackenbach/DPA-Group-Assignment | 3b74fdb3902f77e4ca6aedb76f4dad2f87ee928e | [
"MIT"
] | null | null | null | Old/Group_asgnt (1).ipynb | Rick-Mackenbach/DPA-Group-Assignment | 3b74fdb3902f77e4ca6aedb76f4dad2f87ee928e | [
"MIT"
] | null | null | null | 152.662005 | 939 | 0.72988 | [
[
[
"import numpy\nimport scipy\nimport scipy.sparse\nimport sklearn.metrics.pairwise\nfrom sklearn import datasets\nfrom sklearn.metrics.pairwise import pairwise_distances\n#%%\n\n descriptions = []\n\n with open('descriptions.txt', encoding = \"utf8\") as f:\n for line in f:\n text = line.lower() ## Lowercase all characters\n text = text.replace(\"[comma]\",\" \") ## Replace [commas] with empty space\n for ch in text:\n if ch < \"0\" or (ch < \"a\" and ch > \"9\") or ch > \"z\": ## The cleaning operation happens here, remove all special characters\n text = text.replace(ch,\" \")\n text = ' '.join(text.split()) ## Remove double spacing from sentences\n descriptions.append(text)\n dataSet = numpy.array(descriptions)\n f.close()\n #%%\n vect = sklearn.feature_extraction.text.CountVectorizer()\n ##alternative vect = sklearn.feature_extraction.text.TfidfVectorizer\n\n count = vect.fit_transform(descriptions)\n\n cossim = sklearn.metrics.pairwise.cosine_similarity(count)\n euclid = pairwise_distances(count, metric='euclidean')\n manhat = pairwise_distances(count, metric='manhattan')\n\n print(euclid[1][3])\n print(euclid[1][2])\n print(euclid[2][3])\n print(euclid[21][344])\n\n #from nltk.corpus import stopwords\n #stop = stopwords.words('english')\n\n from nltk.stem import PorterStemmer\n st = PorterStemmer()\n ## Stemming removes -ly, -ing, -ly, etc. \n\n",
"9.797958971132712\n8.54400374531753\n11.269427669584644\n8.774964387392123\n"
],
[
"import numpy\n\ndescriptions = []\n\nwith open('descriptions.txt', encoding = \"utf8\") as f:\n for line in f:\n text = line.lower() ## Lowercase all characters\n text = text.replace(\"[comma]\",\" \") ## Replace [commas] with empty space\n for ch in text:\n if ch < \"0\" or (ch < \"a\" and ch > \"9\") or ch > \"z\": ## The cleaning operation happens here, remove all special characters\n text = text.replace(ch,\" \")\n text = ' '.join(text.split()) ## Remove double spacing from sentences\n descriptions.append(text)\ndataSet = numpy.array(descriptions)\nf.close()",
"_____no_output_____"
],
[
"\nnumpy.save(\"descriptions_cleaned_array.npy\",dataSet)#numpy. \ndataSet = numpy.load(\"descriptions_cleaned_array.npy\")\n#dataSet = numpy.load(\"coco_val.npy\")",
"_____no_output_____"
],
[
"from sklearn.feature_extraction.text import TfidfVectorizer\nvectorizer = TfidfVectorizer()\nTfIdf_dataSet = vectorizer.fit_transform(dataSet)\nprint(\"What our Tf-Idf looks like: \")\nprint()\nprint(TfIdf_dataSet[1:2])\n\nvectorVocab = vectorizer._validate_vocabulary()",
"What our Tf-Idf looks like: \n\n (0, 228)\t0.0999230235196548\n (0, 2737)\t0.16083047896043273\n (0, 1776)\t0.06254106376813398\n (0, 2119)\t0.3161753448886334\n (0, 1247)\t0.14464356086569088\n (0, 2538)\t0.19064057405466286\n (0, 419)\t0.18076247495377387\n (0, 2292)\t0.1401975901762004\n (0, 3445)\t0.21120111824703844\n (0, 3749)\t0.2492839547283478\n (0, 2604)\t0.3123113475808705\n (0, 2188)\t0.2417063139284673\n (0, 2262)\t0.264108063599575\n (0, 1420)\t0.07045478691841404\n (0, 286)\t0.11292286212515924\n (0, 772)\t0.21289776024949109\n (0, 1217)\t0.2324320311261342\n (0, 2694)\t0.1235469355267728\n (0, 180)\t0.27051486760744353\n (0, 878)\t0.20649095624162253\n (0, 2276)\t0.14173141580413545\n (0, 1605)\t0.1515561961580996\n (0, 1191)\t0.3161753448886334\n (0, 740)\t0.1644468421153148\n"
],
[
"## COSINE\n\ncosineSimilarity = sklearn.metrics.pairwise.cosine_similarity(TfIdf_dataSet)\ncosineSimilaritySorted = numpy.argsort(cosineSimilarity, axis=1)\ntop5Similar = cosineSimilaritySorted[:,0:5]\n\nprint(top5Similar)",
"_____no_output_____"
],
[
"from nltk.tokenize import sent_tokenize, word_tokenize",
"_____no_output_____"
],
[
"print(sent_tokenize(descriptions[2]))",
"['red hair a little lower than the ears big face a little weirdly shaped around the jaw freckles he looks like he had a hard childhood and isn t a happy person he probably has a lot of repressed feeling or the photographer didn t get him on a good day']\n"
],
[
"print(word_tokenize(descriptions[2]))",
"['red', 'hair', 'a', 'little', 'lower', 'than', 'the', 'ears', 'big', 'face', 'a', 'little', 'weirdly', 'shaped', 'around', 'the', 'jaw', 'freckles', 'he', 'looks', 'like', 'he', 'had', 'a', 'hard', 'childhood', 'and', 'isn', 't', 'a', 'happy', 'person', 'he', 'probably', 'has', 'a', 'lot', 'of', 'repressed', 'feeling', 'or', 'the', 'photographer', 'didn', 't', 'get', 'him', 'on', 'a', 'good', 'day']\n"
],
[
"from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize",
"_____no_output_____"
],
[
"stop_words = set(stopwords.words(\"english\"))\n# removes standard words such as \"have\" \"just\" \"until\" \"it\" \"did\"...\n\nwords = word_tokenize(descriptions[123])\n\nfiltered = []\n\nfor w in words:\n if w not in stop_words:\n filtered.append(w)\nprint(filtered)",
"['person', 'tall', 'long', 'skinny', 'legs', 'long', 'arms', 'long', 'fingers', 'toes', 'big', 'feet', 'person', 'works', 'hard', 'pursuing', 'higher', 'education', 'one', 'child', 'wife', 'home']\n"
],
[
"## Stemming\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\n\nps = PorterStemmer()\n\nfor w in descriptions:\n print(ps.stem(w))\n ",
"jug ears mustache and beard and long sideburns stylish hair no laugh lines eyes are clear no drugs or alcohol confident a little overweight from double chin \nshe is tall and athletic she is lean she is thin she is outgoing she is single she loves hiking and nature \nthis guy is an attractive he specified at working an sales or marketing field he is an latino person he looks like a married person and she is an parents also \nthis person is a white male under 30 with red hair and green eyes this person graduated from college several years ago with a degree in accounting he enjoys spending time with his girlfriend he is thinking about proposing soon \nshe is average height slim and eats healthy her hair is hardly ever let out but rather in a bun and has a good posture she doesn t smile much she likes to ear turtle necks and wears a lot of professional and not cute clothing she takes her job and life seriously which is seen in the adults and successful people she hangs out with \nthis person s facial features indicate they are somewhat heavy in terms of their weight this person s chubby cheeks and the shape of their forehead give a very rounded look to the face in general one in which there are few strong visible contours i think this person is not physically active at all and likely overeats with some regularity they may in turn lack the self control that others would typically exhibit \nshe has black hair parted down the middle and pulled back she has black shaped eyebrows she wears no makeup and has thin lips her cheeks are rosy she s boring she has cats she doesn t ever go out she doesnt have a lot of money or a lot of friends \nthis girls is very like much and so on her eyes are very nice and excellent and very beautiful and nose is beautiful the girl is very beautiful she is so beautiful nice person she like very much all over the boys \nbig oval shaped face with blue eyes brown hair and confident confident active and intelligent person with good personality strong man with attractive face \nshort white woman with an athletic build green eyes blonde hair they like to attend social gatherings with their friends they are going to school for a master s degree \nnormal guy with some scruff very normal good looking guy i can guess that he would be a funny guy based on his look he s grinning \nhe is very thin and probably on the short side he likes punk music spends his free time playing video and computer games he went to college but dropped out after the first semester \nshe has hort blonde hair nice thick black eyelashes a crooked nose thin shaped eyebrows likes to wear head bands on her head she likes to listen to music and hang with friends she loves texting and staying up late to chill with her friends \nthis person has grayish hazel eyes and looks very young he is smiling a little and has brown to blonde hair he seems to be a student as he looks very young \na white person possibly male female or transgender they have darkish brown hair hazel or green eyes and a heavier set face i m guessing they either identify as a lesbian or transgendered male female or male female i m not sure for some reason i m guessing car salesperson i would imagine they re just past typical college age \nblonde haired woman with a short bob cut that s swept to the side blue eyes and a few minor moles along her jaw they care a lot about their appearance their family is well off financially they are a bit conceited \nfair skinned caucasian male with blond hair blue eyes looks young probably late teens he is a student he is young he gets sunburned easily he likes to watch tv and play sports \nhe is a teenager of about average height and slim build he has brown hair and blue eyes he is young he is in highschool he doesn t put much effort into his appearance \nyoung white woman short brown hair with blond highlights blue eyes medium complexion has long term boyfriend enjoys outdoors camping hiking big fan of sports has a cat \nthis person is of a light skin complexity and has red hair and freckles this person is of a big build and is somewhat overweight and has bigger features i can guess this person does not spend much time outside has a bad sense of style does not like sports has a lot of family is somewhat isolated \nhe s tall and weighs about 145 pounds he s somewhat muscular because he works out he goes to school but sometimes cuts classes he s a below average student and gets into trouble by shop lifting \nthe person maintains a stylish haircut he often has a five o clock shadow he is taller than average but is of average weight and build in comparison to his peers he is relatively healthy despite not being physically active he likely works in a white collar job probably as a professional or in a managerial position he is generally amicable and well received by peers he is respected by others and people defer to his authority and expertise \nsmart looking personality small beard and mustache which adds to his face seems smart seems jobless seems he belongs to a rich family drinks too much good height \nthis person has very short cut brown auburn or red hair he has dark blue eyes and a very small amount of facial hair i guess that this person works in food service based on the noticeable lack of facial or head hair as this is common among food service professionals \na little chubby short about 5 4 in height wears closed up shirts and long skirts friendly and out going sometimes can be shy stays in school most of her free time with known friends and studies alot \nshe is a bit chubby and short she isn t in the most shape and she dresses kind of like a skater or so she is nice caring and likes cats she is into classic rock and making blankets \nthis woman has short brown hair with hazel eyes and a symmetrical face this person enjoys going shopping with friends this person loves her family deeply this person can be selfish at times \na redhead with dark auburn hair and blue eyes eyebrows are faint and straight he has freckles as well as reddish cheeks he s got thin lips and a round jaw both his parents are white he s a nerd he doesn t really care about style \nshe has brownish hair she has attractive eyes her nose is medium and lips are flat she is a steno she has an innocent face she looks like modelling \nhe having long hair middle age men nice look and blue eyes with calm face and silent he is looking like a hairstyles new look hair style with attractive look more over silent his nature \nbrown hair and eyes average build mid 20s longer hair on the sides no hair on face he looks like he would be a professional of sorts but nothing too prestigious not a business man \ni hope you all enjoyed writing and reading the last assignment if you did not get your text corrected by someone please let me know no texts should go uncorrected many project websites link to this document in their sections on how to get help that s fine it s the use we intended but if you are a webmaster creating such a link for your project page please display prominently near the link notice that we are not a help desk for your project \nshort and petite and thin wears loose jeans and sweaters only shy around a lot of people tends to talk to females only doesnt really go out in the weekends much to be quite honest \na mid 20 s latino man with dark brown or black hair and dark brown eyes he has a prominent oval birthmark on his lower right cheek hard worker young perhaps a bit shy capable determined his family is important to him \nhe is having black curly hair his eyes are black in colour with thin eye brows small nose with a broad chin he seems to be a talkative person his height would be around 5 feet 5 inches \ndark dyed hair face stubble and dark eyebrows large ears and smaller eyes thin lips and sparse eyelashes has a family to support and works hard does ok but not rich cares about work and supporting his family \nthis woman is medium weight she is about 5 7 in height she doesn t wear any make up her hair is short she has fair skin complexion she has a small child a girl she uses a computer a lot she watches basketball and is a fan of a few of the sports guys she isn t athletic herself she loves to shop and adores her family and friends \nshe is thin with small features she has a cup breasts she has slightly uneven posture she works as a cashier at sephora she lives with a roommate she goes to a community college \nshe has blonde hair although it may be dyed blonde she has a round face and very dark eyes that are possibly green or blue she has rather thin eyebrows she is somewhat concerned about her appearance but doesn t exercise a ton she s able to laugh easily and often \nthis person is a very upset face and handsome face his eyes are very beautiful this person is very smart and intelligent if this person comes home there is a great peace \nlikes to have his bangs hang down looks very feminine is bigger than other peoples has a clean face he is very unhappy bigger than most may be into men deals with problems by eating \na white female in her 20s who has brown hair and brown eyes they are mean and stuck up they probably think they are better than everyone else they are probably a show off who thinks the world owes them everything \nwhite female young adult with medium length brown hair they are a stable middle class young adult living in the southern region of the united states of america \nslim tall man with a pizza face and no muscle mass i am modest but hard working and i consistently sets firm goals for myself then once i ve defined the benchmarks i take the necessary steps to achieve those milestones \nthe girls face is excellent and very nice person this person nose is beautiful and mouth is beautiful this person is excellent person and very nice like much all over the members \noblong face stocky build ordinary looking fair complexion possibly freckles not satisfied with thei appearance seem slightly messy looking or unkept \nwrinkled skin frowning mouth arthritis or osteoporosis probably hunches over they look unhappy might have children and or grandchildren looks like they ve worked hard in life \nthis person seems to be little tall about 5 feet 11 inch height with symmetrical body build she seems to be working as a school teacher with good family background \nshe has stylish hair she has two attractive eyes her nose is medium and lips are silent she is a business women she has aggressive face expression \nhe is tall black hair regular size lips very white he is talented he can draw he is smart he likes to party he loves life \nthe shapeshifting excludes clothing trope as used in popular culture items of clothing have a way of sticking around unchanged even if their wearer is also a frequent pairing with the baleful polymorph or incredible shrinking man appearances who suffer from curses that frequently alter their physical forms there are a lot of things that can signify class such as how we speak and how we eat but can we guess your social class from just eigh \n5 4 120 lbs short legs long torso skinny short arms talks to friends a lot does yoga watches a lot of tv shows home cook meals \nshe is around 36 years old has thick hair that is light brown her hair does have some lighter highlights she has blue eyes and a small nose her chin is pronounced she has thin lips nice rosey cheeks she may not be getting enough sleep as she looks a little tired i think she really wants to smile and look happy but she is trying to give off a serious tone she wants to look professional for most people but really she is a happy fun individual may be afraid of letting people see her vulnerable \nthis person is average weight and has short hair he also has gray hair and slight facial hair his cheeks are full this person seems clean cut and conservative he is not smiling so he seems like he might not be very friendly \nlooks like a younger white male with brown hair and brown or hazel eyes from his picture i am guessing this individual is young motivated short energized \nteenage boy average height and build athletic looks vert young i feel like this is a younger person that still attends primary school \nhe is 5 5 tall and weighs around 150 pounds he is a little goofy and not a hard worker this guy will get away with as little as possible he is not a hard work and loves his video games he is not married and probably won t be any time soon \nthis person is white male with medium short brown hair and greenish blue eyes and light facial hair this person likes going out with friends seeing movies and eating at restaurants they enjoy craft beer and artisan cheeses he enjoys riding his motorcycle as a hobby \na middle aged man of average built with short brown hair and no beard obsessions sports sex passion social class gender financial status video games played height weight music hobbies career friends country of birth nationality obsessions sports sex passion accent religion education level marital status shopping preferences race friends social class gender financial status video games played height weight music hobbies career friends country of birth nationality \nthis person seems to be a little older he has blue eyes and orangish hair i think this person is a person working in the business world \nblonde blue eyed white male with short hair thin beard and slight unibrow they come from a lower middle class background in a poorer u s state bu are nonetheless confident and satisfied with the direction they ve taken in life \nthis man has a light white complexion with blonde hair and blue eyes he has fairly large ears and a light amount of facial hair he has a shaved head and seems to be of average weight or maybe a bit underweight i imagine this person likes sports i imagine they like dating women and hanging with their friends i imagine they are nice and popular among their peers \nshort brown hair with hazel eyes pursed lips and a slender face she is very organized and was top in her class stable relationship and doesn t want kids \nthis person is fairly tall and of average built they are muscular this person is reserved and quiet this person likes to exercise \nthis man is average weight and a little shorter than average he has black hair and brown eyes he has a beard coming in so he s kind of scruffy he doesn t like his job he is single and no kids he still lives at home sometimes he steals from places \nshort average weight average height nothing really stands out as far as being different than most average people i seriously do not know what i am supposed to put here sorry \nshe is a white female with brown hair and brown eyes she spends most of her time studying she thinks she can have fun after she graduates her family wishes she would visit more but she is just too busy \nthis woman has very dark black hair and pale skin and a fairly round face with thin brows and light brown eyes she has a slightly uneven nose and average lips and a slight dimple on her chin stressful job might be a mother introvert likes movies stays up late \na young caucasian male that looks to be in his early 20s he has red hair and brown eyes i think he is a fitness guy enjoys going to the gym and working out regularly he loves football and other sports \nwhite man neither young nor old longish greasy blond hair blue eyes tipped downward smug expression asymmetrical eyes and ears he s probably physically fairly strong he looks like he s not rich has experienced some adversity in life for some reason \ndark hair with blue eyes and bad skin with a serious look smart assertive likes sports probably a college student and very serious \nhe is probably skinny has a beard and has dark hair maybe highlights as well he probably works retail maybe at a movie theater he has a girlfriend and smokes weed \nhe is a white male with red hair and green eyes probably enjoys going out with friends likes listening to music enjoys eating good food \nhere is a short orange haired woman slender with light skin and bluish eyes she s about 5 4 she s a nurse likes helping people can be shy likes to hang out with friends and have a good time when not working \npossibly long hair blond blue eyes and wearing mascara wide nose and small ears dark eyebrows that have been plucked crooked probably has a good bit of friends in school and still doing fairly well with studies has good relationship with family though starting to keep a few secrets \nmarine type hair cut arched dark brown brows and hair small hazel eyes smooth face very small lips and ears that stick out a bit looks very tired and intoxicated angry hostile under influence of drugs rude arrogant annoying smarmy probably over spoiled as a child or neglected dishonest manipulative \n5 feet 11 inches tall with a athletic build muscular arms and slim waistline very outgoing very handy around the house a avid sports fan \npositive attitude is the one of the main thing i loved from this person as it is pretty well clear from the photos positive attitude is the one of the main thing i loved from this person as it is pretty well clear from the photos \nthis is a female with brown hair and blue eyes she is smiling but it looks more like a smirk due to her hooded eyes and light makeuup her face and hair is very symmetrical and her face is fairly round i think she s probably a student perhaps almost done with school she seems like someone who enjoys the social aspect of going to college so maybe it s taking her a bit longer to get through than normal \nhis eyes are very dry very cute and calm easy to use the man is very beautiful and then i thought that the film was good \nthis person has shaggy ear length light brown hair blue eyes and light stubble this person does not work in a highly public environment as they are not required to maintain a 100 pristine personal image but they do work with people \nshe is around 32 years old and has short black hair her eyes are a pretty light blue she has small bags under her eyes her nose is a little off center but is very cute has beautiful lips very nice complexion and skin tone she is a happy person cares about others may work a lot of hours and can get a little tired from that likes to laugh and have a good time really values her family and friends \nhe looks skinny and frail looks like he doesn t do much except lounge around most of the day since he is a student and does not look stressed goes to school parties hangs out with friends most of the time is popular \nthis person is skinny and of medium height around 5 10 this person enjoys sports and watching movies he enjoys hanging with his friends in his spare time and is a very serious person \na blonde white male serious long hair small mouth average nose and ears he likes rock and metal music he loves spicy food \nprobably 6 170 pounds not very muscular they seem like they would be kind of lanky with long arms and legs and very sinewy they enjoy video games they have a decent sense of humor they are not very alpha \nhe is roughly 6 3 and is bigger and slightly overweight he is mean to people gets in trouble with the law and he has been arrested \nthe person with long eye brows and oval face with brown hair he looks a like smiling face and kind hearted and attach to everyone without any expectations \nyoung caucasian female of short stature naturally brown hair dyed blonde white somewhat blemished skin person is probably working class due to the garish hair dye she is hard working and views the world through a fairly simplistic filter she is reasonably pleasant \nneat short hair very clean nice make up done takes care of her self works hard very jealous likes to be around people naturally competitive \nhe has slightly short brown hair he has it short on the sides and long on top he has wide brown eyes and bushy eyebrows he has some slight stubble his nose is pointed up he has small ears and normal sized lips he looks like someone who has worked for a while he has some wrinkles on his face so he is a little older he s experienced adulthood he looks like someone who works with his hands \nmedium height stocky build muscular body big feet big hands short temper not a reliable worker steals takes many breaks rude \nhe has brown hair that is neatly styles he has wide set blue eyes that seem lively he has very thin lips but a strong chin and slight stubble he cares about his appearance and likes to stay in shape he is very friendly and laughs easily \nthis person looks female she has blondish brown hair her eyes are blue and she has freckles on her cheeks she looks very young might be slightly overweight she is young and is likely still a teenager she is likely rather short \n5 7 160 pounds large hips relatively pear shaped more muscular than average mother of 2 is often called a soccer mom has back pain leads a generally stressful life \nthey have brown hair and have a clean shaven face the hair is kind of short man white single son brother middle class likes movies likes sports likes movies \ni think this person is of medium build they are probably short and of average weight they are probably somewhat muscular and exercise frequently i think they are very hard working and friendly i think they work hard at their job and have a strong relationship with their family i believe they are single and have dedicated a large portion of their life to their job \naround 5 3 130 lbs short and rugged a bit of a fit body but not too fit a bit of a mom body slightly worked out but not very strong by any means not muscular but not overweight either enjoys helping people thoughtful a bit moody wants to change the world reads a lot of books \nhe has medium length hair for a boy with a slight curl to it his eyes are light and he is kind of expressionless i would guess that he is maybe in high school or recently graduated he looks like he s maybe like a band kid but with a different expression i could also picture him as a jock type he seems like he would have a larger frame \nhe has medium length medium blonde hair he has hazel eyes and attends the local school the like to smoke pot the are a bit lazy they like to watch a lot of tv \nthis person appears to be latino has short black hair brown eyes a light moustache and average size ears and nose mean nasty yells at customers and co workers tries to take charge of things doesn t like to be denied things \nthis woman is early 30 s with very light blue eyes she has light skin and long blonde hair i would guess she is in law enforcement and doesn t put up with anybodys drama look like she d be a confrontational person \nhe is middle eastern he has black hair and brown eyes he keeps himself pretty clean shaven he has very thick eye brows he has medium length hair he has a big nose he is also pretty tall he likes to spend time with his family he loves his job as a doctor he is married with 2 kids he likes to travel his main hobby is photography he is very outgoing and approachable \nyellowish hazel eyes well taken care of eyebrows a scar above right eyebrow very round jawline seems to be a fan of plucking her eyebrows probably uses skin products as her skin looks quite nice \nshort brown hair thin eyes thin eyebrows medium ears downturned mouth long nose 5 o clock shadow a high school dropout who became a mildly successful mechanic has kept a job for a moderate amount of time but has some substance abuse problems \nthis person has a very good hair line on his head this person also has some very pretty blue eyes this person would be funny to be around this person would go out of his way to help others \nshe is old man head of the family she is cotton shirt and long skirt to use very beautiful she is care taker of family members she is head of our family decisions she is bold women \nthis individual is short at 5 2 and a proportional body shape at 102 lbs short brown hair brown eyes and light skinned outgoing personality bright cheerful energetic healthy diet doesn t drink or do drugs conservative stays busy active social life \nthis person is average height and has a stocky build this person is social and likes to party and have a good time he is into sports and likes talking to the ladies \nthe person has curly hair may be slightly overweight and short i think this person may enjoy heavy metal music and looks like she maybe self absord \ntall maybe close to 6 feet he s thin probably wiry build he s a student he s a friendly person he is close with his family \nshe is lean having a height of 164 cms and weight of 53kg silent character she looks like she is facing some kind of problems she lacks confidence she does t like to compete much \naverage build and height somewhat athletic build but not overly muscled they are much similar to other people this age i believe this person goes to school and is not formally employed i think they spend a great deal of time in study and when they are not studying they probably party a little at their college campus i think this person is probably slightly entitled feeling as their upbringing has spoiled them somewhat \nabout 5 4 tall with a slightly heavy build and slightly overweight stands with a bit of a stoop not college educated worked in the same job for a long time worries a lot \nprobably larger build has black hair some freckles and little stubble probably works as a uber driver might have issues with his anger because of his facial expression probably came from a rich family growing up \nhe s eye brow was very thick he s eyes was very clean and nice he s smile was very cute he s looking smart and brave he s have a good attractive face \nwide head large nose bags under his eyes mustache hair covering ears fat chin big lips thick cheeks this guys face makes me think that he is not that social and does not have the greatest interactions with people i think that he has trouble with the ladies \n5 foot 3 250 pounds has a perpetual smirk dresses in knock off namebrands enjoys complaining to corporate blames everything on anybody that isn t her thought she would be a stripper forever and now stuck being an uber driver due to having no qualifications never left her small town in pa until it was too late on her third failing marriage \nhe has long spikey blonde hair a light beard and mustache on his face his nose is smaller than average and his features are all very light he looks like a very easy going guy someone that would be fun to hang out with and not take life too seriously \nshe looks slightly sleepy she has a crooked nose dry lips big eyes and hair pulled in ponytail i think that she is a school teacher who loves her students i think she likes to read and loves books \nthis boy has a sort of spiky gel filled hairstyle he is clean shaven he seems to care about his appearance as his hair is done carefully and his eyebrows look neat and his face is clean shaven he looks young and i can picture him has a college student \ngeneric looking white guy with hazel eyes and brown hair in a trendy style big bushy eyebrows and unkempt facial hair he s a slacker from a middle class family in the us who is in a band and hangs out on 4chan \nthis person is young and has clear fair skin they have light red hair and blue eyes they are on the small side probably pretty slight in build and not very tall fair in coloring sunburns easily awkward shy quiet determined hopeful funny \nthis person is very tall has long skinny legs long arms long fingers and toes and has very big feet this person works hard is pursuing higher education and he has one child and a wife at home \nthis is a female that has dark brown hair and it s mid level in length her eyes are brown her height is 5 feet 3 and she weighs around 120 pounds this person enjoys spending time with family and friends the most when she isn t working at the printing company she is employed at she enjoys gardening shopping and spending hours watching movies on netflix and hulu \nmale medium height medium build short black hair clean shaven brown eyes no visible tattoos he likes sports he likes girls he likes beer and he likes mexican food \n6 1 tall short slight stature around 150 lbs short dark brown hair with dark brown eyes and slight mustache and goatee this guy still wears cool water because it s what the girls in high school liked and he is a creature of habit maybe one day he ll move on to ax body spray he really enjoys the comedy styling of jeff dunham and especially likes the dead terrorist puppet he lives with his mom and gets mad when she tells him to get a real job at best buy \nhis eyes are very dry very cute and calm easy to use the man is very beautiful and then i thought that the film was good \nshe has blonde hair cut in a trendy style she has blue eyes with hooded lids she has a mole under her nose she wears a lot of makeup and tries to keep up with the latest fashions she is very concerned with her appearance she s not as concerned with grades as she is with her social life \nbrown hair brown eyes freckles 5 4 tall weighs around 180 intelligent shy married has children likes to be around family doesn t like to be alone goes to church enjoys gardening \nprobably around five feet eight inches tall short dark brown hair blue eyes light complexion close set eyes unfriendly a bit obnoxious and rude comes from a working class family with a somewhat cruel father works in finance maybe some sort of investments has a dangerously volatile temper treats women cruelly \nmale with brown hair in his mid twenties clean cut with facial scruff but not unruly blue eyes and a natural smile he is active and outgoing likes to socialize and has lots of friends \nthe person is light skin with blue eyes and dark brown or black hair they are probably a happy person because they look like they are already smiling in the photo i m sure that they like hanging out with friends and having fun \nthis boy has long red hair blue eyes red eyebrows and slightly reddish face he is still in high school plays soccer and is likes by everyone \nyounger woman short dirty blonde hair styled to one side green eyes and full lips in school listens to alternative music is not afraid to have fun and live a little \nhe has attractive hair style he has cute eyes with long nose his cheek is also broad he is look like a college student he is an hacker too \nthe person seems to have a slim body based on her face feature she doesn t belong to overweight type soft person warm doesn t seem very strong physically seem to be a good parent \nhe has a slim and muscular physique he is 6 fee tall and has good posture he is a lady killer who has broken many hearts he has an ego that is not pleasant \nslightly overweight about 5 feet 10 inches tall has a sleeve tattoo he likes mma and stopped watching football because players took a knee \nthis female has short brown hair and thin eyebrows she has a wide nose and full lips her face is an oval shape and her ears are small her eyes are a sea green color she is educated she is successful in her job she doesn t appear to be very happy \nthis person has short curly hair with eyes that sort of look like the sea he has fair skin plays sports like theater family is jewish average student \nhe have a blue eyes and professional look and bald head round face structure he is looking like a professor with a happy face middle age man with more experience in his profession \nroundish head thick brown eyebrows short brown hair long brown sideburns became a bus driver for the mentally disabled after he was unable to get into any decent colleges due to his bad grades \nthis person will be in white color slim looking this person will not be social outgoing and will be moody \nthis woman is early twenties with light red hair her hair is medium length and im guessing she s 140 lbs i would guess she has one child no education and likes to listen to hard rock and roll \nthis person look very charm i like the attitude this person he s look good person looks trustworthy \nthey have short hair with thin lips they eyebrows seemed to be arched really good they body type would go for on the curvy side they are in school they have kids they like to have fun \na man in his mid forties strong chin unshaven small and narrow nose thick eyebrows thin lips short brown hair brown eyes and small forehead i can just guess that he is a truck driver he has a wife and two children he has mortgage on his house because of a new truck but he ll soon pay it off he is mostly tired \ntall dark handsome toned body blemish free dimple in the chin this person probably is anal or a perfectionist has high standards for everyone but not himself \nthis lady is rugged and strong she wears black often this person is independent does not take no for an answer is happily divorced and has a few kids and grandkids \nthis male has short black hair that doesn t cover his ears he has a slight beard and mustache that is also black his eyes are brown his nose is of average size his skin is tan his ears are in proportion to the rest of his head face he is of middle eastern descent he looks like he would be intelligent he looks like he would be kind \nhe is of medium height with a thin build he has larger pores he is quiet and serious he is a bit judgemental too \nthis person has pale blotched skin and no facial hair he has large ears and greyish white hair he has very light eyebrows and pronounced ears he has light blue eyes this person looks like they drink a lot and gets into fights they probably have a bad diet he seems quite surly and to have a short temper \nhe has light brown hair that is cropped into a short cut he has piercing blue eyes high cheekbones and fairly ample lips he has a slight beard ant the hint of a mustache he is kind he is humble he is good at sports he loves anima s \nthis person looks in the forties and has black hair color with same color eyes this person looks smart intelligent clever and looks professional or experienced \nattractive lady with short blonde hair she is older and was very pretty when younger kind but serious she loves to read books and watch movies \n5 5 130 pounds not of an exceedingly petite figure short arms relatively uncurvy self conscious about size of eyes not particularly fashionable wore glasses at some point during life \nthis person is short about 5 feet 5 inch tall with slight over weight body build this person is hard working and successful person he is from lower middle class family \nredhead with blue eyes seems like since this guy is a red head he played in harry potter \n22 year old white female with dirty blonde hair and grey eyes build is overweight possibly a mother may be employed her hair looks like she gets it highlighted so she cares enough about her appearance and could work in a setting where she d have to be put together in her appearance \nthey look indian they have a mole on their side short cropped hair brownish skin they are probably a recent immigrant they hate the mole on their face \nabout 5 7 tall slim build and in good shape stands upright with their chest pumped out tries to make themselves appear bigger than they are self assured arrogant works as a car sales person and is very aggressive in sales works out at the gym tries to project an alpha male image \nthey are of average height and weight for a person of their age and gender they are a nice person to be around with mostly nice things to say \nhe is an students he is an distubed mind personalities he nervous type for any time i things the person should nervous from all time then he still working in an students \nmedium length brown hair she has hazel eyes and very thin eyebrows she has a long and thin nose and medium sized lips she likes to drink boxed wine with her girl friends every weekend \nthere are pimples on his mouth his lips are pink his eyes are blue short hair eyebrows pink lips wide jaw he seems like a quiet person that keeps to himself i think that he likes to do things on the computer \nnice hair styles nice cheeks nice eyes nice nose smiley face thin eyebrow she is polite she helps others she works hard easy to approach she is lovable \nshe is short and of an average build maintains her weight by doing yoga and working out she is career minded probably in collage she likes to cook and lives with her boyfriend in a tiny apartment they share \nthis is a male possibly hispanic with dark brown eyes and straight very dark brown hair with bangs slightly sideswept he looks to be in his mid to late teens and the slightest hint of stubble is on his chin stressed out or otherwise at least mildly upset student lives somewhere in the americas late in adolescence \nwhite male late 20s to mid 30s short dirty blonde hair thick eyebrows and green eyes thin mouth and oval face he seems to either be the sneering type or the playful type he doesn t put too much effort into grooming or skin maintenance \nshe from her face is a below average sized female with some spots on her face she seems to be a cunning person from her facial expression \nthis person is normal weight and normal height he probably somewhat works out all the time this person is probably somewhat active and has a desk job he is probably a nice guy \naverage height weight male dark blue eyes and brown hair slightly overweight he is kind and works hard he is family oriented and spends a lot of time looking out for other people \nit s a young guy in his 20 s brown short hair and light blue eyes it s an average looking white guy he s probably a college student at a big college straight man friendly very average looking he is probably from the us europe australia \nshe is a little short around 5 foot 2 inches her shoe size is around 7 and one leg is shorter than the other she has a husband and a couple of daughters in high school she is looking forward to a vacation with her family before her daughters move out she works hard and owns her house \npatient may be tall and slender wearing jeans and a tshirt with a pair of converses no kids boyfriend smokes family oriented likes cats loves pizza listens to rock \nthey are short and hairy has a belly that is a little potbelly and walks very slow smells of indian food shy and awkward in the workplace drives a corolla does not interact well among people \nshe is 5 7 tall and weighs around 175 she is tall and lanky she has bags under her eyes she is a minimum wage employee and is barely making ends meet she has 2 children and is married to an addict she is the only worker in her home and is always stressed out \nmale approx 32 with short dark brown hair and brown eyes seems to be from middle eastern desent also has a beard and mustache of dark brown color angry middle aged tired he seems annoyed appears to be male has short hair has a short beard has a short mustache \nblonde hair and green eyes small thin lips and thin brown eye brows they look like they are a dancer they are outgoing and happy \nthis person has light blue eyes and thick brown eyebrows their face is shaped like a fruit that is starting to ripen they have big ears and brown hair they love animals they have three cats from a rescue shelter they are not married \nthis is a 25 year old male with short dark blonde hair and hazel eyes he is tall and thin he is caucasian police officer friendly wants to help other has many family and friends respected eager to do a good job \nthe person is looking like a innocent this person eyes was explore a truth nice person looking very cute and charming he s person mouth was something telling about \nyoung caucasian male with medium length dyed blond hair brown undertones and blue eyes fairly thick blond eyebrows with a scar on left one looks like he would fit in surfing on the beach seems to care about looking stylish given his hair sculpting \nhis eyes are very dry very cute and calm easy to use the man is very beautiful and then i thought that the film was good \nshe is female white short blonde hair grey eyes young she is a college student probably likes cats likes to dress comfortably \nappears to have an slender well thought of composure does not have flair complexity nor time for any special delivery retorts to simple straight grammatical phrase often has short tips of humour relies on gossip to nudge for longevity of communications \nthey have short hair full lips a narrow nose and a round jawline they like video games play an instrument either a guitar or the drums has a large circle of friends lives with a roommate likes baseball \nphysical characteristics are defining traits or features about your body the first thing you see when you look at someone could be their hair clothes nose or figure to get good examples of physical characteristics you should look at a person s face how tall they are and what they are wearing this person is looking attractive and she is 26 years old and hair color is brown and eye color is brown \nshe has pale skin with freckles she s white and big boned her hair color looks natural she doesn t look like a happy person at all maybe she is part irish \nshes on the taller side she has a nice athletic body type and good fashion sense she wears jeans and t shirts nothing to fancy she likes to do comedy and acting things she might be trying to get into the entertainment business \naverage build though slightly chubby and not in a bad way tall has issues with pimples on the body he s a geek enjoys games and movie culture also tries to talk to everyone he encounters very sociable \nthis is a young indian man with black hair and brown eyes he has olive toned skin he has thick hair he is smart he is hard working he likes his family \nthis woman is probably around 5 8 and is a bit above average weight she has a big family not easily swayed generally happy in life \nhey person has short hair and a rounded face but a nice complexion they seem a bit tired this person is probably smart but maybe doesn t have a great job the person also may be gay \nhe has pale skin with lips that turn up in the corners and dark eyes he has a dog he is still looking for the right person to be with \nthis young woman is slender with a fair complexion she has short blond hair that part on the right and she has blue eyes she has a slender facial build with full lips i think that she is a college student who probably has a part time job to help pay for her education \nthey are younger looking and have light skin with brown hair and blue eyes the person also looks younger and might be in high school i would assume that they like to watch tv and maybe playing video games and listening to music \nshort in height a bit over weight wide hips short arms big thighs small hands hard worker helps friends helps children goes out of her way to be kind reliable \nshe looks irish with short blonde hair blue eyes and a small mouth her nose is small she has freckles she has probably worked retail she is most likely college educated from middle america she is pretty but a little plain probably has a boyfriend \nhe s got a short and newly growing in beard with a mustache he s got bushy eyebrows and short straight hair his eyes are bright and wide and his ears are very close to his head his nose is long and thin he seems fun loving and kind of laid back he doesn t get too worked up over things and likes to keep his life simple and easy going \nvery light white skin with dark brown hair and blue eyes clean shaven with stern jawline takes his work seriously works well alone friendly outgoing personality responsible person \nbigger nose decently kept hair the left side of the photo shows his face being a little more lifted than his right notice his nose being a little higher his top eyelid being a little larger and eyebrow being higher aswell his home is probably a little messy not bad he works hard he s smart and curious and i think those traits drive him to do well \nhe is fairly tall with brown hair and brown eyes he likes to keep a five o clock shadow his hair is short he is white he has fairly long sideburns his weight is average for his height he likes to play videogames he also enjoys watching football he currently has an it support desk job he is hoping to move up in the company he is friendly but extremely outgoing \ni bet this person is short around 5 5 he has a full head of hair and keeps his face clean shaven i would guess this person lives in a big city he looks like he would possibly be a teacher or possible a student i bet this person has a large family \nhe is 5 8 tall and 140 pounds medium build he has many friends and is a funny person likes to tell jokes he has average grades in school \nthis person appears to be an early 30 s female she appears to be of average weight and has a healthy appearance she has short reddish colored hair that appears to have darker roots she has hazel eyes average weight friendly dyes her hair original hair color was dark brown \n5 10 tall with an athletic build he is fairly hairy all over he has moves a lot even when he s standing still he likes to work out at the gym but doesn t play any sports \n5 ft 8 inches 200 pounds dark brown hair hair middle parted brown eyes blemishes on face he is a happy person he is married he is nerdy computer smart he issocially awkward he likes working \nwhite male with brown hair and green eyes thin beard with a nose ring on the left nostril tattoo artist unique single humble quiet has a few close friends \nthis is an attractive young lady in her mid to late twenties with short dark brown hair and brown eyes she has an olive complexion and a round face she wears her hair parted with the part just to her right of centerline she normally wears her hair over her ears she grew up in a broken home she is attracted to older men she can be difficult to get along with she is hard to please she loves animals she plays the piano very well she enjoys art museums she is polyamorous \nwhite male dark brown hair blue eyes longish sideburns unkempt eyebrows i find this impossible i dont like making assumptions about people based on how their face looks so i cant really guess anything other than he is a man with the traits described above \nabout 5 10 and medium build stands upright and tall and has good posture maybe has a couple of tattoos lower middle working class not college educated possibly ex military \ntall maybe 6 2 slender build physically fit but not muscular smart but not educated not outgoing or friendly has a lot of family who he is close with but is not close with many others doesn t really feel like he fits in with mainstream american culture \nthis woman is of ever so slightly larger build and approximately 5 6 in height this woman enjoys reading and school she doesn t have many friends but the friends she has are very close friends from her earlier years she is quiet yet has a lot of good ideas \nthis woman is possibly a mix of german and irish descent she is short probably 5 2 and a little chubby her proportions are otherwise normal she freckles when exposed to sunlight 1 she gets sunburned easily 2 she is highly talkative 3 she likes being sarcastic \nask police and other law enforcement agencies in the area where you believe the person disappeared to help you file a missing persons report provide as much detail as possible including any medical or dental records that could help establish an identity if a body is found if you believe the missing person may be dead ask if the coroner or medical examiner can take a dna sample from a family member \n6 tall 160 lbs broad shoulders big stomach long legs short torso medium arm length graduated works in retail likes to hang out with friends parties a lot \nthey are pretty short has a build body because they need to compensate for their height medium built plays a lot of video games has lax parents drinks and smokes pot does not shower \nfemale with light skin and blue eyes she has short brown hair with bangs she has a nose ring on she looks young and a little unkept looks like a gamer sort and likes body jewelry \nshe is white with brown hair and green eyes with little to no eyebrows and a wide bolubous nose and small lips with a slightly wide face she works as a manager she looks like she doesn t look happy she looks like the type that will cause a scene if something doesn t go her way mean irrational rude selfish and careless \nyoung white male blue eyes and light red hair slim can grow a full beard small build and stature does not tan lacks melanin \nmale honey brown eyes auburn deep brown hair bushy eyebrows stubble full jaw line slender to medium physical frame flared nostrils small thin lips this person is not happy with his life there is something missing in his day to day life he looks as if he s been wrong in some ways and he s not yet over whatever it was that hurt him \nshort and on the thinner side but not too thin she is unique she doesn t like to follow trends \nthis is a young woman with short dark brown hair they have bright blue eyes and wears blue eye shadow they have two piercings in their lower left ear they have an average nose and average lips they wear their hair so that only part of their bangs is covering their forehead they enjoy changing hairstyles frequently and enjoys playing around with various makeup styles they change nail colors frequently and wants to get more piercings they are somewhat shy but very loud and outgoing once you get to know them they get very emotional when drunk \nshe is about 5 feet 4 inches tall she needs to lose about 30 pounds she isn t completely out of shape but she does need work she s kind she is quick witted she is smart she wants to move up in her career she takes extra college courses at night \nwhite guy with brown hair and light blue eyes big nose small lips looks a bit serious i think he s a student doesn t have many friends and is a serious person he doesn t look friendly \naverage height about 6 foot moderately pitched voice not too high or low skinny proportional good with computers likes to spend time playing video games online slightly active few good friends \nthis is a young man with shaggy light brown hair and blue eyes he has a little bit of acne on his face he has a thin long nose and thick lips he enjoys being alone and enjoys being nonconformist he dislikes most people and most popular things he tends to think he s smarter than other people and is very sarcastic \nfemale aged 23 brown hair and brown eyes mixed asian and white races this person has lots of friends and is very social \nlong face with a flat chin tall nose with eyes that are a little close together has a very thin full beard he seems intelligent or at least likes to think about complicated topics probably mainly prefers being alone but does not mind communication he probably lives a very typical life \ntypical white female thin lips think eyes were caught in the middle of a blinke small nose hair in a ponytail she is very smart she has two kids she is very good at math she loves reading \nthis person is 6 feet tall medium build approximately 190 pounds this person is married with two children his wife works with him in the business he owns \nshe s tall and thin about 5 8 to 5 10 weighing 120 to 130 pounds although she appears to weigh less she has medium to long hair that she wears in a very tight bun to keep off her face she is careful about her grooming plucking her eyebrows carefully and dutifully removing any trace of facial hair she s a type a personality who has to have everything just so from her face to her desk at work she has to have everything a certain way as she can have anxiety otherwise she is very neat and clean and will not tolerate uncleanliness she has lost friends over her pickiness in the past so treasures the few friends that she has very dearly \nthis is a middle aged balding man not to big of a guy average build single accountant bland unsocial stays to himself like to read doesnt play sports gambles stays home alot goes to bed early leads a dull life \nthis person is white in their 30 s and has brown hair and blueish eyes this person doesn t have a lot of money this person may work at a grocery store maybe a cashier or something in that area this person can be nice when she wants to \nlong thin face large ears close to the head chin stubble thin lips uneven thin eyebrows uneven eyelids forehead wrinkles hair is thin and combed forward over forehead slow and takes things easy would be my guess doesn t let much upset him \nthey are of average height and weight no tattoos they don t walk with any sort of limp they don t wear jewelry they dress a bit more conservatively they exercise regularly \nshe is look like beautiful and it almost hair style are look smart she is not active at a moment to see the image \nthin built woman in her late 20s she looks healthy she likes wearing her hair up and doesn t wear too much makeup shy average intelligence good citizen good at her job maybe has a couple kids low maintenance nice person \na young 32 years old young white man thought semi built short brown hair and blue eyes tough resistant appealing angry repellant considerate revengeful sad worried concerned leader mature \nthis person is tall about 6 average build and average weight this person is very trustworthy he is kind and has many friends \nhandsome i like his beard and black hair his eyes look worried so does his face he is a teacher i can guese from the look in his face that he is a teacher who teaches high school \na latin american male with black hair and brown eyes in their 30s they are kind but like to take charge their quick temper sometimess gets them into trouble they are shy but like to mingle with those they are already close to \na determined look on his face he has longer hair a nose ring and a tight upper lip he s a guy that likes to have fun and party he cares about work and making money but i think there is something that he would rather be doing with his life \nhe has brown hair and eyes and a crooked nose it looks like it s been broken and causes the rest of his face to look a bit off kilter has been in a fight clumsy good vision arrogant attitude \nblonde hair thin eyebrows grey eyes sharp nose round face small lips calm nature deep thinker mother wife professionally stable intelligent person \na little chubby and short about 5 4 likes to show off her body so she wears tight lower jeans and crop tops very friendly and humorous outgoing and likes to party alot very responsible when it comes to her job and responsibilities \nhe has blue eyes shaggy blonde hair he has full lips that make a bow his nose is a bit weird and he has big nostriles works a lot plays video games anti social hangs out at malls plays dnd \nlooking little bit attractive and having blurred face having more spotting skin having strong knowledgeable person having more attitude and lots of anger \nwhite male with short black hair he has longer sideburns he has brown eyes angry competitive argumentative liar scammer likes to play mean jokes on people \na man in his mid 30 s with short standard brown hair he s got a longer face and ears that stick out his eyebrows are straight rather than curved he s got thin lips and little facial hair he s freckled smokes weed plays call of duty single wanted to join the army but was not physically good enough \nthis person is strong but out of shape due to smoking and drinking this person has poor posture this person has body odor angry drinks alcohol lonely depressed lives in a city has a studio apartment financial issues \nshe is a tad bit chubby she has big eyes she has a pleasant expression on her face she is short she is friendly to people she trusts others she has a few good friends and many acquaintances \nadult male between the age of 27 40 dark tanned skin dark hair dark eyes larger nose protruding ears goatee and mustache i can guess the person grooms his facial hair i can guess he likely has no facial piercings or tattoos i can guess he has facial scarring \nblond short hair with brown eyes bushy eye brows big ears and his eyes are a little too far apart his nose is round at the tip hes a jerk super smug doesn t get a long with people grew up poor makes trouble uneducated \nslightly over weight white female in her mid 30s brown hair brown eyes she is nice she serves food she likes food she cooks a lot she is married to a man she works in a cafeteria \nbased on this person s face feature this person belong to very slim type of person below is my short list of my guessing this person seems not too friendly and can be mean sometimes \nthey would be an athletic build they would be tall and slim they would have the build of a runner they would be a very kind person they would be a bit awkward socially they would always be willing to help others \nhe has pale skin and hazel eyes that tend to look greener with certain clothes his eyebrows are messy and he has a patch of stubble above his small upper lip he also has fairly small ears with a slight point to them at the top he has tried growing a goatee and mustache on more than one occasion unsuccessfully he plays video games his grades are barely a c because he s just lazy he is spoiled and expect things given to him \nthey have average facial features but slight thicker lips and thin eyebrows ear length thinning grey white hair there older they look hard headed they have had an ok life they are staring to loose hair \ntypical height of a women her age about 5 7 wears high wedge heels and summer classy dreeses for work has a very strong character not everyone likes her can shout alot and very bossy its close to her family member and doesnt make friends that close \nslightly overweight plain straight hair smooth skin pierced ears wide face kind of bratty likes to shop c student has a boyfriend \nthis woman is about 5 4 and of average build and proportions she is often tan from sunbathing her hair is naturally brunette but she dyes it blonde 1 she is usually a very friendly person 2 she likes to drink coffee 3 she likes dogs \nhe is tall average body shape he may manipulate at times he is more or less successful businessman he is married having kids he drinks frequently smokes too he loves his children taking them out frequently he may have affair with some other married women \nformal dress loves to wear handsome and respect full man reliable person trustworthy but selfish man he try to respect others but all are fake \nshe is short she is skinny has freckles has short noise and small lips she is responsible she doesn t sleep around she is reserved has a few friends \ncould be around 150 lbs and 5 10 skinner than he should be likes to socialize likes going to parties loves being surrounded by friends likes to drink wines probably an upper class person probably single \na white female with short dark brown hair and brown eyes she is from middle class she has kids she is married \nthis is an average looking caucasian woman who is probably either from the us uk or aus she looks like she has acne but has pretty eyes and a nice smile i m guessing she is reasonably bright maybe in school mostly happy has a boyfriend and loves spending time with her friends and family \nthis man has a thin nose eyes that are close together normal size ears a small mouth and a short head his eyebrows match his hair i think that they are relatively quiet like to play video games and watch movies \nhe looks to be very tall and has long hair he also has clear face and helpful in his field sales person smart tall long hair funny interesting \nthis person is an average weight build and height for a female she is around 5 4 and 130 145 pounds she may have one tattoo that is visable hidden anti social argumentative cold quick to judgement fierce tongue when confronted will not back down shows no fear \nthis person has brown hair and hazel eyes she is neat and tidy and cares about her appearance her face is oval shaped and her hair is short this person is a hardworking and caring individual she deeply cares about others and goes out of her way to take care of people she has lots of friends and is very sociable \nhair is too long and hanging in his eyes start of a beard and mustache has long side burns stays up late per bangs under the eyes no laugh lines so busy can t clean himself up ie haircut shave or is so lazy he does not clean himself up determined from the set of the jaw works hard for what he needs \nabove average height slightly overweight but otherwise healthy black hair blue eyes married with children slightly conservative religious educated with a middle class job minor police record misdemeanors and traffic tickets \na rounded pretty face brown hair brown eyes perfectly shaped nose she s clearly very intelligent educated and accomplished also very pretty she probably has a lot of money i d say she gives to charity \nwhen i saw the image this is a female face this face age approximately age 30 above her profession may be she is a teacher she is a good person her facial expression is very silent so she very silent type this female is a very sensitive person and very silent person his facial expression shows she is a good lady and characters are very genuine \nthis person has brown and blue hair they have acne on their forehead and around their chin area they have pinkish cheeks they have ears that point outward their nose is typical looking and long they have facial hair stubble around their chin area they have thin eyebrows that curve downward they are extroverted they are rebellious and like to break rules they have a serious problem with authority this person has most likely been to jail or prison this person probably likes manual labor this person has a tendency to be rude \nhe has unmistakable bold head with few hairs in the back he has blue eyes and has a nose that s not positioned in the center of his face he could be someone who follows order cause he doesn t look smart nor dumb so he s a normal folk \nlong thin hair could be called shaggy long sideburns budding mustache but not old enough for growing one average build with little fat or muscle tone likely 5 7 5 8 approximately 150 170lbs smokes cannabis relishes the cosmic activities loves lsd and psilocybin wishes he were born in the 50 s loves grateful dead and classic rock indivualistic happy non biased and believes in peace and love above all else \nfemale with fair skin short blonde hair light blue eyes light eyebrows wide nose she is an extrovert she is very organized and likes to have things under control probably has a few kids \nbrown hair highlighted with brown eyes and pale skin probably in there early 20 s cares a lot what they look like and what they wear worries about what people think of them \nthis man has black hair and green eyes he looks to maybe have a gap between his front teeth i think this person hasn t decided what he wants to do with his life just yet i think he s working as a cashier or something while he decides his future \nthis person is very so beautiful and vey nice and manager is keep the worked him the person is knowledge full and excellent talent person then chiled very nice \nthe person has a thin nose and thin lips she has long blonde hair that she keeps pulled back in a ponytail she looks to have hazel or light green eyes she is white with slightly tanned skin she is studying education and wants to be a teacher she has a boyfriend she was a cheerleader in high school she grew up in the suburbs \nsleepy brown eyes thick black eyebrows gels his hair to stick up widow s peak full lips freckle above his lip on the right side likes to get stoned every day good student listens to a lot of music from his home country likes to play video games and eat pizza with friends \nthis person appears to be average height but stout with perhaps a muscular build he has somewhat pale skin that has a few blemishes i guess this person has an aggressive personality and enjoys watching sports and drinking \nthey re relatively heavy set and short they have a rectangular face and inset eyes their lips are very thin and eyebrows nearly non existent they re a bit shy and not super clever they re stubborn and prone to be emotional \nshort probably about 5 3 and really small frame very thin and has a high pitched voice athletic or enjoys dance has a boyfriend likes clothing and shopping enjoys socializing \na regular looking blonde eyed white man he has a normal clean shaven face and fairly typical haircut this guy parties on weekends but maintains a pretty typical life on weekdays shops at the gap \nshe is 5 3 and very small for her frame she has firm muscles and wears a 6 5 shoe she works out daily she works in a law office as a paralegal and attends school at night in hopes of getting her law degree \npale skin short hair balding flush face and a goatee he is someone who has some friends and has a 9 5 regularly \nhe is 20 years old good looking person and like college student may be studied in first year of college he is student in some school or college good looking person and very young \nauburn hair with side swept bangs blue eyes with shaped eyebrows symmetrical nose and full lips oval face and light dusting of freckles she is a young girl starting a career probably likes animals and kids seems friendly \nhe is 5 7 tall and weighs 135 pounds he has light facial hair mustache and goatee he is a computer technician he is smart and very good at his job he is unmarried he likes to play sports in his free time \nhe has short brown hair and brown eyes slight 5 oclock shadow and long sideburns he looks like he is an honest dependable man \nwhite mid 20 s female green eyes brown parted hair soft white skin ears covered from hair she looks like she has a attitude she likes reading potential lazy eye o o \naverage height but a lanky build long oval face and ears close to head brown hair in a choppy style he has a ski slope nose and average lips he looks a bit like a stretched out version of ben wyatt from parks and rec a bit shy and soft spoken prone to wry humour a good listener and a bit submissive good as his job but not very ambitious probably a bit of a nerd \nwhite male blue green eyes soft chin slight facial hair he is of average height and weight student works a job i think that he is lower middle class and is trying to get ahead and learn a skill that will be valuable \nshort black hair cut above the ears almond shaped eyes looks asian slight mustache big bushy eyebrows this person is a mechanic at a local garage single no kids he likes fixing up his car and he loves stereo equipment and playing loud music he is hoping to own the garage someday \nshe has a short brown hair with a light face complexion her eyes are brown in color and her face is a little roundish and small she loves eating out at restaurants and loves pizza she loves playing video games and has a good collection of games she lives with her parents and is sometimes rude to her siblings \nthey are average height and average weight they have brown hair and blue eyes they have minor acne they have a job they have a car they work full time during the week they went to college \nthis person has terrible acne on their face they have short brown hair with a round face and large ears this person is a bit selfish and does not care about others he likes to go to bars in his free time and spend his off days laying around \nthis girl is a good looking young teenager who is well taken care of physically is not overweight has active lifestyle her parents are somewhat rich she is not shy and likes to sing and dance she has very faithful friends \nthick eyebrows with short hair strong chin large ears with sideburns medium sized nose this person enjoys his free time he craves getting off a stressful day of work to enjoy the rest of his day \nshaggy mop of straight brown hair worn long over the ears and parted on the left his nose is straight and high on his face very light facial hair he works in a physical industry e g construction plumbing he may have had his nose broken in a fight or an accident so has been active in his youth and may have done some boxing he is of average intelligence \nhe is 5 feet 8 inches tall he weighs 145lbs he is wearing blue jeans a plaid long sleeve shirt with the sleeves rolled up and construction boots he is a father of two girls he is currently engaged to his childrens mother he loves riding dirt bikes on the weekend \nrelatively healthy individual based on the tightness of their skin around their chin and cheeks clear complexion skin slightly receding hairline above his forehead has a slight goatee forming around his mouth the individual is from a lower middle class family they take care of themselves based on the individual s visible skin condition \nthis person is in good physical shape they have good hygiene and smooth skin smart confident tough athletic environmentally aware lesbian likes animals \ncalculating which is acting in a scheming and ruthlessly determined way analytical which is logical reasoning orrelating to or using analysis \nhe s thin and is tall about 6 he s not lazy but doesn t exert himself too much exercise is not his concern he s somewhat strict with his students and does not put up with disobedience \nthey are probably average weight and slightly taller at 5 8 she is probably mean or has a hard timemaking friends enjoys cats and spends a lot of time alone \nhe look is very decently he studied at school and he is decent guy his eye and brown short hair is identified this person \nblue eyes and very fair skin with red hair and freckles on the chin she is young and is still in elementary school she looks nice and is into dressup and makeup from the blue mascara she s wearing \nfair skinned red head with amber eyes and feminine features she is currently working on her phd to be a pediatrician most of her time is spent in the library and studying \nhe is about 5 6 235lbs slightly overweight not physically strong darker skinned smarter than what some would think slightly overweight but is okay with that wears nicer clothes and goes out a lot \nthis person has very fair skin and light hair with blue eyes they have a goatee and very clear and bright skin their bone structure is a bit feminine but you can easily tell they are male i think this person probably has a job where their appearance matters since they have a trendy type haircut \nthis person will be normal in height slim looking and has a good physic this person will be deep thinker worried a lot for simple things \nbrown skin with brown eyes and short dark brown hair serious hard worker quiet well spoken smart takes on a lot of responsibility \nthey are young they are a student they are male they are right handed they play video games they go to college they are in their 20 s they are nice they are friendly \nthis person is a woman she has beautiful brown eyes clean face and short black hair she likes partying is serious about her job sometimes goes for a run has a boyfriend \nthis person is a white female with brown hair and green eyes her hair is medium length this person might be short she doesn t look to friendly she is most likely a student \ni think that this person is probably between 175 180 pounds i think he has an athletic build he has brown hair and brown eyes he has a shadow from where he has shaved a mustache and partial beard on the lower half of his face he has deep set eyes with some puffiness around the bottoms and bushy eyebrows i think this person probably participates in sports i think this person is probably a freshman in college i would say that he likes to party and have fun with friends i think he would be a class clown \nhe has buzzed black hair with a wide forehead and receding hairline his ears stick out a bit but are small he s got dark bushy eyebrows and small beady eyes he has a short wide nose and narrow lips he s clean shaven but has a hint of five o clock shadow he seems quiet and shy he comes off as a bit of a loner and doesn t like crowds he has a bit of a temper and people think he s mean but it s really he s very shy \nthis person has an oval face and dark brown hair that is ear length and parted in the middle he has light brown eyes an average size of nose is clean shaven and has straight teeth he has a few blemishes on his skin particularly around his nose he is not outdoorsy and is quiet he appears to be someone that would enjoy craft beers and enjoys being around his friends i would guess that he engages in computer gaming and is most likely an rpg fan \nshe is very grade legend morevelous she is un reachable girl one of the more things important lesiously she grade one of the thigs about the person the making of sales previously manager \nthey have medium black hair they are average weight they have a large nose they like video games they like television shows they like board games \nshe is a caucasian female fair complexion brown hair brown eyes average height and build no visible tattoos she doesn t like to wear much makeup she s very calm and self possessed she doesn t like to spend much time on her hair \nhe is about 5 feet 8 inches tall and close to being obese he has short arms and small feet he looks like a fat clown he is very smart and good at observation he treats his friends with respect but is hard to get close to \nbrown hair brown eyes short hair rounded face normal ear structure they are of latino decent unhappy may be a janitor \nthis person physical description is slim maybe and tall in height maybe he works as part timer and goes to school or college \nthis person is average height and weight they have half full lips the nose is somewhat pointed but not abundantly so he has brown almond shaped eyes that are neither too big nor too small the hair is very very short but he s not bald and colour is black he loves rap music loves to dance loves to watch tv and might even get into the acting scene sometimes loves to party \nvery nice looking young man with dark hair and sexy brown eyes if he is not gay he is popular with the ladies if he is gay he is considered a great catch he probably went to college and has a degree depending on his parents wealth he may be deeply in debt and will be for years \nthis man has black hair with bushy eyebrows and a kind face this person enjoys playing soccer this person enjoys reading a good book this person like ice cream \nnice hair pretty eyes starting to show signs of aging and rather short likes taking care of people laughs a lot married has kids stressful job is nice to everyone \n5 feet 5 inches 150 pounds medium length light brown hair brown eyes roundish face small facial features thin eyebrows single not really that happy doesn t make a lot of money \nhe is an older man with an aging wife he hasb 3 children and 10 grandchildren he likes to fish on his days off he has a beautiful yard grumpy loved by his family hard of hearing not a lot of friends retired heart problems \nthis person is stocky to a slightly overweight he is tall this person has a social personality he has a short temper and gets easily upset he has a few close friends that he enjoys playing video games with \nthis person is a young white female with short hair green eyes and a slightly round face this person likes thai food and independent film this person has two cats and likes to hang out with friends on the weekends \ntall white skinny male he has short brown hair and eyes he is a college student and lives on campus college is paid for by parents and he has a girlfriend \na white light skinned woman with dark brown curly hair and brown eyes her hair is short and the curls are tighter than is naturally common looks very done up kind of like would be expected of a model but she doesn t actually have the features of a model so i would guess someone who cares a great deal about her appearance her makeup style is very subtle though so she probably wants to look naturally pretty while still putting in effort \nhe has pretty eyes a small sharp nose is slightly heavy and is short rather smart short quiet recently married heterosexual no kids owns a home decent job \nseems to be a young male in their late teens most likely a healthy build they are in high school they are relatively normal and try to fit in \nthis is a white male with short brown hair he has blue eyes and somewhat shaggy brown eyebrows he has a very light beard moustache growing in perhaps 2 or 3 days worth of shaving he has small ears he s sensitive he s not especially vain about his looks he s just getting started on a career \ntall wide frame a bit off putting stares at others a bit too intensely slightly overweight generally means well not very sociable or socially aware once had artistic ambitions \nthe bestselling authors include this information when telling the reader something else something more meaningful about the hero there is a mountain of meaning buried in those eight words sure change the sequence and you change the meaning but as long as you don t screw with that framework people will stay with you \nthis is a female in her lower 30 s she has a above average build and is slightly overweight they have brown hair and amber colored eyes they are caucasian this person appears insecure about a couple of things and because of that they are introverted they like keeping to themselves and don t have too many friends \nhas a nose piercing and she has blue eyes keeps her hair in a ponytail and have small ears and lips she likes emo she likes to smoke she likes to wear black she likes to drink she likes to party \nthis person is a white male with on oblong head he has brown hair and blue eyes his hair is medium length and has side burns he is clean shaven and has a long chin this person is tall this person is a student this person looks sneaky and untrustworthy \nhe is typical indian with short hair and oval shaped face seems from a middle class family seems to work in service class educated \nthis picture is a female lady in her late thirties with a brown color hair this girl seems furious by nature attentive and foxy in nature \nthis woman has a slightly broad face she has green eyes short length blonde hair possibly shoulder length a short cut chin slightly thick ear lobes also a slightly large forehead she takes pride in her neatly tamed arched eye brows delicate sleek thin lips i feel her name would be something along the lines of susan or samantha if she smokes cigerettes she would smoke menthols i guess she likes to sit in and watch hbo at night probably true blood and game of thrones she looks as if she probably tried to be a vegan at some point \nbased on this woman face feature this person seems to belong the overweight type of person below is my short list of my guessing this person seems to be warm to other people she seems friendly and has soft personality \ncaucian female mid late twenties medium length red hair small mouth and nose green eyes i bet she has read a lot she seems sad probably doesn t drive and owns a lot of black \nyoung caucasian male with short brown hair and hazel eyes smallish mouth small mole on right eyebrow i would guess this man is a student or at least around that age he has taken some care with his appearance hair gel \nmale mid twenties fair skin average physical build blue eyes short brown hair above average education privileged background white collar job healthy sex life social animal good health \npossibly a little heavy maybe short in height she may not be very athletic in build in high school or middle school somewhat shy might like music a lot \nregular build and height wears average clothing and shoes nothing stands out he has a part time job at his school likes to study as much as possible hangs out with his friends when he has time helps his parents at home when he can is focused on his future \nthis person has somewhat defined cheeks somewhat pointy ears and a chiseled jawline the forehead is slightly elongated this person is very outgoing and likely joined or at least pledged in a fraternity he does go to the gym but mostly runs he likes dogs enjoys the city he s travelled outside of the united states at least once \nthis person looking good and nice look and see is look for actor this person looking for manager for the company and also married person \nshe s fit and of average build she has small breasts but fairly broad hips and rather thick thighs she has very small hands and feet she has a short neck and brown skin even in winters she usually picks short hairstyles she s a very active person and do exercise very often she likes a lot being around kids she doesn t get along at all with one or several family members she is a bit cyclothymic she is a lesbian \nshe is short fat short blonde hair gray blue eyes her faces has some freckles and big nose she is a stay at home mom with 2 kids her husbands works for corporation she is bored with her life and husband \nit is a young woman with short brown hair she has arched brown eyebrows and brown eyes she is wearing eyeliner she has several ear piercings her nose is slightly crooked she is good at art she is creative she has unique fashion sense she grew up in a relatively wealthy family \ndark brown hair worn long over the ears parted at the left he has dark blue eyes and wears a nose ring in his left nostril he has a light mustache and beard including sideburns this person works outside and is of average intelligence he tends to be defensive and a bit antisocial he attended a vocational or technical school after leaving high school but does not have a university degree or other advanced education \nwhite male early twenties green eyes and brown hair with frosted tips listens to punk rock music likes cars is bisexual lives with parents spends a lot of time on the internet has right wing leanings \nthe person is a white male average build with black or very dark brown hair that is slightly receding above his forehead and brown eyes he has chapped lips and some acne forming on top of his nose he is probably a middle class individual based on the condition of his skin \nhe is lean his bmi may indicate he is under weight he has curvy back bone and bends while walking he loves to study hard he is good at math he enjoys studying and doing white color job \nan average looking male who has freckles and a slight goatee enjoys hanging out with friends likes to drink and go out \nshaggy black hair with a 5 oclock shadow for facial hair in addition to hazel eyes this person is a student and part time employee this person likes rock n roll music and going to concerts \nold woman with blonde white aging hair has blue eyes and white pale skin most likely has grandchildren and works as a caretaker either at home could possibly be a teacher must have been very pretty when young \noval shaped head with short hair faded eyebrows shortsighted eyes long nose and a white spongy skin she may be a teacher or an employer she must be around aging 40 with children looking ready to start for work \nthis person is average height and well built with blonde hair shaved close to the skull and blue eyes he has average fairly symmetrical features and full lips he enjoys working out and doing things outdoors he is considered a tough guy and a man s man he is fairly quiet and has a few close friends \na young woman of average built with brown eyes and blonde hair financial status video games played height weight music accent religion education level marital status shopping preferences race friends social class gender hobbies career friends country of birth nationality obsessions sports sex passion \nshe look like a woman work in health department or a nurse provate hospital look like angry unfriendly person un talkative self ego person \nthis person has a happy looking face with soft features she has a think build and is short in height she is friendly smart pretty active and loves fashion she is a good student and participates in multiple extra curricular activities \nmale late twenties blue eyes somewhat square jaw some whisker stubble intense looking he is very competitive and working his way through the legal profession to someday become a full blown attorney he is passionate about his career goals and is very intent on achieving them regardless of what obstacles may be in his way \nshe is a young woman with black hair and brown eyes she looks like someone who is currently writing a novel but doesn t want to show it to anyone yet \nthey have short brown hair large brown eyes that are slightly down turned they have small somewhat pointy ears and semi full lips their face shape is kind of a defined oval shape they have a slight cleft in their chin they are capable they are kind they are intelligent they can adapt to new situations well \nmight be belong to below average class look like indian used to be good student look like educated work in a computer or technology field enthusiastic person \nthey are fat with blue eyes they have short to shaggy hair they have an intense gaze they play a lot of video games they complain they like trump because they hate liberals \nmedium to dark skin tone with dark hair and brown eyes stubble on the chin and upper lip with eyes that are closer together very quiet man and stays out of trouble cares about his family and works hard for them \nyoung male approximately 18 years old with short brown hair no facial hair and grayish blue eyes probably just finishing high school enjoys sports and outdoor activities likes video games church and taking care of family \nthis person has dirty blonde hair that is somewhat curly and medium in length also blue eyes and a common type face this person has a somewhat fair complexion with some acne and blemished skin throughout the chin area likely skinny to medium in stature likely just finished college and currently in search of a job seems to be the type of person who likes running cross country marathons likes hanging out with friends movies concerts etc \nsomewhat muscled brown eyes brown hair unkempt hair slightly intimidating gaze linebacker popular drinks lots of beer drives a truck likes eating a lot doesn t think too much about deep things \nsmall mouth with a round head blonde hair part to the side her eyebrows are awkwardly shaped fast food worker not happy with life not too smart in trouble with the law \nthis is a male with red hair and blue eyes i think this person is a college student i think their major is in business i think he hangs out with his friends in his spare time \nthis person is slightly overweight but pretty much average for americans average height average for americans muscle tone and fitness level my guess is she is american possibly midwestern probably married or at least in a steady heterosexual relationship she may have one or at most two young children but more likely she has not yet had any children she is hard working and close to her family \nwhite female in her mid to late 20s blonde hair likely tied behind head and blue eyes small high set mouth and a round face soft eyebrows she wears a simple hair style so either she doesn t care much about standing out or she works in a professional where practicality is more important some people might call her baby faced she does not seem like the carefree type \nslightly overweight and short has a lax style and probably bad hygiene plays video games with the few friends he has spends little time socializing unless going to work \nthey are cute but a bit fat overweight but is well they don t make much don t have a lot of money \nthis person wears down to earth clothes in browns and greens is 5 10 average build weight this person is slightly uncoordinated and a little goofy when it comes to talking with girls \nis short slightly larger build wears nicer casual clothes looks a little more professional than the average person on his off time looks very professional at work he holds a managerial position at his job and is focused on climbing up even more he has a family that he works hard to provide for he likes to spend relaxing time with his family on the weekend he like to just hang out and watch tv at night \nthis person is a little bit chubby and average height this person loves animals she is very social caring and compassionate she has a high degree of empathy \nhe has a birthmark on his right cheek his ears are somewhat larger than average his hair is black or dark brown and cut short he has a little bit of stubble his expression looks sad he might be of mixed race his sideburns are long he probably grew up poor and is still poor he probably faces discrimination he is a muslim he might be self conscious about the birthmark \nshe is an attractive white 32 year old female with light brown hair and brown eyes she works as a nurse she is sweet attentive creative calm reserved and quiet \nno one is ever prepared for the nightmare that comes when someone you love goes missing as the left for dead investigation shows families can wait decades without knowing what really happened on television police shows tell us that cold cases can be solved in under an hour in real life police and coroners may not have the tools time or expertise to pursue a case where clues are few or nonexistent on television police shows tell us that cold cases can be solved in under an hour in real life police and coroners may not have the tools time or expertise to pursue a case where clues are few or nonexistent \naverage height build white female adult medium length strawberry blond hair graduated high school in college likes puppies cats and babies enjoys reading and hiking \n24 year old female black hair brown eyes 5 foot 7 inches college student polite caring single likes books likes horses plays a sport \nthicker of a body on the verge of being fit has a baby face plays sports but is not very good probably a student in college goes to the gym but any progress if offset by the beer he drinks probably wears a flat brim hat \nthey are tall and lanky a little underweight has long limbs and walks in a funny fashion they dont stick to their job for a long time lives with a roommate does not have a girlfriend shy \nbrown short hair blue eyes freckles thin eyebrows thin lips pierced ears friendly in her 20s easy going a happy person easy to get along with \nshe will be looks an so good and the beatiful and the will be good attitude and wear ear rings the lady will be looks an so good and the beatiful and the will be good attitude and wear ear rings beatiful \nthey have a wide face with a small mouth their ears are small they have a slight cleft in their chin and 3 moles by their mouth they have light brown eyes and a short nose their skin is a little tan they have many friends they are funny they like their job they have a big family they talk loudly \nhe has a bit of an aggressive look with judgmental eyes his face is a bit round and he has hair that covers his eyebrows and the tops of his ears he has green eyes and a straight mouth and a wide nose bridge he works a blue collar job he has few friends he enjoys vide games and other solitary activities \nthis person looks like a man but it s kind of hard to tell they have red hair and blue eyes they are probably upset at their lot in life and feel they have not gotten a fair shake on account of being a ginger \nlong dirty blonde hair for a male bushy eyebrows average nose 5 00 shadow beard attached earlobes he is a young adult he has an average or below average income occupation he is generally apathetic towards most things \nshe is about 5 4 and pear shaped she has longer hair that she typically keeps up in a pony tail when she is working she has short arms that are relatively muscular she is probably single and likes to read in her spare time as well as watch netflix reruns she has a small circle of friends and is relatively introverted \nyoung white female with fair skin short black hair that s parted on the side blue eyes think eyebrows wearing what looks to be some sort of glossy light pink lipstick likes spending time with friends enjoys listening to music is fond of movies and tv likes to read enjoys learning new things is usually kind and considerate to others \nthe man is average height slim with short brown hair he has brown eyes and small ears he has a wide forehead and small thin lips his nose is slightly crooked he is young arrogant nice looking and a bit smug he thinks he s charming and handsome and is a bit cocky and overbearing \nthe person has short cropped brown hair with piercing gray eyes and oval face the person seems to be serious and dedicated he seems to be hardwoking \n5 foot 6 black hair brown eyes slight limp from a childhood injury has a limp likes soccer drinks beer but not hard spirits enjoys fifa on his ps4 \ntall with long slinky arms tattao on the back of his left or right claves married has kids have 2 dogs likes to fish hunting and working out \nshe look like sales women like she was middle height and wear court she hair style like sales person lot of sales person same look \nshe has wavy dirty blonde hair thin eyebrows and heavy eyelids over blue eyes she has slight freckles on her cheeks which are quite chubby and thin lips she also has a slight dimple on her chin likes food doesn t exercise a lot possible diabetic likes to shop \n5 foot 6 inches suffers from resting b face blonde hair green eyes enjoys demanding to speak to a manager shops at dollar general drives a geo two children single \nmale 20 years of age medium length black hair with bangs dark brown eyes eyebrows come up to a point as they go out wide nose nostrils scanty facial hair detatched ear lobes thin lips person is a janitor at a hospital person is a soccer player \nthis person has an athletic body type and is about 6 i think this person played high school football and is a hard worker but doesn t like school \nwoman with dirty brown hair green eyes and freckles thin lips and fair skin she is middled aged she is often times serious but can laugh \na caucasian male with a buzz cut he has dark brown hair and dark brown eyes he also has a little bit of stubble is a bit sleazy and untrustworthy doesn t care about anybody but themselves manipulative \nthin lips brown eyes receding hairline light brown hair looks fit he looks mysterious unorthodox determined hard working manipulating and very smart \nthe person is of average height and build not particularly athletic the person is likely to be sedentary during their free time and does not engage in many physical activities the person is likely to be employed in the services industry while pursing higher education the person is conformist and does not like to stand out from others and avoids calling attention to herself in social situations \nhe is a bit more fit compared to the average person he is not extremely tall but he is not short either probably around 5 11 he likes to keep to himself a lot kind of anti social but not in a mean way treats people with the respect they deserve he s not afraid to call someone out on their actions \nbrown hair blue eyes fair skin wrinkles around the eyes and mouth shorter hair that might be pulled back married possibly with kids works in medical field living suburban life does craft things in free time \nthis girl have a average body type charming and smiling face may be her height is short with normal weight bob cut hairstyle and black color eyes this girl may be student in bachelor of arts having a good sense of humor very jovial type girl she is very industrious she works really hard at his job very bold type \nthis person is a bit overweight and carries a lot of the weight in his stomach he s a bit on the short side like maybe 5 8 he s got really hairy arms he has a poor diet he has a bit of a temper he is outspoken he doesn t especially enjoy being outdoors he doesn t laugh out loud a lot \nescription of this person excluding their clothes escription of this person excluding their clothes escription of this person excluding their clothes escription of this person excluding their clothes \nshe will be looks an good and the simple manner and so beatiful looks like an working an professional the person will be working on the company sideso beatiful looks like an working an area \nf you had to describe somebody could you or meet someone who impressed you but when asked found yourself unable to describe them that means you need to write damn good sentences without even thinking about it day in and day out \nhe is at least 6 3 he weighs under 180 pounds he has a lean lanky physique he is anorexic he loves cocaine he smokes cigarettes to curb his appetite \nlight skinned black woman short hair wide nose full lips eyes far apart she graduated at the top of her class she makes lots of money she respects all life she is an outstanding citizen \nmale mid 30 s black hair brown hair fair skin average physical build blue collar worker night club regular multiple jobs afraid of commitment in relationship poor education average upbringing \na middle aged woman with black bangs over her eyelashes and brown eyes has a dark spot on her nose and has wide set eyes she enjoy s her daily routine takes care of her body and plucks her eye brows often \nlight hair concerned expression rosy cheeks green eyes minor aging strict contemptuous disappointed about the way europe has turned out \nmale 19 years of age medium length brown hair hazel eyes oval face 5 o clock shadow narrow nose bridge with a large tipped nose eyes set average length apart person is a student at a university parents are divorced owns a secondhand car \nhe looks like a student his age should be between 20 to 22 his eyes are very attractive he is not reached age to go to work he should be studying \na female has simple face with natural blonde hair and hazel eyes a serious type of person she have more responsibilities and do work very carefully \nhas really good looking hair brown eyes medium build and light skin tone probably is in a band and is a guitarist or a soloist because of his hair \nthis man has a high forehead with low sitting dark eyebrows that are almost an unibrow his eyes are blue and almond shaped he has a larger than average nose that appears to be slightly hooked and looks like he may of broken it before he has a beauty mark on his right cheek his mouth opening looks small but lips itself are of average fullness his hair is longer on the front and appears to be fluffed up this man is shorter than 5 10 he went to college he doesn t live at home he probably lives in a good sized city \nblonde hair blue eyes she is probably 5 5 foot tall weighing around 130 pounds intelligent outgoing loyal trusting has children married went to college she loves to shop enjoys the outdoors \nthey are average height they are slightly overweight they have brown eyes and brown hair they have a full time job they live somewhere with public transportation \nthis person is probaly overwieght and probaly has 2 kids and a house in the suburbs republican a man who thinks he is the smartest person inthe room someone who thinks he can control the people around him through force of will \nhispanic female in their early 30s probably long hair which is brown or black with many brown highlights her eyes are brown and she has thin eyebrows early 30s american or maybe from south central america almost certainly some native american blood somewhat guarded expression \npeople often speak of the color of eyes as if that were of importance yet his would be beautiful in any shade from them comes an intensity an honesty a gentleness perhaps this is what is meant by a gentleman not one of weakness or trite politeness but one of great spirit and noble ways what he is what is beautiful about him this person is trustworthy not selfish and cooperative he is not harmful for any kind of person he is reliable honest friendly kindhearted intelligent \nthis is a woman with long hair that is pulled back and a fair rosy complexion and a wide face and flat nose i could guess perhaps the gender occupation ethnic background and obvious visual characteristics but not much else given just this person s face \nhe has a tiny bit of facial hair he has a medium sized nose blue eyes semi long hair and a strong jaw line i think he likes to surf and hang out with his friends i think he is good enough to compete all over the world \nbit hairy about 200 pounds about 6 feet tall works a full time job drives to work has a stressful life \nthis person is 5 2 weighs 180 pounds her shoe size is 6 5 she enjoys reading biking and going to movies she is not married and has three cats that she calls her furbabies she is a teacher so she is very busy \nshe looks normal and have a humble face she is nice and friendly she is a mom of 2 children she is an immigrant she is not very smart \nhe has a distorted shaped face with light mustache and very small ears he looks quite strange and weird belongs to small business family smart by mind to get success in life manages work easily aims high \nhe is slightly overweight and has really pale skin which burns easily when exposed to sun he likes to go clubbing whenever he can because he is still single \nhe is tall around 6 feet he has a big body frame and is slightly chubby smart shy curious kind helpful hardworking focused unselfish introvert calm capable compassionate creative indecisive disciplined educated \nwe ve touched on some elements of the hero s description for example we know that the hero is generally better looking than he thinks but i think it s worth our while to look more closely on how and when to slip the description into the narrative here are 6 elements to include when writing a physical description of your hero the girl is very useful to normal dress and guess normaly real women \nthis person has soft skin large breasts long legs and a nice voice this person has tattoos married with one child works in an office goes to the gym comes from a middle class family but not wealthy \nthis person has dark features which include skin color hair and eyes this person is likely not into facial grooming because his eyebrows are connecting which points to this individual not being superficial or too concerned about norms society places on beauty \naverage build neither thin nor overweight average height around 5 5 deep brown eyes dark brown hair well kept disciplined respectful towards others loyal hard working kind intelligent diligent responsible not very laid back cannot take criticism well \nthe person has darker skin eyes and hair and looks like he is hispanic likes music and tv and eating good food they probably also like to hang out with their friends and have a good time \nmedium height somewhat long red hair medium heavy build blue eyes light complexion works in service or customer service probably near the poverty line nervous values their friendships \ni think she is short and slightly overweight she is somewhat pale and may have an achne condition i think she looks friendly i get the sense she may be italian or have relatives from that region due to her weight i don t think she is physically active she has a lot of friends and likes to gossip \na long faced person with unruly blond curly hair and a large nose thin lips and a big chin there s a freckle near his nose average weight clean shaven not a lot of time outside a little angry doesn t spend much time on his appearance reads a lot dresses casual \nhe s a 5 10 kind of guy he s chubby he s got kind of a beer belly going on he s married he s unhappy he teaches at a university and hates it \nbrown hair blue eyes light eyebrows slightly scruffy small lips scrawny always looks angry greasy hair he has anger management issues smells weird earwax buildup likes loud music and video games has trouble getting dates \nshe has a teardrop shaped face with a mole under her eyes she seems to be sincere hardworking and dedicated person \nhe weights 220 pounds he likes dressup and combs hair regularly he likes his spouse very much he is jealous and works hard he likes to drive fast cars \ncaucasian latina plump medium height black hair brown eyes tattoo near left ankle scar on right thumb graduated first in her high school class wanted to be a doctor but couldn t afford med school is in a committed relationship is considered an excellent nurse and caregiver \nwhite slighty pudgy face hair is styled into a point freckles on his face he seems happy office job heterosexual college education lives with mother has a small group of friends \nblack hair blue eyes and no facial hair average height and athletic build enjoys sports and skate boarding is currently in college and is outgoing person is friendly and willing to help others out \nthis is a white male that has brown hair and brown eyes they have some brown facial hair their hair is short this person has a girlfriend this person is muscular this person likes video games this person gets angry sometimes \ncute white female dark hair light brown eyes big nose thing lips hair held back squared face she loves horses she is pretty good at swimming she enjoys going to the movies she likes to sleep \nshe was wearing blue jens and t shirt very nice this hair style like college lecture or teacher good look eyes \nan unshaped head with crew cut hair style and some tiny marks looking bright skinny opened ears short eyes long thick eyebrows turned up nose shaved irregular chin short lips may be scientist or a phd in research may be married looking bright and spongy \nthe woman has white skin brown hair down to the length of her jaw and brown eyes she has a few light blemishes spreading across her cheeks chin and forehead with small lips she appears to be in her early 30s she looks like she keeps to herself but with friends and family she is very out going friendly sweet caring and fun she may not look approachable but she is when someone gets to know or talk to her \nthis person is very tall has long arms and skinny legs and he is very hairy this person prefers their own company they do not like kids much and they like to play video games \nthey look old and wore down by life and and not very attractive i guess they are old and they have acen on their face for some reason \nthis person is heavyset and has a pudgy face he doesn t have facial hair and has short hair he enjoys to spend time playing role playing games and watching science fiction he likes to do things that are relaxing \nthis young woman has big warm chestnut brown eyes she has short brown hair and a rounded face her lips are full and pink loves animals and has several pets loves dancing with her boyfriend loves horror movies and owns many dvd s loves to write fantasy novels \nthis is a young student in high school or middle school they are in middle or high school they might be energetic hyper sometimes \nthis guy seems to be front middle east iraq or afganistan or somewhere there he s also bit of typical this is really difficult to guess for i have never personally dealt with someone from iraq but i guess people from there coming all the way to study in us must be exceptional in science or technology he could be some sort of engineer \nshort in stature roundish body type dark brown hair brown eyes pale skin caring and kind smart well liked hard working level headed no drama lifestyle pragmatic caretaker interested in science likes tv especially the hallmark channel kids love her pets love her saves her money owns her own car \nhe is a young boy with a skinny body short hair and a bit tall he is a boy that likes tp lay sports and have a loving caring attitude \nshe has blond hair and grey eyes fair but clean skin she doesn t hurt for dates she makes enough money to afford a good haircut \nrelatively square probably very small in stature and not too tall doesn t weigh a lot and spends a lot of their time indoors student gamer likes to read books is into tech enjoys being with friends and watching television \nthis person is an average build he has basic facial features that don t really stand out he is not muscular at all he is not very smart he isn t friendly he most likely is a drug user of some type he didn t finish school he works at a grocery store \nshe is brown haired brown eyed female she has straight hair the seems to be tied her hair is slightly swept to her left she has small lips and has a small bump on her skin just below her left eye she has thin eyebrows she seems to be of a relatively thin build she probably enjoys watching movies and going out with her friends she is outspoken and a bit of an extrovert she probably engages in introspection \ngood attractive smart enough blue eyes that give make attraction looks so dull and not so curious about his future hope he has lot of worries in his mind \nthey are what people would describe as an average person they work out every other week or so which allows them to stay in average shape and not get too out of shape they wash their face and hair well \nthis person has brown hair fair cool toned skin and brown eyes she has three visible piercings her lobes and cartilage the cartilage piercing may actually be two she has black eyeliner and mascara on she is rebellious and leads an alternative lifestyle she listens to rock music and changes up her look often she may have creative artistic hobbies or may be a writer \nbig nose blue eyes brown eyes very light skin hair styled heavy brow hair and a not amused look not bright at all looks like he will get into a fight \nhe is moderately tall about 5 foot eleven inches he is muscular and of average weight not over or under he works for a roofing contractor he works with a crew that replaces roofs on houses and other buildings he is not married and does not have children he has a girl friend that he lives with he likes to go out for pizza and to movies with his girl friend they have 2 dogs that he walks most evenings \nhe was looking old short black hair sharp long nose clean shaved face may be married person fun and jovial person in nature he loved by his family \na young woman with short dirty blond hair and blue eyes slightly below average height and smaller frame she is probably fairly popular and a cheerleader she is probably an extravert \nthis person has short brown hair and blue eyes with a symmetrical face this person likes playing soccer this person attends college this person has a loving family \na chubby woman who is probably short she s probably 5 feet 3 inches she is friendly she likes to go out she has lots of friends and likes to sunbathe \nthis person has medium length hair with brown eyes and a kind face this person loves to work hard at their job this person likes to treat themselves at the spa \na male in his late 30s of indian descent black hair and eyes with a round face possibly speaks english as a second language works in an office and is good with numbers \nshe is of average height and is somewhat overweight but is very attractive she has a lot of friends and frequently over promises on tasks and puts pressure on herself to accomplish what she promised she makes above average income and enjoys nights out \nthe face seems to indicate that this person is tall and skinny probably high school educated works multiple part time jobs single and never married \nknowing how to describe clothing in a story well will help you create bold the clothes a person wears tells us many things bad results can lead to bad decisions the very thing you set out to avoid by making a survey it s easy to begin the survey writing process by brainstorming a list of questions to as \ndistinct blue eyes slightly bushy but average eyebrows short ish brown hair facial hair that is well taken care of appears to have a triangle shape at his chin likes to shave his beard into various shapes possibly into artsy stuff \nshe is short around 5 3 she is slim and weighs around 127 pounds she isn t athletic so no muscle tone she is strict most of the time and serious she is an introvert but still has good friends \nhe is 5 7 tall and weighs 135 pounds he has no facial hair and no tattoos he is a married father of 3 girls he enjoys his job as a history teacher very much he has a jovial personality \nthey are a little taller then average not fat or skinny they are somewhat outgoing with a small group of friends doesn t socialize more outside of their circle of friends \nwhite female average height and weight for her age and race i dont know what to put here because the text disappeared \nshe is short about 5 3 and has a tiny build and is on the skinny side she has many friends she is kind of ditsy she gets along with everyone she meets \nby face he his looking very free minded person and very focused person my point view he is very friendly and funniest person \nhe seems tall guy weight should be around 50kg he looks very tired he should be father of one or more kids he should be working somewhere \nshe is probably slightly overweight and about 5 5 or a little taller i m guessing she is depressed about her life and doesn t have the money to get a college degree \ni think this is a rather heavy set gentleman he has a full face with brown hair that is mixed with gray he has brown eyes and full slightly puffy cheeks he has thin lips and a small chin i think this man probably is married with 2 3 children i think he probably is a high ranking employee in a company \nhe has a square face with thin lips and a larger forehead his eyes are a bit hooded and an odd shape he is young and carefree he is a bit arrogant and untraditional \nhe has a pear shaped face is clean shaven and looks like he has a pleasant personality he also looks very business like like he has a calm personality and his hair is very neat this person looks like someone that would get along well easily with others and looks like he could be involved in a business persuit such as stockbroker etc \nthey have a wide face with pale skin and high cheekbones they have dark thin straight hair they keep short and style unconventionally their nose and brow piercings interrupt and clash with what is otherwise a very soft face they played sports in high school and might play roller derby today but nothing else athletic they drink a lot of coffee but otherwise eschew typical feminine activities they don t have a great relationship with their parents \nbrown medium hair light chiseled hair on chin eyesbrows curve in loves football likes to go to hooters hates when people asks him questions \nface seems to indicate that this person is short and a bit stocky college educated with an advanced degree likely works a white collar job \nslightly overweight based on her slightly sagging skin by her chin and cheek shape her skin complexion is clear she is probably from a middle class family and has enough available cash to where she can get her hair done regularly by a professional \nthick black hair covering the tips of his ears narrow nose dark eyebrows but not excessively heavy some stubble but only enough that it looks like he may not have shaved this morning average mouth and average overall physical features this person is good natured and very personable he gets along well with others and makes friends easily he has a large social circle and enjoys spending time socializing he enjoys his job but is not especially career focused and may easily jump from job to job he may move about a bit depending on how he feels at any one time \nshort bleached blonde hair about 1 5 inches in length white and fair skin and complexion some stubble on chin and upper lip long sideburns that ended to bottom of ear lobes they are outgoing like to drink have fun attend concerts and listen to music \nthis person is of average appearance they are caucasian and have hazel eyes and brown hair they are female in gender expression they have flushed out cheeks steadfast personality probably not a comedian might be a member of clergy \nlarge outward facing ears acne short black hair with grey tips large nose upward facing jawline this person is religious this person has high standards this person is passionate this person is nice \nthis person is short and skinny she has a small frame and likes to keep her hair short she is funny and has a bubbly personality she smiles a lot she is stylish she changes hairstyles fairly often she is a good loyal friend she seeks others approval \nskinny white european male brown hair brown eyes long face pale skin short hair shaved dark eyebrows probably easter european skinny round 5 10 height kind and caring probably intelligent \nyoung white female with blonde hair and light blue eyes white skin with reddish features around the cheeks probably loves pop music outgoing science fiction fan liberal probably a hippy likes to surf the net a lot \nlikely has masculine features such as strong and broad shoulders but otherwise as average as you can get likely had a tough upbringing might have had to deal with fending for themselves far more than they d care to admit \nhis face is very white her hair style ice white rare this person is very calm and personality then i thought that the film was good \nshe has round face and things she is unattractive she likes to wear sporty clothes she loves hip hop and likes to go to the movies she enjoys pizza and loves her family \nthis is a picture of a female girl with brown hairs and sharp blue eyes this person is careful in nature seems sensible too hard working full of emotion driven \nwhite man around 47 years old he has black hair and he doesn t have a lot short hair on top and shorter on the sides he is shaved but his hair goes down until the middle of the ears his eyes are closed but they look black he has a thick nose and a very tiny lips looks like he is smiling but might be his neutral expression he looks intelligent and i would assume he has a management position doesn t look very sociable but i d guess he is funny when you get to know him he doesn t look a very active person \nas a kid i devoured girly series books like sweet valley and baby sitter s club in sweet valley high the twin protagonists were always described as having blond hair pacific blue eyes and perfect size six figures unfortunately i often find myself describing my own fictional characters as if i m ghost writing for a young adult series i give height hair color eye color and body shape but these standard descriptions can sound generic and they don t really help the reader picture your characters so how can you best describe your characters physical features learn from others here are a few tips along with examples from some of my favorite writers that s why thoughtful survey design is so important it ll help you get better trustworthy results here are some tips on how to build an effective survey starting with the one thing that s most important in a survey questions \nthey are probably average height and average build for a guy short shaved hair stubble on face blue eyes they are probably busy and a little curt but nice and friendly overall tired from working all the time but easy to get along with probably a gamer \nhe has short dark brown hair and a little longer sideburns his eyes are brown in color and have a child like a face he works as a security guard in a mall where he interacts daily with shoppers he likes to drink coffee and eat candies he also plays video games especially sports games with his friend on weekends \nroundish oval face full lips think nose large brown eyes arched dark eyebrows short dark hair cut in a bob style parted on the side and swept over she looks studious in the picture like she would make sure things were done before she left work \nprobably taller than an average female with a strong build probably 5 9ish and roughly 160 pounds probably does heavy lifting my guess is a paramedic based on appearance only \nhe has big ears nice eyes a smaller nose and short messy hair he seems like he s a bit of a troublemaker and that he tries his best in school but might not do too well \nshort brown hair bangs chubby brown eyes freckles bulbous nose light eyebrows she s a typical girl her age she goes to school hangs out with friends studies hard she enjoys listening to loud music she has a giant collection of nail polish \nwhite guy 20ish years old probably about average height maybe 5 feet 10 inches average build not overweight but not muscular college student likes to drink beer is casually dating is a pretty good student but can be a little lazy drives a used car probably a small or midsize sedan \nkind of tall not fat normal looking average white male young white very self confident priveleged maybe frat boy arrogant \nthis is a thin 20 year old male he has short light brown hair and blue eyes he has acne and fair skin student follower difficulty fitting in hard worker girls like him as a friend but not too date \nshort hair well groomed wrinkly eye creases she is patient and clean shes a house wife takes care of her families is very loving and caring \nthis person has a round face from being obese this person has small black moles throughout their face this person has weird looking eyebrows that are very thin toward the outer edge this person has a typical looking nose for a african person this person has somewhat thin lips this person has somewhat smooth skin this person has hair that is typical of a african person this person has big round eyes that are typical of a african female this person most likely has a attitude all the time this person probably goes home and watches tv all night before going to bed this person is probably extroverted and likes to talk with people \nthis person looks thin and she looks like she has short hair i think this person looks sad she might have just lost a family member \nthis person is about 5 feet tall and skinny he has light dark skin and flat feet he speaks very little english but just enough to get by he is friendly with customers and helpful he is a valued worker at his auto shop \nthe person is light skinned with hazel eyes and brown hair she seems to be of average built and female gender weight age career sex race religion place of origin complexion marital status fitness status food preferences social class obsessions shopping preferences accent \nhe is a young white male his skin is very light but a little sun kisses he has curly blond hair he has thin eyebrows he has pretty blue eyes he has thick lips his complexion is mostly good with a few blemishes he is clean shaven he seems like he spends some time in the sun he seems like he would be strong he probably would be good doing physical things he seems like he likes and is good at sports he seems like he might be aggressive \nthis individual is about 6 2 tall 220 lbs overweight short brown hair brown eyes short facial hair and pudgy stomach not athletic slightly lazy not socially adept sloppy dresser like video games slouches eats unhealthy diet doesn t have many friends \ncaucasian male late 20s early thirties short brown hair brown eyes scruffy round faced he probably likes beer and the nfl and video games \nbelow average height with blonde hair and green eyes rounded face and straight nose religious a few very close friends medium sized family moderate politically reasonably accomplished academically but has not attended college \nmid height slightly overweight curvy but otherwise healthy white with brown hair and eyes adult young female grew up middle class went to college has a few close friends and a medium sized family unmarried but dating \nthe person had short brown hair fair skin 5 2 athletic build the person is on the student counseling board the loves to draw the person have 6 brothers and she is the only girl \nshe is fair complected with light freckles she has beautiful large blue eyes and full pink lips she is shy she enjoys reading she is intelligent she is compassionate \nthis young lady is not very tall but is very helpful and is always there to assist you when you need it she has a very nice face and good skin careful helpful smart fast caring loving loves animals \nshe has sandy blond hair that is quite straight her eyes are a shade of green but also almost grey she has scars on her face very angry had a traumatic experience where she got the scars on her face she gets up quite early every morning but she has little enthusiasm about anything due to the horrible experience that has befallen her \nthis person has a chubby face short hair that comes down to their ears that is parted in the middle and a face that could be female or male this person is a rebellious teen boy grew his hair out because he likes 90s fashion this person skateboards \nthis person is quite tall about 5 10 and of average weight she has a slim muscular build this person likes to read she also likes to be outdoors but is careful of her skin she cares about her appearance but it is not the most important thing in the world to her she is sociable and has lots of friends \naverage height slightly over weight no muscle tone paleish skin short hair college grad liberal voted for bernie sanders makes his own beer in his basement \nthis is a young lady with short brown hair and brown eyes she has a freckled face she may not have a high level of education and probably struggles with her life in general \nshe should be very lean weight should be around 45 to 50 kg her height should be around 5 5feet she should have been married she should be working as teacher or relevant field \nshort hair think eyebrows blue eyes big ears sharp nose well groomed guy cruel intelligent deep thinker intended personality goal oriented person \ncaucasian male medium complexion mid 30 s brown hair green eyes average height and build loves planes enjoys auto racing volunteers in his spare time married 3 children rents in suburbs \nthis person is a man with grey hair and blue eyes i think he is a retired grandfather i think his hobbies are working in a garden or yard \nhe is somewhat tall and lanky he has curly blonde hair and isn t overly concerned about his appearance he likes playing video games he doesn t always take care of himself he is away from home for the first time at college living in a dorm setting \nlooks a bit bald on the front side and has sharp and lengthy nose and also light facial hair works with a passion loves traveling doesn t socialize a lot spends more time alone \naverage messy brown hair light eyebrows and light blue eyes sunken eyes low long nose thin pursed lips and light short beard not very educated and a loaner does not like to talk to other people and does not like to interact with strangers \nthis person has a narrowing jaw is clean shaven and has dark brown hair their hair does not have a noticeable part is combed forward and has a somewhat tussled look his ears are not a true oval shape but move upward and then outward he has narrow nostrils and his nose appears to be slightly crooked he has a small mole on his right cheek this person is athletic and enjoys various sports basketball ultimate frisbee and football if i had to guess he is very social and goes to the bars with his friends frequently he likes to joke and enjoys making his friends laugh he currently has a girlfriend of a few months but isn t worried about making the relationship overly serious \nthis person has an athletic built body they have short muscular arms as well as legs this person is not ready to settle down in life he loves his mother is interested in furthering his education and he likes to spend time with his friends \nfemale mid 40 s short hair blue eyes brown hair color fair skin slightly overweight stay at home mother average education married early good health healthy family financially secure active in community \nhe is looking like a professional in marketing field with formal clothes he is white ethnicity working youngster lite sad on his face and more over the person has to be silent his character \nthe male is 6 4 strong athletic build acne prone skin grey eyes and dark blonde hair this person loves to play video games this person loves to play basketball this person loves to cook \na white male with light brown blonde hair and blue eyes he has a five o clock shadow and a receding hairline his face is pretty symmetrical he looks like a laid back guy he probably enjoys beer and maybe a bit of the herb he looks like he d be the soft spoken type i d guess he s on the taller side \ncaucasian female thin auburn hair no style no smile ears too low very little eyebrows rosy cheeks freckles sad grey eyes maybe lesbian came from a family without love hates trump because he reminds her of her own father \nhispanic female mid twenties brown hair with light highlights brown eyes petite unmarried rents an apartment in a big city has a cat loyal friend likes to entertain and cook \nthis woman is of average height and is in her very early thirties she has short blonde hair and light blue eyes she is moderately attractive and is of caucasian descent she is stylish she doesn t wear a lot of make up she is pretty \na young woman in her mid 20 s she s got brown hair that s tied back in a standard ponytail her face is heart shaped her ears stay close to the sides of her face her eyes are a green leaning hazel and she s got slightly arched faint but natural eyebrows she s got red cheeks and some acne across her face she has a college degree she s got a good paying job she doesn t believe in crime she voted for hillary clinton \nolder man with striking blue eyes bit of a crooked nose clean shaven and balding not married loud voice kinda short kinda sleazy messy clothes average at his job \nthe person is female have hazel eyes fair skin and short black cropped cut the person is an animal lover the person is also a college student the person loves boxing and playing video games \nthey have an oval face with small lips their hair in light brown and cut in a trendy style their eyes are hazel and they have bushy eyebrows their nose is short and round they are shy they are inhibited they like computers they have just a handful of friends they can t grow a beard \nher hair is down to her ears and brown maybe dyed her eyebrows looked painted on she is wearing some make up but not much she has some blemishes on her skin she is independent does not seem to care about what others think she does not fit in with a lot of people but she is a strong person \nphysical characteristics are defining traits or features about your body the first thing you see when you look at someone could be their hair clothes nose or figure to get good examples of physical characteristics you should look at a person s face how tall they are and what they are wearing this person is attractive hair color is black and eye color is brown she is 27 years old \nred skin blonde hair medium nose big ears dotted skin having cruelty bad intention cold professionally fit rich person \nslightly crooked nose but very average other than that brown hair with product thick eyebrows they spend time on their hair which means they care at least a little of what others think of them they are not smiling so they have some confidence about themselves and not having to fake an emotion \nhe has a bit of a acne problem is about average height for a male doesn t have much hair on his body has a body that works out parties a bit likes playing videogames enjoys football lives in the south runs often takes things seriously \nshe is out of shape and wears cloths that cover up her body she does not want to be seen by many she she likes to play games and enjoy the outdoors she is kind and fun to be around \nthis person is in their early to mid 30s they re white have a somewhat round face with short spiked up hair this person has a wife and 2 young kids he lives in a suburban neighborhood and is getting by just fine with his job \nthis person has beautiful skin with dark eyes and hair this person is kind helpful and loves kids she is a mom \nthis person is short in height and has a slender build this person is reserved in personality but is out going around friends and family he enjoys going out with friends and socializing \nshe looks attractive and positive so she looks likes a teacher positive attitude is the one of the main thing i loved from this person as it is pretty well clear from the photos \nbrunette male with light blue eyes and a small mouth has light beard goatee scruff started to gel his hair in middle school and never stopped thinks taylor swift is pretty \nhe has shaggy short straight red hair he has very light but bushy eyebrows and a long narrow face he has full lips and a thin mustache as well as a bit of scruff on his chin his ears are small and close to his head he nose is long and wide he s intense and hard working he has is curious about the world and likes to spend time with his friends and family he goes out and enjoys drinking and going to concerts \nhe is about 23 years old he has brown hair and brown eyes and he has a fair complexion he has some freckles on his face i would guess that this guy is a university student i think he probably works part time in a retail job or something like that \nthis lady is somewhat heavy weight but average height she has blue grey eyes and dark blonde hair her skin is a fair shade she wears earrings she has two kids her career is hold until she raises her small kids she loves arts and crafts she is an animal activist she loves to cook \nthis person has a pale white skin complexion with a pronounced rounded nose this person seems to be balding and they regularly shave their head bald this person has large eyebrows and a round face with small mouth i imagine this person is hardworking and kind i imagine this person as a father of young children i guess that this person enjoys weightlifting \nshe looks good she s having average body and don t have much obese she can mingle with people easily she can handle tough situations without any frustrations \npiercing eyes with trimmed eyebrows purposely dangling hair to look playful playful smart confident okay in groups but better one on one \nhe has short brown hair blue eyes fair skin and a stubbly beard he is probably of average height and build there are no visible tattoos he likes sports he likes girls he likes beer he sunburns easily he doesn t like to shave \nshe is tall i would say about 5 8 she is average weight not fat not skinny average she wears athletic clothing she likes to play soccer she has a lot of friends she tries to go out with friends from time to time to see movies she likes to read \nhe is white must be tall person and slim fit like an athlete face look like somewhat handsome i think he is an american tall and slim white boy he is straight forward and enjoyable person i see his eye is really attractive \na middle aged man of average height and slightly slender build shaved head with blue eyes and fair skin angry and frustrated takes things seriously has worked at the same job for a long time \nskinny not very muscular about 5 7 in height with blue denim jeans and a white v nech shirt not very sociable only knows english and chills with friends on the weekends \nappears to have an slender well thought of composure does not have flair complexity nor time for any special delivery retorts to simple straight grammatical phrase appears to have an slender well thought of composure does not have flair complexity nor time for any special delivery retorts to simple straight grammatical phrase \nbig face with big nose broad eyebrows and thin lips oval shaped face and thoughtful eyes smart strong guy with mocking look and handsome face innocent guy \nshe s hair style was so nice and nose is pretty good and lips is so sweet she have destroying look and attractive smile her was looking smart and innocent women \nmiddle age asian female with brown hair and light blue eyes might be mixed with white and asian likes to watch dramas like soap operas listens to classical music probably considers herself a democrat likes to take time to look at nature while outside probably gets confused for being asian or white a lot by strangers \nto get good examples of physical characteristics you should look at a person s face how tall they are and what they are wearing for example build characteristics stocky slim she is very soft and cool woman she is very attractive person she convenience any people very easily \nthis looks to be a woman of indian background she has brown hair and brown eyes to go with it indian smart hard working immigrant woman tough daughter sister reliable \nsomewhat masculine looking female brown hair thin blue eyes pencil thin eyebrows large pointed chin she is a full time student majoring in it studies but is not really sure what career path she wants to take she is currently just enjoying her friends and the college experience hoping that in time her true path through life will become clear \nchubby face with clear skin and brown hair with blue eyes and caucasian she likes to talk with her friends and she is usually happy \naprroximately 5 605 8 average build with a bit of body fat probably easily blends into a crowd nice smile larger than average ears full rounded chin played soccer and volleyball as a youth feminist voted for hillary has a blog beliefs in being fair and honesty as virtuous intelligent and wanting for a relationship \nshe looks friendly and very enthusiastic look like a primary school teacher she work with very honsty like love with her family \nthis person is a young asian woman i can t tell what exact country she is from though she has black hair that is pulled back brown eyes and small earrings this person is an asian immigrant she speaks hardly any english and is a waitress at a chinese buffet \nthey are of average weight and height for a middle aged woman i m guessing she probably has kids and is married she probably dislikes her job \nhe has attractive eyes he has nice nose his face is attractive he is intelligent and hardworking he helps others he is result oriented \nbald has older appearance small mustache large downward pointed nose this person is friendly this person likes to talk alot this person is a family person \nhe face is one pimple he very short hair he nose is very short i decide answer is own mind he look is very confident persion \na good looking female with short blonde hair and long nose over all appearance look like american i think she is soft and sweet person happy peaceful motivated in love and also a short tamper but play funny some times \nwear jeans and t shirt perfect body taller healthy casual person very selfish person not believe others even his group members also \nmale early 30 s short black hair brown hair fair skin average health blue collar job technical education ambitious worker self made good health active in worker unions \n6 feet 1 inches tall very skinny weighing 130 pounds slim arms with no muscular tone big feet and a skinny waist line probably 30 inches very friendly person somewhat goofy and probably does a lot of things to try and fit in with friends he s not much of a leader he s more of a follower he probably has been into trouble due to trying to fit in \nshe has lazy eyes wears her hair slicked back in a pony tail likes to do drugs might like to eat and might like to go shopping \nthinner younger man with brownish hair and blue eyes he has a wide mouth and a prominent nose they are a student they do not have much of a work history \nbrown hair blue eyes large nose sideburns clean shaven probably of above average height and build no visible tattoos he likes sports he likes girls he likes beer he cares about his appearance he likes rock music \nhe is 5 9 and 140 pounds he has to shave twice every day has a hairy back he is quiet and only okay at his job he is married with one child and another on the way \ni think this person would be tall and slender maybe a bit awkward has brown hair with blue eyes and a nice smile he recently moved out of his parents house believes he is special and that all of his dreams will come true \npresumptive identification physical features tattoos scars birthmarks the absence used to make a presumptive identification or to presumptively exclude identity of course a person may not be wearing his or her regular clothes when average height with piercing eyes and a good smile fairly tall with a great body and strong face fairly short with dark hair and an alternative \nthis person is very tall and thin they have long lanky arms and legs this person enjoys playing video games and watching video game related content on the internet \nshe is a thick woman with pale skin and blue eyes she seems to be happy she seems like a busy bank teller who lives in a small city she has cats and a decent social life \nmanlet type of man standing in at five feet tall weighing about a buck fifty i am a person who is able to control a situation rather than have a situation control them \nsomewhat overweight aged but not elderly greying hair moves slowly divorced possible sexual offender conservative goes to church but doesn t believe in god \nyoung caucasian male green eyes day growth of facial hair ears that stick out a bit short hair with a peak in the back combed forward hair seems to be styled so has enough money a bit of a non comformist average younger person \nshe is 5 3 tall and weighs 185 pounds due to her job she has issues with her feet and has a slight limp she works in a manufacturing facility where she is a supervisor she works long days and stands on her feet for much of it she is married with two kids she has two sisters and a brother and her parents are still married she lives in a rural area and commutes 20 minutes to her job she likes facebook country music and having wine with friends \nbrown hair and eyes square jaw thin lips short hair friendly sporty focused quiet a little shy quiet puts herself into her work likes to swim and bicycle \nthis man has dark hair and green eyes he has some stubble on his face as if he has missed shaving for a day not necessarily purposefully he has a very round face with normal features though from what i can see he has a gap between his front two teeth that is probably distracting his face is very symmetrical he probably works in his first job after college i would guess he s in a serious relationship or maybe even engaged but is still planning his future not necessarily in his future yet \nshe is a shorter girl and a bit overweight she has brown hair and bright blue eyes she has a few blond streaks in her hair she has very light freckles she is a student and still lives at home she is not very active \nbrown haired blue eyed male strong nose protruding ears stubble on upper lip and beard line between the ages of 17 25 i can guess the gender is male i can guess they may need a hair cut i can guess they may need a shave or are trying to grow a beard i can guess they do not tweeze their eyebrows i can guess they may have roman or greek ancestors due to nose size \nhe is average height with average body but his body shows some athletic signs he is very energetic and active he loves to try innovative things he is a good creator and creative thinker \nhe is probably around 6 foot tall he is of average weight of around 180 lbs probably average build he is friendly probably considers himself to be an extrovert listens to rock music would be willing to go to the bar if asked \nthis person will be attractive in physic looks white in color slim looking this person will be easy going can mingle with anyone easily \ni think this person is overweight they are below average on height they are probably very short i think this person speaks spanish and english i think they are quiet and they work hard \nhe has good eyes he seems to be fair he looks young he looks social he looks hard working he looks honest \nthe person has a oval shaped face with green eyes and short hair student geek shy reserved honest intelligent respects seniors creative \nhe is tall skinny has a large nose medium size lips and ears has messy hair he likes to party he can also be reliable he cares about his family and friends \nhe has nice dark skin with some acne marks his hair looks well kept his nose is larger than average he looks like an alright person but something seems untrustworthy about him he d probably be an alright friend \nhe is a mexican man who works in construction short built with a chubby body he is a strong minded person that don t take crap from anyone he works hard and love his family \nlooks under the influence almost bald suggest he may be with a bad crowd doesn t look like he gets through life well and is struggling with himself probably uses drugs hangs out with a bad crowd which gets him involved with bad people likes the fight and get into it with other people \noverweight brown hair brown eyes freckles rosy cheeks hard faced permanent scowl hair is always tightly held back she s got a mean streak but she s loyal as all hell she ll spend a ton of time cooking for special occasions all recipes are passed down through generations she probably has mafia connections \nhe is bit fat over weight but not obese he is short he is jovial respects others has a lot of friends going out frequently \nthis person has white skin and dark hair but has a blonde fringe of thin hair they are quite young looking and spots can be seen on their face especially around their chin they have a placid calm look on their expression is quite neutral they have no make up or piercings they seem calm normal not eccentric they are young and could be a student they might have a job paying low wages to earn a little bit of money as their expression is quite neutral it is difficult to say whether they are kind or not but they look like a quiet person \nhe has brown straight short hair and brown eyes he is clean shaven he has a birthmark on his right cheek he is serious but sensitive and kind he works hard and cares for those around him \na bit overweight about six feet tall medium to long hair not much hair on body not much muscle nerdy into computers a lot intelligent is a gamer can be reserved or quiet not many friends \nthis person has a very strong set of eyebrows they have a dark complexion with dark hair and eyes they have a very thick head of hair and a low hairline they probably do not speak english he is probably a muslim i think he would be from india or pakistan he might be a vegetarian \nhe has an athletic build and is quite muscular he is an average height he has rather large arms from working out he is arrogant he is very smart he has a lot of friends but they don t let many new people into their group he tends to intimidate people \nthey are of average height and weight for a person of their age and gender i think they are generally a happy person with little patience for bs \n5 6 120 lbs skinny unfit long legs short torso medium arms small stomach no chest skinny legs works on computer plays games talks to friends watches cartoons hangs out with friends at local mall \nkind of annoying sounding voice tall overzealously expressive at times slightly wide frame slightly overweight poor impulse control hard worker lacks ambition needs a vacation reads but few substantial works \nshe is very fit she cares about her body and works out quite often she knows how to stay in shape she likes fashion and the luxuries of life is recently married doesn t have kids yet \nlookism is discriminatory treatment toward physically unattractive people mainly in the workplace but also in social settings while not classified in the same a short list of things i want you know by kendra life is too short for shitty wine you if you can feel people pulling away you should ask them about it \ndirty blonde hair with grey eyes and relaxed style and split hair i think she is a relaxed and fun person who is also forward \nbrown hair blue eyes around 6 foot tall weighs around 140 pounds not outgoing takes everything seriously and isn t very friendly is single but dates around likes water sports and sports \nshort slightly over weight korean long fingernails dresses casually good health hard worker speaks two languages has many kids eats a lot of fish second generation american \nthis is a white female with red hair with some brown streaks in it this person has green eyes and has short hair that is parted more on one side this person has graduated college this person has a boyfriend this person is very friendly this person loves animals \nit possible to appreciate the relationship of applied decoration to form and of materials to form and decoration she is a older mother it possible to appreciate the relationship of applied decoration to form and of materials to form and decoration \nyoung attractive fair skin but scarred and with a spot on her nose her hair is nice and her face is nice a little thoughtless maybe somewhat dangerous if provoked she looks a bit bored too \nshort hair blue eyes fair skin narrow eyes red eyebrows thin lips light freckles a student in middle school with a few friends a good student and listens well to her parents \nthis guy have a average body type height may be tall attractive face with good speaking knowledge this guy must have lot of knowledge in studies looks like a genius in practical research studies never interested in sports and cultural activities punctuality may be good in work \nslightly muscular build or could be a bit overweight average height about six feet tall hair on arms with some facial hair can be tempermental angry not very trusting anger problems may be friendly only to close friends and family can be lazy \nthey seem very young or just have a young face feature i would guess they love hanging out and listening to music \nhe is short medium length brown hair blue eyes skinny build he has many friends and enjoys being the center of attention he likes to play games \nthis person is quite small in stature and slim she is probably of less than average weight this person is not terribly happy at the moment in fact she looks quite annoyed she is not interested in wearing make up and doesn t really try to impress others with her looks \nhe is short and thin with no facial hair he keeps his hair shorter but enough to cover his ears which are low set he is a customer service representative for a local cable tv company he likes the interactions he has with people and dreams of having his own business one day \nthis person is very hairy all over his body even his toes he is medium height has a beer belly and his hair is thin and easily becomes greasy this person is a loner does not like committed relationships and he is married to his job \nhe has a round face no hair and a stern expression works out watches breaking bad uses a straight razor isn t very nice likes the outdoors \nthis person has light brown skin dark brown hair and dark brown eyes they also have a little dark stubble hooded eyelids medium sized ears that just barely stick out and plush rosy lips that remain in a neutral position technology parties drinking dogs baseball movies and hanging out with friends and family \nits an older male with blue eyes and brown hair its a human that probably is no fun \nvery young and pretty brown hair and brown eyes complete with cleft chin she looks like the suit type nine to five pretty driven \nthis person is more on the average size not too muscular and not fat she is right between she is short prolly about 5 3 and weighs about 150 she can be caring and loving of others but she also has a mean streak she can be rude and angry when things dont go her way \nlooking like old and the face was not good enough attracting it is the minus point to him only grey eyes will attract on his face and some what smiling also help in attracting \nthis person is of average height and weight aside from their longish hair they are much like many others that are this age build on the skinny side but somewhat muscular frame this is a person who works hard at their job so they can afford to play hard when they are not working they put in long hours at their job so they can go out with their friends on the weekend and have fun they are from a middle income family and may not have had the same chances that others had they decided not to go to college and started working right out of high school \nthat is person is the are the africa woman the woman is homemaker we re an online community that encourages and fosters creative writing by providing peer review workshops hone your writing skills by uploading stories and poems to our workshops and by reviewing other members works or join us in our forums and discuss your writing experiences and questions our site is entirely ad free and we totally understand privacy that is would that the of the homemaker hone your writing skills by uploading stories and poems to our workshops and by reviewing other members works \nshort and of average build probably does not work out probably speaks more than 1 language possibly is an immigrant \nhe is a hispanic male he has slightly longish black hair his hair is straight he has dark eyes and thick eyebrows he is cleans shaven except for a shadow he has a cleft in his chin he has a deep olive complexion he has thick lips he seems like he might be good working with his hands he might be a mechanic he might spend a lot of time in the sun i think he is of spanish origin and probably is bilingual he seems like he is confident and wouldn t be afraid of people he is not timid \nthis person seems to small about 5 feet 5 inch height with average body build up he seems to be having difficult time in life with little criminal mind \ntidy small stature average height and build 5 6 about 125 pounds impatient careless focused when it comes to work career oriented \na young male with brown hair and blue eyes he is about 5 10 looks australian male 20 25 years old college student \nthis person has an average and muscular build they are about 5 8 140 lbs they have brown hair and blue eyes and some facial blemishes this person is argumentative and combative they are athletic and competitive this person stands firm in their beliefs \nhe is six feet tall and has a thin build he has a decent muscle mass he worked retail when he was a teenager and ended up getting promoted to management he has a girlfriend he s been dating for a few weeks but they aren t very serious he still lives in the town where he was born \nmore heavy set man standing about six feet tall wears baggy clothes that represent his style i want to be judged by individual performance and i want be rewarded for my efforts based on their my to execute \nthey would be a stockier person short and they would be a little over weight she would be kind to those she knows she would come off as rude to others that she just meets \nshe s tall and thin weighing about 115 to 125 pounds she has long hair that she prefers to wear in a ponytail to keep out of her way since she lives a fairly active life she has oily skin and tends to wear acne medicine she s in her late 20 s to early 30 s she s fairly active enjoying walking and running she s a bit of an introvert preferring time alone reading to hanging out at parties she s a tough cookie who excels at her job she enjoys having a few close friends rather than being a socialite \nhere s a typical average height orange haired male with blue eyes he s a bit chubby a factory worker by day he likes to get drunk at night and go to bars to scope out chicks he s fun to be with but has a mean streak too \ndeep black hair short bushy eye brows tan complexion a small beard mustache clear skin light bags under their eyes likes to play soccer enjoys the outdoors loves his mom speaks spanish works hard doesn t have children yet maybe a student polite and funny loves to laugh and be with friends \nthey have a long narrow head with soft boyish features they have uneven skin and shades of a unibrow they have tiny features and an average sized nose that appears large only by comparison they often fall asleep without proper grooming they play a lot of video games especially extreme sports games they don t own tweezers but have 3 different kinds of hair molding product they prefer art to math \nhe is a tall white male with a medium build he has brown hair and blue eyes slightly depressed works at zumiez has many friends who are similar doesn t talk much around new people \npale with large eyes and a strong pointed chin average in weight and build and ver low maintanence they re friendly natural easygoing not high strung no make up work oriented \nblack color hair and sharpe nose and light black skin black eye brow normal face he is a good person black color skin and lean body he is asian country age is 30 \nthis person is a young white female she is medium weight 5 5 in height and fairly muscular her skin is pale as she does not go to the beach or spend a lot of time outdoors she has brown eyes and dark brown hair that is straight and cut short waits tables in the evenings goes to school during the day is studying to be physical therapist has a great sense of humor has many friends \nthey are short with a small head brown eyes and brownish black hair his ears stick way out and the lips are small and pouty either a student or a criminal they look like they get into trouble or like to start trouble with other people can t keep to themselves \naverage as you can get has average height doesn t weigh a whole lot and probably spends most of their time engaging in unhealthy behaviors probably under a lot of stress deals with family and personal struggles enjoys being by himself more than with anyone else \nthey look like they are worn down they loook kind of depressed he looks serious and well groomed i think that he probably doesn t get too much sleep and drinks a lot of energy drinks to stay awake \nthey are average white and with shaggy hair they are not fat but not overly slender they play video games and are trying to find a part time job \nwhite good looking female with short and brown hair she is probably in her mid 20 s could be around 26 or 27 blue or hazel eyes hard worker she is probably a mom married works as a receptionist or on an office setting \nthis person has short blonde hair with blue eyes with a medium build this person enjoys staying in and watching netflix this person enjoys being alone and avoids large crowds \nthis person is thin and tall he is about 6 feet height this person seems to be from average class family and he is sincere in his work \na slightly blocky face with kind of larger eyes with a lot of eye makeup they have kind of large front teeth and dimples they have a very short bob haircut i think the person is a mother and seems to be a bit cheerful \nhard to describe he s very typical white male with a decent face large eyes long nose light facial hair college student or graduate student he seems to be in financial major couldn t possibly in computer engineering \ntall shapely wears nice clothing and shoes likes to spend money to look nice she is driven to work up the ladder at her job likes to eat at nice restaurants with her friends on the weekend has a very nice apartment that she keeps clean and stylish likes to shop for nice clothes \nyoung female with short red hair she has blueish eyes and an earring in her right ear she s a shy and reserved girl she loves reading and being close with her friends and family \nis on the heavier side and looks unhealthy and that she may get sick quite often she is married and has multiple kids she is a very caring person and enjoys helping people \n20 year old white female dark blonde hair and blue eyes they may be average or slightly overweight i assume they dont not have a white collar job as her makeup is a little sloppy with smudged eyeliner and over tweezed eyebrows making me believe she did it herself and higher quality makeup could prevent smearing she does still care about herself and believe her to be employed \nthis person is possibly of arab or latin decent they have brown eyes and dark brown or black hair prominent nose i think this person works at the library or a book store in a major city i think she is tall and slender very active and friendly \na young man with a round jaw appears to be in his mid 20s brown hair and brown eyes he s got red cheeks and thin lips his eyebrows are rather thick his hair is short and fairly standard for men one hispanic parent and one white parent listens to metal had a scene phase in middle school \nshort person with small features they have light blue eyes and brown hair average sized nose with smallish ears that stick out a bit a very light amount of facial hair this person is a student and they look young not much experience in the world \nthis person is 5 feet 9 inches tall he probably weighs no more than 180 he probably has an athletic build and is physically fit this person look a little lazy all in all he is probably a good person but it looks like he is immature it looks like he can be disorganized and can be unmotivated at times \nwhite male with very short brown hair and brown eyes has a freckle under left eye and a mole on the right side of his chin likes mainstream rap music buys whatever masculine shampoo is on sale isn t scared of bugs \ni feel he would be 6 foot 1 inches tall he would be slender and of average build he would have large feet i forsee him being kind gentle intelligent open straighforward giving and blunt \nthe person has an average body not too fat and not too skinny just pretty average all around i think this person really likes dogs and dopes wear glasses to increase their vision \nthis person is of slim to medium build they have dyed blonde hair and blue eyes they have a slight tan they are caucasian probably happy go lucky university humanities major not too radical of an activist on campus \npossibly a latino with dirty green eyes and ginger hair with a blunt nose and no moustache he may work in a bar or a restaurant he s proud of what he is \nappears to have an slender well thought of composure does not have flair complexity nor time for any special delivery retorts to simple straight grammatical phrase appears to have an slender well thought of composure does not have flair complexity nor time for any special delivery retorts to simple straight grammatical phrase thinks left brained by the twink of the eyelashes has very few or little creative urgency by the press of the lower lips display lack of command direction \nthis guy have a slim body type height is medium with average weight good looking face with black color eyes good hairstyles and no beard this guy may be a student very joyful type good talent in practical research studies not interested in politics he may be good swimmer and bike racer \nhe looks shy and meek he has a small baby face his head is very round he looks like he s probably a nerd he probably is afraid to make friends he probably doesn t have a good paying job \ni think she was short and fat she was wear skirt she hair style and face look like 40 age person \nhe is about 6 0 and weighs approx 180 pounds he works out but not a lot so he is not toned but is healthy he eats well and likes to do his own shopping he is dating but not serious about any one in particular \nshort brown hair long face average ears long nose thicker lips smaller chin downturned eyes thick eyebrows he is a student comes from a very poor background he is known for getting into all sorts of trouble \ntall and a bit lanky however he does not lack muscles likes swimming likes backpacking and hiking likes the outdoors organized and detail oriented \nthey are probably chubby and not very fit he seems to have always a smug look on his face i can guess that they are a bully or very annoying \nhe is young tall black hair with green eye man he looks attractive he looks like a model confidential casual artful amusing cute freewheeling sensual soft smooth crazy captivating colorful \nthis person is a male with brown hair and brown eyes facial hair possibly latin or arab decent this guy probably works in finance or engineering he has a few siblings and is the bread winner of his family \nhe is a moderately handsome man he has short dark brown hair it has some wave to it he keeps gel in it it seems like he is mostly clean shaven with a little shadow he has a small mouth he has an oval shaped face his features are sharp he seems like a serious man he might work in computers he seems smart he does not seem like he jokes around a lot he seems like he might be ambitious for getting what he wants he does not seem timid or shy but seems confident instead \nthis young male has brown hair and blue eyes a bit of acne on his chin above his goatee grad student easily angered not happy ready to be done with school average build and height \naverage build lean slight curves normal build for her age socially awkward but sweet has issues with asserting self but stands up for things she believes in enjoys talking about movies and being with family \nthe edge of her white kimono flapped open in the wind and i could see her breast low and full a first person narrator can give biased opinions about appearances this person is typical this person is attractive his gender is male \nfemale overweight round face pale hooded blue eyes thin eyebrows young single recently college educated entry level job happy uses dating apps \nshe is taller than the average woman at 5 7 and is relatively good shape despite her round face she is well muscled and has longer hair that she usually keeps back in a bun she has long legs she likes to work hard and play hard she is always very serious at work and keeps things very professional she likes to go out and have fun at night with her friends she is single and doesn t have any plans to change that anytime soon \nhe has dark blonde hair and blue eyes he is sixteen and a student at the local school they are average the go to school he is an average student \nugly nerd geek sick ew brown eyes and stupid brown hair nerd haha wtf is this nah im just kidding but he is ugly tho \nthis person had reddish brown hair with blue eyes they probably look younger than they really are there lips are on the small side average weight i think that this person enjoys going to friends houses on the weekend or after work and playing some video games he probably also likes to drink a little bit as well i think that he looks kind and willing to sacrifice for others \ntall slim young woman in her mid twenties she has light brown hair and blue eyes she is reasonably attractive and has pretty eyes she is young she is single she doesn t have a great job she has few friends she has a cat \nnot a white person big nose no earrings nose not straight social person does not speak english well may or may not have a boyfriend family person \naverage height and weight slouches at all times very focused on maintaining his 5 oclock shadow to appear older this person likes to corner you in a room and prattle on about his guitar pedals and the tone he is trying to achieve in his guitar \nwhite male brown hair brown eyes average height slightly overweight works graveyard at target stocking shelves still lives with parents \nwhite male with brown hair and hazel eyes round face with red cheeks single athletic friendly very talkative very polite follows the crowd \nhe is 5 10 and 170 pounds he has black hair and brown eyes he loves his job and has a long term girlfriend and is very close to his parents \nthis woman has short hair thin eyebrows and a relatively wide bottom part of her nose her ears are pretty short and do not stick out of that far her face and chin are pretty wide i think that this woman is pretty closed off socially though she hangs out with friends at times i think that she likes to watch anime and listen to music \n"
],
[
"## Speech tagging\n\nfrom nltk.tokenize import PunktSentenceTokenizer\n\ntrain_text = descriptions[2]\nsample_text = descriptions[22]\n\ncustom_tokenizer = PunktSentenceTokenizer(train_text)\n\ntokenized = custom_tokenizer.tokenize(sample_text)\n\ndef tagging():\n for x in tokenized:\n words = nltk.word_tokenize(x)\n tagged = nltk.pos_tag(words)\n print(tagged)\n \n ",
"_____no_output_____"
],
[
"tagging()",
"[('smart', 'JJ'), ('looking', 'VBG'), ('personality', 'NN'), ('small', 'JJ'), ('beard', 'NN'), ('and', 'CC'), ('mustache', 'NN'), ('which', 'WDT'), ('adds', 'VBZ'), ('to', 'TO'), ('his', 'PRP$'), ('face', 'NN'), ('seems', 'VBZ'), ('smart', 'JJ'), ('seems', 'VBZ'), ('jobless', 'JJ'), ('seems', 'VBZ'), ('he', 'PRP'), ('belongs', 'VBZ'), ('to', 'TO'), ('a', 'DT'), ('rich', 'JJ'), ('family', 'NN'), ('drinks', 'NNS'), ('too', 'RB'), ('much', 'RB'), ('good', 'JJ'), ('height', 'NN')]\n"
],
[
"##Lemmatizing\n\nfrom nltk.stem import WordNetLemmatizer\n\nlemmatizer = WordNetLemmatizer()\n\nprint(lemmatizer.lemmatize(\"better\", pos = \"a\"))",
"good\n"
],
[
"## WordNet = find synonyms (better accuracy)\n\n\nfrom nltk.corpus import wordnet\n\nsyns = wordnet.synsets(\"program\")\n\nprint(syns)",
"[Synset('plan.n.01'), Synset('program.n.02'), Synset('broadcast.n.02'), Synset('platform.n.02'), Synset('program.n.05'), Synset('course_of_study.n.01'), Synset('program.n.07'), Synset('program.n.08'), Synset('program.v.01'), Synset('program.v.02')]\n"
],
[
"print(descriptions[1])",
"she is tall and athletic she is lean she is thin she is outgoing she is single she loves hiking and nature \n"
],
[
"print(len(descriptions))",
"1480\n"
],
[
" \n \na = 'Panama'\nb = 'Pamela'\n\ndef hamming(a,b):\n distance = 0\n for index in range(len(a)):\n # print(a[index], b[index]) # prints each nth letter next to each other\n\n if a[index] != b[index]:\n distance +=1\n #print(distance) \n return distance\n\nhamming(a,b)\n\n## Haming only for strings of the same length",
"_____no_output_____"
],
[
" def minkowski_distance(self,x,y,p_value):\n \n \"\"\" return minkowski distance between two lists \"\"\"\n \n return self.nth_root(sum(pow(abs(a-b),p_value) for a,b in zip(x, y)),\n p_value)\n ",
"_____no_output_____"
],
[
"#!/usr/bin/env python\n\n\nfrom math import*\nfrom decimal import Decimal\n\ndef nth_root(value, n_root):\n\n root_value = 1/float(n_root)\n return round (Decimal(value) ** Decimal(root_value),3)\n\ndef minkowski_distance(x,y,p_value):\n\n return nth_root(sum(pow(abs(a-b),p_value) for a,b in zip(x, y)),p_value)\n\n#print minkowski_distance([0,3,4,5],[7,6,3,-1],3)",
"_____no_output_____"
]
],
[
[
"Also other distance metrics are present, such as chebyshev, minkowski, mahalanobis, haversine, hamming, canberra, braycurtis and many more.\n\n",
"_____no_output_____"
]
],
[
[
"minkowski_distance(x=[7,6,3,-1], y=[0,3,4,5], p_value=3)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ac897a44bde041be754b76d8462a4639d24e1b | 38,004 | ipynb | Jupyter Notebook | intro-to-rnns/Anna_KaRNNa_Solution.ipynb | ys3x/deep-learning | 39a9191e05e1b7005456cacf6b84e1439f8252ec | [
"MIT"
] | null | null | null | intro-to-rnns/Anna_KaRNNa_Solution.ipynb | ys3x/deep-learning | 39a9191e05e1b7005456cacf6b84e1439f8252ec | [
"MIT"
] | null | null | null | intro-to-rnns/Anna_KaRNNa_Solution.ipynb | ys3x/deep-learning | 39a9191e05e1b7005456cacf6b84e1439f8252ec | [
"MIT"
] | null | null | null | 42.845547 | 766 | 0.587333 | [
[
[
"# Anna KaRNNa\n\nIn this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.\n\nThis network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and [implementation in Torch](https://github.com/karpathy/char-rnn). Also, some information [here at r2rt](http://r2rt.com/recurrent-neural-networks-in-tensorflow-ii.html) and from [Sherjil Ozair](https://github.com/sherjilozair/char-rnn-tensorflow) on GitHub. Below is the general architecture of the character-wise RNN.\n\n<img src=\"assets/charseq.jpeg\" width=\"500\">",
"_____no_output_____"
]
],
[
[
"import time\nfrom collections import namedtuple\n\nimport numpy as np\nimport tensorflow as tf",
"_____no_output_____"
]
],
[
[
"First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the characters to and from integers. Encoding the characters as integers makes it easier to use as input in the network.",
"_____no_output_____"
]
],
[
[
"with open('anna.txt', 'r') as f:\n text=f.read()\nvocab = sorted(set(text))\nvocab_to_int = {c: i for i, c in enumerate(vocab)}\nint_to_vocab = dict(enumerate(vocab))\nencoded = np.array([vocab_to_int[c] for c in text], dtype=np.int32)",
"_____no_output_____"
]
],
[
[
"Let's check out the first 100 characters, make sure everything is peachy. According to the [American Book Review](http://americanbookreview.org/100bestlines.asp), this is the 6th best first line of a book ever.",
"_____no_output_____"
]
],
[
[
"text[:100]",
"_____no_output_____"
]
],
[
[
"And we can see the characters encoded as integers.",
"_____no_output_____"
]
],
[
[
"encoded[:100]",
"_____no_output_____"
]
],
[
[
"Since the network is working with individual characters, it's similar to a classification problem in which we are trying to predict the next character from the previous text. Here's how many 'classes' our network has to pick from.",
"_____no_output_____"
]
],
[
[
"len(vocab)",
"_____no_output_____"
]
],
[
[
"## Making training mini-batches\n\nHere is where we'll make our mini-batches for training. Remember that we want our batches to be multiple sequences of some desired number of sequence steps. Considering a simple example, our batches would look like this:\n\n<img src=\"assets/[email protected]\" width=500px>\n\n\n<br>\n\nWe start with our text encoded as integers in one long array in `encoded`. Let's create a function that will give us an iterator for our batches. I like using [generator functions](https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/) to do this. Then we can pass `encoded` into this function and get our batch generator.\n\nThe first thing we need to do is discard some of the text so we only have completely full batches. Each batch contains $N \\times M$ characters, where $N$ is the batch size (the number of sequences) and $M$ is the number of steps. Then, to get the total number of batches, $K$, we can make from the array `arr`, you divide the length of `arr` by the number of characters per batch. Once you know the number of batches, you can get the total number of characters to keep from `arr`, $N * M * K$.\n\nAfter that, we need to split `arr` into $N$ sequences. You can do this using `arr.reshape(size)` where `size` is a tuple containing the dimensions sizes of the reshaped array. We know we want $N$ sequences (`batch_size` below), let's make that the size of the first dimension. For the second dimension, you can use `-1` as a placeholder in the size, it'll fill up the array with the appropriate data for you. After this, you should have an array that is $N \\times (M * K)$.\n\nNow that we have this array, we can iterate through it to get our batches. The idea is each batch is a $N \\times M$ window on the $N \\times (M * K)$ array. For each subsequent batch, the window moves over by `n_steps`. We also want to create both the input and target arrays. Remember that the targets are the inputs shifted over one character. \n\nThe way I like to do this window is use `range` to take steps of size `n_steps` from $0$ to `arr.shape[1]`, the total number of steps in each sequence. That way, the integers you get from `range` always point to the start of a batch, and each window is `n_steps` wide.",
"_____no_output_____"
]
],
[
[
"def get_batches(arr, batch_size, n_steps):\n '''Create a generator that returns batches of size\n batch_size x n_steps from arr.\n \n Arguments\n ---------\n arr: Array you want to make batches from\n batch_size: Batch size, the number of sequences per batch\n n_steps: Number of sequence steps per batch\n '''\n # Get the number of characters per batch and number of batches we can make\n chars_per_batch = batch_size * n_steps\n n_batches = len(arr)//chars_per_batch\n \n # Keep only enough characters to make full batches\n arr = arr[:n_batches * chars_per_batch]\n \n # Reshape into batch_size rows\n arr = arr.reshape((batch_size, -1))\n \n for n in range(0, arr.shape[1], n_steps):\n # The features\n x = arr[:, n:n+n_steps]\n # The targets, shifted by one\n y_temp = arr[:, n+1:n+n_steps+1]\n \n # For the very last batch, y will be one character short at the end of \n # the sequences which breaks things. To get around this, I'll make an \n # array of the appropriate size first, of all zeros, then add the targets.\n # This will introduce a small artifact in the last batch, but it won't matter.\n y = np.zeros(x.shape, dtype=x.dtype)\n y[:,:y_temp.shape[1]] = y_temp\n \n yield x, y",
"_____no_output_____"
]
],
[
[
"Now I'll make my data sets and we can check out what's going on here. Here I'm going to use a batch size of 10 and 50 sequence steps.",
"_____no_output_____"
]
],
[
[
"batches = get_batches(encoded, 10, 50)\nx, y = next(batches)",
"_____no_output_____"
],
[
"print('x\\n', x[:10, :10])\nprint('\\ny\\n', y[:10, :10])",
"x\n [[31 64 57 72 76 61 74 1 16 0]\n [ 1 57 69 1 70 71 76 1 63 71]\n [78 65 70 13 0 0 3 53 61 75]\n [70 1 60 77 74 65 70 63 1 64]\n [ 1 65 76 1 65 75 11 1 75 65]\n [ 1 37 76 1 79 57 75 0 71 70]\n [64 61 70 1 59 71 69 61 1 62]\n [26 1 58 77 76 1 70 71 79 1]\n [76 1 65 75 70 7 76 13 1 48]\n [ 1 75 57 65 60 1 76 71 1 64]]\n\ny\n [[64 57 72 76 61 74 1 16 0 0]\n [57 69 1 70 71 76 1 63 71 65]\n [65 70 13 0 0 3 53 61 75 11]\n [ 1 60 77 74 65 70 63 1 64 65]\n [65 76 1 65 75 11 1 75 65 74]\n [37 76 1 79 57 75 0 71 70 68]\n [61 70 1 59 71 69 61 1 62 71]\n [ 1 58 77 76 1 70 71 79 1 75]\n [ 1 65 75 70 7 76 13 1 48 64]\n [75 57 65 60 1 76 71 1 64 61]]\n"
]
],
[
[
"If you implemented `get_batches` correctly, the above output should look something like \n```\nx\n [[55 63 69 22 6 76 45 5 16 35]\n [ 5 69 1 5 12 52 6 5 56 52]\n [48 29 12 61 35 35 8 64 76 78]\n [12 5 24 39 45 29 12 56 5 63]\n [ 5 29 6 5 29 78 28 5 78 29]\n [ 5 13 6 5 36 69 78 35 52 12]\n [63 76 12 5 18 52 1 76 5 58]\n [34 5 73 39 6 5 12 52 36 5]\n [ 6 5 29 78 12 79 6 61 5 59]\n [ 5 78 69 29 24 5 6 52 5 63]]\n\ny\n [[63 69 22 6 76 45 5 16 35 35]\n [69 1 5 12 52 6 5 56 52 29]\n [29 12 61 35 35 8 64 76 78 28]\n [ 5 24 39 45 29 12 56 5 63 29]\n [29 6 5 29 78 28 5 78 29 45]\n [13 6 5 36 69 78 35 52 12 43]\n [76 12 5 18 52 1 76 5 58 52]\n [ 5 73 39 6 5 12 52 36 5 78]\n [ 5 29 78 12 79 6 61 5 59 63]\n [78 69 29 24 5 6 52 5 63 76]]\n ```\n although the exact numbers will be different. Check to make sure the data is shifted over one step for `y`.",
"_____no_output_____"
],
[
"## Building the model\n\nBelow is where you'll build the network. We'll break it up into parts so it's easier to reason about each bit. Then we can connect them up into the whole network.\n\n<img src=\"assets/charRNN.png\" width=500px>\n\n\n### Inputs\n\nFirst off we'll create our input placeholders. As usual we need placeholders for the training data and the targets. We'll also create a placeholder for dropout layers called `keep_prob`.",
"_____no_output_____"
]
],
[
[
"def build_inputs(batch_size, num_steps):\n ''' Define placeholders for inputs, targets, and dropout \n \n Arguments\n ---------\n batch_size: Batch size, number of sequences per batch\n num_steps: Number of sequence steps in a batch\n \n '''\n # Declare placeholders we'll feed into the graph\n inputs = tf.placeholder(tf.int32, [batch_size, num_steps], name='inputs')\n targets = tf.placeholder(tf.int32, [batch_size, num_steps], name='targets')\n \n # Keep probability placeholder for drop out layers\n keep_prob = tf.placeholder(tf.float32, name='keep_prob')\n \n return inputs, targets, keep_prob",
"_____no_output_____"
]
],
[
[
"### LSTM Cell\n\nHere we will create the LSTM cell we'll use in the hidden layer. We'll use this cell as a building block for the RNN. So we aren't actually defining the RNN here, just the type of cell we'll use in the hidden layer.\n\nWe first create a basic LSTM cell with\n\n```python\nlstm = tf.contrib.rnn.BasicLSTMCell(num_units)\n```\n\nwhere `num_units` is the number of units in the hidden layers in the cell. Then we can add dropout by wrapping it with \n\n```python\ntf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n```\nYou pass in a cell and it will automatically add dropout to the inputs or outputs. Finally, we can stack up the LSTM cells into layers with [`tf.contrib.rnn.MultiRNNCell`](https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/contrib/rnn/MultiRNNCell). With this, you pass in a list of cells and it will send the output of one cell into the next cell. Previously with TensorFlow 1.0, you could do this\n\n```python\ntf.contrib.rnn.MultiRNNCell([cell]*num_layers)\n```\n\nThis might look a little weird if you know Python well because this will create a list of the same `cell` object. However, TensorFlow 1.0 will create different weight matrices for all `cell` objects. But, starting with TensorFlow 1.1 you actually need to create new cell objects in the list. To get it to work in TensorFlow 1.1, it should look like\n\n```python\ndef build_cell(num_units, keep_prob):\n lstm = tf.contrib.rnn.BasicLSTMCell(num_units)\n drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n \n return drop\n \ntf.contrib.rnn.MultiRNNCell([build_cell(num_units, keep_prob) for _ in range(num_layers)])\n```\n\nEven though this is actually multiple LSTM cells stacked on each other, you can treat the multiple layers as one cell.\n\nWe also need to create an initial cell state of all zeros. This can be done like so\n\n```python\ninitial_state = cell.zero_state(batch_size, tf.float32)\n```\n\nBelow, we implement the `build_lstm` function to create these LSTM cells and the initial state.",
"_____no_output_____"
]
],
[
[
"def build_lstm(lstm_size, num_layers, batch_size, keep_prob):\n ''' Build LSTM cell.\n \n Arguments\n ---------\n keep_prob: Scalar tensor (tf.placeholder) for the dropout keep probability\n lstm_size: Size of the hidden layers in the LSTM cells\n num_layers: Number of LSTM layers\n batch_size: Batch size\n\n '''\n ### Build the LSTM Cell\n \n def build_cell(lstm_size, keep_prob):\n # Use a basic LSTM cell\n lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)\n \n # Add dropout to the cell\n drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n return drop\n \n \n # Stack up multiple LSTM layers, for deep learning\n cell = tf.contrib.rnn.MultiRNNCell([build_cell(lstm_size, keep_prob) for _ in range(num_layers)])\n initial_state = cell.zero_state(batch_size, tf.float32)\n \n return cell, initial_state",
"_____no_output_____"
]
],
[
[
"### RNN Output\n\nHere we'll create the output layer. We need to connect the output of the RNN cells to a full connected layer with a softmax output. The softmax output gives us a probability distribution we can use to predict the next character.\n\nIf our input has batch size $N$, number of steps $M$, and the hidden layer has $L$ hidden units, then the output is a 3D tensor with size $N \\times M \\times L$. The output of each LSTM cell has size $L$, we have $M$ of them, one for each sequence step, and we have $N$ sequences. So the total size is $N \\times M \\times L$.\n\nWe are using the same fully connected layer, the same weights, for each of the outputs. Then, to make things easier, we should reshape the outputs into a 2D tensor with shape $(M * N) \\times L$. That is, one row for each sequence and step, where the values of each row are the output from the LSTM cells.\n\nOne we have the outputs reshaped, we can do the matrix multiplication with the weights. We need to wrap the weight and bias variables in a variable scope with `tf.variable_scope(scope_name)` because there are weights being created in the LSTM cells. TensorFlow will throw an error if the weights created here have the same names as the weights created in the LSTM cells, which they will be default. To avoid this, we wrap the variables in a variable scope so we can give them unique names.",
"_____no_output_____"
]
],
[
[
"def build_output(lstm_output, in_size, out_size):\n ''' Build a softmax layer, return the softmax output and logits.\n \n Arguments\n ---------\n \n x: Input tensor\n in_size: Size of the input tensor, for example, size of the LSTM cells\n out_size: Size of this softmax layer\n \n '''\n\n # Reshape output so it's a bunch of rows, one row for each step for each sequence.\n # That is, the shape should be batch_size*num_steps rows by lstm_size columns\n seq_output = tf.concat(lstm_output, axis=1)\n x = tf.reshape(seq_output, [-1, in_size])\n \n # Connect the RNN outputs to a softmax layer\n with tf.variable_scope('softmax'):\n softmax_w = tf.Variable(tf.truncated_normal((in_size, out_size), stddev=0.1))\n softmax_b = tf.Variable(tf.zeros(out_size))\n \n # Since output is a bunch of rows of RNN cell outputs, logits will be a bunch\n # of rows of logit outputs, one for each step and sequence\n logits = tf.matmul(x, softmax_w) + softmax_b\n \n # Use softmax to get the probabilities for predicted characters\n out = tf.nn.softmax(logits, name='predictions')\n \n return out, logits",
"_____no_output_____"
]
],
[
[
"### Training loss\n\nNext up is the training loss. We get the logits and targets and calculate the softmax cross-entropy loss. First we need to one-hot encode the targets, we're getting them as encoded characters. Then, reshape the one-hot targets so it's a 2D tensor with size $(M*N) \\times C$ where $C$ is the number of classes/characters we have. Remember that we reshaped the LSTM outputs and ran them through a fully connected layer with $C$ units. So our logits will also have size $(M*N) \\times C$.\n\nThen we run the logits and targets through `tf.nn.softmax_cross_entropy_with_logits` and find the mean to get the loss.",
"_____no_output_____"
]
],
[
[
"def build_loss(logits, targets, lstm_size, num_classes):\n ''' Calculate the loss from the logits and the targets.\n \n Arguments\n ---------\n logits: Logits from final fully connected layer\n targets: Targets for supervised learning\n lstm_size: Number of LSTM hidden units\n num_classes: Number of classes in targets\n \n '''\n \n # One-hot encode targets and reshape to match logits, one row per batch_size per step\n y_one_hot = tf.one_hot(targets, num_classes)\n y_reshaped = tf.reshape(y_one_hot, logits.get_shape())\n \n # Softmax cross entropy loss\n loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_reshaped)\n loss = tf.reduce_mean(loss)\n return loss",
"_____no_output_____"
]
],
[
[
"### Optimizer\n\nHere we build the optimizer. Normal RNNs have have issues gradients exploding and disappearing. LSTMs fix the disappearance problem, but the gradients can still grow without bound. To fix this, we can clip the gradients above some threshold. That is, if a gradient is larger than that threshold, we set it to the threshold. This will ensure the gradients never grow overly large. Then we use an AdamOptimizer for the learning step.",
"_____no_output_____"
]
],
[
[
"def build_optimizer(loss, learning_rate, grad_clip):\n ''' Build optmizer for training, using gradient clipping.\n \n Arguments:\n loss: Network loss\n learning_rate: Learning rate for optimizer\n \n '''\n \n # Optimizer for training, using gradient clipping to control exploding gradients\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars), grad_clip)\n train_op = tf.train.AdamOptimizer(learning_rate)\n optimizer = train_op.apply_gradients(zip(grads, tvars))\n \n return optimizer",
"_____no_output_____"
]
],
[
[
"### Build the network\n\nNow we can put all the pieces together and build a class for the network. To actually run data through the LSTM cells, we will use [`tf.nn.dynamic_rnn`](https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/nn/dynamic_rnn). This function will pass the hidden and cell states across LSTM cells appropriately for us. It returns the outputs for each LSTM cell at each step for each sequence in the mini-batch. It also gives us the final LSTM state. We want to save this state as `final_state` so we can pass it to the first LSTM cell in the the next mini-batch run. For `tf.nn.dynamic_rnn`, we pass in the cell and initial state we get from `build_lstm`, as well as our input sequences. Also, we need to one-hot encode the inputs before going into the RNN. ",
"_____no_output_____"
]
],
[
[
"class CharRNN:\n \n def __init__(self, num_classes, batch_size=64, num_steps=50, \n lstm_size=128, num_layers=2, learning_rate=0.001, \n grad_clip=5, sampling=False):\n \n # When we're using this network for sampling later, we'll be passing in\n # one character at a time, so providing an option for that\n if sampling == True:\n batch_size, num_steps = 1, 1\n else:\n batch_size, num_steps = batch_size, num_steps\n\n tf.reset_default_graph()\n \n # Build the input placeholder tensors\n self.inputs, self.targets, self.keep_prob = build_inputs(batch_size, num_steps)\n\n # Build the LSTM cell\n cell, self.initial_state = build_lstm(lstm_size, num_layers, batch_size, self.keep_prob)\n\n ### Run the data through the RNN layers\n # First, one-hot encode the input tokens\n x_one_hot = tf.one_hot(self.inputs, num_classes)\n \n # Run each sequence step through the RNN and collect the outputs\n outputs, state = tf.nn.dynamic_rnn(cell, x_one_hot, initial_state=self.initial_state)\n self.final_state = state\n \n # Get softmax predictions and logits\n self.prediction, self.logits = build_output(outputs, lstm_size, num_classes)\n \n # Loss and optimizer (with gradient clipping)\n self.loss = build_loss(self.logits, self.targets, lstm_size, num_classes)\n self.optimizer = build_optimizer(self.loss, learning_rate, grad_clip)",
"_____no_output_____"
]
],
[
[
"## Hyperparameters\n\nHere I'm defining the hyperparameters for the network. \n\n* `batch_size` - Number of sequences running through the network in one pass.\n* `num_steps` - Number of characters in the sequence the network is trained on. Larger is better typically, the network will learn more long range dependencies. But it takes longer to train. 100 is typically a good number here.\n* `lstm_size` - The number of units in the hidden layers.\n* `num_layers` - Number of hidden LSTM layers to use\n* `learning_rate` - Learning rate for training\n* `keep_prob` - The dropout keep probability when training. If you're network is overfitting, try decreasing this.\n\nHere's some good advice from Andrej Karpathy on training the network. I'm going to copy it in here for your benefit, but also link to [where it originally came from](https://github.com/karpathy/char-rnn#tips-and-tricks).\n\n> ## Tips and Tricks\n\n>### Monitoring Validation Loss vs. Training Loss\n>If you're somewhat new to Machine Learning or Neural Networks it can take a bit of expertise to get good models. The most important quantity to keep track of is the difference between your training loss (printed during training) and the validation loss (printed once in a while when the RNN is run on the validation data (by default every 1000 iterations)). In particular:\n\n> - If your training loss is much lower than validation loss then this means the network might be **overfitting**. Solutions to this are to decrease your network size, or to increase dropout. For example you could try dropout of 0.5 and so on.\n> - If your training/validation loss are about equal then your model is **underfitting**. Increase the size of your model (either number of layers or the raw number of neurons per layer)\n\n> ### Approximate number of parameters\n\n> The two most important parameters that control the model are `lstm_size` and `num_layers`. I would advise that you always use `num_layers` of either 2/3. The `lstm_size` can be adjusted based on how much data you have. The two important quantities to keep track of here are:\n\n> - The number of parameters in your model. This is printed when you start training.\n> - The size of your dataset. 1MB file is approximately 1 million characters.\n\n>These two should be about the same order of magnitude. It's a little tricky to tell. Here are some examples:\n\n> - I have a 100MB dataset and I'm using the default parameter settings (which currently print 150K parameters). My data size is significantly larger (100 mil >> 0.15 mil), so I expect to heavily underfit. I am thinking I can comfortably afford to make `lstm_size` larger.\n> - I have a 10MB dataset and running a 10 million parameter model. I'm slightly nervous and I'm carefully monitoring my validation loss. If it's larger than my training loss then I may want to try to increase dropout a bit and see if that helps the validation loss.\n\n> ### Best models strategy\n\n>The winning strategy to obtaining very good models (if you have the compute time) is to always err on making the network larger (as large as you're willing to wait for it to compute) and then try different dropout values (between 0,1). Whatever model has the best validation performance (the loss, written in the checkpoint filename, low is good) is the one you should use in the end.\n\n>It is very common in deep learning to run many different models with many different hyperparameter settings, and in the end take whatever checkpoint gave the best validation performance.\n\n>By the way, the size of your training and validation splits are also parameters. Make sure you have a decent amount of data in your validation set or otherwise the validation performance will be noisy and not very informative.\n",
"_____no_output_____"
]
],
[
[
"batch_size = 100 # Sequences per batch\nnum_steps = 100 # Number of sequence steps per batch\nlstm_size = 512 # Size of hidden layers in LSTMs\nnum_layers = 2 # Number of LSTM layers\nlearning_rate = 0.001 # Learning rate\nkeep_prob = 0.5 # Dropout keep probability",
"_____no_output_____"
]
],
[
[
"## Time for training\n\nThis is typical training code, passing inputs and targets into the network, then running the optimizer. Here we also get back the final LSTM state for the mini-batch. Then, we pass that state back into the network so the next batch can continue the state from the previous batch. And every so often (set by `save_every_n`) I save a checkpoint.\n\nHere I'm saving checkpoints with the format\n\n`i{iteration number}_l{# hidden layer units}.ckpt`",
"_____no_output_____"
]
],
[
[
"epochs = 20\n# Print losses every N interations\nprint_every_n = 50\n\n# Save every N iterations\nsave_every_n = 200\n\nmodel = CharRNN(len(vocab), batch_size=batch_size, num_steps=num_steps,\n lstm_size=lstm_size, num_layers=num_layers, \n learning_rate=learning_rate)\n\nsaver = tf.train.Saver(max_to_keep=100)\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n \n # Use the line below to load a checkpoint and resume training\n #saver.restore(sess, 'checkpoints/______.ckpt')\n counter = 0\n for e in range(epochs):\n # Train network\n new_state = sess.run(model.initial_state)\n loss = 0\n for x, y in get_batches(encoded, batch_size, num_steps):\n counter += 1\n start = time.time()\n feed = {model.inputs: x,\n model.targets: y,\n model.keep_prob: keep_prob,\n model.initial_state: new_state}\n batch_loss, new_state, _ = sess.run([model.loss, \n model.final_state, \n model.optimizer], \n feed_dict=feed)\n if (counter % print_every_n == 0):\n end = time.time()\n print('Epoch: {}/{}... '.format(e+1, epochs),\n 'Training Step: {}... '.format(counter),\n 'Training loss: {:.4f}... '.format(batch_loss),\n '{:.4f} sec/batch'.format((end-start)))\n \n if (counter % save_every_n == 0):\n saver.save(sess, \"checkpoints/i{}_l{}.ckpt\".format(counter, lstm_size))\n \n saver.save(sess, \"checkpoints/i{}_l{}.ckpt\".format(counter, lstm_size))",
"_____no_output_____"
]
],
[
[
"#### Saved checkpoints\n\nRead up on saving and loading checkpoints here: https://www.tensorflow.org/programmers_guide/variables",
"_____no_output_____"
]
],
[
[
"tf.train.get_checkpoint_state('checkpoints')",
"_____no_output_____"
]
],
[
[
"## Sampling\n\nNow that the network is trained, we'll can use it to generate new text. The idea is that we pass in a character, then the network will predict the next character. We can use the new one, to predict the next one. And we keep doing this to generate all new text. I also included some functionality to prime the network with some text by passing in a string and building up a state from that.\n\nThe network gives us predictions for each character. To reduce noise and make things a little less random, I'm going to only choose a new character from the top N most likely characters.\n\n",
"_____no_output_____"
]
],
[
[
"def pick_top_n(preds, vocab_size, top_n=5):\n p = np.squeeze(preds)\n p[np.argsort(p)[:-top_n]] = 0\n p = p / np.sum(p)\n c = np.random.choice(vocab_size, 1, p=p)[0]\n return c",
"_____no_output_____"
],
[
"def sample(checkpoint, n_samples, lstm_size, vocab_size, prime=\"The \"):\n samples = [c for c in prime]\n model = CharRNN(len(vocab), lstm_size=lstm_size, sampling=True)\n saver = tf.train.Saver()\n with tf.Session() as sess:\n saver.restore(sess, checkpoint)\n new_state = sess.run(model.initial_state)\n for c in prime:\n x = np.zeros((1, 1))\n x[0,0] = vocab_to_int[c]\n feed = {model.inputs: x,\n model.keep_prob: 1.,\n model.initial_state: new_state}\n preds, new_state = sess.run([model.prediction, model.final_state], \n feed_dict=feed)\n\n c = pick_top_n(preds, len(vocab))\n samples.append(int_to_vocab[c])\n\n for i in range(n_samples):\n x[0,0] = c\n feed = {model.inputs: x,\n model.keep_prob: 1.,\n model.initial_state: new_state}\n preds, new_state = sess.run([model.prediction, model.final_state], \n feed_dict=feed)\n\n c = pick_top_n(preds, len(vocab))\n samples.append(int_to_vocab[c])\n \n return ''.join(samples)",
"_____no_output_____"
]
],
[
[
"Here, pass in the path to a checkpoint and sample from the network.",
"_____no_output_____"
]
],
[
[
"tf.train.latest_checkpoint('checkpoints')",
"_____no_output_____"
],
[
"checkpoint = tf.train.latest_checkpoint('checkpoints')\nsamp = sample(checkpoint, 2000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)",
"_____no_output_____"
],
[
"checkpoint = 'checkpoints/i200_l512.ckpt'\nsamp = sample(checkpoint, 1000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)",
"_____no_output_____"
],
[
"checkpoint = 'checkpoints/i600_l512.ckpt'\nsamp = sample(checkpoint, 1000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)",
"_____no_output_____"
],
[
"checkpoint = 'checkpoints/i1200_l512.ckpt'\nsamp = sample(checkpoint, 1000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)",
"_____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",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
d0aca803ee4e1622d53a9acb67302f53a7bf53fc | 333,361 | ipynb | Jupyter Notebook | DataSciencefilmes.ipynb | KazumaShachou/DataSciencePython | 04219f3eda5f32e2a7544928cb345bf426fee55f | [
"MIT"
] | null | null | null | DataSciencefilmes.ipynb | KazumaShachou/DataSciencePython | 04219f3eda5f32e2a7544928cb345bf426fee55f | [
"MIT"
] | null | null | null | DataSciencefilmes.ipynb | KazumaShachou/DataSciencePython | 04219f3eda5f32e2a7544928cb345bf426fee55f | [
"MIT"
] | null | null | null | 86.184333 | 56,550 | 0.714574 | [
[
[
"print('Kazuma Shachou')",
"Kazuma Shachou\n"
],
[
"nome_do_filme = \"Bakamon\"",
"_____no_output_____"
],
[
"print(nome_do_filme)",
"Bakamon\n"
],
[
"nome_do_filme",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"filmes = pd.read_csv(\"https://raw.githubusercontent.com/alura-cursos/introducao-a-data-science/master/aula0/ml-latest-small/movies.csv\")\nfilmes.columns = [\"filmeid\", \"titulo\", \"generos\"]\nfilmes.head()",
"_____no_output_____"
],
[
"# Lendo a documwentação de um método atributo\n\n?filmes.head",
"_____no_output_____"
],
[
"#Lendo a documentação do tipo(docstring)\n\n?filmes\navaliacoes = pd.read_csv(\"https://raw.githubusercontent.com/alura-cursos/introducao-a-data-science/master/aula0/ml-latest-small/ratings.csv\")\navaliacoes.head()",
"_____no_output_____"
],
[
"avaliacoes.shape",
"_____no_output_____"
],
[
"len(avaliacoes)",
"_____no_output_____"
],
[
"avaliacoes.columns = [\"usuárioid\", \"filmeid\", \"nota\", \"momento\"]\navaliacoes.head()",
"_____no_output_____"
],
[
"avaliacoes.query(\"filmeid==1\")",
"_____no_output_____"
],
[
"avaliacoes.describe()",
"_____no_output_____"
],
[
"avaliacoes[\"nota\"]",
"_____no_output_____"
],
[
"avaliacoes.query(\"filmeid == 1\").describe()",
"_____no_output_____"
],
[
"avaliacoes.query(\"filmeid == 1\").mean()",
"_____no_output_____"
],
[
"avaliacoes.query(\"filmeid == 1\")[\"nota\"].mean()",
"_____no_output_____"
],
[
"notas_media_por_filme = avaliacoes.groupby(\"filmeid\")[\"nota\"].mean()\nnotas_media_por_filme.head()",
"_____no_output_____"
],
[
" #risco de filmes nao estarem em quantidade exata\n #filme[\"nota media\"] = notas_media_por_filme\n #filmes.head()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"##desafio 1: \nEncontre os 18 filmes que não tiveram avaliação\n",
"_____no_output_____"
]
],
[
[
"filmes_com_media = filmes.join(notas_media_por_filme, on = \"filmeid\")\nfilmes_com_media.head()",
"_____no_output_____"
]
],
[
[
"##desafio 2\nmudar o nome da coluna nota para media apos o join\n",
"_____no_output_____"
]
],
[
[
"filmes_com_media.sort_values(\"nota\", ascending=False).head(15)",
"_____no_output_____"
]
],
[
[
"##desafio 3\ncoloque o numero de avaliações por filme",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\navaliacoes.query(\"filmeid == 1\")[\"nota\"].plot(kind = 'hist',\n title= \"avaliações do filme toy story\")\n#plt.title(\"Avaliações do filme toy story\")\nplt.show()",
"_____no_output_____"
],
[
"avaliacoes.query(\"filmeid == 1\")[\"nota\"].plot(kind = 'hist') ",
"_____no_output_____"
],
[
"avaliacoes.query(\"filmeid == 2\")[\"nota\"].plot(kind = 'hist') ",
"_____no_output_____"
],
[
"avaliacoes.query(\"filmeid == 102084\")[\"nota\"].plot(kind = 'hist') ",
"_____no_output_____"
]
],
[
[
"##desafio4\narredondar o valor da coluna de nota media em 2 casas",
"_____no_output_____"
],
[
"##desafio5 \ndescobrir os generos de filmes(quais são eles, unicos) (esse daqui o bicho pega)",
"_____no_output_____"
],
[
"##desafio6\ncontar o numero de aparições de cada genero.",
"_____no_output_____"
],
[
"##desafio7\nplotar o gráfico de aparições por genero, pode ser um gráfico de tipo igual a \nbarra\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"# Aula 2 \n\n\n",
"_____no_output_____"
]
],
[
[
"filmes[\"generos\"].str.get_dummies('|').sum() #srt é string, para cortar a parte que você quer, get dummies cria variaveis que true é 1 e 0 falso, por ultimo o | é para separação, por ultimo \"sum\" é somar generos\n",
"_____no_output_____"
],
[
"filmes[\"generos\"].str.get_dummies('|').sum().sort_values(ascending=False) #ordenar por ordem decrescente generos",
"_____no_output_____"
],
[
"filmes.index #dataframe do filme, tem o indice que vai do 0 até 9742 ",
"_____no_output_____"
],
[
"filmes\n",
"_____no_output_____"
],
[
"filmes.values ",
"_____no_output_____"
],
[
"filmes['generos'].str.get_dummies('|').sum().sort_values(ascending=False).index",
"_____no_output_____"
],
[
"filmes['generos'].str.get_dummies('|').sum().sort_values(ascending=False).values #valores",
"_____no_output_____"
],
[
"filmes['generos'].str.get_dummies('|').sum().sort_index() #ordenar pelo indice, ordem alfabetica",
"_____no_output_____"
],
[
"filmes['generos'].str.get_dummies('|').sum().sort_values(ascending=False).plot()\n#naofaz sentido nenhum porque esta se referindo diferentamente ao genero, nao ao genero mais visto",
"_____no_output_____"
],
[
"filmes['generos'].str.get_dummies('|').sum().sort_values(ascending=False).plot(\n kind='pie',\n title = 'gráfico de generos',\n figsize =(8,8))\nplt.show()",
"_____no_output_____"
],
[
" filmes['generos'].str.get_dummies('|').sum().sort_values(ascending=False).plot(\n kind='bar',\n title = 'gráfico de generos',\n figsize =(8,8))\nplt.show()",
"_____no_output_____"
],
[
"import seaborn as sns\nsns.set_style(\"whitegrid\")\n\nfilmes_por_genero = filmes['generos'].str.get_dummies('|').sum().sort_index().sort_values(ascending = False)\nplt.figure(figsize = (16,8))\nplt.xticks(rotation=45)\n\nsns.barplot(x = filmes_por_genero.index,\n y = filmes_por_genero.values,\n palette=sns.color_palette(\"BuGn_r\",n_colors =len(filmes_por_genero) + 10 ))\nplt.show()\n",
"/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n"
],
[
"pop = 1000\nsal = 1000000\n\nsalario999 = 1\nmedia = (sal * 1 + salario999 * 999)/1000\nmedia",
"_____no_output_____"
],
[
"notas_media_por_filme.describe()",
"_____no_output_____"
],
[
"filmes_com_media.sort_values('nota', ascending=False)[2450:2500] #selecionando para ver os filmes entre o numero 2450 e 2500\n",
"_____no_output_____"
],
[
"notas_do_filme_2 = avaliacoes.query(\"filmeid==1\")[\"nota\"]\nprint(notas_do_filme_2.mean())\navaliacoes.query(\"filmeid==1\")[\"nota\"].plot(kind='hist')\n",
"3.9209302325581397\n"
],
[
"notas_do_filme_2.describe()",
"_____no_output_____"
],
[
"avaliacoes.groupby(\"filmeid\").mean()",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"filmes",
"_____no_output_____"
],
[
"filmes_com_media.sort_values(\"nota\", ascending= False)[2450:2500]",
"_____no_output_____"
],
[
"def plot_filme(n) :\n\n notas_do_filme = avaliacoes.query(f\"filmeid=={n}\")[\"nota\"]\n notas_do_filme.plot(kind='hist')\n return notas_do_filme.describe()\nplot_filme(919)\n",
"_____no_output_____"
],
[
"plot_filme(46578)",
"_____no_output_____"
],
[
"def plot_filme(n) :\n\n notas_do_filme = avaliacoes.query(f\"filmeid=={n}\")[\"nota\"]\n notas_do_filme.plot(kind='hist')\n plt.show()\n notas_do_filme.plot.box()\n plt.show\n return notas_do_filme.describe()",
"_____no_output_____"
],
[
" plot_filme(919)",
"_____no_output_____"
],
[
"sns.boxplot(data = avaliacoes.query('filmeid in [1,2,919,46578]'), x = \"filmeid\", y= \"nota\")",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"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"
],
[
"markdown"
],
[
"code"
]
] |
d0acac05224b9deef235416e01bf8f3e09147cb1 | 757,836 | ipynb | Jupyter Notebook | dogs-vs-cats-transfer-learning.ipynb | saptarshidatta96/Transfer-Learning-with-VGG-16 | 914bf49c0521acb6729dea5138d19514226bc909 | [
"Apache-2.0"
] | null | null | null | dogs-vs-cats-transfer-learning.ipynb | saptarshidatta96/Transfer-Learning-with-VGG-16 | 914bf49c0521acb6729dea5138d19514226bc909 | [
"Apache-2.0"
] | null | null | null | dogs-vs-cats-transfer-learning.ipynb | saptarshidatta96/Transfer-Learning-with-VGG-16 | 914bf49c0521acb6729dea5138d19514226bc909 | [
"Apache-2.0"
] | null | null | null | 457.630435 | 436,996 | 0.937596 | [
[
[
"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session",
"/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip\n/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\n/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv\n"
],
[
"print(os.listdir(\"../input/dogs-vs-cats-redux-kernels-edition/\"))",
"['test.zip', 'train.zip', 'sample_submission.csv']\n"
],
[
"import numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Activation, Dense, Flatten, BatchNormalization, Conv2D, MaxPool2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.metrics import confusion_matrix\nimport itertools\nimport os\nimport shutil\nimport random\nimport glob\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n%matplotlib inline",
"_____no_output_____"
],
[
"!unzip -q ../input/dogs-vs-cats-redux-kernels-edition/train.zip",
"_____no_output_____"
],
[
"!unzip -q ../input/dogs-vs-cats-redux-kernels-edition/test.zip",
"_____no_output_____"
],
[
"filenames = os.listdir(\"/kaggle/working/test\")\nfor filename in filenames:\n test_df = pd.DataFrame({\n 'filename': filenames\n})\n\ntest_df.index = test_df.index + 1\ntest_df.head()",
"_____no_output_____"
],
[
"print(os.listdir(\"/kaggle/working\"))",
"['train', '__notebook__.ipynb', 'test']\n"
],
[
"filenames = os.listdir(\"/kaggle/working/train\")\ncategories = []\nfor filename in filenames:\n category = filename.split('.')[0]\n if category == 'dog':\n categories.append(1)\n else:\n categories.append(0)\n\ndf = pd.DataFrame({\n 'filename': filenames,\n 'category': categories\n})\ndf.head()",
"_____no_output_____"
],
[
"sns.countplot(df['category'])",
"_____no_output_____"
],
[
"df['category'] = df['category'].astype(str)",
"_____no_output_____"
],
[
"train_df, validate_df = train_test_split(df, test_size=0.1)\ntrain_df = train_df.reset_index()\nvalidate_df = validate_df.reset_index()",
"_____no_output_____"
],
[
"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]",
"_____no_output_____"
],
[
"print(total_train)\nprint(total_validate)",
"22500\n2500\n"
],
[
"train_batches = ImageDataGenerator(\n rotation_range=15,\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest',\n width_shift_range=0.1,\n height_shift_range=0.1) \\\n .flow_from_dataframe(\n train_df, \n \"/kaggle/working/train\", \n x_col='filename',\n y_col='category',\n class_mode='binary',\n target_size=(224, 224),\n batch_size=124)\n\nvalid_batches = ImageDataGenerator(rescale=1./255) \\\n .flow_from_dataframe(\n validate_df, \n \"/kaggle/working/train\", \n x_col='filename',\n y_col='category',\n class_mode='binary',\n target_size=(224, 224),\n batch_size=124)\n\ntest_batches = ImageDataGenerator(rescale=1./255) \\\n .flow_from_dataframe(\n test_df, \n \"/kaggle/working/test\", \n x_col='filename',\n y_col=None,\n class_mode=None,\n batch_size=124,\n target_size=(224, 224),\n shuffle=False\n)",
"Found 22500 validated image filenames belonging to 2 classes.\nFound 2500 validated image filenames belonging to 2 classes.\nFound 12500 validated image filenames.\n"
],
[
"assert train_batches.n == 22500\nassert valid_batches.n == 2500",
"_____no_output_____"
],
[
"imgs, labels = next(train_batches)",
"_____no_output_____"
],
[
"# This function will plot images in the form of a grid with 1 row and 10 columns where images are placed in each column.\ndef plotImages(images_arr):\n fig, axes = plt.subplots(1, 10, figsize=(20,20))\n axes = axes.flatten()\n for img, ax in zip( images_arr, axes):\n ax.imshow(img)\n ax.axis('off')\n plt.tight_layout()\n plt.show()",
"_____no_output_____"
],
[
"plotImages(imgs)\nprint(labels[0:10])",
"_____no_output_____"
],
[
"model= tf.keras.models.Sequential(\n [tf.keras.layers.Conv2D(filters = 64, kernel_size = (3,3), activation = 'relu', input_shape = (224,224,3)),\n tf.keras.layers.Conv2D(filters = 64, kernel_size = (3,3), activation = 'relu'),\n tf.keras.layers.MaxPooling2D(2, 2),\n tf.keras.layers.Dropout(.25),\n tf.keras.layers.Conv2D(filters = 64, kernel_size = (3,3), activation = 'relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')]\n)",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 222, 222, 64) 1792 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 220, 220, 64) 36928 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 110, 110, 64) 0 \n_________________________________________________________________\ndropout (Dropout) (None, 110, 110, 64) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 108, 108, 64) 36928 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 54, 54, 64) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 186624) 0 \n_________________________________________________________________\ndense (Dense) (None, 128) 23888000 \n_________________________________________________________________\ndense_1 (Dense) (None, 1) 129 \n=================================================================\nTotal params: 23,963,777\nTrainable params: 23,963,777\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"model.compile(optimizer=Adam(learning_rate=0.0001),\n loss='binary_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"model.fit(x=train_batches,\n steps_per_epoch=len(train_batches),\n validation_data=valid_batches,\n validation_steps=len(valid_batches),\n epochs=2,\n verbose=2\n)",
"Epoch 1/2\n182/182 - 344s - loss: 0.6734 - accuracy: 0.5904 - val_loss: 0.6204 - val_accuracy: 0.6984\nEpoch 2/2\n182/182 - 332s - loss: 0.5923 - accuracy: 0.6782 - val_loss: 0.5587 - val_accuracy: 0.7304\n"
]
],
[
[
"Since accuracy is not that great, we will use a pre-trained model with transfer learning.",
"_____no_output_____"
]
],
[
[
"train_batches1 = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input) \\\n .flow_from_dataframe(\n train_df, \n \"/kaggle/working/train\", \n x_col='filename',\n y_col='category',\n class_mode='binary',\n target_size=(224, 224),\n batch_size=124)\n\nvalid_batches1 = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input) \\\n .flow_from_dataframe(\n validate_df, \n \"/kaggle/working/train\", \n x_col='filename',\n y_col='category',\n class_mode='binary',\n target_size=(224, 224),\n batch_size=124)\n\ntest_batches1 = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input) \\\n .flow_from_dataframe(\n test_df, \n \"/kaggle/working/test\", \n x_col='filename',\n y_col=None,\n class_mode=None,\n batch_size=124,\n target_size=(224, 224),\n shuffle=False\n)",
"Found 22500 validated image filenames belonging to 2 classes.\nFound 2500 validated image filenames belonging to 2 classes.\nFound 12500 validated image filenames.\n"
],
[
"imgs, labels = next(train_batches1)\nplotImages(imgs)\nprint(labels[0:10])",
"_____no_output_____"
],
[
"vgg16_model = tf.keras.applications.vgg16.VGG16()",
"Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5\n553467904/553467096 [==============================] - 5s 0us/step\n"
],
[
"vgg16_model.summary()",
"Model: \"vgg16\"\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_________________________________________________________________\nflatten (Flatten) (None, 25088) 0 \n_________________________________________________________________\nfc1 (Dense) (None, 4096) 102764544 \n_________________________________________________________________\nfc2 (Dense) (None, 4096) 16781312 \n_________________________________________________________________\npredictions (Dense) (None, 1000) 4097000 \n=================================================================\nTotal params: 138,357,544\nTrainable params: 138,357,544\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"Removing the Last Layer",
"_____no_output_____"
]
],
[
[
"model = Sequential()\nfor layer in vgg16_model.layers[:-1]:\n model.add(layer)",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \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_________________________________________________________________\nflatten (Flatten) (None, 25088) 0 \n_________________________________________________________________\nfc1 (Dense) (None, 4096) 102764544 \n_________________________________________________________________\nfc2 (Dense) (None, 4096) 16781312 \n=================================================================\nTotal params: 134,260,544\nTrainable params: 134,260,544\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"for layer in model.layers:\n layer.trainable = False",
"_____no_output_____"
],
[
"model.add(Dense(units=1, activation='sigmoid'))",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \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_________________________________________________________________\nflatten (Flatten) (None, 25088) 0 \n_________________________________________________________________\nfc1 (Dense) (None, 4096) 102764544 \n_________________________________________________________________\nfc2 (Dense) (None, 4096) 16781312 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 4097 \n=================================================================\nTotal params: 134,264,641\nTrainable params: 4,097\nNon-trainable params: 134,260,544\n_________________________________________________________________\n"
],
[
"model.compile(optimizer=Adam(learning_rate=0.0001),\n loss='binary_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"model.fit(x=train_batches1,\n steps_per_epoch=len(train_batches1),\n validation_data=valid_batches1,\n validation_steps=len(valid_batches1),\n epochs=3,\n verbose=2)",
"Epoch 1/3\n182/182 - 114s - loss: 0.2074 - accuracy: 0.9144 - val_loss: 0.0748 - val_accuracy: 0.9764\nEpoch 2/3\n182/182 - 112s - loss: 0.0647 - accuracy: 0.9785 - val_loss: 0.0541 - val_accuracy: 0.9800\nEpoch 3/3\n182/182 - 111s - loss: 0.0519 - accuracy: 0.9826 - val_loss: 0.0470 - val_accuracy: 0.9832\n"
]
],
[
[
"Predict",
"_____no_output_____"
]
],
[
[
"results = model.predict(test_batches)",
"_____no_output_____"
],
[
"test_df['category'] = np.where(results > 0.5, 1,0)",
"_____no_output_____"
]
],
[
[
"Submission",
"_____no_output_____"
]
],
[
[
"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0acbab85e2d0e8f9abcf9ceb313967c165a196b | 994,057 | ipynb | Jupyter Notebook | RF_model_with_PCA.ipynb | shilpiray/ML_Project | 505ff31a332b0988eb47cc26dc41eff7cd7d4be6 | [
"CC-BY-3.0"
] | null | null | null | RF_model_with_PCA.ipynb | shilpiray/ML_Project | 505ff31a332b0988eb47cc26dc41eff7cd7d4be6 | [
"CC-BY-3.0"
] | null | null | null | RF_model_with_PCA.ipynb | shilpiray/ML_Project | 505ff31a332b0988eb47cc26dc41eff7cd7d4be6 | [
"CC-BY-3.0"
] | null | null | null | 396.512565 | 696,952 | 0.909501 | [
[
[
"# Import Dependencies",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\n# scaling and dataset split\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n# OLS, Ridge\nfrom sklearn.linear_model import LinearRegression, Ridge\n# model evaluation\nfrom sklearn.metrics import r2_score, mean_squared_error",
"_____no_output_____"
]
],
[
[
"# Read the CSV and Perform Basic Data Cleaning",
"_____no_output_____"
]
],
[
[
"data_to_load = \"new_folder/googleplaystore.csv\"\ndf_apps = pd.read_csv(data_to_load)",
"_____no_output_____"
],
[
"categories = list(df_apps[\"Category\"].unique())\n#Remove Category 1.9\ncategories.remove('1.9')\n\na = df_apps.loc[df_apps[\"Category\"] == \"1.9\"]\ndf_apps = df_apps.drop(int(a.index.values),axis=0)\n\n#df_apps = df_apps[df_apps['Category']!= \"1.9\"]",
"_____no_output_____"
],
[
"df_apps = df_apps.drop(df_apps[df_apps['Rating'].isnull()].index, axis=0)",
"_____no_output_____"
],
[
"df_apps[\"Type\"] = (df_apps[\"Type\"] == \"Paid\").astype(int)",
"_____no_output_____"
],
[
"#Extract App, Installs, & Content Rating from df_apps\npopApps = df_apps.copy()\npopApps = popApps.drop_duplicates()\n#Remove characters preventing values from being floats and integers\npopApps[\"Installs\"] = popApps[\"Installs\"].str.replace(\"+\",\"\") \npopApps[\"Installs\"] = popApps[\"Installs\"].str.replace(\",\",\"\")\npopApps[\"Installs\"] = popApps[\"Installs\"].astype(\"int64\")\npopApps[\"Price\"] = popApps[\"Price\"].str.replace(\"$\",\"\")\npopApps[\"Price\"] = popApps[\"Price\"].astype(\"float64\")\npopApps[\"Size\"] = popApps[\"Size\"].str.replace(\"Varies with device\",\"0\")\npopApps[\"Size\"] = (popApps[\"Size\"].replace(r'[kM]+$', '', regex=True).astype(float) *\\\n popApps[\"Size\"].str.extract(r'[\\d\\.]+([kM]+)', expand=False).fillna(1).replace(['k','M'], [10**3, 10**6]).astype(int))\npopApps[\"Reviews\"] = popApps[\"Reviews\"].astype(\"int64\")\n\npopApps.reset_index(inplace=True)\npopApps.drop([\"index\"],axis=1,inplace=True)",
"_____no_output_____"
],
[
"popAppsCopy = popApps.drop([\"App\",\"Last Updated\",\"Current Ver\",\"Android Ver\",\"Type\"],axis=1)",
"_____no_output_____"
],
[
"X = popAppsCopy.drop(\"Installs\", axis = 1)\ny = popAppsCopy[\"Installs\"]\ny = y.replace({1:'1000+',5: '1000+', 10: '1000+',50:'1000+',100:'1000+',500:'1000+',\n 1000: '1000+',5000:'10000+',10000: '10000+', 50000:'100000+',100000:'100000+',\n 500000:'1000000+', 1000000:'1000000+',5000000:'10000000+',10000000:'10000000+',\n 50000000:'100000000+',100000000:'100000000+', 500000000:'1000000000+', \n 1000000000:'1000000000+' })\nprint(X.shape, y.shape)",
"(8892, 7) (8892,)\n"
],
[
"import seaborn as sns\ncorr = X.apply(lambda x: x.factorize()[0]).corr()\nplt.figure(figsize=(12,7))\nsns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns,annot=True)\nplt.savefig('Correlation_matrix.png')",
"_____no_output_____"
],
[
"data = popAppsCopy\ndata = data.drop(\"Genres\",axis =1)\ndata_binary_encoded = pd.get_dummies(data, columns=[\"Category\"])\ndata_binary_encoded_1 = pd.get_dummies(data_binary_encoded, columns=[\"Content Rating\"])\ndata_binary_encoded_1.head()",
"_____no_output_____"
],
[
"X = data_binary_encoded_1.drop(\"Installs\", axis = 1)\ny = data_binary_encoded_1[\"Installs\"]\ny = y.replace({1:'1000+',5: '1000+', 10: '1000+',50:'1000+',100:'1000+',500:'1000+',\n 1000: '1000+',5000:'10000+',10000: '10000+', 50000:'100000+',100000:'100000+',\n 500000:'1000000+', 1000000:'1000000+',5000000:'10000000+',10000000:'10000000+',\n 50000000:'100000000+',100000000:'100000000+', 500000000:'1000000000+', \n 1000000000:'1000000000+' })\nprint(X.shape, y.shape)",
"(8892, 43) (8892,)\n"
],
[
"#X = X.drop([\"Content Rating_Adults only 18+\",\"Content Rating_Unrated\"], axis = 1)\nfeature_names = X.columns",
"_____no_output_____"
],
[
"feature_names",
"_____no_output_____"
]
],
[
[
"# Split the data into training and testing",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelEncoder, MinMaxScaler\nX_scaler = MinMaxScaler().fit(X_train)\nX_train_scaled = X_scaler.transform(X_train)\nX_test_scaled = X_scaler.transform(X_test)",
"_____no_output_____"
]
],
[
[
"# SVC Model",
"_____no_output_____"
]
],
[
[
"# Support vector machine linear classifier\nfrom sklearn.svm import SVC \nmodel = SVC(kernel='linear')\nmodel.fit(X_train_scaled, y_train)",
"_____no_output_____"
],
[
"print('Test Acc: %.3f' % model.score(X_test_scaled, y_test))",
"Test Acc: 0.305\n"
],
[
"print(f\"Training Data Score: {model.score(X_train_scaled, y_train)}\")\nprint(f\"Testing Data Score: {model.score(X_test_scaled, y_test)}\")",
"Training Data Score: 0.2949467686309792\nTesting Data Score: 0.3049932523616734\n"
],
[
"import seaborn as sns\ncorr = X.apply(lambda x: x.factorize()[0]).corr()\nplt.figure(figsize=(12,7))\nsns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns,annot=True)\nplt.savefig('large_cor.png')\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Random Forest Model",
"_____no_output_____"
]
],
[
[
"from sklearn import tree",
"_____no_output_____"
],
[
"clf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nprint('Test_score:', clf.score(X_test, y_test))\nprint('Train_score:', clf.score(X_train, y_train))",
"Test_score: 0.7206477732793523\nTrain_score: 1.0\n"
],
[
"clf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train_scaled, y_train)\nprint('Test_score:', clf.score(X_test_scaled, y_test))\nprint('Train_score:', clf.score(X_train_scaled, y_train))",
"Test_score: 0.7062528115159694\nTrain_score: 0.9998500524816314\n"
],
[
"from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=200)\nrf = rf.fit(X_train_scaled, y_train)\nprint('Test_score:', rf.score(X_test_scaled, y_test))\nprint('Train_score:',rf.score(X_train_scaled, y_train))",
"Test_score: 0.7777777777777778\nTrain_score: 0.9995501574448943\n"
],
[
"y_pred = rf.predict(X_test_scaled)",
"_____no_output_____"
],
[
"import seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\n\nlabels = np.unique(y_test)\ncm = confusion_matrix(y_test, y_pred, labels=labels)\ndf_cm = pd.DataFrame(cm, index=labels, columns=labels)\nplt.figure(figsize = (10,7))\nsns.set(font_scale=1.4)#for label size\nsns.heatmap(df_cm, annot=True,annot_kws={\"size\": 16})# font size\nprint('Accuracy' , accuracy_score(y_test, y_pred))\nplt.savefig(\"correlation_rf.png\")",
"Accuracy 0.7773279352226721\n"
],
[
"from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=200)\nrf = rf.fit(X_train_scaled, y_train)\nrf.score(X_test_scaled, y_test)",
"_____no_output_____"
]
],
[
[
"# Hyperparameter Tuning",
"_____no_output_____"
]
],
[
[
"# Create the GridSearch estimator along with a parameter object containing the values to adjust\nfrom sklearn.model_selection import GridSearchCV\nparam_grid = {'n_estimators':[100,200,300,400,500,600,700,800,900,1000],\n 'max_depth':[1,5,10,15,20]}\ngrid = GridSearchCV(rf,param_grid,verbose=3)",
"_____no_output_____"
],
[
"grid.fit(X_train,y_train)",
"C:\\Users\\User\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_split.py:1978: FutureWarning: The default value of cv will change from 3 to 5 in version 0.22. Specify it explicitly to silence this warning.\n warnings.warn(CV_WARNING, FutureWarning)\n[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n"
],
[
"# List the best parameters for this dataset\nprint(grid.best_params_)",
"{'max_depth': 20, 'n_estimators': 1000}\n"
],
[
"# List the best score\nprint(grid.best_score_)",
"0.7737291947818263\n"
],
[
"# Create the GridSearchCV model\npredictions = grid.predict(X_test)\npredictions_train = grid.predict(X_train)",
"_____no_output_____"
],
[
"# Train the model with GridSearch\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test, predictions))",
" precision recall f1-score support\n\n 1000+ 0.88 0.85 0.86 333\n 10000+ 0.72 0.74 0.73 341\n 100000+ 0.68 0.77 0.72 369\n 1000000+ 0.78 0.74 0.76 533\n 10000000+ 0.83 0.82 0.82 464\n 100000000+ 0.83 0.82 0.83 153\n 1000000000+ 1.00 0.63 0.78 30\n\n accuracy 0.78 2223\n macro avg 0.82 0.77 0.79 2223\nweighted avg 0.79 0.78 0.78 2223\n\n"
],
[
"imp_features = sorted(zip(rf.feature_importances_, feature_names), reverse=True)",
"_____no_output_____"
],
[
"imp_features",
"_____no_output_____"
],
[
"y_v = [lis[0] for lis in imp_features]\nx = [lis[1] for lis in imp_features]\nplt.figure(figsize=(12,7))\nplt.bar(y_v,x, align='center', alpha=0.5)\nplt.savefig('Knee_effect.png')",
"_____no_output_____"
]
],
[
[
"# Remove least imp features",
"_____no_output_____"
]
],
[
[
"X_red = popAppsCopy.drop([\"Genres\",\"Category\",\"Installs\",\"Content Rating\",\"Genres\"], axis = 1)\ny_red = popApps[\"Installs\"]\ny = y_red.replace({1:'1000+',5: '1000+', 10: '1000+',50:'1000+',100:'1000+',500:'1000+',\n 1000: '1000+',5000:'10000+',10000: '10000+', 50000:'100000+',100000:'100000+',\n 500000:'1000000+', 1000000:'1000000+',5000000:'10000000+',10000000:'10000000+',\n 50000000:'100000000+',100000000:'100000000+', 500000000:'1000000000+', \n 1000000000:'1000000000+' })\nprint(X_red.shape, y_red.shape)",
"(8892, 4) (8892,)\n"
],
[
"X_red.head()",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_red, y_red, random_state=42)",
"_____no_output_____"
],
[
"from sklearn import tree",
"_____no_output_____"
],
[
"clf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nclf.score(X_test, y_test)",
"_____no_output_____"
],
[
"from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=200)\nrf = rf.fit(X_train, y_train)\nrf.score(X_test, y_test)",
"_____no_output_____"
],
[
"from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=200)\nrf = rf.fit(X_train_scaled, y_train)\nrf.score(X_test_scaled, y_test)",
"_____no_output_____"
],
[
"# Create the GridSearch estimator along with a parameter object containing the values to adjust\nfrom sklearn.model_selection import GridSearchCV\nparam_grid = {'n_estimators':[100,200,300,400,500,600,700,800,900,1000],\n 'max_depth':[5,10,15,20]}\ngrid = GridSearchCV(rf,param_grid,verbose=3)",
"_____no_output_____"
],
[
"grid.fit(X_train,y_train)",
"C:\\Users\\User\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_split.py:1978: FutureWarning: The default value of cv will change from 3 to 5 in version 0.22. Specify it explicitly to silence this warning.\n warnings.warn(CV_WARNING, FutureWarning)\nC:\\Users\\User\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_split.py:657: Warning: The least populated class in y has only 2 members, which is too few. The minimum number of members in any class cannot be less than n_splits=3.\n % (min_groups, self.n_splits)), Warning)\n[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n"
],
[
"# List the best score\nprint(grid.best_score_)",
"0.5518068675963412\n"
],
[
"grid.score(X_train,y_train)",
"_____no_output_____"
]
],
[
[
"# PCA",
"_____no_output_____"
]
],
[
[
"X.head()",
"_____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, random_state=0)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler\n\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)",
"_____no_output_____"
],
[
"from sklearn.decomposition import PCA\n\npca = PCA()\nX_train = pca.fit_transform(X_train)\nX_test = pca.transform(X_test)",
"_____no_output_____"
],
[
"explained_variance = pca.explained_variance_ratio_",
"_____no_output_____"
],
[
"explained_variance",
"_____no_output_____"
],
[
"from sklearn.decomposition import PCA\n\npca = PCA(n_components=39)\nX_train = pca.fit_transform(X_train)\nX_test = pca.transform(X_test)",
"_____no_output_____"
],
[
"from sklearn.ensemble import RandomForestClassifier\n\nclassifier = RandomForestClassifier(max_depth=2, random_state=0)\nclassifier.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)",
"C:\\Users\\User\\Anaconda3\\lib\\site-packages\\sklearn\\ensemble\\forest.py:245: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.\n \"10 in version 0.20 to 100 in 0.22.\", FutureWarning)\n"
],
[
"import seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\n\nlabels = np.unique(y_test)\ncm = confusion_matrix(y_test, y_pred, labels=labels)\ndf_cm = pd.DataFrame(cm, index=labels, columns=labels)\nplt.figure(figsize = (10,7))\nsns.set(font_scale=1.4)#for label size\nsns.heatmap(df_cm, annot=True,annot_kws={\"size\": 16})# font size\nprint('Accuracy' , accuracy_score(y_test, y_pred))",
"Accuracy 0.27262507026419336\n"
]
],
[
[
"# Remove the least 2 values from knee effect",
"_____no_output_____"
]
],
[
[
"X_knee = X.drop([\"Content Rating_Adults only 18+\",\"Content Rating_Unrated\"], axis = 1)\ny_knee = y\nprint(X_knee.shape, y_knee.shape)",
"(8892, 41) (8892,)\n"
],
[
"from sklearn.model_selection import train_test_split\n\nX_train_k, X_test_k, y_train_k, y_test_k = train_test_split(X_knee, y_knee, random_state=42)\n\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler\nX_scaler_k = MinMaxScaler().fit(X_train_k)\nX_train_scaled_k = X_scaler_k.transform(X_train_k)\nX_test_scaled_k = X_scaler_k.transform(X_test_k)",
"_____no_output_____"
],
[
"from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(n_estimators=200)\nrf = rf.fit(X_train_scaled_k, y_train_k)\nrf.score(X_test_scaled_k, y_test_k)",
"_____no_output_____"
],
[
"rf.score(X_train_scaled_k, y_train_k)",
"_____no_output_____"
]
]
] | [
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0acbf86f85e9e2ca200a1e7309a6a0de0db4c28 | 715,554 | ipynb | Jupyter Notebook | Geely Auto-Boosting(Regression).ipynb | ridhimanwazir/Boosting-Regression | 73a6476b21d82a5663f2d607ae8d05aec2b4905d | [
"Apache-2.0"
] | null | null | null | Geely Auto-Boosting(Regression).ipynb | ridhimanwazir/Boosting-Regression | 73a6476b21d82a5663f2d607ae8d05aec2b4905d | [
"Apache-2.0"
] | null | null | null | Geely Auto-Boosting(Regression).ipynb | ridhimanwazir/Boosting-Regression | 73a6476b21d82a5663f2d607ae8d05aec2b4905d | [
"Apache-2.0"
] | null | null | null | 256.839196 | 173,764 | 0.896505 | [
[
[
"# Regression on Decison Trees and Random Forest",
"_____no_output_____"
]
],
[
[
"#importing important libraries\n\n#libraries for reading dataset\nimport numpy as np\nimport pandas as pd\n\n#libraries for data visualisation\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n#libraries for model building and understanding\nimport sklearn\nfrom sklearn.model_selection import train_test_split\n\n#importing label encoder\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\n\n#importing libraries for decision tree regression\nfrom IPython.display import Image \nfrom six import StringIO\nimport graphviz, pydotplus\nfrom sklearn import tree\nfrom sklearn.tree import DecisionTreeRegressor, export_graphviz\nfrom sklearn import metrics\nfrom sklearn.metrics import r2_score,mean_squared_log_error\n\n#importing libraries for boosting\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom xgboost import XGBRegressor\n\n#libraries for hyper parameter tuning\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\n#library to deal with warning\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"#to display all the columns in the dataset\npd.set_option('display.max_columns', 500)",
"_____no_output_____"
]
],
[
[
"## Reading Data",
"_____no_output_____"
]
],
[
[
"cp = pd.read_csv('carprice.csv')",
"_____no_output_____"
]
],
[
[
"### Understanding the data",
"_____no_output_____"
]
],
[
[
"cp.head()",
"_____no_output_____"
],
[
"cp.shape",
"_____no_output_____"
],
[
"cp.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 205 entries, 0 to 204\nData columns (total 26 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 car_ID 205 non-null int64 \n 1 symboling 205 non-null int64 \n 2 CarName 205 non-null object \n 3 fueltype 205 non-null object \n 4 aspiration 205 non-null object \n 5 doornumber 205 non-null object \n 6 carbody 205 non-null object \n 7 drivewheel 205 non-null object \n 8 enginelocation 205 non-null object \n 9 wheelbase 205 non-null float64\n 10 carlength 205 non-null float64\n 11 carwidth 205 non-null float64\n 12 carheight 205 non-null float64\n 13 curbweight 205 non-null int64 \n 14 enginetype 205 non-null object \n 15 cylindernumber 205 non-null object \n 16 enginesize 205 non-null int64 \n 17 fuelsystem 205 non-null object \n 18 boreratio 205 non-null float64\n 19 stroke 205 non-null float64\n 20 compressionratio 205 non-null float64\n 21 horsepower 205 non-null int64 \n 22 peakrpm 205 non-null int64 \n 23 citympg 205 non-null int64 \n 24 highwaympg 205 non-null int64 \n 25 price 205 non-null float64\ndtypes: float64(8), int64(8), object(10)\nmemory usage: 41.8+ KB\n"
],
[
"cp.describe()",
"_____no_output_____"
],
[
"#symboling is a categorical data so we convert to the specified type\n\ncp['symboling'] = cp['symboling'].apply(str)",
"_____no_output_____"
]
],
[
[
"#### There are 11 categorical data and remaining are the numerical data",
"_____no_output_____"
]
],
[
[
"#as per the bussiness requirements we only need name of the carcompany and not the carmodel\n#so we drop carmodel and only keep carCompany\n\ncp['CarName'] = cp['CarName'].str.lower()\ncp['carCompany'] = cp['CarName'].str.split(' ').str[0]\ncp = cp.drop('CarName',axis = 1)",
"_____no_output_____"
],
[
"cp.head()",
"_____no_output_____"
]
],
[
[
"## Data visualization and understanding using EDA",
"_____no_output_____"
],
[
"### Price is a dependent variable",
"_____no_output_____"
],
[
"#### Visualising numerical data",
"_____no_output_____"
]
],
[
[
"#Finding correlation\ncor = cp.corr()\ncor",
"_____no_output_____"
],
[
"# visulaising correlation using heatmap\nplt.subplots(figsize=(20, 20))\nplt.title('Correlation between each data variable')\nsns.heatmap(cor, xticklabels=cor.columns.values,\n yticklabels=cor.columns.values,annot= True,linecolor=\"black\",linewidths=2, cmap=\"viridis\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"`citympg` and `highwaympg` have negative correlation with price\n\n`carlength`,`carwidth`,`curbweight`,`enginesize` and `horsepower` have positve correlation with price",
"_____no_output_____"
]
],
[
[
"#scatter plot for numerical data with yaxis fixed as price\n\nplt.figure(figsize=[18,12])\n\nplt.subplot(3,3,1)\nplt.scatter(cp.wheelbase, cp.price)\nplt.title('wheelbase vs price')\nplt.subplot(3,3,2)\nplt.scatter(cp.peakrpm, cp.price)\nplt.title('peakrpm vs price')\nplt.subplot(3,3,3)\nplt.scatter(cp.carheight, cp.price)\nplt.title('carheight vs price')\n\nplt.subplot(3,3,4)\nplt.scatter(cp.compressionratio, cp.price)\nplt.title('compressionratio vs price')\nplt.subplot(3,3,5)\nplt.scatter(cp.stroke, cp.price)\nplt.title('Stroke vs price')\nplt.subplot(3,3,6)\nplt.scatter(cp.boreratio, cp.price)\nplt.title('boreratio vs price')\n\nplt.subplot(3,3,7)\nplt.scatter(cp.enginesize, cp.price)\nplt.title('enginesize vs price')\nplt.subplot(3,3,8)\nplt.scatter(cp.horsepower, cp.price)\nplt.title('horsepower vs price')\nplt.subplot(3,3,9)\nplt.scatter(cp.curbweight, cp.price)\nplt.title('curbweight vs price')\nplt.show()",
"_____no_output_____"
],
[
"plt.figure(figsize=[15,8])\n\nplt.subplot(2,2,1)\nplt.scatter(cp.carlength, cp.price)\nplt.title('carlength vs price')\nplt.subplot(2,2,2)\nplt.scatter(cp.carwidth, cp.price)\nplt.title('carwidth vs price')\nplt.subplot(2,2,3)\n\nplt.scatter(cp.citympg, cp.price)\nplt.title('citympg vs price')\nplt.subplot(2,2,4)\nplt.scatter(cp.highwaympg, cp.price)\nplt.title('highwaympg vs price')\n\nplt.show()",
"_____no_output_____"
],
[
"print(np.corrcoef(cp['carlength'], cp['carwidth'])[0, 1])\nprint(np.corrcoef(cp['citympg'], cp['highwaympg'])[0, 1])",
"0.841118268481846\n0.9713370423425061\n"
]
],
[
[
"#### Visualising categorical data",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(20, 15))\n\nplt.subplot(3,3,1)\nsns.countplot(cp.fueltype)\n\nplt.subplot(3,3,2)\nsns.countplot(cp.aspiration)\n\nplt.subplot(3,3,3)\nsns.countplot(cp.doornumber)\n\nplt.subplot(3,3,4)\nsns.countplot(cp.drivewheel)\n\nplt.subplot(3,3,5)\nsns.countplot(cp.carbody)\n\nplt.subplot(3,3,6)\nsns.countplot(cp.enginelocation)\n\nplt.subplot(3,3,7)\nsns.countplot(cp.enginetype)\n\nplt.subplot(3,3,8)\nsns.countplot(cp.cylindernumber)\n\nplt.subplot(3,3,9)\nsns.countplot(cp.symboling)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"\n`ohc` is the most preferred enginetype\n\nmost cars have `four cylinders`\n\n`sedan` and `hatchback` are most common carbody\n\nmost cars prefer `gas` fueltype",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(30,25))\n\nplt.subplot(2,1,1)\nsns.countplot(cp.fuelsystem)\n\nplt.subplot(2,1,2)\nsns.countplot(cp.carCompany)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"`mpfi` and `2bbl` are most common fuelsystem\n\n`Toyota` is most favoured carcompany",
"_____no_output_____"
],
[
"##### we can observe that numerous carcompanies are misspelled",
"_____no_output_____"
]
],
[
[
"# replcaing incorrect carcompanies with correct ones so we replace them with correct spellings\n\ncp['carCompany'] = cp['carCompany'].str.replace('vok','volk')\ncp['carCompany'] = cp['carCompany'].str.replace('ou','o')\ncp['carCompany'] = cp['carCompany'].str.replace('cshce','sche')\ncp['carCompany'] = cp['carCompany'].str.replace('vw','volkswagen')\ncp['carCompany'] = cp['carCompany'].str.replace('xd','zd')",
"_____no_output_____"
],
[
"# visualising categorical data vs price\n\nplt.figure(figsize = (25,15))\n\nplt.subplot(3,3,1)\nsns.boxplot(x = 'fueltype',y='price', data = cp)\n\nplt.subplot(3,3,2)\nsns.boxplot(x = 'symboling',y='price', data = cp)\n\nplt.subplot(3,3,3)\nsns.boxplot(x = 'aspiration',y='price', data = cp)\n\nplt.subplot(3,3,4)\nsns.boxplot(x = 'doornumber',y='price', data = cp)\n\nplt.subplot(3,3,5)\nsns.boxplot(x = 'carbody',y='price', data = cp)\n\nplt.subplot(3,3,6)\nsns.boxplot(x = 'drivewheel',y='price', data = cp)\n\nplt.subplot(3,3,7)\nsns.boxplot(x = 'enginelocation',y='price', data = cp)\n\nplt.subplot(3,3,8)\nsns.boxplot(x = 'enginetype',y='price', data = cp)\n\nplt.subplot(3,3,9)\nsns.boxplot(x = 'cylindernumber',y='price', data = cp)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"`ohcv` are most expensive of the enginetype\n\n`doornumber` don't have much impact on the price\n\n`hardtop` and `covertible` are most expensive among the carbody\n\ncars that are `rwd` have higher price",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(30,25))\n\nplt.subplot(2,1,1)\nsns.boxplot(x = 'fuelsystem',y='price', data = cp)\n\nplt.subplot(2,1,2)\nsns.boxplot(x = 'carCompany',y='price', data = cp)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"`buick`, `jaguar`, `porsche` and `bmw` are most expensive carCompany\n\n`mpfi` and `idi` having the highest price range. \n",
"_____no_output_____"
],
[
"### Encoding categorical data",
"_____no_output_____"
]
],
[
[
"#defining fucntion for binary encoding of features with only 2 types of data\ndef number_map(x):\n return x.map({'gas':1,'diesel':0,'std':0,'turbo':1,'two':0,'four':1,'front':0,'rear':1})\n\ncp[['aspiration']] =cp[['aspiration']].apply(number_map)\ncp[['doornumber']] =cp[['doornumber']].apply(number_map)\ncp[['fueltype']] =cp[['fueltype']].apply(number_map)\ncp[['enginelocation']] =cp[['enginelocation']].apply(number_map)",
"_____no_output_____"
],
[
"#applying label encoder on categorical variables\ncp['carCompany'] = le.fit_transform(cp['carCompany'])\ncp['symboling'] = le.fit_transform(cp['symboling'])\ncp['carbody'] = le.fit_transform(cp['carbody'])\ncp['drivewheel'] = le.fit_transform(cp['drivewheel'])\ncp['enginetype'] = le.fit_transform(cp['enginetype'])\ncp['cylindernumber'] = le.fit_transform(cp['cylindernumber'])\ncp['fuelsystem'] = le.fit_transform(cp['fuelsystem'])\n\n",
"_____no_output_____"
],
[
"#and dropping columns that are not required for the analysis\n\ncp = cp.drop(['car_ID'],axis = 1)",
"_____no_output_____"
],
[
"# converting price to thousands i.e 12.1K \ncp['price']=cp['price'].apply(lambda val: round(val/1000,3))\npd.options.display.float_format = '{:,.2f}'.format\n",
"_____no_output_____"
],
[
"cp.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 205 entries, 0 to 204\nData columns (total 25 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 symboling 205 non-null int32 \n 1 fueltype 205 non-null int64 \n 2 aspiration 205 non-null int64 \n 3 doornumber 205 non-null int64 \n 4 carbody 205 non-null int32 \n 5 drivewheel 205 non-null int32 \n 6 enginelocation 205 non-null int64 \n 7 wheelbase 205 non-null float64\n 8 carlength 205 non-null float64\n 9 carwidth 205 non-null float64\n 10 carheight 205 non-null float64\n 11 curbweight 205 non-null int64 \n 12 enginetype 205 non-null int32 \n 13 cylindernumber 205 non-null int32 \n 14 enginesize 205 non-null int64 \n 15 fuelsystem 205 non-null int32 \n 16 boreratio 205 non-null float64\n 17 stroke 205 non-null float64\n 18 compressionratio 205 non-null float64\n 19 horsepower 205 non-null int64 \n 20 peakrpm 205 non-null int64 \n 21 citympg 205 non-null int64 \n 22 highwaympg 205 non-null int64 \n 23 price 205 non-null float64\n 24 carCompany 205 non-null int32 \ndtypes: float64(8), int32(7), int64(10)\nmemory usage: 34.6 KB\n"
],
[
"cp.head(100)",
"_____no_output_____"
],
[
"X=cp.drop([\"price\"],axis=1)\ny=cp[\"price\"]",
"_____no_output_____"
]
],
[
[
"### Splitting data into test and train datasets",
"_____no_output_____"
]
],
[
[
"#splitting the data into test and train for evaluation\n# taking the test data as 30% and train data as 70%\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)",
"_____no_output_____"
]
],
[
[
"## Gradient Boosting",
"_____no_output_____"
]
],
[
[
"# fitting the model on train data\nmodel = GradientBoostingRegressor()\ngbr = model.fit(X_train,y_train)\n",
"_____no_output_____"
],
[
"# predicting on test data\ny_pred = gbr.predict(X_test)",
"_____no_output_____"
],
[
"# checking the goodness of the model\nmetrics.r2_score(y_test, y_pred)",
"_____no_output_____"
]
],
[
[
"### Hyper parameter tuning",
"_____no_output_____"
]
],
[
[
"# hyper parameter tuning for GBR\nGBR = GradientBoostingRegressor()\nparam_dist = {\"learning_rate\": np.linspace(0.05, 0.15,5),\"subsample\": [0.3, 0.6, 0.9]}\n\nrand = RandomizedSearchCV(GBR, param_dist, cv=5,n_iter=10, random_state=100)\nrand.fit(X_train,y_train)\n\nprint(rand.best_params_)",
"{'subsample': 0.6, 'learning_rate': 0.075}\n"
],
[
"GBR = GradientBoostingRegressor(learning_rate= 0.15, subsample= 0.6)\nGBR.fit(X_train,y_train)",
"_____no_output_____"
],
[
"# predicting on test data\ny_pred = GBR.predict(X_test)",
"_____no_output_____"
],
[
"np.sqrt(mean_squared_log_error(y_test, y_pred))",
"_____no_output_____"
],
[
"# checking the goodness of the model\nmetrics.r2_score(y_test, y_pred)",
"_____no_output_____"
],
[
"# plotting feature importance\nimportance = GBR.feature_importances_\nfig = plt.figure(figsize=(10, 10))\nx = X_test.columns.values\nplt.barh(x, 100*importance)\nplt.title('Feature Importance', loc='left')\nplt.xlabel('Percentage')\nplt.grid()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## XGboost",
"_____no_output_____"
]
],
[
[
"# fitting XGB on training data\nXGB = XGBRegressor()\nXGB = XGB.fit(X_train,y_train)",
"_____no_output_____"
],
[
"# predicting on test data\nY_pred = XGB.predict(X_test)",
"_____no_output_____"
],
[
"np.sqrt(mean_squared_log_error(y_test,Y_pred))",
"_____no_output_____"
],
[
"# checking the goodness of the model\nmetrics.r2_score(y_test, Y_pred)",
"_____no_output_____"
],
[
"importance = XGB.feature_importances_",
"_____no_output_____"
],
[
"# plotting feature importance\nfig = plt.figure(figsize=(10, 10))\nx = X_train.columns.values\nplt.barh(x, 100*importance)\nplt.title('Feature Importance', loc='left')\nplt.xlabel('Percentage')\nplt.grid()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Hyperparameter tuning ",
"_____no_output_____"
]
],
[
[
"# hyper parameter tuning for XGB\nXGB = XGBRegressor()\n\n\nparam_grid = {\"learning_rate\": np.linspace(0.05, 0.15,5),\n \"subsample\": [0.3, 0.6, 0.9]}\n\nrand = RandomizedSearchCV(XGB, param_grid, cv=5,n_iter=10, random_state=100)\nrand.fit(X_train,y_train)\n\nprint(rand.best_params_)",
"{'subsample': 0.6, 'learning_rate': 0.05}\n"
],
[
"xgb = XGBRegressor(learning_rate= 0.15, subsample= 0.6)\nxgb.fit(X_train,y_train)",
"_____no_output_____"
],
[
"Y_pred = xgb.predict(X_test)",
"_____no_output_____"
],
[
"np.sqrt(mean_squared_log_error(y_test,Y_pred))",
"_____no_output_____"
],
[
"# checking the goodness of the model\nmetrics.r2_score(y_test, Y_pred)",
"_____no_output_____"
],
[
"importance = xgb.feature_importances_",
"_____no_output_____"
],
[
"# plotting feature importance\nfig = plt.figure(figsize=(10, 10))\nx = X_test.columns.values\nplt.barh(x, 100*importance)\nplt.title('Feature Importance', loc='left')\nplt.xlabel('Percentage')\nplt.grid()\nplt.show()",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0acc80c839e72c6725581e4e78a9e6d38b0d27a | 23,666 | ipynb | Jupyter Notebook | cls8-Assotiation Rule mining and Reccommendation system/Code 2.ipynb | tuhinssam/MLResources | 5410ce33bc6f3a951b0f94c32bf82748a8c5bd6c | [
"MIT"
] | 1 | 2020-01-31T06:18:30.000Z | 2020-01-31T06:18:30.000Z | cls8-Assotiation Rule mining and Reccommendation system/Code 2.ipynb | tuhinssam/MLResources | 5410ce33bc6f3a951b0f94c32bf82748a8c5bd6c | [
"MIT"
] | null | null | null | cls8-Assotiation Rule mining and Reccommendation system/Code 2.ipynb | tuhinssam/MLResources | 5410ce33bc6f3a951b0f94c32bf82748a8c5bd6c | [
"MIT"
] | null | null | null | 30.379974 | 125 | 0.332967 | [
[
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"df = pd.read_csv('Recommend.csv',names=['user_id', 'movie_id', 'rating', 'timestamp'])\ndf",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nn_users = df.user_id.unique().shape[0] \nn_movies = df.movie_id.unique().shape[0]\ntrain_data, test_data = train_test_split(df, test_size=0.25)",
"_____no_output_____"
],
[
"train_data_matrix = np.zeros((n_users, n_movies))\nfor line in train_data.itertuples():\n #[user_id index, movie_id index] = given rating.\n train_data_matrix[line[1]-1, line[2]-1] = line[3] \ntrain_data_matrix",
"_____no_output_____"
],
[
"test_data_matrix = np.zeros((n_users, n_movies))\nfor line in test_data.itertuples():\n #[user_id index, movie_id index] = given rating.\n test_data_matrix[line[1]-1, line[2]-1] = line[3]\ntest_data_matrix",
"_____no_output_____"
],
[
"from sklearn.metrics import pairwise_distances\nuser_similarity = pairwise_distances(train_data_matrix, metric='cosine')\nmovie_similarity = pairwise_distances(train_data_matrix.T, metric='cosine')\nmean_user_rating = train_data_matrix.mean(axis=1)[:, np.newaxis] \nratings_diff = (train_data_matrix - mean_user_rating) \nuser_pred = mean_user_rating + user_similarity.dot(ratings_diff) / np.array([np.abs(user_similarity).sum(axis=1)]).T\nuser_pred",
"_____no_output_____"
],
[
"movie_pred = train_data_matrix.dot(movie_similarity) / np.array([np.abs(movie_similarity).sum(axis=1)])\nmovie_pred",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_squared_error\nfrom math import sqrt\ndef rmse(pred, test):\n pred = pred[test.nonzero()].flatten() \n test = test[test.nonzero()].flatten()\n return sqrt(mean_squared_error(pred, test))",
"_____no_output_____"
],
[
"rmse(user_pred, test_data_matrix)",
"_____no_output_____"
],
[
"rmse(movie_pred, test_data_matrix)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0acd0f33df52f2df66cac24e85460a80932695d | 44,323 | ipynb | Jupyter Notebook | Lecture 2/Iris Classification with Perceptron.ipynb | GO-Loc-GO/MIT-ML-and-CV | e45c2aaf7628e83297f75b7fb16e4215a9587e70 | [
"MIT"
] | null | null | null | Lecture 2/Iris Classification with Perceptron.ipynb | GO-Loc-GO/MIT-ML-and-CV | e45c2aaf7628e83297f75b7fb16e4215a9587e70 | [
"MIT"
] | null | null | null | Lecture 2/Iris Classification with Perceptron.ipynb | GO-Loc-GO/MIT-ML-and-CV | e45c2aaf7628e83297f75b7fb16e4215a9587e70 | [
"MIT"
] | null | null | null | 188.608511 | 28,736 | 0.899104 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.model_selection import train_test_split\n",
"_____no_output_____"
]
],
[
[
"## Data Preprocessing",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('Iris.csv')\n\ndf2 = df.drop(['Id', 'SepalLengthCm', 'PetalLengthCm'], axis=1)\ndf2['Species'].replace(to_replace=['Iris-setosa', 'Iris-virginica', 'Iris-versicolor'], value=[1., -1., -1.], inplace=True)\ndf2.head()",
"_____no_output_____"
],
[
"x = df2[['SepalWidthCm', 'PetalWidthCm']].values\ny = df2['Species'].values\n# Plot the training points\n#plt.subplot(1, 2, 1)\nplt.scatter(x[:, 0], x[:, 1],c=y,cmap=plt.cm.Set1,edgecolor='k')\nplt.xlabel('Sepal Width')\nplt.ylabel('Petal width')\nplt.xticks(())\nplt.yticks(())\nplt.show()",
"_____no_output_____"
],
[
"(x_train,x_test,y_train,y_test)=train_test_split(x, y, test_size=0.7)\nx_train = x_train.transpose()\nXt = np.array([np.ones(len(x_train[0])),x_train[0]])\nX1=Xt.transpose()\nX2=x_train[1].transpose()\nZ = np.matmul(Xt,X1)\nZinv=np.linalg.inv(Z)\nZ2=np.matmul(Zinv,Xt)\nZ3=np.matmul(Z2,X2)\n\n#Z3 is the pseudoinverse\nb = Z3[0]\nm = Z3[1]\nypred=m*x_train[0]+b\n\nprint(\"Problem 3a: \"\"y=\",m,\"x+\",b)",
"Problem 3a: y= -1.0072110569540011 x+ 4.141857514856138\n"
],
[
"fig, ax = plt.subplots(1, 1, figsize=(6, 3))\nax.plot(x_train[0], x_train[1], 'bo')\nax.plot(x_train[0], ypred, 'b')\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.grid()\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0ace1d8c3e8e44536db516c8c497c7beb034d84 | 91,049 | ipynb | Jupyter Notebook | RandomForest-RFECV-BreakStatus-Halifax-RandomizedSearch.ipynb | SadafGharaati/Important-factors | c159e1c783a10af7ba92ff0828542349282609b4 | [
"Unlicense"
] | 1 | 2022-03-23T02:53:37.000Z | 2022-03-23T02:53:37.000Z | RandomForest-RFECV-BreakStatus-Halifax-RandomizedSearch.ipynb | SadafGharaati/Important-factors | c159e1c783a10af7ba92ff0828542349282609b4 | [
"Unlicense"
] | null | null | null | RandomForest-RFECV-BreakStatus-Halifax-RandomizedSearch.ipynb | SadafGharaati/Important-factors | c159e1c783a10af7ba92ff0828542349282609b4 | [
"Unlicense"
] | null | null | null | 90.236868 | 33,504 | 0.78192 | [
[
[
"# In this note book the following steps are taken:\n1. Remove highly correlated attributes\n2. Find the best hyper parameters for estimator\n3. Find the most important features by tunned random forest\n4. Find f1 score of the tunned full model\n5. Find best hyper parameter of model with selected features\n6. Find f1 score of the tuned seleccted model\n7. Compare the two f1 scores",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_selection import RFECV,RFE\nfrom sklearn.model_selection import train_test_split, GridSearchCV, KFold,RandomizedSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn import metrics\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score,f1_score\nimport numpy as np\nfrom sklearn.metrics import make_scorer\nf1_score = make_scorer(f1_score)",
"_____no_output_____"
],
[
"#import data\nData=pd.read_csv(\"Halifax-Transfomed-Data-BS-NoBreak - Copy.csv\")",
"_____no_output_____"
],
[
"X = Data.iloc[:,:-1]\ny = Data.iloc[:,-1]",
"_____no_output_____"
],
[
"#split test and training set. \nnp.random.seed(60)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2,\n random_state = 1000)",
"_____no_output_____"
],
[
"#Define estimator and model\nclassifiers = {}\nclassifiers.update({\"Random Forest\": RandomForestClassifier(random_state=1000)})",
"_____no_output_____"
],
[
"#Define range of hyperparameters for estimator\nnp.random.seed(60)\nparameters = {}\nparameters.update({\"Random Forest\": { \"classifier__n_estimators\": [100,105,110,115,120,125,130,135,140,145,150,155,160,170,180,190,200],\n # \"classifier__n_estimators\": [2,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200],\n #\"classifier__class_weight\": [None, \"balanced\"],\n \"classifier__max_features\": [\"auto\", \"sqrt\", \"log2\"],\n \"classifier__max_depth\" : [4,6,8,10,11,12,13,14,15,16,17,18,19,20,22],\n #\"classifier__max_depth\" : [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],\n \"classifier__criterion\" :[\"gini\", \"entropy\"]\n \n}})",
"_____no_output_____"
],
[
"# Make correlation matrix\ncorr_matrix = X_train.corr(method = \"spearman\").abs()\n\n# Draw the heatmap\nsns.set(font_scale = 1.0)\nf, ax = plt.subplots(figsize=(11, 9))\nsns.heatmap(corr_matrix, cmap= \"YlGnBu\", square=True, ax = ax)\nf.tight_layout()\nplt.savefig(\"correlation_matrix.png\", dpi = 1080)\n\n# Select upper triangle of matrix\nupper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k = 1).astype(np.bool))\n\n# Find index of feature columns with correlation greater than 0.8\nto_drop = [column for column in upper.columns if any(upper[column] > 0.8)]\n\n# Drop features\nX_train = X_train.drop(to_drop, axis = 1)\nX_test = X_test.drop(to_drop, axis = 1)",
"_____no_output_____"
],
[
"X_train",
"_____no_output_____"
],
[
"FEATURE_IMPORTANCE = {\"Random Forest\"}\nselected_classifier = \"Random Forest\"\nclassifier = classifiers[selected_classifier]",
"_____no_output_____"
],
[
"scaler = StandardScaler()\nsteps = [(\"scaler\", scaler), (\"classifier\", classifier)]\npipeline = Pipeline(steps = steps)",
"_____no_output_____"
],
[
"#Define parameters that we want to use in gridsearch cv\nparam_grid = parameters[selected_classifier]",
"_____no_output_____"
],
[
"# Initialize GridSearch object for estimator\ngscv = RandomizedSearchCV(pipeline, param_grid, cv = 3, n_jobs= -1, verbose = 1, scoring = f1_score, n_iter=30)",
"_____no_output_____"
],
[
"# Fit gscv (Tunes estimator)\nprint(f\"Now tuning {selected_classifier}. Go grab a beer or something.\")\ngscv.fit(X_train, np.ravel(y_train)) ",
"Now tuning Random Forest. Go grab a beer or something.\nFitting 3 folds for each of 30 candidates, totalling 90 fits\n"
],
[
"#Getting the best hyperparameters\nbest_params = gscv.best_params_\nbest_params",
"_____no_output_____"
],
[
"#Getting the best score of model\nbest_score = gscv.best_score_\nbest_score",
"_____no_output_____"
],
[
"#Check overfitting of the estimator\nfrom sklearn.model_selection import cross_val_score\nmod = RandomForestClassifier(#class_weight= None,\n criterion= 'gini',\n max_depth= 16,\n max_features= 'auto',\n n_estimators= 155 ,random_state=10000)\n\nscores_test = cross_val_score(mod, X_test, y_test, scoring='f1', cv=5)\n\nscores_test",
"_____no_output_____"
],
[
"tuned_params = {item[12:]: best_params[item] for item in best_params}\nclassifier.set_params(**tuned_params)",
"_____no_output_____"
],
[
"#Find f1 score of the model with all features (Model is tuned for all features)\nresults={}\nmodel=classifier.set_params(criterion= 'gini',\n max_depth= 16,\n max_features= 'auto',\n n_estimators= 155 ,random_state=10000)\nmodel.fit(X_train,y_train)\ny_pred = model.predict(X_test)\nF1 = metrics.f1_score(y_test, y_pred)\nresults = {\"classifier\": model,\n \"Best Parameters\": best_params,\n \"Training f1\": best_score*100,\n \"Test f1\": F1*100}\nresults\n",
"_____no_output_____"
],
[
"# Select Features using RFECV\nclass PipelineRFE(Pipeline):\n # Source: https://ramhiser.com/post/2018-03-25-feature-selection-with-scikit-learn-pipeline/\n def fit(self, X, y=None, **fit_params):\n super(PipelineRFE, self).fit(X, y, **fit_params)\n self.feature_importances_ = self.steps[-1][-1].feature_importances_\n return self",
"_____no_output_____"
],
[
"steps = [(\"scaler\", scaler), (\"classifier\", classifier)]\npipe = PipelineRFE(steps = steps)\nnp.random.seed(60)\n\n# Initialize RFECV object\nfeature_selector = RFECV(pipe, cv = 5, step = 1, verbose = 1)\n\n# Fit RFECV\nfeature_selector.fit(X_train, np.ravel(y_train))\n\n# Get selected features\nfeature_names = X_train.columns\nselected_features = feature_names[feature_selector.support_].tolist()",
"Fitting estimator with 6 features.\nFitting estimator with 5 features.\nFitting estimator with 4 features.\nFitting estimator with 3 features.\nFitting estimator with 2 features.\nFitting estimator with 6 features.\nFitting estimator with 5 features.\nFitting estimator with 4 features.\nFitting estimator with 3 features.\nFitting estimator with 2 features.\nFitting estimator with 6 features.\nFitting estimator with 5 features.\nFitting estimator with 4 features.\nFitting estimator with 3 features.\nFitting estimator with 2 features.\nFitting estimator with 6 features.\nFitting estimator with 5 features.\nFitting estimator with 4 features.\nFitting estimator with 3 features.\nFitting estimator with 2 features.\nFitting estimator with 6 features.\nFitting estimator with 5 features.\nFitting estimator with 4 features.\nFitting estimator with 3 features.\nFitting estimator with 2 features.\n"
],
[
"performance_curve = {\"Number of Features\": list(range(1, len(feature_names) + 1)),\n \"F1\": feature_selector.grid_scores_}\nperformance_curve = pd.DataFrame(performance_curve)\n\n# Performance vs Number of Features\n# Set graph style\nsns.set(font_scale = 1.75)\nsns.set_style({\"axes.facecolor\": \"1.0\", \"axes.edgecolor\": \"0.85\", \"grid.color\": \"0.85\",\n \"grid.linestyle\": \"-\", 'axes.labelcolor': '0.4', \"xtick.color\": \"0.4\",\n 'ytick.color': '0.4'})\ncolors = sns.color_palette(\"RdYlGn\", 20)\nline_color = colors[3]\nmarker_colors = colors[-1]\n\n# Plot\nf, ax = plt.subplots(figsize=(13, 6.5))\nsns.lineplot(x = \"Number of Features\", y = \"F1\", data = performance_curve,\n color = line_color, lw = 4, ax = ax)\nsns.regplot(x = performance_curve[\"Number of Features\"], y = performance_curve[\"F1\"],\n color = marker_colors, fit_reg = False, scatter_kws = {\"s\": 200}, ax = ax)\n\n# Axes limits\nplt.xlim(0.5, len(feature_names)+0.5)\nplt.ylim(0.60, 1)\n\n# Generate a bolded horizontal line at y = 0\nax.axhline(y = 0.625, color = 'black', linewidth = 1.3, alpha = .7)\n\n# Turn frame off\nax.set_frame_on(False)\n\n# Tight layout\nplt.tight_layout()",
"_____no_output_____"
],
[
"#Define new training and test set based based on selected features by RFECV\nX_train_rfecv = X_train[selected_features]\nX_test_rfecv= X_test[selected_features]",
"_____no_output_____"
],
[
"np.random.seed(60)\nclassifier.fit(X_train_rfecv, np.ravel(y_train))",
"_____no_output_____"
],
[
"#Finding important features\nnp.random.seed(60)\nfeature_importance = pd.DataFrame(selected_features, columns = [\"Feature Label\"])\nfeature_importance[\"Feature Importance\"] = classifier.feature_importances_\nfeature_importance = feature_importance.sort_values(by=\"Feature Importance\", ascending=False)\nfeature_importance",
"_____no_output_____"
],
[
"# Initialize GridSearch object for model with selected features\nnp.random.seed(60)\ngscv = RandomizedSearchCV(pipeline, param_grid, cv = 3, n_jobs= -1, verbose = 1, scoring = f1_score, n_iter=30)",
"_____no_output_____"
],
[
"#Tuning random forest classifier with selected features \nnp.random.seed(60)\ngscv.fit(X_train_rfecv,y_train) ",
"Fitting 3 folds for each of 30 candidates, totalling 90 fits\n"
],
[
"#Getting the best parameters of model with selected features\nbest_params = gscv.best_params_\nbest_params",
"_____no_output_____"
],
[
"#Getting the score of model with selected features\nbest_score = gscv.best_score_\nbest_score",
"_____no_output_____"
],
[
"#Check overfitting of the tuned model with selected features \nfrom sklearn.model_selection import cross_val_score\nmod = RandomForestClassifier(#class_weight= None,\n criterion= 'entropy',\n max_depth= 16,\n max_features= 'auto',\n n_estimators= 100 ,random_state=10000)\n\nscores_test = cross_val_score(mod, X_test_rfecv, y_test, scoring='f1', cv=5)\n\nscores_test",
"_____no_output_____"
],
[
"results={}\nmodel=classifier.set_params(criterion= 'entropy',\n max_depth= 16,\n max_features= 'auto',\n n_estimators= 100 ,random_state=10000)\nscores_test = cross_val_score(mod, X_test_rfecv, y_test, scoring='f1', cv=5)\nmodel.fit(X_train_rfecv,y_train)\ny_pred = model.predict(X_test_rfecv)\nF1 = metrics.f1_score(y_test, y_pred)\nresults = {\"classifier\": model,\n \"Best Parameters\": best_params,\n \"Training f1\": best_score*100,\n \"Test f1\": F1*100}\nresults",
"_____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"
]
] |
d0acf436eae85530d7fd43d43c7e1e247c48b415 | 6,248 | ipynb | Jupyter Notebook | doc/ga.ipynb | KoichiYasuoka/deplacy | bb9c19bb8cf00ccf192aa9243666504ddc773018 | [
"MIT"
] | 93 | 2020-03-30T02:34:39.000Z | 2022-03-15T19:36:32.000Z | doc/ga.ipynb | KoichiYasuoka/deplacy | bb9c19bb8cf00ccf192aa9243666504ddc773018 | [
"MIT"
] | 2 | 2022-01-03T00:43:42.000Z | 2022-01-09T23:52:22.000Z | doc/ga.ipynb | KoichiYasuoka/deplacy | bb9c19bb8cf00ccf192aa9243666504ddc773018 | [
"MIT"
] | 4 | 2020-12-03T11:15:19.000Z | 2022-03-15T19:36:34.000Z | 30.778325 | 169 | 0.528329 | [
[
[
"# Anailís ghramadaí trí [deplacy](https://koichiyasuoka.github.io/deplacy/)\n",
"_____no_output_____"
],
[
"## le [Stanza](https://stanfordnlp.github.io/stanza)\n",
"_____no_output_____"
]
],
[
[
"!pip install deplacy stanza\nimport stanza\nstanza.download(\"ga\")\nnlp=stanza.Pipeline(\"ga\")\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
],
[
[
"## le [UDPipe 2](http://ufal.mff.cuni.cz/udpipe/2)\n",
"_____no_output_____"
]
],
[
[
"!pip install deplacy\ndef nlp(t):\n import urllib.request,urllib.parse,json\n with urllib.request.urlopen(\"https://lindat.mff.cuni.cz/services/udpipe/api/process?model=ga&tokenizer&tagger&parser&data=\"+urllib.parse.quote(t)) as r:\n return json.loads(r.read())[\"result\"]\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
],
[
[
"## le [COMBO-pytorch](https://gitlab.clarin-pl.eu/syntactic-tools/combo)\n",
"_____no_output_____"
]
],
[
[
"!pip install --index-url https://pypi.clarin-pl.eu/simple deplacy combo\nimport combo.predict\nnlp=combo.predict.COMBO.from_pretrained(\"irish-ud27\")\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
],
[
[
"## le [Trankit](https://github.com/nlp-uoregon/trankit)\n",
"_____no_output_____"
]
],
[
[
"!pip install deplacy trankit transformers\nimport trankit\nnlp=trankit.Pipeline(\"irish\")\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
],
[
[
"## le [spacy-udpipe](https://github.com/TakeLab/spacy-udpipe)\n",
"_____no_output_____"
]
],
[
[
"!pip install deplacy spacy-udpipe\nimport spacy_udpipe\nspacy_udpipe.download(\"ga\")\nnlp=spacy_udpipe.load(\"ga\")\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
],
[
[
"## le [spaCy-COMBO](https://github.com/KoichiYasuoka/spaCy-COMBO)\n",
"_____no_output_____"
]
],
[
[
"!pip install deplacy spacy_combo\nimport spacy_combo\nnlp=spacy_combo.load(\"ga_idt\")\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
],
[
[
"## le [spaCy-jPTDP](https://github.com/KoichiYasuoka/spaCy-jPTDP)\n",
"_____no_output_____"
]
],
[
[
"!pip install deplacy spacy_jptdp\nimport spacy_jptdp\nnlp=spacy_jptdp.load(\"ga_idt\")\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
],
[
[
"## le [Camphr-Udify](https://camphr.readthedocs.io/en/latest/notes/udify.html)\n",
"_____no_output_____"
]
],
[
[
"!pip install deplacy camphr en-udify@https://github.com/PKSHATechnology-Research/camphr_models/releases/download/0.7.0/en_udify-0.7.tar.gz\nimport pkg_resources,imp\nimp.reload(pkg_resources)\nimport spacy\nnlp=spacy.load(\"en_udify\")\ndoc=nlp(\"Táimid faoi dhraíocht ag ceol na farraige.\")\nimport deplacy\ndeplacy.render(doc)\ndeplacy.serve(doc,port=None)\n# import graphviz\n# graphviz.Source(deplacy.dot(doc))",
"_____no_output_____"
]
]
] | [
"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"
]
] |
d0acfa5823777e9f1686f230ed5fbed1b24bb180 | 1,043,665 | ipynb | Jupyter Notebook | docs/en/tutorials/MMClassification_python.ipynb | HXZhong1997/mmclassification | 8144844007158b866abaab4e1111a80dd9703352 | [
"Apache-2.0"
] | 1 | 2022-02-09T07:31:08.000Z | 2022-02-09T07:31:08.000Z | docs/en/tutorials/MMClassification_python.ipynb | HXZhong1997/mmclassification | 8144844007158b866abaab4e1111a80dd9703352 | [
"Apache-2.0"
] | 5 | 2022-03-02T02:58:56.000Z | 2022-03-23T05:51:53.000Z | docs/en/tutorials/MMClassification_python.ipynb | HXZhong1997/mmclassification | 8144844007158b866abaab4e1111a80dd9703352 | [
"Apache-2.0"
] | 1 | 2022-03-25T08:40:07.000Z | 2022-03-25T08:40:07.000Z | 512.102552 | 378,142 | 0.926014 | [
[
[
"<a href=\"https://colab.research.google.com/github/open-mmlab/mmclassification/blob/master/docs/tutorials/MMClassification_python.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# MMClassification Python API tutorial on Colab\n\nIn this tutorial, we will introduce the following content:\n\n* How to install MMCls\n* Inference a model with Python API\n* Fine-tune a model with Python API",
"_____no_output_____"
],
[
"## Install MMClassification\n\nBefore using MMClassification, we need to prepare the environment with the following steps:\n\n1. Install Python, CUDA, C/C++ compiler and git\n2. Install PyTorch (CUDA version)\n3. Install mmcv\n4. Clone mmcls source code from GitHub and install it\n\nBecause this tutorial is on Google Colab, and the basic environment has been completed, we can skip the first two steps.",
"_____no_output_____"
],
[
"### Check environment",
"_____no_output_____"
]
],
[
[
"%cd /content",
"/content\n"
],
[
"!pwd",
"/content\n"
],
[
"# Check nvcc version\n!nvcc -V",
"nvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2020 NVIDIA Corporation\nBuilt on Mon_Oct_12_20:09:46_PDT_2020\nCuda compilation tools, release 11.1, V11.1.105\nBuild cuda_11.1.TC455_06.29190527_0\n"
],
[
"# Check GCC version\n!gcc --version",
"gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0\nCopyright (C) 2017 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"
],
[
"# Check PyTorch installation\nimport torch, torchvision\nprint(torch.__version__)\nprint(torch.cuda.is_available())",
"1.9.0+cu111\nTrue\n"
]
],
[
[
"### Install MMCV\n\nMMCV is the basic package of all OpenMMLab packages. We have pre-built wheels on Linux, so we can download and install them directly.\n\nPlease pay attention to PyTorch and CUDA versions to match the wheel.\n\nIn the above steps, we have checked the version of PyTorch and CUDA, and they are 1.9.0 and 11.1 respectively, so we need to choose the corresponding wheel.\n\nIn addition, we can also install the full version of mmcv (mmcv-full). It includes full features and various CUDA ops out of the box, but needs a longer time to build.",
"_____no_output_____"
]
],
[
[
"# Install mmcv\n!pip install mmcv -f https://download.openmmlab.com/mmcv/dist/cu111/torch1.9.0/index.html\n# !pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu110/torch1.9.0/index.html",
"Looking in links: https://download.openmmlab.com/mmcv/dist/cu111/torch1.9.0/index.html\nCollecting mmcv\n Downloading mmcv-1.3.15.tar.gz (352 kB)\n\u001b[K |████████████████████████████████| 352 kB 5.2 MB/s \n\u001b[?25hCollecting addict\n Downloading addict-2.4.0-py3-none-any.whl (3.8 kB)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from mmcv) (1.19.5)\nRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from mmcv) (21.0)\nRequirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (from mmcv) (7.1.2)\nRequirement already satisfied: pyyaml in /usr/local/lib/python3.7/dist-packages (from mmcv) (3.13)\nCollecting yapf\n Downloading yapf-0.31.0-py2.py3-none-any.whl (185 kB)\n\u001b[K |████████████████████████████████| 185 kB 49.9 MB/s \n\u001b[?25hRequirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->mmcv) (2.4.7)\nBuilding wheels for collected packages: mmcv\n Building wheel for mmcv (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for mmcv: filename=mmcv-1.3.15-py2.py3-none-any.whl size=509835 sha256=793fe3796421336ca7a7740a1397a54016ba71ce95fd80cb80a116644adb4070\n Stored in directory: /root/.cache/pip/wheels/b2/f4/4e/8f6d2dd2bef6b7eb8c89aa0e5d61acd7bff60aaf3d4d4b29b0\nSuccessfully built mmcv\nInstalling collected packages: yapf, addict, mmcv\nSuccessfully installed addict-2.4.0 mmcv-1.3.15 yapf-0.31.0\n"
]
],
[
[
"### Clone and install MMClassification\n\nNext, we clone the latest mmcls repository from GitHub and install it.",
"_____no_output_____"
]
],
[
[
"# Clone mmcls repository\n!git clone https://github.com/open-mmlab/mmclassification.git\n%cd mmclassification/\n\n# Install MMClassification from source\n!pip install -e . ",
"Cloning into 'mmclassification'...\nremote: Enumerating objects: 4152, done.\u001b[K\nremote: Counting objects: 100% (994/994), done.\u001b[K\nremote: Compressing objects: 100% (576/576), done.\u001b[K\nremote: Total 4152 (delta 476), reused 765 (delta 401), pack-reused 3158\u001b[K\nReceiving objects: 100% (4152/4152), 8.20 MiB | 21.00 MiB/s, done.\nResolving deltas: 100% (2524/2524), done.\n"
],
[
"# Check MMClassification installation\nimport mmcls\nprint(mmcls.__version__)",
"0.16.0\n"
]
],
[
[
"## Inference a model with Python API\n\nMMClassification provides many pre-trained models, and you can check them by the link of [model zoo](https://mmclassification.readthedocs.io/en/latest/model_zoo.html). Almost all models can reproduce the results in original papers or reach higher metrics. And we can use these models directly.\n\nTo use the pre-trained model, we need to do the following steps:\n\n- Prepare the model\n - Prepare the config file\n - Prepare the checkpoint file\n- Build the model\n- Inference with the model",
"_____no_output_____"
]
],
[
[
"# Get the demo image\n!wget https://www.dropbox.com/s/k5fsqi6qha09l1v/banana.png?dl=0 -O demo/banana.png",
"--2021-10-21 03:52:36-- https://www.dropbox.com/s/k5fsqi6qha09l1v/banana.png?dl=0\nResolving www.dropbox.com (www.dropbox.com)... 162.125.3.18, 2620:100:601b:18::a27d:812\nConnecting to www.dropbox.com (www.dropbox.com)|162.125.3.18|:443... connected.\nHTTP request sent, awaiting response... 301 Moved Permanently\nLocation: /s/raw/k5fsqi6qha09l1v/banana.png [following]\n--2021-10-21 03:52:36-- https://www.dropbox.com/s/raw/k5fsqi6qha09l1v/banana.png\nReusing existing connection to www.dropbox.com:443.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://uc10f85c3c33c4b5233bac4d074e.dl.dropboxusercontent.com/cd/0/inline/BYYklQk6LNPXNm7o5xE_fxE2GA9reePyNajQgoe9roPlSrtsJd4WN6RVww7zrtNZWFq8iZv349MNQJlm7vVaqRBxTcd0ufxkqbcJYJvOrORpxOPV7mHmhMjKYUncez8YNqELGwDd-aeZqLGKBC8spSnx/file# [following]\n--2021-10-21 03:52:36-- https://uc10f85c3c33c4b5233bac4d074e.dl.dropboxusercontent.com/cd/0/inline/BYYklQk6LNPXNm7o5xE_fxE2GA9reePyNajQgoe9roPlSrtsJd4WN6RVww7zrtNZWFq8iZv349MNQJlm7vVaqRBxTcd0ufxkqbcJYJvOrORpxOPV7mHmhMjKYUncez8YNqELGwDd-aeZqLGKBC8spSnx/file\nResolving uc10f85c3c33c4b5233bac4d074e.dl.dropboxusercontent.com (uc10f85c3c33c4b5233bac4d074e.dl.dropboxusercontent.com)... 162.125.3.15, 2620:100:601b:15::a27d:80f\nConnecting to uc10f85c3c33c4b5233bac4d074e.dl.dropboxusercontent.com (uc10f85c3c33c4b5233bac4d074e.dl.dropboxusercontent.com)|162.125.3.15|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 297299 (290K) [image/png]\nSaving to: ‘demo/banana.png’\n\ndemo/banana.png 100%[===================>] 290.33K --.-KB/s in 0.08s \n\n2021-10-21 03:52:36 (3.47 MB/s) - ‘demo/banana.png’ saved [297299/297299]\n\n"
],
[
"from PIL import Image\nImage.open('demo/banana.png')",
"_____no_output_____"
]
],
[
[
"### Prepare the config file and checkpoint file\n\nWe configure a model with a config file and save weights with a checkpoint file.\n\nOn GitHub, you can find all these pre-trained models in the config folder of MMClassification. For example, you can find the config files and checkpoints of Mobilenet V2 in [this link](https://github.com/open-mmlab/mmclassification/tree/master/configs/mobilenet_v2).\n\nWe have integrated many config files for various models in the MMClassification repository. As for the checkpoint, we can download it in advance, or just pass an URL to API, and MMClassification will download it before load weights.",
"_____no_output_____"
]
],
[
[
"# Confirm the config file exists\n!ls configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py\n\n# Specify the path of the config file and checkpoint file.\nconfig_file = 'configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py'\ncheckpoint_file = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth'",
"configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py\n"
]
],
[
[
"### Inference the model\n\nMMClassification provides high-level Python API to inference models.\n\nAt first, we build the MobilenetV2 model and load the checkpoint.",
"_____no_output_____"
]
],
[
[
"import mmcv\nfrom mmcls.apis import inference_model, init_model, show_result_pyplot\n\n# Specify the device, if you cannot use GPU, you can also use CPU \n# by specifying `device='cpu'`.\ndevice = 'cuda:0'\n# device = 'cpu'\n\n# Build the model according to the config file and load the checkpoint.\nmodel = init_model(config_file, checkpoint_file, device=device)",
"/usr/local/lib/python3.7/dist-packages/mmcv/cnn/bricks/transformer.py:28: UserWarning: Fail to import ``MultiScaleDeformableAttention`` from ``mmcv.ops.multi_scale_deform_attn``, You should install ``mmcv-full`` if you need this module. \n warnings.warn('Fail to import ``MultiScaleDeformableAttention`` from '\n/usr/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject\n return f(*args, **kwds)\n/usr/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject\n return f(*args, **kwds)\n/usr/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header, got 216 from PyObject\n return f(*args, **kwds)\n/usr/local/lib/python3.7/dist-packages/yaml/constructor.py:126: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working\n if not isinstance(key, collections.Hashable):\n"
],
[
"# The model's inheritance relationship\nmodel.__class__.__mro__",
"_____no_output_____"
],
[
"# The inference result in a single image\nimg = 'demo/banana.png'\nimg_array = mmcv.imread(img)\nresult = inference_model(model, img_array)\nresult",
"_____no_output_____"
],
[
"%matplotlib inline\n# Visualize the inference result\nshow_result_pyplot(model, img, result)",
"_____no_output_____"
]
],
[
[
"## Fine-tune a model with Python API\n\nFine-tuning is to re-train a model which has been trained on another dataset (like ImageNet) to fit our target dataset. Compared with training from scratch, fine-tuning is much faster can avoid over-fitting problems during training on a small dataset.\n\nThe basic steps of fine-tuning are as below:\n\n1. Prepare the target dataset and meet MMClassification's requirements.\n2. Modify the training config.\n3. Start training and validation.\n\nMore details are in [the docs](https://mmclassification.readthedocs.io/en/latest/tutorials/finetune.html).",
"_____no_output_____"
],
[
"### Prepare the target dataset\n\nHere we download the cats & dogs dataset directly. You can find more introduction about the dataset in the [tools tutorial](https://colab.research.google.com/github/open-mmlab/mmclassification/blob/master/docs/tutorials/MMClassification_tools.ipynb).",
"_____no_output_____"
]
],
[
[
"# Download the cats & dogs dataset\n!wget https://www.dropbox.com/s/wml49yrtdo53mie/cats_dogs_dataset_reorg.zip?dl=0 -O cats_dogs_dataset.zip\n!mkdir -p data\n!unzip -qo cats_dogs_dataset.zip -d ./data/",
"--2021-10-21 03:57:58-- https://www.dropbox.com/s/wml49yrtdo53mie/cats_dogs_dataset_reorg.zip?dl=0\nResolving www.dropbox.com (www.dropbox.com)... 162.125.80.18, 2620:100:6018:18::a27d:312\nConnecting to www.dropbox.com (www.dropbox.com)|162.125.80.18|:443... connected.\nHTTP request sent, awaiting response... 301 Moved Permanently\nLocation: /s/raw/wml49yrtdo53mie/cats_dogs_dataset_reorg.zip [following]\n--2021-10-21 03:57:58-- https://www.dropbox.com/s/raw/wml49yrtdo53mie/cats_dogs_dataset_reorg.zip\nReusing existing connection to www.dropbox.com:443.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://ucfd8157272a6270e100392293da.dl.dropboxusercontent.com/cd/0/inline/BYbFG6Zo1S3l2kJtqLrJIne9lTLgQn-uoJxmUjhLSkp36V7AoiwlyR2gP0XVoUQt9WzF2ZsmeERagMy7rpsNoIYG4MjsYA90i_JsarFDs9PHhXHw9qwHpHqBvgd4YU_mwDQHuouJ_oCU1kft04QgCVRg/file# [following]\n--2021-10-21 03:57:59-- https://ucfd8157272a6270e100392293da.dl.dropboxusercontent.com/cd/0/inline/BYbFG6Zo1S3l2kJtqLrJIne9lTLgQn-uoJxmUjhLSkp36V7AoiwlyR2gP0XVoUQt9WzF2ZsmeERagMy7rpsNoIYG4MjsYA90i_JsarFDs9PHhXHw9qwHpHqBvgd4YU_mwDQHuouJ_oCU1kft04QgCVRg/file\nResolving ucfd8157272a6270e100392293da.dl.dropboxusercontent.com (ucfd8157272a6270e100392293da.dl.dropboxusercontent.com)... 162.125.3.15, 2620:100:6018:15::a27d:30f\nConnecting to ucfd8157272a6270e100392293da.dl.dropboxusercontent.com (ucfd8157272a6270e100392293da.dl.dropboxusercontent.com)|162.125.3.15|:443... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: /cd/0/inline2/BYYSXb-0kWS7Lpk-cdrgBGzcOBfsvy7KjhqWEgjI5L9xfcaXohKlVeFMNFVyqvCwZLym2kWCD0nwURRpQ2mnHICrNsrvTvavbn24hk1Bd3_lXX08LBBe3C6YvD2U_iP8UMXROqm-B3JtnBjeMpk1R4YZ0O6aVLgKu0eET9RXsRaNCczD2lTK_i72zmbYhGmBvlRWmf_yQnnS5WKpGhSAobznIqKzw78yPzo5FsgGiEj5VXb91AElrKVAW8HFC9EhdUs7RrL3q9f0mQ9TbQpauoAp32TL3YQcuAp891Rv-EmDVxzfMwKVTGU8hxR2SiIWkse4u2QGhliqhdha7qBu7sIPcIoeI5-DdSoc6XG77vTYTRhrs_cf7rQuTPH2gTIUwTY/file [following]\n--2021-10-21 03:57:59-- https://ucfd8157272a6270e100392293da.dl.dropboxusercontent.com/cd/0/inline2/BYYSXb-0kWS7Lpk-cdrgBGzcOBfsvy7KjhqWEgjI5L9xfcaXohKlVeFMNFVyqvCwZLym2kWCD0nwURRpQ2mnHICrNsrvTvavbn24hk1Bd3_lXX08LBBe3C6YvD2U_iP8UMXROqm-B3JtnBjeMpk1R4YZ0O6aVLgKu0eET9RXsRaNCczD2lTK_i72zmbYhGmBvlRWmf_yQnnS5WKpGhSAobznIqKzw78yPzo5FsgGiEj5VXb91AElrKVAW8HFC9EhdUs7RrL3q9f0mQ9TbQpauoAp32TL3YQcuAp891Rv-EmDVxzfMwKVTGU8hxR2SiIWkse4u2QGhliqhdha7qBu7sIPcIoeI5-DdSoc6XG77vTYTRhrs_cf7rQuTPH2gTIUwTY/file\nReusing existing connection to ucfd8157272a6270e100392293da.dl.dropboxusercontent.com:443.\nHTTP request sent, awaiting response... 200 OK\nLength: 228802825 (218M) [application/zip]\nSaving to: ‘cats_dogs_dataset.zip’\n\ncats_dogs_dataset.z 100%[===================>] 218.20M 86.3MB/s in 2.5s \n\n2021-10-21 03:58:02 (86.3 MB/s) - ‘cats_dogs_dataset.zip’ saved [228802825/228802825]\n\n"
]
],
[
[
"### Read the config file and modify the config\n\nIn the [tools tutorial](https://colab.research.google.com/github/open-mmlab/mmclassification/blob/master/docs/tutorials/MMClassification_tools.ipynb), we have introduced all parts of the config file, and here we can modify the loaded config by Python code.",
"_____no_output_____"
]
],
[
[
"# Load the base config file\nfrom mmcv import Config\ncfg = Config.fromfile('configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py')\n\n# Modify the number of classes in the head.\ncfg.model.head.num_classes = 2\ncfg.model.head.topk = (1, )\n\n# Load the pre-trained model's checkpoint.\ncfg.model.backbone.init_cfg = dict(type='Pretrained', checkpoint=checkpoint_file, prefix='backbone')\n\n# Specify sample size and number of workers.\ncfg.data.samples_per_gpu = 32\ncfg.data.workers_per_gpu = 2\n\n# Specify the path and meta files of training dataset\ncfg.data.train.data_prefix = 'data/cats_dogs_dataset/training_set/training_set'\ncfg.data.train.classes = 'data/cats_dogs_dataset/classes.txt'\n\n# Specify the path and meta files of validation dataset\ncfg.data.val.data_prefix = 'data/cats_dogs_dataset/val_set/val_set'\ncfg.data.val.ann_file = 'data/cats_dogs_dataset/val.txt'\ncfg.data.val.classes = 'data/cats_dogs_dataset/classes.txt'\n\n# Specify the path and meta files of test dataset\ncfg.data.test.data_prefix = 'data/cats_dogs_dataset/test_set/test_set'\ncfg.data.test.ann_file = 'data/cats_dogs_dataset/test.txt'\ncfg.data.test.classes = 'data/cats_dogs_dataset/classes.txt'\n\n# Specify the normalization parameters in data pipeline\nnormalize_cfg = dict(type='Normalize', mean=[124.508, 116.050, 106.438], std=[58.577, 57.310, 57.437], to_rgb=True)\ncfg.data.train.pipeline[3] = normalize_cfg\ncfg.data.val.pipeline[3] = normalize_cfg\ncfg.data.test.pipeline[3] = normalize_cfg\n\n# Modify the evaluation metric\ncfg.evaluation['metric_options']={'topk': (1, )}\n\n# Specify the optimizer\ncfg.optimizer = dict(type='SGD', lr=0.005, momentum=0.9, weight_decay=0.0001)\ncfg.optimizer_config = dict(grad_clip=None)\n\n# Specify the learning rate scheduler\ncfg.lr_config = dict(policy='step', step=1, gamma=0.1)\ncfg.runner = dict(type='EpochBasedRunner', max_epochs=2)\n\n# Specify the work directory\ncfg.work_dir = './work_dirs/cats_dogs_dataset'\n\n# Output logs for every 10 iterations\ncfg.log_config.interval = 10\n\n# Set the random seed and enable the deterministic option of cuDNN\n# to keep the results' reproducible.\nfrom mmcls.apis import set_random_seed\ncfg.seed = 0\nset_random_seed(0, deterministic=True)\n\ncfg.gpu_ids = range(1)",
"_____no_output_____"
]
],
[
[
"### Fine-tune the model\n\nUse the API `train_model` to fine-tune our model on the cats & dogs dataset.",
"_____no_output_____"
]
],
[
[
"import time\nimport mmcv\nimport os.path as osp\n\nfrom mmcls.datasets import build_dataset\nfrom mmcls.models import build_classifier\nfrom mmcls.apis import train_model\n\n# Create the work directory\nmmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))\n# Build the classifier\nmodel = build_classifier(cfg.model)\nmodel.init_weights()\n# Build the dataset\ndatasets = [build_dataset(cfg.data.train)]\n# Add `CLASSES` attributes to help visualization\nmodel.CLASSES = datasets[0].CLASSES\n# Start fine-tuning\ntrain_model(\n model,\n datasets,\n cfg,\n distributed=False,\n validate=True,\n timestamp=time.strftime('%Y%m%d_%H%M%S', time.localtime()),\n meta=dict())",
"2021-10-21 04:04:12,758 - mmcv - INFO - initialize MobileNetV2 with init_cfg {'type': 'Pretrained', 'checkpoint': 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth', 'prefix': 'backbone'}\n2021-10-21 04:04:12,759 - mmcv - INFO - load backbone in model from: https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth\n2021-10-21 04:04:12,815 - mmcv - INFO - initialize LinearClsHead with init_cfg {'type': 'Normal', 'layer': 'Linear', 'std': 0.01}\n2021-10-21 04:04:12,818 - mmcv - INFO - \nbackbone.conv1.conv.weight - torch.Size([32, 3, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,821 - mmcv - INFO - \nbackbone.conv1.bn.weight - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,823 - mmcv - INFO - \nbackbone.conv1.bn.bias - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,824 - mmcv - INFO - \nbackbone.layer1.0.conv.0.conv.weight - torch.Size([32, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,826 - mmcv - INFO - \nbackbone.layer1.0.conv.0.bn.weight - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,827 - mmcv - INFO - \nbackbone.layer1.0.conv.0.bn.bias - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,829 - mmcv - INFO - \nbackbone.layer1.0.conv.1.conv.weight - torch.Size([16, 32, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,830 - mmcv - INFO - \nbackbone.layer1.0.conv.1.bn.weight - torch.Size([16]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,832 - mmcv - INFO - \nbackbone.layer1.0.conv.1.bn.bias - torch.Size([16]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,833 - mmcv - INFO - \nbackbone.layer2.0.conv.0.conv.weight - torch.Size([96, 16, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,835 - mmcv - INFO - \nbackbone.layer2.0.conv.0.bn.weight - torch.Size([96]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,836 - mmcv - INFO - \nbackbone.layer2.0.conv.0.bn.bias - torch.Size([96]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,838 - mmcv - INFO - \nbackbone.layer2.0.conv.1.conv.weight - torch.Size([96, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,839 - mmcv - INFO - \nbackbone.layer2.0.conv.1.bn.weight - torch.Size([96]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,841 - mmcv - INFO - \nbackbone.layer2.0.conv.1.bn.bias - torch.Size([96]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,842 - mmcv - INFO - \nbackbone.layer2.0.conv.2.conv.weight - torch.Size([24, 96, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,844 - mmcv - INFO - \nbackbone.layer2.0.conv.2.bn.weight - torch.Size([24]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,845 - mmcv - INFO - \nbackbone.layer2.0.conv.2.bn.bias - torch.Size([24]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,847 - mmcv - INFO - \nbackbone.layer2.1.conv.0.conv.weight - torch.Size([144, 24, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,848 - mmcv - INFO - \nbackbone.layer2.1.conv.0.bn.weight - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,850 - mmcv - INFO - \nbackbone.layer2.1.conv.0.bn.bias - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,851 - mmcv - INFO - \nbackbone.layer2.1.conv.1.conv.weight - torch.Size([144, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,853 - mmcv - INFO - \nbackbone.layer2.1.conv.1.bn.weight - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,854 - mmcv - INFO - \nbackbone.layer2.1.conv.1.bn.bias - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,856 - mmcv - INFO - \nbackbone.layer2.1.conv.2.conv.weight - torch.Size([24, 144, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,857 - mmcv - INFO - \nbackbone.layer2.1.conv.2.bn.weight - torch.Size([24]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,858 - mmcv - INFO - \nbackbone.layer2.1.conv.2.bn.bias - torch.Size([24]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,860 - mmcv - INFO - \nbackbone.layer3.0.conv.0.conv.weight - torch.Size([144, 24, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,861 - mmcv - INFO - \nbackbone.layer3.0.conv.0.bn.weight - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,863 - mmcv - INFO - \nbackbone.layer3.0.conv.0.bn.bias - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,864 - mmcv - INFO - \nbackbone.layer3.0.conv.1.conv.weight - torch.Size([144, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,866 - mmcv - INFO - \nbackbone.layer3.0.conv.1.bn.weight - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,867 - mmcv - INFO - \nbackbone.layer3.0.conv.1.bn.bias - torch.Size([144]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,869 - mmcv - INFO - \nbackbone.layer3.0.conv.2.conv.weight - torch.Size([32, 144, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,870 - mmcv - INFO - \nbackbone.layer3.0.conv.2.bn.weight - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,872 - mmcv - INFO - \nbackbone.layer3.0.conv.2.bn.bias - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,873 - mmcv - INFO - \nbackbone.layer3.1.conv.0.conv.weight - torch.Size([192, 32, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,875 - mmcv - INFO - \nbackbone.layer3.1.conv.0.bn.weight - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,876 - mmcv - INFO - \nbackbone.layer3.1.conv.0.bn.bias - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,878 - mmcv - INFO - \nbackbone.layer3.1.conv.1.conv.weight - torch.Size([192, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,879 - mmcv - INFO - \nbackbone.layer3.1.conv.1.bn.weight - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,882 - mmcv - INFO - \nbackbone.layer3.1.conv.1.bn.bias - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,883 - mmcv - INFO - \nbackbone.layer3.1.conv.2.conv.weight - torch.Size([32, 192, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,885 - mmcv - INFO - \nbackbone.layer3.1.conv.2.bn.weight - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,886 - mmcv - INFO - \nbackbone.layer3.1.conv.2.bn.bias - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,887 - mmcv - INFO - \nbackbone.layer3.2.conv.0.conv.weight - torch.Size([192, 32, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,889 - mmcv - INFO - \nbackbone.layer3.2.conv.0.bn.weight - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,890 - mmcv - INFO - \nbackbone.layer3.2.conv.0.bn.bias - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,892 - mmcv - INFO - \nbackbone.layer3.2.conv.1.conv.weight - torch.Size([192, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,894 - mmcv - INFO - \nbackbone.layer3.2.conv.1.bn.weight - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,895 - mmcv - INFO - \nbackbone.layer3.2.conv.1.bn.bias - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,896 - mmcv - INFO - \nbackbone.layer3.2.conv.2.conv.weight - torch.Size([32, 192, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,898 - mmcv - INFO - \nbackbone.layer3.2.conv.2.bn.weight - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,899 - mmcv - INFO - \nbackbone.layer3.2.conv.2.bn.bias - torch.Size([32]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,901 - mmcv - INFO - \nbackbone.layer4.0.conv.0.conv.weight - torch.Size([192, 32, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,903 - mmcv - INFO - \nbackbone.layer4.0.conv.0.bn.weight - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,907 - mmcv - INFO - \nbackbone.layer4.0.conv.0.bn.bias - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,908 - mmcv - INFO - \nbackbone.layer4.0.conv.1.conv.weight - torch.Size([192, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,910 - mmcv - INFO - \nbackbone.layer4.0.conv.1.bn.weight - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,911 - mmcv - INFO - \nbackbone.layer4.0.conv.1.bn.bias - torch.Size([192]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,913 - mmcv - INFO - \nbackbone.layer4.0.conv.2.conv.weight - torch.Size([64, 192, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,914 - mmcv - INFO - \nbackbone.layer4.0.conv.2.bn.weight - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,915 - mmcv - INFO - \nbackbone.layer4.0.conv.2.bn.bias - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,917 - mmcv - INFO - \nbackbone.layer4.1.conv.0.conv.weight - torch.Size([384, 64, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,918 - mmcv - INFO - \nbackbone.layer4.1.conv.0.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,920 - mmcv - INFO - \nbackbone.layer4.1.conv.0.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,921 - mmcv - INFO - \nbackbone.layer4.1.conv.1.conv.weight - torch.Size([384, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,923 - mmcv - INFO - \nbackbone.layer4.1.conv.1.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,924 - mmcv - INFO - \nbackbone.layer4.1.conv.1.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,925 - mmcv - INFO - \nbackbone.layer4.1.conv.2.conv.weight - torch.Size([64, 384, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,927 - mmcv - INFO - \nbackbone.layer4.1.conv.2.bn.weight - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,928 - mmcv - INFO - \nbackbone.layer4.1.conv.2.bn.bias - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,930 - mmcv - INFO - \nbackbone.layer4.2.conv.0.conv.weight - torch.Size([384, 64, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,932 - mmcv - INFO - \nbackbone.layer4.2.conv.0.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,933 - mmcv - INFO - \nbackbone.layer4.2.conv.0.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,935 - mmcv - INFO - \nbackbone.layer4.2.conv.1.conv.weight - torch.Size([384, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,936 - mmcv - INFO - \nbackbone.layer4.2.conv.1.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,938 - mmcv - INFO - \nbackbone.layer4.2.conv.1.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,939 - mmcv - INFO - \nbackbone.layer4.2.conv.2.conv.weight - torch.Size([64, 384, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,941 - mmcv - INFO - \nbackbone.layer4.2.conv.2.bn.weight - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,942 - mmcv - INFO - \nbackbone.layer4.2.conv.2.bn.bias - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,944 - mmcv - INFO - \nbackbone.layer4.3.conv.0.conv.weight - torch.Size([384, 64, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,945 - mmcv - INFO - \nbackbone.layer4.3.conv.0.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,946 - mmcv - INFO - \nbackbone.layer4.3.conv.0.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,948 - mmcv - INFO - \nbackbone.layer4.3.conv.1.conv.weight - torch.Size([384, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,949 - mmcv - INFO - \nbackbone.layer4.3.conv.1.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,951 - mmcv - INFO - \nbackbone.layer4.3.conv.1.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,952 - mmcv - INFO - \nbackbone.layer4.3.conv.2.conv.weight - torch.Size([64, 384, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,954 - mmcv - INFO - \nbackbone.layer4.3.conv.2.bn.weight - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,955 - mmcv - INFO - \nbackbone.layer4.3.conv.2.bn.bias - torch.Size([64]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,957 - mmcv - INFO - \nbackbone.layer5.0.conv.0.conv.weight - torch.Size([384, 64, 1, 1]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,958 - mmcv - INFO - \nbackbone.layer5.0.conv.0.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,959 - mmcv - INFO - \nbackbone.layer5.0.conv.0.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,961 - mmcv - INFO - \nbackbone.layer5.0.conv.1.conv.weight - torch.Size([384, 1, 3, 3]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,963 - mmcv - INFO - \nbackbone.layer5.0.conv.1.bn.weight - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n2021-10-21 04:04:12,964 - mmcv - INFO - \nbackbone.layer5.0.conv.1.bn.bias - torch.Size([384]): \nPretrainedInit: load from https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth \n \n"
],
[
"%matplotlib inline\n# Validate the fine-tuned model\n\nimg = mmcv.imread('data/cats_dogs_dataset/training_set/training_set/cats/cat.1.jpg')\n\nmodel.cfg = cfg\nresult = inference_model(model, img)\n\nshow_result_pyplot(model, img, result)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0ad0dfe9d7f79192d593f778fca9004e4ef7e49 | 357,349 | ipynb | Jupyter Notebook | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 | 8432303deb166f866e572c4e22792a89bcae5f37 | [
"MIT"
] | null | null | null | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 | 8432303deb166f866e572c4e22792a89bcae5f37 | [
"MIT"
] | null | null | null | aula05_imersao_alura_dados.ipynb | EnzoGolfetti/imersaoalura_dados_3 | 8432303deb166f866e572c4e22792a89bcae5f37 | [
"MIT"
] | 1 | 2021-05-03T21:40:55.000Z | 2021-05-03T21:40:55.000Z | 48.277357 | 27,374 | 0.47286 | [
[
[
"<a href=\"https://colab.research.google.com/github/EnzoGolfetti/imersaoalura_dados_3/blob/main/aula05_imersao_alura_dados.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"#Análise de Drugs Discovery - Imersão Dados Alura\nDesafio 1: Investigar por que a classe tratamento é tão desbalanceada",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"url_dados = 'https://github.com/alura-cursos/imersaodados3/blob/main/dados/dados_experimentos.zip?raw=true'\n\ndados = pd.read_csv(url_dados, compression = 'zip') #compression = 'zip' serve par aarquivos que estejam comprimidos, isso é bom para arquivos muito grandes\ndados",
"_____no_output_____"
]
],
[
[
"Cada linha é um experimento de cultura de células que foi submetida a alguma droga com determinada dosagem e por determinada quantidade de tempo.",
"_____no_output_____"
]
],
[
[
"dados.info() #para ver as primeiras infos dos dados, número de index (linhas)\n#colunas\n# e tipo dos dados, no caso são 872 de float64, 1 de int64 e 4 object (string)",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 23814 entries, 0 to 23813\nColumns: 877 entries, id to c-99\ndtypes: float64(872), int64(1), object(4)\nmemory usage: 159.3+ MB\n"
],
[
"dados.isnull().sum() #o .isnull .summ serve para somar por coluna os valores nulos, da um parecer inicial sobre quais colunas tem nulos e dar uma ideia\n#do que vamos precisar fazer",
"_____no_output_____"
],
[
"dados['tratamento']",
"_____no_output_____"
],
[
"dados['tratamento'].value_counts()",
"_____no_output_____"
]
],
[
[
"Os tratamentos tem expressiva quantidade de experimentos 'com_droga' e apenas 1866 de 23814 sendo 'com_controle'.",
"_____no_output_____"
],
[
"Com controle significa, aqueles que não recebem os tratamentos para testar como os com experimento reagiram a droga, para saber que foi a droga que mudou a resposta, temos que ter o grupo controle que esteja no mesmo ambiente, exceto a presença da droga para ver a resposta.",
"_____no_output_____"
]
],
[
[
"#próxima variável a ser analisada = tempo\ndados['tempo']",
"_____no_output_____"
],
[
"dados['tempo'].value_counts() ",
"_____no_output_____"
]
],
[
[
"Podemos ver que o tempo está disposto em unidades de 'hora', respectivamente:\n24, 48, 72.\n48 horas foi a maioria do tempo observado nos experimentos, e 24 horas a que menos foi (segundo a bióloga da imersão, devido a que, muitas vezes, 24 horas não é o suficiente para as células desenvolverem respostas à droga aplicada.",
"_____no_output_____"
]
],
[
[
"dados['dose'].value_counts()",
"_____no_output_____"
]
],
[
[
"Observamos que tem apenas dois tipos doses (D1, D2), D1 tendo a maioria dos registros - 12147",
"_____no_output_____"
]
],
[
[
"dados['droga'].value_counts()",
"_____no_output_____"
]
],
[
[
"Nas drogas, podemos ver que a droga 'cacb2b860' foi a mais usada (1866 vezes)\nE a droga '87d714366' foi a segunda mais usada com 718 vezes.\n\nO nome das drogas, é \"confuso\", pois foram anonimizados para evitar vieses nas análises.\n\nO total de drogas investigados foi de 3289 (registrado em 'length')",
"_____no_output_____"
]
],
[
[
"dados['g-0'].value_counts()",
"_____no_output_____"
]
],
[
[
"Os 'g' são abreviação de genes, portanto, existem observações das respostas de vários deles, que estão dispostos nas colunas, e os valores que vemos é a expressão dos genes frente à droga, dose e tempo de exposição.",
"_____no_output_____"
],
[
"Os valores provavelmente estão normalizados para permitir o entendimento e a comparação deles",
"_____no_output_____"
]
],
[
[
"#contando quantos valores maiores que 0, temos em 'g-0'\ndados[dados['g-0'] > 0].count()",
"_____no_output_____"
],
[
"#máscara para os dados g-0 maiores que '0'\ndados_g0_maior_zero = dados[dados['g-0'] > 0]\ndados_g0_maior_zero.head()",
"_____no_output_____"
]
],
[
[
"###Desafio 2: Plotar as últimas 5 linhas do Dataframe",
"_____no_output_____"
]
],
[
[
"#plotando últimas 5 linhas\ndados.iloc[23809:,:]",
"_____no_output_____"
]
],
[
[
"###Desafio 3: Registrar a proporção da classe tratamento",
"_____no_output_____"
]
],
[
[
"#usando método matemático\n(dados['tratamento'].value_counts() * 100) / 23814",
"_____no_output_____"
],
[
"#usando função value_counts do Pandas\ndados['tratamento'].value_counts(normalize=True) #o normalize nos dá os porcent deles",
"_____no_output_____"
]
],
[
[
"É interessante termos um comparativo com dados da própria tabela, porém de outras colunas, nesse caso, vamos comparar com a distribuição das doses",
"_____no_output_____"
]
],
[
[
"dados['dose'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"#plotando gráfico de pizza para mostrar as proporções dos valores em tratamento\nfig, ax = plt.subplots(figsize=(20,6))\nlabels = ['com_droga', 'com_controle']\nax.pie(dados['tratamento'].value_counts(normalize=True), labels=labels, autopct='%1.1f%%')\nax.set_title('Distribuição dos tipos de tratamentos')",
"_____no_output_____"
]
],
[
[
"###Observando graficamente os valores de tempo",
"_____no_output_____"
]
],
[
[
"barplot_time = dados['tempo'].value_counts().plot.bar()\nbarplot_time.set_title('Distribuição dos experimentos por tempo')\nbarplot_time.set_xlabel('Tempo observado')\nbarplot_time.set_ylabel('Nº de experimentos')",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(15,6))\nax.bar(dados['tempo'].unique(), height=dados['tempo'].value_counts(ascending=True), width=20, color='red')\nax.set_xticks(dados['tempo'].unique())\nax.set_title('Distribuição dos experimentos por tempo')\nax.set_xlabel('Tempo observado')\nax.set_ylabel('Nº de experimentos')",
"_____no_output_____"
],
[
"barplot_dose = dados['dose'].value_counts().plot.bar()\nbarplot_dose.set_title('Distribuição dos experimentos por dose')\nbarplot_dose.set_xlabel('Dose administrada')\nbarplot_dose.set_ylabel('Nº de experimentos')",
"_____no_output_____"
]
],
[
[
"###Desafio 4: Quantos tipos de drogas foram investigados?",
"_____no_output_____"
]
],
[
[
"dados['droga'].nunique()",
"_____no_output_____"
]
],
[
[
"###Desafio 5: Procurar a documentação do query (no pandas) e resolver o desafio de criar a máscara de valores g-0 maiores que zero",
"_____no_output_____"
]
],
[
[
"dados.query('g0 > 0')",
"_____no_output_____"
],
[
"dados.query('dose == \"D1\"') #fazendo mais um uso do Query",
"_____no_output_____"
]
],
[
[
"###Desafio 6: Renomear as colunas tirando o hífen",
"_____no_output_____"
]
],
[
[
"dados.columns = dados.columns.str.replace(\"-\",\"\")",
"_____no_output_____"
],
[
"dados.head()",
"_____no_output_____"
]
],
[
[
"###Desafio 7: Fazer um resumo das descobertas",
"_____no_output_____"
],
[
"Preferi deixar as anotações ao longo das células, se você leu até aqui, provavelmente viu minhas notas!",
"_____no_output_____"
],
[
"##Observando a distribuição dos genes g0 e g1",
"_____no_output_____"
]
],
[
[
"#histograma da distribuição dos resultados de g0\nax = sns.displot(data=dados, x='g0', kde=True)\nprint(dados['g0'].min())\nprint(dados['g0'].max())\nprint(dados['g0'].mean())\nprint(dados['g0'].median())\nprint(dados['g0'].var())\nprint(dados['g0'].skew())",
"_____no_output_____"
],
[
"sns.displot(data=dados, x='g1', kde=True)\nprint(dados['g1'].min())\nprint(dados['g1'].max())\nprint(dados['g1'].mean())\nprint(dados['g1'].median())\nprint(dados['g1'].var())\nprint(dados['g1'].skew())",
"_____no_output_____"
]
],
[
[
"###Aula 02",
"_____no_output_____"
]
],
[
[
"#forma interessante de substituir nome de coluna\n#através de um mapa\nmapa = {'droga':'composto'}\ndados.rename(columns=mapa, inplace=True)",
"_____no_output_____"
]
],
[
[
"Criando um countplot com os primeiros 5 compostos mais usados",
"_____no_output_____"
]
],
[
[
"comp = dados['composto'].value_counts().index[:5]",
"_____no_output_____"
],
[
"#coletando as infos dos 5 compostos com o query\nd_comp = dados.query('composto in @comp') #o @ serve para declarar que a váriavel foi definida pelo python e não pelo dados",
"_____no_output_____"
]
],
[
[
"###Desafio 9: Melhorar a visualização e estética dos gráficos",
"_____no_output_____"
]
],
[
[
"#usando o Seaborn\nfig, ax = plt.subplots(figsize=(15,6))\nsns.set() #rodar pelo menos uma vez o .set() tras as novas configurações automáticas de estilização do Seaborn\nax = sns.countplot(data=d_comp, x='composto')\nax.set_title('5 compostos mais usados', )\nax.set_xlabel('Composto')\nax.set_ylabel('vezes usado')\nplt.show() #colocar ele mesmo com o matplotlib inline some com o text que vem em cima do gráfico",
"_____no_output_____"
],
[
"#loc nos genes 'g'\ndados.loc[:,'g0':'g771'].describe()",
"_____no_output_____"
]
],
[
[
"Histograma das médias dos genes 'g'",
"_____no_output_____"
]
],
[
[
"#com o .T fazemos a transposição do DataFrame\ndescribe_g = dados.loc[:,'g0':'g771'].describe().T",
"_____no_output_____"
],
[
"#plotando o histograma das médias\nhist_g = sns.histplot(describe_g, x='mean', kde=True)\nplt.show()",
"_____no_output_____"
],
[
"#histograma dos desvios-padrão\nhist_g = sns.histplot(describe_g, x='std', kde=True)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Observando as variáveis 'c'",
"_____no_output_____"
]
],
[
[
"describe_c = dados.loc[:,'c0':'c99'].describe().T",
"_____no_output_____"
],
[
"#histograma das médias\nsns.histplot(data=describe_c, x='mean', kde=True)\nplt.show()",
"_____no_output_____"
]
],
[
[
"No Dataframe, cada 'c' respresenta linhagens de células, o pressuposto de ter vários tipos de células é para garantir a famosa independência estatística, e não gerar o viés de que o o medicamento agiu em determinado tipo, ou que foi o tipo que gerou o resultado da célula, e também garantir saber possíveis colaterais.\n\nOs valores registrados em c são as viabilidades, ou seja, \"o quanto as células sobreviveram\" à exposição daqueles compostos ",
"_____no_output_____"
],
[
"###Plotando Boxplots",
"_____no_output_____"
]
],
[
[
"sns.boxplot(data=dados, x='g0')",
"_____no_output_____"
],
[
"#boxplot da resposta de g0 por dose administrada\nplt.figure(figsize=(10,6))\nsns.boxplot(data=dados, x='g0', y='dose', )",
"_____no_output_____"
],
[
"#boxplot da resposta de g0 por tratamento\nsns.boxplot(data=dados, x='g0', y='tratamento')",
"_____no_output_____"
]
],
[
[
"Plotando um boxplot mais bonito e mais completo",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(10,9))\nsns.set_style('darkgrid')\nsns.set_context('talk')\nax = sns.boxplot(data=dados, x='tratamento', y='g0', hue='dose', palette='Paired')\nax.set_xlabel('Tipo de tratamento', fontdict={'fontsize':20})\nax.set_ylabel('gene g0')\nax.set_title('Quartis e mediana por tratamento e dose', fontdict={'fontsize':20, 'verticalalignment':'center'})\nplt.show()",
"_____no_output_____"
]
],
[
[
"##Dia 3",
"_____no_output_____"
],
[
"Função nova: \".crosstab\" que cria uma frequency table",
"_____no_output_____"
],
[
"Para filtrar mais de um dado, nas colunas ou linhas (e criar um MultiIndex) devemos inserir os **colchetes antes**(procedimento padrão no Pandas).\n\nPodemos normalizar os valores de várias formas (ver documetação) com o **'normalize='**.\n\nPara adicionar um valor específico que desejamos ver os dados correspondentes a ele, usar **'value='** e podemos inclusive, colocar uma função (média, mediana, std, etc.) com o **'aggfunc='**.",
"_____no_output_____"
]
],
[
[
"pd.crosstab(dados['dose'], [dados['tratamento'], dados['tempo']])",
"_____no_output_____"
],
[
"#outra forma de fazer\npd.crosstab([dados['dose'], dados['tempo']], dados['tratamento']) ",
"_____no_output_____"
],
[
"#plotando as proporções\npd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], normalize=True) * 100",
"_____no_output_____"
],
[
"#plotando as proporções pelo index (nesse caso será em relação as linhas)\npd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], normalize='index')",
"_____no_output_____"
],
[
"pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='mean')",
"_____no_output_____"
]
],
[
[
"###Desafio 08: Fazer uma tabela parecida com a crosstab mas utilizando o Groupby",
"_____no_output_____"
],
[
"Nota pessoal: Eu gosto muito de Groupby, ela é muito poderosa",
"_____no_output_____"
]
],
[
[
"groupby = dados.groupby(by=['dose', 'tratamento','tempo']).count()",
"_____no_output_____"
],
[
"groupby.iloc[:13,2:3]",
"_____no_output_____"
],
[
"groupby.iloc[:13,2:3].T",
"_____no_output_____"
]
],
[
[
"###Desafio 9: Normalizar o crosstab pela coluna",
"_____no_output_____"
]
],
[
[
"pd.crosstab([dados['dose'],dados['tempo']], dados['tratamento'], normalize='columns')",
"_____no_output_____"
]
],
[
[
"###Desafio 10: Quais outros agregadores existem?",
"_____no_output_____"
],
[
"Média",
"_____no_output_____"
]
],
[
[
"pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='mean')",
"_____no_output_____"
]
],
[
[
"Mediana",
"_____no_output_____"
]
],
[
[
"pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='median')",
"_____no_output_____"
]
],
[
[
"Standard Deviation a.k.a Desvio-padrão",
"_____no_output_____"
]
],
[
[
"pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='std')",
"_____no_output_____"
]
],
[
[
"Variância",
"_____no_output_____"
]
],
[
[
"pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='var')",
"_____no_output_____"
]
],
[
[
"###Desafio 11: Explorar o Melt",
"_____no_output_____"
],
[
"Esse método pode ser aplicado tanto em pd (pandas) quanto diretamente no Dataframe",
"_____no_output_____"
]
],
[
[
"pd.melt(dados, id_vars=['dose','tratamento', 'tempo'], value_vars=['g0'])",
"_____no_output_____"
],
[
"dados.melt(id_vars=['dose','tratamento','tempo'], value_vars=['g0'])",
"_____no_output_____"
],
[
"dados.melt(id_vars=['dose','tratamento','tempo'], value_vars=['g0'])[:5]\n#podemos aplicar o index como sempre para dar uma filtrada",
"_____no_output_____"
],
[
"dados.melt(id_vars=['dose','tratamento','tempo'], value_vars=['g0'], value_name='respostas do gene 0').mean()\n#observando a média do gene 0 pela dose, tratamento e tempo",
"_____no_output_____"
]
],
[
[
"###Explorando as correlações e variações de g0 e g1",
"_____no_output_____"
]
],
[
[
"#usando a dispersão\nsns.scatterplot(data=dados, x='g0', y='g1')",
"_____no_output_____"
],
[
"sns.scatterplot(data=dados, x='g0', y='g3', )",
"_____no_output_____"
],
[
"#o jointplot mostra a distruibuição junto com a dispersão\nsns.jointplot(data=dados, x='g0', y='g3', kind='reg')",
"_____no_output_____"
],
[
"#outra forma de ver a linha de distribuição é com o lmplot\nsns.lmplot(data=dados, x='g0', y='g3', line_kws={'color':'red'})",
"_____no_output_____"
],
[
"sns.lmplot(data=dados, x='g0', y='g3', line_kws={'color':'red'}, hue='dose', col='tratamento', row='tempo')",
"_____no_output_____"
]
],
[
[
"Observando as correlações",
"_____no_output_____"
],
[
"O Próprio Pandas pode nos mostrar as correlações",
"_____no_output_____"
]
],
[
[
"#.corr()\ndados.loc[:,'g0':'g771'].corr()",
"_____no_output_____"
]
],
[
[
"No geral, utilizamos um gráfico 'heatmap' para ver as correlações.\n\nAqui, usaremos um ctrl+c ctrl+v da matriz diagonal de correlação",
"_____no_output_____"
]
],
[
[
"corr = dados.loc[:,'g0':'g50'].corr()\n\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(corr, dtype=bool))\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(30, 15))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr, mask=mask, cmap=cmap, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})",
"_____no_output_____"
]
],
[
[
"VELHO LEMBRETE: **Correlação não é causalidade!**",
"_____no_output_____"
],
[
"Correlações de C",
"_____no_output_____"
]
],
[
[
"corr_c = dados.loc[:,'c0':'c50'].corr()\n\n# Generate a mask for the upper triangle\nmask = np.triu(np.ones_like(corr_c, dtype=bool))\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(30, 15))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(230, 20, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr_c, mask=mask, cmap=cmap, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})",
"_____no_output_____"
]
],
[
[
"###Desafio 12: Explorar a correlação entre expressões gênicas g e os tipos célulares c",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"##Dia 4",
"_____no_output_____"
],
[
"###Hoje vamos observar os resultados dos testes experimentais",
"_____no_output_____"
]
],
[
[
"dados_resultados = pd.read_csv('https://github.com/alura-cursos/imersaodados3/blob/main/dados/dados_resultados.csv?raw=true')\ndados_resultados.head()",
"_____no_output_____"
]
],
[
[
"De forma superficial, essa base contém os mecanismos de ação, se 1, foi ativado pelo experimento, se 0 é que não foi ativado pelo experimento",
"_____no_output_____"
]
],
[
[
"dados_resultados.info()",
"_____no_output_____"
]
],
[
[
"###Três formas de fazer a contagem dos mecanismos de ação",
"_____no_output_____"
],
[
"Com o Iloc",
"_____no_output_____"
]
],
[
[
"contagem_moa = dados_resultados.iloc[:,1:].sum().sort_values(ascending=False)\ncontagem_moa",
"_____no_output_____"
]
],
[
[
"COm o select_dtypes",
"_____no_output_____"
]
],
[
[
"contagem_moa = dados_resultados.select_dtypes('int64').sum().sort_values(ascending=False)\ncontagem_moa",
"_____no_output_____"
]
],
[
[
"Com o drop",
"_____no_output_____"
]
],
[
[
"contagem_moa = dados_resultados.drop('id', axis=1).sum().sort_values(ascending=False)\ncontagem_moa",
"_____no_output_____"
],
[
"dados_resultados['n_moa'] = dados_resultados.drop('id', axis=1).sum(axis=1)",
"_____no_output_____"
],
[
"dados_resultados['moa_ativado'] = dados_resultados['n_moa'] != 0",
"_____no_output_____"
],
[
"dados_resultados.head()",
"_____no_output_____"
],
[
"dados_final = pd.merge(dados, dados_resultados[['id', 'n_moa', 'moa_ativado']], on='id')",
"_____no_output_____"
],
[
"dados_final.head(2)",
"_____no_output_____"
]
],
[
[
"###Desafio 01: Encontrar o top10 das ações do MoA (inibidor, agonista, etc.)",
"_____no_output_____"
]
],
[
[
"copy_dados = dados_resultados\ncopy_dados",
"_____no_output_____"
],
[
"#contando quantos tem inhibitor\nlen(copy_dados.columns[copy_dados.columns.str.contains('inhibitor')])",
"_____no_output_____"
],
[
"#Contando quantos tem agonist\nlen(copy_dados.columns[copy_dados.columns.str.contains('agonist')])",
"_____no_output_____"
],
[
"#vendo os que não contém nem inhibitor nem agonist\ncopy_dados.columns[(copy_dados.columns.str.contains('agonist') == False) & (copy_dados.columns.str.contains('inhibitor')==False)]",
"_____no_output_____"
]
],
[
[
"###Desafio 2: Criar uma coluna True False (0,1) para a coluna tratamento",
"_____no_output_____"
]
],
[
[
"dados_final['eh_controle'] = dados_final['tratamento'] == 'com_controle'\n",
"_____no_output_____"
],
[
"dados_final['eh_controle'].value_counts()",
"_____no_output_____"
]
],
[
[
"###Desafio 3: Criar colunas para 24, 48 e 72 de True e False",
"_____no_output_____"
]
],
[
[
"dados_final['tempo'].dtype",
"_____no_output_____"
],
[
"dados_final['24h'] = dados_final['tempo'] == 24\ndados_final.head(2)",
"_____no_output_____"
],
[
"dados_final['48h'] = dados_final['tempo'] == 48",
"_____no_output_____"
],
[
"dados_final['72h'] = dados_final['tempo'] == 72",
"_____no_output_____"
]
],
[
[
"###Desafio 4: Criar coluna para dose ",
"_____no_output_____"
]
],
[
[
"dados_final['d1'] = dados_final['dose'] == 'D1'",
"_____no_output_____"
],
[
"dados_final['d2'] = dados_final['dose'] == 'D2'",
"_____no_output_____"
]
],
[
[
"###Desafio 4: Análise mais profunda para quando há tempo e dose",
"_____no_output_____"
]
],
[
[
"dados_final['composto'].value_counts()",
"_____no_output_____"
],
[
"#não esquecer: para teste boleano não aplicar o filtro (nome do dataset no início), para fazer slice ai sim se coloca o filtro, como no caso abaixo\nanalise_comp = dados_final[(dados_final['composto'] == 'cacb2b860') | (dados_final['composto'] == '5628cb3ee')]\nanalise_comp",
"_____no_output_____"
],
[
"sns.catplot(data=analise_comp, x='composto', y='g0', hue='tratamento', col='dose', row='tempo', kind='box')",
"_____no_output_____"
]
],
[
[
"Observando a partir da coluna eh_controle True False que criamos",
"_____no_output_____"
]
],
[
[
"sns.catplot(data=analise_comp, x='composto', y='g0', hue='eh_controle', col='dose', row='tempo', kind='box')",
"_____no_output_____"
]
],
[
[
"Passando ordem explícita para o hue de como ordenar",
"_____no_output_____"
]
],
[
[
"sns.catplot(data=analise_comp, x='composto', y='g0', hue='tratamento', col='dose', row='tempo', kind='box', hue_order=['com_droga','com_controle'])",
"_____no_output_____"
]
],
[
[
"##Dia 5",
"_____no_output_____"
],
[
"No último dia da imersão, estamos implementando alguns modelos de machine learning para auxiliar no Drug Discovery",
"_____no_output_____"
]
],
[
[
"dados_final.head()",
"_____no_output_____"
]
],
[
[
"No train test split, podemos passar algumas variáveis, para que tenhamos um modelo de comparação para os outros modelos que vamos testar (a benchmark), são eles: random_state, que vai travar em determinada acurácia o modelo e stratify que vai garantir que a acurácia seja igual à realidade.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split #biblioteca para separar as bases de dados para treinar e testar a capacidade do modelo\n\nx = dados_final.select_dtypes('float64')\ny = dados_final['moa_ativado']\n\nx_treino, x_teste, y_treino, y_teste = train_test_split(x,y, test_size=0.2, stratify=y, random_state=350)",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression #modelo de regressão logística\nfrom sklearn.model_selection import train_test_split\n\nmodelo_rlogistica = LogisticRegression(max_iter=1000)\nmodelo_rlogistica.fit(x_treino, y_treino)\nmodelo_rlogistica.score(x_teste, y_teste)",
"_____no_output_____"
]
],
[
[
"Um método interessante para comparar a capacidade do modelo é o uso de modelo Dummy (bobo e simples) para ver se nosso modelo realmente está fazendo uma previsão melhor que \"chutando\".\n\nObs: na página do Sklearn sobre o Dummy há um alerta de não usá-lo para problemas reais.",
"_____no_output_____"
]
],
[
[
"from sklearn.dummy import DummyClassifier\nfrom sklearn.metrics import accuracy_score\ndummy_model = DummyClassifier('most_frequent')\ndummy_model.fit(x_treino, y_treino)\nprevisao_dummy = dummy_model.predict(x_teste)\naccuracy_score(y_teste, previsao_dummy)",
"_____no_output_____"
]
],
[
[
"Com o benchmark feito, agora podemos construir nossa tentativa de um novo modelo com melhor capacidade de previsão, o proposto foi: árvore de decisão (Decision Tree)",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeClassifier\nx = dados_final.select_dtypes('float64')\ny = dados_final['moa_ativado']\n\nx_treino, x_teste, y_treino, y_teste = train_test_split(x,y, test_size=0.2, stratify=y, random_state=350)",
"_____no_output_____"
],
[
"tree = DecisionTreeClassifier(max_depth=3)\n\ntree.fit(x_treino, y_treino)\ntree.score(x_teste, y_teste)",
"_____no_output_____"
]
],
[
[
"O max_depth é a profundidade dos níveis de decisão da árvore, nesse caso, ela está com 3, isso PODE SER um dos problemas da baixa acurácia.\n\nVamos testar para uma profundidade maior e ver o que acontece.",
"_____no_output_____"
]
],
[
[
"tree = DecisionTreeClassifier(max_depth=10)\n\ntree.fit(x_treino, y_treino)\ntree.score(x_teste, y_teste)",
"_____no_output_____"
],
[
"teste=[]\ntreino=[]\nfor i in range(1,15):\n modelo_arvore = DecisionTreeClassifier(max_depth = i)\n modelo_arvore.fit(x_treino, y_treino)\n teste.append(modelo_arvore.score(x_teste, y_teste))\n treino.append(modelo_arvore.score(x_treino, y_treino))",
"_____no_output_____"
],
[
"teste",
"_____no_output_____"
],
[
"treino",
"_____no_output_____"
],
[
"sns.lineplot(x=range(1,15), y=treino, label='treino')\nsns.lineplot(x=range(1,15), y=teste, label='teste')",
"_____no_output_____"
]
],
[
[
"Podemos ver que ao contrário do esperado, o algoritmo passou a performar melhor no treino e pior no teste, esse é um processo conhecido como 'overfitting', ou uma especialização do algoritmo na base de treino e que portanto, perde a capacidade de generalização.",
"_____no_output_____"
],
[
"Já que aprofundar não é uma forma sempre perfeita de aplicar, podemos fazer com que o dataset seja varrido por várias árvores de decisão, esse é o algoritmo chamado de Random Forest.\n\nComo funciona?\n\nEle divide o dataset em várias amostras e aplica as árvores de decisão nelas",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestClassifier\n#aplicação é semelhante ao Decision Tree\n\nx = dados_final.drop(columns=['id', 'moa_ativado', 'n_moa', 'tratamento','tempo','dose','composto']) #podemos ver que o Random Forest consegue arcar com tipos diversos de dados\ny = dados_final['moa_ativado']\n\nx_treino, x_teste, y_treino, y_teste = train_test_split(x,y, test_size=0.2, stratify=y, random_state=350)",
"_____no_output_____"
]
],
[
[
"Testei minha Random Forest para vários parâmetros e cheguei a esses resultados: ",
"_____no_output_____"
]
],
[
[
"random_forest = RandomForestClassifier(n_estimators=1000)\nrandom_forest.fit(x_treino, y_treino)\nrandom_forest.score(x_teste, y_teste)",
"_____no_output_____"
],
[
"random_forest = RandomForestClassifier(n_estimators=1000, max_depth=8)\nrandom_forest.fit(x_treino, y_treino)\nrandom_forest.score(x_teste, y_teste)",
"_____no_output_____"
],
[
"random_forest = RandomForestClassifier()\nrandom_forest.fit(x_treino, y_treino)\nrandom_forest.score(x_teste, y_teste)",
"_____no_output_____"
],
[
"lista_treino = []\nlista_teste = []\nfor i in range(200,238):\n random_forest = RandomForestClassifier(n_estimators=i)\n random_forest.fit(x_treino, y_treino)\n lista_treino.append(random_forest.score(x_treino, y_treino))\n lista_teste.append(random_forest.score(x_teste, y_teste))",
"_____no_output_____"
],
[
"lista_treino",
"_____no_output_____"
],
[
"lista_teste",
"_____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",
"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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ad1e7da2c5005a2f09cd4d68878994d60ee6cd | 3,258 | ipynb | Jupyter Notebook | scripts/tutorials/biginner/01_tensor_tutorial_gpu.ipynb | tayutaedomo/pytorch-sandbox | dc7fb2addf0f053836cd585706f478f4f68ec798 | [
"MIT"
] | null | null | null | scripts/tutorials/biginner/01_tensor_tutorial_gpu.ipynb | tayutaedomo/pytorch-sandbox | dc7fb2addf0f053836cd585706f478f4f68ec798 | [
"MIT"
] | null | null | null | scripts/tutorials/biginner/01_tensor_tutorial_gpu.ipynb | tayutaedomo/pytorch-sandbox | dc7fb2addf0f053836cd585706f478f4f68ec798 | [
"MIT"
] | null | null | null | 3,258 | 3,258 | 0.702885 | [
[
[
"from __future__ import print_function\nimport torch",
"_____no_output_____"
],
[
"print(torch.__version__)",
"1.5.0+cu101\n"
],
[
"x = torch.randn(1)\nprint(x)\nprint(x.item())",
"tensor([0.4148])\n0.41475337743759155\n"
],
[
"if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n y = torch.ones_like(x, device=device) # directly create a tensor on GPU\n x = x.to(device) # or just use strings ``.to(\"cuda\")``\n z = x + y\n\n print(z)\n print(z.to(\"cpu\", torch.double))",
"tensor([1.4148], device='cuda:0')\ntensor([1.4148], dtype=torch.float64)\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
d0ad2e1b350363f369b0a0cec22111233bf17fc4 | 177,601 | ipynb | Jupyter Notebook | engr1330jb/_build/jupyter_execute/lessons/lesson14/lesson14.ipynb | dustykat/engr-1330-psuedo-course | 3e7e31a32a1896fcb1fd82b573daa5248e465a36 | [
"CC0-1.0"
] | null | null | null | engr1330jb/_build/jupyter_execute/lessons/lesson14/lesson14.ipynb | dustykat/engr-1330-psuedo-course | 3e7e31a32a1896fcb1fd82b573daa5248e465a36 | [
"CC0-1.0"
] | null | null | null | engr1330jb/_build/jupyter_execute/lessons/lesson14/lesson14.ipynb | dustykat/engr-1330-psuedo-course | 3e7e31a32a1896fcb1fd82b573daa5248e465a36 | [
"CC0-1.0"
] | null | null | null | 217.648284 | 27,488 | 0.907867 | [
[
[
"<div class=\"alert alert-block alert-info\">\n <b><h1>ENGR 1330 Computational Thinking with Data Science </h1></b> \n</div> \n\nCopyright © 2021 Theodore G. Cleveland and Farhang Forghanparast\n\nLast GitHub Commit Date: \n \n# 14: Visual display of data\n\nThis lesson is a prelude to the `matplotlib` external module package, used to construct\nline charts, scatter plots, bar charts, box plot, and histograms. `matplotlib` is used herein to generate some different plots; with additional detail in a subseqent lesson.\n\n- plot types\n- plot uses\n- plot conventions",
"_____no_output_____"
],
[
"---\n\n## Objectives\n- List common plot types and their uses\n- Identify the parts of a line (or scatter) plot\n 1. Define the ordinate, abscissa\n 2. Define independent and dependent variables\n- Define how to plot experimental data (observations) and theoretical data (model)\n 1. Marker conventions\n 2. Line conventions\n 3. Legends\n\n---\n\n### About `matplotlib`\nQuoting from: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py\n\n`matplotlib.pyplot` is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.\n\nIn `matplotlib.pyplot` various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that \"axes\" here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).\n\n**Computational thinking (CT)** concepts involved are:\n\n- `Decomposition` : Break a problem down into smaller pieces; separating plotting from other parts of analysis simplifies maintenace of scripts\n- `Abstraction` : Pulling out specific differences to make one solution work for multiple problems; wrappers around generic plot calls enhances reuse \n- `Algorithms` : A list of steps that you can follow to finish a task; Often the last step and most important to make professional graphics to justify the expense (of paying you to do engineering) to the client.",
"_____no_output_____"
],
[
"---\n\n## Graphics Conventions for Plots\n\n```{note}\nThis section needs to have graphics replaced with author generated examples in future editions\n\n```\n\n### Terminology: Ordinate, Abscissa, Dependent and Independent Variables\n\nA few terms are used in describing plots:\n- Abscissa – the horizontal axis on a plot (the left-right axis)\n- Ordinate – the vertical axis on a plot (the up-down axis)\n\nA few terms in describing data models\n- Independent Variable (Explainatory, Predictor, Feature, ...) – a variable that can be controlled/manipulated in an experiment or theoretical analysis\n- Dependent Variable (Response, Prediction, ...) – the variable that measured/observed as a function of the independent variable\n\nPlotting convention in most cases assigns explainatory variables to the horizontal axis (e.g. Independent variable is plotted on the Abscissa) and the response variable(s) to the vertical axis (e.g. Dependent Variable is plotted on the Ordinate)\n\n---",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"---\n\n#### Conventions for Proper Plots\n- Include a title OR a caption with a brief description of the plot\n- Label both axes clearly\n - Include the variable name, the variable, and the unit in each label\n \n---",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"---\n\n- If possible, select increments for both the x and y axes that provide for easy interpolation\n\n---\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"---\n\n- Include gridlines\n- Show experimental measurements as symbols\n- Show model (theoretical) relationships as lines\n\n---\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"---\n\n- Use portrait orientation when making your plot\n- Make the plot large enough to be easily read\n- If more than one experimental dataset is plotted\n - Use different shapes for each dataset\n - Use different colors for each dataset\n - Include a legend defining the datasets\n\n---",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"---\n\n### Line Charts using `matplotlib`\nA line chart or line plot or line graph or curve chart is a type of chart which displays information as a series of data points called 'markers' connected by straight line segments.\n\nIt is a basic type of chart common in many fields. It is similar to a scatter plot (below) except that the measurement points are **ordered** (typically by their x-axis value) and joined with straight line segments. \n\nA line chart is often used to visualize a trend in data over intervals of time – a time series – thus the line is often drawn chronologically. \n\nThe x-axis spacing is sometimes tricky, hence line charts can unintentionally decieve - so be careful that it is the appropriate chart for your application. \n\n#### Example\n\nConsider the experimental data below\n\n|Elapsed Time (s)|Speed (m/s)|\n|---:|---:|\n|0 |0|\n|1.0 |3|\n|2.0 |7|\n|3.0 |12|\n|4.0 |20|\n|5.0 |30|\n|6.0 | 45.6| \n\nShow the relationship between time and speed. Is the relationship indicating acceleration? How much?",
"_____no_output_____"
]
],
[
[
"# import the package\nfrom matplotlib import pyplot as plt",
"_____no_output_____"
],
[
"# Create two lists; time and speed.\ntime = [0,1.0,2.0,3.0,4.0,5.0,6.0]\nspeed = [0,3,7,12,20,30,45.6]",
"_____no_output_____"
],
[
"# Create a line chart of speed on y axis and time on x axis\nmydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class\nplt.plot(time, speed, c='red', marker='v',linewidth=1) # basic line plot\nplt.show()",
"_____no_output_____"
],
[
"time = [0,1.0,4.0,5.0,6.0,2.0,3.0]\nspeed = [0,3,20,30,45.6,7,12]\n# Create a line chart of speed on y axis and time on x axis\nmydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class\nplt.plot(time, speed, c='green', marker='o',linewidth=1) # basic line plot\nplt.show()",
"_____no_output_____"
],
[
"# Estimate acceleration (naive)\ndvdt = (max(speed) - min(speed))/(max(time)-min(time))\nplottitle = 'Average acceleration %.1f' % (dvdt) + r' ($\\frac{m}{s^2}$)'\nseriesnames = ['Data','Model']\nmodely = [min(speed),max(speed)]\nmodelx = [min(time),max(time)]\nmydata = plt.figure(figsize = (10,5)) # build a square drawing canvass from figure class\nplt.plot(time, speed, c='red', marker='v',linewidth=1) # basic line plot\nplt.plot(modelx, modely, c='blue',linewidth=1) # basic line plot\nplt.xlabel('Time (sec)')\nplt.ylabel('Speed '+r'($\\frac{m}{s}$)')\nplt.legend(seriesnames)\nplt.title(plottitle)\nplt.show()",
"_____no_output_____"
]
],
[
[
"---\n\n### Line Charts in Pandas\n\nThe next few examples use graphics in pandas. The example below uses a database table from [census_18.csv](http://54.243.252.9/engr-1330-webroot/1-Lessons/Lesson12/census_18.csv)\n\n",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\ndf = pd.read_csv('census_18.csv')\ndf.head()",
"_____no_output_____"
],
[
"df.plot.line(x=\"AGE\", y=\"2010\", label=\"Born in 2014\", c=\"blue\")",
"_____no_output_____"
],
[
"ax = df.plot.line(x=\"AGE\", y=\"2010\", label=\"Born in 2014\", c=\"blue\")\ndf.plot.line(x=\"AGE\", y=\"2014\", label=\"Born in 2015\", c=\"red\", ax=ax)",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\nage = df['AGE']\nborn2010 = df['2010']\nborn2014 = df['2014']\n\nplt.plot(age, born2010, c='blue')\nplt.show()",
"_____no_output_____"
],
[
"plt.plot(age, born2010, c='blue', label='Born in 2010')\nplt.plot(age, born2014, c='red', label='Born in 2014')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## References\n\n1. Grus, Joel (2015-04-14). Data Science from Scratch: First Principles with Python\n(Kindle Locations 1190-1191). O'Reilly Media. Kindle Edition. \n\n2. Call Expressions in \"Adhikari, A. and DeNero, J. Computational and Inferential Thinking The Foundations of Data Science\" https://www.inferentialthinking.com/chapters/03/3/Calls.html\n\n3. Functions and Tables in \"Adhikari, A. and DeNero, J. Computational and Inferential Thinking The Foundations of Data Science\" https://www.inferentialthinking.com/chapters/08/Functions_and_Tables.html\n\n4. Visualization in \"Adhikari, A. and DeNero, J. Computational and Inferential Thinking The Foundations of Data Science\" https://www.inferentialthinking.com/chapters/07/Visualization.html\n\n5. Documentation; The Python Standard Library; 9. Numeric and Mathematical Modules https://docs.python.org/2/library/math.html\n\n6. https://matplotlib.org/gallery/lines_bars_and_markers/horizontal_barchart_distribution.html?highlight=horizontal%20bar%20chart\n\n7. https://www.geeksforgeeks.org/bar-plot-in-matplotlib/",
"_____no_output_____"
],
[
"## Addendum (Scripts that are Interactive)\n\n:::{note}\nThe addendum is intended for in-class demonstration\n:::",
"_____no_output_____"
]
],
[
[
"# python script to illustrate plotting\n# CODE BELOW IS ADAPTED FROM:\n# Grus, Joel (2015-04-14). Data Science from Scratch: First Principles with Python\n# (Kindle Locations 1190-1191). O'Reilly Media. Kindle Edition. \n#\nfrom matplotlib import pyplot as plt # import the plotting library from matplotlibplt.show()\n\nyears = [1950, 1960, 1970, 1980, 1990, 2000, 2010] # define one list for years\ngdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3] # and another one for Gross Domestic Product (GDP)\nplt.plot( years, gdp, color ='green', marker ='o', linestyle ='solid') # create a line chart, years on x-axis, gdp on y-axis\n # what if \"^\", \"P\", \"*\" for marker?\n # what if \"red\" for color? \n # what if \"dashdot\", '--' for linestyle? \n\n\nplt.title(\"Nominal GDP\")# add a title\nplt.ylabel(\"Billions of $\")# add a label to the x and y-axes\nplt.xlabel(\"Year\")\nplt.show() # display the plot",
"_____no_output_____"
]
],
[
[
"Now lets put the plotting script into a function so we can make line charts of any two numeric lists",
"_____no_output_____"
]
],
[
[
"def plotAline(list1,list2,strx,stry,strtitle): # plot list1 on x, list2 on y, xlabel, ylabel, title\n from matplotlib import pyplot as plt # import the plotting library from matplotlibplt.show()\n plt.plot( list1, list2, color ='green', marker ='o', linestyle ='solid') # create a line chart, years on x-axis, gdp on y-axis\n plt.title(strtitle)# add a title\n plt.ylabel(stry)# add a label to the x and y-axes\n plt.xlabel(strx)\n plt.show() # display the plot\n return #null return",
"_____no_output_____"
],
[
"# wrapper\nyears = [1950, 1960, 1970, 1980, 1990, 2000, 2010] # define two lists years and gdp\ngdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]\nprint(type(years[0]))\nprint(type(gdp[0]))\nplotAline(years,gdp,\"Year\",\"Billions of $\",\"Nominal GDP\")",
"<class 'int'>\n<class 'float'>\n"
]
],
[
[
"## Example \nUse the plotting script and create a function that draws a straight line between two points.",
"_____no_output_____"
],
[
"```\n def Line():\n from matplotlib import pyplot as plt # import the plotting library from matplotlibplt.show()\n x1 = input('Please enter x value for point 1')\n y1 = input('Please enter y value for point 1')\n x2 = input('Please enter x value for point 2')\n y2 = input('Please enter y value for point 2')\n xlist = [x1,x2]\n ylist = [y1,y2]\n plt.plot( xlist, ylist, color ='orange', marker ='*', linestyle ='solid') \n #plt.title(strtitle)# add a title\n plt.ylabel(\"Y-axis\")# add a label to the x and y-axes\n plt.xlabel(\"X-axis\")\n plt.show() # display the plot\n return #null return\n```",
"_____no_output_____"
],
[
"---\n\n## Laboratory 14\n\n**Examine** (click) Laboratory 15 as a webpage at [Laboratory 14.html](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab14/Lab14.html)\n\n**Download** (right-click, save target as ...) Laboratory 15 as a jupyterlab notebook from [Laboratory 14.ipynb](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab14/Lab14.ipynb)\n",
"_____no_output_____"
],
[
"<hr><hr>\n\n## Exercise Set 14\n\n**Examine** (click) Exercise Set 15 as a webpage at [Exercise 14.html](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab14/Lab14-TH.html)\n\n**Download** (right-click, save target as ...) Exercise Set 15 as a jupyterlab notebook at [Exercise Set 14.ipynb](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab14/Lab14-TH.ipynb)\n\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d0ad2ee3d630dd4acb4d42b5c540adc3fbe202fe | 7,853 | ipynb | Jupyter Notebook | .ipynb_checkpoints/bootstrap-checkpoint.ipynb | VincentYing/Pix2Code-CapsNet | a936a0a4869c5cc4031492e67fb8d855e9a00f2b | [
"MIT"
] | null | null | null | .ipynb_checkpoints/bootstrap-checkpoint.ipynb | VincentYing/Pix2Code-CapsNet | a936a0a4869c5cc4031492e67fb8d855e9a00f2b | [
"MIT"
] | null | null | null | .ipynb_checkpoints/bootstrap-checkpoint.ipynb | VincentYing/Pix2Code-CapsNet | a936a0a4869c5cc4031492e67fb8d855e9a00f2b | [
"MIT"
] | null | null | null | 35.695455 | 134 | 0.589838 | [
[
[
"from os import listdir\nfrom numpy import array\nfrom keras.preprocessing.text import Tokenizer, one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Model, Sequential, model_from_json\nfrom keras.utils import to_categorical\nfrom keras.layers.core import Dense, Dropout, Flatten\nfrom keras.optimizers import RMSprop\nfrom keras.layers.convolutional import Conv2D\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers import Embedding, TimeDistributed, RepeatVector, LSTM, concatenate , Input, Reshape, Dense\nfrom keras.preprocessing.image import array_to_img, img_to_array, load_img\nimport numpy as np",
"Using TensorFlow backend.\n"
],
[
"dir_name = 'resources/eval_light/'\n\n# Read a file and return a string\ndef load_doc(filename):\n file = open(filename, 'r')\n text = file.read()\n file.close()\n return text\n\ndef load_data(data_dir):\n text = []\n images = []\n # Load all the files and order them\n all_filenames = listdir(data_dir)\n all_filenames.sort()\n for filename in (all_filenames):\n if filename[-3:] == \"npz\":\n # Load the images already prepared in arrays\n image = np.load(data_dir+filename)\n images.append(image['features'])\n else:\n # Load the boostrap tokens and rap them in a start and end tag\n syntax = '<START> ' + load_doc(data_dir+filename) + ' <END>'\n # Seperate all the words with a single space\n syntax = ' '.join(syntax.split())\n # Add a space after each comma\n syntax = syntax.replace(',', ' ,')\n text.append(syntax)\n images = np.array(images, dtype=float)\n return images, text\n\ntrain_features, texts = load_data(dir_name)",
"_____no_output_____"
],
[
"# Initialize the function to create the vocabulary \ntokenizer = Tokenizer(filters='', split=\" \", lower=False)\n# Create the vocabulary \ntokenizer.fit_on_texts([load_doc('resources/bootstrap.vocab')])\n\n# Add one spot for the empty word in the vocabulary \nvocab_size = len(tokenizer.word_index) + 1\n# Map the input sentences into the vocabulary indexes\ntrain_sequences = tokenizer.texts_to_sequences(texts)\n# The longest set of boostrap tokens\nmax_sequence = max(len(s) for s in train_sequences)\n# Specify how many tokens to have in each input sentence\nmax_length = 48\n\ndef preprocess_data(sequences, features):\n X, y, image_data = list(), list(), list()\n for img_no, seq in enumerate(sequences):\n for i in range(1, len(seq)):\n # Add the sentence until the current count(i) and add the current count to the output\n in_seq, out_seq = seq[:i], seq[i]\n # Pad all the input token sentences to max_sequence\n in_seq = pad_sequences([in_seq], maxlen=max_sequence)[0]\n # Turn the output into one-hot encoding\n out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]\n # Add the corresponding image to the boostrap token file\n image_data.append(features[img_no])\n # Cap the input sentence to 48 tokens and add it\n X.append(in_seq[-48:])\n y.append(out_seq)\n return np.array(X), np.array(y), np.array(image_data)\n\nX, y, image_data = preprocess_data(train_sequences, train_features)",
"_____no_output_____"
],
[
"#Create the encoder\nimage_model = Sequential()\nimage_model.add(Conv2D(16, (3, 3), padding='valid', activation='relu', input_shape=(256, 256, 3,)))\nimage_model.add(Conv2D(16, (3,3), activation='relu', padding='same', strides=2))\nimage_model.add(Conv2D(32, (3,3), activation='relu', padding='same'))\nimage_model.add(Conv2D(32, (3,3), activation='relu', padding='same', strides=2))\nimage_model.add(Conv2D(64, (3,3), activation='relu', padding='same'))\nimage_model.add(Conv2D(64, (3,3), activation='relu', padding='same', strides=2))\nimage_model.add(Conv2D(128, (3,3), activation='relu', padding='same'))\n\nimage_model.add(Flatten())\nimage_model.add(Dense(1024, activation='relu'))\nimage_model.add(Dropout(0.3))\nimage_model.add(Dense(1024, activation='relu'))\nimage_model.add(Dropout(0.3))\n\nimage_model.add(RepeatVector(max_length))\n\nvisual_input = Input(shape=(256, 256, 3,))\nencoded_image = image_model(visual_input)\n\nlanguage_input = Input(shape=(max_length,))\nlanguage_model = Embedding(vocab_size, 50, input_length=max_length, mask_zero=True)(language_input)\nlanguage_model = LSTM(128, return_sequences=True)(language_model)\nlanguage_model = LSTM(128, return_sequences=True)(language_model)\n\n#Create the decoder\ndecoder = concatenate([encoded_image, language_model])\ndecoder = LSTM(512, return_sequences=True)(decoder)\ndecoder = LSTM(512, return_sequences=False)(decoder)\ndecoder = Dense(vocab_size, activation='softmax')(decoder)\n\n# Compile the model\nmodel = Model(inputs=[visual_input, language_input], outputs=decoder)\noptimizer = RMSprop(lr=0.0001, clipvalue=1.0)\nmodel.compile(loss='categorical_crossentropy', optimizer=optimizer)",
"_____no_output_____"
],
[
"#Save the model for every 2nd epoch\nfilepath=\"org-weights-epoch-{epoch:04d}--val_loss-{val_loss:.4f}--loss-{loss:.4f}.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_weights_only=True, period=2)\ncallbacks_list = [checkpoint]",
"_____no_output_____"
],
[
"# Train the model\nmodel.fit([image_data, X], y, batch_size=1, shuffle=False, validation_split=0.1, callbacks=callbacks_list, verbose=1, epochs=50)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ad2f60fc7337892782435d4bff89f53684613b | 50,647 | ipynb | Jupyter Notebook | Python_Basics/02_Setting_Up.ipynb | eneskemalergin/Data_Science_with_Python | fad3d83925c05da06eb117eeeaf1cc5302a86e8f | [
"MIT"
] | 1 | 2017-08-11T01:33:52.000Z | 2017-08-11T01:33:52.000Z | Python_Basics/02_Setting_Up.ipynb | eneskemalergin/Data_Science_with_Python | fad3d83925c05da06eb117eeeaf1cc5302a86e8f | [
"MIT"
] | null | null | null | Python_Basics/02_Setting_Up.ipynb | eneskemalergin/Data_Science_with_Python | fad3d83925c05da06eb117eeeaf1cc5302a86e8f | [
"MIT"
] | null | null | null | 477.801887 | 47,274 | 0.931506 | [
[
[
"## Setting Up Python Environment\n\nSetting up Python environment consists of 4 main elements\n\n1. Install Python Environment and Necessary Tools\n2. Execute Python Commands\n3. Run Sample Python Program\n4. Install Python Packages\n\nWe will go with Python Anaconda distribution for our course because it has really comprehensive in terms of 3rd party packages and it is really powerful with it's own package manager; ```conda```. \n\nInstalling Anaconda is straightforward: [download](https://www.continuum.io/downloads) the binary and follow the instructions. But careful to install Python 3.6(or later) version.\n\n> If you are asked during the installation process whether you’d like to make Anaconda your default Python installation, say __yes__\n\nthe ```conda``` command is a tool that keep your packages organized and up to date.\n\n### Jupyter Notebook\n\nJupyter notebooks provide a browser-based interface to Python with:\n\n- The ability to write and execute Python commands directly in your browser\n- Formatted output also in the browser, including tables, figures, animation, etc.\n- The ability to mix in formatted text and mathematical expressions between cells\n\n### Let's Start Jupyter Notebook\n\nAfter the installation is complete open your terminal (or for windows users, open the anaconda and select jupyter). In the terminal type ```jupyter notebook```, this will open the jupyter notebook interface and show the current directories' files. \n\n- Notebook is running at http://localhost:8888/ in default\n\nGo ahead and explore the notebook, here are some of the things to explore:\n\n- Open a new File\n- Running Cells\n- Edit Mode\n- Shortcuts",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nN = 20\ntheta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)\nradii = 10 * np.random.rand(N)\nwidth = np.pi / 4 * np.random.rand(N)\n\nax = plt.subplot(111, polar=True)\nbars = ax.bar(theta, radii, width=width, bottom=0.0)\n\n# Use custom colors and opacity\nfor r, bar in zip(radii, bars):\n bar.set_facecolor(plt.cm.jet(r / 10.))\n bar.set_alpha(0.5)\n\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
d0ad3323c3b99107b9ed2acba743ff99361d6fb4 | 18,208 | ipynb | Jupyter Notebook | boards/MicroZed7010/base/notebooks/pmod/pmod_tc1.ipynb | Picarro-SzeMengTan/MicroZed-PYNQ | ba4a8139c54d81d5cd7c200e44f6eaae0076368e | [
"BSD-3-Clause"
] | 4 | 2017-12-12T17:24:49.000Z | 2019-01-21T10:23:29.000Z | boards/MicroZed7010/base/notebooks/pmod/pmod_tc1.ipynb | Picarro-SzeMengTan/MicroZed-PYNQ | ba4a8139c54d81d5cd7c200e44f6eaae0076368e | [
"BSD-3-Clause"
] | null | null | null | boards/MicroZed7010/base/notebooks/pmod/pmod_tc1.ipynb | Picarro-SzeMengTan/MicroZed-PYNQ | ba4a8139c54d81d5cd7c200e44f6eaae0076368e | [
"BSD-3-Clause"
] | 5 | 2018-05-22T06:54:39.000Z | 2020-07-30T12:24:35.000Z | 101.155556 | 13,960 | 0.862753 | [
[
[
"# PMOD TC1 Sensor demonstration\n\nThis demonstration shows how to use the PmodTC1. You will also see how to plot a graph using matplotlib.\n\nThe PmodTC1 is required.\n\nThe thermocouple sensor is initialized and set to log a reading every 1 second. The temperature of the sensor\ncan be changed by touching it with warm fingers or by blowing on it.",
"_____no_output_____"
],
[
"### 1. Use TC1 to read the current temperature\nConnect the TC1 sensor to PMODB.",
"_____no_output_____"
]
],
[
[
"from pynq.overlays.base import BaseOverlay\nbase = BaseOverlay(\"base.bit\")",
"_____no_output_____"
],
[
"from pynq.lib import Pmod_TC1\n\n# TC1 sensor is on PMODB\nmy_tc1 = Pmod_TC1(base.PMODB)\nprint('Raw Register Value: %08x hex' % my_tc1.read_raw())\nprint('Ref Junction Temp: %.4f' % my_tc1.read_junction_temperature())\nprint('Thermocouple Temp: %.2f' % my_tc1.read_thermocouple_temperature())\nprint('Alarm flags: %08x hex' % my_tc1.read_alarm_flags())",
"Raw Register Value: 01981c90 hex\nRef Junction Temp: 28.5625\nThermocouple Temp: 25.50\nAlarm flags: 00000000 hex\n"
]
],
[
[
"### 2. Starting logging temperature once every second\nUsers can use `set_log_interval_ms` to set the time elapsed during 2 samples. By default it is set to 1 second.",
"_____no_output_____"
]
],
[
[
"my_tc1.start_log()",
"_____no_output_____"
]
],
[
[
"### 3. Modifying the temperture\n\n* Touch the thermocouple with warm fingers; or\n* Blow on the thermocouple with cool air\n\nStop the logging whenever you are finished trying to change the sensor's value.",
"_____no_output_____"
]
],
[
[
"my_tc1.stop_log()\nlog = my_tc1.get_log()",
"_____no_output_____"
]
],
[
[
"### 4. Plot values over time",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pynq.lib.pmod.pmod_tc1 import reg_to_tc\nfrom pynq.lib.pmod.pmod_tc1 import reg_to_ref\n\ntc = [reg_to_tc(v) for v in log]\nref = [reg_to_ref(v) for v in log]\n\nplt.plot(range(len(tc)), tc, 'ro', label='Thermocouple')\nplt.plot(range(len(ref)), ref, 'bo', label='Ref Junction')\nplt.title('TC1 Sensor log')\nplt.axis([0, len(log), min(tc+ref)*0.9, max(tc+ref)*1.1])\nplt.legend()\nplt.xlabel('Sample Number')\nplt.ylabel('Temperature (C)')\nplt.grid()\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ad42a5df99d64c4891f1875020427f3e9ad75c | 76,073 | ipynb | Jupyter Notebook | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning | 5dee1bbe0416ec2ca06fa4ebdaf2df50283e42fe | [
"MIT"
] | 3 | 2020-07-30T11:14:33.000Z | 2021-05-12T09:33:59.000Z | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning | 5dee1bbe0416ec2ca06fa4ebdaf2df50283e42fe | [
"MIT"
] | 1 | 2020-08-17T12:02:17.000Z | 2020-08-17T12:02:17.000Z | DC_GAN_Exercise_Solution.ipynb | SoumyadeepB/DeepLearning | 5dee1bbe0416ec2ca06fa4ebdaf2df50283e42fe | [
"MIT"
] | 1 | 2021-05-12T09:34:07.000Z | 2021-05-12T09:34:07.000Z | 72.312738 | 15,634 | 0.749438 | [
[
[
"",
"_____no_output_____"
]
],
[
[
"# **Deep Convolutional Generative Adversarial Network (DC-GAN):**\n\n",
"_____no_output_____"
],
[
"DC-GAN is a foundational adversarial framework developed in 2015. \n\nIt had a major contribution in streamlining the process of designing adversarial frameworks and visualizing intermediate representations, thus, making GANs more accessible to both researchers and practitioners. This was achieved by enhancing the concept of adversarial training (introduced by [Ian Goodfellow](https://arxiv.org/abs/1406.2661) one year prior) with then-state-of-the-art advances in deep learning such as strided and fractional-strided convolutions, batch normalization and LeakyReLU activations.\n\nIn this programming exercise, you are tasking with creating a miniature [Deep Convolutional Generative Adversarial Network](https://arxiv.org/pdf/1511.06434.pdf) (DC-GAN) framework for the generation of MNIST digits. The goal is to bridge the gap between the theoretical concept and the practical implementation of GANs. \n\n\n\nThe desired DC-GAN network should consist of two principal components: the generator $G$ and the discriminator $D$. The generator should receive as input a 100-dimensional random noise vector $z$ and outputs a synthetically generated MNIST digit $G(z)$ of pixel size $28 \\times 28 \\times 1$. As the adversarial training continues over time, the output digits should increasingly resemble handwritten digits as shown below.\n\n\n\nThe discriminator network receives both the synthetically generated digits as well as ground-truth MNIST digits $x$ as inputs. $D$ is trained as a binary classifier. In other words, it is trained to assign the correct label (real vs fake) to both sets of input images. On the other hand side, $G$ is motivated to fool the discriminator into making a false decision by implicitly improving the quality of the output synthetic image. This adversarial training procedure, where both networks are trained with opposing goals, is represented by the following min-max optimization task:\n\n>$\\underset{G}{\\min} \\underset{D}{\\max} \\mathcal{L}_{\\textrm{adv}} =\\underset{G}{\\min} \\underset{D}{\\max} \\; \\mathbb{E}_{x} \\left[\\textrm{log} D(x) \\right] + \\mathbb{E}_{z} \\left[\\textrm{log} \\left( 1 - D\\left(G(z)\\right) \\right) \\right]$",
"_____no_output_____"
],
[
"# Implementation\n\n",
"_____no_output_____"
],
[
"### Import Import TensorFlow and other libraries\n\n\n\n",
"_____no_output_____"
]
],
[
[
"from __future__ import absolute_import, division, print_function, unicode_literals",
"_____no_output_____"
],
[
"!pip install tensorflow-gpu==2.0.0-alpha0\n",
"Collecting tensorflow-gpu==2.0.0-alpha0\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/1a/66/32cffad095253219d53f6b6c2a436637bbe45ac4e7be0244557210dc3918/tensorflow_gpu-2.0.0a0-cp36-cp36m-manylinux1_x86_64.whl (332.1MB)\n\u001b[K |████████████████████████████████| 332.1MB 63kB/s \n\u001b[?25hRequirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (1.0.9)\nRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (0.7.1)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (1.12.0)\nRequirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (3.7.1)\nRequirement already satisfied: numpy<2.0,>=1.14.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (1.16.4)\nRequirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (0.8.0)\nCollecting tf-estimator-nightly<1.14.0.dev2019030116,>=1.14.0.dev2019030115 (from tensorflow-gpu==2.0.0-alpha0)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/13/82/f16063b4eed210dc2ab057930ac1da4fbe1e91b7b051a6c8370b401e6ae7/tf_estimator_nightly-1.14.0.dev2019030115-py2.py3-none-any.whl (411kB)\n\u001b[K |████████████████████████████████| 419kB 47.2MB/s \n\u001b[?25hRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (1.1.0)\nRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (1.15.0)\nRequirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (1.0.7)\nCollecting tb-nightly<1.14.0a20190302,>=1.14.0a20190301 (from tensorflow-gpu==2.0.0-alpha0)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/a9/51/aa1d756644bf4624c03844115e4ac4058eff77acd786b26315f051a4b195/tb_nightly-1.14.0a20190301-py3-none-any.whl (3.0MB)\n\u001b[K |████████████████████████████████| 3.0MB 35.1MB/s \n\u001b[?25hRequirement already satisfied: gast>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (0.2.2)\nRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow-gpu==2.0.0-alpha0) (0.33.4)\nCollecting google-pasta>=0.1.2 (from tensorflow-gpu==2.0.0-alpha0)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/d0/33/376510eb8d6246f3c30545f416b2263eee461e40940c2a4413c711bdf62d/google_pasta-0.1.7-py3-none-any.whl (52kB)\n\u001b[K |████████████████████████████████| 61kB 9.3MB/s \n\u001b[?25hRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tensorflow-gpu==2.0.0-alpha0) (41.0.1)\nRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.6->tensorflow-gpu==2.0.0-alpha0) (2.8.0)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.14.0a20190302,>=1.14.0a20190301->tensorflow-gpu==2.0.0-alpha0) (3.1.1)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.14.0a20190302,>=1.14.0a20190301->tensorflow-gpu==2.0.0-alpha0) (0.15.4)\nInstalling collected packages: tf-estimator-nightly, tb-nightly, google-pasta, tensorflow-gpu\nSuccessfully installed google-pasta-0.1.7 tb-nightly-1.14.0a20190301 tensorflow-gpu-2.0.0a0 tf-estimator-nightly-1.14.0.dev2019030115\n"
],
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"tf.__version__\n",
"_____no_output_____"
],
[
"# To generate GIFs for illustration\n!pip install imageio",
"Requirement already satisfied: imageio in /usr/local/lib/python3.6/dist-packages (2.4.1)\nRequirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from imageio) (4.3.0)\nRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from imageio) (1.16.4)\nRequirement already satisfied: olefile in /usr/local/lib/python3.6/dist-packages (from pillow->imageio) (0.46)\n"
],
[
"import glob\nimport imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport PIL\nfrom tensorflow.keras import layers\nimport time\n\nfrom IPython import display",
"_____no_output_____"
]
],
[
[
"### Load and prepare the dataset\n\nYou will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data.\n\nYou can also repeat the exercise for other avaliable variations of the MNIST dataset such as: EMNIST, Fashio-MNIST or KMNIST. For more details, please refer to [tensorflow_datasets](https://www.tensorflow.org/datasets/datasets).\n",
"_____no_output_____"
]
],
[
[
"(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()",
"Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n11493376/11490434 [==============================] - 0s 0us/step\n"
],
[
"train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')\ntrain_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]",
"_____no_output_____"
],
[
"BUFFER_SIZE = 60000\nBATCH_SIZE = 256",
"_____no_output_____"
],
[
"# Batch and shuffle the data\ntrain_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)",
"_____no_output_____"
]
],
[
[
"## Create the models\n\nBoth the generator and discriminator are defined using the [Keras Sequential API](https://www.tensorflow.org/guide/keras#sequential_model).",
"_____no_output_____"
],
[
"### The Generator\n\nThe generator uses `tf.keras.layers.Conv2DTranspose` (fractional-strided convolutional) layers to produce an image from an input noise vector. Start with a fully connected layer that takes this vector as input, then upsample several times until you reach the desired image size of $28\\times 28 \\times 1$. Utilize the `tf.keras.layers.LeakyReLU` activation and batch normalization for each intermediate layer, except the output layer which should use tanh.",
"_____no_output_____"
]
],
[
[
"def make_generator_model():\n model = tf.keras.Sequential()\n model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n \n model.add(layers.Reshape((7, 7, 256)))\n assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size\n \n # Layer 2: Hint use layers.Conv2DTranspose with 5x5 kernels and appropriate stride\n \n model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))\n assert model.output_shape == (None, 7, 7, 128)\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n # Layer 3\n \n model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))\n assert model.output_shape == (None, 14, 14, 64)\n model.add(layers.BatchNormalization())\n model.add(layers.LeakyReLU())\n\n #Layer4\n \n model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))\n assert model.output_shape == (None, 28, 28, 1)\n\n return model",
"_____no_output_____"
]
],
[
[
"Use the (as yet untrained) generator to create an image.",
"_____no_output_____"
]
],
[
[
"generator = make_generator_model()\n\nnoise = tf.random.normal([1, 100])\ngenerated_image = generator(noise, training=False)\n\nplt.imshow(generated_image[0, :, :, 0], cmap='gray')",
"_____no_output_____"
]
],
[
[
"### The Discriminator\n\nThe discriminator is a CNN-based image classifier.",
"_____no_output_____"
]
],
[
[
"def make_discriminator_model():\n model = tf.keras.Sequential()\n model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',\n input_shape=[28, 28, 1]))\n model.add(layers.LeakyReLU())\n model.add(layers.Dropout(0.3))\n\n model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))\n model.add(layers.LeakyReLU())\n model.add(layers.Dropout(0.3))\n\n model.add(layers.Flatten())\n model.add(layers.Dense(1))\n\n return model",
"_____no_output_____"
]
],
[
[
"Use the (as yet untrained) discriminator to classify the generated images as real or fake. The model will be trained to output positive values for real images, and negative values for fake images.",
"_____no_output_____"
]
],
[
[
"discriminator = make_discriminator_model()\ndecision = discriminator(generated_image)\nprint (decision)",
"tf.Tensor([[0.00197769]], shape=(1, 1), dtype=float32)\n"
]
],
[
[
"## Define the loss and optimizers\n\nDefine loss functions and optimizers for both models.\n",
"_____no_output_____"
]
],
[
[
"# This method returns a helper function to compute the binary cross entropy loss\ncross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)",
"_____no_output_____"
]
],
[
[
"### Discriminator loss\n\nDefine the discriminator loss function. [Hint](https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy): compare the discriminator's predictions on real images to an array of 1s.",
"_____no_output_____"
]
],
[
[
"def discriminator_loss(real_output, fake_output):\n real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n total_loss = real_loss + fake_loss\n return total_loss",
"_____no_output_____"
]
],
[
[
"### Generator loss\nThe generator's loss quantifies how well it was able to trick the discriminator. Intuitively, if the generator is performing well, the discriminator will classify the fake images as real (or 1). Again, use the same principle used to define the real_loss to define the generator_loss.",
"_____no_output_____"
]
],
[
[
"def generator_loss(fake_output):\n generator_loss = cross_entropy(tf.ones_like(fake_output), fake_output)\n return generator_loss",
"_____no_output_____"
]
],
[
[
"The discriminator and the generator optimizers are different since both networks are trained separately. Hint: use Adam optimizers. Experiment with the learning rates.",
"_____no_output_____"
]
],
[
[
"generator_optimizer = tf.keras.optimizers.Adam(1e-4)\ndiscriminator_optimizer = tf.keras.optimizers.Adam(1e-4)",
"_____no_output_____"
]
],
[
[
"### Save checkpoints\nThis notebook also demonstrates how to save and restore models, which can be helpful in case a long running training task is interrupted (especially for larger datasets).",
"_____no_output_____"
]
],
[
[
"checkpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n discriminator_optimizer=discriminator_optimizer,\n generator=generator,\n discriminator=discriminator)",
"_____no_output_____"
]
],
[
[
"## Define the training loop",
"_____no_output_____"
]
],
[
[
"EPOCHS = 100\nnoise_dim = 100\nnum_examples_to_generate = 16 # For visualization\n\n# We will reuse this noise_vector overtime (so it's easier)\n# to visualize progress in the animated GIF)\nnoise_vector = tf.random.normal([num_examples_to_generate, noise_dim])",
"_____no_output_____"
]
],
[
[
"The training loop should begin with generator receiving a random vector as input. That vector will be used to produce an image. The discriminator should then be used to classify real images (drawn from the training set) and fakes images (produced by the generator). The loss will be calculated for each of these models, and the gradients used to update the generator and discriminator",
"_____no_output_____"
]
],
[
[
"# Notice the use of `tf.function`\n# This annotation causes the function to be \"compiled\".\[email protected]\ndef train_step(images):\n noise = tf.random.normal([BATCH_SIZE, noise_dim])\n\n with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n # Generator output\n generated_images = generator(noise, training=True)\n \n # Discriminator output\n real_output = discriminator(images, training=True)\n fake_output = discriminator(generated_images, training=True) \n \n # Loss functions\n gen_loss = generator_loss(fake_output)\n disc_loss = discriminator_loss(real_output, fake_output)\n \n # Gradients\n gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)\n gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)\n\n # Update both networks\n generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))\n discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))",
"_____no_output_____"
],
[
"def train(dataset, epochs):\n for epoch in range(epochs):\n start = time.time()\n\n for image_batch in dataset:\n train_step(image_batch)\n\n # Produce images for the GIF as we go\n display.clear_output(wait=True)\n generate_and_save_images(generator,\n epoch + 1,\n noise_vector)\n\n # Save the model every 15 epochs\n if (epoch + 1) % 15 == 0:\n checkpoint.save(file_prefix = checkpoint_prefix)\n\n print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))\n\n # Generate after the final epoch\n display.clear_output(wait=True)\n generate_and_save_images(generator,\n epochs,\n noise_vector)",
"_____no_output_____"
]
],
[
[
"**Generate and save images**",
"_____no_output_____"
]
],
[
[
"def generate_and_save_images(model, epoch, test_input):\n # Notice `training` is set to False.\n # This is so all layers run in inference mode (batchnorm).\n predictions = model(test_input, training=False)\n\n fig = plt.figure(figsize=(4,4))\n\n for i in range(predictions.shape[0]):\n plt.subplot(4, 4, i+1)\n plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n plt.axis('off')\n\n plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))\n plt.show()",
"_____no_output_____"
]
],
[
[
"## Train the model\nCall the `train()` method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).\n\nAt the beginning of the training, the generated images look like random noise. As training progresses, the generated digits will look increasingly real. After about 50 epochs, they resemble MNIST digits. This may take about one minute / epoch with the default settings on Colab.",
"_____no_output_____"
]
],
[
[
"%%time\ntrain(train_dataset, EPOCHS)",
"_____no_output_____"
]
],
[
[
"Restore the latest checkpoint.",
"_____no_output_____"
]
],
[
[
"checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))",
"_____no_output_____"
]
],
[
[
"## Create a GIF",
"_____no_output_____"
]
],
[
[
"# Display a single image using the epoch number\ndef display_image(epoch_no):\n return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))",
"_____no_output_____"
],
[
"display_image(EPOCHS)",
"_____no_output_____"
]
],
[
[
"Use imageio to create an animated gif using the images saved during training.",
"_____no_output_____"
]
],
[
[
"anim_file = 'dcgan.gif'\n\nwith imageio.get_writer(anim_file, mode='I') as writer:\n filenames = glob.glob('image*.png')\n filenames = sorted(filenames)\n last = -1\n for i,filename in enumerate(filenames):\n frame = 8*(i**0.25)\n if round(frame) > round(last):\n last = frame\n else:\n continue\n image = imageio.imread(filename)\n writer.append_data(image)\n image = imageio.imread(filename)\n writer.append_data(image)\n\nimport IPython\nif IPython.version_info > (6,2,0,''):\n display.Image(filename=anim_file)",
"_____no_output_____"
]
],
[
[
"If you're working in Colab you can download the animation with the code below:",
"_____no_output_____"
]
],
[
[
"try:\n from google.colab import files\nexcept ImportError:\n pass\nelse:\n files.download(anim_file)",
"_____no_output_____"
]
],
[
[
"## Next Steps",
"_____no_output_____"
],
[
"How does the generated digits compare with the original MNIST? Optimize the network design and training hyperparameters further for better results.\n\nRepeat the above steps for other similar datasets such as Fashion-MNIST or expand the capacities of the network appropriately to suit larger datasets such as the Large-scale Celeb Faces Attributes (CelebA) dataset. ",
"_____no_output_____"
]
]
] | [
"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"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
d0ad518574562dbb2d318bfe2c739d0e9100b91c | 14,178 | ipynb | Jupyter Notebook | notebooks/xcpp.ipynb | wolfv/xeus-cling | f5dd885b696d3dced48c00044c189316bfe5b958 | [
"BSD-3-Clause"
] | 3 | 2018-04-16T10:12:11.000Z | 2019-03-14T06:47:00.000Z | notebooks/xcpp.ipynb | wolfv/xeus-cling | f5dd885b696d3dced48c00044c189316bfe5b958 | [
"BSD-3-Clause"
] | null | null | null | notebooks/xcpp.ipynb | wolfv/xeus-cling | f5dd885b696d3dced48c00044c189316bfe5b958 | [
"BSD-3-Clause"
] | 1 | 2019-11-16T17:14:27.000Z | 2019-11-16T17:14:27.000Z | 22.153125 | 208 | 0.450063 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
d0ad686241454228f19376bfdc2b314e0569a3f0 | 5,952 | ipynb | Jupyter Notebook | notebooks/code_equivalence.ipynb | code-gen/exploration | c83d79745df9566c5f1a82e581008e0984fcc319 | [
"MIT"
] | null | null | null | notebooks/code_equivalence.ipynb | code-gen/exploration | c83d79745df9566c5f1a82e581008e0984fcc319 | [
"MIT"
] | 1 | 2019-05-11T14:49:58.000Z | 2019-05-24T15:02:54.000Z | notebooks/code_equivalence.ipynb | code-gen/data-exploration | c83d79745df9566c5f1a82e581008e0984fcc319 | [
"MIT"
] | null | null | null | 25.008403 | 100 | 0.445397 | [
[
[
"## Code Equivalence",
"_____no_output_____"
]
],
[
[
"import ast\nimport astpretty\nimport showast\nimport sys\nimport re\n\nsys.path.insert(0, '../preprocess/')\nsys.path.insert(0, '../../coarse2fine.git/src')\n\nfrom sketch_generation import Sketch\nfrom tree import SketchRepresentation\nimport table",
"_____no_output_____"
],
[
"SKP_WORD = '<sk>'\nRIG_WORD = '<]>'\nLFT_WORD = '<[>'\n\ndef is_code_eq(tokens1, tokens2, not_layout=False):\n\n if isinstance(tokens1, SketchRepresentation):\n tokens1 = str(tokens1)\n else:\n tokens1 = ' '.join(tokens1)\n\n if isinstance(tokens2, SketchRepresentation):\n tokens2 = str(tokens2)\n else:\n tokens2 = ' '.join(tokens2)\n\n tokens1 = ['\\\"' if it in (RIG_WORD, LFT_WORD) else it for it in tokens1.split(' ')]\n tokens2 = ['\\\"' if it in (RIG_WORD, LFT_WORD) else it for it in tokens2.split(' ')]\n\n if len(tokens1) != len(tokens2):\n return False\n\n return all(map(lambda tk1, tk2: tk1 == tk2, tokens1, tokens2))",
"_____no_output_____"
],
[
"# AST => Node Type [AST]\nclass Node:\n def __init__(self, val, *kids):\n self.val = val\n self.kids = kids\n \n def __str__(self):\n return Node.to_string(self, indent=2, c=' ')\n\n def __repr__(self):\n return str(self)\n \n @staticmethod\n def val_to_string(val):\n if len(val) == 1:\n n, f = val[0]\n if n == 'body':\n f = f[0]\n s = \"%s: %s\\n\" % (n, f.__class__.__name__)\n else:\n s = ', '.join(['%s: %s' % (n, f.__class__.__name__) for n, f in val]) + \"\\n\"\n \n return s\n \n @staticmethod\n def to_string(node, indent=2, c=' '): \n if node.val == []:\n return '' \n\n s = Node.val_to_string(node.val)\n\n for k in node.kids:\n _s = Node.to_string(k, indent*2)\n if _s != '':\n s += (c * indent) + _s\n\n return s\n \nclass Nil(Node):\n def __init__(self):\n self.val = None\n self.kids = []\n \n def __str__(self):\n return \"x\"\n \n def __repr__(self):\n return str(self)\n \nclass Leaf(Node):\n def __init__(self, val):\n self.val = val\n self.kids = []\n \n def __str__(self):\n return '%d' % self.val\n \n def __repr__(self):\n return str(self)\n \n# TODO\n \ndef cons_tree(t):\n val = list(ast.iter_fields(t))\n kids = list(ast.iter_child_nodes(t))\n \n return Node(val, *[cons_tree(k) for k in kids])\n\ndef zip_tree_pred(pred, t1, t2): \n zs = [pred(t1.val, t2.val)]\n \n for k1, k2 in zip(t1.kids, t2.kids):\n zs.append(zip_tree_pred(pred, k1, k2))\n \n return all(zs)",
"_____no_output_____"
],
[
"code1 = '[x for x in range(10)]'\ncode2 = '[i for i in [1,2,3]]'\n\ntree1 = ast.parse(code1)\ntree2 = ast.parse(code2)\n\nt1 = cons_tree(tree1)\nt2 = cons_tree(tree2)\n\ndef cmp_func(x, y):\n s1 = Node.val_to_string(x)\n s2 = Node.val_to_string(y)\n return s1 == s2\n \nzip_tree_pred(cmp_func, t1, t2)",
"_____no_output_____"
],
[
"%%showast\nx = self.func(1, 'test', var)",
"_____no_output_____"
],
[
"%%showast\nraise RuntimeError('[%s]' % self.get_err_msg(timestamp[:2]))\n\n# tree = Node(Assign, [Attribute(Name(self), var), Name(x)])",
"_____no_output_____"
],
[
"# astpretty.pprint(tree1.body[0], indent=' ' * 4)\nastpretty.pprint(tree2.body[0], indent=' ' * 4)",
"_____no_output_____"
]
],
[
[
"## Eval framework",
"_____no_output_____"
]
],
[
[
"## TODO",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ad7157ec9723849ac25e8d82f6b8e7ca517da5 | 241,622 | ipynb | Jupyter Notebook | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization | 1660320069a3b9d6872ec32f4ec1e38d6e10e81f | [
"MIT"
] | null | null | null | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization | 1660320069a3b9d6872ec32f4ec1e38d6e10e81f | [
"MIT"
] | null | null | null | 1. Machine Learning Foundations/Week 3/Analyzing Product Sentiment/Analyzing_product_sentiment_ScikitLearn.ipynb | Abdelrahman350/Machine-Learning-Specialization | 1660320069a3b9d6872ec32f4ec1e38d6e10e81f | [
"MIT"
] | null | null | null | 102.686783 | 28,796 | 0.78384 | [
[
[
"# Import Scikit Learn, Pandas and Numpy",
"_____no_output_____"
]
],
[
[
"import sklearn\nimport numpy as np\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"# 1. Read the Dataset using Pandas",
"_____no_output_____"
]
],
[
[
"data = pd.read_csv(\"data/amazon_baby.csv\")",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
]
],
[
[
"# 2. Exploratory Data Analysis",
"_____no_output_____"
]
],
[
[
"data.head()",
"_____no_output_____"
],
[
"data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 183531 entries, 0 to 183530\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 name 183213 non-null object\n 1 review 182702 non-null object\n 2 rating 183531 non-null int64 \ndtypes: int64(1), object(2)\nmemory usage: 4.2+ MB\n"
]
],
[
[
"### The first observation is that we have cells with null review and they have rating. Those rows which contain those cells should be dropped from the data as they will confuse the model by acting like noise.",
"_____no_output_____"
]
],
[
[
"data.describe()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nfig = sns.countplot(x='rating', data=data)",
"_____no_output_____"
]
],
[
[
"### The second observation is that we have imbalanced classes in our Data. At this project we will just use different metrics to measure model performance besides accuracy like recall, $F_{1}$ score and ROC.",
"_____no_output_____"
],
[
"# 3. Data Preprocessing\n### Drop null rows using DataFrame.dropna()",
"_____no_output_____"
]
],
[
[
"data.dropna(inplace=True)\ndata.reset_index(drop=True, inplace=True)\ndata.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 182384 entries, 0 to 182383\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 name 182384 non-null object\n 1 review 182384 non-null object\n 2 rating 182384 non-null int64 \ndtypes: int64(1), object(2)\nmemory usage: 4.2+ MB\n"
]
],
[
[
"### Ignore the three stars ratings.\n\nBecause they are neutral, and dropp those rows with neutral reviews.\nThis step is done before building the word count vector to save memory space and computational power by not getting the word count vector for those neutral reviews.",
"_____no_output_____"
]
],
[
[
"data = data[data['rating'] != 3]\ndata.reset_index(drop=True, inplace=True)",
"_____no_output_____"
],
[
"data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 165679 entries, 0 to 165678\nData columns (total 3 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 name 165679 non-null object\n 1 review 165679 non-null object\n 2 rating 165679 non-null int64 \ndtypes: int64(1), object(2)\nmemory usage: 3.8+ MB\n"
]
],
[
[
"### Build word count vectors",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np \nfrom sklearn.feature_extraction.text import CountVectorizer\n\ndef dictionarize(row):\n cv = CountVectorizer(\n analyzer = \"word\", \n token_pattern = '[a-zA-Z0-9$&+:;=?@#|<>.^*()%!]+'\n )\n text = [row.loc['review']]\n cv_fit=cv.fit_transform(text) \n word_list = cv.get_feature_names()\n count_list = cv_fit.toarray().sum(axis=0)\n dictionary = dict(zip(word_list,count_list))\n row['word_count'] = dictionary\n return row\n\ndata = data.apply(dictionarize, axis=1)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"data = data.assign(sentiment = (data['rating'] >= 4).astype(int))\ndata.head()",
"_____no_output_____"
],
[
"fig = sns.countplot(x='sentiment', data=data)",
"_____no_output_____"
]
],
[
[
"# 4. Train-Test Split",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(data, test_size=0.2, random_state=42)",
"_____no_output_____"
]
],
[
[
"# 5. Logistic Regression Pipeline",
"_____no_output_____"
]
],
[
[
"from sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer\n\nsentiment_pipeline = Pipeline(\n [\n ('Count_Vectorizer', CountVectorizer()),\n ('TF-IDF', TfidfTransformer()),\n ('Logistic_Regression', LogisticRegression(solver='lbfgs', max_iter=1000, class_weight='dict'))\n ],\n verbose=True\n)\n\nfrom sklearn import set_config\nset_config(display='diagram')\nsentiment_pipeline",
"_____no_output_____"
]
],
[
[
"# 6. Pipeline Training",
"_____no_output_____"
]
],
[
[
"sentiment_pipeline.fit(train_set['review'], train_set['sentiment'])",
"[Pipeline] .. (step 1 of 3) Processing Count_Vectorizer, total= 10.9s\n[Pipeline] ............ (step 2 of 3) Processing TF-IDF, total= 1.2s\n[Pipeline] (step 3 of 3) Processing Logistic_Regression, total= 19.2s\n"
]
],
[
[
"### Plot Learning Curves",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import learning_curve\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):\n \"\"\"\n Generate a simple plot of the test and traning learning curve.\n\n Parameters\n ----------\n estimator : object type that implements the \"fit\" and \"predict\" methods\n An object of that type which is cloned for each validation.\n\n title : string\n Title for the chart.\n\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n ylim : tuple, shape (ymin, ymax), optional\n Defines minimum and maximum yvalues plotted.\n\n cv : integer, cross-validation generator, optional\n If an integer is passed, it is the number of folds (defaults to 3).\n Specific cross-validation objects can be passed, see\n sklearn.cross_validation module for the list of possible objects\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n \"\"\"\n estimator.verbose = False\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n estimator.verbose = True\n return plt",
"_____no_output_____"
]
],
[
[
"# 7. Metrics",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import classification_report\n\ny_pred = sentiment_pipeline.predict(test_set['review'])\nprint('Classification report:\\n\\n{}'.format(\n classification_report(test_set['sentiment'], y_pred))\n)",
"Classification report:\n\n precision recall f1-score support\n\n 0 0.87 0.71 0.78 5338\n 1 0.95 0.98 0.96 27798\n\n accuracy 0.94 33136\n macro avg 0.91 0.84 0.87 33136\nweighted avg 0.93 0.94 0.93 33136\n\n"
],
[
"plot_learning_curve(sentiment_pipeline\\\n , 'Pipeline Learning Curves', train_set['review'], train_set['sentiment'])",
"_____no_output_____"
],
[
"from sklearn.metrics import plot_precision_recall_curve, plot_roc_curve\nfrom sklearn.metrics import average_precision_score\n\naverage_precision = average_precision_score(test_set['sentiment'], y_pred)\ndisp = plot_precision_recall_curve(sentiment_pipeline, test_set['review'], test_set['sentiment'])\n\ndisp.ax_.set_title('Two-class Precision-Recall curve')",
"_____no_output_____"
],
[
"disp = plot_roc_curve(sentiment_pipeline, test_set['review'], test_set['sentiment'])\ndisp.ax_.set_title('Two-class ROC curve')",
"_____no_output_____"
],
[
"from sklearn.metrics import accuracy_score\ny_pred_selected_words = sentiment_pipeline.predict(test_set['review'])\ny_true_selected_words = test_set['sentiment']\naccuracy_score(y_true_selected_words, y_pred_selected_words)\nprint('The accuracy of the sentiment_pipeline is',accuracy_score(y_true_selected_words, y_pred_selected_words))",
"The accuracy of the sentiment_pipeline is 0.9352064220183486\n"
]
],
[
[
"# Assignment\n## 1. Use .apply() to build a new feature with the counts for each of the selected_words.",
"_____no_output_____"
]
],
[
[
"selected_words = ['awesome', 'great', 'fantastic', 'amazing',\\\n 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']",
"_____no_output_____"
],
[
"def dictionary_count(row):\n count_list = []\n for word in selected_words:\n count_list.append(row['word_count'].get(word, 0))\n dictionary = dict(zip(selected_words, count_list))\n row['selected_words'] = dictionary\n return row\n\ndata = data.apply(dictionary_count, axis=1)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"from collections import Counter\n\ncounts = sum(map(Counter, data['selected_words']), Counter())\nresults = pd.DataFrame.from_dict(counts, orient='index', columns=['Sums'])\\\n .sort_values(by=['Sums'], ascending=False)",
"_____no_output_____"
],
[
"results",
"_____no_output_____"
]
],
[
[
"## 2. Create a new sentiment analysis model using only the selected_words as features",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.preprocessing import Normalizer\n\nselected_words_pipeline = Pipeline(\n [\n ('Dictionary_Vectorizer', DictVectorizer(sparse=False, sort=False)),\n ('Scaler', StandardScaler()),\n ('Logistic_Regression', LogisticRegression(solver='lbfgs', max_iter=1000, class_weight='dict'))\n ],\n verbose=True\n)\n\nfrom sklearn import set_config\nset_config(display='diagram')\nselected_words_pipeline",
"_____no_output_____"
]
],
[
[
"### Train-Test split",
"_____no_output_____"
]
],
[
[
"train_set, test_set = train_test_split(data, test_size=0.2, random_state=15)",
"_____no_output_____"
]
],
[
[
"### Training the selected_words_pipeline",
"_____no_output_____"
]
],
[
[
"selected_words_pipeline.fit(train_set['selected_words'], train_set['sentiment'])",
"[Pipeline] (step 1 of 3) Processing Dictionary_Vectorizer, total= 1.8s\n[Pipeline] ............ (step 2 of 3) Processing Scaler, total= 0.0s\n[Pipeline] (step 3 of 3) Processing Logistic_Regression, total= 0.3s\n"
]
],
[
[
"### selected_words_pipeline Metrics",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import classification_report\n\ny_pred = selected_words_pipeline.predict(test_set['selected_words'])\nprint('Classification report:\\n\\n{}'.format(\n classification_report(test_set['sentiment'], y_pred))\n)",
"Classification report:\n\n precision recall f1-score support\n\n 0 0.63 0.05 0.09 5292\n 1 0.85 0.99 0.91 27844\n\n accuracy 0.84 33136\n macro avg 0.74 0.52 0.50 33136\nweighted avg 0.81 0.84 0.78 33136\n\n"
],
[
"disp = plot_learning_curve(selected_words_pipeline, 'selected_words_pipeline Learning Curves', \\\n train_set['selected_words'], train_set['sentiment'])",
"_____no_output_____"
],
[
"average_precision = average_precision_score(test_set['sentiment'], y_pred)\ndisp = plot_precision_recall_curve(selected_words_pipeline, test_set['selected_words'], test_set['sentiment'])\n\ndisp.ax_.set_title('Two-class Precision-Recall curve')",
"_____no_output_____"
],
[
"disp = plot_roc_curve(selected_words_pipeline, test_set['selected_words'], test_set['sentiment'])\ndisp.ax_.set_title('Two-class POC curve')",
"_____no_output_____"
],
[
"weights = dict(zip(selected_words, selected_words_pipeline['Logistic_Regression'].coef_[0]))\nsorted_weights = pd.DataFrame.from_dict(weights, orient='index', columns=['Weights'])\\\n .sort_values(by=['Weights'], ascending=False)\nsorted_weights",
"_____no_output_____"
]
],
[
[
"## 3. Comparing the accuracy of different sentiment analysis models: Using .predict()\n\nIn this task the accuracy of the sentiment_pipeline, selected_words_pipeline and majority_class. The first one has been calculated above.",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import accuracy_score\ny_pred_selected_words = selected_words_pipeline.predict(test_set['selected_words'])\ny_true_selected_words = test_set['sentiment']\naccuracy_score(y_true_selected_words, y_pred_selected_words)\nprint('The accuracy of the selected_words_pipeline is', \n accuracy_score(y_true_selected_words, y_pred_selected_words))",
"The accuracy of the selected_words_pipeline is 0.8434633027522935\n"
],
[
"majority_class = float(test_set[test_set['sentiment'] == 1].shape[0] / test_set.shape[0])\nmajority_class",
"_____no_output_____"
]
],
[
[
"## 4. Interpreting the difference in performance between the models",
"_____no_output_____"
]
],
[
[
"diaper_champ_reviews = data.loc[data['name']=='Baby Trend Diaper Champ',\\\n ['review', 'selected_words', 'sentiment']]\ndiaper_champ_reviews",
"_____no_output_____"
],
[
"diaper_champ_reviews['predicted_sentiment'] = \\\n sentiment_pipeline.predict_proba(diaper_champ_reviews['review'])[:, 1].tolist()\ndiaper_champ_reviews",
"_____no_output_____"
],
[
"diaper_champ_reviews = diaper_champ_reviews.sort_values(by=['predicted_sentiment'], ascending=False)\ndiaper_champ_reviews.head()",
"_____no_output_____"
],
[
"diaper_champ_reviews['predicted_selected_word'] = \\\n selected_words_pipeline\\\n .predict_proba(diaper_champ_reviews['selected_words'])[:, 1].tolist()\ndiaper_champ_reviews.iloc[1]",
"_____no_output_____"
],
[
"diaper_champ_reviews.iloc[1]['review']",
"_____no_output_____"
],
[
"diaper_champ_reviews.iloc[1]['selected_words']",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ad7ceab923c198077337d18b800ed646b47c90 | 10,729 | ipynb | Jupyter Notebook | MCPC-Rehearsal-E.ipynb | ShinjiKatoA16/mcpc2017ucsy | 7f6fbfbb2b05a34c58d30519874b4ca5d0232b94 | [
"MIT"
] | null | null | null | MCPC-Rehearsal-E.ipynb | ShinjiKatoA16/mcpc2017ucsy | 7f6fbfbb2b05a34c58d30519874b4ca5d0232b94 | [
"MIT"
] | null | null | null | MCPC-Rehearsal-E.ipynb | ShinjiKatoA16/mcpc2017ucsy | 7f6fbfbb2b05a34c58d30519874b4ca5d0232b94 | [
"MIT"
] | null | null | null | 29.969274 | 342 | 0.500885 | [
[
[
"%autosave 0",
"_____no_output_____"
]
],
[
[
"# MCPC rehearsal problem Oct 25 2017 at UCSY\n\n## Problem E: Stacking Plates\n\n### Input format\n\n- 1st Line: 1 integer, Number of Test Case, each Test Case has following data\n + 1 Line: 1 integer, **n**(Number of Stacks)\n + **n** Lines: first integer: **h** (Number of Plates), and **h** integers (Plate size)\n \n\n### Output format\n\nCase: (test case number): Number of Operations\n\n\n### Sample Input\n\n```\n3\n2\n3 1 2 4\n2 3 5\n3\n4 1 1 1 1\n4 1 1 1 1\n4 1 1 1 1\n2\n15 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3\n15 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3\n```\n\n\n### Sample Output\n\n```\nCase 1:5\nCase 2:2\nCase 3:5\n```\n\n### Explanation of sample I/O\n\n- 3 test cases\n + Stack of (1,2,4) and (3,5)\n + Stack of 3 (1,1,1,1)\n + Stack of 2 (1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)\n \n- 1st case:\nSplit between 2 and 4, 3 and 5, Move 4 on 5, 3 on 4, (1,2) on 3 ==> Total 5 operations\n\n- 2nd case:\nMove 1st stack (1,1,1,1,1) on 2nd stack, move (1st+2nd stack) on 3rd stack ==> Total 2 operations\n\n- 3rd case:\nSplit between 1 and 2 of 1st stack, between 2 and 3 of 2nd stack, move (2,2,2,2,2,3,3,3,3,3) of 1st stack on (3,3,3,3,3) of 2nd, move (1,1,1,1,1,2,2,2,2,2) of 2nd stack on it, move (1,1,1,1,1) on top ==> Total 5 operations",
"_____no_output_____"
],
[
"### Specific vs Abstract, Find a General Rule from Detail\n\nWhen solving problems and puzzles that you can not find how to solve, thinking specificlly then abstractly is important. Finding general rules from specific examples give you a path to the answer.\n\n- Think about simple cases\n- Find general pattern (idea, rule) from there\n- Proove the rule (if possible)\n- Extend the rule to more complex cases",
"_____no_output_____"
],
[
"### How to calculate number of operation(movement)\n\nIf there are N stacks and each contains just 1 piece (Split is not necessary), (N-1) operations are reuired. (N-1) is a minimum number of oprations.\n\nFor each Split operation, Join operation is required to create single stack. Total number of operation increases by 2 for each Split operations (S). The order of Split and Join does not affect total number of movement. (Split-Split-Join-Join) = (Split-Join-Split-Join) \\begin{equation} Nmber Of Movement = 2S + (N-1) \\end{equation}\n\nSame size of pieces in original stacks (Case 2 and Case 3) can be considered to be same as single piece. Case 2: 3 stack of (1), Case 3: 2 stack of (1,2,3)",
"_____no_output_____"
],
[
"### Optimized movement\n\nReverse-Thinking is sometimes very effective. Create Final Stack and check the boundary. If the combination of the boundary exists in original stacks, it can be used (not necessary to split). **Stack ID needs to be checked, as for detail see later**.\n\n$S = (Maximum Number Of Split) - (Number Of Reused Boundary)$\n\n- Case 1: [1,2,3,4,5] is final form. Boundary of [1,2] exist in Original Stack-1, $S=(2+1)-1=2, Movement=2*2+(2-1)=5$\n- Case 2: Convert original stacks to [1], $Movement=2*0+(3-1)=2$\n- Case 3: Convert original stacks to [1,2,3], Final form is [1,1,2,2,3,3]. Boundary of [1,2] and [2,3] exists. $S=(2+2)-2=2$",
"_____no_output_____"
],
[
"### Sample I/O gives hint\n\nSample Input/Output often gives great hint to solve problems. Same number in original stack cause problem in above idea, but same number can be considered to be 1 digit, so convert input data to eliminate duplicate number.",
"_____no_output_____"
],
[
"### Stack ID checking\n\n- Assign stack ID\n- Merge every plates and sort by radius (size of plate)\n- Manage the list of candidate for boundary reuse (top and bottom)\n- Boundary assignment can be done greedy, if there is only 1 combination between top of stack and next, use it\n",
"_____no_output_____"
]
],
[
[
"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n'''\n 2017 MCPC at UCSY\n Problem-E: Stacking Plates\n'''\nimport sys\n\n\nclass TestCase():\n pass\n\n\nclass Plates():\n # Groupt of same radius plates in merged stack\n # id_list: list of stack ID\n def __init__(self, radius, id_list):\n self.radius = radius\n self.id_list = id_list\n self.top = None\n self.bottom = None\n\n def match_prev(self, prev_bottom):\n self.top = list()\n for stack_id in self.id_list:\n if stack_id in prev_bottom:\n self.top.append(stack_id)\n self.bottom = self.id_list.copy()\n if len(self.top) == 1 and len(self.bottom) != 1:\n self.bottom.remove(self.top[0])\n\n return\n\n def __repr__(self):\n return ('Plates {}: {}, top: {} bottom: {}'.format(self.radius, self.id_list, self.top, self.bottom))\n\n\ndef parse_tc(tc):\n '''\n Input: Test Case\n Update: \n Return: None\n '''\n\n tc.n = int(tc.stdin.readline())\n tc.stacks = list()\n\n for i in range(tc.n):\n stack = tc.stdin.readline().split()[1:] # 2d List, 1st=len\n tc.stacks.append(stack)\n\n return\n\n\ndef reform_stack(org):\n '''\n Input: tc.stacks\n Output: cosolidated stacks (no prefix, no duplicate)\n '''\n\n stacks = list()\n stack_id = 0\n\n for stack in org:\n prev_radius = None\n new_stack = list()\n\n for radius in stack:\n if radius != prev_radius:\n new_stack.append((radius, stack_id))\n prev_radius = radius\n\n stacks.append(new_stack)\n stack_id += 1\n\n return stacks\n\n\ndef merge(stacks):\n '''\n stacks: 2D List of tuple(radius, id)\n Return: 1D sorted List\n '''\n\n merged_stack = list()\n\n for stack in stacks:\n merged_stack.extend(stack)\n\n merged_stack.sort()\n\n return merged_stack\n\n\ndef stack2plates(merged_stack):\n '''\n merged_stack: List of Tuple(radius, id)\n return: List of Plates\n '''\n\n plates_list = list()\n id_list = list()\n prev_size = None\n\n for plate in merged_stack:\n radius, plate_id = plate\n if radius != prev_size:\n if id_list:\n plates_list.append(Plates(prev_size, id_list))\n id_list = [plate_id]\n else:\n id_list.append(plate_id)\n\n prev_size = radius\n\n if id_list:\n plates_list.append(Plates(radius, id_list))\n\n return plates_list\n\n\ndef max_reuse(plates_list):\n\n reuse = 0\n prev_bottom = list()\n\n for plates in plates_list:\n plates.match_prev(prev_bottom)\n if plates.top: reuse += 1\n prev_bottom = plates.bottom\n #print(plates, file=sys.stderr)\n\n return reuse\n\ndef solve(tc):\n '''\n Input: Test Case\n Return: Numper of movement\n '''\n\n parse_tc(tc)\n stacks = reform_stack(tc.stacks)\n #print(stacks)\n num_merge = len(stacks) - 1 ## Join Stacks\n for stack in stacks:\n num_merge += (len(stack) - 1) * 2 ## Split and Join\n\n merged_stack = merge(stacks)\n plates_list = stack2plates(merged_stack) # list of Plates\n\n #return (num_merge - check_bound(merged_stack, stack_bound) * 2)\n return (num_merge - max_reuse(plates_list) * 2)\n",
"_____no_output_____"
],
[
"### Main routine\n\ninfile = open('reh_e.in', 'r')\n\ntc = TestCase()\ntc.stdin = infile\ntc.t = int(tc.stdin.readline())\n\nfor i in range(tc.t):\n print('Case {}:{}'.format(i+1, solve(tc)))",
"Case 1:5\nCase 2:2\nCase 3:5\nCase 4:8\nCase 5:3\n"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
d0ad7dd10e02c16bc9ddbb50cbd9a56099959138 | 520,665 | ipynb | Jupyter Notebook | notebook/sepsis-mortality.ipynb | seoulai/mdml | 0c2bc355e927f5a7cd669da237ef713b4d37bc09 | [
"Apache-2.0"
] | 7 | 2019-01-10T18:45:17.000Z | 2021-05-29T02:46:32.000Z | notebook/sepsis-mortality.ipynb | seoulai/mdml | 0c2bc355e927f5a7cd669da237ef713b4d37bc09 | [
"Apache-2.0"
] | null | null | null | notebook/sepsis-mortality.ipynb | seoulai/mdml | 0c2bc355e927f5a7cd669da237ef713b4d37bc09 | [
"Apache-2.0"
] | null | null | null | 160.798332 | 112,808 | 0.828642 | [
[
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nfrom functools import reduce\nimport seaborn as sns; sns.set(rc={'figure.figsize':(15,15)})\nimport numpy as np\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom sklearn.preprocessing import MinMaxScaler\nengine = create_engine('postgresql://postgres:[email protected]:5555/mimic')",
"_____no_output_____"
],
[
"common_index = ['hadm_id', 'icustay_id', 'ts']\ndef get_mortality_label():\n label = pd.read_sql(\"\"\"\n select icustay_id, hadm_id, date_trunc('day', outtime) as ts, hospital_expire_flag, thirtyday_expire_flag\n from sepsis3\n where excluded=0\n \"\"\", engine)\n label.set_index(common_index, inplace=True)\n return label\n\ndef get_demo():\n demo = pd.read_sql(\"\"\"\n select icustay_id, hadm_id, date_trunc('day', intime) as ts\n , age, is_male, race_white, race_black, race_hispanic, race_other\n from sepsis3\n where excluded=0\n \"\"\", engine)\n demo.set_index(common_index, inplace=True)\n return demo\n\ndef get_admit():\n admit = pd.read_sql(\"\"\"\n select icustay_id, hadm_id, date_trunc('day', intime) as ts, icu_los, hosp_los\n from sepsis3\n where excluded=0\n \"\"\", engine)\n admit.set_index(common_index, inplace=True)\n return admit\n\ndef get_comorbidity():\n com = pd.read_sql('''\n select s.icustay_id, date_trunc('day', admittime) as ts, c.*\n from comorbidity c \n inner join (select icustay_id, hadm_id from sepsis3 where excluded=0) s \n on c.hadm_id=s.hadm_id\n ''', engine)\n del com['subject_id']\n del com['admittime']\n com.set_index(common_index, inplace=True)\n \n return com\n\ndef get_gcs():\n gcs = pd.read_sql('''\n select v.* \n from gcsdaily v\n inner join (select hadm_id from sepsis3 where excluded=0) s \n on v.hadm_id=s.hadm_id\n where charttime_by_day is not null\n ''', engine)\n\n del gcs['subject_id']\n gcs.rename(columns = {'charttime_by_day': 'ts'}, inplace=True)\n gcs.set_index(common_index, inplace=True)\n return gcs\n\ndef get_vitalsign():\n vital = pd.read_sql('''\n select v.* \n from vitalsdaily v\n inner join (select hadm_id from sepsis3 where excluded=0) s \n on v.hadm_id=s.hadm_id\n ''', engine)\n\n del vital['subject_id']\n vital.rename(columns = {'charttime_by_day': 'ts'}, inplace=True)\n vital.set_index(common_index, inplace=True)\n return vital\n\ndef get_drug():\n # (48761, 1770) --> (48761, 8) \n list_of_abx = ['adoxa','ala-tet','alodox','amikacin','amikin','amoxicillin',\n 'amoxicillin%claulanate','clavulanate','ampicillin','augmentin',\n 'avelox','avidoxy','azactam','azithromycin','aztreonam','axetil',\n 'bactocill','bactrim','bethkis','biaxin','bicillin l-a','cayston',\n 'cefazolin','cedax','cefoxitin','ceftazidime','cefaclor','cefadroxil',\n 'cefdinir','cefditoren','cefepime','cefotetan','cefotaxime','cefpodoxime',\n 'cefprozil','ceftibuten','ceftin','cefuroxime ','cefuroxime','cephalexin',\n 'chloramphenicol','cipro','ciprofloxacin','claforan','clarithromycin',\n 'cleocin','clindamycin','cubicin','dicloxacillin','doryx','doxycycline',\n 'duricef','dynacin','ery-tab','eryped','eryc','erythrocin','erythromycin',\n 'factive','flagyl','fortaz','furadantin','garamycin','gentamicin',\n 'kanamycin','keflex','ketek','levaquin','levofloxacin','lincocin',\n 'macrobid','macrodantin','maxipime','mefoxin','metronidazole',\n 'minocin','minocycline','monodox','monurol','morgidox','moxatag',\n 'moxifloxacin','myrac','nafcillin sodium','nicazel doxy 30','nitrofurantoin',\n 'noroxin','ocudox','ofloxacin','omnicef','oracea','oraxyl','oxacillin',\n 'pc pen vk','pce dispertab','panixine','pediazole','penicillin',\n 'periostat','pfizerpen','piperacillin','tazobactam','primsol','proquin',\n 'raniclor','rifadin','rifampin','rocephin','smz-tmp','septra','septra ds',\n 'septra','solodyn','spectracef','streptomycin sulfate','sulfadiazine',\n 'sulfamethoxazole','trimethoprim','sulfatrim','sulfisoxazole','suprax',\n 'synercid','tazicef','tetracycline','timentin','tobi','tobramycin','trimethoprim',\n 'unasyn','vancocin','vancomycin','vantin','vibativ','vibra-tabs','vibramycin',\n 'zinacef','zithromax','zmax','zosyn','zyvox']\n \n drug = pd.read_sql(\"\"\"\n select p.icustay_id, p.hadm_id\n , startdate as ts\n , 'prescription' as category\n , drug\n , sum((EXTRACT(EPOCH FROM enddate - startdate))/ 60 / 60 / 24) as duration\n from prescriptions p\n inner join (select hadm_id, icustay_id from sepsis3 where excluded=0) s \n on p.hadm_id=s.hadm_id and p.icustay_id=s.icustay_id\n \n group by p.icustay_id, p.hadm_id, ts, drug\n \"\"\", engine)\n drug.duration = drug.duration.replace(0, 1) # avoid null of instant prescription\n drug = drug[drug.drug.str.contains('|'.join(list_of_abx), case=False)]\n \n pivot_drug = pd.pivot_table(drug, \n index=common_index, \n columns=['drug'], \n values='duration', \n fill_value=0)\n return pivot_drug\n\ndef get_lab():\n lab = pd.read_sql(\"\"\"\n select s.icustay_id, c.hadm_id, date_trunc('day', c.charttime) as ts\n , d.label\n , valuenum\n from labevents c\n inner join (select hadm_id, icustay_id from sepsis3 where excluded=0) s \n on c.hadm_id=s.hadm_id\n join d_labitems d using (itemid)\n where itemid in (\n 50912 -- 크레아티닌(creatinine)\n ,50905, 50906 -- LDL-콜레스테롤(LDL-cholesterol)\n ,50852 -- 당화혈색소(HbA1c/Hemoglobin A1c)\n ,50809, 50931 -- 공복혈당(fasting plasma glucose)\n ,50889 -- C-반응성 단백질(C-reactive protein)\n ,50811, 51222 -- 헤모글로빈(hemoglobin)\n ,50907 -- 총콜레스테롤(total cholesterol)\n ,50945 -- 호모시스테인(Homocysteine)\n ,51006 -- 혈액 요소 질소(blood urea nitrogen)\n ,51000 -- 중성지방(triglyceride)\n ,51105 -- 요산(uric acid)\n ,50904 -- HDL-콜레스테롤(HDL-cholesterol)\n ,51265 -- 혈소판(platelet)\n ,51288 -- 적혈구침강속도(Erythrocyte sedimentation rate)\n ,51214 -- 피브리노겐(fibrinogen)\n ,51301 -- 백혈구(white blood cell)\n ,50963 -- B형 나트륨 이뇨펩타이드(B-type Natriuretic Peptide)\n ,51002, 51003 -- 트로포닌(Troponin)\n ,50908 -- 크레아티닌키나제-MB(Creatine Kinase - Muscle Brain)\n ,50862 -- 알부민(albumin)\n ,50821 -- 동맥 산소분압(arterial pO2)\n ,50818 -- 이산화탄소분압(pCO2)\n ,50820 -- 동맥혈의 산도(arterial PH)\n ,50910 -- 크레아틴키나제(CK)\n ,51237 -- 혈액응고검사(PT (INR)/aPTT) \n ,50885 -- 빌리루빈(bilirubin)\n ,51144 -- 대상핵세포(band cells)\n ,50863 -- 알칼리 인산염(alkaline phosphatase)\n )\n \"\"\", engine)\n \n pivot_lab = pd.pivot_table(lab, \n index=common_index, \n columns=['label'], \n values='valuenum', \n # aggfunc=['min', 'max', np.mean]\n fill_value=0)\n return pivot_lab\n\n\ndef get_vaso():\n vaso = pd.read_sql(\"\"\"\n select c.icustay_id, s.hadm_id, date_trunc('day', c.starttime) as ts\n , duration_hours as vaso_duration_hours\n from vasopressordurations c\n inner join (select hadm_id, icustay_id from sepsis3 where excluded=0) s \n on c.icustay_id=s.icustay_id\n \"\"\", engine)\n \n vaso.set_index(common_index, inplace=True)\n return vaso\n\ndef get_sepsis():\n s = pd.read_sql(\"\"\"\n select icustay_id, hadm_id, date_trunc('day', intime) as ts\n , sofa, qsofa\n from sepsis3\n where excluded=0\n \"\"\", engine)\n \n s.set_index(common_index, inplace=True)\n return s",
"_____no_output_____"
],
[
"def fig_corr_heatmap(labels, df, feature_df):\n cols = [labels[0]] + feature_df.columns.tolist()\n df_grp = df[cols].groupby(level=0).agg('mean')\n corr = df_grp.corr()\n \n mask = np.zeros_like(corr, dtype=np.bool)\n mask[np.triu_indices_from(mask)] = True\n \n cols[0] = labels[1] \n df_grp = df[cols].groupby(level=0).agg('mean')\n corr_30d = df_grp.corr()\n \n fig, (ax1, ax2) = plt.subplots(1,2, figsize=(15, 5))\n \n sns.heatmap(corr, ax=ax1, mask=mask, vmin=0, vmax=1)\n sns.heatmap(corr_30d, ax=ax2, mask=mask, vmin=0, vmax=1)\n ax1.set_title('In-hospital Death')\n ax2.set_title('30-day Death')\n ",
"_____no_output_____"
]
],
[
[
"- 패혈증 진단받은 환자수, 입원수",
"_____no_output_____"
]
],
[
[
"pd.read_sql(\n\"\"\"\nselect count(distinct hadm_id), count(distinct icustay_id) from sepsis3 where excluded=0\n\"\"\", engine)",
"_____no_output_____"
]
],
[
[
"- ICU, 입원 기간의 최소, 최대",
"_____no_output_____"
]
],
[
[
"pd.read_sql(\n\"\"\"\nselect min(icu_los), max(icu_los), min(hosp_los), max(hosp_los) from sepsis3 where excluded=0\n\"\"\", engine)",
"_____no_output_____"
]
],
[
[
"## 라벨\n- 사망: 원내 사망, 30일 이내 사망",
"_____no_output_____"
]
],
[
[
"label = get_mortality_label()\nlabel.head()",
"_____no_output_____"
]
],
[
[
"## 변수 : 인구통계, 입원, 진단\n",
"_____no_output_____"
]
],
[
[
"demo = get_demo()\ndemo.head() ",
"_____no_output_____"
],
[
"admit = get_admit()\nadmit.head() ",
"_____no_output_____"
],
[
"com = get_comorbidity()\ncom.head()",
"_____no_output_____"
]
],
[
[
"## 변수 : 바이탈사인, 투약, 검사, 승압제",
"_____no_output_____"
]
],
[
[
"gcs = get_gcs()\ngcs.head()",
"_____no_output_____"
],
[
"vital = get_vitalsign()\nvital.head()",
"_____no_output_____"
],
[
"drug = get_drug()\ndrug.head()",
"_____no_output_____"
],
[
"lab = get_lab()\nlab.head()",
"_____no_output_____"
],
[
"vaso = get_vaso()\nvaso.head()",
"_____no_output_____"
],
[
"sepsis = get_sepsis()\nsepsis.head()",
"_____no_output_____"
],
[
"data_frames = [\n label,\n demo,\n admit,\n com,\n gcs,\n vital,\n drug,\n lab,\n vaso,\n sepsis\n]",
"_____no_output_____"
],
[
"df_merged = reduce(lambda left,right: pd.merge(left, right, how='outer', left_index=True, right_index=True), \n data_frames)",
"_____no_output_____"
],
[
"df_merged.head()",
"_____no_output_____"
]
],
[
[
"- hdf 포맷으로 저장",
"_____no_output_____"
]
],
[
[
"filename_sepsis = \"mimiciii_sepsis_mortality.h5\"",
"_____no_output_____"
],
[
"df_merged.to_hdf(filename_sepsis, key='all')",
"_____no_output_____"
]
],
[
[
"# 탐색",
"_____no_output_____"
]
],
[
[
"df = pd.read_hdf(filename_sepsis, key='all')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"# Correlation \n## mortality and features",
"_____no_output_____"
]
],
[
[
"labels = ['hospital_expire_flag', 'thirtyday_expire_flag']",
"_____no_output_____"
],
[
"for f in data_frames[1:]:\n fig_corr_heatmap(labels, df, f)",
"_____no_output_____"
]
],
[
[
"# Feature, Label",
"_____no_output_____"
]
],
[
[
"y = df[labels].groupby(level=0).agg('max').fillna(0).values\nX = df.drop(columns=labels).groupby(level=0).agg(['mean','max', 'min']).fillna(0)",
"_____no_output_____"
],
[
"X.shape, y.shape",
"_____no_output_____"
],
[
"y.sum(axis=0) / y.shape[0]",
"_____no_output_____"
]
],
[
[
"# In-hospital Death - Train and Validation",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, confusion_matrix, f1_score, accuracy_score\nimport numpy as np\nrandom_state = 2",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y[:, 0], test_size=0.3, random_state=random_state)",
"_____no_output_____"
],
[
"clf = LogisticRegression(penalty='l1', \n solver='liblinear',\n# tol=1e-6,\n# max_iter=int(1e6),\n# warm_start=True,\n random_state=random_state)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint('auroc :', roc_auc_score(y_test, y_pred))\nprint('accuracy:', accuracy_score(y_test, y_pred))",
"auroc : 0.8591938845399976\naccuracy: 0.9559072922555116\n"
],
[
"params = {'n_estimators': 1000, 'max_leaf_nodes': None, 'max_depth': None, 'random_state': random_state,\n 'min_samples_split': 4,\n 'learning_rate': 0.1}",
"_____no_output_____"
],
[
"clf = GradientBoostingClassifier(**params)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint('auroc :', roc_auc_score(y_test, y_pred))\nprint('accuracy:', accuracy_score(y_test, y_pred))",
"auroc : 0.866716981193687\naccuracy: 0.9612775579423403\n"
],
[
"clf = RandomForestClassifier(n_estimators=1000, random_state=random_state)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint('auroc :', roc_auc_score(y_test, y_pred))\nprint('accuracy:', accuracy_score(y_test, y_pred))",
"auroc : 0.8163843583591641\naccuracy: 0.9559072922555116\n"
]
],
[
[
"# 30day Death - Train and Validation",
"_____no_output_____"
]
],
[
[
"X_train, X_test, y_train, y_test = train_test_split(X, y[:, 1], test_size=0.3, random_state=random_state)",
"_____no_output_____"
],
[
"clf = LogisticRegression(penalty='l1', \n solver='liblinear',\n# tol=1e-6,\n# max_iter=int(1e6),\n# warm_start=True,\n random_state=random_state)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint('auroc :', roc_auc_score(y_test, y_pred))\nprint('accuracy:', accuracy_score(y_test, y_pred))",
"auroc : 0.8232059239899815\naccuracy: 0.937535330695308\n"
],
[
"clf = GradientBoostingClassifier(**params)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint('auroc :', roc_auc_score(y_test, y_pred))\nprint('accuracy:', accuracy_score(y_test, y_pred))",
"auroc : 0.8264457772326086\naccuracy: 0.9400791407574901\n"
],
[
"clf = RandomForestClassifier(n_estimators=1000, random_state=random_state)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint('auroc :', roc_auc_score(y_test, y_pred))\nprint('accuracy:', accuracy_score(y_test, y_pred))",
"auroc : 0.7760491255033056\naccuracy: 0.9355568117580554\n"
]
]
] | [
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0ad7f4a3face46ce4a9fe041e18d5821567febf | 123,138 | ipynb | Jupyter Notebook | dcgan.ipynb | tjh48/DCGAN | e3d205905cfb5c6d9e182c8340d15dd46f36958b | [
"Unlicense"
] | null | null | null | dcgan.ipynb | tjh48/DCGAN | e3d205905cfb5c6d9e182c8340d15dd46f36958b | [
"Unlicense"
] | null | null | null | dcgan.ipynb | tjh48/DCGAN | e3d205905cfb5c6d9e182c8340d15dd46f36958b | [
"Unlicense"
] | null | null | null | 237.260116 | 58,348 | 0.880865 | [
[
[
"[View in Colaboratory](https://colab.research.google.com/github/tjh48/DCGAN/blob/master/dcgan.ipynb)",
"_____no_output_____"
],
[
"First we'll import all the tools we need and set some initial parameters",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom sklearn.utils import shuffle\nimport matplotlib.pyplot as plt\nimport os\n\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import EarlyStopping\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils\nfrom keras.initializers import RandomNormal\nimport keras.backend as K\nimport time\n\n\n# Just in case we're re-running, clear the Keras session data.\nK.clear_session()\n\n# Shall we use BatchNormalization layers?\nuseBN = False\n# Shall we use bias?\nuseBias = True\n\n# Logging directory and label\nLOG_DIR = './log'\nlogSub = \"mnistDCGAN\"\n",
"_____no_output_____"
]
],
[
[
"This is an optional code block for creating an ngrok tunnel to a tensorboard instance. Useful for running on cloud services ",
"_____no_output_____"
]
],
[
[
"if not os.path.isfile('./ngrok'):\n !wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n !unzip ngrok-stable-linux-amd64.zip \n\nget_ipython().system_raw(\n 'tensorboard --logdir ' + LOG_DIR + ' --host 0.0.0.0 --port 6006 &'\n)\n\nget_ipython().system_raw('./ngrok http 6006 &')\n\n! curl -s http://localhost:4040/api/tunnels | python3 -c \\\n \"import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])\"",
"http://e37a75c1.ngrok.io\r\n"
]
],
[
[
"This code block imports manual logging functionality and defines a couple of extra functions required for GANs in Keras, since we need to use train_on_batch rather than fit. train_on_batch does not log automatically to tensorboard, hence we'll perform the logging manually.",
"_____no_output_____"
]
],
[
[
"if os.path.isfile('tensorboard_logging.py'): os.remove('tensorboard_logging.py')\n!wget https://gist.githubusercontent.com/tjh48/bf56684801d641544e49a5e66bf15fba/raw/9c6e04cca49288ab0920d9a3aeb3283da13d1a39/tensorboard_logging.py\nimport tensorboard_logging as tbl \n\nsubdir = LOG_DIR + \"/\" + logSub + '_' + str(int(np.round(time.time())))\nlogger = tbl.Logger(subdir)",
"--2018-08-29 20:50:54-- https://gist.githubusercontent.com/tjh48/bf56684801d641544e49a5e66bf15fba/raw/9c6e04cca49288ab0920d9a3aeb3283da13d1a39/tensorboard_logging.py\r\nResolving gist.githubusercontent.com (gist.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...\r\nConnecting to gist.githubusercontent.com (gist.githubusercontent.com)|151.101.0.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 3783 (3.7K) [text/plain]\nSaving to: ‘tensorboard_logging.py’\n\ntensorboard_logging 100%[===================>] 3.69K --.-KB/s in 0s \n\n2018-08-29 20:50:54 (31.6 MB/s) - ‘tensorboard_logging.py’ saved [3783/3783]\n\n"
]
],
[
[
"Next we'll download the MNIST data set, in lieu of anything more interesting to work with.\n\nWe'll also define a function for plotting MNIST-type images so that we can see the output of the generator.",
"_____no_output_____"
]
],
[
[
"from keras.datasets import mnist\n\n(x_train, _), (x_test, _) = mnist.load_data()\n\n# just for fun, you can drop in the fashion_mnist dataset here instead of standard mnist\n#from keras.datasets import fashion_mnist\n#(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()\n\nx_train = x_train.astype('float32') / 127.5 - 1\nx_test = x_test.astype('float32') / 127.5 - 1\n\nx_train = x_train[:, :, :, np.newaxis]\n\ndef plotImages(images, n = 25):\n plt.figure(figsize=(32, 32))\n for i in range(n):\n ax = plt.subplot(2, n, i + 1)\n x = images[i]\n if x.shape[2] == 1: x = x.reshape(x.shape[0:2])\n plt.imshow((x + 1) / 2)\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n plt.show()\n \nplotImages(x_train)",
"_____no_output_____"
],
[
"def genfun(inputLayer, initialFeatures = 256, outputDim = 32, outputFeatures = 3, minimumDim = 5):\n # Here we find the number of times the output dimension is divisible by 2\n # while still keeping the initial dimension of the data above some threshold.\n # Letting the threshold go too low results in model collapse; ad hoc experimentation suggests that\n # an initial dimension >= 5 is ok.\n for loop in range(int(np.log2(outputDim)) + 1):\n if(outputDim % np.power(2, loop) != 0 or outputDim / np.power(2, loop) < minimumDim):\n break\n \n # Given the number of times the output dimension is divisible by 2,\n # we can determine the initial dimension of the dense layer from a random vector.\n initialDim = outputDim // np.power(2, loop - 1)\n if initialDim == outputDim:\n raise ValueError(\"The outputDim is not divisible by 2 - there's no clean way to upsample.\")\n \n x = Dense(initialDim*initialDim*initialFeatures, kernel_initializer='glorot_normal', use_bias = useBias)(inputLayer)\n x = LeakyReLU(0.2)(x)\n if useBN: x = BatchNormalization()(x)\n x = Reshape((initialDim, initialDim, initialFeatures))(x)\n \n # Now we can repeatedly upsample doubling the dimension each time \n # and convolute, halving the number of features\n # until we arrive at (half the) right output dimension\n for ii in range(loop - 1):\n x = UpSampling2D(size=(2, 2), data_format='channels_last')(x)\n if ii < loop - 2:\n x = Conv2D(initialFeatures // np.power(2, ii + 1), kernel_size = 5, padding ='same', use_bias = useBias, strides = 1)(x)\n x = LeakyReLU(0.2)(x)\n if useBN: x = BatchNormalization()(x)\n # now reduce the features to one (for MNIST) - for colour images we may need three or more channels in output\n x = Conv2D(outputFeatures, kernel_size = 5, padding ='same', use_bias = useBias, strides = 1)(x)\n x = Activation('tanh')(x)\n return x",
"_____no_output_____"
]
],
[
[
"Here's a function to define the generator layer. We want to upsample from a random vector to an image, with a convolutional layer at each upsampling. Each upsampling with a 2x2 shape doubles the size of the image, so we can start with with a low-dimensional image with a large number of features and upsample until we get to the right size. \n\nStarting with a too-low dimensional image gives model failure, particularly if you don't use batch normalisation. Ad hoc experimentation suggests that an initial dimension > 5 is required to avoid this scenario.\n",
"_____no_output_____"
],
[
"And here's a function to define a discriminator layer. In the original DCGAN paper, this is envisaged as an almost direct mirror image of the generator. It need not be - we could have fewer layers (to make the discriminator less efficient) as long as we end with a dense layer mapping to a single output.",
"_____no_output_____"
]
],
[
[
"def disfun(inputImage, initialFeatures= 64, numLayers = 2):\n x = inputImage\n for ii in range(numLayers):\n x = Conv2D(initialFeatures * np.power(2, ii), kernel_size = 5, padding='same', strides=(2,2), use_bias = useBias)(x)\n x = LeakyReLU(0.2)(x)\n if useBN: x = BatchNormalization()(x)\n x = Flatten()(x)\n x = Dense(1, activation = 'sigmoid', use_bias = useBias)(x)\n return x",
"_____no_output_____"
]
],
[
[
"Now comes the conceptually tricky bit. The best way I've found to think about this is found on ctmakro's github page:\n\n\nThis map of the model makes it clear what we're trying to do in each training pass. We generate a random input 'z' which we feed into the generator along with the weights 'Wg' (the generator's weights, which we want to train). That produces a set of generated images, which we feed into a copy of the discriminator. \n\nThe generator's performance ('G_loss') is measured on its ability to get the discriminator to regard the generated images as true positives - what the discriminator says about the input images is irrelevant to the generator's loss. Then we update (green arrow) the generator's weights based on the generator's loss.\n\nThe discriminator's performance ('D_loss') is measured on its ability to separate the generated images (the output of 'D(copy1)'') from the true images (the output of 'D(copy2)'). We update (blue arrow) the discriminator's weights based on the discriminator's loss.\n\nIn native Keras, we don't have a way to update one set of weights 'Wg' based on the 'G_loss' and another set of weights 'Wd' based on the 'D_loss' and so we have to split this update process. \n\nIn each training step, we first produce a set of generated images to feed into the discriminator (along with the true images) and train the discriminator's loss. Then we freeze the discriminator's weights (make it untrainable) and train the generator by feeding the generated images into the discriminator, with the generator being scored on how strongly the discriminator predicts that the generated images are true.\n\n[ctmakro's github - Fast DCGAN in Keras](https://ctmakro.github.io/site/on_learning/fast_gan_in_keras.html) has a method for rewriting the necessary update steps in tensorflow, making it possible to update both sets of weights in one step, making for a faster update process. For the moment, we'll stick with the longer method as this tends to be the one that gets implemented (but often not explained)",
"_____no_output_____"
],
[
"Here we can build the models. We need a discriminator model that can be trained on true/fake images, a generator model that will be used to create fake images, and a combined model that will link the generator to the discriminator to produce the loss on the generator. \n\nSince the loss on the generator is measured by assuming the fake images are real, we need to freeze (set untrainable) the discriminator model so as not to disrupt the training of the discriminator by feeding it false information.\n\nI'm wrapping the whole thing up in a function so that we can easily generate fresh models for use with a tweaked training regime.",
"_____no_output_____"
]
],
[
[
"optimizer = Adam(0.0002, 0.5)\n\n\ndef dcganModels():\n inputRandom = Input(shape=(100,))\n generator = Model(inputRandom, genfun(inputRandom, initialFeatures = 128, outputDim = x_train.shape[2], outputFeatures = x_train.shape[3]))\n generator.compile(loss = 'binary_crossentropy', optimizer = optimizer)\n \n inputImage = Input(shape=x_train.shape[1:4]) # adapt this if using `channels_first` image data format\n discriminator = Model(inputImage, disfun(inputImage))\n discriminator.compile(loss = 'binary_crossentropy', optimizer = optimizer)\n\n discriminator.trainable = False\n gan = Model(inputRandom, discriminator(generator(inputRandom)))\n gan.compile(loss = 'binary_crossentropy', optimizer = optimizer)\n discriminator.trainable = True\n return(gan, discriminator, generator)",
"_____no_output_____"
]
],
[
[
"Next we'll create a function that creates the data for each training batch. \n\nOne trick for improving performance of GANs is to add random noise to both the true and fake images as they go into the discriminator. This weakens the discriminator by creating more overlap between (the distribution of) true and fake images (http://www.inference.vc/instance-noise-a-trick-for-stabilising-gan-training/). As the generator improves, we require less noise to confuse the discriminator, and so we can weaken the amount of noise being added over time. This seems to offer considerably faster training, and more convincing output.",
"_____no_output_____"
]
],
[
[
"def makeBatch(x_train, batchSize = 128, noisyEpochs = 0.0):\n noise_factor = 0\n if noisyEpochs > 0:\n noise_factor = np.clip(1 - i/noisyEpochs, 0, 1)\n trueImages = x_train[np.random.randint(0, x_train.shape[0], batchSize),]\n trueImages = trueImages + np.random.normal(loc=0.0, scale=noise_factor, size=trueImages.shape)\n trueImages = np.clip(trueImages, -1, 1)\n randomInput = np.random.normal(0, 1, (batchSize,100))\n generatedImages = generator.predict(randomInput)\n generatedImages = generatedImages + np.random.normal(loc=0.0, scale=noise_factor, size=generatedImages.shape)\n generatedImages = np.clip(generatedImages, -1, 1)\n return randomInput, trueImages, generatedImages",
"_____no_output_____"
]
],
[
[
"Now we can train the models. We first generate the fake images, then train the discriminator on these and an equal sized random batch of the true images. Then we train the generator. \n\nEvery fifty epochs, we'll take a look at a sample of the current output and log the various metrics of interest.",
"_____no_output_____"
]
],
[
[
"nbEpoch = 10000\ndLoss = []\ngLoss = []\n\nfrom IPython.display import clear_output, Image\n\ngan, discriminator, generator = dcganModels()\n\nbatchSize = 128\n\nfor epoch in range(nbEpoch):\n randomInput, trueImages, generatedImages = makeBatch(x_train)\n discriminatorLoss = 0.5 * (discriminator.train_on_batch(generatedImages, np.zeros(generatedImages.shape[0])) + discriminator.train_on_batch(trueImages, np.ones(trueImages.shape[0])))\n dcganLabels = np.ones(generatedImages.shape[0]).astype(int)\t\t\t\n discriminator.trainable = False\n dcganLoss = gan.train_on_batch(randomInput, dcganLabels)\n discriminator.trainable = True\n dLoss.append(discriminatorLoss)\n gLoss.append(dcganLoss)\n \n if (epoch % 50 == 0) or (epoch == 0):\n print('after epoch: ', epoch)\n print ('dcgan Loss: ', dcganLoss, '\\t discriminator loss', discriminatorLoss)\n clear_output(wait=True)\n fig, ax1 = plt.subplots(1,1)\n fig.set_size_inches(16, 8)\n ax1.plot(range(len(dLoss)), dLoss, label=\"loss generator\")\n ax1.plot(range(len(gLoss)), gLoss, label=\"loss disc-true\")\n plt.show()\n plotImages(generatedImages)\n tbl.logModel(logger, epoch, generator, \"generator\")\n tbl.logModel(logger, epoch, discriminator, \"discriminator\")\n logger.log_scalar('generator_loss', gLoss[epoch], epoch)\n logger.log_scalar('discriminator_loss', dLoss[epoch], epoch)",
"_____no_output_____"
]
]
] | [
"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"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ad91da1edf29c717764a8b75a014db4799acb7 | 67,255 | ipynb | Jupyter Notebook | Starter_Code.ipynb | Tania612/deep-learning | 40e0da703835eec36488dd654b1c7d3c9a69999f | [
"ADSL"
] | null | null | null | Starter_Code.ipynb | Tania612/deep-learning | 40e0da703835eec36488dd654b1c7d3c9a69999f | [
"ADSL"
] | null | null | null | Starter_Code.ipynb | Tania612/deep-learning | 40e0da703835eec36488dd654b1c7d3c9a69999f | [
"ADSL"
] | null | null | null | 44.896529 | 1,230 | 0.410572 | [
[
[
"## Preprocessing",
"_____no_output_____"
]
],
[
[
"# Import our dependencies\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport pandas as pd\nimport tensorflow as tf\n\n# Import and read the charity_data.csv.\nimport pandas as pd \napplication_df = pd.read_csv(\"Resources/charity_data.csv\")\napplication_df.head()",
"_____no_output_____"
],
[
"# Drop the non-beneficial ID columns, 'EIN' and 'NAME'.\napplication_df = application_df.drop(columns=['EIN','NAME'],axis=1)\napplication_df",
"_____no_output_____"
],
[
"# Determine the number of unique values in each column.\napplication_df.nunique()",
"_____no_output_____"
],
[
"# Look at APPLICATION_TYPE value counts for binning\napp_type = application_df['APPLICATION_TYPE'].value_counts()\napp_type",
"_____no_output_____"
],
[
"# Choose a cutoff value and create a list of application types to be replaced\n# use the variable name `application_types_to_replace\napplication_types_to_replace = list(app_type[app_type<200].index)\n\n# Replace in dataframe\nfor app in application_types_to_replace:\n application_df['APPLICATION_TYPE'] = application_df['APPLICATION_TYPE'].replace(app,\"Other\")\n\n# Check to make sure binning was successful\napplication_df['APPLICATION_TYPE'].value_counts()",
"_____no_output_____"
],
[
"# Look at CLASSIFICATION value counts for binning\napp_class = application_df['CLASSIFICATION'].value_counts()\napp_class",
"_____no_output_____"
],
[
"# You may find it helpful to look at CLASSIFICATION value counts >1\nfor i in app_class:\n if i > 1:\n print(i)",
"17326\n6074\n4837\n1918\n1883\n777\n287\n194\n116\n114\n104\n95\n75\n58\n50\n36\n34\n32\n32\n30\n20\n18\n16\n15\n15\n14\n11\n10\n10\n9\n9\n7\n6\n6\n6\n5\n5\n3\n3\n3\n2\n2\n2\n2\n2\n"
],
[
"# Choose a cutoff value and create a list of classifications to be replaced\n# use the variable name `classifications_to_replace`\nclassifications_to_replace = list(app_class[app_class<800].index)\n\n# Replace in dataframe\nfor cls in classifications_to_replace:\n application_df['CLASSIFICATION'] = application_df['CLASSIFICATION'].replace(cls,\"Other\")\n \n# Check to make sure binning was successful\napplication_df['CLASSIFICATION'].value_counts()",
"_____no_output_____"
],
[
"# Convert categorical data to numeric with `pd.get_dummies`\napplication_df = pd.get_dummies(application_df, dtype=float)\napplication_df",
"_____no_output_____"
],
[
"# Split our preprocessed data into our features and target arrays\ny = application_df.IS_SUCCESSFUL.values\nX = application_df.drop('IS_SUCCESSFUL', axis=1).values\n\n# Split the preprocessed data into a training and\n# testing dataset\nX_train, X_test, y_train, y_test = train_test_split(X,y,random_state= 42)",
"_____no_output_____"
],
[
"# Create a StandardScaler instances\nscaler = StandardScaler()\n\n# Fit the StandardScaler\nX_scaler = scaler.fit(X_train)\n\n# Scale the data\nX_train_scaled = X_scaler.transform(X_train)\nX_test_scaled = X_scaler.transform(X_test)",
"_____no_output_____"
]
],
[
[
"## Compile, Train and Evaluate the Model",
"_____no_output_____"
]
],
[
[
"# # Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.\n# number_input_features = len( X_train_scaled[0])\n# hidden_nodes_layer1=88\n# hidden_nodes_layer2=44\n\n# attempt 2\nnumber_input_features = len( X_train_scaled[0])\nhidden_nodes_layer1=10\nhidden_nodes_layer2=20\n\n# # attempt 3\n# number_input_features = len( X_train_scaled[0])\n# hidden_nodes_layer1=15\n# hidden_nodes_layer2=40\n\nnn = tf.keras.models.Sequential()\n\n# First hidden layer\nnn.add(tf.keras.layers.Dense(units=hidden_nodes_layer1, input_dim=number_input_features, activation='relu'))\n\n\n# Second hidden layer\nnn.add(tf.keras.layers.Dense(units=hidden_nodes_layer2, activation='relu'))\n\n# Output layer\nnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))\n\n# Check the structure of the model\nnn.summary()",
"Model: \"sequential_9\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n dense_27 (Dense) (None, 10) 440 \n \n dense_28 (Dense) (None, 20) 220 \n \n dense_29 (Dense) (None, 1) 21 \n \n=================================================================\nTotal params: 681\nTrainable params: 681\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"# Compile the model\nnn.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics=['accuracy', tf.keras.metrics.Recall()])",
"_____no_output_____"
],
[
"# Train the model\nfit_model = nn.fit(X_train_scaled,y_train,validation_split=0.15, epochs=100)",
"Epoch 1/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.6035 - accuracy: 0.6952 - recall_9: 0.7602 - val_loss: 0.5615 - val_accuracy: 0.7315 - val_recall_9: 0.7680\nEpoch 2/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5652 - accuracy: 0.7211 - recall_9: 0.7822 - val_loss: 0.5532 - val_accuracy: 0.7339 - val_recall_9: 0.7830\nEpoch 3/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5586 - accuracy: 0.7264 - recall_9: 0.7928 - val_loss: 0.5517 - val_accuracy: 0.7362 - val_recall_9: 0.7785\nEpoch 4/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5561 - accuracy: 0.7282 - recall_9: 0.7895 - val_loss: 0.5494 - val_accuracy: 0.7365 - val_recall_9: 0.7785\nEpoch 5/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5543 - accuracy: 0.7280 - recall_9: 0.7924 - val_loss: 0.5509 - val_accuracy: 0.7349 - val_recall_9: 0.7571\nEpoch 6/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5532 - accuracy: 0.7285 - recall_9: 0.7922 - val_loss: 0.5474 - val_accuracy: 0.7341 - val_recall_9: 0.7670\nEpoch 7/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5523 - accuracy: 0.7286 - recall_9: 0.7889 - val_loss: 0.5463 - val_accuracy: 0.7341 - val_recall_9: 0.7820\nEpoch 8/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5519 - accuracy: 0.7299 - recall_9: 0.7875 - val_loss: 0.5469 - val_accuracy: 0.7357 - val_recall_9: 0.7815\nEpoch 9/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5508 - accuracy: 0.7304 - recall_9: 0.7903 - val_loss: 0.5488 - val_accuracy: 0.7341 - val_recall_9: 0.7611\nEpoch 10/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5508 - accuracy: 0.7299 - recall_9: 0.7892 - val_loss: 0.5473 - val_accuracy: 0.7328 - val_recall_9: 0.8148\nEpoch 11/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5502 - accuracy: 0.7300 - recall_9: 0.7919 - val_loss: 0.5471 - val_accuracy: 0.7359 - val_recall_9: 0.7715\nEpoch 12/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5501 - accuracy: 0.7295 - recall_9: 0.7964 - val_loss: 0.5457 - val_accuracy: 0.7341 - val_recall_9: 0.7656\nEpoch 13/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5494 - accuracy: 0.7309 - recall_9: 0.7920 - val_loss: 0.5486 - val_accuracy: 0.7362 - val_recall_9: 0.7621\nEpoch 14/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5496 - accuracy: 0.7308 - recall_9: 0.7909 - val_loss: 0.5461 - val_accuracy: 0.7367 - val_recall_9: 0.7775\nEpoch 15/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5488 - accuracy: 0.7303 - recall_9: 0.7916 - val_loss: 0.5479 - val_accuracy: 0.7344 - val_recall_9: 0.7661\nEpoch 16/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5487 - accuracy: 0.7307 - recall_9: 0.7901 - val_loss: 0.5454 - val_accuracy: 0.7354 - val_recall_9: 0.7656\nEpoch 17/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5486 - accuracy: 0.7313 - recall_9: 0.7895 - val_loss: 0.5446 - val_accuracy: 0.7359 - val_recall_9: 0.7695\nEpoch 18/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5483 - accuracy: 0.7311 - recall_9: 0.7886 - val_loss: 0.5449 - val_accuracy: 0.7346 - val_recall_9: 0.7770\nEpoch 19/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5476 - accuracy: 0.7302 - recall_9: 0.7940 - val_loss: 0.5450 - val_accuracy: 0.7346 - val_recall_9: 0.7631\nEpoch 20/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5479 - accuracy: 0.7315 - recall_9: 0.7925 - val_loss: 0.5466 - val_accuracy: 0.7297 - val_recall_9: 0.8024\nEpoch 21/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5477 - accuracy: 0.7315 - recall_9: 0.7927 - val_loss: 0.5451 - val_accuracy: 0.7362 - val_recall_9: 0.7800\nEpoch 22/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5474 - accuracy: 0.7313 - recall_9: 0.7903 - val_loss: 0.5460 - val_accuracy: 0.7339 - val_recall_9: 0.7636\nEpoch 23/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5473 - accuracy: 0.7316 - recall_9: 0.7881 - val_loss: 0.5457 - val_accuracy: 0.7352 - val_recall_9: 0.7666\nEpoch 24/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5473 - accuracy: 0.7301 - recall_9: 0.7894 - val_loss: 0.5448 - val_accuracy: 0.7344 - val_recall_9: 0.7670\nEpoch 25/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5473 - accuracy: 0.7320 - recall_9: 0.7910 - val_loss: 0.5448 - val_accuracy: 0.7362 - val_recall_9: 0.7700\nEpoch 26/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5466 - accuracy: 0.7324 - recall_9: 0.7910 - val_loss: 0.5457 - val_accuracy: 0.7352 - val_recall_9: 0.7830\nEpoch 27/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5470 - accuracy: 0.7325 - recall_9: 0.7916 - val_loss: 0.5470 - val_accuracy: 0.7352 - val_recall_9: 0.7646\nEpoch 28/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5466 - accuracy: 0.7321 - recall_9: 0.7904 - val_loss: 0.5458 - val_accuracy: 0.7341 - val_recall_9: 0.7646\nEpoch 29/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5460 - accuracy: 0.7325 - recall_9: 0.7917 - val_loss: 0.5460 - val_accuracy: 0.7359 - val_recall_9: 0.7715\nEpoch 30/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5462 - accuracy: 0.7330 - recall_9: 0.7925 - val_loss: 0.5458 - val_accuracy: 0.7370 - val_recall_9: 0.7725\nEpoch 31/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5458 - accuracy: 0.7337 - recall_9: 0.7935 - val_loss: 0.5468 - val_accuracy: 0.7339 - val_recall_9: 0.7641\nEpoch 32/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5459 - accuracy: 0.7329 - recall_9: 0.7918 - val_loss: 0.5473 - val_accuracy: 0.7344 - val_recall_9: 0.7695\nEpoch 33/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5460 - accuracy: 0.7329 - recall_9: 0.7925 - val_loss: 0.5455 - val_accuracy: 0.7372 - val_recall_9: 0.7685\nEpoch 34/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5454 - accuracy: 0.7325 - recall_9: 0.7949 - val_loss: 0.5484 - val_accuracy: 0.7370 - val_recall_9: 0.7546\nEpoch 35/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5458 - accuracy: 0.7337 - recall_9: 0.7881 - val_loss: 0.5452 - val_accuracy: 0.7357 - val_recall_9: 0.7775\nEpoch 36/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5459 - accuracy: 0.7327 - recall_9: 0.7907 - val_loss: 0.5444 - val_accuracy: 0.7365 - val_recall_9: 0.7616\nEpoch 37/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5456 - accuracy: 0.7335 - recall_9: 0.7932 - val_loss: 0.5483 - val_accuracy: 0.7341 - val_recall_9: 0.7466\nEpoch 38/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5456 - accuracy: 0.7326 - recall_9: 0.7870 - val_loss: 0.5463 - val_accuracy: 0.7359 - val_recall_9: 0.7750\nEpoch 39/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5449 - accuracy: 0.7340 - recall_9: 0.7920 - val_loss: 0.5476 - val_accuracy: 0.7365 - val_recall_9: 0.7750\nEpoch 40/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5458 - accuracy: 0.7332 - recall_9: 0.7900 - val_loss: 0.5449 - val_accuracy: 0.7359 - val_recall_9: 0.7710\nEpoch 41/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5454 - accuracy: 0.7330 - recall_9: 0.7901 - val_loss: 0.5446 - val_accuracy: 0.7349 - val_recall_9: 0.7700\nEpoch 42/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5454 - accuracy: 0.7326 - recall_9: 0.7922 - val_loss: 0.5457 - val_accuracy: 0.7336 - val_recall_9: 0.7631\nEpoch 43/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5454 - accuracy: 0.7331 - recall_9: 0.7904 - val_loss: 0.5448 - val_accuracy: 0.7334 - val_recall_9: 0.7646\nEpoch 44/100\n684/684 [==============================] - 1s 1ms/step - loss: 0.5450 - accuracy: 0.7335 - recall_9: 0.7933 - val_loss: 0.5454 - val_accuracy: 0.7334 - val_recall_9: 0.7506\nEpoch 45/100\n"
],
[
"# Evaluate the model using the test data\nmodel_loss, model_accuracy, model_recall = nn.evaluate(X_test_scaled,y_test,verbose=2)\nprint(f\"Loss: {model_loss}, Accuracy: {model_accuracy}\")",
"268/268 - 0s - loss: 0.5546 - accuracy: 0.7233 - recall_9: 0.8154 - 159ms/epoch - 595us/step\nLoss: 0.5546053647994995, Accuracy: 0.7232652902603149\n"
],
[
"# Export our model to HDF5 file\nfrom google.colab import files\n\nnn.save('AlphabetSoupCharity_Optimization.h5')\nfiles.download('AlphabetSoupCharity_Optimization.h5')",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
d0ad93c178b789406fef05846493e540d78c0d8e | 429,369 | ipynb | Jupyter Notebook | dmu16/dmu16_allwise/WISE_2_GAIA-XMM-LSS.ipynb | djbsmith/dmu_products | 4a6e1496a759782057c87ab5a65763282f61c497 | [
"MIT"
] | null | null | null | dmu16/dmu16_allwise/WISE_2_GAIA-XMM-LSS.ipynb | djbsmith/dmu_products | 4a6e1496a759782057c87ab5a65763282f61c497 | [
"MIT"
] | null | null | null | dmu16/dmu16_allwise/WISE_2_GAIA-XMM-LSS.ipynb | djbsmith/dmu_products | 4a6e1496a759782057c87ab5a65763282f61c497 | [
"MIT"
] | null | null | null | 1,027.198565 | 129,960 | 0.955192 | [
[
[
"# Puts ALL WISE Astrometry reference catalogues into GAIA reference frame\n\n<img src=https://avatars1.githubusercontent.com/u/7880370?s=200&v=4>\n\nThe WISE catalogues were produced by ../dmu16_allwise/make_wise_samples_for_stacking.csh\n\nIn the catalogue, we keep:\n\n- The position;\n- The chi^2\n\nThis astrometric correction is adapted from master list code (dmu1_ml_XMM-LSS/1.8_SERVS.ipynb) written by Yannick Rohlly and Raphael Shirley\n",
"_____no_output_____"
]
],
[
[
"field=\"XMM-LSS\"",
"_____no_output_____"
],
[
"from herschelhelp_internal import git_version\nprint(\"This notebook was run with herschelhelp_internal version: \\n{}\".format(git_version()))",
"This notebook was run with herschelhelp_internal version: \n0aab440 (Thu Mar 22 09:41:13 2018 +0000)\n"
],
[
"%matplotlib inline\n#%config InlineBackend.figure_format = 'svg'\n\nimport matplotlib.pyplot as plt\nplt.rc('figure', figsize=(10, 6))\n\nfrom collections import OrderedDict\nimport os\n\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.table import Column, Table\nimport numpy as np\n\nfrom herschelhelp_internal.flagging import gaia_flag_column\nfrom herschelhelp_internal.masterlist import nb_astcor_diag_plot, remove_duplicates\nfrom herschelhelp_internal.utils import astrometric_correction, flux_to_mag",
"/Users/sjo/anaconda3/envs/herschelhelp_internal/lib/python3.6/site-packages/seaborn/apionly.py:6: UserWarning: As seaborn no longer sets a default style on import, the seaborn.apionly module is deprecated. It will be removed in a future version.\n warnings.warn(msg, UserWarning)\n"
],
[
"OUT_DIR = os.environ.get('TMP_DIR', \"../dmu16_allwise/data/\")\ntry:\n os.makedirs(OUT_DIR)\nexcept FileExistsError:\n pass\n\nRA_COL = \"servs_ra\"\nDEC_COL = \"servs_dec\"",
"_____no_output_____"
],
[
"## I - Reading in WISE astrometric catalogue",
"_____no_output_____"
],
[
"wise = Table.read(f\"../dmu16_allwise/data/Allwise_PSF_stack_{field}.fits\")\nwise_coords=SkyCoord(wise['ra'], wise['dec'])\n\nepoch = 2009\n\nwise[:10].show_in_notebook()",
"_____no_output_____"
]
],
[
[
"## III - Astrometry correction\n\nWe match the astrometry to the Gaia one. We limit the Gaia catalogue to sources with a g band flux between the 30th and the 70th percentile. Some quick tests show that this give the lower dispersion in the results.",
"_____no_output_____"
]
],
[
[
"#gaia = Table.read(\"./dmu17_XMM-LSS/data/GAIA_XMM-LSS.fits\")\nprint(f\"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits\")\ngaia = Table.read(f\"../../dmu0/dmu0_GAIA/data/GAIA_{field}.fits\")\ngaia_coords = SkyCoord(gaia['ra'], gaia['dec'])",
"../../dmu0/dmu0_GAIA/data/GAIA_XMM-LSS.fits\n"
],
[
"nb_astcor_diag_plot(wise_coords.ra, wise_coords.dec, \n gaia_coords.ra, gaia_coords.dec, near_ra0=True)",
"/Users/sjo/anaconda3/envs/herschelhelp_internal/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.\n warnings.warn(\"The 'normed' kwarg is deprecated, and has been \"\n"
],
[
"delta_ra, delta_dec = astrometric_correction(\n wise_coords,\n gaia_coords, near_ra0=True\n)\n\nprint(\"RA correction: {}\".format(delta_ra))\nprint(\"Dec correction: {}\".format(delta_dec))",
"RA correction: 0.061640000240004156 arcsec\nDec correction: -0.037516070016963 arcsec\n"
],
[
"print( wise[\"ra\"])\nprint(delta_ra.to(u.deg))",
" ra \n deg \n----------\n32.8599784\n 32.949841\n32.9127882\n32.9166059\n32.9197243\n32.8892899\n 32.885893\n32.8882194\n 32.897283\n32.9007978\n ...\n37.0483865\n 37.043738\n 37.033254\n37.0370584\n37.0309353\n37.0224723\n37.0274276\n37.0556116\n37.0632212\n37.0525429\nLength = 320010 rows\n1.7122222288890043e-05 deg\n"
],
[
"#wise[\"ra\"] += delta_ra.to(u.deg)\nwise[\"ra\"] = wise[\"ra\"]+ delta_ra.to(u.deg)\nwise[\"dec\"] = wise[\"dec\"]+ delta_dec.to(u.deg)",
"_____no_output_____"
],
[
"nb_astcor_diag_plot(wise[\"ra\"], wise[\"dec\"], \n gaia_coords.ra, gaia_coords.dec, near_ra0=True)",
"/Users/sjo/anaconda3/envs/herschelhelp_internal/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.\n warnings.warn(\"The 'normed' kwarg is deprecated, and has been \"\n"
]
],
[
[
"## V - Saving to disk",
"_____no_output_____"
]
],
[
[
"wise.write(f\"../dmu16_allwise/data/Allwise_PSF_stack_GAIA_{field}.fits\", overwrite=True)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ad94790047e51fd430337b464242d6eec3bbf1 | 18,712 | ipynb | Jupyter Notebook | Jupyter-Notebook/Intro to Data Science/intro-to-data-science-applying-functions-to-data.ipynb | shohan4556/machine-learning-course-notes | 981f3d6e9861cbee0f4dec45b1d2e6a214d2a051 | [
"MIT"
] | 8 | 2019-10-12T17:08:58.000Z | 2020-02-26T02:54:01.000Z | Jupyter-Notebook/Intro to Data Science/intro-to-data-science-applying-functions-to-data.ipynb | shohan4556/machine-learning-course-notes | 981f3d6e9861cbee0f4dec45b1d2e6a214d2a051 | [
"MIT"
] | null | null | null | Jupyter-Notebook/Intro to Data Science/intro-to-data-science-applying-functions-to-data.ipynb | shohan4556/machine-learning-course-notes | 981f3d6e9861cbee0f4dec45b1d2e6a214d2a051 | [
"MIT"
] | 5 | 2019-10-30T03:50:20.000Z | 2020-07-11T20:53:47.000Z | 33.354724 | 272 | 0.392956 | [
[
[
"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.",
"/kaggle/input/california-housing-prices/housing.csv\n"
]
],
[
[
"This is the post about **Introduction to Data Scinece**, I am going to write about* handling tabular/dataframe* data in python3. ",
"_____no_output_____"
],
[
"### Importing Data ",
"_____no_output_____"
]
],
[
[
"import pandas as pd \ndf = pd.read_csv('/kaggle/input/california-housing-prices/housing.csv')\ndisplay(df.head())",
"_____no_output_____"
]
],
[
[
"During data analysis, we need to use our data to perform some calculations and generate some new data or output from it. Pandas makes it very easy to apply user-defined operations, in Python terminology, on individual data items, rows, and columns of a dataframe.\n\nPandas has an **apply** function which applies the provided function to the data. One of the reasons for the success of pandas is how fast the apply function performs.",
"_____no_output_____"
],
[
"In the Dataset, the field **median_income** has values which are written in tens of thousands of dollars. During analysis, we might want to convert this to Dollars. Let’s see how we can do that with the apply function.",
"_____no_output_____"
]
],
[
[
"def convert(n):\n return n * 10000\n\nconverted = df['median_income'].apply(convert)\ndisplay(converted.head())\n\n# update value \ndf['median_income'] = converted\ndisplay(df.head())",
"_____no_output_____"
]
],
[
[
"### Converting numerical values to categories \n----\n\nDuring analysis, sometimes we want to classify our data into separate classes based on some criteria. For instance, we might want to separate these housing blocks into three distinct categories based on the median income of the households i.e.\n\n* High-incomes\n* Moderate-incomes\n* Low-incomes",
"_____no_output_____"
]
],
[
[
"def category(n):\n value = n / 10000\n if value > 10:\n return 'high-income'\n elif value > 2 and value < 10:\n return 'moderate-income'\n else: \n return 'low-income'\n \ncategories = df['median_income'].apply(category)\ndf['income-category'] = categories\ndisplay(df.head())\n\nprint(df['income-category'].value_counts())",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ada2e2767c5dcb05ace0f3779dbdc025537f10 | 203,570 | ipynb | Jupyter Notebook | Fabry Perot Cavity/FPMI_9.1_v1.0.ipynb | choudhary0parivesh/Finesse | fa1e6f077565ac4df18960669bbad0b54c2d7f05 | [
"MIT"
] | 2 | 2021-02-19T05:24:19.000Z | 2021-02-19T05:24:21.000Z | Fabry Perot Cavity/FPMI_9.1_v1.0.ipynb | choudhary0parivesh/Finesse | fa1e6f077565ac4df18960669bbad0b54c2d7f05 | [
"MIT"
] | null | null | null | Fabry Perot Cavity/FPMI_9.1_v1.0.ipynb | choudhary0parivesh/Finesse | fa1e6f077565ac4df18960669bbad0b54c2d7f05 | [
"MIT"
] | 1 | 2021-02-20T09:02:29.000Z | 2021-02-20T09:02:29.000Z | 63.161651 | 57,737 | 0.61426 | [
[
[
"\nfrom pykat import finesse \n \nfrom pykat.commands import * \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport scipy \nfrom IPython import display\n \n\npykat.init_pykat_plotting(dpi=200)",
"_____no_output_____"
],
[
"base1 = \"\"\"\n\nl L0 10 0 n0 #input laser\n\ntem L0 0 0 1 0 #tem modes\ntem L0 1 0 1 0 \ntem L0 2 0 1 0 \ntem L0 3 0 1 0 \ntem L0 4 0 1 0 \ntem L0 5 0 1 0 \ntem L0 6 0 1 0 \ntem L0 7 0 1 0 \n\n\ns s1 1 n0 n5 \n\nm itmx0 0 1 0 n5 n6 #ITM surface 1\ns itmx_l 0.035 1.44963 n6 n7 #thickness of mirror\nm2 itmx 0.99 50u 0 n7 n8 #ITM surface 2\n\ns s2 9.1 n8 n9 #cavity length\n\nm2 etmx 0.998 50u 0 n9 n10 #ETM surface 2\ns etmx_l 0.035 1.44963 n10 n11 #thickness of mirror\nm etmx0 0 1 0 n11 n12 #ETM surface 1\n\nattr etmx Rcx 34 #roc of mirror\nattr etmx Rcy 34\n\nxaxis etmx Rcx lin 20 40 6000\nfunc g = 1-(9.1/$x1)\n\n\nput etmx Rcy $x1\n\n\nad order0 0 0 0 n12 #ad detectors\nad order1 1 0 0 n12\nad order2 2 0 0 n12\nad order3 3 0 0 n12\nad order4 4 0 0 n12\nad order5 5 0 0 n12\nad order6 6 0 0 n12\nad order7 7 0 0 n12\n\n\n\ncav FP itmx n8 etmx n9\ncp FP x finesse\nmaxtem 7\nphase 2\n\n#noplot Rc2\n\"\"\"",
"_____no_output_____"
],
[
"basekat = finesse.kat() \nbasekat.verbose = 1\nbasekat.parse(base1)\n\nout = basekat.run()\nout.info()\n#out.plot(['FP_x_w'])",
"Parsing `tem L0 0 0 1 0` into pykat object not implemented yet, added as extra line.\nParsing `tem L0 1 0 1 0` into pykat object not implemented yet, added as extra line.\nParsing `tem L0 2 0 1 0` into pykat object not implemented yet, added as extra line.\nParsing `tem L0 3 0 1 0` into pykat object not implemented yet, added as extra line.\nParsing `tem L0 4 0 1 0` into pykat object not implemented yet, added as extra line.\nParsing `tem L0 5 0 1 0` into pykat object not implemented yet, added as extra line.\nParsing `tem L0 6 0 1 0` into pykat object not implemented yet, added as extra line.\nParsing `tem L0 7 0 1 0` into pykat object not implemented yet, added as extra line.\n--------------------------------------------------------------\nRunning kat - Started at 2021-07-05 03:01:54.118840\n"
],
[
"y=[]\nx= out['g']\ncolors = ['b','g','r','c','m','y','k','teal','violet','pink','olive']\n#plt.figure(figsize=(8,4))\n\n\n#append all output detectors in an array\nfor i in range(0,7,1):\n y.append(out['order'+str(i+1)]/out['order0'])\n\n\n#plot all outputs\nfor k in range(0,7,1):\n plt.semilogy(x,y[k],antialiased=False,label='order'+str(k),c=colors[k]) \n \n \n#label and other stuff\nplt.grid(linewidth=1)\nplt.legend([\"order1\",\"order2\",\"order3\",\"order4\",\"order5\",\"order6\",\"order7\",\"order8\",\"order9\",\"order10\"],loc='center left', bbox_to_anchor=(1, 0.5))\nplt.xlabel(\"g (1-L/R) \\n Finesse = \"+str(out['FP_x_finesse'][1]))\nplt.ylabel(\"HG modes intensity(rel to fund. mode)\",verticalalignment='center')\nplt.axvline(x = 0.708, color = 'r', linestyle = 'dashed')\nplt.axvline(x = 0.73, color = 'b', linestyle = 'dashed')",
"_____no_output_____"
],
[
"display.Image(\"C:/Users/Parivesh/Desktop/9.1m.jpg\",width = 500, height = 300)",
"_____no_output_____"
],
[
"base2 = \"\"\" \nl L0 10 0 n0 #input laser\ns s1 1 n0 n1 #laser cav\n\n\nbs bs1 0.5 0.5 0 0 n1 n2 n3 n4 #beam splitter\n\ns sx 1 n2 n5 #BS to ITMx cav\n\nm itmx0 0 1 0 n5 n6 #ITM surface 1\ns itmx_l 0.035 1.44963 n6 n7 #thickness of mirror\nm2 itmx 0.99 50u 0 n7 n8 #ITM surface 2\n\ns s2 9.1 n8 n9 #arm length\n\nm2 etmx 0.998 50u 0 n9 n10 #ETM surface 2 \ns etmx_l 0.035 1.44963 n10 n11 #thickness of mirror\nm etmx0 0 1 0 n11 dump #ETM surface 1\n\n\ns sy 1 n3 n13 #BS to ITMy cav\n\nm itmy0 0 1 0 n13 n14 \ns itmy_l 0.035 1.44963 n14 n15 \nm2 itmy 0.99 50u 0 n15 n16 \n\ns s3 9.1 n16 n17\n\nm2 etmy 0.998 50u 0 n17 n18\ns etmy_l 0.035 1.44963 n18 n19\nm etmy0 0 1 0 n19 n20\n\n \nattr etmy Rc 34 #roc of mirror\nattr etmx Rc 34\n\n\nxaxis etmy phi lin -220 220 7000\n\n#maxtem 7\n#phase 2\n\n\npd pd_out n4\n#ad order0 0 0 0 n20 #ad detectors\n#ad order1 1 0 0 n20\n#ad order2 2 0 0 n20\n\n\"\"\"",
"_____no_output_____"
],
[
"basekat1 = finesse.kat() \nbasekat1.verbose = 1\nbasekat1.parse(base2)\n\nout = basekat1.run()\n",
"--------------------------------------------------------------\nRunning kat - Started at 2021-07-05 02:59:41.829657\nUsed Finesse None at C:\\Users\\Parivesh\\anaconda3\\Library\\bin\\kat.exe\n"
],
[
"out.info()\nout.plot(['pd_out'])\n#out.plot(['order0','order1','order2'])\nprint(\"Contrast Ratio : \",(np.max(out['pd_out'])-np.min(out['pd_out']))/(np.max(out['pd_out'])+np.min(out['pd_out'])))",
"\n--- Output info ---\n\nRun date and time: 2021-07-05 02:59:41.830646\nDetectors used: pd_out\n\nOne xaxis used: ['xaxis etmy phi lin -220 220 7000']\npd_out : min = 2.898590799580060e-01 max = 4.348973420168640e+00\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0adae1c66710c7d2582477779b5e52d4cec5edc | 3,629 | ipynb | Jupyter Notebook | chapter4/04_05_special.ipynb | yoji-toriumi/Python_Data_Analysis | 17642dea87173530616c0b2fffcee600781915ea | [
"CC0-1.0"
] | null | null | null | chapter4/04_05_special.ipynb | yoji-toriumi/Python_Data_Analysis | 17642dea87173530616c0b2fffcee600781915ea | [
"CC0-1.0"
] | null | null | null | chapter4/04_05_special.ipynb | yoji-toriumi/Python_Data_Analysis | 17642dea87173530616c0b2fffcee600781915ea | [
"CC0-1.0"
] | null | null | null | 17.876847 | 90 | 0.500689 | [
[
[
"# 04_05: special arrays",
"_____no_output_____"
]
],
[
[
"import math\nimport collections\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as pp\n\n%matplotlib inline",
"_____no_output_____"
],
[
"discography = np.load('discography.npy')",
"_____no_output_____"
],
[
"discography",
"_____no_output_____"
],
[
"discography[0]",
"_____no_output_____"
],
[
"discography[0][0]",
"_____no_output_____"
],
[
"discography[0][1]",
"_____no_output_____"
],
[
"discography[0]['title']",
"_____no_output_____"
],
[
"discography['title']",
"_____no_output_____"
],
[
"minidisco = np.zeros(len(discography), dtype=[('title','U16'), ('release','M8[s]')])",
"_____no_output_____"
],
[
"minidisco['title'] = discography['title']\nminidisco['release'] = discography['release']",
"_____no_output_____"
],
[
"minidisco",
"_____no_output_____"
],
[
"np.datetime64('1969')",
"_____no_output_____"
],
[
"np.datetime64('1969-11-14')",
"_____no_output_____"
],
[
"np.datetime64('2015-02-03 12:00')",
"_____no_output_____"
],
[
"np.datetime64('2015-02-03 12:00') < np.datetime64('2015-02-03 18:00')",
"_____no_output_____"
],
[
"np.datetime64('2015-02-03 18:00') - np.datetime64('2015-02-03 12:00')",
"_____no_output_____"
],
[
"np.diff(discography['release'])",
"_____no_output_____"
],
[
"np.arange(np.datetime64('2015-02-03'), np.datetime64('2015-03-01'))",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0adb3da9b1fe88ea70a99ca26ff3fc7bc1f6270 | 289,553 | ipynb | Jupyter Notebook | jupyter_matlab/.ipynb_checkpoints/Chapter 5-checkpoint.ipynb | StaThin/statmat | f80eff25a09b78a923079db9658a5a96224b0dd9 | [
"MIT"
] | null | null | null | jupyter_matlab/.ipynb_checkpoints/Chapter 5-checkpoint.ipynb | StaThin/statmat | f80eff25a09b78a923079db9658a5a96224b0dd9 | [
"MIT"
] | null | null | null | jupyter_matlab/.ipynb_checkpoints/Chapter 5-checkpoint.ipynb | StaThin/statmat | f80eff25a09b78a923079db9658a5a96224b0dd9 | [
"MIT"
] | null | null | null | 208.311511 | 41,324 | 0.916267 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
d0adb5503751b2338cfa7a2be9a84ebaa4ca6a9b | 18,644 | ipynb | Jupyter Notebook | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning | 93a11b42f92eef4ca31147ffd79b3c2f2fe1815c | [
"MIT"
] | null | null | null | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning | 93a11b42f92eef4ca31147ffd79b3c2f2fe1815c | [
"MIT"
] | null | null | null | Neural Networks/Lesson 4 - Deep Learning with PyTorch/intro-to-pytorch/Part 1 - Tensors in PyTorch/Part 1 - Tensors in PyTorch (Exercises).ipynb | dilayercelik/AIPND-learning | 93a11b42f92eef4ca31147ffd79b3c2f2fe1815c | [
"MIT"
] | null | null | null | 38.680498 | 674 | 0.596278 | [
[
[
"-> Associated lecture videos: \n\nin Neural Networks/Lesson 4 - Deep Learning with PyTorch: video 4, video 5, video 6, video 7",
"_____no_output_____"
],
[
"# 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 vectors and 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 5 random normal variables (input features: x1, x2, x3, x4, x5 for each dataset example)\nfeatures = torch.randn((1, 5)) # creates a 2D tensor ('features') of random normal variables, of size (1, 5)\n# True weights for our data, random normal variables again\nweights = torch.randn_like(features) # creates a tensor ('weights') with same shape as the 'features' 2D tensor \n# and a true bias term\nbias = torch.randn((1, 1)) # a single random normal variable",
"_____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_____"
]
],
[
[
"## Calculate the output of this network using the weights and bias tensors\n\nh = torch.sum(features * weights) + bias\noutput_y = activation(h)\n \n# or using (features * weights).sum() instead of torch.sum() \n\n\n### Recall\n# features * weights -> this multiplies each element (5 in total) of 'features' with each element in 'weights'\n## This is called an 'element-wise' operation, here the operation being the multiplication\n\noutput_y",
"_____no_output_____"
]
],
[
[
"You can do the multiplication and sum in the same operation using a matrix multiplication, instead of writing `torch.sum(features * weights)`. 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)` 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\n**BEST OPTION:**\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_____"
]
],
[
[
"## Calculate the output of this network using matrix multiplication\n\nh = torch.mm(features, weights.view(5,1)) + bias\noutput_y = activation(h)\n\noutput_y",
"_____no_output_____"
]
],
[
[
"### Stack them up! -> Multilayer neural networks\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 top) 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: x1, x2 and x3\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_____"
]
],
[
[
"## Your solution here\n\nH = activation(torch.mm(features, W1) + B1) # 2D tensor (shape: 1,2) containing h1 and h2\noutput_y = activation(torch.mm(H, W2) + B2) # 1D tensor (shape: 1,1) containg the single ouput\n\noutput_y",
"_____no_output_____"
]
],
[
[
"If you did this correctly, you should see the output `tensor([[ 0.3171]])`.\n\nThe number of hidden units is 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 # a nd numpy array",
"_____no_output_____"
],
[
"b = torch.from_numpy(a)\nb # a 2D tensor",
"_____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 (symbol: _)\nb.mul_(2) # in place multiplication by 2",
"_____no_output_____"
],
[
"# Numpy array matches new values from Tensor b\na",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0adbb2995e1ee353f2ddf6102bb71871a42c68d | 29,568 | ipynb | Jupyter Notebook | L10_1.ipynb | m0fauzi/BEP2073_S21 | 7d5ef96251292d85ee05c4466e4ea7e8b139da09 | [
"CC0-1.0"
] | null | null | null | L10_1.ipynb | m0fauzi/BEP2073_S21 | 7d5ef96251292d85ee05c4466e4ea7e8b139da09 | [
"CC0-1.0"
] | null | null | null | L10_1.ipynb | m0fauzi/BEP2073_S21 | 7d5ef96251292d85ee05c4466e4ea7e8b139da09 | [
"CC0-1.0"
] | 1 | 2021-11-18T09:49:41.000Z | 2021-11-18T09:49:41.000Z | 128.556522 | 13,590 | 0.859104 | [
[
[
"<a href=\"https://colab.research.google.com/github/m0fauzi/BEP2073_S21/blob/main/L10_1.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 matplotlib.pyplot as plt\nimport scipy.optimize as so\nimport numpy as np\n\nData = pd.read_csv(r'data7_1.csv')\nX = Data.x\nY = Data.y\n\n\n'''\n\n\na_sol, a_cov = so.curve_fit(f, X, Y)\n'''",
"_____no_output_____"
],
[
"plt.plot(X,Y,'.r')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.grid()\nplt.title('Get data from csv file by using Pandas')",
"_____no_output_____"
],
[
"def f(x,a1,a2,a3):\n return a1*x + a2/x + a3*np.log(x)",
"_____no_output_____"
],
[
"a_sol, a_cov = so.curve_fit(f, X, Y)",
"_____no_output_____"
],
[
"print(a_sol)",
"[9.87537362 5.08640997 2.58182286]\n"
],
[
"print(a_cov)",
"[[ 3.48578775e-18 -3.67002247e-18 -9.68422163e-18]\n [-3.67002247e-18 4.24854667e-18 1.02134994e-17]\n [-9.68422163e-18 1.02134994e-17 2.72185752e-17]]\n"
],
[
"A1,A2,A3 = a_sol\nx = np.linspace(0,6,50)\nY_pred = f(x,A1,A2,A3)\n\nplt.plot(x,Y_pred,'-k')\nplt.plot(X,Y,'.r')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.grid()",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in true_divide\n \n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in log\n \n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in add\n \n"
],
[
"plt.plot(Y_tru,Y_pred)",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0add8c9582c202cf81cbc52714ba74aa594114f | 60,308 | ipynb | Jupyter Notebook | compare_numb.ipynb | kOllA666/ADMSync | ae0539ca3eda99d520c2356c7a677eb5a4014181 | [
"MIT"
] | 2 | 2021-04-10T21:24:17.000Z | 2021-04-11T20:00:20.000Z | compare_numb.ipynb | kOllA666/ADMSync | ae0539ca3eda99d520c2356c7a677eb5a4014181 | [
"MIT"
] | 2 | 2021-04-10T21:28:54.000Z | 2021-04-23T10:12:42.000Z | compare_numb.ipynb | kOllA666/ADMSync | ae0539ca3eda99d520c2356c7a677eb5a4014181 | [
"MIT"
] | 1 | 2021-04-10T21:38:34.000Z | 2021-04-10T21:38:34.000Z | 52.624782 | 225 | 0.297357 | [
[
[
"<a href=\"https://colab.research.google.com/github/kOllA666/ADMSync/blob/main/compare_numb.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras",
"_____no_output_____"
],
[
"model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])",
"_____no_output_____"
],
[
"model.compile(optimizer='sgd', loss='mean_squared_error')",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"ys = np.array([-2.0, 2.0, 5.0, 8.0, 11.0, 14.0], dtype=float)\nxs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)\n",
"_____no_output_____"
],
[
"model.fit(ys, xs, epochs=500)",
"Epoch 1/500\n1/1 [==============================] - 0s 4ms/step - loss: 631.8768\nEpoch 2/500\n1/1 [==============================] - 0s 3ms/step - loss: 98.1415\nEpoch 3/500\n1/1 [==============================] - 0s 3ms/step - loss: 16.2327\nEpoch 4/500\n1/1 [==============================] - 0s 3ms/step - loss: 3.6465\nEpoch 5/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.6964\nEpoch 6/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.3785\nEpoch 7/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.3114\nEpoch 8/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.2830\nEpoch 9/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.2609\nEpoch 10/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.2400\nEpoch 11/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.2196\nEpoch 12/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.1995\nEpoch 13/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.1798\nEpoch 14/500\n1/1 [==============================] - 0s 3ms/step - loss: 1.1605\nEpoch 15/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.1414\nEpoch 16/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.1227\nEpoch 17/500\n1/1 [==============================] - 0s 9ms/step - loss: 1.1042\nEpoch 18/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.0861\nEpoch 19/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.0683\nEpoch 20/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.0507\nEpoch 21/500\n1/1 [==============================] - 0s 4ms/step - loss: 1.0335\nEpoch 22/500\n1/1 [==============================] - 0s 5ms/step - loss: 1.0165\nEpoch 23/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.9999\nEpoch 24/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.9834\nEpoch 25/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.9673\nEpoch 26/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.9515\nEpoch 27/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.9359\nEpoch 28/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.9205\nEpoch 29/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.9054\nEpoch 30/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.8906\nEpoch 31/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.8760\nEpoch 32/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.8616\nEpoch 33/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.8475\nEpoch 34/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.8336\nEpoch 35/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.8200\nEpoch 36/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.8065\nEpoch 37/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.7933\nEpoch 38/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.7804\nEpoch 39/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.7676\nEpoch 40/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.7550\nEpoch 41/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.7427\nEpoch 42/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.7305\nEpoch 43/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.7186\nEpoch 44/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.7068\nEpoch 45/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.6953\nEpoch 46/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.6839\nEpoch 47/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.6727\nEpoch 48/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.6617\nEpoch 49/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.6509\nEpoch 50/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.6403\nEpoch 51/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.6298\nEpoch 52/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.6195\nEpoch 53/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.6094\nEpoch 54/500\n1/1 [==============================] - 0s 32ms/step - loss: 0.5995\nEpoch 55/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.5897\nEpoch 56/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.5801\nEpoch 57/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.5706\nEpoch 58/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.5613\nEpoch 59/500\n1/1 [==============================] - 0s 13ms/step - loss: 0.5522\nEpoch 60/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.5432\nEpoch 61/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.5343\nEpoch 62/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.5256\nEpoch 63/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.5171\nEpoch 64/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.5086\nEpoch 65/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.5004\nEpoch 66/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.4922\nEpoch 67/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.4842\nEpoch 68/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.4763\nEpoch 69/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.4686\nEpoch 70/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.4610\nEpoch 71/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.4535\nEpoch 72/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.4461\nEpoch 73/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.4389\nEpoch 74/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.4317\nEpoch 75/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.4247\nEpoch 76/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.4178\nEpoch 77/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.4111\nEpoch 78/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.4044\nEpoch 79/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.3978\nEpoch 80/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.3914\nEpoch 81/500\n1/1 [==============================] - 0s 43ms/step - loss: 0.3851\nEpoch 82/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.3788\nEpoch 83/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.3727\nEpoch 84/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.3667\nEpoch 85/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.3607\nEpoch 86/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.3549\nEpoch 87/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.3492\nEpoch 88/500\n1/1 [==============================] - 0s 12ms/step - loss: 0.3435\nEpoch 89/500\n1/1 [==============================] - 0s 13ms/step - loss: 0.3380\nEpoch 90/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.3325\nEpoch 91/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.3271\nEpoch 92/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.3219\nEpoch 93/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.3167\nEpoch 94/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.3116\nEpoch 95/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.3066\nEpoch 96/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.3016\nEpoch 97/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.2968\nEpoch 98/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.2920\nEpoch 99/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.2873\nEpoch 100/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2827\nEpoch 101/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2781\nEpoch 102/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2737\nEpoch 103/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.2693\nEpoch 104/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.2649\nEpoch 105/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.2607\nEpoch 106/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2565\nEpoch 107/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.2524\nEpoch 108/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.2484\nEpoch 109/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.2444\nEpoch 110/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2405\nEpoch 111/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2366\nEpoch 112/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2329\nEpoch 113/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2291\nEpoch 114/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2255\nEpoch 115/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2219\nEpoch 116/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2184\nEpoch 117/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2149\nEpoch 118/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.2115\nEpoch 119/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.2081\nEpoch 120/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.2048\nEpoch 121/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.2015\nEpoch 122/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1983\nEpoch 123/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1952\nEpoch 124/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1921\nEpoch 125/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1890\nEpoch 126/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1860\nEpoch 127/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1831\nEpoch 128/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.1802\nEpoch 129/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1774\nEpoch 130/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.1746\nEpoch 131/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1718\nEpoch 132/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1691\nEpoch 133/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1664\nEpoch 134/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1638\nEpoch 135/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1612\nEpoch 136/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1587\nEpoch 137/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1562\nEpoch 138/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1538\nEpoch 139/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1513\nEpoch 140/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1490\nEpoch 141/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1466\nEpoch 142/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1444\nEpoch 143/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.1421\nEpoch 144/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1399\nEpoch 145/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1377\nEpoch 146/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1356\nEpoch 147/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1334\nEpoch 148/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1314\nEpoch 149/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1293\nEpoch 150/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1273\nEpoch 151/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.1254\nEpoch 152/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1234\nEpoch 153/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.1215\nEpoch 154/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.1196\nEpoch 155/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1178\nEpoch 156/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.1160\nEpoch 157/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.1142\nEpoch 158/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1124\nEpoch 159/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.1107\nEpoch 160/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.1090\nEpoch 161/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.1073\nEpoch 162/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.1057\nEpoch 163/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1041\nEpoch 164/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.1025\nEpoch 165/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.1009\nEpoch 166/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0994\nEpoch 167/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0979\nEpoch 168/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0964\nEpoch 169/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0949\nEpoch 170/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0935\nEpoch 171/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0921\nEpoch 172/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0907\nEpoch 173/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0893\nEpoch 174/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0880\nEpoch 175/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0867\nEpoch 176/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0853\nEpoch 177/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0841\nEpoch 178/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0828\nEpoch 179/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0816\nEpoch 180/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0804\nEpoch 181/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0792\nEpoch 182/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0780\nEpoch 183/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0768\nEpoch 184/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0757\nEpoch 185/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0746\nEpoch 186/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0735\nEpoch 187/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0724\nEpoch 188/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0713\nEpoch 189/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0703\nEpoch 190/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0692\nEpoch 191/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0682\nEpoch 192/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0672\nEpoch 193/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0663\nEpoch 194/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0653\nEpoch 195/500\n1/1 [==============================] - 0s 16ms/step - loss: 0.0643\nEpoch 196/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0634\nEpoch 197/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0625\nEpoch 198/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0616\nEpoch 199/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0607\nEpoch 200/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0598\nEpoch 201/500\n1/1 [==============================] - 0s 25ms/step - loss: 0.0590\nEpoch 202/500\n1/1 [==============================] - 0s 18ms/step - loss: 0.0581\nEpoch 203/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0573\nEpoch 204/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0565\nEpoch 205/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0557\nEpoch 206/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0549\nEpoch 207/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0541\nEpoch 208/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0534\nEpoch 209/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0526\nEpoch 210/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0519\nEpoch 211/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0512\nEpoch 212/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0504\nEpoch 213/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0497\nEpoch 214/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0491\nEpoch 215/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0484\nEpoch 216/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0477\nEpoch 217/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0470\nEpoch 218/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0464\nEpoch 219/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0458\nEpoch 220/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0451\nEpoch 221/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0445\nEpoch 222/500\n1/1 [==============================] - 0s 15ms/step - loss: 0.0439\nEpoch 223/500\n1/1 [==============================] - 0s 16ms/step - loss: 0.0433\nEpoch 224/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0427\nEpoch 225/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0422\nEpoch 226/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0416\nEpoch 227/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0411\nEpoch 228/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0405\nEpoch 229/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0400\nEpoch 230/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0394\nEpoch 231/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0389\nEpoch 232/500\n1/1 [==============================] - 0s 20ms/step - loss: 0.0384\nEpoch 233/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0379\nEpoch 234/500\n1/1 [==============================] - 0s 13ms/step - loss: 0.0374\nEpoch 235/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0369\nEpoch 236/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0364\nEpoch 237/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0360\nEpoch 238/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0355\nEpoch 239/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0351\nEpoch 240/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0346\nEpoch 241/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0342\nEpoch 242/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0337\nEpoch 243/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0333\nEpoch 244/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0329\nEpoch 245/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0325\nEpoch 246/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0321\nEpoch 247/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0317\nEpoch 248/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0313\nEpoch 249/500\n1/1 [==============================] - 0s 20ms/step - loss: 0.0309\nEpoch 250/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0305\nEpoch 251/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0302\nEpoch 252/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0298\nEpoch 253/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0294\nEpoch 254/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0291\nEpoch 255/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0287\nEpoch 256/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0284\nEpoch 257/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0280\nEpoch 258/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0277\nEpoch 259/500\n1/1 [==============================] - 0s 21ms/step - loss: 0.0274\nEpoch 260/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0271\nEpoch 261/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0268\nEpoch 262/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0264\nEpoch 263/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0261\nEpoch 264/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0258\nEpoch 265/500\n1/1 [==============================] - 0s 17ms/step - loss: 0.0255\nEpoch 266/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0253\nEpoch 267/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0250\nEpoch 268/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0247\nEpoch 269/500\n1/1 [==============================] - 0s 16ms/step - loss: 0.0244\nEpoch 270/500\n1/1 [==============================] - 0s 15ms/step - loss: 0.0241\nEpoch 271/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0239\nEpoch 272/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0236\nEpoch 273/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0234\nEpoch 274/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0231\nEpoch 275/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0229\nEpoch 276/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0226\nEpoch 277/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0224\nEpoch 278/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0221\nEpoch 279/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0219\nEpoch 280/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0217\nEpoch 281/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0214\nEpoch 282/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0212\nEpoch 283/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0210\nEpoch 284/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0208\nEpoch 285/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0206\nEpoch 286/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0204\nEpoch 287/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0202\nEpoch 288/500\n1/1 [==============================] - 0s 30ms/step - loss: 0.0200\nEpoch 289/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0198\nEpoch 290/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0196\nEpoch 291/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0194\nEpoch 292/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0192\nEpoch 293/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0190\nEpoch 294/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0188\nEpoch 295/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0186\nEpoch 296/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0185\nEpoch 297/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0183\nEpoch 298/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0181\nEpoch 299/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0180\nEpoch 300/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0178\nEpoch 301/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0176\nEpoch 302/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0175\nEpoch 303/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0173\nEpoch 304/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0172\nEpoch 305/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0170\nEpoch 306/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0169\nEpoch 307/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0167\nEpoch 308/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0166\nEpoch 309/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0164\nEpoch 310/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0163\nEpoch 311/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0162\nEpoch 312/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0160\nEpoch 313/500\n1/1 [==============================] - 0s 12ms/step - loss: 0.0159\nEpoch 314/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0158\nEpoch 315/500\n1/1 [==============================] - 0s 17ms/step - loss: 0.0156\nEpoch 316/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0155\nEpoch 317/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0154\nEpoch 318/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0153\nEpoch 319/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0151\nEpoch 320/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0150\nEpoch 321/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0149\nEpoch 322/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0148\nEpoch 323/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0147\nEpoch 324/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0146\nEpoch 325/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0145\nEpoch 326/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0144\nEpoch 327/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0142\nEpoch 328/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0141\nEpoch 329/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0140\nEpoch 330/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0139\nEpoch 331/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0138\nEpoch 332/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0137\nEpoch 333/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0137\nEpoch 334/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0136\nEpoch 335/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0135\nEpoch 336/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0134\nEpoch 337/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0133\nEpoch 338/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0132\nEpoch 339/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0131\nEpoch 340/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0130\nEpoch 341/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0129\nEpoch 342/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0129\nEpoch 343/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0128\nEpoch 344/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0127\nEpoch 345/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0126\nEpoch 346/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0126\nEpoch 347/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0125\nEpoch 348/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0124\nEpoch 349/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0123\nEpoch 350/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0123\nEpoch 351/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0122\nEpoch 352/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0121\nEpoch 353/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0121\nEpoch 354/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0120\nEpoch 355/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0119\nEpoch 356/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0119\nEpoch 357/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0118\nEpoch 358/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0117\nEpoch 359/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0117\nEpoch 360/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0116\nEpoch 361/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0115\nEpoch 362/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0115\nEpoch 363/500\n1/1 [==============================] - 0s 16ms/step - loss: 0.0114\nEpoch 364/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0114\nEpoch 365/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0113\nEpoch 366/500\n1/1 [==============================] - 0s 13ms/step - loss: 0.0113\nEpoch 367/500\n1/1 [==============================] - 0s 12ms/step - loss: 0.0112\nEpoch 368/500\n1/1 [==============================] - 0s 94ms/step - loss: 0.0112\nEpoch 369/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0111\nEpoch 370/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0111\nEpoch 371/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0110\nEpoch 372/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0110\nEpoch 373/500\n1/1 [==============================] - 0s 11ms/step - loss: 0.0109\nEpoch 374/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0109\nEpoch 375/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0108\nEpoch 376/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0108\nEpoch 377/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0107\nEpoch 378/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0107\nEpoch 379/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0106\nEpoch 380/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0106\nEpoch 381/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0105\nEpoch 382/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0105\nEpoch 383/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0105\nEpoch 384/500\n1/1 [==============================] - 0s 14ms/step - loss: 0.0104\nEpoch 385/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0104\nEpoch 386/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0103\nEpoch 387/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0103\nEpoch 388/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0103\nEpoch 389/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0102\nEpoch 390/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0102\nEpoch 391/500\n1/1 [==============================] - 0s 51ms/step - loss: 0.0102\nEpoch 392/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0101\nEpoch 393/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0101\nEpoch 394/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0101\nEpoch 395/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0100\nEpoch 396/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0100\nEpoch 397/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0100\nEpoch 398/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0099\nEpoch 399/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0099\nEpoch 400/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0099\nEpoch 401/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0098\nEpoch 402/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0098\nEpoch 403/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0098\nEpoch 404/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0097\nEpoch 405/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0097\nEpoch 406/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0097\nEpoch 407/500\n1/1 [==============================] - 0s 15ms/step - loss: 0.0097\nEpoch 408/500\n1/1 [==============================] - 0s 14ms/step - loss: 0.0096\nEpoch 409/500\n1/1 [==============================] - 0s 17ms/step - loss: 0.0096\nEpoch 410/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0096\nEpoch 411/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0095\nEpoch 412/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0095\nEpoch 413/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0095\nEpoch 414/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0095\nEpoch 415/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0094\nEpoch 416/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0094\nEpoch 417/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0094\nEpoch 418/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0094\nEpoch 419/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0094\nEpoch 420/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0093\nEpoch 421/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0093\nEpoch 422/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0093\nEpoch 423/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0093\nEpoch 424/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0092\nEpoch 425/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0092\nEpoch 426/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0092\nEpoch 427/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0092\nEpoch 428/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0092\nEpoch 429/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0092\nEpoch 430/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0091\nEpoch 431/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0091\nEpoch 432/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0091\nEpoch 433/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0091\nEpoch 434/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0091\nEpoch 435/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0090\nEpoch 436/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0090\nEpoch 437/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0090\nEpoch 438/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0090\nEpoch 439/500\n1/1 [==============================] - 0s 9ms/step - loss: 0.0090\nEpoch 440/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0090\nEpoch 441/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0089\nEpoch 442/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0089\nEpoch 443/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0089\nEpoch 444/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0089\nEpoch 445/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0089\nEpoch 446/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0089\nEpoch 447/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0089\nEpoch 448/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0088\nEpoch 449/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0088\nEpoch 450/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0088\nEpoch 451/500\n1/1 [==============================] - 0s 16ms/step - loss: 0.0088\nEpoch 452/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0088\nEpoch 453/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0088\nEpoch 454/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0088\nEpoch 455/500\n1/1 [==============================] - 0s 16ms/step - loss: 0.0088\nEpoch 456/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0087\nEpoch 457/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0087\nEpoch 458/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0087\nEpoch 459/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0087\nEpoch 460/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0087\nEpoch 461/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0087\nEpoch 462/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0087\nEpoch 463/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0087\nEpoch 464/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0086\nEpoch 465/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0086\nEpoch 466/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0086\nEpoch 467/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0086\nEpoch 468/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0086\nEpoch 469/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0086\nEpoch 470/500\n1/1 [==============================] - 0s 10ms/step - loss: 0.0086\nEpoch 471/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0086\nEpoch 472/500\n1/1 [==============================] - 0s 12ms/step - loss: 0.0086\nEpoch 473/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0086\nEpoch 474/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0086\nEpoch 475/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0085\nEpoch 476/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 477/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 478/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 479/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 480/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0085\nEpoch 481/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 482/500\n1/1 [==============================] - 0s 7ms/step - loss: 0.0085\nEpoch 483/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 484/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 485/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 486/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0085\nEpoch 487/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0084\nEpoch 488/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0084\nEpoch 489/500\n1/1 [==============================] - 0s 4ms/step - loss: 0.0084\nEpoch 490/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0084\nEpoch 491/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0084\nEpoch 492/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0084\nEpoch 493/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0084\nEpoch 494/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0084\nEpoch 495/500\n1/1 [==============================] - 0s 5ms/step - loss: 0.0084\nEpoch 496/500\n1/1 [==============================] - 0s 8ms/step - loss: 0.0084\nEpoch 497/500\n1/1 [==============================] - 0s 6ms/step - loss: 0.0084\nEpoch 498/500\n1/1 [==============================] - 0s 21ms/step - loss: 0.0084\nEpoch 499/500\n1/1 [==============================] - 0s 14ms/step - loss: 0.0084\nEpoch 500/500\n1/1 [==============================] - 0s 3ms/step - loss: 0.0084\n"
],
[
"print(model.predict([11.0]))",
"[[2.9803178]]\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0adf2a66540ed3adcd62d88be4ac3cfe5f3f0e5 | 83,497 | ipynb | Jupyter Notebook | notebooks uni/PC07 - Iterations.ipynb | tintin10q/RandomPythonProjects | f7a026f919d3b80a97060b56bb3fcf96b3c44b23 | [
"MIT"
] | null | null | null | notebooks uni/PC07 - Iterations.ipynb | tintin10q/RandomPythonProjects | f7a026f919d3b80a97060b56bb3fcf96b3c44b23 | [
"MIT"
] | null | null | null | notebooks uni/PC07 - Iterations.ipynb | tintin10q/RandomPythonProjects | f7a026f919d3b80a97060b56bb3fcf96b3c44b23 | [
"MIT"
] | 1 | 2020-06-03T21:50:36.000Z | 2020-06-03T21:50:36.000Z | 41.79029 | 876 | 0.626226 | [
[
[
"# Chapter 7 - Iterations\n",
"_____no_output_____"
],
[
"-------------------------------",
"_____no_output_____"
],
[
"Computers do not get bored. If you want the computer to repeat a certain task hundreds of thousands of times, it does not protest. Humans hate too much repetition. Therefore, repetitious tasks should be performed by computers. All programming languages support repetitions. The general class of programming constructs that allow the definition of repetitions are called \"iterations\". A term which is even more common for such tasks is \"loops\".\n\nThis chapter explains all you need to know about loops in Python. Students who are completely new to programming often find loops the first really hard topic in programming that they encounter. If that is the case for you, then make sure you take your time for this chapter, and work on it until you understand it completely. Loops are such a basic concept in programming that you need to understand them in all their details. Each and every chapter after this one needs loops.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"## `while` loop",
"_____no_output_____"
],
[
"Suppose you have to ask the user for five numbers, then add them up, and show the total. With the material from the previous chapter, you would program that as follows:",
"_____no_output_____"
]
],
[
[
"from pcinput import getInteger\n\nnum1 = getInteger( \"Number 1: \" )\nnum2 = getInteger( \"Number 2: \" )\nnum3 = getInteger( \"Number 3: \" )\nnum4 = getInteger( \"Number 4: \" )\nnum5 = getInteger( \"Number 5: \" )\n\nprint( \"Total is\", num1 + num2 + num3 + num4 + num5 )",
"_____no_output_____"
]
],
[
[
"But what if I want you to ask the user for 500 numbers? Are you going to create a block of code of more than 500 lines long? Surely there must be an easier way to do this?\n\nOf course there is. You can use a loop to do this. \n\nThe first loop I am going to present to you is the `while` loop. A `while` statement is quite similar to an `if` statement. The syntax is:\n\n while <boolean expression>:\n <statements>\n\nJust like an `if` statement, the `while` statement tests a boolean expression, and if the expression evaluates to `True`, it executes the code block below it. However, contrary to the `if` statement, once the code block has finished, the code \"loops\" back to the boolean expression to test it again. If it still evaluates to `True`, the code block below it gets executed once more. And after it has finished, it loops back again, and again, and again...\n\nNote: if the boolean expression immediately evaluates to `False`, then the code block below the `while` is skipped completely, just like with an `if` statement.",
"_____no_output_____"
],
[
"### `while` loop, first example",
"_____no_output_____"
],
[
"Let's take a simple example: printing the numbers 1 to 5. With a `while` loop, that can be done as follows:",
"_____no_output_____"
]
],
[
[
"num = 1\nwhile num <= 5:\n print( num )\n num += 1\nprint( \"Done\" )",
"_____no_output_____"
]
],
[
[
"This code is represented by the flow chart below.\n\n<img src=\"img/Chart4en.png\" alt=\"Simple while-loop\" style=\"width:300px;\"><br>\n<div align=\"center\">Figure 7.1: Simple while-loop.</div>",
"_____no_output_____"
],
[
"It is crucial that you understand this code, so let's discuss it step by step.\n\nThe first line initializes a variable `num`. This is the variable that the code will print, so it is initialized to `1`, as `1` is the first value that must be printed.\n\nThen the `while` loop starts. The boolean expression says `num <= 5`. Since `num` is `1`, and `1` is actually smaller than (or equal to) `5`, the boolean expression evaluates to `True`. Therefore, the code block below the `while` gets executed.\n\nThe first line of the code block below the `while` prints the value of `num`, which is `1`. The second line adds `1` to the value of `num`, which makes `num` hold the value `2`. Then the code loops back to the boolean expression (i.e., the last line of the code, the printing of \"Done\", is not executed as it is not part of the loop and the loop has not finished yet).\n\nSince `num` is `2`, the boolean expression still evaluates to `True`. The code block gets executed once more. `2` is displayed, `num` gets the value `3`, and the code loops back to the boolean expression.\n\nSince `num` is `3`, the boolean expression still evaluates to `True`. The code block gets executed once more. `3` is displayed, `num` gets the value `4`, and the code loops back to the boolean expression.\n\nSince `num` is `4`, the boolean expression still evaluates to `True`. The code block gets executed once more. `4` is displayed, `num` gets the value `5`, and the code loops back to the boolean expression.\n\nSince `num` is `5`, the boolean expression still evaluates to `True` (because `5 <= 5`). The code block gets executed once more. `5` is displayed, `num` gets the value `6`, and the code loops back to the boolean expression.\n\nSince `num` is `6`, the boolean expression now evaluates to `False` (because `6` is bigger than `5`). Therefore, the code block gets skipped, and the code continues with the first line below the code block, which is the last line of the code. The word `Done` is printed, and the code ends.\n\n**Exercise**: Change the code above so that it prints the numbers 1, 3, 5, 7, and 9.",
"_____no_output_____"
],
[
"### `while` loop, second example",
"_____no_output_____"
],
[
"If you understand the first example, you probably also understand how to ask the user for five numbers and print the total. This is implemented as follows:",
"_____no_output_____"
]
],
[
[
"from pcinput import getInteger\n\ntotal = 0\ncount = 0\nwhile count < 5:\n total += getInteger( \"Please give a number: \" )\n count += 1\n\nprint( \"Total is\", total )",
"_____no_output_____"
]
],
[
[
"Study this code closely. There are two variables used. `total` is used to add up the five numbers that the user enters. It is started at zero, as at the start of the code the user has not yet entered any numbers, so the total is still zero. `count` is used to count how often the code has gone through the loop. Since the loop must be done five times, `count` is started at `0` and the boolean expression for the loop continues until `count` is `5` (or higher). Thus, in the loop `count` gets increased by `1` at the end of every cycle through the loop.\n\nYou may wonder why `count` is started at `0` and the boolean expression checks if `count < 5`. Why not start `count` at `1` and check if `count <= 5`? The reason is convention: programmers are used to start indices at `0`, and if they count, they count \"up to but not including\". When you continue with programming, you will find that most code sticks to this convention. Most standard programming constructs that use indices or count things apply this convention too. My advice is therefore that you get used to it, as it makes code easier to read.\n\nNote: The variable `count` is what programmers call a \"throw-away variable\". Its only purpose is to count how often the loop has been cycled through, and it has no real meaning before the loop, in the loop, or after the loop has ended. Programmers often choose a single-character variable name for such a variable, usually `i` or `j`. In this example I chose the name `count` because it is illustrative of what the variable does for the code, but a single-character name for this variable would have been acceptable.\n\n**Exercise**: Change the code block above so that it not only prints the total, but also the average of the five numbers.\n\n**Exercise**: The first code block of this chapter also asks the user for five numbers, and prints the total. However, that code block uses \"Enter number *x*: \" as a prompt, whereby *x* is a digit. Can you change the code block above so that it also uses such a changing prompt to ask for each number? Hint: you can construct a string that represents the prompt by adding a couple of strings together; remember that you can use the `str()` function to turn a number into a string.",
"_____no_output_____"
],
[
"### Putting the `while` loop under user control",
"_____no_output_____"
],
[
"Suppose that, in the second example, you do not want the user to be restricted to entering exactly five numbers. You want the user to enter as many numbers as he wants, including none. This means that you cannot predict how many iterations through the `while` loop are needed. Instead, it is the user who controls when the loop ends. You therefore have to give the user the means to indicate that the loop should end. \n\nThe code block below shows how to use a `while` loop to allow the user to enter numbers as long as he wants, until he enters a zero. Once a zero is entered, the total is printed, and the program ends.",
"_____no_output_____"
]
],
[
[
"from pcinput import getInteger\n\nnum = -1\ntotal = 0\nwhile num != 0:\n num = getInteger( \"Enter a number: \" )\n total += num\nprint( \"Total is\", total )",
"_____no_output_____"
]
],
[
[
"This code works, but there are (at least) two ugly things about it. First, `num` is initialized to `-1`. The `-1` is meaningless, I just needed an initialization that would ensure that the `while` loop would be entered at least once. Second, when the user enters zero, `total` still gets increased by `num`. Since `num` is zero at that point, it does not matter for the total, but if I wanted the user to end the program by typing something else (for instance, a negative number), then `total` would now hold the wrong value.\n\nBecause of these ugly elements, some programmers prefer to write this code as follows:",
"_____no_output_____"
]
],
[
[
"from pcinput import getInteger\n\nnum = getInteger( \"Enter a number: \" )\ntotal = 0\nwhile num != 0:\n total += num\n num = getInteger( \"Enter a number: \" )\nprint( \"Total is\", total )",
"_____no_output_____"
]
],
[
[
"This solves the ugly parts from the previous code, but introduces something new that is ugly, namely the repetition of the `getInteger()` function. How this can be solved follows at the end of this chapter. For now, make sure that you understand how `while` loops work.",
"_____no_output_____"
],
[
"### Endless loops",
"_____no_output_____"
],
[
"The code below is supposed to start at number 1, and add up numbers, until it encounters a number that, when squared, is dividable by 1000. The code contains an error, though. See if you can spot it (without running the code!).",
"_____no_output_____"
]
],
[
[
"number = 1\ntotal = 0\nwhile (number * number) % 1000 != 0:\n total += number\nprint( \"Total is\", total )",
"_____no_output_____"
]
],
[
[
"The heading of this subsection gave away the answer, of course: this code contains a loop that never terminates. If you run it, it looks like the program \"hangs\", i.e., sits there and does nothing. It is not doing nothing, it is actually highly active, but it is in a neverending addition. `number` starts at `1`, and is never increased in the loop, so the boolean expression will always be `True`. This is called an \"endless loop\", and it is the single one great danger in using `while` loops.\n\nIf you did run this code, you can go the the \"Kernel\" menu and choose \"Interrupt\". If you ran the code without modifications, you will have to do that. \n\nIf you did not spot that this is an example of an endless loop, you might have seen what happened if I had written code that prints something in the loop. Unfortunately, browsers tend not to handle notebooks that print a lot of stuff well, and you would probably need a reboot of your computer, or at least the shutdown of the browser via a task manager, to resolve the problem. That's not very nice, so I did not do that.\n\nSince every programmer writes endless loops by accident now and again, it is good practice when you program a loop to immediately add a statement to a loop that makes a change that is tested in the boolean expression, so that you do not forget about it.\n\nShould you still write an endless loop and have troubles interrupting the kernel, if you are on the notebook server the instructor can shut down your kernel for you.\n\n**Exercise**: Fix the code above so that it no longer is an endless loop.",
"_____no_output_____"
],
[
"### `while` loop practice exercises",
"_____no_output_____"
],
[
"You should now practice a bit with simple `while` loops.\n\n**Exercise**: In the code block below, write a countdown function. It starts with a given number (in this case 10, but you should be able to change it), and counts down to zero, printing each number it encounters (10, 9, 8, ...). It does not print `0`, instead it prints \"Blast off!\".",
"_____no_output_____"
]
],
[
[
"# Countdown.\ncount = 10\n",
"_____no_output_____"
]
],
[
[
"**Exercise**: The factorial of a positive integer is that integer, multiplied by all positive integers that are lower (excluding zero). You write the factorial as the number with an exclamation mark after it. E.g., the factorial of 5 is `5! = 5 * 4 * 3 * 2 * 1 = 120`. Write some code that calculates the factorial of a number. The number is given here as `num`. You can try out different values for `num`, but do not make them too high, as factorials grow exponentially. Hint: to do this with a `while` loop, you need at least one more variable.",
"_____no_output_____"
]
],
[
[
"# Factorial.\nnum = 5\n",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## `for` loop",
"_____no_output_____"
],
[
"An alternative way of implementing loops is by using a `for` loop. `for` loops tends to be easier and safer to use than `while` loops, but cannot be applied to all iteration problems. `while` loops are more general. In other words, everything that a `for` loop can do, a `while` loop can do too, but not the other way around.\n\nThe syntax of a `for` loop is as follows:\n\n for <variable> in <collection>:\n <statements>\n\nA `for` loop gets presented with a collection of items, and it will process these items, in order, one by one. Every cycle through the loop will put one item in the variable given next to the `for`, and can then be used in the code block under the `for`. The variable does *not* need to exist before the `for` loop is encountered. If it does, it gets overwritten. It is a real variable, by the way, in the sense that it still exists after the loop has finished. It will contain the last value that it got assigned during the processing of the loop.\n\nAt this point you might wonder what a \"collection\" is. There are many different kinds of collections in Python, and in this section I will introduce a few. In later chapters collections will be discussed in more detail.",
"_____no_output_____"
],
[
"### `for` loop with strings",
"_____no_output_____"
],
[
"The only collection introduced until now is the string. A string is a collection of characters, e.g., the string \"banana\" is a collection of the characters \"b\", \"a\", \"n\", \"a\", \"n\", and \"a\", in that specific order. The following code loops through each of these letters:",
"_____no_output_____"
]
],
[
[
"for letter in \"banana\":\n print( letter )\nprint( \"Done\" )",
"_____no_output_____"
]
],
[
[
"While this code is fairly trivial, let's go through it step by step.\n\nWhen the `for` loop is encountered, Python takes the collection (i.e., the string \"banana\") and turns it into an \"iterable\". What that is exactly I will get to in a later chapter, but for now assume that it is a list of all the letters in the string, in the order that they appear in the string. Python then takes the first of those letters, and puts it in the variable `letter`. It then executes the code block below the `for`.\n\nThe code block contains only one statement, which is the printing of `letter`. So the program prints \"b\", and then loops back to the `for`. \n\nPython then takes the next letter, which is an \"a\", and it executes the code block with `letter` being an \"a\". \n\nIt then repeats this process for each of the remaining letters.\n\nOnce all the letters have been used, the `for` loop ends, and Python executes the last line of the code, which is the printing of the word \"Done\".\n\nTo be absolutely clear: In a `for` loop you do *not* have to write code that explicitly increases some kind of variable that then grabs the next letter, or something like that. The `for` statement handles that automatically: every time it is looped back to, it takes the next item from the collection. ",
"_____no_output_____"
],
[
"### `for` loop using a variable as collection",
"_____no_output_____"
],
[
"In the code above, the literal string \"banana\" was used as the collection, but it could also be a variable that contains a string. For instance, the following code runs similar to the previous code:",
"_____no_output_____"
]
],
[
[
"fruit = \"banana\"\nfor letter in fruit:\n print( letter )\nprint( \"Done\" )",
"_____no_output_____"
]
],
[
[
"You might wonder if this isn't dangerous. What happens if the programmer changes the contents of the variable `fruit` *in* the loop's code block? Let's try that out:",
"_____no_output_____"
]
],
[
[
"fruit = \"banana\"\nfor letter in fruit:\n print( letter )\n if letter == \"n\":\n fruit = \"orange\"\nprint( \"Done\" )",
"_____no_output_____"
]
],
[
[
"As you can see when you run this code, changing the contents of the variable `fruit` in the loop has *no effect* on the loop's processing. The sequence of characters that the loop processes is only constituted once, when the `for` loop is first entered. This is a great feature of `for` loops, because it means they are *guaranteed* to end. No `for` loops are endless! (Unfortunately, I will have to revise this statement in a much later chapter, but it requires knowledge of pretty advanced Python to create an endless `for` loop -- for now, and in general practice, you may assume that `for` loops are guaranteed to end.)\n\nNote that there is a conditional statement in the loop above. There is nothing that stops you from putting conditions in the code block for a loop. There is also nothing against putting loops in the code block for a condition, or even putting loops inside loops (more on that last option follows later in this chapter). Most students probably are not surprised to hear that, but for the few who are completely new to programming: as long as you stick to the syntactic requirements, you can use conditional statements and loops wherever you can write Python statements. ",
"_____no_output_____"
],
[
"### `for` loop using a range of numbers",
"_____no_output_____"
],
[
"Python offers a `range()` function that generates a collection of sequential numbers, which is often used for `for` loops. The simplest call to `range()` has one parameter, which is a number. It will generate all integers, starting at zero, up to but not including the parameter.",
"_____no_output_____"
]
],
[
[
"for x in range( 10 ):\n print( x )",
"_____no_output_____"
]
],
[
[
"`range()` can get multiple parameters. If you give two parameters, then the first will be the starting number (default is zero), while the second will be the \"up to but not including\" number. If you give three parameters, the third will be a step size (default is `1`). You can choose a negative step size if you want to count down. With a negative step size, make sure that the starting number is higher than the number that you want to count up to (or down to, in this case).",
"_____no_output_____"
]
],
[
[
"for x in range( 1, 11, 2 ):\n print( x )",
"_____no_output_____"
]
],
[
[
"**Exercise:** Change the three parameters above to observe their effect, until you fully understand the `range()` function.\n\n**Exercise:** Use the `for` loop and `range()` function to print multiples of 3, starting at 21, counting down to 3, in just two lines of code.",
"_____no_output_____"
]
],
[
[
"# Counting down by threes.\n",
"_____no_output_____"
]
],
[
[
"### `for` loop with manual collections",
"_____no_output_____"
],
[
"If you want to use a `for` loop to cycle through items in a collection that you create manually, you can do so by listing all your items between parentheses. This defines a \"tuple\" for the items of your collection. Tuples will be discussed later.",
"_____no_output_____"
]
],
[
[
"for x in ( 10, 100, 1000, 10000 ):\n print( x )",
"_____no_output_____"
]
],
[
[
"Or:",
"_____no_output_____"
]
],
[
[
"for x in ( \"apple\", \"pear\", \"orange\", \"banana\", \"mango\", \"cherry\" ):\n print( x )",
"_____no_output_____"
]
],
[
[
"Your collection can even consist of mixed types.",
"_____no_output_____"
],
[
"### Practice with `for` loops",
"_____no_output_____"
],
[
"To get strong grips on how to use `for` loops, do the following exercises.\n\n**Exercise**: You already created code with a `while` loop that asked the user for five numbers, and displayed their total. Create code for this task, but now use a `for` loop.",
"_____no_output_____"
]
],
[
[
"# Total of five numbers.\n",
"_____no_output_____"
]
],
[
[
"**Exercise**: Create a countdown function that starts at a certain count, and counts down to zero. Instead of zero, print \"Blast off!\". Use a `for` loop. ",
"_____no_output_____"
]
],
[
[
"# Count down with for loop.\n",
"_____no_output_____"
]
],
[
[
"**Exercise**: I am not going to ask you to build a `for` loop that asks the user to enter numbers until the user enters zero. Why not? Hint: How often do you think that the user will enter a number that is not zero?",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"## Loop control statements",
"_____no_output_____"
],
[
"There are three extra statements that help you control the flow in a loop. They are `else`, `break`, and `continue`.",
"_____no_output_____"
],
[
"### `else`",
"_____no_output_____"
],
[
"Just like with an `if` statement, you can add an `else` statement to the end of a `while` or `for` loop. The code block for the `else` is executed whenever the loop ends, i.e., when the boolean expression for the `while` loop evaluates to `False`, or when the last item of the collection of the `for` loop is processed.\n\nHere is an example of using the `else` clause for a `while` loop:",
"_____no_output_____"
]
],
[
[
"i = 0\nwhile i < 5:\n print( i )\n i += 1\nelse:\n print( \"The loop ends, i is now\", i )\nprint( \"Done\" )",
"_____no_output_____"
]
],
[
[
"This code is represented by the flow chart below.\n\n<img src=\"img/Chart5en.png\" alt=\"Example of an else-branch in a loop\" style=\"width:300px;\"><br>\n<div align=\"center\">Figure 7.2: Example of an else-branch in a loop.</div>",
"_____no_output_____"
],
[
"And here is an example of using `else` for a `for` loop:",
"_____no_output_____"
]
],
[
[
"for fruit in ( \"apple\", \"orange\", \"strawberry\" ):\n print( fruit )\nelse:\n print( \"The loop ends, fruit is now\", fruit )\nprint( \"Done\" ) ",
"_____no_output_____"
]
],
[
[
"### `break`",
"_____no_output_____"
],
[
"The `break` statement allows you to prematurely break out of a loop. I.e., when Python encounters the `break` statement, it will no longer process the remainder of the code block for the loop, and will not loop back to the boolean expression. It will simply continue with the first statement after the loop's code block.\n\nTo see why this is useful, here follows an interesting exercise. I am looking for a number that starts with a 1, and when you transfer that 1 to the end of the number, the result is a number that is three times as high. For example, if I check the number 1867, I move the 1 from the start to the end, which gives 8671. If 8671 would be three times 1867, that is the answer I seek. It is not, so 1867 is not correct. The code to solve this is actually fairly short, and gives the lowest number for which the comparison holds:",
"_____no_output_____"
]
],
[
[
"i = 1\nwhile i <= 1000000:\n num1 = int( \"1\" + str( i ) )\n num2 = int( str( i ) + \"1\" )\n if num2 == 3 * num1:\n print( num2, \"is three times\", num1 )\n break\n i += 1\nelse:\n print( \"No answer found\" )",
"_____no_output_____"
]
],
[
[
"This code is represented by the flow chart below.\n\n<img src=\"img/Chart6en.png\" alt=\"Example of a break in a loop\" style=\"width:400px;\"><br>\n<div align=\"center\">Figure 7.3: Example of a break in a loop.</div>",
"_____no_output_____"
],
[
"In this example we see the `break` statement used to good effect. Since I have no idea which number I am looking for, I am just going to check a whole bunch of numbers. I let a counter `i` run up to `1000000`. Of course, I don't know if I find the answer before `i` has reached `1000000`, but I should set a limit somewhere, because I don't know if a number with the requested property exists at all, and I do not want to create an endless loop. I might find the answer at any point, and when I do, I `break` out of the loop, because further testing of numbers no longer serves a purpose.\n\nThe point here is that the setting of the maximum value of `i` to `1000000` is not because I know that I have to generate one million numbers. I have no idea how many times I have to cycle through the loop. I just know that if I encounter the requested number at some point, I am done and can skip the remainder of the cycles. That is exactly what the purpose of the `break` is.\n\nWith some juggling I could make sure that the boolean expression for the loop actually does the comparison for me. It would be something like `while (i < 1000000) and (num1 != 3 * num2):`. This becomes a bit convoluted, and I would also have to give `num1` and `num2` starting values before the loop starts. Still, it is always possible to avoid using a `break`, but applying the `break` might make code more readable and flow better, as it does in this case.\n\nThe `break` statement also works for `for` loops.\n\nThe `break` statement cannot be used outside a loop. It is only defined for loops. (Take note of this. I very often see students putting `break` statements in conditions that are not inside a loop, and then look mystified when Python reports a runtime error.)\n\nNote that when a `break` statement is encountered, and the loop also has an `else` clause, the code block for the `else` will *not* be executed. I use this to good effect in the code above, by ensuring that the text that indicates that no answer is found, only will be printed if the loop ends by checking all the numbers without finding an answer.\n\nThe following code checks a list of grades for a student. As long as all grades are 5.5 or higher, the student passes. When one or more grades are lower than 5.5, the student fails. The grades are in a collection that is given to a `for` loop.",
"_____no_output_____"
]
],
[
[
"for grade in ( 8, 7.5, 9, 6, 6, 6, 5.5, 7, 5, 8, 7, 7.5 ):\n if grade < 5.5:\n print( \"The student fails!\" )\n break\nelse:\n print( \"The student passes!\" )",
"_____no_output_____"
]
],
[
[
"**Exercise**: Remove the 5 from the list of grades and notice that the student now passes. Study this code carefully until you understand it.",
"_____no_output_____"
],
[
"### `continue`",
"_____no_output_____"
],
[
"When the `continue` statement is encountered in the code block of a loop, the current cycle ends immediately and the code loops back to the start of the loop. For a `while` loop, that means that the boolean expression is evaluated again. For a `for` loop, that means that the next item is taken from the collection and processed.\n\nThe following code prints all numbers between 1 and 100 that cannot be divided by 2 or 3, and do not end in a 7 or 9.",
"_____no_output_____"
]
],
[
[
"num = 0\nwhile num < 100:\n num += 1\n if num%2 == 0:\n continue\n if num%3 == 0:\n continue\n if num%10 == 7:\n continue\n if num%10 == 9:\n continue\n print( num )",
"_____no_output_____"
]
],
[
[
"This code is represented by the flow chart below.\n\n<img src=\"img/Chart7.png\" alt=\"Example of a continue in a loop\" style=\"width:300px;\"><br>\n<div align=\"center\">Figure 7.4: Example of a continue in a loop.</div>",
"_____no_output_____"
],
[
"I don't know why you would want this list, but the use of `continue` statements to implement it helps. Alternatively, you could have created one big boolean expression for an `if` statement, but that would become unreadable quickly. Still, just like `break` statements, `continue` statements can always be avoided if you really want to, but they do help keeping code understandable.\n\nNote that `continue` statements, just like `break` statements, can only be used inside loops.\n\nBe very, very careful when using a `continue` in a `while` loop. Most `while` loops use a number that restricts the number of cycles through the loop. Usually such a number is increased at the bottom of the code block for the loop. A `continue` statement would loop back to the boolean expression immediately, without increasing the number, and thus such a `continue` could easily cause an endless loop. I.e.:\n\n i = 0\n while i < 10:\n if i == 5:\n continue\n i += 1\n\ncauses an endless loop!\n\n**Exercise**: Write a program that processes a collection of numbers using a `for` loop. The program should end immediately, printing only the word \"Done\", when a zero is encountered (use a `break` for this). Negative numbers should be ignored (use a `continue` for this; I know you can also easily do this with a condition, but I want you to practice with `continue`). If no zero is encountered, the program should display the sum of all numbers (do this in an `else` clause). Always display \"Done\" at the end of the program.",
"_____no_output_____"
]
],
[
[
"for num in ( 12, 4, 3, 33, -2, -5, 7, 0, 22, 4 ):\n # Write your code here",
"_____no_output_____"
]
],
[
[
"With the numbers provided, the program should display only \"Done\". If you remove the zero, it should display 85 (and \"Done\").",
"_____no_output_____"
],
[
"-------",
"_____no_output_____"
],
[
"## Nested loops",
"_____no_output_____"
],
[
"You can put a loop inside another loop. \n\nThat is a simple statement, but it is one of the hardest concepts for students to wrap their minds around.\n\nLet's first look at an example of a double-nested loop, i.e., a loop which contains one other loop. Usually programmers talk about an \"outer loop\" and an \"inner loop\". The inner loop is part of the code block for the outer loop.",
"_____no_output_____"
]
],
[
[
"for i in range( 3 ):\n print( \"Entering the outer loop for i =\", i )\n for j in range( 3 ):\n print( \" Entering the inner loop for j =\", j )\n print( \" (i,j) = ({},{})\".format( i, j ) )\n print( \" Leaving the inner loop for j =\", j )\n print( \"Leaving the outer loop for i =\", i )",
"_____no_output_____"
]
],
[
[
"Study this code and its output until you fully understand it!\n\nThe code first gives `i` the value `0`, and then lets `j` take on the values `0`, `1`, and `2`. It then gives `i` the value `1`, and then lets `j` take on the values `0`, `1`, and `2`. Finally, it gives `i` the value `2`, and then lets `j` take on the values `0`, `1`, and `2`. So this code runs through all possible pairs of `(i,j)` with `i` and `j` being `0`, `1`, or `2`.\n\nNotice how variables for the outer loop are also accessible by the inner loop. `i` exists in both the outer and the inner loop.\n\nSuppose that you want to print all pairs `(i,j)` where `i` and `j` can take on the values `0` to `3`, but `j` must be higher than `i`. Code that does that is:",
"_____no_output_____"
]
],
[
[
"for i in range( 4 ):\n for j in range( i+1, 4 ):\n print( \"({},{})\".format( i, j ) )",
"_____no_output_____"
]
],
[
[
"See how I cleverly use `i` to set the range for `j`?\n\n**Exercise**: Write code that prints all pairs `(i,j)` where `i` and `j` can take on the values `0` to `3`, but they cannot be equal.",
"_____no_output_____"
]
],
[
[
"# Pairs of (i,j) where i != j.\n",
"_____no_output_____"
]
],
[
[
"You can, of course, also nest `while` loops, or mix nesting `for` loops with `while` loops.\n\nYou should be aware that when you use a `break` or `continue` in an inner loop, it will only `break` out of the inner loop or `continue` with the inner loop, respectively. There is no command that you can give in an inner loop that breaks out of both the inner and outer loop immediately.\n\nOnce you understand double-nested loops, it should come as no surpise that you can also triple-nest loops, quadruple-nest loops, or go even deeper. However, in practice I have seldom seen a nesting deeper than triple-nested.",
"_____no_output_____"
]
],
[
[
"for i in range( 3 ):\n for j in range( 3 ):\n for k in range( 3 ):\n print( \"({},{},{})\".format( i, j, k ) )",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## The loop-and-a-half",
"_____no_output_____"
],
[
"Suppose you want to ask the user for two numbers in a loop. For every two numbers that the user enters, you want to show their multiplication. You allow the user to stop the program when he enters zero for any of the numbers. For some reason, if the numbers are dividers of each other, that is an error and the program also stops, but with an error message. Finally, you will not process numbers higher than 1000 or smaller than zero, but that is not an error; you just want to allow the user to enter new numbers. How do you program that? Here is a first attempt:",
"_____no_output_____"
]
],
[
[
"from pcinput import getInteger\n\nx = 3\ny = 7\n\nwhile (x != 0) and (y != 0) and (x%y != 0) and (y%x != 0):\n x = getInteger( \"Enter number 1: \" )\n y = getInteger( \"Enter number 2: \" )\n if (x > 1000) or (y > 1000) or (x < 0) or (y < 0):\n print( \"Numbers should both be between 0 and 1000\" )\n continue\n print( \"Multiplication of\", x, \"and\", y, \"gives\", x * y )\n \nif x == 0 or y == 0:\n print( \"Goodbye!\" )\nelse:\n print( \"Error: the numbers cannot be dividers of each other\" )",
"_____no_output_____"
]
],
[
[
"**Exercise**: Study this code and make a list of everything that you feel is bad about it. Once you have done that, continue reading and compare your notes to the list below. If you noted things that are bad about it that are not on the list below, inform the instructor of the course.\n\nThere are many things bad about this code. Here is a list:\n\n- To ensure that the loop is run at least once, `x` and `y` must be initialized. Why did I choose 3 and 7 for that? That was arbitrary, but I had to pick two numbers that are not dividers of each other. Otherwise the loop would not have been entered. On the whole, having to give variables some arbitrary starting values just to make sure that they exist is not nice, as their initial values are meaningless. You want to avoid that.\n- When you enter something that should end the loop (e.g., zero for `x`), the multiplication will still be executed before the loop really has ended. That was not supposed to happen.\n- If you enter 0 for `x`, the code will still ask for a value for `y`, even if it does not need it anymore.\n- The boolean expression next to the `while` is rather complex. In this code it is still readable, but you can imagine what happens when you have many more requirements.\n- The error message for the dividers is not next to the actual test where you decide to leave the loop (i.e., the boolean expression next to the `while`).\n\nThe solution to some of these issues that certain programmers prefer, is to initialize `x` and `y` with values that you read from the input. This solves the arbitrary initialization, and also gets around the problem that you print the result of the multiplication even when the loop was already supposed to end. If you do this, however, in the loop you have to move the asking for input to the end of the loop, and if you ever have a `continue` in the loop, you also have to copy it there. The code becomes something like this:",
"_____no_output_____"
]
],
[
[
"from pcinput import getInteger\n\nx = getInteger( \"Enter number 1: \" )\ny = getInteger( \"Enter number 2: \" )\n\nwhile (x != 0) and (y != 0) and (x%y != 0) and (y%x != 0):\n if (x > 1000) or (y > 1000) or (x < 0) or (y < 0):\n print( \"Numbers should both be between 0 and 1000\" )\n x = getInteger( \"Enter number 1: \" )\n y = getInteger( \"Enter number 2: \" )\n continue\n print( \"Multiplication of\", x, \"and\", y, \"gives\", x * y )\n x = getInteger( \"Enter number 1: \" )\n y = getInteger( \"Enter number 2: \" )\n \nif x == 0 or y == 0:\n print( \"Goodbye!\" )\nelse:\n print( \"Error: the numbers cannot be dividers of each other\" )",
"_____no_output_____"
]
],
[
[
"So this code removes two of the issues, but it adds a new one, which makes the code a lot worse. The list of issues now is:\n\n- The statements that ask for input for each of the variables occur no less than three times in the code. \n- If you enter 0 for `x`, the code will still ask for a value for `y`.\n- The boolean expression next to the `while` is rather complex.\n- The error message for the dividers is not next to the actual test where you decide to leave the loop.\n\nThe trick to get around these issues is to control the loop solely through `continue`s and `break`s (and perhaps the occasional `exit` when errors occur, though later in the course you will learn to use the much \"cleaner\" `return` for that). I.e., you do the loop \"always\", but decide to leave the loop or redo the loop when certain events occur which you notice *in* the loop. Doing the loop \"always\" you can effectuate with the statement `while True` (as this simply means: the test that decides whether or not you have to do the loop again, always results in `True`).",
"_____no_output_____"
]
],
[
[
"from pcinput import getInteger\nfrom sys import exit\n\nwhile True:\n x = getInteger( \"Enter number 1: \" )\n if x == 0:\n break\n y = getInteger( \"Enter number 2: \" )\n if y == 0:\n break\n if (x < 0 or x > 1000) or (y < 0 or y > 1000):\n print( \"The numbers should be between 0 and 1000\" )\n continue\n if x%y == 0 or y%x == 0:\n print( \"Error: the numbers cannot be dividers of each other\" )\n exit()\n print( \"Multiplication of\", x, \"and\", y, \"gives\", x * y )\n \nprint( \"Goodbye!\" )",
"_____no_output_____"
]
],
[
[
"This code gets around almost all the problems. It asks for the input for `x` and `y` only once. There is no arbitrary initialization for `x` and `y`. The loop stops as soon as you enter zero for one of the numbers. It prints error messages at the moment that the errors are noted. There is no complex boolean expression needed with lots of `and`s and `or`s. \n\nThe only issue that is still remaining is that when the user enters a value outside the range 0 to 1000 for `x`, he still gets to enter `y` before the program says that he has to enter the numbers again. That is best solved by writing your own functions, which follows in the next chapter. (If you really want to solve it now, you can do that with a nested loop, but I wouldn't bother.)\n\nThe code is slightly longer than the first version, but length is no issue, and the code is a lot more readable.\n\nA loop like this one, that uses `while True`, is sometimes called a \"loop-and-a-half\". It is a common approach to writing loops for which you cannot predict when they will end.\n\n**Exercise**: The user must enter a positive integer. You use the `getInteger()` function from `pcinput` for that. This function also allows entering negative numbers. If the user enters a negative number, you want to print a message and ask him again, until he entered a positive number. Once a positive number is entered, you print that number and the program ends. Such a problem is typically solved using a loop-and-a-half, as you cannot predict how often the user will enter a negative number before he gets wise. Write such a loop-and-a-half in the code block below (you will need exactly one `break`, and you need at most one `continue`). Print the final number that the user entered *after* you have exited the loop. The reason to do it afterwards is that the loop is just there to control the entering of the input, not the processing of the resulting variable.",
"_____no_output_____"
]
],
[
[
"# Input entering.\n",
"_____no_output_____"
]
],
[
[
"I have noted in the past that many students find the use of `while True` confusing. They see it often in example code, but do not really grasp what the point of it is. And then they start inserting `while True` in their code whenever they do not know exactly what they need to do. If you have troubles understanding the loop-and-a-half, study this section again, until you do.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"## Being smart about loops",
"_____no_output_____"
],
[
"To complete this chapter, I want to discuss a few strategies on loop design.",
"_____no_output_____"
],
[
"### When to use a loop",
"_____no_output_____"
],
[
"If you roll five 6-sided dice, how big is the chance that you roll five sixes? The answer is `1/(6**5)`, but suppose that you did not know that, and wanted to use a simulation to estimate the chance. You can imitate the rolling of a die using `randint()`, and so you can imitate the rolling of five dice this way. You can check whether they all show a 6. You can do that a large number of times, and then divide the number of times that you rolled five sixes by the number of times that you rolled five dice, to get an estimate. When I put this problem to students (in a slightly more complicated form, so that the answer cannot easily be calculated), I often get code that looks like this: ",
"_____no_output_____"
]
],
[
[
"from random import randint\n\nTESTS = 10000\n\nsuccess = 0\nfor i in range( TESTS ):\n die1 = randint( 1, 6 )\n die2 = randint( 1, 6 )\n die3 = randint( 1, 6 )\n die4 = randint( 1, 6 )\n die5 = randint( 1, 6 )\n if die1 == 6 and die2 == 6 and die3 == 6 and die4 == 6 and die5 == 6:\n success += 1\n \nprint( \"Chance at five sixes is\", success / TESTS )",
"_____no_output_____"
]
],
[
[
"(You would need a bigger number of tests to get a more accurate estimate, but I did not want this code to run too long.)\n\nWhen I see code like this, I ask: \"What if I had asked you to roll one hundred dice? Would you really repeat that die rolling line 100 times?\" Whenever you see lines of code repeated with just a slight change between them (or when you are copying/pasting within a block of code), you should start thinking about loops. You can roll five dice by stating: ",
"_____no_output_____"
]
],
[
[
"from random import randint\n\nfor i in range( 5 ):\n die = randint( 1, 6 )",
"_____no_output_____"
]
],
[
[
"\"But\", you might argue: \"I need the value of all the five dice to see if they are all sixes! Every time you cycle through the loop, you lose the value of the previous roll!\"\n\nTrue enough, but the line that checks all the dice by using five boolean expressions concatenated with `and`s is particularly ugly too. Can't you streamline this? Is there no way that you can draw some conclusion upon the rolling of one die?\n\nBy thinking a bit about it, you might come to the following conclusion: as soon as you roll a die that is not a six, you already have failed on your try, and you can skip to the next try. There are many ways to effectuate this, but here is a brief one using a `break` and an `else`:",
"_____no_output_____"
]
],
[
[
"from random import randint\n\nTESTS = 10000\n\nsuccess = 0\nfor i in range( TESTS ):\n for j in range( 5 ):\n if randint( 1, 6 ) != 6:\n break\n else:\n success += 1\n \nprint( \"Chance at five sixes is\", success / TESTS )",
"_____no_output_____"
]
],
[
[
"You might think this is difficult to come up with, but there are other ways too. You can, for instance, add up the values of the rolls and test if the total is 30 after the inner loop. Or you can keep track of how many dice were rolled to a value of 6 and check if that is 5 after the inner loop. Or you can set a boolean variable to `True` before the inner loop, then set it to `False` as soon as you roll something that is not 6 in the inner loop, and then test the variable after the inner loop.\n\nThe point is that the arbitrary long repetition of pieces of code can probably be replaced by a loop. ",
"_____no_output_____"
],
[
"### Processing data items one by one",
"_____no_output_____"
],
[
"Usually, when a loop is applied, you are working through a long series of data items. Each cycle through the loop will process one of those data items. You then often need to remember something about the data items that you have processed so far, for which you need extra variables. You have to be smart in thinking about such variables.\n\nTake the following example: I will provide you with ten numbers, and I need you to create a program that tells me which is the largest, which is the smallest, and how many are dividable by 3. You might say: \"It is easy to determine the largest and the smallest; I just use the `max()` and `min()` functions. Dividable by 3 is a bit tricky, I have to think about that.\" But `max()` and `min()` require you to keep all the numbers in memory. That's fine for 10 numbers, but what about one hundred? Or a million?\n\nSince you will have to process all the numbers, you have to think about a loop, and in particular, a loop wherein you have only one of the numbers available each cycle through the loop (but you will see them all before the loop ends). You must now think about variables that you can use to remember something each cycle through the loop, that allows you to determine, at the end, which number was the largest, which the smallest, and how many are dividable by 3. Which variables do you need?\n\nThe answer, which comes easy to anyone who has been doing some programming, is that you need to remember, each cycle through the loop, which is the largest number *until now*, which is the smallest number *until now*, and how many numbers are dividable by 3 *until now*. That means that every cycle through the loop you compare the new number with the variables in which you retain the largest and smallest, and replace them with the new number if that is appropriate. You also check if the new number is dividable by three, and if so, increase the variable that you use to keep track of that. \n\nYou will have to find good initial values for the three variables. The dividable-by-3 variable can start at zero, but the largest and smallest need an appropriate value. The best solution in this case is to fill them with the first number, as that number is both the largest and the smallest at that point.\n\nI give this problem as an exercise below. Use the algorithm described here to solve it.",
"_____no_output_____"
],
[
"### Start with the smallest unit and build outward",
"_____no_output_____"
],
[
"Suppose that I give you the following assignment: Of all the books on all the shelves in the library, count the number of words and report the average number of words for the books. If you ask a human to perform this task, he or she will probably think: \"I go to the library, get the first book from the first shelf, count the words, write that number down, then take the second book and do the same thing, etcetera. When I finished the first shelf, I go to the second shelf and treat that one in the same way, until I have done all the books on all the shelves in the library. Then I add up the counts and divide by the number of books.\" For humans this approach works, but when you need to tell a computer how to do this, the task seems hard.\n\nTo solve this problem, I should start with the smallest unit that I need to work with. In this case, the smallest unit is a \"book\". It is not \"word\", because I don't need to do anything with a \"word\"; what I need to do is count the words in a book. In pseudocode, that would be something like:\n\n wordcount = 0\n for word in book:\n wordcount += 1\n \nWhen I code something like this, I can already test it. Once I am satisfied that I can count the words in a book, I can move up to the next smallest unit, which is the shelf. How do I process all the books on a shelf? In pseudocode, it is something like:\n\n for book on shelf:\n process_book()\n \nBut what does `process_book()` do? It counts the words. I already wrote pseudocode for that, which I simply need to insert in place of the statement `process_book()`. This then becomes:\n\n for book on shelf:\n wordcount = 0\n for word in book:\n wordcount += 1\n \nWhen I test this, I run into a problem. I find that I am counting the words per book, but I am not doing anything with those word counts. I just overwrite them. To get the average, I first need a count of all the words in all the books. This means I have to initialize `wordcount` only once. \n\n wordcount = 0\n for book on shelf:\n for word in book:\n wordcount += 1\n\nTo calculate the average, I need to also count the books. Again, I only need to initialize the `bookcount` once, at the start, and I have to increase the `bookcount` every time I have processed one book. At the end, I can then print the average.\n\n wordcount = 0\n bookcount = 0\n for book on shelf:\n for word in book:\n wordcount += 1\n bookcount += 1\n print( wordcount / bookcount )\n\nFinally, I can go up to the highest level: the library as a whole. I know how to process one shelf, now I need to process all the shelves. I should, of course, remember that the initialization of `wordcount` and `bookcount` only should be done once, and the printing of the average too. With that in mind, it is easy to extend the pseudocode to encompass the library as a whole:\n\n wordcount = 0\n bookcount = 0\n for shelf in library:\n for book on shelf:\n for word in book:\n wordcount += 1\n bookcount += 1\n print( wordcount / bookcount )\n\nAs you can see, I built a triple-nested loop, working from the inner loop outward. To learn how to deal with nested loops, this is usually the best approach.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"## On designing algorithms",
"_____no_output_____"
],
[
"At this point in the course, you will often run into exercises and coding problems for which you are unsure how to solve them. I gave an example of such a problem above (finding of ten numbers the largest, the smallest, and the number dividable by 3), and the solution I came to. Such a solution approach is called an \"algorithm\". But how do you design such algorithms?\n\nI often see students typing code without really knowing what they are doing. They are trying to solve a problem but do not know how, so they start typing. You may realize that this is not a good approach to creating solutions (even though experimenting a bit might help).\n\nWhat you have to do in such a situation is sit back, leave the keyboard alone, and think \"How would I solve this problem as a human?\" Try to write down what you would do if you would do it by hand. It does not matter if what you would do is a very boring task that you would never *want* to do by hand -- you have a computer to do the boring things for you.\n\nOnce you have figured out what you would do, then try to think about how you would translate that to code. Because basically, that is what you need to tell the computer: the steps that you as a human would take to get to a solution. If you really cannot think of any way that you as a human would use to solve a problem, then you sure as hell won't be able to tell the computer how to do it for you.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"## What you learned",
"_____no_output_____"
],
[
"In this chapter, you learned about:\n\n- What loops are\n- `while` loops\n- `for` loops\n- Endless loops\n- Loop control via `else`, `break`, and `continue`\n- Nested loops\n- The loop-and-a-half\n- Being smart about loops",
"_____no_output_____"
],
[
"-------",
"_____no_output_____"
],
[
"## Exercises",
"_____no_output_____"
],
[
"Since loops are incredibly important and students often have problems with them, I provide a considerable number of exercises here. I recommend that you do them all. You will learn a lot.",
"_____no_output_____"
],
[
"### Exercise 7.1",
"_____no_output_____"
],
[
"Write a program that lets the user enter a number. Then the program displays the multiplication table for that number from 1 to 10. E.g., when the user enters `12`, the first line printed is \"`1 * 12 = 12`\" and the last line printed is \"`10 * 12 = 120`\".",
"_____no_output_____"
]
],
[
[
"# Multiplication table.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.2",
"_____no_output_____"
],
[
"If you did the previous exercise with a `while` loop, then do it again with a `for` loop. If you did it with a `for` loop, then do it again with a `while` loop. If you did not use a loop at all, you should be ashamed of yourself.",
"_____no_output_____"
]
],
[
[
"# Multiplication table (again).\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.3",
"_____no_output_____"
],
[
"Write a program that asks the user for ten numbers, and then prints the largest, the smallest, and how many are dividable by 3. Use the algorithm described earlier in this chapter.",
"_____no_output_____"
]
],
[
[
"# Largest, smallest, dividable by 3.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.4",
"_____no_output_____"
],
[
"\"99 bottles of beer\" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows: \"99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall.\" The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero. Write a program that generates all the verses of the song (though you might start a bit lower, for instance with 10 bottles). Make sure that your loop is not endless, and that you use the proper inflection for the word \"bottle\".",
"_____no_output_____"
]
],
[
[
"# Bottles of beer.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.5",
"_____no_output_____"
],
[
"The Fibonacci sequence is a sequence of numbers that starts with 1, followed by 1 again. Every next number is the sum of the two previous numbers. I.e., the sequence starts with 1, 1, 2, 3, 5, 8, 13, 21,... Write a program that calculates and prints the Fibonacci sequence until the numbers get higher than 1000.",
"_____no_output_____"
]
],
[
[
"# Fibonacci.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.6",
"_____no_output_____"
],
[
"Write a program that asks the user for two words. Then print all the characters that the words have in common. You can consider capitals different from lower case letters, but each character that you report, should be reported only once (e.g., the strings \"bee\" and \"peer\" only have one character in common, namely the letter \"e\"). Hint: Gather the characters in a third string, and when you find a character that the two words have in common, check if it is already in the third string before reporting it.",
"_____no_output_____"
]
],
[
[
"# Common characters.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.7",
"_____no_output_____"
],
[
"Write a program that approximates the value of `pi` by using random numbers, as follows. Consider a square measuring 1 by 1. If you throw a dart into that square in a random location, the probability that it will have a distance of 1 or less to the lower left corner is `pi/4`. To see why that is, remember that the area of a circle with a radius of 1 is `pi`, so the area of a quarter circle is `pi/4`. Thus, if a dart lands in a random point in the square, the chance that it lands in the quarter circle with its centre at the lower left corner is `pi/4`. Therefore, if you throw `N` darts into the square, and `M` of those land inside a distance of 1 to the lower left corner, then `4M/N` approximates `pi` if `N` is very large. \n\nThe program holds a constant that determines how many darts it will simulate. It prints an approximation of `pi` derived by simulating the throwing of that number of darts. Remember that the distance of a point `(x,y)` to the lower-left corner is calculated as `sqrt( x*x + y*y )`. Use the `random()` function from the `random` module.\n\n<img src=\"img/pi4.png\" alt=\"quarter circle\" style=\"width:100px;\">",
"_____no_output_____"
]
],
[
[
"# Approximation of pi.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.8",
"_____no_output_____"
],
[
"Write a program that takes a random integer between 1 and 1000 (you can use the `randint()` function for that). The program then asks the user to guess the number. After every guess, the program will say either \"Lower\" if the number it took is lower, \"Higher\" if the number it took is higher, and \"You guessed it!\" if the number it took is equal to the number that the user entered. It will end with displaying how many guesses the user needed. It might be wise, for testing purposes, to also display the number that the program randomly picks, until you are sure that the program works correctly. ",
"_____no_output_____"
]
],
[
[
"# Number guessing.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.9",
"_____no_output_____"
],
[
"Write a program that is the opposite of the previous one: now *you* take a number in mind, and the computer will try to guess it. You respond to the computer's guesses by entering a letter: \"L\" for lower, \"H\" for higher, and \"C\" for correct (you can use the `getLetter()` function from `pcinput` for that). Once the computer has guessed your number, it displays how many guesses it needed. Make sure that you let the computer recognize when there is no answer (maybe because you made a mistake or because you tried to fool the computer).",
"_____no_output_____"
]
],
[
[
"# Opposite number guessing.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.10",
"_____no_output_____"
],
[
"A prime number is a positive integer that is dividable by exactly two different numbers, namely 1 and itself. The lowest (and only even) prime number is 2. The first 10 prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. Write a program that asks the user for a number and then displays whether or not it is prime. Hint: In a loop where you test the possible dividers of the number, you can conclude that the number is not prime as soon as you encounter a number other than 1 or itself that divides it. However, you can *only* conclude that it actually *is* prime after you have tested all possible dividers.",
"_____no_output_____"
]
],
[
[
"# Prime number tester.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.11",
"_____no_output_____"
],
[
"Write a program that prints a multiplication table for digits 1 to a certain number `num` (you may assume for the output that num is one digit). A multiplication table for the numbers 1 to `num = 3` looks as follows:\n\n`. | 1 2 3`<br>\n`------------`<br>\n`1 | 1 2 3`<br>\n`2 | 2 4 6`<br>\n`3 | 3 6 9`\n\nSo the labels on the rows are multiplied by the labels on the columns, and the result is shown in the cell that is on that row/column combination. ",
"_____no_output_____"
]
],
[
[
"# Multiplication table.\nnum = 9\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.12",
"_____no_output_____"
],
[
"Write a program that displays all integers between 1 and 100 that can be written as the sum of two squares. Produce output in the form of `z = x**2 + y**2`, e.g., `58 = 3**2 + 7**2`. If a number occurs on the list with multiple *different* ways of writing it as the sum of two squares, that is acceptable. ",
"_____no_output_____"
]
],
[
[
"# Sum of two squares.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.13",
"_____no_output_____"
],
[
"You roll five six-sided dice, one by one. How big is the probability that the value of each die is greater than or equal to the value of the previous die that you rolled? For example, the sequence \"1, 1, 4, 4, 6\" is a success, but \"1, 1, 4, 3, 6\" is not. Determine the probability of success using a simulation of a large number of trials. ",
"_____no_output_____"
]
],
[
[
"# Increasing die values.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.14",
"_____no_output_____"
],
[
"A, B, C, and D are all different digits. The number DCBA is equal to 4 times the number ABCD. What are the digits? Note: to make ABCD and DCBA conventional numbers, neither A nor D can be zero. Use a quadruple-nested loop.",
"_____no_output_____"
]
],
[
[
"# Solve 4*ABCD == DCBA.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.15",
"_____no_output_____"
],
[
"According to an old puzzle, five pirates and their monkey are stranded on an island. During the day they gather coconuts, which they put in a big pile. When night falls, they go asleep. \n\nIn the middle of the night, the first pirate wakes up, and, not trusting his buddies, he divides the pile into five equal parts, takes what he believes to be his share and hides it. Since he had one coconut left after the division, he gives it to the monkey. Then he goes back to sleep.\n\nAn hour later, the next pirate wakes up. He behaves in the same way as the first pirate: he divides the pile into five equal shares, with one coconut left over which he gives to the monkey, hides what he believes to be his share, and goes to sleep again.\n\nThe same happens to the other pirates: they wake up one by one, divide the pile, give one coconut to the monkey, hide their share, and go back to sleep.\n\nIn the morning they all wake up. They divide what remains of the coconuts equally among them. Since that leaves one coconut, they give it to the monkey.\n\nThe question is: what is the smallest number of coconuts that they can have started with?\n\nWrite a Python program that solves this puzzle. If you can solve it for any number of pirates, all the better.",
"_____no_output_____"
]
],
[
[
"# The monkey and the coconuts.\n",
"_____no_output_____"
]
],
[
[
"### Exercise 7.16",
"_____no_output_____"
],
[
"Consider the triangle shown below. This triangle houses a colony of Triangle Crawlers, and one big Eater of Triangle Crawlers. The Eater is located in point D. All Triangle Crawlers are born in point A. A Triangle Crawler which ends up in point D gets eaten. \n\nEvery day, each Triangle Crawler moves over one of the lines to a randomly-determined neighboring point, but not to the point where he was the day before. This movement takes one day. For instance, a Triangle Crawler that was just born in A, on the first day of his life will move to B, C, or D. If he moves to B, the next day he will move to C or D (but not back to A). If on his first day he moves to C instead, the next day he will move to B or D (but not back to A). If he moves to D, he gets eaten.\n\nThere is a one-third probability that Triangle Crawler on the first day of his life immediately goes to D, and therefore only lives one day. In principle, a Triangle Crawler may reach any age, however high, by moving in circles from A to B to C and back to A again (or counterclockwise, from A to C to B and back to A again). However, since every day he makes a random choice between the two possible follow-up directions, every day after the first there is a one-half probability that he ends up in point D, and dies.\n\nWrite a program that calculates an approximation of the average age that a Triangle Crawler reaches. Do this by simulating the lives of 100,000 Triangle Crawlers, counting the days that they live, and dividing the total by 100,000. The output of your program should be a single floating point number, rounded to two decimals. \n\nHint 1: You can follow two different approaches: either you simulate the behavior of one single Triangle Crawler and repeat that 100,000 times, or you start with a population of 100,000 triangle crawlers in point A, and divide these over variables that keep track of how many Triangles are in each point, each day, including the point that they came from (assigning a remaining odd Triangle Crawler to a randomly determined neighboring point). The first method is short and simple but slow, the second is long and complex but fast. You may use either method.\n\nHint 2: Do not use 100,000 Triangle Crawlers in your first attempts. Start with 1000 (or even only 1), and only try it out with 100,000 once your program is more or less finished. Testing is much quicker with fewer Triangle Crawlers. 1000 Triangle Crawlers should be done in under a second, so if your program takes longer, you probably have created an endless loop.\n\nHint 3: I won't be too specific, but the final answer is somewhere between 1 and 5 days. If you get something outside that range, it is definitely wrong. You may try to determine the exact answer mathematically before starting on the exercise, which is doable though quite hard.\n\n<img src=\"img/Triangle.png\" alt=\"Triangle\" style=\"width:200px;\">",
"_____no_output_____"
]
],
[
[
"# Triangle crawlers.\n",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## Python 2",
"_____no_output_____"
],
[
"In Python 3, the `range()` function is an iterator. This entails that it needs very little memory space: it only retains the last number generated, the step size, and the limit that it should reach. In Python 2 `range()` is implemented differently: it produces all the numbers of the range in memory at once. This means that a statement like `range(1000000000)` in Python 2 requires so much memory that it may very well crash the program. In Python 3, such issues do not exist. In Python 2 it is therefore recommended not to use `range()` for more than 10,000 numbers or so, while in Python 3 no restrictions exist.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"End of Chapter 7. Version 1.3.",
"_____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",
"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"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d0ae15e6376ecda3289e2392933efe57f753d9ed | 547,661 | ipynb | Jupyter Notebook | paper/Advection_diffusion/Old/Paper/AD_sensor_density_15-19-20-Copy1.ipynb | remykusters/DeePyMoD | c53ce939c5e6a5f0207b042d8d42bc0197d66073 | [
"MIT"
] | null | null | null | paper/Advection_diffusion/Old/Paper/AD_sensor_density_15-19-20-Copy1.ipynb | remykusters/DeePyMoD | c53ce939c5e6a5f0207b042d8d42bc0197d66073 | [
"MIT"
] | null | null | null | paper/Advection_diffusion/Old/Paper/AD_sensor_density_15-19-20-Copy1.ipynb | remykusters/DeePyMoD | c53ce939c5e6a5f0207b042d8d42bc0197d66073 | [
"MIT"
] | null | null | null | 365.594793 | 61,400 | 0.932688 | [
[
[
"# 2D Advection-Diffusion equation",
"_____no_output_____"
],
[
"in this notebook we provide a simple example of the DeepMoD algorithm and apply it on the 2D advection-diffusion equation. ",
"_____no_output_____"
]
],
[
[
"# General imports\nimport numpy as np\nimport torch\nimport matplotlib.pylab as plt\n\n# DeepMoD functions\n\nfrom deepymod import DeepMoD\nfrom deepymod.model.func_approx import NN, Siren\nfrom deepymod.model.library import Library2D_third\nfrom deepymod.model.constraint import LeastSquares\nfrom deepymod.model.sparse_estimators import Threshold,PDEFIND\nfrom deepymod.training import train\nfrom deepymod.training.sparsity_scheduler import TrainTestPeriodic\nfrom scipy.io import loadmat\n\n# Settings for reproducibility\nnp.random.seed(42)\ntorch.manual_seed(0)\n\n\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
]
],
[
[
"## Prepare the data",
"_____no_output_____"
],
[
"Next, we prepare the dataset.",
"_____no_output_____"
]
],
[
[
"data = np.load('data_paper.npy')",
"_____no_output_____"
],
[
"down_data= np.take(np.take(np.take(data,np.arange(0,data.shape[0],6),axis=0),np.arange(0,data.shape[1],6),axis=1),np.arange(0,data.shape[2],1),axis=2)",
"_____no_output_____"
],
[
"down_data.shape",
"_____no_output_____"
],
[
"steps = down_data.shape[2]\nwidth = down_data.shape[0]\nwidth_2 = down_data.shape[1]",
"_____no_output_____"
],
[
"x_arr = np.arange(0,width)\ny_arr = np.arange(0,width_2)\nt_arr = np.arange(0,steps)\nx_grid, y_grid, t_grid = np.meshgrid(x_arr, y_arr, t_arr, indexing='ij')\nX = np.transpose((t_grid.flatten(), x_grid.flatten(), y_grid.flatten()))",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(15,5))\n\nplt.subplot(1,3, 1)\nplt.imshow(down_data[:,:,1], aspect=0.5)\n\nplt.subplot(1,3, 2)\nplt.imshow(down_data[:,:,9], aspect=0.5)\n\nplt.subplot(1,3, 3)\nplt.imshow(down_data[:,:,19], aspect=0.5)",
"_____no_output_____"
]
],
[
[
"We flatten it to give it the right dimensions for feeding it to the network:",
"_____no_output_____"
]
],
[
[
"X = np.transpose((t_grid.flatten()/np.max(t_grid), x_grid.flatten()/np.max(y_grid), y_grid.flatten()/np.max(y_grid)))\ny = np.float32(down_data.reshape((down_data.size, 1)))\ny = y/np.max(y)",
"_____no_output_____"
],
[
"len(y)",
"_____no_output_____"
],
[
"number_of_samples = 10000\n\nidx = np.random.permutation(y.shape[0])\nX_train = torch.tensor(X[idx, :][:number_of_samples], dtype=torch.float32, requires_grad=True)\ny_train = torch.tensor(y[idx, :][:number_of_samples], dtype=torch.float32)\n\n",
"_____no_output_____"
]
],
[
[
"## Configuration of DeepMoD",
"_____no_output_____"
],
[
"Configuration of the function approximator: Here the first argument is the number of input and the last argument the number of output layers.",
"_____no_output_____"
]
],
[
[
"network = NN(3, [30, 30, 30, 30], 1)",
"_____no_output_____"
]
],
[
[
"Configuration of the library function: We select athe library with a 2D spatial input. Note that that the max differential order has been pre-determined here out of convinience. So, for poly_order 1 the library contains the following 12 terms:\n* [$1, u_x, u_y, u_{xx}, u_{yy}, u_{xy}, u, u u_x, u u_y, u u_{xx}, u u_{yy}, u u_{xy}$]",
"_____no_output_____"
]
],
[
[
"library = Library2D_third(poly_order=0) ",
"_____no_output_____"
]
],
[
[
"Configuration of the sparsity estimator and sparsity scheduler used. In this case we use the most basic threshold-based Lasso estimator and a scheduler that asseses the validation loss after a given patience. If that value is smaller than 1e-5, the algorithm is converged. ",
"_____no_output_____"
]
],
[
[
"estimator = Threshold(0.025) \nsparsity_scheduler = TrainTestPeriodic(periodicity=50, patience=200, delta=1e-5) ",
"_____no_output_____"
]
],
[
[
"\nConfiguration of the sparsity estimator ",
"_____no_output_____"
]
],
[
[
"constraint = LeastSquares() \n# Configuration of the sparsity scheduler",
"_____no_output_____"
]
],
[
[
"Now we instantiate the model and select the optimizer ",
"_____no_output_____"
]
],
[
[
"model = DeepMoD(network, library, estimator, constraint)\n\n# Defining optimizer\noptimizer = torch.optim.Adam(model.parameters(), betas=(0.99, 0.999), amsgrad=True, lr=1e-3) \n",
"_____no_output_____"
]
],
[
[
"## Run DeepMoD ",
"_____no_output_____"
],
[
"We can now run DeepMoD using all the options we have set and the training data:\n* The directory where the tensorboard file is written (log_dir)\n* The ratio of train/test set used (split)\n* The maximum number of iterations performed (max_iterations)\n* The absolute change in L1 norm considered converged (delta)\n* The amount of epochs over which the absolute change in L1 norm is calculated (patience)",
"_____no_output_____"
]
],
[
[
"train(model, X_train, y_train, optimizer,sparsity_scheduler, log_dir='runs/space_new/', split=0.8, max_iterations=100000, delta=1e-5, patience=200) ",
" 1450 MSE: 2.00e-03 Reg: 2.21e-04 L1: 1.25e+00 "
]
],
[
[
"Sparsity masks provide the active and non-active terms in the PDE:",
"_____no_output_____"
]
],
[
[
"sol = model(torch.tensor(X, dtype=torch.float32))[0].reshape((width,width_2,steps)).detach().numpy()",
"_____no_output_____"
],
[
"ux = model(torch.tensor(X, dtype=torch.float32))[2][0][:,1].reshape((width,width_2,steps)).detach().numpy()\nuy = model(torch.tensor(X, dtype=torch.float32))[2][0][:,2].reshape((width,width_2,steps)).detach().numpy()",
"_____no_output_____"
],
[
"uxx = model(torch.tensor(X, dtype=torch.float32))[2][0][:,3].reshape((width,width_2,steps)).detach().numpy()\nuyy = model(torch.tensor(X, dtype=torch.float32))[2][0][:,4].reshape((width,width_2,steps)).detach().numpy()",
"_____no_output_____"
],
[
"import pysindy as ps",
"_____no_output_____"
],
[
"fd_spline = ps.SINDyDerivative(kind='spline', s=1e-2)\nfd_spectral = ps.SINDyDerivative(kind='spectral')\nfd_sg = ps.SINDyDerivative(kind='savitzky_golay', left=0.5, right=0.5, order=3)",
"_____no_output_____"
],
[
"y = down_data[5,:,1]\nx = y_arr\nplt.plot(x,y, 'bo--')\nplt.plot(x,sol[5,:,1]*np.max(down_data),'b', label='t = 1',linewidth=3)\ny = down_data[5,:,5]\nx = y_arr\nplt.plot(x,y, 'go--')\nplt.plot(x,sol[5,:,5]*np.max(down_data),'g', label='t = 5',linewidth=3)\ny = down_data[5,:,10]\nx = y_arr\nplt.plot(x,y, 'ro--')\nplt.plot(x,sol[5,:,10]*np.max(down_data),'r', label='t = 10',linewidth=3)\nplt.legend()",
"_____no_output_____"
],
[
"y = down_data[5,:,1]\nx = y_arr\nplt.plot(x,fd_sg(y,x), 'bo--')\nplt.plot(x,uy[5,:,1]*np.max(down_data)/np.max(y_grid),'b', label='x = 1',linewidth=3)\ny = down_data[5,:,5]\nx = y_arr\nplt.plot(x,fd_sg(y,x), 'go--')\nplt.plot(x,uy[5,:,5]*np.max(down_data)/np.max(y_grid),'g', label='x = 5',linewidth=3)\ny = down_data[5,:,10]\nx = y_arr\nplt.plot(x,fd_sg(y,x), 'ro--')\nplt.plot(x,uy[5,:,10]*np.max(down_data)/np.max(y_grid),'r', label='x = 10',linewidth=3)\nplt.legend()",
"_____no_output_____"
],
[
"y = down_data[5,:,1]\nx = y_arr\nplt.plot(x,fd_sg(fd_sg(y,x)), 'bo--')\nplt.plot(x,uyy[5,:,1]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'b',linewidth=3)\ny = down_data[5,:,5]\nx = y_arr\nplt.plot(x,fd_sg(fd_sg(y,x)), 'go--')\nplt.plot(x,uyy[5,:,5]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'g',linewidth=3)\ny = down_data[5,:,10]\nx = y_arr\nplt.plot(x,fd_sg(fd_sg(y,x)), 'ro--')\nplt.plot(x,uyy[5,:,10]*np.max(down_data)/(np.max(y_grid)*np.max(y_grid)),'r',linewidth=3)",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(15,5))\n\nplt.subplot(1,3, 1)\nplt.imshow(sol[:,:,1], aspect=0.5)\n\nplt.subplot(1,3, 2)\nplt.imshow(sol[:,:,5], aspect=0.5)\n\nplt.subplot(1,3, 3)\nplt.imshow(sol[:,:,10], aspect=0.5)\n\n\n#plt.savefig('reconstruction.pdf')",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(15,5))\n\nplt.subplot(1,3, 1)\nplt.imshow(down_data[:,:,1], aspect=0.5)\n\nplt.subplot(1,3, 2)\nplt.imshow(down_data[:,:,19], aspect=0.5)\n\nplt.subplot(1,3, 3)\nplt.imshow(down_data[:,:,39], aspect=0.5)\n\nplt.savefig('original_20_20_40.pdf')",
"_____no_output_____"
],
[
"np.max(down_data)",
"_____no_output_____"
],
[
"plt.plot(x,sol[5,:,10]*np.max(down_data))",
"_____no_output_____"
],
[
"noise_level = 0.025\ny_noisy = y + noise_level * np.std(y) * np.random.randn(y.size)",
"_____no_output_____"
],
[
"plt.plot(x,uy[25,:,10])\nplt.plot(x,ux[25,:,10])",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(15,5))\n\nplt.subplot(1,3, 1)\nplt.plot(fd_spline(y.reshape(-1,1),x), label='Ground truth',linewidth=3)\nplt.plot(fd_spline(y_noisy.reshape(-1,1),x), label='Spline',linewidth=3)\nplt.legend()\n\nplt.subplot(1,3, 2)\nplt.plot(fd_spline(y.reshape(-1,1),x), label='Ground truth',linewidth=3)\nplt.plot(fd_sg(y_noisy.reshape(-1,1),x), label='Savitzky Golay',linewidth=3)\nplt.legend()\n\nplt.subplot(1,3, 3)\nplt.plot(fd_spline(y.reshape(-1,1),x), label='Ground truth',linewidth=3)\nplt.plot(uy[25,:,10],linewidth=3, label='DeepMoD')\nplt.legend()\n\nplt.show()",
"_____no_output_____"
],
[
"plt.plot(ux[10,:,5])\nax = plt.subplot(1,1,1)\nax.plot(fd(y.reshape(-1,1),x), label='Ground truth')\nax.plot(fd_sline(y_noisy.reshape(-1,1),x), label='Spline')\nax.plot(fd_sg(y_noisy.reshape(-1,1),x), label='Savitzky Golay')\nax.legend()",
"_____no_output_____"
],
[
"plt.plot(model(torch.tensor(X, dtype=torch.float32))[2][0].detach().numpy())",
"_____no_output_____"
],
[
"sol = model(torch.tensor(X, dtype=torch.float32))[0]",
"_____no_output_____"
],
[
"plt.imshow(sol[:,:,4].detach().numpy())",
"_____no_output_____"
],
[
"plt.plot(sol[10,:,6].detach().numpy())\nplt.plot(down_data[10,:,6]/np.max(down_data))",
"_____no_output_____"
],
[
"x = np.arange(0,len(y))",
"_____no_output_____"
],
[
"import pysindy as ps\ndiffs = [\n ('PySINDy Finite Difference', ps.FiniteDifference()),\n ('Smoothed Finite Difference', ps.SmoothedFiniteDifference()),\n ('Savitzky Golay', ps.SINDyDerivative(kind='savitzky_golay', left=0.5, right=0.5, order=3)),\n ('Spline', ps.SINDyDerivative(kind='spline', s=1e-2)),\n ('Trend Filtered', ps.SINDyDerivative(kind='trend_filtered', order=0, alpha=1e-2)),\n ('Spectral', ps.SINDyDerivative(kind='spectral')),\n]",
"_____no_output_____"
],
[
"fd = ps.SINDyDerivative(kind='spline', s=1e-2)",
"_____no_output_____"
],
[
"y = down_data[:,10,9]/np.max(down_data)",
"_____no_output_____"
],
[
"x = np.arange(0,len(y))",
"_____no_output_____"
],
[
"t = np.linspace(0,1,5)\nX = np.vstack((np.sin(t),np.cos(t))).T",
"_____no_output_____"
],
[
"plt.plot(y)",
"_____no_output_____"
],
[
"plt.plot(fd(y.reshape(-1,1),x))",
"_____no_output_____"
],
[
"y.shape",
"_____no_output_____"
],
[
"plt.plot(fd._differentiate(y.reshape(-1,1),x))\n",
"_____no_output_____"
],
[
"plt.plot(ux[:,10,6])",
"_____no_output_____"
],
[
"plt.plot(sol[:,10,6].detach().numpy())\nplt.plot(down_data[:,10,6]/np.max(down_data))",
"_____no_output_____"
],
[
"model.sparsity_masks",
"_____no_output_____"
]
],
[
[
"estimatior_coeffs gives the magnitude of the active terms:",
"_____no_output_____"
]
],
[
[
"print(model.estimator_coeffs())",
"[array([[ 0.02962998],\n [ 1.0108052 ],\n [ 0. ],\n [ 0.0981451 ],\n [ 0.21595249],\n [ 0. ],\n [-0.04595437],\n [ 0. ],\n [ 0. ],\n [ 0. ],\n [ 0. ],\n [ 0. ]], dtype=float32)]\n"
],
[
"plt.contourf(ux[:,:,10])",
"_____no_output_____"
],
[
"plt.plot(ux[25,:,2])",
"_____no_output_____"
],
[
"ax = plt.subplot(1,1,1)\nax.plot(fd(y.reshape(-1,1),x), label='Ground truth')\nax.plot(fd_sline(y_noisy.reshape(-1,1),x), label='Spline')\nax.plot(fd_sg(y_noisy.reshape(-1,1),x), label='Savitzky Golay')\nax.legend()",
"_____no_output_____"
],
[
"import pysindy as ps",
"_____no_output_____"
],
[
"fd_spline = ps.SINDyDerivative(kind='spline', s=1e-2)\nfd_spectral = ps.SINDyDerivative(kind='spectral')\nfd_sg = ps.SINDyDerivative(kind='savitzky_golay', left=0.5, right=0.5, order=3)",
"_____no_output_____"
],
[
"y = u_v[25,:,2]\nx = y_v[25,:,2]\nplt.scatter(x,y)",
"_____no_output_____"
],
[
"y.shape",
"_____no_output_____"
],
[
"noise_level = 0.025\ny_noisy = y + noise_level * np.std(y) * np.random.randn(y.size)",
"_____no_output_____"
],
[
"ax = plt.subplot(1,1,1)\nax.plot(x,y_noisy, label=\"line 1\")\nax.plot(x,y, label=\"line 2\")\nax.legend()",
"_____no_output_____"
],
[
"ax = plt.subplot(1,1,1)\nax.plot(fd(y.reshape(-1,1),x), label='Ground truth')\nax.plot(fd_sline(y_noisy.reshape(-1,1),x), label='Spline')\nax.plot(fd_sg(y_noisy.reshape(-1,1),x), label='Savitzky Golay')\nax.legend()\n",
"_____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",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ae2aa7249768cdfde0f83e07403270c2161264 | 300,857 | ipynb | Jupyter Notebook | PXL_DIGITAL_JAAR_2/AI & Robotics/Oplossingen/Spring_Break/jupyter/regressor.ipynb | RubenMoensJonkersPXL/PXL-DIGITAL | 86460ac0512e01a36e3e680500cdb317abdb3d07 | [
"MIT"
] | null | null | null | PXL_DIGITAL_JAAR_2/AI & Robotics/Oplossingen/Spring_Break/jupyter/regressor.ipynb | RubenMoensJonkersPXL/PXL-DIGITAL | 86460ac0512e01a36e3e680500cdb317abdb3d07 | [
"MIT"
] | null | null | null | PXL_DIGITAL_JAAR_2/AI & Robotics/Oplossingen/Spring_Break/jupyter/regressor.ipynb | RubenMoensJonkersPXL/PXL-DIGITAL | 86460ac0512e01a36e3e680500cdb317abdb3d07 | [
"MIT"
] | 1 | 2020-10-30T10:02:44.000Z | 2020-10-30T10:02:44.000Z | 104.210946 | 26,800 | 0.594768 | [
[
[
"## Decision Trees\n### Regression",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom sklearn import tree\nimport matplotlib.pyplot as plt\nimport graphviz",
"_____no_output_____"
]
],
[
[
"Create a random dataset",
"_____no_output_____"
]
],
[
[
"rng = np.random.RandomState(1)\nX = np.sort(5 * rng.rand(80, 1), axis=0)\ny = np.sin(X).ravel()\ny[::5] += 3 * (0.5 - rng.rand(16))\nX",
"_____no_output_____"
]
],
[
[
"Create decision trees",
"_____no_output_____"
]
],
[
[
"regr_1 = tree.DecisionTreeRegressor(max_depth=2)\nregr_2 = tree.DecisionTreeRegressor()",
"_____no_output_____"
]
],
[
[
"Fit regression models",
"_____no_output_____"
]
],
[
[
"regr_1.fit(X, y)\nregr_2.fit(X, y)",
"_____no_output_____"
]
],
[
[
"Predict",
"_____no_output_____"
]
],
[
[
"X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]\ny_1 = regr_1.predict(X_test)\ny_2 = regr_2.predict(X_test)",
"_____no_output_____"
]
],
[
[
"Plot the results",
"_____no_output_____"
]
],
[
[
"plt.figure()\nplt.scatter(X, y, s=20, edgecolor=\"black\",\n c=\"darkorange\", label=\"data\")\n#plt.plot(X_test, y_1, color=\"cornflowerblue\",\n# label=\"max_depth=2\", linewidth=2)\nplt.plot(X_test, y_2, color=\"yellowgreen\", label=\"max_depth=3\", linewidth=2)\nplt.xlabel(\"data\")\nplt.ylabel(\"target\")\nplt.title(\"Decision Tree Regression\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"Display the decision trees",
"_____no_output_____"
]
],
[
[
"dot_data = tree.export_graphviz(regr_1, out_file=None, \n filled=True, rounded=True, \n special_characters=True) \ngraph = graphviz.Source(dot_data) \ngraph",
"_____no_output_____"
],
[
"dot_data = tree.export_graphviz(regr_2, out_file=None, \n filled=True, rounded=True, \n special_characters=True) \ngraph = graphviz.Source(dot_data) \ngraph",
"_____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",
"code"
]
] |
d0ae2ce5155aadee076d4f4fe608eb6fb0e6104e | 47,712 | ipynb | Jupyter Notebook | web_10_Web Crawling Exercise.ipynb | hyeshinoh/Study_Web | 935f9db618b0879f0c6fedf7d670186d7f7eef6d | [
"MIT"
] | 1 | 2021-01-20T13:53:16.000Z | 2021-01-20T13:53:16.000Z | web_10_Web Crawling Exercise.ipynb | hyeshinoh/Study_Web | 935f9db618b0879f0c6fedf7d670186d7f7eef6d | [
"MIT"
] | null | null | null | web_10_Web Crawling Exercise.ipynb | hyeshinoh/Study_Web | 935f9db618b0879f0c6fedf7d670186d7f7eef6d | [
"MIT"
] | 1 | 2021-06-27T06:08:34.000Z | 2021-06-27T06:08:34.000Z | 29.932246 | 157 | 0.312521 | [
[
[
"# Web crawling exercise",
"_____no_output_____"
]
],
[
[
"from selenium import webdriver",
"_____no_output_____"
]
],
[
[
"## Quiz 1\n- 아래 URL의 NBA 데이터를 크롤링하여 판다스 데이터 프레임으로 나타내세요.\n- http://stats.nba.com/teams/traditional/?sort=GP&dir=-1",
"_____no_output_____"
],
[
"### 1.1 webdriver를 실행하고 사이트에 접속하기",
"_____no_output_____"
]
],
[
[
"driver = webdriver.Chrome() ",
"_____no_output_____"
],
[
"url = \"http://stats.nba.com/teams/traditional/?sort=GP&dir=-1\"",
"_____no_output_____"
],
[
"driver.get(url)",
"_____no_output_____"
]
],
[
[
"링크로 들어가면 GP로 정렬되어 있는 상태임 \n",
"_____no_output_____"
],
[
"### 1.2 표 데이터 받아오기",
"_____no_output_____"
],
[
"#### (1) column 이름을 받아와서 pandas dataframe 만들기",
"_____no_output_____"
]
],
[
[
"columns = driver.find_elements_by_css_selector(\"div.nba-stat-table__overflow > table > thead > tr > th\")[:28]\nlen(columns)",
"_____no_output_____"
],
[
"ls_column = []\nfor column in columns:\n ls_column.append(column.text)\n \nls_column",
"_____no_output_____"
],
[
"df = pd.DataFrame(columns = ls_column)\ndf",
"_____no_output_____"
]
],
[
[
"#### (2) 각 row의 팀별 데이터를 받아와서 dataframe에 넣기",
"_____no_output_____"
]
],
[
[
"team_stat = driver.find_elements_by_css_selector(\"div.nba-stat-table__overflow > table > tbody > tr\")\nlen(team_stat)",
"_____no_output_____"
],
[
"for stat in team_stat:\n stats = stat.find_elements_by_css_selector(\"td\")\n stat = {}\n for i in range(len(stats)):\n stat[ls_column[i]] = stats[i].text\n df.loc[len(df)] = stat\ndf",
"_____no_output_____"
],
[
"driver.quit()",
"_____no_output_____"
]
],
[
[
"## Quiz 2\n- Selenium을 이용하여 네이버 IT/과학 기사의 10 페이지 까지의 최신 제목 리스트를 크롤링하세요.\n- http://news.naver.com/main/main.nhn?mode=LSD&mid=shm&sid1=105",
"_____no_output_____"
],
[
"### 2.1 webdriver를 실행하고 사이트에 접속하기",
"_____no_output_____"
]
],
[
[
"driver = webdriver.Chrome() ",
"_____no_output_____"
],
[
"def make_url(page=1):\n return \"http://news.naver.com/main/main.nhn?mode=LSD&mid=shm&sid1=105#&date=%2000:00:00&page=\"\\\n + str(page)",
"_____no_output_____"
],
[
"url = make_url()",
"_____no_output_____"
],
[
"driver.get(url)",
"_____no_output_____"
]
],
[
[
"### 2.2 기사 제목 리스트 가져오기",
"_____no_output_____"
],
[
"#### (1) 1페이지에 대해 기사 제목 가져오기",
"_____no_output_____"
],
[
"##### 1페이지의 기사 리스트 가져오기\n- 한 페이지에 20개의 기사가 있음",
"_____no_output_____"
]
],
[
[
"articles = driver.find_elements_by_css_selector(\"#section_body > ul > li\")\nlen(articles)",
"_____no_output_____"
]
],
[
[
"##### 1페이지 안의 기사 제목 가져오기",
"_____no_output_____"
]
],
[
[
"dict_list = []\nfor article in articles:\n dict_list.append({\n \"title\": article.find_element_by_css_selector(\"dt:nth-child(2)\").text \n })\ndf = pd.DataFrame(dict_list)\ndf.tail() ",
"_____no_output_____"
]
],
[
[
"#### (2) 1-10페이지에서 기사 제목 가져오기\n- 2페이지와 7페이지에서 에러가 발생해서 try & except 처리함",
"_____no_output_____"
]
],
[
[
"dict_list = []\n\nfor i in range(1, 11):\n driver.get(make_url(i))\n articles = driver.find_elements_by_css_selector(\"#section_body > ul > li\")\n print(len(articles))\n try:\n for article in articles:\n dict_list.append({\"title\": article.find_element_by_css_selector(\"dl > dt:nth-child(2)\").text})\n except: \n print(str(i)+\"페이지 에러 발생\")\n \ndf = pd.DataFrame(dict_list)\ndf.tail()",
"20\n20\n2페이지 에러 발생\n20\n20\n20\n20\n20\n7페이지 에러 발생\n20\n20\n20\n"
]
],
[
[
"총 168개의 기사 제목이 크롤링됨",
"_____no_output_____"
]
],
[
[
"driver.quit()",
"_____no_output_____"
]
],
[
[
"#### 참고자료\n- 패스트캠퍼스, ⟪데이터사이언스스쿨 8기⟫ 수업자료",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d0ae3a8d05e31fde7330059e004a45b209409add | 9,378 | ipynb | Jupyter Notebook | 11_Day_Functions.ipynb | ayushjindal23/30-Days-Of-Python | 564564fb82a73a3f9be5634d46393fa88af4da6b | [
"MIT"
] | null | null | null | 11_Day_Functions.ipynb | ayushjindal23/30-Days-Of-Python | 564564fb82a73a3f9be5634d46393fa88af4da6b | [
"MIT"
] | null | null | null | 11_Day_Functions.ipynb | ayushjindal23/30-Days-Of-Python | 564564fb82a73a3f9be5634d46393fa88af4da6b | [
"MIT"
] | null | null | null | 19.995736 | 235 | 0.475581 | [
[
[
"### Functions",
"_____no_output_____"
]
],
[
[
"# syntax\n# Declaring a function\ndef function_name():\n codes\n codes\n# Calling a function\nfunction_name()",
"_____no_output_____"
],
[
"def generate_full_name ():\n first_name = 'Ayush'\n last_name = 'Jindal'\n space = ' '\n full_name = first_name + space + last_name\n print(full_name)\n \ngenerate_full_name () # calling a function\n\ndef add_two_numbers ():\n num_one = 2\n num_two = 3\n total = num_one + num_two\n print(total)\n \nadd_two_numbers()",
"Ayush Jindal\n5\n"
]
],
[
[
"### Function Returning a Value - Part 1",
"_____no_output_____"
]
],
[
[
"def generate_full_name ():\n first_name = 'Ayush'\n last_name = 'Jindal'\n space = ' '\n full_name = first_name + space + last_name\n return full_name\n \nprint(generate_full_name () )\n\ndef add_two_numbers ():\n num_one = 2\n num_two = 3\n total = num_one + num_two\n return total\n \nprint(add_two_numbers())",
"Ayush Jindal\n5\n"
]
],
[
[
"### Function with Parameters",
"_____no_output_____"
],
[
"- Single Parameter: If our function takes a parameter we should call our function with an argument",
"_____no_output_____"
]
],
[
[
"def greetings(name):\n message = name + ', Welcome to my Youtube Channel'\n return message\nprint(greetings('Ayush'))\n\ndef add_ten(num):\n ten = 10\n return num + 10\nprint(add_ten(10))\n\ndef sq(x):\n return x*x\nprint(sq(9))\n\ndef area(r):\n PI = 3.14\n area=PI*r**2\n return area\nprint(area(1))\n\ndef sum_of_numbers(n):\n total = 0\n for i in range(n+1):\n total+=i\n print(total)\nsum_of_numbers(10) # 55\nsum_of_numbers(100) # 5050",
"Ayush, Welcome to my Youtube Channel\n20\n81\n3.14\n55\n5050\n"
]
],
[
[
"- Two Parameter: A function may or may not have a parameter or parameters. A function may have two or more parameters. If our function takes parameters we should call it with arguments. Let's check a function with two parameters:",
"_____no_output_____"
]
],
[
[
"def generate_full_name (first_name, last_name):\n space = ' '\n full_name = first_name + space + last_name\n return full_name\n\nprint('Full Name: ', generate_full_name('Ayush','Jindal'))",
"Full Name: Ayush Jindal\n"
]
],
[
[
"### Passing Arguments with Key and Value",
"_____no_output_____"
],
[
"If we pass the arguments with key and value, the order of the arguments does not matter.",
"_____no_output_____"
]
],
[
[
"def add_two_numbers (num1, num2):\n total = num1 + num2\n print(total)\nadd_two_numbers(num2 = 3, num1 = 2) ",
"5\n"
]
],
[
[
"### Function Returning a Value - Part 2",
"_____no_output_____"
],
[
"- Returning a string:",
"_____no_output_____"
]
],
[
[
"def print_name(firstname):\n return firstname\nprint_name('Asabeneh') ",
"_____no_output_____"
]
],
[
[
"- Returning a number:",
"_____no_output_____"
]
],
[
[
"def add_two_numbers (num1, num2):\n total = num1 + num2\n return total\nprint(add_two_numbers(2, 3))\n",
"5\n"
]
],
[
[
"- Returning a boolean: ",
"_____no_output_____"
]
],
[
[
"def is_even (n):\n if n % 2 == 0:\n print('even')\n return True # return stops further execution of the function, similar to break \n return False\nprint(is_even(10))\nprint(is_even(7)) ",
"even\nTrue\nFalse\n"
]
],
[
[
"- Returning a list: ",
"_____no_output_____"
]
],
[
[
"def find_even_numbers(n):\n evens = []\n for i in range(n+1):\n if i % 2 == 0:\n evens.append(i)\n return evens\nprint(find_even_numbers(10))",
"[0, 2, 4, 6, 8, 10]\n"
]
],
[
[
"### Arbitrary Number of Arguments",
"_____no_output_____"
],
[
"If we do not know the number of arguments we pass to our function, we can create a function which can take arbitrary number of arguments by adding * before the parameter name.",
"_____no_output_____"
]
],
[
[
"def sum_all_nums(*nums):\n total = 0\n for num in nums:\n total += num # same as total = total + num \n return total\nprint(sum_all_nums(2, 3, 5))",
"10\n"
]
],
[
[
"### Default and Arbitrary Number of Parameters in Functions",
"_____no_output_____"
]
],
[
[
"def generate_groups (team,*args):\n print(team)\n for i in args:\n print(i)\ngenerate_groups('Team-1','Asabeneh','Brook','David','Eyob')",
"Team-1\nAsabeneh\nBrook\nDavid\nEyob\n"
]
],
[
[
"### Function as a Parameter of Another Function",
"_____no_output_____"
]
],
[
[
"def square_number (n):\n return n * n\ndef do_something(f, x):\n return f(x)\nprint(do_something(square_number, 3))",
"9\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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0ae49535f2e89b77c4196d5d7af416aef1cfb78 | 5,187 | ipynb | Jupyter Notebook | stage_3.ipynb | SuperSaiyan-God/Circuit | 55f667f5c8eca32eb7e6f7ee16ae3354fad876b9 | [
"MIT"
] | 1 | 2021-04-29T09:35:18.000Z | 2021-04-29T09:35:18.000Z | stage_3.ipynb | SuperSaiyan-God/Circuit | 55f667f5c8eca32eb7e6f7ee16ae3354fad876b9 | [
"MIT"
] | null | null | null | stage_3.ipynb | SuperSaiyan-God/Circuit | 55f667f5c8eca32eb7e6f7ee16ae3354fad876b9 | [
"MIT"
] | null | null | null | 22.552174 | 87 | 0.474648 | [
[
[
"from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute\nfrom qiskit import execute, Aer, BasicAer, IBMQ\nfrom qiskit.circuit import Gate\nfrom qiskit.tools.visualization import plot_histogram\nfrom qiskit.providers.aer import QasmSimulator\nfrom qiskit.compiler import transpile, assemble\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\nimport numpy as np\nfrom matplotlib import pyplot as plt",
"_____no_output_____"
],
[
"q0 = QuantumRegister(5, 'q0')\nswitch = QuantumCircuit(q0, name=\"Switch\")",
"_____no_output_____"
],
[
"switch.reset(q0[4])\nswitch.cx(q0[0],q0[1])\nswitch.ccx(q0[2],q0[1],q0[0])\nswitch.cx(q0[0],q0[1])\nswitch.barrier(q0[1])\nswitch.cx(q0[0],q0[1])\nswitch.ccx(q0[1],q0[2],q0[4])\nswitch.ccx(q0[3],q0[1],q0[0])\nswitch.cx(q0[0],q0[1])\nswitch.cx(q0[4],q0[0])\n\n\nswitch.draw(output='mpl')",
"_____no_output_____"
],
[
"q9 = QuantumRegister(5, 'q9')\nq8 = QuantumRegister(5, 'q8')\nq7 = QuantumRegister(5, 'q7')\nq6 = QuantumRegister(5, 'q6')\nc = ClassicalRegister(8, 'c')\n\na0 = QuantumCircuit(q9,q8,q7,q6,c)",
"_____no_output_____"
],
[
"inp1 = []\n\nfor i in range(0,8):\n inp = input(\"Enter I{}: \".format(i))\n inp1.append(inp)\n \nif inp1[0] == \"1\":\n a0.x(q9[0])\nif inp1[1] == \"1\":\n a0.x(q7[0])\nif inp1[2] == \"1\":\n a0.x(q8[0])\nif inp1[3] == \"1\":\n a0.x(q6[0])\nif inp1[4] == \"1\":\n a0.x(q9[1])\nif inp1[5] == \"1\":\n a0.x(q7[1])\nif inp1[6] == \"1\":\n a0.x(q8[1])\nif inp1[7] == \"1\":\n a0.x(q6[1])\n \n \ninp2 = input(\"Enter C0: \")\ninp3 = input(\"Enter C1: \")\n\nif inp2 == \"1\":\n a0.x(q9[2])\nif inp3 == \"1\":\n a0.x(q9[3])\nif inp2 == \"1\":\n a0.x(q8[2])\nif inp3 == \"1\":\n a0.x(q8[3])\nif inp2 == \"1\":\n a0.x(q7[2])\nif inp3 == \"1\":\n a0.x(q7[3])\nif inp2 == \"1\":\n a0.x(q6[2])\nif inp3 == \"1\":\n a0.x(q6[3])",
"_____no_output_____"
],
[
"register = switch.to_instruction()",
"_____no_output_____"
],
[
"a0.append(register, [q9[0],q7[0],q9[2],q9[3],q9[4]])\na0.append(register, [q8[0],q6[0],q8[2],q8[3],q8[4]])\na0.append(register, [q9[1],q7[1],q7[2],q7[3],q7[4]])\na0.append(register, [q8[1],q6[1],q6[2],q6[3],q6[4]])",
"_____no_output_____"
],
[
"a0.draw(output='mpl')",
"_____no_output_____"
],
[
"a0.measure(q9[0],c[0])\na0.measure(q7[0],c[1])\na0.measure(q8[0],c[2])\na0.measure(q6[0],c[3])\na0.measure(q9[1],c[4])\na0.measure(q7[1],c[5])\na0.measure(q8[1],c[6])\na0.measure(q6[1],c[7])",
"_____no_output_____"
],
[
"a0.draw(output='mpl')",
"_____no_output_____"
],
[
"simulator = QasmSimulator()",
"_____no_output_____"
],
[
"result = execute(a0, backend=simulator).result()",
"_____no_output_____"
],
[
"plot_histogram(result.get_counts(a0))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ae51af4ebe2fa9baca8630eb4ad9aede275701 | 23,005 | ipynb | Jupyter Notebook | Bases de Sympy.ipynb | CogniMath/MPC | d3d0b70be6a209aa67a8f6b4ef2dff352228a922 | [
"MIT"
] | null | null | null | Bases de Sympy.ipynb | CogniMath/MPC | d3d0b70be6a209aa67a8f6b4ef2dff352228a922 | [
"MIT"
] | null | null | null | Bases de Sympy.ipynb | CogniMath/MPC | d3d0b70be6a209aa67a8f6b4ef2dff352228a922 | [
"MIT"
] | 1 | 2021-01-26T17:58:00.000Z | 2021-01-26T17:58:00.000Z | 33.053161 | 10,364 | 0.681026 | [
[
[
"# Modelización de Procesos Cognitivos: Bases de Sympy y Conjuntos",
"_____no_output_____"
],
[
"## Conjuntos",
"_____no_output_____"
],
[
"Hagamos operaciones de conjuntos",
"_____no_output_____"
]
],
[
[
"# Definamos primero los dos conjuntos a trabajar\nc1 = {3,6,2,7,8}\nc2 = {1,2,6,3}",
"_____no_output_____"
],
[
"#Trabajemos primero con la unión de conjuntos que se denota por el operador |\nc1|c2",
"_____no_output_____"
],
[
"# De manera opcional se puede emplear el comando print\nprint(c1|c2)",
"{1, 2, 3, 6, 7, 8}\n"
],
[
"# Para el caso de la intersección de conjuntos se emplea el operador &\nc1&c2",
"_____no_output_____"
],
[
"# la diferencia de conjuntos se denota por -, que son los elemetos que están en A pero no están en B\nc1-c2",
"_____no_output_____"
]
],
[
[
"Se puede también trabajar con caracteres",
"_____no_output_____"
]
],
[
[
"# por ejemplo los conjuntos de nombres de personas\na1 = {'juan','jenny','sandra','noe'}\na2 = {'jose', 'rita', 'juan', 'ramon', 'sandra'}",
"_____no_output_____"
],
[
"print(a1|a2)\nprint(a1&a2)\nprint(a1-a2)",
"{'juan', 'jenny', 'jose', 'sandra', 'ramon', 'noe', 'rita'}\n{'juan', 'sandra'}\n{'noe', 'jenny'}\n"
]
],
[
[
"## Calculo con Sympy",
"_____no_output_____"
]
],
[
[
"from __future__ import division\nfrom sympy import * # Para importar todas las funciones de Sympy\nx, y, z, t = symbols('x y z t')\nk, m, n = symbols('k m n', integer = True)\nf, g, h = symbols('f g h', cls = Function)",
"_____no_output_____"
]
],
[
[
"Podemos ocupar Sympy para resolver ecuaciones como $x^2 + 9 x - 70 = 0$",
"_____no_output_____"
]
],
[
[
"solve(x**2 + 9*x - 70, x) # se resuelve la ecuación para x",
"_____no_output_____"
]
],
[
[
"Se pueden factorizar ecuaciones como $x^2 - x - 6$",
"_____no_output_____"
]
],
[
[
"factor(x**2 - x - 6)",
"_____no_output_____"
]
],
[
[
"Se pueden expandir los términos",
"_____no_output_____"
]
],
[
[
"expr1 = (3*x**2 + 5*x)*(x - 2)\nexpand(expr1)",
"_____no_output_____"
]
],
[
[
"Se pueden resolver sistemas de ecuaciones: por ejemplo, las ecuaciones $x+3y=4$ y $2x+5y=5$",
"_____no_output_____"
]
],
[
[
"solve([x + 3*y - 4, 2*x + 5*y -5],[x,y])",
"_____no_output_____"
]
],
[
[
"Se puede trabajar con polinomios",
"_____no_output_____"
]
],
[
[
"P = (x - 3)*(x - 4)*(x - 6)\nP",
"_____no_output_____"
],
[
"P.expand()",
"_____no_output_____"
],
[
"P.factor()",
"_____no_output_____"
]
],
[
[
"Se pueden extraer las raíces (soluciones) del polinomio",
"_____no_output_____"
]
],
[
[
"raices = solve(P,x)\nraices",
"_____no_output_____"
]
],
[
[
"Se pueden definir funciones por ejemplo: $f(x) = x^2$",
"_____no_output_____"
]
],
[
[
"def f(x):\n return x**2 # definimos la función x^2",
"_____no_output_____"
],
[
"f(2) # se sustituye el valor de interes",
"_____no_output_____"
],
[
"f(x)",
"_____no_output_____"
]
],
[
[
"Podemos trabajar con límites dentro de Sympy",
"_____no_output_____"
]
],
[
[
"limit(x**2, x, 0)",
"_____no_output_____"
],
[
"limit(1/x, x, 0)",
"_____no_output_____"
],
[
"limit(1/x, x, oo)",
"_____no_output_____"
]
],
[
[
"Y se pueden evaluar límites lateral",
"_____no_output_____"
]
],
[
[
"print(limit(x/abs(x), x, 0, dir='+'))\nprint(limit(x/abs(x), x, 0, dir='-'))",
"1\n-1\n"
],
[
"p1 = plot(x/abs(x),show=False)\np1.show()",
"_____no_output_____"
]
],
[
[
"Se pueden obtener las derivadas de la funciones por medio del comando **diff(f(x), x)**. Así por ejemplo, para la función lineal $f(x) = x$",
"_____no_output_____"
]
],
[
[
"def f(x): \n return x # se define la función f(x) = x",
"_____no_output_____"
],
[
"diff(f(x), x) # se calcula la respectiva derivada",
"_____no_output_____"
],
[
"diff(x, x) # o simplemente calcular la derivada de la expresión sin necesidad de definir la función",
"_____no_output_____"
],
[
"diff(x**k, x)",
"_____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",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0ae5acb2f97fd1d5188fcab8e8a6e3d9dedde33 | 67,243 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb | aadimangla/Custom-Trained-Recurrent-Neural-Network | 2fd76e1008b829df86851d1e07a2c6ff2efdebe6 | [
"MIT"
] | 1 | 2020-09-08T07:51:36.000Z | 2020-09-08T07:51:36.000Z | .ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb | aadimangla/Custom-Trained-Recurrent-Neural-Network | 2fd76e1008b829df86851d1e07a2c6ff2efdebe6 | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Building_a_Recurrent_Neural_Network_Step_by_Step_v3a-checkpoint.ipynb | aadimangla/Custom-Trained-Recurrent-Neural-Network | 2fd76e1008b829df86851d1e07a2c6ff2efdebe6 | [
"MIT"
] | null | null | null | 35.843817 | 319 | 0.461371 | [
[
[
"# Custom Building Recurrent Neural Network\n\n**Notation**:\n- Superscript $[l]$ denotes an object associated with the $l^{th}$ layer. \n\n- Superscript $(i)$ denotes an object associated with the $i^{th}$ example. \n\n- Superscript $\\langle t \\rangle$ denotes an object at the $t^{th}$ time-step. \n \n- **Sub**script $i$ denotes the $i^{th}$ entry of a vector.\n\nExample: \n- $a^{(2)[3]<4>}_5$ denotes the activation of the 2nd training example (2), 3rd layer [3], 4th time step <4>, and 5th entry in the vector.\n",
"_____no_output_____"
],
[
"Let's first import all the packages.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom rnn_utils import *",
"_____no_output_____"
]
],
[
[
"## Forward propagation for the basic Recurrent Neural Network\n\n",
"_____no_output_____"
],
[
"## RNN cell",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: rnn_cell_forward\n\ndef rnn_cell_forward(xt, a_prev, parameters):\n # Retrieve parameters from \"parameters\"\n Wax = parameters[\"Wax\"]\n Waa = parameters[\"Waa\"]\n Wya = parameters[\"Wya\"]\n ba = parameters[\"ba\"]\n by = parameters[\"by\"]\n \n \n # compute next activation state using the formula given above\n a_next = a_next = np.tanh(np.dot(Wax, xt) + np.dot(Waa, a_prev) + ba)\n # compute output of the current cell using the formula given above\n yt_pred = softmax(np.dot(Wya, a_next) + by) \n\n \n # store values you need for backward propagation in cache\n cache = (a_next, a_prev, xt, parameters)\n \n return a_next, yt_pred, cache",
"_____no_output_____"
],
[
"np.random.seed(1)\nxt_tmp = np.random.randn(3,10)\na_prev_tmp = np.random.randn(5,10)\nparameters_tmp = {}\nparameters_tmp['Waa'] = np.random.randn(5,5)\nparameters_tmp['Wax'] = np.random.randn(5,3)\nparameters_tmp['Wya'] = np.random.randn(2,5)\nparameters_tmp['ba'] = np.random.randn(5,1)\nparameters_tmp['by'] = np.random.randn(2,1)\n\na_next_tmp, yt_pred_tmp, cache_tmp = rnn_cell_forward(xt_tmp, a_prev_tmp, parameters_tmp)\nprint(\"a_next[4] = \\n\", a_next_tmp[4])\nprint(\"a_next.shape = \\n\", a_next_tmp.shape)\nprint(\"yt_pred[1] =\\n\", yt_pred_tmp[1])\nprint(\"yt_pred.shape = \\n\", yt_pred_tmp.shape)",
"a_next[4] = \n [ 0.59584544 0.18141802 0.61311866 0.99808218 0.85016201 0.99980978\n -0.18887155 0.99815551 0.6531151 0.82872037]\na_next.shape = \n (5, 10)\nyt_pred[1] =\n [ 0.9888161 0.01682021 0.21140899 0.36817467 0.98988387 0.88945212\n 0.36920224 0.9966312 0.9982559 0.17746526]\nyt_pred.shape = \n (2, 10)\n"
]
],
[
[
"## 1.2 - RNN forward pass \n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: rnn_forward\n\ndef rnn_forward(x, a0, parameters):\n # Initialize \"caches\" which will contain the list of all caches\n caches = []\n \n # Retrieve dimensions from shapes of x and parameters[\"Wya\"]\n n_x, m, T_x = x.shape\n n_y, n_a = parameters[\"Wya\"].shape\n \n \n \n # initialize \"a\" and \"y_pred\" with zeros (≈2 lines)\n a = np.zeros((n_a, m, T_x))\n y_pred = np.zeros((n_y, m, T_x))\n \n # Initialize a_next (≈1 line)\n a_next = a0\n \n # loop over all time-steps of the input 'x' (1 line)\n for t in range(T_x):\n # Update next hidden state, compute the prediction, get the cache (≈1 line)\n a_next, yt_pred, cache = rnn_cell_forward(x[:,:,t], a_next, parameters)\n # Save the value of the new \"next\" hidden state in a (≈1 line)\n a[:,:,t] = a_next\n # Save the value of the prediction in y (≈1 line)\n y_pred[:,:,t] = yt_pred\n # Append \"cache\" to \"caches\" (≈1 line)\n caches.append(cache)\n \n \n \n # store values needed for backward propagation in cache\n caches = (caches, x)\n \n return a, y_pred, caches",
"_____no_output_____"
],
[
"np.random.seed(1)\nx_tmp = np.random.randn(3,10,4)\na0_tmp = np.random.randn(5,10)\nparameters_tmp = {}\nparameters_tmp['Waa'] = np.random.randn(5,5)\nparameters_tmp['Wax'] = np.random.randn(5,3)\nparameters_tmp['Wya'] = np.random.randn(2,5)\nparameters_tmp['ba'] = np.random.randn(5,1)\nparameters_tmp['by'] = np.random.randn(2,1)\n\na_tmp, y_pred_tmp, caches_tmp = rnn_forward(x_tmp, a0_tmp, parameters_tmp)\nprint(\"a[4][1] = \\n\", a_tmp[4][1])\nprint(\"a.shape = \\n\", a_tmp.shape)\nprint(\"y_pred[1][3] =\\n\", y_pred_tmp[1][3])\nprint(\"y_pred.shape = \\n\", y_pred_tmp.shape)\nprint(\"caches[1][1][3] =\\n\", caches_tmp[1][1][3])\nprint(\"len(caches) = \\n\", len(caches_tmp))",
"a[4][1] = \n [-0.99999375 0.77911235 -0.99861469 -0.99833267]\na.shape = \n (5, 10, 4)\ny_pred[1][3] =\n [ 0.79560373 0.86224861 0.11118257 0.81515947]\ny_pred.shape = \n (2, 10, 4)\ncaches[1][1][3] =\n [-1.1425182 -0.34934272 -0.20889423 0.58662319]\nlen(caches) = \n 2\n"
]
],
[
[
"## Long Short-Term Memory (LSTM) network\n",
"_____no_output_____"
],
[
"### Overview of gates and states\n\n#### - Forget gate $\\mathbf{\\Gamma}_{f}$\n\n* Let's assume we are reading words in a piece of text, and plan to use an LSTM to keep track of grammatical structures, such as whether the subject is singular (\"puppy\") or plural (\"puppies\"). \n* If the subject changes its state (from a singular word to a plural word), the memory of the previous state becomes outdated, so we \"forget\" that outdated state.\n* The \"forget gate\" is a tensor containing values that are between 0 and 1.\n * If a unit in the forget gate has a value close to 0, the LSTM will \"forget\" the stored state in the corresponding unit of the previous cell state.\n * If a unit in the forget gate has a value close to 1, the LSTM will mostly remember the corresponding value in the stored state.\n\n##### Equation\n\n$$\\mathbf{\\Gamma}_f^{\\langle t \\rangle} = \\sigma(\\mathbf{W}_f[\\mathbf{a}^{\\langle t-1 \\rangle}, \\mathbf{x}^{\\langle t \\rangle}] + \\mathbf{b}_f)\\tag{1} $$\n\n##### Explanation of the equation:\n\n* $\\mathbf{W_{f}}$ contains weights that govern the forget gate's behavior. \n* The previous time step's hidden state $[a^{\\langle t-1 \\rangle}$ and current time step's input $x^{\\langle t \\rangle}]$ are concatenated together and multiplied by $\\mathbf{W_{f}}$. \n* A sigmoid function is used to make each of the gate tensor's values $\\mathbf{\\Gamma}_f^{\\langle t \\rangle}$ range from 0 to 1.\n* The forget gate $\\mathbf{\\Gamma}_f^{\\langle t \\rangle}$ has the same dimensions as the previous cell state $c^{\\langle t-1 \\rangle}$. \n* This means that the two can be multiplied together, element-wise.\n* Multiplying the tensors $\\mathbf{\\Gamma}_f^{\\langle t \\rangle} * \\mathbf{c}^{\\langle t-1 \\rangle}$ is like applying a mask over the previous cell state.\n* If a single value in $\\mathbf{\\Gamma}_f^{\\langle t \\rangle}$ is 0 or close to 0, then the product is close to 0.\n * This keeps the information stored in the corresponding unit in $\\mathbf{c}^{\\langle t-1 \\rangle}$ from being remembered for the next time step.\n* Similarly, if one value is close to 1, the product is close to the original value in the previous cell state.\n * The LSTM will keep the information from the corresponding unit of $\\mathbf{c}^{\\langle t-1 \\rangle}$, to be used in the next time step.\n \n##### Variable names in the code\nThe variable names in the code are similar to the equations, with slight differences. \n* `Wf`: forget gate weight $\\mathbf{W}_{f}$\n* `Wb`: forget gate bias $\\mathbf{W}_{b}$\n* `ft`: forget gate $\\Gamma_f^{\\langle t \\rangle}$",
"_____no_output_____"
],
[
"#### Candidate value $\\tilde{\\mathbf{c}}^{\\langle t \\rangle}$\n* The candidate value is a tensor containing information from the current time step that **may** be stored in the current cell state $\\mathbf{c}^{\\langle t \\rangle}$.\n* Which parts of the candidate value get passed on depends on the update gate.\n* The candidate value is a tensor containing values that range from -1 to 1.\n* The tilde \"~\" is used to differentiate the candidate $\\tilde{\\mathbf{c}}^{\\langle t \\rangle}$ from the cell state $\\mathbf{c}^{\\langle t \\rangle}$.\n\n##### Equation\n$$\\mathbf{\\tilde{c}}^{\\langle t \\rangle} = \\tanh\\left( \\mathbf{W}_{c} [\\mathbf{a}^{\\langle t - 1 \\rangle}, \\mathbf{x}^{\\langle t \\rangle}] + \\mathbf{b}_{c} \\right) \\tag{3}$$\n\n##### Explanation of the equation\n* The 'tanh' function produces values between -1 and +1.\n\n\n##### Variable names in the code\n* `cct`: candidate value $\\mathbf{\\tilde{c}}^{\\langle t \\rangle}$",
"_____no_output_____"
],
[
"#### - Update gate $\\mathbf{\\Gamma}_{i}$\n\n* We use the update gate to decide what aspects of the candidate $\\tilde{\\mathbf{c}}^{\\langle t \\rangle}$ to add to the cell state $c^{\\langle t \\rangle}$.\n* The update gate decides what parts of a \"candidate\" tensor $\\tilde{\\mathbf{c}}^{\\langle t \\rangle}$ are passed onto the cell state $\\mathbf{c}^{\\langle t \\rangle}$.\n* The update gate is a tensor containing values between 0 and 1.\n * When a unit in the update gate is close to 1, it allows the value of the candidate $\\tilde{\\mathbf{c}}^{\\langle t \\rangle}$ to be passed onto the hidden state $\\mathbf{c}^{\\langle t \\rangle}$\n * When a unit in the update gate is close to 0, it prevents the corresponding value in the candidate from being passed onto the hidden state.\n* Notice that we use the subscript \"i\" and not \"u\", to follow the convention used in the literature.\n\n##### Equation\n\n$$\\mathbf{\\Gamma}_i^{\\langle t \\rangle} = \\sigma(\\mathbf{W}_i[a^{\\langle t-1 \\rangle}, \\mathbf{x}^{\\langle t \\rangle}] + \\mathbf{b}_i)\\tag{2} $$ \n\n##### Explanation of the equation\n\n* Similar to the forget gate, here $\\mathbf{\\Gamma}_i^{\\langle t \\rangle}$, the sigmoid produces values between 0 and 1.\n* The update gate is multiplied element-wise with the candidate, and this product ($\\mathbf{\\Gamma}_{i}^{\\langle t \\rangle} * \\tilde{c}^{\\langle t \\rangle}$) is used in determining the cell state $\\mathbf{c}^{\\langle t \\rangle}$.\n\n##### Variable names in code (Please note that they're different than the equations)\nIn the code, we'll use the variable names found in the academic literature. These variables don't use \"u\" to denote \"update\".\n* `Wi` is the update gate weight $\\mathbf{W}_i$ (not \"Wu\") \n* `bi` is the update gate bias $\\mathbf{b}_i$ (not \"bu\")\n* `it` is the forget gate $\\mathbf{\\Gamma}_i^{\\langle t \\rangle}$ (not \"ut\")",
"_____no_output_____"
],
[
"#### - Cell state $\\mathbf{c}^{\\langle t \\rangle}$\n\n* The cell state is the \"memory\" that gets passed onto future time steps.\n* The new cell state $\\mathbf{c}^{\\langle t \\rangle}$ is a combination of the previous cell state and the candidate value.\n\n##### Equation\n\n$$ \\mathbf{c}^{\\langle t \\rangle} = \\mathbf{\\Gamma}_f^{\\langle t \\rangle}* \\mathbf{c}^{\\langle t-1 \\rangle} + \\mathbf{\\Gamma}_{i}^{\\langle t \\rangle} *\\mathbf{\\tilde{c}}^{\\langle t \\rangle} \\tag{4} $$\n\n##### Explanation of equation\n* The previous cell state $\\mathbf{c}^{\\langle t-1 \\rangle}$ is adjusted (weighted) by the forget gate $\\mathbf{\\Gamma}_{f}^{\\langle t \\rangle}$\n* and the candidate value $\\tilde{\\mathbf{c}}^{\\langle t \\rangle}$, adjusted (weighted) by the update gate $\\mathbf{\\Gamma}_{i}^{\\langle t \\rangle}$\n\n##### Variable names and shapes in the code\n* `c`: cell state, including all time steps, $\\mathbf{c}$ shape $(n_{a}, m, T)$\n* `c_next`: new (next) cell state, $\\mathbf{c}^{\\langle t \\rangle}$ shape $(n_{a}, m)$\n* `c_prev`: previous cell state, $\\mathbf{c}^{\\langle t-1 \\rangle}$, shape $(n_{a}, m)$",
"_____no_output_____"
],
[
"#### - Output gate $\\mathbf{\\Gamma}_{o}$\n\n* The output gate decides what gets sent as the prediction (output) of the time step.\n* The output gate is like the other gates. It contains values that range from 0 to 1.\n\n##### Equation\n\n$$ \\mathbf{\\Gamma}_o^{\\langle t \\rangle}= \\sigma(\\mathbf{W}_o[\\mathbf{a}^{\\langle t-1 \\rangle}, \\mathbf{x}^{\\langle t \\rangle}] + \\mathbf{b}_{o})\\tag{5}$$ \n\n##### Explanation of the equation\n* The output gate is determined by the previous hidden state $\\mathbf{a}^{\\langle t-1 \\rangle}$ and the current input $\\mathbf{x}^{\\langle t \\rangle}$\n* The sigmoid makes the gate range from 0 to 1.\n\n\n##### Variable names in the code\n* `Wo`: output gate weight, $\\mathbf{W_o}$\n* `bo`: output gate bias, $\\mathbf{b_o}$\n* `ot`: output gate, $\\mathbf{\\Gamma}_{o}^{\\langle t \\rangle}$",
"_____no_output_____"
],
[
"### LSTM cell\n\n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: lstm_cell_forward\n\ndef lstm_cell_forward(xt, a_prev, c_prev, parameters):\n # Retrieve parameters from \"parameters\"\n Wf = parameters[\"Wf\"] # forget gate weight\n bf = parameters[\"bf\"]\n Wi = parameters[\"Wi\"] # update gate weight (notice the variable name)\n bi = parameters[\"bi\"] # (notice the variable name)\n Wc = parameters[\"Wc\"] # candidate value weight\n bc = parameters[\"bc\"]\n Wo = parameters[\"Wo\"] # output gate weight\n bo = parameters[\"bo\"]\n Wy = parameters[\"Wy\"] # prediction weight\n by = parameters[\"by\"]\n \n # Retrieve dimensions from shapes of xt and Wy\n n_x, m = xt.shape\n n_y, n_a = Wy.shape\n\n \n # Concatenate a_prev and xt (≈1 line)\n concat = np.zeros((n_a + n_x, m))\n concat[: n_a, :] = a_prev\n concat[n_a :, :] = xt\n\n\n # Compute values for ft (forget gate), it (update gate),\n # cct (candidate value), c_next (cell state), \n # ot (output gate), a_next (hidden state) (≈6 lines)\n ft = sigmoid(np.dot(Wf, concat) + bf)\n it = sigmoid(np.dot(Wi, concat) + bi)\n cct = np.tanh(np.dot(Wc, concat) + bc)\n c_next = ft * c_prev + it * cct\n ot = sigmoid(np.dot(Wo, concat) + bo)\n a_next = ot * np.tanh(c_next)\n \n # Compute prediction of the LSTM cell (≈1 line)\n yt_pred = softmax(np.dot(Wy, a_next) + by)\n \n\n # store values needed for backward propagation in cache\n cache = (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters)\n\n return a_next, c_next, yt_pred, cache",
"_____no_output_____"
],
[
"np.random.seed(1)\nxt_tmp = np.random.randn(3,10)\na_prev_tmp = np.random.randn(5,10)\nc_prev_tmp = np.random.randn(5,10)\nparameters_tmp = {}\nparameters_tmp['Wf'] = np.random.randn(5, 5+3)\nparameters_tmp['bf'] = np.random.randn(5,1)\nparameters_tmp['Wi'] = np.random.randn(5, 5+3)\nparameters_tmp['bi'] = np.random.randn(5,1)\nparameters_tmp['Wo'] = np.random.randn(5, 5+3)\nparameters_tmp['bo'] = np.random.randn(5,1)\nparameters_tmp['Wc'] = np.random.randn(5, 5+3)\nparameters_tmp['bc'] = np.random.randn(5,1)\nparameters_tmp['Wy'] = np.random.randn(2,5)\nparameters_tmp['by'] = np.random.randn(2,1)\n\na_next_tmp, c_next_tmp, yt_tmp, cache_tmp = lstm_cell_forward(xt_tmp, a_prev_tmp, c_prev_tmp, parameters_tmp)\nprint(\"a_next[4] = \\n\", a_next_tmp[4])\nprint(\"a_next.shape = \", c_next_tmp.shape)\nprint(\"c_next[2] = \\n\", c_next_tmp[2])\nprint(\"c_next.shape = \", c_next_tmp.shape)\nprint(\"yt[1] =\", yt_tmp[1])\nprint(\"yt.shape = \", yt_tmp.shape)\nprint(\"cache[1][3] =\\n\", cache_tmp[1][3])\nprint(\"len(cache) = \", len(cache_tmp))",
"a_next[4] = \n [-0.66408471 0.0036921 0.02088357 0.22834167 -0.85575339 0.00138482\n 0.76566531 0.34631421 -0.00215674 0.43827275]\na_next.shape = (5, 10)\nc_next[2] = \n [ 0.63267805 1.00570849 0.35504474 0.20690913 -1.64566718 0.11832942\n 0.76449811 -0.0981561 -0.74348425 -0.26810932]\nc_next.shape = (5, 10)\nyt[1] = [ 0.79913913 0.15986619 0.22412122 0.15606108 0.97057211 0.31146381\n 0.00943007 0.12666353 0.39380172 0.07828381]\nyt.shape = (2, 10)\ncache[1][3] =\n [-0.16263996 1.03729328 0.72938082 -0.54101719 0.02752074 -0.30821874\n 0.07651101 -1.03752894 1.41219977 -0.37647422]\nlen(cache) = 10\n"
]
],
[
[
"### Forward pass for LSTM\n\n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: lstm_forward\n\ndef lstm_forward(x, a0, parameters):\n # Initialize \"caches\", which will track the list of all the caches\n caches = []\n \n \n # Retrieve dimensions from shapes of x and Wy (≈2 lines)\n n_x, m, T_x = x.shape\n n_y, n_a = parameters[\"Wy\"].shape\n \n # initialize \"a\", \"c\" and \"y\" with zeros (≈3 lines)\n a = np.zeros((n_a, m, T_x))\n c = np.zeros((n_a, m, T_x))\n y = np.zeros((n_y, m, T_x))\n \n # Initialize a_next and c_next (≈2 lines)\n a_next = a0\n c_next = np.zeros(a_next.shape)\n \n # loop over all time-steps\n for t in range(T_x):\n # Update next hidden state, next memory state, compute the prediction, get the cache (≈1 line)\n a_next, c_next, yt, cache = lstm_cell_forward(x[:, :, t], a_next, c_next, parameters)\n # Save the value of the new \"next\" hidden state in a (≈1 line)\n a[:,:,t] = a_next\n # Save the value of the prediction in y (≈1 line)\n y[:,:,t] = yt\n # Save the value of the next cell state (≈1 line)\n c[:,:,t] = c_next\n # Append the cache into caches (≈1 line)\n caches.append(cache)\n\n \n # store values needed for backward propagation in cache\n caches = (caches, x)\n\n return a, y, c, caches",
"_____no_output_____"
],
[
"np.random.seed(1)\nx_tmp = np.random.randn(3,10,7)\na0_tmp = np.random.randn(5,10)\nparameters_tmp = {}\nparameters_tmp['Wf'] = np.random.randn(5, 5+3)\nparameters_tmp['bf'] = np.random.randn(5,1)\nparameters_tmp['Wi'] = np.random.randn(5, 5+3)\nparameters_tmp['bi']= np.random.randn(5,1)\nparameters_tmp['Wo'] = np.random.randn(5, 5+3)\nparameters_tmp['bo'] = np.random.randn(5,1)\nparameters_tmp['Wc'] = np.random.randn(5, 5+3)\nparameters_tmp['bc'] = np.random.randn(5,1)\nparameters_tmp['Wy'] = np.random.randn(2,5)\nparameters_tmp['by'] = np.random.randn(2,1)\n\na_tmp, y_tmp, c_tmp, caches_tmp = lstm_forward(x_tmp, a0_tmp, parameters_tmp)\nprint(\"a[4][3][6] = \", a_tmp[4][3][6])\nprint(\"a.shape = \", a_tmp.shape)\nprint(\"y[1][4][3] =\", y_tmp[1][4][3])\nprint(\"y.shape = \", y_tmp.shape)\nprint(\"caches[1][1][1] =\\n\", caches_tmp[1][1][1])\nprint(\"c[1][2][1]\", c_tmp[1][2][1])\nprint(\"len(caches) = \", len(caches_tmp))",
"a[4][3][6] = 0.172117767533\na.shape = (5, 10, 7)\ny[1][4][3] = 0.95087346185\ny.shape = (2, 10, 7)\ncaches[1][1][1] =\n [ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139\n 0.41005165]\nc[1][2][1] -0.855544916718\nlen(caches) = 2\n"
]
],
[
[
"**Expected Output**:\n\n```Python\na[4][3][6] = 0.172117767533\na.shape = (5, 10, 7)\ny[1][4][3] = 0.95087346185\ny.shape = (2, 10, 7)\ncaches[1][1][1] =\n [ 0.82797464 0.23009474 0.76201118 -0.22232814 -0.20075807 0.18656139\n 0.41005165]\nc[1][2][1] -0.855544916718\nlen(caches) = 2\n```",
"_____no_output_____"
],
[
"## Backpropagation in recurrent neural networks",
"_____no_output_____"
],
[
"This section is optional and ungraded. It is more difficult and has fewer details regarding its implementation. This section only implements key elements of the full path.",
"_____no_output_____"
],
[
"### Basic RNN backward pass\n",
"_____no_output_____"
],
[
"##### Equations\nTo compute the rnn_cell_backward you can utilize the following equations. It is a good exercise to derive them by hand. Here, $*$ denotes element-wise multiplication while the absence of a symbol indicates matrix multiplication.\n\n$a^{\\langle t \\rangle} = \\tanh(W_{ax} x^{\\langle t \\rangle} + W_{aa} a^{\\langle t-1 \\rangle} + b_{a})\\tag{-}$\n \n$\\displaystyle \\frac{\\partial \\tanh(x)} {\\partial x} = 1 - \\tanh^2(x) \\tag{-}$\n \n$\\displaystyle {dW_{ax}} = da_{next} * ( 1-\\tanh^2(W_{ax}x^{\\langle t \\rangle}+W_{aa} a^{\\langle t-1 \\rangle} + b_{a}) ) x^{\\langle t \\rangle T}\\tag{1}$\n\n$\\displaystyle dW_{aa} = da_{next} * (( 1-\\tanh^2(W_{ax}x^{\\langle t \\rangle}+W_{aa} a^{\\langle t-1 \\rangle} + b_{a}) ) a^{\\langle t-1 \\rangle T}\\tag{2}$\n\n$\\displaystyle db_a = da_{next} * \\sum_{batch}( 1-\\tanh^2(W_{ax}x^{\\langle t \\rangle}+W_{aa} a^{\\langle t-1 \\rangle} + b_{a}) )\\tag{3}$\n \n$\\displaystyle dx^{\\langle t \\rangle} = da_{next} * { W_{ax}}^T ( 1-\\tanh^2(W_{ax}x^{\\langle t \\rangle}+W_{aa} a^{\\langle t-1 \\rangle} + b_{a}) )\\tag{4}$\n \n$\\displaystyle da_{prev} = da_{next} * { W_{aa}}^T ( 1-\\tanh^2(W_{ax}x^{\\langle t \\rangle}+W_{aa} a^{\\langle t-1 \\rangle} + b_{a}) )\\tag{5}$\n",
"_____no_output_____"
],
[
"#### Implementing rnn_cell_backward\n",
"_____no_output_____"
]
],
[
[
"def rnn_cell_backward(da_next, cache):\n # Retrieve values from cache\n (a_next, a_prev, xt, parameters) = cache\n \n # Retrieve values from parameters\n Wax = parameters[\"Wax\"]\n Waa = parameters[\"Waa\"]\n Wya = parameters[\"Wya\"]\n ba = parameters[\"ba\"]\n by = parameters[\"by\"]\n\n \n # compute the gradient of the loss with respect to z (optional) (≈1 line)\n dtanh = (1 - a_next ** 2) * da_next\n\n # compute the gradient of the loss with respect to Wax (≈2 lines)\n dxt = np.dot(Wax.T, dtanh) \n dWax = np.dot(dtanh, xt.T)\n\n # compute the gradient with respect to Waa (≈2 lines)\n da_prev = np.dot(Waa.T, dtanh)\n dWaa = np.dot(dtanh, a_prev.T)\n\n # compute the gradient with respect to b (≈1 line)\n dba = np.sum(dtanh, axis = 1,keepdims=1)\n\n\n \n \n # Store the gradients in a python dictionary\n gradients = {\"dxt\": dxt, \"da_prev\": da_prev, \"dWax\": dWax, \"dWaa\": dWaa, \"dba\": dba}\n \n return gradients",
"_____no_output_____"
],
[
"np.random.seed(1)\nxt_tmp = np.random.randn(3,10)\na_prev_tmp = np.random.randn(5,10)\nparameters_tmp = {}\nparameters_tmp['Wax'] = np.random.randn(5,3)\nparameters_tmp['Waa'] = np.random.randn(5,5)\nparameters_tmp['Wya'] = np.random.randn(2,5)\nparameters_tmp['ba'] = np.random.randn(5,1)\nparameters_tmp['by'] = np.random.randn(2,1)\n\na_next_tmp, yt_tmp, cache_tmp = rnn_cell_forward(xt_tmp, a_prev_tmp, parameters_tmp)\n\nda_next_tmp = np.random.randn(5,10)\ngradients_tmp = rnn_cell_backward(da_next_tmp, cache_tmp)\nprint(\"gradients[\\\"dxt\\\"][1][2] =\", gradients_tmp[\"dxt\"][1][2])\nprint(\"gradients[\\\"dxt\\\"].shape =\", gradients_tmp[\"dxt\"].shape)\nprint(\"gradients[\\\"da_prev\\\"][2][3] =\", gradients_tmp[\"da_prev\"][2][3])\nprint(\"gradients[\\\"da_prev\\\"].shape =\", gradients_tmp[\"da_prev\"].shape)\nprint(\"gradients[\\\"dWax\\\"][3][1] =\", gradients_tmp[\"dWax\"][3][1])\nprint(\"gradients[\\\"dWax\\\"].shape =\", gradients_tmp[\"dWax\"].shape)\nprint(\"gradients[\\\"dWaa\\\"][1][2] =\", gradients_tmp[\"dWaa\"][1][2])\nprint(\"gradients[\\\"dWaa\\\"].shape =\", gradients_tmp[\"dWaa\"].shape)\nprint(\"gradients[\\\"dba\\\"][4] =\", gradients_tmp[\"dba\"][4])\nprint(\"gradients[\\\"dba\\\"].shape =\", gradients_tmp[\"dba\"].shape)",
"gradients[\"dxt\"][1][2] = -1.3872130506\ngradients[\"dxt\"].shape = (3, 10)\ngradients[\"da_prev\"][2][3] = -0.152399493774\ngradients[\"da_prev\"].shape = (5, 10)\ngradients[\"dWax\"][3][1] = 0.410772824935\ngradients[\"dWax\"].shape = (5, 3)\ngradients[\"dWaa\"][1][2] = 1.15034506685\ngradients[\"dWaa\"].shape = (5, 5)\ngradients[\"dba\"][4] = [ 0.20023491]\ngradients[\"dba\"].shape = (5, 1)\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **gradients[\"dxt\"][1][2]** =\n </td>\n <td>\n -1.3872130506\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dxt\"].shape** =\n </td>\n <td>\n (3, 10)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da_prev\"][2][3]** =\n </td>\n <td>\n -0.152399493774\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da_prev\"].shape** =\n </td>\n <td>\n (5, 10)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWax\"][3][1]** =\n </td>\n <td>\n 0.410772824935\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWax\"].shape** =\n </td>\n <td>\n (5, 3)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWaa\"][1][2]** = \n </td>\n <td>\n 1.15034506685\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWaa\"].shape** =\n </td>\n <td>\n (5, 5)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dba\"][4]** = \n </td>\n <td>\n [ 0.20023491]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dba\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"#### Backward pass through the RNN\n\n",
"_____no_output_____"
]
],
[
[
"def rnn_backward(da, caches):\n \n\n \n \n # Retrieve values from the first cache (t=1) of caches (≈2 lines)\n (caches, x) = caches\n (a1, a0, x1, parameters) = caches[0]\n \n # Retrieve dimensions from da's and x1's shapes (≈2 lines)\n n_a, m, T_x = da.shape\n n_x, m = x1.shape\n \n # initialize the gradients with the right sizes (≈6 lines)\n dx = np.zeros((n_x, m, T_x))\n dWax = np.zeros((n_a, n_x))\n dWaa = np.zeros((n_a, n_a))\n dba = np.zeros((n_a, 1))\n da0 = np.zeros((n_a, m))\n da_prevt = np.zeros((n_a, m))\n \n \n # Loop through all the time steps\n for t in reversed(range(T_x)):\n # Compute gradients at time step t. Choose wisely the \"da_next\" and the \"cache\" to use in the backward propagation step. (≈1 line)\n gradients = rnn_cell_backward(da[:,:,t] + da_prevt, caches[t])\n # Retrieve derivatives from gradients (≈ 1 line)\n dxt, da_prevt, dWaxt, dWaat, dbat = gradients[\"dxt\"], gradients[\"da_prev\"], gradients[\"dWax\"], gradients[\"dWaa\"], gradients[\"dba\"]\n # Increment global derivatives w.r.t parameters by adding their derivative at time-step t (≈4 lines)\n dx[:, :, t] = dxt\n dWax += dWaxt\n dWaa += dWaat\n dba += dbat\n \n # Set da0 to the gradient of a which has been backpropagated through all time-steps (≈1 line) \n da0 = da_prevt\n\n # Store the gradients in a python dictionary\n gradients = {\"dx\": dx, \"da0\": da0, \"dWax\": dWax, \"dWaa\": dWaa,\"dba\": dba}\n \n return gradients",
"_____no_output_____"
],
[
"np.random.seed(1)\nx = np.random.randn(3,10,4)\na0 = np.random.randn(5,10)\nWax = np.random.randn(5,3)\nWaa = np.random.randn(5,5)\nWya = np.random.randn(2,5)\nba = np.random.randn(5,1)\nby = np.random.randn(2,1)\nparameters = {\"Wax\": Wax, \"Waa\": Waa, \"Wya\": Wya, \"ba\": ba, \"by\": by}\na, y, caches = rnn_forward(x, a0, parameters)\nda = np.random.randn(5, 10, 4)\ngradients = rnn_backward(da, caches)\n\nprint(\"gradients[\\\"dx\\\"][1][2] =\", gradients[\"dx\"][1][2])\nprint(\"gradients[\\\"dx\\\"].shape =\", gradients[\"dx\"].shape)\nprint(\"gradients[\\\"da0\\\"][2][3] =\", gradients[\"da0\"][2][3])\nprint(\"gradients[\\\"da0\\\"].shape =\", gradients[\"da0\"].shape)\nprint(\"gradients[\\\"dWax\\\"][3][1] =\", gradients[\"dWax\"][3][1])\nprint(\"gradients[\\\"dWax\\\"].shape =\", gradients[\"dWax\"].shape)\nprint(\"gradients[\\\"dWaa\\\"][1][2] =\", gradients[\"dWaa\"][1][2])\nprint(\"gradients[\\\"dWaa\\\"].shape =\", gradients[\"dWaa\"].shape)\nprint(\"gradients[\\\"dba\\\"][4] =\", gradients[\"dba\"][4])\nprint(\"gradients[\\\"dba\\\"].shape =\", gradients[\"dba\"].shape)",
"gradients[\"dx\"][1][2] = [-2.07101689 -0.59255627 0.02466855 0.01483317]\ngradients[\"dx\"].shape = (3, 10, 4)\ngradients[\"da0\"][2][3] = -0.314942375127\ngradients[\"da0\"].shape = (5, 10)\ngradients[\"dWax\"][3][1] = 11.2641044965\ngradients[\"dWax\"].shape = (5, 3)\ngradients[\"dWaa\"][1][2] = 2.30333312658\ngradients[\"dWaa\"].shape = (5, 5)\ngradients[\"dba\"][4] = [-0.74747722]\ngradients[\"dba\"].shape = (5, 1)\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **gradients[\"dx\"][1][2]** =\n </td>\n <td>\n [-2.07101689 -0.59255627 0.02466855 0.01483317]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dx\"].shape** =\n </td>\n <td>\n (3, 10, 4)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da0\"][2][3]** =\n </td>\n <td>\n -0.314942375127\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da0\"].shape** =\n </td>\n <td>\n (5, 10)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWax\"][3][1]** =\n </td>\n <td>\n 11.2641044965\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWax\"].shape** =\n </td>\n <td>\n (5, 3)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWaa\"][1][2]** = \n </td>\n <td>\n 2.30333312658\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWaa\"].shape** =\n </td>\n <td>\n (5, 5)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dba\"][4]** = \n </td>\n <td>\n [-0.74747722]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dba\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"## LSTM backward pass",
"_____no_output_____"
],
[
"### One Step backward\n",
"_____no_output_____"
],
[
"### Gate derivatives\nNote the location of the gate derivatives ($\\gamma$..) between the dense layer and the activation function (see graphic above). This is convenient for computing parameter derivatives in the next step. \n\n$d\\gamma_o^{\\langle t \\rangle} = da_{next}*\\tanh(c_{next}) * \\Gamma_o^{\\langle t \\rangle}*\\left(1-\\Gamma_o^{\\langle t \\rangle}\\right)\\tag{7}$\n\n$dp\\widetilde{c}^{\\langle t \\rangle} = \\left(dc_{next}*\\Gamma_u^{\\langle t \\rangle}+ \\Gamma_o^{\\langle t \\rangle}* (1-\\tanh^2(c_{next})) * \\Gamma_u^{\\langle t \\rangle} * da_{next} \\right) * \\left(1-\\left(\\widetilde c^{\\langle t \\rangle}\\right)^2\\right) \\tag{8}$\n\n$d\\gamma_u^{\\langle t \\rangle} = \\left(dc_{next}*\\widetilde{c}^{\\langle t \\rangle} + \\Gamma_o^{\\langle t \\rangle}* (1-\\tanh^2(c_{next})) * \\widetilde{c}^{\\langle t \\rangle} * da_{next}\\right)*\\Gamma_u^{\\langle t \\rangle}*\\left(1-\\Gamma_u^{\\langle t \\rangle}\\right)\\tag{9}$\n\n$d\\gamma_f^{\\langle t \\rangle} = \\left(dc_{next}* c_{prev} + \\Gamma_o^{\\langle t \\rangle} * (1-\\tanh^2(c_{next})) * c_{prev} * da_{next}\\right)*\\Gamma_f^{\\langle t \\rangle}*\\left(1-\\Gamma_f^{\\langle t \\rangle}\\right)\\tag{10}$\n\n### Parameter derivatives \n\n$ dW_f = d\\gamma_f^{\\langle t \\rangle} \\begin{bmatrix} a_{prev} \\\\ x_t\\end{bmatrix}^T \\tag{11} $\n$ dW_u = d\\gamma_u^{\\langle t \\rangle} \\begin{bmatrix} a_{prev} \\\\ x_t\\end{bmatrix}^T \\tag{12} $\n$ dW_c = dp\\widetilde c^{\\langle t \\rangle} \\begin{bmatrix} a_{prev} \\\\ x_t\\end{bmatrix}^T \\tag{13} $\n$ dW_o = d\\gamma_o^{\\langle t \\rangle} \\begin{bmatrix} a_{prev} \\\\ x_t\\end{bmatrix}^T \\tag{14}$\n\nTo calculate $db_f, db_u, db_c, db_o$ you just need to sum across the horizontal (axis= 1) axis on $d\\gamma_f^{\\langle t \\rangle}, d\\gamma_u^{\\langle t \\rangle}, dp\\widetilde c^{\\langle t \\rangle}, d\\gamma_o^{\\langle t \\rangle}$ respectively. Note that you should have the `keepdims = True` option.\n\n$\\displaystyle db_f = \\sum_{batch}d\\gamma_f^{\\langle t \\rangle}\\tag{15}$\n$\\displaystyle db_u = \\sum_{batch}d\\gamma_u^{\\langle t \\rangle}\\tag{16}$\n$\\displaystyle db_c = \\sum_{batch}d\\gamma_c^{\\langle t \\rangle}\\tag{17}$\n$\\displaystyle db_o = \\sum_{batch}d\\gamma_o^{\\langle t \\rangle}\\tag{18}$\n\nFinally, you will compute the derivative with respect to the previous hidden state, previous memory state, and input.\n\n$ da_{prev} = W_f^T d\\gamma_f^{\\langle t \\rangle} + W_u^T d\\gamma_u^{\\langle t \\rangle}+ W_c^T dp\\widetilde c^{\\langle t \\rangle} + W_o^T d\\gamma_o^{\\langle t \\rangle} \\tag{19}$\n\nHere, to account for concatenation, the weights for equations 19 are the first n_a, (i.e. $W_f = W_f[:,:n_a]$ etc...)\n\n$ dc_{prev} = dc_{next}*\\Gamma_f^{\\langle t \\rangle} + \\Gamma_o^{\\langle t \\rangle} * (1- \\tanh^2(c_{next}))*\\Gamma_f^{\\langle t \\rangle}*da_{next} \\tag{20}$\n\n$ dx^{\\langle t \\rangle} = W_f^T d\\gamma_f^{\\langle t \\rangle} + W_u^T d\\gamma_u^{\\langle t \\rangle}+ W_c^T dp\\widetilde c^{\\langle t \\rangle} + W_o^T d\\gamma_o^{\\langle t \\rangle}\\tag{21} $\n\nwhere the weights for equation 21 are from n_a to the end, (i.e. $W_f = W_f[:,n_a:]$ etc...)\n\n**Exercise:** Implement `lstm_cell_backward` by implementing equations $7-21$ below. \n \n \nNote: In the code:\n\n$d\\gamma_o^{\\langle t \\rangle}$ is represented by `dot`, \n$dp\\widetilde{c}^{\\langle t \\rangle}$ is represented by `dcct`, \n$d\\gamma_u^{\\langle t \\rangle}$ is represented by `dit`, \n$d\\gamma_f^{\\langle t \\rangle}$ is represented by `dft`\n",
"_____no_output_____"
]
],
[
[
"def lstm_cell_backward(da_next, dc_next, cache):\n # Retrieve information from \"cache\"\n (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) = cache\n \n # Retrieve dimensions from xt's and a_next's shape (≈2 lines)\n n_x, m = xt.shape\n n_a, m = a_next.shape\n \n # Compute gates related derivatives, you can find their values can be found by looking carefully at equations (7) to (10) (≈4 lines)\n dot = da_next * np.tanh(c_next) * ot * (1 - ot)\n dcct = (da_next * ot * (1 - np.tanh(c_next) ** 2) + dc_next) * it * (1 - cct ** 2)\n dit = (da_next * ot * (1 - np.tanh(c_next) ** 2) + dc_next) * cct * (1 - it) * it\n dft = (da_next * ot * (1 - np.tanh(c_next) ** 2) + dc_next) * c_prev * ft * (1 - ft)\n\n # Compute parameters related derivatives. Use equations (11)-(14) (≈8 lines)\n \n dWf = np.dot(dft, np.hstack([a_prev.T, xt.T]))\n dWi = np.dot(dit, np.hstack([a_prev.T, xt.T]))\n dWc = np.dot(dcct, np.hstack([a_prev.T, xt.T]))\n dWo = np.dot(dot, np.hstack([a_prev.T, xt.T]))\n dbf = np.sum(dft, axis=1, keepdims=True)\n dbi = np.sum(dit, axis=1, keepdims=True)\n dbc = np.sum(dcct, axis=1, keepdims=True)\n dbo = np.sum(dot, axis=1, keepdims=True)\n\n # Compute derivatives w.r.t previous hidden state, previous memory state and input. Use equations (15)-(17). (≈3 lines) \n da_prev = np.dot(Wf[:, :n_a].T, dft) + np.dot(Wc[:, :n_a].T, dcct) + np.dot(Wi[:, :n_a].T, dit) + np.dot(Wo[:, :n_a].T, dot)\n dc_prev = (da_next * ot * (1 - np.tanh(c_next) ** 2) + dc_next) * ft\n dxt = np.dot(Wf[:, n_a:].T, dft) + np.dot(Wc[:, n_a:].T, dcct) + np.dot(Wi[:, n_a:].T, dit) + np.dot(Wo[:, n_a:].T, dot)\n \n # Save gradients in dictionary\n gradients = {\"dxt\": dxt, \"da_prev\": da_prev, \"dc_prev\": dc_prev, \"dWf\": dWf,\"dbf\": dbf, \"dWi\": dWi,\"dbi\": dbi,\n \"dWc\": dWc,\"dbc\": dbc, \"dWo\": dWo,\"dbo\": dbo}\n\n return gradients",
"_____no_output_____"
],
[
"np.random.seed(1)\nxt_tmp = np.random.randn(3,10)\na_prev_tmp = np.random.randn(5,10)\nc_prev_tmp = np.random.randn(5,10)\nparameters_tmp = {}\nparameters_tmp['Wf'] = np.random.randn(5, 5+3)\nparameters_tmp['bf'] = np.random.randn(5,1)\nparameters_tmp['Wi'] = np.random.randn(5, 5+3)\nparameters_tmp['bi'] = np.random.randn(5,1)\nparameters_tmp['Wo'] = np.random.randn(5, 5+3)\nparameters_tmp['bo'] = np.random.randn(5,1)\nparameters_tmp['Wc'] = np.random.randn(5, 5+3)\nparameters_tmp['bc'] = np.random.randn(5,1)\nparameters_tmp['Wy'] = np.random.randn(2,5)\nparameters_tmp['by'] = np.random.randn(2,1)\n\na_next_tmp, c_next_tmp, yt_tmp, cache_tmp = lstm_cell_forward(xt_tmp, a_prev_tmp, c_prev_tmp, parameters_tmp)\n\nda_next_tmp = np.random.randn(5,10)\ndc_next_tmp = np.random.randn(5,10)\ngradients_tmp = lstm_cell_backward(da_next_tmp, dc_next_tmp, cache_tmp)\nprint(\"gradients[\\\"dxt\\\"][1][2] =\", gradients_tmp[\"dxt\"][1][2])\nprint(\"gradients[\\\"dxt\\\"].shape =\", gradients_tmp[\"dxt\"].shape)\nprint(\"gradients[\\\"da_prev\\\"][2][3] =\", gradients_tmp[\"da_prev\"][2][3])\nprint(\"gradients[\\\"da_prev\\\"].shape =\", gradients_tmp[\"da_prev\"].shape)\nprint(\"gradients[\\\"dc_prev\\\"][2][3] =\", gradients_tmp[\"dc_prev\"][2][3])\nprint(\"gradients[\\\"dc_prev\\\"].shape =\", gradients_tmp[\"dc_prev\"].shape)\nprint(\"gradients[\\\"dWf\\\"][3][1] =\", gradients_tmp[\"dWf\"][3][1])\nprint(\"gradients[\\\"dWf\\\"].shape =\", gradients_tmp[\"dWf\"].shape)\nprint(\"gradients[\\\"dWi\\\"][1][2] =\", gradients_tmp[\"dWi\"][1][2])\nprint(\"gradients[\\\"dWi\\\"].shape =\", gradients_tmp[\"dWi\"].shape)\nprint(\"gradients[\\\"dWc\\\"][3][1] =\", gradients_tmp[\"dWc\"][3][1])\nprint(\"gradients[\\\"dWc\\\"].shape =\", gradients_tmp[\"dWc\"].shape)\nprint(\"gradients[\\\"dWo\\\"][1][2] =\", gradients_tmp[\"dWo\"][1][2])\nprint(\"gradients[\\\"dWo\\\"].shape =\", gradients_tmp[\"dWo\"].shape)\nprint(\"gradients[\\\"dbf\\\"][4] =\", gradients_tmp[\"dbf\"][4])\nprint(\"gradients[\\\"dbf\\\"].shape =\", gradients_tmp[\"dbf\"].shape)\nprint(\"gradients[\\\"dbi\\\"][4] =\", gradients_tmp[\"dbi\"][4])\nprint(\"gradients[\\\"dbi\\\"].shape =\", gradients_tmp[\"dbi\"].shape)\nprint(\"gradients[\\\"dbc\\\"][4] =\", gradients_tmp[\"dbc\"][4])\nprint(\"gradients[\\\"dbc\\\"].shape =\", gradients_tmp[\"dbc\"].shape)\nprint(\"gradients[\\\"dbo\\\"][4] =\", gradients_tmp[\"dbo\"][4])\nprint(\"gradients[\\\"dbo\\\"].shape =\", gradients_tmp[\"dbo\"].shape)",
"gradients[\"dxt\"][1][2] = 3.23055911511\ngradients[\"dxt\"].shape = (3, 10)\ngradients[\"da_prev\"][2][3] = -0.0639621419711\ngradients[\"da_prev\"].shape = (5, 10)\ngradients[\"dc_prev\"][2][3] = 0.797522038797\ngradients[\"dc_prev\"].shape = (5, 10)\ngradients[\"dWf\"][3][1] = -0.147954838164\ngradients[\"dWf\"].shape = (5, 8)\ngradients[\"dWi\"][1][2] = 1.05749805523\ngradients[\"dWi\"].shape = (5, 8)\ngradients[\"dWc\"][3][1] = 2.30456216369\ngradients[\"dWc\"].shape = (5, 8)\ngradients[\"dWo\"][1][2] = 0.331311595289\ngradients[\"dWo\"].shape = (5, 8)\ngradients[\"dbf\"][4] = [ 0.18864637]\ngradients[\"dbf\"].shape = (5, 1)\ngradients[\"dbi\"][4] = [-0.40142491]\ngradients[\"dbi\"].shape = (5, 1)\ngradients[\"dbc\"][4] = [ 0.25587763]\ngradients[\"dbc\"].shape = (5, 1)\ngradients[\"dbo\"][4] = [ 0.13893342]\ngradients[\"dbo\"].shape = (5, 1)\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **gradients[\"dxt\"][1][2]** =\n </td>\n <td>\n 3.23055911511\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dxt\"].shape** =\n </td>\n <td>\n (3, 10)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da_prev\"][2][3]** =\n </td>\n <td>\n -0.0639621419711\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da_prev\"].shape** =\n </td>\n <td>\n (5, 10)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dc_prev\"][2][3]** =\n </td>\n <td>\n 0.797522038797\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dc_prev\"].shape** =\n </td>\n <td>\n (5, 10)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWf\"][3][1]** = \n </td>\n <td>\n -0.147954838164\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWf\"].shape** =\n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWi\"][1][2]** = \n </td>\n <td>\n 1.05749805523\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWi\"].shape** = \n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWc\"][3][1]** = \n </td>\n <td>\n 2.30456216369\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWc\"].shape** = \n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWo\"][1][2]** = \n </td>\n <td>\n 0.331311595289\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWo\"].shape** = \n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbf\"][4]** = \n </td>\n <td>\n [ 0.18864637]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbf\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbi\"][4]** = \n </td>\n <td>\n [-0.40142491]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbi\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbc\"][4]** = \n </td>\n <td>\n [ 0.25587763]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbc\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbo\"][4]** = \n </td>\n <td>\n [ 0.13893342]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbo\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"### LSTM BACKWARD",
"_____no_output_____"
]
],
[
[
"def lstm_backward(da, caches):\n # Retrieve values from the first cache (t=1) of caches.\n (caches, x) = caches\n (a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0]\n \n \n # Retrieve dimensions from da's and x1's shapes (≈2 lines)\n n_a, m, T_x = da.shape\n n_x, m = x1.shape\n \n # initialize the gradients with the right sizes (≈12 lines)\n dx = np.zeros((n_x, m, T_x))\n da0 = np.zeros((n_a, m))\n da_prevt = np.zeros((n_a, m))\n dc_prevt = np.zeros((n_a, m))\n dWf = np.zeros((n_a, n_a + n_x))\n dWi = np.zeros((n_a, n_a + n_x))\n dWc = np.zeros((n_a, n_a + n_x))\n dWo = np.zeros((n_a, n_a + n_x))\n dbf = np.zeros((n_a, 1))\n dbi = np.zeros((n_a, 1))\n dbc = np.zeros((n_a, 1))\n dbo = np.zeros((n_a, 1))\n \n # loop back over the whole sequence\n for t in reversed(range(T_x)):\n # Compute all gradients using lstm_cell_backward\n gradients = lstm_cell_backward(da[:,:,t] + da_prevt, dc_prevt, caches[t])\n # Store or add the gradient to the parameters' previous step's gradient\n dx[:,:,t] = gradients[\"dxt\"]\n dWf += gradients[\"dWf\"]\n dWi += gradients[\"dWi\"]\n dWc += gradients[\"dWc\"]\n dWo += gradients[\"dWo\"]\n dbf += gradients[\"dbf\"]\n dbi += gradients[\"dbi\"]\n dbc += gradients[\"dbc\"]\n dbo += gradients[\"dbo\"]\n # Set the first activation's gradient to the backpropagated gradient da_prev.\n da0 = gradients[\"da_prev\"]\n \n\n\n # Store the gradients in a python dictionary\n gradients = {\"dx\": dx, \"da0\": da0, \"dWf\": dWf,\"dbf\": dbf, \"dWi\": dWi,\"dbi\": dbi,\n \"dWc\": dWc,\"dbc\": dbc, \"dWo\": dWo,\"dbo\": dbo}\n \n return gradients",
"_____no_output_____"
],
[
"np.random.seed(1)\nx_tmp = np.random.randn(3,10,7)\na0_tmp = np.random.randn(5,10)\n\nparameters_tmp = {}\nparameters_tmp['Wf'] = np.random.randn(5, 5+3)\nparameters_tmp['bf'] = np.random.randn(5,1)\nparameters_tmp['Wi'] = np.random.randn(5, 5+3)\nparameters_tmp['bi'] = np.random.randn(5,1)\nparameters_tmp['Wo'] = np.random.randn(5, 5+3)\nparameters_tmp['bo'] = np.random.randn(5,1)\nparameters_tmp['Wc'] = np.random.randn(5, 5+3)\nparameters_tmp['bc'] = np.random.randn(5,1)\nparameters_tmp['Wy'] = np.zeros((2,5)) # unused, but needed for lstm_forward\nparameters_tmp['by'] = np.zeros((2,1)) # unused, but needed for lstm_forward\n\na_tmp, y_tmp, c_tmp, caches_tmp = lstm_forward(x_tmp, a0_tmp, parameters_tmp)\n\nda_tmp = np.random.randn(5, 10, 4)\ngradients_tmp = lstm_backward(da_tmp, caches_tmp)\n\nprint(\"gradients[\\\"dx\\\"][1][2] =\", gradients_tmp[\"dx\"][1][2])\nprint(\"gradients[\\\"dx\\\"].shape =\", gradients_tmp[\"dx\"].shape)\nprint(\"gradients[\\\"da0\\\"][2][3] =\", gradients_tmp[\"da0\"][2][3])\nprint(\"gradients[\\\"da0\\\"].shape =\", gradients_tmp[\"da0\"].shape)\nprint(\"gradients[\\\"dWf\\\"][3][1] =\", gradients_tmp[\"dWf\"][3][1])\nprint(\"gradients[\\\"dWf\\\"].shape =\", gradients_tmp[\"dWf\"].shape)\nprint(\"gradients[\\\"dWi\\\"][1][2] =\", gradients_tmp[\"dWi\"][1][2])\nprint(\"gradients[\\\"dWi\\\"].shape =\", gradients_tmp[\"dWi\"].shape)\nprint(\"gradients[\\\"dWc\\\"][3][1] =\", gradients_tmp[\"dWc\"][3][1])\nprint(\"gradients[\\\"dWc\\\"].shape =\", gradients_tmp[\"dWc\"].shape)\nprint(\"gradients[\\\"dWo\\\"][1][2] =\", gradients_tmp[\"dWo\"][1][2])\nprint(\"gradients[\\\"dWo\\\"].shape =\", gradients_tmp[\"dWo\"].shape)\nprint(\"gradients[\\\"dbf\\\"][4] =\", gradients_tmp[\"dbf\"][4])\nprint(\"gradients[\\\"dbf\\\"].shape =\", gradients_tmp[\"dbf\"].shape)\nprint(\"gradients[\\\"dbi\\\"][4] =\", gradients_tmp[\"dbi\"][4])\nprint(\"gradients[\\\"dbi\\\"].shape =\", gradients_tmp[\"dbi\"].shape)\nprint(\"gradients[\\\"dbc\\\"][4] =\", gradients_tmp[\"dbc\"][4])\nprint(\"gradients[\\\"dbc\\\"].shape =\", gradients_tmp[\"dbc\"].shape)\nprint(\"gradients[\\\"dbo\\\"][4] =\", gradients_tmp[\"dbo\"][4])\nprint(\"gradients[\\\"dbo\\\"].shape =\", gradients_tmp[\"dbo\"].shape)",
"gradients[\"dx\"][1][2] = [ 0.00433841 0.01182645 -0.01648453 0.20649992]\ngradients[\"dx\"].shape = (3, 10, 4)\ngradients[\"da0\"][2][3] = 0.176564564406\ngradients[\"da0\"].shape = (5, 10)\ngradients[\"dWf\"][3][1] = -0.0698198561274\ngradients[\"dWf\"].shape = (5, 8)\ngradients[\"dWi\"][1][2] = 0.102371820249\ngradients[\"dWi\"].shape = (5, 8)\ngradients[\"dWc\"][3][1] = -0.0624983794927\ngradients[\"dWc\"].shape = (5, 8)\ngradients[\"dWo\"][1][2] = 0.0484389131444\ngradients[\"dWo\"].shape = (5, 8)\ngradients[\"dbf\"][4] = [-0.0565788]\ngradients[\"dbf\"].shape = (5, 1)\ngradients[\"dbi\"][4] = [-0.15399065]\ngradients[\"dbi\"].shape = (5, 1)\ngradients[\"dbc\"][4] = [-0.29691142]\ngradients[\"dbc\"].shape = (5, 1)\ngradients[\"dbo\"][4] = [-0.29798344]\ngradients[\"dbo\"].shape = (5, 1)\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td>\n **gradients[\"dx\"][1][2]** =\n </td>\n <td>\n [0.00218254 0.28205375 -0.48292508 -0.43281115]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dx\"].shape** =\n </td>\n <td>\n (3, 10, 4)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da0\"][2][3]** =\n </td>\n <td>\n 0.312770310257\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"da0\"].shape** =\n </td>\n <td>\n (5, 10)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWf\"][3][1]** = \n </td>\n <td>\n -0.0809802310938\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWf\"].shape** =\n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWi\"][1][2]** = \n </td>\n <td>\n 0.40512433093\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWi\"].shape** = \n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWc\"][3][1]** = \n </td>\n <td>\n -0.0793746735512\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWc\"].shape** = \n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWo\"][1][2]** = \n </td>\n <td>\n 0.038948775763\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dWo\"].shape** = \n </td>\n <td>\n (5, 8)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbf\"][4]** = \n </td>\n <td>\n [-0.15745657]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbf\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbi\"][4]** = \n </td>\n <td>\n [-0.50848333]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbi\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbc\"][4]** = \n </td>\n <td>\n [-0.42510818]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbc\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbo\"][4]** = \n </td>\n <td>\n [ -0.17958196]\n </td>\n </tr>\n <tr>\n <td>\n **gradients[\"dbo\"].shape** = \n </td>\n <td>\n (5, 1)\n </td>\n </tr>\n</table>",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
d0ae6e327a8dc51d0ad4138909415bc9c7796f03 | 4,404 | ipynb | Jupyter Notebook | Document classify - KMeans.ipynb | heolin123/text_analysis | 06ae7ec1402da60ce386d70929076b7ea90faefe | [
"MIT"
] | 1 | 2018-02-20T03:24:13.000Z | 2018-02-20T03:24:13.000Z | Document classify - KMeans.ipynb | heolin123/text_analysis | 06ae7ec1402da60ce386d70929076b7ea90faefe | [
"MIT"
] | null | null | null | Document classify - KMeans.ipynb | heolin123/text_analysis | 06ae7ec1402da60ce386d70929076b7ea90faefe | [
"MIT"
] | null | null | null | 29.36 | 119 | 0.532016 | [
[
[
"Based on http://scikit-learn.org/stable/auto_examples/text/document_clustering.html",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import fetch_20newsgroups\nfrom sklearn import metrics\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.svm import SVC, LinearSVC\n\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn import metrics\n\nimport numpy as np",
"_____no_output_____"
],
[
"input_categories = ['talk.politics.misc', 'soc.religion.christian', 'comp.graphics', 'sci.med']\ntrain_dataset = fetch_20newsgroups(subset='train', categories=input_categories, shuffle=True, random_state=42)\ntest_dataset = fetch_20newsgroups(subset='test', categories=input_categories, shuffle=True, random_state=42)",
"_____no_output_____"
],
[
"nb_text_clf = Pipeline([('vect', CountVectorizer()),\n ('tfid', TfidfTransformer()),\n ('clf', MultinomialNB())])\n\nnb_text_clf.fit(train_dataset.data, train_dataset.target)\npredicted = nb_text_clf.predict(test_dataset.data)\nprint \"Naive Bayes classifier\"\nprint metrics.classification_report(test_dataset.target, predicted, target_names=test_dataset.target_names)",
"Naive Bayes classifier\n precision recall f1-score support\n\n comp.graphics 0.96 0.90 0.93 389\n sci.med 0.96 0.82 0.88 396\nsoc.religion.christian 0.66 0.99 0.79 398\n talk.politics.misc 0.99 0.61 0.76 310\n\n avg / total 0.89 0.84 0.85 1493\n\n"
],
[
"svc_text_clf = Pipeline([('vect', CountVectorizer()),\n ('tfid', TfidfTransformer()),\n ('clf', LinearSVC())])\n\nsvc_text_clf.fit(train_dataset.data, train_dataset.target)\npredicted = svc_text_clf.predict(test_dataset.data)\nprint \"Linear Support Vector classifier\"\nprint metrics.classification_report(test_dataset.target, predicted, target_names=test_dataset.target_names)",
"Linear Support Vector classifier\n precision recall f1-score support\n\n comp.graphics 0.91 0.97 0.94 389\n sci.med 0.95 0.90 0.92 396\nsoc.religion.christian 0.96 0.97 0.96 398\n talk.politics.misc 0.96 0.92 0.94 310\n\n avg / total 0.94 0.94 0.94 1493\n\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0ae7445c2ba582e983ecec2a9a564cc0eb333b7 | 38,388 | ipynb | Jupyter Notebook | tutorial/pandas.ipynb | tsahara/python_stat | d9953ada172efff83c342dd1b61403a73a001d2f | [
"BSD-3-Clause"
] | 97 | 2018-09-04T05:55:33.000Z | 2022-02-17T08:45:50.000Z | tutorial/pandas.ipynb | tsahara/python_stat | d9953ada172efff83c342dd1b61403a73a001d2f | [
"BSD-3-Clause"
] | 1 | 2021-03-03T13:55:10.000Z | 2021-03-03T13:55:10.000Z | tutorial/pandas.ipynb | tsahara/python_stat | d9953ada172efff83c342dd1b61403a73a001d2f | [
"BSD-3-Clause"
] | 98 | 2018-09-22T12:02:32.000Z | 2022-03-12T03:12:29.000Z | 25.205515 | 86 | 0.310722 | [
[
[
"pandasはpdという名前でインポートされることがほとんどです",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"本書第1章で使うデータを読み込みましょう \nread_csv関数を使うことでcsvをpandasのDataFrameという形式で読み込むことができます",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('../data/ch1_sport_test.csv')\ndf",
"_____no_output_____"
]
],
[
[
"# 抽出",
"_____no_output_____"
],
[
"今回はDataFrameが10行と比較的小規模ですが、数百行・数千行のDataFrameを扱うことも珍しくありません \nそのようなDataFrameの概観を知るためにDataFrameのheadメソッドがよく使われます \nheadメソッドはDataFrameの先頭の数行を抽出するメソッドです \nここでは3行抽出してみましょう",
"_____no_output_____"
]
],
[
[
"df.head(3)",
"_____no_output_____"
]
],
[
[
"何も指定しないと5行抽出されます",
"_____no_output_____"
]
],
[
[
"df.head()",
"_____no_output_____"
]
],
[
[
"同様にtailメソッドはDataFrameの末尾を抽出します",
"_____no_output_____"
]
],
[
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"スライスで抽出することもできます",
"_____no_output_____"
]
],
[
[
"df[2:5]",
"_____no_output_____"
]
],
[
[
"列は列名によって抽出できます ",
"_____no_output_____"
]
],
[
[
"df['握力']",
"_____no_output_____"
]
],
[
[
"複数列を同時に指定することもできます",
"_____no_output_____"
]
],
[
[
"df[['学年', '点数']]",
"_____no_output_____"
]
],
[
[
"行と列を同時に指定して抽出したいときはlocメソッドが便利です \nたとえば1行目の学年は次のように抽出できます",
"_____no_output_____"
]
],
[
[
"df.loc[1, '学年']",
"_____no_output_____"
]
],
[
[
"スライスによる指定も可能です",
"_____no_output_____"
]
],
[
[
"df.loc[1:3, '握力']",
"_____no_output_____"
]
],
[
[
"条件に合致する行を抽出したい場合は次のように書きます \nここでは握力が30より下の行を抽出しています",
"_____no_output_____"
]
],
[
[
"df[df['握力'] < 30]",
"_____no_output_____"
]
],
[
[
"# データの概要",
"_____no_output_____"
],
[
"データの大きさはshapeでわかります",
"_____no_output_____"
]
],
[
[
"df.shape",
"_____no_output_____"
]
],
[
[
"列名はcolumnsです",
"_____no_output_____"
]
],
[
[
"df.columns",
"_____no_output_____"
],
[
"df.index",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"# データの追加",
"_____no_output_____"
],
[
"dfにデータを追加してみましょう \nまずは列の追加です",
"_____no_output_____"
]
],
[
[
"df['腕立て伏せ'] = [15, 12, 10, 4, 20,\n 24, 9, 11, 11, 17]\ndf",
"_____no_output_____"
]
],
[
[
"次は行を追加してみます",
"_____no_output_____"
]
],
[
[
"new_row = pd.Series([11, 3, 42.4, 30, 15, 11, 12], index=df.columns, name=10)\nnew_row",
"_____no_output_____"
],
[
"df.append(new_row)",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0ae760e7c6c9ef7008dc2769539f0d5e1dfad8b | 110,279 | ipynb | Jupyter Notebook | Deep Learning with Keras_TensorFlow/Airlline Passengers prediction (with LSTM RNN in Keras-TensorFlow).ipynb | RooHashemi/Data-Science-Projects-with-Python-Spark-Keras_TensorFlow-AWS | 18b689decaed259a26ef7b9a8f894752acb567a9 | [
"MIT"
] | 2 | 2019-01-02T02:50:29.000Z | 2020-06-16T12:32:37.000Z | Time Series Analysis with ARIMA and Recurrent Neural Nets/Airlline Passengers prediction (with LSTM RNN in Keras-TensorFlow).ipynb | RooHashemi/Data-Science-Projects-with-Python-Spark-Keras_TensorFlow-AWS | 18b689decaed259a26ef7b9a8f894752acb567a9 | [
"MIT"
] | null | null | null | Time Series Analysis with ARIMA and Recurrent Neural Nets/Airlline Passengers prediction (with LSTM RNN in Keras-TensorFlow).ipynb | RooHashemi/Data-Science-Projects-with-Python-Spark-Keras_TensorFlow-AWS | 18b689decaed259a26ef7b9a8f894752acb567a9 | [
"MIT"
] | null | null | null | 330.176647 | 50,884 | 0.93307 | [
[
[
"# Data description: \nI'm going to solve the International Airline Passengers prediction problem. This is a problem where given a year and a month, the task is to predict the number of international airline passengers in units of 1,000. The data ranges from January 1949 to December 1960 or 12 years, with 144 observations.\n\n# Workflow:\n- Load the Time Series (TS) by Pandas Library\n- Prepare the data, i.e. convert the problem to a supervised ML problem\n- Build and evaluate the RNN model: \n - Fit the best RNN model\n - Evaluate model by in-sample prediction: Calculate RMSE\n- Forecast the future trend: Out-of-sample prediction\n\nNote: For data exploration of this TS, please refer to the notebook of my alternative solution with \"Seasonal ARIMA model\"",
"_____no_output_____"
]
],
[
[
"import keras\nimport sklearn\nimport tensorflow as tf\nimport numpy as np\nfrom scipy import stats\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import metrics\nfrom sklearn import preprocessing\nimport random as rn\nimport math\n%matplotlib inline\n\nfrom keras import backend as K\nsession_conf = tf.ConfigProto(intra_op_parallelism_threads=5, inter_op_parallelism_threads=5)\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")",
"Using TensorFlow backend.\n"
],
[
"# Load data using Series.from_csv\nfrom pandas import Series\n#TS = Series.from_csv('C:/Users/rhash/Documents/Datasets/Time Series analysis/daily-minimum-temperatures.csv', header=0)\n\n# Load data using pandas.read_csv\n# in case, specify your own date parsing function and use the date_parser argument\nfrom pandas import read_csv\nTS = read_csv('C:/Users/rhash/Documents/Datasets/Time Series analysis/AirPassengers.csv', header=0, parse_dates=[0], index_col=0, squeeze=True)\n\nprint(TS.head())",
"Month\n1949-01-01 112\n1949-02-01 118\n1949-03-01 132\n1949-04-01 129\n1949-05-01 121\nName: #Passengers, dtype: int64\n"
],
[
"#TS=pd.to_numeric(TS, errors='coerce')\nTS.dropna(inplace=True)\ndata=pd.DataFrame(TS.values)",
"_____no_output_____"
],
[
"# prepare the data (i.e. convert problem to a supervised ML problem)\ndef prepare_data(data, lags=1):\n \"\"\"\n Create lagged data from an input time series\n \"\"\"\n X, y = [], []\n for row in range(len(data) - lags - 1):\n a = data[row:(row + lags), 0]\n X.append(a)\n y.append(data[row + lags, 0])\n return np.array(X), np.array(y)",
"_____no_output_____"
],
[
"# normalize the dataset\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler(feature_range=(0, 1))\ndataset = scaler.fit_transform(data)\n \n# split into train and test sets\ntrain = dataset[0:120, :]\ntest = dataset[120:, :]",
"_____no_output_____"
],
[
"# LSTM RNN model: _________________________________________________________________\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, LSTM, Dropout, average, Input, merge, concatenate\nfrom keras.layers.merge import concatenate\nfrom keras.regularizers import l2, l1\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom sklearn.utils.class_weight import compute_sample_weight\nfrom keras.layers.normalization import BatchNormalization\n\n\n# reshape into X=t and Y=t+1\nlags = 3\nX_train, y_train = prepare_data(train, lags)\nX_test, y_test = prepare_data(test, lags)\n\n# reshape input to be [samples, time steps, features]\nX_train = np.reshape(X_train, (X_train.shape[0], lags, 1))\nX_test = np.reshape(X_test, (X_test.shape[0], lags, 1))\n\n# create and fit the LSTM network\nmdl = Sequential()\n#mdl.add(Dense(3, input_shape=(1, lags), activation='relu'))\nmdl.add(LSTM(4, activation='relu'))\n#mdl.add(Dropout(0.1))\nmdl.add(Dense(1))\n\nmdl.compile(loss='mean_squared_error', optimizer='adam')\nmonitor=EarlyStopping(monitor='loss', min_delta=0.001, patience=100, verbose=1, mode='auto')\nhistory=mdl.fit(X_train, y_train, epochs=1000, batch_size=1, validation_data=(X_test, y_test), callbacks=[monitor], verbose=0)\n\n\n# To measure RMSE and evaluate the RNN model:\nfrom sklearn.metrics import mean_squared_error\n\n# make predictions\ntrain_predict = mdl.predict(X_train)\ntest_predict = mdl.predict(X_test)\n \n# invert transformation\ntrain_predict = scaler.inverse_transform(pd.DataFrame(train_predict))\ny_train = scaler.inverse_transform(pd.DataFrame(y_train))\ntest_predict = scaler.inverse_transform(pd.DataFrame(test_predict))\ny_test = scaler.inverse_transform(pd.DataFrame(y_test))\n \n# calculate root mean squared error\ntrain_score = math.sqrt(mean_squared_error(y_train, train_predict[:,0]))\nprint('Train Score: {:.2f} RMSE'.format(train_score))\ntest_score = math.sqrt(mean_squared_error(y_test, test_predict[:,0]))\nprint('Test Score: {:.2f} RMSE'.format(test_score))",
"Epoch 00161: early stopping\nTrain Score: 27.08 RMSE\nTest Score: 57.58 RMSE\n"
],
[
"# list all data in history\n#print(history.history.keys())\n\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()",
"_____no_output_____"
],
[
"mdl.save('passenger_model.h5')",
"_____no_output_____"
],
[
"# shift train predictions for plotting\ntrain_predict_plot =np.full(data.shape, np.nan)\ntrain_predict_plot[lags:len(train_predict)+lags, :] = train_predict\n \n# shift test predictions for plotting\ntest_predict_plot =np.full(data.shape, np.nan)\ntest_predict_plot[len(train_predict) + (lags * 2)+1:len(data)-1, :] = test_predict\n \n# plot observation and predictions\nplt.figure(figsize=(8,6))\nplt.plot(data, label='Observed', color='#006699');\nplt.plot(train_predict_plot, label='Prediction for Train Set', color='#006699', alpha=0.5);\nplt.plot(test_predict_plot, label='Prediction for Test Set', color='#ff0066');\nplt.legend(loc='upper left')\n\nplt.title('LSTM Recurrent Neural Net')\nplt.show()",
"_____no_output_____"
],
[
"mse = mean_squared_error(y_test, test_predict[:,0])\nplt.title('Prediction quality: {:.2f} MSE ({:.2f} RMSE)'.format(mse, math.sqrt(mse)))\nplt.plot(y_test.reshape(-1, 1), label='Observed', color='#006699')\nplt.plot(test_predict.reshape(-1, 1), label='Prediction', color='#ff0066')\nplt.legend(loc='upper left');\n\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0ae7d3c2a1b10de5fa9ea2facf05a9acc788982 | 5,110 | ipynb | Jupyter Notebook | chapters/ch01/sections/chem4tech01_05.ipynb | pscoppock/chem4tech | 01cdcbf138b33eb32d00024f77dc1d661369a2e2 | [
"MIT"
] | null | null | null | chapters/ch01/sections/chem4tech01_05.ipynb | pscoppock/chem4tech | 01cdcbf138b33eb32d00024f77dc1d661369a2e2 | [
"MIT"
] | null | null | null | chapters/ch01/sections/chem4tech01_05.ipynb | pscoppock/chem4tech | 01cdcbf138b33eb32d00024f77dc1d661369a2e2 | [
"MIT"
] | null | null | null | 30.783133 | 424 | 0.601566 | [
[
[
"<font color ='0c6142' size=6)> Chemistry </font> <font color ='708090' size=3)> for Technology Students at GGC </font> ",
"_____no_output_____"
],
[
"<font color ='708090' size=3)> Measurement Uncertainty, Accuracy, and Precision </font>\n\n[Textbook: Chapter 1, section 5](https://openstax.org/books/chemistry-2e/pages/1-5-measurement-uncertainty-accuracy-and-precision)",
"_____no_output_____"
],
[
"### Measurement Uncertainty",
"_____no_output_____"
],
[
"Most measurements are very much _not_ like that. You can easily imagine getting 4.34 gallons of gasoline at the gas station, right? Or 2.47 pounds of catfish at the deli?\n\nPython has a way to deal with these numbers. And they're called __floats__. It turns out the difference between these numbers is not going to be a big deal in most applications, but it's a fundamental concept, and sometimes it matters. Computers store integers and floats differently and use them differently, and when we are doing really big calculations, it could mean the difference between _can_ and _can't_.\n\nTry `print(type(3.14159))`.",
"_____no_output_____"
],
[
"What would you say if your friend told you he measured the diameter of a hair with a yardstick? Nonsense, right? Or the length of a cellphone with a car's odometer?\n\nIn order to do that, he would have to take a cellphone and put it on the ground - hopefully his own. Then he would have to drive over the phone, checking his odometer as the center of the wheel passed over the first edge, and then again as it passed over the far edge.\n\nWhat's the problem with those examples? Besides the fact dude just ruined his cellphone, in both cases, the measurements exceed the limits of the apparatus. Yardsticks aren't made to measure lengths smaller than the markings on the stick, let alone lengths much, much smaller.\n\nThis is where _significant figures_ comes in. The number of sig figs gives us a measure of how precise our measurement is.\n\nPython has a way of formatting strings, so when your calcuation makes an output, and you send it to a file, you can show how precisely your measurement was taken.\n\n`d = 1.00 # inches` \n`pi = 3.1415926` \n`c = pi*d` \n`print (\"The circumference of the circle is {:.2f}\".format(c))` \n\nTry it.",
"_____no_output_____"
]
],
[
[
"d = 1.00 # inches\npi = 3.1415926\nc = pi*d\nprint (\"The circumference of the circle is {:.2f} inches.\".format(c)) ",
"The circumference of the circle is 3.14 inches.\n"
]
],
[
[
"## Exercises",
"_____no_output_____"
],
[
"1. In the last example above, the circumference of a circle is given to 2 decimal places - or 3 significant figures. Suppose we had a way of measuring the diameter to a much higher precision. Namely, suppose we knew it was 1.0000 inches. Copy the code and alter it so that this is reflected in the output string.",
"_____no_output_____"
],
[
"2. Set two variables, `exact_nums` and `uncertain_nums`. Go to your textbook and draft good definitions of those.",
"_____no_output_____"
],
[
"***\n[Table of Contents](../../../chem4tech.ipynb) \n[Chapter 1, section 6](../sections/chem4tech01_06.ipynb)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
d0ae8c30db23c3c1d41b6c34222ab50ddd70ec87 | 10,774 | ipynb | Jupyter Notebook | Tarea4-sol.ipynb | diegotg2000/Tarea1-Lineal | 70c4bcd70d9ca484b64ade59d755de4389e3e1ee | [
"MIT"
] | null | null | null | Tarea4-sol.ipynb | diegotg2000/Tarea1-Lineal | 70c4bcd70d9ca484b64ade59d755de4389e3e1ee | [
"MIT"
] | null | null | null | Tarea4-sol.ipynb | diegotg2000/Tarea1-Lineal | 70c4bcd70d9ca484b64ade59d755de4389e3e1ee | [
"MIT"
] | null | null | null | 17.956667 | 102 | 0.406256 | [
[
[
"#i)\nV=QQ^3\ndef f(v):\n x=v[0]\n y=v[1]\n z=v[2]\n \n a=4*x\n b=3*x + y - 3*z\n c=3*x - 3*y + z\n \n w=vector(QQ,[a,b,c])\n return w",
"_____no_output_____"
],
[
"#Rep matricial\nA=column_matrix([f([1,0,0]),f([0,1,0]),f([0,0,1])])\nA",
"_____no_output_____"
],
[
"#Factorizacion del polinomio\nt=PolynomialRing(RationalField(), 't').gen()\nP=A.charpoly('t')\nP1,P2=factor(P)\nfactor(P)",
"_____no_output_____"
],
[
"P1 = (t+2)\nP2 = (t-4)^2\nP12, Q1, Q2 = xgcd(P1,P2)\nPi1=Q2*P2\nPi2=Q1*P1",
"_____no_output_____"
],
[
"Pr1=Pi1(A)\nPr2=Pi2(A)",
"_____no_output_____"
],
[
"#Polinomios\nprint(\"Pi1=\",(Pi1),' y Pi2=',(Pi2))",
"('Pi1=', 1/36*t^2 - 2/9*t + 4/9, ' y Pi2=', -1/36*t^2 + 2/9*t + 5/9)\n"
],
[
"#Verificamos que las matrices de proyeccion sean en efecto \n#proyecciones (A^2 = A) y que la suma de la identidad\nPr1^2-Pr1",
"_____no_output_____"
],
[
"Pr2^2 - Pr2",
"_____no_output_____"
],
[
"Pr1+Pr2",
"_____no_output_____"
],
[
"#ii)\nV=QQ^3\ndef f(v):\n x=v[0]\n y=v[1]\n z=v[2]\n \n a=5*x - y + z\n b=5*x - y -3*z\n c=4*x - 4*y\n \n a=0.5*a\n b=0.5*b\n c=0.5*c\n \n w=vector(QQ,[a,b,c])\n return w",
"_____no_output_____"
],
[
"#Rep matricial\nA=column_matrix([f([1,0,0]),f([0,1,0]),f([0,0,1])])\nA",
"_____no_output_____"
],
[
"#Factorizacion del polinomio\nt=PolynomialRing(RationalField(), 't').gen()\nP=A.charpoly('t')\nP1,P2=factor(P)\nfactor(P)",
"_____no_output_____"
],
[
"P1 = (t+2)\nP2 = (t-2)^2\nP12, Q1, Q2 = xgcd(P1,P2)\nPi1=Q2*P2\nPi2=Q1*P1",
"_____no_output_____"
],
[
"Pr1=Pi1(A)\nPr2=Pi2(A)",
"_____no_output_____"
],
[
"#Polinomios\nprint(\"Pi1=\",(Pi1),' y Pi2=',(Pi2))",
"('Pi1=', 1/16*t^2 - 1/4*t + 1/4, ' y Pi2=', -1/16*t^2 + 1/4*t + 3/4)\n"
],
[
"#Verificamos que las matrices de proyeccion sean en efecto \n#proyecciones (A^2 = A) y que la suma de la identidad\nPr1^2-Pr1",
"_____no_output_____"
],
[
"Pr2^2 - Pr2",
"_____no_output_____"
],
[
"Pr1+Pr2",
"_____no_output_____"
],
[
"#iii)\nV=QQ^4\ndef f(v):\n x=v[0]\n y=v[1]\n z=v[2]\n w=v[3]\n \n a=11*x - y - z + 2*w\n b=14*x + 2*y - 7*z - 4*w\n c=13*x - 5*y + z -5*w\n d=13*x - 8*y -5*z + 4*w\n \n a=a/3\n b=b/3\n c=c/3\n d=d/3\n \n g=vector(QQ,[a,b,c,d])\n return g",
"_____no_output_____"
],
[
"#Rep matricial\nA=column_matrix([f([1,0,0,0]),f([0,1,0,0]),f([0,0,1,0]),f([0,0,0,1])])\nA",
"_____no_output_____"
],
[
"#Factorizacion del polinomio\nt=PolynomialRing(RationalField(), 't').gen()\nP=A.charpoly('t')\nP1,P2=factor(P)\nfactor(P)",
"_____no_output_____"
],
[
"P1 = (t+3)\nP2 = (t-3)^3\nP12, Q1, Q2 = xgcd(P1,P2)\nPi1=Q2*P2\nPi2=Q1*P1",
"_____no_output_____"
],
[
"Pr1=Pi1(A)\nPr2=Pi2(A)",
"_____no_output_____"
],
[
"#Polinomios\nprint(\"Pi1=\",(Pi1),' y Pi2=',(Pi2))",
"('Pi1=', -1/216*t^3 + 1/24*t^2 - 1/8*t + 1/8, ' y Pi2=', 1/216*t^3 - 1/24*t^2 + 1/8*t + 7/8)\n"
],
[
"#Verificamos que las matrices de proyeccion sean en efecto \n#proyecciones (A^2 = A) y que la suma de la identidad\nPr1^2-Pr1",
"_____no_output_____"
],
[
"Pr2^2 - Pr2",
"_____no_output_____"
],
[
"Pr1+Pr2",
"_____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"
]
] |
d0ae8cbe67543d1349463e9dd76618f6eb572848 | 127,956 | ipynb | Jupyter Notebook | EnsemblePursuitSynapseExploration.ipynb | mariakesa/DayanAbbottExplorations | bbaeabf40842c4a7b101a465f7a127853fa929a3 | [
"MIT"
] | null | null | null | EnsemblePursuitSynapseExploration.ipynb | mariakesa/DayanAbbottExplorations | bbaeabf40842c4a7b101a465f7a127853fa929a3 | [
"MIT"
] | null | null | null | EnsemblePursuitSynapseExploration.ipynb | mariakesa/DayanAbbottExplorations | bbaeabf40842c4a7b101a465f7a127853fa929a3 | [
"MIT"
] | null | null | null | 247.019305 | 27,528 | 0.915385 | [
[
[
"import sys\nsys.path.insert(1, '/home/maria/Documents/EnsemblePursuit')\nfrom EnsemblePursuit.EnsemblePursuit import EnsemblePursuit\nimport numpy as np\nfrom scipy.stats import zscore\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import gaussian_filter, gaussian_filter1d",
"_____no_output_____"
],
[
"data_path='/home/maria/Documents/data_for_suite2p/TX39/'\ndt=1\nspks= np.load(data_path+'spks.npy')\nprint('Shape of the data matrix, neurons by timepoints:',spks.shape)\niframe = np.load(data_path+'iframe.npy') # iframe[n] is the microscope frame for the image frame n\nivalid = iframe+dt<spks.shape[-1] # remove timepoints outside the valid time range\niframe = iframe[ivalid]\nS = spks[:, iframe+dt]\nprint(S.shape)\n#Uncomment to compute U and V\nep=EnsemblePursuit(n_components=200,lam=0.01,n_kmeans=200)\nmodel=ep.fit(S.T[:10000,:])\nV=model.components_\nU=model.weights\nnp.save('U.npy',U)",
"Shape of the data matrix, neurons by timepoints: (18795, 30766)\n(18795, 30560)\nobtained 200 PCs in 14.3127 seconds\ninitialized 200 clusters with k-means in 27.3413 seconds\nensemble 0, time 14.31, nr neurons 6340, EV 0.0086\nensemble 25, time 102.67, nr neurons 206, EV 0.0329\nensemble 50, time 170.51, nr neurons 90, EV 0.0420\nensemble 75, time 232.66, nr neurons 95, EV 0.0492\nensemble 100, time 290.18, nr neurons 100, EV 0.0551\nensemble 125, time 344.61, nr neurons 80, EV 0.0605\nensemble 150, time 396.57, nr neurons 50, EV 0.0652\nensemble 175, time 445.77, nr neurons 46, EV 0.0695\nensemble 199, time 491.43, nr neurons 41, EV 0.0734\naverage sparsity is 0.0100\n"
],
[
"#13\nprint(U.shape)\nprint(np.nonzero(U[:,13])[0])\nprint(S.shape)\nprint(S[np.nonzero(U[:,13])[0],:].shape)",
"(18795, 200)\n[ 2879 2883 2890 2929 2955 2976 2980 3017 3033 3034 3082 3097\n 3107 3117 3126 3137 3159 3167 3207 3210 3256 3266 3268 3286\n 3291 3294 3316 3335 3360 3364 3368 3371 3372 3378 3426 3429\n 3451 3456 3460 3482 3490 3491 3520 3561 3585 3612 3615 3618\n 3641 3660 3663 3668 3677 3702 3724 3756 3760 3781 3809 3869\n 3872 3878 3882 3939 3975 3988 3992 4004 4016 4030 4049 4054\n 4083 4085 4086 4094 4095 4150 4159 4169 4182 4221 4247 4249\n 4253 4285 4320 4356 4376 4381 4403 4418 4428 4435 4449 4463\n 4474 4489 4501 4518 4521 4523 4566 4575 4578 4581 4588 4591\n 4606 4617 4619 4641 4667 4671 4680 4682 4691 4733 4751 4755\n 4776 4783 4786 4844 4855 4860 4922 4928 4946 4959 4973 4975\n 4988 5004 5027 5039 5061 5067 5096 5107 5127 5158 5179 5200\n 5214 5225 5228 5241 5261 5296 5312 5324 5359 5368 5370 5389\n 5405 5434 5470 5474 5476 5486 5515 5535 5553 5557 5579 5584\n 5601 5688 5694 5714 5722 5727 5733 5758 5772 5787 5802 5844\n 5853 5903 5920 5944 5952 5954 5962 5970 5986 6032 6033 6070\n 6100 6107 6138 6177 6181 6184 6246 6253 6276 6298 6305 6342\n 6363 6390 6422 6439 6451 6492 6493 6539 6588 6599 6619 6623\n 6629 6631 6651 6659 6725 6760 6780 6803 6815 6816 6819 6882\n 6915 6928 6954 6976 7056 7069 7082 7107 7118 7158 7163 7200\n 7230 7253 7263 7264 7272 7281 7300 7328 7371 7378 7388 7399\n 7420 7424 7436 7438 7440 7457 7500 7511 7540 7551 7570 7592\n 7593 7606 7611 7625 7640 7641 7655 7663 7668 7685 7734 7740\n 7743 7749 7758 7769 7783 7855 7860 7870 7900 7923 7933 7938\n 7945 7972 7994 8004 8007 8008 8028 8042 8045 8057 8071 8094\n 8134 8152 8167 8470 8515 8521 8527 8529 8548 8557 8605 8654\n 8677 8710 8723 8725 8757 8773 8774 8779 8794 8796 8804 8813\n 8842 8843 8851 8855 8858 8861 8867 8881 8899 8929 8944 8960\n 8985 9004 9013 9031 9046 9057 9066 9069 9088 9106 9107 9122\n 9124 9149 9150 9158 9191 9192 9224 9230 9254 9263 9275 9295\n 9300 9317 9320 9329 9337 9352 9354 9365 9419 9428 9437 9455\n 9462 9503 9566 9574 9583 9591 9599 9614 9616 9655 9662 9678\n 9698 9710 9716 9730 9737 9747 9748 9781 9782 9808 9815 9834\n 9837 9838 9844 9850 9866 9880 9882 9891 9949 9953 9980 9989\n 9994 10007 10010 10021 10031 10035 10056 10057 10066 10103 10116 10121\n 10134 10147 10154 10165 10172 10182 10185 10186 10203 10248 10250 10290\n 10293 10294 10325 10327 10329 10350 10351 10358 10396 10406 10431 10466\n 10501 10514 10568 10571 10623 10631 10633 10661 10664 10683 10700 10702\n 10703 10718 10725 10764 10771 10790 10809 10816 10831 10905 10917 10920\n 10948 10958 10967 10991 11081 11088 11090 11108 11122 11125 11127 11129\n 11146 11147 11162 11163 11164 11167 11187 11211 11223 11225 11240 11247\n 11289 11295 11317 11335 11344 11352 11355 11356 11361 11382 11385 11388\n 11390 11396 11403 11404 11443 11451 11455 11471 11474 11478 11481 11482\n 11491 11506 11509 11516 11523 11531 11534 11542 11554 11566 11569 11570\n 11579 11581 11596 11597 11608 11636 11658 11664 11678 11679 11688 11692\n 11699 11710 11724 11745 11747 11792 11878 11882 11891 11892 11902 11906\n 11907 11909 11934 11947 11950 12026 12029 12040 12044 12046 12052 12055\n 12072 12094 12133 12149 12151 12152 12212 12261 12263 12269 12280 12287\n 12314 12329 12344 12356 12358 12362 12364 12377 12381 12396 12434 12439\n 12444 12462 12495 12500 12526 12569 12581 12592 12602 12607 12609 12613\n 12658 12662 12670 12673 12680 12703 12726 12739 12744 12752 12757 12806\n 12824 12837 12861 12868 12878 12893 12908 12937 12957 12968 12969 12973\n 12984 12997 13003 13009 13017 13031 13079 13084 13091 13096 13100 13110\n 13139 13140 13143 13151 13152 13195 13196 13197 13223 13228 13283 13936\n 14039 14397 14593 15434 15464 15554 16350 16697]\n(18795, 30560)\n(656, 30560)\n"
],
[
"stat = np.load(('/home/maria/Documents/data_for_suite2p/TX39/'+'stat.npy'), allow_pickle=True) # these are the per-neuron stats returned by suite2p\n# these are the neurons' 2D coordinates\nypos = np.array([stat[n]['med'][0] for n in range(len(stat))]) \n# (notice the python list comprehension [X(n) for n in range(N)])\nxpos = np.array([stat[n]['med'][1] for n in range(len(stat))]) \ncomp=U[:,13]\ncomp= comp/np.max(np.abs(comp))\nlam = np.abs(comp) \nplt.scatter(xpos, -ypos, s = 50 * lam, c = comp, cmap='bwr', alpha = .5)",
"_____no_output_____"
]
],
[
[
"# Inject activity patterns without plasticity",
"_____no_output_____"
]
],
[
[
"np.random.seed(7)\ninput_patterns=S[np.nonzero(U[:,13])[0],:]\ninput_patterns=zscore(input_patterns,axis=1)\nv_lst=[]\nw=np.random.normal(loc=0,size=(656,))\nv_lst=[np.dot(w,input_patterns[:,0])]\nfor j in range(1,30560):\n v_lst.append(np.dot(w,input_patterns[:,j]))\n \nplt.plot(zscore(v_lst[:100]))\nplt.show()\nplt.plot(input_patterns[1,:100])\nv_lst=np.array(zscore(v_lst))",
"_____no_output_____"
],
[
"print(v_lst.shape)",
"(30560,)\n"
],
[
"def train_test_split(NT):\n nsegs = 20\n nt=NT\n nlen = nt/nsegs\n ninds = np.linspace(0,nt-nlen,nsegs).astype(int)\n itest = (ninds[:,np.newaxis] + np.arange(0,nlen*0.25,1,int)).flatten()\n itrain = np.ones(nt, np.bool)\n itrain[itest] = 0\n return itrain, itest\n\nmov=np.load(data_path+'mov.npy')\nmov = mov[:, :, ivalid]\nly, lx, nstim = mov.shape\n#print(nstim)\nNT = v_lst.shape[0]\nNN=1\nmov=mov[:,:,:NT]\nprint(NT)\nitrain,itest=train_test_split(NT)\n\nX = np.reshape(mov, [-1, NT]) # reshape to Npixels by Ntimepoints\nX = X-0.5 # subtract the background\nX = np.abs(X) # does not matter if a pixel is black (0) or white (1)\nX = zscore(X, axis=1)/NT**.5 # z-score each pixel separately\nnpix = X.shape[0]\n\nlam = 0.1\nncomps = Sp.shape[0]\nB0 = np.linalg.solve((X[:,itrain] @ X[:,itrain].T + lam * np.eye(npix)), (X[:,itrain] @ v_lst[itrain].T)) # get the receptive fields for each neuron\n\nB0 = np.reshape(B0, (ly, lx, 1))\nB0 = gaussian_filter(B0, [.5, .5, 0]) # smooth each receptive field a littleb",
"30560\n"
],
[
"rf = B0[:,:,0]\nrfmax = np.max(B0)\n# rfmax = np.max(np.abs(rf))\nplt.imshow(rf, aspect='auto', cmap = 'bwr', vmin = -rfmax, vmax = rfmax)",
"_____no_output_____"
]
],
[
[
"# Inject patterns with plasticity",
"_____no_output_____"
]
],
[
[
"#Using Euler's method to calculate the weight increments\nh=0.001\ninput_patterns=S[np.nonzero(U[:,13])[0],:]\ninput_patterns=zscore(input_patterns,axis=1)\nprint(input_patterns.shape)\nv_lst=[]\nw_lst=[]\nw=np.random.normal(loc=0,size=(656,))\nv_lst=[np.dot(w,input_patterns[:,1])]\nfor j in range(0,1000):\n v_lst.append(np.dot(w,input_patterns[:,j]))\n w=w+h*v_lst[-1]*input_patterns[:,j]\n w=np.clip(w,a_min=-100,a_max=100)\n w_lst.append(w)\nw_arr=np.array(w_lst).T\nprint(w_arr.shape)\nplt.plot(w_arr[0,:])",
"(656, 30560)\n(656, 1000)\n"
],
[
"for j in range(0,10):\n plt.plot(w_arr[j,:])",
"_____no_output_____"
],
[
"v_lst=np.array(zscore(v_lst))\nmov=np.load(data_path+'mov.npy')\nmov = mov[:, :, ivalid]\nly, lx, nstim = mov.shape\n#print(nstim)\nNT = v_lst.shape[0]\nNN=1\nmov=mov[:,:,:NT]\nprint(NT)\nitrain,itest=train_test_split(NT)\n\nX = np.reshape(mov, [-1, NT]) # reshape to Npixels by Ntimepoints\nX = X-0.5 # subtract the background\nX = np.abs(X) # does not matter if a pixel is black (0) or white (1)\nX = zscore(X, axis=1)/NT**.5 # z-score each pixel separately\nnpix = X.shape[0]\n\nlam = 0.1\nncomps = Sp.shape[0]\nB0 = np.linalg.solve((X[:,itrain] @ X[:,itrain].T + lam * np.eye(npix)), (X[:,itrain] @ v_lst[itrain].T)) # get the receptive fields for each neuron\n\nB0 = np.reshape(B0, (ly, lx, 1))\nB0 = gaussian_filter(B0, [.5, .5, 0]) # smooth each receptive field a littleb",
"1001\n"
],
[
"rf = B0[:,:,0]\nrfmax = np.max(B0)\n# rfmax = np.max(np.abs(rf))\nplt.imshow(rf, aspect='auto', cmap = 'bwr', vmin = -rfmax, vmax = rfmax)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0aea2e91203aaef13806ec7021a5f4380752b9d | 553,841 | ipynb | Jupyter Notebook | docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb | cjcardinale/climlab | 95d64326713f27b9a3b84aabfd9e70e93e13a2f0 | [
"BSD-3-Clause",
"MIT"
] | 160 | 2015-02-25T15:56:37.000Z | 2022-03-14T23:51:23.000Z | docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb | cjcardinale/climlab | 95d64326713f27b9a3b84aabfd9e70e93e13a2f0 | [
"BSD-3-Clause",
"MIT"
] | 137 | 2015-12-18T17:39:31.000Z | 2022-02-04T20:50:53.000Z | docs/source/courseware/Soundings_from_Observations_and_RCE_Models.ipynb | cjcardinale/climlab | 95d64326713f27b9a3b84aabfd9e70e93e13a2f0 | [
"BSD-3-Clause",
"MIT"
] | 54 | 2015-04-28T05:57:39.000Z | 2022-02-17T08:15:11.000Z | 302.645355 | 73,112 | 0.904458 | [
[
[
"# Comparing soundings from NCEP Reanalysis and various models",
"_____no_output_____"
],
[
"We are going to plot the global, annual mean sounding (vertical temperature profile) from observations.\n\nRead in the necessary NCEP reanalysis data from the online server.\n\nThe catalog is here: <https://psl.noaa.gov/psd/thredds/catalog/Datasets/ncep.reanalysis.derived/catalog.html>",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xarray as xr\n\nncep_url = \"https://psl.noaa.gov/thredds/dodsC/Datasets/ncep.reanalysis.derived/\"\nncep_air = xr.open_dataset( ncep_url + \"pressure/air.mon.1981-2010.ltm.nc\", decode_times=False)",
"_____no_output_____"
],
[
"level = ncep_air.level\nlat = ncep_air.lat",
"_____no_output_____"
]
],
[
[
"Take global averages and time averages.",
"_____no_output_____"
]
],
[
[
"Tzon = ncep_air.air.mean(dim=('lon','time'))\nweight = np.cos(np.deg2rad(lat)) / np.cos(np.deg2rad(lat)).mean(dim='lat')\nTglobal = (Tzon * weight).mean(dim='lat')",
"_____no_output_____"
]
],
[
[
"Here is code to make a nicely labeled sounding plot.",
"_____no_output_____"
]
],
[
[
"fig = plt.figure( figsize=(10,8) )\nax = fig.add_subplot(111)\nax.plot( Tglobal + 273.15, np.log(level/1000))\nax.invert_yaxis()\nax.set_xlabel('Temperature (K)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nax.set_yticks( np.log(level/1000) )\nax.set_yticklabels( level.values )\nax.set_title('Global, annual mean sounding from NCEP Reanalysis', fontsize = 24)\nax2 = ax.twinx()\nax2.plot( Tglobal + 273.15, -8*np.log(level/1000) );\nax2.set_ylabel('Approx. height above surface (km)', fontsize=16 );\nax.grid()",
"_____no_output_____"
]
],
[
[
"## Now compute the Radiative Equilibrium solution for the grey-gas column model",
"_____no_output_____"
]
],
[
[
"import climlab\nfrom climlab import constants as const",
"_____no_output_____"
],
[
"col = climlab.GreyRadiationModel()\nprint(col)",
"climlab Process of type <class 'climlab.model.column.GreyRadiationModel'>. \nState variables and domain shapes: \n Ts: (1,) \n Tatm: (30,) \nThe subprocess tree: \nUntitled: <class 'climlab.model.column.GreyRadiationModel'>\n LW: <class 'climlab.radiation.greygas.GreyGas'>\n SW: <class 'climlab.radiation.greygas.GreyGasSW'>\n insolation: <class 'climlab.radiation.insolation.FixedInsolation'>\n\n"
],
[
"col.subprocess['LW'].diagnostics",
"_____no_output_____"
],
[
"col.integrate_years(1)\n\nprint(\"Surface temperature is \" + str(col.Ts) + \" K.\")\nprint(\"Net energy in to the column is \" + str(col.ASR - col.OLR) + \" W / m2.\")",
"Integrating for 365 steps, 365.2422 days, or 1 years.\nTotal elapsed time is 0.9993368783782377 years.\nSurface temperature is [287.84577808] K.\nNet energy in to the column is [0.00165505] W / m2.\n"
]
],
[
[
"### Plot the radiative equilibrium temperature on the same plot with NCEP reanalysis",
"_____no_output_____"
]
],
[
[
"pcol = col.lev\n\nfig = plt.figure( figsize=(10,8) )\nax = fig.add_subplot(111)\nax.plot( Tglobal + 273.15, np.log(level/1000), 'b-', col.Tatm, np.log( pcol/const.ps ), 'r-' )\nax.plot( col.Ts, 0, 'ro', markersize=20 )\nax.invert_yaxis()\nax.set_xlabel('Temperature (K)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nax.set_yticks( np.log(level/1000) )\nax.set_yticklabels( level.values )\nax.set_title('Temperature profiles: observed (blue) and radiative equilibrium in grey gas model (red)', fontsize = 18)\nax2 = ax.twinx()\nax2.plot( Tglobal + const.tempCtoK, -8*np.log(level/1000) );\nax2.set_ylabel('Approx. height above surface (km)', fontsize=16 );\nax.grid()",
"_____no_output_____"
]
],
[
[
"## Now use convective adjustment to compute a Radiative-Convective Equilibrium temperature profile",
"_____no_output_____"
]
],
[
[
"dalr_col = climlab.RadiativeConvectiveModel(adj_lapse_rate='DALR')\nprint(dalr_col)",
"climlab Process of type <class 'climlab.model.column.RadiativeConvectiveModel'>. \nState variables and domain shapes: \n Ts: (1,) \n Tatm: (30,) \nThe subprocess tree: \nUntitled: <class 'climlab.model.column.RadiativeConvectiveModel'>\n LW: <class 'climlab.radiation.greygas.GreyGas'>\n SW: <class 'climlab.radiation.greygas.GreyGasSW'>\n insolation: <class 'climlab.radiation.insolation.FixedInsolation'>\n convective adjustment: <class 'climlab.convection.convadj.ConvectiveAdjustment'>\n\n"
],
[
"dalr_col.integrate_years(2.)\n\nprint(\"After \" + str(dalr_col.time['days_elapsed']) + \" days of integration:\")\nprint(\"Surface temperature is \" + str(dalr_col.Ts) + \" K.\")\nprint(\"Net energy in to the column is \" + str(dalr_col.ASR - dalr_col.OLR) + \" W / m2.\")",
"Integrating for 730 steps, 730.4844 days, or 2.0 years.\nTotal elapsed time is 1.9986737567564754 years.\nAfter 730.0 days of integration:\nSurface temperature is [283.040058] K.\nNet energy in to the column is [1.09588387e-06] W / m2.\n"
],
[
"dalr_col.param",
"_____no_output_____"
]
],
[
[
"Now plot this \"Radiative-Convective Equilibrium\" on the same graph:",
"_____no_output_____"
]
],
[
[
"fig = plt.figure( figsize=(10,8) )\nax = fig.add_subplot(111)\nax.plot( Tglobal + 273.15, np.log(level/1000), 'b-', col.Tatm, np.log( pcol/const.ps ), 'r-' )\nax.plot( col.Ts, 0, 'ro', markersize=16 )\nax.plot( dalr_col.Tatm, np.log( pcol / const.ps ), 'k-' )\nax.plot( dalr_col.Ts, 0, 'ko', markersize=16 )\nax.invert_yaxis()\nax.set_xlabel('Temperature (K)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nax.set_yticks( np.log(level/1000) )\nax.set_yticklabels( level.values )\nax.set_title('Temperature profiles: observed (blue), RE (red) and dry RCE (black)', fontsize = 18)\nax2 = ax.twinx()\nax2.plot( Tglobal + const.tempCtoK, -8*np.log(level/1000) );\nax2.set_ylabel('Approx. height above surface (km)', fontsize=16 );\nax.grid()",
"_____no_output_____"
]
],
[
[
"The convective adjustment gets rid of the unphysical temperature difference between the surface and the overlying air.\n\nBut now the surface is colder! Convection acts to move heat upward, away from the surface.\n\nAlso, we note that the observed lapse rate (blue) is always shallower than $\\Gamma_d$ (temperatures decrease more slowly with height).",
"_____no_output_____"
],
[
"## \"Moist\" Convective Adjustment",
"_____no_output_____"
],
[
"To approximately account for the effects of latent heat release in rising air parcels, we can just adjust to a lapse rate that is a little shallow than $\\Gamma_d$.\n\nWe will choose 6 K / km, which gets close to the observed mean lapse rate.\n\nWe will also re-tune the longwave absorptivity of the column to get a realistic surface temperature of 288 K:\n",
"_____no_output_____"
]
],
[
[
"rce_col = climlab.RadiativeConvectiveModel(adj_lapse_rate=6, abs_coeff=1.7E-4)\nprint(rce_col)",
"climlab Process of type <class 'climlab.model.column.RadiativeConvectiveModel'>. \nState variables and domain shapes: \n Ts: (1,) \n Tatm: (30,) \nThe subprocess tree: \nUntitled: <class 'climlab.model.column.RadiativeConvectiveModel'>\n LW: <class 'climlab.radiation.greygas.GreyGas'>\n SW: <class 'climlab.radiation.greygas.GreyGasSW'>\n insolation: <class 'climlab.radiation.insolation.FixedInsolation'>\n convective adjustment: <class 'climlab.convection.convadj.ConvectiveAdjustment'>\n\n"
],
[
"rce_col.integrate_years(2.)\n\nprint(\"After \" + str(rce_col.time['days_elapsed']) + \" days of integration:\")\nprint(\"Surface temperature is \" + str(rce_col.Ts) + \" K.\")\nprint(\"Net energy in to the column is \" + str(rce_col.ASR - rce_col.OLR) + \" W / m2.\")",
"Integrating for 730 steps, 730.4844 days, or 2.0 years.\nTotal elapsed time is 1.9986737567564754 years.\nAfter 730.0 days of integration:\nSurface temperature is [287.9049635] K.\nNet energy in to the column is [2.14745046e-06] W / m2.\n"
]
],
[
[
"Now add this new temperature profile to the graph:",
"_____no_output_____"
]
],
[
[
"fig = plt.figure( figsize=(10,8) )\nax = fig.add_subplot(111)\nax.plot( Tglobal + 273.15, np.log(level/1000), 'b-', col.Tatm, np.log( pcol/const.ps ), 'r-' )\nax.plot( col.Ts, 0, 'ro', markersize=16 )\nax.plot( dalr_col.Tatm, np.log( pcol / const.ps ), 'k-' )\nax.plot( dalr_col.Ts, 0, 'ko', markersize=16 )\nax.plot( rce_col.Tatm, np.log( pcol / const.ps ), 'm-' )\nax.plot( rce_col.Ts, 0, 'mo', markersize=16 )\nax.invert_yaxis()\nax.set_xlabel('Temperature (K)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nax.set_yticks( np.log(level/1000) )\nax.set_yticklabels( level.values )\nax.set_title('Temperature profiles: observed (blue), RE (red), dry RCE (black), and moist RCE (magenta)', fontsize = 18)\nax2 = ax.twinx()\nax2.plot( Tglobal + const.tempCtoK, -8*np.log(level/1000) );\nax2.set_ylabel('Approx. height above surface (km)', fontsize=16 );\nax.grid()",
"_____no_output_____"
]
],
[
[
"## Adding stratospheric ozone",
"_____no_output_____"
],
[
"Our model has no equivalent of the stratosphere, where temperature increases with height. That's because our model has been completely transparent to shortwave radiation up until now.\n\nWe can load some climatogical ozone data:",
"_____no_output_____"
]
],
[
[
"# Put in some ozone\nimport xarray as xr\n\nozonepath = \"http://thredds.atmos.albany.edu:8080/thredds/dodsC/CLIMLAB/ozone/apeozone_cam3_5_54.nc\"\nozone = xr.open_dataset(ozonepath)\nozone",
"_____no_output_____"
]
],
[
[
"Take the global average of the ozone climatology, and plot it as a function of pressure (or height)",
"_____no_output_____"
]
],
[
[
"# Taking annual, zonal, and global averages of the ozone data\nO3_zon = ozone.OZONE.mean(dim=(\"time\",\"lon\"))\n\nweight_ozone = np.cos(np.deg2rad(ozone.lat)) / np.cos(np.deg2rad(ozone.lat)).mean(dim='lat')\nO3_global = (O3_zon * weight_ozone).mean(dim='lat')",
"_____no_output_____"
],
[
"O3_global.shape",
"_____no_output_____"
],
[
"ax = plt.figure(figsize=(10,8)).add_subplot(111)\nax.plot( O3_global * 1.E6, np.log(O3_global.lev/const.ps) )\nax.invert_yaxis()\nax.set_xlabel('Ozone (ppm)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nyticks = np.array([1000., 500., 250., 100., 50., 20., 10., 5.])\nax.set_yticks( np.log(yticks/1000.) )\nax.set_yticklabels( yticks )\nax.set_title('Global, annual mean ozone concentration', fontsize = 24);",
"_____no_output_____"
]
],
[
[
"This shows that most of the ozone is indeed in the stratosphere, and peaks near the top of the stratosphere.\n\nNow create a new column model object **on the same pressure levels as the ozone data**. We are also going set an adjusted lapse rate of 6 K / km, and tune the longwave absorption ",
"_____no_output_____"
]
],
[
[
"oz_col = climlab.RadiativeConvectiveModel(lev = ozone.lev, \n abs_coeff=1.82E-4, \n adj_lapse_rate=6, \n albedo=0.315)",
"_____no_output_____"
]
],
[
[
"Now we will do something new: let the column absorb some shortwave radiation. We will assume that the shortwave absorptivity is proportional to the ozone concentration we plotted above. We need to weight the absorptivity by the pressure (mass) of each layer.",
"_____no_output_____"
]
],
[
[
"ozonefactor = 75\ndp = oz_col.Tatm.domain.axes['lev'].delta\nsw_abs = O3_global * dp * ozonefactor\noz_col.subprocess.SW.absorptivity = sw_abs\noz_col.compute()\noz_col.compute()\nprint(oz_col.SW_absorbed_atm)",
"[0.01521244 0.00239547 0.00294491 0.00359022 0.00437158 0.0053308\n 0.006518 0.00801322 0.00983974 0.0122112 0.01517438 0.01896033\n 0.02378877 0.03006126 0.03813404 0.04839947 0.06121356 0.07689825\n 0.0956929 0.11774895 0.14311224 0.17200325 0.20535155 0.24420577\n 0.28873387 0.33942617 0.39635885 0.45785715 0.51545681 0.57046196\n 0.61908838 0.65388737 0.67529707 0.68302918 0.67627911 0.65546409\n 0.61861086 0.56348381 0.48940972 0.40411693 0.32861214 0.27967132\n 0.23974031 0.20685342 0.18078828 0.16426141 0.14274006 0.1154594\n 0.09590159 0.09087993 0.09138546 0.09250529 0.09439986 0.09848981\n 0.10256593 0.10092918 0.09452428 0.05852275 0.01312565]\n"
]
],
[
[
"Now run it out to Radiative-Convective Equilibrium, and plot",
"_____no_output_____"
]
],
[
[
"oz_col.integrate_years(2.)\n\nprint(\"After \" + str(oz_col.time['days_elapsed']) + \" days of integration:\")\nprint(\"Surface temperature is \" + str(oz_col.Ts) + \" K.\")\nprint(\"Net energy in to the column is \" + str(oz_col.ASR - oz_col.OLR) + \" W / m2.\")",
"Integrating for 730 steps, 730.4844 days, or 2.0 years.\nTotal elapsed time is 1.9986737567564754 years.\nAfter 730.0 days of integration:\nSurface temperature is [289.52088978] K.\nNet energy in to the column is [-9.48869513e-07] W / m2.\n"
],
[
"pozcol = oz_col.lev\n\nfig = plt.figure( figsize=(10,8) )\nax = fig.add_subplot(111)\nax.plot( Tglobal + const.tempCtoK, np.log(level/1000), 'b-', col.Tatm, np.log( pcol/const.ps ), 'r-' )\nax.plot( col.Ts, 0, 'ro', markersize=16 )\nax.plot( dalr_col.Tatm, np.log( pcol / const.ps ), 'k-' )\nax.plot( dalr_col.Ts, 0, 'ko', markersize=16 )\nax.plot( rce_col.Tatm, np.log( pcol / const.ps ), 'm-' )\nax.plot( rce_col.Ts, 0, 'mo', markersize=16 )\nax.plot( oz_col.Tatm, np.log( pozcol / const.ps ), 'c-' )\nax.plot( oz_col.Ts, 0, 'co', markersize=16 )\nax.invert_yaxis()\nax.set_xlabel('Temperature (K)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nax.set_yticks( np.log(level/1000) )\nax.set_yticklabels( level.values )\nax.set_title('Temperature profiles: observed (blue), RE (red), dry RCE (black), moist RCE (magenta), RCE with ozone (cyan)', fontsize = 18)\nax.grid()",
"_____no_output_____"
]
],
[
[
"And we finally have something that looks looks like the tropopause, with temperature increasing above at about the correct rate. Though the tropopause temperature is off by 15 degrees or so.",
"_____no_output_____"
],
[
"## Greenhouse warming in the RCE model with ozone",
"_____no_output_____"
]
],
[
[
"oz_col2 = climlab.process_like( oz_col )",
"_____no_output_____"
],
[
"oz_col2.subprocess['LW'].absorptivity *= 1.2 ",
"_____no_output_____"
],
[
"oz_col2.integrate_years(2.)",
"Integrating for 730 steps, 730.4844 days, or 2.0 years.\nTotal elapsed time is 3.997347513512951 years.\n"
],
[
"fig = plt.figure( figsize=(10,8) )\nax = fig.add_subplot(111)\nax.plot( Tglobal + const.tempCtoK, np.log(level/const.ps), 'b-' )\nax.plot( oz_col.Tatm, np.log( pozcol / const.ps ), 'c-' )\nax.plot( oz_col.Ts, 0, 'co', markersize=16 )\nax.plot( oz_col2.Tatm, np.log( pozcol / const.ps ), 'c--' )\nax.plot( oz_col2.Ts, 0, 'co', markersize=16 )\nax.invert_yaxis()\nax.set_xlabel('Temperature (K)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nax.set_yticks( np.log(level/const.ps) )\nax.set_yticklabels( level.values )\nax.set_title('Temperature profiles: observed (blue), RCE with ozone (cyan)', fontsize = 18)\nax.grid()",
"_____no_output_____"
]
],
[
[
"And we find that the troposphere warms, while the stratosphere cools!",
"_____no_output_____"
],
[
"### Vertical structure of greenhouse warming in CESM model",
"_____no_output_____"
]
],
[
[
"datapath = \"http://thredds.atmos.albany.edu:8080/thredds/dodsC/CESMA/\"\natmstr = \".cam.h0.clim.nc\"\n\ncesm_ctrl = xr.open_dataset(datapath + 'som_1850_f19/clim/som_1850_f19' + atmstr)\ncesm_2xCO2 = xr.open_dataset(datapath + 'som_1850_2xCO2/clim/som_1850_2xCO2' + atmstr)",
"_____no_output_____"
],
[
"cesm_ctrl.T",
"_____no_output_____"
],
[
"T_cesm_ctrl_zon = cesm_ctrl.T.mean(dim=('time', 'lon'))\nT_cesm_2xCO2_zon = cesm_2xCO2.T.mean(dim=('time', 'lon'))",
"_____no_output_____"
],
[
"weight = np.cos(np.deg2rad(cesm_ctrl.lat)) / np.cos(np.deg2rad(cesm_ctrl.lat)).mean(dim='lat')\n\nT_cesm_ctrl_glob = (T_cesm_ctrl_zon*weight).mean(dim='lat')\nT_cesm_2xCO2_glob = (T_cesm_2xCO2_zon*weight).mean(dim='lat')",
"_____no_output_____"
],
[
"fig = plt.figure( figsize=(10,8) )\nax = fig.add_subplot(111)\nax.plot( Tglobal + const.tempCtoK, np.log(level/const.ps), 'b-' )\nax.plot( oz_col.Tatm, np.log( pozcol / const.ps ), 'c-' )\nax.plot( oz_col.Ts, 0, 'co', markersize=16 )\nax.plot( oz_col2.Tatm, np.log( pozcol / const.ps ), 'c--' )\nax.plot( oz_col2.Ts, 0, 'co', markersize=16 )\nax.plot( T_cesm_ctrl_glob, np.log( cesm_ctrl.lev/const.ps ), 'r-' )\nax.plot( T_cesm_2xCO2_glob, np.log( cesm_ctrl.lev/const.ps ), 'r--' )\nax.invert_yaxis()\nax.set_xlabel('Temperature (K)', fontsize=16)\nax.set_ylabel('Pressure (hPa)', fontsize=16 )\nax.set_yticks( np.log(level/const.ps) )\nax.set_yticklabels( level.values )\nax.set_title('Temperature profiles: observed (blue), RCE with ozone (cyan), CESM (red)', fontsize = 18)\nax.grid()",
"_____no_output_____"
]
],
[
[
"And we find that CESM has the same tendency for increased CO2: warmer troposphere, colder stratosphere.",
"_____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"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
d0aea4ebf1e1eb75a844c89ac5e855af0f3415d0 | 16,167 | ipynb | Jupyter Notebook | euler's.ipynb | boopathiviky/Eulers-Project | 5fdbf691ff2d150c812266535e87cee18bdd509c | [
"MIT"
] | null | null | null | euler's.ipynb | boopathiviky/Eulers-Project | 5fdbf691ff2d150c812266535e87cee18bdd509c | [
"MIT"
] | null | null | null | euler's.ipynb | boopathiviky/Eulers-Project | 5fdbf691ff2d150c812266535e87cee18bdd509c | [
"MIT"
] | null | null | null | 26.075806 | 825 | 0.420734 | [
[
[
"<a href=\"https://colab.research.google.com/github/boopathiviky/Eulers-Project/blob/repo/euler's.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"#1.multiples of 3 and 5",
"_____no_output_____"
]
],
[
[
"sum1=0\nx=int(input())\nfor i in range(1,x):\n if(i%3==0 or i%5==0):\n sum1=sum1+i\nprint(sum1)",
"1000\n233168\n"
]
],
[
[
"#2.even fib numbers",
"_____no_output_____"
]
],
[
[
"a=0\nb=1\nc=0\nsum2=0\nfor i in range(0,10):\n c=a+b\n a=b\n b=c\n print(c)\n if(c%2==0):\n sum2=sum2+c\nprint('sum',sum2)",
"1\n2\n3\n5\n8\n13\n21\n34\n55\n89\nsum 44\n"
]
],
[
[
"#3.prime fact of ",
"_____no_output_____"
]
],
[
[
"def isprime(n):\n pr=1\n for i in range(2,int(n/2)):\n if(n%i==0):\n pr=0\n break\n if(pr==1):\n print(n)",
"_____no_output_____"
],
[
"x=int(input())\nfor i in range(2,x):\n if(x%i==0):\n isprime(i)",
"15\n3\n5\n"
]
],
[
[
"#4.Largest palindrome product",
"_____no_output_____"
]
],
[
[
"li=[]\ndef ispalindrome(c):\n if(str(c) == str(c)[::-1]):\n li.append(c)\n #print(list)\n li.sort()\n\nfor i in range(100,1000):\n for k in range(i,1000):\n a=i*k\n ispalindrome(a)\nprint(\"Largest palindrome is:\", li[-1]) ",
"Largest palindrome is: 906609\n"
]
],
[
[
"#5.Smallest multiple",
"_____no_output_____"
]
],
[
[
"n=1\n \nwhile (n>=1):\n n=n+1\n c=1\n for i in range(1,11):\n if (n%i==0):\n c=c+1\n if (c>10):\n print(n)\n break\n",
"2520\n"
]
],
[
[
"#6.Sum square difference",
"_____no_output_____"
]
],
[
[
"sq1=0\nsq=0\n# i insiate start,stop 10 1,9 1,11\nfor i in range(1,100+1):\n sq=i**2\n sq1=sq1+sq\nsqr=0\nfor j in range(1,100+1):\n sqr=sqr+j\ns1=sqr**2\nfinal=s1-sq1\nprint(sq1)\nprint(s1)\nprint(final)",
"338350\n25502500\n25164150\n"
],
[
"# sq1=0\n# for i in range(1,10+1):\n# sq=i**2\n# sq1=sq1+sq\n# print(sq)\n# print('\\t',sq1)",
"_____no_output_____"
]
],
[
[
"#7.10001st prime",
"_____no_output_____"
]
],
[
[
"def isprime(n):\n pr=1\n for i in range(2,int(n/2)):\n if(n%i==0):\n pr=0\n break\n if(pr==1):\n return 1\nc=0\nfor i in range(3,1000000):\n if (isprime(i)==1):\n c=c+1\n if (c>=10001):\n print (i)\n break\n\n",
"104743\n"
]
],
[
[
"#8.Largest product in a series",
"_____no_output_____"
]
],
[
[
"n='731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511\\\n125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749\\\n303589072962904915604407723907138105158593079608667017242712188399879790879227492190169972088809377665727333001053367881220235421809751254540594752243\\\n525849077116705560136048395864467063244157221553975369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474\\\n821663704844031998900088952434506585412275886668811642717147992444292823086346567481391912316282458617866458359124566529476545682848912883142\\\n60769004224219022671055626321111109370544217506941658960408\\\n0719840385096245544436298123098787992724428490918884580156166097919133875499200524063689912560717606\\\n0588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'\nlst=[]\nh=1\nlst=str(n)\np=13\nfor i in range(0,1000):\n temp=lst[i:i+p]\n sum1=1\n for j in range(len(temp)):\n v=int(temp[j])\n sum1=sum1*v\n if h<sum1 :\n h=sum1\nprint(h)\n\n ",
"23514624000\n"
]
],
[
[
"#9.Special Pythagorean triplet",
"_____no_output_____"
]
],
[
[
"for i in range(500):\n for j in range(500):\n for k in range(500):\n if i+j+k == 1000:\n if i<j<k:\n if i**2+j**2==k**2:\n print (i,j,k)\n",
"200 375 425\n"
]
],
[
[
"#10.Summation of primes",
"_____no_output_____"
]
],
[
[
"num1=[]\npr=0\nfor num in range(0,11):\n if num>=1:\n for i in range(2,num):\n if(num%i==0):\n pr=0\n break\n else:\n pr=1\n if(pr==1):\n num1.append(num)\nprint(sum(num1))",
"_____no_output_____"
]
],
[
[
"#11.Largest product in a grid\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nlst1=[]\nlst2=[]\nlst3=[]\nlst4=[]\ndt=np.genfromtxt('data.txt', delimiter=' ')\nrows, cols=dt.shape\nprint(dt[0])\nsu=1\nfor i in range(0,rows):\n for j in range(0,cols):\n # forward\n if(j+4<=cols):\n su=dt[i,j]*dt[i,j+1]*dt[i,j+2]*dt[i,j+3]\n lst1.append(su)\n su=1\n #downward\n if(i+4<=rows):\n su=dt[i,j]*dt[i+1,j]*dt[i+2,j]*dt[i+3,j]\n lst2.append(su)\n su=1\n # diagonal l-r\n if(i+4<=rows and j+4<=cols):\n su=dt[i,j]*dt[i+1,j+1]*dt[i+2,j+2]*dt[i+3,j+3]\n lst3.append(su)\n su=1\n # diagonal r-l\n if(j>2 and i<cols-3):\n su=dt[i,j]*dt[i+1,j-1]*dt[i+2,j-2]*dt[i+3,j-3]\n lst4.append(su)\n su=1\nprint(max(lst1),max(lst2),max(lst3),max(lst4)) ",
"[ 8. 2. 22. 97. 38. 15. 0. 40. 0. 75. 4. 5. 7. 78. 52. 12. 50. 77.\n 91. 8.]\n48477312.0 51267216.0 40304286.0 70600674.0\n"
],
[
"\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
d0aeaa7ed21f9ccb0f9f82e0d6079983994298a6 | 10,541 | ipynb | Jupyter Notebook | week07/01_numpy.ipynb | neolaw84/data_science_using_python_labs | 15bd2445577c5e254831f2acd97ea4b93a224229 | [
"Apache-2.0"
] | 1 | 2022-03-20T12:49:43.000Z | 2022-03-20T12:49:43.000Z | week07/01_numpy.ipynb | neolaw84/data_science_using_python_labs | 15bd2445577c5e254831f2acd97ea4b93a224229 | [
"Apache-2.0"
] | null | null | null | week07/01_numpy.ipynb | neolaw84/data_science_using_python_labs | 15bd2445577c5e254831f2acd97ea4b93a224229 | [
"Apache-2.0"
] | null | null | null | 23.634529 | 223 | 0.432597 | [
[
[
"# `numpy`\n\nမင်္ဂလာပါ၊ welcome to the week 07 of Data Science Using Python. \n\nWe will go into details of `numpy` this week (as well as do some linear algebra stuffs).\n\n## `numpy` အကြောင်း သိပြီးသမျှ\n\n* `numpy` ဟာ array library ဖြစ်တယ်၊\n * efficient ဖြစ်တယ်၊\n * vector နဲ့ matrix တွေကို လွယ်လွယ်ကူကူ ကိုင်တွယ်နိုင်တယ်၊ \n * tensor တွေကို ရောပဲ ??? ",
"_____no_output_____"
]
],
[
[
"# tensor ဆိုတာ 2 ထက်များတဲ့ dimension ရှိတဲ့ array ကြီးတွေကို သင်္ချာဆန်ဆန် ခေါ်တာပါပဲ။ \n\nimport numpy as np\n\ntensor_3d = np.array(\n [\n [\n [1, 2],\n [3, 4]\n ], \n [\n [10, 20],\n [30, 40]\n ], \n ]\n)\nprint (tensor_3d.ndim, tensor_3d.shape, tensor_3d.size)",
"_____no_output_____"
]
],
[
[
"* **array indexing** `numpy` array တွေကို index လုပ်ဖို့ square bracket '[]' ထဲမှာ comma ',' ခံပြီး ရေးရတယ်။ dimension အရေအတွက် ရှိတဲ့အတိုင်း အကုန်ရေးရတယ်။ ချန်ထားရင် ကျန်တဲ့ dimensional တွေအတွက် အကုန်လို့ ယူဆတယ်။ \n* **slicing/dicing** `numpy` array တွေရဲ့ view တခုကို dimension အတွက် index ဂဏန်း နေရာမှာ start:end:step syntax သုံးပြီး slice လုပ်နိုင်တယ်။",
"_____no_output_____"
]
],
[
[
"from utils import my_data, np_data\nprint (my_data)\nprint ('---')\nprint (np_data)",
"_____no_output_____"
],
[
"# so, how to get the id, length, width view and height view ?\n",
"_____no_output_____"
]
],
[
[
"## `numpy` array creation\n\n`numpy` မှာ array ဖန်တီးဖို့ short-cut function တွေရှိတယ်။",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\na = np.zeros((2,2)) # Create an array of all zeros\nprint(a) # Prints \"[[ 0. 0.]\n # [ 0. 0.]]\"\n\nb = np.ones((1,2)) # Create an array of all ones\nprint(b) # Prints \"[[ 1. 1.]]\"\n\nc = np.full((2,2), 7) # Create a constant array\nprint(c) # Prints \"[[ 7. 7.]\n # [ 7. 7.]]\"\n\nd = np.eye(2) # Create a 2x2 identity matrix\nprint(d) # Prints \"[[ 1. 0.]\n # [ 0. 1.]]\"\n\ne = np.random.random((2,2)) # Create an array filled with random values\nprint(e) # Might print \"[[ 0.91940167 0.08143941]\n # [ 0.68744134 0.87236687]]\"\n \nr = np.arange(35)\nprint (r)",
"[[0. 0.]\n [0. 0.]]\n[[1. 1.]]\n[[7 7]\n [7 7]]\n[[1. 0.]\n [0. 1.]]\n[[0.12793776 0.2217626 ]\n [0.03490039 0.66624149]]\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\n 24 25 26 27 28 29 30 31 32 33 34]\n"
]
],
[
[
"အသုံးများတာကတော့ ... \n\n* `arange`\n* `zeros`\n* `ones`\n* `full`\n* `eye` နဲ့\n* `random.random` တို့ ဖြစ်တယ်။\n\nအပြည့်အစုံကို [Numpy official documentation](https://numpy.org/doc/stable/reference/routines.array-creation.html) မှာ ကြည့်နိုင်တယ်။",
"_____no_output_____"
],
[
"## `numpy` array manipulation\n\nအသုံးအများဆုံး array manipulation ကတော့ ... \n\n* `copy`\n* `reshape`\n* `vstack`\n* `hstack` နဲ့\n* `block` တို့ပဲ ဖြစ်တယ်။",
"_____no_output_____"
]
],
[
[
"v1 = np_data[::2]\nv2 = np_data[1::2,0]\nprint (v1.shape, v2.shape)\nprint (v1)\nprint (v2)",
"_____no_output_____"
],
[
"v2 =v2.reshape(-1,1) # here, -1 means \"ကိုယ့်ဟာကိုယ် ကြည့်ဖြည့်လိုက်\"\nprint (v2.shape)\nnp.hstack((v1, v2))",
"_____no_output_____"
],
[
"A = np.zeros((3,3)) # သတိထားစရာက tuple တွေကို parameter pass တာပဲ\nprint (A)\nprint (\"---\")\nB = np.eye(2, 2)\nprint (B)\nprint (\"---\")\nA_sub = A[1:3, 1:3]\nA_sub += B\nprint (A)",
"_____no_output_____"
],
[
"A = np.zeros((3,3))\nprint (A)\nprint (\"---\")\nB = np.eye(2, 2)\nprint (B)\nprint (\"---\")\nA_sub = A[1:3, 1:3].copy() # this copy make sure A_sub is a copy (not a view)\nA_sub += B\nprint (A)",
"_____no_output_____"
],
[
"A = np.ones(2, 2) # this will give you an error. check it out\nB = np.zeros((2, 2))\nC = np.block([[A, B, B], [B, A, B]])\nprint (C)",
"_____no_output_____"
],
[
"D = np.hstack((A, B))\nE = np.vstack((A, B))\nprint (D)\nprint (E)",
"_____no_output_____"
]
],
[
[
"နောက်ထပ် အသုံးများတဲ့ property တခုကတော့ `T` ပဲ။ transpose လုပ်တာ။",
"_____no_output_____"
]
],
[
[
"print (D.T)\nprint (E.T)",
"_____no_output_____"
]
],
[
[
"## vector/matrix calculations\n\n`dot` function ဟာ matrix/vector တွေကို လွယ်ကူစွာ မြှောက်နိုင်စေတယ်။",
"_____no_output_____"
]
],
[
[
"x = np.array(\n [\n [1,2],\n [3,4]\n ])\ny = np.array(\n [\n [5,6],\n [7,8]\n ])\n\nv = np.array([9,10])\nw = np.array([11, 12])\n\n# Inner product of vectors; both produce 219\nprint(v.dot(w))\nprint(np.dot(v, w))\n\n# Matrix / vector product; both produce the rank 1 array [29 67]\nprint(x.dot(v))\nprint(np.dot(x, v))\n\n# Matrix / matrix product; both produce the rank 2 array\n# [[19 22]\n# [43 50]]\nprint(x.dot(y))\nprint(np.dot(x, y))",
"219\n219\n[29 67]\n[29 67]\n[[19 22]\n [43 50]]\n[[19 22]\n [43 50]]\n"
]
],
[
[
"## Special Array indexing\n\n`numpy` မှာ array တခုရဲ့ dimension တခုစီအတွက် list တခုနှုန်းနဲ့ (အဲဒီ list ထဲမှာ ကိုယ်လိုချင်တဲ့ element အရေအတွက်အတိုင်း ပါရ) index လုပ်တဲ့ special indexing method လဲ ရှိတယ်။",
"_____no_output_____"
]
],
[
[
"r = np.arange(35).reshape(5, 7)\nprint (r)\nindex_x0 = [3, 4, 4]\nindex_x1 = [6, 2, 3]\nprint (r[index_x0, index_x1])",
"[[ 0 1 2 3 4 5 6]\n [ 7 8 9 10 11 12 13]\n [14 15 16 17 18 19 20]\n [21 22 23 24 25 26 27]\n [28 29 30 31 32 33 34]]\n[27 30 31]\n"
]
],
[
[
"### `numpy` special boolean ability and boolean indexing\n\n",
"_____no_output_____"
]
],
[
[
"r_index = r % 2 == 0\nprint (r_index)",
"[[ True False True False True False True]\n [False True False True False True False]\n [ True False True False True False True]\n [False True False True False True False]\n [ True False True False True False True]]\n"
]
],
[
[
"အဲဒီလို boolean array (size တူရမယ်) ကို အသုံးပြုပြီး မူလ array ကနေ data retrieval လုပ်နိုင်တယ်။",
"_____no_output_____"
]
],
[
[
"r_selected = r[r_index]\nprint (r_selected)",
"[ 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34]\n"
]
]
] | [
"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",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
d0aebbef2b132bc130c66fa9eb7f7568a082a92a | 66,667 | ipynb | Jupyter Notebook | Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb | alivara/deep_learning | 190a8f6806c588f6207ed668e11a5c255df37f76 | [
"MIT"
] | null | null | null | Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb | alivara/deep_learning | 190a8f6806c588f6207ed668e11a5c255df37f76 | [
"MIT"
] | null | null | null | Course_By_Andrew_Ng/Building_your_Deep_Neural_Network_Step_by_Step.ipynb | alivara/deep_learning | 190a8f6806c588f6207ed668e11a5c255df37f76 | [
"MIT"
] | null | null | null | 36.509858 | 490 | 0.529257 | [
[
[
"# Building your Deep Neural Network: Step by Step\n\nWelcome to your week 4 assignment (part 1 of 2)! Previously you trained a 2-layer Neural Network with a single hidden layer. This week, you will build a deep neural network with as many layers as you want!\n\n- In this notebook, you'll implement all the functions required to build a deep neural network.\n- For the next assignment, you'll use these functions to build a deep neural network for image classification.\n\n**By the end of this assignment, you'll be able to:**\n\n- Use non-linear units like ReLU to improve your model\n- Build a deeper neural network (with more than 1 hidden layer)\n- Implement an easy-to-use neural network class\n\n**Notation**:\n- Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer. \n - Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters.\n- Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example. \n - Example: $x^{(i)}$ is the $i^{th}$ training example.\n- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.\n - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations).\n\nLet's get started!",
"_____no_output_____"
],
[
"## Table of Contents\n- [1 - Packages](#1)\n- [2 - Outline](#2)\n- [3 - Initialization](#3)\n - [3.1 - 2-layer Neural Network](#3-1)\n - [Exercise 1 - initialize_parameters](#ex-1)\n - [3.2 - L-layer Neural Network](#3-2)\n - [Exercise 2 - initialize_parameters_deep](#ex-2)\n- [4 - Forward Propagation Module](#4)\n - [4.1 - Linear Forward](#4-1)\n - [Exercise 3 - linear_forward](#ex-3)\n - [4.2 - Linear-Activation Forward](#4-2)\n - [Exercise 4 - linear_activation_forward](#ex-4)\n - [4.3 - L-Layer Model](#4-3)\n - [Exercise 5 - L_model_forward](#ex-5)\n- [5 - Cost Function](#5)\n - [Exercise 6 - compute_cost](#ex-6)\n- [6 - Backward Propagation Module](#6)\n - [6.1 - Linear Backward](#6-1)\n - [Exercise 7 - linear_backward](#ex-7)\n - [6.2 - Linear-Activation Backward](#6-2)\n - [Exercise 8 - linear_activation_backward](#ex-8)\n - [6.3 - L-Model Backward](#6-3)\n - [Exercise 9 - L_model_backward](#ex-9)\n - [6.4 - Update Parameters](#6-4)\n - [Exercise 10 - update_parameters](#ex-10)",
"_____no_output_____"
],
[
"<a name='1'></a>\n## 1 - Packages\n\nFirst, import all the packages you'll need during this assignment. \n\n- [numpy](www.numpy.org) is the main package for scientific computing with Python.\n- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.\n- dnn_utils provides some necessary functions for this notebook.\n- testCases provides some test cases to assess the correctness of your functions\n- np.random.seed(1) is used to keep all the random function calls consistent. It helps grade your work. Please don't change the seed! ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nfrom testCases import *\nfrom dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward\nfrom public_tests import *\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n%load_ext autoreload\n%autoreload 2\n\nnp.random.seed(1)",
"_____no_output_____"
]
],
[
[
"<a name='2'></a>\n## 2 - Outline\n\nTo build your neural network, you'll be implementing several \"helper functions.\" These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. \n\nEach small helper function will have detailed instructions to walk you through the necessary steps. Here's an outline of the steps in this assignment:\n\n- Initialize the parameters for a two-layer network and for an $L$-layer neural network\n- Implement the forward propagation module (shown in purple in the figure below)\n - Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$).\n - The ACTIVATION function is provided for you (relu/sigmoid)\n - Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function.\n - Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.\n- Compute the loss\n- Implement the backward propagation module (denoted in red in the figure below)\n - Complete the LINEAR part of a layer's backward propagation step\n - The gradient of the ACTIVATE function is provided for you(relu_backward/sigmoid_backward) \n - Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function\n - Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function\n- Finally, update the parameters\n\n<img src=\"images/final outline.png\" style=\"width:800px;height:500px;\">\n<caption><center><b>Figure 1</b></center></caption><br>\n\n\n**Note**:\n\nFor every forward function, there is a corresponding backward function. This is why at every step of your forward module you will be storing some values in a cache. These cached values are useful for computing gradients. \n\nIn the backpropagation module, you can then use the cache to calculate the gradients. Don't worry, this assignment will show you exactly how to carry out each of these steps! ",
"_____no_output_____"
],
[
"<a name='3'></a>\n## 3 - Initialization\n\nYou will write two helper functions to initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one generalizes this initialization process to $L$ layers.\n\n<a name='3-1'></a>\n### 3.1 - 2-layer Neural Network\n\n<a name='ex-1'></a>\n### Exercise 1 - initialize_parameters\n\nCreate and initialize the parameters of the 2-layer neural network.\n\n**Instructions**:\n\n- The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*. \n- Use this random initialization for the weight matrices: `np.random.randn(shape)*0.01` with the correct shape\n- Use zero initialization for the biases: `np.zeros(shape)`",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters\n\ndef initialize_parameters(n_x, n_h, n_y):\n \"\"\"\n Argument:\n n_x -- size of the input layer\n n_h -- size of the hidden layer\n n_y -- size of the output layer\n \n Returns:\n parameters -- python dictionary containing your parameters:\n W1 -- weight matrix of shape (n_h, n_x)\n b1 -- bias vector of shape (n_h, 1)\n W2 -- weight matrix of shape (n_y, n_h)\n b2 -- bias vector of shape (n_y, 1)\n \"\"\"\n \n np.random.seed(1)\n \n #(≈ 4 lines of code)\n # W1 = ...\n # b1 = ...\n # W2 = ...\n # b2 = ...\n # YOUR CODE STARTS HERE\n W1 = np.random.randn(n_h,n_x)*0.01\n b1 = np.zeros([n_h,1])\n W2 = np.random.randn(n_y,n_h)*0.01\n b2 = np.zeros([n_y,1])\n # YOUR CODE ENDS HERE\n \n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n \n return parameters ",
"_____no_output_____"
],
[
"parameters = initialize_parameters(3,2,1)\n\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))\n\ninitialize_parameters_test(initialize_parameters)",
"W1 = [[ 0.01624345 -0.00611756 -0.00528172]\n [-0.01072969 0.00865408 -0.02301539]]\nb1 = [[0.]\n [0.]]\nW2 = [[ 0.01744812 -0.00761207]]\nb2 = [[0.]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"***Expected output***\n```\nW1 = [[ 0.01624345 -0.00611756 -0.00528172]\n [-0.01072969 0.00865408 -0.02301539]]\nb1 = [[0.]\n [0.]]\nW2 = [[ 0.01744812 -0.00761207]]\nb2 = [[0.]]\n```",
"_____no_output_____"
],
[
"<a name='3-2'></a>\n### 3.2 - L-layer Neural Network\n\nThe initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the `initialize_parameters_deep` function, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. For example, if the size of your input $X$ is $(12288, 209)$ (with $m=209$ examples) then:\n\n<table style=\"width:100%\">\n <tr>\n <td> </td> \n <td> <b>Shape of W</b> </td> \n <td> <b>Shape of b</b> </td> \n <td> <b>Activation</b> </td>\n <td> <b>Shape of Activation</b> </td> \n <tr>\n <tr>\n <td> <b>Layer 1</b> </td> \n <td> $(n^{[1]},12288)$ </td> \n <td> $(n^{[1]},1)$ </td> \n <td> $Z^{[1]} = W^{[1]} X + b^{[1]} $ </td> \n <td> $(n^{[1]},209)$ </td> \n <tr>\n <tr>\n <td> <b>Layer 2</b> </td> \n <td> $(n^{[2]}, n^{[1]})$ </td> \n <td> $(n^{[2]},1)$ </td> \n <td>$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ </td> \n <td> $(n^{[2]}, 209)$ </td> \n <tr>\n <tr>\n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$ </td> \n <td> $\\vdots$</td> \n <td> $\\vdots$ </td> \n <tr> \n <tr>\n <td> <b>Layer L-1</b> </td> \n <td> $(n^{[L-1]}, n^{[L-2]})$ </td> \n <td> $(n^{[L-1]}, 1)$ </td> \n <td>$Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ </td> \n <td> $(n^{[L-1]}, 209)$ </td> \n <tr>\n <tr>\n <td> <b>Layer L</b> </td> \n <td> $(n^{[L]}, n^{[L-1]})$ </td> \n <td> $(n^{[L]}, 1)$ </td>\n <td> $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$</td>\n <td> $(n^{[L]}, 209)$ </td> \n <tr>\n</table>\n\nRemember that when you compute $W X + b$ in python, it carries out broadcasting. For example, if: \n\n$$ W = \\begin{bmatrix}\n w_{00} & w_{01} & w_{02} \\\\\n w_{10} & w_{11} & w_{12} \\\\\n w_{20} & w_{21} & w_{22} \n\\end{bmatrix}\\;\\;\\; X = \\begin{bmatrix}\n x_{00} & x_{01} & x_{02} \\\\\n x_{10} & x_{11} & x_{12} \\\\\n x_{20} & x_{21} & x_{22} \n\\end{bmatrix} \\;\\;\\; b =\\begin{bmatrix}\n b_0 \\\\\n b_1 \\\\\n b_2\n\\end{bmatrix}\\tag{2}$$\n\nThen $WX + b$ will be:\n\n$$ WX + b = \\begin{bmatrix}\n (w_{00}x_{00} + w_{01}x_{10} + w_{02}x_{20}) + b_0 & (w_{00}x_{01} + w_{01}x_{11} + w_{02}x_{21}) + b_0 & \\cdots \\\\\n (w_{10}x_{00} + w_{11}x_{10} + w_{12}x_{20}) + b_1 & (w_{10}x_{01} + w_{11}x_{11} + w_{12}x_{21}) + b_1 & \\cdots \\\\\n (w_{20}x_{00} + w_{21}x_{10} + w_{22}x_{20}) + b_2 & (w_{20}x_{01} + w_{21}x_{11} + w_{22}x_{21}) + b_2 & \\cdots\n\\end{bmatrix}\\tag{3} $$\n",
"_____no_output_____"
],
[
"<a name='ex-2'></a>\n### Exercise 2 - initialize_parameters_deep\n\nImplement initialization for an L-layer Neural Network. \n\n**Instructions**:\n- The model's structure is *[LINEAR -> RELU] $ \\times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.\n- Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`.\n- Use zeros initialization for the biases. Use `np.zeros(shape)`.\n- You'll store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for last week's Planar Data classification model would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers! \n- Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).\n```python\n if L == 1:\n parameters[\"W\" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01\n parameters[\"b\" + str(L)] = np.zeros((layer_dims[1], 1))\n```",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_parameters_deep\n\ndef initialize_parameters_deep(layer_dims):\n \"\"\"\n Arguments:\n layer_dims -- python array (list) containing the dimensions of each layer in our network\n \n Returns:\n parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])\n bl -- bias vector of shape (layer_dims[l], 1)\n \"\"\"\n \n np.random.seed(3)\n parameters = {}\n l = len(layer_dims) # number of layers in the network\n\n for l in range(1, l):\n #(≈ 2 lines of code)\n # parameters['W' + str(l)] = ...\n # parameters['b' + str(l)] = ...\n # YOUR CODE STARTS HERE\n parameters[\"W\" + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1])* 0.01\n parameters[\"b\" + str(l)] = np.zeros((layer_dims[l], 1))\n\n # YOUR CODE ENDS HERE\n \n assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l - 1]))\n assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))\n\n \n return parameters",
"_____no_output_____"
],
[
"parameters = initialize_parameters_deep([5,4,3])\n\nprint(\"W1 = \" + str(parameters[\"W1\"]))\nprint(\"b1 = \" + str(parameters[\"b1\"]))\nprint(\"W2 = \" + str(parameters[\"W2\"]))\nprint(\"b2 = \" + str(parameters[\"b2\"]))\n\ninitialize_parameters_deep_test(initialize_parameters_deep)",
"W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]\nb1 = [[0.]\n [0.]\n [0.]\n [0.]]\nW2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716]\n [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n [-0.00768836 -0.00230031 0.00745056 0.01976111]]\nb2 = [[0.]\n [0.]\n [0.]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"***Expected output***\n```\nW1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]\nb1 = [[0.]\n [0.]\n [0.]\n [0.]]\nW2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716]\n [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n [-0.00768836 -0.00230031 0.00745056 0.01976111]]\nb2 = [[0.]\n [0.]\n [0.]]\n```",
"_____no_output_____"
],
[
"<a name='4'></a>\n## 4 - Forward Propagation Module\n\n<a name='4-1'></a>\n### 4.1 - Linear Forward \n\nNow that you have initialized your parameters, you can do the forward propagation module. Start by implementing some basic functions that you can use again later when implementing the model. Now, you'll complete three functions in this order:\n\n- LINEAR\n- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid. \n- [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID (whole model)\n\nThe linear forward module (vectorized over all the examples) computes the following equations:\n\n$$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\\tag{4}$$\n\nwhere $A^{[0]} = X$. \n\n<a name='ex-3'></a>\n### Exercise 3 - linear_forward \n\nBuild the linear part of forward propagation.\n\n**Reminder**:\nThe mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find `np.dot()` useful. If your dimensions don't match, printing `W.shape` may help.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_forward\n\ndef linear_forward(A, W, b):\n \"\"\"\n Implement the linear part of a layer's forward propagation.\n\n Arguments:\n A -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n\n Returns:\n Z -- the input of the activation function, also called pre-activation parameter \n cache -- a python tuple containing \"A\", \"W\" and \"b\" ; stored for computing the backward pass efficiently\n \"\"\"\n \n #(≈ 1 line of code)\n # Z = ...\n # YOUR CODE STARTS HERE\n Z = np.dot(W,A)+ b\n \n # YOUR CODE ENDS HERE\n cache = (A, W, b)\n \n return Z, cache",
"_____no_output_____"
],
[
"t_A, t_W, t_b = linear_forward_test_case()\nt_Z, t_linear_cache = linear_forward(t_A, t_W, t_b)\nprint(\"Z = \" + str(t_Z))\n\nlinear_forward_test(linear_forward)",
"Z = [[ 3.26295337 -1.23429987]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"***Expected output***\n```\nZ = [[ 3.26295337 -1.23429987]]\n```",
"_____no_output_____"
],
[
"<a name='4-2'></a>\n### 4.2 - Linear-Activation Forward\n\nIn this notebook, you will use two activation functions:\n\n- **Sigmoid**: $\\sigma(Z) = \\sigma(W A + b) = \\frac{1}{ 1 + e^{-(W A + b)}}$. You've been provided with the `sigmoid` function which returns **two** items: the activation value \"`a`\" and a \"`cache`\" that contains \"`Z`\" (it's what we will feed in to the corresponding backward function). To use it you could just call: \n``` python\nA, activation_cache = sigmoid(Z)\n```\n\n- **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. You've been provided with the `relu` function. This function returns **two** items: the activation value \"`A`\" and a \"`cache`\" that contains \"`Z`\" (it's what you'll feed in to the corresponding backward function). To use it you could just call:\n``` python\nA, activation_cache = relu(Z)\n```",
"_____no_output_____"
],
[
"For added convenience, you're going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you'll implement a function that does the LINEAR forward step, followed by an ACTIVATION forward step.\n\n<a name='ex-4'></a>\n### Exercise 4 - linear_activation_forward\n\nImplement the forward propagation of the *LINEAR->ACTIVATION* layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation \"g\" can be sigmoid() or relu(). Use `linear_forward()` and the correct activation function.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_activation_forward\n\ndef linear_activation_forward(A_prev, W, b, activation):\n \"\"\"\n Implement the forward propagation for the LINEAR->ACTIVATION layer\n\n Arguments:\n A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)\n W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n b -- bias vector, numpy array of shape (size of the current layer, 1)\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n\n Returns:\n A -- the output of the activation function, also called the post-activation value \n cache -- a python tuple containing \"linear_cache\" and \"activation_cache\";\n stored for computing the backward pass efficiently\n \"\"\"\n \n if activation == \"sigmoid\":\n #(≈ 2 lines of code)\n # Z, linear_cache = ...\n # A, activation_cache = ...\n # YOUR CODE STARTS HERE\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = sigmoid(Z)\n # YOUR CODE ENDS HERE\n \n elif activation == \"relu\":\n #(≈ 2 lines of code)\n # Z, linear_cache = ...\n # A, activation_cache = ...\n # YOUR CODE STARTS HERE\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = relu(Z)\n \n # YOUR CODE ENDS HERE\n cache = (linear_cache, activation_cache)\n\n return A, cache",
"_____no_output_____"
],
[
"t_A_prev, t_W, t_b = linear_activation_forward_test_case()\n\nt_A, t_linear_activation_cache = linear_activation_forward(t_A_prev, t_W, t_b, activation = \"sigmoid\")\nprint(\"With sigmoid: A = \" + str(t_A))\n\nt_A, t_linear_activation_cache = linear_activation_forward(t_A_prev, t_W, t_b, activation = \"relu\")\nprint(\"With ReLU: A = \" + str(t_A))\n\nlinear_activation_forward_test(linear_activation_forward)",
"With sigmoid: A = [[0.96890023 0.11013289]]\nWith ReLU: A = [[3.43896131 0. ]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"***Expected output***\n```\nWith sigmoid: A = [[0.96890023 0.11013289]]\nWith ReLU: A = [[3.43896131 0. ]]\n```",
"_____no_output_____"
],
[
"**Note**: In deep learning, the \"[LINEAR->ACTIVATION]\" computation is counted as a single layer in the neural network, not two layers. ",
"_____no_output_____"
],
[
"<a name='4-3'></a>\n### 4.3 - L-Layer Model \n\nFor even *more* convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID.\n\n<img src=\"images/model_architecture_kiank.png\" style=\"width:600px;height:300px;\">\n<caption><center> <b>Figure 2</b> : *[LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model</center></caption><br>\n\n<a name='ex-5'></a>\n### Exercise 5 - L_model_forward\n\nImplement the forward propagation of the above model.\n\n**Instructions**: In the code below, the variable `AL` will denote $A^{[L]} = \\sigma(Z^{[L]}) = \\sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\\hat{Y}$.) \n\n**Hints**:\n- Use the functions you've previously written \n- Use a for loop to replicate [LINEAR->RELU] (L-1) times\n- Don't forget to keep track of the caches in the \"caches\" list. To add a new value `c` to a `list`, you can use `list.append(c)`.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: L_model_forward\n\ndef L_model_forward(X, parameters):\n \"\"\"\n Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation\n \n Arguments:\n X -- data, numpy array of shape (input size, number of examples)\n parameters -- output of initialize_parameters_deep()\n \n Returns:\n AL -- activation value from the output (last) layer\n caches -- list of caches containing:\n every cache of linear_activation_forward() (there are L of them, indexed from 0 to L-1)\n \"\"\"\n\n caches = []\n A = X\n L = len(parameters) // 2 # number of layers in the neural network\n # Implement [LINEAR -> RELU]*(L-1). Add \"cache\" to the \"caches\" list.\n # The for loop starts at 1 because layer 0 is the input\n for l in range(1, L):\n A_prev = A \n #(≈ 2 lines of code)\n # A, cache = ...\n # caches ...\n # YOUR CODE STARTS HERE\n A, cache = linear_activation_forward(A, parameters['W' + str(l)], parameters['b' + str(l)], \"relu\")\n caches.append(cache) \n # YOUR CODE ENDS HERE\n \n # Implement LINEAR -> SIGMOID. Add \"cache\" to the \"caches\" list.\n #(≈ 2 lines of code)\n # AL, cache = ...\n # caches ...\n # YOUR CODE STARTS HERE\n AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], \"sigmoid\")\n caches.append(cache)\n # YOUR CODE ENDS HERE\n \n return AL, caches",
"_____no_output_____"
],
[
"t_X, t_parameters = L_model_forward_test_case_2hidden()\nt_AL, t_caches = L_model_forward(t_X, t_parameters)\n\nprint(\"AL = \" + str(t_AL))\n\nL_model_forward_test(L_model_forward)",
"AL = [[0.03921668 0.70498921 0.19734387 0.04728177]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"***Expected output***\n```\nAL = [[0.03921668 0.70498921 0.19734387 0.04728177]]\n```",
"_____no_output_____"
],
[
"**Awesome!** You've implemented a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in \"caches\". Using $A^{[L]}$, you can compute the cost of your predictions.",
"_____no_output_____"
],
[
"<a name='5'></a>\n## 5 - Cost Function\n\nNow you can implement forward and backward propagation! You need to compute the cost, in order to check whether your model is actually learning.\n\n<a name='ex-6'></a>\n### Exercise 6 - compute_cost\nCompute the cross-entropy cost $J$, using the following formula: $$-\\frac{1}{m} \\sum\\limits_{i = 1}^{m} (y^{(i)}\\log\\left(a^{[L] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[L](i)}\\right)) \\tag{7}$$\n",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: compute_cost\n\ndef compute_cost(AL, Y):\n \"\"\"\n Implement the cost function defined by equation (7).\n\n Arguments:\n AL -- probability vector corresponding to your label predictions, shape (1, number of examples)\n Y -- true \"label\" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)\n\n Returns:\n cost -- cross-entropy cost\n \"\"\"\n \n m = Y.shape[1]\n\n # Compute loss from aL and y.\n # (≈ 1 lines of code)\n # cost = ...\n # YOUR CODE STARTS HERE\n cost = (-1/m)*(np.dot(Y,np.log(AL).T)+np.dot(1-Y,np.log(1-AL).T))\n \n # YOUR CODE ENDS HERE\n \n cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).\n\n \n return cost",
"_____no_output_____"
],
[
"t_Y, t_AL = compute_cost_test_case()\nt_cost = compute_cost(t_AL, t_Y)\n\nprint(\"Cost: \" + str(t_cost))\n\ncompute_cost_test(compute_cost)",
"Cost: 0.2797765635793422\n\u001b[92m All tests passed.\n"
]
],
[
[
"**Expected Output**:\n\n<table>\n <tr>\n <td><b>cost</b> </td>\n <td> 0.2797765635793422</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"<a name='6'></a>\n## 6 - Backward Propagation Module\n\nJust as you did for the forward propagation, you'll implement helper functions for backpropagation. Remember that backpropagation is used to calculate the gradient of the loss function with respect to the parameters. \n\n**Reminder**: \n<img src=\"images/backprop_kiank.png\" style=\"width:650px;height:250px;\">\n<caption><center><font color='purple'><b>Figure 3</b>: Forward and Backward propagation for LINEAR->RELU->LINEAR->SIGMOID <br> <i>The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.</font></center></caption>\n\n\n<!-- \nFor those of you who are experts in calculus (which you don't need to be to do this assignment!), the chain rule of calculus can be used to derive the derivative of the loss $\\mathcal{L}$ with respect to $z^{[1]}$ in a 2-layer network as follows:\n\n$$\\frac{d \\mathcal{L}(a^{[2]},y)}{{dz^{[1]}}} = \\frac{d\\mathcal{L}(a^{[2]},y)}{{da^{[2]}}}\\frac{{da^{[2]}}}{{dz^{[2]}}}\\frac{{dz^{[2]}}}{{da^{[1]}}}\\frac{{da^{[1]}}}{{dz^{[1]}}} \\tag{8} $$\n\nIn order to calculate the gradient $dW^{[1]} = \\frac{\\partial L}{\\partial W^{[1]}}$, use the previous chain rule and you do $dW^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial W^{[1]}}$. During backpropagation, at each step you multiply your current gradient by the gradient corresponding to the specific layer to get the gradient you wanted.\n\nEquivalently, in order to calculate the gradient $db^{[1]} = \\frac{\\partial L}{\\partial b^{[1]}}$, you use the previous chain rule and you do $db^{[1]} = dz^{[1]} \\times \\frac{\\partial z^{[1]} }{\\partial b^{[1]}}$.\n\nThis is why we talk about **backpropagation**.\n!-->\n\nNow, similarly to forward propagation, you're going to build the backward propagation in three steps:\n1. LINEAR backward\n2. LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation\n3. [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model)",
"_____no_output_____"
],
[
"For the next exercise, you will need to remember that:\n\n- `b` is a matrix(np.ndarray) with 1 column and n rows, i.e: b = [[1.0], [2.0]] (remember that `b` is a constant)\n- np.sum performs a sum over the elements of a ndarray\n- axis=1 or axis=0 specify if the sum is carried out by rows or by columns respectively\n- keepdims specifies if the original dimensions of the matrix must be kept.\n- Look at the following example to clarify:",
"_____no_output_____"
]
],
[
[
"A = np.array([[1, 2], [3, 4]])\n\nprint('axis=1 and keepdims=True')\nprint(np.sum(A, axis=1, keepdims=True))\nprint('axis=1 and keepdims=False')\nprint(np.sum(A, axis=1, keepdims=False))\nprint('axis=0 and keepdims=True')\nprint(np.sum(A, axis=0, keepdims=True))\nprint('axis=0 and keepdims=False')\nprint(np.sum(A, axis=0, keepdims=False))",
"axis=1 and keepdims=True\n[[3]\n [7]]\naxis=1 and keepdims=False\n[3 7]\naxis=0 and keepdims=True\n[[4 6]]\naxis=0 and keepdims=False\n[4 6]\n"
]
],
[
[
"<a name='6-1'></a>\n### 6.1 - Linear Backward\n\nFor layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).\n\nSuppose you have already calculated the derivative $dZ^{[l]} = \\frac{\\partial \\mathcal{L} }{\\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$.\n\n<img src=\"images/linearback_kiank.png\" style=\"width:250px;height:300px;\">\n<caption><center><font color='purple'><b>Figure 4</b></font></center></caption>\n\nThe three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$.\n\nHere are the formulas you need:\n$$ dW^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial W^{[l]}} = \\frac{1}{m} dZ^{[l]} A^{[l-1] T} \\tag{8}$$\n$$ db^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial b^{[l]}} = \\frac{1}{m} \\sum_{i = 1}^{m} dZ^{[l](i)}\\tag{9}$$\n$$ dA^{[l-1]} = \\frac{\\partial \\mathcal{L} }{\\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \\tag{10}$$\n\n\n$A^{[l-1] T}$ is the transpose of $A^{[l-1]}$. ",
"_____no_output_____"
],
[
"<a name='ex-7'></a>\n### Exercise 7 - linear_backward \n\nUse the 3 formulas above to implement `linear_backward()`.\n\n**Hint**:\n\n- In numpy you can get the transpose of an ndarray `A` using `A.T` or `A.transpose()`",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_backward\n\ndef linear_backward(dZ, cache):\n \"\"\"\n Implement the linear portion of backward propagation for a single layer (layer l)\n\n Arguments:\n dZ -- Gradient of the cost with respect to the linear output (of current layer l)\n cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer\n\n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n A_prev, W, b = cache\n m = A_prev.shape[1]\n\n ### START CODE HERE ### (≈ 3 lines of code)\n # dW = ...\n # db = ... sum by the rows of dZ with keepdims=True\n # dA_prev = ...\n # YOUR CODE STARTS HERE\n dW = (1/m)*(np.dot(dZ,A_prev.T))\n db = (1/m)*(np.sum(dZ,axis=1,keepdims=True))\n dA_prev = np.dot(W.T,dZ)\n # YOUR CODE ENDS HERE\n \n return dA_prev, dW, db",
"_____no_output_____"
],
[
"t_dZ, t_linear_cache = linear_backward_test_case()\nt_dA_prev, t_dW, t_db = linear_backward(t_dZ, t_linear_cache)\n\nprint(\"dA_prev: \" + str(t_dA_prev))\nprint(\"dW: \" + str(t_dW))\nprint(\"db: \" + str(t_db))\n\nlinear_backward_test(linear_backward)",
"dA_prev: [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n [-0.4319552 -1.30987417 1.72354705 0.05070578]\n [-0.38981415 0.60811244 -1.25938424 1.47191593]\n [-2.52214926 2.67882552 -0.67947465 1.48119548]]\ndW: [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\ndb: [[-0.14713786]\n [-0.11313155]\n [-0.13209101]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"**Expected Output**:\n```\ndA_prev: [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n [-0.4319552 -1.30987417 1.72354705 0.05070578]\n [-0.38981415 0.60811244 -1.25938424 1.47191593]\n [-2.52214926 2.67882552 -0.67947465 1.48119548]]\ndW: [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\ndb: [[-0.14713786]\n [-0.11313155]\n [-0.13209101]]\n ```",
"_____no_output_____"
],
[
"<a name='6-2'></a>\n### 6.2 - Linear-Activation Backward\n\nNext, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**. \n\nTo help you implement `linear_activation_backward`, two backward functions have been provided:\n- **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:\n\n```python\ndZ = sigmoid_backward(dA, activation_cache)\n```\n\n- **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:\n\n```python\ndZ = relu_backward(dA, activation_cache)\n```\n\nIf $g(.)$ is the activation function, \n`sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}). \\tag{11}$$ \n\n<a name='ex-8'></a>\n### Exercise 8 - linear_activation_backward\n\nImplement the backpropagation for the *LINEAR->ACTIVATION* layer.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: linear_activation_backward\n\ndef linear_activation_backward(dA, cache, activation):\n \"\"\"\n Implement the backward propagation for the LINEAR->ACTIVATION layer.\n \n Arguments:\n dA -- post-activation gradient for current layer l \n cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n \n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n linear_cache, activation_cache = cache\n \n if activation == \"relu\":\n #(≈ 2 lines of code)\n # dZ = ...\n # dA_prev, dW, db = ...\n # YOUR CODE STARTS HERE\n dZ = relu_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n # YOUR CODE ENDS HERE\n \n elif activation == \"sigmoid\":\n #(≈ 2 lines of code)\n # dZ = ...\n # dA_prev, dW, db = ...\n # YOUR CODE STARTS HERE\n dZ = sigmoid_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n # YOUR CODE ENDS HERE\n \n return dA_prev, dW, db",
"_____no_output_____"
],
[
"t_dAL, t_linear_activation_cache = linear_activation_backward_test_case()\n\nt_dA_prev, t_dW, t_db = linear_activation_backward(t_dAL, t_linear_activation_cache, activation = \"sigmoid\")\nprint(\"With sigmoid: dA_prev = \" + str(t_dA_prev))\nprint(\"With sigmoid: dW = \" + str(t_dW))\nprint(\"With sigmoid: db = \" + str(t_db))\n\nt_dA_prev, t_dW, t_db = linear_activation_backward(t_dAL, t_linear_activation_cache, activation = \"relu\")\nprint(\"With relu: dA_prev = \" + str(t_dA_prev))\nprint(\"With relu: dW = \" + str(t_dW))\nprint(\"With relu: db = \" + str(t_db))\n\nlinear_activation_backward_test(linear_activation_backward)",
"With sigmoid: dA_prev = [[ 0.11017994 0.01105339]\n [ 0.09466817 0.00949723]\n [-0.05743092 -0.00576154]]\nWith sigmoid: dW = [[ 0.10266786 0.09778551 -0.01968084]]\nWith sigmoid: db = [[-0.05729622]]\nWith relu: dA_prev = [[ 0.44090989 0. ]\n [ 0.37883606 0. ]\n [-0.2298228 0. ]]\nWith relu: dW = [[ 0.44513824 0.37371418 -0.10478989]]\nWith relu: db = [[-0.20837892]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"**Expected output:**\n\n```\nWith sigmoid: dA_prev = [[ 0.11017994 0.01105339]\n [ 0.09466817 0.00949723]\n [-0.05743092 -0.00576154]]\nWith sigmoid: dW = [[ 0.10266786 0.09778551 -0.01968084]]\nWith sigmoid: db = [[-0.05729622]]\nWith relu: dA_prev = [[ 0.44090989 0. ]\n [ 0.37883606 0. ]\n [-0.2298228 0. ]]\nWith relu: dW = [[ 0.44513824 0.37371418 -0.10478989]]\nWith relu: db = [[-0.20837892]]\n```",
"_____no_output_____"
],
[
"<a name='6-3'></a>\n### 6.3 - L-Model Backward \n\nNow you will implement the backward function for the whole network! \n\nRecall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you'll use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you'll iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass. \n\n\n<img src=\"images/mn_backward.png\" style=\"width:450px;height:300px;\">\n<caption><center><font color='purple'><b>Figure 5</b>: Backward pass</font></center></caption>\n\n**Initializing backpropagation**:\n\nTo backpropagate through this network, you know that the output is: \n$A^{[L]} = \\sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \\frac{\\partial \\mathcal{L}}{\\partial A^{[L]}}$.\nTo do so, use this formula (derived using calculus which, again, you don't need in-depth knowledge of!):\n```python\ndAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL\n```\n\nYou can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). \n\nAfter that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula : \n\n$$grads[\"dW\" + str(l)] = dW^{[l]}\\tag{15} $$\n\nFor example, for $l=3$ this would store $dW^{[l]}$ in `grads[\"dW3\"]`.\n\n<a name='ex-9'></a>\n### Exercise 9 - L_model_backward\n\nImplement backpropagation for the *[LINEAR->RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: L_model_backward\n\ndef L_model_backward(AL, Y, caches):\n \"\"\"\n Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group\n \n Arguments:\n AL -- probability vector, output of the forward propagation (L_model_forward())\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat)\n caches -- list of caches containing:\n every cache of linear_activation_forward() with \"relu\" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)\n the cache of linear_activation_forward() with \"sigmoid\" (it's caches[L-1])\n \n Returns:\n grads -- A dictionary with the gradients\n grads[\"dA\" + str(l)] = ... \n grads[\"dW\" + str(l)] = ...\n grads[\"db\" + str(l)] = ... \n \"\"\"\n grads = {}\n L = len(caches) # the number of layers\n m = AL.shape[1]\n Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL\n \n # Initializing the backpropagation\n #(1 line of code)\n # dAL = ...\n # YOUR CODE STARTS HERE\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n \n # YOUR CODE ENDS HERE\n \n # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: \"dAL, current_cache\". Outputs: \"grads[\"dAL-1\"], grads[\"dWL\"], grads[\"dbL\"]\n #(approx. 5 lines)\n # current_cache = ...\n # dA_prev_temp, dW_temp, db_temp = ...\n # grads[\"dA\" + str(L-1)] = ...\n # grads[\"dW\" + str(L)] = ...\n # grads[\"db\" + str(L)] = ...\n # YOUR CODE STARTS HERE\n current_cache = caches[1]\n grads[\"dA\" + str(L-1)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = linear_activation_backward(dAL, current_cache,'sigmoid')\n \n # YOUR CODE ENDS HERE\n \n # Loop from l=L-2 to l=0\n for l in reversed(range(L-1)):\n # lth layer: (RELU -> LINEAR) gradients.\n # Inputs: \"grads[\"dA\" + str(l + 1)], current_cache\". Outputs: \"grads[\"dA\" + str(l)] , grads[\"dW\" + str(l + 1)] , grads[\"db\" + str(l + 1)] \n #(approx. 5 lines)\n # current_cache = ...\n # dA_prev_temp, dW_temp, db_temp = ...\n # grads[\"dA\" + str(l)] = ...\n # grads[\"dW\" + str(l + 1)] = ...\n # grads[\"db\" + str(l + 1)] = ...\n # YOUR CODE STARTS HERE\n current_cache = caches[l]\n dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads[\"dA\" + str(l + 1)], current_cache, 'relu')\n grads[\"dA\" + str(l)] = dA_prev_temp\n grads[\"dW\" + str(l + 1)] = dW_temp\n grads[\"db\" + str(l + 1)] = db_temp\n \n # YOUR CODE ENDS HERE\n\n return grads",
"_____no_output_____"
],
[
"t_AL, t_Y_assess, t_caches = L_model_backward_test_case()\ngrads = L_model_backward(t_AL, t_Y_assess, t_caches)\n\nprint(\"dA0 = \" + str(grads['dA0']))\nprint(\"dA1 = \" + str(grads['dA1']))\nprint(\"dW1 = \" + str(grads['dW1']))\nprint(\"dW2 = \" + str(grads['dW2']))\nprint(\"db1 = \" + str(grads['db1']))\nprint(\"db2 = \" + str(grads['db2']))\n\nL_model_backward_test(L_model_backward)",
"dA0 = [[ 0. 0.52257901]\n [ 0. -0.3269206 ]\n [ 0. -0.32070404]\n [ 0. -0.74079187]]\ndA1 = [[ 0.12913162 -0.44014127]\n [-0.14175655 0.48317296]\n [ 0.01663708 -0.05670698]]\ndW1 = [[0.41010002 0.07807203 0.13798444 0.10502167]\n [0. 0. 0. 0. ]\n [0.05283652 0.01005865 0.01777766 0.0135308 ]]\ndW2 = [[-0.39202432 -0.13325855 -0.04601089]]\ndb1 = [[-0.22007063]\n [ 0. ]\n [-0.02835349]]\ndb2 = [[0.15187861]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"**Expected output:**\n\n```\ndA0 = [[ 0. 0.52257901]\n [ 0. -0.3269206 ]\n [ 0. -0.32070404]\n [ 0. -0.74079187]]\ndA1 = [[ 0.12913162 -0.44014127]\n [-0.14175655 0.48317296]\n [ 0.01663708 -0.05670698]]\ndW1 = [[0.41010002 0.07807203 0.13798444 0.10502167]\n [0. 0. 0. 0. ]\n [0.05283652 0.01005865 0.01777766 0.0135308 ]]\ndW2 = [[-0.39202432 -0.13325855 -0.04601089]]\ndb1 = [[-0.22007063]\n [ 0. ]\n [-0.02835349]]\ndb2 = [[0.15187861]]\n```",
"_____no_output_____"
],
[
"<a name='6-4'></a>\n### 6.4 - Update Parameters\n\nIn this section, you'll update the parameters of the model, using gradient descent: \n\n$$ W^{[l]} = W^{[l]} - \\alpha \\text{ } dW^{[l]} \\tag{16}$$\n$$ b^{[l]} = b^{[l]} - \\alpha \\text{ } db^{[l]} \\tag{17}$$\n\nwhere $\\alpha$ is the learning rate. \n\nAfter computing the updated parameters, store them in the parameters dictionary. ",
"_____no_output_____"
],
[
"<a name='ex-10'></a>\n### Exercise 10 - update_parameters\n\nImplement `update_parameters()` to update your parameters using gradient descent.\n\n**Instructions**:\nUpdate parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$. ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: update_parameters\n\ndef update_parameters(params, grads, learning_rate):\n \"\"\"\n Update parameters using gradient descent\n \n Arguments:\n params -- python dictionary containing your parameters \n grads -- python dictionary containing your gradients, output of L_model_backward\n \n Returns:\n parameters -- python dictionary containing your updated parameters \n parameters[\"W\" + str(l)] = ... \n parameters[\"b\" + str(l)] = ...\n \"\"\"\n parameters = params.copy()\n L = len(parameters) // 2 # number of layers in the neural network\n\n # Update rule for each parameter. Use a for loop.\n #(≈ 2 lines of code)\n for l in range(L):\n # parameters[\"W\" + str(l+1)] = ...\n # parameters[\"b\" + str(l+1)] = ...\n # YOUR CODE STARTS HERE\n parameters[\"W\" + str(l + 1)] = parameters[\"W\" + str(l + 1)] - learning_rate * grads[\"dW\" + str(l + 1)]\n parameters[\"b\" + str(l + 1)] = parameters[\"b\" + str(l + 1)] - learning_rate * grads[\"db\" + str(l + 1)]\n # YOUR CODE ENDS HERE\n return parameters",
"_____no_output_____"
],
[
"t_parameters, grads = update_parameters_test_case()\nt_parameters = update_parameters(t_parameters, grads, 0.1)\n\nprint (\"W1 = \"+ str(t_parameters[\"W1\"]))\nprint (\"b1 = \"+ str(t_parameters[\"b1\"]))\nprint (\"W2 = \"+ str(t_parameters[\"W2\"]))\nprint (\"b2 = \"+ str(t_parameters[\"b2\"]))\n\nupdate_parameters_test(update_parameters)",
"W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n [-1.0535704 -0.86128581 0.68284052 2.20374577]]\nb1 = [[-0.04659241]\n [-1.28888275]\n [ 0.53405496]]\nW2 = [[-0.55569196 0.0354055 1.32964895]]\nb2 = [[-0.84610769]]\n\u001b[92m All tests passed.\n"
]
],
[
[
"**Expected output:**\n\n```\nW1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n [-1.0535704 -0.86128581 0.68284052 2.20374577]]\nb1 = [[-0.04659241]\n [-1.28888275]\n [ 0.53405496]]\nW2 = [[-0.55569196 0.0354055 1.32964895]]\nb2 = [[-0.84610769]]\n```",
"_____no_output_____"
],
[
"### Congratulations! \n\nYou've just implemented all the functions required for building a deep neural network, including: \n\n- Using non-linear units improve your model\n- Building a deeper neural network (with more than 1 hidden layer)\n- Implementing an easy-to-use neural network class\n\nThis was indeed a long assignment, but the next part of the assignment is easier. ;) \n\nIn the next assignment, you'll be putting all these together to build two models:\n\n- A two-layer neural network\n- An L-layer neural network\n\nYou will in fact use these models to classify cat vs non-cat images! (Meow!) Great work and see you next time. ",
"_____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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
d0aebe8e3b6d2ef816e6e94ada23f73764a4e4ce | 4,243 | ipynb | Jupyter Notebook | notebook04cb9a8032.ipynb | brendanmanning/Kaggle-Housing-Price-Activity | e341adabc8aba0a9931f4aabe9519244e60195c9 | [
"MIT"
] | null | null | null | notebook04cb9a8032.ipynb | brendanmanning/Kaggle-Housing-Price-Activity | e341adabc8aba0a9931f4aabe9519244e60195c9 | [
"MIT"
] | null | null | null | notebook04cb9a8032.ipynb | brendanmanning/Kaggle-Housing-Price-Activity | e341adabc8aba0a9931f4aabe9519244e60195c9 | [
"MIT"
] | null | null | null | 4,243 | 4,243 | 0.744285 | [
[
[
"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.feature_extraction import DictVectorizer\n\n\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session",
"/kaggle/input/house-prices-advanced-regression-techniques/sample_submission.csv\n/kaggle/input/house-prices-advanced-regression-techniques/data_description.txt\n/kaggle/input/house-prices-advanced-regression-techniques/train.csv\n/kaggle/input/house-prices-advanced-regression-techniques/test.csv\n"
]
],
[
[
"**Load training data**",
"_____no_output_____"
]
],
[
[
"train_df = pd.read_csv(\"/kaggle/input/house-prices-advanced-regression-techniques/train.csv\")",
"_____no_output_____"
]
],
[
[
"**Remove categorical features, handle missing data, cast improper types**",
"_____no_output_____"
]
],
[
[
"train_df['MSSubClass'] = train_df['MSSubClass'].apply(str)\ntrain_df['MoSold'] = train_df['MoSold'].astype(str)\ntrain_df['YrSold'] = train_df['YrSold'].astype(str)\n\ncat_features = train_df.select_dtypes(include = 'object').columns\ntrain_df.drop(cat_features, axis=1, inplace=True)\n\nfor c in train_df.columns:\n train_df[c].fillna(train_df[c].median(), inplace=True)",
"_____no_output_____"
]
],
[
[
"**Split the data into X(test/train) and Y(test/train) datasets**",
"_____no_output_____"
]
],
[
[
"y = train_df['SalePrice']\nx = train_df.loc[:, train_df.columns != 'SalePrice']\n\nX_dict = x.to_dict(orient='records')\ndv_X = DictVectorizer(sparse=False) \nX_encoded = dv_X.fit_transform(X_dict)\n\nX_Train, X_Test, Y_Train, Y_Test = train_test_split(X_encoded, y.to_numpy(), test_size=0.33, random_state=42)",
"_____no_output_____"
]
],
[
[
"**Train a Linear Regression Model**",
"_____no_output_____"
]
],
[
[
"# Create linear regression object\nregr = linear_model.LinearRegression()\n\n# Train the model using the training sets\nregr.fit(X_Train, Y_Train)",
"_____no_output_____"
]
],
[
[
"**Predict from the testing set**",
"_____no_output_____"
]
],
[
[
"# Make predictions using the testing set\npreds = regr.predict(X_Test)",
"_____no_output_____"
]
],
[
[
"**Score the model**",
"_____no_output_____"
]
],
[
[
"regr.score(X_Test, Y_Test)",
"_____no_output_____"
]
]
] | [
"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"
]
] |
d0aec2e770117f5f6a26bda49ad4aba57df46302 | 41,360 | ipynb | Jupyter Notebook | model_benchmarko_comparison.ipynb | egruttadauria98/Crypto-Efficient-Asset-Management | ce4d47a8fe0b3a01bbad654e45afb5c335a2dc0f | [
"MIT"
] | 6 | 2021-11-29T14:05:56.000Z | 2022-03-26T21:41:49.000Z | model_benchmarko_comparison.ipynb | egruttadauria98/Crypto-Efficient-Asset-Management | ce4d47a8fe0b3a01bbad654e45afb5c335a2dc0f | [
"MIT"
] | null | null | null | model_benchmarko_comparison.ipynb | egruttadauria98/Crypto-Efficient-Asset-Management | ce4d47a8fe0b3a01bbad654e45afb5c335a2dc0f | [
"MIT"
] | 2 | 2021-12-24T16:02:31.000Z | 2021-12-25T11:25:44.000Z | 31.238671 | 138 | 0.411871 | [
[
[
"import pandas as pd\nimport datetime\nfrom finquant.portfolio import build_portfolio\nfrom finquant.moving_average import compute_ma, ema\nfrom finquant.moving_average import plot_bollinger_band\nfrom finquant.efficient_frontier import EfficientFrontier",
"_____no_output_____"
],
[
"### DOES OUR OPTIMIZATION ACTUALLY WORK? \n# COMPARING AN OPTIMIZED PORTFOLIO WITH OTHER 2: THE FIRST WITH THE SAME AMOUNT OF ALL CURRENCIES AND ONE WITH ETH ONLY",
"_____no_output_____"
],
[
"# TIME-FRAME: WINTER 2021 IN WHICH ALL CURRENCIES WERE WERE GOING UP\n# NO STABLECOINS",
"_____no_output_____"
],
[
"L = ['ETH', 'BTC', 'USDT', 'USDC','ENJ', 'MANA']\nnames = ['ETH-USD', 'BTC-USD', 'ENJ-USD', 'MANA-USD']\nstart_date = '2021-01-01'\nend_date = '2021-03-01' #datetime.date.today()\npf = build_portfolio(names=names, data_api=\"yfinance\", start_date=start_date,end_date=end_date)",
"[*********************100%***********************] 4 of 4 completed\n"
],
[
"pf.data=pf.data.fillna('nan')\nfor i in range(pf.data.shape[0]):\n for k in range(pf.data.shape[1]):\n if pf.data.iloc[i,k]=='nan':\n pf.data.iloc[i,k]=pf.data.iloc[i-1,k]\npf.data.head()",
"_____no_output_____"
],
[
"pf.properties()",
"----------------------------------------------------------------------\nStocks: ETH-USD, BTC-USD, ENJ-USD, MANA-USD\nTime window/frequency: 252\nRisk free rate: 0.005\nPortfolio Expected Return: 4.900\nPortfolio Volatility: 1.041\nPortfolio Sharpe Ratio: 4.704\n\nSkewness:\n ETH-USD BTC-USD ENJ-USD MANA-USD\n0 -0.146324 0.616203 -0.094322 0.361746\n\nKurtosis:\n ETH-USD BTC-USD ENJ-USD MANA-USD\n0 -0.595774 -0.748084 -1.285856 -1.196845\n\nInformation:\n Allocation Name\n0 0.25 ETH-USD\n1 0.25 BTC-USD\n2 0.25 ENJ-USD\n3 0.25 MANA-USD\n----------------------------------------------------------------------\n"
],
[
"ef=EfficientFrontier(pf.comp_mean_returns(freq=30), pf.comp_cov(), risk_free_rate=0.0232)\nmax_sr=ef.maximum_sharpe_ratio().reset_index().rename({\"index\":\"Crypto\"},axis=1)\ndata = {i : {'Name':max_sr.iloc[i,0], \"Allocation\":max_sr.iloc[i,1]}for i in range(max_sr.shape[0])}\nalloc=[max_sr.iloc[i,1] for i in range(max_sr.shape[0])]\ndata",
"_____no_output_____"
],
[
"pf_allocation = pd.DataFrame.from_dict(data, orient=\"index\")\nnames=pf_allocation[\"Name\"].values.tolist()\npf_opt = build_portfolio(names=names,pf_allocation=pf_allocation, start_date=start_date ,end_date=end_date,data_api=\"yfinance\")\npf_opt.properties()",
"[*********************100%***********************] 4 of 4 completed\n----------------------------------------------------------------------\nStocks: ETH-USD, BTC-USD, ENJ-USD, MANA-USD\nTime window/frequency: 252\nRisk free rate: 0.005\nPortfolio Expected Return: 5.787\nPortfolio Volatility: 1.208\nPortfolio Sharpe Ratio: 4.784\n\nSkewness:\n ETH-USD BTC-USD ENJ-USD MANA-USD\n0 -0.146324 0.616203 -0.094322 0.361746\n\nKurtosis:\n ETH-USD BTC-USD ENJ-USD MANA-USD\n0 -0.595774 -0.748084 -1.285856 -1.196845\n\nInformation:\n Name Allocation\n0 ETH-USD 0.305539\n1 BTC-USD 0.040423\n2 ENJ-USD 0.376308\n3 MANA-USD 0.277729\n----------------------------------------------------------------------\n"
],
[
"# OUR OPTIMIZATION EXPECTS A RETURN OF 578%",
"_____no_output_____"
],
[
"start_date = '2021-03-01'\nend_date = '2021-04-01'\n\npf_real = build_portfolio(names=names, data_api=\"yfinance\", start_date=start_date,end_date=end_date)\npf_real.data=pf_real.data.fillna('nan')\nfor i in range(pf_real.data.shape[0]):\n for k in range(pf_real.data.shape[1]):\n if pf_real.data.iloc[i,k]=='nan':\n pf_real.data.iloc[i,k]=pf_real.data.iloc[i-1,k]\nds=pf_real.data\nds",
"[*********************100%***********************] 4 of 4 completed\n"
],
[
"returns = {i : {'Name':ds.columns[i], \"Returns\":(ds.iloc[-1,i]-ds.iloc[0,i])/ds.iloc[0,i]}for i in range(ds.shape[1])}\nr=[(ds.iloc[-1,i]-ds.iloc[0,i])/ds.iloc[0,i] for i in range(ds.shape[1])]\nreturns,r\n",
"_____no_output_____"
],
[
"DATA = pd.DataFrame(names, columns=['Crypto'])\nDATA[\"p_1\"]=alloc\nDATA[\"p_2\"]=0.2\nDATA[\"p_3\"]=0\nDATA.iloc[0,3]=1\nDATA[\"Returns\"]=r\nDATA",
"_____no_output_____"
],
[
"p_1_returns = 0\np_2_returns = 0\np_3_returns = 0\nfor i in range(DATA.shape[0]):\n p_1_returns+=DATA.iloc[i,1]*DATA.iloc[i,4]\n p_2_returns+=DATA.iloc[i,2]*DATA.iloc[i,4]\n p_3_returns+=DATA.iloc[i,3]*DATA.iloc[i,4]\n\np_1_returns,p_2_returns,p_3_returns",
"_____no_output_____"
],
[
"# AS WE CAN SEE, OUR PORTFOLIO PERFORMED MUCH BETTER, WITH 240% ACTUAL RETURN RATE",
"_____no_output_____"
],
[
"# TIME_FRAME: SUMMER 2021, WHEN CRYPTOS WERE GOING DOWN\n# WITH STABLECOINS",
"_____no_output_____"
],
[
"L = ['ETH', 'BTC', 'USDT', 'USDC','ENJ', 'MANA']\nnames = ['ETH-USD', 'BTC-USD', 'ENJ-USD', 'MANA-USD', 'USDC-USD','USDT-USD']\nstart_date = '2021-06-01'\nend_date = '2021-09-01' #datetime.date.today()\npf = build_portfolio(names=names, data_api=\"yfinance\", start_date=start_date,end_date=end_date)",
"[*********************100%***********************] 6 of 6 completed\n"
],
[
"pf.data=pf.data.fillna('nan')\nfor i in range(pf.data.shape[0]):\n for k in range(pf.data.shape[1]):\n if pf.data.iloc[i,k]=='nan':\n pf.data.iloc[i,k]=pf.data.iloc[i-1,k]\npf.data.head()",
"_____no_output_____"
],
[
"ef=EfficientFrontier(pf.comp_mean_returns(freq=30), pf.comp_cov(), risk_free_rate=0.0232)\nmax_sr=ef.maximum_sharpe_ratio().reset_index().rename({\"index\":\"Crypto\"},axis=1)\ndata = {i : {'Name':max_sr.iloc[i,0], \"Allocation\":max_sr.iloc[i,1]}for i in range(max_sr.shape[0])}\nalloc=[max_sr.iloc[i,1] for i in range(max_sr.shape[0])]\npf_allocation = pd.DataFrame.from_dict(data, orient=\"index\")\nnames=pf_allocation[\"Name\"].values.tolist()\npf_opt = build_portfolio(names=names,pf_allocation=pf_allocation, start_date=start_date ,end_date=end_date,data_api=\"yfinance\")\npf_opt.properties()",
"[*********************100%***********************] 6 of 6 completed\n----------------------------------------------------------------------\nStocks: ETH-USD, BTC-USD, ENJ-USD, MANA-USD, USDC-USD, USDT-USD\nTime window/frequency: 252\nRisk free rate: 0.005\nPortfolio Expected Return: 0.065\nPortfolio Volatility: 0.046\nPortfolio Sharpe Ratio: 1.300\n\nSkewness:\n ETH-USD BTC-USD ENJ-USD MANA-USD USDC-USD USDT-USD\n0 0.307993 0.532192 0.802842 -0.010326 1.097377 0.621434\n\nKurtosis:\n ETH-USD BTC-USD ENJ-USD MANA-USD USDC-USD USDT-USD\n0 -1.216315 -1.073198 0.42159 -0.525589 2.322316 1.081765\n\nInformation:\n Name Allocation\n0 ETH-USD 1.726851e-02\n1 BTC-USD 5.059439e-02\n2 ENJ-USD 6.267677e-03\n3 MANA-USD 0.000000e+00\n4 USDC-USD 9.258694e-01\n5 USDT-USD 1.377404e-11\n----------------------------------------------------------------------\n"
],
[
"# OUR OPTIMIZATION EXPECTS A RETURN OF 6.5%",
"_____no_output_____"
],
[
"start_date = '2021-09-01'\nend_date = '2021-10-01'\n\npf_real = build_portfolio(names=names, data_api=\"yfinance\", start_date=start_date,end_date=end_date)\npf_real.data=pf_real.data.fillna('nan')\nfor i in range(pf_real.data.shape[0]):\n for k in range(pf_real.data.shape[1]):\n if pf_real.data.iloc[i,k]=='nan':\n pf_real.data.iloc[i,k]=pf_real.data.iloc[i-1,k]\nds=pf_real.data\nds.head()",
"[*********************100%***********************] 6 of 6 completed\n"
],
[
"returns = {i : {'Name':ds.columns[i], \"Returns\":(ds.iloc[-1,i]-ds.iloc[0,i])/ds.iloc[0,i]}for i in range(ds.shape[1])}\nr=[(ds.iloc[-1,i]-ds.iloc[0,i])/ds.iloc[0,i] for i in range(ds.shape[1])]\nDATA = pd.DataFrame(names, columns=['Crypto'])\nDATA[\"p_1\"]=alloc\nDATA[\"p_2\"]=0.2\nDATA[\"p_3\"]=0\nDATA.iloc[0,3]=1\nDATA[\"Returns\"]=r\nDATA",
"_____no_output_____"
],
[
"p_1_returns = 0\np_2_returns = 0\np_3_returns = 0\nfor i in range(DATA.shape[0]):\n p_1_returns+=DATA.iloc[i,1]*DATA.iloc[i,4]\n p_2_returns+=DATA.iloc[i,2]*DATA.iloc[i,4]\n p_3_returns+=DATA.iloc[i,3]*DATA.iloc[i,4]\n\np_1_returns,p_2_returns,p_3_returns",
"_____no_output_____"
],
[
"# ACTUAL RETURN RATE IS -0.8%, WAY LOWER THAN THE OTHER PORTFOLIOS",
"_____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"
]
] |
d0aecb76062fe733b31c819aa53f05d710f8e18f | 17,509 | ipynb | Jupyter Notebook | components/outlier-detection/isolation-forest/isolation_forest.ipynb | OrthoDex/seldon-core | 1c2b511d1b14cbdae64ebde2e67f20aa18e6554e | [
"Apache-2.0"
] | 1 | 2020-03-29T18:56:31.000Z | 2020-03-29T18:56:31.000Z | components/outlier-detection/isolation-forest/isolation_forest.ipynb | OrthoDex/seldon-core | 1c2b511d1b14cbdae64ebde2e67f20aa18e6554e | [
"Apache-2.0"
] | 16 | 2019-12-16T22:22:13.000Z | 2022-03-12T00:07:55.000Z | components/outlier-detection/isolation-forest/isolation_forest.ipynb | OrthoDex/seldon-core | 1c2b511d1b14cbdae64ebde2e67f20aa18e6554e | [
"Apache-2.0"
] | 1 | 2020-03-29T18:56:33.000Z | 2020-03-29T18:56:33.000Z | 28.750411 | 434 | 0.590896 | [
[
[
"# Isolation Forest (IF) outlier detector deployment",
"_____no_output_____"
],
[
"Wrap a scikit-learn Isolation Forest python model for use as a prediction microservice in seldon-core and deploy on seldon-core running on minikube or a Kubernetes cluster using GCP.",
"_____no_output_____"
],
[
"## Dependencies",
"_____no_output_____"
],
[
"- [helm](https://github.com/helm/helm)\n- [minikube](https://github.com/kubernetes/minikube) \n- [s2i](https://github.com/openshift/source-to-image) >= 1.1.13 \n\npython packages:\n- scikit-learn: pip install scikit-learn --> 0.20.1",
"_____no_output_____"
],
[
"## Task",
"_____no_output_____"
],
[
"The outlier detector needs to detect computer network intrusions using TCP dump data for a local-area network (LAN) simulating a typical U.S. Air Force LAN. A connection is a sequence of TCP packets starting and ending at some well defined times, between which data flows to and from a source IP address to a target IP address under some well defined protocol. Each connection is labeled as either normal, or as an attack. \n\nThere are 4 types of attacks in the dataset:\n- DOS: denial-of-service, e.g. syn flood;\n- R2L: unauthorized access from a remote machine, e.g. guessing password;\n- U2R: unauthorized access to local superuser (root) privileges;\n- probing: surveillance and other probing, e.g., port scanning.\n \nThe dataset contains about 5 million connection records.\n\nThere are 3 types of features:\n- basic features of individual connections, e.g. duration of connection\n- content features within a connection, e.g. number of failed log in attempts\n- traffic features within a 2 second window, e.g. number of connections to the same host as the current connection\n\nThe outlier detector is only using 40 out of 41 features.",
"_____no_output_____"
],
[
"## Train locally\n\nTrain on small dataset where you roughly know the fraction of outliers, defined by the \"contamination\" parameter.",
"_____no_output_____"
]
],
[
[
"# define columns to keep\ncols=['duration','protocol_type','flag','src_bytes','dst_bytes','land',\n 'wrong_fragment','urgent','hot','num_failed_logins','logged_in',\n 'num_compromised','root_shell','su_attempted','num_root','num_file_creations',\n 'num_shells','num_access_files','num_outbound_cmds','is_host_login',\n 'is_guest_login','count','srv_count','serror_rate','srv_serror_rate',\n 'rerror_rate','srv_rerror_rate','same_srv_rate','diff_srv_rate',\n 'srv_diff_host_rate','dst_host_count','dst_host_srv_count','dst_host_same_srv_rate',\n 'dst_host_diff_srv_rate','dst_host_same_src_port_rate','dst_host_srv_diff_host_rate',\n 'dst_host_serror_rate','dst_host_srv_serror_rate','dst_host_rerror_rate',\n 'dst_host_srv_rerror_rate','target']\ncols_str = str(cols)",
"_____no_output_____"
],
[
"!python train.py \\\n--dataset 'kddcup99' \\\n--samples 50000 \\\n--keep_cols \"$cols_str\" \\\n--contamination .1 \\\n--n_estimators 100 \\\n--max_samples .8 \\\n--max_features 1. \\\n--save_path './models/'",
"_____no_output_____"
]
],
[
[
"## Test using Kubernetes cluster on GCP or Minikube",
"_____no_output_____"
],
[
"Run the outlier detector as a model or a transformer. If you want to run the anomaly detector as a transformer, change the SERVICE_TYPE variable from MODEL to TRANSFORMER [here](./.s2i/environment), set MODEL = False and change ```OutlierIsolationForest.py``` to:\n\n```python\nfrom CoreIsolationForest import CoreIsolationForest\n\nclass OutlierIsolationForest(CoreIsolationForest):\n \"\"\" Outlier detection using Isolation Forests.\n\n Parameters\n ----------\n threshold (float) : anomaly score threshold; scores below threshold are outliers\n \"\"\"\n def __init__(self,threshold=0.,load_path='./models/'):\n\n super().__init__(threshold=threshold, load_path=load_path)\n```",
"_____no_output_____"
]
],
[
[
"MODEL = True",
"_____no_output_____"
]
],
[
[
"Pick Kubernetes cluster on GCP or Minikube.",
"_____no_output_____"
]
],
[
[
"MINIKUBE = True",
"_____no_output_____"
],
[
"if MINIKUBE:\n !minikube start --memory 4096\nelse:\n !gcloud container clusters get-credentials standard-cluster-1 --zone europe-west1-b --project seldon-demos",
"_____no_output_____"
]
],
[
[
"Create a cluster-wide cluster-admin role assigned to a service account named “default” in the namespace “kube-system”.",
"_____no_output_____"
]
],
[
[
"!kubectl create clusterrolebinding kube-system-cluster-admin --clusterrole=cluster-admin \\\n--serviceaccount=kube-system:default",
"_____no_output_____"
],
[
"!kubectl create namespace seldon",
"_____no_output_____"
]
],
[
[
"Add current context details to the configuration file in the seldon namespace.",
"_____no_output_____"
]
],
[
[
"!kubectl config set-context $(kubectl config current-context) --namespace=seldon",
"_____no_output_____"
]
],
[
[
"Create tiller service account and give it a cluster-wide cluster-admin role.",
"_____no_output_____"
]
],
[
[
"!kubectl -n kube-system create sa tiller\n!kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller\n!helm init --service-account tiller",
"_____no_output_____"
]
],
[
[
"Check deployment rollout status and deploy seldon/spartakus helm charts.",
"_____no_output_____"
]
],
[
[
"!kubectl rollout status deploy/tiller-deploy -n kube-system",
"_____no_output_____"
],
[
"!helm install ../../../helm-charts/seldon-core-operator --name seldon-core --set usage_metrics.enabled=true --namespace seldon-system",
"_____no_output_____"
]
],
[
[
"Check deployment rollout status for seldon core.",
"_____no_output_____"
]
],
[
[
"!kubectl rollout status deploy/seldon-controller-manager -n seldon-system",
"_____no_output_____"
]
],
[
[
"Install Ambassador API gateway",
"_____no_output_____"
]
],
[
[
"!helm install stable/ambassador --name ambassador --set crds.keep=false",
"_____no_output_____"
],
[
"!kubectl rollout status deployment.apps/ambassador",
"_____no_output_____"
]
],
[
[
"If Minikube used: create docker image for outlier detector inside Minikube using s2i. Besides the transformer image and the demo specific model image, the general model image for the Isolation Forest outlier detector is also available from Docker Hub as ***seldonio/outlier-if-model:0.1***.",
"_____no_output_____"
]
],
[
[
"if MINIKUBE & MODEL:\n !eval $(minikube docker-env) && \\\n s2i build . seldonio/seldon-core-s2i-python3:0.4 seldonio/outlier-if-model-demo:0.1\nelif MINIKUBE:\n !eval $(minikube docker-env) && \\\n s2i build . seldonio/seldon-core-s2i-python3:0.4 seldonio/outlier-if-transformer:0.1",
"_____no_output_____"
]
],
[
[
"Install outlier detector helm charts either as a model or transformer and set *threshold* hyperparameter value.",
"_____no_output_____"
]
],
[
[
"if MODEL:\n !helm install ../../../helm-charts/seldon-od-model \\\n --name outlier-detector \\\n --namespace=seldon \\\n --set model.type=isolationforest \\\n --set model.isolationforest.image.name=seldonio/outlier-if-model-demo:0.1 \\\n --set model.isolationforest.threshold=0 \\\n --set oauth.key=oauth-key \\\n --set oauth.secret=oauth-secret \\\n --set replicas=1\nelse:\n !helm install ../../../helm-charts/seldon-od-transformer \\\n --name outlier-detector \\\n --namespace=seldon \\\n --set outlierDetection.enabled=true \\\n --set outlierDetection.name=outlier-if \\\n --set outlierDetection.type=isolationforest \\\n --set outlierDetection.isolationforest.image.name=seldonio/outlier-if-transformer:0.1 \\\n --set outlierDetection.isolationforest.threshold=0 \\\n --set oauth.key=oauth-key \\\n --set oauth.secret=oauth-secret \\\n --set model.image.name=seldonio/mock_classifier:1.0",
"_____no_output_____"
]
],
[
[
"## Port forward Ambassador\n\nRun command in terminal:",
"_____no_output_____"
],
[
"```\nkubectl port-forward $(kubectl get pods -n seldon -l app.kubernetes.io/name=ambassador -o jsonpath='{.items[0].metadata.name}') -n seldon 8003:8080\n```",
"_____no_output_____"
],
[
"## Import rest requests, load data and test requests",
"_____no_output_____"
]
],
[
[
"from utils import get_payload, rest_request_ambassador, send_feedback_rest, get_kdd_data, generate_batch\n\ndata = get_kdd_data(keep_cols=cols,percent10=True) # load dataset\nprint(data.shape)",
"_____no_output_____"
]
],
[
[
"Generate a random batch from the data",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nsamples = 1\nfraction_outlier = 0.\nX, labels = generate_batch(data,samples,fraction_outlier)\nprint(X.shape)\nprint(labels.shape)",
"_____no_output_____"
]
],
[
[
"Test the rest requests with the generated data. It is important that the order of requests is respected. First we make predictions, then we get the \"true\" labels back using the feedback request. If we do not respect the order and eg keep making predictions without getting the feedback for each prediction, there will be a mismatch between the predicted and \"true\" labels. This will result in errors in the produced metrics.",
"_____no_output_____"
]
],
[
[
"request = get_payload(X)",
"_____no_output_____"
],
[
"response = rest_request_ambassador(\"outlier-detector\",\"seldon\",request,endpoint=\"localhost:8003\")",
"_____no_output_____"
]
],
[
[
"If the outlier detector is used as a transformer, the output of the anomaly detection is added as part of the metadata. If it is used as a model, we send model feedback to retrieve custom performance metrics.",
"_____no_output_____"
]
],
[
[
"if MODEL:\n send_feedback_rest(\"outlier-detector\",\"seldon\",request,response,0,labels,endpoint=\"localhost:8003\")",
"_____no_output_____"
]
],
[
[
"## Analytics",
"_____no_output_____"
],
[
"Install the helm charts for prometheus and the grafana dashboard",
"_____no_output_____"
]
],
[
[
"!helm install ../../../helm-charts/seldon-core-analytics --name seldon-core-analytics \\\n --set grafana_prom_admin_password=password \\\n --set persistence.enabled=false \\\n --namespace seldon",
"_____no_output_____"
]
],
[
[
"## Port forward Grafana dashboard",
"_____no_output_____"
],
[
"Run command in terminal:",
"_____no_output_____"
],
[
"```\nkubectl port-forward $(kubectl get pods -n seldon -l app=grafana-prom-server -o jsonpath='{.items[0].metadata.name}') -n seldon 3000:3000\n```",
"_____no_output_____"
],
[
"You can then view an analytics dashboard inside the cluster at http://localhost:3000/dashboard/db/prediction-analytics?refresh=5s&orgId=1. Your IP address may be different. get it via minikube ip. Login with:\n\nUsername : admin\n\npassword : password (as set when starting seldon-core-analytics above)\n\nImport the outlier-detector-if dashboard from ../../../helm-charts/seldon-core-analytics/files/grafana/configs.",
"_____no_output_____"
],
[
"## Run simulation\n\n- Sample random network intrusion data with a certain outlier probability.\n- Get payload for the observation.\n- Make a prediction.\n- Send the \"true\" label with the feedback if the detector is run as a model.\n\nIt is important that the prediction-feedback order is maintained. Otherwise there will be a mismatch between the predicted and \"true\" labels.\n\nView the progress on the grafana \"Outlier Detection\" dashboard. Most metrics need the outlier detector to be run as a model since they need model feedback.",
"_____no_output_____"
]
],
[
[
"import time\nn_requests = 100\nsamples = 1\nfor i in range(n_requests):\n fraction_outlier = .1\n X, labels = generate_batch(data,samples,fraction_outlier)\n request = get_payload(X)\n response = rest_request_ambassador(\"outlier-detector\",\"seldon\",request,endpoint=\"localhost:8003\")\n if MODEL:\n send_feedback_rest(\"outlier-detector\",\"seldon\",request,response,0,labels,endpoint=\"localhost:8003\")\n time.sleep(1)",
"_____no_output_____"
],
[
"if MINIKUBE:\n !minikube delete",
"_____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",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
d0aed6ddc981bc2efc31a6eb01650c833ebe2d82 | 209,022 | ipynb | Jupyter Notebook | MediCare_ItemItemCollabFiltering.ipynb | aishwarya8615/Medicare_Drug-Recommendation | 1cc911ef4cb9e82e5b047c271a4e6a4adaedae56 | [
"MIT"
] | null | null | null | MediCare_ItemItemCollabFiltering.ipynb | aishwarya8615/Medicare_Drug-Recommendation | 1cc911ef4cb9e82e5b047c271a4e6a4adaedae56 | [
"MIT"
] | null | null | null | MediCare_ItemItemCollabFiltering.ipynb | aishwarya8615/Medicare_Drug-Recommendation | 1cc911ef4cb9e82e5b047c271a4e6a4adaedae56 | [
"MIT"
] | null | null | null | 41.081368 | 489 | 0.370612 | [
[
[
"import numpy as np\nimport pandas as pd\nimport os\nimport spacy\nimport en_core_web_sm\nfrom spacy.lang.en import English\nfrom spacy.lang.en.stop_words import STOP_WORDS\nimport string\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer,HashingVectorizer\nfrom sklearn.base import TransformerMixin\nfrom sklearn.pipeline import Pipeline\n!pip install vaderSentiment\nimport vaderSentiment\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer",
"Requirement already satisfied: vaderSentiment in /usr/local/lib/python3.6/dist-packages (3.3.1)\n"
],
[
"!pip install -U -q PyDrive\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom google.colab import auth\nfrom oauth2client.client import GoogleCredentials\nauth.authenticate_user()\ngauth = GoogleAuth()\ngauth.credentials = GoogleCredentials.get_application_default()\ndrive = GoogleDrive(gauth)\n\n\nfrom google.colab import drive\ndrive.mount('/content/gdrive')",
"Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount(\"/content/gdrive\", force_remount=True).\n"
],
[
"# preprocessing the data file\n# read the data\ndf1 = pd.read_csv(\"/content/gdrive/My Drive/Colab Notebooks/drugsComTrain_raw.csv\")\ndf2 = pd.read_csv(\"/content/gdrive/My Drive/Colab Notebooks/drugsComTest_raw.csv\")\n# combine two file\ndf = pd.concat([df1, df2])\ndf\n# rename the cols\ndf.columns = ['ID','drug name','condition','review','rating','date','useful count']",
"_____no_output_____"
],
[
"df2 = df[df['useful count'] > 10] ",
"_____no_output_____"
],
[
"df_condition = df2.groupby(['condition'])['drug name'].nunique().sort_values(ascending=False)\ndf_condition = pd.DataFrame(df_condition).reset_index()\ndf_condition.tail(20)",
"_____no_output_____"
],
[
"df_condition_1 = df_condition[df_condition['drug name'] == 1].reset_index()\n\nall_list = set(df.index)\n\n# deleting them\ncondition_list = []\nfor i,j in enumerate(df['condition']):\n for c in list(df_condition_1['condition']):\n if j == c:\n condition_list.append(i)\n \nnew_idx = all_list.difference(set(condition_list))\ndf = df.iloc[list(new_idx)].reset_index()\ndel df['index']",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"# removing the conditions with <span> in it.\n\nall_list = set(df.index)\nspan_list = []\nfor i,j in enumerate(df['condition']):\n if \"</span>\" in str(j):\n span_list.append(i)\nnew_idx = all_list.difference(set(span_list))\ndf = df.iloc[list(new_idx)].reset_index()\ndel df['index']",
"_____no_output_____"
],
[
"import re\nfrom bs4 import BeautifulSoup\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem.porter import PorterStemmer",
"[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n"
],
[
"# removing some stopwords from the list of stopwords as they are important for drug recommendation\n\nstops = set(stopwords.words('english'))\n\nnot_stop = [\"aren't\",\"couldn't\",\"didn't\",\"doesn't\",\"don't\",\"hadn't\",\"hasn't\",\"haven't\",\"isn't\",\"mightn't\",\n \"mustn't\",\"needn't\",\"no\",\"nor\",\"not\",\"shan't\",\"shouldn't\",\"wasn't\",\"weren't\",\"wouldn't\"]\nfor i in not_stop:\n stops.remove(i)",
"_____no_output_____"
],
[
"stemmer = SnowballStemmer('english')\n\ndef review_to_words(raw_review):\n # 1. Delete HTML \n review_text = BeautifulSoup(raw_review, 'html.parser').get_text()\n # 2. Make a space\n letters_only = re.sub('[^a-zA-Z]', ' ', review_text)\n # 3. lower letters\n words = letters_only.lower().split()\n # 5. Stopwords \n meaningful_words = [w for w in words if not w in stops]\n # 6. Stemming\n stemming_words = [stemmer.stem(w) for w in meaningful_words]\n # 7. space join words\n return( ' '.join(stemming_words))\n\n# create a list of stopwords\nnlp = spacy.load('en_core_web_sm')\nstop_words = spacy.lang.en.stop_words.STOP_WORDS\nparser = English()\npunctuations = string.punctuation\n# Creating our tokenizer function\ndef spacy_tokenizer(sentence):\n # Creating our token object, which is used to create documents with linguistic annotations.\n mytokens = parser(sentence)\n\n # Lemmatizing each token and converting each token into lowercase\n mytokens = [ word.lemma_.lower().strip() if word.lemma_ != \"-PRON-\" else word.lower_ for word in mytokens ]\n\n # Removing stop words\n mytokens = [ word for word in mytokens if word not in stop_words and word not in punctuations ]\n\n # return preprocessed list of tokens\n return mytokens\n",
"_____no_output_____"
],
[
"%time df['review_clean'] = df['review'].apply(review_to_words)\ndf.head()",
"CPU times: user 1min 26s, sys: 397 ms, total: 1min 26s\nWall time: 1min 26s\n"
],
[
"bow_vector = CountVectorizer(tokenizer = spacy_tokenizer, ngram_range=(1,2))\n# tf-idf vector\ntfidf_vector = TfidfVectorizer(tokenizer = spacy_tokenizer)",
"_____no_output_____"
],
[
"# part 1---vader sentiment analyzer for c_review\nanalyzer = SentimentIntensityAnalyzer()\n# create new col vaderReviewScore based on C-review\ndf['vaderReviewScore'] = df['review_clean'].apply(lambda x: analyzer.polarity_scores(x)['compound'])\n\n# define the positive, neutral and negative\npositive_num = len(df[df['vaderReviewScore'] >=0.05])\nneutral_num = len(df[(df['vaderReviewScore'] >-0.05) & (df['vaderReviewScore']<0.05)])\nnegative_num = len(df[df['vaderReviewScore']<=-0.05])\n\n# create new col vaderSentiment based on vaderReviewScore\ndf['vaderSentiment'] = df['vaderReviewScore'].map(lambda x:int(2) if x>=0.05 else int(1) if x<=-0.05 else int(0) )\ndf['vaderSentiment'].value_counts() # 2-pos: 99519; 1-neg: 104434; 0-neu: 11110\n\n# label pos/neg/neu based on vaderSentiment result\ndf.loc[df['vaderReviewScore'] >=0.05,\"vaderSentimentLabel\"] =\"positive\"\ndf.loc[(df['vaderReviewScore'] >-0.05) & (df['vaderReviewScore']<0.05),\"vaderSentimentLabel\"]= \"neutral\"\ndf.loc[df['vaderReviewScore']<=-0.05,\"vaderSentimentLabel\"] = \"negative\"",
"_____no_output_____"
],
[
"df['vaderReviewScore'].max()",
"_____no_output_____"
],
[
"df['vaderReviewScore'].min()",
"_____no_output_____"
],
[
"criteria = [df['vaderReviewScore'].between(-0.997, -0.799), df['vaderReviewScore'].between(-0.798, -0.601), df['vaderReviewScore'].between(-0.600, 0.403), df['vaderReviewScore'].between(-0.402, -0.205), df['vaderReviewScore'].between(-0.204, -0.007), df['vaderReviewScore'].between(-0.006,0.191), df['vaderReviewScore'].between(0.192, 0.389), df['vaderReviewScore'].between(0.390, 0.587), df['vaderReviewScore'].between(0.588, 0.785), df['vaderReviewScore'].between(0.786, 1)]\nvalues = [1, 2, 3,4,5,6,7,8,9,10]\n\ndf['normalVaderScore'] = np.select(criteria, values, 0)",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"df['meanNormalizedScore'] = (df['rating'] + df['normalVaderScore'])/2\ndf.head()",
"_____no_output_____"
],
[
"grouped = df.groupby(['condition','drug name', 'ID']).agg({'meanNormalizedScore' : ['mean']})\ngrouped.to_csv('Medicare_Normalized_results')\ngrouped1 = grouped.reset_index()\ngrouped1.head(100)",
"_____no_output_____"
],
[
"grouped1.set_index('ID')",
"_____no_output_____"
],
[
"user_ratings = grouped1.pivot_table(index = ['condition'], columns = ['ID'], values = 'meanNormalizedScore')\nuser_ratings1 = grouped1.pivot_table(index = ['condition'], columns = ['ID'], values = 'meanNormalizedScore')\nuser_ratings.head(20)\nuser_ratings.to_csv('Itemtoitem_recom.csv')",
"/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py:3936: PerformanceWarning: dropping on a non-lexsorted multi-index without a level parameter may impact performance.\n obj = obj._drop_axis(labels, axis, level=level, errors=errors)\n"
],
[
"user_ratings.iloc[0,:].sum(axis=0)",
"_____no_output_____"
],
[
"#Let's predict the rating for the first drug for the 1st condition.\n#Therefore, we need to find the similarity between the them\nimport math as np\ndef takesec(num):\n return num[1]\n\ncosine_vector = []\nnum = 0\nl1 = 0\nl2 = 0\nfor i in range(1,user_ratings.shape[0]):\n num = 0\n l1 = 0\n l2 = 0\n for j in range(user_ratings.shape[1]):\n if not np.isnan(user_ratings.iloc[i,j]) and not np.isnan(user_ratings.iloc[0,j]):\n num = num + (user_ratings.iloc[i,j] * user_ratings.iloc[0,j])\n if not np.isnan(user_ratings.iloc[i,j]):\n l1 = l1 + (user_ratings.iloc[i,j] * user_ratings.iloc[i,j])\n if not np.isnan(user_ratings.iloc[0,j]):\n l2 = l2 + (user_ratings.iloc[0,j] * user_ratings.iloc[0,j])\n eventual_prod = np.sqrt(l1) * np.sqrt(l2)\n if eventual_prod != 0 :\n eventual_div = num/eventual_prod\n cosine_vector.append([i,eventual_div])\n cosine_vector.sort(key=takesec, reverse=True)",
"_____no_output_____"
],
[
"cosine_vector[:100000]\nuser_ratings1.iloc[4,1]",
"_____no_output_____"
],
[
"import csv\n# opening the csv file in 'w+' mode \nfile = open('cosine_vec.csv', 'w+', newline ='') \n \n# writing the data into the file \nwith file: \n write = csv.writer(file) \n write.writerows(cosine_vector) ",
"_____no_output_____"
],
[
"\n#Let's consider the top 50 similar rated drugs and predict the output.\n\npredict_drug = int(input (\"Enter a drug ID within range 0 to 1000000 : \"))\ncount = 0\nnum1 = 0\nden1 = 0\nfor i in cosine_vector:\n if user_ratings1.iloc[i[0],predict_drug] > 0:\n count = count + 1\n num1 = num1 + i[1] * user_ratings1.iloc[i[0],predict_drug]\n #print(num1)\n den1 = den1 + i[1]\n #print(den1)\n #print(\"{}..{}\".format(i[0],i[1]))\n \n if count == 50:\n print (\"Reached 50 :)\")\n break\n\nprint(\"Expected Rating for 1st Drug for condition: {} is :{}\".format(predict_drug,num1/den1))",
"Enter a drug ID within range 0 to 1000000 : 61002\nExpected Rating for 1st Drug for condition: 61002 is :nan\n"
],
[
"for i in range(user_ratings1.shape[1]):\n if user_ratings1.iloc[0,i] > 0:\n print(\"Id = {} , Rating = {}\".format(i,user_ratings1.iloc[0,i]))",
"Id = 584 , Rating = 5.5\nId = 585 , Rating = 9.0\nId = 587 , Rating = 6.0\nId = 588 , Rating = 3.5\nId = 589 , Rating = 6.5\nId = 590 , Rating = 6.0\nId = 591 , Rating = 9.0\nId = 1858 , Rating = 9.0\nId = 1893 , Rating = 8.5\nId = 1894 , Rating = 10.0\nId = 1895 , Rating = 6.0\nId = 1896 , Rating = 3.5\nId = 1897 , Rating = 4.0\nId = 1898 , Rating = 2.5\nId = 1899 , Rating = 2.0\nId = 1900 , Rating = 1.0\nId = 1901 , Rating = 2.5\nId = 1902 , Rating = 1.5\nId = 9035 , Rating = 8.5\nId = 9036 , Rating = 3.0\nId = 9037 , Rating = 2.0\nId = 9038 , Rating = 10.0\nId = 9039 , Rating = 2.0\nId = 9040 , Rating = 8.0\nId = 9041 , Rating = 6.0\nId = 9042 , Rating = 9.5\nId = 9043 , Rating = 3.0\nId = 9044 , Rating = 8.5\nId = 9045 , Rating = 4.0\nId = 9046 , Rating = 8.0\nId = 9047 , Rating = 9.0\nId = 9048 , Rating = 2.5\nId = 9049 , Rating = 2.0\nId = 9050 , Rating = 2.0\nId = 9051 , Rating = 1.0\nId = 9052 , Rating = 1.5\nId = 9053 , Rating = 1.5\nId = 9054 , Rating = 9.0\nId = 9055 , Rating = 6.0\nId = 9056 , Rating = 9.0\nId = 9059 , Rating = 9.5\nId = 9060 , Rating = 7.5\nId = 9061 , Rating = 2.0\nId = 9062 , Rating = 9.0\nId = 9064 , Rating = 9.0\nId = 9065 , Rating = 6.0\nId = 9066 , Rating = 7.0\nId = 9067 , Rating = 6.5\nId = 9069 , Rating = 7.0\nId = 9070 , Rating = 10.0\nId = 9071 , Rating = 2.5\nId = 9072 , Rating = 9.0\nId = 9073 , Rating = 5.5\nId = 9074 , Rating = 10.0\nId = 9075 , Rating = 2.0\nId = 9076 , Rating = 8.5\nId = 9079 , Rating = 9.0\nId = 9080 , Rating = 6.5\nId = 9081 , Rating = 9.5\nId = 9082 , Rating = 6.0\nId = 9083 , Rating = 8.5\nId = 9084 , Rating = 5.5\nId = 9085 , Rating = 5.5\nId = 9086 , Rating = 6.5\nId = 9087 , Rating = 5.5\nId = 9088 , Rating = 9.0\nId = 9089 , Rating = 5.0\nId = 9090 , Rating = 5.0\nId = 9091 , Rating = 9.5\nId = 9092 , Rating = 8.5\nId = 9093 , Rating = 6.0\nId = 9094 , Rating = 8.0\nId = 9095 , Rating = 6.5\nId = 9096 , Rating = 7.0\nId = 9097 , Rating = 6.5\nId = 9098 , Rating = 9.5\nId = 9099 , Rating = 9.0\nId = 9101 , Rating = 6.5\nId = 9102 , Rating = 8.0\nId = 9103 , Rating = 5.5\nId = 9106 , Rating = 9.5\nId = 9107 , Rating = 8.5\nId = 9108 , Rating = 2.0\nId = 9109 , Rating = 6.5\nId = 9110 , Rating = 2.0\nId = 9111 , Rating = 9.5\nId = 9113 , Rating = 6.0\nId = 9114 , Rating = 6.0\nId = 9115 , Rating = 10.0\nId = 9116 , Rating = 6.0\nId = 9117 , Rating = 6.0\nId = 9118 , Rating = 3.0\nId = 9119 , Rating = 2.5\nId = 9120 , Rating = 8.0\nId = 9121 , Rating = 8.0\nId = 9122 , Rating = 10.0\nId = 9123 , Rating = 6.5\nId = 9124 , Rating = 5.5\nId = 9125 , Rating = 4.0\nId = 9126 , Rating = 9.5\nId = 9128 , Rating = 9.5\nId = 9129 , Rating = 6.0\nId = 9130 , Rating = 3.0\nId = 9133 , Rating = 2.0\nId = 9134 , Rating = 6.5\nId = 9136 , Rating = 3.5\nId = 9137 , Rating = 7.5\nId = 9139 , Rating = 9.0\nId = 9140 , Rating = 9.0\nId = 9142 , Rating = 10.0\nId = 9144 , Rating = 4.5\nId = 9145 , Rating = 10.0\nId = 9146 , Rating = 10.0\nId = 9147 , Rating = 5.5\nId = 9149 , Rating = 1.5\nId = 9151 , Rating = 8.0\nId = 9152 , Rating = 9.5\nId = 9153 , Rating = 9.0\nId = 9154 , Rating = 9.0\nId = 9155 , Rating = 3.5\nId = 9156 , Rating = 10.0\nId = 9157 , Rating = 9.0\nId = 9158 , Rating = 8.0\nId = 9159 , Rating = 1.0\nId = 9160 , Rating = 9.5\nId = 9161 , Rating = 5.0\nId = 9162 , Rating = 6.5\nId = 9163 , Rating = 9.0\nId = 9164 , Rating = 9.0\nId = 9165 , Rating = 6.0\nId = 9167 , Rating = 10.0\nId = 9168 , Rating = 9.5\nId = 9169 , Rating = 9.5\nId = 9170 , Rating = 9.0\nId = 9171 , Rating = 4.0\nId = 9173 , Rating = 9.5\nId = 9174 , Rating = 6.5\nId = 9175 , Rating = 8.5\nId = 9176 , Rating = 10.0\nId = 9177 , Rating = 6.0\nId = 9178 , Rating = 5.0\nId = 9179 , Rating = 6.5\nId = 9180 , Rating = 9.5\nId = 9181 , Rating = 9.0\nId = 9182 , Rating = 6.0\nId = 9183 , Rating = 4.0\nId = 9184 , Rating = 9.0\nId = 9186 , Rating = 1.5\nId = 9187 , Rating = 8.5\nId = 9188 , Rating = 6.5\nId = 9189 , Rating = 9.0\nId = 9190 , Rating = 5.5\nId = 9191 , Rating = 5.5\nId = 9192 , Rating = 4.5\nId = 9194 , Rating = 6.0\nId = 9195 , Rating = 9.0\nId = 9196 , Rating = 9.0\nId = 9197 , Rating = 6.5\nId = 9198 , Rating = 1.5\nId = 9199 , Rating = 9.5\nId = 9200 , Rating = 5.5\nId = 9201 , Rating = 6.0\nId = 9202 , Rating = 4.0\nId = 9203 , Rating = 4.0\nId = 9204 , Rating = 9.0\nId = 9205 , Rating = 10.0\nId = 9206 , Rating = 5.0\nId = 9207 , Rating = 8.5\nId = 9208 , Rating = 5.5\nId = 9209 , Rating = 6.5\nId = 9212 , Rating = 9.5\nId = 9213 , Rating = 6.5\nId = 9214 , Rating = 6.5\nId = 9215 , Rating = 9.0\nId = 9216 , Rating = 9.0\nId = 9218 , Rating = 8.0\nId = 9219 , Rating = 9.0\nId = 9221 , Rating = 4.0\nId = 9222 , Rating = 5.5\nId = 9223 , Rating = 5.5\nId = 9224 , Rating = 8.0\nId = 9226 , Rating = 6.5\nId = 9227 , Rating = 8.0\nId = 9228 , Rating = 8.5\nId = 9229 , Rating = 9.5\nId = 9230 , Rating = 6.5\nId = 9231 , Rating = 6.0\nId = 9232 , Rating = 10.0\nId = 9234 , Rating = 9.0\nId = 9235 , Rating = 6.0\nId = 9236 , Rating = 6.0\nId = 9238 , Rating = 8.0\nId = 9239 , Rating = 6.0\nId = 9241 , Rating = 5.0\nId = 9242 , Rating = 4.5\nId = 9243 , Rating = 3.5\nId = 9244 , Rating = 9.5\nId = 9245 , Rating = 9.0\nId = 9246 , Rating = 9.0\nId = 9247 , Rating = 5.0\nId = 9248 , Rating = 6.5\nId = 9250 , Rating = 9.0\nId = 9252 , Rating = 8.5\nId = 9254 , Rating = 8.5\nId = 9255 , Rating = 5.5\nId = 9256 , Rating = 10.0\nId = 9257 , Rating = 2.0\nId = 9258 , Rating = 6.5\nId = 9259 , Rating = 6.5\nId = 9260 , Rating = 9.5\nId = 9261 , Rating = 10.0\nId = 9262 , Rating = 9.5\nId = 9264 , Rating = 4.0\nId = 9266 , Rating = 6.5\nId = 9267 , Rating = 6.5\nId = 9268 , Rating = 9.5\nId = 9269 , Rating = 6.5\nId = 9270 , Rating = 5.5\nId = 9271 , Rating = 2.0\nId = 9272 , Rating = 9.0\nId = 9273 , Rating = 6.0\nId = 9275 , Rating = 6.5\nId = 9276 , Rating = 9.5\nId = 9277 , Rating = 6.5\nId = 9278 , Rating = 4.5\nId = 9279 , Rating = 9.0\nId = 9280 , Rating = 6.5\nId = 9282 , Rating = 6.5\nId = 9283 , Rating = 6.0\nId = 9285 , Rating = 9.0\nId = 9286 , Rating = 5.0\nId = 9287 , Rating = 9.0\nId = 9288 , Rating = 6.0\nId = 9289 , Rating = 5.5\nId = 9290 , Rating = 5.0\nId = 9291 , Rating = 6.0\nId = 9293 , Rating = 9.0\nId = 9294 , Rating = 9.0\nId = 9295 , Rating = 9.5\nId = 9296 , Rating = 5.5\nId = 9297 , Rating = 9.0\nId = 9298 , Rating = 5.5\nId = 9299 , Rating = 9.0\nId = 9300 , Rating = 10.0\nId = 9301 , Rating = 9.0\nId = 9302 , Rating = 5.5\nId = 9303 , Rating = 8.0\nId = 9304 , Rating = 6.0\nId = 9305 , Rating = 5.0\nId = 9306 , Rating = 6.0\nId = 9307 , Rating = 10.0\nId = 9308 , Rating = 8.5\nId = 9309 , Rating = 4.5\nId = 9311 , Rating = 6.0\nId = 9312 , Rating = 5.5\nId = 9313 , Rating = 6.5\nId = 9315 , Rating = 5.0\nId = 9317 , Rating = 9.5\nId = 9318 , Rating = 10.0\nId = 9319 , Rating = 5.0\nId = 9320 , Rating = 6.0\nId = 9322 , Rating = 6.5\nId = 9324 , Rating = 8.0\nId = 9325 , Rating = 6.0\nId = 9326 , Rating = 6.0\nId = 9327 , Rating = 10.0\nId = 9328 , Rating = 6.5\nId = 9329 , Rating = 9.5\nId = 9330 , Rating = 5.5\nId = 9332 , Rating = 6.0\nId = 9333 , Rating = 9.0\nId = 9334 , Rating = 5.5\nId = 9335 , Rating = 6.0\nId = 9336 , Rating = 6.0\nId = 9338 , Rating = 9.0\nId = 9339 , Rating = 5.5\nId = 9340 , Rating = 6.0\nId = 9341 , Rating = 9.5\nId = 9342 , Rating = 9.5\nId = 9344 , Rating = 5.5\nId = 9345 , Rating = 8.0\nId = 9346 , Rating = 9.0\nId = 9347 , Rating = 9.5\nId = 9348 , Rating = 9.5\nId = 9349 , Rating = 5.5\nId = 9350 , Rating = 8.5\nId = 9351 , Rating = 9.0\nId = 9352 , Rating = 1.0\nId = 9353 , Rating = 9.5\nId = 9354 , Rating = 9.0\nId = 9355 , Rating = 6.0\nId = 9356 , Rating = 3.0\nId = 9357 , Rating = 5.5\nId = 9358 , Rating = 5.0\nId = 9359 , Rating = 9.5\nId = 9360 , Rating = 6.5\nId = 9361 , Rating = 6.5\nId = 9362 , Rating = 5.5\nId = 9363 , Rating = 5.5\nId = 9364 , Rating = 5.0\nId = 9365 , Rating = 6.0\nId = 9366 , Rating = 5.5\nId = 9367 , Rating = 4.5\nId = 9368 , Rating = 5.5\nId = 9369 , Rating = 6.0\nId = 9370 , Rating = 8.5\nId = 9371 , Rating = 6.0\nId = 9372 , Rating = 4.5\nId = 9373 , Rating = 10.0\nId = 9374 , Rating = 5.5\nId = 9375 , Rating = 9.0\nId = 9376 , Rating = 8.0\nId = 9377 , Rating = 9.0\nId = 9378 , Rating = 5.0\nId = 9379 , Rating = 9.0\nId = 9380 , Rating = 5.0\nId = 9381 , Rating = 6.5\nId = 9382 , Rating = 6.0\nId = 9383 , Rating = 9.0\nId = 9385 , Rating = 9.0\nId = 9386 , Rating = 8.5\nId = 9387 , Rating = 8.0\nId = 9388 , Rating = 6.5\nId = 9390 , Rating = 6.0\nId = 9391 , Rating = 9.5\nId = 9392 , Rating = 6.0\nId = 9393 , Rating = 5.5\nId = 9394 , Rating = 8.0\nId = 9395 , Rating = 5.5\nId = 9396 , Rating = 8.5\nId = 9397 , Rating = 5.5\nId = 9398 , Rating = 8.5\nId = 9399 , Rating = 8.5\nId = 9400 , Rating = 6.5\nId = 9402 , Rating = 8.5\nId = 9403 , Rating = 9.5\nId = 9405 , Rating = 10.0\nId = 9406 , Rating = 5.5\nId = 9407 , Rating = 8.5\nId = 9408 , Rating = 3.5\nId = 9409 , Rating = 10.0\nId = 9410 , Rating = 4.5\nId = 9411 , Rating = 2.5\nId = 9412 , Rating = 6.5\nId = 9413 , Rating = 6.5\nId = 9414 , Rating = 10.0\nId = 9415 , Rating = 3.5\nId = 9416 , Rating = 9.0\nId = 9417 , Rating = 10.0\nId = 9418 , Rating = 10.0\nId = 9419 , Rating = 5.5\nId = 9420 , Rating = 6.5\nId = 9421 , Rating = 5.5\nId = 9422 , Rating = 9.0\nId = 9423 , Rating = 9.0\nId = 9424 , Rating = 9.5\nId = 9426 , Rating = 9.5\nId = 9427 , Rating = 9.0\nId = 9428 , Rating = 6.0\nId = 9429 , Rating = 6.5\nId = 9430 , Rating = 8.5\nId = 9431 , Rating = 6.5\nId = 9432 , Rating = 5.5\nId = 9433 , Rating = 6.5\nId = 9434 , Rating = 9.0\nId = 9435 , Rating = 6.5\nId = 9436 , Rating = 6.5\nId = 9438 , Rating = 7.0\nId = 9439 , Rating = 9.5\nId = 9440 , Rating = 8.5\nId = 9442 , Rating = 5.5\nId = 11591 , Rating = 10.0\nId = 11901 , Rating = 5.5\nId = 11902 , Rating = 9.0\nId = 11903 , Rating = 2.5\nId = 11904 , Rating = 4.0\nId = 11905 , Rating = 2.0\nId = 11906 , Rating = 6.5\nId = 11907 , Rating = 10.0\nId = 11908 , Rating = 4.0\nId = 12873 , Rating = 7.5\nId = 12874 , Rating = 4.0\nId = 12875 , Rating = 6.0\nId = 14511 , Rating = 7.0\nId = 14512 , Rating = 9.5\nId = 14513 , Rating = 8.0\nId = 14514 , Rating = 3.0\nId = 14515 , Rating = 9.0\nId = 14516 , Rating = 5.5\nId = 14517 , Rating = 8.5\nId = 14518 , Rating = 5.0\nId = 14519 , Rating = 5.5\nId = 14520 , Rating = 4.5\nId = 14521 , Rating = 6.5\nId = 14522 , Rating = 8.5\nId = 14523 , Rating = 5.5\nId = 14524 , Rating = 5.5\nId = 14525 , Rating = 4.0\nId = 14526 , Rating = 9.0\nId = 14527 , Rating = 5.5\nId = 14528 , Rating = 6.5\nId = 14529 , Rating = 9.0\nId = 14530 , Rating = 3.5\nId = 14531 , Rating = 3.5\nId = 14532 , Rating = 6.0\nId = 14533 , Rating = 7.5\nId = 14534 , Rating = 1.5\nId = 14535 , Rating = 9.0\nId = 14536 , Rating = 6.5\nId = 14537 , Rating = 8.5\nId = 14538 , Rating = 2.5\nId = 14539 , Rating = 6.0\nId = 14540 , Rating = 8.5\nId = 14541 , Rating = 9.0\nId = 14542 , Rating = 9.0\nId = 14543 , Rating = 6.5\nId = 14544 , Rating = 5.0\nId = 14545 , Rating = 6.0\nId = 14546 , Rating = 9.5\nId = 14547 , Rating = 9.0\nId = 14548 , Rating = 6.0\nId = 14549 , Rating = 1.5\nId = 14550 , Rating = 6.5\nId = 14551 , Rating = 9.0\nId = 14552 , Rating = 9.5\nId = 14553 , Rating = 6.5\nId = 14554 , Rating = 2.0\nId = 14555 , Rating = 8.5\nId = 14556 , Rating = 6.0\nId = 14557 , Rating = 6.5\nId = 14558 , Rating = 6.5\nId = 14559 , Rating = 5.5\nId = 14560 , Rating = 5.5\nId = 17771 , Rating = 1.0\nId = 17772 , Rating = 8.5\nId = 17773 , Rating = 5.5\nId = 17774 , Rating = 3.5\nId = 17775 , Rating = 6.0\nId = 17776 , Rating = 9.5\nId = 17777 , Rating = 10.0\nId = 17778 , Rating = 6.5\nId = 17779 , Rating = 4.0\nId = 17780 , Rating = 5.0\nId = 17781 , Rating = 8.5\nId = 17782 , Rating = 10.0\nId = 22080 , Rating = 5.0\nId = 22090 , Rating = 10.0\nId = 22092 , Rating = 5.5\nId = 22099 , Rating = 5.5\nId = 22112 , Rating = 9.5\nId = 22115 , Rating = 6.5\nId = 25388 , Rating = 4.5\nId = 25390 , Rating = 8.0\nId = 25392 , Rating = 1.0\nId = 25393 , Rating = 10.0\nId = 25394 , Rating = 4.0\nId = 25396 , Rating = 6.5\nId = 25398 , Rating = 8.5\nId = 25399 , Rating = 6.0\nId = 25402 , Rating = 5.0\nId = 25403 , Rating = 9.0\nId = 25405 , Rating = 2.0\nId = 25406 , Rating = 4.5\nId = 25407 , Rating = 6.5\nId = 25408 , Rating = 7.0\nId = 25410 , Rating = 8.5\nId = 25411 , Rating = 7.5\nId = 25413 , Rating = 4.0\nId = 25415 , Rating = 1.5\nId = 25416 , Rating = 5.5\nId = 25417 , Rating = 7.0\nId = 25418 , Rating = 1.0\nId = 25419 , Rating = 9.0\nId = 25420 , Rating = 6.5\nId = 25421 , Rating = 1.5\nId = 25422 , Rating = 4.0\nId = 25423 , Rating = 6.5\nId = 25424 , Rating = 3.0\nId = 25426 , Rating = 9.0\nId = 25427 , Rating = 9.0\nId = 25428 , Rating = 10.0\nId = 25429 , Rating = 8.5\nId = 25430 , Rating = 9.5\nId = 25432 , Rating = 5.5\nId = 25436 , Rating = 2.5\nId = 25437 , Rating = 6.5\nId = 25438 , Rating = 5.0\nId = 25439 , Rating = 2.0\nId = 25440 , Rating = 3.0\nId = 25441 , Rating = 1.0\nId = 25442 , Rating = 6.0\nId = 25443 , Rating = 2.0\nId = 25444 , Rating = 3.5\nId = 25445 , Rating = 6.5\nId = 25446 , Rating = 1.5\nId = 25447 , Rating = 10.0\nId = 25448 , Rating = 7.5\nId = 25449 , Rating = 10.0\nId = 25450 , Rating = 1.5\nId = 25451 , Rating = 10.0\nId = 25452 , Rating = 10.0\nId = 25453 , Rating = 9.0\nId = 25454 , Rating = 7.0\nId = 25455 , Rating = 9.5\nId = 25456 , Rating = 5.5\nId = 25457 , Rating = 3.0\nId = 25458 , Rating = 8.0\nId = 25459 , Rating = 5.0\nId = 25460 , Rating = 8.5\nId = 25461 , Rating = 4.5\nId = 25462 , Rating = 2.0\nId = 25463 , Rating = 6.0\nId = 25464 , Rating = 3.0\nId = 25465 , Rating = 6.0\nId = 25466 , Rating = 6.0\nId = 25467 , Rating = 9.5\nId = 25469 , Rating = 2.0\nId = 25472 , Rating = 7.0\nId = 25473 , Rating = 9.5\nId = 25474 , Rating = 6.0\nId = 25475 , Rating = 8.0\nId = 25477 , Rating = 6.0\nId = 25478 , Rating = 10.0\nId = 25479 , Rating = 4.0\nId = 25480 , Rating = 4.5\nId = 25481 , Rating = 6.5\nId = 25482 , Rating = 8.0\nId = 25483 , Rating = 9.0\nId = 25484 , Rating = 6.5\nId = 25485 , Rating = 10.0\nId = 25487 , Rating = 9.0\nId = 25488 , Rating = 6.0\nId = 25490 , Rating = 6.0\nId = 25491 , Rating = 1.5\nId = 25492 , Rating = 7.5\nId = 25493 , Rating = 6.0\nId = 25496 , Rating = 2.0\nId = 25497 , Rating = 6.5\nId = 25498 , Rating = 5.5\nId = 25499 , Rating = 5.0\nId = 25500 , Rating = 6.5\nId = 25501 , Rating = 9.0\nId = 25502 , Rating = 10.0\nId = 25503 , Rating = 6.0\nId = 25504 , Rating = 5.0\nId = 25505 , Rating = 6.0\nId = 25508 , Rating = 6.0\nId = 25509 , Rating = 8.0\nId = 25510 , Rating = 6.5\nId = 25511 , Rating = 4.0\nId = 25512 , Rating = 2.0\nId = 25514 , Rating = 9.5\nId = 25515 , Rating = 9.0\nId = 25516 , Rating = 6.0\nId = 25518 , Rating = 4.5\nId = 25519 , Rating = 2.0\nId = 25521 , Rating = 9.0\nId = 25522 , Rating = 5.5\nId = 25523 , Rating = 8.5\nId = 25524 , Rating = 5.5\nId = 25525 , Rating = 1.0\nId = 25526 , Rating = 2.0\nId = 25528 , Rating = 9.5\nId = 25529 , Rating = 6.0\nId = 25531 , Rating = 3.0\nId = 25533 , Rating = 2.5\nId = 25534 , Rating = 3.0\nId = 25535 , Rating = 8.5\nId = 25536 , Rating = 5.5\nId = 25537 , Rating = 3.5\nId = 25538 , Rating = 4.5\nId = 25539 , Rating = 8.5\nId = 25540 , Rating = 8.5\nId = 25541 , Rating = 1.0\nId = 25542 , Rating = 9.0\nId = 25544 , Rating = 6.5\nId = 25545 , Rating = 10.0\nId = 25546 , Rating = 9.0\nId = 25547 , Rating = 6.0\nId = 25549 , Rating = 10.0\nId = 25550 , Rating = 2.0\nId = 25551 , Rating = 9.0\nId = 25552 , Rating = 5.5\nId = 25554 , Rating = 10.0\nId = 25555 , Rating = 5.0\nId = 25556 , Rating = 9.5\nId = 25557 , Rating = 1.5\nId = 25558 , Rating = 6.5\nId = 25559 , Rating = 9.5\nId = 25560 , Rating = 6.0\nId = 25561 , Rating = 9.0\nId = 25562 , Rating = 8.5\nId = 25563 , Rating = 6.5\nId = 25564 , Rating = 5.5\nId = 25565 , Rating = 2.5\nId = 25566 , Rating = 6.5\nId = 25567 , Rating = 9.0\nId = 25568 , Rating = 9.0\nId = 25569 , Rating = 6.5\nId = 25570 , Rating = 8.0\nId = 25571 , Rating = 5.5\nId = 25572 , Rating = 5.0\nId = 25573 , Rating = 6.0\nId = 25574 , Rating = 5.0\nId = 25575 , Rating = 5.0\nId = 25576 , Rating = 9.0\nId = 25577 , Rating = 9.5\nId = 25578 , Rating = 6.5\nId = 25579 , Rating = 5.5\nId = 25580 , Rating = 6.0\nId = 25581 , Rating = 9.0\nId = 25582 , Rating = 5.0\nId = 25583 , Rating = 9.5\nId = 25584 , Rating = 10.0\nId = 25585 , Rating = 5.0\nId = 25586 , Rating = 5.5\nId = 25587 , Rating = 6.0\nId = 25588 , Rating = 4.5\nId = 25589 , Rating = 3.0\nId = 25590 , Rating = 6.0\nId = 25591 , Rating = 9.5\nId = 25592 , Rating = 9.5\nId = 25593 , Rating = 8.5\nId = 25594 , Rating = 9.0\nId = 25595 , Rating = 9.0\nId = 25596 , Rating = 8.5\nId = 25597 , Rating = 9.0\nId = 25598 , Rating = 8.5\nId = 25599 , Rating = 9.0\nId = 25600 , Rating = 7.5\nId = 25601 , Rating = 6.5\nId = 25602 , Rating = 9.0\nId = 25603 , Rating = 4.5\nId = 25604 , Rating = 8.5\nId = 25605 , Rating = 6.0\nId = 25606 , Rating = 9.0\nId = 25607 , Rating = 10.0\nId = 25608 , Rating = 6.5\nId = 25609 , Rating = 9.0\nId = 25610 , Rating = 9.5\nId = 25611 , Rating = 9.5\nId = 25612 , Rating = 5.5\nId = 25613 , Rating = 9.5\nId = 25614 , Rating = 6.0\nId = 25615 , Rating = 10.0\nId = 25616 , Rating = 10.0\nId = 25617 , Rating = 9.5\nId = 25618 , Rating = 6.5\nId = 25619 , Rating = 8.0\nId = 25620 , Rating = 9.0\nId = 25621 , Rating = 10.0\nId = 25622 , Rating = 5.5\nId = 25623 , Rating = 5.5\nId = 25624 , Rating = 9.5\nId = 25625 , Rating = 8.5\nId = 25626 , Rating = 9.0\nId = 25627 , Rating = 9.0\nId = 25628 , Rating = 4.5\nId = 25629 , Rating = 6.0\nId = 25630 , Rating = 9.0\nId = 25631 , Rating = 2.5\nId = 25632 , Rating = 9.0\nId = 25633 , Rating = 9.5\nId = 25634 , Rating = 5.5\nId = 25635 , Rating = 5.5\nId = 25636 , Rating = 3.0\nId = 25637 , Rating = 6.0\nId = 25638 , Rating = 4.0\nId = 25639 , Rating = 7.0\nId = 25640 , Rating = 6.0\nId = 25642 , Rating = 6.5\nId = 25643 , Rating = 7.5\nId = 25644 , Rating = 9.5\nId = 25645 , Rating = 5.0\nId = 25646 , Rating = 9.5\nId = 25647 , Rating = 6.0\nId = 25648 , Rating = 10.0\nId = 25649 , Rating = 6.0\nId = 25650 , Rating = 6.0\nId = 25651 , Rating = 6.0\nId = 25652 , Rating = 8.5\nId = 25653 , Rating = 10.0\nId = 25654 , Rating = 9.5\nId = 25655 , Rating = 10.0\nId = 25656 , Rating = 3.5\nId = 25657 , Rating = 8.0\nId = 25658 , Rating = 9.5\nId = 25659 , Rating = 8.5\nId = 25660 , Rating = 6.0\nId = 25661 , Rating = 4.5\nId = 25662 , Rating = 9.5\nId = 25663 , Rating = 9.5\nId = 25664 , Rating = 6.0\nId = 25665 , Rating = 6.5\nId = 25666 , Rating = 10.0\nId = 25667 , Rating = 9.0\nId = 25668 , Rating = 9.5\nId = 25669 , Rating = 5.0\nId = 25670 , Rating = 5.5\nId = 25671 , Rating = 10.0\nId = 25672 , Rating = 10.0\nId = 25673 , Rating = 8.0\nId = 25674 , Rating = 6.5\nId = 25675 , Rating = 9.5\nId = 25676 , Rating = 5.5\nId = 25677 , Rating = 9.5\nId = 25678 , Rating = 5.5\nId = 25679 , Rating = 5.0\nId = 25680 , Rating = 8.5\nId = 25681 , Rating = 5.0\nId = 25682 , Rating = 6.5\nId = 25683 , Rating = 9.0\nId = 25684 , Rating = 9.5\nId = 25685 , Rating = 10.0\nId = 25686 , Rating = 5.5\nId = 25687 , Rating = 3.5\nId = 25688 , Rating = 6.5\nId = 25689 , Rating = 5.5\nId = 25690 , Rating = 5.0\nId = 25691 , Rating = 9.0\nId = 25692 , Rating = 2.0\nId = 25694 , Rating = 6.0\nId = 25695 , Rating = 10.0\nId = 25696 , Rating = 6.5\nId = 25697 , Rating = 8.5\nId = 25698 , Rating = 6.5\nId = 25699 , Rating = 3.0\nId = 25700 , Rating = 9.0\nId = 25701 , Rating = 5.5\nId = 25703 , Rating = 6.0\nId = 25704 , Rating = 8.0\nId = 25705 , Rating = 10.0\nId = 25706 , Rating = 9.0\nId = 25707 , Rating = 9.5\nId = 25708 , Rating = 6.0\nId = 25709 , Rating = 6.5\nId = 25710 , Rating = 6.5\nId = 25711 , Rating = 5.0\nId = 25712 , Rating = 6.0\nId = 25713 , Rating = 8.0\nId = 25714 , Rating = 9.5\nId = 25715 , Rating = 10.0\nId = 25716 , Rating = 10.0\nId = 25717 , Rating = 5.0\nId = 25718 , Rating = 9.5\nId = 25719 , Rating = 9.0\nId = 25720 , Rating = 5.5\nId = 25721 , Rating = 9.0\nId = 25722 , Rating = 3.0\nId = 25723 , Rating = 9.5\nId = 25725 , Rating = 3.5\nId = 25726 , Rating = 3.5\nId = 25727 , Rating = 6.0\nId = 25728 , Rating = 9.0\nId = 25729 , Rating = 6.0\nId = 25730 , Rating = 9.5\nId = 25731 , Rating = 9.5\nId = 25732 , Rating = 5.5\nId = 25733 , Rating = 6.0\nId = 25734 , Rating = 2.5\nId = 25735 , Rating = 4.0\nId = 25736 , Rating = 8.0\nId = 25737 , Rating = 8.5\nId = 25738 , Rating = 5.0\nId = 25739 , Rating = 8.0\nId = 25740 , Rating = 9.0\nId = 25741 , Rating = 5.5\nId = 25742 , Rating = 9.0\nId = 25743 , Rating = 6.5\nId = 25744 , Rating = 3.0\nId = 25745 , Rating = 9.5\nId = 25746 , Rating = 6.5\nId = 25747 , Rating = 5.5\nId = 25748 , Rating = 8.5\nId = 25749 , Rating = 9.5\nId = 25750 , Rating = 9.5\nId = 25751 , Rating = 9.5\nId = 25752 , Rating = 9.5\nId = 25753 , Rating = 6.5\nId = 25754 , Rating = 9.5\nId = 25755 , Rating = 6.0\nId = 25756 , Rating = 1.5\nId = 25757 , Rating = 9.5\nId = 25759 , Rating = 6.5\nId = 25760 , Rating = 6.5\nId = 25761 , Rating = 5.0\nId = 25762 , Rating = 10.0\nId = 25763 , Rating = 9.5\nId = 25764 , Rating = 9.5\nId = 25765 , Rating = 7.0\nId = 25766 , Rating = 6.0\nId = 25767 , Rating = 7.5\nId = 25769 , Rating = 6.0\nId = 25770 , Rating = 7.5\nId = 25771 , Rating = 5.5\nId = 25772 , Rating = 10.0\nId = 25773 , Rating = 2.5\nId = 25774 , Rating = 7.5\nId = 25775 , Rating = 5.5\nId = 25776 , Rating = 8.5\nId = 25777 , Rating = 6.0\nId = 25778 , Rating = 10.0\nId = 25779 , Rating = 9.5\nId = 25780 , Rating = 8.0\nId = 25781 , Rating = 6.5\nId = 25782 , Rating = 10.0\nId = 25783 , Rating = 6.5\nId = 25784 , Rating = 6.0\nId = 25785 , Rating = 9.0\nId = 25786 , Rating = 6.5\nId = 25787 , Rating = 6.0\nId = 25788 , Rating = 6.0\nId = 25789 , Rating = 9.0\nId = 25790 , Rating = 10.0\nId = 25791 , Rating = 4.5\nId = 25792 , Rating = 3.5\nId = 25793 , Rating = 6.5\nId = 25794 , Rating = 5.5\nId = 25795 , Rating = 5.5\nId = 25796 , Rating = 10.0\nId = 25797 , Rating = 9.5\nId = 25798 , Rating = 5.0\nId = 25799 , Rating = 5.5\nId = 25800 , Rating = 9.5\nId = 25801 , Rating = 6.5\nId = 25802 , Rating = 6.5\nId = 25803 , Rating = 10.0\nId = 25804 , Rating = 9.0\nId = 25805 , Rating = 8.0\nId = 25806 , Rating = 8.5\nId = 25807 , Rating = 6.0\nId = 25808 , Rating = 10.0\nId = 25809 , Rating = 9.5\nId = 25810 , Rating = 5.0\nId = 25811 , Rating = 10.0\nId = 25812 , Rating = 10.0\nId = 25813 , Rating = 5.5\nId = 25814 , Rating = 10.0\nId = 25815 , Rating = 9.5\nId = 25816 , Rating = 6.0\nId = 25817 , Rating = 6.0\nId = 25818 , Rating = 8.5\nId = 25819 , Rating = 5.5\nId = 26180 , Rating = 6.5\nId = 26181 , Rating = 10.0\nId = 26182 , Rating = 6.0\nId = 26183 , Rating = 9.5\nId = 26184 , Rating = 5.5\nId = 26185 , Rating = 6.0\nId = 28365 , Rating = 9.5\nId = 28391 , Rating = 10.0\nId = 28423 , Rating = 10.0\nId = 28432 , Rating = 1.0\nId = 28438 , Rating = 10.0\nId = 28449 , Rating = 8.5\nId = 28482 , Rating = 6.5\nId = 28493 , Rating = 8.0\nId = 28494 , Rating = 9.5\nId = 28522 , Rating = 5.5\nId = 28552 , Rating = 6.0\nId = 28589 , Rating = 8.5\nId = 28597 , Rating = 10.0\nId = 28630 , Rating = 10.0\nId = 28656 , Rating = 6.0\nId = 28657 , Rating = 9.5\nId = 28661 , Rating = 10.0\nId = 28671 , Rating = 8.5\nId = 28672 , Rating = 9.5\nId = 28674 , Rating = 8.5\nId = 28680 , Rating = 8.0\nId = 28682 , Rating = 10.0\nId = 28684 , Rating = 9.0\nId = 28685 , Rating = 8.5\nId = 28971 , Rating = 2.0\nId = 28972 , Rating = 3.5\nId = 28973 , Rating = 10.0\nId = 28974 , Rating = 2.0\nId = 28975 , Rating = 10.0\nId = 28976 , Rating = 1.5\nId = 28977 , Rating = 1.5\nId = 28978 , Rating = 9.0\nId = 28979 , Rating = 5.0\nId = 28980 , Rating = 2.0\nId = 28981 , Rating = 9.5\nId = 28983 , Rating = 8.5\nId = 28984 , Rating = 5.0\nId = 28985 , Rating = 5.0\nId = 28986 , Rating = 9.0\nId = 28987 , Rating = 9.5\nId = 28991 , Rating = 9.0\nId = 28992 , Rating = 2.0\nId = 28993 , Rating = 6.0\nId = 28994 , Rating = 2.0\nId = 28995 , Rating = 6.5\nId = 28996 , Rating = 6.0\nId = 28997 , Rating = 7.0\nId = 28998 , Rating = 5.5\nId = 28999 , Rating = 8.0\nId = 29000 , Rating = 5.5\nId = 29001 , Rating = 8.0\nId = 29002 , Rating = 4.5\nId = 29003 , Rating = 2.5\nId = 29004 , Rating = 2.5\nId = 29005 , Rating = 2.0\nId = 29006 , Rating = 9.0\nId = 29007 , Rating = 9.0\nId = 29008 , Rating = 6.5\nId = 29009 , Rating = 3.0\nId = 29010 , Rating = 4.0\nId = 29011 , Rating = 3.5\nId = 29012 , Rating = 6.5\nId = 29013 , Rating = 10.0\nId = 29014 , Rating = 9.0\nId = 29015 , Rating = 6.0\nId = 29016 , Rating = 5.0\nId = 29017 , Rating = 4.5\nId = 29018 , Rating = 8.0\nId = 29019 , Rating = 9.0\nId = 29020 , Rating = 6.5\nId = 29021 , Rating = 6.0\nId = 29022 , Rating = 8.5\nId = 29023 , Rating = 9.0\nId = 29024 , Rating = 9.0\nId = 29025 , Rating = 6.5\nId = 29026 , Rating = 10.0\nId = 29027 , Rating = 6.5\nId = 29028 , Rating = 9.0\nId = 29029 , Rating = 9.5\nId = 29030 , Rating = 9.0\nId = 29031 , Rating = 5.5\nId = 29032 , Rating = 2.5\nId = 29033 , Rating = 8.5\nId = 29034 , Rating = 4.5\nId = 29035 , Rating = 6.5\nId = 29036 , Rating = 5.0\nId = 29037 , Rating = 4.5\nId = 29038 , Rating = 4.5\nId = 29039 , Rating = 9.5\nId = 29040 , Rating = 6.5\nId = 29041 , Rating = 6.0\nId = 29042 , Rating = 9.5\nId = 29043 , Rating = 5.0\nId = 29044 , Rating = 6.0\nId = 29045 , Rating = 3.5\nId = 29046 , Rating = 9.5\nId = 29047 , Rating = 6.5\nId = 29048 , Rating = 9.0\nId = 29049 , Rating = 5.0\nId = 29050 , Rating = 5.5\nId = 29051 , Rating = 3.5\nId = 29052 , Rating = 6.5\nId = 29053 , Rating = 1.5\nId = 29054 , Rating = 9.0\nId = 29055 , Rating = 4.0\nId = 29056 , Rating = 5.0\nId = 29057 , Rating = 9.5\nId = 29058 , Rating = 4.5\nId = 29059 , Rating = 6.5\nId = 29060 , Rating = 6.0\nId = 29061 , Rating = 9.5\nId = 29062 , Rating = 2.5\nId = 29063 , Rating = 9.5\nId = 29064 , Rating = 5.0\nId = 29065 , Rating = 5.5\nId = 29066 , Rating = 6.5\nId = 29067 , Rating = 6.0\nId = 29068 , Rating = 8.5\nId = 29069 , Rating = 5.5\nId = 29070 , Rating = 5.0\nId = 29071 , Rating = 10.0\nId = 29072 , Rating = 10.0\nId = 29073 , Rating = 5.5\nId = 29075 , Rating = 5.5\nId = 29076 , Rating = 10.0\nId = 29077 , Rating = 2.0\nId = 29078 , Rating = 7.0\nId = 29079 , Rating = 6.5\nId = 29080 , Rating = 9.5\nId = 29081 , Rating = 4.5\nId = 29082 , Rating = 6.0\nId = 29083 , Rating = 2.5\nId = 29084 , Rating = 5.5\nId = 29085 , Rating = 9.5\nId = 29086 , Rating = 1.5\nId = 29087 , Rating = 6.0\nId = 29088 , Rating = 8.0\nId = 29090 , Rating = 9.5\nId = 29091 , Rating = 10.0\nId = 29092 , Rating = 6.0\nId = 29093 , Rating = 9.0\nId = 29094 , Rating = 9.5\nId = 29095 , Rating = 9.5\nId = 29096 , Rating = 7.0\nId = 29097 , Rating = 9.5\nId = 29098 , Rating = 4.5\nId = 29099 , Rating = 8.0\nId = 29100 , Rating = 6.5\nId = 29101 , Rating = 5.0\nId = 29102 , Rating = 6.5\nId = 29103 , Rating = 3.5\nId = 29104 , Rating = 8.0\nId = 29105 , Rating = 5.5\nId = 29106 , Rating = 3.0\nId = 29108 , Rating = 1.5\nId = 29109 , Rating = 9.0\nId = 29110 , Rating = 8.5\nId = 29111 , Rating = 2.0\nId = 29112 , Rating = 8.5\nId = 29113 , Rating = 4.0\nId = 29114 , Rating = 6.0\nId = 29115 , Rating = 10.0\nId = 29116 , Rating = 10.0\nId = 29117 , Rating = 10.0\nId = 29118 , Rating = 9.0\nId = 29119 , Rating = 6.5\nId = 29120 , Rating = 6.5\nId = 29121 , Rating = 9.0\nId = 29122 , Rating = 8.0\nId = 29123 , Rating = 3.5\nId = 29124 , Rating = 6.0\nId = 29125 , Rating = 4.5\nId = 29126 , Rating = 5.5\nId = 29127 , Rating = 9.0\nId = 29128 , Rating = 9.5\nId = 29129 , Rating = 5.0\nId = 29130 , Rating = 4.0\nId = 29131 , Rating = 9.0\nId = 29133 , Rating = 9.0\nId = 29134 , Rating = 6.0\nId = 29135 , Rating = 4.5\nId = 29137 , Rating = 6.0\nId = 29138 , Rating = 8.5\nId = 29139 , Rating = 7.5\nId = 29140 , Rating = 9.5\nId = 29141 , Rating = 5.5\nId = 29142 , Rating = 9.0\nId = 29143 , Rating = 7.5\nId = 29144 , Rating = 9.0\nId = 29145 , Rating = 7.5\nId = 29146 , Rating = 4.5\nId = 29147 , Rating = 6.0\nId = 29148 , Rating = 3.0\nId = 29149 , Rating = 6.5\nId = 29150 , Rating = 9.0\nId = 29151 , Rating = 2.0\nId = 29152 , Rating = 2.5\nId = 29153 , Rating = 3.0\nId = 29154 , Rating = 10.0\nId = 29155 , Rating = 2.0\nId = 29156 , Rating = 5.5\nId = 29157 , Rating = 6.5\nId = 29158 , Rating = 10.0\nId = 29159 , Rating = 9.0\nId = 29160 , Rating = 2.0\nId = 29161 , Rating = 8.5\nId = 29162 , Rating = 4.5\nId = 29163 , Rating = 6.0\nId = 29164 , Rating = 9.5\nId = 29165 , Rating = 9.5\nId = 29166 , Rating = 6.0\nId = 29168 , Rating = 10.0\nId = 29169 , Rating = 10.0\nId = 29170 , Rating = 3.5\nId = 30498 , Rating = 8.0\nId = 30503 , Rating = 9.5\nId = 30504 , Rating = 10.0\nId = 31587 , Rating = 2.0\nId = 31588 , Rating = 9.5\nId = 31601 , Rating = 6.5\nId = 31603 , Rating = 9.5\nId = 31620 , Rating = 9.0\nId = 31623 , Rating = 9.5\nId = 31624 , Rating = 6.5\nId = 31628 , Rating = 6.0\nId = 31636 , Rating = 8.0\nId = 31669 , Rating = 6.5\nId = 31694 , Rating = 8.0\nId = 31734 , Rating = 8.5\nId = 31756 , Rating = 6.0\nId = 31758 , Rating = 10.0\nId = 31765 , Rating = 9.5\nId = 31780 , Rating = 6.5\nId = 36977 , Rating = 1.0\nId = 36978 , Rating = 5.0\nId = 36979 , Rating = 8.5\nId = 36980 , Rating = 8.5\nId = 36981 , Rating = 6.0\nId = 36982 , Rating = 2.0\nId = 36983 , Rating = 5.5\nId = 36984 , Rating = 6.5\nId = 36985 , Rating = 6.5\nId = 36986 , Rating = 4.5\nId = 36987 , Rating = 9.5\nId = 36988 , Rating = 9.0\nId = 36990 , Rating = 10.0\nId = 36991 , Rating = 5.5\nId = 36992 , Rating = 10.0\nId = 36993 , Rating = 10.0\nId = 36994 , Rating = 9.5\nId = 36995 , Rating = 5.0\nId = 36996 , Rating = 6.5\nId = 36997 , Rating = 8.0\nId = 36999 , Rating = 9.0\nId = 37000 , Rating = 3.5\nId = 37001 , Rating = 9.5\nId = 37002 , Rating = 9.0\nId = 37003 , Rating = 5.5\nId = 37004 , Rating = 7.5\nId = 37005 , Rating = 9.0\nId = 37006 , Rating = 4.5\nId = 37007 , Rating = 9.5\nId = 37008 , Rating = 6.0\nId = 37010 , Rating = 7.5\nId = 37012 , Rating = 9.0\nId = 37013 , Rating = 4.5\nId = 37014 , Rating = 6.5\nId = 37015 , Rating = 6.5\nId = 37016 , Rating = 8.0\nId = 37018 , Rating = 8.5\nId = 37019 , Rating = 6.5\nId = 37020 , Rating = 6.5\nId = 37022 , Rating = 9.0\nId = 37023 , Rating = 9.0\nId = 37024 , Rating = 6.5\nId = 37025 , Rating = 9.5\nId = 37028 , Rating = 9.5\nId = 37030 , Rating = 9.5\nId = 37031 , Rating = 7.0\nId = 37034 , Rating = 3.5\nId = 37035 , Rating = 4.5\nId = 37036 , Rating = 9.0\nId = 37037 , Rating = 8.5\nId = 37038 , Rating = 6.5\nId = 37040 , Rating = 6.5\nId = 37042 , Rating = 5.0\nId = 37044 , Rating = 5.0\nId = 37046 , Rating = 6.5\nId = 37047 , Rating = 5.0\nId = 37048 , Rating = 6.5\nId = 37049 , Rating = 5.5\nId = 37050 , Rating = 5.5\nId = 37051 , Rating = 6.5\nId = 37052 , Rating = 1.5\nId = 40628 , Rating = 5.0\nId = 40632 , Rating = 5.5\nId = 40634 , Rating = 6.5\nId = 41768 , Rating = 5.5\nId = 41769 , Rating = 5.5\nId = 41770 , Rating = 5.5\nId = 41771 , Rating = 10.0\nId = 41772 , Rating = 4.0\nId = 41773 , Rating = 9.0\nId = 41774 , Rating = 9.0\nId = 41775 , Rating = 5.5\nId = 41776 , Rating = 2.0\nId = 41777 , Rating = 9.5\nId = 41778 , Rating = 4.5\nId = 41779 , Rating = 8.5\nId = 41780 , Rating = 9.0\nId = 41781 , Rating = 2.5\nId = 41782 , Rating = 1.5\nId = 41783 , Rating = 6.0\nId = 41784 , Rating = 8.5\nId = 41786 , Rating = 6.0\nId = 41787 , Rating = 10.0\nId = 41788 , Rating = 8.0\nId = 41789 , Rating = 10.0\nId = 41790 , Rating = 6.5\nId = 41791 , Rating = 1.5\nId = 41792 , Rating = 1.0\nId = 41793 , Rating = 5.0\nId = 41794 , Rating = 10.0\nId = 41795 , Rating = 5.5\nId = 41796 , Rating = 9.0\nId = 41797 , Rating = 3.5\nId = 41798 , Rating = 7.0\nId = 41799 , Rating = 9.0\nId = 41800 , Rating = 6.0\nId = 41801 , Rating = 2.0\nId = 41802 , Rating = 5.5\nId = 41803 , Rating = 6.0\nId = 41804 , Rating = 3.0\nId = 41805 , Rating = 2.5\nId = 41806 , Rating = 10.0\nId = 41807 , Rating = 5.0\nId = 41808 , Rating = 4.0\nId = 47919 , Rating = 4.5\nId = 48886 , Rating = 6.0\nId = 48887 , Rating = 9.0\nId = 48888 , Rating = 10.0\nId = 48889 , Rating = 8.5\nId = 48890 , Rating = 6.5\nId = 48891 , Rating = 9.0\nId = 48892 , Rating = 6.0\nId = 51077 , Rating = 9.0\nId = 51083 , Rating = 9.5\nId = 51085 , Rating = 9.5\nId = 51088 , Rating = 3.0\nId = 53753 , Rating = 5.5\nId = 53754 , Rating = 8.5\nId = 53755 , Rating = 9.0\nId = 53756 , Rating = 10.0\nId = 53757 , Rating = 6.5\nId = 53758 , Rating = 6.5\nId = 53759 , Rating = 6.5\nId = 53760 , Rating = 10.0\nId = 53761 , Rating = 6.5\nId = 53762 , Rating = 5.5\nId = 53763 , Rating = 9.0\nId = 53764 , Rating = 9.5\nId = 53765 , Rating = 1.5\nId = 53766 , Rating = 9.5\nId = 53767 , Rating = 9.5\nId = 53768 , Rating = 9.0\nId = 53769 , Rating = 5.5\nId = 53770 , Rating = 4.0\nId = 53771 , Rating = 6.5\nId = 53772 , Rating = 6.5\nId = 53773 , Rating = 9.5\nId = 53774 , Rating = 9.0\nId = 53775 , Rating = 10.0\nId = 53776 , Rating = 5.0\nId = 53777 , Rating = 7.0\nId = 53778 , Rating = 4.5\nId = 53779 , Rating = 10.0\nId = 53780 , Rating = 5.5\nId = 53781 , Rating = 4.0\nId = 53782 , Rating = 9.0\nId = 53783 , Rating = 6.5\nId = 53784 , Rating = 6.0\nId = 53785 , Rating = 6.0\nId = 53786 , Rating = 6.0\nId = 53788 , Rating = 6.0\nId = 53789 , Rating = 6.5\nId = 53790 , Rating = 5.5\nId = 53791 , Rating = 3.0\nId = 53792 , Rating = 8.5\nId = 53793 , Rating = 8.0\nId = 53794 , Rating = 6.5\nId = 53795 , Rating = 9.5\nId = 53796 , Rating = 8.5\nId = 53797 , Rating = 5.5\nId = 53798 , Rating = 9.0\nId = 60439 , Rating = 4.5\nId = 60440 , Rating = 6.0\nId = 60441 , Rating = 10.0\nId = 60442 , Rating = 8.5\nId = 60443 , Rating = 5.5\nId = 60444 , Rating = 6.5\nId = 60445 , Rating = 5.0\nId = 60446 , Rating = 6.0\nId = 60447 , Rating = 4.0\nId = 60448 , Rating = 6.5\nId = 60449 , Rating = 6.5\nId = 60450 , Rating = 8.0\nId = 60451 , Rating = 5.5\nId = 60453 , Rating = 10.0\nId = 60454 , Rating = 2.0\nId = 60455 , Rating = 6.5\nId = 60456 , Rating = 6.5\nId = 60457 , Rating = 1.0\nId = 60458 , Rating = 9.5\nId = 60459 , Rating = 8.5\nId = 60460 , Rating = 9.0\nId = 60462 , Rating = 6.0\nId = 60464 , Rating = 9.5\nId = 60465 , Rating = 10.0\nId = 60466 , Rating = 10.0\nId = 60467 , Rating = 6.0\nId = 60468 , Rating = 2.0\nId = 60470 , Rating = 9.0\nId = 60471 , Rating = 6.5\nId = 60473 , Rating = 9.0\nId = 60475 , Rating = 5.0\nId = 60476 , Rating = 9.5\nId = 60477 , Rating = 6.0\nId = 60478 , Rating = 6.0\nId = 60479 , Rating = 6.0\nId = 60480 , Rating = 3.0\nId = 60481 , Rating = 10.0\nId = 60482 , Rating = 5.5\nId = 60483 , Rating = 8.5\nId = 60484 , Rating = 5.0\nId = 60485 , Rating = 6.5\nId = 60487 , Rating = 10.0\nId = 60489 , Rating = 8.0\nId = 60490 , Rating = 5.5\nId = 60491 , Rating = 9.5\nId = 60492 , Rating = 3.5\nId = 60493 , Rating = 6.5\nId = 60494 , Rating = 6.0\nId = 60497 , Rating = 5.5\nId = 60499 , Rating = 9.0\nId = 60500 , Rating = 8.0\nId = 60501 , Rating = 9.5\nId = 60502 , Rating = 9.5\nId = 60504 , Rating = 6.5\nId = 60505 , Rating = 9.0\nId = 60506 , Rating = 6.0\nId = 60509 , Rating = 9.5\nId = 60510 , Rating = 10.0\nId = 60512 , Rating = 6.5\nId = 60513 , Rating = 9.5\nId = 60514 , Rating = 10.0\nId = 60515 , Rating = 5.0\nId = 60516 , Rating = 6.5\nId = 60518 , Rating = 8.5\nId = 60520 , Rating = 6.5\nId = 60521 , Rating = 9.0\nId = 60522 , Rating = 3.5\nId = 60523 , Rating = 6.0\nId = 60524 , Rating = 6.5\nId = 60525 , Rating = 4.5\nId = 60526 , Rating = 6.5\nId = 60527 , Rating = 9.5\nId = 60528 , Rating = 4.5\nId = 60529 , Rating = 9.0\nId = 60530 , Rating = 10.0\nId = 60531 , Rating = 5.0\nId = 60532 , Rating = 9.0\nId = 60533 , Rating = 5.5\nId = 60534 , Rating = 9.0\nId = 60535 , Rating = 5.5\nId = 60536 , Rating = 10.0\nId = 60537 , Rating = 5.5\nId = 60538 , Rating = 6.0\nId = 60539 , Rating = 5.0\nId = 60540 , Rating = 6.5\nId = 60541 , Rating = 5.5\nId = 60542 , Rating = 8.0\nId = 60543 , Rating = 6.0\nId = 60546 , Rating = 4.5\nId = 60547 , Rating = 3.5\nId = 60548 , Rating = 9.5\nId = 60549 , Rating = 9.0\nId = 60550 , Rating = 9.0\nId = 60551 , Rating = 6.5\nId = 60552 , Rating = 5.0\nId = 60553 , Rating = 9.5\nId = 60555 , Rating = 9.0\nId = 60557 , Rating = 8.5\nId = 60559 , Rating = 6.5\nId = 60560 , Rating = 2.5\nId = 60561 , Rating = 9.5\nId = 60562 , Rating = 9.5\nId = 60563 , Rating = 6.5\nId = 60564 , Rating = 2.0\nId = 60565 , Rating = 6.0\nId = 60566 , Rating = 4.5\nId = 60567 , Rating = 9.0\nId = 60568 , Rating = 4.0\nId = 60570 , Rating = 5.0\nId = 60571 , Rating = 9.5\nId = 60572 , Rating = 6.5\nId = 60573 , Rating = 6.5\nId = 60575 , Rating = 9.5\nId = 60576 , Rating = 5.5\nId = 60577 , Rating = 9.5\nId = 60578 , Rating = 8.5\nId = 60579 , Rating = 1.0\nId = 60580 , Rating = 6.5\nId = 60581 , Rating = 6.0\nId = 60582 , Rating = 5.5\nId = 60583 , Rating = 6.5\nId = 60584 , Rating = 5.5\nId = 60585 , Rating = 6.0\nId = 60586 , Rating = 4.5\nId = 60587 , Rating = 6.5\nId = 60588 , Rating = 5.5\nId = 60589 , Rating = 9.0\nId = 60590 , Rating = 10.0\nId = 60591 , Rating = 6.5\nId = 60592 , Rating = 9.5\nId = 60593 , Rating = 9.0\nId = 60595 , Rating = 5.5\nId = 60596 , Rating = 9.5\nId = 60598 , Rating = 5.5\nId = 60599 , Rating = 5.0\nId = 60600 , Rating = 6.5\nId = 60602 , Rating = 8.0\nId = 60623 , Rating = 6.5\nId = 60625 , Rating = 8.5\nId = 60626 , Rating = 8.5\nId = 60627 , Rating = 8.5\nId = 60628 , Rating = 9.5\nId = 60630 , Rating = 10.0\nId = 60631 , Rating = 8.5\nId = 60645 , Rating = 6.5\nId = 60646 , Rating = 6.0\nId = 60647 , Rating = 6.0\nId = 60648 , Rating = 6.5\nId = 60649 , Rating = 5.5\nId = 60650 , Rating = 6.5\nId = 60651 , Rating = 6.5\nId = 60652 , Rating = 9.0\nId = 60653 , Rating = 10.0\nId = 60654 , Rating = 6.5\nId = 60655 , Rating = 5.5\nId = 60656 , Rating = 9.5\nId = 60657 , Rating = 9.0\nId = 60658 , Rating = 6.5\nId = 60659 , Rating = 5.5\nId = 60660 , Rating = 6.5\nId = 65194 , Rating = 3.0\nId = 65196 , Rating = 6.0\nId = 65197 , Rating = 10.0\nId = 65198 , Rating = 6.5\nId = 65199 , Rating = 2.5\nId = 65200 , Rating = 5.0\nId = 65201 , Rating = 2.0\nId = 65202 , Rating = 1.5\nId = 65203 , Rating = 9.0\nId = 65204 , Rating = 5.0\nId = 65205 , Rating = 2.0\nId = 65206 , Rating = 1.5\nId = 65207 , Rating = 1.5\nId = 65208 , Rating = 1.0\nId = 65209 , Rating = 1.5\nId = 65210 , Rating = 1.5\nId = 65211 , Rating = 8.5\nId = 65212 , Rating = 4.5\nId = 65213 , Rating = 6.5\nId = 65214 , Rating = 4.0\nId = 65217 , Rating = 6.5\nId = 65218 , Rating = 6.5\nId = 65219 , Rating = 8.0\nId = 65220 , Rating = 5.0\nId = 65221 , Rating = 9.0\nId = 65222 , Rating = 9.5\nId = 65223 , Rating = 7.5\nId = 65225 , Rating = 6.5\nId = 65226 , Rating = 4.0\nId = 65227 , Rating = 10.0\nId = 65228 , Rating = 1.0\nId = 65237 , Rating = 6.5\nId = 65238 , Rating = 9.5\nId = 65239 , Rating = 2.0\nId = 65240 , Rating = 2.0\nId = 65241 , Rating = 3.0\nId = 65242 , Rating = 2.0\nId = 65243 , Rating = 7.5\nId = 65244 , Rating = 8.0\nId = 65245 , Rating = 2.5\nId = 65246 , Rating = 3.0\nId = 65247 , Rating = 8.5\nId = 65248 , Rating = 10.0\nId = 65249 , Rating = 6.5\nId = 65250 , Rating = 6.5\nId = 65251 , Rating = 1.5\nId = 65252 , Rating = 8.0\nId = 65253 , Rating = 6.5\nId = 65254 , Rating = 2.0\nId = 65256 , Rating = 4.5\nId = 65257 , Rating = 5.5\nId = 65258 , Rating = 3.0\nId = 65259 , Rating = 6.5\nId = 65260 , Rating = 5.0\nId = 65261 , Rating = 1.0\nId = 65262 , Rating = 1.0\nId = 65263 , Rating = 2.0\nId = 65264 , Rating = 2.5\nId = 65265 , Rating = 8.0\nId = 65266 , Rating = 9.0\nId = 65267 , Rating = 9.0\nId = 65268 , Rating = 6.5\nId = 65269 , Rating = 6.0\nId = 65270 , Rating = 8.5\nId = 65271 , Rating = 6.5\nId = 65272 , Rating = 3.0\nId = 65273 , Rating = 4.5\nId = 65274 , Rating = 10.0\nId = 65275 , Rating = 7.0\nId = 65276 , Rating = 8.5\nId = 65277 , Rating = 8.5\nId = 65278 , Rating = 9.0\nId = 65279 , Rating = 9.5\nId = 65280 , Rating = 2.0\nId = 65281 , Rating = 5.0\nId = 65282 , Rating = 6.0\nId = 65283 , Rating = 1.5\nId = 65284 , Rating = 9.5\nId = 65285 , Rating = 5.0\nId = 65286 , Rating = 9.5\nId = 65287 , Rating = 9.0\nId = 65288 , Rating = 9.5\nId = 65289 , Rating = 9.5\nId = 65290 , Rating = 6.0\nId = 65291 , Rating = 9.0\nId = 65292 , Rating = 9.0\nId = 65293 , Rating = 10.0\nId = 65294 , Rating = 10.0\nId = 65295 , Rating = 9.0\nId = 65296 , Rating = 2.5\nId = 65297 , Rating = 5.0\nId = 65298 , Rating = 6.0\nId = 65299 , Rating = 3.0\nId = 65300 , Rating = 2.0\nId = 65301 , Rating = 8.5\nId = 65302 , Rating = 9.5\nId = 65303 , Rating = 9.0\nId = 65304 , Rating = 6.0\nId = 65305 , Rating = 9.5\nId = 65306 , Rating = 5.0\nId = 65308 , Rating = 6.0\nId = 65309 , Rating = 9.5\nId = 65310 , Rating = 5.0\nId = 65311 , Rating = 2.0\nId = 65312 , Rating = 9.5\nId = 65313 , Rating = 6.0\nId = 65314 , Rating = 4.0\nId = 65315 , Rating = 9.5\nId = 65316 , Rating = 3.5\nId = 65318 , Rating = 8.5\nId = 65319 , Rating = 5.5\nId = 65320 , Rating = 9.0\nId = 65321 , Rating = 5.5\nId = 65322 , Rating = 2.5\nId = 65323 , Rating = 9.5\nId = 65324 , Rating = 9.0\nId = 65325 , Rating = 5.0\nId = 65326 , Rating = 2.0\nId = 65327 , Rating = 3.0\nId = 71069 , Rating = 9.5\nId = 71070 , Rating = 9.0\nId = 71071 , Rating = 6.5\nId = 71072 , Rating = 9.5\nId = 71073 , Rating = 4.5\nId = 71074 , Rating = 9.5\nId = 71075 , Rating = 6.5\nId = 71076 , Rating = 5.0\nId = 71077 , Rating = 9.5\nId = 71078 , Rating = 5.5\nId = 71079 , Rating = 2.0\nId = 71080 , Rating = 9.5\nId = 71081 , Rating = 5.5\nId = 71082 , Rating = 5.5\nId = 71083 , Rating = 9.0\nId = 71084 , Rating = 10.0\nId = 71085 , Rating = 9.5\nId = 71086 , Rating = 6.0\nId = 71088 , Rating = 5.0\nId = 71090 , Rating = 6.0\nId = 71091 , Rating = 6.0\nId = 71092 , Rating = 9.5\nId = 71093 , Rating = 9.5\nId = 71094 , Rating = 6.5\nId = 71095 , Rating = 5.0\nId = 71096 , Rating = 3.5\nId = 71097 , Rating = 6.0\nId = 71099 , Rating = 10.0\nId = 71100 , Rating = 9.0\nId = 71102 , Rating = 6.5\nId = 71103 , Rating = 8.0\nId = 71105 , Rating = 6.0\nId = 71106 , Rating = 9.5\nId = 71107 , Rating = 8.5\nId = 71108 , Rating = 9.5\nId = 71110 , Rating = 9.0\nId = 71112 , Rating = 9.5\nId = 71114 , Rating = 6.5\nId = 71117 , Rating = 6.5\nId = 71118 , Rating = 9.5\nId = 71119 , Rating = 9.5\nId = 71120 , Rating = 9.5\nId = 71121 , Rating = 6.5\nId = 71122 , Rating = 10.0\nId = 71123 , Rating = 9.0\nId = 71124 , Rating = 6.0\nId = 71125 , Rating = 9.5\nId = 71126 , Rating = 5.0\nId = 71127 , Rating = 6.0\nId = 72504 , Rating = 1.5\nId = 72505 , Rating = 6.0\nId = 72506 , Rating = 9.0\nId = 72507 , Rating = 1.0\nId = 72508 , Rating = 2.0\nId = 72509 , Rating = 1.5\nId = 72510 , Rating = 2.5\nId = 72511 , Rating = 1.0\nId = 72512 , Rating = 1.0\nId = 72513 , Rating = 1.5\nId = 72514 , Rating = 9.0\nId = 72515 , Rating = 6.5\nId = 72516 , Rating = 2.0\nId = 72517 , Rating = 4.0\nId = 72518 , Rating = 7.0\nId = 72519 , Rating = 1.5\nId = 72520 , Rating = 8.5\nId = 72521 , Rating = 0.5\nId = 72522 , Rating = 1.5\nId = 72523 , Rating = 1.5\nId = 72524 , Rating = 2.0\nId = 72525 , Rating = 1.0\nId = 72526 , Rating = 8.0\nId = 72527 , Rating = 6.5\nId = 72528 , Rating = 2.0\nId = 72529 , Rating = 9.5\nId = 72530 , Rating = 6.5\nId = 72531 , Rating = 9.0\nId = 72532 , Rating = 3.5\nId = 72533 , Rating = 3.5\nId = 72534 , Rating = 1.5\nId = 72535 , Rating = 1.0\nId = 72537 , Rating = 9.0\nId = 72538 , Rating = 2.5\nId = 72539 , Rating = 9.0\nId = 72540 , Rating = 3.0\nId = 72541 , Rating = 4.0\nId = 72542 , Rating = 6.5\nId = 72543 , Rating = 8.5\nId = 72544 , Rating = 9.5\nId = 72545 , Rating = 2.5\nId = 72546 , Rating = 4.5\nId = 72547 , Rating = 3.0\nId = 72548 , Rating = 2.0\nId = 72549 , Rating = 9.5\nId = 72550 , Rating = 6.0\nId = 72551 , Rating = 2.0\nId = 72552 , Rating = 2.5\nId = 72553 , Rating = 2.0\nId = 72554 , Rating = 2.0\nId = 72555 , Rating = 1.0\nId = 72556 , Rating = 9.5\nId = 72557 , Rating = 4.5\nId = 72558 , Rating = 1.5\nId = 72559 , Rating = 1.5\nId = 72560 , Rating = 9.5\nId = 72561 , Rating = 6.0\nId = 72562 , Rating = 5.0\nId = 72563 , Rating = 8.0\nId = 72564 , Rating = 5.0\nId = 72565 , Rating = 5.0\nId = 72566 , Rating = 6.0\nId = 72567 , Rating = 7.0\nId = 72568 , Rating = 5.5\nId = 72569 , Rating = 6.5\nId = 72570 , Rating = 8.5\nId = 72571 , Rating = 2.5\nId = 72572 , Rating = 3.0\nId = 72573 , Rating = 5.0\nId = 72574 , Rating = 8.5\nId = 72575 , Rating = 6.0\nId = 72576 , Rating = 2.5\nId = 72577 , Rating = 9.5\nId = 72578 , Rating = 9.5\nId = 72579 , Rating = 2.0\nId = 72580 , Rating = 4.5\nId = 72581 , Rating = 2.0\nId = 72582 , Rating = 5.5\nId = 72583 , Rating = 9.5\nId = 72584 , Rating = 6.0\nId = 72585 , Rating = 6.0\nId = 72586 , Rating = 9.5\nId = 72587 , Rating = 1.5\nId = 72588 , Rating = 5.0\nId = 72589 , Rating = 3.0\nId = 72590 , Rating = 4.5\nId = 72591 , Rating = 3.0\nId = 72592 , Rating = 2.5\nId = 72593 , Rating = 4.5\nId = 72594 , Rating = 2.5\nId = 72595 , Rating = 1.5\nId = 72596 , Rating = 1.5\nId = 72597 , Rating = 2.0\nId = 72598 , Rating = 8.0\nId = 72599 , Rating = 5.5\nId = 72600 , Rating = 1.0\nId = 72601 , Rating = 5.0\nId = 72602 , Rating = 2.5\nId = 72603 , Rating = 8.5\nId = 72604 , Rating = 5.5\nId = 72605 , Rating = 8.5\nId = 72606 , Rating = 10.0\nId = 72607 , Rating = 5.5\nId = 72608 , Rating = 5.0\nId = 72609 , Rating = 6.5\nId = 72610 , Rating = 3.0\nId = 72611 , Rating = 2.5\nId = 72612 , Rating = 1.0\nId = 72613 , Rating = 3.0\nId = 72614 , Rating = 1.0\nId = 72615 , Rating = 5.0\nId = 72616 , Rating = 6.0\nId = 72617 , Rating = 2.0\nId = 72618 , Rating = 7.5\nId = 72619 , Rating = 6.0\nId = 72620 , Rating = 9.5\nId = 72621 , Rating = 6.0\nId = 72622 , Rating = 1.0\nId = 72623 , Rating = 6.5\nId = 72624 , Rating = 2.5\nId = 72625 , Rating = 4.5\nId = 72626 , Rating = 9.0\nId = 72627 , Rating = 7.5\nId = 72628 , Rating = 9.0\nId = 72629 , Rating = 3.5\nId = 72630 , Rating = 5.5\nId = 72631 , Rating = 5.5\nId = 72632 , Rating = 8.5\nId = 72633 , Rating = 9.0\nId = 72634 , Rating = 9.0\nId = 72635 , Rating = 9.5\nId = 72636 , Rating = 8.5\nId = 72637 , Rating = 1.0\nId = 72639 , Rating = 8.5\nId = 72640 , Rating = 4.0\nId = 72641 , Rating = 5.0\nId = 72642 , Rating = 10.0\nId = 72643 , Rating = 3.0\nId = 72644 , Rating = 4.0\nId = 72645 , Rating = 7.0\nId = 72646 , Rating = 6.5\nId = 72647 , Rating = 4.5\nId = 72648 , Rating = 8.0\nId = 72649 , Rating = 8.5\nId = 72650 , Rating = 5.0\nId = 72651 , Rating = 5.0\nId = 72652 , Rating = 2.0\nId = 72653 , Rating = 2.0\nId = 72654 , Rating = 4.0\nId = 72655 , Rating = 9.5\nId = 72656 , Rating = 5.5\nId = 72657 , Rating = 2.5\nId = 72658 , Rating = 5.5\nId = 72659 , Rating = 6.0\nId = 72660 , Rating = 8.5\nId = 72661 , Rating = 6.5\nId = 72662 , Rating = 8.5\nId = 72663 , Rating = 5.0\nId = 72681 , Rating = 1.5\nId = 72682 , Rating = 2.5\nId = 72683 , Rating = 3.0\nId = 72684 , Rating = 7.0\nId = 72685 , Rating = 1.0\nId = 72686 , Rating = 2.0\nId = 72687 , Rating = 4.5\nId = 72688 , Rating = 2.0\nId = 72689 , Rating = 6.5\nId = 72690 , Rating = 9.5\nId = 72691 , Rating = 1.0\nId = 72692 , Rating = 5.5\nId = 72693 , Rating = 6.0\nId = 72694 , Rating = 1.5\nId = 72695 , Rating = 5.5\nId = 72696 , Rating = 6.5\nId = 72697 , Rating = 4.5\nId = 72698 , Rating = 6.5\nId = 72699 , Rating = 10.0\nId = 72700 , Rating = 6.0\nId = 72701 , Rating = 5.0\nId = 72702 , Rating = 9.5\nId = 72703 , Rating = 2.0\nId = 72704 , Rating = 5.5\nId = 72705 , Rating = 9.0\nId = 72706 , Rating = 2.5\nId = 72707 , Rating = 9.0\nId = 72708 , Rating = 8.5\nId = 72709 , Rating = 3.5\nId = 72710 , Rating = 6.5\nId = 72711 , Rating = 3.5\nId = 72712 , Rating = 3.0\nId = 72713 , Rating = 10.0\nId = 72714 , Rating = 5.5\nId = 72715 , Rating = 1.0\nId = 72716 , Rating = 2.0\nId = 72717 , Rating = 6.5\nId = 72718 , Rating = 7.5\nId = 72719 , Rating = 5.5\nId = 72720 , Rating = 9.0\nId = 72721 , Rating = 9.5\nId = 72722 , Rating = 8.0\nId = 72723 , Rating = 5.0\nId = 72724 , Rating = 9.5\nId = 72725 , Rating = 4.5\nId = 74347 , Rating = 5.5\nId = 74348 , Rating = 5.0\nId = 74349 , Rating = 2.0\nId = 74350 , Rating = 4.5\nId = 74351 , Rating = 2.5\nId = 74352 , Rating = 9.5\nId = 74353 , Rating = 2.0\nId = 74354 , Rating = 3.0\nId = 74355 , Rating = 6.0\nId = 74356 , Rating = 4.5\nId = 74357 , Rating = 4.5\nId = 74358 , Rating = 10.0\nId = 74359 , Rating = 2.0\nId = 74360 , Rating = 2.5\nId = 74361 , Rating = 6.0\nId = 74362 , Rating = 9.0\nId = 74363 , Rating = 10.0\nId = 74364 , Rating = 5.5\nId = 74365 , Rating = 5.5\nId = 74366 , Rating = 9.5\nId = 74367 , Rating = 5.5\nId = 74368 , Rating = 7.5\nId = 74369 , Rating = 5.0\nId = 74371 , Rating = 9.0\nId = 74372 , Rating = 9.5\nId = 74373 , Rating = 9.5\nId = 74374 , Rating = 8.5\nId = 74375 , Rating = 9.5\nId = 74376 , Rating = 9.0\nId = 74377 , Rating = 7.5\nId = 74378 , Rating = 10.0\nId = 74379 , Rating = 9.5\nId = 74380 , Rating = 4.0\nId = 74381 , Rating = 8.5\nId = 74382 , Rating = 1.0\nId = 74384 , Rating = 6.5\nId = 74440 , Rating = 9.0\nId = 74441 , Rating = 6.0\nId = 74442 , Rating = 9.0\nId = 74443 , Rating = 8.0\nId = 74444 , Rating = 9.5\nId = 74445 , Rating = 5.0\nId = 74446 , Rating = 5.5\nId = 74447 , Rating = 6.0\nId = 78180 , Rating = 6.0\nId = 83840 , Rating = 6.5\nId = 85574 , Rating = 9.0\nId = 85578 , Rating = 6.0\nId = 85583 , Rating = 8.0\nId = 85589 , Rating = 9.0\nId = 92813 , Rating = 6.5\nId = 92814 , Rating = 6.5\nId = 92815 , Rating = 6.5\nId = 92816 , Rating = 1.5\nId = 92817 , Rating = 6.5\nId = 92818 , Rating = 6.5\nId = 92819 , Rating = 2.0\nId = 92820 , Rating = 3.0\nId = 92821 , Rating = 2.0\nId = 92822 , Rating = 5.0\nId = 92823 , Rating = 1.0\nId = 92824 , Rating = 2.0\nId = 92825 , Rating = 2.0\nId = 92826 , Rating = 6.5\nId = 92827 , Rating = 2.5\nId = 92828 , Rating = 8.5\nId = 92829 , Rating = 6.5\nId = 92830 , Rating = 8.0\nId = 92831 , Rating = 9.0\nId = 92832 , Rating = 8.5\nId = 92833 , Rating = 6.5\nId = 92834 , Rating = 6.0\nId = 92835 , Rating = 1.5\nId = 92836 , Rating = 3.0\nId = 92837 , Rating = 2.5\nId = 92838 , Rating = 9.0\nId = 92839 , Rating = 5.0\nId = 92840 , Rating = 6.5\nId = 92841 , Rating = 1.0\nId = 92842 , Rating = 4.0\nId = 92843 , Rating = 10.0\nId = 92844 , Rating = 5.0\nId = 92845 , Rating = 9.5\nId = 92846 , Rating = 6.5\nId = 92847 , Rating = 2.0\nId = 92848 , Rating = 2.5\nId = 92849 , Rating = 9.5\nId = 92850 , Rating = 5.0\nId = 92851 , Rating = 9.5\nId = 92852 , Rating = 9.5\nId = 92853 , Rating = 9.5\nId = 92854 , Rating = 9.0\nId = 92855 , Rating = 10.0\nId = 92856 , Rating = 9.0\nId = 92857 , Rating = 5.5\nId = 92858 , Rating = 8.5\nId = 92859 , Rating = 8.5\nId = 92860 , Rating = 9.0\nId = 92861 , Rating = 10.0\nId = 92862 , Rating = 7.0\nId = 92863 , Rating = 8.5\nId = 92864 , Rating = 2.5\nId = 92865 , Rating = 8.5\nId = 92866 , Rating = 9.0\nId = 92867 , Rating = 8.5\nId = 92868 , Rating = 9.5\nId = 92869 , Rating = 2.0\nId = 92870 , Rating = 5.0\nId = 92871 , Rating = 6.0\nId = 92872 , Rating = 9.5\nId = 92873 , Rating = 5.0\nId = 92874 , Rating = 5.0\nId = 92875 , Rating = 2.0\nId = 92876 , Rating = 9.5\nId = 92877 , Rating = 6.0\nId = 92878 , Rating = 4.0\nId = 92879 , Rating = 2.0\nId = 92913 , Rating = 5.5\nId = 92914 , Rating = 9.0\nId = 92915 , Rating = 5.5\nId = 92916 , Rating = 9.5\nId = 92917 , Rating = 2.0\nId = 92918 , Rating = 3.0\nId = 92919 , Rating = 6.5\nId = 92920 , Rating = 3.0\nId = 92921 , Rating = 2.0\nId = 92922 , Rating = 8.5\nId = 92923 , Rating = 9.0\nId = 92924 , Rating = 6.0\nId = 92925 , Rating = 2.5\nId = 92926 , Rating = 3.5\nId = 92927 , Rating = 9.5\nId = 95379 , Rating = 1.5\nId = 95386 , Rating = 6.0\nId = 95449 , Rating = 10.0\nId = 95471 , Rating = 9.0\nId = 95521 , Rating = 9.0\nId = 95539 , Rating = 8.5\nId = 95548 , Rating = 9.0\nId = 95595 , Rating = 2.5\nId = 108500 , Rating = 9.5\nId = 108501 , Rating = 6.0\nId = 108502 , Rating = 8.5\nId = 108503 , Rating = 2.5\nId = 108504 , Rating = 2.0\nId = 108505 , Rating = 1.5\nId = 108506 , Rating = 9.0\nId = 108507 , Rating = 9.0\nId = 108508 , Rating = 6.5\nId = 108509 , Rating = 6.5\nId = 108510 , Rating = 5.0\nId = 108511 , Rating = 8.5\nId = 108512 , Rating = 10.0\nId = 108513 , Rating = 10.0\nId = 108514 , Rating = 5.5\nId = 108515 , Rating = 3.0\nId = 108518 , Rating = 6.0\nId = 108519 , Rating = 9.5\nId = 108520 , Rating = 3.0\nId = 108521 , Rating = 5.5\nId = 108523 , Rating = 4.5\nId = 108525 , Rating = 4.0\nId = 108526 , Rating = 3.5\nId = 108527 , Rating = 9.5\nId = 108528 , Rating = 10.0\nId = 108529 , Rating = 6.5\nId = 108532 , Rating = 5.5\nId = 108533 , Rating = 6.0\nId = 108534 , Rating = 6.5\nId = 108537 , Rating = 4.0\nId = 108538 , Rating = 1.5\nId = 108539 , Rating = 1.0\nId = 108541 , Rating = 10.0\nId = 108542 , Rating = 10.0\nId = 108543 , Rating = 1.5\nId = 108544 , Rating = 5.0\nId = 108546 , Rating = 5.5\nId = 108547 , Rating = 2.5\nId = 108548 , Rating = 8.5\nId = 108549 , Rating = 9.5\nId = 108550 , Rating = 8.5\nId = 108553 , Rating = 4.5\nId = 108554 , Rating = 2.0\nId = 108555 , Rating = 6.5\nId = 108556 , Rating = 5.0\nId = 108557 , Rating = 3.5\nId = 108558 , Rating = 9.5\nId = 108559 , Rating = 2.0\nId = 108560 , Rating = 4.5\nId = 108561 , Rating = 8.5\nId = 108562 , Rating = 10.0\nId = 108563 , Rating = 4.5\nId = 108565 , Rating = 9.5\nId = 108566 , Rating = 9.5\nId = 108567 , Rating = 6.5\nId = 108568 , Rating = 3.5\nId = 108569 , Rating = 2.0\nId = 108570 , Rating = 9.0\nId = 108571 , Rating = 6.5\nId = 108572 , Rating = 8.0\nId = 108574 , Rating = 6.5\nId = 108575 , Rating = 6.0\nId = 108576 , Rating = 8.5\nId = 108577 , Rating = 9.0\nId = 108578 , Rating = 9.0\nId = 108579 , Rating = 6.5\nId = 108580 , Rating = 4.5\nId = 108581 , Rating = 8.5\nId = 108582 , Rating = 10.0\nId = 108583 , Rating = 6.5\nId = 108584 , Rating = 9.5\nId = 108585 , Rating = 9.5\nId = 108586 , Rating = 6.0\nId = 108587 , Rating = 4.0\nId = 108588 , Rating = 5.5\nId = 108589 , Rating = 6.0\nId = 108590 , Rating = 9.5\nId = 108591 , Rating = 6.0\nId = 108592 , Rating = 9.0\nId = 108593 , Rating = 9.5\nId = 108595 , Rating = 6.0\nId = 108597 , Rating = 6.0\nId = 108598 , Rating = 10.0\nId = 108599 , Rating = 6.0\nId = 108600 , Rating = 6.5\nId = 108601 , Rating = 6.5\nId = 108602 , Rating = 9.0\nId = 108603 , Rating = 6.5\nId = 108604 , Rating = 6.5\nId = 108605 , Rating = 9.5\nId = 108606 , Rating = 4.5\nId = 108607 , Rating = 6.5\nId = 108608 , Rating = 6.0\nId = 108609 , Rating = 9.5\nId = 108610 , Rating = 9.5\nId = 108611 , Rating = 8.0\nId = 108612 , Rating = 6.0\nId = 108613 , Rating = 8.0\nId = 108614 , Rating = 2.5\nId = 108615 , Rating = 9.5\nId = 108616 , Rating = 5.0\nId = 108618 , Rating = 10.0\nId = 108619 , Rating = 9.0\nId = 108620 , Rating = 6.0\nId = 108621 , Rating = 10.0\nId = 108622 , Rating = 4.0\nId = 108623 , Rating = 9.5\nId = 108624 , Rating = 5.5\nId = 108625 , Rating = 5.5\nId = 108627 , Rating = 5.5\nId = 108628 , Rating = 4.5\nId = 108629 , Rating = 9.0\nId = 108630 , Rating = 5.0\nId = 108631 , Rating = 9.5\nId = 108632 , Rating = 5.0\nId = 108633 , Rating = 6.0\nId = 108634 , Rating = 6.5\nId = 108635 , Rating = 5.0\nId = 108636 , Rating = 10.0\nId = 108637 , Rating = 5.5\nId = 108639 , Rating = 5.5\nId = 108640 , Rating = 8.0\nId = 108641 , Rating = 2.0\nId = 108642 , Rating = 6.0\nId = 108644 , Rating = 6.0\nId = 108647 , Rating = 5.5\nId = 108649 , Rating = 3.5\nId = 108650 , Rating = 6.5\nId = 108651 , Rating = 1.5\nId = 108652 , Rating = 6.5\nId = 108654 , Rating = 9.0\nId = 108655 , Rating = 6.5\nId = 108656 , Rating = 6.5\nId = 108657 , Rating = 4.0\nId = 108658 , Rating = 9.5\nId = 108659 , Rating = 9.0\nId = 108660 , Rating = 5.0\nId = 108661 , Rating = 4.0\nId = 108662 , Rating = 7.0\nId = 108663 , Rating = 5.0\nId = 108664 , Rating = 6.5\nId = 108665 , Rating = 9.5\nId = 108666 , Rating = 4.5\nId = 108667 , Rating = 7.5\nId = 108668 , Rating = 5.5\nId = 108669 , Rating = 9.0\nId = 108670 , Rating = 6.0\nId = 108671 , Rating = 7.0\nId = 108672 , Rating = 5.5\nId = 108673 , Rating = 4.5\nId = 108674 , Rating = 9.5\nId = 108675 , Rating = 1.5\nId = 108676 , Rating = 6.0\nId = 108677 , Rating = 8.0\nId = 108678 , Rating = 4.5\nId = 108679 , Rating = 4.5\nId = 108681 , Rating = 4.0\nId = 108682 , Rating = 7.5\nId = 108684 , Rating = 5.5\nId = 108685 , Rating = 6.5\nId = 108686 , Rating = 10.0\nId = 108688 , Rating = 6.0\nId = 108689 , Rating = 9.0\nId = 108690 , Rating = 9.5\nId = 108693 , Rating = 9.5\nId = 108694 , Rating = 7.0\nId = 108695 , Rating = 9.5\nId = 108696 , Rating = 4.5\nId = 108698 , Rating = 6.0\nId = 108699 , Rating = 10.0\nId = 108700 , Rating = 5.5\nId = 108701 , Rating = 8.0\nId = 108702 , Rating = 5.5\nId = 108703 , Rating = 9.0\nId = 108704 , Rating = 8.0\nId = 108705 , Rating = 3.0\nId = 108706 , Rating = 10.0\nId = 108707 , Rating = 10.0\nId = 108710 , Rating = 7.5\nId = 108711 , Rating = 9.0\nId = 108712 , Rating = 9.0\nId = 108713 , Rating = 8.5\nId = 108715 , Rating = 6.5\nId = 108716 , Rating = 5.5\nId = 108717 , Rating = 6.5\nId = 108718 , Rating = 9.0\nId = 108719 , Rating = 9.5\nId = 108721 , Rating = 9.0\nId = 108722 , Rating = 8.0\nId = 108723 , Rating = 9.0\nId = 108725 , Rating = 6.5\nId = 108726 , Rating = 6.5\nId = 108727 , Rating = 7.5\nId = 108728 , Rating = 3.5\nId = 108729 , Rating = 9.0\nId = 108730 , Rating = 5.5\nId = 108731 , Rating = 5.0\nId = 108732 , Rating = 4.5\nId = 108733 , Rating = 6.5\nId = 108734 , Rating = 5.5\nId = 108735 , Rating = 6.5\nId = 108736 , Rating = 2.5\nId = 108739 , Rating = 7.5\nId = 108740 , Rating = 9.0\nId = 108741 , Rating = 3.5\nId = 108742 , Rating = 7.0\nId = 108743 , Rating = 4.5\nId = 108744 , Rating = 5.5\nId = 108745 , Rating = 10.0\nId = 108746 , Rating = 8.0\nId = 108747 , Rating = 8.5\nId = 108748 , Rating = 9.5\nId = 108749 , Rating = 5.0\nId = 108750 , Rating = 4.0\nId = 108751 , Rating = 6.0\nId = 108752 , Rating = 9.0\nId = 108753 , Rating = 8.0\nId = 108754 , Rating = 6.5\nId = 108755 , Rating = 9.5\nId = 108757 , Rating = 8.0\nId = 108758 , Rating = 6.5\nId = 108759 , Rating = 6.0\nId = 108760 , Rating = 6.5\nId = 108761 , Rating = 4.5\nId = 108763 , Rating = 6.0\nId = 108764 , Rating = 8.5\nId = 108765 , Rating = 7.5\nId = 108766 , Rating = 6.5\nId = 108767 , Rating = 9.5\nId = 108768 , Rating = 9.0\nId = 108770 , Rating = 5.5\nId = 108771 , Rating = 9.0\nId = 108772 , Rating = 7.5\nId = 108773 , Rating = 9.0\nId = 108774 , Rating = 4.0\nId = 108775 , Rating = 6.0\nId = 108776 , Rating = 9.0\nId = 108777 , Rating = 4.5\nId = 108778 , Rating = 6.5\nId = 108779 , Rating = 9.0\nId = 108780 , Rating = 8.0\nId = 108782 , Rating = 6.0\nId = 108784 , Rating = 5.5\nId = 108785 , Rating = 9.5\nId = 108786 , Rating = 9.0\nId = 108787 , Rating = 6.0\nId = 108790 , Rating = 9.0\nId = 108791 , Rating = 9.0\nId = 108792 , Rating = 5.5\nId = 108793 , Rating = 3.0\nId = 108794 , Rating = 8.5\nId = 108795 , Rating = 5.5\nId = 108796 , Rating = 8.5\nId = 108797 , Rating = 10.0\nId = 108798 , Rating = 4.5\nId = 108800 , Rating = 8.0\nId = 108801 , Rating = 2.5\nId = 108802 , Rating = 8.0\nId = 108803 , Rating = 9.0\nId = 108804 , Rating = 2.0\nId = 108805 , Rating = 5.5\nId = 108808 , Rating = 6.5\nId = 108809 , Rating = 6.5\nId = 108810 , Rating = 9.5\nId = 108812 , Rating = 6.0\nId = 108813 , Rating = 6.0\nId = 108814 , Rating = 3.0\nId = 108815 , Rating = 9.0\nId = 108816 , Rating = 6.5\nId = 108817 , Rating = 6.0\nId = 108818 , Rating = 9.0\nId = 108819 , Rating = 9.0\nId = 108820 , Rating = 4.5\nId = 108821 , Rating = 8.5\nId = 108822 , Rating = 2.0\nId = 108823 , Rating = 2.5\nId = 108824 , Rating = 3.0\nId = 108825 , Rating = 9.0\nId = 108826 , Rating = 6.5\nId = 108827 , Rating = 4.0\nId = 108828 , Rating = 6.0\nId = 108829 , Rating = 10.0\nId = 108830 , Rating = 8.0\nId = 108832 , Rating = 9.0\nId = 108833 , Rating = 10.0\nId = 108834 , Rating = 3.5\nId = 108835 , Rating = 9.5\nId = 108837 , Rating = 9.5\nId = 108838 , Rating = 2.0\nId = 108839 , Rating = 10.0\nId = 108840 , Rating = 8.5\nId = 108841 , Rating = 4.5\nId = 108842 , Rating = 5.0\nId = 108843 , Rating = 9.0\nId = 108844 , Rating = 2.0\nId = 108845 , Rating = 3.0\nId = 108846 , Rating = 8.5\nId = 108847 , Rating = 5.0\nId = 108849 , Rating = 2.0\nId = 108850 , Rating = 8.5\nId = 108851 , Rating = 6.5\nId = 108852 , Rating = 6.0\nId = 108853 , Rating = 10.0\nId = 108854 , Rating = 10.0\nId = 108855 , Rating = 6.5\nId = 108856 , Rating = 10.0\nId = 108857 , Rating = 6.5\nId = 108858 , Rating = 7.0\nId = 108859 , Rating = 9.0\nId = 108860 , Rating = 7.0\nId = 108898 , Rating = 6.0\nId = 108900 , Rating = 10.0\nId = 108901 , Rating = 10.0\nId = 108902 , Rating = 6.0\nId = 108904 , Rating = 5.5\nId = 108905 , Rating = 9.5\nId = 108906 , Rating = 3.5\nId = 111688 , Rating = 6.5\nId = 111689 , Rating = 10.0\nId = 111690 , Rating = 6.0\nId = 111691 , Rating = 6.5\nId = 111692 , Rating = 5.5\nId = 111693 , Rating = 6.0\nId = 111939 , Rating = 2.0\nId = 111940 , Rating = 3.5\nId = 111941 , Rating = 9.0\nId = 111942 , Rating = 3.5\nId = 111943 , Rating = 10.0\nId = 111945 , Rating = 2.0\nId = 111946 , Rating = 10.0\nId = 111947 , Rating = 5.5\nId = 111948 , Rating = 4.5\nId = 111949 , Rating = 1.5\nId = 111951 , Rating = 1.5\nId = 111952 , Rating = 9.0\nId = 111953 , Rating = 5.5\nId = 111954 , Rating = 8.5\nId = 111955 , Rating = 10.0\nId = 111956 , Rating = 3.0\nId = 111958 , Rating = 4.5\nId = 111959 , Rating = 7.0\nId = 111960 , Rating = 9.0\nId = 111961 , Rating = 2.0\nId = 111963 , Rating = 2.0\nId = 111964 , Rating = 3.5\nId = 111965 , Rating = 6.5\nId = 111966 , Rating = 5.0\nId = 111967 , Rating = 2.0\nId = 111968 , Rating = 2.0\nId = 111969 , Rating = 9.0\nId = 111970 , Rating = 6.5\nId = 111971 , Rating = 9.5\nId = 111972 , Rating = 8.5\nId = 111974 , Rating = 2.0\nId = 111975 , Rating = 6.5\nId = 111976 , Rating = 6.0\nId = 111977 , Rating = 7.0\nId = 111979 , Rating = 7.0\nId = 111980 , Rating = 4.0\nId = 111981 , Rating = 9.0\nId = 111982 , Rating = 4.0\nId = 111983 , Rating = 6.0\nId = 111984 , Rating = 5.5\nId = 111985 , Rating = 8.0\nId = 111986 , Rating = 4.5\nId = 111987 , Rating = 5.5\nId = 111988 , Rating = 4.0\nId = 111990 , Rating = 8.5\nId = 111991 , Rating = 6.0\nId = 111992 , Rating = 5.0\nId = 111993 , Rating = 4.0\nId = 111994 , Rating = 9.5\nId = 111995 , Rating = 2.5\nId = 111996 , Rating = 6.5\nId = 111997 , Rating = 5.5\nId = 111999 , Rating = 9.0\nId = 112000 , Rating = 6.5\nId = 112001 , Rating = 9.0\nId = 112025 , Rating = 9.0\nId = 112026 , Rating = 3.5\nId = 112027 , Rating = 4.5\nId = 112028 , Rating = 2.0\nId = 112029 , Rating = 6.0\nId = 112031 , Rating = 2.0\nId = 112032 , Rating = 6.5\nId = 112033 , Rating = 9.0\nId = 112034 , Rating = 9.0\nId = 112035 , Rating = 10.0\nId = 112036 , Rating = 5.0\nId = 112037 , Rating = 7.5\nId = 112038 , Rating = 6.5\nId = 112039 , Rating = 6.5\nId = 112040 , Rating = 5.5\nId = 112041 , Rating = 9.0\nId = 115158 , Rating = 3.0\nId = 117630 , Rating = 10.0\nId = 117647 , Rating = 2.0\nId = 117668 , Rating = 2.0\nId = 117677 , Rating = 10.0\nId = 119141 , Rating = 6.5\nId = 119200 , Rating = 8.5\nId = 119207 , Rating = 10.0\nId = 119211 , Rating = 9.5\nId = 122283 , Rating = 7.5\nId = 122284 , Rating = 9.5\nId = 122285 , Rating = 8.5\nId = 122286 , Rating = 9.0\nId = 122287 , Rating = 7.5\nId = 122288 , Rating = 10.0\nId = 122289 , Rating = 9.5\nId = 122290 , Rating = 1.0\nId = 122291 , Rating = 6.5\nId = 122292 , Rating = 5.5\nId = 122293 , Rating = 5.0\nId = 122294 , Rating = 4.5\nId = 122295 , Rating = 9.5\nId = 122296 , Rating = 3.0\nId = 122297 , Rating = 4.5\nId = 122298 , Rating = 6.0\nId = 122299 , Rating = 10.0\nId = 122300 , Rating = 5.5\nId = 123730 , Rating = 2.0\nId = 123731 , Rating = 3.0\nId = 123732 , Rating = 4.0\nId = 123733 , Rating = 7.0\nId = 123734 , Rating = 5.5\nId = 123735 , Rating = 9.5\nId = 123736 , Rating = 5.5\nId = 123737 , Rating = 5.5\nId = 123738 , Rating = 8.0\nId = 123739 , Rating = 9.0\nId = 123740 , Rating = 9.0\nId = 123741 , Rating = 4.0\nId = 123742 , Rating = 9.5\nId = 123743 , Rating = 9.5\nId = 123744 , Rating = 3.5\nId = 123745 , Rating = 10.0\nId = 123746 , Rating = 10.0\nId = 123747 , Rating = 10.0\nId = 123748 , Rating = 6.5\nId = 123765 , Rating = 3.0\nId = 123766 , Rating = 4.5\nId = 123767 , Rating = 6.0\nId = 123768 , Rating = 9.0\nId = 123769 , Rating = 9.5\nId = 123770 , Rating = 4.0\nId = 123771 , Rating = 1.5\nId = 123772 , Rating = 9.0\nId = 123773 , Rating = 10.0\nId = 123774 , Rating = 9.0\nId = 123775 , Rating = 8.0\nId = 123776 , Rating = 1.0\nId = 123777 , Rating = 9.0\nId = 123778 , Rating = 4.0\nId = 123779 , Rating = 4.5\nId = 123780 , Rating = 6.5\nId = 123781 , Rating = 8.5\nId = 123782 , Rating = 10.0\nId = 123783 , Rating = 10.0\nId = 123784 , Rating = 9.5\nId = 123785 , Rating = 9.0\nId = 123786 , Rating = 6.5\nId = 123787 , Rating = 9.5\nId = 123788 , Rating = 5.0\nId = 123789 , Rating = 6.5\nId = 123790 , Rating = 6.5\nId = 123791 , Rating = 6.0\nId = 123792 , Rating = 5.0\nId = 123794 , Rating = 5.5\nId = 123795 , Rating = 9.0\nId = 123796 , Rating = 10.0\nId = 123797 , Rating = 10.0\nId = 123798 , Rating = 9.5\nId = 123799 , Rating = 9.0\nId = 123800 , Rating = 9.5\nId = 123801 , Rating = 4.0\nId = 123802 , Rating = 9.5\nId = 123803 , Rating = 8.5\nId = 123804 , Rating = 6.0\nId = 123805 , Rating = 4.0\nId = 123806 , Rating = 5.0\nId = 123807 , Rating = 10.0\nId = 123808 , Rating = 6.5\nId = 123809 , Rating = 8.0\nId = 123810 , Rating = 9.0\nId = 123811 , Rating = 5.0\nId = 123813 , Rating = 8.5\nId = 123814 , Rating = 6.5\nId = 123815 , Rating = 9.5\nId = 123816 , Rating = 6.5\nId = 123817 , Rating = 9.0\nId = 123818 , Rating = 6.0\nId = 123819 , Rating = 9.0\nId = 123820 , Rating = 8.5\nId = 123822 , Rating = 5.5\nId = 123823 , Rating = 8.0\nId = 123824 , Rating = 10.0\nId = 123825 , Rating = 4.5\nId = 123826 , Rating = 10.0\nId = 123827 , Rating = 10.0\nId = 123828 , Rating = 9.5\nId = 123829 , Rating = 9.5\nId = 123830 , Rating = 6.0\nId = 123831 , Rating = 9.0\nId = 123832 , Rating = 6.5\nId = 123833 , Rating = 9.0\nId = 123834 , Rating = 7.0\nId = 123835 , Rating = 5.5\nId = 123836 , Rating = 5.5\nId = 123837 , Rating = 5.5\nId = 123838 , Rating = 3.5\nId = 123839 , Rating = 6.5\nId = 123840 , Rating = 5.5\nId = 123841 , Rating = 10.0\nId = 123842 , Rating = 5.0\nId = 123843 , Rating = 4.5\nId = 123844 , Rating = 6.0\nId = 123845 , Rating = 6.5\nId = 123846 , Rating = 8.0\nId = 123847 , Rating = 6.0\nId = 123848 , Rating = 4.5\nId = 123850 , Rating = 6.0\nId = 123851 , Rating = 9.0\nId = 123852 , Rating = 6.0\nId = 123853 , Rating = 9.5\nId = 123854 , Rating = 6.5\nId = 123855 , Rating = 9.0\nId = 123856 , Rating = 9.0\nId = 126543 , Rating = 8.5\nId = 126545 , Rating = 8.5\nId = 126546 , Rating = 7.0\nId = 126548 , Rating = 9.0\nId = 126549 , Rating = 9.0\nId = 126550 , Rating = 10.0\nId = 126551 , Rating = 9.0\nId = 126552 , Rating = 6.5\nId = 127841 , Rating = 8.5\nId = 127860 , Rating = 5.5\nId = 127861 , Rating = 6.5\nId = 127862 , Rating = 9.0\nId = 127863 , Rating = 7.5\nId = 127864 , Rating = 6.5\nId = 127865 , Rating = 6.5\nId = 127867 , Rating = 6.5\nId = 127868 , Rating = 10.0\nId = 127869 , Rating = 9.0\nId = 127870 , Rating = 9.0\nId = 127871 , Rating = 8.0\nId = 127872 , Rating = 8.5\nId = 127873 , Rating = 6.0\nId = 127875 , Rating = 8.5\nId = 127876 , Rating = 10.0\nId = 127877 , Rating = 5.0\nId = 127878 , Rating = 10.0\nId = 127895 , Rating = 10.0\nId = 127896 , Rating = 5.5\nId = 127897 , Rating = 9.0\nId = 127898 , Rating = 10.0\nId = 127899 , Rating = 9.5\nId = 127900 , Rating = 8.5\nId = 127901 , Rating = 5.5\nId = 127902 , Rating = 9.0\nId = 127903 , Rating = 6.5\nId = 127904 , Rating = 10.0\nId = 127905 , Rating = 6.5\nId = 127906 , Rating = 6.0\nId = 127907 , Rating = 9.0\nId = 127908 , Rating = 9.0\nId = 127909 , Rating = 6.5\nId = 127910 , Rating = 6.0\nId = 127912 , Rating = 9.0\nId = 127913 , Rating = 10.0\nId = 127914 , Rating = 4.5\nId = 127915 , Rating = 3.5\nId = 127916 , Rating = 6.5\nId = 127917 , Rating = 5.5\nId = 127918 , Rating = 5.5\nId = 127919 , Rating = 10.0\nId = 127920 , Rating = 10.0\nId = 127921 , Rating = 9.5\nId = 130091 , Rating = 4.5\nId = 130877 , Rating = 4.0\nId = 130878 , Rating = 6.5\nId = 130879 , Rating = 3.5\nId = 130880 , Rating = 6.5\nId = 130881 , Rating = 1.5\nId = 130882 , Rating = 10.0\nId = 130884 , Rating = 10.0\nId = 130885 , Rating = 1.5\nId = 130886 , Rating = 10.0\nId = 130887 , Rating = 10.0\nId = 130888 , Rating = 9.0\nId = 130889 , Rating = 7.0\nId = 130890 , Rating = 5.5\nId = 130891 , Rating = 3.0\nId = 130893 , Rating = 6.5\nId = 130894 , Rating = 6.5\nId = 130895 , Rating = 7.0\nId = 130897 , Rating = 8.5\nId = 130898 , Rating = 5.5\nId = 130899 , Rating = 7.5\nId = 130901 , Rating = 4.0\nId = 130903 , Rating = 5.5\nId = 130904 , Rating = 7.0\nId = 130905 , Rating = 8.5\nId = 130906 , Rating = 1.0\nId = 130907 , Rating = 9.0\nId = 130908 , Rating = 1.5\nId = 130929 , Rating = 3.0\nId = 130930 , Rating = 1.0\nId = 130931 , Rating = 6.0\nId = 130932 , Rating = 2.0\nId = 130933 , Rating = 1.5\nId = 130934 , Rating = 4.5\nId = 130935 , Rating = 2.0\nId = 130936 , Rating = 6.5\nId = 130937 , Rating = 6.0\nId = 130938 , Rating = 3.0\nId = 130939 , Rating = 6.0\nId = 130941 , Rating = 6.0\nId = 130942 , Rating = 7.0\nId = 130943 , Rating = 9.5\nId = 130945 , Rating = 2.0\nId = 130947 , Rating = 8.0\nId = 130948 , Rating = 8.5\nId = 130949 , Rating = 4.5\nId = 130950 , Rating = 8.0\nId = 130952 , Rating = 1.0\nId = 130953 , Rating = 4.0\nId = 130954 , Rating = 5.5\nId = 130956 , Rating = 6.5\nId = 130958 , Rating = 8.5\nId = 130961 , Rating = 9.0\nId = 130962 , Rating = 5.0\nId = 130964 , Rating = 2.0\nId = 130965 , Rating = 9.0\nId = 130966 , Rating = 10.0\nId = 130967 , Rating = 9.0\nId = 130968 , Rating = 10.0\nId = 130969 , Rating = 8.5\nId = 130971 , Rating = 5.5\nId = 130972 , Rating = 5.5\nId = 130973 , Rating = 5.0\nId = 130977 , Rating = 2.5\nId = 130978 , Rating = 6.5\nId = 130979 , Rating = 5.0\nId = 130980 , Rating = 2.0\nId = 130981 , Rating = 6.0\nId = 130982 , Rating = 1.5\nId = 130983 , Rating = 7.5\nId = 130985 , Rating = 6.0\nId = 130987 , Rating = 9.0\nId = 130988 , Rating = 2.0\nId = 130989 , Rating = 6.5\nId = 130990 , Rating = 5.5\nId = 130991 , Rating = 6.0\nId = 130993 , Rating = 5.0\nId = 130994 , Rating = 9.5\nId = 130995 , Rating = 6.5\nId = 130996 , Rating = 5.5\nId = 130997 , Rating = 9.0\nId = 130998 , Rating = 10.0\nId = 130999 , Rating = 10.0\nId = 131000 , Rating = 6.0\nId = 131002 , Rating = 5.0\nId = 131003 , Rating = 6.0\nId = 131005 , Rating = 6.5\nId = 131008 , Rating = 8.0\nId = 131009 , Rating = 6.5\nId = 131010 , Rating = 9.5\nId = 131011 , Rating = 6.0\nId = 131012 , Rating = 6.5\nId = 131013 , Rating = 4.0\nId = 131014 , Rating = 2.0\nId = 131016 , Rating = 9.5\nId = 131017 , Rating = 6.0\nId = 131020 , Rating = 7.5\nId = 131021 , Rating = 7.0\nId = 131022 , Rating = 9.5\nId = 131023 , Rating = 6.0\nId = 131024 , Rating = 8.0\nId = 131026 , Rating = 6.0\nId = 131027 , Rating = 9.5\nId = 131028 , Rating = 4.0\nId = 131029 , Rating = 6.5\nId = 131030 , Rating = 9.0\nId = 131031 , Rating = 5.5\nId = 131032 , Rating = 6.5\nId = 131033 , Rating = 10.0\nId = 131035 , Rating = 9.0\nId = 131036 , Rating = 8.0\nId = 131037 , Rating = 5.5\nId = 131038 , Rating = 4.5\nId = 131039 , Rating = 2.0\nId = 131040 , Rating = 5.0\nId = 131041 , Rating = 9.0\nId = 131042 , Rating = 5.5\nId = 131043 , Rating = 1.5\nId = 131044 , Rating = 8.5\nId = 131045 , Rating = 1.0\nId = 131048 , Rating = 9.5\nId = 131049 , Rating = 6.0\nId = 131050 , Rating = 9.5\nId = 131053 , Rating = 2.5\nId = 131054 , Rating = 3.0\nId = 131057 , Rating = 3.5\nId = 131058 , Rating = 6.0\nId = 131059 , Rating = 4.5\nId = 131060 , Rating = 6.0\nId = 131061 , Rating = 10.0\nId = 131062 , Rating = 5.5\nId = 131063 , Rating = 9.0\nId = 131064 , Rating = 8.5\nId = 131065 , Rating = 8.5\nId = 131066 , Rating = 7.5\nId = 131067 , Rating = 10.0\nId = 131068 , Rating = 9.0\nId = 131069 , Rating = 6.5\nId = 131070 , Rating = 9.5\nId = 131071 , Rating = 6.5\nId = 131072 , Rating = 5.5\nId = 131073 , Rating = 6.0\nId = 131074 , Rating = 9.0\nId = 131075 , Rating = 6.5\nId = 131076 , Rating = 9.5\nId = 131077 , Rating = 9.5\nId = 131078 , Rating = 5.5\nId = 131080 , Rating = 6.0\nId = 131081 , Rating = 4.5\nId = 131082 , Rating = 10.0\nId = 131083 , Rating = 5.5\nId = 131084 , Rating = 9.5\nId = 131085 , Rating = 1.5\nId = 131086 , Rating = 6.5\nId = 131087 , Rating = 9.5\nId = 131088 , Rating = 6.0\nId = 131089 , Rating = 5.5\nId = 131091 , Rating = 2.0\nId = 131092 , Rating = 9.0\nId = 131093 , Rating = 5.5\nId = 131094 , Rating = 5.5\nId = 131095 , Rating = 1.5\nId = 131099 , Rating = 6.0\nId = 131100 , Rating = 5.5\nId = 131101 , Rating = 5.0\nId = 131102 , Rating = 6.0\nId = 131103 , Rating = 5.0\nId = 131104 , Rating = 5.0\nId = 131105 , Rating = 8.5\nId = 131106 , Rating = 5.5\nId = 131107 , Rating = 6.0\nId = 131108 , Rating = 10.0\nId = 131109 , Rating = 6.5\nId = 131110 , Rating = 9.0\nId = 131111 , Rating = 9.0\nId = 131112 , Rating = 3.0\nId = 131113 , Rating = 6.5\nId = 131114 , Rating = 6.0\nId = 131115 , Rating = 9.5\nId = 131116 , Rating = 9.5\nId = 131117 , Rating = 8.5\nId = 131118 , Rating = 3.0\nId = 131119 , Rating = 9.0\nId = 131120 , Rating = 8.5\nId = 131121 , Rating = 9.0\nId = 131123 , Rating = 8.5\nId = 131124 , Rating = 10.0\nId = 131125 , Rating = 9.0\nId = 131126 , Rating = 7.5\nId = 131128 , Rating = 6.5\nId = 131129 , Rating = 9.0\nId = 131130 , Rating = 4.5\nId = 131131 , Rating = 8.5\nId = 131132 , Rating = 6.0\nId = 131133 , Rating = 6.5\nId = 131134 , Rating = 9.0\nId = 131135 , Rating = 10.0\nId = 131136 , Rating = 6.5\nId = 131137 , Rating = 9.0\nId = 131138 , Rating = 9.5\nId = 131139 , Rating = 9.0\nId = 131140 , Rating = 2.5\nId = 131141 , Rating = 9.5\nId = 131142 , Rating = 9.0\nId = 131143 , Rating = 5.5\nId = 131144 , Rating = 3.0\nId = 131145 , Rating = 9.5\nId = 131146 , Rating = 4.0\nId = 131147 , Rating = 7.0\nId = 131149 , Rating = 6.5\nId = 131150 , Rating = 7.5\nId = 131151 , Rating = 5.0\nId = 131152 , Rating = 9.5\nId = 131153 , Rating = 6.0\nId = 131154 , Rating = 6.0\nId = 131155 , Rating = 10.0\nId = 131156 , Rating = 9.5\nId = 131157 , Rating = 10.0\nId = 131158 , Rating = 6.5\nId = 131159 , Rating = 5.5\nId = 131160 , Rating = 9.5\nId = 131161 , Rating = 9.5\nId = 131162 , Rating = 6.0\nId = 131163 , Rating = 6.5\nId = 131164 , Rating = 8.0\nId = 131165 , Rating = 9.0\nId = 131166 , Rating = 9.5\nId = 131167 , Rating = 5.5\nId = 131168 , Rating = 9.5\nId = 131169 , Rating = 9.0\nId = 131170 , Rating = 9.0\nId = 131171 , Rating = 4.5\nId = 131172 , Rating = 6.0\nId = 131173 , Rating = 6.0\nId = 131174 , Rating = 6.5\nId = 131175 , Rating = 3.0\nId = 131176 , Rating = 5.5\nId = 131178 , Rating = 9.5\nId = 131179 , Rating = 9.0\nId = 131180 , Rating = 5.5\nId = 131181 , Rating = 6.5\nId = 131182 , Rating = 6.0\nId = 131183 , Rating = 6.5\nId = 131184 , Rating = 4.0\nId = 131185 , Rating = 5.5\nId = 131186 , Rating = 9.5\nId = 131187 , Rating = 5.5\nId = 131188 , Rating = 6.5\nId = 131189 , Rating = 1.5\nId = 131190 , Rating = 9.0\nId = 131191 , Rating = 9.0\nId = 131192 , Rating = 9.5\nId = 131194 , Rating = 5.0\nId = 131195 , Rating = 5.5\nId = 131196 , Rating = 10.0\nId = 131197 , Rating = 8.0\nId = 131198 , Rating = 6.5\nId = 131199 , Rating = 9.5\nId = 131201 , Rating = 10.0\nId = 131202 , Rating = 6.0\nId = 131203 , Rating = 6.5\nId = 131204 , Rating = 9.0\nId = 131205 , Rating = 6.0\nId = 131206 , Rating = 8.5\nId = 131207 , Rating = 7.5\nId = 131208 , Rating = 9.5\nId = 131209 , Rating = 8.5\nId = 131210 , Rating = 10.0\nId = 131211 , Rating = 5.5\nId = 131212 , Rating = 8.0\nId = 131213 , Rating = 9.5\nId = 131214 , Rating = 4.5\nId = 131215 , Rating = 3.0\nId = 131217 , Rating = 8.5\nId = 131218 , Rating = 5.0\nId = 131219 , Rating = 6.5\nId = 131220 , Rating = 6.5\nId = 131221 , Rating = 9.0\nId = 131222 , Rating = 9.5\nId = 131223 , Rating = 10.0\nId = 131224 , Rating = 6.5\nId = 131225 , Rating = 5.5\nId = 131226 , Rating = 9.0\nId = 131227 , Rating = 3.5\nId = 131228 , Rating = 4.0\nId = 131229 , Rating = 9.5\nId = 131230 , Rating = 6.5\nId = 131231 , Rating = 5.5\nId = 131232 , Rating = 5.0\nId = 131233 , Rating = 9.0\nId = 131234 , Rating = 9.0\nId = 131235 , Rating = 2.0\nId = 131236 , Rating = 6.5\nId = 131237 , Rating = 5.0\nId = 131238 , Rating = 8.0\nId = 131239 , Rating = 10.0\nId = 131240 , Rating = 7.0\nId = 131241 , Rating = 9.5\nId = 131242 , Rating = 10.0\nId = 131243 , Rating = 10.0\nId = 131244 , Rating = 9.5\nId = 131245 , Rating = 9.0\nId = 131246 , Rating = 3.0\nId = 131247 , Rating = 9.5\nId = 131248 , Rating = 4.5\nId = 131249 , Rating = 5.5\nId = 131251 , Rating = 3.5\nId = 131252 , Rating = 3.5\nId = 131253 , Rating = 3.5\nId = 131254 , Rating = 6.0\nId = 131256 , Rating = 5.5\nId = 131270 , Rating = 8.5\nId = 131271 , Rating = 9.5\nId = 131272 , Rating = 4.0\nId = 131273 , Rating = 6.5\nId = 131274 , Rating = 9.5\nId = 131275 , Rating = 6.0\nId = 131276 , Rating = 1.5\nId = 131277 , Rating = 9.5\nId = 131278 , Rating = 6.5\nId = 131279 , Rating = 6.5\nId = 131280 , Rating = 5.0\nId = 131281 , Rating = 10.0\nId = 131282 , Rating = 9.5\nId = 131283 , Rating = 9.5\nId = 131284 , Rating = 7.0\nId = 131285 , Rating = 9.5\nId = 131286 , Rating = 8.0\nId = 131287 , Rating = 6.5\nId = 131288 , Rating = 7.5\nId = 131289 , Rating = 3.0\nId = 131290 , Rating = 6.0\nId = 131291 , Rating = 4.5\nId = 131292 , Rating = 5.5\nId = 131293 , Rating = 5.0\nId = 131295 , Rating = 10.0\nId = 131296 , Rating = 2.5\nId = 131297 , Rating = 4.0\nId = 131298 , Rating = 7.5\nId = 131299 , Rating = 8.5\nId = 131300 , Rating = 6.0\nId = 131301 , Rating = 10.0\nId = 131302 , Rating = 9.5\nId = 131303 , Rating = 5.5\nId = 131304 , Rating = 9.5\nId = 131305 , Rating = 9.5\nId = 131306 , Rating = 5.5\nId = 131307 , Rating = 6.0\nId = 131308 , Rating = 5.5\nId = 131309 , Rating = 5.0\nId = 131310 , Rating = 9.0\nId = 131311 , Rating = 4.0\nId = 131312 , Rating = 5.0\nId = 131313 , Rating = 8.5\nId = 131314 , Rating = 5.0\nId = 131315 , Rating = 8.0\nId = 131316 , Rating = 9.0\nId = 131317 , Rating = 5.5\nId = 131318 , Rating = 9.0\nId = 131319 , Rating = 6.5\nId = 131320 , Rating = 3.0\nId = 131321 , Rating = 9.0\nId = 131322 , Rating = 8.5\nId = 131323 , Rating = 5.0\nId = 131324 , Rating = 6.0\nId = 132086 , Rating = 9.5\nId = 132087 , Rating = 6.0\nId = 132089 , Rating = 6.5\nId = 132091 , Rating = 9.5\nId = 132092 , Rating = 5.5\nId = 132093 , Rating = 9.0\nId = 132094 , Rating = 6.0\nId = 132096 , Rating = 3.0\nId = 132098 , Rating = 6.5\nId = 132099 , Rating = 6.5\nId = 132100 , Rating = 9.5\nId = 132102 , Rating = 10.0\nId = 132113 , Rating = 6.5\nId = 132114 , Rating = 10.0\nId = 132116 , Rating = 9.0\nId = 132117 , Rating = 6.0\nId = 132118 , Rating = 9.0\nId = 132119 , Rating = 9.5\nId = 132120 , Rating = 5.0\nId = 132121 , Rating = 9.0\nId = 132123 , Rating = 9.5\nId = 132125 , Rating = 6.0\nId = 132126 , Rating = 6.0\nId = 132151 , Rating = 10.0\nId = 132152 , Rating = 10.0\nId = 132153 , Rating = 1.0\nId = 132154 , Rating = 5.0\nId = 132155 , Rating = 8.0\nId = 132157 , Rating = 6.0\nId = 132158 , Rating = 9.5\nId = 132159 , Rating = 9.5\nId = 132160 , Rating = 6.0\nId = 132162 , Rating = 6.5\nId = 132163 , Rating = 9.5\nId = 132164 , Rating = 4.5\nId = 132166 , Rating = 6.5\nId = 132167 , Rating = 2.0\nId = 132169 , Rating = 9.5\nId = 132170 , Rating = 9.5\nId = 132171 , Rating = 6.5\nId = 132172 , Rating = 8.5\nId = 132173 , Rating = 5.0\nId = 132175 , Rating = 9.5\nId = 132176 , Rating = 5.5\nId = 132177 , Rating = 10.0\nId = 132178 , Rating = 9.5\nId = 132179 , Rating = 9.0\nId = 132180 , Rating = 9.5\nId = 132182 , Rating = 6.0\nId = 132184 , Rating = 5.0\nId = 132187 , Rating = 5.0\nId = 132189 , Rating = 9.5\nId = 132191 , Rating = 8.5\nId = 132192 , Rating = 9.0\nId = 132193 , Rating = 9.5\nId = 132194 , Rating = 10.0\nId = 132196 , Rating = 9.5\nId = 132197 , Rating = 9.0\nId = 132199 , Rating = 8.5\nId = 132200 , Rating = 5.0\nId = 132201 , Rating = 3.5\nId = 132202 , Rating = 6.0\nId = 132204 , Rating = 9.0\nId = 132205 , Rating = 10.0\nId = 132206 , Rating = 9.0\nId = 132208 , Rating = 10.0\nId = 132210 , Rating = 6.5\nId = 132211 , Rating = 6.5\nId = 140874 , Rating = 5.0\nId = 141561 , Rating = 10.0\nId = 141562 , Rating = 9.5\nId = 141563 , Rating = 9.0\nId = 141564 , Rating = 9.5\nId = 141565 , Rating = 10.0\nId = 141566 , Rating = 6.5\nId = 141567 , Rating = 9.5\nId = 141568 , Rating = 6.5\nId = 141569 , Rating = 9.5\nId = 141570 , Rating = 6.5\nId = 141571 , Rating = 8.0\nId = 141573 , Rating = 9.0\nId = 141574 , Rating = 5.0\nId = 141575 , Rating = 9.5\nId = 141576 , Rating = 6.0\nId = 141577 , Rating = 6.5\nId = 141736 , Rating = 2.0\nId = 141737 , Rating = 2.0\nId = 141738 , Rating = 2.0\nId = 141739 , Rating = 3.5\nId = 141740 , Rating = 6.5\nId = 141741 , Rating = 4.0\nId = 141742 , Rating = 9.0\nId = 141743 , Rating = 6.0\nId = 141744 , Rating = 3.5\nId = 141745 , Rating = 5.5\nId = 145892 , Rating = 10.0\nId = 145983 , Rating = 9.0\nId = 145999 , Rating = 9.0\nId = 146008 , Rating = 9.0\nId = 146029 , Rating = 2.5\nId = 146032 , Rating = 9.5\nId = 148802 , Rating = 4.5\nId = 148803 , Rating = 5.0\nId = 148805 , Rating = 9.5\nId = 148806 , Rating = 8.5\nId = 148807 , Rating = 3.5\nId = 148808 , Rating = 6.0\nId = 148809 , Rating = 9.0\nId = 148810 , Rating = 2.0\nId = 148811 , Rating = 9.5\nId = 148812 , Rating = 6.0\nId = 148813 , Rating = 9.0\nId = 148814 , Rating = 8.0\nId = 148815 , Rating = 5.0\nId = 148907 , Rating = 6.0\nId = 148908 , Rating = 9.0\nId = 148909 , Rating = 2.0\nId = 148910 , Rating = 6.5\nId = 148911 , Rating = 1.5\nId = 148912 , Rating = 6.0\nId = 148913 , Rating = 2.5\nId = 148914 , Rating = 1.0\nId = 148915 , Rating = 1.0\nId = 148916 , Rating = 1.5\nId = 148917 , Rating = 9.0\nId = 148918 , Rating = 6.5\nId = 148919 , Rating = 7.0\nId = 148920 , Rating = 6.0\nId = 148921 , Rating = 1.5\nId = 148922 , Rating = 3.0\nId = 148923 , Rating = 9.5\nId = 148924 , Rating = 3.0\nId = 148925 , Rating = 5.0\nId = 148926 , Rating = 9.0\nId = 148927 , Rating = 9.0\nId = 148928 , Rating = 3.0\nId = 148929 , Rating = 4.0\nId = 148930 , Rating = 6.5\nId = 148931 , Rating = 9.5\nId = 148932 , Rating = 4.5\nId = 148933 , Rating = 3.0\nId = 148934 , Rating = 2.0\nId = 148935 , Rating = 2.0\nId = 148936 , Rating = 8.5\nId = 148937 , Rating = 1.0\nId = 148938 , Rating = 5.0\nId = 148939 , Rating = 0.5\nId = 148940 , Rating = 1.5\nId = 148944 , Rating = 2.5\nId = 148945 , Rating = 1.5\nId = 148946 , Rating = 2.0\nId = 148947 , Rating = 1.0\nId = 148948 , Rating = 2.0\nId = 148949 , Rating = 1.5\nId = 148950 , Rating = 8.0\nId = 148951 , Rating = 6.5\nId = 148952 , Rating = 2.0\nId = 148953 , Rating = 9.5\nId = 148954 , Rating = 9.0\nId = 148955 , Rating = 3.5\nId = 148956 , Rating = 5.5\nId = 148957 , Rating = 6.5\nId = 148958 , Rating = 3.0\nId = 148959 , Rating = 3.5\nId = 148960 , Rating = 9.5\nId = 148962 , Rating = 1.5\nId = 148963 , Rating = 9.5\nId = 148964 , Rating = 6.0\nId = 148965 , Rating = 5.0\nId = 148966 , Rating = 5.0\nId = 148967 , Rating = 6.0\nId = 148968 , Rating = 6.0\nId = 148969 , Rating = 7.0\nId = 148970 , Rating = 1.0\nId = 148971 , Rating = 5.0\nId = 148972 , Rating = 2.5\nId = 148973 , Rating = 8.5\nId = 148974 , Rating = 5.5\nId = 148975 , Rating = 1.5\nId = 148976 , Rating = 8.5\nId = 148977 , Rating = 10.0\nId = 148978 , Rating = 5.5\nId = 148979 , Rating = 1.0\nId = 148980 , Rating = 4.0\nId = 148981 , Rating = 5.0\nId = 148982 , Rating = 2.5\nId = 148983 , Rating = 4.5\nId = 148984 , Rating = 5.5\nId = 148985 , Rating = 4.5\nId = 148986 , Rating = 1.5\nId = 148987 , Rating = 1.5\nId = 148988 , Rating = 5.5\nId = 148989 , Rating = 6.0\nId = 148990 , Rating = 2.0\nId = 148991 , Rating = 5.0\nId = 148992 , Rating = 2.0\nId = 148993 , Rating = 2.0\nId = 148994 , Rating = 9.5\nId = 148995 , Rating = 2.0\nId = 148996 , Rating = 6.5\nId = 148997 , Rating = 2.0\nId = 148998 , Rating = 1.0\nId = 148999 , Rating = 5.5\nId = 149000 , Rating = 3.0\nId = 149001 , Rating = 1.0\nId = 149002 , Rating = 6.0\nId = 149003 , Rating = 7.0\nId = 149004 , Rating = 7.5\nId = 149005 , Rating = 9.5\nId = 149006 , Rating = 6.0\nId = 149007 , Rating = 1.0\nId = 149008 , Rating = 6.5\nId = 149009 , Rating = 5.5\nId = 149010 , Rating = 9.5\nId = 149011 , Rating = 2.0\nId = 149012 , Rating = 4.5\nId = 149013 , Rating = 2.0\nId = 149014 , Rating = 5.5\nId = 149015 , Rating = 5.0\nId = 149016 , Rating = 4.5\nId = 149017 , Rating = 7.5\nId = 149018 , Rating = 5.5\nId = 149019 , Rating = 9.0\nId = 149020 , Rating = 9.0\nId = 149021 , Rating = 8.5\nId = 149022 , Rating = 1.0\nId = 149023 , Rating = 8.5\nId = 149024 , Rating = 1.0\nId = 149026 , Rating = 2.5\nId = 149027 , Rating = 4.5\nId = 149028 , Rating = 3.0\nId = 149029 , Rating = 9.0\nId = 149030 , Rating = 8.0\nId = 149031 , Rating = 9.0\nId = 149032 , Rating = 7.5\nId = 149033 , Rating = 5.5\nId = 149034 , Rating = 5.5\nId = 149035 , Rating = 6.5\nId = 149036 , Rating = 8.5\nId = 149037 , Rating = 2.5\nId = 149038 , Rating = 3.0\nId = 149039 , Rating = 5.0\nId = 149040 , Rating = 8.5\nId = 149041 , Rating = 4.5\nId = 149042 , Rating = 1.5\nId = 149043 , Rating = 4.0\nId = 149044 , Rating = 5.0\nId = 149045 , Rating = 10.0\nId = 149046 , Rating = 3.0\nId = 149047 , Rating = 4.0\nId = 149048 , Rating = 5.5\nId = 149049 , Rating = 8.0\nId = 149050 , Rating = 6.5\nId = 149051 , Rating = 8.0\nId = 149052 , Rating = 8.5\nId = 149053 , Rating = 5.0\nId = 149054 , Rating = 5.0\nId = 149055 , Rating = 5.0\nId = 149056 , Rating = 2.0\nId = 149057 , Rating = 5.5\nId = 149058 , Rating = 2.5\nId = 149059 , Rating = 5.5\nId = 149060 , Rating = 6.0\nId = 149061 , Rating = 4.5\nId = 149062 , Rating = 8.5\nId = 149063 , Rating = 8.5\nId = 149064 , Rating = 5.0\nId = 149065 , Rating = 4.0\nId = 149066 , Rating = 10.0\nId = 149067 , Rating = 9.5\nId = 149068 , Rating = 2.0\nId = 149069 , Rating = 7.5\nId = 149070 , Rating = 5.5\nId = 149072 , Rating = 9.0\nId = 149073 , Rating = 2.5\nId = 149074 , Rating = 9.5\nId = 149075 , Rating = 1.0\nId = 149076 , Rating = 9.5\nId = 149077 , Rating = 6.0\nId = 149078 , Rating = 5.5\nId = 149079 , Rating = 7.5\nId = 149080 , Rating = 4.5\nId = 149081 , Rating = 2.0\nId = 149082 , Rating = 7.5\nId = 149083 , Rating = 2.0\nId = 149084 , Rating = 9.0\nId = 149085 , Rating = 9.5\nId = 149086 , Rating = 8.0\nId = 149087 , Rating = 5.0\nId = 149088 , Rating = 8.5\nId = 149089 , Rating = 9.0\nId = 149090 , Rating = 5.5\nId = 149091 , Rating = 3.5\nId = 149092 , Rating = 6.5\nId = 149093 , Rating = 3.0\nId = 149094 , Rating = 10.0\nId = 149095 , Rating = 5.5\nId = 149096 , Rating = 9.5\nId = 149097 , Rating = 1.0\nId = 149098 , Rating = 1.5\nId = 149099 , Rating = 2.5\nId = 149100 , Rating = 7.0\nId = 149101 , Rating = 1.0\nId = 149102 , Rating = 2.0\nId = 149103 , Rating = 4.5\nId = 149104 , Rating = 8.5\nId = 149105 , Rating = 2.0\nId = 149106 , Rating = 6.5\nId = 149107 , Rating = 8.5\nId = 149108 , Rating = 9.5\nId = 149109 , Rating = 4.5\nId = 150040 , Rating = 4.5\nId = 150041 , Rating = 3.5\nId = 150042 , Rating = 9.0\nId = 150043 , Rating = 9.0\nId = 150044 , Rating = 1.5\nId = 150045 , Rating = 1.0\nId = 150046 , Rating = 5.0\nId = 150047 , Rating = 6.5\nId = 150048 , Rating = 3.0\nId = 150049 , Rating = 5.0\nId = 150050 , Rating = 6.0\nId = 150051 , Rating = 10.0\nId = 150052 , Rating = 5.5\nId = 150054 , Rating = 9.0\nId = 150055 , Rating = 3.5\nId = 150056 , Rating = 9.5\nId = 150057 , Rating = 9.0\nId = 150058 , Rating = 6.0\nId = 150059 , Rating = 1.5\nId = 150081 , Rating = 9.0\nId = 150082 , Rating = 5.5\nId = 150083 , Rating = 9.0\nId = 150084 , Rating = 6.0\nId = 150085 , Rating = 6.0\nId = 150086 , Rating = 2.0\nId = 150087 , Rating = 9.5\nId = 150088 , Rating = 5.5\nId = 150089 , Rating = 6.0\nId = 150090 , Rating = 5.5\nId = 150091 , Rating = 6.5\nId = 150092 , Rating = 3.0\nId = 150093 , Rating = 2.0\nId = 150094 , Rating = 8.5\nId = 150095 , Rating = 10.0\nId = 150096 , Rating = 4.5\nId = 150097 , Rating = 5.0\nId = 150098 , Rating = 6.0\nId = 150099 , Rating = 8.5\nId = 150100 , Rating = 6.5\nId = 150101 , Rating = 6.0\nId = 150102 , Rating = 6.5\nId = 150103 , Rating = 4.0\nId = 150104 , Rating = 6.5\nId = 150105 , Rating = 9.5\nId = 150106 , Rating = 5.5\nId = 150107 , Rating = 5.5\nId = 150108 , Rating = 5.5\nId = 150109 , Rating = 5.5\nId = 150110 , Rating = 8.5\nId = 150111 , Rating = 5.5\nId = 150112 , Rating = 5.5\nId = 150113 , Rating = 5.5\nId = 150114 , Rating = 4.0\nId = 150115 , Rating = 9.0\nId = 150116 , Rating = 5.5\nId = 150117 , Rating = 6.5\nId = 150118 , Rating = 10.0\nId = 150120 , Rating = 9.0\nId = 150121 , Rating = 9.5\nId = 150122 , Rating = 3.5\nId = 150123 , Rating = 3.5\nId = 150124 , Rating = 4.0\nId = 150125 , Rating = 6.0\nId = 150126 , Rating = 9.0\nId = 150127 , Rating = 7.5\nId = 150128 , Rating = 1.5\nId = 150129 , Rating = 2.5\nId = 150130 , Rating = 9.0\nId = 150131 , Rating = 5.5\nId = 150132 , Rating = 8.5\nId = 150133 , Rating = 6.5\nId = 150134 , Rating = 8.5\nId = 150135 , Rating = 2.5\nId = 150136 , Rating = 2.0\nId = 150137 , Rating = 4.5\nId = 150138 , Rating = 6.0\nId = 150139 , Rating = 8.5\nId = 150140 , Rating = 5.5\nId = 150141 , Rating = 6.5\nId = 150142 , Rating = 9.0\nId = 150143 , Rating = 8.5\nId = 150144 , Rating = 5.5\nId = 150145 , Rating = 9.0\nId = 150146 , Rating = 10.0\nId = 150147 , Rating = 2.5\nId = 150148 , Rating = 7.0\nId = 150149 , Rating = 5.5\nId = 150150 , Rating = 9.5\nId = 150151 , Rating = 8.0\nId = 150152 , Rating = 5.0\nId = 150153 , Rating = 6.0\nId = 150154 , Rating = 8.5\nId = 150155 , Rating = 6.0\nId = 150157 , Rating = 6.0\nId = 150158 , Rating = 10.0\nId = 150160 , Rating = 8.0\nId = 150161 , Rating = 9.0\nId = 151725 , Rating = 9.0\nId = 151726 , Rating = 5.0\nId = 151727 , Rating = 9.5\nId = 151728 , Rating = 6.5\nId = 151729 , Rating = 6.0\nId = 151730 , Rating = 6.5\nId = 151731 , Rating = 1.5\nId = 151732 , Rating = 2.0\nId = 151733 , Rating = 10.0\nId = 151734 , Rating = 10.0\nId = 151735 , Rating = 6.0\nId = 151736 , Rating = 9.5\nId = 151737 , Rating = 9.5\nId = 151738 , Rating = 9.0\nId = 151739 , Rating = 4.0\nId = 151740 , Rating = 9.5\nId = 151741 , Rating = 9.0\nId = 151742 , Rating = 9.5\nId = 151743 , Rating = 6.5\nId = 151744 , Rating = 9.5\nId = 151745 , Rating = 6.5\nId = 151746 , Rating = 8.5\nId = 151747 , Rating = 8.0\nId = 153103 , Rating = 6.5\nId = 153104 , Rating = 3.0\nId = 153105 , Rating = 1.5\nId = 153106 , Rating = 9.5\nId = 153107 , Rating = 6.0\nId = 153108 , Rating = 5.5\nId = 153109 , Rating = 2.0\nId = 153110 , Rating = 6.0\nId = 153111 , Rating = 5.5\nId = 153112 , Rating = 7.5\nId = 153113 , Rating = 7.5\nId = 153114 , Rating = 6.5\nId = 153115 , Rating = 7.0\nId = 153116 , Rating = 5.5\nId = 153117 , Rating = 9.0\nId = 153118 , Rating = 7.0\nId = 153119 , Rating = 10.0\nId = 153120 , Rating = 4.5\nId = 153121 , Rating = 9.0\nId = 153122 , Rating = 8.5\nId = 153123 , Rating = 8.5\nId = 153124 , Rating = 9.0\nId = 153125 , Rating = 9.5\nId = 153126 , Rating = 10.0\nId = 153127 , Rating = 2.0\nId = 153128 , Rating = 9.0\nId = 153129 , Rating = 10.0\nId = 153569 , Rating = 7.0\nId = 153668 , Rating = 7.0\nId = 153680 , Rating = 6.0\nId = 153717 , Rating = 10.0\nId = 153751 , Rating = 6.5\nId = 153760 , Rating = 2.0\nId = 153793 , Rating = 5.5\nId = 153795 , Rating = 4.5\nId = 153803 , Rating = 3.0\nId = 153829 , Rating = 6.5\nId = 153841 , Rating = 8.0\nId = 153845 , Rating = 5.0\nId = 153849 , Rating = 4.0\nId = 153868 , Rating = 7.5\nId = 153898 , Rating = 4.5\nId = 153905 , Rating = 5.0\nId = 153907 , Rating = 9.5\nId = 153919 , Rating = 5.5\nId = 153937 , Rating = 10.0\nId = 153971 , Rating = 10.0\nId = 153994 , Rating = 9.0\nId = 153997 , Rating = 5.5\nId = 154000 , Rating = 5.5\nId = 154037 , Rating = 9.5\nId = 154045 , Rating = 9.5\nId = 154064 , Rating = 2.0\nId = 154109 , Rating = 9.0\nId = 154117 , Rating = 10.0\nId = 154156 , Rating = 10.0\nId = 154161 , Rating = 6.0\nId = 154172 , Rating = 6.5\nId = 154191 , Rating = 9.5\nId = 154197 , Rating = 5.0\nId = 154225 , Rating = 7.5\nId = 154226 , Rating = 5.5\nId = 154236 , Rating = 9.5\nId = 154251 , Rating = 6.0\nId = 154289 , Rating = 6.5\nId = 154293 , Rating = 5.0\nId = 154382 , Rating = 8.5\nId = 154431 , Rating = 9.5\nId = 154434 , Rating = 8.0\nId = 154458 , Rating = 9.5\nId = 154466 , Rating = 8.5\nId = 154475 , Rating = 5.0\nId = 154484 , Rating = 5.5\nId = 154499 , Rating = 10.0\nId = 154504 , Rating = 3.0\nId = 154510 , Rating = 5.5\nId = 154515 , Rating = 9.5\nId = 154522 , Rating = 5.0\nId = 154540 , Rating = 10.0\nId = 154551 , Rating = 5.0\nId = 154559 , Rating = 2.0\nId = 154577 , Rating = 6.5\nId = 154584 , Rating = 10.0\nId = 154593 , Rating = 5.5\nId = 154634 , Rating = 8.5\nId = 158146 , Rating = 6.0\nId = 158147 , Rating = 9.5\nId = 158148 , Rating = 6.0\nId = 158149 , Rating = 6.0\nId = 158150 , Rating = 2.0\nId = 158151 , Rating = 9.5\nId = 158152 , Rating = 10.0\nId = 158153 , Rating = 6.0\n"
],
[
"",
"_____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"
]
] |
d0aed9f64158df45d5903a7b70fb0b77f1355df7 | 5,729 | ipynb | Jupyter Notebook | hw2.ipynb | dyllanwli/spatialstat-notabook | a0b6f86712eafb1d6c4490f48faa95a9b4a26c6c | [
"MIT"
] | null | null | null | hw2.ipynb | dyllanwli/spatialstat-notabook | a0b6f86712eafb1d6c4490f48faa95a9b4a26c6c | [
"MIT"
] | null | null | null | hw2.ipynb | dyllanwli/spatialstat-notabook | a0b6f86712eafb1d6c4490f48faa95a9b4a26c6c | [
"MIT"
] | null | null | null | 5,729 | 5,729 | 0.705533 | [
[
[
"!pip install rpy2",
"Requirement already satisfied: rpy2 in /usr/local/lib/python3.6/dist-packages (3.2.7)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.6/dist-packages (from rpy2) (2.11.2)\nRequirement already satisfied: tzlocal in /usr/local/lib/python3.6/dist-packages (from rpy2) (1.5.1)\nRequirement already satisfied: cffi>=1.13.1 in /usr/local/lib/python3.6/dist-packages (from rpy2) (1.14.2)\nRequirement already satisfied: simplegeneric in /usr/local/lib/python3.6/dist-packages (from rpy2) (0.8.1)\nRequirement already satisfied: pytest in /usr/local/lib/python3.6/dist-packages (from rpy2) (3.6.4)\nRequirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from rpy2) (2018.9)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from jinja2->rpy2) (1.1.1)\nRequirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi>=1.13.1->rpy2) (2.20)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from pytest->rpy2) (50.3.0)\nRequirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.6/dist-packages (from pytest->rpy2) (1.4.0)\nRequirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.6/dist-packages (from pytest->rpy2) (0.7.1)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from pytest->rpy2) (1.15.0)\nRequirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.6/dist-packages (from pytest->rpy2) (1.9.0)\nRequirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.6/dist-packages (from pytest->rpy2) (20.2.0)\nRequirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.6/dist-packages (from pytest->rpy2) (8.5.0)\n"
],
[
"import numpy as np\nimport pandas as pd\n\nfrom sklearn.gaussian_process import GaussianProcessRegressor",
"_____no_output_____"
],
[
"# Generate n = 1500 random locations from [0, 10] × [0, 10], denoted as si = (loni, lati), for i = 1, · · · , 1500.\nn = [ x*10 for x in np.random.rand(1500, 2) ]",
"_____no_output_____"
],
[
"# Generate data y from a spatial Gaussian process regression model with an intercept, two covariates (lon and lat)\n# a spatial random effect following GP with mean 0 and covariance C = 2∗exp(−d/1.5), and a nugget effect with τ2 = 0.1\n",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"# R package names\npacknames = ('ggplot2', 'spBayes')\n\n# R vector of strings\nfrom rpy2.robjects.vectors import StrVector\n\n# Selectively install what needs to be install.\n# We are fancy, just because we can.\nnames_to_install = [x for x in packnames if not rpackages.isinstalled(x)]\nif len(names_to_install) > 0:\n utils.install_packages(StrVector(names_to_install))",
"_____no_output_____"
],
[
"from rpy2 import robjects\npi = robjects.r['pi']",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0aeea75e916ad004c7572fa535c2f34914bc0d9 | 36,613 | ipynb | Jupyter Notebook | C03/w02/C03w02_nb_pa1.ipynb | pascal-p/ML_UW_Spec | 5e19916b62fd776b1412ba31d06b41049a1ec7d8 | [
"BSD-3-Clause"
] | null | null | null | C03/w02/C03w02_nb_pa1.ipynb | pascal-p/ML_UW_Spec | 5e19916b62fd776b1412ba31d06b41049a1ec7d8 | [
"BSD-3-Clause"
] | null | null | null | C03/w02/C03w02_nb_pa1.ipynb | pascal-p/ML_UW_Spec | 5e19916b62fd776b1412ba31d06b41049a1ec7d8 | [
"BSD-3-Clause"
] | null | null | null | 30.767227 | 632 | 0.55341 | [
[
[
"# Implementing logistic regression from scratch\n\nThe goal of this notebook is to implement your own logistic regression classifier. We will:\n\n * Extract features from Amazon product reviews.\n * Convert an SFrame into a NumPy array.\n * Implement the link function for logistic regression.\n * Write a function to compute the derivative of the log likelihood function with respect to a single coefficient.\n * Implement gradient ascent.\n * Given a set of coefficients, predict sentiments.\n * Compute classification accuracy for the logistic regression model.\n \nLet's get started!\n \n## Fire up Turi Create\n\nMake sure you have the latest version of Turi Create.",
"_____no_output_____"
]
],
[
[
"import turicreate",
"_____no_output_____"
],
[
"## utils for this notebooks moved into its own package\nimport sys\nsys.path.append(\"../common\")\n\nfrom utils import time_it, assert_all, get_numpy_data, load_important_words",
"_____no_output_____"
]
],
[
[
"## Load review dataset",
"_____no_output_____"
],
[
"For this assignment, we will use a subset of the Amazon product review dataset. The subset was chosen to contain similar numbers of positive and negative reviews, as the original dataset consisted primarily of positive reviews.",
"_____no_output_____"
]
],
[
[
"products = turicreate.SFrame('../data/amazon_baby_subset.sframe/')",
"_____no_output_____"
]
],
[
[
"One column of this dataset is 'sentiment', corresponding to the class label with +1 indicating a review with positive sentiment and -1 indicating one with negative sentiment.",
"_____no_output_____"
]
],
[
[
"products['sentiment'][1:20]",
"_____no_output_____"
]
],
[
[
"Let us quickly explore more of this dataset. The 'name' column indicates the name of the product. Here we list the first 10 products in the dataset. We then count the number of positive and negative reviews.",
"_____no_output_____"
]
],
[
[
"products.head(10)['name']",
"_____no_output_____"
],
[
"print('# of positive reviews =', len(products[products['sentiment'] == 1]))\nprint('# of negative reviews =', len(products[products['sentiment'] == -1]))",
"# of positive reviews = 26579\n# of negative reviews = 26493\n"
]
],
[
[
"**Note:** For this assignment, we eliminated class imbalance by choosing \na subset of the data with a similar number of positive and negative reviews. \n\n## Apply text cleaning on the review data\n\nIn this section, we will perform some simple feature cleaning using **SFrames**. The last assignment used all words in building bag-of-words features, but here we limit ourselves to 193 words (for simplicity). We compiled a list of 193 most frequent words into a JSON file. \n\nNow, we will load these words from this JSON file:",
"_____no_output_____"
]
],
[
[
"important_words = load_important_words()\n\nimportant_words[0:10], len(important_words)",
"_____no_output_____"
]
],
[
[
"Now, we will perform 2 simple data transformations:\n\n1. Remove punctuation using [Python's built-in](https://docs.python.org/2/library/string.html) string functionality.\n2. Compute word counts (only for **important_words**)\n\nWe start with *Step 1* which can be done as follows:",
"_____no_output_____"
]
],
[
[
"import string\n\ndef remove_punctuation(text):\n translator = text.maketrans('', '', string.punctuation)\n return text.translate(translator)\n\nproducts['review_clean'] = products['review'].apply(remove_punctuation)",
"_____no_output_____"
]
],
[
[
"Now we proceed with *Step 2*. For each word in **important_words**, we compute a count for the number of times the word occurs in the review. We will store this count in a separate column (one for each word). The result of this feature processing is a single column for each word in **important_words** which keeps a count of the number of times the respective word occurs in the review text.\n\n\n**Note:** There are several ways of doing this. In this assignment, we use the built-in *count* function for Python lists. Each review string is first split into individual words and the number of occurances of a given word is counted.",
"_____no_output_____"
]
],
[
[
"for word in important_words:\n products[word] = products['review_clean'].apply(lambda s: s.split().count(word))",
"_____no_output_____"
],
[
"products.column_names()[0:10], len(products.column_names())",
"_____no_output_____"
]
],
[
[
"The SFrame **products** now contains one column for each of the 193 **important_words**. As an example, the column **perfect** contains a count of the number of times the word **perfect** occurs in each of the reviews.",
"_____no_output_____"
]
],
[
[
"products['perfect'][0:10], len(products['perfect'])",
"_____no_output_____"
]
],
[
[
"Now, write some code to compute the number of product reviews that contain the word **perfect**.\n\n**Hint**: \n* First create a column called `contains_perfect` which is set to 1 if the count of the word **perfect** (stored in column **perfect**) is >= 1.\n* Sum the number of 1s in the column `contains_perfect`.",
"_____no_output_____"
]
],
[
[
"products['contains_perfect'] = products['perfect'].apply(lambda c: 1 if c >= 1 else 0)\n\nsum(products['contains_perfect'])",
"_____no_output_____"
],
[
"sum(products['great'].apply(lambda c: 1 if c >= 1 else 0)), sum(products['quality'].apply(lambda c: 1 if c >= 1 else 0))",
"_____no_output_____"
]
],
[
[
"**Quiz Question**. How many reviews contain the word **perfect**?\n - cf. above cell.",
"_____no_output_____"
],
[
"## Convert SFrame to NumPy array\n\nAs you have seen previously, NumPy is a powerful library for doing matrix manipulation. Let us convert our data to matrices and then implement our algorithms with matrices.\n\nFirst, make sure you can perform the following import. If it doesn't work, you need to go back to the terminal and run\n\n`pip install numpy`.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"We now provide you with a function that extracts columns from an SFrame and converts them into a NumPy array. Two arrays are returned: one representing features and another representing class labels. Note that the feature matrix includes an additional column 'intercept' to take account of the intercept term.",
"_____no_output_____"
],
[
"Let us convert the data into NumPy arrays.",
"_____no_output_____"
]
],
[
[
"# Warning: This may take a few minutes...\nfeature_matrix, sentiment = get_numpy_data(products, important_words, 'sentiment') ",
"_____no_output_____"
]
],
[
[
"**Are you running this notebook on an Amazon EC2 t2.micro instance?** (If you are using your own machine, please skip this section)\n\nIt has been reported that t2.micro instances do not provide sufficient power to complete the conversion in acceptable amount of time. For interest of time, please refrain from running `get_numpy_data` function. Instead, download the [binary file](https://s3.amazonaws.com/static.dato.com/files/coursera/course-3/numpy-arrays/module-3-assignment-numpy-arrays.npz) containing the four NumPy arrays you'll need for the assignment. To load the arrays, run the following commands:\n```\narrays = np.load('module-3-assignment-numpy-arrays.npz')\nfeature_matrix, sentiment = arrays['feature_matrix'], arrays['sentiment']\n```",
"_____no_output_____"
],
[
"**Quiz Question:** How many features are there in the **feature_matrix**?",
"_____no_output_____"
]
],
[
[
"feature_matrix.shape, feature_matrix.shape[1] ## == number of features / number of important word + 1 (interept)",
"_____no_output_____"
]
],
[
[
"**Quiz Question:** Assuming that the intercept is present, how does the number of features in **feature_matrix** relate to the number of features in the logistic regression model? <br />\n Let x = [number of features in feature_matrix] and y = [number of features in logistic regression model].",
"_____no_output_____"
],
[
" - [ ] y = x - 1\n - [x] y = x\n - [ ] y = x + 1\n - [ ] None of the above",
"_____no_output_____"
],
[
"Now, let us see what the **sentiment** column looks like:",
"_____no_output_____"
]
],
[
[
"sentiment",
"_____no_output_____"
]
],
[
[
"## Estimating conditional probability with link function",
"_____no_output_____"
],
[
"Recall from lecture that the link function is given by:\n$$\nP(y_i = +1 | \\mathbf{x}_i,\\mathbf{w}) = \\frac{1}{1 + \\exp(-\\mathbf{w}^T h(\\mathbf{x}_i))},\n$$\n\nwhere the feature vector $h(\\mathbf{x}_i)$ represents the word counts of **important_words** in the review $\\mathbf{x}_i$. Complete the following function that implements the link function:",
"_____no_output_____"
]
],
[
[
"'''\nproduces probablistic estimate for P(y_i = +1 | x_i, w).\nestimate ranges between 0 and 1.\n'''\ndef predict_probability(feature_matrix, coefficients):\n score = np.dot(feature_matrix, coefficients) ## Take dot product of feature_matrix and coefficients \n \n return 1. / (1. + np.exp(-score)) # Compute P(y_i = +1 | x_i, w) using the link function ",
"_____no_output_____"
]
],
[
[
"**Aside**. How the link function works with matrix algebra\n\nSince the word counts are stored as columns in **feature_matrix**, each $i$-th row of the matrix corresponds to the feature vector $h(\\mathbf{x}_i)$:\n$$\n[\\text{feature_matrix}] =\n\\left[\n\\begin{array}{c}\nh(\\mathbf{x}_1)^T \\\\\nh(\\mathbf{x}_2)^T \\\\\n\\vdots \\\\\nh(\\mathbf{x}_N)^T\n\\end{array}\n\\right] =\n\\left[\n\\begin{array}{cccc}\nh_0(\\mathbf{x}_1) & h_1(\\mathbf{x}_1) & \\cdots & h_D(\\mathbf{x}_1) \\\\\nh_0(\\mathbf{x}_2) & h_1(\\mathbf{x}_2) & \\cdots & h_D(\\mathbf{x}_2) \\\\\n\\vdots & \\vdots & \\ddots & \\vdots \\\\\nh_0(\\mathbf{x}_N) & h_1(\\mathbf{x}_N) & \\cdots & h_D(\\mathbf{x}_N)\n\\end{array}\n\\right]\n$$\n\nBy the rules of matrix multiplication, the score vector containing elements $\\mathbf{w}^T h(\\mathbf{x}_i)$ is obtained by multiplying **feature_matrix** and the coefficient vector $\\mathbf{w}$.\n$$\n[\\text{score}] =\n[\\text{feature_matrix}]\\mathbf{w} =\n\\left[\n\\begin{array}{c}\nh(\\mathbf{x}_1)^T \\\\\nh(\\mathbf{x}_2)^T \\\\\n\\vdots \\\\\nh(\\mathbf{x}_N)^T\n\\end{array}\n\\right]\n\\mathbf{w}\n= \\left[\n\\begin{array}{c}\nh(\\mathbf{x}_1)^T\\mathbf{w} \\\\\nh(\\mathbf{x}_2)^T\\mathbf{w} \\\\\n\\vdots \\\\\nh(\\mathbf{x}_N)^T\\mathbf{w}\n\\end{array}\n\\right]\n= \\left[\n\\begin{array}{c}\n\\mathbf{w}^T h(\\mathbf{x}_1) \\\\\n\\mathbf{w}^T h(\\mathbf{x}_2) \\\\\n\\vdots \\\\\n\\mathbf{w}^T h(\\mathbf{x}_N)\n\\end{array}\n\\right]\n$$",
"_____no_output_____"
],
[
"**Checkpoint**\n\nJust to make sure we are on the right track, we have provided a few examples. If our `predict_probability` function is implemented correctly, then the following should pass:",
"_____no_output_____"
]
],
[
[
"dummy_feature_matrix = np.array([[1., 2., 3.], [1., -1., -1]])\ndummy_coefficients = np.array([1., 3., -1.])\n\ncorrect_scores = np.array([1.*1. + 2.*3. + 3.*(-1.), 1.*1. + (-1.)*3. + (-1.)*(-1.)])\ncorrect_preds = np.array([1. / (1 + np.exp(-correct_scores[0])), 1. / (1 + np.exp(-correct_scores[1]))])\n\neps = 1e-7\nassert_all(lambda t: abs(t[0] - t[1]) <= eps, zip(predict_probability(dummy_feature_matrix, dummy_coefficients), correct_preds))",
"_____no_output_____"
]
],
[
[
"## Compute derivative of log likelihood with respect to a single coefficient\n\nRecall from lecture:\n$$\n\\frac{\\partial\\ell}{\\partial w_j} = \\sum_{i=1}^N h_j(\\mathbf{x}_i)\\left(\\mathbf{1}[y_i = +1] - P(y_i = +1 | \\mathbf{x}_i, \\mathbf{w})\\right)\n$$\n\nWe will now write a function that computes the derivative of log likelihood with respect to a single coefficient $w_j$. The function accepts two arguments:\n* `errors` vector containing $\\mathbf{1}[y_i = +1] - P(y_i = +1 | \\mathbf{x}_i, \\mathbf{w})$ for all $i$.\n* `feature` vector containing $h_j(\\mathbf{x}_i)$ for all $i$. \n\nComplete the following code block:",
"_____no_output_____"
]
],
[
[
"def feature_derivative(errors, features): \n return np.dot(errors, features) # Compute the dot product...",
"_____no_output_____"
]
],
[
[
"In the main lecture, our focus was on the likelihood. In the advanced optional video, however, we introduced a transformation of this likelihood---called the log likelihood---that simplifies the derivation of the gradient and is more numerically stable. Due to its numerical stability, we will use the log likelihood instead of the likelihood to assess the algorithm.\n\nThe log likelihood is computed using the following formula (see the advanced optional video if you are curious about the derivation of this equation):\n\n$$\\ell\\ell(\\mathbf{w}) = \\sum_{i=1}^N \\Big( (\\mathbf{1}[y_i = +1] - 1)\\mathbf{w}^T h(\\mathbf{x}_i) - \\ln\\left(1 + \\exp(-\\mathbf{w}^T h(\\mathbf{x}_i))\\right) \\Big) $$\n\nWe provide a function to compute the log likelihood for the entire dataset. ",
"_____no_output_____"
]
],
[
[
"def compute_log_likelihood(feature_matrix, sentiment, coefficients):\n indic = (sentiment == +1)\n scores = np.dot(feature_matrix, coefficients)\n logexp = np.log(1. + np.exp(-scores))\n \n # Simple check to prevent overflow\n mask = np.isinf(logexp)\n logexp[mask] = -scores[mask]\n \n return np.sum((indic - 1) * scores - logexp)",
"_____no_output_____"
]
],
[
[
"**Checkpoint**\n\nJust to make sure we are on the same page, run the following code block and check that the outputs match.",
"_____no_output_____"
]
],
[
[
"dummy_feature_matrix = np.array([[1.,2.,3.], [1.,-1.,-1]])\ndummy_coefficients = np.array([1., 3., -1.])\ndummy_sentiment = np.array([-1, 1])\n\ncorrect_indicators = np.array( [-1 == +1, 1 == +1])\ncorrect_scores = np.array( [1.*1. + 2.*3. + 3.*(-1.), 1.*1. + (-1.)*3. + (-1.)*(-1.)])\ncorrect_first_term = np.array( [(correct_indicators[0]-1)*correct_scores[0], (correct_indicators[1]-1)*correct_scores[1]])\ncorrect_second_term = np.array( [np.log(1. + np.exp(-correct_scores[0])), np.log(1. + np.exp(-correct_scores[1]))])\n\ncorrect_ll = sum([correct_first_term[0] - correct_second_term[0], correct_first_term[1] - correct_second_term[1]]) \n\nassert abs(compute_log_likelihood(dummy_feature_matrix, dummy_sentiment, dummy_coefficients) - correct_ll) <= eps",
"_____no_output_____"
]
],
[
[
"## Taking gradient steps",
"_____no_output_____"
],
[
"Now we are ready to implement our own logistic regression. All we have to do is to write a gradient ascent function that takes gradient steps towards the optimum. \n\nComplete the following function to solve the logistic regression model using gradient ascent:",
"_____no_output_____"
]
],
[
[
"from math import sqrt\n\ndef logistic_regression(feature_matrix, sentiment, initial_coefficients, step_size, max_iter):\n coeffs = np.array(initial_coefficients) # make sure it's a numpy array\n \n for itr in range(max_iter):\n # Predict P(y_i = +1|x_i,w) using your predict_probability() function\n preds = predict_probability(feature_matrix, coeffs)\n indic = (sentiment == +1) ## Compute indicator value for (y_i = +1)\n errors = indic - preds ## Compute the errors as indicator - predictions\n \n for jx in range(len(coeffs)): # loop over each coefficient\n # Recall that feature_matrix[:, jx] is the feature column associated with coeffs[j].\n # Compute the derivative for coeffs[jx]. Save it in a variable called derivative\n derivative = feature_derivative(errors, feature_matrix[:, jx])\n \n # add the step size times the derivative to the current coefficient\n coeffs[jx] += step_size * derivative \n \n # Checking whether log likelihood is increasing\n if itr <= 15 or (itr <= 100 and itr % 10 == 0) or (itr <= 1000 and itr % 100 == 0) \\\n or (itr <= 10000 and itr % 1000 == 0) or itr % 10000 == 0:\n lp = compute_log_likelihood(feature_matrix, sentiment, coeffs)\n print('iteration %*d: log likelihood of observed labels = %.8f' % \\\n (int(np.ceil(np.log10(max_iter))), itr, lp))\n return coeffs",
"_____no_output_____"
]
],
[
[
"Now, let us run the logistic regression solver.",
"_____no_output_____"
]
],
[
[
"coefficients = logistic_regression(feature_matrix, sentiment, initial_coefficients=np.zeros(194),\n step_size=1e-7, max_iter=301)",
"iteration 0: log likelihood of observed labels = -36780.91768478\niteration 1: log likelihood of observed labels = -36775.13434712\niteration 2: log likelihood of observed labels = -36769.35713564\niteration 3: log likelihood of observed labels = -36763.58603240\niteration 4: log likelihood of observed labels = -36757.82101962\niteration 5: log likelihood of observed labels = -36752.06207964\niteration 6: log likelihood of observed labels = -36746.30919497\niteration 7: log likelihood of observed labels = -36740.56234821\niteration 8: log likelihood of observed labels = -36734.82152213\niteration 9: log likelihood of observed labels = -36729.08669961\niteration 10: log likelihood of observed labels = -36723.35786366\niteration 11: log likelihood of observed labels = -36717.63499744\niteration 12: log likelihood of observed labels = -36711.91808422\niteration 13: log likelihood of observed labels = -36706.20710739\niteration 14: log likelihood of observed labels = -36700.50205049\niteration 15: log likelihood of observed labels = -36694.80289716\niteration 20: log likelihood of observed labels = -36666.39512033\niteration 30: log likelihood of observed labels = -36610.01327118\niteration 40: log likelihood of observed labels = -36554.19728365\niteration 50: log likelihood of observed labels = -36498.93316099\niteration 60: log likelihood of observed labels = -36444.20783914\niteration 70: log likelihood of observed labels = -36390.00909449\niteration 80: log likelihood of observed labels = -36336.32546144\niteration 90: log likelihood of observed labels = -36283.14615871\niteration 100: log likelihood of observed labels = -36230.46102347\niteration 200: log likelihood of observed labels = -35728.89418769\niteration 300: log likelihood of observed labels = -35268.51212683\n"
]
],
[
[
"**Quiz Question:** As each iteration of gradient ascent passes, does the log likelihood increase or decrease?\n - increase",
"_____no_output_____"
],
[
"## Predicting sentiments",
"_____no_output_____"
],
[
"Recall from lecture that class predictions for a data point $\\mathbf{x}$ can be computed from the coefficients $\\mathbf{w}$ using the following formula:\n$$\n\\hat{y}_i = \n\\left\\{\n\\begin{array}{ll}\n +1 & \\mathbf{x}_i^T\\mathbf{w} > 0 \\\\\n -1 & \\mathbf{x}_i^T\\mathbf{w} \\leq 0 \\\\\n\\end{array} \n\\right.\n$$\n\nNow, we will write some code to compute class predictions. We will do this in two steps:\n* **Step 1**: First compute the **scores** using **feature_matrix** and **coefficients** using a dot product.\n* **Step 2**: Using the formula above, compute the class predictions from the scores.\n\nStep 1 can be implemented as follows:",
"_____no_output_____"
]
],
[
[
"# Compute the scores as a dot product between feature_matrix and coefficients.\nscores = np.dot(feature_matrix, coefficients)\nlen(scores), scores",
"_____no_output_____"
]
],
[
[
"Now, complete the following code block for **Step 2** to compute the class predictions using the **scores** obtained above:",
"_____no_output_____"
]
],
[
[
"preds = np.where(scores > 0., 1, -1)\nlen(scores), scores",
"_____no_output_____"
]
],
[
[
"**Quiz Question:** How many reviews were predicted to have positive sentiment?",
"_____no_output_____"
]
],
[
[
"n_pos = np.where(scores > 0., 1, 0).sum()\nn_neg = np.where(scores > 0., 0, 1).sum()\nassert n_pos + n_neg == len(scores)\n\nn_pos",
"_____no_output_____"
],
[
"n_pos, n_neg = len(preds[preds == 1]), len(preds[preds == -1])\nassert n_pos + n_neg == len(scores)\n\nn_pos",
"_____no_output_____"
]
],
[
[
"## Measuring accuracy\n\nWe will now measure the classification accuracy of the model. Recall from the lecture that the classification accuracy can be computed as follows:\n\n$$\n\\mbox{accuracy} = \\frac{\\mbox{# correctly classified data points}}{\\mbox{# total data points}}\n$$\n\nComplete the following code block to compute the accuracy of the model.",
"_____no_output_____"
]
],
[
[
"np.where(sentiment - preds != 0, 1, 0).sum()",
"_____no_output_____"
],
[
"n = len(products)\n\nnum_mistakes = np.where(sentiment - preds != 0, 1, 0).sum()\naccuracy = (n - num_mistakes) / n \nprint(\"-----------------------------------------------------\")\nprint(f'# Reviews correctly classified = {n - num_mistakes}')\nprint(f'# Reviews incorrectly classified = {num_mistakes}')\nprint(f'# Reviews total = {n}')\nprint(\"-----------------------------------------------------\")\nprint(f'Accuracy = {accuracy:.2f}')",
"-----------------------------------------------------\n# Reviews correctly classified = 39903\n# Reviews incorrectly classified = 13169\n# Reviews total = 53072\n-----------------------------------------------------\nAccuracy = 0.75\n"
]
],
[
[
"**Quiz Question**: What is the accuracy of the model on predictions made above? (round to 2 digits of accuracy)",
"_____no_output_____"
],
[
"## Which words contribute most to positive & negative sentiments?",
"_____no_output_____"
],
[
"Recall that in Module 2 assignment, we were able to compute the \"**most positive words**\". These are words that correspond most strongly with positive reviews. In order to do this, we will first do the following:\n* Treat each coefficient as a tuple, i.e. (**word**, **coefficient_value**).\n* Sort all the (**word**, **coefficient_value**) tuples by **coefficient_value** in descending order.",
"_____no_output_____"
]
],
[
[
"def top_n(words=important_words, coeffs=list(coefficients[1:]), key='positive'):\n return sorted(\n [(word, coeff) for word, coeff in zip(words, coeffs)], \n key=lambda x: x[1], \n reverse=True if key == 'positive' else False\n)",
"_____no_output_____"
]
],
[
[
"Now, **word_coefficient_tuples** contains a sorted list of (**word**, **coefficient_value**) tuples. The first 10 elements in this list correspond to the words that are most positive.",
"_____no_output_____"
],
[
"### Ten \"most positive\" words\n\nNow, we compute the 10 words that have the most positive coefficient values. These words are associated with positive sentiment.",
"_____no_output_____"
]
],
[
[
"list(map(lambda t: t[0], top_n()[0:10]))",
"_____no_output_____"
]
],
[
[
"**Quiz Question:** Which word is **NOT** present in the top 10 \"most positive\" words?\n\n- [ ] love\n- [ ] easy\n- [ ] great\n- [ ] perfect\n- [x] cheap",
"_____no_output_____"
],
[
"### Ten \"most negative\" words\n\nNext, we repeat this exercise on the 10 most negative words. That is, we compute the 10 words that have the most negative coefficient values. These words are associated with negative sentiment.",
"_____no_output_____"
]
],
[
[
"list(map(lambda t: t[0], top_n(key='negative')[0:10]))",
"_____no_output_____"
]
],
[
[
"**Quiz Question:** Which word is **NOT** present in the top 10 \"most negative\" words?\n\n- [x] need\n- [ ] work\n- [ ] disappointed\n- [ ] even\n- [ ] return",
"_____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"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d0aeeecd646a7ff881016e7f49d35a5585c13c78 | 458,467 | ipynb | Jupyter Notebook | notebooks/23_Simple_feeder_process_MC.ipynb | VanOord/OpenCLSim | 8c2f520982febd950e33cdfd0dca42031b9d9103 | [
"MIT"
] | null | null | null | notebooks/23_Simple_feeder_process_MC.ipynb | VanOord/OpenCLSim | 8c2f520982febd950e33cdfd0dca42031b9d9103 | [
"MIT"
] | 7 | 2020-04-17T06:38:01.000Z | 2021-07-14T10:14:44.000Z | notebooks/23_Simple_feeder_process_MC.ipynb | VanOord/OpenCLSim | 8c2f520982febd950e33cdfd0dca42031b9d9103 | [
"MIT"
] | 2 | 2020-06-15T14:59:59.000Z | 2020-10-08T12:46:59.000Z | 64.355278 | 83,068 | 0.643156 | [
[
[
"## Demo: MultiContainer feeder example\nThe basic steps to set up an OpenCLSim simulation are:\n* Import libraries\n* Initialise simpy environment\n* Define object classes\n* Create objects\n * Create sites\n * Create vessels\n * Create activities\n* Register processes and run simpy\n\n----\n",
"_____no_output_____"
],
[
"#### 0. Import libraries",
"_____no_output_____"
]
],
[
[
"import datetime, time\nimport simpy\n\nimport numpy as np\nimport pandas as pd\nimport shapely.geometry\n\nimport openclsim.core as core\nimport openclsim.model as model\nimport openclsim.plot as plot",
"_____no_output_____"
]
],
[
[
"#### 1. Initialise simpy environment",
"_____no_output_____"
]
],
[
[
"NR_BARGES = 3\nTOTAL_AMOUNT = 100\nBARGE_CAPACITY=10\n\n# setup environment\nsimulation_start = 0\nmy_env = simpy.Environment(initial_time=simulation_start)\nregistry = {}\n",
"_____no_output_____"
]
],
[
[
"#### 2. Define object classes",
"_____no_output_____"
]
],
[
[
"# create a Site object based on desired mixin classes\nSite = type(\n \"Site\",\n (\n core.Identifiable,\n core.Log,\n core.Locatable,\n core.HasMultiContainer,\n core.HasResource,\n ),\n {},\n)\n\n# create a TransportProcessingResource object based on desired mixin classes\nTransportProcessingResource = type(\n \"TransportProcessingResource\",\n (\n core.Identifiable,\n core.Log,\n core.MultiContainerDependentMovable,\n core.Processor,\n core.HasResource,\n ),\n {\"key\": \"MultiStoreHopper\"},\n)",
"_____no_output_____"
]
],
[
[
"#### 3. Create objects\n##### 3.1. Create site object(s)",
"_____no_output_____"
]
],
[
[
"location_from_site = shapely.geometry.Point(4.18055556, 52.18664444)\ndata_from_site = {\"env\": my_env,\n \"name\": \"from_site\",\n \"geometry\": location_from_site,\n \"store_capacity\": 4,\n \"nr_resources\": 1,\n \"initials\": [\n {\n \"id\": \"Cargo type 1\",\n \"level\": TOTAL_AMOUNT,\n \"capacity\": TOTAL_AMOUNT\n },\n ],\n }\nfrom_site = Site(**data_from_site)\n\nlocation_to_site = shapely.geometry.Point(4.25222222, 52.11428333)\ndata_to_site = {\"env\": my_env,\n \"name\": \"to_site\",\n \"geometry\": location_to_site,\n \"store_capacity\": 4,\n \"nr_resources\": 1,\n \"initials\": [\n {\n \"id\": \"Cargo type 1\",\n \"level\": 0,\n \"capacity\": TOTAL_AMOUNT\n },\n ],\n }\nto_site = Site(**data_to_site)",
"_____no_output_____"
]
],
[
[
"##### 3.2. Create vessel object(s)",
"_____no_output_____"
]
],
[
[
"vessels = {}\nfor i in range(NR_BARGES):\n vessels[f\"vessel{i}\"] = TransportProcessingResource(\n env=my_env,\n name=f\"vessel{i}\",\n geometry=location_from_site, \n store_capacity=4,\n nr_resources=1,\n compute_v=lambda x: 10,\n initials=[\n {\n \"id\": \"Cargo type 1\",\n \"level\": 0,\n \"capacity\": BARGE_CAPACITY\n },\n ],\n )\n \n\n\n# prepare input data for installer01\ndata_installer01 = {\"env\": my_env,\n \"name\": \"installer01\",\n \"geometry\": location_to_site, \n \"store_capacity\": 4,\n \"nr_resources\": 1,\n \"compute_v\": lambda x: 10,\n \"initials\": [\n {\n \"id\": \"Cargo type 1\",\n \"level\": 0,\n \"capacity\": NR_BARGES, # Bug we need a watchtower for this\n },\n ],\n }\n# instantiate vessel_02 \ninstaller01 = TransportProcessingResource(**data_installer01)",
"_____no_output_____"
]
],
[
[
"##### 3.3 Create activity/activities",
"_____no_output_____"
]
],
[
[
"processes = []\nfor i in range(NR_BARGES):\n vessel = vessels[f\"vessel{i}\"]\n requested_resources={}\n \n processes.append(\n model.WhileActivity(\n env=my_env,\n name=f\"while {vessel.name}\",\n registry=registry,\n sub_processes=[\n model.SequentialActivity(\n env=my_env,\n name=f\"sequence {vessel.name}\",\n registry=registry,\n sub_processes=[\n model.MoveActivity(\n env=my_env,\n name=f\"sailing empty {vessel.name}\",\n registry=registry,\n mover=vessel,\n destination=from_site,\n duration=10,\n ),\n model.ShiftAmountActivity(\n env=my_env,\n name=f\"load cargo type 1 {vessel.name}\",\n registry=registry,\n processor=vessel,\n origin=from_site,\n destination=vessel,\n amount=BARGE_CAPACITY,\n duration=10,\n id_=\"Cargo type 1\",\n requested_resources=requested_resources,\n ),\n model.MoveActivity(\n env=my_env,\n name=f\"sailing filled {vessel.name}\",\n registry=registry,\n mover=vessel,\n destination=to_site,\n duration=10,\n ),\n model.WhileActivity(\n env=my_env,\n name=f\"unload cycle {vessel.name}\",\n registry=registry,\n condition_event={\n \"type\": \"container\", \n \"concept\": vessel, \n \"state\": \"empty\",\n \"id_\":\"Cargo type 1\"\n },\n sub_processes=[\n model.ShiftAmountActivity(\n env=my_env,\n name=f\"unload cargo type 1 {vessel.name}\",\n registry=registry,\n processor=installer01,\n origin=vessel,\n destination=installer01,\n amount=1,\n duration=10,\n id_=\"Cargo type 1\",\n requested_resources=requested_resources,\n start_event={\n \"type\": \"container\", \n \"concept\": installer01, \n \"state\": \"lt\", \n \"level\":1,\n \"id_\":\"Cargo type 1\"\n }\n ),\n ]\n )\n ],\n )\n ],\n condition_event={\n \"type\": \"container\", \n \"concept\": from_site, \n \"state\": \"empty\",\n \"id_\":\"Cargo type 1_reservations\"\n },\n )\n )",
"_____no_output_____"
],
[
"install_process = model.WhileActivity(\n env=my_env,\n name=f\"While installer\",\n registry=registry,\n condition_event={\n \"type\": \"container\", \n \"concept\": to_site, \n \"state\": \"full\",\n \"id_\":\"Cargo type 1\"\n },\n sub_processes=[\n model.ShiftAmountActivity(\n env=my_env,\n name=f\"Install Cargo type 1\",\n registry=registry,\n processor=installer01,\n origin=installer01,\n destination=to_site,\n amount=1,\n duration=2,\n id_=\"Cargo type 1\",\n start_event={\n \"type\": \"container\", \n \"concept\": installer01, \n \"state\": \"ge\", \n \"level\":1,\n \"id_\":\"Cargo type 1\"\n }\n )\n ],\n)",
"_____no_output_____"
]
],
[
[
"#### 4. Register processes and run simpy",
"_____no_output_____"
]
],
[
[
"model.register_processes([install_process, *processes])\nmy_env.run()",
"_____no_output_____"
],
[
"def extend_id_map(activity, id_map):\n if hasattr(activity, \"sub_processes\"):\n for sub_process in activity.sub_processes:\n id_map = extend_id_map(sub_process, id_map)\n \n return {**id_map, activity.id: activity }\n\nactivity_map = {}\nfor activity in [*processes, install_process]:\n activity_map = extend_id_map(activity, activity_map)\n \nid_map = {key:val.name for (key,val) in activity_map.items()}",
"_____no_output_____"
]
],
[
[
"#### 5. Inspect results\n##### 5.1 Inspect logs",
"_____no_output_____"
]
],
[
[
"plot.get_log_dataframe(installer01, list(activity_map.values())).head()",
"_____no_output_____"
]
],
[
[
"##### 5.2 Visualise gantt charts",
"_____no_output_____"
]
],
[
[
"acts = []\nfor proc in processes:\n acts.extend(proc.sub_processes[0].sub_processes)\n \nplot.get_gantt_chart([*install_process.sub_processes, *acts])",
"_____no_output_____"
],
[
"plot.get_gantt_chart(\n [installer01], \n id_map=id_map\n)",
"_____no_output_____"
]
],
[
[
"##### 5.3 Visualise step charts",
"_____no_output_____"
]
],
[
[
"fig = plot.get_step_chart([installer01])",
"_____no_output_____"
],
[
"fig = plot.get_step_chart([from_site, *vessels.values(), installer01, to_site])",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0aef693f1d162d93a15953c0226f3b77cea8bb4 | 6,956 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Model_Examples-checkpoint.ipynb | WealtHawk-prod/WH_Utils | 713b464a4a0971c8d5bc9bebc2e68f129ec65a4c | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/Model_Examples-checkpoint.ipynb | WealtHawk-prod/WH_Utils | 713b464a4a0971c8d5bc9bebc2e68f129ec65a4c | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/Model_Examples-checkpoint.ipynb | WealtHawk-prod/WH_Utils | 713b464a4a0971c8d5bc9bebc2e68f129ec65a4c | [
"Apache-2.0"
] | null | null | null | 29.226891 | 971 | 0.604658 | [
[
[
"import WH_Utils\nimport json\n\nfrom importlib import reload\nreload(WH_Utils);",
"_____no_output_____"
]
],
[
[
"## Setting Up Authentication\n\n### WH Authentication\n\n1. get API key by going to https://db.wealthawk.com/docs \n2. click authorize in the upper right\n3. click 'try it out' on `/api/user` and then click excecute\n4. copy the code in the `curl` box that corrosponds to 'Authorazation'",
"_____no_output_____"
]
],
[
[
"WH_API_KEY = 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjY5NGNmYTAxOTgyMDNlMjgwN2Q4MzRkYmE2MjBlZjczZjI4ZTRlMmMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vd2gtbWFpbi0zMDc3MjIiLCJhdWQiOiJ3aC1tYWluLTMwNzcyMiIsImF1dGhfdGltZSI6MTYzNjIyMzA5MywidXNlcl9pZCI6Ik1zc0FpNzFOcUZkMXkySk5GT2tpaXRrSjRJZjIiLCJzdWIiOiJNc3NBaTcxTnFGZDF5MkpORk9raWl0a0o0SWYyIiwiaWF0IjoxNjM2MjIzMDkzLCJleHAiOjE2MzYyMjY2OTMsImVtYWlsIjoibWNjbGFpbi50aGllbEBiZXJrZWxleS5lZHUiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsibWNjbGFpbi50aGllbEBiZXJrZWxleS5lZHUiXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwYXNzd29yZCJ9fQ.K6LQTLtWowsPvNLeomujsTxroK2ARhi1m4-Tc_tq0DI-M1-J35eNkRPcaxwwC7WMdVHyjYbzp2a6y9PO65stMdQ912D9PgQIJaclwZrvl6a4rNyv5eRqlxEwMdtMEcVBW2p4OxPCm6426eOHSo6ChJzzBaE2pVegkPsT58Wu3wkHZ237jLNRFWAGISM-NbbrSLxXlcj30PBxCXGCgVJBGQ7RafHaSfK6OUBfZQr-tMg_dVcv6VRAUzkxBIgU82FRkNAvJ2oP2aZ5yD2-w_6DWqGSubdhdTktA2IgxcNbO-ne4gQfe50Gx8QWaqLU4VOPTLoiJweE66FS45clxdlNQQ'\n\nWH_auth_dict = {\n \"accept\": \"application/json\",\n \"Authorization\": WH_API_KEY\n}",
"_____no_output_____"
]
],
[
[
"### Coresignal Authentication\n\nJust like above but the whole company shares one API key so I won't be writing in down here",
"_____no_output_____"
],
[
"## User\n\nThis is the model for working with our users i.e. the wealth managers. \n\n### Creating Users\n\n#### From json / dict",
"_____no_output_____"
]
],
[
[
"with open('tests/test_data/user.json', 'r') as f:\n user_dict = json.load(f)\n \nuser_dict",
"_____no_output_____"
],
[
"user_example = WH_Utils.User(data_dict = user_dict)\nuser_example.__dict__",
"_____no_output_____"
],
[
"user_example",
"_____no_output_____"
]
],
[
[
"### From WH API",
"_____no_output_____"
]
],
[
[
"user_id = \"6091f72d-9b4c-4af9-9b25-e75811a2667e\"\nexample_client2 = WH_Utils.User(WH_ID= user_id, auth_header = WH_auth_dict)",
"_____no_output_____"
],
[
"example_client2",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
d0aeff86ed6b91aa213d502861ca2bb246971e1f | 242,234 | ipynb | Jupyter Notebook | fig_notebooks/explore_tanh.ipynb | dlanier/FlyingMachineFractal | 3889bfb8b8005717de83954d4a705154e908273b | [
"MIT"
] | 4 | 2017-03-27T19:50:37.000Z | 2021-07-15T03:23:03.000Z | fig_notebooks/explore_tanh.ipynb | dlanier/FlyingMachineFractal | 3889bfb8b8005717de83954d4a705154e908273b | [
"MIT"
] | null | null | null | fig_notebooks/explore_tanh.ipynb | dlanier/FlyingMachineFractal | 3889bfb8b8005717de83954d4a705154e908273b | [
"MIT"
] | 1 | 2017-03-27T19:50:54.000Z | 2017-03-27T19:50:54.000Z | 319.992074 | 98,084 | 0.929543 | [
[
[
"from IPython.display import Latex\n# Latex(r\"\"\"\\begin{eqnarray} \\large \n# Z_{n+1} = Z_{n}^(-e^(Z_{n}^p)^(e^(Z_{n}^p)^(-e^(Z_{n}^p)^(e^(Z_{n}^p)^(-e^(Z_{n}^p))))))\n# \\end{eqnarray}\"\"\")",
"_____no_output_____"
]
],
[
[
"# Parameterized machine learning algo: \n## tanh(Z) = (a exp(Z) - b exp(-Z)) / (c exp(Z) + d exp(-Z))\n### with parameters a,b,c,d s.t. ad - bc = 1\n\n Sequential iteration of difference equation:\n Z = \n ",
"_____no_output_____"
]
],
[
[
"import warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nimport sys \nimport numpy as np\nimport time\n\nfrom IPython.display import display\n\nsys.path.insert(1, '../src');\nimport z_plane as zp\nimport graphic_utility as gu;\nimport itergataters as ig\nimport numcolorpy as ncp",
"_____no_output_____"
],
[
"def rnd_lambda(s=1):\n \"\"\" random parameters s.t. a*d - b*c = 1 \"\"\"\n b = np.random.random()\n c = np.random.random()\n ad = b*c + 1\n a = np.random.random()\n d = ad / a\n lamb0 = {'a': a, 'b': b, 'c': c, 'd': d}\n lamb0 = np.array([a, b, c, d]) * s\n \n return lamb0",
"_____no_output_____"
],
[
"def tanh_lmbd(Z, p, Z0=None, ET=None):\n \"\"\" Z = starfish_ish(Z, p) \n Args:\n Z: a real or complex number\n p: a real of complex number\n Returns:\n Z: the result (complex)\n \"\"\"\n Zp = np.exp(Z)\n Zm = np.exp(-Z)\n return (p[0] * Zp - p[1] * Zm) / (p[2] * Zp + p[3] * Zm)",
"_____no_output_____"
],
[
"def plane_gradient(X):\n \"\"\" DX, DY = plane_gradient(X) \n Args:\n X: matrix\n Returns:\n DX: gradient in X direction\n DY: gradient in Y direction\n \"\"\"\n n_rows = X.shape[0]\n n_cols = X.shape[1]\n DX = np.zeros(X.shape)\n DY = np.zeros(X.shape)\n for r in range(0, n_rows):\n xr = X[r, :]\n for c in range(0, n_cols - 1):\n DX[r,c] = xr[c+1] - xr[c]\n \n for c in range(0, n_cols):\n xc = X[:, c]\n for r in range(0, n_rows -1):\n DY[r, c] = xc[r+1] - xc[r]\n \n return DX, DY\n\ndef grad_Im(X):\n \"\"\"\n Args:\n X: matrix\n Returns:\n Gradient_Image: positive matrix representation of the X-Y gradient of X\n \"\"\"\n DX, DY = plane_gradient(X)\n return gu.graphic_norm(DX + DY * 1j)\n\ndef grad_pct(X):\n \"\"\" percentage of X s.t gradient > 0 \"\"\"\n I = grad_Im(X)\n \n return (I > 0).sum() / (X.shape[0] * X.shape[1])\n\ndef get_half_n_half(X):\n \"\"\" box counting, fractal dimension submatrix shortcut \"\"\"\n \n x_rows = X.shape[0]\n x_cols = X.shape[1]\n x_numel = x_rows * x_cols\n \n y_rows = np.int(np.ceil(x_rows / 2))\n y_cols = np.int(np.ceil(x_cols / 2))\n y_numel = y_rows * y_cols\n Y = np.zeros([y_rows, y_cols])\n \n for r in range(0, y_rows):\n for c in range(0, y_cols):\n Y[r,c] = X[2*r, 2*c]\n \n return Y, y_numel, x_numel\n\n\ndef get_fractal_dim(X):\n \"\"\" estimate fractal dimension by box counting \"\"\"\n Y, y_numel, x_numel = get_half_n_half(X)\n X_pct = grad_pct(X) + 1\n Y_pct = grad_pct(Y) + 1\n \n return X_pct / Y_pct",
"_____no_output_____"
],
[
"X = np.random.random([5,5])\nX[X < 0.5] = 0\nY, y_numel, x_numel = get_half_n_half(X)\nX_pct = grad_pct(X)\nY_pct = grad_pct(Y)\n\nprint(X_pct, Y_pct)\nprint('y_numel', y_numel, '\\nx_numel', x_numel)\nprint(X_pct / Y_pct)\n# print(Y)\n# print(X)\nprint(get_fractal_dim(X))",
"0.88 0.6666666666666666\ny_numel 9 \nx_numel 25\n1.32\n1.1280000000000001\n"
],
[
"# -- machine with 8 cores --\nP0 = [ 1.68458678, 1.72346312, 0.53931956, 2.92623535]\nP1 = [ 1.99808082, 0.68298986, 0.80686446, 2.27772581] \nP2 = [ 1.97243201, 1.32849475, 0.24972699, 2.19615225]\nP3 = [ 1.36537498, 1.02648965, 0.60966423, 3.38794403]\n\np_scale = 2\nP = rnd_lambda(p_scale)\n# P = np.array(P3)\n\nN = 200\npar_set = {'n_rows': N, 'n_cols': N}\npar_set['center_point'] = 0.0 + 0.0j\npar_set['theta'] = np.pi / 2\npar_set['zoom'] = 1/2\n\npar_set['it_max'] = 16\npar_set['max_d'] = 12 / par_set['zoom']\npar_set['dir_path'] = os.getcwd()\n\nlist_tuple = [(tanh_lmbd, (P))]\n\nt0 = time.time()\nET, Z, Z0 = ig.get_primitives(list_tuple, par_set)\ntt = time.time() - t0\nprint(P, '\\n', tt, '\\t total time')\n\nZd, Zr, ETn = ncp.etg_norm(Z0, Z, ET)\nprint('Fractal Dimensionn = ', get_fractal_dim(ETn) - 1)\n\nZrN = ncp.range_norm(Zr, lo=0.25, hi=1.0)\ndisplay(ncp.gray_mat(ZrN))\n\nZrN = ncp.range_norm(gu.grad_Im(ETn), lo=0.25, hi=1.0)\nR = ncp.gray_mat(ZrN)\n\ndisplay(R)",
"[0.4523232 0.5507815 0.75367311 9.76096118] \n 4.287211894989014 \t total time\nFractal Dimensionn = 0.0001500000000000945\n"
],
[
"# -- machine with 4 cores --\np_scale = 2\n# P = rnd_lambda(p_scale)\nP = np.array([1.97243201, 1.32849475, 0.24972699, 2.19615225])\n\nN = 800\npar_set = {'n_rows': N, 'n_cols': N}\npar_set['center_point'] = 0.0 + 0.0j\npar_set['theta'] = np.pi / 2\npar_set['zoom'] = 1/2\n\npar_set['it_max'] = 16\npar_set['max_d'] = 12 / par_set['zoom']\npar_set['dir_path'] = os.getcwd()\n\nlist_tuple = [(tanh_lmbd, (P))]\n\nt0 = time.time()\nET, Z, Z0 = ig.get_primitives(list_tuple, par_set)\ntt = time.time() - t0\nprint(P, '\\n', tt, '\\t total time')\n\nt0 = time.time()\nZd, Zr, ETn = ncp.etg_norm(Z0, Z, ET)\nprint('converstion time =\\t', time.time() - t0)\n\nt0 = time.time()\n# ZrN = ncp.range_norm(Zr, lo=0.25, hi=1.0)\n# R = ncp.gray_mat(ZrN)\n\nZrN = ncp.range_norm(gu.grad_Im(ETn), lo=0.25, hi=1.0)\nR = ncp.gray_mat(ZrN)\n\nprint('coloring time =\\t',time.time() - t0)\ndisplay(R)",
"[1.97243201 1.32849475 0.24972699 2.19615225] \n 70.47121977806091 \t total time\nconverstion time =\t 1.586843729019165\ncoloring time =\t 3.6288599967956543\n"
],
[
"# def grad_pct(X):\n# \"\"\" percentage of X s.t gradient > 0 \"\"\"\n# I = gu.grad_Im(X)\n# nz = (I == 0).sum()\n# if nz > 0:\n# grad_pct = (I > 0).sum() / nz\n# else:\n# grad_pct = 1\n# return grad_pct",
"_____no_output_____"
],
[
"I = gu.grad_Im(ETn)\nnz = (I == 0).sum()\nnb = (I > 0).sum()\n\nprint(nz, nb, ETn.shape[0] * ETn.shape[1], nz + nb) \n\n",
"637849 2151 640000 640000\n"
],
[
"P0 = [ 1.68458678, 1.72346312, 0.53931956, 2.92623535]\nP1 = [ 1.99808082, 0.68298986, 0.80686446, 2.27772581] \nP2 = [ 1.97243201, 1.32849475, 0.24972699, 2.19615225]\nP3 = [ 1.36537498, 1.02648965, 0.60966423, 3.38794403]",
"_____no_output_____"
],
[
"H = ncp.range_norm(1 - Zd, lo=0.5, hi=1.0)\nS = ncp.range_norm(1 - ETn, lo=0.0, hi=0.15)\nV = ncp.range_norm(Zr, lo=0.2, hi=1.0)\nt0 = time.time()\nIhsv = ncp.rgb_2_hsv_mat(H, S, V)\nprint('coloring time:\\t',time.time() - t0)\ndisplay(Ihsv)",
"coloring time:\t 7.2474751472473145\n"
],
[
"H = ncp.range_norm(Zd, lo=0.05, hi=0.55)\nS = ncp.range_norm(1 - ETn, lo=0.0, hi=0.35)\nV = ncp.range_norm(Zr, lo=0.0, hi=0.7)\nt0 = time.time()\nIhsv = ncp.rgb_2_hsv_mat(H, S, V)\nprint('coloring time:\\t',time.time() - t0)\ndisplay(Ihsv)",
"coloring time:\t 7.5052080154418945\n"
],
[
"# smaller for analysis\npar_set = {'n_rows': 200, 'n_cols': 200}\npar_set['center_point'] = 0.0 + 0.0j\npar_set['theta'] = 0.0\npar_set['zoom'] = 5/8\n\npar_set['it_max'] = 16\npar_set['max_d'] = 10 / par_set['zoom']\npar_set['dir_path'] = os.getcwd()\n\n# list_tuple = [(starfish_ish, (-0.040431211565+0.388620268274j))]\nlist_tuple = [(tanh_lmbd, (P))]\nt0 = time.time()\nET_sm, Z_sm, Z0_zm = ig.get_primitives(list_tuple, par_set)\ntt = time.time() - t0\nprint(tt, '\\t total time')",
"4.391478061676025 \t total time\n"
],
[
"# view smaller - individual escape time starting points\nfor t in range(1,7):\n print('ET =\\t',t)\n I = np.ones(ET_sm.shape)\n I[ET_sm == t] = 0\n display(ncp.mat_to_gray(I))\nI = np.ones(ET_sm.shape)\nI[ET_sm > 7] = 0\ndisplay(ncp.mat_to_gray(I))",
"ET =\t 1\n"
],
[
"# view smaller - individual escape time frequency\nfor k in range(0,int(ET_sm.max())):\n print(k, (ET_sm == k).sum())\nprint('\\nHow many never escaped:\\n>',(ET_sm > k).sum())",
"0 0\n1 974\n2 148\n3 42\n4 18\n5 12\n6 16\n7 56\n8 116\n9 52\n10 26\n11 10\n12 8\n13 6\n14 8\n15 10\n16 8\n\nHow many never escaped:\n> 38490\n"
],
[
"# get the list of unescaped starting points and look for orbit points\nZ_overs = Z0_zm[ET_sm == ET_sm.max()]\n\nv1 = Z_overs[0]\nd = '%0.2f'%(np.abs(v1))\ntheta = '%0.1f'%(180*np.arctan2(np.imag(v1), np.real(v1))/np.pi)\nprint('One Unescaped Vector:\\n\\tV = ', d, theta, 'degrees\\n')\n\nprint('%9d'%Z_overs.size, 'total unescaped points\\n')\nprint('%9s'%('points'), 'near V', ' (plane units)')\nfor denom0 in range(1,12):\n neighbor_distance = np.abs(v1) * 1/denom0\n v1_list = Z_overs[np.abs(Z_overs-v1) < neighbor_distance]\n print('%9d'%len(v1_list), 'within V/%2d (%0.3f)'%(denom0, neighbor_distance))",
"One Unescaped Vector:\n\tV = 2.26 135.0 degrees\n\n 38490 total unescaped points\n\n points near V (plane units)\n 15466 within V/ 1 (2.263)\n 3964 within V/ 2 (1.131)\n 1774 within V/ 3 (0.754)\n 1009 within V/ 4 (0.566)\n 648 within V/ 5 (0.453)\n 459 within V/ 6 (0.377)\n 339 within V/ 7 (0.323)\n 261 within V/ 8 (0.283)\n 208 within V/ 9 (0.251)\n 170 within V/10 (0.226)\n 140 within V/11 (0.206)\n"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0aeffe4d6863c5b201c7fb89b8d84fcbf6955ed | 68,704 | ipynb | Jupyter Notebook | hashtags.ipynb | puregome/notebooks | 3b9dc20b769244f79be13c096c543805e2948d24 | [
"Apache-2.0"
] | 3 | 2020-04-30T13:44:17.000Z | 2020-05-07T15:28:32.000Z | hashtags.ipynb | puregome/notebooks | 3b9dc20b769244f79be13c096c543805e2948d24 | [
"Apache-2.0"
] | null | null | null | hashtags.ipynb | puregome/notebooks | 3b9dc20b769244f79be13c096c543805e2948d24 | [
"Apache-2.0"
] | 1 | 2020-05-08T20:10:24.000Z | 2020-05-08T20:10:24.000Z | 153.357143 | 2,537 | 0.734557 | [
[
[
"# Hashtags",
"_____no_output_____"
]
],
[
[
"from nltk.tokenize import TweetTokenizer\nimport os\nimport pandas as pd\nimport re\nimport sys\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom IPython.display import clear_output",
"_____no_output_____"
],
[
"def squeal(text=None):\n clear_output(wait=True)\n if not text is None: print(text)",
"_____no_output_____"
],
[
"DATADIR = \"../data/text/\"\nID_STR = \"id_str\"\nTEXT = \"text\"\nTOPICQUERY = \"corona|covid|huisarts|mondkapje|rivm|blijfthuis|flattenthecurve|houvol\"\nPANDEMICQUERY = \"|\".join([TOPICQUERY, r'virus|besmet|ziekenhui|\\bic\\b|intensive.care|^zorg|vaccin|[^ad]arts|uitbraak|uitbrak|pandemie|ggd|'+\n r'mondkapje|quarantaine|\\bwho\\b|avondklok|variant|verple|sympto|e.golf|mutant|^omt$|umc|hcq|'+\n r'hydroxychloroquine|virolo|zkh|oversterfte|patiënt|patient|intensivist|🦠|ivermectin'])\nDISTANCEQUERY = \"1[.,]5[ -]*m|afstand.*hou|hou.*afstand|anderhalve[ -]*meter\"\nLOCKDOWNQUERY = \"lock.down|lockdown\"\nVACCINQUERY = \"vaccin|ingeënt|ingeent|inent|prik|spuit|bijwerking|-->|💉|pfizer|moderna|astrazeneca|astra|zeneca|novavax|biontech\"\nTESTQUERY = r'\\btest|getest|sneltest|pcr'\nQUERY = \"|\".join([PANDEMICQUERY, TESTQUERY, VACCINQUERY, LOCKDOWNQUERY, DISTANCEQUERY])\nBASEQUERY = \"corona|covid\"\nHAPPY_QUERY = r'\\b(geluk|gelukkig|gelukkige|blij|happy)\\b'\nLONELY_QUERY = r'eenza|alleen.*voel|voel.*alleen|lonely|loneli'\nIK_QUERY = r'\\b(ik|mij|mijn|me|mn|m\\'n|zelf|mezelf|mijzelf|i)\\b'",
"_____no_output_____"
],
[
"def get_tweets(file_pattern, query, query2=\"\", spy=False):\n tweets = []\n file_names = sorted(os.listdir(DATADIR))\n for file_name in file_names:\n if re.search('^' + file_pattern, file_name):\n if spy:\n squeal(file_name)\n df = pd.read_csv(DATADIR+file_name,index_col=ID_STR)\n if query2 == \"\":\n df_query = df[df[TEXT].str.contains(query, flags=re.IGNORECASE)]\n else:\n df_query = df[df[TEXT].str.contains(query, flags=re.IGNORECASE) & df[TEXT].str.contains(query2, flags=re.IGNORECASE)]\n tweets.extend(list(df_query[TEXT]))\n return(tweets)",
"_____no_output_____"
],
[
"def get_hashtags(tweet):\n hashtags = []\n for token in TweetTokenizer().tokenize(tweet):\n if re.search(r'#', token):\n hashtags.append(token)\n return(hashtags)",
"_____no_output_____"
],
[
"def process_month(month, query=BASEQUERY, query2=\"\"):\n tweets = [re.sub(r'\\\\n', ' ', tweet) for tweet in get_tweets(month, query, query2=query2, spy=False)]\n hashtags = {}\n for tweet in tweets:\n if re.search(r'#', tweet):\n for hashtag in get_hashtags(tweet):\n if hashtag in hashtags:\n hashtags[hashtag] += 1\n else:\n hashtags[hashtag] = 1\n print(month, \" \".join([hashtag for hashtag in sorted(hashtags.keys(), key=lambda hashtag:hashtags[hashtag], reverse=True)][:200]))",
"_____no_output_____"
],
[
"pd.DataFrame([{\"202105\": \"measures\", \"202106\": \"pandemic\", \"202107\": \"measures\", \n \"202108\": \"pandemic\", \"202109\": \"entry pass\", \"202110\": \"entry pass\"},\n {\"202105\": \"pandemic\", \"202106\": \"measures\", \"202107\": \"pandemic\", \n \"202108\": \"measures\", \"202109\": \"measures\", \"202110\": \"measures\"},\n {\"202105\": \"vaccination\", \"202106\": \"vaccination\", \"202107\": \"vaccination\", \n \"202108\": \"vaccination obligation\", \"202109\": \"vaccination obligation\", \"202110\": \"pandemic\"},\n {\"202105\": \"entry pass\", \"202106\": \"FVD\", \"202107\": \"vaccination obligation\", \n \"202108\": \"vaccination\", \"202109\": \"pandemic\", \"202110\": \"vaccination obligation\"},\n {\"202105\": \"Netherlands\", \"202106\": \"Netherlands\", \"202107\": \"FVD\", \n \"202108\": \"Netherlands\", \"202109\": \"press conference\", \"202110\": \"press conference\"},\n {\"202105\": \"testing\", \"202106\": \"facemasks\", \"202107\": \"Netherlands\", \n \"202108\": \"lockdown\", \"202109\": \"FVD\", \"202110\": \"unvaccinated\"},\n {\"202105\": \"FVD\", \"202106\": \"entry pass\", \"202107\": \"lockdown\", \n \"202108\": \"press conference\", \"202109\": \"Hugo de Jonge\", \"202110\": \"3 October protest\"},\n {\"202105\": \"ivermectine\", \"202106\": \"app\", \"202107\": \"press conference\", \n \"202108\": \"entry pass\", \"202109\": \"hospitality business\", \"202110\": \"Netherlands\"},\n {\"202105\": \"long covid\", \"202106\": \"variants\", \"202107\": \"long covid\", \n \"202108\": \"FVD\", \"202109\": \"Mark Rutte\", \"202110\": \"Hugo de Jonge\"},\n {\"202105\": \"lockdown\", \"202106\": \"lab leak\", \"202107\": \"Hugo de Jonge\", \n \"202108\": \"long covid\", \"202109\": \"Mona Keizer\", \"202110\": \"FVD\"},\n ])",
"_____no_output_____"
],
[
"for month in \"202105 202106 202107 202108 202109 202110\".split():\n process_month(month)",
"202105 #coronamaatregelen #coronavirus #COVID19 #corona #coronavaccin #Corona #coronapaspoort #COVID19NL #covid19nl #testsamenleving #vaccinatiepaspoort #vaccinatie #covid19 #Vaccinatie #covid #coronadebat #FVD #testmaatschappij #coronavaccinatie #ikweiger #Ivermectine #Covid_19 #vaccineren #vaccin #Covid19 #LongCovid #lockdown #vaccinatieplicht #dtv #testbewijzen #coronahoax #coronacrisis #vaccinaties #persconferentie #RIVM #versoepelingen # #Covid #Rutte #stopdelockdown #Baudet #mondkapjes #vrijheid #CoronaCrisis #Eurovision #nederland #klaarmetRutte #COVID #Nieuwsuur #londonprotest #vaccins #hugodejongekanniks #volksgezondheid #testwet #AstraZeneca #plandemie #Wilders #Wuhan #WuhanLab #Pfizer #IkPrikHetNiet #debat #zorg #India #nederlands #mondkapjesplicht #nederlandsnews #WHO #fvd #peilingen #peiling #politiegeweld #rutte #WEF #OMT #wappie #vanangstnaarvertrouwen #ZeroCovid #vaccinatiebewijs #TeHoog #hugodejonge #worldwidefreedomrally #aerosolen #EU #PVV #bevrijdingsdag #longcovid #ikdoenietmeermee #wappies #fucktheNWO #gentherapie #vaccinatiestrategie #covid1948 #avondklok #AlleenSamen #nosjournaal #Trump #vanranst #geleboekje #testbewijzendebat #politie #kinderen #ikvaccineer #nieuws #bpoc2020 #nieuwsuur #Ajax #FreePalestine #poll #toeslagenaffaire #Beau #coronawet #onderwijs #boek #Amsterdam #4mei #jurgenconings #coronabeleid #Kaag #beau #CoronaVaccine #Coronavirus #koningsdag #giro555 #ikprikhetniet #groepsimmuniteit #coronavaccins #GMO #ivermectine #coronacijfers #realitycheck #coronatest #rivm #Nederland #horeca #codezwart #LongCovidKids #besmettingen #HugodeJonge #viruswaarheid #CDA #vrtnws #laboum2 #ikwildieprik #7dag #covidpaspoort #mondkapje #privacy #QRcode #D66 #Barneveld #FvD #Bevrijdingsdag #complot #deafspraak #DEBAT #terzaketv #stopwillemengel #voorspellingen #eenvandaag #PoliceForFreedom #op1 #vaccinated #pandemie #baudet #Rotterdam #Vaccin #virus #1mei #Coronamaatregelen #infectieziekte #GGD #Op1 #coronazwendel #Giro555 #Hamas #ME #prullenbakvaccin #museumplein #Biden #telegraafextra #NPO #Malieveld #5mei #dictatuur #tweedekamer #nieuwsinperspectief #Hydroxychloroquine #telegraafpremium #Texas #thegreatreset #ventilatie #PCRtest #scholenveilig #IC #TheGreatReset #BREAKING #Followback #maatregelen #coronaprik\n202106 #coronavirus #coronamaatregelen #COVID19 #corona #coronavaccinatie #coronadebat #Corona #FVD #covid19nl #VoorWeinigCovid #COVID19NL #vaccinatie #Vaccinatie #mondkapjesplicht #Covid19 #vaccin #covid19 #coronapaspoort #coronavaccin #vaccineren #CoronaCheckApp #DeltaVariant #WuhanLabLeak #Ivermectine #versoepelingen #LongCovid #coronacheckapp #persconferentie #covid #mondkapjes #LabLeakTheory #FauciEmails #RIVM #coronacrisis #Wilders #vaccinatiebewijs #FauciLiedPeopleDied #vaccinaties #lockdown #Rutte #PVV #Covid_19 #Pfizer #CoronaCrisis #Nieuwsuur #nederland #mondkapje #peiling #persco #coronahoax #CoronaCheck #Fauci #nederlands #nederlandsnews #Covid #peilingen #COVID #dtv #wappies #BlijfVanOnzeKinderenAf #sywertvanlienden #volksgezondheid # #vanangstnaarvertrouwen #mRNA #nietgevaccineerdenclub #AstraZeneca #longcovid #OMT #vaccins #AlleenSamen #vrijheid #HugodeJonge #testsamenleving #D66 #klaarmetRutte #WuhanLab #testenvoortoegang #vaccinatiepaspoort #Vaccin #EU #CoronaVaccinatie #hugodejonge #nieuwsinperspectief #Koning #coronavaccins #Kaag #vaccinated #ikwildieprik #thegreatreset #Wuhan #coronabeleid #TestenvoorToegang #Nederland #MarionKoopmans #SARSCoV2 #Followback #boek #ivermectine #Moderna #Duitsland #stopdelockdown #opznkop #NooitMeerLockdown #WHO #vaccinatieplicht #Coronadebat #coronawet #zorg #nosjournaal #TheGreatReset #vakantie #IkPrikNiet #BuildBackBetter #TweedeKamer #hugodejongekanniks #anderhalvemeterfetisj #VVD #ANWB #persconferenties #IkPrikHetNiet #ZeroCovid #WEF #kinderen #coronazwendel #Sywert #rutte #censuur #Janssen #plandemie #Coronavirus #ChristianDrosten #IC #janssen #nieuws #ikvaccineer #overheid #ikweiger #deltavariant #HCQ #Op1 #VrijheidIsNietOnderhandelbaar #immigranten #vaccinatiepas #Trump #antistoffen #vrtnws #VaccinatieSchade #politiegeweld #myocarditis #Eriksen #InformeerJeOverJePrik #dictatuur #onderwijs #antilichamen #spoedwet #HydroxyChloroquine #BIJ1 #gevaccineerd #pandemie #VOLT #MSM #nos #vrijheidvooreenprikkie #Neurenberg2 #FvD #Janssen-vaccin #HugoDeJonge #BigPharma #FauciLeaks #maatregelen #buitenhof #Merkel #Covid19NL #politiek #bijwerkingen #LongCovidKids #Hongarije #nieuwsuur #FVD-Kamerlid #buildbackbetter #nieuwsvoorziening #gentherapie #Science #petitie #pfizer #rivm #Rotterdam #bewaartweet #Folllowback #GGD #geleboekje #ikprikwel #klausschwab #poll #griep #Lareb #telegraafpremium #goedemorgen #EK\n202107 #coronamaatregelen #coronadebat #coronavirus #COVID19 #corona #coronavaccinatie #Corona #vaccinatieplicht #FVD #COVID19NL #Vaccinatie #NooitMeerLockdown #persconferentie #covid19nl #vaccinatie #VoorWeinigCovid #LongCovid #covid19 #BVNL #hugodejongekanniks #Rutte #prikpooier #Astatus #coronavaccin #Covid19 #hugodejonge #covid #DeltaVariant #coronahoax #Covid_19 #Frankrijk #coronabesmettingen #rutte #BelangVanNederland #vaccinaties #klaarmetRutte #dtv #vaccin #RIVM #Nieuwsuur #besmettingen #IkPrikNiet #vaccineren #Coronamaatregelen #ongevaccineerden #TestenvoorToegang #fvd #lockdown #Covid #wappies #Pfizer #WuhanLabLeak #volksgezondheid #CoronaCrisis #coronacheckapp #CoronaVaccinatie #bpoc2020 #debat #OMT #nieuweverkiezingen #BlijfVanOnzeKinderenAf #migratie #longcovid #VaccinatieSchade #coronacrisis #toeslagenaffaire #DansenMetJanssen #PfizerLeak #nieuwsinperspectief #PVV #peiling #vakantie #coronapaspoort # #Hugodejongemoetweg #omtzigt #zelfnadenken #vrijheid #woningnood #vaccins #testsamenleving #peilingen #Griekenland #peterrdevries #TK #coronabeleid #ikprikwel #Op1 #RutteMoetWeg #baudet #Wilders #PCR #gideonvanmeijeren #persco #schwab #COVID #WEF #wappie #Coronadebat #deltavariant #nieuws #Ebola #ventilatie #Humberto #DeJonge #horeca #PCRtest #mondkapjes #Macron #Malta #jongeren #AlleenSamen #Followback #versoepelingen #vaccinatiebewijs #media #ZeroCovid #vaccinatiedwang #tweedekamer #Nederland #op1 #EU #Delta #vaccinated #BigPharma #mRNA #CoronaCheck #MedischeApartheid #Op1npo #mondkapje #vaccinatiepaspoort #testenvoorjereis #nosjournaal #mondkapjesplicht #lableak #ivermectine #AstraZeneca #KlausSchwab #ikprikniet #FVD-Kamerleden #BuildBackBetter #plandemie #coronazwendel #Coronavirus #pandemie #dezevariantiseenbitch #covidgeenAstatus #frankrijk #boek #rivm #MarionKoopmans #zorg #GreatReset #coronadictatuur #covidAstatus #VVD #gevaccineerd #VaccinatiePlicht #Vaccin #formatie #Sywert #Ivermectine #testen #covid19zwendel #olympischespelen #rechtszaak #coronapas #demonstratie #vaccinatieschade #politiegeweld #TestenVoorToegang #verplichtevaccinatie #pfizer #nieuwsuur #GGD #TheGreatReset #coronatest #Malieveld #stopmettesten #CoronaMaatregelen #Paris #kabinet #Janssen #testenvoortoegang #Amsterdam #NederlandisKapot #VWS #14Juillet #nooitmeerlockdown #klaarmetrutte #mnra #Nena #CoronaHoax #kinderen #medischeapartheid #WHO #gevaccineerden #VaccinatieHoax #grafeenoxide #astatus\n202108 #coronavirus #coronamaatregelen #vaccinatieplicht #COVID19 #coronabeleid #corona #vaccinatiedwang #coronadebat #Corona #coronavaccinatie #covid19nl #vaccinatie #CoronaBeleid #vaccinaties #COVID19NL #Covid_19 #NooitMeerLockdown #VaccinatieSchade #persconferentie #covid #Vaccinatie #VoorWeinigCovid #BVNL #Corona_Origin_Untold_Secret #Covid19 #medischeapartheid #coronavaccin #covid19 #FVD #vaccin #prikspijt #vrijheid #prikpooier #BelangVanNederland #LongCovid #COVID #VaccinatiePlicht #WEF #coronapaspoort #Rutte #TestenvoorToegang #VaccinatieDwang #coronacrisis #vaccinatiepaspoort #wappies #UnmuteUs #hugodejonge #Wilders #lockdown #coronapas #volksgezondheid #vaccineren #Pfizer #dtv #vaccins #opznkop #klaarmetRutte #ongevaccineerden #Covid #hugodejongekanniks #RIVM #bijwerkingen #rutte #gevaccineerden #TheGreatReset #thegreatreset #NoVaccinePassports #CoronaHoax #BPOC2020 #peiling #stopdewaanzin #coronahoax #peilingen # #gevaccineerd #DeltaVariant #Lareb #apartheid #Vaccinaties #pcrtest #kutland #verzet #D66 #PassSanitaire #Agenda2030 #apartheidspas #Kaag #vaccinschade #mondkapjes #burgerlijkeongehoorzaamheid #vaccinatiedrang #covid19zwendel #Coronadebat #CoronaCrisis #Amsterdam #vaccinatieschade #GiletJaunes #Apartheid #gevaccineerde #coronacheckapp #OMT #Vaccinatiepaspoort #demissionair #ivermectine #Duitsland #festivals #VaccinatieHoax #Afghanistan #Frankrijk #telegraafpremium #coronatoegangsbewijs #VeiligOnderwijs #FvD #frankrijk #longcovid #persco #Nieuwsuur #kinderen #kabinet #onlycovidcounts #Ivermectine #antivaxxers #Nederland #greenpass #klausschwab #zorg #horeca #nieuwsinperspectief #scholenveilig #LongCovidKids #op1 #overheid #hugodejongemoetweg #coronazwendel #CoronaVaccinatie #ScholenVeilig #politie #knettergek #Zandvoort #30 #klimaatverandering #nooitmeerlockdown #BigPharma #Vaccin #mondkapjesplicht #Totalitarisme #kutrabobank #Gommers #NOW #klimaat #F1 #coronavaccins #COVIDIOTS #coronacritici #vrtnws #onderwijs #AlleenSamen #boek #besmettingen #PCRtest #waanzin #Discriminatie #ongrondwettelijk #VVD #poll #Berlin #NOS #intensivecare #ZeroCovid #Op1 #Humberto #Berlijn #coronapaspoorten #IkPrikNiet #prik #wef #covid19be #Festivals #ongevaccineerde #Coronavirus #klimaatcrisis #introductieweken #testenvoortoegang #EU #genocide #vaccinatiespijt #voetbalstadions #kaag #bpoc2020 #eenvandaag #versoepelingen #NWO #formatie #Moderna #vaccination #wetenschap #dictatuur #Gevaccineerde #NoVaccinePassportsAnywhere #Denemarken\n202109 #coronapas #coronamaatregelen #coronadebat #coronapaspoort #vaccinatiedwang #coronatoegangsbewijs #coronavirus #medischeapartheid #persconferentie #QRCode #corona #FVD #COVID19 #Corona #vaccinatieplicht #HugoDeQRankzinnige #QRsamenleving #horeca #coronabeleid #ikweiger #apartheidspas #BVNL #Rutte #monakeizer #5septemberAmsterdam #covid19nl #DeTeringMetDeRegering #Coronapas #NooitMeerLockdown #Covid_19 #vrijheid #vaccinatie #QRcode #jinek #COVID19NL #ikdoenietmeermee #Amsterdam #VaccinatieSchade #Wilders #Zandvoort #D66 #rutte #discriminatie #wakuwaku #BelangVanNederland #hugodejonge #VVD #coronavaccinatie #nieuweverkiezingen #TestenvoorToegang #coronacheckapp #COVID #covid19 #AllesOpen #DutchGP #covid #vaccinatiepaspoort #ZonderVoorwaarden #TeamBartMaes #WAKUWAKU #LongCovid #StopQR #Kaag #vaccinatiebewijs #gevaccineerden #CDA #WEF #Vaccinatie #DDoS #vragenuurtje #toeslagenaffaire #VoorWeinigCovid #dtv #Covid19 #RIVM #wappies #vaccin #demonstratie #CoronaPas # #klaarmetRutte #vaccineren #UnmuteUs #ongevaccineerden #BuildBackBetter #politiek #apartheid #tweedeling #Keijzer #CoronaCheck #HugodeJonge #Afghanistandebat #VrijheidIsNietOnderhandelbaar #boeren #qrcode #waanzin #TheGreatReset #prikpooier #hugodejongekanniks #nieuwsinperspectief #coronaprotest #OMT #fvd #kabinet #tweedekamer #lockdown #Nieuwsuur #ZandvoortF1 #monakeijzer #Prinsjesdag #peilingen #Coronadebat #WakuWaku #onwettelijk #dictatuur #coronavaccin #peiling #onteigening #NoVaccinePassportsAnywhere #algemenebeschouwingen #coronacrisis #volksgezondheid #persco #hypocriet #MedischeApartheid #theater #SDGs #Kerkrade #MonaKeijzer #zorginfarct #apb21 #onteigenen #CoronaMaatregelen #nooitmeerlockdown #F1 #StopPolarisatie #kaag #uitsluiting #Omtzigt #coronahoax #PassSanitaire #VaccinePassports #op1 #baudet #longcovid #Apartheid #maatregelen #griep #Utrecht #coronadictatuur #Op1 #PvdA #Halsema #FvD #teambartmaes #groenlinks #PVV #nieuwsuur #stopdecoronaidiotie #kortgedingcoronapas #WeLevenNietInChina #QR-code #gehoorzaamheidspas #zandvoort #Baudet #5september #vrijekeuze #zorg #nosjournaal #discriminatiepas #Horeca #vaccinaties #Ivermectine #Hugo #Griep #GeenCoronapas #covid19zwendel #gevaccineerd #ivermectine #formatie #IC #Nederlander #vaccinatieschade #DenHaag #Op1npo #Nederland #7dag #geenvaccinatieplicht #Jinek #Rutte3 #Coronamaatregelen #Covid #VeiligOnderwijs #frankrijk #NazisRaus #LongCovidKids #QRoegentocht #stopcoronapas #COVIDIOTS #troonrede\n202110 #coronapas #coronamaatregelen #coronavirus #vaccinatiedwang #corona #COVID19 #Corona #persconferentie #QRcode #Coronapas #vaccinatieplicht #coronatoegangsbewijs #coronapaspoort #QRsamenleving #ongevaccineerden #covid19nl #QRCode #BVNL #VaccinatieSchade #3oktoberAmsterdam #COVID19NL #hugodejonge #FVD #zorginfarct #jinek #Covid_19 #CoronaPas #covid19 #covid #HugoDeQRankzinnige #apartheidspas #vaccinatie #Rutte #CoronaMaatregelen #vaccin #vaccinaties #coronabeleid #QRterreur #CoronaToegangsbewijs #griepprik #Covid19 #vaccinatiepaspoort #OMT #Jinek #NoVaccinePassportsAnywhere #medischeapartheid #prikpooier #lockdown #Nieuwsuur #qrcode #gevaccineerd #NooitMeerLockdown #coronavaccinatie #oversterfte #Gommers #TheGreatReset #horeca #persco #Vaccinatie #RIVM #LongCovid #Covid #terugvolgvrijdag #gevaccineerden #klaarmetRutte #QR #wappies #Hugo #VoorWeinigCovid #ikweiger #GeenQR #nieuwsinperspectief #rugrecht #discriminatie #Coronamaatregelen #nietmijnregering #bruls #qrankzinnig #COVID # #eenvandaag #vaccineren #Ivermectine #VaccinatiePlicht #zorg #Biblebelt #WEF #vrijheid #Pfizer #coronacrisis #vaccinatieschade #IkPrikNiet #nosjournaal #BelangVanNederland #nieuwsuur #Prikpooier #Op1npo #italië #toeslagenaffaire #Op1 #rutte #ZorgInfarct #dtv #ongevaccineerd #griep #Roma #nieuweverkiezingen #wappie #BuildBackBetter #Isala #wijzijnmetveelmeer #Italië #Italy #Bruls #buitenhof #op1 #zelfnadenken #thegreatreset #HugodeQRankzinnige #TestenVoorToegang #avondklok #volksgezondheid #groepsimmuniteit #mondkapjesplicht #GreatReset #Censuur #coronacheckapp #framing #WHORichtlijnen #ikdoenietmeermee #SocialCreditSystem #SociaalKredietSysteem #besmettingen #HaatHugo #BigPharma #NOS #apartheid #Nederland #uitsluiting #peiling #tweedeling #KNMG #galg #peilingen #retorischevraag #CovidSafeTicket #KlaarmetRutte #longcovid #coronavaccin #mondkapjes #klimaat #verzet #Amsterdam #vrtnws #greenpass #Kuipers #myocarditis #Staphorst #coronavaccins #coronahoax #BPOC2020 #demonstratie #WHO #dorhout #vaccins #Rutte3 #gevaccineerde #ICbedden #cda #AllesOpen #overlegcomite #demo #vaccinatiegraad #VrijheidIsNietOnderhandelbaar #Coronapaspoort #EU #7dag #QRankzinnig #CoronaDictatuur #qrsamenleving #InspectieGezondheidszorg #rivm #d66 #fvd #vvd #kortgedingcoronapas #NoGreenPass #LinkedIn #ikprikhetniet #baudet #omt #HugoDeJonge #pvv #tweedekamer #linkedin #formatie2021 #GeenCoronapas #coronopas #Vaccinatiedwang #vaccinatieDwang\n"
],
[
"for month in \"202105\".split():\n tweets = [re.sub(r'\\\\n', ' ', tweet) for tweet in get_tweets(month, LONELY_QUERY, query2=IK_QUERY, spy=False)]\n hashtags = {}\n for tweet in tweets:\n if re.search(r'#', tweet):\n for hashtag in get_hashtags(tweet):\n if hashtag in hashtags:\n hashtags[hashtag] += 1\n else:\n hashtags[hashtag] = 1\n print(month, \" \".join([hashtag for hashtag in sorted(hashtags.keys(), key=lambda hashtag:hashtags[hashtag], reverse=True)][:200]))",
"202105 #maatjegezocht #eenzamejongeren #vrijheid #walgelijk #keeponmoving #durftevragen #eenzaamheid #dodenherdenking #hemels #Walgelijk #geile #kanker #bloomforjulie #mondkapje #rouw #AstraZeneca #Eurovision #liefde # #KunstvanhetSamenleven #Citaten #poems #poetry #Vaccinatie #mondneusmasker #faceshield #Jurgen #brommeropzee #eenzaam #wevergetenbekeniet #brabantmaatjes #corona #Arnhem #Baudet #GoVegan #nieuweburen #buuf #nieuwhuis #wereldibddag #breakthesilence #crohn #colitis #kiplekker #Janssen #Bedankt #WaarisWaldy #nieuwsenco #kutkaag #LonelyFans #moederdag #deugonderwijs #ikvaccineerniet #ikvaccineer #deverraders #Pfizer #zelf #bewonersinitiatief #buurthuis #ABCD #deochtend #leeftijdsdiscriminatie #Grondwet #esf21 #jurgenconings #NowPlaying #Corona #COVID19 #fvd #vaccinatiepaspoort #TolkenTerugInDeZorg #Stichting #songfestival #wandelenmetIddo #Eurovision2021 #samentegeneenzaamheid #vraaghetonzewetenschappers #vandaag #Vites #alleenwinsttelt #Mottenzedan #goedemorgen #NPO2 #Eenzaamheid #stigmatisering #burnout #ZieMij #twittelier #kijkersstaking #anderetijdenmoetblijven #natuur #team #VerGeetOnsNietHugo #VAR #KNVB #feyaja #Kamphuis #pannenkoek #alleenmaarliefde #persconferentie #ikdoenietmeermee #zeist #DeGraafschap #lldl #LongCovid #vaccinatie #EUROVISION #BroekinWaterland #Ictloketnoordkade #snelleleerling #92jaar #nooitteoudomteleren #zinvollestage #huiszoeking #BDSM #opsluiten #onderdanig #dominant #meesteres #geldslaaf #findom #femdom #findomslave #klaarmetRutte #coronamaatregelen #lonely #gezondverstand #fuckingnitwits #tonychocolonely #Rutte #vvvvenlo #ikhoopdathetgeholpenheeft #aandachttrekkenissowiesogelukt #ingeborgvraagt #Oegstgeest #ajaemm #35 #wiestaaterboven #thuiszitter #thuiswerkcultuur #anderhalvemetersamenleving #alleensamen #ramadan #coronatijd #solidariteit #ADA #VET #Bevrijdingsdag2021 #5mei #zorgvoorelkaar #wewillriseup #schildklier #man #ZwarteMuisjes #Nederland #kunstcultuurenentertainment #kunstenentertainment #onlythelonely #thuis #april21 #Eiland #Hebriden #eiland #overleving #EU #Europa #ClubCleven #justanothercommercialday #dtv #Tweedekamer #toeslagenaffaire #Werkgeluk #GelukkigLeiderschap #versoepelingstijden #spaces #vanHaga #fascistendekameruit #LangLeveDeLiefde #Covid_19 #100jaareenzaamheid #alleen #baudetmoetweg #creatief #eentegeneenzaamheid #sterkewijken #Songfestival #eenzaakvoorjou #feyutr #baudet #vluggertje #eurovision #wonen #Knarrenhof #omziennaarelkaar #rugzalvolervaringen #Joinus #Lldl #jurgenConing #verdriet #rijangst #jennygierveld\n"
],
[
"for month in \"202002 202003 202004 202005 202006 202007 202008 202009 202010 202011 202012 201201\".split():\n tweets = [re.sub(r'\\\\n', ' ', tweet) for tweet in get_tweets(month, BASEQUERY, spy=False)]\n hashtags = {}\n for tweet in tweets:\n if re.search(r'#', tweet):\n for hashtag in get_hashtags(tweet):\n if hashtag in hashtags:\n hashtags[hashtag] += 1\n else:\n hashtags[hashtag] = 1\n print(month, \" \".join([hashtag for hashtag in sorted(hashtags.keys(), key=lambda hashtag:hashtags[hashtag], reverse=True)][:200]))",
"202002 #coronavirus #corona #Coronavirus #COVID19 #coronavragen #Corona #COVID2019 #COVIDー19 #coronavirusNederland #CoronavirusOutbreak #virus #covid19 #RIVM #China #Coronavirius #FVD #Iran #CoronaVirus #Wuhan #EU #Covid_19 #ncov #COVID #patiënt #schengen #coronavirusus #Tilburg #Covid19 #Coronavius #CoronaVirusUpdates #Nederland #Italie #rivm #covid #dtv #PVV #Italië #china #Nieuwsuur #wuhan #WHO #sarscov2 #jinek #vrtnws #CoronaOutbreak #quarantaine #op1 #handenwassen #nieuws #coronavavirus #dwdd #Jinek #Erdogan #tilburg #coronaviruschina #coronarovirus #coronacrisis #boeren #nepnieuws #nieuwsuur #SARSCoV2 # #GGD #GoogleAlerts #griep #fakenews #COVID_19 #COVID19NL #Coronarivus #opengrenzen #terzaketv #Schengengrenscode #stikstofcrisis #Coronavid19 #waarschuwing #WhatsApp #nepbericht #telegraafpremium #nos #NOS #WuhanVirus #Baudet #coronavrees #Op1 #corona-virus #Rusland #NWO #Europa #vragen #FvD #Diemen #nosjournaal #antwoorden #F1 #vtmnieuws #Westerdam #coronavirus-besmetting #AEX #coronacoalitie #mondkapjes #carnaval #Bilderberg #Amsterdam #covid2019 #BNR #media #ggd #eenvandaag #kozp #coronauitbraak #CORONA #nederland #WNL #ncov2019 #Schiphol #pandemie #coronvirus #2019nCoV #coronarvirus #RodeKruis #coronavirusnederland #COVID-19 #coronaviruswuhan #globalisering #DWDD #Tenerife #D66 #delft #racisme #deafspraak #COVD19 #songfestival #Limburg #breaking #wuhanvirus #CoronaVirusitaly #Covid #FokSuk #SARS_CoV_2 #UAETour #Blok #Jankenomzwartepiet #Breaking #Wuhanvirus #Rutte #CORONAVIRUS #wnl #hypocriet #Trump #buitenhof #België #beurs #islamisering #islam #stikstof #economie #Chinezen #overheid #paniek #KLM #ChinaVirus #italie #zorg #Coronavirusnl #Beleggen #Duitsland #Update #FakeNews #besmet #npo1 #besmetting #diemen #babbeltruc #COVID19italia #covid-19 #Vilvoorde #RETWEET #Belgium #Coronavragen #Covid19-infectie #Japan #huisarts #coronarvirusitalia #Rotterdam #FD #politie #preventie #regering #nCoV2019 #Covid19Virus #NEXIT #nexit #kinderrechten #thuisquarantaine #onderwijs #Soros #AlgemeenNieuws #VVD #mondkapje #technews\n202003 #coronavirus #corona #COVID19 #coronavirusNederland #Corona #coronanederland #Coronavirusnl #COVID19NL #coronadebat #CoronaCrisis #Covid_19 #coronacrisis #COVIDー19 #Coronavirus #COVID2019NL #covid19 #COVID2019 #lockdown #RIVM #coronahulp #PVV #blijfthuis #Rutte #covid19Nederland #samentegencorona #FVD #EU #COVID19BE #Wilders #coronanl #hamsteren #rivm #coronavirusnl #Covid19 #SocialDistancing #scholendicht #coronalied #dtv #coronavirusnetherlands #zorg #op1 #lockdownnl #Nieuwsuur #coronavirusnederland #covid19nl #COVID-19 #groepsimmuniteit #Nederland #persconferentie #Coronavid19 #samensterk #houdafstand # #thuiswerken #ikblijfthuis #CoronaVirusUpdate #Baudet #Coronalul #Op1 #CoronaVirus #StayAtHome #CoronaPandemie #jinek #applausvoordezorg #SocialDistance #Jinek #Rutte3 #mondkapjes #rutte #onderwijs #COVID19Belgium #vrtnws #VVD #Italië #covid_19 #blijfbinnen #NEXIT #buitenhof #quarantaine #CoronaVirusUpdates #coronalul #nieuwsuur #virus #terzaketv #Coronacrisis #covid #dwdd #Coronabelgie #kanker #deafspraak #Nexit #China #Amsterdam #scholensluiten #blijfinuwkot #FlattenTheCurve #AlleenSamen #Trump #LockdownHolland #pandemie #CoronaOutbreak #COVID #7dag #klimaat #Iran #FvD #CoronavirusPandemic #D66 #covid19be #CoronaUpdate #Brabant #coronavragen #Italie #Groningen #mondmaskers #Europa #eenvandaag #coronapocalypse #begov #KLM #zorgvoorelkaar #België #coronamaatregelen #covid19NL #vtmnieuws #nieuws #politie #coronavirusNL #Turkije #CoronavirusOutbreak #CoronaNederland #nexit #flattenthecurve #staysafe #Covid19NL #WHO #herdimmunity #Coronadebat #groningen #SamenTegenCorona #sluitdescholen #StayHome #toespraak #horeca #COVIDIOTS #CoronaLockdown #vvd #huisartsen #zzp #Bruins #klapcoronadewerelduit #klimaathysterie #alleensamen #GGD #solidariteit #Spanje #coronapocolypse #stayathome #CoronaVirusNL #zorghelden #thuisblijven #groepimmuniteit #blijfgezond #groenlinks #covid2019 #amsterdam #ouderen #Vindicat #NOS #CoronaNL #nosjournaal #Rotterdam #Griekenland #wcpapier #ondernemers #vindicat #Buitenhof #fvd #boeren #COVIDIOT #nederland #stopcorona #covid2019nl #stikstof #stayhome #DenHaag #Coronalied #nlalert #Schiphol #Rusland #Duitsland #lockdownnederland #grenzendicht #UAntwerpen #crisis #anderhalvemeter #toiletpapier #coronavirusBE #pvda #WNL\n202004 #coronavirus #corona #COVID19 #coronacrisis #Corona #CoronaCrisis #coronadebat #coronavirusNederland #coronanederland #coronamaatregelen #COVIDー19 #covid19 #blijfthuis #Coronavirusnl #Covid_19 #samentegencorona #COVID19NL #COVID2019 #RIVM #Rutte #Coronavirus #persconferentie #PVV #mondkapjes #FVD #CoronaApp #coronanl #lockdown #COVID2019NL #Covid19NL #Wilders #Covid19 #alleensamen #op1 #EU #dtv #samensterk #AlleenSamen #COVID19BE #Nieuwsuur #jinek #BlijfThuis #covid19nl #zorg #Op1 #Nederland #coronavirusnl #mondmaskers # #rivm #China #Coronacrisis #WHO #Trump #nieuwsuur #privacy #vrtnws #VVD #Jinek #deafspraak #blijfinuwkot #5G #ikblijfthuis #Eurobonds #covid19be #Rutte3 #stopdelockdown #coronavirusnederland #coronahulp #COVID #SOSMoria #onderwijs #appathon #thuiswerken #Baudet #D66 #rutte #terzaketv #houdafstand #covid #FvD #houvol #groepsimmuniteit #COVID19Belgium #klimaat #buitenhof #SamenTegenCorona #anderhalvemeter #CoronaVirus #COVID19Pandemic #coronavragen #StayHome #stikstof #klimaathysterie #ZondagMetLubach #België #blijfgezond #anderhalvemetersamenleving #staysafe #veiligheidsraad #eurobonds #quarantaine #KLM #Amsterdam #CoronaVirusUpdate #Pasen #testen #virus #telegraafpremium #vtmnieuws #economie #politie #nieuws #CoronavirusPandemic #CDA #goedemorgen #tweedekamer #CoronaLockdown #7dag #SocialDistancing #covid19Nederland #crisis #ouderen #Duitsland #Italië #blijfbinnen #Brussel #coronabonds #begov #COVID-19 #BeterNaCorona #nexit #ondernemers #covid_19 #mensenrechten #nosjournaal #NEXIT #StayAtHome #Op1npo #eenvandaag #Zembla #coronatijd #COVID19be #Koningsdag #VolgWyniasWeek #wnl #vvd #deochtend #pandemie #Groningen #coronaNL #WNL #wilders #OMT #app #horeca #stayhome #StaySafe #CoronaHoax #ouderenzorg #Rotterdam #medicijnen #FFP2 #coronadoden #koningsdag2020 #durftevragen #Spanje #5GCoronavirus #FD #fail #NWO #mondkapje #maatregelen #frontberichten #coronaapp #FFP3 #coronalul #coronajournaal #openheid #politiek #verpleeghuizen #HongKong #IC #klokkenluiders #nederland #coronaRotterdam #COVID19-uitbraak #Europa #zorgvoorelkaar #natuur #CoronaNederland #Alleensamen #112 #ramadan #gehandicaptenzorg #LockdownSA #paasweekend #HouVol #Nexit #DitIsM\n202005 #corona #coronavirus #COVID19 #Corona #coronacrisis #coronamaatregelen #CoronaCrisis #coronadebat #covid19 #Covid_19 #COVIDー19 #Coronavirusnl #Covid19NL #persconferentie #coronanederland #RIVM #coronavirusNederland #lockdown #Coronavirus #mondkapjes #Covid19 #samentegencorona #Rutte #stopdelockdown #Op1 #COVID__19 #FVD #AlleenSamen #anderhalvemetersamenleving #Wilders #PVV #Nederland # #Op1npo #EU #rivm #dtv #Nieuwsuur #anderhalvemeter #covid19nl #covid19be #COVID19NL #horeca #zorg #covid #op1 #coronavirusnl #blijfthuis #Trump #vrtnws #Hydroxychloroquine #alleensamen #COVID #China #WHO #BlijfThuis #mondkapje #versoepeling #Rutte3 #BidVoorHelden #4mei #mondmaskers #coronatijd #coronanl #deafspraak #coronavirusnederland #Coronacrisis #beau #VVD #onderwijs #rutte #hydroxychloroquine #vrijheid #buitenhof #privacy #samensterk #D66 #COVID2019NL #bevrijdingsdag #coronaproof #7dag #virus #HongKong #AfterCovid19 #klokkenluiders #CoronaVirus #terzaketv #vaccin #economie #StopDeLockdown #CoronaApp #klimaat #BeterNaCorona #politiek #KLM #nieuwsuur #LockdownSA #ondernemers #COVIDIOTS #FvD #Covid19SA #Nexit #5G #Lockdown #NWO #staysafe #SamenSterk #houdafstand #vermijddrukte #eenvandaag #coronavragen #NEXIT #nieuws #OM #België #thuiswerken #NOS #SamenTegenCorona #OMT #OV #WNL #belang #Hondenkattenhandel #Amsterdam #klimaathysterie #COVID2019 #DenHaag #moederdag #COVID-19 #Brussel #BillGates #jinek #1mei #politie #blijfgezond #scholenopen #NPO #YULIN #groepsimmuniteit #Dodenherdenking #biomassa #denhaag #nepnieuws #wnl #verpleeghuizen #schande #begov #Bevrijdingsdag #75jaarvrijheid #vaccinatie #Covid #pandemie #MSM #nosjournaal #CDA #testen #Beau #Rotterdam #Ramadan #scholendicht #cultuur #op1npo #cartoon #warmtepomp #Antwerpen #NL #media #durftevragen #luchtvaart #scholen #goedemorgen #vtmnieuws #veiligheidsraad #humor #ouderen #nexit #BREAKING #5mei #CoronavirusPandemic #EU-schulden #kapper #kinderen #coronaboete #coronahulp #COVID19be #uk #Onderwijs #crisis #Gates #webinar #Jensen #vvd #Vrijheid #ov #dagvandeverpleging #vakantie #Covid-19 #school #Virus #dictatuur\n202006 #corona #coronavirus #Corona #COVID19 #Halsema #coronamaatregelen #coronacrisis #coronadebat #Amsterdam #coronawet #covid19 #viruswaanzin #PVV #CoronaCrisis #Covid_19 #anderhalvemeter #Wilders #BlackLivesMatterNL #Rutte #Coronavirusnl #COVID19NL #Coronavirus #demonstratie #RIVM #Malieveld #halsema #Covid19 #FVD #blijfthuis #spoedwet #BlackLivesMatter # #Coronawet #COVIDー19 #Nieuwsuur #lockdown #covid19nl #zorg #coronanederland #Nederland #SocialDistancing #op1 #dtv #racisme #persconferentie #beau #corona-regels #Malieveld21juni #anderhalvemetersamenleving #HalsemaAftreden #AlleenSamen #coronavirusNederland #Op1 #samentegencorona #vrijheid #BLM #triest #COVID__19 #coronaise #Grapperhaus #esbeek #hugodejonge #mondkapjes #Spoedwet #FemkeHalsema #LiftTheTravelBan #LoveIsNotTourism #Loveisessential #horeca #DenHaag #luchtvaart #Rotterdam #amsterdam #kermisprotest #vaccin #rivm #stopdelockdown #malieveld #vrtnws #alleensamen #covid #rutte #EU #CDA #Coronacrisis #Op1npo #coronavirusnl #covid19be #Dam #VVD #5G #Hydroxychloroquine #politie #Antifa #coronaproof #coronaregels #KICKOUTRUTTE #coronanl #CoronaApp #virus #scholendicht #noodwet #nosjournaal #johanderksen #privacy #teamJohanDerksen #eenvandaag #deafspraak #Trump #politiek #Suriname #COVID #nieuwsuur #Covid-19 #coronatijd #BLMBelgium #NWO #klimaat #Covid19NL #mondmaskers #COVIDIOTS #KLM #Lockdown #teamvrijheid #COVID-19 #Brussel #zorgpersoneel #COVID2019NL #halsemagate #dejonge #onderwijs #burgemeester #coronahoax #nertsen #denhaag #ihoik #staycation #D66 #terzaketv #indenbak #ophetstrand #ikremvoorcorona #dam #WHO #Schiphol #dictatuur #JaapvanDissel #BlackLivesMatterNL-protesten #vakantie #mondkapje #Covid19SA #China #democratie #CoronaVirus #scholen #aftreden #BlackLivesMattters #HalsemaExit #scholenopen #ouderen #GGD #nosnieuws #FvD #LockdownSA #samensterk #NOS #NoExamsInCovid #Groenlinks #frontberichten #BillGates #Koning #HugodeJonge #vvd #AllLivesMatter #besmettingen #WNL #economie #malieveld28juni #coronatest #rechtsgeluid #LivesMatter #Beau #Flikker #anderhalvemeterdictatuur #StemZeWeg #NPO #Rutte3 #thuiswerken #16Juin2020 #Erasmusbrug #nieuws #pvda #kickoutrutte #KOZP #blm #rotterdam #durftevragen #verpleeghuizen #vliegen #7dag\n202007 #coronavirus #corona #COVID19 #Corona #coronamaatregelen #covid19 #coronacrisis #COVID19NL #RIVM #Rutte #viruswaanzin #Covid_19 #COVIDー19 #CoronaCrisis #Covid19 #mondkapjes #COVID__19 # #Coronavirus #Nieuwsuur #lockdown #HugoDeJonge #covid19nl #dtv #EU #coronawet #anderhalvemeter #spoedwet #Antwerpen #Coronavirusnl #covid #AlleenSamen #samentegencorona #mondkapje #mondmaskers #Nederland #WHO #Op1 #vrtnws #Hydroxychloroquine #mondkapjesplicht #Coronawet #PVV #boerenprotest #hugodejonge #coronavirusnl #veiligheidsraad #staysafe #Wilders #rivm #Op1npo #BillGates #Covid-19 #klimaat #StemZeWeg #pandemie #tweedegolf #coronacommissie #Gommers #CoronaApp #zorg #vaccin #CoronaMelder #vrijheid #vakantie #covid19be #CoronaVirus #Trump #terzaketv #HongKong #op1 #DeJonge #VVD #COVID19be #boeren #BLM #EUtop #peiling #COVID #nexit #anderhalvemeterdictatuur #BigPharma #nertsen #COVID-19 #virus #NEXIT #mondmasker #noodwet #coronatest #persconferentie #stopcorona #MSM #Vrijheid #Schiphol #OMT #Amsterdam #rutte #coronanederland #eurotop #boerenprotesten #coronavragen #besmettingen #CDA #coronaproof #BlackLivesMatter #CDA-lijsttrekker #asielzoekers #luchtvaart #België #NoordKorea #coronanl #WWG1WGA #coronahoax #Covid19NL #blijfthuis #coronavaccin #Covidioten #testen #horeca #HCQ #GiletsJaunes #media #scholendicht #DontTurnPrisonsIntoGraveyard #poll #COVID_19 #Lockdown #VanRanst #economie #alleensamen #avondklok #nosjournaal #politie #BREAKING #CDAdebat #offerfeest #spoedWET #Offerfeest #machtsgreep #COVID19BE #Netherlands #COVID19-pandemie #Mondkapjes #politiek #Coronacrisis #COVIDIOTS #eenvandaag #Macron #vvd #transferunie #anderhalvemetersamenleving #corona-uitbraak #Rutte3 #Beau #corona-besmettingen #herstelfonds #Covid #beau #SamenTegenCorona #RTLNieuws #SARSCoV2 #vtmnieuws #coronavirusNederland #racisme #EUCO #veto #gezondheid #KICKOUTRUTTE #nieuws #nieuwsuur #racistisch #begov #NWO #dieprespect #Politie #Rotterdam #RACISME #coronabeleid #Belgie #D66 #Brexit #stikstof #CoronaVirusHoax #USA #stopdelockdown #FVD #solidariteit #stemzeweg #kinderen #EU-landen #thuiswerken #telegraafpremium #SocialDistancing #coronawaanzin #quarantaine #niettegeloven #KLM #StilleLente #Vaccin #scholen\n202008 #corona #coronadebat #coronavirus #coronamaatregelen #Corona #COVID19 #COVID19NL #Covid_19 #persconferentie #Wilders #Grapperhaus #covid19 #coronacrisis #RIVM #viruswaanzin #CoronaCrisis #CoronaMelder #Rutte #covid19nl #coronawet #Coronavirusnl #spoedwet #GeenDorHout #Covid19 #hugodejonge # #Nederland #PVV2021 #Coronavirus #mondkapjes #anderhalvemeter #mondkapjesplicht #PVV #nexit #covid #lockdown #COVID__19 #AlleenSamen #Amsterdam #Berlin2908 #zorg #CDA #COVIDー19 #dtv #Coronaregels #FVD #coronahoax #scholenveilig #viruswaarheid #Rutte3 #Covidioten #EU #samentegencorona #Rotterdam #coronanederland #mondkapje #StemZeWeg #horeca #zorgmedewerkers #Malieveld #schande #Berlijn #coronavirusnl #Coronacrisis #Nieuwsuur #coronaregels #GGD #rivm #zorgpersoneel #GrapperhausCoronaGate #Op1 #zorghelden #virus #VVD #politie #noodwet #mondmaskers #coronatest #coronamelder #pandemie #nederland #Covid-19 #rutte #Hydroxychloroquine #scholen #WakeUp #vaccin #coronaboete #bruiloft #Schiphol #Spoedwet #FerdGrapperhaus #HugodeJongeKanNiks #vrtnws #coronanl #Coronadebat #LinkedIn #privacy #BerlinDemo #vrijheid #op1 #quarantaine #alleensamen #COVIDIOTS #OMT #ContainmentNu #Coronademo #coronaproof #stopdespoedwet #COVID #onderwijs #huisartsen #artsen #berlijn #nosjournaal #nertsen #CoronaApp #ventilatie #dictatuur #malieveld #denhaag #tweedekamer #hittegolf #MauricedeHond #nederlanders #teststraat #COVID_19 #geendorhout #wilders #coronawaanzin #WHO #DenHaag #Coronawet #codeoranje #vvd #wilders2021 #D66 #𝗭𝗮𝗮𝗻𝘀𝘁𝗮𝗱 #Op1npo #coronavirusNederland #testen #Spanje #Covid19NL #COVID-19 #coronabeleid #eenvandaag #GerechtigheidVoorBas #belastinggeld #telegraafpremium #ggd #Covid #Transferunie #WWG1WGA #nederlandsnieuws #Antwerpen #TK2021 #peiling #Netherlands #held #SPOEDWET #Halsema #VRIJHEID #Berlin #covid19be #Lockdown #besmettingen #tweedegolf #volksmanipulatie #Mondkapjes #stopdelockdown #MSM #HCQW0RKS #economie #terzaketv #poll #CovidHoax #londonprotest #politiek #SARSCoV2 #NWO #SpoedwetNee #Beiroet #bronencontactonderzoek #klimaat #kabinet #Beirut #hoax #NEDERLAND #willemengel #groepsimmuniteit #grapperhaus #vakantie #defensie #grondwet #coroNEE #nieuws #Onderwijs #EenVandaag #coronaisfakenews #Coronamaatregelen\n202009 #corona #coronadebat #coronamaatregelen #COVID19 #Corona #coronavirus #FVD #Grapperhaus #persconferentie #COVID19NL #ikdoenietmeermee #Covid_19 #covid19 #mondkapjes #coronacrisis #ikdoewelmee #Rutte #coronaregels #RIVM #PVV #coronawet #covid19nl #CoronaCrisis #Wilders #Covid19 #spoedwet #coronatest #COVIDー19 #PCRgate #Spoedwet #dtv #AlleenSamen #covid # #Nederland #jinek #mondkapje #Coronavirus #tweedegolf #Baudet #scholenveilig #COVID__19 #avondklok #Nieuwsuur #coronavaccin #lockdown #anderhalvemeter #coronatesten #hugodejonge #mondkapjesplicht #ikdoenietmee #peiling #grapperhaus #coronavirusnl #Op1 #virus #GrapperhausCoronaGate #samentegencorona #noodwet #rutte #zorg #kabinet #coronaproof #vaccin #aftreden #Rutte3 #PCR #nederland #FamkeLouise #horeca #Amsterdam #Coronavirusnl #rivm #viruswaanzin #coronanl #op1 #EU #nexit #Jinek #BreekDeGolf #coronahoax #Pfizer #GGD #APB2020 #LongCovid #nietmijnregering #Rotterdam #vrtnws #testen #alleensamen #Grapperhausaftreden #COVID #StemZeWeg #stopdespoedwet #PCRGATE #CoronaMelder #onderwijs #HydroxyChloroquine #thuiswerken #Covid #FvD #CDA #maatregelen #coronabeleid #ZondagMetLubach #PCRtest #viruswaarheid #persco #NWO #politiek #poll #WHO #Moria #Nijmegen #Covidioten #gewoonjebekhouden #deafspraak #prinsjesdag2020 #ContainmentNu #Coronadebat #Op1npo #coronaboete #Akwasi #pandemie #scholen #coronanederland #OMT #ZML #nosjournaal #nieuwsuur #quarantaine #nederlandsnieuws #hugodejongekanniks #besmettingen #guestpost #coronaboetes #poppenkast #grapperhausdebat #VVD #Trump #Tilburg #veiligheidsraad #politie #Lockdown2 #peilingen #NOS #tweedekamer #mondkappennou #Duitsland #wnlopzondag #SpoedwetNee #longcovid #DenHaag #voetbal #nieuws #HCQ #ferdgrapperhaus #dictatuur #zorgpersoneel #telegraafpremium #op1npo #buitenhof #Ikdoenietmeermee #Prinsjesdag #HugodeJongeKanNiks #hoax #Netherlands #Albert #Monaco #COVID_19 #TweedeKamer #wijdoenwelmee #SARSCoV2 #vrijheid #grappenhaus #Coronawet #deochtend #terzaketv #ggd #privacy #stopwillemengel #economie #zondagmetlubach #covid19be #Vaccin #ikdoeooknietmeermee #eenvandaag #herstelfonds #Onderwijs #kinderen #COVIDIOTS #luchtvaart #groningen #coronamelder-app #Coronastaatsgreep #fail #FVD-leider #Corona-regels #Coronamaatregelen #COVID-19\n202010 #coronamaatregelen #corona #COVID19 #Corona #coronavirus #coronadebat #COVID19NL #FVD #lockdown #persconferentie #spoedwet #covid19 #Covid_19 #coronawet #mondkapjes #Wilders #covid19nl #Rutte #PVV #COVID__19 #coronacrisis #horeca #coronaregels #Covid19 #CoronaMelder #CoronaCrisis #dtv #Spoedwet #AlleenSamen #RIVM #covid #samentegencorona #Trump #zorg #Coronapandemie #PCRGATE #PCRgate #mondkapje #mondkapjesplicht # #deafspraak #jinek #blijfthuis #scholendicht #Lockdown2 #Nederland #vrtnws #Staphorst #Nieuwsuur #Op1 #coronavirusnl #peiling #COVID #virus #rutte #avondklok #op1 #TrumpHasCovid #vaccin #zorgpersoneel #scholenveilig #Coronavirus #Rutte3 #COVIDIOTS #Coronavirusnl #coronavragen #ikdoenietmeermee #COVIDー19 #routekaart #coronanl #Jinek #wilders #rivm #coronatest #terzaketv #COVID19be #Covid #BREAKING #hydroxychloroquine #Coronadebat #hugodejonge #tweedegolf #mondkapjesadvies #onderwijs #coronaproof #scholen #alleensamen #nietmijnregering #noodwet #PCRtest #maatregelen #WHO #DenHaag #Brussel #horecadicht #vtmnieuws #LongCovid #coronahoax #veerkracht #covid19be #groepsimmuniteit #pandemie #begov #Coronalert #Coronamaatregelen #vierdagenextra #Griekenland #StaySafe #anderhalvemeter #TK2021 #7dag #coronamelder #NWO #Covidioten #TrumpCovid #CoronaApp #D66 #Amsterdam #OMT #dictatuur #mondmaskers #koningshuis #StemZeWeg #Op1npo #deochtend #democratie #VVD #EersteKamer #nosjournaal #denhaag #GERRITSEN #besmettingen #hydroxycholoroquine #poll #EU #hoax #vakantie #coronalert #islam #persco #coronamadness #coronatesten #hugodejongekanniks #WWG1WGA #thuiswerken #ikdoewelmee #viruswaarheid #coronabeleid #Zorgsalaris #peilingen #tweedekamer #WillemAlexander #Demmink #Verzet #NOS #nederland #trump #Remdesivir #Lockdown #Rotterdam #events #SamenTegenCorona #media #nieuws #viruswaanzin #briefing #kabinet #vvem #TweedeKamer #coronabesmettingen #OpenData #Aboutaleb #stopdelockdown #FvD #fail #Coronawet #nieuwsuur #ZondagMetLubach #Onderwijs #voetbal #Baudet #buitenhof #China #klimaat #wijdoenmee #coronanederland #Netherlands #vvd #ikdoenietmee #covid19NL #quarantaine #veiligheidsraad #alcoholverbod #koning #mondkappennou #PCR #eenzamejongeren #sluitnoutochdescholen #WelkomInDystopia #vrt\n202011 #coronamaatregelen #corona #COVID19 #coronavirus #Corona #COVID19NL #coronadebat #covid19nl #FVD #persconferentie #PCRgate #covid19 #coronavaccin #coronacrisis #mondkapjesplicht #Covid_19 #lockdown #ditismijnzorg #PVV #vaccinatieplicht #mondkapjes #vaccin #Wilders #Rutte #Covid19 #vaccinatie #AlleenSamen #covid #PCRtest #Vaccin #samentegencorona #dtv #RIVM #VVD #mondkapje #blijfthuis #CoronaCrisis #spoedwet #zorg # #coronavirusnl #virus #avondklok #Vaccinatie #Trump #Nederland #horeca #scholenveilig #vrtnws #tweedekamer #Nieuwsuur #EU #coronaproof #COVID #vuurwerkverbod #coronawet #nertsen #COVIDー19 #vrijheid #pandemie #coronatest #rutte #peiling #LongCovid #OMT #coronanl #7dag #Coronavirus #scholendicht #FvD #politie #D66 #Verzet #NWO #COVIDIOTS #alleensamen #hugodejonge #WEF #WHO #Pfizer #coronahoax #BlackFriday #Coronavirusnl #coronascam #jinek #maatregelen #deafspraak #PCRGATE #TK2021 #op1 #dictatuur #terzaketv #informeer #Elections2020 #Op1 #Lockdown2 #onderwijs #TheGreatReset #thuiswerken #rivm #Baudet #nietmijnregering #Rutte3 #CoronaMelder #Rotterdam #COVID1984 #Covidioten #scholen #Sinterklaas #Covid #coronaregels #kerst #Brussel #coronatijd #pcrtest #anderhalvemeter #Biden #ikdoenietmeermee #vuurwerk #SamenTegenCorona #COVID19be #nieuws #beau #vaccineren #toeslagenaffaire #OpenData #Jinek #Mondkapjes #Agenda2030 #coronazwendel #begov #wezijnjulliespuugzat #Coronapandemie #StemZeWeg #ikvaccineer #klimaat #overheid #Amsterdam #KLM #laatjeniettesten #durftevragen #covid19be #media #besmettingen #MSM #CDA #poll #fvd #StopCovid #ZeroCovid #PCR #vvd #demonstratie #persco #Coronamaatregelen #coronadictatuur #fitness #KOZP #verkiezingen #ikvaccineerniet #blijfgezond #telegraafpremium #deochtend #gezondheid #vivaldi #DitIsM #bpoc2020 #VeiligOnderwijs #testen #NEPcoronacrisis #nosjournaal #vtmnieuws #patenten #fakenews #groningen #Spoedwet #koopzondag #iklaatmeniettesten #Vivaldi #StaySafe #coronabesmettingen #covid19NL #economie #255 #hoax #downtheroad #viruswaanzin #DenHaag #quarantaine #kinderen #peilingen #privacy #samensterk #luchtvaart #horecadicht #Denemarken #ondernemers #kabinet #proximusepic #GGD\n202012 #coronamaatregelen #corona #coronavirus #COVID19 #Corona #lockdown #FVD #coronadebat #coronavaccin #COVID19NL #persconferentie #Rutte #covid19nl #Covid_19 #covid19 #mondkapjesplicht #coronacrisis #vaccin #Covid19 #horeca #Vaccinatie #coronabeleid #CoronaCrisis #vaccinatieplicht #AlleenSamen #Lockdownnl #covid #vaccinatie #toespraakrutte #Vaccin #VVD #PVV #mondkapjes #blijfthuis #avondklok #dtv #kerst #zorg #RIVM #mondkapje #CodeZwart #toeslagenaffaire #vaccineren #rutte #hugodejongekanniks #Nederland #PCRGATE #TheGreatReset #hugodejonge #virus #PCRtest # #Nieuwsuur #ikdoenietmeermee #LongCovid #coronahoax #samentegencorona #vaccinatiestrategie #CDA #D66 #codezwart #coronatest #COVIDー19 #Wilders #Covid #vaccinatiebewijs #StemZeWeg #Schiphol #COVID #CatshuisOverleg #peiling #OMT #coronazwendel #Rutte3 #vaccins #op1 #spoedwet #coronavirusnl #StemNederlandTerug #mutatie #vrijheid #persco #Lockdown #Coronavirus #tweedekamer #EU #Pfizer #Coronabeleid #coronavragen #maatregelen #coronaproof #lockdownnl #vaccinatiedebat #poll #vrtnws #beau #VeiligOnderwijs #FvD #besmettingen #Covidioten #scholen #PCRgate #viruswaanzin #arrogant #oudennieuw #kerstmis #rivm #alleensamen #politie #wappies #Op1 #coronapaspoort #peilingen #volksgezondheid #torentje #nosjournaal #Kerst #kabinet #CoronaVaccine #Lockdown2 #kerst2020 #covid19be #onderwijs #coronacircus #MinistryOfTruth #ZeroCovid #coronanl #gezondheid #pandemie #coronawet #HugodeJonge #Coronamaatregelen #Covid-19 #schiphol #CU #scholenveilig #GreatReset #WEF #BREAKING #Brexit #luchtvaart #Beau #CovidVaccine #covid1984 #7dag #vvd #AbOsterhaus #overheid #Influenza #fail #eenvandaag #Corona-besmettingen #thuiswerken #deafspraak #WHO #toespraak #Hydroxychloroquine #hoax #KerstZonderPiek #nieuwsuur #terzaketv #Pandemie #vuurwerkverbod #bezuinigingen #TK2021 #GGD #schandalig #feestdagen #Coronavirusnl #groepsimmuniteit #Avondklok #femkehalsema #Gommers #SARSCoV2 #brexit #StaySafe #Covid1984 #Coronacrisis #COVID-19 #griep #coronawaanzin #vaccindwang #kinderen #nieuws #dictatuur #anderhalvemeter #Demmink #Spoedwet #deochtend #Corona-virus #Amsterdam #DeJonge #IC #OudEnNieuw #ikvaccineer #scholendicht #BlijfThuis #buitenhof #COVID1984 #BigPharma\n201201 #coronamaatregelen #corona #coronavirus #mondkapjesplicht #COVID19NL #COVID19 #Corona #femkehalsema #coronavaccin #covid19nl #mondkapjes #mondkapje #Covid19 #hugodejongekanniks #covid19 #coronacrisis #AlleenSamen #Covid #elite #PCRtest #Coronacrazy #HugodeJonge #Fidesz #CrimesAgainstHumanity #Rutte #lockdown #Nieuwsuur #F1 #poll #dtv #vaccinatie #LGBTQ'ers #vaccin #peilingen #peiling #PCRTestPandemic #SakhirGP #CoronaMelder-app #Spoedwet #Covid_19 #coronavirusnl #BahrainGP #pcrgate #coronafascisme #RIVM #samentegencorona #ZiggoSportF1 #vaccindwang #hugodejonge #covid #PCRGATE #Coronamaatregelen #besmettingen #horeca #COVID1984 #TK2021 #TotalControl #Amsterdam #PCRTest #PCRgate #BlackFriday #Rutte3 #vaccine #virus #CoronaCrisis #mijnbrief #VeiligOnderwijs #tweet #citeren #retweeten #liken #VRIJHEID #GERRITSEN #terzaketv #wereldaidsdag #wetenschap #COVID #Vaccin #VVD #testen #covID19 #begov #vivaldi #spoedwet #coronawet #alleensamen # #CovidInJeBroekje #Coronapandemie #coronatest #Otterlo #CDC #GGD #FVD #vaccinatieplicht #Coronavirus #_vvd #Nederland #kerst2020 #vuurwerkverbod #onderwijs #PCR-testen #USA #covid19NL #coronadebat #coronagate #Hamilton #coronanl #coronahoax #coronatijd #politie #vrijheid #Pfizer #Vaccinatie #BigPharma #teststraten #Vivaldi #OMT #blijfthuis #CovidVaccine #Denemarken #overheid #Mondkapjesplicht #verzet #downtheroad #covid19be #dictatuur #vrtnws #followback #pandemie #zorg #scholenveilig #WorldAIDSDay #top2000 #CoronaMelder #coronaproof #toeslagenaffaire #coronavaccins #vrijheidop1 #top2000agogo #nosjournaal #volger #supermarktmedewerkers #koekeerlijkverdelen #beau #Coronabedrog #kinderen #scholen #boek #nertsen #AstraZeneca #Ademtesten #vaccins #GivingTuesday #PVV #samensterk #nieuws #Coronamelder #omvolking #taboeisering #waardeeronswerk #WEF #VictorOrban #homofobe #nationalistische #EPP #Op1 #pcrtest #Top2000 #Alleensamen #Mondkapjes #BlackFriday2020 #CoronaCrazy #SARSCoV2 #rivm #anderhalvemeter #fitness #FixedItForYa #muilkorf #maatregelen #vuurwerk #Brexit #BlijfThuis #coronadictatuur #Mondkapje #Coronavirusnl #Coronacrisis #UGent-onderzoeker #AbOsterhaus #Amerika #StemZeWeg #PCR #emmen #coronazwendel #durftevragen #Wilders #fit #deafspraak #kerst #Followback\n"
],
[
"for month in \"202101 202102 202103 202104\".split():\n tweets = [re.sub(r'\\\\n', ' ', tweet) for tweet in get_tweets(month, BASEQUERY, spy=False)]\n hashtags = {}\n for tweet in tweets:\n if re.search(r'#', tweet):\n for hashtag in get_hashtags(tweet):\n if hashtag in hashtags:\n hashtags[hashtag] += 1\n else:\n hashtags[hashtag] = 1\n print(month, \" \".join([hashtag for hashtag in sorted(hashtags.keys(), key=lambda hashtag:hashtags[hashtag], reverse=True)][:200]))",
"202101 #coronamaatregelen #coronavirus #corona #avondklok #coronadebat #COVID19 #lockdown #Corona #FVD #coronavaccin #COVID19NL #coronaprotest #Rutte #covid19nl #vaccin #covid19 #avondklokrellen #persconferentie #vaccinatie #Covid19 #coronabeleid #Vaccinatie #rellen #museumplein #avondklokdebat #covid #stopdelockdown #Eindhoven #coronacrisis #toeslagenaffaire #Covid_19 #PVV #vaccinatiestrategie #Amsterdam #AlleenSamen #AvondklokProtest #dtv #CoronaCrisis #politie #Wilders #vaccineren #vrijheid #lockdown2021 #ikwildieprik #VVD #jinek #COVID #op1 #RIVM #OMT #coronarellen # #zorg #kabinet #rutte #mondkapjes #hugodejonge #Nederland #Urk #TheGreatReset #StemNederlandTerug #peiling #virus #Op1npo #ikdoenietmeermee #StemZeWeg #Ivermectine #samentegencorona #Nieuwsuur #coronavaccinatie #coronazwendel #opendebat #coronavirusnl #COVIDー19 #amsterdam #Pfizer #Coronavirus #Avondklok #D66 #coronanl #Vaccin #peilingen #ZeroCovid #onderwijs #blijfthuis #IkPrikHetNiet #LongCovid #vaccins #nosjournaal #scholen #coronatest #thegreatreset #CDA #vvd #Trump #mondkapjesplicht #EU #Covid #vaccinatieplicht #eindhoven #BuildBackBetter #mondkapje #wappies #tweedekamer #coronaspreekuur #demonstratie #Lockdownnl #rutteaftreden #Jinek #Museumplein #Baudet #WHO #pcrtest #pandemie #codezwart #vrtnws #horeca #persco #lockdownnl #ikvaccineer #coronahoax #relschoppers #nieuws #rivm #verkiezingen #GGD #scholendicht #TK2021 #coronawet #Ruttedoctrine #kinderen #PCRtest #informeer #FvD #deafspraak #avondklokprotest #durftevragen #CrimesAgainstHumanity #alleensamen #spoedwet #NEPcoronacrisis #GreatReset #Op1 #WEF #hugodejongekanniks #thuisonderwijs #op1npo #wijzijnmetmeer #vliegverbod #dictatuur #Gommers #toeslagenschandaal #vaccinaties #stemnederlandterug #urkers #klimaat #Lockdown #poll #B117 #thuiswerken #Enschede #Rutte3 #politiek #covID19 #Schiphol #NOS #nieuwsuur #viruswaanzin #gezondheid #maatregelen #DenHaag #britsevariant #coronaproof #luchtvaart #covid19be #overheid #CoronaVirus #geenavondklok #ivermectine #HugodeJonge #vuurwerkverbod #AstraZeneca #protest #mRNA #ME #vivaldi #Biden #Coronamaatregelen #StopDeLockdown #CovidMemorialDay #TheGreatResist #coronavaccins #wappie #verzet #vaccinatiedebat #NWO #urk #VanDissel #fail #lekkerrelatief\n202102 #coronamaatregelen #coronavirus #corona #avondklok #Corona #COVID19 #FVD #lockdown #coronadebat #klaarmetRutte #persconferentie #StemNederlandTerug #coronavaccin #COVID19NL #Rutte #coronaregels #covid19 #covid19nl #vaccinatie #stopdelockdown #PVV #horeca #ZeroCovid #Vaccinatie #Covid19 #RIVM #Wilders #vaccin #LongCovid #spoedwet #StopDeLockdown #coronacrisis #OMT #coronabeleid #BuildBackBetter #vanangstnaarvertrouwen #AlleenSamen #persco #museumplein #dtv #scholenopen #covid #VVD #CoronaCrisis #HerstelNL #jinek #mondkapjesplicht #vaccineren #TheGreatReset #Covid_19 #vaccinatiestrategie #kutcorona #Ivermectine #klaarmetdeJonge #lockdownnl # #Nieuwsuur #Baudet #hugodejonge #TK2021 #CDA #FvD #vrijheid #vaccinatiepaspoort #avondklokdebat #viruswaarheid #vaccinatiebewijs #StemZeWeg #verkiezingen #sneeuw #D66 #Avondklok #openNLnu #17maartFVD #Nederland #rutte #waarligtjouwgrens #Op1 #opendebat #COVID #coronavaccinatie #op1 #klaarmetRutte3 #hogerberoep #lockdown2021 #Vaccin #PandemiePremie #virus #toeslagenaffaire #coronatest #Spoedwet #vaccinatieplicht #hugodejongekanniks #Covid #coronawet #onderwijs #retweet #coronazwendel #Op1npo #Vondelpark #peiling #dictatuur #zorg #viruswaanzin #testen #wnl #GreatReset #scholendicht #AstraZeneca #horecaopen #overheid #TweedeKamer #kabinet #vaccins #volksgezondheid #rivm #nieuws #AvondklokProtest #COVIDー19 #longcovid #NOS #opennlnu #peilingen #nosjournaal #mondkapjes #scholen #WHO #Elfstedentocht #angstzaaierij #eerstekamer #schaatsen #Coronavirus #coronaproof #vrtnws #EU #StemPVV #kinderpersconferentie #BREAKING #coronavirusnl #Coronamaatregelen #kinderen #Jinek #telegraafpremium #coronahoax #bewaartweet #WinkelsOpen #GGD #mondkapje #leugen #pandemie #coronapaspoort #Ruttedoctrine #MKB #poll #jongeren #coronadictatuur #pcrtest #politie #ikdoenietmeermee #fvd #buitenhof #avondklokzaak #versoepelingen #FD #ziek #HorecaOpen #Amsterdam #Nexit #politiek #vaccine #Fact #China #tweedekamer #MSM #testsamenleving #vvd #avondklokwet #7dag #nature #WatNouLockdown #Duitsland #klaarmetRIVM #zerocovid #blijfthuis #klimaat #Pfizer #coronaprotest #ophokplicht #samentegencorona #ivermectine #scholenveilig #VergeetOnsNietHugo #pandemiepremie #BuildBackBetterDebat #kappers #deafspraak #baudet #eenvandaag #Verkiezingen2021 #wnlopzondag\n202103 #coronamaatregelen #coronavirus #corona #FVD #COVID19 #Corona #coronadebat #lockdown #avondklok #coronapaspoort #coronavaccin #StemNederlandTerug #COVID19NL #persconferentie #covid19nl #stopdelockdown #PVV #Rutte #museumplein #Verkiezingen2021 #Wilders #vaccinatie #TK2021 #covid19 #AstraZeneca #ZeroCovid #Museumplein #Malieveld #vaccinatiepaspoort #IkSpreekMeUit #RIVM #Covid19 #StemZeWeg #LongCovid #Vaccinatie #vaccin #mondkapjesplicht #vrijheid #coronacrisis #dtv #Ollongren #VVD #politie #D66 #StemFVD #horeca #covid #klaarmetRutte # #verkiezingen #politiegeweld #FvD #CDA #vaccinatieplicht #StopDeLockdown #hugodejonge #Nederland #testbewijs #COVID #Baudet #fvd #vaccinatiestrategie #mondkapjes #vrijheidskaravaan #17maartFVD #AlleenSamen #rutte #coronatribunaal #coronabeleid #TheGreatReset #malieveld #hugodejongekanniks #Covid #coronavaccinatie #Amsterdam #vaccineren #klaarmetdeJonge #Covid_19 #jinek #Kaag #BuildBackBetter #Op1 #testsamenleving #vaccins #CoronaCrisis #vanangstnaarvertrouwen #EU #vaccinatiegate #Nieuwsuur #pandemie #OMT #moederhart #TeHoog #ikbeneenwappie #versoepelingen #iktwijfel #griep #Pfizer #Ruttedoctrine #coronahoax #wappies #Coronavirus #SP #toeslagenaffaire #lockdown2021 #coronatest #coronawaanzin #PCRgate #PvdA #grondrechten #vrtnws #vaccinatiebewijs #aboutaleb #ivermectine #nederland #overlegcomite #Vaccin #coronaregels #verkiezingsuitslag #peiling #onderwijs #Avondklok #op1 #VergeetOnsNietHugo #censuur #covid19be #nieuws #SolidairNaarNul #exitpoll #JA21 #ikprikhetniet #TweedeKamer #rivm #longcovid #peilingen #uitslagenavond #CatshuisOverleg #stemzeweg #besmettingen #overlegcomité #nepnieuws #volksgezondheid #Zweden #zorg #Corona-virus #Groenlinks #coronavaccins #7dag #coronaproof #nosjournaal #transparantie #50Plus #Coronamaatregelen #NOS #vvd #deafspraak #TeamSamen #lockdowns #beau #kinderen #stopwillemengel #griepje #dictatuur #spoedwet #Op1npo #formatie #museumplein20maart #COVIDー19 #LongCovidKids #verkiezingen2021 #ikspreekmeuit #Omtzigt #onzekinderenonzekeuze #Jinek #Texas #maatregelen #tk2021 #GL #Mondkapjes #d66 #demonstratie #debat #persco #coronawet #WHO #wappie #testen #Ivermectine #horecaopen #PCR #klaarmetrutte #AstraZenaca #thegreatreset #politiek #Ramadan #Nexit #nederlandkiest #Urk #klaarmetRutte3 #terzaketv\n202104 #coronamaatregelen #coronavirus #corona #coronadebat #COVID19 #Corona #coronavaccin #FVD #lockdown #stopdelockdown #versoepelingen #COVID19NL #Rutte #covid19nl #vaccinatie #covid19 #AstraZeneca #ZeroCovid #avondklok #coronapaspoort #Vaccinatie #RIVM #covid #persconferentie #Covid19 #testsamenleving #coronacrisis #vaccin #horeca #coronavaccinatie #persco #vaccinatiestrategie #ZeroCovidDayOfAction #testmaatschappij # #LongCovid #dtv #codezwart #politie #PVV #Ivermectine #vrijheid #Coronadebat #TegenGecontroleerdVerspreiden #vaccinatiepaspoort #nederland #Covid #Nieuwsuur #zorg #Nederland #CoronaCrisis #Wilders #TestenvoorToegang #terrassen #India #Covid_19 #COVID #hugodejonge #rutte #museumplein #OMT #catshuis #AlleenSamen #vaccineren #TeHoog #vaccins #mondkapjes #Testsamenleving #beau #koningsdag #nederlands #politiegeweld #nederlandsnews #Koolmees #quarantaineplicht #vaccinatieplicht #omtzigtdebat #koningsdag2021 #wappies #peiling #Coronavirus #BPOC2020 #Op1 #coronatest #coronabeleid #WEF #notulen #lekkereten #bijnaopen #buiteneten #steunhoreca #bestaan #longcovid #op1 #testbewijs #mondkapjesplicht #peilingen #mondkapje #coronahoax #IC #Fieldlab #terrassenopen #mRNA #pandemie #toeslagenaffaire #fvd #Terrassen #beterschapthierry #ruttefunctieelders #coronatribunaal #fakenews #COVIDー19 #coronawet #vaccinaties #RutteLeugenaar #coronamaatregel #moederhart #hugodejongekanniks #Ruttedoctrine #zerocovid #VVD #nieuws #poll #fieldlabs #EU #Duitsland #astrazeneca #rivm #besmettingen #Vaccin #Pfizer #virus #vrtnws #TheGreatReset #Koningsdag #Museumplein #JA21-politica #kabinet #AstraZenaca #groepsimmuniteit #wappie #Hugomoetsnelweg #tweedekamer #WHO #ziekenhuis #durftevragen #Kaag #klaarmetRutte #Coronamaatregelen #coronawaanzin #coronavaccins #nosjournaal #terzaketv #griep #sneltesten #KlapVoorDeZorg #PCRtest #CDA #politieverhoren #LongCovidKids #COVIDIOTS #toeslagenschandaal #baudet #onderwijs #debat #Beau #Rotterdam #Amsterdam #nep #PCR #MSM #D66 #zelftest #anderhalvemeter #scholen #nieuweverkiezingen #coronaproof #ikdoenietmeermee #samentegencorona #covid19be #fuellmich #TweedeKamer #demonstratie #kinderen #vaccinatietempo #noodwet #sneltest #lockdown2021 #538koningsdag #ZeroCovidDayofAction #notulendebat #Baudet #volksgezondheid #ikwildieprik #kaag #DEBAT #Gommers #spoedwet #studiovoetbal #Covidioten\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0af18a90ed1d56c04d8f157dce40d407e8607dd | 25,478 | ipynb | Jupyter Notebook | Lecture 11, Methods for multiobjective optimization.ipynb | bshavazipour/TIES483-2022 | 93dfabbfe1e953e5c5f83c44412963505ecf575a | [
"MIT"
] | null | null | null | Lecture 11, Methods for multiobjective optimization.ipynb | bshavazipour/TIES483-2022 | 93dfabbfe1e953e5c5f83c44412963505ecf575a | [
"MIT"
] | null | null | null | Lecture 11, Methods for multiobjective optimization.ipynb | bshavazipour/TIES483-2022 | 93dfabbfe1e953e5c5f83c44412963505ecf575a | [
"MIT"
] | 1 | 2022-02-03T09:40:02.000Z | 2022-02-03T09:40:02.000Z | 28.626966 | 437 | 0.544901 | [
[
[
"from IPython.core.display import HTML\nHTML(\"<style>.container { width:95% !important; }</style>\")",
"_____no_output_____"
]
],
[
[
"# Lecture 11, Solution methods for multiobjective optimization ",
"_____no_output_____"
],
[
"## Reminder:",
"_____no_output_____"
],
[
"### Mathematical formulation of multiobjective optimization problems\n\nMultiobjective optimization problems are often formulated as\n$$\n\\begin{align} \\\n\\min \\quad &\\{f_1(x),\\ldots,f_k(x)\\}\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_q(x) = 0\\text{ for all }q=1,\\ldots,Q\\\\\n&a_i\\leq x_i\\leq b_i\\text{ for all } i=1,\\ldots,n\\\\\n&x\\in \\mathbb R^n,\n\\end{align}\n$$\nwhere $$f_1,\\ldots,f_k:\\{x\\in\\mathbb R^n: g_j(x) \\geq 0 \\text{ for all }j=1,\\ldots,J \\text{ and } h_q(x) = 0\\text{ for all }q=1,\\ldots,Q\\}\\mapsto\\mathbb R$$ are the objective functions.",
"_____no_output_____"
],
[
"## Pareto optimality\nA feasible solution $x_1$ is Pareto optimal to the multiobjective optimization problem, if there does not exist a feasible solution $x_2$, $x_1\\neq x_2$, such that \n$$\n\\left\\{\n\\begin{align}\n&f_i(x_2)\\leq f_i(x_1)\\text{ for all }i\\in \\{1,\\ldots,k\\}\\\\\n&f_j(x_2)<f_j(x_1)\\text{ for some }j\\in \\{1,\\ldots,k\\}.\\\\\n\\end{align}\n\\right.\n$$",
"_____no_output_____"
],
[
"### Basic concepts",
"_____no_output_____"
],
[
"* There is no single optimal solution, instead we have a set of solutions called pareto optimal set.\n* All the objectives don’t have the same optimal solution → optimality needs to be modified ",
"_____no_output_____"
],
[
"### PARETO OPTIMALITY (PO)\n* A solution is pareto optimal if none of the objectives can be improved without impairing at least one of the others\n\nIt means: \n$$\n\\text{“Take from Sami to pay Anna”}\n$$\n\n* Optimal solutions are located at the boundary to the down & left (for minimization problems)*\n",
"_____no_output_____"
],
[
"* There are to spaces connected to the problem: the space $\\mathbb R^n$ is called the decision space and $\\mathbb R^k$ is called the objective space. \n\n1. **Decision space**: includes the **Pareto optimal solution set**\n2. **Objective space**: consists of the image of Pareto optimal solutions (**Pareto frontier**) \n\n\n\n",
"_____no_output_____"
],
[
"## Some more concepts:",
"_____no_output_____"
],
[
"In addition to Pareto optimality, two more concepts are important, which are called the ideal and the nadir vector. \n\n* **Ideal objective vector $𝒛^∗$:** best values for each objective (when optimized independently)\n* **Nadir objective vector $𝒛^𝑛𝑎𝑑$:** worst values for each objective in PO set \n\n",
"_____no_output_____"
],
[
"Mathematically the ideal vector $z^{ideal}$ can be defined as having \n$$\nz^{ideal}_i = \\begin{align} \\\n\\min \\quad &f_i(x)\\\\\n\\text{s.t.} \\quad &x\\text{ is feasible}\n\\end{align}\n$$\nfor all $i=1,\\ldots,k$ (i.e., by **solving single-objective optimization problems, one for each objective**). \n\nThe nadir vector $z^{nadir}$ on the other hand has\n$$\nz^{nadir}_i = \n\\begin{align}\n\\max \\quad &f_i(x)\\\\\n\\text{s.t.} \\quad &x\\text{ is Pareto optimal},\n\\end{align}\n$$\nfor all $i=1,\\ldots,k$ (**not as straightforward as calculating the ideal points for more than two objectives**).",
"_____no_output_____"
],
[
"## Optimization problem formulation\n* By optimizing only one criterion, the rest are not considered\n* Objective vs. constraint\n* Summation of the objectives\n * adding apples and oranges\n* Converting the objectives (e.g. as costs)\n * not easy, includes uncertainteis\n* Multiobjective formulation reveals interdependences between the objectives",
"_____no_output_____"
],
[
"## Example\n\nConsider multiobjective optimization problem\n$$\n\\min \\{f_1(x,y)=x^2+y,\\quad f_2(x,y)=1-x\\}\\\\\n\\text{s.t. }x\\in[0,1], y\\geq0.\n$$",
"_____no_output_____"
],
[
"#### Pareto optimal solutions\nNow, the set of Pareto optimal solutions is\n\n$$\n\\{(x,0):x\\in[0,1]\\}.\n$$\n\nHow to show this?",
"_____no_output_____"
],
[
"Let's show that $(x',0)$ is Pareto optimal for all $x'\\in[0,1]$. *The idea of the proof: assume that $(x',0)$ is not Pareto optimal and then deduce a contradiction.*\n\nLet's assume $(x,y)$ with $x\\in[0,1]$ and $y\\geq0$ such that\n\n$$\n\\left\\{\n\\begin{align}\nf_1(x,y)=x^2+y\\leq x'^2=f_1(x',0),\\textbf{ and}\\\\\nf_2(x,y)=1-x\\leq 1-x'=f_2(x',0).\n\\end{align}\n\\right.\n$$\n\nand\n\n$$\n\\left\\{\n\\begin{align}\nf_1(x,y)=x^2+y< x'^2 =f_1(x',0)\\textbf{ or}\\\\\nf_2(x,y)=1-x< 1-x'=f_2(x',0).\n\\end{align}\n\\right.\n$$\n\nSecond inequality in the first system of inequalities gives $x\\geq x'$. This yields from the first inequality in that same system of inequalities\n\n$$\ny\\leq x'^2-x^2\\leq 0.\n$$\n\nThus, $y=0$. This means that $x=x'$ using again the first inequality.\n\nThis means that the solution cannot satisfy the second system of strict inequalities. We have a contradiction and, therefore, $(x',0)$ has to be Pareto optimal.",
"_____no_output_____"
],
[
"Now, we show that any other feasible solution can not be Pareto optimal. Let's assume a solution $(x,y)$, where $x\\in[0,1]$ and $y>0$ and show that this is not Pareto optimal:\n\nBy choosing solution $(x,0)$, we have \n\n$$\n\\left\\{\n\\begin{align}\nf_1(x,0)=x^2<x^2+y=f_1(x,y) ,\\text{ and}\\\\\nf_2(x,0)=1-x\\leq 1-x=f_2(x,y).\n\\end{align}\n\\right.\n$$\n\nThus, the solution $(x,y)$ cannot be Pareto optimal.",
"_____no_output_____"
],
[
"#### Ideal\nNow\n\n$$\n\\begin{align}\n\\min x^2+y\\\\\n\\text{s.t. }x\\in[0,1],\\ y\\geq0\n\\end{align}\n= 0\n$$\n\nand\n\n$$\n\\begin{align}\n\\min 1-x\\\\\n\\text{s.t. }x\\in[0,1],\\ y\\geq0\n\\end{align}\n= 0.\n$$\n\nThus, the ideal is\n\n$$\nz^{ideal} = (0,0)^T\n$$",
"_____no_output_____"
],
[
"#### Nadir\nNow,\n\n$$\n\\begin{align}\n\\max x^2+y\\\\\n\\text{s.t. }x\\in[0,1],\\ y=0\n\\end{align}\n= 1\n$$\n\nand\n\n$$\n\\begin{align}\n\\max 1-x\\\\\n\\text{s.t. }x\\in[0,1],\\ y=0\n\\end{align}\n= 1.\n$$\n\nThus, \n\n$$\nz^{nadir}=(1,1)^T.\n$$",
"_____no_output_____"
],
[
"# What means solving a multiobjective optimization problem?\n\n* **Find all Pareto optimal solutions**\n * As we learned in the previous lecture, there can be infinitely many Pareto optimal solutions for problems having real valued variables $\\rightarrow$ extremely difficult and possible only in some simple special cases",
"_____no_output_____"
],
[
"* **Find a set of solutions that approximate the set of all Pareto optimal solutions**\n * How to evaluate the goodness of the approximation? (closeness, spread, ...)\n * The number of solutions required for a good approximation grows exponentially with the number of objectives!\n * Works well with two objectives and, in some cases, for three objectives",
"_____no_output_____"
],
[
"* **Find a solution/solutions that best satisfies the preferences of a decision maker**\n * Usually in practical problems one solution has to be finally selected for further analysis\n * Sometimes, more than one (but not that many) are needed $\\rightarrow$ e.g. choose best design for different types of cars to be manufactured (small and economic sedan, spacious vagon, efficient sports model, etc.)\n * does not depend on the number of objectives",
"_____no_output_____"
],
[
"If you want to know more about the topic of this lecture, I urge you to read Professor Miettinen's book Nonlinear Multiobjective Optimization\n\n",
"_____no_output_____"
],
[
"## Scalarization\n* One way to consider a multiobjective optimization problem is to convert it to a single objective subproblem whose solution is Pareto optimal for the original problem\n* The subproblem is called a *scalarization* and it can be solved by using a suitable single objective optimization method\n* By changing the values of the parameters in the scalarization, different (Pareto optimal) solutions can be computed",
"_____no_output_____"
],
[
"## Classification of methods",
"_____no_output_____"
],
[
"Methods for multiobjective optimization are often characterized by the involvement of the decision maker in the process.",
"_____no_output_____"
],
[
"The types of methods are\n* **no preference methods**, where the decision maker does not play a role,\n* **a priori methods**, where the decision maker gives his/her preference information at first and then the optimization method finds the best match to that preference information,\n* **a posteriori methods**, where the optimization methods try to characterize all/find a good representation of the Pareto optimal solutions and the decision maker chooses the most preferred one of those,\n* **interactive methods**, where the optimization method and the decision maker alternate in iterative search for the most preferred solution.",
"_____no_output_____"
],
[
"## Multiple Criteria Decision Making (MCDM)\n* The related research field is called multiple criteria decision making\n* More information in the website of the <a href=\"http://www.mcdmsociety.org/\">International Society on MCDM</a>",
"_____no_output_____"
],
[
"## Our example problem for this lecture\n\nWe study a hypothetical decision problem of buying a car, when you can choose to have a car with power between (denoted by $p$) 50 and 200 kW and average consumption (denoted by $c$) per 100 km between 3 and 10 l. However, in addition to the average consumption and power, you need to decide the volume of the cylinders (v), which may be between 1000 $cm^3$ and 4000 $cm^3$. Finally, the price of the car follows now a function \n\n$$\n\\left(\\sqrt{\\frac{p-50}{50}}\\\\\n+\\left(\\frac{p-50}{50}\\right)^2+0.3(10-c)\\\\ +10^{-5}\\left(v-\\left(1000+3000\\frac{p-50}{150}\\right)\\right)^2\\right)10000\\\\+5000\n$$\n\nin euros. This problem can be formulated as a multiobjective optimization problem\n\n$$\n\\begin{align}\n\\min \\quad & \\{c,-p,P\\},\\\\\n\\text{s.t. }\\quad\n&50\\leq p\\leq 200\\\\\n&3\\leq c\\leq 10\\\\\n&1000\\leq v\\leq 4000,\\\\\n\\text{where }\\quad&P = \\left(\\sqrt{\\frac{p-50}{50}}+\\left(\\frac{p-50}{50}\\right)^2+0.3(10-c)\\right.\\\\\n& \\left.+ 10^{-5}\\left(v-\\left(1000+3000\\frac{p-50}{150}\\right)\\right)^2\\right)10000+5000\n\\end{align}\n$$",
"_____no_output_____"
]
],
[
[
"#Let us define a Python function which returns the value of this\nimport math\ndef car_problem(c,p,v):\n# import pdb; pdb.set_trace()\n return [#Objective function values\n c,-p,\n (math.sqrt((p-50.)/50.)+((p-50.)/50.)**2+\n 0.3*(10.-c)+0.00001*(v-(1000.+3000.*(p-50.)/150.))**2)*10000.\n +5000.] ",
"_____no_output_____"
],
[
"print(\"Car with 3 l/100km consumption, 50kW and 1000cm^3 engine would cost \"\n +str(car_problem(3,50,1000)[2])+\"€\")\nprint(\"Car with 3 l/100km consumption, 100kW and 2000cm^3 engine would cost \"\n +str(car_problem(3,100,2000)[2])+\"€\")\nprint(\"Car with 3 l/100km consumption, 100kW and 1000cm^3 engine would cost \"\n +str(car_problem(3,100,1000)[2])+\"€\")",
"Car with 3 l/100km consumption, 50kW and 1000cm^3 engine would cost 26000.0€\nCar with 3 l/100km consumption, 100kW and 2000cm^3 engine would cost 46000.0€\nCar with 3 l/100km consumption, 100kW and 1000cm^3 engine would cost 146000.0€\n"
]
],
[
[
"## Normalization of the objectives",
"_____no_output_____"
],
[
"**In many of the methods, the normalization of the objectives is necessary.**\n\nWe can normalize the objectives using the nadir and ideal and setting the normalized objective as\n$$ \\tilde f_i = \\frac{f_i-z_i^{ideal}}{z_i^{nadir}-z_i^{ideal}}$$",
"_____no_output_____"
],
[
"## Calculating the ideal",
"_____no_output_____"
],
[
"**Finding the ideal for problems is usually easy, if you can optimize the objective functions separately.**\n\nFor the car problem, ideal can be computed easily using the script:",
"_____no_output_____"
]
],
[
[
"#Calculating the ideal\nfrom scipy.optimize import minimize\nimport ad\ndef calc_ideal(f):\n ideal = [0]*3 #Because three objectives\n solutions = [] #list for storing the actual solutions, which give the ideal\n bounds = ((3,10),(50,200),(1000,4000)) #Bounds of the problem\n starting_point = [3,50,1000]\n for i in range(3):\n res=minimize(\n #Minimize each objective at the time\n lambda x: f(x[0],x[1],x[2])[i], starting_point, method='SLSQP'\n #Jacobian using automatic differentiation (note: SLSQP can estimate gradiants itself with some extra function evaluations)\n #,jac=ad.gh(lambda x: f(x[0],x[1],x[2])[i])[0]\n #bounds given above\n ,bounds = bounds\n ,options = {'disp':True, 'ftol': 1e-20, 'maxiter': 1000})\n solutions.append(f(res.x[0],res.x[1],res.x[2]))\n ideal[i]=res.fun\n return ideal,solutions",
"_____no_output_____"
],
[
"ideal, solutions= calc_ideal(car_problem)\nprint (\"ideal is \"+str(ideal))",
"Optimization terminated successfully (Exit mode 0)\n Current function value: 3.0\n Iterations: 1\n Function evaluations: 4\n Gradient evaluations: 1\nOptimization terminated successfully (Exit mode 0)\n Current function value: -200.0\n Iterations: 5\n Function evaluations: 20\n Gradient evaluations: 5\nOptimization terminated successfully (Exit mode 0)\n Current function value: 5000.0\n Iterations: 6\n Function evaluations: 8\n Gradient evaluations: 2\nideal is [3.0, -200.0, 5000.0]\n"
]
],
[
[
"## Pay-off table method\n\n**Finding the nadir value is however, usually much harder.**\n\nUsually, the nadir value is estimated using the so-called pay-off table method.\n\nThe pay-off table method does not guarantee to find the exact nadir for problems with more than two objectives. <!--(One of your exercises this week will be to show this.)--> \n\nThe method is, however, a generally accepted way of approximating the nadir vector.\n\nIn the pay-off table method:\n1. the objective values for attaining the individual minima are added in table\n2. the nadir is estimated by each objectives maxima in the table.\n3. the ideal values are located in the diagonal of the pay-off table",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"### $x^{(*,i)} =$ optimal solution for $f_i$ ",
"_____no_output_____"
],
[
"### The nadir for the car selection problem\nThe table now becomes by using the *solutions* that we returned while calculating the ideal",
"_____no_output_____"
]
],
[
[
"for solution in solutions:\n print(solution) ",
"[3.0, -50.0, 26000.0]\n[3.0, -200.0, 1033320.5080756888]\n[10.0, -50.0, 5000.0]\n"
]
],
[
[
"Thus, the esimation of the nadir vector is \n$$(10,-50,1033320.5080756888)$$\n\nThis is actually the real Nadir vector for this problem.",
"_____no_output_____"
],
[
"### Normalized car problem",
"_____no_output_____"
]
],
[
[
"#Let us define a Python function which returns the value of this\nimport math\ndef car_problem_normalized(c,p,v):\n z_ideal = [3.0, -200.0, 5000]\n z_nadir = [10,-50,1033320.5080756888]\n z = car_problem(c,p,v) \n return [(zi-zideali)/(znadiri-zideali) for \n (zi,zideali,znadiri) in zip(z,z_ideal,z_nadir)]",
"_____no_output_____"
]
],
[
[
"<a href=\"https://docs.python.org/3.3/library/functions.html#zip\">the zip function</a> in Python",
"_____no_output_____"
]
],
[
[
"print(\"Normalized value of the car problem at (3,50,1000) is \"\n +str(car_problem_normalized(3,50,1000)))\nprint(\"Normalized value of the car problem at (3,125,2500) is \"\n +str(car_problem_normalized(3,125,2500)))\nprint(\"Normalized value of the car problem at (10,100,1000) is \"\n +str(car_problem_normalized(10,100,1000)))",
"Normalized value of the car problem at (3,50,1000) is [0.0, 1.0, 0.020421648537670038]\nNormalized value of the car problem at (3,125,2500) is [0.0, 0.5, 0.054212133547970276]\nNormalized value of the car problem at (10,100,1000) is [1.0, 0.6666666666666666, 0.11669513450097163]\n"
]
],
[
[
"**So, value 1 now indicates the worst value on the Pareto frontier and value 0 indicates the best values**",
"_____no_output_____"
],
[
"Let's set the ideal and nadir for later reference:",
"_____no_output_____"
]
],
[
[
"z_ideal = [3.0, -200.0, 5000]\nz_nadir = [10.,-50,1033320.5080756888]",
"_____no_output_____"
]
],
[
[
"**From now on, we will deal with the normalized problem, although, we write just $f$.** The aim of this is to simplify presentation.",
"_____no_output_____"
]
]
] | [
"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",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
d0af1abef17034f3fe90d013f8e1f53dae543007 | 54,216 | ipynb | Jupyter Notebook | notebooks/kde on triptime.ipynb | desultir/nyctaxi | 07ddab136df88341f8c9e06d9956257b35982e68 | [
"MIT"
] | null | null | null | notebooks/kde on triptime.ipynb | desultir/nyctaxi | 07ddab136df88341f8c9e06d9956257b35982e68 | [
"MIT"
] | null | null | null | notebooks/kde on triptime.ipynb | desultir/nyctaxi | 07ddab136df88341f8c9e06d9956257b35982e68 | [
"MIT"
] | null | null | null | 234.701299 | 37,268 | 0.92303 | [
[
[
"import pandas as pd\nimport os, sys\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nimport shapefile\nfrom functools import partial\nimport pyproj\nfrom shapely.geometry import shape, Point, mapping\nfrom shapely.ops import transform\nprocesseddir = \"../data/processed/\"\nrawdir = \"../data/raw/\"\ndf = pd.read_csv(os.path.join(processeddir,\"nyctaxiclean.csv\"), dtype={\"store_and_fwd_flag\": \"object\"})",
"_____no_output_____"
],
[
"df[\"pickup_float\"] = pd.to_datetime(df[\"pickup_datetime\"]).apply(lambda x: x.timestamp())\ndf[\"pickup_datetime\"] = pd.to_datetime(df[\"pickup_datetime\"])\ndf[\"dropoff_datetime\"] = pd.to_datetime(df[\"dropoff_datetime\"])\ndf[\"pickup_datetime\"] = pd.to_datetime(df[\"pickup_datetime\"])\ndf[\"dropoff_datetime\"] = pd.to_datetime(df[\"dropoff_datetime\"])",
"_____no_output_____"
],
[
"df[\"trip_time_in_secs\"].describe()",
"_____no_output_____"
],
[
"df[\"pickup_hour\"] = df[\"pickup_datetime\"].apply(lambda x: x.hour)\ndf[\"pickup_dayofweek\"] = df[\"pickup_datetime\"].apply(lambda x: x.weekday())\ndf[\"pickup_dayofmonth\"] = df[\"pickup_datetime\"].apply(lambda x: x.day)\n",
"_____no_output_____"
],
[
"from statsmodels.nonparametric.kernel_density import KDEMultivariate\nfrom sklearn.model_selection import KFold\n# 4 POC neighbourhoods\nchosen_neighbourhoods = [\"Upper East Side South\", \"Midtown Center\", \"Flatiron\", \"JFK Airport\"]\nfiltered_df = df[df[\"pickup_neighbourhood\"].isin(chosen_neighbourhoods)]\n# as this dataset is not aggregated we can use random 4-fold CV\nkf = KFold(n_splits=4, shuffle=True)\n\nkde_models = []\nx_models = []\nlikelihood = []\n\nfiltered_df = filtered_df[[\"pickup_hour\", \"pickup_dayofweek\", \"trip_time_in_secs\"]]\nx_df = filtered_df[[\"pickup_hour\", \"pickup_dayofweek\"]]\n\nfor train_index, test_index in list(kf.split(filtered_df))[:2]:\n train_df = filtered_df.iloc[train_index]\n test_df = filtered_df.iloc[test_index][:100]\n kde_models.append(KDEMultivariate(train_df, var_type='ooc'))\n x_models.append(KDEMultivariate(x_df, var_type='oo'))\n \n likelihood.append(np.exp(kde_models[-1].pdf(test_df))/np.exp(x_models[-1].pdf(test_df[[\"pickup_hour\", \"pickup_dayofweek\"]])))",
"_____no_output_____"
],
[
"%matplotlib inline\nimport numpy as np\nfrom matplotlib import pyplot as plt\nplt.plot(likelihood[0])\nplt.title(\"Likelihood for trip time KDE\")\nplt.ylabel(\"Likelihood\")\nplt.xlabel(\"Test index\")\n\n#likelihood is sufficiently high for held out test set - 99-100%",
"_____no_output_____"
],
[
"#now assess some predictions\nimport numpy as np\ntriptime = np.linspace(0,960,25) #test up to 3rd percentile; no point assesing the long tail as\n #we're looking for short trips here\n\nx_data = [[4, x] for x in range(24)]\nyx_data = np.asarray([[x+[y] for x in x_data] for y in triptime])\nx_data = np.asarray(x_data)\nkde_time = kde_models[-1]\nx_model = x_models[-1]\n\nprobs = []\nfor i in range(len(yx_data)):\n probs.append(np.exp(kde_time.cdf(yx_data[i])))",
"_____no_output_____"
],
[
"plt.plot(probs[18])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
d0af1f162a412b3097be3cb4692f653d0d465af9 | 9,644 | ipynb | Jupyter Notebook | _notebooks/draft/Graph.ipynb | phucnsp/blog | 343e5987628276ff2c74e4e3ebdcb5a4a1baa1df | [
"Apache-2.0"
] | 2 | 2021-06-06T07:17:53.000Z | 2022-01-18T17:12:17.000Z | _notebooks/draft/Graph.ipynb | phucnsp/blog | 343e5987628276ff2c74e4e3ebdcb5a4a1baa1df | [
"Apache-2.0"
] | 7 | 2020-03-08T02:50:29.000Z | 2022-02-26T06:55:02.000Z | _notebooks/draft/Graph.ipynb | phucnsp/blog | 343e5987628276ff2c74e4e3ebdcb5a4a1baa1df | [
"Apache-2.0"
] | 2 | 2021-08-30T07:19:54.000Z | 2022-01-18T17:12:26.000Z | 34.815884 | 423 | 0.640813 | [
[
[
"# Graph\n> in progress\n- toc: true \n- badges: true\n- comments: true\n- categories: [self-taught]\n- image: images/bone.jpeg\n- hide: true",
"_____no_output_____"
],
[
"https://towardsdatascience.com/using-graph-convolutional-neural-networks-on-structured-documents-for-information-extraction-c1088dcd2b8f\n\nCNNs effectively capture patterns in data in Euclidean space\n\ndata is represented in the form of a Graph and lack a grid-like regularity. \nAs Graphs can be irregular, they may have a variable size of un-ordered nodes and each node may have a different number of neighbors, resulting in mathematical operations such as convolutions difficult to apply to the Graph domain.\n\nSome examples of such non-Euclidean data include:\n- Protein-Protein Interaction Data where interactions between molecules are modeled as graphs\n- Citation Networks where scientific papers are nodes and citations are uni- or bi-directional edges\n- Social Networks where people on the network are nodes and their relationships are edges\n\nThis article particularly discusses the use of Graph Convolutional Neural Networks (GCNs) on structured documents such as Invoices and Bills to automate the extraction of meaningful information by learning positional relationships between text entities.\n\nWhat is a Graph?\n\n\n\n**How to convert Structured Documents to Graphs?**\nSuch recurring structural information along with text attributes can help a Graph Neural Network learn neighborhood representations and perform node classification as a result\n\n\nGeometric Algorithm: Connecting objects based on visibility\n\n\n**Convolution on Document Graphs for Information Extraction**\n\n",
"_____no_output_____"
],
[
"# References",
"_____no_output_____"
],
[
"https://towardsdatascience.com/overview-of-deep-learning-on-graph-embeddings-4305c10ad4a4\n\nGraph embedding",
"_____no_output_____"
],
[
"https://towardsdatascience.com/graph-convolutional-networks-for-geometric-deep-learning-1faf17dee008m\n\nGraph Conv",
"_____no_output_____"
],
[
"https://arxiv.org/pdf/1611.08097.pdf \nhttps://arxiv.org/pdf/1901.00596.pdf",
"_____no_output_____"
],
[
"https://towardsdatascience.com/graph-theory-and-deep-learning-know-hows-6556b0e9891b\n\n**Everything you need to know about Graph Theory for Deep Learning**\n\nGraph Theory — crash course\n\n1. What is a graph?\n\nA graph, in the context of graph theory, is a structured datatype that has nodes (entities that hold information) and edges (connections between nodes that can also hold information). A graph is a way of structuring data, but can be a datapoint itself. Graphs are a type of Non-Euclidean data, which means they exist in 3D, unlike other datatypes like images, text, and audio.\n\n\n- Graphs can have labels on their edges and/or nodes\n- Labels can also be considered weights, but that’s up to the graph’s designer.\n- Labels don’t have to be numerical, they can be textual.\n- Labels don’t have to be unique;\n- Graphs can have features (a.k.a attributes).\n\nTake care not to mix up features and labels. \n> Note: a node is a person, a node’s label is a person’s name, and the node’s features are the person’s characteristics.\n\n- Graphs can be directed or undirected\n- A node in the graph can even have an edge that points/connects to itself. This is known as a self-loop.\n\nGraphs can be either:\n- Heterogeneous — composed of different types of nodes\n- Homogeneous — composed of the same type of nodes\n\nand are either:\n- Static — nodes and edges do not change, nothing is added or taken away\n- Dynamic — nodes and edges change, added, deleted, moved, etc.\n\ngraphs can be vaguely described as either\n- Dense — composed of many nodes and edges\n- Sparse — composed of fewer nodes and edges\n\nGraphs can be made to look neater by turning them into their planar form, which basically means rearranging nodes such that edges don’t intersect\n\n2. Graph Analysis\n3. E-graphs — graphs on computers\n\n\n\n",
"_____no_output_____"
],
[
"https://medium.com/@flawnsontong1/what-is-geometric-deep-learning-b2adb662d91d\n\n**What is Geometric Deep Learning?**\n\nThe vast majority of deep learning is performed on Euclidean data. This includes datatypes in the 1-dimensional and 2-dimensional domain. \nImages, text, audio, and many others are all euclidean data.\n\n`Non-euclidean data` can represent more complex items and concepts with more accuracy than 1D or 2D representation:\n\nWhen we represent things in a non-euclidean way, we are giving it an inductive bias. \nAn inductive bias allows a learning algorithm to prioritize one solution (or interpretation) over another, independent of the observed data. Inductive biases can express assumptions about either the data-generating process or the space of solutions.\nIn the majority of current research pursuits and literature, the inductive bias that is used is relational.\n\nBuilding on this intuition, `Geometric Deep Learning (GDL)` is the niche field under the umbrella of deep learning that aims to build neural networks that can learn from non-euclidean data.\n\nThe prime example of a non-euclidean datatype is a graph. `Graphs` are a type of data structure that consists of `nodes` (entities) that are connected with `edges` (relationships). This abstract data structure can be used to model almost anything.\n\n\nWe want to be able to learn from graphs because:\n\n`\nGraphs allow us to represent individual features, while also providing information regarding relationships and structure.\n`\n`Graph theory` is the study of graphs and what we can learn from them. There are various types of graphs, each with a set of rules, properties, and possible actions. \n\nExamples of Geometric Deep Learning\n- Molecular Modeling and learning: \nOne of the bottlenecks in computational chemistry, biology, and physics is the representation concepts, entities, and interactions. Our current methods of representing these concepts computationally can be considered “lossy”, since we lose a lot of valuable information. By treating atoms as nodes, and bonds as edges, we can save structural information that can be used downstream in prediction or classification.\n\n- 3D Modeling and Learning\n\n",
"_____no_output_____"
],
[
"5 types of bias\nhttps://twitter.com/math_rachel/status/1113203073051033600\nhttps://arxiv.org/pdf/1806.01261.pdf\nhttps://stackoverflow.com/questions/35655267/what-is-inductive-bias-in-machine-learning",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.