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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ece37fb07a0d4a1019478002a4518a21be7c2168 | 275,422 | ipynb | Jupyter Notebook | notebooks/01_data_analysis.ipynb | Jprebys/crypto_tracker | c365a1dc835d85d09b28d606a2fa6b751e5e4893 | [
"Apache-2.0"
] | null | null | null | notebooks/01_data_analysis.ipynb | Jprebys/crypto_tracker | c365a1dc835d85d09b28d606a2fa6b751e5e4893 | [
"Apache-2.0"
] | 1 | 2020-12-07T03:05:56.000Z | 2020-12-07T03:05:56.000Z | notebooks/01_data_analysis.ipynb | Jprebys/crypto_tracker | c365a1dc835d85d09b28d606a2fa6b751e5e4893 | [
"Apache-2.0"
] | null | null | null | 532.731141 | 259,964 | 0.933317 | [
[
[
"# Data Analysis\n\nHere I am going to try to make a pipeline for getting the price data out of the [prices.txt](../src/prices.txt) file, and working it into a usable format for visualization and analysis.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport json\nfrom dateutil.parser import parse\nimport pandas as pd",
"_____no_output_____"
],
[
"with open('../src/prices.txt', 'r') as file:\n lines = [json.loads(line) for line in file.readlines()]",
"_____no_output_____"
]
],
[
[
"This will leave me with a list of dicts, each one representing a price check on all of the coins",
"_____no_output_____"
]
],
[
[
"lines[0]",
"_____no_output_____"
],
[
"dates = [parse(date) for line in lines for date in line]\ndates",
"_____no_output_____"
],
[
"data = [list(x.values())[0] for x in lines]",
"_____no_output_____"
],
[
"df = pd.DataFrame(data, index=dates)\ndf.head()",
"_____no_output_____"
]
],
[
[
"#### That looks great\n\nNow I'll just wrap it all in a helper function and put it in a little module",
"_____no_output_____"
]
],
[
[
"def load_data():\n \"\"\"Load data from raw text files into a DataFrame\n \"\"\"\n import pandas as pd\n import json\n from dateutil.parser import parse\n \n # Load raw text\n with open('../src/prices.txt', 'r') as file:\n lines = [json.loads(line) for line in file.readlines()]\n with open('../src/decoder.txt', 'r') as file:\n decoder = json.load(file) \n \n # Hacky formatting for DataFrame\n dates = [parse(date) for line in lines for date in line]\n data = [list(x.values())[0] for x in lines]\n \n # Make Dataframe and convert coin codes to names\n result = pd.DataFrame(data=data, index=dates) \n result.columns = result.columns.map(decoder)\n \n return result",
"_____no_output_____"
]
],
[
[
"### Visualization.........\n\nVisualizing these prices will be an interesting challenge. Typically you see separate line plots for each coin, laid out in a grid. Maybe that's worth trying at first.",
"_____no_output_____"
]
],
[
[
"font = {'weight' : 'bold',\n 'size' : 12}\n\nplt.rc('font', **font)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(9, figsize=(8, 50))\n\nfor i in range(9):\n ax[i].set_xlabel('Timestamp')\n plt.xticks(rotation=20)\n ax[i].set_ylabel('Value (USD)')\n ax[i].set_title('Value of Selected Cryptocurrencies Over Time')\n ax[i].plot(df.iloc[:,i], linewidth=10);",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece3910e8984db59cd0d4c10cf39ae6e3d36aecc | 171,380 | ipynb | Jupyter Notebook | Nicolae_Dubenco_Cross_Validation,_Hyperparameter_Optimization.ipynb | NikuDubenco/DS-Unit-2-Regression-2 | 21e384f766cdc2e4221f97b1f490f9269d9b4c0e | [
"MIT"
] | null | null | null | Nicolae_Dubenco_Cross_Validation,_Hyperparameter_Optimization.ipynb | NikuDubenco/DS-Unit-2-Regression-2 | 21e384f766cdc2e4221f97b1f490f9269d9b4c0e | [
"MIT"
] | null | null | null | Nicolae_Dubenco_Cross_Validation,_Hyperparameter_Optimization.ipynb | NikuDubenco/DS-Unit-2-Regression-2 | 21e384f766cdc2e4221f97b1f490f9269d9b4c0e | [
"MIT"
] | null | null | null | 45.495089 | 17,480 | 0.37194 | [
[
[
"<a href=\"https://colab.research.google.com/github/NikuDubenco/DS-Unit-2-Regression-2/blob/master/Nicolae_Dubenco_Cross_Validation%2C_Hyperparameter_Optimization.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"from google.colab import files\nfiles.upload()",
"_____no_output_____"
],
[
"!unzip caterpillar-tube-pricing.zip",
"Archive: caterpillar-tube-pricing.zip\nreplace sample_submission.csv? [y]es, [n]o, [A]ll, [N]one, [r]ename: A\n inflating: sample_submission.csv \n inflating: data.zip \n"
],
[
"!unzip data.zip",
"Archive: data.zip\nreplace competition_data/bill_of_materials.csv? [y]es, [n]o, [A]ll, [N]one, [r]ename: A\n inflating: competition_data/bill_of_materials.csv \n inflating: competition_data/comp_adaptor.csv \n inflating: competition_data/comp_boss.csv \n inflating: competition_data/comp_elbow.csv \n inflating: competition_data/comp_float.csv \n inflating: competition_data/comp_hfl.csv \n inflating: competition_data/comp_nut.csv \n inflating: competition_data/comp_other.csv \n inflating: competition_data/comp_sleeve.csv \n inflating: competition_data/comp_straight.csv \n inflating: competition_data/comp_tee.csv \n inflating: competition_data/comp_threaded.csv \n inflating: competition_data/components.csv \n inflating: competition_data/specs.csv \n inflating: competition_data/test_set.csv \n inflating: competition_data/train_set.csv \n inflating: competition_data/tube.csv \n inflating: competition_data/tube_end_form.csv \n inflating: competition_data/type_component.csv \n inflating: competition_data/type_connection.csv \n inflating: competition_data/type_end_form.csv \n"
]
],
[
[
"### Wrangle data",
"_____no_output_____"
]
],
[
[
"import category_encoders as ce\nfrom glob import glob\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.pipeline import make_pipeline",
"_____no_output_____"
],
[
"#read data\ntrain = pd.read_csv('competition_data/train_set.csv')\ntest = pd.read_csv('competition_data/test_set.csv')\ntube = pd.read_csv('competition_data/tube.csv')\nmaterials = pd.read_csv('competition_data/bill_of_materials.csv')\ncomponents = pd.read_csv('competition_data/components.csv')\ncomp = pd.concat((pd.read_csv(path) for path in glob('competition_data/comp_*.csv')), sort=False)",
"_____no_output_____"
],
[
"comp.describe()",
"_____no_output_____"
],
[
"# get a tidy list of the component types in each tube assembly\nassembly_components = materials.melt(id_vars='tube_assembly_id',\n value_vars=[f'component_id_{n}' for n in range(1,9)])\nassembly_components = assembly_components.sort_values(\n by='tube_assembly_id').dropna().rename(columns={'value': 'component_id'})\n\nassembly_component_types = assembly_components.merge(components, how='left')",
"_____no_output_____"
],
[
"table = pd.crosstab(assembly_component_types['tube_assembly_id'],\n assembly_component_types['component_type_id'])\ntable = table.reset_index()",
"_____no_output_____"
],
[
"table",
"_____no_output_____"
],
[
"features = ['component_id', 'component_type_id', 'orientation', 'unique_feature', 'weight']\ncomp = comp[features]\ncomp['orientation'] = (comp['orientation']=='Yes').astype(int)\ncomp['unique_feature'] = (comp['unique_feature']=='Yes').astype(int)\ncomp['weight'] = comp['weight'].fillna(comp['weight'].median())",
"_____no_output_____"
],
[
"# get agg features for all components in each tube assembly\n# this code is a little complex, but we discussed in detail last lesson\n\nmaterials['components_total'] = sum(materials[f'quantity_{n}'].fillna(0) for n in range(1,9))\nmaterials['components_distinct'] = sum(materials[f'component_id_{n}'].notnull().astype(int) for n in range(1,9))\nmaterials['orientation'] = 0\nmaterials['unique_feature'] = 0\nmaterials['weight'] = 0\n\nfor n in range(1,9):\n materials = materials.merge(comp, how='left',\n left_on=f'component_id_{n}',\n right_on='component_id',\n suffixes=('', f'_{n}'))\n \nfor col in materials:\n if 'orientation' in col or 'unique_feature' in col or 'weight' in col:\n materials[col] = materials[col].fillna(0)\n \nmaterials['orientation'] = sum(materials[f'orientation_{n}'] for n in range(1,9))\nmaterials['unique_feature'] = sum(materials[f'unique_feature_{n}'] for n in range(1,9))\nmaterials['weight'] = sum(materials[f'weight_{n}'] for n in range(1,9))\n\nfeatures = ['tube_assembly_id', 'orientation', 'unique_feature', 'weight', 'components_total',\n 'components_distinct', 'component_id_1']\nmaterials = materials[features]",
"_____no_output_____"
],
[
"# extract year from quote date\ntrain['quote_date_year'] = pd.to_datetime(train['quote_date'], infer_datetime_format=True).dt.year\ntest['quote_date_year'] = pd.to_datetime(test['quote_date'], infer_datetime_format=True).dt.year",
"_____no_output_____"
],
[
"# merge data\ntrain = (train\n .merge(tube, how='left')\n .merge(materials, how='left')\n .merge(table, how='left')\n .fillna(0))\n\ntest = (test\n .merge(tube, how='left')\n .merge(materials, how='left')\n .merge(table, how='left')\n .fillna(0))\n\n# arrange X matrix and y vector.\n# drop 'tube_assembly_id' because our goal is to predict unknown assemblies,\n# and no tube assembly_id's are shared between the train and test sets\ntarget = 'cost'\nfeatures = train.columns.drop([target, 'tube_assembly_id'])\nX_train = train[features]\ny_train = train[target]\nX_test = test[features]",
"_____no_output_____"
],
[
"y_train.describe()",
"_____no_output_____"
],
[
"# log-transform the target\ny_train_log = np.log1p(y_train)\n\n# make pipeline\npipeline = make_pipeline(ce.OrdinalEncoder(),\n RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=42))",
"_____no_output_____"
]
],
[
[
"### cross_val_score",
"_____no_output_____"
]
],
[
[
"%%time\nfrom sklearn.model_selection import cross_val_score\n\nk=3\ngroups = train['tube_assembly_id']\nscores = cross_val_score(pipeline, X_train, y_train_log, cv=k,\n scoring='neg_mean_squared_error', groups=groups)\n\nprint(f'RMSLE for {k} folds:', np.sqrt(-scores))",
"RMSLE for 3 folds: [0.29148895 0.32165194 0.34699508]\nCPU times: user 2.91 s, sys: 370 ms, total: 3.29 s\nWall time: 35.6 s\n"
],
[
"print('Model Hyperparameters:')\nprint(pipeline.named_steps['randomforestregressor'])",
"Model Hyperparameters:\nRandomForestRegressor(bootstrap=True, criterion='mse', max_depth=None,\n max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=-1,\n oob_score=False, random_state=42, verbose=0,\n warm_start=False)\n"
]
],
[
[
"### validation curve",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import validation_curve\nfrom sklearn.tree import DecisionTreeRegressor\n\npipeline = make_pipeline(ce.OrdinalEncoder(), DecisionTreeRegressor())\n\ndepth = range(1, 15, 2)\n\ntrain_scores, val_scores = validation_curve(pipeline, X_train, y_train_log, \n param_name='decisiontreeregressor__max_depth',\n param_range=depth, scoring='neg_mean_squared_error',\n cv=2, groups=groups)\n\ntrain_rmsle = np.sqrt(-train_scores)\nval_rmsle = np.sqrt(-val_scores)\n\nplt.plot(depth, np.mean(train_rmsle, axis=1), color='blue', label='training error')\nplt.plot(depth, np.mean(val_rmsle, axis=1), color='r', label='validation error')\nplt.xlabel('depth')\nplt.ylabel('rmsle')\nplt.legend();",
"_____no_output_____"
],
[
"# use scikit-learn for hyperparameter optimization\nfrom scipy.stats import randint, uniform\nfrom sklearn.model_selection import RandomizedSearchCV\n\npipeline = make_pipeline(ce.OrdinalEncoder(),\n RandomForestRegressor(random_state=42))\n\nparam_distributions = {\n 'randomforestregressor__n_estimators': randint(50,500),\n 'randomforestregressor__max_features': uniform(),\n 'randomforestregressor__min_samples_leaf': [1,10,100]\n}\n\nsearch = RandomizedSearchCV(pipeline,\n param_distributions=param_distributions,\n n_iter=5,\n cv=2,\n scoring='neg_mean_squared_error',\n verbose=10,\n return_train_score=True,\n n_jobs=-1)\n\nsearch.fit(X_train, y_train_log, groups=groups)",
"Fitting 2 folds for each of 5 candidates, totalling 10 fits\n"
],
[
"print('Best hyperparameters', search.best_params_)\nprint('Cross-validation RMSLE', np.sqrt(-search.best_score_))",
"Best hyperparameters {'randomforestregressor__max_features': 0.4229655360081511, 'randomforestregressor__min_samples_leaf': 1, 'randomforestregressor__n_estimators': 143}\nCross-validation RMSLE 0.3274006006106637\n"
]
],
[
[
"### xgboost",
"_____no_output_____"
]
],
[
[
"from xgboost import XGBRegressor\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\npipeline = make_pipeline(ce.OrdinalEncoder(),\n XGBRegressor(random_state=42))\n\nparam_distributions = {\n 'xgbregressor__n_estimators': randint(500, 1000),\n 'xgbregressor__max_depth': randint(3, 7)\n}\n\nsearch = RandomizedSearchCV(pipeline,\n param_distributions=param_distributions,\n n_iter=5,\n cv=2,\n scoring='neg_mean_squared_error',\n return_train_score=True,\n n_jobs=-1)\n\nsearch.fit(X_train, y_train_log, groups=groups)",
"[00:41:53] WARNING: /workspace/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n"
],
[
"print('Best hyperparameters', search.best_params_)\nprint('Cross-validation RMSLE', np.sqrt(-search.best_score_))",
"Best hyperparameters {'xgbregressor__max_depth': 5, 'xgbregressor__n_estimators': 772}\nCross-validation RMSLE 0.31132190861521936\n"
],
[
"results_df = pd.DataFrame(search.cv_results_)\nresults_df.head()",
"_____no_output_____"
],
[
"results_df.sort_values(by='rank_test_score')",
"_____no_output_____"
]
],
[
[
"### make prediction",
"_____no_output_____"
]
],
[
[
"pipeline = search.best_estimator_\ny_pred_log = pipeline.predict(X_test)\ny_pred = np.expm1(y_pred_log) # convert from log-dollars to dollars\nsubmission = pd.read_csv('sample_submission.csv')\nsubmission['cost'] = y_pred\nsubmission.to_csv('submission.csv', index=False)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece39143c3418df16daddf096d68efabec4f5d32 | 49,426 | ipynb | Jupyter Notebook | workshops/kdd_2020/graph_regularization_pheme_natural_graph.ipynb | zoeyz101/neural-structured-learning | 06522dbb3356db5be94f94b73478c1bbc1670fe0 | [
"Apache-2.0"
] | 1 | 2021-01-13T03:41:12.000Z | 2021-01-13T03:41:12.000Z | workshops/kdd_2020/graph_regularization_pheme_natural_graph.ipynb | zoeyz101/neural-structured-learning | 06522dbb3356db5be94f94b73478c1bbc1670fe0 | [
"Apache-2.0"
] | 1 | 2021-02-24T01:03:59.000Z | 2021-02-24T01:03:59.000Z | workshops/kdd_2020/graph_regularization_pheme_natural_graph.ipynb | zoeyz101/neural-structured-learning | 06522dbb3356db5be94f94b73478c1bbc1670fe0 | [
"Apache-2.0"
] | 1 | 2020-08-03T20:51:51.000Z | 2020-08-03T20:51:51.000Z | 34.782548 | 294 | 0.508943 | [
[
[
"##### Copyright 2020 Google LLC\n\n",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Graph regularization for Twitter rumour veracity classification using natural graphs\n\n\n",
"_____no_output_____"
],
[
"## Overview\n\nThis tutorial uses the PHEME dataset for veracity classification of Twitter rumours, a binary classification task.\n\nTweet texts are used as input for computing embeddings, e.g. with ALBERT. Those representations are then used as features for the baseline MLP classification model, as well as for the graph regularized version, which uses the structure defined by the tweet replies as a natural graph.",
"_____no_output_____"
],
[
"## Install and import dependencies",
"_____no_output_____"
]
],
[
[
"!pip install --quiet neural-structured-learning\n!pip install --quiet transformers\n!pip install --quiet tokenizers",
"_____no_output_____"
],
[
"import os\nimport json\nimport random\nimport pprint\n\nimport numpy as np\n\nimport neural_structured_learning as nsl\n\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\nfrom tokenizers import BertWordPieceTokenizer\n\nfrom transformers import BertConfig\nfrom transformers import BertTokenizer, TFBertModel\nfrom transformers import XLNetTokenizer, TFXLNetModel\nfrom transformers import RobertaTokenizer, TFRobertaModel\nfrom transformers import AlbertTokenizer, TFAlbertModel\nfrom transformers import T5Tokenizer, TFT5Model\nfrom transformers import ElectraTokenizer, TFElectraModel\n\n# Resets notebook state\ntf.keras.backend.clear_session()\n\nprint(\"Version: \", tf.__version__)\nprint(\"Eager mode: \", tf.executing_eagerly())\nprint(\n \"GPU is\",\n \"available\" if tf.config.list_physical_devices(\"GPU\") else \"NOT AVAILABLE\")",
"_____no_output_____"
]
],
[
[
"## Dataset description\n\nThe PHEME dataset includes the following, which are used in this tutorial. \n\n* Twitter rumours associated with diverse news events\n* Source tweets, each of which is accompanied by reaction tweets\n* The reply structure for each source and corresponding reaction tweets\n* Veracity label annotations (by professional journalists) for each source tweet.\n\n",
"_____no_output_____"
],
[
"## Download and extract the dataset\n\n### Attribution\n\n\nWe use the [PHEME dataset for Rumour Detection and Veracity Classification](https://figshare.com/articles/dataset/PHEME_dataset_for_Rumour_Detection_and_Veracity_Classification/6392078)\ncreated by Elena Kochkina, Maria Liakata, and Arkaitz Zubiaga.\n\nThis data set is licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).\nThe underlying data is used without modifications as labels or for computing model features.",
"_____no_output_____"
]
],
[
[
"!mkdir /tmp/PHEME\n!wget --quiet -P /tmp/PHEME https://ndownloader.figshare.com/files/11767817",
"_____no_output_____"
],
[
"!ls -l /tmp/PHEME",
"_____no_output_____"
],
[
"!tar -C /tmp/PHEME -xvzf /tmp/PHEME/11767817",
"_____no_output_____"
],
[
"!ls /tmp/PHEME/all-rnr-annotated-threads/",
"_____no_output_____"
]
],
[
[
"## Convert rumor annotations to labels\n\nCode available in `convert_veracity_annotations.py` together with the [PHEME dataset](https://figshare.com/articles/PHEME_dataset_for_Rumour_Detection_and_Veracity_Classification/6392078)",
"_____no_output_____"
]
],
[
[
"\"\"\"\nPython 3 function to convert rumour annotations into True, False, Unverified\n\"\"\"\n\ndef convert_annotations(annotation, string = True):\n if 'misinformation' in annotation.keys() and 'true'in annotation.keys():\n if int(annotation['misinformation'])==0 and int(annotation['true'])==0:\n if string:\n label = \"unverified\"\n else:\n label = 2\n elif int(annotation['misinformation'])==0 and int(annotation['true'])==1 :\n if string:\n label = \"true\"\n else:\n label = 1\n elif int(annotation['misinformation'])==1 and int(annotation['true'])==0 :\n if string:\n label = \"false\"\n else:\n label = 0\n elif int(annotation['misinformation'])==1 and int(annotation['true'])==1:\n print (\"OMG! They both are 1!\")\n print(annotation['misinformation'])\n print(annotation['true'])\n label = None\n \n elif 'misinformation' in annotation.keys() and 'true' not in annotation.keys():\n # all instances have misinfo label but don't have true label\n if int(annotation['misinformation'])==0:\n if string:\n label = \"unverified\"\n else:\n label = 2\n elif int(annotation['misinformation'])==1:\n if string:\n label = \"false\"\n else:\n label = 0\n \n elif 'true' in annotation.keys() and 'misinformation' not in annotation.keys():\n print ('Has true not misinformation')\n label = None\n else:\n print('No annotations')\n label = None\n \n return label",
"_____no_output_____"
]
],
[
[
"## Load annotated rumours from dataset",
"_____no_output_____"
]
],
[
[
"def load_pheme_data(parent_dir):\n \"\"\" Loads and returns tweets and their replies from input `parent_dir`.\n \n Args:\n parent_dir: A string with full path to directory where the data lies in.\n\n Returns:\n A tuple T (annotation, structure, source_tweets, reactions) such that:\n Each of them is a dictionary directly read from the underlying JSON\n structure provided in the PHEME dataset.\n \"\"\"\n with open(parent_dir + '/annotation.json') as f:\n annotation = json.load(f)\n with open(parent_dir + '/structure.json') as f:\n structure = json.load(f)\n source_tweets = {}\n for f in os.scandir(parent_dir + '/source-tweets'):\n if f.name[0] != '.':\n with open(f.path) as json_file:\n source_tweets[f.name.split('.json')[0]] = json.load(json_file)\n reactions = {}\n for f in os.scandir(parent_dir + '/reactions'):\n if f.name[0] != '.':\n with open(f.path) as json_file:\n reactions[f.name.split('.json')[0]] = json.load(json_file)\n return annotation, structure, source_tweets, reactions",
"_____no_output_____"
],
[
"def load_labels_and_texts(topics):\n \"\"\"Reads verified rumour tweets, replies and labels for input `topics`.\n Non-rumours or unverified tweet threads aren't included in returned dataset.\n\n Args:\n topics: A List of strings, each containing the full path to a topic\n to be read.\n\n Returns:\n A List of dictionaries such that each entry E contains:\n E['label']: (integer) the rumour veracity annotation.\n E['source_text']: (string) the source tweet text.\n E['reactions']: (List of strings) the texts from the tweet replies.\n \"\"\"\n labels_and_texts = []\n for t in topics:\n rumours = [\n f.path for f in os.scandir(t + '/rumours') if f.is_dir()\n ]\n for r in rumours:\n annotation, structure, source_tweets, reactions = load_pheme_data(r)\n for source_tweet in source_tweets.values():\n labels_and_texts.append({\n 'label' : convert_annotations(annotation, string = False),\n 'source_text' : source_tweet['text'],\n 'reactions' : [reaction['text'] for reaction in reactions.values()]\n })\n\n print('Read', len(labels_and_texts), 'annotated rumour tweet threads')\n\n verified_labels_and_texts = list(\n filter(lambda d : d['label'] != 2, labels_and_texts))\n\n print('Returning', len(verified_labels_and_texts),\n 'verified rumour tweet threads')\n \n return verified_labels_and_texts",
"_____no_output_____"
],
[
"topics = [\n f.path\n for f in os.scandir('/tmp/PHEME/all-rnr-annotated-threads/')\n if f.is_dir()\n]\ntopics",
"_____no_output_____"
]
],
[
[
"## Load tokenizers, model architectures and pre-trained weights",
"_____no_output_____"
]
],
[
[
"configuration = BertConfig()\n\n\"\"\"\nUncomment any tokenizer-model pair for experimentation with other models.\n\"\"\"\n\nTOKENIZERS = {\n # 'bert_base' : BertTokenizer.from_pretrained('bert-base-uncased'),\n # 'bert_large' : BertTokenizer.from_pretrained('bert-large-uncased'),\n # 'xlnet_base' : XLNetTokenizer.from_pretrained('xlnet-base-cased'),\n # 'xlnet_large' : XLNetTokenizer.from_pretrained('xlnet-large-cased'),\n # 'roberta_base' : RobertaTokenizer.from_pretrained('roberta-base'),\n # 'roberta_large' : RobertaTokenizer.from_pretrained('roberta-large'),\n 'albert_base' : AlbertTokenizer.from_pretrained('albert-base-v2'),\n # 'albert_large' : AlbertTokenizer.from_pretrained('albert-large-v2'),\n # 'albert_xlarge' : AlbertTokenizer.from_pretrained('albert-xlarge-v2'),\n # 'albert_xxlarge' : AlbertTokenizer.from_pretrained('albert-xxlarge-v2'),\n # 't5_small' : T5Tokenizer.from_pretrained('t5-small'),\n # 't5_base' : T5Tokenizer.from_pretrained('t5-base'),\n # 't5_large' : T5Tokenizer.from_pretrained('t5-large'),\n # 'electra_small' : ElectraTokenizer.from_pretrained('google/electra-small-discriminator'),\n # 'electra_large' : ElectraTokenizer.from_pretrained('google/electra-large-discriminator'),\n}\n\nPRETRAINED_MODELS = {\n # 'bert_base' : TFBertModel.from_pretrained('bert-base-uncased'),\n # 'bert_large' : TFBertModel.from_pretrained('bert-large-uncased'),\n # 'xlnet_base' : TFXLNetModel.from_pretrained('xlnet-base-cased'),\n # 'xlnet_large' : TFXLNetModel.from_pretrained('xlnet-large-cased'),\n # 'roberta_base' : TFRobertaModel.from_pretrained('roberta-base'),\n # 'roberta_large' : TFRobertaModel.from_pretrained('roberta-large'),\n 'albert_base' : TFAlbertModel.from_pretrained('albert-base-v2'),\n # 'albert_large' : TFAlbertModel.from_pretrained('albert-large-v2'),\n # 'albert_xlarge' : TFAlbertModel.from_pretrained('albert-xlarge-v2'),\n # 'albert_xxlarge' : TFAlbertModel.from_pretrained('albert-xxlarge-v2'),\n # 't5_small' : TFT5Model.from_pretrained('t5-small'),\n # 't5_base' : TFT5Model.from_pretrained('t5-base'),\n # 't5_large' : TFT5Model.from_pretrained('t5-large'),\n # 'electra_small' : TFElectraForPreTraining.from_pretrained('google/electra-small-discriminator'),\n # 'electra_large' : TFElectraForPreTraining.from_pretrained('google/electra-large-discriminator')\n}\n",
"_____no_output_____"
]
],
[
[
"## Tokenization and model inference functions",
"_____no_output_____"
]
],
[
[
"# Given that tweets are short, use a small value for reduced inference time\nTOKENIZER_MAX_SEQ_LENGTH = 64 \n \n\ndef bert_embedding_model_inference(model, tokenizer, text):\n \"\"\" Tokenizes and computes BERT `model` inference for input `text`. \"\"\"\n input_ids = tf.constant(\n tokenizer.encode(text, add_special_tokens=True))[None, :] # Batch size 1\n outputs = model(input_ids)\n # The last hidden-state is the first element of the output tuple \n last_hidden_states = outputs[0]\n cls_embedding = last_hidden_states[0][0]\n return cls_embedding\n\n\ndef albert_embedding_model_inference(model, tokenizer, text):\n \"\"\" Tokenizes and computes ALBERT `model` inference for input `text`. \"\"\"\n encoded_text = tf.constant(tokenizer.encode(text))[None, :]\n outputs = model(encoded_text)\n # The last hidden-state is the first element of the output tuple \n last_hidden_states = outputs[0]\n cls_embedding = last_hidden_states[0][0]\n return cls_embedding\n\n\ndef albert_embedding_batch_model_inference(model, tokenizer, text_batch):\n \"\"\" Tokenizes and computes ALBERT `model` inference for input `text_batch`.\n \"\"\"\n encoded_text = [\n tf.constant(tokenizer.encode(\n t, max_length=TOKENIZER_MAX_SEQ_LENGTH, pad_to_max_length=True))\n for t in text_batch\n ]\n encoded_batch = tf.stack(encoded_text)\n outputs = model(encoded_text)\n cls_embeddings = []\n for last_hidden_state in outputs[0]:\n cls_embeddings.append(last_hidden_state[0])\n return cls_embeddings\n\n\ndef t5_embedding_model_inference(model, tokenizer, text):\n \"\"\" Tokenizes and computes T5 `model` inference for input `text`. \"\"\"\n inputs = tokenizer.encode(text, return_tensors=\"tf\") # Batch size 1\n outputs = model(inputs, decoder_input_ids=inputs)\n # The last hidden-state is the first element of the output tuple \n last_hidden_states = outputs[0]\n cls_embedding = last_hidden_states[0][0]\n return cls_embedding\n\n'''\nMore model inference functions can be added, following documentation on\nhttps://huggingface.co/transformers/\n'''\n\nINFERENCE_MODELS = {\n 'bert' : bert_embedding_model_inference,\n 'albert' : albert_embedding_model_inference,\n 'albert_batch' : albert_embedding_batch_model_inference,\n 't5' : t5_embedding_model_inference\n}",
"_____no_output_____"
]
],
[
[
"## Testing tokenization and model inference with an example",
"_____no_output_____"
]
],
[
[
"PRETRAINED_MODEL = 'albert_base'\nINFERENCE = 'albert'\n\ntest_inference = INFERENCE_MODELS[INFERENCE](\n PRETRAINED_MODELS[PRETRAINED_MODEL],\n TOKENIZERS[PRETRAINED_MODEL],\n \"Why is the sky blue\"\n)\n\nprint('Example embedding', test_inference)\n\nembedding_dim = test_inference.shape[0]",
"_____no_output_____"
]
],
[
[
"## Hyperparameters for the classifier to be trained",
"_____no_output_____"
]
],
[
[
"class HParams(object):\n \"\"\"Hyperparameters used for training.\"\"\"\n def __init__(self):\n ### dataset parameters\n self.num_classes = 2\n self.embedding_dim = embedding_dim\n ### neural graph learning parameters\n self.distance_type = nsl.configs.DistanceType.L2\n self.graph_regularization_multiplier = 0.1\n self.num_neighbors = 5\n ### model architecture\n self.num_fc_units = [64, 64]\n ### training parameters\n self.train_epochs = 50\n self.batch_size = 128\n self.encoder_inference_batch_size = 32\n self.dropout_rate = 0.2\n ### eval parameters\n self.eval_steps = None # All instances in the test set are evaluated.\n\nHPARAMS = HParams()",
"_____no_output_____"
]
],
[
[
"## Process dataset in batch or single inference mode",
"_____no_output_____"
]
],
[
[
"def add_batch_embeddings(labels_and_texts):\n \"\"\"Splits `labels_and_texts` into batches and performs tokenization and\n converts tweet text into its corresponding embedding.\n\n Args:\n labels_and_texts: A List of dictionaries such that each entry E contains:\n E['label']: (integer) the rumour veracity annotation.\n E['source_text']: (string) the source tweet text.\n E['reactions']: (List of strings) the texts from the tweet replies.\n\n Each entry E from labels_and_texts is updated, adding the following key,\n value pairs:\n E['source_embedding']: (Tensor of floats) embeddings for E['source_text']\n E['reaction_embedding']: (List of float Tensors) embeddings for\n E['reactions'], up to HPARAMS.num_neighbors and\n in the corresponding E['reactions'] order.\n \"\"\"\n inputs = []\n print('Accumulating inputs')\n for e in labels_and_texts:\n inputs.append(e['source_text'])\n for r in e['reactions'][:HPARAMS.num_neighbors]:\n # Alternative ways to select neighbors within a tweet thread can be used.\n inputs.append(r)\n\n def generate_batches(inputs, batch_size):\n \"\"\"Splits `inputs` list into chunks of (up to) `batch_size` length.\"\"\"\n for i in range(0, len(inputs), batch_size):\n yield inputs[i: i + batch_size]\n\n inferences = []\n for i, batch in enumerate(generate_batches(\n inputs, HPARAMS.encoder_inference_batch_size)):\n print('Running model inference for batch', i)\n batch_inference = INFERENCE_MODELS[INFERENCE](\n PRETRAINED_MODELS[PRETRAINED_MODEL],\n TOKENIZERS[PRETRAINED_MODEL],\n batch)\n for inference in batch_inference:\n inferences.append(inference)\n\n i = 0\n for e in labels_and_texts:\n e['source_embedding'] = inferences[i]\n i += 1\n e['reaction_embedding'] = []\n for r in e['reactions'][:HPARAMS.num_neighbors]:\n e['reaction_embedding'].append(inferences[i])\n i += 1",
"_____no_output_____"
],
[
"def add_embeddings(labels_and_texts):\n \"\"\"Performs tokenization and model inference for each element of\n labels_and_texts, updating it with computed embeddings.\n\n Args:\n labels_and_texts: A List of dictionaries such that each entry E contains:\n E['label']: (integer) the rumour veracity annotation.\n E['source_text']: (string) the source tweet text.\n E['reactions']: (List of strings) the texts from the tweet replies.\n\n Each entry E from labels_and_texts is updated, adding the following key,\n value pairs:\n E['source_embedding']: (Tensor of floats) embeddings for E['source_text']\n E['reaction_embedding']: (List of float Tensors) embeddings for\n E['reactions'], up to HPARAMS.num_neighbors and\n in the corresponding E['reactions'] order.\n \"\"\"\n for index, label_and_texts in enumerate(labels_and_texts):\n if index % 100 == 0:\n print('Computing embeddings for item', index)\n label_and_texts['source_embedding'] = INFERENCE_MODELS[INFERENCE](\n PRETRAINED_MODELS[PRETRAINED_MODEL],\n TOKENIZERS[PRETRAINED_MODEL],\n label_and_texts['source_text'])\n label_and_texts['reaction_embedding'] = []\n for r in label_and_texts['reactions'][:HPARAMS.num_neighbors]:\n # Alternative ways to select neighbors within a tweet thread can be used.\n label_and_texts['reaction_embedding'].append(INFERENCE_MODELS[INFERENCE](\n PRETRAINED_MODELS[PRETRAINED_MODEL],\n TOKENIZERS[PRETRAINED_MODEL],\n r))",
"_____no_output_____"
]
],
[
[
"## Load and inspect dataset",
"_____no_output_____"
]
],
[
[
"labels_and_texts = load_labels_and_texts(topics)",
"_____no_output_____"
],
[
"for e in random.sample(labels_and_texts, 3):\n pprint.pprint(e)",
"_____no_output_____"
]
],
[
[
"## Compute and store textual embeddings",
"_____no_output_____"
]
],
[
[
"if 'batch' in INFERENCE:\n add_batch_embeddings(labels_and_texts)\nelse:\n add_embeddings(labels_and_texts)",
"_____no_output_____"
]
],
[
[
"## Create train and test datasets\n\nUsing a 80:20 train:test split",
"_____no_output_____"
]
],
[
[
"# Alternative ways to split include a split by time or by news event.\nrandom.shuffle(labels_and_texts)\n\ntrain_size = int(0.8 * len(labels_and_texts))\n\nTRAIN_DATA = labels_and_texts[:train_size]\nTEST_DATA = labels_and_texts[train_size:]\n\n# Constants used to identify neighbor features in the input.\nNBR_FEATURE_PREFIX = 'NL_nbr_'\nNBR_WEIGHT_SUFFIX = '_weight'",
"_____no_output_____"
],
[
"def create_np_tensors_from_datum(datum, propagate_label=True):\n \"\"\"Creates a node and neighbor numpy tensors given input datum.\n\n Args:\n datum: A dictionary with node and neighbor features and annotation label.\n propagate_label: Boolean indicating if we labels should be propagated to\n neighbors.\n\n Returns:\n A tuple T (node_tensor, neighbor_tensors) such that:\n T[0]: a dictionary containing node embeddings and label\n T[1]: a List of dictionaries, each containing embeddings for a\n neighbor and, if propagate_label is true, the corresponding label.\n\n \"\"\"\n label_tensor = datum['label']\n \n def get_float32_tensor(d):\n np_array = np.array(d, dtype='f')\n return np_array\n \n node_tensor = {\n 'embedding' : get_float32_tensor(datum['source_embedding']),\n 'label' : label_tensor\n }\n\n neighbor_tensors = []\n for re in datum['reaction_embedding']:\n tensor = {\n 'embedding' : get_float32_tensor(re),\n }\n if propagate_label:\n tensor['label'] = label_tensor\n neighbor_tensors.append(dict(tensor))\n\n return node_tensor, neighbor_tensors",
"_____no_output_____"
],
[
"TRAIN_TENSORS = [\n create_np_tensors_from_datum(d) for d in TRAIN_DATA\n]",
"_____no_output_____"
],
[
"TEST_TENSORS = [\n create_np_tensors_from_datum(d) for d in TEST_DATA\n]",
"_____no_output_____"
],
[
"TRAIN_TENSORS[0][0], TEST_TENSORS[0][0]",
"_____no_output_____"
]
],
[
[
"## Create train and test tf.data.TFRecordDataset",
"_____no_output_____"
]
],
[
[
"def make_dataset(tf_features, training=False):\n \"\"\"Creates a `tf.data.TFRecordDataset`.\n\n Args:\n tf_features: List of (node_tensor, neighbor_tensors) tuples.\n training: Boolean indicating if we are in training mode.\n\n Returns:\n An instance of `tf.data.TFRecordDataset` containing the `tf.train.Example`\n objects.\n \"\"\"\n\n def get_tf_examples_with_nsl_signals(node_feature, neighbor_features):\n \"\"\"Merges `neighbor_features` and `node_feature`.\n\n Args:\n node_feature: A dictionary of `tf.train.Feature`.\n neighbor_features: A list of `tf.train.Feature` dictionaries.\n\n Returns:\n A pair whose first value is a dictionary containing relevant features\n and whose second value contains the ground truth label.\n \"\"\"\n feature_dict = dict(node_feature)\n # We also extract corresponding neighbor features in a similar manner to\n # the features above during training.\n if training:\n for i in range(HPARAMS.num_neighbors):\n nbr_feature_key = '{}{}_{}'.format(NBR_FEATURE_PREFIX, i, 'embedding')\n nbr_weight_key = '{}{}{}'.format(NBR_FEATURE_PREFIX, i,\n NBR_WEIGHT_SUFFIX)\n if i < len(neighbor_features):\n nf = neighbor_features[i]\n feature_dict[nbr_feature_key] = nf['embedding']\n feature_dict[nbr_weight_key] = 1.0\n else:\n feature_dict[nbr_feature_key] = np.zeros(\n HPARAMS.embedding_dim, dtype='f')\n feature_dict[nbr_weight_key] = 0.0\n\n label = feature_dict.pop('label')\n \n return feature_dict, label\n\n print('Adding NSL features for entries')\n tensors_with_nsl = {}\n labels = []\n for (node, neighbors) in tf_features:\n feature_dict, label = get_tf_examples_with_nsl_signals(node, neighbors)\n for k,v in feature_dict.items():\n if k not in tensors_with_nsl:\n tensors_with_nsl[k] = []\n tensors_with_nsl[k].append(v)\n labels.append(label)\n \n print('Creating tf.data.Dataset from tensors')\n dataset = tf.data.Dataset.from_tensor_slices((tensors_with_nsl, labels))\n dataset = dataset.batch(HPARAMS.batch_size)\n return dataset",
"_____no_output_____"
],
[
"train_dataset = make_dataset(TRAIN_TENSORS, training=True)",
"_____no_output_____"
],
[
"test_dataset = make_dataset(TEST_TENSORS)\n",
"_____no_output_____"
]
],
[
[
"## Inspecting train dataset",
"_____no_output_____"
]
],
[
[
"for feature_batch, label_batch in train_dataset.take(1):\n print('Feature list:', list(feature_batch.keys()))\n print('Batch of inputs:', feature_batch['embedding'])\n nbr_feature_key = '{}{}_{}'.format(NBR_FEATURE_PREFIX, 0, 'embedding')\n nbr_weight_key = '{}{}{}'.format(NBR_FEATURE_PREFIX, 0, NBR_WEIGHT_SUFFIX)\n print('Batch of neighbor inputs:', feature_batch[nbr_feature_key])\n print('Batch of neighbor weights:',\n tf.reshape(feature_batch[nbr_weight_key], [-1]))\n print('Batch of labels:', label_batch)",
"_____no_output_____"
]
],
[
[
"## Inspecting test dataset",
"_____no_output_____"
]
],
[
[
"for feature_batch, label_batch in test_dataset.take(1):\n print('Feature list:', list(feature_batch.keys()))\n print('Batch of inputs:', feature_batch['embedding'])\n print('Batch of labels:', label_batch)",
"_____no_output_____"
]
],
[
[
"## Multi-layer perpectron classification model",
"_____no_output_____"
],
[
"### Sequential MLP model",
"_____no_output_____"
]
],
[
[
"def make_mlp_sequential_model(hparams):\n \"\"\"Creates a sequential multi-layer perceptron model.\"\"\"\n model = tf.keras.Sequential()\n model.add(\n tf.keras.layers.InputLayer(\n input_shape=(hparams.embedding_dim,), name='embedding'))\n for num_units in hparams.num_fc_units:\n model.add(tf.keras.layers.Dense(num_units, activation='relu'))\n # For sequential models, by default, Keras ensures that the 'dropout' layer\n # is invoked only during training.\n model.add(tf.keras.layers.Dropout(hparams.dropout_rate))\n model.add(tf.keras.layers.Dense(hparams.num_classes, activation='softmax'))\n return model",
"_____no_output_____"
]
],
[
[
"### Functional MLP model",
"_____no_output_____"
]
],
[
[
"def make_mlp_functional_model(hparams):\n \"\"\"Creates a functional API-based multi-layer perceptron model.\"\"\"\n inputs = tf.keras.Input(\n shape=(hparams.embedding_dim,), dtype='int64', name='embedding')\n\n cur_layer = inputs\n\n for num_units in hparams.num_fc_units:\n cur_layer = tf.keras.layers.Dense(num_units, activation='relu')(cur_layer)\n # For functional models, by default, Keras ensures that the 'dropout' layer\n # is invoked only during training.\n cur_layer = tf.keras.layers.Dropout(hparams.dropout_rate)(cur_layer)\n\n outputs = tf.keras.layers.Dense(\n hparams.num_classes, activation='softmax')(\n cur_layer)\n\n model = tf.keras.Model(inputs, outputs=outputs)\n return model",
"_____no_output_____"
]
],
[
[
"### tf.Keras.Model subclass MLP",
"_____no_output_____"
]
],
[
[
"def make_mlp_subclass_model(hparams):\n \"\"\"Creates a multi-layer perceptron subclass model in Keras.\"\"\"\n\n class MLP(tf.keras.Model):\n \"\"\"Subclass model defining a multi-layer perceptron.\"\"\"\n\n def __init__(self):\n super(MLP, self).__init__()\n self.dense_layers = [\n tf.keras.layers.Dense(num_units, activation='relu')\n for num_units in hparams.num_fc_units\n ]\n self.dropout_layer = tf.keras.layers.Dropout(hparams.dropout_rate)\n self.output_layer = tf.keras.layers.Dense(\n hparams.num_classes, activation='softmax')\n\n def call(self, inputs, training=False):\n cur_layer = inputs['embedding']\n for dense_layer in self.dense_layers:\n cur_layer = dense_layer(cur_layer)\n cur_layer = self.dropout_layer(cur_layer, training=training)\n\n outputs = self.output_layer(cur_layer)\n\n return outputs\n\n return MLP()",
"_____no_output_____"
]
],
[
[
"# Base MLP model",
"_____no_output_____"
]
],
[
[
"# Create a base MLP model using the functional API.\n# Alternatively, you can also create a sequential or subclass base model using\n# the make_mlp_sequential_model() or make_mlp_subclass_model() functions\n# respectively, defined above. Note that if a subclass model is used, its\n# summary cannot be generated until it is built.\nbase_model_tag, base_model = 'FUNCTIONAL', make_mlp_functional_model(HPARAMS)\nbase_model.summary()",
"_____no_output_____"
]
],
[
[
"## Compile and train the base MLP model",
"_____no_output_____"
]
],
[
[
"base_model.compile(\n optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\nbase_model.fit(train_dataset, epochs=HPARAMS.train_epochs, verbose=1)",
"_____no_output_____"
]
],
[
[
"## Evaluate base model on test dataset",
"_____no_output_____"
]
],
[
[
"# Helper function to print evaluation metrics.\ndef print_metrics(model_desc, eval_metrics):\n \"\"\"Prints evaluation metrics.\n\n Args:\n model_desc: A description of the model.\n eval_metrics: A dictionary mapping metric names to corresponding values. It\n must contain the loss and accuracy metrics.\n \"\"\"\n print('\\n')\n print('Eval accuracy for ', model_desc, ': ', eval_metrics['accuracy'])\n print('Eval loss for ', model_desc, ': ', eval_metrics['loss'])\n if 'graph_loss' in eval_metrics:\n print('Eval graph loss for ', model_desc, ': ', eval_metrics['graph_loss'])",
"_____no_output_____"
],
[
"eval_results = dict(\n zip(base_model.metrics_names,\n base_model.evaluate(test_dataset, steps=HPARAMS.eval_steps)))\nprint_metrics('Base MLP model', eval_results)\n",
"_____no_output_____"
]
],
[
[
"## Create, compile and train MLP model with graph regularization",
"_____no_output_____"
]
],
[
[
"# Build a new base MLP model.\nbase_reg_model_tag, base_reg_model = 'FUNCTIONAL', make_mlp_functional_model(\n HPARAMS)\n\n# Wrap the base MLP model with graph regularization.\ngraph_reg_config = nsl.configs.make_graph_reg_config(\n max_neighbors=HPARAMS.num_neighbors,\n multiplier=HPARAMS.graph_regularization_multiplier,\n distance_type=HPARAMS.distance_type,\n sum_over_axis=-1)\ngraph_reg_model = nsl.keras.GraphRegularization(base_reg_model,\n graph_reg_config)\ngraph_reg_model.compile(\n optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\ngraph_reg_model.fit(train_dataset, epochs=HPARAMS.train_epochs, verbose=1)",
"_____no_output_____"
]
],
[
[
"## Evaluate MLP model with graph regularization on test dataset",
"_____no_output_____"
]
],
[
[
"eval_results = dict(\n zip(graph_reg_model.metrics_names,\n graph_reg_model.evaluate(test_dataset, steps=HPARAMS.eval_steps)))\nprint_metrics('MLP + graph regularization', eval_results)",
"_____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"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece398f1e2e54ebfd04ad7f4c8ab849f25deb306 | 465,575 | ipynb | Jupyter Notebook | 1. Load and Visualize Data.ipynb | muhyun/facial-keypoint-detection | 0c0e914300ee5dd33df97fcd2e7cfed44a212af1 | [
"MIT"
] | 1 | 2019-06-25T12:33:21.000Z | 2019-06-25T12:33:21.000Z | 1. Load and Visualize Data.ipynb | GeonSeok-Lee/facial-keypoint-detection | b02edbb510da1f626de7bd9dd998010730c768bd | [
"MIT"
] | null | null | null | 1. Load and Visualize Data.ipynb | GeonSeok-Lee/facial-keypoint-detection | b02edbb510da1f626de7bd9dd998010730c768bd | [
"MIT"
] | 1 | 2019-06-24T13:08:38.000Z | 2019-06-24T13:08:38.000Z | 700.112782 | 162,272 | 0.947497 | [
[
[
"# Facial Keypoint Detection\n \nThis project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working with. \n\nLet's take a look at some examples of images and corresponding facial keypoints.\n\n<img src='images/key_pts_example.png' width=50% height=50%/>\n\nFacial keypoints (also called facial landmarks) are the small magenta dots shown on each of the faces in the image above. In each training and test image, there is a single face and **68 keypoints, with coordinates (x, y), for that face**. These keypoints mark important areas of the face: the eyes, corners of the mouth, the nose, etc. These keypoints are relevant for a variety of tasks, such as face filters, emotion recognition, pose recognition, and so on. Here they are, numbered, and you can see that specific ranges of points match different portions of the face.\n\n<img src='images/landmarks_numbered.jpg' width=30% height=30%/>\n\n---",
"_____no_output_____"
],
[
"## Load and Visualize Data\n\nThe first step in working with any dataset is to become familiar with your data; you'll need to load in the images of faces and their keypoints and visualize them! This set of image data has been extracted from the [YouTube Faces Dataset](https://www.cs.tau.ac.il/~wolf/ytfaces/), which includes videos of people in YouTube videos. These videos have been fed through some processing steps and turned into sets of image frames containing one face and the associated keypoints.\n\n#### Training and Testing Data\n\nThis facial keypoints dataset consists of 5770 color images. All of these images are separated into either a training or a test set of data.\n\n* 3462 of these images are training images, for you to use as you create a model to predict keypoints.\n* 2308 are test images, which will be used to test the accuracy of your model.\n\nThe information about the images and keypoints in this dataset are summarized in CSV files, which we can read in using `pandas`. Let's read the training CSV and get the annotations in an (N, 2) array where N is the number of keypoints and 2 is the dimension of the keypoint coordinates (x, y).\n\n---",
"_____no_output_____"
]
],
[
[
"# import the required libraries\nimport glob\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport cv2",
"_____no_output_____"
],
[
"key_pts_frame = pd.read_csv('data/training_frames_keypoints.csv')\n\nn = 0\nimage_name = key_pts_frame.iloc[n, 0]\nkey_pts = key_pts_frame.iloc[n, 1:].as_matrix()\nkey_pts = key_pts.astype('float').reshape(-1, 2)\n\nprint('Image name: ', image_name)\nprint('Landmarks shape: ', key_pts.shape)\nprint('First 4 key pts: {}'.format(key_pts[:4]))",
"Image name: Luis_Fonsi_21.jpg\nLandmarks shape: (68, 2)\nFirst 4 key pts: [[ 45. 98.]\n [ 47. 106.]\n [ 49. 110.]\n [ 53. 119.]]\n"
],
[
"# print out some stats about the data\nprint('Number of images: ', key_pts_frame.shape[0])",
"Number of images: 3462\n"
]
],
[
[
"## Look at some images\n\nBelow, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape.",
"_____no_output_____"
]
],
[
[
"def show_keypoints(image, key_pts):\n \"\"\"Show image with keypoints\"\"\"\n plt.imshow(image)\n plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='.', c='m')\n",
"_____no_output_____"
],
[
"# Display a few different types of images by changing the index n\n\n# select an image by index in our data frame\nn = 100\nimage_name = key_pts_frame.iloc[n, 0]\nkey_pts = key_pts_frame.iloc[n, 1:].as_matrix()\nkey_pts = key_pts.astype('float').reshape(-1, 2)\n\nplt.figure(figsize=(5, 5))\nshow_keypoints(mpimg.imread(os.path.join('data/training/', image_name)), key_pts)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Dataset class and Transformations\n\nTo prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html).\n\n#### Dataset class\n\n``torch.utils.data.Dataset`` is an abstract class representing a\ndataset. This class will allow us to load batches of image/keypoint data, and uniformly apply transformations to our data, such as rescaling and normalizing images for training a neural network.\n\n\nYour custom dataset should inherit ``Dataset`` and override the following\nmethods:\n\n- ``__len__`` so that ``len(dataset)`` returns the size of the dataset.\n- ``__getitem__`` to support the indexing such that ``dataset[i]`` can\n be used to get the i-th sample of image/keypoint data.\n\nLet's create a dataset class for our face keypoints dataset. We will\nread the CSV file in ``__init__`` but leave the reading of images to\n``__getitem__``. This is memory efficient because all the images are not\nstored in the memory at once but read as required.\n\nA sample of our dataset will be a dictionary\n``{'image': image, 'keypoints': key_pts}``. Our dataset will take an\noptional argument ``transform`` so that any required processing can be\napplied on the sample. We will see the usefulness of ``transform`` in the\nnext section.\n",
"_____no_output_____"
]
],
[
[
"from torch.utils.data import Dataset, DataLoader\n\nclass FacialKeypointsDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, csv_file, root_dir, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.key_pts_frame = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.key_pts_frame)\n\n def __getitem__(self, idx):\n image_name = os.path.join(self.root_dir,\n self.key_pts_frame.iloc[idx, 0])\n \n image = mpimg.imread(image_name)\n \n # if image has an alpha color channel, get rid of it\n if(image.shape[2] == 4):\n image = image[:,:,0:3]\n \n key_pts = self.key_pts_frame.iloc[idx, 1:].as_matrix()\n key_pts = key_pts.astype('float').reshape(-1, 2)\n sample = {'image': image, 'keypoints': key_pts}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample",
"_____no_output_____"
]
],
[
[
"Now that we've defined this class, let's instantiate the dataset and display some images.",
"_____no_output_____"
]
],
[
[
"# Construct the dataset\nface_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv',\n root_dir='data/training/')\n\n# print some stats about the dataset\nprint('Length of dataset: ', len(face_dataset))",
"Length of dataset: 3462\n"
],
[
"# Display a few of the images from the dataset\nnum_to_display = 3\n\nfor i in range(num_to_display):\n \n # define the size of images\n fig = plt.figure(figsize=(20,10))\n \n # randomly select a sample\n rand_i = np.random.randint(0, len(face_dataset))\n sample = face_dataset[rand_i]\n\n # print the shape of the image and keypoints\n print(i, sample['image'].shape, sample['keypoints'].shape)\n\n ax = plt.subplot(1, num_to_display, i + 1)\n ax.set_title('Sample #{}'.format(i))\n \n # Using the same display function, defined earlier\n show_keypoints(sample['image'], sample['keypoints'])\n \n plt.show()",
"0 (200, 181, 3) (68, 2)\n"
]
],
[
[
"## Transforms\n\nNow, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors.\n\nTherefore, we will need to write some pre-processing code.\nLet's create four transforms:\n\n- ``Normalize``: to convert a color image to grayscale values with a range of [0,1] and normalize the keypoints to be in a range of about [-1, 1]\n- ``Rescale``: to rescale an image to a desired size.\n- ``RandomCrop``: to crop an image randomly.\n- ``ToTensor``: to convert numpy images to torch images.\n\n\nWe will write them as callable classes instead of simple functions so\nthat parameters of the transform need not be passed everytime it's\ncalled. For this, we just need to implement ``__call__`` method and \n(if we require parameters to be passed in), the ``__init__`` method. \nWe can then use a transform like this:\n\n tx = Transform(params)\n transformed_sample = tx(sample)\n\nObserve below how these transforms are generally applied to both the image and its keypoints.\n\n",
"_____no_output_____"
]
],
[
[
"import torch\nfrom torchvision import transforms, utils\n# tranforms\n\nclass Normalize(object):\n \"\"\"Convert a color image to grayscale and normalize the color range to [0,1].\"\"\" \n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n \n image_copy = np.copy(image)\n key_pts_copy = np.copy(key_pts)\n\n # convert image to grayscale\n image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n \n # scale color range from [0, 255] to [0, 1]\n image_copy= image_copy/255.0\n \n # scale keypoints to be centered around 0 with a range of [-1, 1]\n # mean = 100, sqrt = 50, so, pts should be (pts - 100)/50\n key_pts_copy = (key_pts_copy - 100)/50.0\n\n\n return {'image': image_copy, 'keypoints': key_pts_copy}\n\n\nclass Rescale(object):\n \"\"\"Rescale the image in a sample to a given size.\n\n Args:\n output_size (tuple or int): Desired output size. If tuple, output is\n matched to output_size. If int, smaller of image edges is matched\n to output_size keeping aspect ratio the same.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n self.output_size = output_size\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n\n h, w = image.shape[:2]\n if isinstance(self.output_size, int):\n if h > w:\n new_h, new_w = self.output_size * h / w, self.output_size\n else:\n new_h, new_w = self.output_size, self.output_size * w / h\n else:\n new_h, new_w = self.output_size\n\n new_h, new_w = int(new_h), int(new_w)\n\n img = cv2.resize(image, (new_w, new_h))\n \n # scale the pts, too\n key_pts = key_pts * [new_w / w, new_h / h]\n\n return {'image': img, 'keypoints': key_pts}\n\n\nclass RandomCrop(object):\n \"\"\"Crop randomly the image in a sample.\n\n Args:\n output_size (tuple or int): Desired output size. If int, square crop\n is made.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n if isinstance(output_size, int):\n self.output_size = (output_size, output_size)\n else:\n assert len(output_size) == 2\n self.output_size = output_size\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n\n h, w = image.shape[:2]\n new_h, new_w = self.output_size\n\n top = np.random.randint(0, h - new_h)\n left = np.random.randint(0, w - new_w)\n\n image = image[top: top + new_h,\n left: left + new_w]\n\n key_pts = key_pts - [left, top]\n\n return {'image': image, 'keypoints': key_pts}\n\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n \n # if image has no grayscale color channel, add one\n if(len(image.shape) == 2):\n # add that third color dim\n image = image.reshape(image.shape[0], image.shape[1], 1)\n \n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n image = image.transpose((2, 0, 1))\n \n return {'image': torch.from_numpy(image),\n 'keypoints': torch.from_numpy(key_pts)}",
"_____no_output_____"
]
],
[
[
"## Test out the transforms\n\nLet's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescale the original image, you can then crop it to any size smaller than the rescaled size.",
"_____no_output_____"
]
],
[
[
"# test out some of these transforms\nrescale = Rescale(100)\ncrop = RandomCrop(50)\ncomposed = transforms.Compose([Rescale(250),\n RandomCrop(224)])\n\n# apply the transforms to a sample image\ntest_num = 500\nsample = face_dataset[test_num]\n\nfig = plt.figure()\nfor i, tx in enumerate([rescale, crop, composed]):\n print(type(sample))\n print(sample['image'].shape)\n transformed_sample = tx(sample)\n\n ax = plt.subplot(1, 3, i + 1)\n plt.tight_layout()\n ax.set_title(type(tx).__name__)\n show_keypoints(transformed_sample['image'], transformed_sample['keypoints'])\n\nplt.show()",
"<class 'dict'>\n(174, 153, 3)\n<class 'dict'>\n(174, 153, 3)\n<class 'dict'>\n(174, 153, 3)\n"
]
],
[
[
"## Create the transformed dataset\n\nApply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size).",
"_____no_output_____"
]
],
[
[
"# define the data tranform\n# order matters! i.e. rescaling should come before a smaller crop\ndata_transform = transforms.Compose([Rescale(250),\n RandomCrop(224),\n Normalize(),\n ToTensor()])\n\n# create the transformed dataset\ntransformed_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv',\n root_dir='data/training/',\n transform=data_transform)\n",
"_____no_output_____"
],
[
"# print some stats about the transformed data\nprint('Number of images: ', len(transformed_dataset))\n\n# make sure the sample tensors are the expected size\nfor i in range(5):\n sample = transformed_dataset[i]\n print(i, sample['image'].size(), sample['keypoints'].size())\n",
"_____no_output_____"
]
],
[
[
"## Data Iteration and Batching\n\nRight now, we are iterating over this data using a ``for`` loop, but we are missing out on a lot of PyTorch's dataset capabilities, specifically the abilities to:\n\n- Batch the data\n- Shuffle the data\n- Load the data in parallel using ``multiprocessing`` workers.\n\n``torch.utils.data.DataLoader`` is an iterator which provides all these\nfeatures, and we'll see this in use in the *next* notebook, Notebook 2, when we load data in batches to train a neural network!\n\n---\n\n",
"_____no_output_____"
],
[
"## Ready to Train!\n\nNow that you've seen how to load and transform our data, you're ready to build a neural network to train on this data.\n\nIn the next notebook, you'll be tasked with creating a CNN for facial keypoint detection.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
ece39a2751a4b701143c0ef485c11db2fe17d65b | 3,243 | ipynb | Jupyter Notebook | bader charge calculation workflow.ipynb | shan-ping/usefull-dft-workflow | 9f36e05f1bf3c5b229bcb6e248b7cda24195f632 | [
"MIT"
] | null | null | null | bader charge calculation workflow.ipynb | shan-ping/usefull-dft-workflow | 9f36e05f1bf3c5b229bcb6e248b7cda24195f632 | [
"MIT"
] | null | null | null | bader charge calculation workflow.ipynb | shan-ping/usefull-dft-workflow | 9f36e05f1bf3c5b229bcb6e248b7cda24195f632 | [
"MIT"
] | null | null | null | 21.058442 | 111 | 0.526981 | [
[
[
"# Calculate the bader charge to identify the charge transfer",
"_____no_output_____"
],
[
"## Cd the file that you want to calculate the bader charge you shuold put the INCAR(for scf calculation)",
"_____no_output_____"
]
],
[
[
"!ls",
" 100K 298K\t\t\t\t INCARscf1 INCARsr1\r\n 230K 'bader charge calculation.ipynb' INCARsr PbTa2Se4workflow.ipynb\r\n"
],
[
"!cd ",
"_____no_output_____"
],
[
"#!mkdir bader\nwith open(\"./INCAR\", encoding=\"utf-8\",mode=\"a\") as file: \n file.write(\"\\n\\nLAECHG=.TRUE. !for bader charge calculation\") \n file.write(\"\\nNGXF=(please put a number) !the grid for CHGCAR file along the a vector\")\n file.write(\"\\nNGYF=(please put a number) !the grid for CHGCAR file along the b vector\")\n file.write(\"\\nNGZF=(please put a number) !the grid for CHGCAR file along the c vector\")",
"_____no_output_____"
]
],
[
[
"## Then run the vasp to do DFT calculation",
"_____no_output_____"
],
[
"## Arfter finishing the calculation the result should contain the AECCAR0 AECCAR1 AECCAR2 and CHGCAR file",
"_____no_output_____"
]
],
[
[
"!chgsum.pl AECCAR0 AECCAR2",
"_____no_output_____"
]
],
[
[
"## Then get the CHGCAR_sum file ",
"_____no_output_____"
]
],
[
[
"!bader CHGCAR -ref CHGCAR_sum",
"_____no_output_____"
]
],
[
[
"## You should make sure the charge converged when NG(XYZ)F increased ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ece3a447b74823ef57ed727818218a489acba7a3 | 47,797 | ipynb | Jupyter Notebook | scripts/random forest/majro2_random_forest.ipynb | amanparmar17/short-text-classification | f8514f90bb7b7771621a21eeadeb13b273139d61 | [
"Apache-2.0"
] | null | null | null | scripts/random forest/majro2_random_forest.ipynb | amanparmar17/short-text-classification | f8514f90bb7b7771621a21eeadeb13b273139d61 | [
"Apache-2.0"
] | null | null | null | scripts/random forest/majro2_random_forest.ipynb | amanparmar17/short-text-classification | f8514f90bb7b7771621a21eeadeb13b273139d61 | [
"Apache-2.0"
] | null | null | null | 47,797 | 47,797 | 0.784108 | [
[
[
"#MAJOR 2- RANDOM FOREST\n\n",
"_____no_output_____"
]
],
[
[
"#mount the drive for accessing the dataset from the drive\nfrom google.colab import drive\ndrive.mount('/content/drive')",
"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/drive\n"
]
],
[
[
"#checking the gpu for tensorflow",
"_____no_output_____"
]
],
[
[
"from keras import backend as K\nK.tensorflow_backend._get_available_gpus()",
"Using TensorFlow backend.\n"
],
[
"from tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())",
"[name: \"/device:CPU:0\"\ndevice_type: \"CPU\"\nmemory_limit: 268435456\nlocality {\n}\nincarnation: 2216297801004431993\n, name: \"/device:XLA_CPU:0\"\ndevice_type: \"XLA_CPU\"\nmemory_limit: 17179869184\nlocality {\n}\nincarnation: 9261371543184261176\nphysical_device_desc: \"device: XLA_CPU device\"\n, name: \"/device:XLA_GPU:0\"\ndevice_type: \"XLA_GPU\"\nmemory_limit: 17179869184\nlocality {\n}\nincarnation: 4245860295538836463\nphysical_device_desc: \"device: XLA_GPU device\"\n, name: \"/device:GPU:0\"\ndevice_type: \"GPU\"\nmemory_limit: 11330115994\nlocality {\n bus_id: 1\n links {\n }\n}\nincarnation: 8185910357940848198\nphysical_device_desc: \"device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7\"\n]\n"
],
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"df=pd.read_csv(\"drive/My Drive/major2/random forest/DATASET_19classes.csv\")",
"/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (4,5,6,7,8) have mixed types. Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
],
[
"print(df.head())\nprint(df.shape)\nprint(df.columns)",
" text_instance ... Unnamed: 8\n0 Will Smith Joins Diplo And Nicky Jam For The 2... ... NaN\n1 Of course it has a song. ... NaN\n2 Hugh Grant Marries For The First Time At Age 57 ... NaN\n3 The actor and his longtime girlfriend Anna Ebe... ... NaN\n4 Jim Carrey Blasts 'Castrato' Adam Schiff And D... ... NaN\n\n[5 rows x 9 columns]\n(368536, 9)\nIndex(['text_instance', 'category', 'Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4',\n 'Unnamed: 5', 'Unnamed: 6', 'Unnamed: 7', 'Unnamed: 8'],\n dtype='object')\n"
],
[
"print(len(df.category.unique()))",
"625\n"
],
[
"#to remove the aomalies from the dataset \n\nfilter=\"^[A-Z]+$\"\nfo=df['category'].str.contains(filter)\ndf=df[fo]",
"_____no_output_____"
],
[
"print(len(df.category.unique()))\n\nfor i in df.category.unique():\n print(i)",
"16\nENTERTAINMENT\nNEWS\nIMPACT\nPOLITICS\nVOICES\nWOMEN\nCOMEDY\nSPORTS\nTRAVEL\nPARENTING\nARTS\nSTYLE\nENVIRONMENT\nLIVING\nWORLDPOST\nWELLNESS\n"
],
[
"df.head()",
"_____no_output_____"
],
[
"#to remove the NaN columns from the dataset\ndf=df.drop(df.columns[2:8],axis=1)",
"_____no_output_____"
],
[
"df=df.drop(df.columns[-1],axis=1)\nprint(df.head(5))\ndf.shape",
" text_instance category\n0 Will Smith Joins Diplo And Nicky Jam For The 2... ENTERTAINMENT\n1 Of course it has a song. ENTERTAINMENT\n2 Hugh Grant Marries For The First Time At Age 57 ENTERTAINMENT\n3 The actor and his longtime girlfriend Anna Ebe... ENTERTAINMENT\n4 Jim Carrey Blasts 'Castrato' Adam Schiff And D... ENTERTAINMENT\n"
],
[
"df = df[pd.notnull(df['text_instance'])]",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 306866 entries, 0 to 368535\nData columns (total 2 columns):\ntext_instance 306866 non-null object\ncategory 306866 non-null object\ndtypes: object(2)\nmemory usage: 7.0+ MB\n"
],
[
"df['category_id'] = df['category'].factorize()[0]\nfrom io import StringIO\ncategory_id_df = df[['text_instance', 'category_id']].drop_duplicates().sort_values('category_id')\ncategory_to_id = dict(category_id_df.values)\nid_to_category = dict(category_id_df[['category_id', 'text_instance']].values)",
"_____no_output_____"
],
[
"print(df.head)\nprint(df.shape)\nprint(df.columns)",
"<bound method NDFrame.head of text_instance ... category_id\n0 Will Smith Joins Diplo And Nicky Jam For The 2... ... 0\n1 Of course it has a song. ... 0\n2 Hugh Grant Marries For The First Time At Age 57 ... 0\n3 The actor and his longtime girlfriend Anna Ebe... ... 0\n4 Jim Carrey Blasts 'Castrato' Adam Schiff And D... ... 0\n... ... ... ...\n368531 THREE million children in this country take dr... ... 7\n368532 TSA Workers Suspended From Newark Airport For ... ... 7\n368533 An official with the local union told the site... ... 7\n368534 Kylie, Kendall Jenner Cover Teen Vogue March 2... ... 7\n368535 She lands a Teen Vogue cover, of course. Altho... ... 7\n\n[306866 rows x 3 columns]>\n(306866, 3)\nIndex(['text_instance', 'category', 'category_id'], dtype='object')\n"
]
],
[
[
"#to check the imbalance in the dataset",
"_____no_output_____"
]
],
[
[
"\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(8,6))\ndf.groupby('category').text_instance.count().plot.bar(ylim=0)\nplt.show()",
"_____no_output_____"
],
[
"from sklearn.feature_extraction.text import TfidfVectorizer\n\ntfidf = TfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')\n\nfeatures1 = tfidf.fit_transform(df.text_instance[:100000]).toarray()\nfeatures2 = tfidf.fit_transform(df.text_instance[100000:200000]).toarray()\nfeatures3 = tfidf.fit_transform(df.text_instance[200000:]).toarray()\nlabels1 = df.category_id[:100000]\nlabels2 = df.category_id[100000:200000]\nlabels3 = df.category_id[200000:]\nprint(features1.shape)\nprint(features2.shape)\nprint(features3.shape)\n",
"_____no_output_____"
],
[
"print(type(features1))\nprint(type(labels1))\n#if the type of the features and labels object is a dataframe\nfeatures=features1.append(features2)\nfeatures=features.append(features3)\n\nlabels=labels1.append(labels2)\nlabels=labels.append(labels3)",
"_____no_output_____"
],
[
"from sklearn.feature_selection import chi2\nimport numpy as np\n\nN = 2\nfor text_instance, category_id in sorted(category_to_id.items()):\n features_chi2 = chi2(features, labels == category_id)\n indices = np.argsort(features_chi2[0])\n feature_names = np.array(tfidf.get_feature_names())[indices]\n unigrams = [v for v in feature_names if len(v.split(' ')) == 1]\n bigrams = [v for v in feature_names if len(v.split(' ')) == 2]\n print(\"# '{}':\".format(Product))\n print(\" . Most correlated unigrams:\\n . {}\".format('\\n . '.join(unigrams[-N:])))\n print(\" . Most correlated bigrams:\\n . {}\".format('\\n . '.join(bigrams[-N:])))",
"_____no_output_____"
],
[
"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\n\nX_train, X_test, y_train, y_test = train_test_split(df['text_instance'], df['category'], random_state = 0)\ncount_vect = CountVectorizer()\nX_train_counts = count_vect.fit_transform(X_train)\ntfidf_transformer = TfidfTransformer()\nX_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)\n\nclf = MultinomialNB().fit(X_train_tfidf, y_train)",
"_____no_output_____"
],
[
"print(clf.predict(count_vect.transform([\"This company refuses to provide me verification and validation of debt per my right under the FDCPA. I do not believe this debt is mine.\"])))",
"_____no_output_____"
],
[
"print(clf.predict(count_vect.transform([\"I am disputing the inaccurate information the Chex-Systems has on my credit report. I initially submitted a police report on XXXX/XXXX/16 and Chex Systems only deleted the items that I mentioned in the letter and not all the items that were actually listed on the police report. In other words they wanted me to say word for word to them what items were fraudulent. The total disregard of the police report and what accounts that it states that are fraudulent. If they just had paid a little closer attention to the police report I would not been in this position now and they would n't have to research once again. I would like the reported information to be removed : XXXX XXXX XXXX\"])))",
"_____no_output_____"
],
[
"df[df['Consumer_complaint_narrative'] == \"This company refuses to provide me verification and validation of debt per my right under the FDCPA. I do not believe this debt is mine.\"]",
"_____no_output_____"
],
[
"df[df['Consumer_complaint_narrative'] == \"I am disputing the inaccurate information the Chex-Systems has on my credit report. I initially submitted a police report on XXXX/XXXX/16 and Chex Systems only deleted the items that I mentioned in the letter and not all the items that were actually listed on the police report. In other words they wanted me to say word for word to them what items were fraudulent. The total disregard of the police report and what accounts that it states that are fraudulent. If they just had paid a little closer attention to the police report I would not been in this position now and they would n't have to research once again. I would like the reported information to be removed : XXXX XXXX XXXX\"]",
"_____no_output_____"
],
[
"rom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.svm import LinearSVC\n\nfrom sklearn.model_selection import cross_val_score\n\n\nmodels = [\n RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0),\n LinearSVC(),\n MultinomialNB(),\n LogisticRegression(random_state=0),\n]\nCV = 5\ncv_df = pd.DataFrame(index=range(CV * len(models)))\nentries = []\nfor model in models:\n model_name = model.__class__.__name__\n accuracies = cross_val_score(model, features, labels, scoring='accuracy', cv=CV)\n for fold_idx, accuracy in enumerate(accuracies):\n entries.append((model_name, fold_idx, accuracy))\ncv_df = pd.DataFrame(entries, columns=['model_name', 'fold_idx', 'accuracy'])",
"_____no_output_____"
],
[
"import seaborn as sns\n\nsns.boxplot(x='model_name', y='accuracy', data=cv_df)\nsns.stripplot(x='model_name', y='accuracy', data=cv_df, \n size=8, jitter=True, edgecolor=\"gray\", linewidth=2)\nplt.show()",
"_____no_output_____"
],
[
"cv_df.groupby('model_name').accuracy.mean()\n",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nmodel = LinearSVC()\n\nX_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(features, labels, df.index, test_size=0.33, random_state=0)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import confusion_matrix\n\nconf_mat = confusion_matrix(y_test, y_pred)\nfig, ax = plt.subplots(figsize=(8,6))\nsns.heatmap(conf_mat, annot=True, fmt='d',\n xticklabels=category_id_df.Product.values, yticklabels=category_id_df.Product.values)\nplt.ylabel('Actual')\nplt.xlabel('Predicted')\nplt.show()",
"_____no_output_____"
],
[
"from IPython.display import display\n\nfor predicted in category_id_df.category_id:\n for actual in category_id_df.category_id:\n if predicted != actual and conf_mat[actual, predicted] >= 6:\n print(\"'{}' predicted as '{}' : {} examples.\".format(id_to_category[actual], id_to_category[predicted], conf_mat[actual, predicted]))\n display(df.loc[indices_test[(y_test == actual) & (y_pred == predicted)]][['Product', 'Consumer_complaint_narrative']])\n print('')",
"_____no_output_____"
],
[
"model.fit(features, labels)\n",
"_____no_output_____"
],
[
"from sklearn.feature_selection import chi2\n\nN = 2\nfor Product, category_id in sorted(category_to_id.items()):\n indices = np.argsort(model.coef_[category_id])\n feature_names = np.array(tfidf.get_feature_names())[indices]\n unigrams = [v for v in reversed(feature_names) if len(v.split(' ')) == 1][:N]\n bigrams = [v for v in reversed(feature_names) if len(v.split(' ')) == 2][:N]\n print(\"# '{}':\".format(Product))\n print(\" . Top unigrams:\\n . {}\".format('\\n . '.join(unigrams)))\n print(\" . Top bigrams:\\n . {}\".format('\\n . '.join(bigrams)))",
"_____no_output_____"
],
[
"texts = [\"I requested a home loan modification through Bank of America. Bank of America never got back to me.\",\n \"It has been difficult for me to find my past due balance. I missed a regular monthly payment\",\n \"I can't get the money out of the country.\",\n \"I have no money to pay my tuition\",\n \"Coinbase closed my account for no reason and furthermore refused to give me a reason despite dozens of request\"]\ntext_features = tfidf.transform(texts)\npredictions = model.predict(text_features)\nfor text, predicted in zip(texts, predictions):\n print('\"{}\"'.format(text))\n print(\" - Predicted as: '{}'\".format(id_to_category[predicted]))\n print(\"\")",
"_____no_output_____"
],
[
"from sklearn import metrics\nprint(metrics.classification_report(y_test, y_pred, \n target_names=df['category'].unique()))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece3a76940ecdb635df2150b9a9725893f7caab0 | 78,896 | ipynb | Jupyter Notebook | Historic_Prediction.ipynb | AksanBA/March_Madness | 109bcfb5825997c78ae2b9363625d71407f06cd5 | [
"MIT"
] | null | null | null | Historic_Prediction.ipynb | AksanBA/March_Madness | 109bcfb5825997c78ae2b9363625d71407f06cd5 | [
"MIT"
] | null | null | null | Historic_Prediction.ipynb | AksanBA/March_Madness | 109bcfb5825997c78ae2b9363625d71407f06cd5 | [
"MIT"
] | null | null | null | 53.416385 | 21,416 | 0.651427 | [
[
[
"import pandas as pd\nimport numpy as np\nimport collections\nimport sys\nfrom sklearn.linear_model import LogisticRegression\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom sklearn import linear_model\nfrom sklearn import svm\nfrom sklearn.svm import SVC\nfrom sklearn import tree\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import GradientBoostingRegressor\nimport csv\n%matplotlib inline",
"_____no_output_____"
],
[
"## Read in dataframes \ndata_dir = './DataFiles/'\n# This file provides a master list of cities that have been locations for games played.\ndf_cities = pd.read_csv(data_dir + 'Cities.csv')\ndf_conferences = pd.read_csv(data_dir + 'Conferences.csv')\ndf_conferencetourney = pd.read_csv(data_dir + 'ConferenceTourneyGames.csv')\ndf_gamecities = pd.read_csv(data_dir + 'GameCities.csv')\ndf_tourneycompact = pd.read_csv(data_dir + 'NCAATourneyCompactResults.csv')\ndf_tourneydetailed = pd.read_csv(data_dir + 'NCAATourneyDetailedResults.csv')\ndf_tourneyseedroundslots = pd.read_csv(data_dir + 'NCAATourneySeedRoundSlots.csv')\ndf_tourneyseeds = pd.read_csv(data_dir + 'NCAATourneySeeds.csv')\ndf_tourneyslots = pd.read_csv(data_dir + 'NCAATourneySlots.csv')\ndf_seasoncompact = pd.read_csv(data_dir + 'RegularSeasonCompactResults.csv')\ndf_seasondetailed = pd.read_csv(data_dir + 'RegularSeasonDetailedResults.csv')\ndf_seasons = pd.read_csv(data_dir + 'Seasons.csv')\ndf_secondtourneycompact = pd.read_csv(data_dir + 'SecondaryTourneyCompactResults.csv')\ndf_coaches = pd.read_csv(data_dir + 'TeamCoaches.csv')\ndf_teamconferences = pd.read_csv(data_dir + 'TeamConferences.csv')\ndf_teams = pd.read_csv(data_dir + 'Teams.csv')\n# df_teamspellings = pd.read_csv(data_dir + 'TeamSpellings.csv') utf-8 encoding issue\n\ndf_teams.head()",
"_____no_output_____"
],
[
"def handleDifferentCSV(df):\n # The stats CSV is a lit different in terms of naming so below is just some data cleaning\n df['School'] = df['School'].replace('(State)', 'St', regex=True) \n df['School'] = df['School'].replace('Albany (NY)', 'Albany NY') \n df['School'] = df['School'].replace('Boston University', 'Boston Univ')\n df['School'] = df['School'].replace('Central Michigan', 'C Michigan')\n df['School'] = df['School'].replace('(Eastern)', 'E', regex=True)\n df['School'] = df['School'].replace('Louisiana St', 'LSU')\n df['School'] = df['School'].replace('North Carolina St', 'NC State')\n df['School'] = df['School'].replace('Southern California', 'USC')\n df['School'] = df['School'].replace('University of California', 'California', regex=True) \n df['School'] = df['School'].replace('American', 'American Univ')\n df['School'] = df['School'].replace('Arkansas-Little Rock', 'Ark Little Rock')\n df['School'] = df['School'].replace('Arkansas-Pine Bluff', 'Ark Pine Bluff')\n df['School'] = df['School'].replace('Bowling Green St', 'Bowling Green')\n df['School'] = df['School'].replace('Brigham Young', 'BYU')\n df['School'] = df['School'].replace('Cal Poly', 'Cal Poly SLO')\n df['School'] = df['School'].replace('Centenary (LA)', 'Centenary')\n df['School'] = df['School'].replace('Central Connecticut St', 'Central Conn')\n df['School'] = df['School'].replace('Charleston Southern', 'Charleston So')\n df['School'] = df['School'].replace('Coastal Carolina', 'Coastal Car')\n df['School'] = df['School'].replace('College of Charleston', 'Col Charleston')\n df['School'] = df['School'].replace('Cal St Fullerton', 'CS Fullerton')\n df['School'] = df['School'].replace('Cal St Sacramento', 'CS Sacramento')\n df['School'] = df['School'].replace('Cal St Bakersfield', 'CS Bakersfield')\n df['School'] = df['School'].replace('Cal St Northridge', 'CS Northridge')\n df['School'] = df['School'].replace('East Tennessee St', 'ETSU')\n df['School'] = df['School'].replace('Detroit Mercy', 'Detroit')\n df['School'] = df['School'].replace('Fairleigh Dickinson', 'F Dickinson')\n df['School'] = df['School'].replace('Florida Atlantic', 'FL Atlantic')\n df['School'] = df['School'].replace('Florida Gulf Coast', 'FL Gulf Coast')\n df['School'] = df['School'].replace('Florida International', 'Florida Intl')\n df['School'] = df['School'].replace('George Washington', 'G Washington')\n df['School'] = df['School'].replace('Georgia Southern', 'Ga Southern')\n df['School'] = df['School'].replace('Gardner-Webb', 'Gardner Webb')\n df['School'] = df['School'].replace('Illinois-Chicago', 'IL Chicago')\n df['School'] = df['School'].replace('Kent St', 'Kent')\n df['School'] = df['School'].replace('Long Island University', 'Long Island')\n df['School'] = df['School'].replace('Loyola Marymount', 'Loy Marymount')\n df['School'] = df['School'].replace('Loyola (MD)', 'Loyola MD')\n df['School'] = df['School'].replace('Loyola (IL)', 'Loyola-Chicago')\n df['School'] = df['School'].replace('Massachusetts', 'MA Lowell')\n df['School'] = df['School'].replace('Maryland-Eastern Shore', 'MD E Shore')\n df['School'] = df['School'].replace('Miami (FL)', 'Miami FL')\n df['School'] = df['School'].replace('Miami (OH)', 'Miami OH')\n df['School'] = df['School'].replace('Missouri-Kansas City', 'Missouri KC')\n df['School'] = df['School'].replace('Monmouth', 'Monmouth NJ')\n df['School'] = df['School'].replace('Mississippi Valley St', 'MS Valley St')\n df['School'] = df['School'].replace('Montana St', 'MTSU')\n df['School'] = df['School'].replace('Northern Colorado', 'N Colorado')\n df['School'] = df['School'].replace('North Dakota St', 'N Dakota St')\n df['School'] = df['School'].replace('Northern Illinois', 'N Illinois')\n df['School'] = df['School'].replace('Northern Kentucky', 'N Kentucky')\n df['School'] = df['School'].replace('North Carolina A&T', 'NC A&T')\n df['School'] = df['School'].replace('North Carolina Central', 'NC Central')\n df['School'] = df['School'].replace('Pennsylvania', 'Penn')\n df['School'] = df['School'].replace('South Carolina St', 'S Carolina St')\n df['School'] = df['School'].replace('Southern Illinois', 'S Illinois')\n df['School'] = df['School'].replace('UC-Santa Barbara', 'Santa Barbara')\n df['School'] = df['School'].replace('Southeastern Louisiana', 'SE Louisiana')\n df['School'] = df['School'].replace('Southeast Missouri St', 'SE Missouri St')\n df['School'] = df['School'].replace('Stephen F. Austin', 'SF Austin')\n df['School'] = df['School'].replace('Southern Methodist', 'SMU')\n df['School'] = df['School'].replace('Southern Mississippi', 'Southern Miss')\n df['School'] = df['School'].replace('Southern', 'Southern Univ')\n df['School'] = df['School'].replace('St. Bonaventure', 'St Bonaventure')\n df['School'] = df['School'].replace('St. Francis (NY)', 'St Francis NY')\n df['School'] = df['School'].replace('Saint Francis (PA)', 'St Francis PA')\n df['School'] = df['School'].replace('St. John\\'s (NY)', 'St John\\'s')\n df['School'] = df['School'].replace('Saint Joseph\\'s', 'St Joseph\\'s PA')\n df['School'] = df['School'].replace('Saint Louis', 'St Louis')\n df['School'] = df['School'].replace('Saint Mary\\'s (CA)', 'St Mary\\'s CA')\n df['School'] = df['School'].replace('Mount Saint Mary\\'s', 'Mt St Mary\\'s')\n df['School'] = df['School'].replace('Saint Peter\\'s', 'St Peter\\'s')\n df['School'] = df['School'].replace('Texas A&M-Corpus Christian', 'TAM C. Christian')\n df['School'] = df['School'].replace('Texas Christian', 'TCU')\n df['School'] = df['School'].replace('Tennessee-Martin', 'TN Martin')\n df['School'] = df['School'].replace('Texas-Rio Grande Valley', 'UTRGV')\n df['School'] = df['School'].replace('Texas Southern', 'TX Southern')\n df['School'] = df['School'].replace('Alabama-Birmingham', 'UAB')\n df['School'] = df['School'].replace('UC-Davis', 'UC Davis')\n df['School'] = df['School'].replace('UC-Irvine', 'UC Irvine')\n df['School'] = df['School'].replace('UC-Riverside', 'UC Riverside')\n df['School'] = df['School'].replace('Central Florida', 'UCF')\n df['School'] = df['School'].replace('Louisiana-Lafayette', 'ULL')\n df['School'] = df['School'].replace('Louisiana-Monroe', 'ULM')\n df['School'] = df['School'].replace('Maryland-Baltimore County', 'UMBC')\n df['School'] = df['School'].replace('North Carolina-Asheville', 'UNC Asheville')\n df['School'] = df['School'].replace('North Carolina-Greensboro', 'UNC Greensboro')\n df['School'] = df['School'].replace('North Carolina-Wilmington', 'UNC Wilmington')\n df['School'] = df['School'].replace('Nevada-Las Vegas', 'UNLV')\n df['School'] = df['School'].replace('Texas-Arlington', 'UT Arlington')\n df['School'] = df['School'].replace('Texas-San Antonio', 'UT San Antonio')\n df['School'] = df['School'].replace('Texas-El Paso', 'UTEP')\n df['School'] = df['School'].replace('Virginia Commonwealth', 'VA Commonwealth')\n df['School'] = df['School'].replace('Western Carolina', 'W Carolina')\n df['School'] = df['School'].replace('Western Illinois', 'W Illinois')\n df['School'] = df['School'].replace('Western Kentucky', 'WKU')\n df['School'] = df['School'].replace('Western Michigan', 'W Michigan')\n df['School'] = df['School'].replace('Abilene Christian', 'Abilene Chr')\n df['School'] = df['School'].replace('Montana State', 'Montana St')\n df['School'] = df['School'].replace('Central Arkansas', 'Cent Arkansas')\n df['School'] = df['School'].replace('Houston Baptist', 'Houston Bap')\n df['School'] = df['School'].replace('South Dakota St', 'S Dakota St')\n df['School'] = df['School'].replace('Maryland-Eastern Shore', 'MD E Shore')\n return df",
"_____no_output_____"
],
[
"def getTeamName(team_id):\n return df_teams[df_teams['TeamID'] == team_id].values[0][1]\ngetTeamName(1200)",
"_____no_output_____"
],
[
"df_year = df_seasoncompact[df_seasoncompact['Season'] == 2010]\ndf_year2 = df_seasondetailed[df_seasondetailed['Season'] == 2010]\n#df_year.info()\ngamesWon = df_year[df_year.WTeamID == 1120] \ngamesWon2 = df_year2[df_year2.WTeamID == 1120] \nprint(gamesWon.head(10))\n#print(gamesWon2.head(10))",
" Season DayNum WTeamID WScore LTeamID LScore WLoc NumOT\n108134 2010 11 1120 69 1310 65 H 0\n108535 2010 19 1120 80 1237 65 N 0\n108770 2010 23 1120 75 1219 54 H 0\n109033 2010 29 1120 87 1105 52 N 0\n109322 2010 35 1120 68 1438 67 H 0\n109795 2010 50 1120 94 1106 78 H 0\n109976 2010 57 1120 77 1149 62 H 0\n110135 2010 61 1120 95 1204 75 H 0\n110991 2010 79 1120 84 1261 80 A 0\n111458 2010 89 1120 58 1104 57 H 0\n"
],
[
"tourneyYear = df_tourneyseeds[df_tourneyseeds['Season'] == 2010]\nseed = tourneyYear[tourneyYear['TeamID'] == 1246]\nif (len(seed.index) != 0):\n seed = seed.values[0][1]\n tournamentSeed = int(seed[1:3])\n \ntournamentSeed",
"_____no_output_____"
],
[
"def getSeasonData(team_id, year):\n # The data frame below holds stats for every single game in the given year\n df_year = df_seasondetailed[df_seasondetailed['Season'] == year]\n \n df_stats_SOS = pd.read_csv('./RegSeasonStats/MMStats_'+str(year)+'.csv')\n df_stats_SOS = handleDifferentCSV(df_stats_SOS)\n df_ratings = pd.read_csv('./RatingStats/RatingStats_'+str(year)+'.csv')\n df_ratings = handleDifferentCSV(df_ratings)\n \n name = getTeamName(team_id)\n team = df_stats_SOS[df_stats_SOS['School'] == name]\n team_rating = df_ratings[df_ratings['School'] == name]\n \n \n # Finding number of points per game\n gamesWon = df_year[df_year.WTeamID == team_id] \n totalPoints = gamesWon['WScore'].sum()\n gamesLost = df_year[df_year.LTeamID == team_id] \n totalGames = gamesWon.append(gamesLost)\n numGames = len(totalGames.index)\n totalPoints += gamesLost['LScore'].sum()\n \n # Finding number of points per game allowed\n totalPointsAllowed = gamesWon['LScore'].sum()\n totalPointsAllowed += gamesLost['WScore'].sum()\n \n #FGM - field goals made\n totalFGM = gamesWon['WFGM'].sum()\n totalFGM += gamesLost['LFGM'].sum()\n \n #FGM - field goals made (by opponent)\n totalOppFGM = gamesWon['LFGM'].sum()\n totalOppFGM += gamesLost['WFGM'].sum()\n \n #FGA - field goals attempted\n totalFGA = gamesWon['WFGA'].sum()\n totalFGA += gamesLost['LFGA'].sum()\n \n #FGA - field goals attempted (by opponent)\n totalOppFGA = gamesWon['LFGA'].sum()\n totalOppFGA += gamesLost['WFGA'].sum()\n \n #FGM3 - three pointers made\n totalFGM3 = gamesWon['WFGM3'].sum()\n totalFGM3 += gamesLost['LFGM3'].sum()\n \n #FGM3 - three pointers made (by opponent)\n totalOppFGM3 = gamesWon['LFGM3'].sum()\n totalOppFGM3 += gamesLost['WFGM3'].sum()\n \n #FGA3 - three pointers attempted\n totalFGA3 = gamesWon['WFGA3'].sum()\n totalFGA3 += gamesLost['LFGA3'].sum()\n \n #FGA3 - three pointers attempted (by opponent)\n totalOppFGA3 = gamesWon['LFGA3'].sum()\n totalOppFGA3 += gamesLost['WFGA3'].sum()\n \n #FTM - free throws made\n totalFTM = gamesWon['WFTM'].sum()\n totalFTM += gamesLost['LFTM'].sum()\n \n #FTM - free throws made (by opponent)\n totalOppFTM = gamesWon['LFTM'].sum()\n totalOppFTM += gamesLost['WFTM'].sum()\n \n #FTA - free throws attempted\n totalFTA = gamesWon['WFTA'].sum()\n totalFTA += gamesLost['LFTA'].sum()\n \n #FTA - free throws attempted (by opponent)\n totalOppFTA = gamesWon['LFTA'].sum()\n totalOppFTA += gamesLost['WFTA'].sum()\n \n #OR - offensive rebounds\n totalOR = gamesWon['WOR'].sum()\n totalOR += gamesLost['LOR'].sum()\n \n #OR - offensive rebounds (by opponent)\n totalOppOR = gamesWon['LOR'].sum()\n totalOppOR += gamesLost['WOR'].sum()\n \n #DR - defensive rebounds\n totalDR = gamesWon['WDR'].sum()\n totalDR += gamesLost['LDR'].sum()\n \n #DR - defensive rebounds (by opponent)\n totalOppDR = gamesWon['LDR'].sum()\n totalOppDR += gamesLost['WDR'].sum()\n \n #Ast - assists\n totalAst = gamesWon['WAst'].sum()\n totalAst += gamesLost['LAst'].sum()\n \n #Ast - assists (by opponent)\n totalOppAst = gamesWon['LAst'].sum()\n totalOppAst += gamesLost['WAst'].sum()\n \n #TO - turnovers committed\n totalTO = gamesWon['WTO'].sum()\n totalTO += gamesLost['LTO'].sum()\n \n #TO - turnovers committed (by opponent)\n totalOppTO = gamesWon['LTO'].sum()\n totalOppTO += gamesLost['WTO'].sum()\n \n #Stl - steals\n totalStl = gamesWon['WStl'].sum()\n totalStl += gamesLost['LStl'].sum()\n \n #Stl - steals (by opponent)\n totalOppStl = gamesWon['LStl'].sum()\n totalOppStl += gamesLost['WStl'].sum()\n \n #Blk - blocks\n totalBlk = gamesWon['WBlk'].sum()\n totalBlk += gamesLost['LBlk'].sum()\n \n #Blk - blocks (by opponent)\n totalOppBlk = gamesWon['LBlk'].sum()\n totalOppBlk += gamesLost['WBlk'].sum()\n \n #PF - personal fouls committed\n totalPF = gamesWon['WPF'].sum()\n totalPF += gamesLost['LPF'].sum()\n \n #PF - personal fouls committed (by opponent)\n totalOppPF = gamesWon['LPF'].sum()\n totalOppPF += gamesLost['WPF'].sum()\n \n #Finding tournament seed for that year\n tourneyYear = df_tourneyseeds[df_tourneyseeds['Season'] == year]\n seed = tourneyYear[tourneyYear['TeamID'] == team_id]\n if (len(seed.index) != 0):\n seed = seed.values[0][1]\n tournamentSeed = int(seed[1:3])\n else:\n tournamentSeed = 25\n \n # Finding number of wins and losses\n numWins = len(gamesWon.index)\n \n # Creating averages\n if numGames == 0 or len(team_rating.index) == 0:\n avgPoints = 0\n avgPointsAllowed = 0 \n avgFGM = 0\n avgOppFGM = 0\n avgFGA = 0\n avgOppFGA = 0\n avgFGM3 = 0\n avgOppFGM3 = 0\n avgFGA3 = 0\n avgOppFGA3 = 0\n avgFTM = 0\n avgOppFTM = 0\n avgFTA = 0\n avgOppFTA = 0\n avgOR = 0\n avgOppOR = 0\n avgDR = 0\n avgOppDR = 0\n avgAst = 0\n avgOppAst = 0\n avgTO = 0\n avgOppTO = 0\n avgStl = 0\n avgOppStl = 0\n avgBlk = 0\n avgOppBlk = 0\n avgPF = 0\n avgOppPF = 0\n tournamentSeed = 0\n sos = 0\n srs = 0\n else:\n avgPoints = totalPoints/numGames\n avgPointsAllowed = totalPointsAllowed/numGames\n avgFGM = totalFGM/numGames\n avgOppFGM = totalOppFGM/numGames\n avgFGA = totalFGA/numGames\n avgOppFGA = totalOppFGA/numGames\n avgFGM3 = totalFGM3/numGames\n avgOppFGM3 = totalOppFGM3/numGames\n avgFGA3 = totalFGA3/numGames\n avgOppFGA3 = totalOppFGA3/numGames\n avgFTM = totalFTM/numGames\n avgOppFTM = totalOppFTM/numGames\n avgFTA = totalFTA/numGames\n avgOppFTA = totalOppFTA/numGames\n avgOR = totalOR/numGames\n avgOppOR = totalOppOR/numGames\n avgDR = totalDR/numGames\n avgOppDR = totalOppDR/numGames\n avgAst = totalAst/numGames\n avgOppAst = totalOppAst/numGames\n avgTO = totalTO/numGames\n avgOppTO = totalOppTO/numGames\n avgStl = totalStl/numGames\n avgOppStl = totalOppStl/numGames\n avgBlk = totalBlk/numGames\n avgOppBlk = totalOppBlk/numGames\n avgPF = totalPF/numGames\n avgOppPF = totalOppPF/numGames\n sos = team['SOS'].values[0]\n srs = team['SRS'].values[0]\n \n\n #return gamesLost\n return [numWins, avgPoints, avgPointsAllowed, avgFGM, avgOppFGM, avgFGA, avgOppFGA, avgFGM3, avgOppFGM3, avgFGA3, avgOppFGA3,\n avgFTM, avgOppFTM, avgFTA, avgOppFTA, avgOR, avgOppOR, avgDR, avgOppDR, avgAst, avgOppAst, avgTO, avgOppTO, avgStl,\n avgOppStl, avgBlk, avgOppBlk, avgPF, avgOppPF, tournamentSeed, sos, srs]\n \n #return [numWins]",
"_____no_output_____"
],
[
"#getSeasonData(1246, 2010) #Kentucky",
"_____no_output_____"
],
[
"#getSeasonData(1242, 2016) #Kansas",
"_____no_output_____"
],
[
"def compareTwoTeams(id_1, id_2, year):\n team_1 = getSeasonData(id_1, year)\n team_2 = getSeasonData(id_2, year)\n diff = [a - b for a, b in zip(team_1, team_2)]\n return diff",
"_____no_output_____"
],
[
"#compareTwoTeams(1246,1452, 2010)",
"_____no_output_____"
],
[
"teamList = df_teams['TeamName'].tolist()\n\ndef createSeasonDict(year):\n seasonDictionary = collections.defaultdict(list)\n for team in teamList:\n team_id = df_teams[df_teams['TeamName'] == team].values[0][0]\n team_vector = getSeasonData(team_id, year)\n seasonDictionary[team_id] = team_vector\n return seasonDictionary\n",
"_____no_output_____"
],
[
"def getHomeStat(row):\n if (row == 'H'):\n home = 1\n if (row == 'A'):\n home = -1\n if (row == 'N'):\n home = 0\n return home",
"_____no_output_____"
],
[
"def createTrainingSet(years):\n totalNumGames = 0\n for year in years:\n season = df_seasoncompact[df_seasoncompact['Season'] == year]\n totalNumGames += len(season.index)\n tourney = df_tourneycompact[df_tourneycompact['Season'] == year]\n totalNumGames += len(tourney.index)\n numFeatures = len(getSeasonData(1246,2010))\n #xTrain = np.zeros((totalNumGames, numFeatures + 1))\n #yTrain = np.zeros((totalNumGames))\n xTrain=[]\n yTrain=[]\n indexCounter = 0\n for year in years:\n team_vectors = createSeasonDict(year)\n season = df_seasoncompact[df_seasoncompact['Season'] == year]\n numGamesInSeason = len(season.index)\n tourney = df_tourneycompact[df_tourneycompact['Season'] == year]\n numGamesInSeason += len(tourney.index)\n #xTrainSeason = np.zeros(( numGamesInSeason, numFeatures + 1))\n #yTrainSeason = np.zeros(( numGamesInSeason ))\n xTrainSeason = []\n yTrainSeason = []\n counter = 0\n for index, row in season.iterrows():\n w_team = row['WTeamID']\n w_vector = team_vectors[w_team]\n #if w_vector is np.any(w_vector): #check if w_vector contains only zeros\n # continue\n if all([x == 0 for x in w_vector]):\n continue\n l_team = row['LTeamID']\n l_vector = team_vectors[l_team]\n diff = [a - b for a, b in zip(w_vector, l_vector)]\n home = getHomeStat(row['WLoc'])\n if (counter % 2 == 0):\n diff.append(home) \n #xTrainSeason[counter] = diff\n #yTrainSeason[counter] = 1\n xTrainSeason.append(diff)\n yTrainSeason.append(1)\n else:\n diff.append(-home)\n #xTrainSeason[counter] = [ -p for p in diff]\n #yTrainSeason[counter] = 0\n xTrainSeason.append([-p for p in diff])\n yTrainSeason.append(0)\n counter += 1\n for index, row in tourney.iterrows():\n w_team = row['WTeamID']\n w_vector = team_vectors[w_team]\n #if w_vector is np.any(w_vector): #check if w_vector contains only zeros\n # continue\n if all([x == 0 for x in w_vector]):\n continue\n l_team = row['LTeamID']\n l_vector = team_vectors[l_team]\n diff = [a - b for a, b in zip(w_vector, l_vector)]\n home = 0 #All tournament games are neutral\n if (counter % 2 == 0):\n diff.append(home) \n #xTrainSeason[counter] = diff\n #yTrainSeason[counter] = 1\n xTrainSeason.append(diff)\n yTrainSeason.append(1)\n else:\n diff.append(-home)\n #xTrainSeason[counter] = [ -p for p in diff]\n #yTrainSeason[counter] = 0\n xTrainSeason.append([-p for p in diff])\n yTrainSeason.append(0)\n counter += 1\n xTrain[indexCounter:numGamesInSeason+indexCounter] = xTrainSeason\n yTrain[indexCounter:numGamesInSeason+indexCounter] = yTrainSeason\n indexCounter += numGamesInSeason\n #xTrain[(xTrain != 0).sum(axis=1) >= 5, :]\n #xTrain[:,:29][~np.all(xTrain == 0, axis=1)]\n xTrain = np.array(xTrain)\n yTrain = np.array(yTrain)\n return xTrain, yTrain",
"_____no_output_____"
]
],
[
[
"## Testing",
"_____no_output_____"
]
],
[
[
"numFeatures = len(getSeasonData(1246,2010))\nprint(numFeatures)\nteam_vectors = createSeasonDict(2016)\nseason = df_seasoncompact[df_seasoncompact['Season'] == 2016]\nnumGamesInSeason = len(season.index)\ntourney = df_tourneycompact[df_tourneycompact['Season'] == 2016]\nnumGamesInSeason += len(tourney.index)\nxTrainSeason = np.zeros(( numGamesInSeason, numFeatures + 1))\nyTrainSeason = np.zeros(( numGamesInSeason ))\ncounter = 0\nfor index, row in season.iterrows():\n w_team = row['WTeamID']\n w_vector = team_vectors[w_team]\n l_team = row['LTeamID']\n l_vector = team_vectors[l_team]\n diff = [a - b for a, b in zip(w_vector, l_vector)]\n home = getHomeStat(row['WLoc'])\n if (counter % 2 == 0):\n diff.append(home) \n xTrainSeason[counter] = diff\n yTrainSeason[counter] = 1\n else:\n diff.append(-home)\n xTrainSeason[counter] = [-p for p in diff]\n yTrainSeason[counter] = 0\n counter += 1\n\n#np.savetxt(\"xTrainSeason2016.csv\", xTrainSeason, delimiter=\",\")\nprint(season.iloc[2,:])\nprint(team_vectors[1112])\nprint(team_vectors[1334])\ndiff = [a - b for a, b in zip(team_vectors[1112], team_vectors[1334])]\nprint(diff)\nprint(xTrainSeason[2])",
"32\nSeason 2016\nDayNum 11\nWTeamID 1112\nWScore 79\nLTeamID 1334\nLScore 61\nWLoc H\nNumOT 0\nName: 139922, dtype: object\n[25, 81.21212121212122, 69.0, 28.060606060606062, 25.12121212121212, 58.24242424242424, 60.81818181818182, 6.515151515151516, 6.090909090909091, 17.03030303030303, 18.96969696969697, 18.575757575757574, 12.666666666666666, 25.696969696969695, 17.78787878787879, 11.636363636363637, 9.484848484848484, 28.606060606060606, 21.545454545454547, 14.515151515151516, 12.212121212121213, 12.818181818181818, 11.606060606060606, 4.909090909090909, 5.393939393939394, 4.787878787878788, 3.4545454545454546, 18.21212121212121, 22.0, 6, 7.23, 18.79]\n[6, 68.5, 74.42307692307692, 23.807692307692307, 23.923076923076923, 55.34615384615385, 55.19230769230769, 6.576923076923077, 7.423076923076923, 20.423076923076923, 20.26923076923077, 14.307692307692308, 19.153846153846153, 21.26923076923077, 27.192307692307693, 10.038461538461538, 10.461538461538462, 24.923076923076923, 25.153846153846153, 12.153846153846153, 12.846153846153847, 13.692307692307692, 11.384615384615385, 4.076923076923077, 5.884615384615385, 2.4615384615384617, 3.3461538461538463, 23.384615384615383, 20.53846153846154, 25, 2.35, -3.57]\n[19, 12.712121212121218, -5.42307692307692, 4.252913752913756, 1.1981351981351978, 2.8962703962703955, 5.625874125874127, -0.06177156177156107, -1.3321678321678325, -3.392773892773892, -1.2995337995338012, 4.268065268065266, -6.487179487179487, 4.427738927738925, -9.404428904428904, 1.5979020979020984, -0.9766899766899773, 3.682983682983682, -3.6083916083916066, 2.3613053613053623, -0.6340326340326339, -0.8741258741258733, 0.2214452214452205, 0.8321678321678325, -0.49067599067599144, 2.3263403263403264, 0.10839160839160833, -5.172494172494172, 1.46153846153846, -19, 4.880000000000001, 22.36]\n[ 19. 12.71212121 -5.42307692 4.25291375 1.1981352\n 2.8962704 5.62587413 -0.06177156 -1.33216783 -3.39277389\n -1.2995338 4.26806527 -6.48717949 4.42773893 -9.4044289\n 1.5979021 -0.97668998 3.68298368 -3.60839161 2.36130536\n -0.63403263 -0.87412587 0.22144522 0.83216783 -0.49067599\n 2.32634033 0.10839161 -5.17249417 1.46153846 -19.\n 4.88 22.36 1. ]\n"
],
[
"years = range(2010,2013)\nxTrain, yTrain = createTrainingSet(years)\n#np.save('xTrain', xTrain)\n#np.save('yTrain', yTrain)\nprint(xTrain)",
"[[ -5. 1.87594697 7.36268939 ... 12.15 8.6\n 1. ]\n [-10. -7.83266129 4.6875 ... -12.57 -22.95\n 1. ]\n [ 25. 13.59013283 -20.79411765 ... 16.37 49.85\n 1. ]\n ...\n [ 0. -0.26559715 -2.88057041 ... -0.86 2.23\n 0. ]\n [ 6. 7.84789916 -2.17142857 ... -1.09 8.54\n 0. ]\n [ -5. -1.64616756 2.93939394 ... 2. -3.01\n 0. ]]\n"
],
[
"xTrain.shape, yTrain.shape\nxTrain\n#np.savetxt(\"xTrain.csv\", xTrain, delimiter=\",\")\n#np.savetxt(\"yTrain.csv\", yTrain, delimiter=\",\")",
"_____no_output_____"
],
[
"#xTrain.shape",
"_____no_output_____"
],
[
"#x = createSeasonDict(2016)",
"_____no_output_____"
],
[
"#x[1109] - zeros\n#1101 - not zeros\n#print(x)\n#all([y == 0 for y in x[1109]])",
"_____no_output_____"
]
],
[
[
"## Loading Data",
"_____no_output_____"
]
],
[
[
"years = range(2014,2018)\nxTrain, yTrain = createTrainingSet(years)\n#np.save('xTrain', xTrain)\n#np.save('yTrain', yTrain)\n#xTrain = np.load('PrecomputedMatrices/xTrain.npy')\n#yTrain = np.load('PrecomputedMatrices/yTrain.npy')",
"_____no_output_____"
],
[
"xTrain.shape, yTrain.shape",
"_____no_output_____"
]
],
[
[
"## Prelim Model Work",
"_____no_output_____"
]
],
[
[
"model4 = RandomForestClassifier(n_estimators=200)\nmodel2 = linear_model.BayesianRidge()\nmodel5 = AdaBoostClassifier(n_estimators=100)\nmodel = GradientBoostingRegressor(n_estimators=100)\nmodel3 = KNeighborsClassifier(n_neighbors=101)",
"_____no_output_____"
],
[
"def showFeatureImportance(my_categories):\n fx_imp = pd.Series(model.feature_importances_, index=my_categories)\n fx_imp /= fx_imp.max()\n fx_imp.sort()\n fx_imp.plot(kind='barh')",
"_____no_output_____"
],
[
"def showDependency(predictions, test, stat, my_categories):\n difference = test[:,my_categories.index(stat)]\n plt.scatter(difference, predictions)\n plt.ylabel('Probability of Team 1 Win')\n plt.xlabel(stat + ' Difference (Team 1 - Team 2)')\n plt.show()",
"_____no_output_____"
],
[
"#categories=['Wins','PPG','PPGA','PowerConf','3PG', 'APG','TOP','Conference Champ','Tourney Conference Champ',\n# 'Seed','SOS','SRS', 'RPG', 'SPG', 'Tourney Appearances','National Championships','Location']\ncategories = ['numWins', 'avgPoints', 'avgPointsAllowed', 'avgFGM', 'avgOppFGM', 'avgFGA', 'avgOppFGA', 'avgFGM3', 'avgOppFGM3', 'avgFGA3', 'avgOppFGA3',\n 'avgFTM', 'avgOppFTM', 'avgFTA', 'avgOppFTA', 'avgOR', 'avgOppOR', 'avgDR', 'avgOppDR', 'avgAst', 'avgOppAst', 'avgTO', 'avgOppTO', 'avgStl',\n 'avgOppStl', 'avgBlk', 'avgOppBlk', 'avgPF', 'avgOppPF', 'tournamentSeed', 'sos', 'srs', 'location']\naccuracy=[]\ntotals=[]\nfor i in range(1):\n X_train, X_test, Y_train, Y_test = train_test_split(xTrain, yTrain)\n results1 = model.fit(X_train, Y_train)\n preds1 = model.predict(X_test)\n \n results2 = model2.fit(X_train, Y_train)\n preds2 = model2.predict(X_test)\n \n results3 = model3.fit(X_train, Y_train)\n preds3 = model3.predict(X_test)\n\n results4 = model4.fit(X_train, Y_train)\n preds4 = model4.predict(X_test)\n \n results5 = model5.fit(X_train, Y_train)\n preds5 = model5.predict(X_test)\n \n preds = (preds1 + preds2 + preds3 + preds4 + preds5)/5\n totals.append(preds)\n preds[preds < .5] = 0\n preds[preds >= .5] = 1\n accuracy.append(np.mean(preds == Y_test))\n #accuracy.append(np.mean(predictions == Y_test))\nprint(\"The accuracy is: \", sum(accuracy)/len(accuracy))\n",
"The accuracy is: 0.7586189126513785\n"
],
[
"showFeatureImportance(categories)",
"/home/aksan/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:4: FutureWarning: sort is deprecated, use sort_values(inplace=True) for INPLACE sorting\n"
]
],
[
[
"## Actual Model",
"_____no_output_____"
]
],
[
[
"#model = tree.DecisionTreeClassifier()\n#model = tree.DecisionTreeRegressor()\n#model = linear_model.LogisticRegression()\n#model = linear_model.BayesianRidge()\n#model = linear_model.Lasso()\nmodel = svm.SVC()\n#model = svm.SVR()\n#model = linear_model.Ridge(alpha = 0.5)\n#model = AdaBoostClassifier(n_estimators=100)\n#model = GradientBoostingClassifier(n_estimators=100)\n#model = GradientBoostingRegressor(n_estimators=100, max_depth=5)\n#model = RandomForestClassifier(n_estimators=64)\n#model = KNeighborsClassifier(n_neighbors=39)\n#neuralNetwork(10)\n#model = VotingClassifier(estimators=[('GBR', model1), ('BR', model2), ('KNN', model3)], voting='soft')\n#model = LinearSVC(penalty='l2', loss='squared_hinge', dual=True, tol=0.0001, C=0.1)",
"_____no_output_____"
],
[
"from sklearn.utils.testing import all_estimators\n\nestimators = all_estimators()\n\nfor name, class_ in estimators:\n if hasattr(class_, 'predict_proba'):\n print(name)",
"/home/aksan/anaconda3/lib/python3.5/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n \"This module will be removed in 0.20.\", DeprecationWarning)\n/home/aksan/anaconda3/lib/python3.5/site-packages/sklearn/grid_search.py:42: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.\n DeprecationWarning)\n/home/aksan/anaconda3/lib/python3.5/site-packages/sklearn/learning_curve.py:22: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the functions are moved. This module will be removed in 0.20\n DeprecationWarning)\n"
],
[
"accuracy=[]\nfor i in range(1):\n X_train, X_test, Y_train, Y_test = train_test_split(xTrain, yTrain)\n results = model.fit(X_train, Y_train)\n preds = model.predict(X_test)\n\n preds[preds < .5] = 0\n preds[preds >= .5] = 1\n accuracy.append(np.mean(preds == Y_test))\n #accuracy.append(np.mean(predictions == Y_test))\n print(\"Finished iteration:\", i)\nprint(\"The accuracy is\", sum(accuracy)/len(accuracy))",
"Finished iteration: 0\nThe accuracy is 0.7632885782600699\n"
],
[
"X_train, X_test, Y_train, Y_test = train_test_split(xTrain, yTrain)\n\nlogreg = linear_model.LogisticRegression()\nparams = {'C': np.logspace(start=-5, stop=3, num=9)}\nclf = GridSearchCV(logreg, params, scoring='neg_log_loss', refit=True)\nclf.fit(X_train, Y_train)\nprint('Best log_loss: {:.4}, with best C: {}'.format(clf.best_score_, clf.best_params_['C']))",
"Best log_loss: -0.4869, with best C: 0.01\n"
],
[
"X_train, X_test, Y_train, Y_test = train_test_split(xTrain, yTrain)\n\nada = AdaBoostClassifier()\nparams = {'n_estimators': np.arange(10,150,10)}\nclf2 = GridSearchCV(ada, params, scoring='neg_log_loss', refit=True)\nclf2.fit(X_train, Y_train)\nprint('Best log_loss: {:.4}, with best num_estimators: {}'.format(clf2.best_score_, clf2.best_params_['n_estimators']))",
"Best log_loss: -0.6426, with best C: 10\n"
],
[
"X_train, X_test, Y_train, Y_test = train_test_split(xTrain, yTrain)\n\ngb = GradientBoostingClassifier()\nparams = {'n_estimators': np.arange(10,150,10), 'max_depth': np.arange(1,5,1)}\nclf3 = GridSearchCV(gb, params, scoring='neg_log_loss', refit=True)\nclf3.fit(X_train, Y_train)\nprint('Best log_loss: {:.4}, with best num_estimators: {} and best max_depth: {}'.format(clf3.best_score_, clf3.best_params_['n_estimators']), clf3.best_params_['max_depth'])\n",
"_____no_output_____"
],
[
"clf3.best_params_['n_estimators']",
"_____no_output_____"
],
[
"X_train, X_test, Y_train, Y_test = train_test_split(xTrain, yTrain)\n\nknn = KNeighborsClassifier()\nparams = {'n_neighbors': np.arange(1,50,1)}\nclf4 = GridSearchCV(knn, params, scoring='neg_log_loss', refit=True)\nclf4.fit(X_train, Y_train)\nprint('Best log_loss: {:.4}, with best num_estimators: {}'.format(clf4.best_score_, clf4.best_params_['n_neighbors']))\n",
"Best log_loss: -0.5068, with best num_estimators: 49\n"
]
],
[
[
"# Applying Model",
"_____no_output_____"
]
],
[
[
"def predictGame(team_1_vector, team_2_vector, home):\n diff = [a - b for a, b in zip(team_1_vector, team_2_vector)]\n diff.append(home)\n #return model.predict([diff]) \n return clf.predict_proba([diff])",
"_____no_output_____"
],
[
"# This was the national championship matchup last year\nteam1_name = 'North Carolina' #1314\nteam2_name = 'Villanova' #1437\nteam1_vector = getSeasonData(df_teams[df_teams['TeamName'] == team1_name].values[0][0], 2016)\nteam2_vector = getSeasonData(df_teams[df_teams['TeamName'] == team2_name].values[0][0], 2016)\nprint('Probability that ' + team1_name + ' wins:', predictGame(team1_vector, team2_vector, 0))\n#team1_vector\n#team2_vector\ndiff = [a - b for a, b in zip(team1_vector, team2_vector)]\ndiff\ndiff.append(0)\nclf.predict_proba([diff])",
"Probability that North Carolina wins: [[0.49724076 0.50275924]]\n"
],
[
"sample_sub_pd = pd.read_csv('SampleSubmissionStage1.csv')\ndef createPrediction():\n results = [[0 for x in range(2)] for x in range(len(sample_sub_pd.index))]\n for index, row in sample_sub_pd.iterrows():\n matchup_id = row['ID']\n year = matchup_id[0:4]\n team1_id = matchup_id[5:9]\n team2_id = matchup_id[10:14]\n team1_vector = getSeasonData(int(team1_id), int(year))\n team2_vector = getSeasonData(int(team2_id), int(year))\n pred = predictGame(team1_vector, team2_vector, 0)\n results[index][0] = matchup_id\n results[index][1] = np.clip(pred[0,1], 0.05, 0.95)\n #results[index][1] = pred[0][1]\n results = pd.np.array(results)\n firstRow = [[0 for x in range(2)] for x in range(1)]\n firstRow[0][0] = 'id'\n firstRow[0][1] = 'pred'\n with open(\"result8.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(firstRow)\n writer.writerows(results)",
"_____no_output_____"
],
[
"createPrediction()",
"_____no_output_____"
],
[
"def getAllTeamVectors():\n year = 2016\n numFeatures = len(getSeasonData(1181,2012))\n numTeams = len(df_teams)\n teamvecs = np.zeros(( numTeams, numFeatures ))\n teams=[]\n counter = 0\n for team in teamList:\n team_id = df_teams[df_teams['TeamName'] == team].values[0][0]\n team_vector = getSeasonData(team_id, year)\n if (team_vector[0] == 0 or team_vector[4] == 0):\n continue\n teamvecs[counter] = team_vector\n teams.append(team)\n counter += 1\n team = pd.np.array(teams)\n team = np.reshape(team, (team.shape[0], 1))\n \n with open(\"allNames.csv\", \"w\") as f:\n writer = csv.writer(f, delimiter=',')\n writer.writerows(team)\n with open(\"allVecs.csv\", \"w\") as f:\n writer = csv.writer(f, delimiter=',')\n writer.writerows(teamvecs)\n with open(\"combine.csv\", \"w\") as f:\n writer = csv.writer(f, delimiter=',')\n writer.writerows([team,teamvecs])\ngetAllTeamVectors()",
"_____no_output_____"
]
]
] | [
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
ece3adbe04ea1255adf4b1e46610a31e1b67e691 | 93,487 | ipynb | Jupyter Notebook | RandomWalk/RandomWalk(n-step).ipynb | Amisha328/reinforcement-learning-implementation | 5fe813f3b97ce1a00c2e7104d1573844121998b6 | [
"MIT"
] | 116 | 2020-10-18T13:55:54.000Z | 2022-03-26T00:26:30.000Z | RandomWalk/RandomWalk(n-step).ipynb | Amisha328/reinforcement-learning-implementation | 5fe813f3b97ce1a00c2e7104d1573844121998b6 | [
"MIT"
] | 5 | 2020-03-23T16:56:26.000Z | 2020-10-04T21:28:11.000Z | RandomWalk/RandomWalk(n-step).ipynb | Amisha328/reinforcement-learning-implementation | 5fe813f3b97ce1a00c2e7104d1573844121998b6 | [
"MIT"
] | 104 | 2019-07-02T03:49:28.000Z | 2020-10-14T07:15:18.000Z | 191.179959 | 75,088 | 0.879106 | [
[
[
"Randow Walk\n---\n## n-step TD Method\n\n<img style=\"float\" src=\"rw-game.png\" alt=\"drawing\" width=\"700\"/>\n\nIn this MRP, all episodes start in the center state, C, then proceed either left or right by one state on each step, with equal probability. Episodes terminate either on the extreme left or the extreme right. When an episode terminates on the right, a reward of +1 occurs; all other rewards are zero.\n\n<img style=\"float\" src=\"n-step.png\" alt=\"drawing\" width=\"700\"/>",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"# 19 states (not including the ending state)\nNUM_STATES = 19\nSTART = 9\nEND_0 = 0\nEND_1 = 20",
"_____no_output_____"
],
[
"class RandomWalk:\n \n def __init__(self, n, start=START, end=False, lr=0.1, gamma=1, debug=False):\n self.actions = [\"left\", \"right\"]\n self.state = start # current state\n self.end = end\n self.n = n\n self.lr = lr\n self.gamma = gamma\n self.state_actions = []\n self.debug = debug\n # init q estimates\n self.Q_values = {}\n for i in range(NUM_STATES+2): \n self.Q_values[i] = {}\n for a in self.actions:\n if i in [END_0, END_1]:\n # explicitly set end state values\n if i == END_0:\n self.Q_values[i][a] = -1\n else:\n self.Q_values[i][a] = 1 \n else:\n self.Q_values[i][a] = 0\n \n def chooseAction(self): \n action = np.random.choice(self.actions)\n return action \n \n def takeAction(self, action):\n new_state = self.state\n if not self.end:\n if action == \"left\":\n new_state = self.state-1\n else:\n new_state = self.state+1\n \n if new_state in [END_0, END_1]:\n self.end = True\n self.state = new_state\n return self.state\n \n def giveReward(self):\n if self.state == END_0:\n return -1\n if self.state == END_1:\n return 1\n # other states\n return 0\n \n def reset(self):\n self.state = START\n self.end = False\n \n def play(self, rounds=100):\n for _ in range(rounds):\n self.reset()\n t = 0\n T = np.inf\n action = self.chooseAction()\n \n actions = [action]\n states = [self.state]\n rewards = [0]\n while True:\n if t < T:\n state = self.takeAction(action) # next state\n reward = self.giveReward() # next state-reward\n \n states.append(state)\n rewards.append(reward)\n \n if self.end:\n if self.debug:\n print(\"End at state {} | number of states {}\".format(state, len(states)))\n T = t+1\n else:\n action = self.chooseAction()\n actions.append(action) # next action\n # state tau being updated\n tau = t - self.n + 1\n if tau >= 0:\n G = 0\n for i in range(tau+1, min(tau+self.n+1, T+1)):\n G += np.power(self.gamma, i-tau-1)*rewards[i]\n if tau+self.n < T:\n state_action = (states[tau+self.n], actions[tau+self.n])\n G += np.power(self.gamma, self.n)*self.Q_values[state_action[0]][state_action[1]]\n # update Q values\n state_action = (states[tau], actions[tau])\n self.Q_values[state_action[0]][state_action[1]] += self.lr*(G-self.Q_values[state_action[0]][state_action[1]])\n \n if tau == T-1:\n break\n \n t += 1",
"_____no_output_____"
],
[
"rw = RandomWalk(n=3, debug=True)\nrw.play(100)",
"End at state 0 | number of states 128\nEnd at state 20 | number of states 54\nEnd at state 0 | number of states 62\nEnd at state 20 | number of states 78\nEnd at state 20 | number of states 120\nEnd at state 20 | number of states 162\nEnd at state 20 | number of states 28\nEnd at state 20 | number of states 96\nEnd at state 20 | number of states 64\nEnd at state 20 | number of states 22\nEnd at state 20 | number of states 58\nEnd at state 0 | number of states 20\nEnd at state 0 | number of states 112\nEnd at state 20 | number of states 178\nEnd at state 20 | number of states 34\nEnd at state 20 | number of states 94\nEnd at state 20 | number of states 194\nEnd at state 20 | number of states 28\nEnd at state 0 | number of states 32\nEnd at state 20 | number of states 28\nEnd at state 20 | number of states 32\nEnd at state 20 | number of states 196\nEnd at state 0 | number of states 22\nEnd at state 0 | number of states 94\nEnd at state 20 | number of states 270\nEnd at state 0 | number of states 70\nEnd at state 0 | number of states 30\nEnd at state 0 | number of states 20\nEnd at state 0 | number of states 134\nEnd at state 20 | number of states 78\nEnd at state 0 | number of states 146\nEnd at state 0 | number of states 134\nEnd at state 20 | number of states 196\nEnd at state 20 | number of states 18\nEnd at state 0 | number of states 26\nEnd at state 0 | number of states 36\nEnd at state 20 | number of states 94\nEnd at state 0 | number of states 110\nEnd at state 0 | number of states 114\nEnd at state 0 | number of states 64\nEnd at state 20 | number of states 52\nEnd at state 20 | number of states 54\nEnd at state 0 | number of states 26\nEnd at state 0 | number of states 202\nEnd at state 0 | number of states 18\nEnd at state 20 | number of states 64\nEnd at state 0 | number of states 128\nEnd at state 0 | number of states 212\nEnd at state 20 | number of states 26\nEnd at state 20 | number of states 54\nEnd at state 0 | number of states 234\nEnd at state 20 | number of states 56\nEnd at state 0 | number of states 110\nEnd at state 0 | number of states 24\nEnd at state 20 | number of states 154\nEnd at state 0 | number of states 184\nEnd at state 0 | number of states 66\nEnd at state 0 | number of states 46\nEnd at state 0 | number of states 144\nEnd at state 0 | number of states 212\nEnd at state 20 | number of states 388\nEnd at state 20 | number of states 46\nEnd at state 20 | number of states 64\nEnd at state 0 | number of states 42\nEnd at state 20 | number of states 88\nEnd at state 0 | number of states 138\nEnd at state 0 | number of states 104\nEnd at state 20 | number of states 134\nEnd at state 20 | number of states 32\nEnd at state 20 | number of states 24\nEnd at state 20 | number of states 48\nEnd at state 20 | number of states 96\nEnd at state 0 | number of states 50\nEnd at state 0 | number of states 24\nEnd at state 0 | number of states 44\nEnd at state 20 | number of states 252\nEnd at state 20 | number of states 164\nEnd at state 0 | number of states 16\nEnd at state 0 | number of states 38\nEnd at state 0 | number of states 116\nEnd at state 20 | number of states 46\nEnd at state 0 | number of states 36\nEnd at state 20 | number of states 20\nEnd at state 0 | number of states 114\nEnd at state 20 | number of states 36\nEnd at state 20 | number of states 116\nEnd at state 0 | number of states 22\nEnd at state 20 | number of states 106\nEnd at state 20 | number of states 26\nEnd at state 0 | number of states 122\nEnd at state 20 | number of states 148\nEnd at state 0 | number of states 66\nEnd at state 0 | number of states 42\nEnd at state 20 | number of states 196\nEnd at state 0 | number of states 80\nEnd at state 20 | number of states 108\nEnd at state 0 | number of states 32\nEnd at state 20 | number of states 88\nEnd at state 20 | number of states 214\nEnd at state 20 | number of states 20\n"
],
[
"rw.Q_values",
"_____no_output_____"
]
],
[
[
"### Compute (n, lr) -> state-error",
"_____no_output_____"
]
],
[
[
"actual_state_values = np.arange(-20, 22, 2) / 20.0\n\nlr_range = np.linspace(0, 1, 6)\nn_range = np.power(2, range(10))\nepisodes = 100",
"_____no_output_____"
],
[
"sq_errors = {}\n\nfor n in n_range:\n ers = []\n for lr in lr_range:\n print(\"running estimation for lr={} and step={}\".format(lr, n))\n rw = RandomWalk(n=n, lr=lr, debug=False)\n rw.play(episodes)\n # V(s) = 0.5*Q(S, 'left') + 0.5*Q(S, 'right')\n estimate_state_values = [np.mean(list(v.values())) for v in rw.Q_values.values()]\n \n ers.append(np.mean([er**2 for er in actual_state_values - np.array(estimate_state_values)]))\n sq_errors[n] = ers",
"running estimation for lr=0.0 and step=1\nrunning estimation for lr=0.2 and step=1\nrunning estimation for lr=0.4 and step=1\nrunning estimation for lr=0.6000000000000001 and step=1\nrunning estimation for lr=0.8 and step=1\nrunning estimation for lr=1.0 and step=1\nrunning estimation for lr=0.0 and step=2\nrunning estimation for lr=0.2 and step=2\nrunning estimation for lr=0.4 and step=2\nrunning estimation for lr=0.6000000000000001 and step=2\nrunning estimation for lr=0.8 and step=2\nrunning estimation for lr=1.0 and step=2\nrunning estimation for lr=0.0 and step=4\nrunning estimation for lr=0.2 and step=4\nrunning estimation for lr=0.4 and step=4\nrunning estimation for lr=0.6000000000000001 and step=4\nrunning estimation for lr=0.8 and step=4\nrunning estimation for lr=1.0 and step=4\nrunning estimation for lr=0.0 and step=8\nrunning estimation for lr=0.2 and step=8\nrunning estimation for lr=0.4 and step=8\nrunning estimation for lr=0.6000000000000001 and step=8\nrunning estimation for lr=0.8 and step=8\nrunning estimation for lr=1.0 and step=8\nrunning estimation for lr=0.0 and step=16\nrunning estimation for lr=0.2 and step=16\nrunning estimation for lr=0.4 and step=16\nrunning estimation for lr=0.6000000000000001 and step=16\nrunning estimation for lr=0.8 and step=16\nrunning estimation for lr=1.0 and step=16\nrunning estimation for lr=0.0 and step=32\nrunning estimation for lr=0.2 and step=32\nrunning estimation for lr=0.4 and step=32\nrunning estimation for lr=0.6000000000000001 and step=32\nrunning estimation for lr=0.8 and step=32\nrunning estimation for lr=1.0 and step=32\nrunning estimation for lr=0.0 and step=64\nrunning estimation for lr=0.2 and step=64\nrunning estimation for lr=0.4 and step=64\nrunning estimation for lr=0.6000000000000001 and step=64\nrunning estimation for lr=0.8 and step=64\nrunning estimation for lr=1.0 and step=64\nrunning estimation for lr=0.0 and step=128\nrunning estimation for lr=0.2 and step=128\nrunning estimation for lr=0.4 and step=128\nrunning estimation for lr=0.6000000000000001 and step=128\nrunning estimation for lr=0.8 and step=128\nrunning estimation for lr=1.0 and step=128\nrunning estimation for lr=0.0 and step=256\nrunning estimation for lr=0.2 and step=256\nrunning estimation for lr=0.4 and step=256\nrunning estimation for lr=0.6000000000000001 and step=256\nrunning estimation for lr=0.8 and step=256\nrunning estimation for lr=1.0 and step=256\nrunning estimation for lr=0.0 and step=512\nrunning estimation for lr=0.2 and step=512\nrunning estimation for lr=0.4 and step=512\nrunning estimation for lr=0.6000000000000001 and step=512\nrunning estimation for lr=0.8 and step=512\nrunning estimation for lr=1.0 and step=512\n"
]
],
[
[
"### Visualise Error",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.figure(figsize=[10, 6])\n\nfor n in n_range:\n plt.plot(lr_range, sq_errors[n], label=\"n={}\".format(n))\n\nplt.xlabel('learning rate')\nplt.ylabel('RMS error')\nplt.legend()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece3bd8c1e3432d53c24669ece34327b8b540a16 | 21,692 | ipynb | Jupyter Notebook | tutorial/tutorial12_semantic_analysis.ipynb | ggirou/melusine | 38cb5ac677fa0b1ac312ffc13c3090392f40c6b0 | [
"Apache-2.0"
] | null | null | null | tutorial/tutorial12_semantic_analysis.ipynb | ggirou/melusine | 38cb5ac677fa0b1ac312ffc13c3090392f40c6b0 | [
"Apache-2.0"
] | null | null | null | tutorial/tutorial12_semantic_analysis.ipynb | ggirou/melusine | 38cb5ac677fa0b1ac312ffc13c3090392f40c6b0 | [
"Apache-2.0"
] | null | null | null | 30.595205 | 230 | 0.558962 | [
[
[
"# Unsupervised Semantic Analysis tutorial",
"_____no_output_____"
],
[
"The **SemanticDetector** class is used to predict a sentiment score in a document / email.\n\nFor that purpose, two inputs are required:\n- a list of seed words that caracterize a sentiment \n Exemple : the seed words [\"mad\", \"furious\", \"insane\"] caracterize the sentiment \"dissatisfaction\"\n- a trained embedding (Melusine **Embedding** class instance) to compute distances between words/tokens\n\nThe three steps for sentiment score prediction are the following:\n- Instanciate a SentimentDetector object with a list of seed words as argument\n- Use the SentimentDetector.fit method (with an embedding object as argument) to compute the lexicons\n- Use the SentimentDetector.predict method on a document/email DataFrame to predict the sentiment score",
"_____no_output_____"
],
[
"## Minimal working exemple",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n\n# NLP tools\nfrom melusine.nlp_tools.embedding import Embedding\nfrom melusine.nlp_tools.tokenizer import Tokenizer\n\n# Models\nfrom melusine.models.modeler_semantic import SemanticDetector",
"_____no_output_____"
]
],
[
[
"### Load email data",
"_____no_output_____"
]
],
[
[
"df_emails_clean = pd.read_csv('./data/emails_preprocessed.csv', encoding='utf-8', sep=';')\ndf_emails_clean = df_emails_clean[['clean_body']]\ndf_emails_clean = df_emails_clean.astype(str)",
"_____no_output_____"
]
],
[
[
"### Embedding",
"_____no_output_____"
]
],
[
[
"# Train an embedding using the text data in the 'clean_body' column\nembedding = Embedding(input_column='clean_body', size=300, min_count=2)\nembedding.train(df_emails_clean)",
"_____no_output_____"
],
[
"# Print a list of words present in the Embedding vocabulary\nlist(embedding.embedding.vocab.keys())[:3]",
"_____no_output_____"
],
[
"# Test the trained embedding : print most similar words\nembedding.embedding.most_similar('client', topn=3)",
"_____no_output_____"
]
],
[
[
"### Tokenizer",
"_____no_output_____"
]
],
[
[
"# Tokenize the text in the clean_body column\ntokenizer = Tokenizer (input_column='clean_body', stop_removal=True, n_jobs=20)\ndf_emails_clean = tokenizer.fit_transform(df_emails_clean)",
"_____no_output_____"
],
[
"# Test the tokenizer : print tokens\ndf_emails_clean['tokens'].head()",
"_____no_output_____"
]
],
[
[
"### Instanciate and fit the Sentiment Detector",
"_____no_output_____"
]
],
[
[
"seed_word_list = ['immatriculation']\n\n# Instanciate a SentimentDetector object\nsemantic_detector = SemanticDetector(base_seed_words=seed_word_list, tokens_column='tokens')\n\n# Fit the SentimentDetector using the trained embedding\nsemantic_detector.fit(embedding=embedding)",
"_____no_output_____"
],
[
"print('List of seed words:')\nprint(semantic_detector.seed_list)",
"List of seed words:\n['immatriculation']\n"
],
[
"seed_word = semantic_detector.seed_list[0]\nlexicon = semantic_detector.lexicon_dict[seed_word]\nsorted_lexicon = dict(sorted(lexicon.items(), key = lambda x: x[0]))\n\nprint(f'(Part of) Lexicon associated with the seed word \"{seed_word}\":')\nfor word, sentiment_score in list(sorted_lexicon.items())[:10]:\n print(' ' + word + ' : ' + str(sentiment_score))",
"(Part of) Lexicon associated with the seed word \"immatriculation\":\n 00 : -0.01054505\n 1 : -0.028735867\n 2 : 0.034027718\n a : -0.05048247\n adresse : -0.12165247\n afin : 0.03517899\n ainsi : -0.05758333\n assurance : 0.061626766\n assurer : 0.06983626\n attached : -0.027480457\n"
]
],
[
[
"### Predict and print the sentiment score\n\n**Warning :** In this exemple, the embedding is trained on a corpus of 40 emails which is WAY too small to yield valuable results",
"_____no_output_____"
]
],
[
[
"# Choose the name of the column returned (default is \"score\")\nreturn_column = \"semantic_score\"\n\n# Predict the sentiment score on each email of the DataFrame\ndf_emails_clean = semantic_detector.predict(df_emails_clean, return_column=return_column)\n\n# Print emails with the maximum sentiment score\ndf_emails_clean.sort_values(by=return_column, ascending=False).head()",
"_____no_output_____"
]
],
[
[
"## The SentimentDetector class",
"_____no_output_____"
],
[
"The SemanticDetector class provides an unsupervised methodology to assign a sentiment score to a corpus of documents/emails. The methodology used to predict a sentiment score using the SemanticDetector is described below:\n\n1. **Define a list of seed words that caracterize a sentiment**\n - Take a list of seed words as input\n - If the `extend_seed_word_list` parameter is set to True: extend the list of seed words with words sharing the same root (dance -> [\"dancing\", \"dancer\"]) \n \n \n2. **Fit the model (= create a lexicon for each one of the selected seed words)**\n - Create a lexicon for each seed word by computing the cosine similarity between the seed word and all the words in the vocabulary is computed. \n - To compute cosine similarities, a trained embedding is required. \n \n \n3. **Predict a sentiment score for emails/documents**\n - Filter out the tokens in the document that are not in the vocabulary.\n - For each remaining token, compute its sentiment score using the different lexicons.\n - For each token, aggregate the score accross different seeds\n - For each email, aggregate the score accross different tokens",
"_____no_output_____"
],
[
"The arguments of a SemanticDetector object are :\n \n- **base_seed_words :** the list of seed words that caracterize a sentiment\n- **tokens_column :** name of the column in the input DataFrame that contains tokens\n- **extend_seed_word_list :** if True: complement seed words with words sharing the same root (dance -> [\"dancing\", \"dancer\"]). Default value False.\n- **normalize_scores :** if True: normalize the lexicon scores of eache word. Default value False.\n- **aggregation_function_seed_wise :** Function to aggregate the scores associated with a token accross the different seeds. Default function is a max.\n- **aggregation_function_email_wise :** Function to aggregate the scores associated with the different tokens in an email. Default function is the 60th percentile.\n- **n_jobs :** the number of cores used for computation. Default value, 1.",
"_____no_output_____"
],
[
"## Find extra seed words with the `extend_seed_word_list` parameter",
"_____no_output_____"
],
[
"The SentimentDetector \"extend_seed_word_list\" parameter activates the search for extra seed words sharing the same root as the base seed words. \n\nFor example, if \"dance\" is a base seed word, \"extend_seed_word_list\" will loop through the words in the embedding vocabulary and find new seed words such as \"dancer\", \"dancing\".",
"_____no_output_____"
]
],
[
[
"# Instanciate a SentimentDetector object\nsemantic_detector_extended_seed = SemanticDetector(\n base_seed_words=['tel', 'assur'], tokens_column='tokens', extend_seed_word_list=True)\n\n# Fit the SentimentDetector using the trained embedding\nsemantic_detector_extended_seed.fit(embedding=embedding)",
"_____no_output_____"
],
[
"# Print the extended list of seed words\nprint(semantic_detector_extended_seed.seed_dict)\nprint(semantic_detector_extended_seed.seed_list)",
"{'tel': ['telephonique', 'telephone', 'tel'], 'assur': ['assurance', 'assurer']}\n['telephonique', 'telephone', 'tel', 'assurance', 'assurer']\n"
]
],
[
[
"## Use a custom function to aggregate lexicon scores",
"_____no_output_____"
],
[
"### Parse an email using lexicons\nThe SentimentDetector creates a Lexicon for each seed word, therefore, when parsing an email, a score is obtained for each token and each lexicon. \n\nExemple : \n- Sentence : \"Hello, I like ponies\"\n- Seed word list : [\"horse\", \"animal\"]\n- Embedding : simulated\n\nLexicon \"horse\" :\n{\n \"apple\" : 0.2,\n ...\n \"hello\" : 0.1,\n ...\n \"ponies\" : 8.8,\n ...\n \"zebra\" : 1.2\n} \nLexicon \"animal\" :\n{\n \"apple\" : 0.1,\n ...\n \"hello\" : 0.3,\n ...\n \"ponies\" : 4.8,\n ...\n \"zebra\" : 6.2\n}\n\nSentence score :\n- \"horse\" score : 0.1 + 0.3 + 0.2 + 8.8\n- \"animal\" score : 0.3 + 0.2 + 0.2 + 4.8\n\n\nAfter parsing, N_token * N_seed scores are obtained and an aggregation function is necessary to obtain a single sentiment_score for the email.",
"_____no_output_____"
],
[
"### Aggregate the score obtained for the different tokens\n\nThe default aggregation methodology is the following: \n- Seed-wise aggregation : For a token, take the max score accross seed\n - Exemple : \n ponies_score = 8.8 (lexicon \"horse\") \n ponies_score = 4.8 (lexicon \"animal\") \n => Score for the \"ponies\" token = np.max(8.8, 4.8) = 8.8 \n \n \n- Email-wise aggregation : Given a list of token scores, take the percentile 60 as the sentiment_score for the email\n - Exemple : \n token_score_list : [0.3 (hello), 0.3 (i), 0.2 (ponies)] \n => sentiment_score = np.percentile([0.3, 0.3, 0.2, 8.8], 60) = 0.3 ",
"_____no_output_____"
]
],
[
[
"# Instanciate a SentimentDetector object with custom aggregation function:\n# - A mean for the seed-wise aggregation\n# - A 95th percentile for the email-wise aggregation\n\nsemantic_detector_custom_aggregation = SemanticDetector(\n base_seed_words=['client'], \n tokens_column='tokens', \n aggregation_function_seed_wise=np.mean,\n aggregation_function_email_wise=lambda x: np.percentile(x, 95)\n)\n\n# Fit the SentimentDetector using the trained embedding\nsemantic_detector_custom_aggregation.fit(embedding=embedding)\n\n# Predict the sentiment score on each email of the DataFrame\ndf_emails_clean_custom_aggregation = semantic_detector_custom_aggregation.predict(df_emails_clean)",
"_____no_output_____"
]
],
[
[
"## Multiprocessing",
"_____no_output_____"
]
],
[
[
"semantic_detector_multiprocessing = SemanticDetector(\n base_seed_words=['certificat'], \n tokens_column='tokens', \n n_jobs = 2\n)\n\n# Fit the SentimentDetector using the trained embedding\nsemantic_detector_multiprocessing.fit(embedding=embedding)\n\n# Predict the sentiment score on each email of the DataFrame\ndf_emails_multiprocessing = semantic_detector_multiprocessing.predict(df_emails_clean)",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece3ca545ee289b10876a53258f2c32f93f5184e | 81,688 | ipynb | Jupyter Notebook | 01 Getting Started with PCSE.ipynb | albertdaniell/wofost_kalro | 0d1eff238e4e3eac41245e9858467bfbd07b796e | [
"MIT"
] | null | null | null | 01 Getting Started with PCSE.ipynb | albertdaniell/wofost_kalro | 0d1eff238e4e3eac41245e9858467bfbd07b796e | [
"MIT"
] | null | null | null | 01 Getting Started with PCSE.ipynb | albertdaniell/wofost_kalro | 0d1eff238e4e3eac41245e9858467bfbd07b796e | [
"MIT"
] | null | null | null | 144.836879 | 55,184 | 0.862611 | [
[
[
"<img style=\"float: right;\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOIAAAAjCAYAAACJpNbGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABR0RVh0Q3JlYXRpb24gVGltZQAzLzcvMTNND4u/AAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAACMFJREFUeJztnD1y20gWgD+6nJtzAsPhRqKL3AwqwQdYDpXDZfoEppNNTaWbmD7BUEXmI3EPMFCR2YI1UDQpdAPqBNzgvRZA/BGUZEnk9FeFIgj0z2ugX7/XP+jGer2mLv/8b6d+4Efgf/8KG0+Zn8XyXLx+bgEslqegcfzxSY3Irrx6bgEsFssBWsRGowGufwHAYtq7u+H6fUCOxTTWax4wBAbr+SRqNDKesOv3gN/133sW0yh927j1mucIaFWINl7PJ+OcvMcfW8Bol3iN44+mLIOsTCp3UJFfAETr+WRQcG8EOJpunEnTyDlYzycbeWr5xxq3jOF6PglK8ix9buv5xCsrAzBkMV1l5OwD/aJ4BXzV3+8F9z4gz/hTSbz8cxc84FuNvDc4VIsYA7+qohmGwAnycA194G22YqUYlZxv4vpN4AuwBv4oON5m8k3TVLnK4sYFcRyN86dWvCwnlCvFCeUVvwX8CkSZZ5eWs5mLJWE/VZThBMgpfirPk5J4f1SU4QsQ6LNP4+j9OkSUKdRiGlD87CWe3PcyR5PFdAhc1cz/joOziMoIeVF95GX1EGVY6bWhvsAeZQrm+kON80PDneD6PRbTi4LQpmJfsZieFaR1qXlXURh3y2BaBPyG63sspv0t6e+CKJTrf2YxHe8Qr6z8AXBdGbMoHgCTshgr4AiItfxljenPJGv5roCi+rGVw1TExTTWl99ThRsglfYHUnF7SMv+Bhjn4idxbhFLGiAu6gjXD3LuUBF5VzWi3CoAfMP1kxe7mNYZMT5DLFgf13eAXi3ZtvMOsUb3V3J5/mmqy+/66RbnTC1LFdfIu/kd8Qx2bTQeg2GBTPfiUF1TgHNE0QaIq/JDX9RKr/WBy/V8EhfEHWncWMO2EKV8S7UypYnYdE2r+o8gyj5MHXVYsZh+JnG7A+3LPQxR5g9II/UJ148ockmrybqm2+Qapo6gppwB8J7EM6jqaz8u0lhfkXgB58BKPam6rvEdh2kRARbTMa7/HXEfVqnW8hxxWwE+5+JJRTYd9CM90gxw/XFuMKMo/yTNDzUkLnbr6rCYnuH6N8igQ3CvNPJproDPuH6MKMd4Z5kMUjnrh98tn1if72/Ie729Vzq708L0YV3/HGmgB4iHsjOProhhd1lrEr4zaz/FvM4lolTnqWum/6jKmeuDmFb1jHylNg96hPQbhcU0wPVBXESvQI4W5aNshsK4jeOPhSOcOaThMVb48dhU8m2UlR+29ZHzrqyhLL0EaTROteGt67EYIsT6F1HXC/ikcvS00dl51PRwLaIwQtzCxGWRFnRMkT8v/SyAy8I+iliHJtDUsHHq7imipE42GtJanxdcB6mgQcm9MmKNs1m5F9MI13+n+cXZSEpAeV8mQgZqNkmU/HsuT7kf4PrGhXcK0h1SXv7iPKsJKCrDYvoV17+meMqhiDFlll7GEb4U3iseAf+k7mqksmU9qUoaj73E7TEtol3iZnks7Moai8WylUN3TS0WANbzyYv2rqxFtFheANYi7iGNRoPOrO2QGTQIu8vhU8vSmbWNDAHQD7vLYWfWbgFx2F3ee3FBZ9ZuIgMpTWAQdpeRXm9pPoPOrD3UMCtkQM4BRmF3ubG6ZZdxkOfCWsT9pU96CuX56KfOjeIFVC8Ar8NI0xuyOQJsVkWl8xzptQGPNY/6xFiLuL+0gIu0FVTrNESmbK7C7tLrzNpmPW0EeGF32UyFN19UnCAT4ZHGWWnYqDNrB4jViZBK/kbD9sLuMiBZSD8AVp1Z+0LD/NmZta+BIzOS3pm1xwBhd9kvkeEGUbQeqSmIdHhkXnGs5fIQRUxPV1x0Zm2zMuoq7C69rU/yBWAt4v7iAd86s/ZaDweZP+wBvwBOZ9b2SCrrmPzk+AWizA09j1QxMK4gZumcWKUWMvkdA56mfxN2l7GmHWk6V2F32Qi7yxaIsmnYHvkJ9zEQqAwBotQXwK2m0c+EN/Kk8zPTZiOkIWrp/xNTnpeOtYh7iFauN+k5W+0vXab6UsbyecAw229SxWiG3aVZ7NBCKrGHuneazy2iyBeIuxkjk9UDE1bzOtJ4IzbdwysNN0D6dnf9Rk3/iKSBWOnhUbASSWW+DbvLWM+HKreZ3O/r77gza5u842w6LxFrEfcTj+Jv3mK4q7Co63hE+fI6E94hUaT0cry+XushSuvoNZO2CdsCrlXJHDYVMUIUJso2BmhfL+wuV6rMvVR6AXnS1428XupaE7Hwnrqkg4cMGD0lr3NfpVegrUw1m2sN0+crNirEX1uTqiPbPoyI/QSKKmqA9I9aer+fcR2zxIj7GiMV+EYVIkZc3r5eH2rYI+0vnpBYIE/vGwUCdYM7s3agbqXJu58VIOwug86sfd2ZtSPNKwi7S9PHy4UnscCmXKuUZQRdsqbPwCHp2754pKYnW0akcZBO/x2df29XnvA//6iV8T3TSluBmOQlR+v5JNvaHixlDZRalRZifbZaAg3vIIrkmP6YVu6owI1M9x2r0vVIFCBGXNLS96Ph45IGY2ey6e1DY20UMaLGItUXoIhVvCv5tvDg2MWLqYNaoKBKWe6Z7gBR8OwAzZOyD4poBmtidlwt/gIxw/QHz0+oWKIoj19fRz8p3YOjoV8195F5l31ltZ5PfnluISyW+/IK6SPstRIiH/FaLHvLa2R+6F6f978AVsD7v0vf0HK4vNK9VfbVojSBceP4o/PcglgsD8GMmjaRbRCc1PEQIrbv45nlIfleIrs778XkrcWSZXMcXPZyqbvfxy7ckuyqHJPslJzH9c3We2ZRbx1O/07ziJbDI1FE2Qwp4n4DNzHJhkZF16+3bnwrCmi40U2eWoj7KZvobn7+YtKO1vPJVyyWPSZrER1kNU0TqfienpvlaWZR7oX+3tba6lxcX7MK3tNfo2RlpNc8tthsIFbAKYtpsA+TtRbLNp5/H4/EFXX0MOfbOGUxvbCKaDkEnl8Rq0jc1ayFjhFFjKwiWg6B/wNk+JCXXNBIXQAAAABJRU5ErkJggg==\">\n\n",
"_____no_output_____"
]
],
[
[
"!pip install matplotlib\n!pip install pandas pcse",
"Requirement already satisfied: matplotlib in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (3.4.3)\nRequirement already satisfied: kiwisolver>=1.0.1 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from matplotlib) (1.3.1)\nRequirement already satisfied: pillow>=6.2.0 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from matplotlib) (8.3.1)\nRequirement already satisfied: numpy>=1.16 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from matplotlib) (1.21.2)\nRequirement already satisfied: pyparsing>=2.2.1 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from matplotlib) (2.4.7)\nRequirement already satisfied: cycler>=0.10 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from matplotlib) (0.10.0)\nRequirement already satisfied: python-dateutil>=2.7 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from matplotlib) (2.8.2)\nRequirement already satisfied: six in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from cycler>=0.10->matplotlib) (1.16.0)\n\u001b[33mWARNING: You are using pip version 21.1.3; however, version 21.2.4 is available.\nYou should consider upgrading via the '/Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/bin/python3.9 -m pip install --upgrade pip' command.\u001b[0m\nRequirement already satisfied: pandas in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (1.3.2)\nRequirement already satisfied: pcse in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (5.4.2)\nRequirement already satisfied: python-dateutil>=2.7.3 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pandas) (2.8.2)\nRequirement already satisfied: pytz>=2017.3 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pandas) (2021.1)\nRequirement already satisfied: numpy>=1.17.3 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pandas) (1.21.2)\nRequirement already satisfied: six>=1.5 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from python-dateutil>=2.7.3->pandas) (1.16.0)\nRequirement already satisfied: SQLAlchemy>=0.8.0 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pcse) (1.4.22)\nRequirement already satisfied: PyYAML>=3.11 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pcse) (5.4.1)\nRequirement already satisfied: xlrd>=0.9.3 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pcse) (2.0.1)\nRequirement already satisfied: xlwt>=1.0.0 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pcse) (1.3.0)\nRequirement already satisfied: requests>=2.0.0 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pcse) (2.26.0)\nRequirement already satisfied: traitlets-pcse==5.0.0.dev in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from pcse) (5.0.0.dev0)\nRequirement already satisfied: ipython_genutils in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from traitlets-pcse==5.0.0.dev->pcse) (0.2.0)\nRequirement already satisfied: decorator in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from traitlets-pcse==5.0.0.dev->pcse) (5.0.9)\nRequirement already satisfied: certifi>=2017.4.17 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from requests>=2.0.0->pcse) (2021.5.30)\nRequirement already satisfied: charset-normalizer~=2.0.0 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from requests>=2.0.0->pcse) (2.0.4)\nRequirement already satisfied: idna<4,>=2.5 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from requests>=2.0.0->pcse) (3.2)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from requests>=2.0.0->pcse) (1.26.6)\nRequirement already satisfied: greenlet!=0.4.17 in /Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/lib/python3.9/site-packages (from SQLAlchemy>=0.8.0->pcse) (1.1.1)\n\u001b[33mWARNING: You are using pip version 21.1.3; however, version 21.2.4 is available.\nYou should consider upgrading via the '/Users/mac34/Projects/Python/Jupyter/wofost/wofost_venv/bin/python3.9 -m pip install --upgrade pip' command.\u001b[0m\n"
]
],
[
[
"# Getting Started with PCSE/WOFOST\n\nThis Jupyter notebook will introduce PCSE and explain the basics of running models with PCSE, taking WOFOST as an example.\n\nAllard de Wit, March 2018\n\n**Prerequisites for running this notebook**\n\nSeveral packages need to be installed for running PCSE/WOFOST:\n\n 1. `PCSE` and its dependencies. See the [PCSE user guide](http://pcse.readthedocs.io/en/stable/installing.html) for more information;\n 2. `pandas` for processing and storing WOFOST output;\n 3. `matplotlib` for generating charts\n",
"_____no_output_____"
],
[
"## Importing the relevant modules\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport sys, os\nimport pcse\nimport pandas\nimport matplotlib\nmatplotlib.style.use(\"ggplot\")\nimport matplotlib.pyplot as plt\nprint(\"This notebook was built with:\")\nprint(\"python version: %s \" % sys.version)\nprint(\"PCSE version: %s\" % pcse.__version__)",
"Platform not recognized, using system temp directory for PCSE settings.\nPlatform not recognized, using system temp directory for PCSE settings.\n"
]
],
[
[
"## Starting from the internal demo database\nFor demonstration purposes, we can start WOFOST with a single function call. This function reads all relevant data from the internal demo databases. In the next notebook we will demonstrate how to read data from external sources.\n\nThe command below starts WOFOST in potential production mode for winter-wheat for a location in Southern Spain.",
"_____no_output_____"
]
],
[
[
"wofostPP = pcse.start_wofost(mode=\"pp\")",
"/usr/local/lib/python3.9/site-packages/pcse/db/pcse/db_input.py:630: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.\n items = yaml.load(input)\n/usr/local/lib/python3.9/site-packages/pcse/db/pcse/db_input.py:652: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n r = select([table_site],\n/usr/local/lib/python3.9/site-packages/pcse/db/pcse/db_input.py:127: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n r = s.execute()\n/usr/local/lib/python3.9/site-packages/pcse/db/pcse/db_input.py:183: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n r = s.execute()\n/usr/local/lib/python3.9/site-packages/pcse/db/pcse/db_input.py:493: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n cursor = select([table_soil_layers.c.thickness,\n/usr/local/lib/python3.9/site-packages/pcse/db/pcse/db_input.py:522: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n r = select([table_soil_pg],\n/usr/local/lib/python3.9/site-packages/pcse/db/cgms8/data_providers.py:108: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n r = select([table_grid.c.latitude, table_grid.c.longitude,\n/usr/local/lib/python3.9/site-packages/pcse/db/cgms8/data_providers.py:133: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n r = select([table_gw],and_(table_gw.c.grid_no==self.grid_no,\n"
]
],
[
[
"You have just successfully initialized a PCSE/WOFOST object in the Python interpreter, which is in its initial state and waiting to do some simulation. We can now advance the model state for example with 1 day:\n",
"_____no_output_____"
]
],
[
[
"wofostPP.run()",
"_____no_output_____"
]
],
[
[
"Advancing the crop simulation with only 1 day, is often not so useful so the number of days to simulate can be specified as well:",
"_____no_output_____"
]
],
[
[
"wofostPP.run(days=10)",
"_____no_output_____"
]
],
[
[
"## Getting information about state and rate variables\nRetrieving information about the calculated model states or rates can be done with the `get_variable()` method on a PCSE object. For example, to retrieve the leaf area index value in the current model state you can do:",
"_____no_output_____"
]
],
[
[
"wofostPP.get_variable(\"LAI\")",
"_____no_output_____"
],
[
"wofostPP.run(days=25)\nwofostPP.get_variable(\"LAI\")",
"_____no_output_____"
]
],
[
[
"Showing that after 11 days the LAI value is 0.287. When we increase time with another 25 days, the LAI increases to 1.528. The `get_variable()` method can retrieve any state or rate variable that is defined somewhere in the model. \n\nFinally, we can finish the crop season by letting it run until the model terminates because the crop reaches maturity or the harvest date:",
"_____no_output_____"
]
],
[
[
"wofostPP.run_till_terminate()",
"_____no_output_____"
]
],
[
[
"Note that before or after the crop cycle, the object representing the crop does not exist and therefore retrieving a crop related variable results in a `None` value. Off course the simulation results are stored and can be obtained, see next section.",
"_____no_output_____"
]
],
[
[
"print(wofostPP.get_variable(\"LAI\"))",
"None\n"
]
],
[
[
"## Retrieving and displaying WOFOST output\nWe can retrieve the results of the simulation at each time step using `get_output()`. In python terms this returns a list of dictionaries, one dictionary for each time step of the the simulation results. Each dictionary contains the key:value pairs of the state or rate variables that were stored at that time step.\n\n",
"_____no_output_____"
]
],
[
[
"output = wofostPP.get_output()",
"_____no_output_____"
]
],
[
[
"The most convenient way to handle the output from WOFOST is to used the `pandas` module to convert it into a dataframe. Pandas DataFrames can be converted to a variety of formats including excel, CSV or database tables.",
"_____no_output_____"
]
],
[
[
"dfPP = pandas.DataFrame(output).set_index(\"day\")\ndfPP.tail()",
"_____no_output_____"
]
],
[
[
"Besides the output at each time step, WOFOST also provides summary output which summarizes the crop cycle and provides you the total crop biomass, total yield, maximum LAI and other variables. In case of crop rotations, the summary output will consist of several sets of variables, one for each crop cycle.",
"_____no_output_____"
]
],
[
[
"summary_output = wofostPP.get_summary_output()\nmsg = \"Reached maturity at {DOM} with total biomass {TAGP:.1f} kg/ha, \" \\\n \"a yield of {TWSO:.1f} kg/ha with a maximum LAI of {LAIMAX:.2f}.\"\nfor crop_cycle in summary_output:\n print(msg.format(**crop_cycle))",
"Reached maturity at 2000-05-31 with total biomass 18091.0 kg/ha, a yield of 8729.4 kg/ha with a maximum LAI of 6.23.\n"
]
],
[
[
"## Visualizing output\nThe pandas module is also very useful for generating charts from simulation results. In this case we generate graphs of leaf area index and crop biomass including total biomass and grain yield.",
"_____no_output_____"
]
],
[
[
"fig, (axis1, axis2) = plt.subplots(nrows=1, ncols=2, figsize=(16,8))\ndfPP.LAI.plot(ax=axis1, label=\"LAI\", color='k')\ndfPP.TAGP.plot(ax=axis2, label=\"Total biomass\")\ndfPP.TWSO.plot(ax=axis2, label=\"Yield\")\naxis1.set_title(\"Leaf Area Index\")\naxis2.set_title(\"Crop biomass\")\nfig.autofmt_xdate()\nr = fig.legend()",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece3eac59bd2ae0d69d9cb1614d9c2937b255563 | 109,090 | ipynb | Jupyter Notebook | All python files/1_5_3_Text_Summarization_Custom_Politics.ipynb | worachot-n/Text_summarization_T5 | ad06e556813f23c98c0f60dc8b5e08e5d6c4601a | [
"MIT"
] | null | null | null | All python files/1_5_3_Text_Summarization_Custom_Politics.ipynb | worachot-n/Text_summarization_T5 | ad06e556813f23c98c0f60dc8b5e08e5d6c4601a | [
"MIT"
] | null | null | null | All python files/1_5_3_Text_Summarization_Custom_Politics.ipynb | worachot-n/Text_summarization_T5 | ad06e556813f23c98c0f60dc8b5e08e5d6c4601a | [
"MIT"
] | null | null | null | 46.819742 | 509 | 0.521487 | [
[
[
"<a href=\"https://colab.research.google.com/github/worachot-n/Text_summarization_T5/blob/main/1_5_3_Text_Summarization_Custom_Politics.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Import Google Drive",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
]
],
[
[
"# Set Location Folder",
"_____no_output_____"
]
],
[
[
"import os\nos.chdir('/content/drive/MyDrive/Kaggle')",
"_____no_output_____"
]
],
[
[
"# Install Library",
"_____no_output_____"
]
],
[
[
"!pip install sentencepiece\n!pip install transformers\n!pip install rich[jupyter]\n!pip install datasets rouge-score nltk\n!pip install tensorboard\n!pip install bert-score",
"Collecting sentencepiece\n Downloading sentencepiece-0.1.96-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.2 MB)\n\u001b[K |████████████████████████████████| 1.2 MB 4.1 MB/s \n\u001b[?25hInstalling collected packages: sentencepiece\nSuccessfully installed sentencepiece-0.1.96\nCollecting transformers\n Downloading transformers-4.18.0-py3-none-any.whl (4.0 MB)\n\u001b[K |████████████████████████████████| 4.0 MB 4.1 MB/s \n\u001b[?25hCollecting sacremoses\n Downloading sacremoses-0.0.49-py3-none-any.whl (895 kB)\n\u001b[K |████████████████████████████████| 895 kB 65.0 MB/s \n\u001b[?25hRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from transformers) (4.11.3)\nCollecting tokenizers!=0.11.3,<0.13,>=0.11.1\n Downloading tokenizers-0.12.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (6.6 MB)\n\u001b[K |████████████████████████████████| 6.6 MB 53.9 MB/s \n\u001b[?25hRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers) (4.64.0)\nRequirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from transformers) (21.3)\nCollecting pyyaml>=5.1\n Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n\u001b[K |████████████████████████████████| 596 kB 66.6 MB/s \n\u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers) (3.6.0)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers) (2.23.0)\nRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (1.21.5)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (2019.12.20)\nCollecting huggingface-hub<1.0,>=0.1.0\n Downloading huggingface_hub-0.5.1-py3-none-any.whl (77 kB)\n\u001b[K |████████████████████████████████| 77 kB 7.9 MB/s \n\u001b[?25hRequirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.7/dist-packages (from huggingface-hub<1.0,>=0.1.0->transformers) (4.1.1)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=20.0->transformers) (3.0.8)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers) (3.8.0)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2021.10.8)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (3.0.4)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2.10)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (1.24.3)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.15.0)\nRequirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (7.1.2)\nRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.1.0)\nInstalling collected packages: pyyaml, tokenizers, sacremoses, huggingface-hub, transformers\n Attempting uninstall: pyyaml\n Found existing installation: PyYAML 3.13\n Uninstalling PyYAML-3.13:\n Successfully uninstalled PyYAML-3.13\nSuccessfully installed huggingface-hub-0.5.1 pyyaml-6.0 sacremoses-0.0.49 tokenizers-0.12.1 transformers-4.18.0\nCollecting rich[jupyter]\n Downloading rich-12.2.0-py3-none-any.whl (229 kB)\n\u001b[K |████████████████████████████████| 229 kB 4.1 MB/s \n\u001b[?25hCollecting commonmark<0.10.0,>=0.9.0\n Downloading commonmark-0.9.1-py2.py3-none-any.whl (51 kB)\n\u001b[K |████████████████████████████████| 51 kB 7.4 MB/s \n\u001b[?25hRequirement already satisfied: pygments<3.0.0,>=2.6.0 in /usr/local/lib/python3.7/dist-packages (from rich[jupyter]) (2.6.1)\nRequirement already satisfied: typing-extensions<5.0,>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from rich[jupyter]) (4.1.1)\nRequirement already satisfied: ipywidgets<8.0.0,>=7.5.1 in /usr/local/lib/python3.7/dist-packages (from rich[jupyter]) (7.7.0)\nRequirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.3.0)\nRequirement already satisfied: traitlets>=4.3.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.1.1)\nRequirement already satisfied: ipython>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.5.0)\nRequirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (1.1.0)\nRequirement already satisfied: widgetsnbextension~=3.6.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (3.6.0)\nRequirement already satisfied: ipython-genutils~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.2.0)\nRequirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (4.10.1)\nRequirement already satisfied: tornado>=4.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.1.1)\nRequirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel>=4.5.1->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.3.5)\nRequirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (1.0.18)\nRequirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.8.1)\nRequirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.7.5)\nRequirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (57.4.0)\nRequirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (4.8.0)\nRequirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (4.4.2)\nRequirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (4.3.3)\nRequirement already satisfied: fastjsonschema in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (2.15.3)\nRequirement already satisfied: jupyter-core in /usr/local/lib/python3.7/dist-packages (from nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (4.9.2)\nRequirement already satisfied: importlib-resources>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=2.6->nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.6.0)\nRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from jsonschema>=2.6->nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (4.11.3)\nRequirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=2.6->nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (21.4.0)\nRequirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=2.6->nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.18.1)\nRequirement already satisfied: zipp>=3.1.0 in /usr/local/lib/python3.7/dist-packages (from importlib-resources>=1.4.0->jsonschema>=2.6->nbformat>=4.2.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (3.8.0)\nRequirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (1.15.0)\nRequirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=4.0.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.2.5)\nRequirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.7/dist-packages (from widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.3.1)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (2.11.3)\nRequirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.6.1)\nRequirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (1.8.0)\nRequirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.13.3)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (2.8.2)\nRequirement already satisfied: pyzmq>=13 in /usr/local/lib/python3.7/dist-packages (from jupyter-client->ipykernel>=4.5.1->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (22.3.0)\nRequirement already satisfied: ptyprocess in /usr/local/lib/python3.7/dist-packages (from terminado>=0.8.1->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.7.0)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (2.0.1)\nRequirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.4)\nRequirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.7.1)\nRequirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.8.4)\nRequirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (5.0.0)\nRequirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (1.5.0)\nRequirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.6.0)\nRequirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.0->ipywidgets<8.0.0,>=7.5.1->rich[jupyter]) (0.5.1)\nInstalling collected packages: commonmark, rich\nSuccessfully installed commonmark-0.9.1 rich-12.2.0\nCollecting datasets\n Downloading datasets-2.1.0-py3-none-any.whl (325 kB)\n\u001b[K |████████████████████████████████| 325 kB 4.3 MB/s \n\u001b[?25hCollecting rouge-score\n Downloading rouge_score-0.0.4-py2.py3-none-any.whl (22 kB)\nRequirement already satisfied: nltk in /usr/local/lib/python3.7/dist-packages (3.2.5)\nCollecting responses<0.19\n Downloading responses-0.18.0-py3-none-any.whl (38 kB)\nRequirement already satisfied: dill in /usr/local/lib/python3.7/dist-packages (from datasets) (0.3.4)\nRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from datasets) (21.3)\nRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from datasets) (1.21.5)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from datasets) (1.3.5)\nRequirement already satisfied: multiprocess in /usr/local/lib/python3.7/dist-packages (from datasets) (0.70.12.2)\nCollecting fsspec[http]>=2021.05.0\n Downloading fsspec-2022.3.0-py3-none-any.whl (136 kB)\n\u001b[K |████████████████████████████████| 136 kB 56.3 MB/s \n\u001b[?25hRequirement already satisfied: pyarrow>=5.0.0 in /usr/local/lib/python3.7/dist-packages (from datasets) (6.0.1)\nRequirement already satisfied: tqdm>=4.62.1 in /usr/local/lib/python3.7/dist-packages (from datasets) (4.64.0)\nCollecting xxhash\n Downloading xxhash-3.0.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (212 kB)\n\u001b[K |████████████████████████████████| 212 kB 60.5 MB/s \n\u001b[?25hRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from datasets) (4.11.3)\nCollecting aiohttp\n Downloading aiohttp-3.8.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)\n\u001b[K |████████████████████████████████| 1.1 MB 46.3 MB/s \n\u001b[?25hRequirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from datasets) (2.23.0)\nRequirement already satisfied: huggingface-hub<1.0.0,>=0.1.0 in /usr/local/lib/python3.7/dist-packages (from datasets) (0.5.1)\nRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from huggingface-hub<1.0.0,>=0.1.0->datasets) (3.6.0)\nRequirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.7/dist-packages (from huggingface-hub<1.0.0,>=0.1.0->datasets) (4.1.1)\nRequirement already satisfied: pyyaml in /usr/local/lib/python3.7/dist-packages (from huggingface-hub<1.0.0,>=0.1.0->datasets) (6.0)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->datasets) (3.0.8)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->datasets) (2.10)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->datasets) (1.24.3)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->datasets) (2021.10.8)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->datasets) (3.0.4)\nCollecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1\n Downloading urllib3-1.25.11-py2.py3-none-any.whl (127 kB)\n\u001b[K |████████████████████████████████| 127 kB 82.8 MB/s \n\u001b[?25hRequirement already satisfied: six>=1.14.0 in /usr/local/lib/python3.7/dist-packages (from rouge-score) (1.15.0)\nRequirement already satisfied: absl-py in /usr/local/lib/python3.7/dist-packages (from rouge-score) (1.0.0)\nCollecting yarl<2.0,>=1.0\n Downloading yarl-1.7.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (271 kB)\n\u001b[K |████████████████████████████████| 271 kB 81.9 MB/s \n\u001b[?25hCollecting aiosignal>=1.1.2\n Downloading aiosignal-1.2.0-py3-none-any.whl (8.2 kB)\nRequirement already satisfied: charset-normalizer<3.0,>=2.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp->datasets) (2.0.12)\nCollecting async-timeout<5.0,>=4.0.0a3\n Downloading async_timeout-4.0.2-py3-none-any.whl (5.8 kB)\nCollecting asynctest==0.13.0\n Downloading asynctest-0.13.0-py3-none-any.whl (26 kB)\nCollecting multidict<7.0,>=4.5\n Downloading multidict-6.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (94 kB)\n\u001b[K |████████████████████████████████| 94 kB 4.0 MB/s \n\u001b[?25hCollecting frozenlist>=1.1.1\n Downloading frozenlist-1.3.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (144 kB)\n\u001b[K |████████████████████████████████| 144 kB 82.4 MB/s \n\u001b[?25hRequirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp->datasets) (21.4.0)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->datasets) (3.8.0)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->datasets) (2.8.2)\nRequirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas->datasets) (2018.9)\nInstalling collected packages: multidict, frozenlist, yarl, urllib3, asynctest, async-timeout, aiosignal, fsspec, aiohttp, xxhash, responses, rouge-score, datasets\n Attempting uninstall: urllib3\n Found existing installation: urllib3 1.24.3\n Uninstalling urllib3-1.24.3:\n Successfully uninstalled urllib3-1.24.3\n\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ndatascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\u001b[0m\nSuccessfully installed aiohttp-3.8.1 aiosignal-1.2.0 async-timeout-4.0.2 asynctest-0.13.0 datasets-2.1.0 frozenlist-1.3.0 fsspec-2022.3.0 multidict-6.0.2 responses-0.18.0 rouge-score-0.0.4 urllib3-1.25.11 xxhash-3.0.0 yarl-1.7.2\nRequirement already satisfied: tensorboard in /usr/local/lib/python3.7/dist-packages (2.8.0)\nRequirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.0.0)\nRequirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.35.0)\nRequirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.44.0)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (0.4.6)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.8.1)\nRequirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (3.17.3)\nRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (0.37.1)\nRequirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (2.23.0)\nRequirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (57.4.0)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.0.1)\nRequirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (0.6.1)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (3.3.6)\nRequirement already satisfied: numpy>=1.12.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.21.5)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from absl-py>=0.4->tensorboard) (1.15.0)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard) (0.2.8)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard) (4.2.4)\nRequirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard) (4.8)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard) (1.3.1)\nRequirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard) (4.11.3)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard) (3.8.0)\nRequirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard) (4.1.1)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard) (0.4.8)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (1.25.11)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (2021.10.8)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (3.0.4)\nRequirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard) (3.2.0)\nCollecting bert-score\n Downloading bert_score-0.3.11-py3-none-any.whl (60 kB)\n\u001b[K |████████████████████████████████| 60 kB 2.9 MB/s \n\u001b[?25hRequirement already satisfied: packaging>=20.9 in /usr/local/lib/python3.7/dist-packages (from bert-score) (21.3)\nRequirement already satisfied: torch>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from bert-score) (1.10.0+cu111)\nRequirement already satisfied: tqdm>=4.31.1 in /usr/local/lib/python3.7/dist-packages (from bert-score) (4.64.0)\nRequirement already satisfied: transformers>=3.0.0numpy in /usr/local/lib/python3.7/dist-packages (from bert-score) (4.18.0)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from bert-score) (2.23.0)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from bert-score) (3.2.2)\nRequirement already satisfied: pandas>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from bert-score) (1.3.5)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=20.9->bert-score) (3.0.8)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.0.1->bert-score) (2.8.2)\nRequirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.0.1->bert-score) (1.21.5)\nRequirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.0.1->bert-score) (2018.9)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=1.0.1->bert-score) (1.15.0)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.0.0->bert-score) (4.1.1)\nRequirement already satisfied: tokenizers!=0.11.3,<0.13,>=0.11.1 in /usr/local/lib/python3.7/dist-packages (from transformers>=3.0.0numpy->bert-score) (0.12.1)\nRequirement already satisfied: huggingface-hub<1.0,>=0.1.0 in /usr/local/lib/python3.7/dist-packages (from transformers>=3.0.0numpy->bert-score) (0.5.1)\nRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers>=3.0.0numpy->bert-score) (3.6.0)\nRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from transformers>=3.0.0numpy->bert-score) (4.11.3)\nRequirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.7/dist-packages (from transformers>=3.0.0numpy->bert-score) (6.0)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers>=3.0.0numpy->bert-score) (2019.12.20)\nRequirement already satisfied: sacremoses in /usr/local/lib/python3.7/dist-packages (from transformers>=3.0.0numpy->bert-score) (0.0.49)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers>=3.0.0numpy->bert-score) (3.8.0)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->bert-score) (0.11.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->bert-score) (1.4.2)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->bert-score) (2021.10.8)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->bert-score) (1.25.11)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->bert-score) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->bert-score) (3.0.4)\nRequirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers>=3.0.0numpy->bert-score) (7.1.2)\nRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers>=3.0.0numpy->bert-score) (1.1.0)\nInstalling collected packages: bert-score\nSuccessfully installed bert-score-0.3.11\n"
]
],
[
[
"# Import Library",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler\nimport os\nfrom datasets import load_dataset, load_metric\n\nfrom rich.table import Column, Table\nfrom rich import box\nfrom rich.console import Console\n\n# Importing the T5 modules \nfrom transformers import T5Tokenizer, T5ForConditionalGeneration\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"# Import Dataset With Categories",
"_____no_output_____"
]
],
[
[
"dataset_finetune = pd.read_csv('/content/drive/MyDrive/Kaggle/Dataset_Finetune_Mixed.csv')\ndataset_evaluate = pd.read_csv('/content/drive/MyDrive/Kaggle/Dataset_Evaluate_Mixed.csv')",
"_____no_output_____"
],
[
"dataset_finetune[\"summaries\"] = \"summarize: \"+dataset_finetune[\"summaries\"]\ndataset_evaluate[\"summaries\"] = \"summarize: \"+dataset_evaluate[\"summaries\"]",
"_____no_output_____"
],
[
"dataset_finetune.head()",
"_____no_output_____"
],
[
"dataset_evaluate.head()",
"_____no_output_____"
]
],
[
[
"# Read Categories From Dataset",
"_____no_output_____"
]
],
[
[
"categories = np.unique(dataset_evaluate[['categories']].values).tolist()\nprint(categories)",
"['Mixed', 'business', 'entertainment', 'politics', 'sport', 'tech']\n"
],
[
"dataset_dict = {}\n# print(type(dataset_dict))\nfor i, category in enumerate(categories):\n dataset_dict[category] = dataset_evaluate.loc[dataset_evaluate['categories'] == category]",
"_____no_output_____"
]
],
[
[
"# Console Logger",
"_____no_output_____"
]
],
[
[
"# define a rich console logger\nconsole=Console(record=True)\n\ntraining_logger = Table(Column(\"Epoch\", justify=\"center\" ), \n Column(\"Steps\", justify=\"center\"),\n Column(\"Loss\", justify=\"center\"), \n title=\"Training Status\",pad_edge=False, box=box.ASCII)",
"_____no_output_____"
]
],
[
[
"# Use GPU",
"_____no_output_____"
]
],
[
[
"# Setting up the device for GPU usage\nfrom torch import cuda\ndevice = 'cuda' if cuda.is_available() else 'cpu'",
"_____no_output_____"
],
[
"class YourDataSetClass(Dataset):\n \"\"\"\n Creating a custom dataset for reading the dataset and \n loading it into the dataloader to pass it to the neural network for finetuning the model\n\n \"\"\"\n\n def __init__(self, dataframe, tokenizer, source_len, target_len, source_text, target_text):\n self.tokenizer = tokenizer\n self.data = dataframe\n self.source_len = source_len\n self.summ_len = target_len\n self.target_text = self.data[target_text]\n self.source_text = self.data[source_text]\n\n def __len__(self):\n return len(self.target_text)\n\n def __getitem__(self, index):\n source_text = str(self.source_text[index])\n target_text = str(self.target_text[index])\n\n #cleaning data so as to ensure data is in string type\n source_text = ' '.join(source_text.split())\n target_text = ' '.join(target_text.split())\n\n source = self.tokenizer.batch_encode_plus([source_text], max_length= self.source_len, pad_to_max_length=True, truncation=True, padding=\"max_length\", return_tensors='pt')\n target = self.tokenizer.batch_encode_plus([target_text], max_length= self.summ_len, pad_to_max_length=True, truncation=True, padding=\"max_length\", return_tensors='pt')\n\n source_ids = source['input_ids'].squeeze()\n source_mask = source['attention_mask'].squeeze()\n target_ids = target['input_ids'].squeeze()\n target_mask = target['attention_mask'].squeeze()\n\n return {\n 'source_ids': source_ids.to(dtype=torch.long), \n 'source_mask': source_mask.to(dtype=torch.long), \n 'target_ids': target_ids.to(dtype=torch.long),\n 'target_ids_y': target_ids.to(dtype=torch.long),\n }",
"_____no_output_____"
]
],
[
[
"# Import Tensorboard",
"_____no_output_____"
]
],
[
[
"import torch\nimport torchvision\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchvision import datasets, transforms",
"_____no_output_____"
],
[
"# SummaryWriter takes log directory as argument\nwriter = SummaryWriter()",
"_____no_output_____"
]
],
[
[
"# Train & Validate Function",
"_____no_output_____"
]
],
[
[
"def train(epoch, tokenizer, model, device, loader, optimizer, finetune):\n\n \"\"\"\n Function to be called for training with the parameters passed from main function\n\n \"\"\"\n running_loss = 0.0\n model.train()\n for _,data in enumerate(loader, 0):\n y = data['target_ids'].to(device, dtype = torch.long)\n y_ids = y[:, :-1].contiguous()\n lm_labels = y[:, 1:].clone().detach()\n lm_labels[y[:, 1:] == tokenizer.pad_token_id] = -100\n ids = data['source_ids'].to(device, dtype = torch.long)\n mask = data['source_mask'].to(device, dtype = torch.long)\n\n outputs = model(input_ids = ids, attention_mask = mask, decoder_input_ids=y_ids, labels=lm_labels)\n loss = outputs[0]\n\n if _%10==0:\n training_logger.add_row(str(epoch), str(_), str(loss))\n console.print(training_logger)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n if _%10==0:\n writer.add_scalar(f'training loss {finetune}', running_loss / 10, epoch * len(loader) + _)\n running_loss = 0.0\n writer.close()",
"_____no_output_____"
],
[
"def validate(epoch, tokenizer, model, device, loader, max_lengths):\n\n \"\"\"\n Function to evaluate model for predictions\n\n \"\"\"\n model.eval()\n predictions = []\n actuals = []\n texts = []\n with torch.no_grad():\n for i, data in enumerate(loader, 0):\n y = data['target_ids'].to(device, dtype = torch.long)\n ids = data['source_ids'].to(device, dtype = torch.long)\n mask = data['source_mask'].to(device, dtype = torch.long)\n\n generated_ids = model.generate(\n input_ids = ids,\n attention_mask = mask, \n max_length=max_lengths, \n num_beams=2,\n repetition_penalty=2.5, \n length_penalty=1.0, \n early_stopping=True\n )\n text = [tokenizer.decode(f, skip_special_tokens=True, clean_up_tokenization_spaces=True) for f in ids]\n preds = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in generated_ids]\n target = [tokenizer.decode(t, skip_special_tokens=True, clean_up_tokenization_spaces=True)for t in y]\n\n predictions.extend(preds)\n actuals.extend(target)\n texts.extend(text)\n return predictions, actuals, texts",
"_____no_output_____"
]
],
[
[
"# Set Model Parameters",
"_____no_output_____"
]
],
[
[
"model_params={\n \"MODEL\":\"t5-base\", # model_type: t5-base/t5-large\n \"TRAIN_BATCH_SIZE\":4, # training batch size\n \"VALID_BATCH_SIZE\":4, # validation batch size\n \"TRAIN_EPOCHS\":50, # number of training epochs\n \"VAL_EPOCHS\":1, # number of validation epochs\n \"LEARNING_RATE\":1e-4, # learning rate\n \"MAX_SOURCE_TEXT_LENGTH\":512, # max length of source text (article)\n \"MAX_TARGET_TEXT_LENGTH\":\n {'Mixed': 189, 'business': 181, 'entertainment': 171, 'politics': 217, 'sport': 172, 'tech': 211}, # max length of target text (summarize)\n \"SEED\": 42 # set seed for reproducibility \n}",
"_____no_output_____"
],
[
"def T5Trainer(dataframe, valid, finetune, categories, source_text, target_text, model_params, output_dir=\"./outputs/\" ):\n \n \"\"\"\n T5 trainer\n\n \"\"\"\n\n # Set random seeds and deterministic pytorch for reproducibility\n torch.manual_seed(model_params[\"SEED\"]) # pytorch random seed\n np.random.seed(model_params[\"SEED\"]) # numpy random seed\n torch.backends.cudnn.deterministic = True\n\n # logging\n console.log(f\"\"\"[Model]: Loading {model_params[\"MODEL\"]}...\\n\"\"\")\n\n # tokenzier for encoding the text\n tokenizer = T5Tokenizer.from_pretrained(model_params[\"MODEL\"])\n\n # Defining the model. We are using t5-base model and added a Language model layer on top for generation of Summary. \n # Further this model is sent to device (GPU/TPU) for using the hardware.\n model = T5ForConditionalGeneration.from_pretrained(model_params[\"MODEL\"])\n model = model.to(device)\n \n # logging\n console.log(f\"[Data]: Reading data...\\n\")\n\n # Importing the raw dataset\n dataframe_select = dataframe.loc[dataset_finetune['categories'] == finetune]\n max_length = int(model_params[\"MAX_TARGET_TEXT_LENGTH\"][finetune])\n\n # Creation of Dataset and Dataloader\n train_size = 1\n train_dataset = dataframe_select.sample(frac=train_size,random_state = model_params[\"SEED\"]).reset_index(drop=True)\n val_dataset_dict = {}\n for i, category in enumerate(categories):\n dataset_dict[category] = dataset_evaluate.loc[dataset_evaluate['categories'] == category]\n val_dataset_dict[category] = dataset_dict[category].sample(frac=train_size).reset_index(drop=True)\n\n console.print(f\"FULL Dataset: {dataframe_select.shape}\")\n console.print(f\"TRAIN Dataset {finetune}: {train_dataset.shape}\")\n for i, category in enumerate(categories):\n console.print(f\"TEST Dataset {category}: {val_dataset_dict[category].shape}\")\n console.print(\"\\n\")\n\n console.print(f'[MAX_TARGET_TEXT_LENGTH ({finetune})] = {max_length}...\\n')\n\n # Creating the Training and Validation dataset for further creation of Dataloader\n training_set = YourDataSetClass(train_dataset, tokenizer, model_params[\"MAX_SOURCE_TEXT_LENGTH\"], max_length, source_text, target_text)\n \n val_set_dict = {}\n for i, category in enumerate(categories):\n val_set_dict[category] = YourDataSetClass(val_dataset_dict[category], tokenizer, model_params[\"MAX_SOURCE_TEXT_LENGTH\"], max_length, source_text, target_text)\n\n # Defining the parameters for creation of dataloaders\n train_params = {\n 'batch_size': model_params[\"TRAIN_BATCH_SIZE\"],\n 'shuffle': True,\n 'num_workers': 0\n }\n\n val_params = {\n 'batch_size': model_params[\"VALID_BATCH_SIZE\"],\n 'shuffle': False,\n 'num_workers': 0\n }\n\n # Creation of Dataloaders for testing and validation. This will be used down for training and validation stage for the model.\n training_loader = DataLoader(training_set, **train_params)\n val_loader_dict = {}\n for i, category in enumerate(categories):\n val_loader_dict[category] = DataLoader(val_set_dict[category], **val_params)\n\n # Defining the optimizer that will be used to tune the weights of the network in the training session. \n optimizer = torch.optim.Adam(params = model.parameters(), lr=model_params[\"LEARNING_RATE\"])\n\n # Training loop\n console.log(f'[Initiating Fine Tuning]...\\n')\n\n epochs = model_params[\"TRAIN_EPOCHS\"]\n for epoch in range(model_params[\"TRAIN_EPOCHS\"]):\n train(epoch, tokenizer, model, device, training_loader, optimizer, finetune)\n console.log(f\"[Train {epochs} epochs with {finetune} is Completed.]\\n\")\n \n console.log(f\"[Saving Model]...\\n\")\n # Saving the model after training\n path = os.path.join(output_dir, f\"model_files_{finetune}\")\n model.save_pretrained(path)\n tokenizer.save_pretrained(path)\n\n # Evaluating test dataset\n console.log(f\"[Initiating Validation]...\\n\")\n\n final_df_dict = {}\n for i, category in enumerate(categories):\n for epoch in range(model_params[\"VAL_EPOCHS\"]):\n predictions, actuals, texts = validate(epoch, tokenizer, model, device, val_loader_dict[category], max_length)\n actuals_clean = [s.replace(\"summarize: \", \"\") for s in actuals]\n final_df_dict[category] = pd.DataFrame({'Full Text':texts, 'Generated Text':predictions, 'Actual Text':actuals_clean, 'Finetune':finetune, 'Category':category})\n final_df_dict[category].to_csv(os.path.join(output_dir,f'predictions_{finetune}_{category}.csv'), index=False)\n console.log(f\"[Validation with {category} is Completed.]\\n\")\n \n console.save_text(os.path.join(output_dir,f'logs_{finetune}_finetune.txt'))",
"_____no_output_____"
]
],
[
[
"# Start Training & Evaluation",
"_____no_output_____"
]
],
[
[
"T5Trainer(dataframe=dataset_finetune, valid=dataset_dict, finetune='politics', categories=categories, source_text=\"articles\", target_text=\"summaries\", model_params=model_params, output_dir=\"./outputs/\")",
"_____no_output_____"
]
],
[
[
"# Show Train Loss on Tensorboard",
"_____no_output_____"
]
],
[
[
"# %load_ext tensorboard\n%reload_ext tensorboard\n%tensorboard --logdir runs",
"_____no_output_____"
],
[
"# import torch\n# torch.cuda.empty_cache()",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece3f405c8f6d42217961a252fedb70f6921c339 | 31,413 | ipynb | Jupyter Notebook | Market_Data/Yahoo-Finance/Yahoo_Get_stock_data.ipynb | arimbr/awesome-notebooks | 2c79821b57446f6e122f38c4ccb59d7dd3b7a808 | [
"BSD-3-Clause"
] | null | null | null | Market_Data/Yahoo-Finance/Yahoo_Get_stock_data.ipynb | arimbr/awesome-notebooks | 2c79821b57446f6e122f38c4ccb59d7dd3b7a808 | [
"BSD-3-Clause"
] | null | null | null | Market_Data/Yahoo-Finance/Yahoo_Get_stock_data.ipynb | arimbr/awesome-notebooks | 2c79821b57446f6e122f38c4ccb59d7dd3b7a808 | [
"BSD-3-Clause"
] | null | null | null | 209.42 | 28,696 | 0.925604 | [
[
[
"<img width=\"10%\" alt=\"Naas\" src=\"https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160\"/>",
"_____no_output_____"
],
[
"# Yahoo - Get Stock Data",
"_____no_output_____"
],
[
"<img width=\"20%\" alt=\"Naas\" src=\"https://landen.imgix.net/jtci2pxwjczr/assets/vnr9fs3w.png?w=800&h=400&fit=crop\"/>",
"_____no_output_____"
],
[
"### 1. Install the quandl package",
"_____no_output_____"
]
],
[
[
"#!pip install yfinance",
"_____no_output_____"
]
],
[
[
"### 2. Import the quandl package",
"_____no_output_____"
]
],
[
[
"import yfinance as yf",
"_____no_output_____"
]
],
[
[
"### 3. Get the data for the stock AAPL",
"_____no_output_____"
]
],
[
[
"data = yf.download('TSLA','2016-01-01','2019-08-01')",
"[*********************100%***********************] 1 of 1 completed\n"
]
],
[
[
"### 4. Import the plotting library",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### 5. Plot the close price of the AAPL",
"_____no_output_____"
]
],
[
[
"data['Adj Close'].plot()\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece41517b58580fbd7e31bc182b9a95790bea633 | 6,917 | ipynb | Jupyter Notebook | examples/pyolite/folium.ipynb | Muflhi01/jupyterlite | fa985055885cb1d53cccbf6e46ced7d14d38ea06 | [
"BSD-3-Clause"
] | 1,392 | 2021-03-28T01:11:50.000Z | 2022-03-23T21:46:27.000Z | examples/pyolite/folium.ipynb | Muflhi01/jupyterlite | fa985055885cb1d53cccbf6e46ced7d14d38ea06 | [
"BSD-3-Clause"
] | 352 | 2021-07-08T07:32:53.000Z | 2022-03-31T22:06:45.000Z | examples/pyolite/folium.ipynb | Muflhi01/jupyterlite | fa985055885cb1d53cccbf6e46ced7d14d38ea06 | [
"BSD-3-Clause"
] | 58 | 2021-07-08T07:21:45.000Z | 2022-03-19T23:28:25.000Z | 3,458.5 | 6,916 | 0.745699 | [
[
[
"# `folium` Interactive Map Demo\n\nSimple demonstration of rendering a map in a `jupyterlite` notebook.",
"_____no_output_____"
]
],
[
[
"# Install folium requirements\nimport piplite\nawait piplite.install(\"folium\")",
"_____no_output_____"
]
],
[
[
"## Demo of `folium` Map\n\nLoad in the `folium` package:",
"_____no_output_____"
]
],
[
[
"import folium",
"_____no_output_____"
]
],
[
[
"And render a demo map:",
"_____no_output_____"
]
],
[
[
"m = folium.Map(location=[50.693848, -1.304734], zoom_start=11)\nm",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece4442d1875358ec0fccef4ca56339c0caf520f | 744 | ipynb | Jupyter Notebook | .ipynb_checkpoints/1002 - Circle Area (Level 4)-checkpoint.ipynb | Lucas-Lira/Algorithms_solved_in_python_URI_Online_Judge | 6537c5017f44a4cbd127cd6dc88f56bb324f8866 | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/1002 - Circle Area (Level 4)-checkpoint.ipynb | Lucas-Lira/Algorithms_solved_in_python_URI_Online_Judge | 6537c5017f44a4cbd127cd6dc88f56bb324f8866 | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/1002 - Circle Area (Level 4)-checkpoint.ipynb | Lucas-Lira/Algorithms_solved_in_python_URI_Online_Judge | 6537c5017f44a4cbd127cd6dc88f56bb324f8866 | [
"Apache-2.0"
] | null | null | null | 18.6 | 44 | 0.497312 | [
[
[
"try:\n raio = round(float(input()), 2)\n area = 3.14159 * raio ** 2\n print('A=%.4f' % area)\nexcept:\n print('Invalid value')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
ece447c93b5d4c05f740fe0b0e6fb9a57bc8030c | 52,602 | ipynb | Jupyter Notebook | examples/Chron1.0DistOnly.ipynb | brenhinkeller/Chron.jl | 2b459ac3b1f601b116731731c59a882638a9ebdf | [
"MIT"
] | 10 | 2018-04-09T17:13:34.000Z | 2022-01-12T01:59:53.000Z | examples/Chron1.0DistOnly.ipynb | brenhinkeller/Chron.jl | 2b459ac3b1f601b116731731c59a882638a9ebdf | [
"MIT"
] | 2 | 2021-06-03T19:38:46.000Z | 2022-02-21T13:57:02.000Z | examples/Chron1.0DistOnly.ipynb | brenhinkeller/Chron.jl | 2b459ac3b1f601b116731731c59a882638a9ebdf | [
"MIT"
] | 4 | 2021-02-05T03:18:51.000Z | 2022-03-10T19:29:41.000Z | 81.427245 | 33,373 | 0.821813 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
ece449f4546fdee1a59b17455ce533043223ab7d | 69,595 | ipynb | Jupyter Notebook | 2- Regression/projects/week 1/PhillyCrime.ipynb | Magho/Ml-regression-washintgon-course | cfacd62d4741153dcf6116ad9319de550370b066 | [
"MIT"
] | 8 | 2020-11-03T19:45:03.000Z | 2022-02-20T14:04:19.000Z | 2- Regression/projects/week 1/PhillyCrime.ipynb | chitrita/ML-Washington-specialization-coursera | cfacd62d4741153dcf6116ad9319de550370b066 | [
"MIT"
] | null | null | null | 2- Regression/projects/week 1/PhillyCrime.ipynb | chitrita/ML-Washington-specialization-coursera | cfacd62d4741153dcf6116ad9319de550370b066 | [
"MIT"
] | 3 | 2019-03-30T06:09:35.000Z | 2020-12-02T14:30:01.000Z | 75.400867 | 14,440 | 0.678669 | [
[
[
"# Fire up graphlab create",
"_____no_output_____"
]
],
[
[
"import graphlab",
"_____no_output_____"
]
],
[
[
"# Load some house value vs. crime rate data\n\nDataset is from Philadelphia, PA and includes average house sales price in a number of neighborhoods. The attributes of each neighborhood we have include the crime rate ('CrimeRate'), miles from Center City ('MilesPhila'), town name ('Name'), and county name ('County').",
"_____no_output_____"
]
],
[
[
"sales = graphlab.SFrame.read_csv('Philadelphia_Crime_Rate_noNA.csv/')",
"[INFO] graphlab.cython.cy_server: GraphLab Create v2.1 started. Logging: /tmp/graphlab_server_1529941819.log\n"
],
[
"sales",
"_____no_output_____"
]
],
[
[
"# Exploring the data ",
"_____no_output_____"
],
[
"The house price in a town is correlated with the crime rate of that town. Low crime towns tend to be associated with higher house prices and vice versa.",
"_____no_output_____"
]
],
[
[
"graphlab.canvas.set_target('ipynb')\nsales.show(view=\"Scatter Plot\", x=\"CrimeRate\", y=\"HousePrice\")",
"_____no_output_____"
]
],
[
[
"# Fit the regression model using crime as the feature",
"_____no_output_____"
]
],
[
[
"crime_model = graphlab.linear_regression.create(sales, target='HousePrice', features=['CrimeRate'],validation_set=None,verbose=False)",
"_____no_output_____"
]
],
[
[
"# Let's see what our fit looks like",
"_____no_output_____"
],
[
"Matplotlib is a Python plotting library that is also useful for plotting. You can install it with:\n\n'pip install matplotlib'",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"plt.plot(sales['CrimeRate'],sales['HousePrice'],'.',\n sales['CrimeRate'],crime_model.predict(sales),'-')",
"_____no_output_____"
]
],
[
[
"Above: blue dots are original data, green line is the fit from the simple regression.",
"_____no_output_____"
],
[
"# Remove Center City and redo the analysis",
"_____no_output_____"
],
[
"Center City is the one observation with an extremely high crime rate, yet house prices are not very low. This point does not follow the trend of the rest of the data very well. A question is how much including Center City is influencing our fit on the other datapoints. Let's remove this datapoint and see what happens.",
"_____no_output_____"
]
],
[
[
"sales_noCC = sales[sales['MilesPhila'] != 0.0] ",
"_____no_output_____"
],
[
"sales_noCC.show(view=\"Scatter Plot\", x=\"CrimeRate\", y=\"HousePrice\")",
"_____no_output_____"
]
],
[
[
"### Refit our simple regression model on this modified dataset:",
"_____no_output_____"
]
],
[
[
"crime_model_noCC = graphlab.linear_regression.create(sales_noCC, target='HousePrice', features=['CrimeRate'],validation_set=None, verbose=False)",
"_____no_output_____"
]
],
[
[
"### Look at the fit:",
"_____no_output_____"
]
],
[
[
"plt.plot(sales_noCC['CrimeRate'],sales_noCC['HousePrice'],'.',\n sales_noCC['CrimeRate'],crime_model.predict(sales_noCC),'-')",
"_____no_output_____"
]
],
[
[
"# Compare coefficients for full-data fit versus no-Center-City fit",
"_____no_output_____"
],
[
"Visually, the fit seems different, but let's quantify this by examining the estimated coefficients of our original fit and that of the modified dataset with Center City removed.",
"_____no_output_____"
]
],
[
[
"crime_model.get('coefficients')",
"_____no_output_____"
],
[
"crime_model_noCC.get('coefficients')",
"_____no_output_____"
]
],
[
[
"Above: We see that for the \"no Center City\" version, per unit increase in crime, the predicted decrease in house prices is 2,287. In contrast, for the original dataset, the drop is only 576 per unit increase in crime. This is significantly different!",
"_____no_output_____"
],
[
"### High leverage points: \nCenter City is said to be a \"high leverage\" point because it is at an extreme x value where there are not other observations. As a result, recalling the closed-form solution for simple regression, this point has the *potential* to dramatically change the least squares line since the center of x mass is heavily influenced by this one point and the least squares line will try to fit close to that outlying (in x) point. If a high leverage point follows the trend of the other data, this might not have much effect. On the other hand, if this point somehow differs, it can be strongly influential in the resulting fit.\n\n### Influential observations: \nAn influential observation is one where the removal of the point significantly changes the fit. As discussed above, high leverage points are good candidates for being influential observations, but need not be. Other observations that are *not* leverage points can also be influential observations (e.g., strongly outlying in y even if x is a typical value).",
"_____no_output_____"
],
[
"# Remove high-value outlier neighborhoods and redo analysis",
"_____no_output_____"
],
[
"Based on the discussion above, a question is whether the outlying high-value towns are strongly influencing the fit. Let's remove them and see what happens.",
"_____no_output_____"
]
],
[
[
"sales_nohighend = sales_noCC[sales_noCC['HousePrice'] < 350000] \ncrime_model_nohighend = graphlab.linear_regression.create(sales_nohighend, target='HousePrice', features=['CrimeRate'],validation_set=None, verbose=False)",
"_____no_output_____"
]
],
[
[
"### Do the coefficients change much?",
"_____no_output_____"
]
],
[
[
"crime_model_noCC.get('coefficients')",
"_____no_output_____"
],
[
"crime_model_nohighend.get('coefficients')",
"_____no_output_____"
]
],
[
[
"Above: We see that removing the outlying high-value neighborhoods has *some* effect on the fit, but not nearly as much as our high-leverage Center City datapoint.",
"_____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",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
ece44a75eec8d3fc4127b8b1413bab89dc9a2668 | 9,938 | ipynb | Jupyter Notebook | day three/multiple_linear_regression.ipynb | aswnss-m/ras_ml_bootcamp | 46bcf88749de6bce25205a30217bd6f1a8ab2554 | [
"MIT"
] | null | null | null | day three/multiple_linear_regression.ipynb | aswnss-m/ras_ml_bootcamp | 46bcf88749de6bce25205a30217bd6f1a8ab2554 | [
"MIT"
] | null | null | null | day three/multiple_linear_regression.ipynb | aswnss-m/ras_ml_bootcamp | 46bcf88749de6bce25205a30217bd6f1a8ab2554 | [
"MIT"
] | null | null | null | 29.754491 | 129 | 0.446871 | [
[
[
"#importing dependencies\nimport pandas as pd\nimport numpy as np\nimport pickle\n#Encoding modules\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\n\n#linear Regression modules\nfrom sklearn import linear_model, model_selection",
"_____no_output_____"
],
[
"dataset = pd.read_csv('/home/aswnss/Coding/Python/Machine-Learning-Projects/ras ml/datasets/Startups.csv',sep=',')\ndataset.head()",
"_____no_output_____"
],
[
"# Encoding the Column State\nLabel_Encode = LabelEncoder()\ndataset['State'] = Label_Encode.fit_transform(dataset['State'])\ndataset.head()\n\n",
"_____no_output_____"
],
[
"ct = ColumnTransformer( [('State', OneHotEncoder(),[3])], remainder='passthrough' )\ndataset = ct.fit_transform(dataset)",
"_____no_output_____"
],
[
"# numpy array alicing [rows , column]\ny = dataset[:,-1] # All rows of last column \nX = dataset[:,:-1] # All rows till second last column\n",
"_____no_output_____"
],
[
"## Uncomment and run this to train model again\n## last trained modelaccuracy max accuracy = 0.9968765816617785\n\n# max_ac = -1\n# for _ in range(100):\n# x_train,x_test,y_train,y_test = model_selection.train_test_split(X,y,test_size=0.1)\n# Model = linear_model.LinearRegression()\n# Model = Model.fit(x_train,y_train)\n# accuracy = Model.score(x_test,y_test)\n# if accuracy > max_ac:\n# max_ac = accuracy\n# with open('Startup_model.pickle','wb') as f:\n# pickle.dump(Model,f)\n# print(\"max accuracy = \",max_ac)",
"max accuracy = 0.9968765816617785\n"
],
[
"pickle_in = open('Startup_model.pickle','rb')\nModel = pickle.load(pickle_in)",
"_____no_output_____"
],
[
"x_train,x_test,y_train,y_test = model_selection.train_test_split(X,y,test_size=0.1)\nprediction = Model.predict(x_test)\nfor i in range(len(prediction)):\n print(\"Predicted Profit : {} Actual Profit : {} Loss : {}\".format(prediction[i],y_test[i],y_test[i]-prediction[i]))",
"Predicted Profit : 154425.16014930804 Actual Profit : 149759.96 Loss : -4665.200149308046\nPredicted Profit : 49814.208659203054 Actual Profit : 35673.41 Loss : -14140.79865920305\nPredicted Profit : 98891.22511990316 Actual Profit : 97427.84 Loss : -1463.3851199031633\nPredicted Profit : 83659.1371722173 Actual Profit : 81005.76 Loss : -2653.3771722173115\nPredicted Profit : 129847.48769590256 Actual Profit : 125370.37 Loss : -4477.1176959025615\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece46425c3e9c2cb99b361cf31d9ad0abf3ae2f4 | 7,144 | ipynb | Jupyter Notebook | machine_learning/lecture/week_1/iii_linear_algebra_review_week_1_optional/.ipynb_checkpoints/Linear Algebra Review-checkpoint.ipynb | Rabeeah/coursera-stanford | f6f8087e3db936e1125ae590edcb6d3f189c1d8b | [
"MIT"
] | 4 | 2022-01-19T14:46:36.000Z | 2022-01-20T08:32:11.000Z | machine_learning/lecture/week_1/iii_linear_algebra_review_week_1_optional/Linear Algebra Review.ipynb | DineshBafila-DS/coursera-stanford | f6f8087e3db936e1125ae590edcb6d3f189c1d8b | [
"MIT"
] | null | null | null | machine_learning/lecture/week_1/iii_linear_algebra_review_week_1_optional/Linear Algebra Review.ipynb | DineshBafila-DS/coursera-stanford | f6f8087e3db936e1125ae590edcb6d3f189c1d8b | [
"MIT"
] | 3 | 2016-01-25T02:58:20.000Z | 2016-04-10T18:35:26.000Z | 26.264706 | 170 | 0.56397 | [
[
[
"#Table of Contents\n* [Matrices and Vectors](#Matrices-and-Vectors)\n* [Addition and Scalar Multiplication](#Addition-and-Scalar-Multiplication)\n* [Matrix Vectore Multiplication](#Matrix-Vectore-Multiplication)\n\t* [(Linear Regression) Predict house prices with matrix vector multiplication](#%28Linear-Regression%29-Predict-house-prices-with-matrix-vector-multiplication)\n* [Matrix Matrix Multiplication](#Matrix-Matrix-Multiplication)\n\t* [Predict house prices with matrix matrix multiplication](#Predict-house-prices-with-matrix-matrix-multiplication)\n* [Matrix Multiplication Properties](#Matrix-Multiplication-Properties)\n* [Inverse and Transpose](#Inverse-and-Transpose)\n",
"_____no_output_____"
],
[
"# Matrices and Vectors",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic1.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/38jIT/matrices-and-vectors) 2:26*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic2.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/38jIT/matrices-and-vectors) 6:16*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"# Addition and Scalar Multiplication",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic3.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/R4hiJ/addition-and-scalar-multiplication) 1:53*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic4.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/R4hiJ/addition-and-scalar-multiplication) 4:01*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic5.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/R4hiJ/addition-and-scalar-multiplication) 6:40*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"# Matrix Vectore Multiplication",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic6.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/aQDta/matrix-vector-multiplication) 5:15*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic7.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/aQDta/matrix-vector-multiplication) 7:28*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"## (Linear Regression) Predict house prices with matrix vector multiplication",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic8.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/aQDta/matrix-vector-multiplication) 13:05*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"# Matrix Matrix Multiplication",
"_____no_output_____"
],
[
"- Multiply the left matrix with each column (vector) in the right matrix",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic9.png\">\n<img src=\"images/lec3_pic10.png\">\n<img src=\"images/lec3_pic11.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/dpF1j/matrix-matrix-multiplication) 7:33*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"## Predict house prices with matrix matrix multiplication",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic12.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/dpF1j/matrix-matrix-multiplication) 10:17*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"# Matrix Multiplication Properties",
"_____no_output_____"
],
[
"- Commutative: 3 x 5 = 5 x 3\n- Let A and B be matrices. Then in general, A x B $\\neq$ B x A (not commutative)\n- Matrices are associative: A x (B x C) = (A x B) x C\n- Identity Matrix\n - Denoted I (or $I_{n x n}$)\n - Example identity matrices:\n \\begin{bmatrix}\n 1 & 0 & 0 \\\\\n 0 & 1 & 0 \\\\\n 0 & 0 & 1 \\\\\n \\end{bmatrix}\n- For any matrix A,\n - A . I = I . A = A\n \n",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic13.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/W1LNU/matrix-multiplication-properties) 8:39*\n\n<!--TEASER_END-->",
"_____no_output_____"
],
[
"# Inverse and Transpose",
"_____no_output_____"
],
[
"- Not all numbers have an inverse\n- Matrix inverse:\n - If A is an m x m matrix, and if it has an inverse: $A(A^{-1}) = A^{-1}A = I$\n- Matrix transpose:\n - Let A be an m x n matrix, and let $B = A^{T}$\n - Then B is an n x m matrix",
"_____no_output_____"
],
[
"<img src=\"images/lec3_pic14.png\">\n\n*Screenshot taken from [Coursera](https://www.coursera.org/learn/machine-learning/lecture/FuSWY/inverse-and-transpose) 9:38*\n\n<!--TEASER_END-->",
"_____no_output_____"
]
]
] | [
"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"
]
] |
ece46725adefff64a65622c5e4e42e01b8a2ef36 | 34,142 | ipynb | Jupyter Notebook | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/iotedge/05_DeployOnIOTedge.ipynb | dciborow/AIArchitecturesAndPractices | a3d7588d9f4eb9e71867c9f9098643233ccb5db1 | [
"MIT"
] | 1 | 2021-07-07T02:07:25.000Z | 2021-07-07T02:07:25.000Z | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/iotedge/05_DeployOnIOTedge.ipynb | dciborow/AIArchitecturesAndPractices | a3d7588d9f4eb9e71867c9f9098643233ccb5db1 | [
"MIT"
] | 3 | 2019-08-15T16:31:42.000Z | 2019-08-16T12:36:19.000Z | architectures/Python-ML-RealTimeServing/{{cookiecutter.project_name}}/iotedge/05_DeployOnIOTedge.ipynb | dciborow/AIArchitecturesAndPractices | a3d7588d9f4eb9e71867c9f9098643233ccb5db1 | [
"MIT"
] | 1 | 2019-08-15T15:49:46.000Z | 2019-08-15T15:49:46.000Z | 38.275785 | 7,742 | 0.63766 | [
[
[
"Copyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the MIT License.",
"_____no_output_____"
],
[
"# Deploying a ML module on IoT Edge Device\n\n\nIn this notebook, we introduce the steps of deploying an ML module on [Azure IoT Edge](https://docs.microsoft.com/en-us/azure/iot-edge/how-iot-edge-works). The purpose is to deploy a trained machine learning model to the edge device. When the input data is generated from a particular process pipeline and fed into the edge device, the deployed model is able to make predictions right on the edge device without accessing to the cloud. \n\n\n## Outline<a id=\"BackToTop\"></a>\n- [Prerequisites](#prerequisite)\n- [Step 1: Create an IoT Hub and Register an IoT Edge device](#step1)\n- [Step 2: Provision and Configure IoT Edge Device](#step2)\n- [Step 3: Deploy ML Module on IoT Edge Device](#step3)\n- [Step 4: Test ML Module](#step4)\n- [Clean up resource](#cleanup)",
"_____no_output_____"
],
[
"## Prerequisites <a id=\"Prerequisite\"></a>\n\n- Satisfy the requirment specified in Sections `Prerequisites` and `Setup` in the repo's [README page](./README.md).\n\n- Build the trained ML Model into a docker image. \n \n - You have two options to satisfy this requirment. The first option is to complete all the notebooks from [00_AML_Configuration.ipynb](./00_AMLConfiguration.ipynb) through [04_CreateImage.ipynb](./04_CreateImage.ipynb). In this tutorial, we show the steps when using this option. The second option is to use a prebuilt docker image created by the user. Instructions need to be adjusted to proceed with this option.",
"_____no_output_____"
]
],
[
[
"import sys\nimport pandas as pd\nimport requests\nimport numpy as np\nimport json\nimport docker\nimport time\n\nfrom azureml.core import Workspace\nfrom azureml.core.image import Image\nfrom azureml.core.workspace import Workspace\nfrom azureml.core.conda_dependencies import CondaDependencies\nfrom azure.mgmt.containerregistry import ContainerRegistryManagementClient\nfrom azure.mgmt import containerregistry\nfrom dotenv import set_key, get_key, find_dotenv\n\nfrom utilities import text_to_json, get_auth",
"_____no_output_____"
],
[
"env_path = find_dotenv(raise_error_if_not_found=True)",
"_____no_output_____"
]
],
[
[
"## Step 1 Create an IoT Hub and Register an IoT Edge device <a id=\"step1\"></a>\n\nFor more infromation, please check Sections `Create an IoT hub` and `Register an IoT Edge device` in document [Deploy Azure IoT Edge on a simulated device in Linux or MacOS - preview](https://docs.microsoft.com/en-us/azure/iot-edge/tutorial-simulate-device-linux). When creating IoT hub, we assume you use the same resource group as the one created in [00_AML_Configuration.ipynb](./00_AML_Configuration.ipynb). ",
"_____no_output_____"
],
[
"### Get workspace\n\nLoad existing workspace from the config file.",
"_____no_output_____"
]
],
[
[
"ws = Workspace.from_config(auth=get_auth(env_path))\nprint(ws.name, ws.resource_group, ws.location, sep=\"\\n\")",
"_____no_output_____"
],
[
"iot_hub_name = \"<YOUR_IOT_HUB_NAME>\" # a UNIQUE name is required, e.g. \"fstlstnameiothub\". Avoid too simple name such as \"myiothub\".\ndevice_id = \"<YOUR_EDGE_DEVICE_NAME>\" # the name you give to the edge device. e.g. device_id = 'mydevice'\nmodule_name = \"<YOUR_MODULE_NAME>\" # the module name. e.g. module_name = 'mymodule'",
"_____no_output_____"
],
[
"set_key(env_path, \"iot_hub_name\", iot_hub_name)\nset_key(env_path, \"device_id\", device_id)\nset_key(env_path, \"module_name\", module_name)",
"_____no_output_____"
],
[
"iot_hub_name = get_key(env_path, 'iot_hub_name')\ndevice_id = get_key(env_path, 'device_id')\nmodule_name = get_key(env_path, 'module_name')\nresource_group = get_key(env_path, 'resource_group')\nimage_name = get_key(env_path, 'image_name')",
"_____no_output_____"
]
],
[
[
"### Install az-cli iot extension ",
"_____no_output_____"
]
],
[
[
"accounts = !az account list --all -o tsv\nif \"Please run \\\"az login\\\" to access your accounts.\" in accounts[0]:\n !az login -o table\nelse:\n print(\"Already logged in\")",
"_____no_output_____"
]
],
[
[
"### Create IoT Hub\n\nThe following code creates a free F1 hub with name `iot_hub_name` in the resource group `resource_group`.\n\nCommon issue and resolution are shown below.\n\n(1) See error message \"Resource group `<resource_group>` could not be found\". You may forget to set which Azure subscription to use. Run command `az account set --subscription <subscription_id>` to set your subscription.\n\n(2) See error message \"Max number of Iot Hubs exceeded for sku = Free, Max Allowed = 1, Current = 2 in the subscription Id: `<subscription_id>`.\" This error message indicates that the quota is reached for creating the specific type of IoT Hub resource in Azure.",
"_____no_output_____"
]
],
[
[
"!az extension add --name azure-cli-iot-ext\n!az iot hub list --resource-group $resource_group -o table",
"_____no_output_____"
],
[
"!az iot hub create --resource-group $resource_group --name $iot_hub_name --sku F1 ",
"_____no_output_____"
]
],
[
[
"### Register an IoT Edge device\n\nIn the Azure cloud shell, enter the following command to create a device with name `device_id` in your iot hub.",
"_____no_output_____"
]
],
[
[
"!az iot hub device-identity create --hub-name $iot_hub_name --device-id $device_id --edge-enabled -g $resource_group",
"_____no_output_____"
]
],
[
[
"Obtain `device_connection_string`. It will be used in the next step.",
"_____no_output_____"
]
],
[
[
"json_data = !az iot hub device-identity show-connection-string --device-id $device_id --hub-name $iot_hub_name -g $resource_group\nprint(json_data)",
"_____no_output_____"
],
[
"device_connection_string = json.loads(''.join([i for i in json_data if 'WARNING' not in i]))['connectionString']\nprint(device_connection_string)",
"_____no_output_____"
]
],
[
[
"## Step 2 Provision and Configure IoT Edge Device <a id=\"step2\"></a>\n\nIn this tutorial, we use a NC6 Ubuntu Linux VM as the edge device, which is the same Linux VM where you run the current notebook. The goal is to configure the edge device so that it can run [Docker](https://docs.docker.com/v17.12/install/linux/docker-ee/ubuntu), [nvidia-docker](https://github.com/NVIDIA/nvidia-docker), and [IoT Edge runtime](https://docs.microsoft.com/en-us/azure/iot-edge/how-to-install-iot-edge-linux). If another device is used as the edge device, instructions need to be adjusted accordingly. ",
"_____no_output_____"
],
[
"### Register Microsoft key and software repository feed\n\nPrepare your device for the IoT Edge runtime installation.",
"_____no_output_____"
]
],
[
[
"# Install the repository configuration. Replace <release> with 16.04 or 18.04 as appropriate for your release of Ubuntu.\nrelease = !lsb_release -r\nrelease = release[0].split('\\t')[1]\nprint(release)",
"16.04\n"
],
[
"!curl https://packages.microsoft.com/config/ubuntu/$release/prod.list > ./microsoft-prod.list",
"_____no_output_____"
],
[
"# Copy the generated list.\n!sudo cp ./microsoft-prod.list /etc/apt/sources.list.d/",
"_____no_output_____"
],
[
"#Install Microsoft GPG public key\n!curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\n!sudo cp ./microsoft.gpg /etc/apt/trusted.gpg.d/",
"_____no_output_____"
]
],
[
[
"### Install the Azure IoT Edge Security Daemon\n\nThe IoT Edge security daemon provides and maintains security standards on the IoT Edge device. The daemon starts on every boot and bootstraps the device by starting the rest of the IoT Edge runtime.\nThe installation command also installs the standard version of the iothsmlib if not already present.",
"_____no_output_____"
]
],
[
[
"# Perform apt update.\n!sudo apt-get update",
"_____no_output_____"
],
[
"# Install the security daemon. The package is installed at /etc/iotedge/.\n!sudo apt-get install iotedge -y --no-install-recommends",
"_____no_output_____"
]
],
[
[
"### Configure the Azure IoT Edge Security \n\nConfigure the IoT Edge runtime to link your physical device with a device identity that exists in an Azure IoT hub.\nThe daemon can be configured using the configuration file at /etc/iotedge/config.yaml. The file is write-protected by default, you might need elevated permissions to edit it.",
"_____no_output_____"
]
],
[
[
"# Manual provisioning IoT edge device\n!sudo sed -i \"s#\\(device_connection_string: \\).*#\\1\\\"$device_connection_string\\\"#g\" /etc/iotedge/config.yaml",
"_____no_output_____"
],
[
"# restart the daemon\n!sudo systemctl restart iotedge\ntime.sleep(10) # Wait 10 seconds for iotedge to restart",
"_____no_output_____"
],
[
"# restart the daemon again\n!sudo systemctl restart iotedge",
"_____no_output_____"
]
],
[
[
"### Disable process identification\n\nWhile in preview, Azure Machine Learning does not support the process identification security feature enabled by default with IoT Edge. Below are the steps to disable it. This is however not suitable for use in production. These steps are only necessary on Linux, as you will have completed this during the Windows Edge runtime installation.\n\nTo disable process identification on your IoT edge device, you'll need to provide the ip address and port for workload_uri and management_uri in the connect section of the IoT Edge daemon configuration.\n\nGet the IP address first. Enter `ifconfig` in your command line and copy the IP address of the docker0 interface.\n\nFor more information, please check section `Disable process identification` of document [Tutorial: Deploy Azure Machine Learning as an IoT Edge module ](https://docs.microsoft.com/en-us/azure/iot-edge/tutorial-deploy-machine-learning).",
"_____no_output_____"
]
],
[
[
"output_data = !ifconfig\nip_docker0 = output_data[1].split(\":\")[1].split()[0]\nprint(ip_docker0)",
"172.17.0.1\n"
],
[
"management_uri = 'http://{}:15580'.format(ip_docker0)\nworkload_uri = 'http://{}:15581'.format(ip_docker0)",
"_____no_output_____"
],
[
"!sudo sed -i \"s#\\(management_uri: \\).*#\\1\\\"$management_uri\\\"#g\" /etc/iotedge/config.yaml\n!sudo sed -i \"s#\\(workload_uri: \\).*#\\1\\\"$workload_uri\\\"#g\" /etc/iotedge/config.yaml",
"_____no_output_____"
],
[
"# restart the daemon\n!sudo systemctl restart iotedge\ntime.sleep(10) # Wait 10 seconds for iotedge to restsrt",
"_____no_output_____"
]
],
[
[
"### Verify successful installation",
"_____no_output_____"
]
],
[
[
"# check the status of the IoT Edge Daemon\n!systemctl status iotedge",
"_____no_output_____"
],
[
"# Examine daemon logs\n!journalctl -u iotedge --no-pager --no-full",
"_____no_output_____"
]
],
[
[
"When you run `docker ps` command in the edge device, you should see `edgeAgent` container is up running.",
"_____no_output_____"
]
],
[
[
"!docker ps",
"_____no_output_____"
]
],
[
[
"### (Optional) Alternative Approach to Configure IoT Edge Device\n\nUse this approach if your edge device is a different server than the host server. Note that your edge device must satisfy following prequequisites:\n\n- Linux (x64)\n- Docker installed\n\nStep 1: run appropriate cells above to get the value for following variable.\n\n- device_connection_string\n\n\nStep 2: run approprate commands on the edge device to get values for following variables.\n\n- release\n- management_uri\n- workload_uri\n\nStep 3: run next cell to generate *deviceconfig.sh* file. \n\nStep 4: run all the commands in *deviceconfig.sh* file on your edge device. \n",
"_____no_output_____"
]
],
[
[
"file = open('./deviceconfig_template.sh')\ncontents = file.read()\ncontents = contents.replace('__release', release)\ncontents = contents.replace('__device_connection_string', device_connection_string)\ncontents = contents.replace('__management_uri', management_uri)\ncontents = contents.replace('__workload_uri', workload_uri)\n\nwith open('./deviceconfig.sh', 'wt', encoding='utf-8') as output_file:\n output_file.write(contents)",
"_____no_output_____"
]
],
[
[
"## Step 3: Deploy the ML module <a id=\"step3\"></a>\n\nFor more information, please check instructions from [this doc](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-deploy-and-where).",
"_____no_output_____"
]
],
[
[
"docker_client = docker.APIClient(base_url='unix://var/run/docker.sock')",
"_____no_output_____"
],
[
"# get the image from workspace in case the 'image' object is not in the memory\nimage_name = get_key(env_path, 'image_name')\nimage = ws.images[image_name]",
"_____no_output_____"
],
[
"# Getting your container details\ncontainer_reg = ws.get_details()[\"containerRegistry\"]\nreg_name=container_reg.split(\"/\")[-1]\ncontainer_url = \"\\\"\" + image.image_location + \"\\\",\"\nsubscription_id = ws.subscription_id\n\nclient = ContainerRegistryManagementClient(ws._auth,subscription_id)\nresult= client.registries.list_credentials(resource_group, reg_name, custom_headers=None, raw=False)\nusername = result.username\npassword = result.passwords[0].value\nprint('ContainerURL:{}'.format(image.image_location))\nprint('Servername: {}'.format(reg_name))\nprint('Username: {}'.format(username))\nprint('Password: {}'.format(password))",
"_____no_output_____"
],
[
"file = open('MLmodule_deployment_template.json')\ncontents = file.read()\ncontents = contents.replace('__MODULE_NAME', module_name)\ncontents = contents.replace('__REGISTRY_NAME', reg_name)\ncontents = contents.replace('__REGISTRY_USER_NAME', username)\ncontents = contents.replace('__REGISTRY_PASSWORD', password)\ncontents = contents.replace('__REGISTRY_IMAGE_LOCATION', image.image_location)\nwith open('./deployment.json', 'wt', encoding='utf-8') as output_file:\n output_file.write(contents)",
"_____no_output_____"
],
[
"# Push the deployment JSON to the IOT Hub\n!az iot edge set-modules --device-id $device_id \\\n --hub-name $iot_hub_name \\\n --content deployment.json \\\n -g $resource_group",
"_____no_output_____"
]
],
[
[
"You can check the logs of the ML module with using the command in the next cell. **Note that if your edge device differs from the host server, you need to run this command on the edge device.** \n\nCommon issue and resolution are shown below.\n\nAn error message \"Error: No such container: module_name\" is shown. Resolution - Please wait for a couple minutes and run this command again. The container is starting up. ",
"_____no_output_____"
]
],
[
[
"!docker logs -f $module_name",
"_____no_output_____"
],
[
"def get_id(container_name):\n contents = docker_client.containers()\n for cont in contents:\n if container_name in cont['Names'][0]:\n return cont[\"Id\"]\n return None",
"_____no_output_____"
],
[
"d_id = get_id(module_name)\nwhile d_id is None:\n d_id = get_id(module_name)\n time.sleep(1)",
"_____no_output_____"
],
[
"logs = docker_client.attach(d_id, stream=True, logs=True)",
"_____no_output_____"
],
[
"# keep running this cell until the log contains \"Using TensorFlow backend\", which indicates the container is up running.\nfor l in logs:\n msg = l.decode('utf-8')\n print(msg)\n if \"Opened module client connection\" in msg:\n break ",
"_____no_output_____"
]
],
[
[
"When you run `docker ps` command in the edge device, you should see there are three containers running: `edgeAgent`, `edgeHub`, and the container with name `module_name`.",
"_____no_output_____"
],
[
"## Step 4: Test ML Module <a id=\"step4\"></a>\nWe now test the ML Module from iot Edge device.",
"_____no_output_____"
]
],
[
[
"dupes_test_path = './data_folder/dupes_test.tsv'\ndupes_test = pd.read_csv(dupes_test_path, sep='\\t', encoding='latin1')\ntext_to_score = dupes_test.iloc[0,4]\ntext_to_score",
"_____no_output_____"
],
[
"jsontext = text_to_json(text_to_score)",
"_____no_output_____"
]
],
[
[
"Let's try a few more duplicate questions and display their top 3 original matches. Let's first get the scoring URL and and API key for the web service.",
"_____no_output_____"
]
],
[
[
"scoring_url = 'http://localhost:5001/score'",
"_____no_output_____"
],
[
"# call the web service end point\nheaders = {'Content-Type':'application/json'}\nresponse = requests.post(scoring_url, data=jsontext, headers=headers)\nresponse",
"_____no_output_____"
],
[
"prediction = json.loads(response.content.decode('ascii'))\nprediction",
"_____no_output_____"
],
[
"dupes_to_score = dupes_test.iloc[:5,4]",
"_____no_output_____"
],
[
"results = [\n requests.post(scoring_url, data=text_to_json(text), headers=headers)\n for text in dupes_to_score\n]",
"_____no_output_____"
]
],
[
[
"Let's print top 3 matches for each duplicate question.",
"_____no_output_____"
]
],
[
[
"[eval(results[i].json())[0:3] for i in range(0, len(results))]",
"_____no_output_____"
]
],
[
[
"Next let's quickly check what the request response performance is for the deployed model on IoT edge device.",
"_____no_output_____"
]
],
[
[
"text_data = list(map(text_to_json, dupes_to_score)) # Retrieve the text data",
"_____no_output_____"
],
[
"timer_results = list()\nfor text in text_data:\n res=%timeit -r 1 -o -q requests.post(scoring_url, data=text, headers=headers)\n timer_results.append(res.best)",
"_____no_output_____"
],
[
"timer_results",
"_____no_output_____"
],
[
"print(\"Average time taken: {0:4.2f} ms\".format(10 ** 3 * np.mean(timer_results)))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
ece46a5ef2baccc7db4123c002bf434cae71ca79 | 4,390 | ipynb | Jupyter Notebook | notebook/operator_itemgetter_timeit.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 174 | 2018-05-30T21:14:50.000Z | 2022-03-25T07:59:37.000Z | notebook/operator_itemgetter_timeit.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 5 | 2019-08-10T03:22:02.000Z | 2021-07-12T20:31:17.000Z | notebook/operator_itemgetter_timeit.ipynb | puyopop/python-snippets | 9d70aa3b2a867dd22f5a5e6178a5c0c5081add73 | [
"MIT"
] | 53 | 2018-04-27T05:26:35.000Z | 2022-03-25T07:59:37.000Z | 18.368201 | 82 | 0.453986 | [
[
[
"import operator",
"_____no_output_____"
],
[
"l = [{'k1': i} for i in range(10000)]",
"_____no_output_____"
],
[
"print(len(l))",
"10000\n"
],
[
"print(l[:5])",
"[{'k1': 0}, {'k1': 1}, {'k1': 2}, {'k1': 3}, {'k1': 4}]\n"
],
[
"print(l[-5:])",
"[{'k1': 9995}, {'k1': 9996}, {'k1': 9997}, {'k1': 9998}, {'k1': 9999}]\n"
],
[
"%%timeit\nsorted(l, key=lambda x: x['k1'])",
"1.09 ms ± 35 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"%%timeit\nsorted(l, key=operator.itemgetter('k1'))",
"716 µs ± 28.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"%%timeit\nsorted(l, key=lambda x: x['k1'], reverse=True)",
"1.11 ms ± 41.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"%%timeit\nsorted(l, key=operator.itemgetter('k1'), reverse=True)",
"768 µs ± 58.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"%%timeit\nmax(l, key=lambda x: x['k1'])",
"1.33 ms ± 130 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"%%timeit\nmax(l, key=operator.itemgetter('k1'))",
"813 µs ± 54.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"%%timeit\nmin(l, key=lambda x: x['k1'])",
"1.27 ms ± 69.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"%%timeit\nmin(l, key=operator.itemgetter('k1'))",
"824 µs ± 83.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece4757b92ea06ec9fc1742ebae572ec1c174160 | 4,074 | ipynb | Jupyter Notebook | RingFinding2.ipynb | hwpang/misc_scripts | 73c1af452d55a3a602f382a17802697a14d69379 | [
"MIT"
] | null | null | null | RingFinding2.ipynb | hwpang/misc_scripts | 73c1af452d55a3a602f382a17802697a14d69379 | [
"MIT"
] | null | null | null | RingFinding2.ipynb | hwpang/misc_scripts | 73c1af452d55a3a602f382a17802697a14d69379 | [
"MIT"
] | 2 | 2019-09-19T19:25:12.000Z | 2021-01-13T20:20:17.000Z | 21.329843 | 81 | 0.526019 | [
[
[
"import py_rdl\nfrom py_rdl.wrapper import DataInternal\nimport timeit\nimport numpy as np\nfrom IPython.display import display",
"_____no_output_____"
],
[
"from rmgpy.molecule import Molecule\nfrom rmgpy.molecule.graph import Vertex, Edge, Graph",
"_____no_output_____"
],
[
"m = Molecule(SMILES='c1ccccc1')\ndisplay(m)\nprint m.toAdjacencyList()",
"_____no_output_____"
],
[
"sssr = m.getSmallestSetOfSmallestRings()\n[atom.label for atom in sssr[0]]",
"_____no_output_____"
],
[
"m.atoms[0].label = '1'\nm.atoms[1].label = '2'\nm.atoms[2].label = '3'\nm.atoms[3].label = '4'\nm.atoms[4].label = '5'\nm.atoms[5].label = '6'",
"_____no_output_____"
],
[
"m.getSmallestSetOfSmallestRings()",
"_____no_output_____"
],
[
"setup = \"\"\"\nimport py_rdl\nfrom py_rdl.wrapper import DataInternal\nfrom rmgpy.molecule import Molecule\nm = Molecule(SMILES='C12C3C4C1C1C2C3C41')\n\"\"\"\n\ntest = \"\"\"\ngraph = py_rdl.Graph.from_edges(\n m.edges,\n lambda x: x.vertex1,\n lambda x: x.vertex2,\n)\n\ndata = DataInternal(graph.get_nof_nodes(), graph.get_edges().iterkeys())\ndata.calculate()\nrc = []\nfor cycle in data.get_rcs():\n rc.append([graph.get_node_for_index(i) for i in cycle.nodes])\n\"\"\"",
"_____no_output_____"
],
[
"result = timeit.repeat(test, setup, repeat=10, number=100)\nresult = np.array(result)\nprint np.mean(result), np.std(result)",
"_____no_output_____"
],
[
"graph = py_rdl.Graph.from_edges(\n m.edges,\n lambda x: x.vertex1,\n lambda x: x.vertex2,\n)\n\ndata = DataInternal(graph.get_nof_nodes(), graph.get_edges().iterkeys())\ndata.calculate()\nrc = []\nfor cycle in data.get_rcs():\n rc.append([graph.get_node_for_index(i) for i in cycle.nodes])\nsssr = []\nfor cycle in data.get_sssr():\n sssr.append([graph.get_node_for_index(i) for i in cycle.nodes])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece483b8419e6b761b0173787a5e2898805e41d9 | 85,810 | ipynb | Jupyter Notebook | shallow_net_in_keras.ipynb | hongqin/deep-learning-illustrated | 052edcc0ccf5c0106837a52b42adde311c9670d9 | [
"MIT"
] | 1 | 2021-02-26T10:16:01.000Z | 2021-02-26T10:16:01.000Z | shallow_net_in_keras.ipynb | hongqin/deep-learning-illustrated | 052edcc0ccf5c0106837a52b42adde311c9670d9 | [
"MIT"
] | null | null | null | shallow_net_in_keras.ipynb | hongqin/deep-learning-illustrated | 052edcc0ccf5c0106837a52b42adde311c9670d9 | [
"MIT"
] | 1 | 2021-04-03T16:42:00.000Z | 2021-04-03T16:42:00.000Z | 62.091172 | 8,374 | 0.4482 | [
[
[
"<a href=\"https://colab.research.google.com/github/hongqin/deep-learning-illustrated/blob/master/shallow_net_in_keras.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Shallow Neural Network in Keras",
"_____no_output_____"
],
[
"Build a shallow neural network to classify MNIST digits",
"_____no_output_____"
],
[
"#### Load dependencies",
"_____no_output_____"
]
],
[
[
"import keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD\nfrom matplotlib import pyplot as plt",
"_____no_output_____"
]
],
[
[
"#### Load data",
"_____no_output_____"
]
],
[
[
"(X_train, y_train), (X_valid, y_valid) = mnist.load_data()",
"Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n11493376/11490434 [==============================] - 0s 0us/step\n"
],
[
"X_train.shape",
"_____no_output_____"
],
[
"y_train.shape",
"_____no_output_____"
],
[
"y_train[0:12]",
"_____no_output_____"
],
[
"plt.figure(figsize=(2,2))\nfor k in range(12):\n plt.subplot(3, 4, k+1)\n plt.imshow(X_train[k], cmap='Greys')\n plt.axis('off')\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
],
[
"X_valid.shape",
"_____no_output_____"
],
[
"y_valid.shape",
"_____no_output_____"
],
[
"plt.imshow(X_valid[0], cmap='Greys')",
"_____no_output_____"
],
[
"X_valid[0]",
"_____no_output_____"
],
[
"y_valid[0]",
"_____no_output_____"
]
],
[
[
"#### Preprocess data",
"_____no_output_____"
]
],
[
[
"X_train = X_train.reshape(60000, 784).astype('float32')\nX_valid = X_valid.reshape(10000, 784).astype('float32')",
"_____no_output_____"
],
[
"X_train /= 255\nX_valid /= 255",
"_____no_output_____"
],
[
"X_valid[0]",
"_____no_output_____"
],
[
"n_classes = 10\ny_train = keras.utils.to_categorical(y_train, n_classes)\ny_valid = keras.utils.to_categorical(y_valid, n_classes)",
"_____no_output_____"
],
[
"y_valid[0]",
"_____no_output_____"
]
],
[
[
"#### Design neural network architecture",
"_____no_output_____"
]
],
[
[
"model = Sequential()\nmodel.add(Dense(64, activation='sigmoid', input_shape=(784,)))\nmodel.add(Dense(10, activation='softmax'))",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 64) 50240 \n_________________________________________________________________\ndense_1 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 50,890\nTrainable params: 50,890\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"(64*784)",
"_____no_output_____"
],
[
"(64*784)+64",
"_____no_output_____"
],
[
"(10*64)+10",
"_____no_output_____"
]
],
[
[
"#### Configure model",
"_____no_output_____"
]
],
[
[
"model.compile(loss='mean_squared_error', optimizer=SGD(lr=0.01), metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"#### Train!",
"_____no_output_____"
]
],
[
[
"model.fit(X_train, y_train, batch_size=128, epochs=200, verbose=1, validation_data=(X_valid, y_valid))",
"Epoch 1/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0941 - accuracy: 0.1008 - val_loss: 0.0929 - val_accuracy: 0.1081\nEpoch 2/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0922 - accuracy: 0.1089 - val_loss: 0.0917 - val_accuracy: 0.1168\nEpoch 3/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0914 - accuracy: 0.1163 - val_loss: 0.0911 - val_accuracy: 0.1299\nEpoch 4/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0908 - accuracy: 0.1331 - val_loss: 0.0906 - val_accuracy: 0.1506\nEpoch 5/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0904 - accuracy: 0.1521 - val_loss: 0.0902 - val_accuracy: 0.1691\nEpoch 6/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0900 - accuracy: 0.1732 - val_loss: 0.0898 - val_accuracy: 0.1866\nEpoch 7/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0897 - accuracy: 0.1970 - val_loss: 0.0895 - val_accuracy: 0.2101\nEpoch 8/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0894 - accuracy: 0.2174 - val_loss: 0.0892 - val_accuracy: 0.2282\nEpoch 9/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0890 - accuracy: 0.2334 - val_loss: 0.0889 - val_accuracy: 0.2410\nEpoch 10/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0887 - accuracy: 0.2456 - val_loss: 0.0886 - val_accuracy: 0.2497\nEpoch 11/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0884 - accuracy: 0.2545 - val_loss: 0.0883 - val_accuracy: 0.2566\nEpoch 12/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0882 - accuracy: 0.2614 - val_loss: 0.0880 - val_accuracy: 0.2641\nEpoch 13/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0879 - accuracy: 0.2744 - val_loss: 0.0877 - val_accuracy: 0.2879\nEpoch 14/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0876 - accuracy: 0.3096 - val_loss: 0.0874 - val_accuracy: 0.3312\nEpoch 15/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0873 - accuracy: 0.3414 - val_loss: 0.0871 - val_accuracy: 0.3584\nEpoch 16/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0870 - accuracy: 0.3607 - val_loss: 0.0868 - val_accuracy: 0.3711\nEpoch 17/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0867 - accuracy: 0.3684 - val_loss: 0.0865 - val_accuracy: 0.3766\nEpoch 18/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0863 - accuracy: 0.3708 - val_loss: 0.0861 - val_accuracy: 0.3776\nEpoch 19/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0860 - accuracy: 0.3704 - val_loss: 0.0858 - val_accuracy: 0.3779\nEpoch 20/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0857 - accuracy: 0.3692 - val_loss: 0.0855 - val_accuracy: 0.3765\nEpoch 21/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0854 - accuracy: 0.3686 - val_loss: 0.0851 - val_accuracy: 0.3754\nEpoch 22/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0850 - accuracy: 0.3684 - val_loss: 0.0848 - val_accuracy: 0.3751\nEpoch 23/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0847 - accuracy: 0.3700 - val_loss: 0.0844 - val_accuracy: 0.3754\nEpoch 24/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0843 - accuracy: 0.3688 - val_loss: 0.0840 - val_accuracy: 0.3769\nEpoch 25/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0839 - accuracy: 0.3709 - val_loss: 0.0837 - val_accuracy: 0.3797\nEpoch 26/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0836 - accuracy: 0.3737 - val_loss: 0.0833 - val_accuracy: 0.3847\nEpoch 27/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0832 - accuracy: 0.3776 - val_loss: 0.0829 - val_accuracy: 0.3876\nEpoch 28/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0828 - accuracy: 0.3820 - val_loss: 0.0825 - val_accuracy: 0.3930\nEpoch 29/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0824 - accuracy: 0.3876 - val_loss: 0.0821 - val_accuracy: 0.3986\nEpoch 30/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0820 - accuracy: 0.3918 - val_loss: 0.0816 - val_accuracy: 0.4060\nEpoch 31/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0816 - accuracy: 0.3992 - val_loss: 0.0812 - val_accuracy: 0.4117\nEpoch 32/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0811 - accuracy: 0.4053 - val_loss: 0.0808 - val_accuracy: 0.4183\nEpoch 33/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0807 - accuracy: 0.4120 - val_loss: 0.0803 - val_accuracy: 0.4260\nEpoch 34/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0803 - accuracy: 0.4197 - val_loss: 0.0799 - val_accuracy: 0.4329\nEpoch 35/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0798 - accuracy: 0.4254 - val_loss: 0.0794 - val_accuracy: 0.4422\nEpoch 36/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0794 - accuracy: 0.4339 - val_loss: 0.0790 - val_accuracy: 0.4496\nEpoch 37/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0789 - accuracy: 0.4399 - val_loss: 0.0785 - val_accuracy: 0.4567\nEpoch 38/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0785 - accuracy: 0.4467 - val_loss: 0.0780 - val_accuracy: 0.4625\nEpoch 39/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0780 - accuracy: 0.4536 - val_loss: 0.0776 - val_accuracy: 0.4679\nEpoch 40/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0775 - accuracy: 0.4597 - val_loss: 0.0771 - val_accuracy: 0.4729\nEpoch 41/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0771 - accuracy: 0.4661 - val_loss: 0.0766 - val_accuracy: 0.4788\nEpoch 42/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0766 - accuracy: 0.4723 - val_loss: 0.0761 - val_accuracy: 0.4861\nEpoch 43/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0761 - accuracy: 0.4787 - val_loss: 0.0756 - val_accuracy: 0.4917\nEpoch 44/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0756 - accuracy: 0.4835 - val_loss: 0.0751 - val_accuracy: 0.4965\nEpoch 45/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0751 - accuracy: 0.4882 - val_loss: 0.0746 - val_accuracy: 0.5003\nEpoch 46/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0746 - accuracy: 0.4925 - val_loss: 0.0741 - val_accuracy: 0.5051\nEpoch 47/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0742 - accuracy: 0.4973 - val_loss: 0.0737 - val_accuracy: 0.5101\nEpoch 48/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0737 - accuracy: 0.5019 - val_loss: 0.0732 - val_accuracy: 0.5136\nEpoch 49/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0732 - accuracy: 0.5064 - val_loss: 0.0727 - val_accuracy: 0.5162\nEpoch 50/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0727 - accuracy: 0.5099 - val_loss: 0.0722 - val_accuracy: 0.5199\nEpoch 51/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0722 - accuracy: 0.5145 - val_loss: 0.0717 - val_accuracy: 0.5242\nEpoch 52/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0717 - accuracy: 0.5184 - val_loss: 0.0711 - val_accuracy: 0.5283\nEpoch 53/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0712 - accuracy: 0.5221 - val_loss: 0.0706 - val_accuracy: 0.5330\nEpoch 54/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0707 - accuracy: 0.5264 - val_loss: 0.0701 - val_accuracy: 0.5370\nEpoch 55/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0702 - accuracy: 0.5314 - val_loss: 0.0696 - val_accuracy: 0.5405\nEpoch 56/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0697 - accuracy: 0.5348 - val_loss: 0.0691 - val_accuracy: 0.5444\nEpoch 57/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0692 - accuracy: 0.5392 - val_loss: 0.0686 - val_accuracy: 0.5474\nEpoch 58/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0687 - accuracy: 0.5443 - val_loss: 0.0682 - val_accuracy: 0.5521\nEpoch 59/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0682 - accuracy: 0.5494 - val_loss: 0.0677 - val_accuracy: 0.5573\nEpoch 60/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0678 - accuracy: 0.5542 - val_loss: 0.0672 - val_accuracy: 0.5610\nEpoch 61/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0673 - accuracy: 0.5586 - val_loss: 0.0667 - val_accuracy: 0.5667\nEpoch 62/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0668 - accuracy: 0.5631 - val_loss: 0.0662 - val_accuracy: 0.5715\nEpoch 63/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0663 - accuracy: 0.5687 - val_loss: 0.0657 - val_accuracy: 0.5754\nEpoch 64/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0658 - accuracy: 0.5732 - val_loss: 0.0652 - val_accuracy: 0.5814\nEpoch 65/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0654 - accuracy: 0.5781 - val_loss: 0.0647 - val_accuracy: 0.5868\nEpoch 66/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0649 - accuracy: 0.5832 - val_loss: 0.0642 - val_accuracy: 0.5925\nEpoch 67/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0644 - accuracy: 0.5880 - val_loss: 0.0638 - val_accuracy: 0.5988\nEpoch 68/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0639 - accuracy: 0.5939 - val_loss: 0.0633 - val_accuracy: 0.6048\nEpoch 69/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0635 - accuracy: 0.5986 - val_loss: 0.0628 - val_accuracy: 0.6092\nEpoch 70/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0630 - accuracy: 0.6044 - val_loss: 0.0624 - val_accuracy: 0.6126\nEpoch 71/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0626 - accuracy: 0.6089 - val_loss: 0.0619 - val_accuracy: 0.6176\nEpoch 72/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0621 - accuracy: 0.6138 - val_loss: 0.0614 - val_accuracy: 0.6225\nEpoch 73/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0616 - accuracy: 0.6190 - val_loss: 0.0610 - val_accuracy: 0.6265\nEpoch 74/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0612 - accuracy: 0.6246 - val_loss: 0.0605 - val_accuracy: 0.6313\nEpoch 75/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0607 - accuracy: 0.6298 - val_loss: 0.0601 - val_accuracy: 0.6361\nEpoch 76/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0603 - accuracy: 0.6348 - val_loss: 0.0596 - val_accuracy: 0.6418\nEpoch 77/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0599 - accuracy: 0.6392 - val_loss: 0.0592 - val_accuracy: 0.6480\nEpoch 78/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0594 - accuracy: 0.6439 - val_loss: 0.0587 - val_accuracy: 0.6528\nEpoch 79/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0590 - accuracy: 0.6486 - val_loss: 0.0583 - val_accuracy: 0.6580\nEpoch 80/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0586 - accuracy: 0.6532 - val_loss: 0.0578 - val_accuracy: 0.6623\nEpoch 81/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0581 - accuracy: 0.6574 - val_loss: 0.0574 - val_accuracy: 0.6662\nEpoch 82/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0577 - accuracy: 0.6621 - val_loss: 0.0570 - val_accuracy: 0.6696\nEpoch 83/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0573 - accuracy: 0.6657 - val_loss: 0.0566 - val_accuracy: 0.6739\nEpoch 84/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0569 - accuracy: 0.6699 - val_loss: 0.0561 - val_accuracy: 0.6776\nEpoch 85/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0565 - accuracy: 0.6744 - val_loss: 0.0557 - val_accuracy: 0.6816\nEpoch 86/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0560 - accuracy: 0.6782 - val_loss: 0.0553 - val_accuracy: 0.6864\nEpoch 87/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0556 - accuracy: 0.6819 - val_loss: 0.0549 - val_accuracy: 0.6896\nEpoch 88/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0552 - accuracy: 0.6864 - val_loss: 0.0545 - val_accuracy: 0.6931\nEpoch 89/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0548 - accuracy: 0.6896 - val_loss: 0.0541 - val_accuracy: 0.6970\nEpoch 90/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0544 - accuracy: 0.6928 - val_loss: 0.0537 - val_accuracy: 0.7011\nEpoch 91/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0540 - accuracy: 0.6960 - val_loss: 0.0533 - val_accuracy: 0.7037\nEpoch 92/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0536 - accuracy: 0.6990 - val_loss: 0.0529 - val_accuracy: 0.7076\nEpoch 93/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0533 - accuracy: 0.7023 - val_loss: 0.0525 - val_accuracy: 0.7109\nEpoch 94/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0529 - accuracy: 0.7061 - val_loss: 0.0521 - val_accuracy: 0.7135\nEpoch 95/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0525 - accuracy: 0.7089 - val_loss: 0.0517 - val_accuracy: 0.7175\nEpoch 96/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0521 - accuracy: 0.7120 - val_loss: 0.0513 - val_accuracy: 0.7215\nEpoch 97/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0517 - accuracy: 0.7153 - val_loss: 0.0509 - val_accuracy: 0.7246\nEpoch 98/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0514 - accuracy: 0.7183 - val_loss: 0.0506 - val_accuracy: 0.7272\nEpoch 99/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0510 - accuracy: 0.7215 - val_loss: 0.0502 - val_accuracy: 0.7306\nEpoch 100/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0506 - accuracy: 0.7241 - val_loss: 0.0498 - val_accuracy: 0.7328\nEpoch 101/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0503 - accuracy: 0.7264 - val_loss: 0.0494 - val_accuracy: 0.7349\nEpoch 102/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0499 - accuracy: 0.7292 - val_loss: 0.0491 - val_accuracy: 0.7383\nEpoch 103/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0496 - accuracy: 0.7313 - val_loss: 0.0487 - val_accuracy: 0.7410\nEpoch 104/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0492 - accuracy: 0.7341 - val_loss: 0.0484 - val_accuracy: 0.7443\nEpoch 105/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0489 - accuracy: 0.7367 - val_loss: 0.0480 - val_accuracy: 0.7459\nEpoch 106/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0485 - accuracy: 0.7385 - val_loss: 0.0477 - val_accuracy: 0.7477\nEpoch 107/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0482 - accuracy: 0.7404 - val_loss: 0.0473 - val_accuracy: 0.7502\nEpoch 108/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0479 - accuracy: 0.7423 - val_loss: 0.0470 - val_accuracy: 0.7522\nEpoch 109/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0475 - accuracy: 0.7446 - val_loss: 0.0467 - val_accuracy: 0.7550\nEpoch 110/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0472 - accuracy: 0.7464 - val_loss: 0.0463 - val_accuracy: 0.7575\nEpoch 111/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0469 - accuracy: 0.7488 - val_loss: 0.0460 - val_accuracy: 0.7595\nEpoch 112/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0466 - accuracy: 0.7504 - val_loss: 0.0457 - val_accuracy: 0.7609\nEpoch 113/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0462 - accuracy: 0.7527 - val_loss: 0.0453 - val_accuracy: 0.7644\nEpoch 114/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0459 - accuracy: 0.7551 - val_loss: 0.0450 - val_accuracy: 0.7653\nEpoch 115/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0456 - accuracy: 0.7571 - val_loss: 0.0447 - val_accuracy: 0.7684\nEpoch 116/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0453 - accuracy: 0.7591 - val_loss: 0.0444 - val_accuracy: 0.7699\nEpoch 117/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0450 - accuracy: 0.7611 - val_loss: 0.0441 - val_accuracy: 0.7712\nEpoch 118/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0447 - accuracy: 0.7630 - val_loss: 0.0438 - val_accuracy: 0.7728\nEpoch 119/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0444 - accuracy: 0.7650 - val_loss: 0.0435 - val_accuracy: 0.7745\nEpoch 120/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0441 - accuracy: 0.7672 - val_loss: 0.0432 - val_accuracy: 0.7764\nEpoch 121/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0438 - accuracy: 0.7690 - val_loss: 0.0429 - val_accuracy: 0.7781\nEpoch 122/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0435 - accuracy: 0.7709 - val_loss: 0.0426 - val_accuracy: 0.7804\nEpoch 123/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0432 - accuracy: 0.7727 - val_loss: 0.0423 - val_accuracy: 0.7816\nEpoch 124/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0430 - accuracy: 0.7742 - val_loss: 0.0420 - val_accuracy: 0.7829\nEpoch 125/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0427 - accuracy: 0.7765 - val_loss: 0.0417 - val_accuracy: 0.7845\nEpoch 126/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0424 - accuracy: 0.7786 - val_loss: 0.0415 - val_accuracy: 0.7870\nEpoch 127/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0421 - accuracy: 0.7805 - val_loss: 0.0412 - val_accuracy: 0.7894\nEpoch 128/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0419 - accuracy: 0.7823 - val_loss: 0.0409 - val_accuracy: 0.7914\nEpoch 129/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0416 - accuracy: 0.7841 - val_loss: 0.0406 - val_accuracy: 0.7945\nEpoch 130/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0413 - accuracy: 0.7862 - val_loss: 0.0404 - val_accuracy: 0.7958\nEpoch 131/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0411 - accuracy: 0.7882 - val_loss: 0.0401 - val_accuracy: 0.7976\nEpoch 132/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0408 - accuracy: 0.7898 - val_loss: 0.0399 - val_accuracy: 0.7988\nEpoch 133/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0406 - accuracy: 0.7919 - val_loss: 0.0396 - val_accuracy: 0.8006\nEpoch 134/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0403 - accuracy: 0.7935 - val_loss: 0.0393 - val_accuracy: 0.8026\nEpoch 135/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0400 - accuracy: 0.7958 - val_loss: 0.0391 - val_accuracy: 0.8037\nEpoch 136/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0398 - accuracy: 0.7973 - val_loss: 0.0388 - val_accuracy: 0.8058\nEpoch 137/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0396 - accuracy: 0.7992 - val_loss: 0.0386 - val_accuracy: 0.8071\nEpoch 138/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0393 - accuracy: 0.8009 - val_loss: 0.0383 - val_accuracy: 0.8086\nEpoch 139/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0391 - accuracy: 0.8022 - val_loss: 0.0381 - val_accuracy: 0.8106\nEpoch 140/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0388 - accuracy: 0.8042 - val_loss: 0.0379 - val_accuracy: 0.8129\nEpoch 141/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0386 - accuracy: 0.8054 - val_loss: 0.0376 - val_accuracy: 0.8145\nEpoch 142/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0384 - accuracy: 0.8071 - val_loss: 0.0374 - val_accuracy: 0.8165\nEpoch 143/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0381 - accuracy: 0.8088 - val_loss: 0.0371 - val_accuracy: 0.8182\nEpoch 144/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0379 - accuracy: 0.8100 - val_loss: 0.0369 - val_accuracy: 0.8213\nEpoch 145/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0377 - accuracy: 0.8115 - val_loss: 0.0367 - val_accuracy: 0.8225\nEpoch 146/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0375 - accuracy: 0.8132 - val_loss: 0.0365 - val_accuracy: 0.8242\nEpoch 147/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0372 - accuracy: 0.8150 - val_loss: 0.0362 - val_accuracy: 0.8252\nEpoch 148/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0370 - accuracy: 0.8165 - val_loss: 0.0360 - val_accuracy: 0.8264\nEpoch 149/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0368 - accuracy: 0.8179 - val_loss: 0.0358 - val_accuracy: 0.8281\nEpoch 150/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0366 - accuracy: 0.8193 - val_loss: 0.0356 - val_accuracy: 0.8300\nEpoch 151/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0364 - accuracy: 0.8211 - val_loss: 0.0354 - val_accuracy: 0.8314\nEpoch 152/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0362 - accuracy: 0.8224 - val_loss: 0.0352 - val_accuracy: 0.8324\nEpoch 153/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0360 - accuracy: 0.8235 - val_loss: 0.0350 - val_accuracy: 0.8346\nEpoch 154/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0358 - accuracy: 0.8248 - val_loss: 0.0347 - val_accuracy: 0.8356\nEpoch 155/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0355 - accuracy: 0.8260 - val_loss: 0.0345 - val_accuracy: 0.8372\nEpoch 156/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0353 - accuracy: 0.8274 - val_loss: 0.0343 - val_accuracy: 0.8385\nEpoch 157/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0352 - accuracy: 0.8287 - val_loss: 0.0341 - val_accuracy: 0.8398\nEpoch 158/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0350 - accuracy: 0.8299 - val_loss: 0.0339 - val_accuracy: 0.8406\nEpoch 159/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0348 - accuracy: 0.8314 - val_loss: 0.0337 - val_accuracy: 0.8413\nEpoch 160/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0346 - accuracy: 0.8325 - val_loss: 0.0336 - val_accuracy: 0.8423\nEpoch 161/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0344 - accuracy: 0.8338 - val_loss: 0.0334 - val_accuracy: 0.8440\nEpoch 162/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0342 - accuracy: 0.8347 - val_loss: 0.0332 - val_accuracy: 0.8451\nEpoch 163/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0340 - accuracy: 0.8356 - val_loss: 0.0330 - val_accuracy: 0.8460\nEpoch 164/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0338 - accuracy: 0.8367 - val_loss: 0.0328 - val_accuracy: 0.8474\nEpoch 165/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0336 - accuracy: 0.8377 - val_loss: 0.0326 - val_accuracy: 0.8480\nEpoch 166/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0335 - accuracy: 0.8385 - val_loss: 0.0324 - val_accuracy: 0.8495\nEpoch 167/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0333 - accuracy: 0.8393 - val_loss: 0.0323 - val_accuracy: 0.8506\nEpoch 168/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0331 - accuracy: 0.8404 - val_loss: 0.0321 - val_accuracy: 0.8509\nEpoch 169/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0329 - accuracy: 0.8415 - val_loss: 0.0319 - val_accuracy: 0.8516\nEpoch 170/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0328 - accuracy: 0.8423 - val_loss: 0.0317 - val_accuracy: 0.8530\nEpoch 171/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0326 - accuracy: 0.8430 - val_loss: 0.0316 - val_accuracy: 0.8539\nEpoch 172/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0324 - accuracy: 0.8439 - val_loss: 0.0314 - val_accuracy: 0.8545\nEpoch 173/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0323 - accuracy: 0.8446 - val_loss: 0.0312 - val_accuracy: 0.8550\nEpoch 174/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0321 - accuracy: 0.8449 - val_loss: 0.0311 - val_accuracy: 0.8556\nEpoch 175/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0320 - accuracy: 0.8459 - val_loss: 0.0309 - val_accuracy: 0.8558\nEpoch 176/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0318 - accuracy: 0.8465 - val_loss: 0.0308 - val_accuracy: 0.8563\nEpoch 177/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0316 - accuracy: 0.8471 - val_loss: 0.0306 - val_accuracy: 0.8568\nEpoch 178/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0315 - accuracy: 0.8476 - val_loss: 0.0305 - val_accuracy: 0.8572\nEpoch 179/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0313 - accuracy: 0.8482 - val_loss: 0.0303 - val_accuracy: 0.8580\nEpoch 180/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0312 - accuracy: 0.8492 - val_loss: 0.0301 - val_accuracy: 0.8582\nEpoch 181/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0310 - accuracy: 0.8496 - val_loss: 0.0300 - val_accuracy: 0.8589\nEpoch 182/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0309 - accuracy: 0.8501 - val_loss: 0.0298 - val_accuracy: 0.8590\nEpoch 183/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0307 - accuracy: 0.8510 - val_loss: 0.0297 - val_accuracy: 0.8596\nEpoch 184/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0306 - accuracy: 0.8516 - val_loss: 0.0296 - val_accuracy: 0.8599\nEpoch 185/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0304 - accuracy: 0.8521 - val_loss: 0.0294 - val_accuracy: 0.8601\nEpoch 186/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0303 - accuracy: 0.8525 - val_loss: 0.0293 - val_accuracy: 0.8610\nEpoch 187/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0302 - accuracy: 0.8533 - val_loss: 0.0291 - val_accuracy: 0.8619\nEpoch 188/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0300 - accuracy: 0.8536 - val_loss: 0.0290 - val_accuracy: 0.8625\nEpoch 189/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0299 - accuracy: 0.8540 - val_loss: 0.0289 - val_accuracy: 0.8631\nEpoch 190/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0298 - accuracy: 0.8545 - val_loss: 0.0287 - val_accuracy: 0.8634\nEpoch 191/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0296 - accuracy: 0.8546 - val_loss: 0.0286 - val_accuracy: 0.8637\nEpoch 192/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0295 - accuracy: 0.8553 - val_loss: 0.0285 - val_accuracy: 0.8641\nEpoch 193/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0294 - accuracy: 0.8557 - val_loss: 0.0283 - val_accuracy: 0.8645\nEpoch 194/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0292 - accuracy: 0.8559 - val_loss: 0.0282 - val_accuracy: 0.8644\nEpoch 195/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0291 - accuracy: 0.8563 - val_loss: 0.0281 - val_accuracy: 0.8648\nEpoch 196/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0290 - accuracy: 0.8566 - val_loss: 0.0280 - val_accuracy: 0.8654\nEpoch 197/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0289 - accuracy: 0.8572 - val_loss: 0.0278 - val_accuracy: 0.8658\nEpoch 198/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0288 - accuracy: 0.8576 - val_loss: 0.0277 - val_accuracy: 0.8662\nEpoch 199/200\n469/469 [==============================] - 1s 2ms/step - loss: 0.0286 - accuracy: 0.8582 - val_loss: 0.0276 - val_accuracy: 0.8665\nEpoch 200/200\n469/469 [==============================] - 1s 3ms/step - loss: 0.0285 - accuracy: 0.8585 - val_loss: 0.0275 - val_accuracy: 0.8666\n"
],
[
"model.evaluate(X_valid, y_valid)",
"313/313 [==============================] - 0s 965us/step - loss: 0.0275 - accuracy: 0.8666\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
ece4909ac7931a0729b734f7a7bbc8521ba788bf | 1,583 | ipynb | Jupyter Notebook | tutorials/.ipynb_checkpoints/index-checkpoint.ipynb | BCampforts/hylands_modeling | 2bf99ee7938b6b132829b5269792231eb7798443 | [
"CC-BY-4.0"
] | 5 | 2021-11-30T17:50:42.000Z | 2022-02-02T13:59:05.000Z | tutorials/.ipynb_checkpoints/index-checkpoint.ipynb | elizama1/hylands_modeling | 2bf99ee7938b6b132829b5269792231eb7798443 | [
"CC-BY-4.0"
] | null | null | null | tutorials/.ipynb_checkpoints/index-checkpoint.ipynb | elizama1/hylands_modeling | 2bf99ee7938b6b132829b5269792231eb7798443 | [
"CC-BY-4.0"
] | 3 | 2021-11-30T17:51:06.000Z | 2022-02-08T22:19:16.000Z | 29.867925 | 174 | 0.617814 | [
[
[
"<a href=\"https://doi.org/10.5194/gmd-13-3863-2020\"><img style=\"float: center; width: 100%\" src=\"../media/HyLands_Logo_Header.png\"></a>",
"_____no_output_____"
],
[
"# Simulating bedrock landslides with Landlab\n\n### Introduction to Landlab\n* [Introduction to Landlab](https://landlab.readthedocs.io/en/latest/index.html) and [tutorials](https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html)\n\n### Bedrock landslides\n* [Bedrock landslides on existing topography (SRTM DEM)](./hylands_real/bedrockLandslides_on_DEMs.ipynb)\n\n### Large scale landscape evolution models\n* [Large scale landscape evolution](./large_scale_LEM/large_scale_LEMs.ipynb)\n* [Large scale landscape evolution using real topography](./large_scale_LEM/large_scale_LEMs-real-topography.ipynb)\n\n### HyLands (Hybrid Landscape evolution model)\n* [HyLands](./hylands_LEM/HyLandsTutorial.ipynb)",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown"
]
] |
ece498bcb4ae0c770439246897fee2f28cec7f02 | 223,088 | ipynb | Jupyter Notebook | ETL PipeLines/Transform/Cleaning_Data_(Outlier_Detection).ipynb | chaithanya21/Data-PipeLines | c189c9b085704ee956f8a56b792ad1a4a650492e | [
"MIT"
] | null | null | null | ETL PipeLines/Transform/Cleaning_Data_(Outlier_Detection).ipynb | chaithanya21/Data-PipeLines | c189c9b085704ee956f8a56b792ad1a4a650492e | [
"MIT"
] | null | null | null | ETL PipeLines/Transform/Cleaning_Data_(Outlier_Detection).ipynb | chaithanya21/Data-PipeLines | c189c9b085704ee956f8a56b792ad1a4a650492e | [
"MIT"
] | null | null | null | 120.263073 | 71,372 | 0.807009 | [
[
[
"# Finding Outliers\n\nIn this exercise, you'll practice looking for outliers. You'll look at the World Bank GDP and population data sets. First, you'll look at the data from a one-dimensional perspective and then a two-dimensional perspective.\n\nRun the code below to import the data sets and prepare the data for analysis. The code:\n* reads in the data sets\n* reshapes the datasets to a long format\n* uses back fill and forward fill to fill in missing values\n* merges the gdp and population data together\n* shows the first 10 values in the data set",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n\n# read in the projects data set and do basic wrangling \ngdp = pd.read_csv('../data/gdp_data.csv', skiprows=4)\ngdp.drop(['Unnamed: 62', 'Country Code', 'Indicator Name', 'Indicator Code'], inplace=True, axis=1)\npopulation = pd.read_csv('../data/population_data.csv', skiprows=4)\npopulation.drop(['Unnamed: 62', 'Country Code', 'Indicator Name', 'Indicator Code'], inplace=True, axis=1)\n\n\n# Reshape the data sets so that they are in long format\ngdp_melt = gdp.melt(id_vars=['Country Name'], \n var_name='year', \n value_name='gdp')\n\n# Use back fill and forward fill to fill in missing gdp values\ngdp_melt['gdp'] = gdp_melt.sort_values('year').groupby('Country Name')['gdp'].fillna(method='ffill').fillna(method='bfill')\n\npopulation_melt = population.melt(id_vars=['Country Name'], \n var_name='year', \n value_name='population')\n\n# Use back fill and forward fill to fill in missing population values\npopulation_melt['population'] = population_melt.sort_values('year').groupby('Country Name')['population'].fillna(method='ffill').fillna(method='bfill')\n\n# merge the population and gdp data together into one data frame\ndf_country = gdp_melt.merge(population_melt, on=('Country Name', 'year'))\n\n# filter data for the year 2016\ndf_2016 = df_country[df_country['year'] == '2016']\n\n# see what the data looks like\ndf_2016.head(10)",
"_____no_output_____"
]
],
[
[
"# Exercise\n\nExplore the data set to identify outliers using the Tukey rule. Follow the TODOs.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline \n\n# TODO: Make a boxplot of the population data for the year 2016\ndf_2016.plot('population', kind='box')\n\n# TODO: Make a boxplot of the gdp data for the year 2016\ndf_2016.plot('gdp', kind='box')",
"_____no_output_____"
]
],
[
[
"Use the Tukey rule to determine what values of the population data are outliers for the year 2016. The Tukey rule finds outliers in one-dimension. The steps are:\n\n* Find the first quartile (ie .25 quantile)\n* Find the third quartile (ie .75 quantile)\n* Calculate the inter-quartile range (Q3 - Q1)\n* Any value that is greater than Q3 + 1.5 * IQR is an outlier\n* Any value that is less than Qe - 1.5 * IQR is an outlier",
"_____no_output_____"
]
],
[
[
"# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need\n# to keep the Country Name and population columns\npopulation_2016 = df_2016[['Country Name','population']]\n\n# TODO: Calculate the first quartile of the population values\n# HINT: you can use the pandas quantile method \nQ1 = population_2016['population'].quantile(0.25)\n\n# TODO: Calculate the third quartile of the population values\nQ3 = population_2016['population'].quantile(0.75)\n\n# TODP: Calculate the interquartile range Q3 - Q1\nIQR = Q3 - Q1\n\n# TODO: Calculate the maximum value and minimum values according to the Tukey rule\n# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR\nmax_value = Q3 + 1.5 * IQR\nmin_value = Q1 - 1.5 * IQR\n\n# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value\npopulation_outliers = population_2016[(population_2016['population'] > max_value) | (population_2016['population'] < min_value)]\npopulation_outliers",
"_____no_output_____"
]
],
[
[
"Many of these aren't countries at all but rather aggregates of various countries. Notice as well that the min_value calculated above was negative. According to the Tukey rule, there are no minimum population outliers in this data set. If you were going to study how population and gdp correlate, you might want to remove these aggregated regions from the data set.\n\nNext, use the Tukey method to do the same analysis for gdp.",
"_____no_output_____"
]
],
[
[
"# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need\n# to keep the Country Name and population columns\ngdp_2016 = df_2016[['Country Name','gdp']]\n\n# TODO: Calculate the first quartile of the population values\n# HINT: you can use the pandas quantile method \nQ1 = gdp_2016['gdp'].quantile(0.25)\n\n# TODO: Calculate the third quartile of the population values\nQ3 = gdp_2016['gdp'].quantile(0.75)\n\n# TODP: Calculate the interquartile range Q3 - Q1\nIQR = Q3 - Q1\n\n# TODO: Calculate the maximum value and minimum values according to the Tukey rule\n# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR\nmax_value = Q3 + 1.5 * IQR\nmin_value = Q1 - 1.5 * IQR\n\n# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value\ngdp_outliers = gdp_2016[(gdp_2016['gdp'] > max_value) | (gdp_2016['gdp'] < min_value)]\ngdp_outliers",
"_____no_output_____"
]
],
[
[
"Clearly many of these outliers are due to regional data getting aggregated together. \n\nRemove these data points and redo the analysis. There's a list provided below of the 'Country Name' values that are not actually countries.",
"_____no_output_____"
]
],
[
[
"# TODO: remove the rows from the data that have Country Name values in the non_countries list\n# Store the filter results back into the df_2016 variable\n\nnon_countries = ['World',\n 'High income',\n 'OECD members',\n 'Post-demographic dividend',\n 'IDA & IBRD total',\n 'Low & middle income',\n 'Middle income',\n 'IBRD only',\n 'East Asia & Pacific',\n 'Europe & Central Asia',\n 'North America',\n 'Upper middle income',\n 'Late-demographic dividend',\n 'European Union',\n 'East Asia & Pacific (excluding high income)',\n 'East Asia & Pacific (IDA & IBRD countries)',\n 'Euro area',\n 'Early-demographic dividend',\n 'Lower middle income',\n 'Latin America & Caribbean',\n 'Latin America & the Caribbean (IDA & IBRD countries)',\n 'Latin America & Caribbean (excluding high income)',\n 'Europe & Central Asia (IDA & IBRD countries)',\n 'Middle East & North Africa',\n 'Europe & Central Asia (excluding high income)',\n 'South Asia (IDA & IBRD)',\n 'South Asia',\n 'Arab World',\n 'IDA total',\n 'Sub-Saharan Africa',\n 'Sub-Saharan Africa (IDA & IBRD countries)',\n 'Sub-Saharan Africa (excluding high income)',\n 'Middle East & North Africa (excluding high income)',\n 'Middle East & North Africa (IDA & IBRD countries)',\n 'Central Europe and the Baltics',\n 'Pre-demographic dividend',\n 'IDA only',\n 'Least developed countries: UN classification',\n 'IDA blend',\n 'Fragile and conflict affected situations',\n 'Heavily indebted poor countries (HIPC)',\n 'Low income',\n 'Small states',\n 'Other small states',\n 'Not classified',\n 'Caribbean small states',\n 'Pacific island small states']\n\n# remove non countries from the data\ndf_2016 = df_2016[~df_2016['Country Name'].isin(non_countries)]",
"_____no_output_____"
],
[
"# TODO: Re-rerun the Tukey code with this filtered data to find population outliers\n\n# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need\n# to keep the Country Name and population columns\npopulation_2016 = df_2016[['Country Name','population']]\n\n# TODO: Calculate the first quartile of the population values\n# HINT: you can use the pandas quantile method \nQ1 = population_2016['population'].quantile(0.25)\n\n# TODO: Calculate the third quartile of the population values\nQ3 = population_2016['population'].quantile(0.75)\n\n# TODO: Calculate the interquartile range Q3 - Q1\nIQR = Q3 - Q1\n\n# TODO: Calculate the maximum value and minimum values according to the Tukey rule\n# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR\nmax_value = Q3 + 1.5 * IQR\nmin_value = Q1 - 1.5 * IQR\n\n# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value\npopulation_outliers = population_2016[(population_2016['population'] > max_value) | (population_2016['population'] < min_value)]\npopulation_outliers",
"_____no_output_____"
],
[
"# TODO: Filter the data for the year 2016 and put the results in the population_2016 variable. You only need\n# to keep the Country Name and population columns\ngdp_2016 = df_2016[['Country Name','gdp']]\n\n# TODO: Calculate the first quartile of the population values\n# HINT: you can use the pandas quantile method \nQ1 = gdp_2016['gdp'].quantile(0.25)\n\n# TODO: Calculate the third quartile of the population values\nQ3 = gdp_2016['gdp'].quantile(0.75)\n\n# TODO: Calculate the interquartile range Q3 - Q1\nIQR = Q3 - Q1\n\n# TODO: Calculate the maximum value and minimum values according to the Tukey rule\n# max_value is Q3 + 1.5 * IQR while min_value is Q1 - 1.5 * IQR\nmax_value = Q3 + 1.5 * IQR\nmin_value = Q1 - 1.5 * IQR\n\n# TODO: filter the population_2016 data for population values that are greater than max_value or less than min_value\ngdp_outliers = gdp_2016[(gdp_2016['gdp'] > max_value) | (gdp_2016['gdp'] < min_value)]\ngdp_outliers",
"_____no_output_____"
]
],
[
[
"Next, write code to determine which countries are in the population_outliers array and in the gdp_outliers array. ",
"_____no_output_____"
]
],
[
[
"# TODO: Find country names that are in both the population_outliers and the gdp_outliers \nlist(set(population_outliers['Country Name']).intersection(gdp_outliers['Country Name']))",
"_____no_output_____"
]
],
[
[
"These countries have both relatively high populations and high GDPs. That might be an indication that although these countries have high values for both gdp and population, they're not true outliers when looking at these values from a two-dimensional perspective.\n\nNow write code to find countries in population_outliers but not in the gdp_outliers. ",
"_____no_output_____"
]
],
[
[
"# TODO: Find country names that are in the population outliers list but not the gdp outliers list\n# HINT: Python's set() and list() methods should be helpful\n\nlist(set(population_outliers['Country Name']) - set(gdp_outliers['Country Name']))",
"_____no_output_____"
]
],
[
[
"These countries are population outliers but not GDP outliers. If looking at outliers from a two-dimensional perspective, there's some indication that these countries might be outliers.\n\nAnd finally, write code to find countries that are in the gdp_outliers array but not the population_outliers array.",
"_____no_output_____"
]
],
[
[
"# TODO: Find country names that are in the gdp outliers list but not the population outliers list\n# HINT: Python's set() and list() methods should be helpful\n\nlist(set(gdp_outliers['Country Name']) - set(population_outliers['Country Name']))",
"_____no_output_____"
]
],
[
[
"On the other hand, these countries have high GDP but are not population outliers.\n\n\n# Demo: 2-Dimensional Analysis\n\nNext, look at the data from a two-dimensional perspective. You don't have to do anything in this section other than run the code cells below. This gives a basic example of how outlier removal affects machine learning algorithms.\n\nThe next code cell plots the GDP vs Population data including the country name of each point.",
"_____no_output_____"
]
],
[
[
"# run the code cell below\n\nx = list(df_2016['population'])\ny = list(df_2016['gdp'])\ntext = df_2016['Country Name']\n\nfig, ax = plt.subplots(figsize=(15,10))\nax.scatter(x, y)\nplt.title('GDP vs Population')\nplt.xlabel('population')\nplt.ylabel('GDP')\nfor i, txt in enumerate(text):\n ax.annotate(txt, (x[i],y[i]))",
"_____no_output_____"
]
],
[
[
"The United States, China, and India have such larger values that it's hard to see this data. Let's take those countries out for a moment and look at the data again.",
"_____no_output_____"
]
],
[
[
"# Run the code below to see the results \ndf_no_large = (df_2016['Country Name'] != 'United States') & (df_2016['Country Name'] != 'India') & (df_2016['Country Name'] != 'China')\nx = list(df_2016[df_no_large]['population'])\ny = list(df_2016[df_no_large]['gdp'])\ntext = df_2016[df_no_large]['Country Name']\n\nfig, ax = plt.subplots(figsize=(15,10))\nax.scatter(x, y)\nplt.title('GDP vs Population')\nplt.xlabel('population')\nplt.ylabel('GDP')\nfor i, txt in enumerate(text):\n ax.annotate(txt, (x[i],y[i]))",
"_____no_output_____"
]
],
[
[
"Run the code below to build a simple linear regression model with the population and gdp data for 2016.",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LinearRegression\n\n# fit a linear regression model on the population and gdp data\nmodel = LinearRegression()\nmodel.fit(df_2016['population'].values.reshape(-1, 1), df_2016['gdp'].values.reshape(-1, 1))\n\n# plot the data along with predictions from the linear regression model\ninputs = np.linspace(1, 2000000000, num=50)\npredictions = model.predict(inputs.reshape(-1,1))\n\ndf_2016.plot('population', 'gdp', kind='scatter')\nplt.plot(inputs, predictions)\nprint(model.predict(1000000000))",
"[[6.54170378e+12]]\n"
]
],
[
[
"Notice that the code ouputs a GDP value of 6.54e+12 when population equals 1e9. Now run the code below when the United States is taken out of the data set.",
"_____no_output_____"
]
],
[
[
"# Remove the United States to see what happens with the linear regression model\ndf_2016[df_2016['Country Name'] != 'United States'].plot('population', 'gdp', kind='scatter')\n# plt.plot(inputs, predictions)\nmodel.fit(df_2016[df_2016['Country Name'] != 'United States']['population'].values.reshape(-1, 1), \n df_2016[df_2016['Country Name'] != 'United States']['gdp'].values.reshape(-1, 1))\ninputs = np.linspace(1, 2000000000, num=50)\npredictions = model.predict(inputs.reshape(-1,1))\nplt.plot(inputs, predictions)\nprint(model.predict(1000000000))",
"[[5.25824554e+12]]\n"
]
],
[
[
"Notice that the code now ouputs a GDP value of 5.26e+12 when population equals 1e9. In other words, removing the United States shifted the linear regression line down.\n\n# Conclusion\n\nData scientists sometimes have the task of creating an outlier removal model. In this exercise, you've used the Tukey rule. There are other one-dimensional models like eliminating data that is far from the mean. There are also more sophisticated models that take into account multi-dimensional data.\n\nRemember, however, that this is a course on data engineering. As a data engineer, your job will be to remove outliers using code based on whatever model you're given.\n\nIf you were using the Tukey rule, for example, you'd calculate Q1, Q3, and IQR on your training data. You'd need to store these results. Then as new data comes in, you'd use these stored values to eliminate any outliers.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ece4a10fa36e978613e5c80ac9c6fb5ed87a5803 | 68,095 | ipynb | Jupyter Notebook | resae/resae-13-for-digit-classification.ipynb | myinxd/res_ae | 7f682583f79f6f6d6ba94147b557f111ad113dd6 | [
"MIT"
] | 16 | 2018-01-26T06:24:04.000Z | 2021-08-14T10:07:51.000Z | resae/resae-13-for-digit-classification.ipynb | myinxd/res_ae | 7f682583f79f6f6d6ba94147b557f111ad113dd6 | [
"MIT"
] | 3 | 2019-02-27T06:26:50.000Z | 2019-03-04T10:08:48.000Z | resae/resae-13-for-digit-classification.ipynb | myinxd/res_ae | 7f682583f79f6f6d6ba94147b557f111ad113dd6 | [
"MIT"
] | 9 | 2018-07-17T17:23:18.000Z | 2021-12-24T19:17:58.000Z | 106.731975 | 29,320 | 0.847213 | [
[
[
"# Realize ResAE \n# The decoder part only have the symmetic sturcture as the encoder, but weights and biase are initialized.\n# Let's have a try.",
"_____no_output_____"
],
[
"# Display the result\nimport matplotlib\nmatplotlib.use('Agg')\n%matplotlib inline\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"import utils\nimport Block",
"_____no_output_____"
],
[
"import os\nimport time\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.layers as layers",
"_____no_output_____"
],
[
"tf.__version__",
"_____no_output_____"
],
[
"# Step1 load MNITST data\n# change to mat file\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data\", \n one_hot=True,\n validation_size=2000)",
"Extracting MNIST_data/train-images-idx3-ubyte.gz\nExtracting MNIST_data/train-labels-idx1-ubyte.gz\nExtracting MNIST_data/t10k-images-idx3-ubyte.gz\nExtracting MNIST_data/t10k-labels-idx1-ubyte.gz\n"
],
[
"x_in = tf.placeholder(tf.float32, shape=[None,28,28,1],name='inputs')\nx_out = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='outputs')\ncode_length = 128\ncode = tf.placeholder(tf.float32, shape=[None,code_length],name='code')\n\nis_training = tf.placeholder(tf.bool, name='is_training')",
"_____no_output_____"
]
],
[
[
"## Encoder part",
"_____no_output_____"
]
],
[
[
"# Reisudal blocks\nencode_flag = True\nodd_flags = None\nnet = x_in\nblocks_en = [\n [(16, 8, 2)],\n [(32, 16, 2)],\n]\nfor i, block in enumerate(blocks_en):\n print(\"index\", i)\n block_params = utils.get_block(block, is_training=is_training)\n # build the net\n block_obj = Block.Block(\n inputs = net,\n block_params = block_params,\n is_training = is_training,\n encode_flag=encode_flag,\n scope = 'block'+str(i),\n summary_flag = True,\n odd_flags = odd_flags\n )\n net, odd_flags = block_obj.get_block()\n print(\"note odd flags : \", odd_flags)",
"index 0\nen: False\nodd_flags: False\nodd_flags: [False]\nblock en: [False] <class 'tensorflow.python.framework.ops.Tensor'> Tensor(\"block0/block0/bottleneck_en0/add:0\", shape=(?, 14, 14, 16), dtype=float32)\nnote odd flags : [False]\nindex 1\nen: True\nodd_flags: True\nodd_flags: [False, True]\nblock en: [False, True] <class 'tensorflow.python.framework.ops.Tensor'> Tensor(\"block1/block1/bottleneck_en0/add:0\", shape=(?, 7, 7, 32), dtype=float32)\nnote odd flags : [False, True]\n"
],
[
"# get shape of last block\nencode_last_block_shape = net.get_shape()",
"_____no_output_____"
],
[
"# flatten layer\nwith tf.name_scope('flatten_en'):\n net = layers.flatten(net)\n tf.summary.histogram('flatten_en',net)\nflatten_length = int(net.get_shape()[-1])",
"_____no_output_____"
]
],
[
[
"## Encoder layer",
"_____no_output_____"
]
],
[
[
"with tf.name_scope('encoder_layer'):\n net = layers.fully_connected(\n inputs = net,\n num_outputs=code_length,\n activation_fn=tf.nn.relu,\n )\n tf.summary.histogram('encode_layer',net)\n code = net",
"_____no_output_____"
]
],
[
[
"## Decoder block",
"_____no_output_____"
]
],
[
[
"encode_last_block_shape[2]\nprint(odd_flags)",
"[False, True]\n"
],
[
"with tf.name_scope('flatten_de'):\n net = layers.fully_connected(\n inputs = net,\n num_outputs=flatten_length,\n activation_fn=tf.nn.relu,\n )\n tf.summary.histogram('flatten_en', net)",
"_____no_output_____"
],
[
"# flatten to convolve\nwith tf.name_scope('flatten_to_conv'):\n net = tf.reshape(\n net, \n [-1, int(encode_last_block_shape[1]), \n int(encode_last_block_shape[2]), int(encode_last_block_shape[3])])",
"_____no_output_____"
],
[
"net.get_shape()",
"_____no_output_____"
],
[
"# Residual blocks\nblocks_de = [\n [(16, 16, 2)],\n [(1, 8, 2)],]\nfor i, block in enumerate(blocks_de):\n block_params = utils.get_block(block, is_training=is_training)\n # build the net\n \n block_obj = Block.Block(\n inputs = net,\n block_params = block_params,\n is_training = is_training,\n encode_flag=False,\n scope = 'block'+str(i),\n summary_flag = True,\n odd_flags = odd_flags\n )\n net = block_obj.get_block()\nx_out = net",
"0 (?, 7, 7, 16)\n1 (?, 14, 14, 16)\n2 (?, 14, 14, 16)\n(?, 14, 14, 16)\nblock de: <class 'tensorflow.python.framework.ops.Tensor'> Tensor(\"block0_1/add:0\", shape=(?, 14, 14, 16), dtype=float32)\n0 (?, 14, 14, 8)\n1 (?, 28, 28, 8)\n2 (?, 28, 28, 1)\n(?, 28, 28, 1)\nblock de: <class 'tensorflow.python.framework.ops.Tensor'> Tensor(\"block1_1/add:0\", shape=(?, 28, 28, 1), dtype=float32)\n"
],
[
"# loss function\nwith tf.name_scope('loss'):\n cost = tf.reduce_mean(tf.square(x_out-x_in))\n tf.summary.scalar('loss', cost)",
"_____no_output_____"
],
[
"# learning rate\nwith tf.name_scope('learning_rate'):\n init_lr = tf.placeholder(tf.float32, name='LR')\n global_step = tf.placeholder(tf.float32, name=\"global_step\")\n decay_step = tf.placeholder(tf.float32, name=\"decay_step\")\n decay_rate = tf.placeholder(tf.float32, name=\"decay_rate\")\n learning_rate = tf.train.exponential_decay(\n learning_rate = init_lr ,\n global_step = global_step,\n decay_steps = decay_step,\n decay_rate = decay_rate,\n staircase=False,\n name=None) ",
"_____no_output_____"
],
[
"def feed_dict(train,batchsize=100,drop=0.5, lr_dict=None):\n \"\"\"Make a TensorFlow feed_dict: maps data onto Tensor placeholders.\"\"\"\n if train:\n xs, _ = mnist.train.next_batch(batchsize)\n f_dict = {x_in: xs.reshape([-1,28,28,1]), \n is_training: True}\n f_dict.update(lr_dict)\n else: \n # validation\n x_val,_ = mnist.validation.images,mnist.validation.labels\n f_dict = {x_in: x_val.reshape([-1,28,28,1]),\n is_training: False}\n return f_dict",
"_____no_output_____"
],
[
"# Train step \n# note: should add update_ops to the train graph\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\nwith tf.control_dependencies(update_ops):\n with tf.name_scope('train'):\n train_step = tf.train.AdamOptimizer(learning_rate).minimize(cost) ",
"_____no_output_____"
],
[
"# Merge all the summaries and write to logdir\nlogdir = './log'\nif not os.path.exists(logdir):\n os.mkdir(logdir)\nmerged = tf.summary.merge_all()\n# Initialize the variables\nsess = tf.InteractiveSession()\nsess.run(tf.global_variables_initializer())\ntrain_writer = tf.summary.FileWriter(logdir + '/train',\n sess.graph)\nval_writer = tf.summary.FileWriter(logdir + '/validation',\n sess.graph)",
"_____no_output_____"
],
[
"# Training the model by repeatedly running train_step\nimport time \nepochs = 100\nbatchsize= 100\nnum_batches = mnist.train.images.shape[0] // batchsize\n# num_batches = 200\n\nlr_init = 0.001\nd_rate = 0.9\n\nx_epoch = np.arange(0,epochs,1)\ny_loss_trn = np.zeros(x_epoch.shape)\ny_loss_val = np.zeros(x_epoch.shape)\n\n# Init all variables\ntimestamp = time.strftime('%Y-%m-%d: %H:%M:%S', time.localtime(time.time()))\nprint(\"[%s]: Epochs Trn_loss Val_loss\" % (timestamp))\nfor i in range(epochs):\n lr_dict = {init_lr: lr_init, global_step:i,\n decay_step: i, decay_step: batchsize,\n decay_rate: d_rate}\n loss_trn_all = 0.0\n for b in range(num_batches):\n train_dict = feed_dict(True,lr_dict=lr_dict)\n # train\n summary_trn, _, loss_trn = sess.run(\n [merged, train_step, cost], \n feed_dict=train_dict)\n loss_trn_all += loss_trn\n \n y_loss_trn[i] = loss_trn_all / num_batches\n train_writer.add_summary(summary_trn, i)\n # validation\n val_dict = feed_dict(False)\n summary_val, y_loss_val[i] = sess.run(\n [merged, cost],feed_dict=val_dict)\n val_writer.add_summary(summary_val, i)\n if i % 10 == 0:\n timestamp = time.strftime('%Y-%m-%d: %H:%M:%S', time.localtime(time.time()))\n print('[%s]: %d %.4f %.4f' % (timestamp, i, \n y_loss_trn[i], y_loss_val[i]))",
"[2019-02-27: 17:18:12]: Epochs Trn_loss Val_loss\n[2019-02-27: 17:18:26]: 0 0.0172 0.0055\n[2019-02-27: 17:20:41]: 10 0.0018 0.0018\n[2019-02-27: 17:22:54]: 20 0.0014 0.0014\n[2019-02-27: 17:25:05]: 30 0.0012 0.0013\n[2019-02-27: 17:27:17]: 40 0.0011 0.0012\n[2019-02-27: 17:29:31]: 50 0.0011 0.0011\n[2019-02-27: 17:31:43]: 60 0.0010 0.0011\n[2019-02-27: 17:33:58]: 70 0.0010 0.0010\n[2019-02-27: 17:36:11]: 80 0.0009 0.0010\n[2019-02-27: 17:38:25]: 90 0.0009 0.0010\n"
],
[
"plt.rcParams[\"figure.figsize\"] = [8.0,6.0]\n\nplt.plot(x_epoch, y_loss_trn)\nplt.plot(x_epoch, y_loss_val)\nplt.legend(['Training loss', 'Validation loss'])\nplt.xlabel('Epochs')\nplt.ylabel('Loss')",
"_____no_output_____"
],
[
"import pickle\ndata_dict = {\n \"x_epoch\": x_epoch,\n \"y_loss_trn\": y_loss_trn,\n \"y_loss_val\": y_loss_val,\n}\nwith open(\"./result_resae13.pkl\", 'wb') as fp:\n pickle.dump(data_dict, fp)",
"_____no_output_____"
],
[
"# test a image\nimg, _ = mnist.validation.next_batch(10)\nimg = img.reshape(-1,28,28,1)",
"_____no_output_____"
],
[
"img_est = sess.run(x_out, feed_dict={x_in: img, is_training: False})",
"_____no_output_____"
],
[
"def gen_norm(img):\n return (img-img.min())/(img.max() - img.min())\n\nn_examples = 10\nfig, axs = plt.subplots(3, n_examples, figsize=(10, 2))\nfor example_i in range(n_examples):\n # raw\n axs[0][example_i].imshow(np.reshape(img[example_i, :], (28, 28)), cmap='gray')\n axs[0][example_i].axis('off')\n # learned\n axs[1][example_i].imshow(np.reshape(img_est[example_i, :], (28, 28)), cmap='gray')\n axs[1][example_i].axis('off')\n # residual\n norm_raw = gen_norm(np.reshape(img[example_i, :], (28, 28)))\n norm_est = gen_norm(np.reshape(img_est[example_i, :],(28, 28)))\n axs[2][example_i].imshow(norm_raw - norm_est, cmap='gray')\n axs[2][example_i].axis('off')\n\nfig.show()\nplt.draw()",
"/usr/local/lib/python3.5/dist-packages/matplotlib/figure.py:459: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure\n \"matplotlib is currently using a non-GUI backend, \"\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece4d55eed06c718abd222241bad9f894536b46d | 4,969 | ipynb | Jupyter Notebook | SDDVR/viewpointGuiding/ssim_test.ipynb | kidrabit/Data-Visualization-Lab-RND | baa19ee4e9f3422a052794e50791495632290b36 | [
"Apache-2.0"
] | 1 | 2022-01-18T01:53:34.000Z | 2022-01-18T01:53:34.000Z | SDDVR/viewpointGuiding/ssim_test.ipynb | kidrabit/Data-Visualization-Lab-RND | baa19ee4e9f3422a052794e50791495632290b36 | [
"Apache-2.0"
] | null | null | null | SDDVR/viewpointGuiding/ssim_test.ipynb | kidrabit/Data-Visualization-Lab-RND | baa19ee4e9f3422a052794e50791495632290b36 | [
"Apache-2.0"
] | null | null | null | 32.058065 | 121 | 0.461662 | [
[
[
"import cv2, enum, time, os, math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import rankdata\nfrom scipy import spatial\n\n#############################################################################\n# User variables (static)\n#############################################################################\nclass PltFunc :\n def plot1row2Img(img1, img2):\n fig = plt.figure(figsize=(8, 4))\n fig.add_subplot(1,2,1)\n plt.imshow(img1)\n fig.add_subplot(1,2,2)\n plt.imshow(img2)\n plt.show() \n\nclass ALG(enum.Enum):\n MAE = 0\n MSE = 1\n RMSE = 2\n PSNR = 3\n SSIM = 4\n P_MSE = 5 \n \nclass ImgCompare :\n def cvt256gray(img) :\n img = cv2.resize(img, (320,240), interpolation=cv2.INTER_LINEAR )\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n return img\n \n def mae(img1, img2):\n img1 = ImgCompare.cvt256gray(img1)\n img2 = ImgCompare.cvt256gray(img2)\n err = np.sum(abs((img1.astype(\"float\") - img2.astype(\"float\"))))\n err /= float(img1.shape[0] * img1.shape[1])\n return err\n\n def mse(img1, img2):\n img1 = ImgCompare.cvt256gray(img1)\n img2 = ImgCompare.cvt256gray(img2)\n err = np.sum((img1.astype(\"float\") - img2.astype(\"float\")) ** 2)\n err /= float(img1.shape[0] * img1.shape[1])\n return err\n\n def p_mse(img1, img2):\n img1 = ImgCompare.cvt256gray(img1)\n img2 = ImgCompare.cvt256gray(img2)\n maxval = np.max((img1.astype(\"float\") - img2.astype(\"float\")) ** 2)\n err = np.sum((img1.astype(\"float\") - img2.astype(\"float\")) ** 2)\n err /= float(img1.shape[0] * img1.shape[1])\n return err/maxval\n\n def rmse(img1, img2):\n err = ImgCompare.mse(img1, img2)\n return math.sqrt(err)\n\n def psnr(img1, img2):\n _rmse = ImgCompare.rmse(img1,img2)\n if _rmse == 0:\n return 100\n PIXEL_MAX = 255.0\n return 20 * math.log10(PIXEL_MAX / _rmse)\n \n def p_cosSim(img1, img2):\n i1 = img1.flatten()\n i2 = img2.flatten()\n s = spatial.distance.cosine(i2, i1)\n s = abs(s)\n return s\n \n\n def percent_ssim(img1, img2) :\n from skimage.measure import compare_ssim as ssim\n img1 = cv2.resize(img1, (256,256), interpolation=cv2.INTER_LINEAR )\n img2 = cv2.resize(img2, (256,256), interpolation=cv2.INTER_LINEAR )\n s = ssim(img1,img2, multichannel = True)\n return s\n\nif __name__ == \"__main__\":\n imgarr1 = [\"t/11.png\", \"t/21.png\", \"t/31.png\", \"t/41.png\", \"t/51.png\", \"t/61.png\", \"t/71.png\"]\n imgarr2 = [\"t/12.png\", \"t/22.png\", \"t/32.png\", \"t/42.png\", \"t/52.png\", \"t/62.png\", \"t/72.png\"]\n \n for i in range(len(imgarr1)):\n img1 = cv2.imread(imgarr1[i])\n img2 = cv2.imread(imgarr2[i])\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)\n\n ttt = ImgCompare.percent_ssim(img1, img2)\n print(ttt)",
"0.5777726231046171\n0.5793196224441196\n0.49476609318792303\n0.6307202632715424\n0.5459651682576641\n0.3355764917040352\n0.509021141131945\n"
]
]
] | [
"code"
] | [
[
"code"
]
] |
ece4de90c5c548306c5228bf9898a6b1948913b1 | 16,329 | ipynb | Jupyter Notebook | 2D Scatter Plot Age & Strength.ipynb | AustineDsouza/Age-Strength---2D-Scatter-Plot- | 17cfb4c5d29aed07f412347a48996d7bf338f1fa | [
"BSD-2-Clause"
] | null | null | null | 2D Scatter Plot Age & Strength.ipynb | AustineDsouza/Age-Strength---2D-Scatter-Plot- | 17cfb4c5d29aed07f412347a48996d7bf338f1fa | [
"BSD-2-Clause"
] | null | null | null | 2D Scatter Plot Age & Strength.ipynb | AustineDsouza/Age-Strength---2D-Scatter-Plot- | 17cfb4c5d29aed07f412347a48996d7bf338f1fa | [
"BSD-2-Clause"
] | null | null | null | 164.939394 | 14,396 | 0.909425 | [
[
[
"#Exploratory Data Analysis\n#2D Scatter plot",
"_____no_output_____"
],
[
"import pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"#Load dataset into pandas dataframe\nresults = pd.read_excel('C:\\Austine\\Blog\\ML\\Reference\\Age_Strength.xlsx')",
"_____no_output_____"
],
[
"#Always understand the axis: labels and scale\n\nresults.plot(kind='scatter', x='Age', y='Weight');\nplt.xlabel('Age')\nplt.ylabel('Weights pulled')\nplt.title('Weight pulling capacity')\nplt.show()\n\n#We can see that the students who are spending more time studies daily have received higher score in maths",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
ece4ed83a886276cb86c236935907c896617c606 | 902 | ipynb | Jupyter Notebook | csgm.ipynb | zbaoye/progressive_growing_of_gans_tensorflow | 7eefe325e40c7af4462d53836d0cf11511c58c41 | [
"MIT"
] | null | null | null | csgm.ipynb | zbaoye/progressive_growing_of_gans_tensorflow | 7eefe325e40c7af4462d53836d0cf11511c58c41 | [
"MIT"
] | null | null | null | csgm.ipynb | zbaoye/progressive_growing_of_gans_tensorflow | 7eefe325e40c7af4462d53836d0cf11511c58c41 | [
"MIT"
] | null | null | null | 20.044444 | 53 | 0.488914 | [
[
[
"[9,1],[17,1],[25,1],[33,1],[41,1],[49,1]\n[13,5],[21,5],[29,5],[37,5],[45,5],[53,5]\n[9,9],[17,9],[25,9],[33,9],[41,9],[49,9]\n[13,13],[21,13],[29,13],[37,13],[45,13],[53,13]",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
ece4edeb352e0a9736f70573bfe6db1c24b6de3b | 878,601 | ipynb | Jupyter Notebook | 02_rainbow(1)(1).ipynb | muath22/BookStore | db5b30e540de311931b234e71937ace3db9750c8 | [
"MIT"
] | null | null | null | 02_rainbow(1)(1).ipynb | muath22/BookStore | db5b30e540de311931b234e71937ace3db9750c8 | [
"MIT"
] | null | null | null | 02_rainbow(1)(1).ipynb | muath22/BookStore | db5b30e540de311931b234e71937ace3db9750c8 | [
"MIT"
] | null | null | null | 408.651628 | 146,986 | 0.902214 | [
[
[
"<a href=\"https://colab.research.google.com/github/DanIulian/BookStore/blob/master/02_rainbow(1)(1).ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Not Quite Rainbow",
"_____no_output_____"
]
],
[
[
" !apt install xvfb python-opengl ffmpeg -y > /dev/null 2>&1\n !pip install pyvirtualdisplay > /dev/null 2>&1\n !pip install -U torch > /dev/null 2>&1\n !pip install git+git://github.com/maximecb/gym-minigrid.git@master#egg=gym-minigrid > /dev/null 2>&1\n\n!pip uninstall gym-minigrid gym\n!pip install --upgrade pip!pip install git+git://github.com/floringogianu/gym-minigrid.git@poli#egg=gym-minigrid > /dev/null 2>&1\n!pip install --ignore-installed sixprint(\"\\nRuntime > Restart Runtime after this cell executes!\")",
"\u001b[33mWARNING: Skipping gym-minigrid as it is not installed.\u001b[0m\nUninstalling gym-0.10.11:\n Would remove:\n /usr/local/lib/python3.6/dist-packages/gym-0.10.11.dist-info/*\n /usr/local/lib/python3.6/dist-packages/gym/*\nProceed (y/n)? y\n Successfully uninstalled gym-0.10.11\n\nRuntime > Restart Runtime after this cell executes!\n"
],
[
"import itertools\nimport random\nfrom argparse import Namespace\nfrom collections import deque, defaultdict\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as O\nfrom torchvision import transforms as T\nfrom PIL import Image\nimport gym\nimport gym_minigrid\nfrom gym_minigrid.wrappers import RGBImgPartialObsWrapper, ImgObsWrapper, ReseedWrapper\n\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\nsns.set()\n\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"OpenAI Gym: {gym.__version__}. \\t\\tShould be: ~0.15.x\")\nprint(f\"PyTorch : {torch.__version__}. \\tShould be: >=1.2.x+cu100\")\nprint(f\"DEVICE : {DEVICE}. \\t\\tShould be: cuda\")",
"OpenAI Gym: 0.15.3. \t\tShould be: ~0.15.x\nPyTorch : 1.3.0+cu100. \tShould be: >=1.2.x+cu100\nDEVICE : cuda. \t\tShould be: cuda\n"
],
[
"def reset_rng(seed=42):\n print(f\"Setting all rngs to seed={seed}\")\n torch.manual_seed(seed)\n np.random.seed(seed)\n random.seed(seed)\n\nreset_rng()",
"Setting all rngs to seed=42\n"
],
[
"envs = Namespace(\n easy=\"MiniGrid-Empty-5x5-v0\",\n maze=\"MiniGrid-SimpleCrossingS9N1-v0\",\n two_maze=\"MiniGrid-SimpleCrossingS9N2-v0\",\n large_maze=\"MiniGrid-SimpleCrossingS11N1-v0\",\n overestimation=\"MiniGrid-OverEstimation-9x9-v0\",\n random_overestimation=\"MiniGrid-OverEstimation-Random-9x9-v0\",\n fetch=\"MiniGrid-Fetch-8x8-N3-v0\"\n)",
"_____no_output_____"
],
[
"# Define some helpers: Gym Wrappers and visualization functions\n\nclass TorchWrapper(gym.ObservationWrapper):\n \"\"\" Applies a couple of transformations depending on the mode.\n Receives numpy arrays and returns torch tensors.\n \"\"\"\n\n def __init__(self, env):\n super().__init__(env)\n self._transform = T.Compose([\n lambda obs: (obs * int(255 / 9)).swapaxes(1, 0),\n lambda obs: torch.from_numpy(obs).permute(2, 1, 0)\n ])\n \n def observation(self, obs):\n return self._transform(obs).unsqueeze(0).to(DEVICE)\n\n\nclass FrameStack(gym.Wrapper):\n \"\"\"Stack k last frames. \"\"\"\n\n def __init__(self, env, k, verbose=False):\n super().__init__(env)\n self.k = k\n self.frames = deque([], maxlen=k)\n\n def reset(self):\n observation = self.env.reset()\n for _ in range(self.k):\n self.frames.append(observation)\n return self._get_ob()\n\n def step(self, action):\n observation, reward, done, info = self.env.step(action)\n self.frames.append(observation)\n return self._get_ob(), reward, done, info\n\n def _get_ob(self):\n assert len(self.frames) == self.k\n if self.k == 1:\n return self.frames.pop()\n return np.concatenate(list(self.frames), axis=2)\n\n\ndef show_representations(env_name=\"MiniGrid-SimpleCrossingS9N1-v0\", tile_size=8):\n seed = torch.randint(100, (1,)).item()\n\n env = ImgObsWrapper(RGBImgPartialObsWrapper(gym.make(env_name), tile_size=tile_size))\n print(\"Action-space: \", env.action_space.n)\n env.seed(seed)\n rgb_obs = env.reset()\n\n env = ImgObsWrapper(gym.make(env_name))\n env.seed(seed)\n sym_obs = env.reset()\n\n print(\"RGB:\", rgb_obs.shape)\n print(\"SYM:\", sym_obs.shape)\n\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 36))\n ax1.imshow(rgb_obs)\n ax2.imshow((sym_obs * int(255 / 9)).swapaxes(1, 0))\n ax3.imshow(env.render(mode=\"rgb_array\"))\n\n\ndef plot_stats(stats, y=\"ep_rewards\", hue=None, window=10):\n df = pd.DataFrame(stats)\n\n if window:\n new_col = f\"avg_{y}\"\n if hue is not None:\n df[new_col] = df.groupby(hue)[y].rolling(window=window).mean().reset_index(0,drop=True)\n else:\n df[new_col] = df[y].rolling(window=window).mean()\n \n y = f\"avg_{y}\" if window else y\n with matplotlib.rc_context({'figure.figsize':(10, 6)}):\n sns.lineplot(x=\"step_idx\", y=y, hue=hue, data=df)",
"_____no_output_____"
]
],
[
[
"## Let's take a look at the environments",
"_____no_output_____"
]
],
[
[
"for k, v in vars(envs).items():\n print(f\"{k:<24}: {v}\")",
"easy : MiniGrid-Empty-5x5-v0\nmaze : MiniGrid-SimpleCrossingS9N1-v0\ntwo_maze : MiniGrid-SimpleCrossingS9N2-v0\nlarge_maze : MiniGrid-SimpleCrossingS11N1-v0\noverestimation : MiniGrid-OverEstimation-9x9-v0\nrandom_overestimation : MiniGrid-OverEstimation-Random-9x9-v0\nfetch : MiniGrid-Fetch-8x8-N3-v0\n"
],
[
"# you can execute this a few times to get an idea about the two possible\n# views of the agent\nshow_representations(envs.overestimation, tile_size=8)",
"Action-space: 7\nRGB: (56, 56, 3)\nSYM: (7, 7, 3)\n"
]
],
[
[
"## Let's define the training routine.\n\nIt takes an agent and an environment and implements the action-perception loop.",
"_____no_output_____"
]
],
[
[
"def train(agent, env, step_num=100_000):\n \n stats, N = {\"step_idx\": [0], \"ep_rewards\": [0.0], \"ep_steps\": [0.0]}, 0\n\n state, done = env.reset().clone(), False\n for step in range(step_num):\n\n action = agent.step(state)\n state_, reward, done, _ = env.step(action)\n agent.learn(state, action, reward, state_, done)\n\n # some envs just update the state and are not returning a new one\n state = state_.clone()\n\n # stats\n stats[\"ep_rewards\"][N] += reward\n stats[\"ep_steps\"][N] += 1\n\n if done:\n # episode done, reset env!\n state, done = env.reset().clone(), False\n \n # some more stats\n if N % 10 == 0:\n print(\"[{0:3d}][{1:6d}], R/ep={2:6.2f}, steps/ep={3:2.0f}.\".format(\n N, step,\n torch.tensor(stats[\"ep_rewards\"][-10:]).mean().item(),\n torch.tensor(stats[\"ep_steps\"][-10:]).mean().item(),\n ))\n\n stats[\"ep_rewards\"].append(0.0) # reward accumulator for a new episode\n stats[\"ep_steps\"].append(0.0) # reward accumulator for a new episode\n stats[\"step_idx\"].append(step)\n N += 1\n\n print(\"[{0:3d}][{1:6d}], R/ep={2:6.2f}, steps/ep={3:2.0f}.\".format(\n N, step, torch.tensor(stats[\"ep_rewards\"][-10:]).mean().item(),\n torch.tensor(stats[\"ep_steps\"][-10:]).mean().item(),\n ))\n stats[\"agent\"] = [agent.__class__.__name__ for _ in range(N+1)]\n return stats",
"_____no_output_____"
]
],
[
[
"## Start implementing the DQN agent",
"_____no_output_____"
],
[
"## 1. Experience Replay\n\n#### TASK 1: implement `sample` method.",
"_____no_output_____"
]
],
[
[
"class ReplayMemory:\n def __init__(self, size=1000, batch_size=32):\n self._buffer = deque(maxlen=size)\n self._batch_size = batch_size\n \n def push(self, transition):\n self._buffer.append(transition)\n \n def sample(self):\n \"\"\" Sample from self._buffer\n\n Should return a tuple of tensors of size: \n (\n states: N * (C*K) * H * W, (torch.uint8)\n actions: N * 1, (torch.int64)\n rewards: N * 1, (torch.float32)\n states_: N * (C*K) * H * W, (torch.uint8)\n done: N * 1, (torch.uint8)\n )\n\n where N is the batch_size, C is the number of channels = 3 and\n K is the number of stacked states.\n \"\"\"\n # sample\n \n s_list, a_list, r_list, s_list_, d_list = zip(*random.sample(self._buffer, self._batch_size))\n \n s = torch.cat(s_list).to(DEVICE)\n s_ = torch.cat(s_list_).to(DEVICE)\n a = torch.LongTensor(a_list).unsqueeze(-1).to(DEVICE)\n r = torch.DoubleTensor(r_list).unsqueeze(-1).to(DEVICE)\n d = torch.zeros((self._batch_size, 1), dtype=torch.uint8).to(DEVICE)\n d[np.array(d_list) == True] = 1\n \n return (s, a, r, s_, d)\n \n\n def __len__(self):\n return len(self._buffer)",
"_____no_output_____"
]
],
[
[
"## 2. $\\epsilon$-greedy schedule.\n\n#### TASK 2: Implement the epsilon-greedy schedule",
"_____no_output_____"
]
],
[
[
"def get_epsilon_schedule(start=1.0, end=0.1, steps=500):\n \"\"\" Returns either:\n - a generator of epsilon values\n - a function that receives the current step and returns an epsilon\n\n The epsilon values returned by the generator or function need\n to be degraded from the `start` value to the `end` within the number \n of `steps` and then continue returning the `end` value indefinetly.\n\n You can pick any schedule (exp, poly, etc.). I tested with linear decay.\n \"\"\"\n t = 0\n while True:\n if t >= steps:\n yield end\n else:\n eps = start - (start - end) / steps * t\n t += 1\n yield eps\n \n\n\n# test it, it needs to look nice\nepsilon = get_epsilon_schedule(1.0, 0.1, 100)\nplt.plot([next(epsilon) for _ in range(500)])\n\n# or if you prefer a function\n# epsilon_fn = get_epsilon_schedule(1.0, 0.1, 100)\n# plt.plot([epsilon(step_idx) for step_idx in range(500)])",
"_____no_output_____"
]
],
[
[
"### Define a Neural Network Approximator for your Agents",
"_____no_output_____"
]
],
[
[
"class ByteToFloat(nn.Module):\n \"\"\" Converts ByteTensor to FloatTensor and rescales.\n \"\"\"\n def forward(self, x):\n assert (\n x.dtype == torch.uint8\n ), \"The model expects states of type ByteTensor.\"\n return x.float().div_(255)\n\n\nclass View(nn.Module):\n def forward(self, x):\n return x.view(x.size(0), -1)\n\n\ndef get_estimator(action_num, input_ch=3, lin_size=32):\n return nn.Sequential(\n ByteToFloat(),\n nn.Conv2d(input_ch, 16, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.Conv2d(16, 16, kernel_size=2),\n nn.ReLU(inplace=True),\n nn.Conv2d(16, 16, kernel_size=2),\n nn.ReLU(inplace=True),\n View(),\n nn.Linear(9 * 16, lin_size),\n nn.ReLU(inplace=True),\n nn.Linear(lin_size, action_num),\n ).to(DEVICE)",
"_____no_output_____"
]
],
[
[
"## 3. DQN Agent, finally\n\n#### TASK 3: \n- implement the `step()` method\n- implement the `learn()` method\n- implement the `_update()` method",
"_____no_output_____"
]
],
[
[
"class DQN:\n def __init__(\n self,\n estimator,\n buffer,\n optimizer,\n epsilon_schedule,\n action_num,\n gamma=0.92,\n update_steps=4,\n update_target_steps=10,\n warmup_steps=100,\n ):\n self._estimator = estimator\n self._target_estimator = deepcopy(estimator)\n self._buffer = buffer\n self._optimizer = optimizer\n self._epsilon = epsilon_schedule\n self._action_num = action_num\n self._gamma = gamma\n self._update_steps=update_steps\n self._update_target_steps=update_target_steps\n self._warmup_steps = warmup_steps\n self._step_cnt = 0\n assert warmup_steps > self._buffer._batch_size, (\n \"You should have at least a batch in the ER.\")\n \n def step(self, state):\n # implement an epsilon greedy policy using the\n # estimator and epsilon schedule attributes.\n\n # warning, you should make sure you are not including\n # this step into torch computation graph\n \n if self._step_cnt < self._warmup_steps:\n return torch.randint(self._action_num, (1,)).item()\n\n # return the action according to the self._epsilon schedule\n # you defined earlier\n if np.random.random() < next(self._epsilon):\n return torch.randint(self._action_num, (1,)).item()\n else:\n with torch.no_grad():\n acts = self._estimator(state)\n return acts.argmax(dim=1)\n\n \n\n def learn(self, state, action, reward, state_, done):\n\n # TODO: add transition to the experience replay\n self._buffer.push((state, action, reward, state_, done))\n \n if self._step_cnt < self._warmup_steps:\n self._step_cnt += 1\n return\n\n if self._step_cnt % self._update_steps == 0:\n # TODO: sample from experience replay and do an update\n s, a, r, s_, d = self._buffer.sample() \n self._update(s, a, r, s_, d)\n \n if self._step_cnt % self._update_target_steps == 0:\n # TODO: update the target estimator (hint, use pytorch state_dict methods)\n self._target_estimator.load_state_dict(self._estimator.state_dict())\n \n self._step_cnt += 1\n\n def _update(self, states, actions, rewards, states_, done):\n # compute the DeepQNetwork update. Carefull not to include the\n # target network in the computational graph.\n \n # Compute Q(s, * | θ) and Q(s', . | θ^)\n q_values = self._estimator(states)\n \n with torch.no_grad():\n q_values_ = self._target_estimator(states_)\n \n qsa = torch.gather(q_values, dim=1, index=actions)\n qsa_, _ = torch.max(q_values_, dim=1)\n qsa_ = qsa_.unsqueeze(-1)\n # compute Q(s, a) and max_a' Q(s', a')\n # qsa = \n # qsa_ = \n\n \n # compute target values\n target_qsa = rewards + (1 - done) * self._gamma * qsa_\n\n # at this step you should check the target values\n # are looking about right :). You can use this code.\n # if rewards.squeeze().sum().item() > 0.0:\n # print(\"R: \", rewards.squeeze())\n # print(\"T: \", target_qsa.squeeze())\n # print(\"D: \", done.squeeze())\n\n # compute the loss and average it over the entire batch\n \n loss = nn.functional.mse_loss(qsa.float(), target_qsa.float())\n \n self._optimizer.zero_grad()\n loss.backward()\n\n self._optimizer.step()\n # backprop and optimize\n \n",
"_____no_output_____"
],
[
"env = gym.make(envs.easy)\nenv = TorchWrapper(ImgObsWrapper(env))\nnet = get_estimator(env.action_space.n)\n\nstats = train(\n DQN(\n net,\n ReplayMemory(size=1000, batch_size=32),\n O.Adam(net.parameters(), lr=1e-3, eps=1e-4),\n get_epsilon_schedule(start=1.0, end=0.1, steps=4000),\n env.action_space.n,\n warmup_steps=100,\n update_steps=2,\n ),\n env,\n step_num=7_000 # change the experiment length if it's learning but not reaching about .95\n)",
"[ 0][ 99], R/ep= 0.00, steps/ep=100.\n[ 10][ 851], R/ep= 0.28, steps/ep=75.\n[ 20][ 1596], R/ep= 0.29, steps/ep=74.\n[ 30][ 2156], R/ep= 0.47, steps/ep=56.\n[ 40][ 2942], R/ep= 0.25, steps/ep=79.\n[ 50][ 3704], R/ep= 0.26, steps/ep=76.\n[ 60][ 4590], R/ep= 0.15, steps/ep=89.\n[ 70][ 4858], R/ep= 0.76, steps/ep=27.\n[ 80][ 5050], R/ep= 0.83, steps/ep=19.\n[ 90][ 5125], R/ep= 0.93, steps/ep= 8.\n[100][ 5234], R/ep= 0.90, steps/ep=11.\n[110][ 5302], R/ep= 0.94, steps/ep= 7.\n[120][ 5373], R/ep= 0.94, steps/ep= 7.\n[130][ 5449], R/ep= 0.93, steps/ep= 8.\n[140][ 5511], R/ep= 0.94, steps/ep= 6.\n[150][ 5583], R/ep= 0.94, steps/ep= 7.\n[160][ 5649], R/ep= 0.94, steps/ep= 7.\n[170][ 5718], R/ep= 0.94, steps/ep= 7.\n[180][ 5785], R/ep= 0.94, steps/ep= 7.\n[190][ 5848], R/ep= 0.94, steps/ep= 6.\n[200][ 5926], R/ep= 0.93, steps/ep= 8.\n[210][ 5994], R/ep= 0.94, steps/ep= 7.\n[220][ 6061], R/ep= 0.94, steps/ep= 7.\n[230][ 6133], R/ep= 0.94, steps/ep= 7.\n[240][ 6195], R/ep= 0.94, steps/ep= 6.\n[250][ 6265], R/ep= 0.94, steps/ep= 7.\n[260][ 6335], R/ep= 0.94, steps/ep= 7.\n[270][ 6401], R/ep= 0.94, steps/ep= 7.\n[280][ 6474], R/ep= 0.93, steps/ep= 7.\n[290][ 6540], R/ep= 0.94, steps/ep= 7.\n[300][ 6613], R/ep= 0.93, steps/ep= 7.\n[310][ 6686], R/ep= 0.93, steps/ep= 7.\n[320][ 6748], R/ep= 0.94, steps/ep= 6.\n[330][ 6813], R/ep= 0.94, steps/ep= 6.\n[340][ 6884], R/ep= 0.94, steps/ep= 7.\n[350][ 6951], R/ep= 0.94, steps/ep= 7.\n[358][ 6999], R/ep= 0.84, steps/ep= 6.\n"
],
[
"plot_stats(stats)",
"_____no_output_____"
]
],
[
[
"## 4. Train on a partial observable maze",
"_____no_output_____"
]
],
[
[
"show_representations(envs.maze)\n# show_representations(envs.large_maze)",
"Action-space: 7\nRGB: (56, 56, 3)\nSYM: (7, 7, 3)\n"
],
[
"step_num=30_000\nseeds = [2, 5] # add more map configurations\nhist_len = [1, 2, 3] # increase it to two and compare\n\ncommon_seed = np.random.randint(1000)\nstats = defaultdict(list)\nfor K in hist_len:\n print(f\"Started training with hist_len={K}.\")\n # 102 worked nicely here :))\n reset_rng(common_seed) # we want each experiment to have the same starting conditions\n \n env = gym.make(envs.maze)\n env = TorchWrapper(FrameStack(ImgObsWrapper(ReseedWrapper(env, seeds=seeds)), k=K))\n net = get_estimator(env.action_space.n, input_ch=K*3, lin_size=64)\n \n stats_ = train(\n DQN(\n net,\n ReplayMemory(size=10_000, batch_size=32),\n O.Adam(net.parameters(), lr=1e-3, eps=1e-4),\n get_epsilon_schedule(start=1.0, end=0.1, steps=10_000),\n env.action_space.n,\n warmup_steps=1000,\n update_steps=2,\n update_target_steps=8\n ),\n env,\n step_num=step_num\n )\n\n stats_[\"hist_len\"] = [K] * len(stats_[\"ep_rewards\"])\n for k, v in stats_.items():\n stats[k] += v",
"Started training with hist_len=1.\nSetting all rngs to seed=988\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 3432], R/ep= 0.06, steps/ep=311.\n[ 20][ 6672], R/ep= 0.00, steps/ep=324.\n[ 30][ 9213], R/ep= 0.24, steps/ep=254.\n[ 40][ 12297], R/ep= 0.06, steps/ep=308.\n[ 50][ 15499], R/ep= 0.03, steps/ep=320.\n[ 60][ 17776], R/ep= 0.33, steps/ep=228.\n[ 70][ 20292], R/ep= 0.24, steps/ep=252.\n[ 80][ 22879], R/ep= 0.21, steps/ep=259.\n[ 90][ 24408], R/ep= 0.55, steps/ep=153.\n[100][ 25161], R/ep= 0.79, steps/ep=75.\n[110][ 25914], R/ep= 0.78, steps/ep=75.\n[120][ 26319], R/ep= 0.89, steps/ep=40.\n[130][ 26812], R/ep= 0.86, steps/ep=49.\n[140][ 27114], R/ep= 0.92, steps/ep=30.\n[150][ 27678], R/ep= 0.84, steps/ep=56.\n[160][ 28567], R/ep= 0.73, steps/ep=89.\n[170][ 29232], R/ep= 0.82, steps/ep=66.\n[180][ 29646], R/ep= 0.89, steps/ep=41.\n[190][ 29932], R/ep= 0.92, steps/ep=29.\n[191][ 29999], R/ep= 0.83, steps/ep=31.\nStarted training with hist_len=2.\nSetting all rngs to seed=988\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 3450], R/ep= 0.04, steps/ep=313.\n[ 20][ 6690], R/ep= 0.00, steps/ep=324.\n[ 30][ 9930], R/ep= 0.00, steps/ep=324.\n[ 40][ 13170], R/ep= 0.00, steps/ep=324.\n[ 50][ 16410], R/ep= 0.00, steps/ep=324.\n[ 60][ 19490], R/ep= 0.05, steps/ep=308.\n[ 70][ 22641], R/ep= 0.03, steps/ep=315.\n[ 80][ 25626], R/ep= 0.10, steps/ep=298.\n[ 90][ 26653], R/ep= 0.71, steps/ep=103.\n"
],
[
"plot_stats(stats, hue=\"hist_len\")",
"_____no_output_____"
]
],
[
[
"## 5. Double DQN\n\n\n#### TASK 4: Implement the _update() method for DoubleDQN",
"_____no_output_____"
]
],
[
[
"class DoubleDQN(DQN):\n def _update(self, states, actions, rewards, states_, done):\n # compute the DeepQNetwork update. Carefull not to include the\n # target network in the computational graph.\n\n # Compute Q(s, * | θ) and Q(s', . | θ^)\n # q_values = \n # q_values_ = \n \n #... and the rest of it\n\n # Compute Q(s, * | θ) and Q(s', . | θ^)\n \n with torch.no_grad():\n q_values_target = self._target_estimator(states_)\n q_values_doubledqn = self._estimator(states_)\n \n q_values_online_net = self._estimator(states)\n\n qsa_online_net = torch.gather(q_values_online_net, dim=1, index=actions)\n \n actions_max = torch.argmax(q_values_doubledqn, dim=1).unsqueeze(-1)\n \n qsa_target_net = torch.gather(q_values_target, dim=1, index=actions_max)\n \n #qsa = torch.gather(q_values, dim=1, index=actions)\n #qsa_, _ = torch.max(q_values_, dim=1)\n #qsa_ = qsa_.unsqueeze(-1)\n # compute Q(s, a) and max_a' Q(s', a')\n # qsa = \n # qsa_ = \n\n \n # compute target values\n target_qsa = rewards + (1 - done) * self._gamma * qsa_target_net\n\n # at this step you should check the target values\n # are looking about right :). You can use this code.\n # if rewards.squeeze().sum().item() > 0.0:\n # print(\"R: \", rewards.squeeze())\n # print(\"T: \", target_qsa.squeeze())\n # print(\"D: \", done.squeeze())\n\n # compute the loss and average it over the entire batch\n \n loss = nn.functional.mse_loss(qsa_online_net.float(), target_qsa.float())\n \n self._optimizer.zero_grad()\n loss.backward()\n\n self._optimizer.step()\n # backprop and optimize",
"_____no_output_____"
],
[
"env = gym.make(envs.easy)\nenv = TorchWrapper(ImgObsWrapper(env))\nnet = get_estimator(env.action_space.n)\n\nstats = train(\n DoubleDQN(\n net,\n ReplayMemory(size=1000, batch_size=32),\n O.Adam(net.parameters(), lr=1e-3, eps=1e-4),\n get_epsilon_schedule(start=1.0, end=0.1, steps=4000),\n env.action_space.n,\n warmup_steps=100,\n update_steps=2,\n update_target_steps=16\n ),\n env,\n step_num=7_000 # change the experiment length if it's learning but not reaching about .95\n)",
"[ 0][ 21], R/ep= 0.80, steps/ep=22.\n[ 10][ 890], R/ep= 0.15, steps/ep=87.\n[ 20][ 1481], R/ep= 0.45, steps/ep=59.\n[ 30][ 1967], R/ep= 0.55, steps/ep=49.\n[ 40][ 2525], R/ep= 0.48, steps/ep=56.\n[ 50][ 3191], R/ep= 0.37, steps/ep=67.\n[ 60][ 3835], R/ep= 0.38, steps/ep=64.\n[ 70][ 4340], R/ep= 0.52, steps/ep=50.\n[ 80][ 4527], R/ep= 0.83, steps/ep=19.\n[ 90][ 4690], R/ep= 0.85, steps/ep=16.\n[100][ 4871], R/ep= 0.84, steps/ep=18.\n[110][ 4944], R/ep= 0.93, steps/ep= 7.\n[120][ 5024], R/ep= 0.93, steps/ep= 8.\n[130][ 5124], R/ep= 0.91, steps/ep=10.\n[140][ 5257], R/ep= 0.88, steps/ep=13.\n[150][ 5345], R/ep= 0.92, steps/ep= 9.\n[160][ 5429], R/ep= 0.92, steps/ep= 8.\n[170][ 5524], R/ep= 0.91, steps/ep=10.\n[180][ 5593], R/ep= 0.94, steps/ep= 7.\n[190][ 5676], R/ep= 0.93, steps/ep= 8.\n[200][ 5760], R/ep= 0.92, steps/ep= 8.\n[210][ 5836], R/ep= 0.93, steps/ep= 8.\n[220][ 5910], R/ep= 0.93, steps/ep= 7.\n[230][ 5988], R/ep= 0.93, steps/ep= 8.\n[240][ 6062], R/ep= 0.93, steps/ep= 7.\n[250][ 6135], R/ep= 0.93, steps/ep= 7.\n[260][ 6219], R/ep= 0.92, steps/ep= 8.\n[270][ 6296], R/ep= 0.93, steps/ep= 8.\n[280][ 6373], R/ep= 0.93, steps/ep= 8.\n[290][ 6454], R/ep= 0.93, steps/ep= 8.\n[300][ 6523], R/ep= 0.94, steps/ep= 7.\n[310][ 6592], R/ep= 0.94, steps/ep= 7.\n[320][ 6655], R/ep= 0.94, steps/ep= 6.\n[330][ 6746], R/ep= 0.92, steps/ep= 9.\n[340][ 6813], R/ep= 0.94, steps/ep= 7.\n[350][ 6881], R/ep= 0.94, steps/ep= 7.\n[360][ 6945], R/ep= 0.94, steps/ep= 6.\n[369][ 6999], R/ep= 0.85, steps/ep= 6.\n"
],
[
"plot_stats(stats)",
"_____no_output_____"
]
],
[
[
"## 6. DQN vs Double DQN: OverEstimation environment",
"_____no_output_____"
]
],
[
[
"show_representations(envs.overestimation)",
"Action-space: 7\nRGB: (56, 56, 3)\nSYM: (7, 7, 3)\n"
],
[
"step_num = 50_000 # change the experiment length\nstats = defaultdict(list)\n\ncommon_seed = np.random.randint(1000)\nfor Agent in [DQN, DoubleDQN]:\n # 256 worked nicely here :))\n reset_rng(common_seed) # we want each experiment to have the same starting conditions\n\n env = TorchWrapper(ImgObsWrapper(gym.make(envs.overestimation)))\n net = get_estimator(env.action_space.n)\n \n agent_name = Agent.__name__\n print(f\"\\n{agent_name} started training.\")\n stats_ = train(\n Agent(\n net,\n ReplayMemory(size=5000, batch_size=32),\n O.Adam(net.parameters(), lr=1e-3, eps=1e-4),\n get_epsilon_schedule(start=1.0, end=0.1, steps=5000),\n env.action_space.n,\n warmup_steps=3000,\n update_steps=2,\n update_target_steps=256\n ),\n env,\n step_num=step_num\n )\n\n for k, v in stats_.items():\n stats[k] += v",
"Setting all rngs to seed=668\n\nDQN started training.\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 2902], R/ep= 0.33, steps/ep=258.\n[ 20][ 5564], R/ep= 0.49, steps/ep=266.\n[ 30][ 6351], R/ep= 2.20, steps/ep=79.\n[ 40][ 7539], R/ep= 0.67, steps/ep=119.\n[ 50][ 9377], R/ep= -0.38, steps/ep=184.\n[ 60][ 12617], R/ep= 0.00, steps/ep=324.\n[ 70][ 14374], R/ep= 0.39, steps/ep=176.\n[ 80][ 15398], R/ep= 0.35, steps/ep=102.\n[ 90][ 15831], R/ep= 0.54, steps/ep=43.\n[100][ 16695], R/ep= 1.80, steps/ep=86.\n[110][ 17018], R/ep= 1.42, steps/ep=32.\n[120][ 17176], R/ep= 0.89, steps/ep=16.\n[130][ 17973], R/ep= 1.17, steps/ep=80.\n[140][ 20592], R/ep= 0.86, steps/ep=262.\n[150][ 21701], R/ep= 0.75, steps/ep=111.\n[160][ 22048], R/ep= 1.44, steps/ep=35.\n[170][ 22373], R/ep= 1.72, steps/ep=32.\n[180][ 22706], R/ep= 0.71, steps/ep=33.\n[190][ 22996], R/ep= -0.20, steps/ep=29.\n[200][ 23614], R/ep= 0.72, steps/ep=62.\n[210][ 23913], R/ep= 1.39, steps/ep=30.\n[220][ 24179], R/ep= 0.19, steps/ep=27.\n[230][ 25991], R/ep= 0.50, steps/ep=181.\n[240][ 27474], R/ep= 0.49, steps/ep=148.\n[250][ 30228], R/ep= 0.22, steps/ep=275.\n[260][ 31845], R/ep= -0.47, steps/ep=162.\n[270][ 35085], R/ep= 0.00, steps/ep=324.\n[280][ 38325], R/ep= 0.00, steps/ep=324.\n[290][ 41565], R/ep= 0.00, steps/ep=324.\n[300][ 44805], R/ep= 0.00, steps/ep=324.\n[310][ 48045], R/ep= 0.00, steps/ep=324.\n[317][ 49999], R/ep= 0.00, steps/ep=293.\nSetting all rngs to seed=668\n\nDoubleDQN started training.\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 2902], R/ep= 0.33, steps/ep=258.\n[ 20][ 5232], R/ep= -0.63, steps/ep=233.\n[ 30][ 6922], R/ep= 0.26, steps/ep=169.\n[ 40][ 7994], R/ep= 1.12, steps/ep=107.\n[ 50][ 8914], R/ep= 0.20, steps/ep=92.\n[ 60][ 10620], R/ep= 0.29, steps/ep=171.\n[ 70][ 12405], R/ep= 0.18, steps/ep=178.\n[ 80][ 12924], R/ep= 0.86, steps/ep=52.\n[ 90][ 13329], R/ep= 0.89, steps/ep=40.\n[100][ 13857], R/ep= 0.84, steps/ep=53.\n[110][ 14357], R/ep= 0.85, steps/ep=50.\n[120][ 16176], R/ep= 0.48, steps/ep=182.\n[130][ 17090], R/ep= 0.73, steps/ep=91.\n[140][ 17436], R/ep= 0.90, steps/ep=35.\n[150][ 17564], R/ep= 0.96, steps/ep=13.\n[160][ 17692], R/ep= 0.96, steps/ep=13.\n[170][ 17837], R/ep= 0.96, steps/ep=14.\n[180][ 17968], R/ep= 0.96, steps/ep=13.\n[190][ 18086], R/ep= 0.97, steps/ep=12.\n[200][ 18237], R/ep= 0.96, steps/ep=15.\n[210][ 18359], R/ep= 0.97, steps/ep=12.\n[220][ 18545], R/ep= 0.95, steps/ep=19.\n[230][ 18918], R/ep= 0.90, steps/ep=37.\n[240][ 19073], R/ep= 0.96, steps/ep=16.\n[250][ 19198], R/ep= 0.97, steps/ep=12.\n[260][ 19730], R/ep= 0.84, steps/ep=53.\n[270][ 20035], R/ep= 0.92, steps/ep=30.\n[280][ 20207], R/ep= 0.95, steps/ep=17.\n[290][ 20384], R/ep= 0.95, steps/ep=18.\n[300][ 20810], R/ep= 0.88, steps/ep=43.\n[310][ 20937], R/ep= 0.96, steps/ep=13.\n[320][ 21065], R/ep= 0.96, steps/ep=13.\n[330][ 21191], R/ep= 0.96, steps/ep=13.\n[340][ 21315], R/ep= 0.97, steps/ep=12.\n[350][ 21440], R/ep= 0.97, steps/ep=12.\n[360][ 21585], R/ep= 0.96, steps/ep=14.\n[370][ 21701], R/ep= 0.97, steps/ep=12.\n[380][ 21826], R/ep= 0.97, steps/ep=12.\n[390][ 21951], R/ep= 0.97, steps/ep=12.\n[400][ 22070], R/ep= 0.97, steps/ep=12.\n[410][ 22198], R/ep= 0.96, steps/ep=13.\n[420][ 22363], R/ep= 0.95, steps/ep=16.\n[430][ 22765], R/ep= 0.89, steps/ep=40.\n[440][ 23552], R/ep= 0.77, steps/ep=79.\n[450][ 23689], R/ep= 0.96, steps/ep=14.\n[460][ 23818], R/ep= 0.96, steps/ep=13.\n[470][ 23937], R/ep= 0.97, steps/ep=12.\n[480][ 24058], R/ep= 0.97, steps/ep=12.\n[490][ 24183], R/ep= 0.97, steps/ep=12.\n[500][ 24330], R/ep= 0.96, steps/ep=15.\n[510][ 24459], R/ep= 0.96, steps/ep=13.\n[520][ 24587], R/ep= 0.96, steps/ep=13.\n[530][ 24708], R/ep= 0.97, steps/ep=12.\n[540][ 25000], R/ep= 0.92, steps/ep=29.\n[550][ 25131], R/ep= 0.96, steps/ep=13.\n[560][ 25590], R/ep= 0.86, steps/ep=46.\n[570][ 25710], R/ep= 0.97, steps/ep=12.\n[580][ 25843], R/ep= 0.96, steps/ep=13.\n[590][ 25972], R/ep= 0.96, steps/ep=13.\n[600][ 26101], R/ep= 0.96, steps/ep=13.\n[610][ 26228], R/ep= 0.96, steps/ep=13.\n[620][ 26353], R/ep= 0.97, steps/ep=12.\n[630][ 26787], R/ep= 0.87, steps/ep=43.\n[640][ 26909], R/ep= 0.97, steps/ep=12.\n[650][ 27346], R/ep= 0.87, steps/ep=44.\n[660][ 27782], R/ep= 0.87, steps/ep=44.\n[670][ 27932], R/ep= 0.96, steps/ep=15.\n[680][ 28056], R/ep= 0.97, steps/ep=12.\n[690][ 28195], R/ep= 0.96, steps/ep=14.\n[700][ 28597], R/ep= 0.89, steps/ep=40.\n[710][ 29096], R/ep= 0.85, steps/ep=50.\n[720][ 29542], R/ep= 0.87, steps/ep=45.\n[730][ 29671], R/ep= 0.96, steps/ep=13.\n[740][ 29798], R/ep= 0.96, steps/ep=13.\n[750][ 29923], R/ep= 0.97, steps/ep=12.\n[760][ 30072], R/ep= 0.96, steps/ep=15.\n[770][ 30516], R/ep= 0.87, steps/ep=44.\n[780][ 30661], R/ep= 0.96, steps/ep=14.\n[790][ 30854], R/ep= 0.95, steps/ep=19.\n[800][ 31335], R/ep= 0.86, steps/ep=48.\n[810][ 31895], R/ep= 0.54, steps/ep=56.\n[820][ 32037], R/ep= 0.96, steps/ep=14.\n[830][ 32519], R/ep= 0.86, steps/ep=48.\n[840][ 32933], R/ep= 0.89, steps/ep=41.\n[850][ 33063], R/ep= 0.96, steps/ep=13.\n[860][ 33375], R/ep= 0.91, steps/ep=31.\n[870][ 33545], R/ep= 0.95, steps/ep=17.\n[880][ 33987], R/ep= 0.87, steps/ep=44.\n[890][ 34137], R/ep= 0.96, steps/ep=15.\n[900][ 34308], R/ep= 0.95, steps/ep=17.\n[910][ 34919], R/ep= 0.82, steps/ep=61.\n[920][ 35047], R/ep= 0.96, steps/ep=13.\n[930][ 35477], R/ep= 0.87, steps/ep=43.\n[940][ 35944], R/ep= 0.86, steps/ep=47.\n[950][ 36515], R/ep= 0.83, steps/ep=57.\n[960][ 36671], R/ep= 0.96, steps/ep=16.\n[970][ 36973], R/ep= 0.92, steps/ep=30.\n[980][ 37155], R/ep= 0.12, steps/ep=18.\n[990][ 37930], R/ep= 0.77, steps/ep=78.\n[1000][ 38772], R/ep= 0.76, steps/ep=84.\n[1010][ 40242], R/ep= 0.63, steps/ep=147.\n[1020][ 42131], R/ep= 0.06, steps/ep=189.\n[1030][ 42337], R/ep= 1.11, steps/ep=21.\n[1040][ 42663], R/ep= 0.91, steps/ep=33.\n[1050][ 42788], R/ep= 0.97, steps/ep=12.\n[1060][ 42963], R/ep= 0.95, steps/ep=18.\n[1070][ 43186], R/ep= 1.15, steps/ep=22.\n[1080][ 43370], R/ep= 0.95, steps/ep=18.\n[1090][ 43633], R/ep= 0.93, steps/ep=26.\n[1100][ 44159], R/ep= 0.85, steps/ep=53.\n[1110][ 44308], R/ep= 0.96, steps/ep=15.\n[1120][ 44527], R/ep= 0.94, steps/ep=22.\n[1130][ 44674], R/ep= 0.96, steps/ep=15.\n[1140][ 44940], R/ep= 0.93, steps/ep=27.\n[1150][ 45067], R/ep= 0.96, steps/ep=13.\n[1160][ 45277], R/ep= 0.94, steps/ep=21.\n[1170][ 45704], R/ep= 0.88, steps/ep=43.\n[1180][ 45832], R/ep= 0.96, steps/ep=13.\n[1190][ 45963], R/ep= 0.96, steps/ep=13.\n[1200][ 46102], R/ep= 0.96, steps/ep=14.\n[1210][ 46266], R/ep= 0.95, steps/ep=16.\n[1220][ 46410], R/ep= 0.96, steps/ep=14.\n[1230][ 46754], R/ep= 0.90, steps/ep=34.\n[1240][ 47034], R/ep= 0.92, steps/ep=28.\n[1250][ 47182], R/ep= 0.96, steps/ep=15.\n[1260][ 47301], R/ep= 0.97, steps/ep=12.\n[1270][ 47472], R/ep= 0.95, steps/ep=17.\n[1280][ 47590], R/ep= 0.97, steps/ep=12.\n[1290][ 47713], R/ep= 0.97, steps/ep=12.\n[1300][ 47841], R/ep= 0.96, steps/ep=13.\n[1310][ 47971], R/ep= 0.96, steps/ep=13.\n[1320][ 48096], R/ep= 0.97, steps/ep=12.\n[1330][ 48741], R/ep= 0.98, steps/ep=64.\n[1340][ 48856], R/ep= 0.98, steps/ep=12.\n[1350][ 48993], R/ep= 1.05, steps/ep=14.\n[1360][ 49108], R/ep= 0.97, steps/ep=12.\n[1370][ 49231], R/ep= 0.97, steps/ep=12.\n[1380][ 49428], R/ep= 0.95, steps/ep=20.\n[1390][ 49643], R/ep= 0.94, steps/ep=22.\n[1400][ 49793], R/ep= 0.96, steps/ep=15.\n[1410][ 49923], R/ep= 0.96, steps/ep=13.\n[1415][ 49999], R/ep= 0.86, steps/ep=14.\n"
],
[
"plot_stats(stats, hue=\"agent\")",
"_____no_output_____"
]
],
[
[
"## 7. DQN vs DoubleDQN: Maze Environment",
"_____no_output_____"
]
],
[
[
"show_representations(envs.maze)",
"Action-space: 7\nRGB: (56, 56, 3)\nSYM: (7, 7, 3)\n"
],
[
"env_name = envs.maze\nstep_num = 50_000 # change the experiment length\nseeds = [2, 5] # add more maps\nK = 2\nstats = defaultdict(list)\n\ncommon_seed = np.random.randint(1000)\nfor Agent in [DQN, DoubleDQN]:\n # maybe 621? :))\n reset_rng(common_seed) # we want each experiment to have the same starting conditions\n\n env = gym.make(env_name)\n env = TorchWrapper(FrameStack(ImgObsWrapper(ReseedWrapper(env, seeds=seeds)), k=K))\n net = get_estimator(env.action_space.n, input_ch=K*3, lin_size=64)\n \n agent_name = Agent.__name__\n print(f\"\\n{agent_name} started training.\")\n stats_ = train(\n Agent(\n net,\n ReplayMemory(size=10_000, batch_size=32),\n O.Adam(net.parameters(), lr=1e-3, eps=1e-4),\n get_epsilon_schedule(start=1.0, end=0.1, steps=10_000),\n env.action_space.n,\n warmup_steps=1000,\n update_steps=2,\n update_target_steps=256\n ),\n env,\n step_num=step_num\n )\n\n for k, v in stats_.items():\n stats[k] += v",
"Setting all rngs to seed=526\n\nDQN started training.\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 3563], R/ep= 0.00, steps/ep=324.\n[ 20][ 6668], R/ep= 0.05, steps/ep=310.\n[ 30][ 9758], R/ep= 0.05, steps/ep=309.\n[ 40][ 12998], R/ep= 0.00, steps/ep=324.\n[ 50][ 16222], R/ep= 0.01, steps/ep=322.\n[ 60][ 19196], R/ep= 0.10, steps/ep=297.\n[ 70][ 22362], R/ep= 0.03, steps/ep=317.\n[ 80][ 25238], R/ep= 0.13, steps/ep=288.\n[ 90][ 28403], R/ep= 0.04, steps/ep=316.\n[100][ 31643], R/ep= 0.00, steps/ep=324.\n[110][ 34796], R/ep= 0.03, steps/ep=315.\n[120][ 37419], R/ep= 0.20, steps/ep=262.\n[130][ 39680], R/ep= 0.34, steps/ep=226.\n[140][ 40807], R/ep= 0.69, steps/ep=113.\n[150][ 42796], R/ep= 0.41, steps/ep=199.\n[160][ 46036], R/ep= 0.00, steps/ep=324.\n[170][ 48264], R/ep= 0.36, steps/ep=223.\n[179][ 49999], R/ep= 0.36, steps/ep=182.\nSetting all rngs to seed=526\n\nDoubleDQN started training.\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 3501], R/ep= 0.04, steps/ep=318.\n[ 20][ 6741], R/ep= 0.00, steps/ep=324.\n[ 30][ 9848], R/ep= 0.06, steps/ep=311.\n[ 40][ 12693], R/ep= 0.13, steps/ep=284.\n[ 50][ 15784], R/ep= 0.05, steps/ep=309.\n[ 60][ 19024], R/ep= 0.00, steps/ep=324.\n[ 70][ 22264], R/ep= 0.00, steps/ep=324.\n[ 80][ 25504], R/ep= 0.00, steps/ep=324.\n[ 90][ 28744], R/ep= 0.00, steps/ep=324.\n[100][ 31984], R/ep= 0.00, steps/ep=324.\n[110][ 35162], R/ep= 0.03, steps/ep=318.\n[120][ 38402], R/ep= 0.00, steps/ep=324.\n[130][ 41642], R/ep= 0.00, steps/ep=324.\n[140][ 44882], R/ep= 0.00, steps/ep=324.\n[150][ 48122], R/ep= 0.00, steps/ep=324.\n[157][ 49999], R/ep= 0.08, steps/ep=285.\n"
],
[
"plot_stats(stats, hue=\"agent\")",
"_____no_output_____"
]
],
[
[
"## 8. Dueling DQN\n\n### BONUS TASK: Implement Dueling DQN and compare it on any env you want with the other two methods.\n\nExtra-credits for showing statistically-relevant graphs, unlike I did in\nthis lab.",
"_____no_output_____"
]
],
[
[
"# Dueling DQN can be implemented fairly easy by defining a new \n# nn.Module instead of the one returned by `get_estimator()`.\n# It can **probably** be used with both DQN and DoubleDQN as they are.\n\n\nclass DuelingNet(nn.Module):\n def __init__(self, num_inputs, num_outputs):\n super(DuelingNet, self).__init__()\n # define convolutional feature extractor\n # advantage layers\n # value layers \n self.num_inputs = num_inputs\n self.num_outputs = num_outputs\n \n self.conv = nn.Sequential(\n ByteToFloat(),\n nn.Conv2d(self.num_inputs, 16, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.Conv2d(16, 16, kernel_size=2),\n nn.ReLU(inplace=True),\n nn.Conv2d(16, 16, kernel_size=2),\n nn.ReLU(inplace=True)\n )\n\n self.value_stream = nn.Sequential(\n nn.Linear(9 * 16, 32),\n nn.ReLU(inplace=True),\n nn.Linear(32, 1)\n )\n\n self.advantage_stream = nn.Sequential(\n nn.Linear(9 * 16, 32),\n nn.ReLU(inplace=True),\n nn.Linear(32, self.num_outputs)\n )\n \n def forward(self, x):\n \n features = self.conv(x)\n features = features.view(features.size(0), -1)\n value_estimate = self.value_stream(features)\n advantage_estimate = self.advantage_stream(features)\n qvals = values + (advantages - advantages.mean())\n \n return qvals\n \n\n\nclass DuelingDQN(DoubleDQN):\n def __init__(\n self,\n estimator,\n buffer,\n optimizer,\n epsilon_schedule,\n action_num,\n gamma=0.92,\n update_steps=4,\n update_target_steps=10,\n warmup_steps=100,\n ):\n super(DuelingDQN, self).__init__(\n estimator,\n buffer,\n optimizer,\n epsilon_schedule,\n action_num,\n gamma,\n update_steps,\n update_target_steps,\n warmup_steps\n )",
"_____no_output_____"
],
[
"env = gym.make(envs.easy)\nenv = TorchWrapper(ImgObsWrapper(env))\nnet = get_estimator(env.action_space.n)\n\nstats = train(\n DuelingDQN(\n net,\n ReplayMemory(size=1000, batch_size=32),\n O.Adam(net.parameters(), lr=1e-3, eps=1e-4),\n get_epsilon_schedule(start=1.0, end=0.1, steps=4000),\n env.action_space.n,\n warmup_steps=100,\n update_steps=2,\n update_target_steps=16\n ),\n env,\n step_num=7_000 # change the experiment length if it's learning but not reaching about .95\n)",
"[ 0][ 49], R/ep= 0.55, steps/ep=50.\n[ 10][ 742], R/ep= 0.33, steps/ep=69.\n[ 20][ 1528], R/ep= 0.23, steps/ep=79.\n[ 30][ 2054], R/ep= 0.53, steps/ep=53.\n[ 40][ 2459], R/ep= 0.64, steps/ep=40.\n[ 50][ 2615], R/ep= 0.86, steps/ep=16.\n[ 60][ 2708], R/ep= 0.92, steps/ep= 9.\n[ 70][ 2796], R/ep= 0.92, steps/ep= 9.\n[ 80][ 2896], R/ep= 0.91, steps/ep=10.\n[ 90][ 2992], R/ep= 0.91, steps/ep=10.\n[100][ 3080], R/ep= 0.92, steps/ep= 9.\n[110][ 3162], R/ep= 0.93, steps/ep= 8.\n[120][ 3233], R/ep= 0.94, steps/ep= 7.\n[130][ 3297], R/ep= 0.94, steps/ep= 6.\n[140][ 3367], R/ep= 0.94, steps/ep= 7.\n[150][ 3448], R/ep= 0.93, steps/ep= 8.\n[160][ 3517], R/ep= 0.94, steps/ep= 7.\n[170][ 3588], R/ep= 0.94, steps/ep= 7.\n[180][ 3664], R/ep= 0.93, steps/ep= 8.\n[190][ 3720], R/ep= 0.95, steps/ep= 6.\n[200][ 3791], R/ep= 0.94, steps/ep= 7.\n[210][ 3854], R/ep= 0.94, steps/ep= 6.\n[220][ 3913], R/ep= 0.95, steps/ep= 6.\n[230][ 3972], R/ep= 0.95, steps/ep= 6.\n[240][ 4030], R/ep= 0.95, steps/ep= 6.\n[250][ 4091], R/ep= 0.95, steps/ep= 6.\n[260][ 4148], R/ep= 0.95, steps/ep= 6.\n[270][ 4204], R/ep= 0.95, steps/ep= 6.\n[280][ 4261], R/ep= 0.95, steps/ep= 6.\n[290][ 4316], R/ep= 0.95, steps/ep= 6.\n[300][ 4372], R/ep= 0.95, steps/ep= 6.\n[310][ 4425], R/ep= 0.95, steps/ep= 5.\n[320][ 4488], R/ep= 0.94, steps/ep= 6.\n[330][ 4549], R/ep= 0.95, steps/ep= 6.\n[340][ 4601], R/ep= 0.95, steps/ep= 5.\n[350][ 4653], R/ep= 0.95, steps/ep= 5.\n[360][ 4715], R/ep= 0.94, steps/ep= 6.\n[370][ 4773], R/ep= 0.95, steps/ep= 6.\n[380][ 4831], R/ep= 0.95, steps/ep= 6.\n[390][ 4886], R/ep= 0.95, steps/ep= 6.\n[400][ 4940], R/ep= 0.95, steps/ep= 5.\n[410][ 4994], R/ep= 0.95, steps/ep= 5.\n[420][ 5052], R/ep= 0.95, steps/ep= 6.\n[430][ 5114], R/ep= 0.94, steps/ep= 6.\n[440][ 5166], R/ep= 0.95, steps/ep= 5.\n[450][ 5224], R/ep= 0.95, steps/ep= 6.\n[460][ 5280], R/ep= 0.95, steps/ep= 6.\n[470][ 5343], R/ep= 0.94, steps/ep= 6.\n[480][ 5400], R/ep= 0.95, steps/ep= 6.\n[490][ 5453], R/ep= 0.95, steps/ep= 5.\n[500][ 5512], R/ep= 0.95, steps/ep= 6.\n[510][ 5566], R/ep= 0.95, steps/ep= 5.\n[520][ 5621], R/ep= 0.95, steps/ep= 6.\n[530][ 5679], R/ep= 0.95, steps/ep= 6.\n[540][ 5733], R/ep= 0.95, steps/ep= 5.\n[550][ 5788], R/ep= 0.95, steps/ep= 6.\n[560][ 5849], R/ep= 0.95, steps/ep= 6.\n[570][ 5903], R/ep= 0.95, steps/ep= 5.\n[580][ 5960], R/ep= 0.95, steps/ep= 6.\n[590][ 6017], R/ep= 0.95, steps/ep= 6.\n[600][ 6071], R/ep= 0.95, steps/ep= 5.\n[610][ 6128], R/ep= 0.95, steps/ep= 6.\n[620][ 6180], R/ep= 0.95, steps/ep= 5.\n[630][ 6240], R/ep= 0.95, steps/ep= 6.\n[640][ 6306], R/ep= 0.94, steps/ep= 7.\n[650][ 6364], R/ep= 0.95, steps/ep= 6.\n[660][ 6420], R/ep= 0.95, steps/ep= 6.\n[670][ 6474], R/ep= 0.95, steps/ep= 5.\n[680][ 6532], R/ep= 0.95, steps/ep= 6.\n[690][ 6588], R/ep= 0.95, steps/ep= 6.\n[700][ 6639], R/ep= 0.95, steps/ep= 5.\n[710][ 6695], R/ep= 0.95, steps/ep= 6.\n[720][ 6749], R/ep= 0.95, steps/ep= 5.\n[730][ 6803], R/ep= 0.95, steps/ep= 5.\n[740][ 6854], R/ep= 0.95, steps/ep= 5.\n[750][ 6905], R/ep= 0.95, steps/ep= 5.\n[760][ 6962], R/ep= 0.95, steps/ep= 6.\n[767][ 6999], R/ep= 0.85, steps/ep= 6.\n"
],
[
"plot_stats(stats)",
"_____no_output_____"
],
[
"env_name = envs.maze\nstep_num = 50_000 # change the experiment length\nseeds = [2, 5] # add more maps\nK = 2\nstats = defaultdict(list)\n\ncommon_seed = np.random.randint(1000)\nfor Agent in [DQN, DoubleDQN, DuelingDQN]:\n # maybe 621? :))\n reset_rng(526) # we want each experiment to have the same starting conditions\n\n env = gym.make(env_name)\n env = TorchWrapper(FrameStack(ImgObsWrapper(ReseedWrapper(env, seeds=seeds)), k=K))\n net = get_estimator(env.action_space.n, input_ch=K*3, lin_size=64)\n \n agent_name = Agent.__name__\n print(f\"\\n{agent_name} started training.\")\n stats_ = train(\n Agent(\n net,\n ReplayMemory(size=10_000, batch_size=32),\n O.Adam(net.parameters(), lr=1e-3, eps=1e-4),\n get_epsilon_schedule(start=1.0, end=0.1, steps=10_000),\n env.action_space.n,\n warmup_steps=1000,\n update_steps=2,\n update_target_steps=256\n ),\n env,\n step_num=step_num\n )\n\n for k, v in stats_.items():\n stats[k] += v",
"Setting all rngs to seed=526\n\nDQN started training.\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 3563], R/ep= 0.00, steps/ep=324.\n[ 20][ 6668], R/ep= 0.05, steps/ep=310.\n[ 30][ 9908], R/ep= 0.00, steps/ep=324.\n[ 40][ 13148], R/ep= 0.00, steps/ep=324.\n[ 50][ 15863], R/ep= 0.17, steps/ep=272.\n[ 60][ 18829], R/ep= 0.10, steps/ep=297.\n[ 70][ 22006], R/ep= 0.03, steps/ep=318.\n[ 80][ 25246], R/ep= 0.00, steps/ep=324.\n[ 90][ 28486], R/ep= 0.00, steps/ep=324.\n[100][ 31726], R/ep= 0.00, steps/ep=324.\n[110][ 34966], R/ep= 0.00, steps/ep=324.\n[120][ 38206], R/ep= 0.00, steps/ep=324.\n[130][ 41446], R/ep= 0.00, steps/ep=324.\n[140][ 44686], R/ep= 0.00, steps/ep=324.\n[150][ 47926], R/ep= 0.00, steps/ep=324.\n[157][ 49999], R/ep= 0.00, steps/ep=304.\nSetting all rngs to seed=526\n\nDoubleDQN started training.\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 3501], R/ep= 0.04, steps/ep=318.\n[ 20][ 6741], R/ep= 0.00, steps/ep=324.\n[ 30][ 9735], R/ep= 0.09, steps/ep=299.\n[ 40][ 12505], R/ep= 0.16, steps/ep=277.\n[ 50][ 15745], R/ep= 0.00, steps/ep=324.\n[ 60][ 18985], R/ep= 0.00, steps/ep=324.\n[ 70][ 22225], R/ep= 0.00, steps/ep=324.\n[ 80][ 25465], R/ep= 0.00, steps/ep=324.\n[ 90][ 28705], R/ep= 0.00, steps/ep=324.\n[100][ 31945], R/ep= 0.00, steps/ep=324.\n[110][ 35185], R/ep= 0.00, steps/ep=324.\n[120][ 38425], R/ep= 0.00, steps/ep=324.\n[130][ 41665], R/ep= 0.00, steps/ep=324.\n[140][ 44905], R/ep= 0.00, steps/ep=324.\n[150][ 48145], R/ep= 0.00, steps/ep=324.\n[156][ 49999], R/ep= 0.00, steps/ep=315.\nSetting all rngs to seed=526\n\nDuelingDQN started training.\n[ 0][ 323], R/ep= 0.00, steps/ep=324.\n[ 10][ 3501], R/ep= 0.04, steps/ep=318.\n[ 20][ 6741], R/ep= 0.00, steps/ep=324.\n[ 30][ 9735], R/ep= 0.09, steps/ep=299.\n[ 40][ 12975], R/ep= 0.00, steps/ep=324.\n[ 50][ 16192], R/ep= 0.02, steps/ep=322.\n[ 60][ 19226], R/ep= 0.08, steps/ep=303.\n[ 70][ 22466], R/ep= 0.00, steps/ep=324.\n[ 80][ 25706], R/ep= 0.00, steps/ep=324.\n[ 90][ 28946], R/ep= 0.00, steps/ep=324.\n[100][ 32186], R/ep= 0.00, steps/ep=324.\n[110][ 35426], R/ep= 0.00, steps/ep=324.\n[120][ 38666], R/ep= 0.00, steps/ep=324.\n[130][ 41906], R/ep= 0.00, steps/ep=324.\n[140][ 45146], R/ep= 0.00, steps/ep=324.\n[150][ 48386], R/ep= 0.00, steps/ep=324.\n[155][ 49999], R/ep= 0.00, steps/ep=323.\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",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
ece4f32c7f35a4cbbe473711f16d0700dcecc6a5 | 137,923 | ipynb | Jupyter Notebook | notebooks/i_introduction.ipynb | marketpsych/sftp | dbff90233b01bdf06fe8f9d09f0ac86292f5cb6a | [
"MIT"
] | 2 | 2021-07-08T03:12:09.000Z | 2021-09-27T08:31:20.000Z | notebooks/i_introduction.ipynb | marketpsych/sftp | dbff90233b01bdf06fe8f9d09f0ac86292f5cb6a | [
"MIT"
] | null | null | null | notebooks/i_introduction.ipynb | marketpsych/sftp | dbff90233b01bdf06fe8f9d09f0ac86292f5cb6a | [
"MIT"
] | 3 | 2021-09-12T21:08:31.000Z | 2022-01-11T16:21:38.000Z | 44.107131 | 35,247 | 0.645853 | [
[
[
"<a href=\"https://colab.research.google.com/github/marketpsych/marketpsych/blob/main/notebooks/i_introduction.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Visualising and Downloading CSV files directly from SFTP\n\nThis notebook shows how to load MarketPsych's data with your SFTP credentials directly into a Jupyter Notebook. Please note, this notebook is intended for simple analyses, visualizations and small downloads. For larger testing requirements, you need to use the flat files, as instructed by the MRNSupport. \n \nTo open this notebook please click the blue \"Open in Colab\" button above, if you have Anaconda installed you can download and run the notebook there.\n\n---\n## 1. Settings\nThis notebook uses some widgets (to facilitate with your navigation) and MarketPsych's library. To install the libraries and enable widgets, please run the following cell. \n\n\n<font color='blue'>**HOW TO**</font> \n<font color='blue'>1. Run the following cell, you can run cells by pressing <kbd>Control</kbd>+<kbd>Shift</kbd> (<kbd>Command</kbd>+<kbd>Shift</kbd> on Mac) at the same time.</font> ",
"_____no_output_____"
]
],
[
[
"import sys\n# Installs marketpsych library into your environment\n!{sys.executable} -m pip install marketpsych ipywidgets --upgrade --quiet\n# Allows using the widgets\n!{sys.executable} -m jupyter nbextension enable --py widgetsnbextension\n\n## Libraries\nfrom marketpsych import sftp, mpwidgets\nfrom IPython.core.magic import register_cell_magic\nfrom IPython.display import HTML, display\nimport pandas as pd",
"Enabling notebook extension jupyter-js-widgets/extension...\r\n - Validating: \u001b[32mOK\u001b[0m\r\n"
]
],
[
[
"---\n## 2. Selecting your login credentials\n\nPlease input your credentials, i.e., the path to the .ppk as provided by the MRNSupport. \n \n<font color='blue'>**HOW TO**</font> \n<font color='blue'>1. Run the following cell.</font> \n<font color='blue'>2. Click on `Key File`.</font> \n<font color='blue'>3. Select your .ppk key [it must have be in a 1234567.ppk format].</font> ",
"_____no_output_____"
]
],
[
[
"cwdgts = mpwidgets.LoginWidgets()\ncwdgts.display()",
"_____no_output_____"
]
],
[
[
"---\n\n<a id='the_destination'></a>\n## 3. Loading the data\n\nNow you can download the files directly into a pandas dataframe. The options can be defined through the 5 widgets below. A description of each option is given in the following:\n\n - **Trial**: Select the checkbox if you are trialing the data. In some special cases, even if you are trialing, you may need to uncheck it (you can try both options in case of Permission errors).\n\n - **Asset class**: \n \n|Asset class | Description|\n|:-------------|:------------|\n|`CMPNY` | Individual companies|\n|`CMPNY_AMER` | Individual companies domiciled in America|\n|`CMPNY_APAC` | Individual companies domiciled in APAC|\n|`CMPNY_EMEA` | Individual companies domiciled in EMEA|\n|`CMPNY_ESG` | Individual companies (ESG package)|\n|`CMPNY_GRP` | Company groups and ETFs|\n|`COM_AGR` | Agricultural commodities| \n|`COM_ENM` | Energy and Metals|\n|`COU` | Countries|\n|`COU_ESG` | Countries (ESG package)|\n|`COU_MKT` | Stock indices, sovereign bonds, real estate|\n|`CRYPTO` | Cryptocurrencies|\n|`CUR` | Currencies| \n\n - **Frequencies**: \n \n|Frequency | Description| Use case |\n|:----------|:-----------|:---------|\n|`W365_UDAI`| Yearly lookback window and daily updates| ESG Core only |\n|`WDAI_UDAI`| Daily lookback window and daily updates| Daily data stamped at 15:30 ET|\n|`WDAI_UHOU`| Daily lookback window and hourly updates| Daily data stamped hourly (in case you want daily data adjusted to your time-zone) |\n|`W01M_U01M`| Minutely lookback window and minutely updates| Low-latency data (**WARNING:** extremely large datasets)|\n\n- **Start Date**: Select the start of the period for which you would like to download the data.\n- **End Date**: Select the end of the period for which you would like to download the data.\n\n- **Data Type**: \n\n|Frequency | Description|\n|:----------|:-----------|\n|`News`| For news sources only (headlines and corpus)|\n|`News_Headline`| For the headlines of news sources only| \n|`Social`| For social media sources| \n|`News_Social`| For the combined content|\n \n- **Assets**: Asset codes as provided in the user guide. For companies, use the PermID. This is useful when you only want to use data for one or a few assets.\n\n**WARNING** \n- I. Loading large files such as CMPNY data with a long window-frame can take quite a while and take all the available memory. Start by loading short periods (e.g., one month of data). Alternatively, you can select a subset of assets, as above.\n\n- II. Check your asset class permissions. If you try downloading data for which no access was provided, it will give a Permission error:\n```python\n\"PermissionError\": [Errno 13] Access denied\n``` ",
"_____no_output_____"
],
[
"<font color='blue'>**HOW TO**</font> \n<font color='blue'>1. Run the cell below (after running it, you should see several widgets).</font> \n<font color='blue'>2. Make your selections according to the explanations above.</font> \n<font color='blue'>3. Click on the `Load Selection` button.</font> ",
"_____no_output_____"
]
],
[
[
"lwdgts = mpwidgets.LoaderWidgets(cwdgts.client)\nlwdgts.display()",
"_____no_output_____"
]
],
[
[
"If you can see a dataframe above, congratulations! You have loaded some data into your notebook. From here, you can have fun exploring it. Below, you'll find a plotting tool for some simple understanding of the data.\n\n---\n## 4. Visualizing the data\n\nBelow you can use the widgets to do some basic exploration. A description of the widgets is given below.\n\n- **Data Type**: It is selected above, if you selected only one source but would like to visualise a different source please select it in <a href='#the_destination'>Loading the data</a> and then refer back to here\n\n- **Anaytics**: This is the specific MarketPsych score you wish to plot, the actual values you see will be dependent on the asset class selected. There are a large range of indicators provided some example categories are:\n - Emotional indicators such as Anger, Fear and Joy\n - 'Economic' metrics including Earnings Forecast, Interest Rate Forecast, Long vs. Short \n - ESG measures including CarbonEmissionsControversy, ManagementTrust, and WorkplaceSafety\n\n- **Asset**: The asset of choice. To see all options, clear the cell. For a description of each asset, please search for the asset code in the User Guide or Eikon app.\n\n- **Roll. window**: The length in the smoothing function (a simple moving average).\n\n- **Min. period**: Minimum number of observations in window required to have a value (otherwise result is NA).\n\n**WARNING** \nIf your plot is empty, it is likely that there is no data for that combination of variables.\n\n<font color='blue'>**HOW TO**</font> \n<font color='blue'>1. Run the cell below (after running it, you should see several widgets).</font> \n<font color='blue'>2. Make your selections according to the explanations above.</font> ",
"_____no_output_____"
]
],
[
[
"swdgts = mpwidgets.SlicerWidgets(lwdgts.df)\nswdgts.display()",
"_____no_output_____"
]
],
[
[
"---\n## 5. Downloading the data\n\nIf you are using Colab, you can also download your selected dataframe:\n\n<font color='blue'>**HOW TO**</font> \n<font color='blue'>1. Run the cell below (after running it, you should see several widgets).</font> \n<font color='blue'>2. Change the file name and file extensions (.csv or .xlsx).</font> \n<font color='blue'>3. Click on `Download`.</font> ",
"_____no_output_____"
]
],
[
[
"dwdgts = mpwidgets.DownloaderWidgets(lwdgts.df)\ndwdgts.display()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece4f40260570ff8f8fc8c61e07b1009cbbb36b3 | 79,908 | ipynb | Jupyter Notebook | Lab12/crvargasmAlgorithmicToolboxWeek5InterpolationApproximationModelingData.ipynb | crvargasm/MetNumUN2021I | e8b56337482c51eb0ca397ebd173360979e9013c | [
"MIT"
] | 1 | 2021-07-27T05:34:50.000Z | 2021-07-27T05:34:50.000Z | Lab12/crvargasmAlgorithmicToolboxWeek5InterpolationApproximationModelingData.ipynb | crvargasm/MetNumUN2021I | e8b56337482c51eb0ca397ebd173360979e9013c | [
"MIT"
] | null | null | null | Lab12/crvargasmAlgorithmicToolboxWeek5InterpolationApproximationModelingData.ipynb | crvargasm/MetNumUN2021I | e8b56337482c51eb0ca397ebd173360979e9013c | [
"MIT"
] | null | null | null | 165.099174 | 28,950 | 0.879174 | [
[
[
"#QR Decomposition \n*by: Cristian Camilo Vargas Morales*",
"_____no_output_____"
],
[
"This Course is part of ***Introduction to numerical analysis*** by HSE University **[[Coursera](https://www.coursera.org/learn/intro-to-numerical-analysis)]**",
"_____no_output_____"
],
[
"# I. Linear least squares approximation",
"_____no_output_____"
],
[
"Consider a function $y = f(x)$ which is defined by a set of values $y_0, y_1, \\cdots, y_n$ at points $x_0, x_1, \\cdots, x_n$.",
"_____no_output_____"
]
],
[
[
"x = [-1, -0.7, -0.43, -0.14, -0.14, 0.43, 0.71, 1, 1.29, 1.57, 1.86, 2.14, 2.43, 2.71, 3]\ny = [-2.25, -0.77, 0.21, 0.44, 0.64, 0.03, -0.22, -0.84, -1.2, -1.03, -0.37, 0.61, 2.67, 5.04, 8.90]",
"_____no_output_____"
]
],
[
[
"### I.I. Find a best fit polynomial\n\n$$\nP_m(x) = a_0 + a_1 x + \\cdots + a_m x^m\n$$\n\nusing the linear least squares approach. To this end\n\n1. implement a function which constructs the design matrix using $1, x, \\cdots, x^m$ as the basis functions.\n\n2. construct explicitly the normal system of equations of the linear least squares problem at fixed $m$.\n\n3. Solve the normal equations to find the coefficients of $P_m(x)$ for $m = 0, 1, 2, \\dots$. For the linear algebra problem, you can either use library functions (`numpy.linalg.solve`) or your LU factorization code from week 1.\n\n(20% of the total grade)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom scipy import optimize\nimport matplotlib.pyplot as plt\n\nplt.style.use('seaborn-poster')",
"_____no_output_____"
],
[
"def design_matrix(x, m):\n x = np.array(x)\n A = []\n for k in range(m+1):\n A.append(x**k)\n \n return np.array(A).T",
"_____no_output_____"
],
[
"def normal_eq_solution(A,b):\n x = np.dot(np.linalg.inv(A.T @ A) @ A.T, b)\n res = np.linalg.norm(A @ x - b)\n return x, res",
"_____no_output_____"
],
[
"ms = range(1,10)\ncoef = [normal_eq_solution(design_matrix(x,m), y) for m in ms]",
"_____no_output_____"
]
],
[
[
"### I.II \n\nTo find the optimal value of m, use the following criterion: take $m=0, 1, 2, \\dots$, for each value of $m$ compute \n\n$$\n\\sigma_m^2 = \\frac{1}{n - m} \\sum_{k=0}^n \\left( P_m(x_k) - y_k \\right)^2\n$$\n\nAnd take the value of $m$, at which $\\sigma_m$ stabilizes or starts increasing.\n\n(20% of the total grade)",
"_____no_output_____"
]
],
[
[
"for a in coef:\n print(a[1]/(16 - len(a[0])))",
"0.5638018817879079\n0.43442508405930796\n0.032237270226312724\n0.033656564378641424\n0.035496562200205625\n0.03588688045729664\n0.03919349715902616\n0.04065424160744067\n0.04642385374986461\n"
]
],
[
[
"Plot your polynomials $P_m(x)$ on one plot, together with the datapoints. Visually compare best-fit polynomials of different degrees. Is the visual comparison consistent with the optimal value of $m$?",
"_____no_output_____"
]
],
[
[
"import numpy.polynomial.polynomial as pm\nimport matplotlib.pyplot as plt\nplt.scatter(x,y)\n\nfor pol in coef:\n pl = pm.polyval(x,pol[0])\n plt.plot(x,pl)\n\nplt.legend(list(ms))\nplt.show()",
"_____no_output_____"
]
],
[
[
"### I.III. Linear least-squares using the QR factorization.\n\nFor the optimal value of $m$ from the previous part, solve the LLS problem using the QR factorization, withou ever forming the normal equations explicitly. For linear algebra, you can use standard library functions (look up `numpy.linalg.solve`, `numpy.linalg.qr` etc) or your code from previous weeks.\n\nCompare the results with the results of solving the normal system of equations.\n\n(20% of the grade)",
"_____no_output_____"
]
],
[
[
"def qr_lls(A, b):\n m = A.shape[1]\n q, r = np.linalg.qr(A)\n f = (q.T @ b)[:m]\n return np.linalg.solve(r[:m], f)",
"_____no_output_____"
],
[
"c = qr_lls(design_matrix(x,3), y)\nprint(c-coef[2][0])",
"[-1.32116540e-14 -1.60982339e-15 4.44089210e-14 -1.48769885e-14]\n"
]
],
[
[
"# II. Lagrange interpolation",
"_____no_output_____"
],
[
"### II.1 \n\nConsider the function, $f(x) = x^2 \\cos{x}$. On the interval $x\\in [\\pi/2, \\pi]$, interpolate the function using the Lagrange interpolating polynomial of degree $m$ with $m=1, 2, 3, 4, 5$. Use the uniform mesh. Plot the resulting interpolants together with $f(x)$.\n\n(20% of the total grade)",
"_____no_output_____"
]
],
[
[
"def lagr_poly(grid, k, x):\n \n poly = 1\n for i in range(len(grid)):\n if i!=k:\n poly*=x-grid[i]\n poly/=grid[k]-grid[i] \n \n return poly",
"_____no_output_____"
],
[
"def lagr_interp(grid, x, y):\n y_interp = np.zeros(len(x))\n for i in range(len(grid)):\n y_interp+=y[i]*lagr_poly(grid,i,x)\n return y_interp",
"_____no_output_____"
],
[
"f = lambda x:x**2*np.cos(x)\nx = np.linspace(np.pi/2,np.pi, 50)\nplt.plot(x,f(x), \"r+\")\n\nfor m in range(1,6):\n grid = np.linspace(np.pi/2,np.pi, m)\n plt.plot(x, lagr_interp(grid, x, f(grid)))",
"_____no_output_____"
]
],
[
[
"### II.2. \n\nRepeat the previous task using the Chebyshev nodes. Compare the quality of interpolation on a uniform mesh and Chebyshev nodes for $m=3$.\n\n(20% of the total grade)",
"_____no_output_____"
]
],
[
[
"def chebishev_nodes(a,b,m):\n k = np.array(range(m))\n x = np.cos(2*k+1/m)\n return (x+1)*(b-a)/2 + a",
"_____no_output_____"
],
[
"grid = chebishev_nodes(np.pi/2, np.pi, 3)\n\nplt.plot(x,f(x), \"r+\")\nplt.plot(x, lagr_interp(grid, x, f(grid)))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece4f443ebe206bcae758c54589590d80bfb326a | 2,246 | ipynb | Jupyter Notebook | examples/Untitled.ipynb | SnailJie/Prior-BO | e2eeb6dd556046f952c68f78780843ad30eaefb0 | [
"MIT"
] | null | null | null | examples/Untitled.ipynb | SnailJie/Prior-BO | e2eeb6dd556046f952c68f78780843ad30eaefb0 | [
"MIT"
] | null | null | null | examples/Untitled.ipynb | SnailJie/Prior-BO | e2eeb6dd556046f952c68f78780843ad30eaefb0 | [
"MIT"
] | null | null | null | 35.650794 | 899 | 0.60374 | [
[
[
"from bayes_opt import BayesianOptimization\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n%matplotlib inline",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
ece506cfe39dcd5c52e5969c60532ae1c5e46b5f | 1,811 | ipynb | Jupyter Notebook | 03 Deep Dive- Functions and OOPs/10_Method_Overriding_OOPs.ipynb | aadhikar/python-3-basics-and-beyond | 34d3612cde720d164f473bb7d38ce0280e289ad3 | [
"MIT"
] | 1 | 2020-11-11T02:11:32.000Z | 2020-11-11T02:11:32.000Z | 03 Deep Dive- Functions and OOPs/10_Method_Overriding_OOPs.ipynb | aadhikar/python-3-basics-and-beyond | 34d3612cde720d164f473bb7d38ce0280e289ad3 | [
"MIT"
] | null | null | null | 03 Deep Dive- Functions and OOPs/10_Method_Overriding_OOPs.ipynb | aadhikar/python-3-basics-and-beyond | 34d3612cde720d164f473bb7d38ce0280e289ad3 | [
"MIT"
] | 2 | 2020-01-31T04:42:44.000Z | 2020-01-31T05:17:18.000Z | 21.819277 | 158 | 0.50635 | [
[
[
"**Method overriding** is the way of overriding parent class method in sub class. This feature is helpful when different behavior in sub class is needed.",
"_____no_output_____"
]
],
[
[
"class Rectangle():\n def __init__(self, lenth, breadth):\n self.lenth = lenth\n self.breadth = breadth\n \n def getArea(self):\n return f'Area of th Rectangle is {self.lenth * self.breadth}'\n \nclass Square(Rectangle):\n def __init__(self, side):\n self.side = side\n \n def getArea(self):\n return f'Area of th Square is {self.side * self.side}'",
"_____no_output_____"
],
[
"a = Rectangle(2, 4)\nprint(a.getArea())\nd = Square(5)\nprint(d.getArea())",
"Area of th Rectangle is 8\nArea of th Square is 25\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
]
] |
ece514c2f557a9d2ae1898e22131dacedd0d535c | 32,501 | ipynb | Jupyter Notebook | notebooks/01-Python Basic.ipynb | suyash101998/python-training | 9d2ab6534284134c6e3b090496e7310506c3add9 | [
"Apache-2.0"
] | null | null | null | notebooks/01-Python Basic.ipynb | suyash101998/python-training | 9d2ab6534284134c6e3b090496e7310506c3add9 | [
"Apache-2.0"
] | null | null | null | notebooks/01-Python Basic.ipynb | suyash101998/python-training | 9d2ab6534284134c6e3b090496e7310506c3add9 | [
"Apache-2.0"
] | null | null | null | 15.854146 | 318 | 0.418695 | [
[
[
"* Data types\n * Numbers\n * Strings\n * Printing\n * Lists\n * Dictionaries\n * Booleans\n * Tuples \n * Sets\n* Comparison Operators\n* if, elif, else Statements\n* for Loops\n* while Loops\n* range()\n* list comprehension\n* functions\n* lambda expressions\n* map and filter\n* methods\n____",
"_____no_output_____"
],
[
"## Data types\n\n### Numbers",
"_____no_output_____"
]
],
[
[
"1 + 1",
"_____no_output_____"
],
[
"1 * 3",
"_____no_output_____"
],
[
"1 / 2",
"_____no_output_____"
],
[
"2 ** 4",
"_____no_output_____"
],
[
"4 % 2",
"_____no_output_____"
],
[
"5 % 2",
"_____no_output_____"
],
[
"(2 + 3) * (5 + 5)",
"_____no_output_____"
]
],
[
[
"### Variable Assignment",
"_____no_output_____"
]
],
[
[
"# Can not start with number or special characters\nname_of_var = 2",
"_____no_output_____"
],
[
"x = 2\ny = 3",
"_____no_output_____"
],
[
"z = x + y",
"_____no_output_____"
],
[
"z",
"_____no_output_____"
]
],
[
[
"### Strings",
"_____no_output_____"
]
],
[
[
"'single quotes'",
"_____no_output_____"
],
[
"\"double quotes\"",
"_____no_output_____"
],
[
"\" wrap lot's of other quotes\"",
"_____no_output_____"
]
],
[
[
"### Printing",
"_____no_output_____"
]
],
[
[
"x = 'hello'",
"_____no_output_____"
],
[
"x",
"_____no_output_____"
],
[
"print(x)",
"hello\n"
],
[
"num = 12\nname = 'Sam'",
"_____no_output_____"
],
[
"print('My number is: {one}, and my name is: {two}'.format(one=num,two=name))",
"My number is: 12, and my name is: Sam\n"
],
[
"print('My number is: {}, and my name is: {}'.format(num,name))",
"My number is: 12, and my name is: Sam\n"
]
],
[
[
"### Lists",
"_____no_output_____"
]
],
[
[
"[1,2,3]",
"_____no_output_____"
],
[
"['hi',1,[1,2]]",
"_____no_output_____"
],
[
"my_list = ['a','b','c']",
"_____no_output_____"
],
[
"my_list.append('d')",
"_____no_output_____"
],
[
"my_list",
"_____no_output_____"
],
[
"my_list[0]",
"_____no_output_____"
],
[
"my_list[1]",
"_____no_output_____"
],
[
"my_list[1:]",
"_____no_output_____"
],
[
"my_list[:1]",
"_____no_output_____"
],
[
"my_list[0] = 'NEW'",
"_____no_output_____"
],
[
"my_list",
"_____no_output_____"
],
[
"nest = [1,2,3,[4,5,['target']]]",
"_____no_output_____"
],
[
"nest[3]",
"_____no_output_____"
],
[
"nest[3][2]",
"_____no_output_____"
],
[
"nest[3][2][0]",
"_____no_output_____"
]
],
[
[
"### Dictionaries",
"_____no_output_____"
]
],
[
[
"d = {'key1':'item1','key2':'item2'}",
"_____no_output_____"
],
[
"d",
"_____no_output_____"
],
[
"d['key1']",
"_____no_output_____"
]
],
[
[
"### Booleans",
"_____no_output_____"
]
],
[
[
"True",
"_____no_output_____"
],
[
"False",
"_____no_output_____"
]
],
[
[
"### Tuples ",
"_____no_output_____"
]
],
[
[
"t = (1,2,3)",
"_____no_output_____"
],
[
"t[0]",
"_____no_output_____"
],
[
"t[0] = 'NEW'",
"_____no_output_____"
]
],
[
[
"### Sets",
"_____no_output_____"
]
],
[
[
"{1,2,3}",
"_____no_output_____"
],
[
"{1,2,3,1,2,1,2,3,3,3,3,2,2,2,1,1,2}",
"_____no_output_____"
]
],
[
[
"## Comparison Operators",
"_____no_output_____"
]
],
[
[
"1 > 2",
"_____no_output_____"
],
[
"1 < 2",
"_____no_output_____"
],
[
"1 >= 1",
"_____no_output_____"
],
[
"1 <= 4",
"_____no_output_____"
],
[
"1 == 1",
"_____no_output_____"
],
[
"'hi' == 'bye'",
"_____no_output_____"
]
],
[
[
"## Logic Operators",
"_____no_output_____"
]
],
[
[
"(1 > 2) and (2 < 3)",
"_____no_output_____"
],
[
"(1 > 2) or (2 < 3)",
"_____no_output_____"
],
[
"(1 == 2) or (2 == 3) or (4 == 4)",
"_____no_output_____"
]
],
[
[
"## if,elif, else Statements",
"_____no_output_____"
]
],
[
[
"if 1 < 2:\n print('Yep!')",
"Yep!\n"
],
[
"if 1 < 2:\n print('yep!')",
"yep!\n"
],
[
"if 1 < 2:\n print('first')\nelse:\n print('last')",
"first\n"
],
[
"if 1 > 2:\n print('first')\nelse:\n print('last')",
"last\n"
],
[
"if 1 == 2:\n print('first')\nelif 3 == 3:\n print('middle')\nelse:\n print('Last')",
"middle\n"
]
],
[
[
"## for Loops",
"_____no_output_____"
]
],
[
[
"seq = [1,2,3,4,5]",
"_____no_output_____"
],
[
"for item in seq:\n print(item)",
"1\n2\n3\n4\n5\n"
],
[
"for item in seq:\n print('Yep')",
"Yep\nYep\nYep\nYep\nYep\n"
],
[
"for jelly in seq:\n print(jelly+jelly)",
"2\n4\n6\n8\n10\n"
]
],
[
[
"## while Loops",
"_____no_output_____"
]
],
[
[
"i = 1\nwhile i < 5:\n print('i is: {}'.format(i))\n i = i+1",
"i is: 1\ni is: 2\ni is: 3\ni is: 4\n"
]
],
[
[
"## range()",
"_____no_output_____"
]
],
[
[
"range(5)",
"_____no_output_____"
],
[
"for i in range(5):\n print(i)",
"0\n1\n2\n3\n4\n"
],
[
"list(range(5))",
"_____no_output_____"
]
],
[
[
"## list comprehension",
"_____no_output_____"
]
],
[
[
"x = [1,2,3,4]",
"_____no_output_____"
],
[
"out = []\nfor item in x:\n out.append(item**2)\nprint(out)",
"[1, 4, 9, 16]\n"
],
[
"[item**2 for item in x]",
"_____no_output_____"
]
],
[
[
"## functions",
"_____no_output_____"
]
],
[
[
"def my_func(param1='default'):\n \"\"\"\n Docstring goes here.\n \"\"\"\n print(param1)",
"_____no_output_____"
],
[
"my_func",
"_____no_output_____"
],
[
"my_func()",
"default\n"
],
[
"my_func('new param')",
"new param\n"
],
[
"my_func(param1='new param')",
"new param\n"
],
[
"def square(x):\n return x**2",
"_____no_output_____"
],
[
"out = square(2)",
"_____no_output_____"
],
[
"print(out)",
"4\n"
]
],
[
[
"## lambda expressions",
"_____no_output_____"
]
],
[
[
"def times2(var):\n return var*2",
"_____no_output_____"
],
[
"times2(2)",
"_____no_output_____"
],
[
"lambda var: var*2",
"_____no_output_____"
]
],
[
[
"## map and filter",
"_____no_output_____"
]
],
[
[
"seq = [1,2,3,4,5]",
"_____no_output_____"
],
[
"map(times2,seq)",
"_____no_output_____"
],
[
"list(map(times2,seq))",
"_____no_output_____"
],
[
"list(map(lambda var: var*2,seq))",
"_____no_output_____"
],
[
"filter(lambda item: item%2 == 0,seq)",
"_____no_output_____"
],
[
"list(filter(lambda item: item%2 == 0,seq))",
"_____no_output_____"
]
],
[
[
"## methods",
"_____no_output_____"
]
],
[
[
"st = 'hello my name is Sam'",
"_____no_output_____"
],
[
"st.lower()",
"_____no_output_____"
],
[
"st.upper()",
"_____no_output_____"
],
[
"st.split()",
"_____no_output_____"
],
[
"tweet = 'Go Sports! #Sports'",
"_____no_output_____"
],
[
"tweet.split('#')",
"_____no_output_____"
],
[
"tweet.split('#')[1]",
"_____no_output_____"
],
[
"d",
"_____no_output_____"
],
[
"d.keys()",
"_____no_output_____"
],
[
"d.items()",
"_____no_output_____"
],
[
"lst = [1,2,3]",
"_____no_output_____"
],
[
"lst.pop()",
"_____no_output_____"
],
[
"lst",
"_____no_output_____"
],
[
"'x' in [1,2,3]",
"_____no_output_____"
],
[
"'x' in ['x','y','z']",
"_____no_output_____"
]
],
[
[
"# Great Job!",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"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"
],
[
"markdown"
]
] |
ece51ed86fb6ccd4a82a2b93502ea87587aa40ec | 750,352 | ipynb | Jupyter Notebook | pycrm-dev-nb.ipynb | pfcor/pycrm | 57a74774d1d513a9ee49a06c296b06812ffd486e | [
"MIT"
] | null | null | null | pycrm-dev-nb.ipynb | pfcor/pycrm | 57a74774d1d513a9ee49a06c296b06812ffd486e | [
"MIT"
] | 2 | 2019-03-01T12:09:16.000Z | 2019-03-11T19:41:55.000Z | pycrm-dev-nb.ipynb | pfcor/pycrm | 57a74774d1d513a9ee49a06c296b06812ffd486e | [
"MIT"
] | null | null | null | 289.599382 | 60,752 | 0.910253 | [
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\nimport pycrm\n\nsns.set(style='white')\n%matplotlib inline",
"_____no_output_____"
],
[
"from lifetimes.plotting import *\nfrom lifetimes.utils import *\nfrom lifetimes import BetaGeoFitter, GammaGammaFitter",
"_____no_output_____"
],
[
"df = pd.read_excel(\"pycrm/datasets/Online_Retail.xlsx\")",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df = df.dropna(subset=[\"CustomerID\"])",
"_____no_output_____"
],
[
"df = df[df[\"Quantity\"] > 0].copy()",
"_____no_output_____"
],
[
"df[\"InvoiceDate\"] = df[\"InvoiceDate\"].dt.date",
"_____no_output_____"
],
[
"df['Sales'] = df['Quantity'] * df['UnitPrice']",
"_____no_output_____"
],
[
"df = df.rename(columns={\"CustomerID\": \"customer_id\", \n \"InvoiceDate\": \"order_date\", \n \"Sales\": \"order_value\"})",
"_____no_output_____"
],
[
"df = df[[\"customer_id\", \"order_date\", \"order_value\"]].copy()",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.groupby(\"order_date\").size().plot(figsize=(14,4))",
"_____no_output_____"
],
[
"df[\"order_date\"] = pd.to_datetime(df[\"order_date\"])",
"_____no_output_____"
],
[
"df[\"order_date\"].describe()",
"_____no_output_____"
],
[
"df_rfm = summary_data_from_transaction_data(df, \n 'customer_id', \n 'order_date', \n monetary_value_col='order_value', \n observation_period_end='2011-12-9')",
"_____no_output_____"
],
[
"df_rfm.head()",
"_____no_output_____"
],
[
"df_rfm.loc[(df_rfm[\"frequency\"]>0) & (df_rfm[\"frequency\"]<=30), \"frequency\"].hist(bins=30)",
"_____no_output_____"
],
[
"df_rfm.loc[df_rfm[\"recency\"]>0, \"recency\"].hist(bins=50)",
"_____no_output_____"
],
[
"(df_rfm[\"frequency\"]==0).mean()",
"_____no_output_____"
],
[
"df[df[\"customer_id\"] == 12346.0]",
"_____no_output_____"
],
[
"bgf = BetaGeoFitter(penalizer_coef=0.0)\nbgf.fit(df_rfm['frequency'], df_rfm['recency'], df_rfm['T'])",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(12,8))\nplot_frequency_recency_matrix(bgf)",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(12,8))\nplot_probability_alive_matrix(bgf)",
"_____no_output_____"
],
[
"t = 1\ndf_rfm['predicted_purchases'] = (\n bgf.conditional_expected_number_of_purchases_up_to_time(t, df_rfm['frequency'], df_rfm['recency'], df_rfm['T'])\n)\n\ndf_rfm.sort_values(by='predicted_purchases').tail(5)",
"_____no_output_____"
],
[
"plot_period_transactions(bgf)",
"_____no_output_____"
],
[
"from lifetimes.utils import calibration_and_holdout_data",
"_____no_output_____"
],
[
"summary_cal_holdout = calibration_and_holdout_data(df, \n 'customer_id', \n 'order_date',\n calibration_period_end='2011-06-08',\n observation_period_end='2011-12-09' ) \n",
" frequency_cal recency_cal T_cal frequency_holdout \\\ncustomer_id \n12346.0 0.0 0.0 141.0 0.0 \n12347.0 2.0 121.0 183.0 4.0 \n12348.0 2.0 110.0 174.0 1.0 \n12350.0 0.0 0.0 126.0 0.0 \n12352.0 3.0 34.0 112.0 3.0 \n\n duration_holdout \ncustomer_id \n12346.0 184 \n12347.0 184 \n12348.0 184 \n12350.0 184 \n12352.0 184 \n"
],
[
"summary_cal_holdout.head()",
"_____no_output_____"
],
[
"bgf.fit(summary_cal_holdout['frequency_cal'], summary_cal_holdout['recency_cal'], summary_cal_holdout['T_cal'])\nplot_calibration_purchases_vs_holdout_purchases(bgf, summary_cal_holdout)",
"_____no_output_____"
],
[
"t = 10\nindividual = df_rfm.loc[12347]\nbgf.predict(t, individual['frequency'], individual['recency'], individual['T'])",
"_____no_output_____"
],
[
"individual",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(12,8))\nid = 12348\ndays_since_birth = 365\nsp_trans = df.loc[df['customer_id'] == id]\nplot_history_alive(bgf, days_since_birth, sp_trans, 'order_date')",
"_____no_output_____"
],
[
"df = pd.read_excel(\"/home/pfcor/Downloads/chapter-12-relay-foods.xlsx\", sheet_name=1)\ndf.columns = [\"order_id\", \"order_date\", \"customer_id\", \"order_value\", \"sku\", \"pup_id\", \"pickup_date\"]",
"_____no_output_____"
],
[
"\"{0:s} {1:o} {2:.2f} {3:d}\".format(\"Hello\", 71, 45836.12589, 45 )",
"_____no_output_____"
],
[
"'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)",
"_____no_output_____"
]
],
[
[
"COHORT",
"_____no_output_____"
]
],
[
[
"user_retention_matrix",
"_____no_output_____"
],
[
"user_retention_matrix = pycrm.user_retention_matrix(df, cohort_frequency=\"Q\")\npycrm.plotting.plot_user_retention_matrix(user_retention_matrix.iloc[1:])",
"_____no_output_____"
],
[
"for cg in user_retention_matrix.columns: \n ax = user_retention_matrix.plot(figsize=(10,5), color=\"#aaaaaa\", legend=False)\n user_retention_matrix[[cg]].plot(ax=ax)\n plt.title(f'Cohorts: User Retention - {cg}')\n plt.xticks(np.arange(1, 7.1, 1))\n plt.xlim(1, 7)\n plt.ylim(0,1)\n plt.ylabel('% of Cohort Purchasing');",
"_____no_output_____"
],
[
"user_retention_matrix[\"2009\"]",
"_____no_output_____"
]
],
[
[
"CDNOW",
"_____no_output_____"
]
],
[
[
"df_cdnow = pycrm.datasets.load_cdnow_dataset()",
"_____no_output_____"
],
[
"df_cdnow.head()",
"_____no_output_____"
],
[
"df_cdnow_agg = pycrm.aggregate_transactions_time(df_cdnow, aggregation=\"revenue\", freq=\"D\", full_intervals_only=False)",
"_____no_output_____"
],
[
"pycrm.plotting.plot_transaction_timeseries(df_cdnow_agg, rolling_window=7)",
"_____no_output_____"
],
[
"df_cdnow_agg",
"_____no_output_____"
],
[
"lang = 'Python'\nadj = 'Very Good'\nwidth = \"<20\"\nf'{lang:{width}}: {adj:{width}}'\n# Out[582]: ' Python: Very Good'",
"_____no_output_____"
],
[
"v = 251246134 \n\nf_mlt = 1/1e6\nf_fmt = f\".0f\"\nf_pref = \"R$ \"\nf_suff = \"M\"",
"_____no_output_____"
],
[
"f\"{pref}{v:{fmt}}{suff}\"",
"_____no_output_____"
],
[
"df_cdnow_agg.plot(kind=\"line\", figsize=(14,3))",
"_____no_output_____"
],
[
"def plot_transaction_timeseries(transaction_series, reg=False, **kwargs):\n \n # input validation \n if isinstance(transaction_series, pd.DataFrame):\n assert transaction_series.shape[1] == 1, \"only single column pandas.DataFrame supported\"\n transaction_series = transaction_series.copy()\n elif isinstance(transaction_series, pd.Series):\n transaction_series = transaction_series.copy().to_frame()\n else:\n raise TypeError(f\"invalid transaction_series input: {type(transaction_series)} - pandas.Series or single column pandas.DataFrame supported only\")\n assert isinstance(transaction_series.index, pd.DatetimeIndex), \"index not of pandas.DatetimeIndex type\"\n \n rolling_window = kwargs.get(\"rolling_window\", 1)\n assert rolling_window > 0, \"window must be positive\"\n assert isinstance(rolling_window, int), \"window must be an integer\" \n \n # creating figure \n ax = kwargs.get(\"ax\")\n if not ax:\n fig, ax = plt.subplots(figsize=kwargs.get(\"figsize\", (18,4)))\n \n # plotting series\n (transaction_series.iloc[:, 0]).rolling(rolling_window).mean().plot(ax=ax, label=kwargs.get(\"label\"))\n \n # perform (and plot) single linear regression on series\n # WARNING: simplistic treatment of timeseries data - should not be used in serious analysis\n if reg:\n f = np.poly1d(np.polyfit(range(transaction_series.shape[0]), (transaction_series.iloc[:, 0]).values, 1)) \n transaction_series[\"fitted_line\"] = f(np.arange(transaction_series.shape[0]))\n transaction_series[\"fitted_line\"].plot(ax=ax, lw=2, ls='--', alpha=.5, label=\"Eq_normal: \" + f\"{f}\".strip())\n \n # plot details shortcut\n if kwargs.get(\"legend\", False):\n ax.legend()\n ax.set_title(kwargs.get(\"title\", f\"{transaction_series.columns[0].upper()}\"), size=kwargs.get(\"title_size\", 14))\n ax.set_xlabel(kwargs.get(\"xlabel\", \"\"))\n ax.set_ylabel(kwargs.get(\"ylabel\", \"\"))\n if \"xlim\" in kwargs:\n ax.set_xlim(kwargs.get(\"xlim\"))\n if \"ylim\" in kwargs:\n ax.set_ylim(kwargs.get(\"ylim\"))\n\n return ax\n ",
"_____no_output_____"
],
[
"plot_transaction_timeseries(df_cdnow_agg, legend=True, rolling_window=4)",
"_____no_output_____"
],
[
"isinstance(df_cdnow_agg, pd.DataFrame)",
"_____no_output_____"
],
[
"isinstance(df_cdnow_agg[\"basket_size\"].index, pd.DatetimeIndex)",
"_____no_output_____"
],
[
"df_cdnow_agg[\"basket_size\"].to_frame()",
"_____no_output_____"
],
[
"type(df_cdnow_agg.index)",
"_____no_output_____"
],
[
"def plot_transactions_ts(transactional_df, frequency=\"M\", aggregation=\"n_purchases\", reg=False, black_friday_dates=None, plot_black_friday=False, plot_normal_only=False, **kwargs):\n \"\"\"\n plota a evolucao das compras no tempo\n black_friday_dates:: list of datetime.date\n \"\"\"\n\n if \"black_friday\" in transactional_df.columns:\n if frequency != 'Y':\n df = df.join(grouper[\"black_friday\"].max())\n \n \n if plot_black_friday or plot_normal_only:\n assert \"black_friday\" in df.columns, \"No Black Friday Information Available\"\n \n # n_purchases on normal days\n df[f\"{aggregation}_normal\"] = df[aggregation]\n df.loc[df[\"black_friday\"] == 1, f\"{aggregation}_normal\"] = np.nan\n df[f\"{aggregation}_normal\"] = df[f\"{aggregation}_normal\"].interpolate(method=\"linear\")\n \n # por plotting reasons, considering \"neighbor\" rows as black_friday == 1\n try:\n bf_idx = [(i-1, i, i+1) for i in df.reset_index()[df.reset_index()[\"black_friday\"] == 1].index]\n bf_idx = list(set(list(sum(bf_idx, ()))))\n df.iloc[bf_idx, (df.columns == \"black_friday\").argmax()] = 1\n except IndexError:\n pass\n \n # n_purchases on black friday days\n df[f\"{aggregation}_bf\"] = df[aggregation]\n df.loc[df[\"black_friday\"] != 1, f\"{aggregation}_bf\"] = np.nan \n \n # plot!\n ax = kwargs.get(\"ax\")\n if not ax:\n fig, ax = plt.subplots(figsize=kwargs.get(\"figsize\", (18,4)))\n\n if plot_black_friday:\n (df[f'{aggregation}_normal']).rolling(kwargs.get(\"rolling_window\", 1)).mean().plot(ax=ax, label=kwargs.get(\"label_normal\", \"Normal\"))\n (df[f'{aggregation}_bf']).rolling(kwargs.get(\"rolling_window\", 1)).mean().plot(ax=ax, label=kwargs.get(\"label_bf\", \"Black Friday\"))\n \n # simple linear regression - WARNING: simplistic treatment of timeseries data\n if reg:\n f = np.poly1d(np.polyfit(range(df.shape[0]), (df[f'{aggregation}_normal']).values, 1)) \n df[\"fitted_line\"] = f(np.arange(df.shape[0]))\n df[\"fitted_line\"].plot(ax=ax, lw=2, ls='--', alpha=.5, label=\"Eq_normal: \" + f\"{f}\".strip())\n \n elif plot_normal_only:\n (df[f'{aggregation}_normal']).rolling(kwargs.get(\"rolling_window\", 1)).mean().plot(ax=ax, label=kwargs.get(\"label_normal\", \"Normal\"))\n \n # simple linear regression - WARNING: simplistic treatment of timeseries data\n if reg:\n f = np.poly1d(np.polyfit(range(df.shape[0]), (df[f'{aggregation}_normal']).values, 1)) \n df[\"fitted_line\"] = f(np.arange(df.shape[0]))\n df[\"fitted_line\"].plot(ax=ax, lw=2, ls='--', alpha=.5, label=\"Eq_normal: \" + f\"{f}\".strip())\n \n else:\n (df[aggregation]).rolling(kwargs.get(\"rolling_window\", 1)).mean().plot(ax=ax, label=kwargs.get(\"label\"))\n \n # simple linear regression - WARNING: simplistic treatment of timeseries data\n if reg:\n f = np.poly1d(np.polyfit(range(df.shape[0]), (df[aggregation]).values, 1)) \n df[\"fitted_line\"] = f(np.arange(df.shape[0]))\n df[\"fitted_line\"].plot(ax=ax, lw=2, ls='--', alpha=.5, label=\"Eq_normal: \" + f\"{f}\".strip())\n\n if kwargs.get(\"legend\", False):\n ax.legend()\n\n ax.set_title(kwargs.get(\"title\", f\"{aggregation.upper()} - {frequency}\"), size=kwargs.get(\"title_size\", 14))\n \n ax.set_xlabel(kwargs.get(\"xlabel\",\"\"))\n\n return ax\n",
"_____no_output_____"
]
]
] | [
"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",
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece52cc4c656238e4099be49d7dfcc9633efbda3 | 870,859 | ipynb | Jupyter Notebook | hw1/MIRONENCO_MIRCEA_HW1.ipynb | mirceamironenco/IRHomeworks | 217c6c724d9689db288051d412f1b57082ca145a | [
"BSD-Source-Code"
] | 1 | 2017-12-31T18:40:58.000Z | 2017-12-31T18:40:58.000Z | hw1/MIRONENCO_MIRCEA_HW1.ipynb | mirceamironenco/IRHomeworks | 217c6c724d9689db288051d412f1b57082ca145a | [
"BSD-Source-Code"
] | 1 | 2018-04-09T09:27:02.000Z | 2018-04-09T09:27:02.000Z | hw1/MIRONENCO_MIRCEA_HW1.ipynb | mirceamironenco/IRHomeworks | 217c6c724d9689db288051d412f1b57082ca145a | [
"BSD-Source-Code"
] | 2 | 2018-06-17T17:32:59.000Z | 2020-04-08T04:59:42.000Z | 265.343998 | 174,254 | 0.890676 | [
[
[
"<center> <h1> Information Retrieval Assignment 1 </h1> </center>\n<center> <h3> MSc. Artificial Intelligence </h3> </center>\n<center> <h3> Mircea Mironenco </h2> </center>",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport matplotlib.pyplot as plt\nimport cPickle as pickle\nfrom itertools import product\nfrom __future__ import division\nimport seaborn as sns",
"_____no_output_____"
],
[
"# Some print helpers\ndef print_list(element_list):\n print '\\n'.join([str(element) for element in element_list])\n\ndef print_clicked_list(clicked_list, clicks):\n for index, document in enumerate(clicked_list):\n clicked = clicks[index] == 1\n print '{0} {1}'.format(document,'was clicked' if clicked else ' ')",
"_____no_output_____"
]
],
[
[
"### Step 1\nIn the first step you will generate pairs of rankings of relevance, for the production P and experimental E, respectively, for a hypothetical query q. Assume a 3-graded relevance, i.e. {N, R, HR}. Construct all possible P and E ranking pairs of length 5",
"_____no_output_____"
]
],
[
[
"def construct_rankings(relev_length, pair_length, pairs):\n \"\"\"\n Constructs pairs of rankings for a set of exepriments.\n \n itertools.product(A,B) will return cartesian product of A,B\n i.e. product(A,B) = [(x,y) for x in A for y in B]\n \n Args:\n - relev_length: Number of grades possible for a document.\n - pair_length: Length of a list of documents that are graded.\n - pairs: Number of systems we are producing rankings for.\n \"\"\"\n return product(product(range(relev_length), repeat=pair_length), repeat=pairs)",
"_____no_output_____"
],
[
"rankings = list(construct_rankings(3, 5, 2))\nprint 'Produced a total of {0} pairs. Some examples:'.format(len(rankings))\nprint rankings[1567:1577]",
"Produced a total of 59049 pairs. Some examples:\n[((0, 0, 0, 2, 0), (1, 1, 0, 0, 1)), ((0, 0, 0, 2, 0), (1, 1, 0, 0, 2)), ((0, 0, 0, 2, 0), (1, 1, 0, 1, 0)), ((0, 0, 0, 2, 0), (1, 1, 0, 1, 1)), ((0, 0, 0, 2, 0), (1, 1, 0, 1, 2)), ((0, 0, 0, 2, 0), (1, 1, 0, 2, 0)), ((0, 0, 0, 2, 0), (1, 1, 0, 2, 1)), ((0, 0, 0, 2, 0), (1, 1, 0, 2, 2)), ((0, 0, 0, 2, 0), (1, 1, 1, 0, 0)), ((0, 0, 0, 2, 0), (1, 1, 1, 0, 1))]\n"
]
],
[
[
"### Step 2\n\nImplement 1 binary and 2 multi-graded evaluation measures out of the 7 measures mentioned above. \n\n(Note 2: Some of the aforementioned measures require the total number of relevant and highly relevant documents in the entire collection – pay extra attention on how to find this)",
"_____no_output_____"
],
[
"##### Binary precision - Precision at rank K\n\n**Note**: Becuase our data is graded on a scale, and this is a binary evaluation measure, we make the following assumption:\n\n**All documents that have any degree of relevancy are categorized as RELEVANT. Remaining documents are categorized as NOT RELEVANT.**\n\nExample: *R HR HR R N*. First 4 documents are all *RELEVANT* (irrespective of the relative degree of relevancy), the last one is *NOT RELEVANT*.",
"_____no_output_____"
]
],
[
[
"def precision_at_rank(results,rank=5):\n \"\"\"\n Given a list of results (i.e. documents/URLs)\n from a query. Returns the precision at the specified\n rank.\n \n x = 0 - NOT RELEVANT\n x > 0 - RELEVANT\n \n Args:\n - result: A set of relevance marks corresponding to documents.\n \"\"\"\n if rank > len(results):\n raise Exception('Rank cannot be larger than document list.')\n \n return len([results[i] for i in range(rank) if results[i] > 0]) / rank",
"_____no_output_____"
],
[
"# Example binary evaluation using precision at rank k.\nresult = [0,1,1,0,2] # Equivalent to {N R R N HR}\nprint 'Binary precision at rank 5 for results [N R R N HR] is {0}.'.format(precision_at_rank(result,5))",
"Binary precision at rank 5 for results [N R R N HR] is 0.6.\n"
]
],
[
[
"##### Multi-graded evaluation measures.\n\nAlgorithms implemented:\n- Discounted cumulative gain @ rank K. (DCG@K)\n\n$DCG_{k} = \\sum_{r=1}^{k} \\dfrac{2^{REL(r)} - 1}{log_{2}(1+r)}$\n\n- Rank biased precision with persistance parameter = 0.8. (RBP)\n\n$RBP_{k} = (1 - \\theta) \\cdot \\sum_{r=1}^{k} REL(r) \\cdot \\theta^{r-1}$\n\n- Expected reciprocal rank. (ERR)\n\n$\\sum_{r=1}^{n} \\frac{R_{r}}{r} \\cdot \\prod_{i=1}^{r-1} (1 - R_{i})$",
"_____no_output_____"
]
],
[
[
"def DCG(results, rank=5):\n \"\"\"\n Given a list of results from a query,\n returns the Discounted Cumulative Gains\n at rank k.\n \n Note: Croft et al. (2010) and Burges et al. (2005) \n present the second DCG with a log of base. This one\n uses a log base of 2, as discussed in the lectures.\n \n Args:\n - result: A set of relevance marks corresponding to documents.\n \"\"\"\n return sum([(2**results[i-1] - 1) / np.log2(i + 1) for i in range(1, rank + 1)])",
"_____no_output_____"
],
[
"def RBP(results, rank=5, persistance=0.8):\n \"\"\"\n Given a list of results from a query,\n returns the Rank biased precision with\n the specified persistance.\n \n A. Moffat and J. Zobel. -\n Rank-biased precision for measurement \n of retrieval effectiveness.\n \n Args:\n - result: A set of relevance marks corresponding to documents.\n \"\"\"\n \n return (1. - persistance) * sum([results[i] * persistance**i for i in range(rank)])",
"_____no_output_____"
],
[
"def ERR(results):\n \"\"\"\n Given a list of results from a query,\n returns the expected reciprocal rank.\n \n Chapelle et al. - Expected Reciprocal Rank \n for Graded Relevance\n \n Args:\n - result: A set of relevance marks corresponding to documents.\n \"\"\"\n \n # Relevance grades, with maximum grade 2\n maximum_grade = 2**2\n R = [(2**grade - 1) / maximum_grade for grade in results]\n \n # O(N) ERR algorithm\n ERR, p = 0, 1\n for r in range(len(results)):\n ERR += p * R[r] / (r+1)\n p *= (1 - R[r])\n \n return ERR",
"_____no_output_____"
],
[
"# Example DCG, RBP, ERR evaluation\nprint DCG([2,2,0,0,1], 5)\nprint RBP([2,2,0,0,1], 5)\nprint ERR([2,2,0,0,1])",
"5.27964206795\n0.80192\n0.846875\n"
]
],
[
[
"### Step 3\n\nCalculate the $\\Delta$measure. For the three measures and all P and E ranking pairs constructed above calculate the difference: 𝛥measure = measureE-measureP. Consider only those pairs for which E outperforms P.",
"_____no_output_____"
]
],
[
[
"def delta_measure(measure_algorithm, rankings, biased=True):\n \"\"\"\n Construct groups of pairings between different algorithms,\n depending on the value of the delta measure, using different\n offline measuring techniques.\n \n Args:\n - measure_algorithm: Offline measuring algorithm to be applied (e.g DCG).\n - rankigns: A set of relevance marks corresponding to documents.\n - biased: Boolean value indicating whether or not to return only groups\n for which the delta measure is greater than 0.\n \"\"\"\n results = []\n for production, experiment in rankings:\n delta_measure = measure_algorithm(experiment) - measure_algorithm(production)\n if biased:\n if delta_measure > 0:\n results.append((production, experiment, delta_measure))\n else:\n results.append((production, experiment, delta_measure))\n \n return results",
"_____no_output_____"
],
[
"rankings = list(construct_rankings(3, 5, 2))\ndcg_biased_results, rbp_biased_results, err_biased_results = delta_measure(DCG, rankings), delta_measure(RBP, rankings), delta_measure(ERR, rankings)",
"_____no_output_____"
],
[
"print 'According to DCG are {0} instances where experimental > production.'.format(len(dcg_biased_results))\nprint 'According to RBP are {0} instances where experimental > production.'.format(len(rbp_biased_results))\nprint 'According to ERR are {0} instances where experimental > production.'.format(len(err_biased_results))",
"According to DCG are 29376 instances where experimental > production.\nAccording to RBP are 29403 instances where experimental > production.\nAccording to ERR are 29369 instances where experimental > production.\n"
]
],
[
[
"### Step 4\n\nImplement interleaving. Implement 2 interleaving algorithms: \n- (1) Team-Draft Interleaving OR Balanced Interleaving, \n- (2), Probabilistic Interleaving. \n\nThe interleaving algorithms should \n\n- (a) given two rankings of relevance interleave them into a single ranking, and \n- (b) given the users clicks on the interleaved ranking assign credit to the algorithms that produced the rankings.\n\n(Note 4: Make your implementation as generic as possible such that it could work outside this assignment.)\n\n(Note 5: Note here that as opposed to a normal interleaving experiment where rankings consists of urls or docids, in our case the rankings consist of relevance labels. Hence in this case (a) you will assume that E and P return different documents, (b) the interleaved ranking will also be a ranking of labels.)",
"_____no_output_____"
]
],
[
[
"class Document(object):\n \"\"\"\n Document class used to describe a document return\n by a search algorithm from a query.\n \"\"\"\n def __init__(self, document_id, team, relevance=1):\n self.document_id = document_id\n self.team = team\n self.relevance = relevance\n \n def __repr__(self):\n return str(self.document_id) + ' from team ' + self.team\n \n def __eq__(self, other):\n # Documents are made unique by their id (position in array) and team name.\n return (self.document_id == other.document_id) and (self.team == other.team)\n \nclass InterleavedRanking(object):\n \"\"\"\n Ranking of documents, obtained by using either the\n TeamDraft or Probabilistic interleaving algorithm.\n \"\"\"\n def __init__(self, ranking, lists, algo_names):\n self.ranking = ranking\n self.lists = lists\n self.algo_names = algo_names",
"_____no_output_____"
],
[
"class TeamDraft(object):\n \"\"\"\n Team draft interleaving algorithm class that\n can be used to sample, create an interleaved list,\n as well as evaluate clicks on.\n \"\"\"\n \n def interleave(self, lists, algo_names):\n \"\"\"\n Interleaves the two ranked lists and returns\n a ranking of all the documents. Assumes rankings \n have 5 unique documents, and no document is \n in another ranking.\n \"\"\"\n if len(lists) < 2:\n raise Exception('Cannot interleave less than 2 lists.')\n \n i, j = 0, 0\n interleaved_docs = []\n rankingsA, rankingsB = lists[0], lists[1]\n \n # While we still have documents left in either rankings\n while (i < len(rankingsA) or j < len(rankingsB)):\n if i < len(rankingsA) and j < len(rankingsB):\n # There are still rankings in both lists.\n # Create document objects to be stored in list\n document_a = Document(document_id=i, team=algo_names[0], relevance=rankingsA[i])\n document_b = Document(document_id=j, team=algo_names[1], relevance=rankingsB[j])\n \n # Flip a coin to determine which goes first\n # Add documents to interleaved list\n coin_flip = np.random.randint(low=0, high=2)\n if coin_flip == 0: # First extract from rankingA\n interleaved_docs.extend([document_a, document_b])\n else:\n interleaved_docs.extend([document_b, document_a])\n i += 1\n j += 1\n elif i < len(rankingsA): # There are only documents left in ranking A\n while i < len(rankingsA):\n document_a = Document(document_id=i, team=algo_names[0], relevance=rankingsA[i])\n interleaved_docs.append(document_a)\n i += 1\n else:\n while j < len(rankingsB): # There are only documents left in ranking A\n document_b = Document(document_id=j, team=algo_names[1], relevance=rankingsB[j])\n interleaved_docs.append(document_b)\n j += 1\n \n # Create and return an InterleavedRanking object.\n interleaved_ranking = InterleavedRanking(ranking=interleaved_docs, \n lists=lists, \n algo_names=algo_names)\n return interleaved_ranking\n \n def _deterministic_scores(self, interleaved_ranking, clicks):\n \"\"\"\n Given an interleaved set of documents, and a set of clicks\n determine the score associated with each algorithm that generated\n the documents.\n \n Args:\n - interleaved_ranking: Set of documents interleaved using TeamDraft\n - clicks: Array of 0/1 values indicating clicks at each index (rank).\n \"\"\"\n # Get interleaved list and algorithm names.\n L = interleaved_ranking.ranking\n algo_names = interleaved_ranking.algo_names\n \n scores = [0,0]\n for i in range(len(clicks)):\n # Did click document at rank i\n clicked = clicks[i] == 1\n \n # If we did click the document at rank i, determine\n # which ranking algorithm produced that document\n # and increment it's points\n if clicked and (L[i].team == algo_names[0]):\n scores[0] += 1\n elif clicked and (L[i].team == algo_names[1]):\n scores[1] += 1\n \n return scores\n \n def evaluate(self, interleaved_ranking, clicks):\n \"\"\"\n Returns the winning ranking algorithm. \n \"\"\"\n scores = self._deterministic_scores(interleaved_ranking, clicks)\n# print scores\n # Algorithms used to generate the individual rankings.\n # Determine winner using deterministically generated scores.\n algo_names = interleaved_ranking.algo_names\n \n # Return interleaved list and winner\n if scores[0] > scores[1]:\n return algo_names[0]\n elif scores[0] < scores[1]:\n return algo_names[1]\n else:\n return 'TIE'",
"_____no_output_____"
],
[
"class Softmax(object):\n \n def __init__(self, ranking, team, tau=3):\n \"\"\"\n Softmax function used in a probabilistic\n interleaving algorithm. Assumes rankings have 5\n unique documents, and no document is in another ranking.\n \n Args:\n - tau: \"Controls how quickly selection probabilities\n decay as as rank increases\". Default is 3, as suggested\n in the paper.\n - ranking: A list of documents consisting a ranking by \n a search algorithm.\n - team: Unique identifier for the ranking, which makes it easier\n to associate the document with the particular ranking.\n \"\"\"\n \n self.tau = tau\n self.ranking = ranking\n self.documents = []\n # Create numerator/denominator for original ranking size.\n # Store documents from ranking.\n numerators = np.ndarray(len(ranking))\n for r in range(len(ranking)):\n # Create and store numerator for this rank\n rank_numerator = 1.0 / ((r+1)**tau)\n numerators[r] = rank_numerator\n \n # Store document\n self.documents.append(Document(document_id=r, team=team, relevance=ranking[r]))\n \n denominator = np.sum(numerators)\n # Store probabilities for each document\n self.probs = numerators / denominator\n \n def remove_document(self, document):\n \"\"\"\n Removes a document from the set of documents\n managed by this softmax function. Renormalizes\n the probabilities, and returns the probability\n of sampling the removed document from removal.\n \"\"\"\n index = -1\n for i, curr_doc in enumerate(self.documents):\n if curr_doc == document:\n index = i\n break\n \n if index == -1:\n return 0\n \n # Probability of sampling document before deletion\n prob_document = self.probs[index]\n \n # Remove document\n self.documents.pop(index)\n \n # Renomralize probabilities\n self.probs = np.delete(self.probs, index)\n self.probs = self.probs / sum(self.probs)\n \n return prob_document\n \n def sample(self):\n \"\"\"\n Used to sample a document from the softmax distribution.\n Picks and returns a document, renormalizes probabilities.\n \"\"\"\n # We have no documents left\n if len(self.documents) < 1:\n return None\n \n # We have only 1 document left\n if len(self.documents) == 1:\n self.probs = np.delete(self.probs, 0) # Empty.\n pick = self.documents.pop()\n return pick\n \n # Otherwise sample from the distribution\n cumulative_probs = np.cumsum(self.probs)\n pick = -1\n rand = np.random.rand()\n for pos, cp in enumerate(cumulative_probs):\n if rand < cp:\n pick = self.documents.pop(pos) # Remove document from list.\n break\n \n # Ugly debugging check.\n if not isinstance(pick, Document) and pick == -1:\n print 'cumprobs'\n print 'rand'\n raise Exception('Could not select document')\n \n # Renormalization\n self.probs = np.delete(self.probs, pos)\n self.probs = self.probs / sum(self.probs)\n \n return pick\n ",
"_____no_output_____"
],
[
"class Probabilistic(object):\n \n def __init__(self):\n self.softmaxs = {}\n \n def interleave(self, lists, algo_names, list_length=10):\n \"\"\"\n Returns interleaved document list using \n a probabilistic interleaving method.\n \n Args:\n - lists: A list of rankings to be interleaved,\n e.g. [rankingA, rankingB], where each ranking is \n a list of documents.\n - algo_names: A list of names to be assigned to \n each corresponding ranking. e.g. ['A','B'].\n \"\"\"\n if len(lists) < 2:\n raise Exception('Cannot interleave less than 2 lists.')\n \n if list_length > sum([len(ranking) for ranking in lists]):\n raise Exception('Not enough documents available for requested length')\n \n # Create Softmax functions.\n for i, ranking in enumerate(lists):\n self.softmaxs[i] = Softmax(ranking, algo_names[i])\n \n # Create indexes of rankings.\n list_indexes = list(range(len(lists)))\n interleaved_docs = []\n \n # Start interleaving\n while len(interleaved_docs) < list_length:\n # Stochastically select a softmax to draw documents from.\n np.random.shuffle(list_indexes)\n selected_softmax = np.random.choice(list_indexes)\n \n # Sample and delete document from ranking.\n document = self.softmaxs[selected_softmax].sample()\n \n # No more documents in ranking list.\n if not document:\n # Remove list for future sampling to be\n # done from the other one.\n # Note: :remove: will eliminate the index of the\n # softmax list that is empty.\n list_indexes.remove(selected_softmax)\n else:\n # Add sampled document to interleaved list.\n interleaved_docs.append(document)\n \n # Create and return an InterleavedRanking object.\n interleaved_ranking = InterleavedRanking(ranking=interleaved_docs, \n lists=lists, \n algo_names=algo_names)\n \n return interleaved_ranking\n \n def _probabilistic_scores(self, interleaved_ranking, clicks):\n \"\"\"\n Compute scores for each ranking.\n Implements marginalization comparison\n from the Probabilistic Interleaving paper.\n \"\"\"\n # Interleaved list of documents.\n # Unpack elements, as each is used differently.\n L = interleaved_ranking.ranking\n lists = interleaved_ranking.lists\n algo_names = interleaved_ranking.algo_names \n \n # Get set of documents that were clicked on.\n C = set()\n for i in range(len(clicks)):\n # If document at rank i is clicked\n # add it to the set of documents that were clicked on.\n if clicks[i] == 1:\n C.add(L[i])\n \n # Probability scores for each ranking.\n probability_scores = {0:0.0, 1:0.0}\n \n # All possible assignments.\n # used to marginalize and obtain outcomes.\n # example: [0, 0, 0, 1, 1, 1, 1, 0, 1, 1]\n assignments = [list(arr[0]) for arr in construct_rankings(2,10,1)]\n \n for assignment in assignments:\n # initialize click probabilities\n c = [0,0]\n \n # Softmaxs for assignments\n R = [Softmax(lists[i], algo_names[i]) for i in range(len(lists))]\n \n prob = 1.0\n \n for assignment_index, document in zip(assignment, L):\n alternative_index = (assignment_index + 1) % 2\n \n if document in C:\n c[assignment_index] += 1\n \n # Remove document and store\n # probability of sampling before deletion\n prob *= R[assignment_index].remove_document(document)\n \n # In case document are duplicated in lists\n # Note: With the current implementation, this should\n # never happen. As mentioned in the requirements, all\n # documents should be unique. Implemented as a convenience.\n try:\n R[alternative_index].remove_document(document)\n except:\n pass\n \n # Assign probability score to whicever ranking\n # produced the document.\n if c[0] < c[1]:\n probability_scores[1] += prob\n elif c[0] > c[1]:\n probability_scores[0] += prob\n \n # Return interleaved list and scores.\n return probability_scores\n \n def evaluate(self, interleaved_ranking, clicks):\n \"\"\"\n Given a list of documents interleaved using the\n Probabilistic Interleaving algorithm and a set of clicks,\n determine the 'winning' algorithm.\n \"\"\"\n # Get scores for each ranking.\n scores = self._probabilistic_scores(interleaved_ranking, clicks)\n\n # Team names to be outputted as result / winning algo.\n algo_names = interleaved_ranking.algo_names\n \n # Return interleaved list and winner\n if scores[0] > scores[1]:\n return algo_names[0]\n elif scores[1] > scores[0]:\n return algo_names[1]\n else:\n return 'TIE'",
"_____no_output_____"
],
[
"# Testing interleaving for both Team Draft\n# and Probabilistic Interleaving algorithms.\nprobinter = Probabilistic()\nteamdrft = TeamDraft()\n\n# Rankings to be interleaved\nrankingA = [1,2,2,1,2]\nrankingB = [1,0,2,2,1]\n\n# Interleaved lists from each algorithm\nranking_tdraft = teamdrft.interleave(lists=[rankingA, rankingB], algo_names=['A','B'])\nranking_probs = probinter.interleave(lists=[rankingA, rankingB], algo_names=['A','B'])",
"_____no_output_____"
],
[
"print 'Selected the following documents using Team Draft Interleaving:'\nprint_list(ranking_tdraft.ranking)\n \nprint '\\nSelected the following documents using Probabilistic Interleaving'\nprint_list(ranking_probs.ranking)",
"Selected the following documents using Team Draft Interleaving:\n0 from team B\n0 from team A\n1 from team A\n1 from team B\n2 from team B\n2 from team A\n3 from team B\n3 from team A\n4 from team B\n4 from team A\n\nSelected the following documents using Probabilistic Interleaving\n0 from team B\n1 from team A\n0 from team A\n1 from team B\n2 from team B\n4 from team B\n2 from team A\n3 from team B\n3 from team A\n4 from team A\n"
],
[
"# Test evaluations using clicks on Team Draft Algorithm\nclicks = [1, 0, 1, 0, 1, 0, 0, 0, 0, 0] # Clicked on first, third, and fifth document.\nrankingA = [1,2,2,1,2]\nrankingB = [1,0,2,2,1]\nteamdrft = TeamDraft()\n\n# Generate interleaved document\ninterleaved_ranking = teamdrft.interleave(lists=[rankingA, rankingB], algo_names=['A','B'])\n\n# Interleave list, and obtain evaluation by applying clicks\nwinner = teamdrft.evaluate(interleaved_ranking, clicks)\n\nprint_clicked_list(interleaved_ranking.ranking, clicks)\nprint '\\nWinning ranking algorithm is ', winner",
"0 from team B was clicked\n0 from team A \n1 from team B was clicked\n1 from team A \n2 from team B was clicked\n2 from team A \n3 from team A \n3 from team B \n4 from team B \n4 from team A \n\nWinning ranking algorithm is B\n"
],
[
"# Test evaluations using clicks on Probabilistic Interleaving Algorithm\nclicks = [1, 0, 1, 0, 1, 1, 0, 0, 0, 0] # Clicked on first, third, fifth, sixth document.\nrankingA = [1,2,2,1,2]\nrankingB = [1,0,2,2,1]\nprobinter = Probabilistic()\n\n# Generate interleaved document\ninterleaved_ranking = probinter.interleave(lists=[rankingA, rankingB], algo_names=['A','B'])\n\n# Interleave list, and obtain evaluation by applying clicks\nwinner = probinter.evaluate(interleaved_ranking, clicks)\n\nprint_clicked_list(interleaved_ranking.ranking, clicks)\nprint '\\nWinning ranking algorithm is ', winner",
"0 from team A was clicked\n1 from team A \n2 from team A was clicked\n4 from team A \n3 from team A was clicked\n0 from team B was clicked\n2 from team B \n1 from team B \n3 from team B \n4 from team B \n\nWinning ranking algorithm is A\n"
]
],
[
[
"# Step 5\n\nHaving interleaved all the ranking pairs an online experiment could be ran. However, given that we do not have any users (and the entire homework is a big simulation) we will simulate user clicks.\n\nWe have considered a number of click models including:\n- Random Click Model (RCM)\n- Position-Based Model (PBM)\n- Simple Dependent Click Model (SDCM)\n- Simple Dynamic Bayesian Network (SDBN)\n\nConsider two different click models, (a) the Random Click Model (RCM), and (b) one out of the remaining 3 aforementioned models. The parameters of some of these models can be estimated using the Maximum Likelihood Estimation (MLE) method, while others require using the Expectation-Maximization (EM) method. Implement the two models so that \n- (a) there is a method that learns the parameters of the model given a set of training data. (**train_model**)\n- (b) there is a method that predicts the click probability given a ranked list of relevance labels. (**predict_clicks**)\n- (c) there is a method that decides - stochastically - whether a document is clicked based on these probabilities. (**is_clicked**)\n\nHaving implemented the two click models, estimate the model parameters using the Yandex Click Log (YandexRelPredChallenge.txt).\n\n(Note 6: Do not learn the attractiveness parameter $𝑎_{uq}$.)\n\n**Note on solution**: The chosen algorithms are **Random Click Model** and **Simple Dependent Click Model**",
"_____no_output_____"
],
[
"Before implementing the algorithms, I first preprocess the data. To do this I initally explore how the data is structured. The following are some experiments, in which I show the existence of some corner cases. The following are **assumptions** about the data that I will prove by exploring the dataset:\n\n- A user session is composed of multiple queries, some of them having the same id, while other being different. There are cases where clicks happen on a document that is not in the immediatly previous query (from a time perspective). This can only mean that **the user is opening multiple tabs and doing searches in the same session**. I will rebuild the dataset so that user sessions are transformed in to query-sessions, which are used in click models literature. \n",
"_____no_output_____"
]
],
[
[
"# Load data in pandas to be explored.\npdata = pd.read_csv('YandexRelPredChallenge.txt', sep='\\t', header=None)\npdata.columns = ['session_id', 'time_passed', 'action_type', 'query_click_id', 'region_id',\n 'docid_1', 'docid_2', 'docid_3', 'docid_4', 'docid_5',\n 'docid_6', 'docid_7', 'docid_8', 'docid_9', 'docid_10']",
"_____no_output_____"
]
],
[
[
"Furthermore there are multiple sessions where:\n- There are multiple queries with the same id and **exactly the same 10 documents.**. This corresponds to the user simply hitting enter again on a query.\n- There are multiple queries with the same id, but **10 different documents**. This can be interpreted as the user going to the next page of search results, and will be treated accordingly (where in a cascade model, the documents on the second page start from rank 11, etc.)\n- There are multiple queries with the same id, but **some documents are the same, while some are different**. This is not pagination, this is indicative of using a search engine where the algorithm is being updated in real time. These are a corner case and number around ~196 user sessions. ",
"_____no_output_____"
]
],
[
[
"# Example of user session where an identical query is repeated (same id, same 10 documents)\n# See query with QUERY_ID = 9282\npdata[pdata['session_id'] == 9441]",
"_____no_output_____"
],
[
"# Example of user session where an identical query is repeated \n# but 10 different documents are presented. (next page of search)\n# See query with QUERY_ID = 6091\npdata[pdata['session_id'] == 8667]",
"_____no_output_____"
],
[
"# Example of user session where an identical query is repeated \n# but only the first ~7-8 documents are identical (with a 7 second time difference)\n# while the other are different.\n# See query with QUERY_ID = 4626\npdata[pdata['session_id'] == 5239]",
"_____no_output_____"
]
],
[
[
"#### Data preprocessing - Design decisions\n\nThe following points explain the preprocessing of the data. We make the following modifications to the data:\n\n- Queries within a sessions are transformed into query-session pairs, where the clicks present in the sessions are associated with the last query (from a time perspective) where the document is present.\n- If queries are identical (same id and same documents) they are merged, however the position of a query is moved to the front (i.e. to the position of the second occurance of the same query).\n- If queries are identical but have 10 completely different documents, they are merged into one query where the last 10 documenst are added to the documents of the initial query (i.e. 20 documents, 2 pages, pagination.), and the query is moved to the last position as the most recently seen one.\n- Queries with the same id but only partially different documents are considered different queries.",
"_____no_output_____"
]
],
[
[
"class Query(object):\n def __init__(self, session_id, time_passed, query_id, region_id, documents):\n self.query_id = query_id\n self.session_id = session_id\n self.time_passed = time_passed\n self.region_id = region_id\n self.documents = documents\n self.clicks = []\n \n def has_click(self, click_document_id):\n \"\"\"\n Determines if the clicked document is in this query\n and returns it's rank.\n \"\"\"\n for rank, doc in enumerate(self.documents):\n if doc == click_document_id:\n return rank\n \n return -1\n \n def add_documents(self, documents):\n self.documents.extend(documents)\n \n def has_document(self, document_id):\n for doc in self.documents:\n if document_id == doc:\n return True\n \n return False\n \n def identical_queries(self, query_row):\n \"\"\"\n Compares a query object with a query row\n from the Yandex log file.\n Returns True if they share the same id and all documents are identical.\n \"\"\"\n if self.query_id == query_row[3]:\n for i in range(10):\n if self.documents[i] != query_row[5+i]:\n return False\n return True\n return False\n \n def distinct_queries(self, query_row):\n \"\"\"\n Compares a query object with a query row\n from the Yandex log file.\n Return True if they share the same id, but all 10 documents are different\n (i.e. one is the next page of the other)\n \"\"\"\n if self.query_id == query_row[3]:\n for i in range(10):\n if self.documents[i] == query_row[5+i]:\n return False\n return True\n return False\n\nclass Click(object):\n def __init__(self, session_id, time_passed, document_id, query_id, rank):\n self.session_id = session_id\n self.document_id = document_id\n self.time_passed = time_passed\n self.query_id = query_id\n self.rank = rank",
"_____no_output_____"
],
[
"def getYandexData():\n \"\"\"\n Used to retrieve stripped yandex rows from the text file.\n \"\"\"\n data = []\n with open('YandexRelPredChallenge.txt') as f:\n for row in f:\n row_data = row.split('\\t')\n row_data = [col.strip() for col in row_data]\n data.append(row_data)\n return data",
"_____no_output_____"
],
[
"# First run last cell, for data preprocessing algorithm\nyandex_queries = preprocess_yandex_data()\nprint 'After data processing there are {0} query-session pairs.'.format(len(yandex_queries))",
"After data processing there are 38686 query-session pairs.\n"
]
],
[
[
"### Click model implementations\n\nRequirements:\n- (a) there is a method that learns the parameters of the model given a set of training data. (**train_model**)\n- (b) there is a method that predicts the click probability given a ranked list of relevance labels. (**predict_click_prob**)\n- (c) there is a method that decides - stochastically - whether a document is clicked based on these probabilities. (**is_clicked** in RCM, merged with second method in SDCM)",
"_____no_output_____"
],
[
"### Random Click Model",
"_____no_output_____"
]
],
[
[
"class RCM(object):\n # Random Click Model\n def __init__(self, prob=0.5):\n # Set default probability\n # this variable will be estimated using MLE.\n self.click_prob = prob \n \n def train_model(self, queries):\n \"\"\"\n Given a set of query-session pairs \n (containing both clicks and queries),\n learn the probability of clicking on a document,\n estimated as:\n --> p = number of clicks / number of documents.\n \"\"\"\n num_clicks = sum([len(query.clicks) for query in queries])\n num_docs = sum([len(query.documents) for query in queries])\n \n # MLE estimation\n self.click_prob = num_clicks / num_docs\n \n def predict_click_prob(self, documents):\n \"\"\"\n The probability of a click is associated with the probability\n of each document.\n \n Args:\n - :documents: A list (ranking) of document objects.\n \"\"\"\n # There is no 'prediction' here, as this is the \n # random click model, the probability of a click is\n # the only parameter whe know\n # simply associated the probability of clicking each document\n return np.ones_like(documents) * self.click_prob\n \n def is_clicked(self, documents):\n # Get probabilities for each document\n # based on predict probability method.\n click_probs = self.predict_click_prob(documents)\n \n # Return 1 - Click/0 - No click depending on if the document is clicked\n return [1 if (np.random.uniform(0,1) <= click_prob) else 0 for click_prob in click_probs]",
"_____no_output_____"
],
[
"# Instantiate and train the model\nrandom_click_model = RCM()\nrandom_click_model.train_model(yandex_queries)\n\n# Probability of clicking on a document\nprint 'Random Click Model probability inferred by training on yandex logs is ', random_click_model.click_prob\n\n# Test the random click model on an interleaved list.\nrankingA, rankingB = [1,2,2,1,2], [1,0,2,2,1]\nteamdrft = TeamDraft()\n\n# Generate interleaved document\ninterleaved_ranking = teamdrft.interleave(lists=[rankingA, rankingB], algo_names=['A','B'])\n\n# Predict if documents are clicked, given a set of documents with relevance labels.\nprint 'RCM predicts the following clicks: ',random_click_model.is_clicked(interleaved_ranking.ranking)",
"Random Click Model probability inferred by training on yandex logs is 0.147983381932\nRCM predicts the following clicks: [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]\n"
]
],
[
[
"### Simple dependent click model\n\n**Note**: I have merged the last 2 methods in this class, as the probability of clicking on a document is also dependent on the previous clicks.",
"_____no_output_____"
]
],
[
[
"class SDCM(object):\n # Simple dependent click model\n def __init__(self, num_documents):\n # num_documents = maximum number of documents for a query.\n self.num_documents = num_documents\n \n # Continuation parameter default value.\n self.lmbd = [0.5] * num_documents\n \n def train_model(self, queries):\n \"\"\"\n Given a set of query-session pairs \n (containing both clicks and queries),\n learn the continuation paramter = 1 - satisfaction.\n continuation = 1 - (number of times rank r is last clicked document) / # times rank r is clicked.\n \"\"\"\n # Store last rank clicks for each rank\n last_rank_clicks = [0] * self.num_documents\n \n # Store clicks for each rank\n rank_clicks = [0] * self.num_documents\n \n for query in queries:\n # For each queries that has clicks\n if len(query.clicks) > 0:\n # Record last click\n last_click = query.clicks[-1]\n last_rank_clicks[last_click.rank] += 1\n \n # Record all clicks, including last rank click\n # as formula is last_clicks_at_r / total_clicks_at_r\n # including when it is the last click\n for i in range(len(query.clicks)):\n click = query.clicks[i]\n rank_clicks[click.rank] += 1\n \n # Compute continuation parameters\n for r in range(0, len(self.lmbd)):\n satisfaction = (last_rank_clicks[r] / rank_clicks[r])\n self.lmbd[r] = 1.0 - satisfaction\n \n def predict_and_click(self, documents):\n \"\"\"\n Given a set of documents with relevance labels, returns the probability of clicking\n each one and the ones that were clicked, using the\n Simplified Dependent Click Model algorithm, which implements:\n \n (1) P(C_u = 1) = alpha_u * e_u (attractiveness time examination)\n (2) P(C_u = 1 | C_{<r_u}) = alpha_u * e_u where,\n (3) e_{r+1} = C_r * lambda_r + (1 - C_r) * ((1 - alpha_u) * e_r / 1 - alpha_u * e_r\n \n Args:\n - :documents: A list (ranking) of document objects.\n \"\"\"\n # To compute attractiveness of each document\n # take the relevance of the document * 1.0 / max_relevance\n max_relevance = 2.1\n prev_examination = 1.0\n \n # Store and return the clicks and probabilities\n clicks = [0] * len(documents)\n probs = [0] * len(documents)\n \n for r in range(len(documents)):\n # Attractiveness is determine using the relevance label.\n # Maximum relevance is 2, so the attractiveness for each document\n # is calculated using relevance_u / max_relevance + 0.1\n # This is done based on the assumption that no documents is ever\n # perfectly relevant (i.e. 1.0 attractiveness).\n alpha = documents[r].relevance / max_relevance\n \n # Determine examination probability.\n # Examination for first document is 1\n examination = 1\n \n if r > 0:\n # We are not at the first document\n # Compute examination probability\n \n if clicks[r-1] == 1:\n # If we have a click at the previous document\n # the examination probability = continuation probability\n examination = self.lmbd[r-1]\n else:\n # Attractiveness of previous document\n previous_alpha = documents[r-1].relevance / max_relevance\n \n # Current examination probability\n examination = ((1 - previous_alpha) * prev_examination) / (1 - previous_alpha * prev_examination)\n \n prev_examination = examination\n \n # Compute probability and stochastically determine if document was clicked.\n click_probability = alpha * examination\n did_click = np.random.uniform(0,1) <= click_probability\n \n probs[r] = click_probability\n clicks[r] = 1 if did_click else 0\n \n return probs, clicks\n \n def is_clicked(self, documents):\n # Return only clicks\n _, clicks = self.predict_and_click(documents)\n return clicks",
"_____no_output_____"
],
[
"# Instantiate and train the model\nsdcm_click_model = SDCM(20)\nsdcm_click_model.train_model(yandex_queries)\n\n# Continuation probabilities\nprint 'After training on Yandex logs, the SDCM probabilities of continuation for the first 10 ranks are: '\nprint_list(sdcm_click_model.lmbd[:10])\n\n# Test the Simple dependent click model on an interleaved list.\nrankingA, rankingB = [1,2,2,1,2], [1,0,2,2,1]\nteamdrft = TeamDraft()\n\n# Generate interleaved document\ninterleaved_ranking = teamdrft.interleave(lists=[rankingA, rankingB], algo_names=['A','B'])\n\nprint 'Testing SDCM click prediction on interleaved list.\\n'\n\nclick_probs, did_click = sdcm_click_model.predict_and_click(interleaved_ranking.ranking)\nprint 'Click probabilities are ', click_probs\nprint 'Clicked documents are ', did_click\n\nprint '\\nAnother prediction, only clicks: '\nprint sdcm_click_model.is_clicked(interleaved_ranking.ranking)",
"After training on Yandex logs, the SDCM probabilities of continuation for the first 10 ranks are: \n0.415054787994\n0.584873760144\n0.609322974473\n0.619697606048\n0.615822270387\n0.599480688088\n0.586334942443\n0.543369474562\n0.526833631485\n0.282219309742\nTesting SDCM click prediction on interleaved list.\n\nClick probabilities are [0.47619047619047616, 0.47619047619047616, 0.5570226287088325, 0.0, 0.5803075947360075, 0.06584273301311461, 0.0016781800824784271, 0.0017610487767206705, 8.400740669892987e-05, 2.000344393719544e-06]\nClicked documents are [0, 1, 1, 0, 0, 0, 0, 0, 0, 0]\n\nAnother prediction, only clicks: \n[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n"
]
],
[
[
"### Step 6 - Simulate interleaving experiment\n\nHaving implemented the click models, it is time to run the simulated experiment.\n\nFor each of interleaved ranking run N simulations for each one of the click models implemented and measure the proportion p of wins for E.\n\n(Note 7: Some of the models above include an attractiveness parameter 𝑎uq. Use the relevance label to assign this parameter by setting 𝑎uq for a document u in the ranked list accordingly. (See Click Models for Web Search)",
"_____no_output_____"
]
],
[
[
"# For each measure we want to take the pairs for which E outperforms P (biased)\n# and all the normal pairs.\n# Construct all possible rankings using function from step 1.\nrankings = list(construct_rankings(3, 5, 2))\n\n# All groups of the form (production, experiment, delta_measure) for which \n# the Experimental algorithm beats the Production algorithm, according to\n# the three previously implemented evaluation measures: DCG, RBP, ERR.\ndcg_biased_pairs = np.array(delta_measure(DCG, rankings))\nrbp_biased_pairs = np.array(delta_measure(RBP, rankings))\nerr_biased_pairs = np.array(delta_measure(ERR, rankings))\n\nbiased_measurements = [dcg_biased_pairs, rbp_biased_pairs, err_biased_pairs]\n\n# Same groups but unbiased, contains all pairs from each measurement.\ndcg_pairs = np.array(delta_measure(DCG, rankings, biased=False))\nrbp_pairs = np.array(delta_measure(RBP, rankings, biased=False))\nerr_pairs = np.array(delta_measure(ERR, rankings, biased=False))\n\nunbiased_measurements = [dcg_pairs, rbp_pairs, err_pairs]\n\n# Train the click models beforehand, on the yandex logs.\nyandex_queries = preprocess_yandex_data()\n\nrcm = RCM()\nrcm.train_model(yandex_queries)\n\nsdcm = SDCM(20) # 20 documents - maximum of 2 pages for a query.\nsdcm.train_model(yandex_queries)\n\n# Initialize interleaving algorithms.\nteam_draft = TeamDraft()\nprob_draft = Probabilistic()",
"_____no_output_____"
],
[
"# The logical steps that should be taken for the online case are: \n# 1. Take a pair of rankings with relevance for labels\n# 2. Generate the interleaved list using one of the interleaving algorithms.\n# 3. Give that interleaved list to the SDCM/ RCM model which is trained on yandex, \n# and determine the positions at which clicks happen.\n# 4. Using the algorithm you used to implement the interleaving model, evaluate the\n# 'winner' by using the interleaved list and the clicks.\n# 5. Count all the winners, and compare the proportion of cases where E wins\n# from the online model with offline model.\n\n\ninterleaving_algos = [team_draft, prob_draft]\nclick_algos = [rcm, sdcm]\n\ndef get_online_results(measurements, num_simulations=35, num_samples=100):\n \"\"\"\n Performs an online exepriemnt, using both interleaving algorithms, both\n click models, and all offline measures.\n \n Args:\n - measurements: The offline measurements data to be experimented on.\n - num_simulations: Number of click simulations for each experiment.\n - num_samples: Number of pairs of samples to take from each offline dataset.\n \"\"\"\n # Split results into the specific measurement, and interleaving algorithm\n # they come from, for in-depth analysis at step 7.\n online_results = {'DCG':{'team':{'RCM':[],'SDCM':[]},\n 'probabilistic':{'RCM':[], 'SDCM':[]}}, \n 'RBP':{'team':{'RCM':[],'SDCM':[]},\n 'probabilistic':{'RCM':[],'SDCM':[]}}, \n 'ERR':{'team':{'RCM':[],'SDCM':[]},\n 'probabilistic':{'RCM':[],'SDCM':[]}}}\n\n # For each type of measurement\n for measure_index, off_pairs_group in enumerate(measurements):\n # Sample (without replacement) a number of pairs from this group\n pairs_samples = off_pairs_group[np.random.choice(len(off_pairs_group), num_samples, replace=False)]\n\n # For each sample pair.\n for sample_num, sample in enumerate(pairs_samples):\n if sample_num % 25 == 0:\n print 'Analyzing sample {0} from measurement {1}'.format(sample_num, measure_index)\n\n # Algorithms to compare\n production_ranking = sample[0]\n experimental_ranking = sample[1]\n\n # For each interleaving algorithm\n for algo_index, interleaving_algo in enumerate(interleaving_algos):\n # Create interleaved list.\n interleaved_list = interleaving_algo.interleave([production_ranking, experimental_ranking], ['P', 'E'])\n\n for click_index, click_algorithm in enumerate(click_algos):\n # Record number of wins for each algorithm\n e_wins = 0\n p_wins = 0\n\n # Run 'num_simulations' experiments on the list.\n for simulation_index in range(num_simulations):\n # Simulate clicks\n clicks = click_algorithm.is_clicked(interleaved_list.ranking)\n\n # Determine winner\n winner = interleaving_algo.evaluate(interleaved_list, clicks)\n if winner == 'E':\n e_wins += 1\n elif winner == 'P':\n p_wins += 1\n\n\n # Set which interleaving algorithm and measurement produced result\n algo_name = 'team' if algo_index == 0 else 'probabilistic'\n measure_name = ''\n if measure_index == 0:\n measure_name = 'DCG'\n else:\n measure_name = 'RBP' if measure_index == 1 else 'ERR'\n\n # Determine click algorithm used\n click_name = 'RCM' if click_index == 0 else 'SDCM'\n \n # Save result, save pair, delta_measurement and proportion.\n proportion = e_wins / (e_wins + p_wins)\n online_results[measure_name][algo_name][click_name].append((sample, proportion))\n return online_results",
"_____no_output_____"
],
[
"# Run online simulation on biased data\nbiased_online_results = get_online_results(biased_measurements)",
"_____no_output_____"
],
[
"# Save data\nbiased_file_name = 'biased_online_results.p'\nwith open(biased_file_name, 'wb') as fp:\n pickle.dump(biased_online_results, fp)",
"_____no_output_____"
],
[
"# Run online simulation on normal data\ngeneral_online_results = get_online_results(unbiased_measurements)",
"_____no_output_____"
],
[
"# Save data\ngeneral_file_name = 'general_online_results.p'\nwith open(general_file_name, 'wb') as fp:\n pickle.dump(general_online_results, fp)",
"_____no_output_____"
]
],
[
[
"### Step 7 - Results and Analysis \n\nIn the following section I perform an analysis by studying: \n- **Biased data** - Random samples from the cases where for the offline measures (DCG,RBP,ERR) $\\Delta measure > 0$ (E wins)\n- **Normal data** - Random samples from the entire dataset.",
"_____no_output_____"
]
],
[
[
"with open('biased_online_results.p', 'rb') as fp:\n biased_online_results = pickle.load(fp)",
"_____no_output_____"
],
[
"with open('general_online_results.p', 'rb') as fp:\n general_online_results = pickle.load(fp)",
"_____no_output_____"
],
[
"# Study biased results first\n# Separate results dependeing on measurement and click/interleaving algorithm.\nbiased_DCG, biased_RBP, biased_ERR = biased_online_results['DCG'], biased_online_results['RBP'], biased_online_results['ERR']\nunbiased_DCG, unbiased_RBP, unbiased_ERR = general_online_results['DCG'], general_online_results['RBP'], general_online_results['ERR']\n\ndef print_measurement_results(measurement, measurement_name, num_samples):\n print 'For {0} pairs sampled from the dataset, the results for {1} are: '.format(num_samples, measurement_name)\n for interleaving_algo in measurement:\n algo_name = 'Team Draft Interleaving' if interleaving_algo == 'team' else 'Probabilistic Interleaving'\n algo_results = measurement[interleaving_algo]\n\n for click_model in algo_results:\n click_name = 'Random Click Model' if click_model == 'RCM' else 'Simple Dependent Click Model'\n click_results = algo_results[click_model]\n\n # Compute absolute number of time proportion is greater than > 0.5\n # Also compute the average value of the proportion.\n e_greater = sum([int(click_results[i][1] > 0.5) for i in range(len(click_results))]) # Number of times p > 0.5\n \n # Compute average proportion values.\n avg_proportion = sum([click_results[i][1] for i in range(len(click_results))]) / len(click_results)\n \n print '------------------'\n print 'Using {0} and {1}. \\nThe number of times the proportion(e_wins) > 0.5 is {2}/{3}'.format(algo_name, click_name, e_greater, len(click_results))\n print 'The average proportion of times E wins is {0}'.format(avg_proportion)\n print '------------------'\n print '\\n'\n",
"_____no_output_____"
],
[
"# Considering only measurements from the offline experiment where E > P\nprint_measurement_results(biased_DCG, 'Biased Discounted Cumulative Gains', 100)\nprint_measurement_results(biased_RBP, 'Biased Rank-biased precision', 100)\nprint_measurement_results(biased_ERR, ' Expected Reciprocal Rank', 100)",
"For 100 pairs sampled from the dataset, the results for Biased Discounted Cumulative Gains are: \n------------------\nUsing Probabilistic Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 37/100\nThe average proportion of times E wins is 0.476888769934\n------------------\n------------------\nUsing Probabilistic Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 60/100\nThe average proportion of times E wins is 0.621069666576\n------------------\n------------------\nUsing Team Draft Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 40/100\nThe average proportion of times E wins is 0.49096818663\n------------------\n------------------\nUsing Team Draft Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 81/100\nThe average proportion of times E wins is 0.732384090706\n------------------\n\n\nFor 100 pairs sampled from the dataset, the results for Biased Rank-biased precision are: \n------------------\nUsing Probabilistic Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 51/100\nThe average proportion of times E wins is 0.495143952595\n------------------\n------------------\nUsing Probabilistic Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 66/100\nThe average proportion of times E wins is 0.640666305232\n------------------\n------------------\nUsing Team Draft Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 40/100\nThe average proportion of times E wins is 0.488122294494\n------------------\n------------------\nUsing Team Draft Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 79/100\nThe average proportion of times E wins is 0.729360125366\n------------------\n\n\nFor 100 pairs sampled from the dataset, the results for Expected Reciprocal Rank are: \n------------------\nUsing Probabilistic Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 44/100\nThe average proportion of times E wins is 0.497705748447\n------------------\n------------------\nUsing Probabilistic Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 65/100\nThe average proportion of times E wins is 0.658571428571\n------------------\n------------------\nUsing Team Draft Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 51/100\nThe average proportion of times E wins is 0.505813053875\n------------------\n------------------\nUsing Team Draft Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 82/100\nThe average proportion of times E wins is 0.757394724247\n------------------\n\n\n"
],
[
"# Considering measurements from the entire set of offline experiments (no bias)\nprint_measurement_results(unbiased_DCG, 'Discounted Cumulative Gains', 100)\nprint_measurement_results(unbiased_RBP, 'Rank-biased precision', 100)\nprint_measurement_results(unbiased_ERR, 'Rank-biased precision', 100)",
"For 100 pairs sampled from the dataset, the results for Discounted Cumulative Gains are: \n------------------\nUsing Probabilistic Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 36/100\nThe average proportion of times E wins is 0.481810708186\n------------------\n------------------\nUsing Probabilistic Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 50/100\nThe average proportion of times E wins is 0.491142857143\n------------------\n------------------\nUsing Team Draft Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 53/100\nThe average proportion of times E wins is 0.513907486002\n------------------\n------------------\nUsing Team Draft Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 49/100\nThe average proportion of times E wins is 0.469385185524\n------------------\n\n\nFor 100 pairs sampled from the dataset, the results for Rank-biased precision are: \n------------------\nUsing Probabilistic Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 43/100\nThe average proportion of times E wins is 0.47370409365\n------------------\n------------------\nUsing Probabilistic Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 46/100\nThe average proportion of times E wins is 0.478658008658\n------------------\n------------------\nUsing Team Draft Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 43/100\nThe average proportion of times E wins is 0.489622478702\n------------------\n------------------\nUsing Team Draft Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 43/100\nThe average proportion of times E wins is 0.465636228249\n------------------\n\n\nFor 100 pairs sampled from the dataset, the results for Rank-biased precision are: \n------------------\nUsing Probabilistic Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 40/100\nThe average proportion of times E wins is 0.481763723885\n------------------\n------------------\nUsing Probabilistic Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 44/100\nThe average proportion of times E wins is 0.484050420168\n------------------\n------------------\nUsing Team Draft Interleaving and Random Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 39/100\nThe average proportion of times E wins is 0.490516926937\n------------------\n------------------\nUsing Team Draft Interleaving and Simple Dependent Click Model. \nThe number of times the proportion(e_wins) > 0.5 is 55/100\nThe average proportion of times E wins is 0.544534713551\n------------------\n\n\n"
],
[
"rez = []\nfor dataset_index, dataset in enumerate([biased_online_results, general_online_results]):\n # Measurement of total results for datasets\n total_e_wins = 0 # Total number of times the proportion e_wins > 0.5\n total_pairs = 0\n for measurement in dataset:\n for interleaving_algo in dataset[measurement]:\n for click_model in dataset[measurement][interleaving_algo]:\n results = dataset[measurement][interleaving_algo][click_model]\n total_e_wins += sum([int(results[i][1] > 0.5) for i in range(len(results))])\n total_pairs += len(results)\n \n rez.append((total_e_wins, total_pairs))\n dataset_name = 'biased' if dataset_index == 0 else 'general'\n print 'For the {0} dataset, the average number of times the proportion p (e wins) > 0.5 is {1}'.format(dataset_name ,total_e_wins / total_pairs)",
"For the biased dataset, the average number of times the proportion p (e wins) > 0.5 is 0.584158415842\nFor the general dataset, the average number of times the proportion p (e wins) > 0.5 is 0.456270627063\n"
]
],
[
[
"### Binomial signifiance test",
"_____no_output_____"
]
],
[
[
"# Separate data\nbiased_success = rez[0][0]\nbiased_trials = rez[0][1]\n\ngeneral_success = rez[1][0]\ngeneral_trials = rez[1][1]\n\n# Use statistical binomial test to see if probability of success is:\n# H0: greater than 0.5\n# H1: lesser than 0.5\nprint 'Biased dataset E proportion > 0.5 with confidence', scipy.stats.binom_test(x=biased_success, n=biased_trials, p=0.5, alternative='less') # One-sided binomial test\nprint 'General dataset E proportion > 0.5 with confidence', scipy.stats.binom_test(x=general_success, n=general_trials, p=0.5, alternative='less') # One-sided binomial test",
"Biased dataset E proportion > 0.5 with confidence 0.999999998207\nGeneral dataset E proportion > 0.5 with confidence 0.0012733798075\n"
]
],
[
[
"### Plots",
"_____no_output_____"
]
],
[
[
"# Now separate results in lists, and plot them. Use signed binomial test and seaborn for plotting\ndef res_lists(measurement, pandas=True):\n # Theoretically there are 4 lists for each measurement -> 12 lists \n # Preprocess each list so that only delta_measure and proportion remains\n # from each element in the list, the values in the pairs are not relevant now\n RCM_team = np.array([[element[1], element[0][2]] for element in measurement['team']['RCM']])\n RCM_prob = np.array([[element[1], element[0][2]] for element in measurement['probabilistic']['RCM']])\n SDCM_team = np.array([[element[1], element[0][2]] for element in measurement['team']['SDCM']])\n SDCM_prob = np.array([[element[1], element[0][2]] for element in measurement['probabilistic']['SDCM']])\n \n if pandas:\n RCM_team = pd.DataFrame(RCM_team, columns=['x', 'y'])\n RCM_prob = pd.DataFrame(RCM_prob, columns=['x', 'y'])\n SDCM_team = pd.DataFrame(SDCM_team, columns=['x', 'y'])\n SDCM_prob = pd.DataFrame(SDCM_prob, columns=['x', 'y'])\n \n return RCM_team, RCM_prob, SDCM_team, SDCM_prob",
"_____no_output_____"
],
[
"# DCG\ndcg_lists = res_lists(general_online_results['DCG'])\nbiased_dcg_lists = res_lists(biased_online_results['DCG'])\n# RBP\nrbp_lists = res_lists(general_online_results['RBP'])\nbiased_rbp_lists = res_lists(biased_online_results['RBP'])\n# ERR\nerr_lists = res_lists(general_online_results['ERR'])\nbiased_err_lists = res_lists(biased_online_results['ERR'])",
"_____no_output_____"
],
[
"def plot_proportion_distribution(dataset, title):\n fig, axs = plt.subplots(ncols=4, nrows=3, figsize=(12,6))\n \n # Set title, axis labels.\n fig.suptitle(title)\n x_axis = [['RCM-TeamDraft \\nE success ratio', 'RCM-Probabilistic \\nE success ratio','SDCM-TeamDraft \\nE success ratio','SDCM-Probabilistic \\nE success ratio'],\n ['RCM-TeamDraft \\nE success ratio', 'RCM-Probabilistic \\nE success ratio','SDCM-TeamDraft \\nE success ratio','SDCM-Probabilistic \\nE success ratio'],\n ['RCM-TeamDraft \\nE success ratio', 'RCM-Probabilistic \\nE success ratio','SDCM-TeamDraft \\nE success ratio','SDCM-Probabilistic \\nE success ratio']]\n y_axis = ['DCG','RBP','ERR']\n \n # Plot all distributions\n for r, dataset_lists in enumerate(dataset):\n for c, d_list in enumerate(dataset_lists):\n proportions = d_list.iloc[:,0].values\n ax = sns.distplot(proportions, ax=axs[r][c])\n if c == 0:\n ax.set(xlabel=x_axis[r][c],ylabel=y_axis[r])\n else:\n ax.set(xlabel=x_axis[r][c],ylabel='')",
"_____no_output_____"
]
],
[
[
"#### Analysis of proportion p's distribution for both biased and general dataset.\n\nPlot the distribution of the value of p (the proportion of E wins). If the online and offline evaluation techinques have a correlation we should see a tendency for the biased dataset (where we have taken only those pairs for which E won) to have a distribution with a larger mean than the normal dataset.",
"_____no_output_____"
]
],
[
[
"# Plot biased dataset proportion distribution\nbiased_dataset = [biased_dcg_lists, biased_rbp_lists, biased_err_lists]\nplot_proportion_distribution(biased_dataset, 'Distribution of p (proportion of E wins) for biased data.')",
"_____no_output_____"
],
[
"# Plot biased dataset proportion distribution\ngeneral_dataset = [dcg_lists, rbp_lists, err_lists]\nplot_proportion_distribution(general_dataset, 'Distribution of p (proportion of E wins) for general data.')",
"_____no_output_____"
],
[
"def plot_bivariate_distributions(dataset, title):\n # Function to plot the distribution of data\n # for both proportion (x axis) and delta measure (y axis)\n fig, axs = plt.subplots(ncols=4, nrows=3, figsize=(12,6))\n fig.suptitle(title)\n x_axis = [['RCM-TeamDraft \\nE success ratio', 'RCM-Probabilistic \\nE success ratio','SDCM-TeamDraft \\nE success ratio','SDCM-Probabilistic \\nE success ratio'],\n ['RCM-TeamDraft \\nE success ratio', 'RCM-Probabilistic \\nE success ratio','SDCM-TeamDraft \\nE success ratio','SDCM-Probabilistic \\nE success ratio'],\n ['RCM-TeamDraft \\nE success ratio', 'RCM-Probabilistic \\nE success ratio','SDCM-TeamDraft \\nE success ratio','SDCM-Probabilistic \\nE success ratio']]\n y_axis = ['DCG \\n$\\Delta measure$','RBP \\n$\\Delta measure$','ERR \\n$\\Delta measure$']\n \n for r, dataset_lists in enumerate(dataset):\n for c, d_list in enumerate(dataset_lists):\n ax = sns.kdeplot(d_list.x, d_list.y, shade=True, cmap='Blues', ax=axs[r][c])\n ax.set_xlim(0,1)\n \n if c == 0:\n ax.set(xlabel=x_axis[r][c], ylabel=y_axis[r])\n else:\n ax.set(xlabel=x_axis[r][c], ylabel='')",
"_____no_output_____"
]
],
[
[
"#### Analysis of both $\\Delta measure$ and p-proportion\n\nPlot the bivariate distribution of the proportion and the delta measure, thus effectively comparing and obtaining an idea about the correlation of the 2 variables. ",
"_____no_output_____"
]
],
[
[
"# Plot distributions for biased dataset\nplot_bivariate_distributions(biased_dataset, 'Biased dataset proportion and $\\Delta measure$ distributions')",
"_____no_output_____"
],
[
"# Plot distributions for general dataset\nplot_bivariate_distributions(general_dataset, 'General dataset proportion and $\\Delta measure$ distributions')",
"_____no_output_____"
],
[
"# Studying individual datasets will help us determine even more conclusive results\n# DCG\n# dcg_lists = res_lists(general_online_results['DCG'], pandas=False)\nbiased_dcg_lists = res_lists(biased_online_results['DCG'], pandas=False)\n# RBP\n# rbp_lists = res_lists(general_online_results['RBP'], pandas=False)\nbiased_rbp_lists = res_lists(biased_online_results['RBP'], pandas=False)\n# ERR\n# err_lists = res_lists(general_online_results['ERR'], pandas=False)\nbiased_err_lists = res_lists(biased_online_results['ERR'], pandas=False)\n\n\n# We merge RCM and SDCM results, for each dataset, and study trends on the larger datasets.\n# This analysis is performed only on the biased dataset, for brevity and to provide further\n# insights into the coorrelation between the offline and online results.\nDCG_biased_RCM = pd.DataFrame(np.vstack((biased_dcg_lists[0],biased_dcg_lists[1])), columns=['x','y'])\nDCG_biased_SDCM = pd.DataFrame(np.vstack((biased_dcg_lists[2],biased_dcg_lists[3])), columns=['x','y'])\n\nRBP_biased_RCM = pd.DataFrame(np.vstack((biased_rbp_lists[0],biased_rbp_lists[1])), columns=['x','y'])\nRBP_biased_SDCM = pd.DataFrame(np.vstack((biased_rbp_lists[2],biased_rbp_lists[3])), columns=['x','y'])\n\nERR_biased_RCM = pd.DataFrame(np.vstack((biased_err_lists[0],biased_err_lists[1])), columns=['x','y'])\nERR_biased_SDCM = pd.DataFrame(np.vstack((biased_err_lists[2],biased_err_lists[3])), columns=['x','y'])",
"_____no_output_____"
]
],
[
[
"#### Analysis using pearson correlation of relationship between $\\Delta measure$ and proportion\n\nWe merge the results from the 2 interleaving algorithms, effectively only retaining the separation created by the click algorithms in the distribution of the data. We shall see that given a 'less biased' click model (like the SDCM) we find a small corelation between the biased data pairs and the increase in the proportion of wins for the Experimental algorithm.\n\n**Note**: Unfortunately *jointplots* in seaborn cannot be plotted as subplots, so this section is composed of 6 cells. While quite verbose I believe it serves the purpose of showing the relationship between the proportion and $\\Delta measure$, helping us draw better conclusions about the online/offline performance of the algorithms.",
"_____no_output_____"
]
],
[
[
"print 'Online-Offline correlation for DCG with RCM'\nsns.jointplot(x='x',y='y', size=4, kind='kde', data=DCG_biased_RCM).set_axis_labels(\"E success ratio\", \"$\\Delta measure$\")",
"Online-Offline correlation for DCG with RCM\n"
],
[
"print 'Online-Offline correlation for DCG with SDCM'\nsns.jointplot(x='x',y='y', size=4, kind='kde', data=DCG_biased_SDCM).set_axis_labels(\"E success ratio\", \"$\\Delta measure$\")",
"Online-Offline correlation for DCG with SDCM\n"
],
[
"print 'Online-Offline correlation for RBP with RCM'\nsns.jointplot(x='x',y='y', size=4, kind='kde', data=RBP_biased_RCM).set_axis_labels(\"E success ratio\", \"$\\Delta measure$\")",
"Online-Offline correlation for RBP with RCM\n"
],
[
"print 'Online-Offline correlation for RBP with SDCM'\nsns.jointplot(x='x',y='y', size=4, kind='kde', data=RBP_biased_SDCM).set_axis_labels(\"E success ratio\", \"$\\Delta measure$\")",
"Online-Offline correlation for RBP with SDCM\n"
],
[
"print 'Online-Offline correlation for ERR with RCM'\nsns.jointplot(x='x',y='y', size=4, kind='kde', data=ERR_biased_RCM).set_axis_labels(\"E success ratio\", \"$\\Delta measure$\")",
"Online-Offline correlation for ERR with RCM\n"
],
[
"print 'Online-Offline correlation for ERR with SDCM'\nsns.jointplot(x='x',y='y', size=4, kind='kde', data=ERR_biased_SDCM).set_axis_labels(\"E success ratio\", \"$\\Delta measure$\")",
"Online-Offline correlation for ERR with SDCM\n"
],
[
"print 'Online-Offline correlation for ERR with SDCM'\nsns.jointplot(x='x',y='y', size=4, kind='reg', data=ERR_biased_SDCM).set_axis_labels(\"E success ratio\", \"$\\Delta measure$\")",
"Online-Offline correlation for ERR with SDCM\n"
]
],
[
[
"## Conclusions and analysis\n\n- By studying the binomial test done previously, we can see that if we set a null hypothesis for the biased dataset to have a success greater than 0.5 using the Experimental algorithm, the hypotesis will be accepted. While if we use the general dataset that is not biased towards E, the null hypothesis is rejected.\n- From the 1 sided test we can conclude that there is a tendency for the distribution mass of the dataset to favor the E algorithm when our offline measurements indicate this direction. However, as expected, when we sample from the entire dataset, there is no correlation between the offline and online measurements.\n- Studying the plots and the interaction between the click models and the proportion - $\\Delta measure$ relationship, we can see that the Random Click Model doesn't capture the small correlation between the 2 variables, that exists when the data is biased towards the E algorithm. This correlation, while small, is captured by the Simple Dependent Click Model, as observed both in the plots showing the distribution of the proportion and the ones mapping the bivariate distribution of the 2 variables.\n- The SDCM makes much less assumption, and is much less biased then the Random Click Model, which can only map clicks on the documents without considering any form of relationships between previous clicks or documents. Therefore it is obvious that the SDCM model is prefered, as it can capture user behaviour better, as well as serve as a better baseline for online-offline comparisons.\n- By observing the effect of the Probabilistic Interleaving algorithm, we can conclude that the additional smoothing provided add a 'sensability' to the process of interleaving the algorithms, and has the effect of reducing the effect of the biased data; if we compare the average proportion of E wins for the biased data using the TeamDraft and Probabilistic algorithms, the former tends more towards 1 and indicates a stronger correlation between offline and online performance of the E algorithm.\n- Using the SDCM model the distribution of the proportion tends towards 1 for the biased dataset, with values generally hoverwing around ~0.7, which indicates a (slightly) better performance of the E algorithm in both settings.",
"_____no_output_____"
],
[
"### Pitfalls, drawbacks\n\n- DCG and RBP do not take into account relevance of neighbour documents. ERR attempt to solve this by considering the relevance of previous document, but does not consider subsequent documents.\n- SDCM doesn't allow users to skip documents when examining a SERP.\n- Team Draft seems unreliable on small datasets, as it cannot break ties and create randomness if there are very few clicks.",
"_____no_output_____"
],
[
"#### \"Appendix A\" - Yandex Data preprocessing",
"_____no_output_____"
]
],
[
[
"def preprocess_yandex_data():\n # def preprocess_yandex_data():\n yandex_data = getYandexData()\n index = 0\n query_session_counter = 0\n all_queries = []\n while index < len(yandex_data):\n # Current row\n datapoint = yandex_data[index]\n\n # Current user session id\n session = datapoint[0]\n\n # Process current sessions queries and clicks.\n session_queries = []\n session_unique_queries = {}\n\n # Iterate through current session\n sess = session\n session_index = index\n while sess == session:\n row_datapoint = yandex_data[session_index]\n\n # Found a query\n if row_datapoint[2] == 'Q':\n query_id = row_datapoint[3]\n\n # We have never seen this query before\n if not query_id in session_unique_queries:\n # Create query object\n query = Query(session_id=query_session_counter, time_passed=row_datapoint[1], query_id=row_datapoint[3], region_id=row_datapoint[4], documents=[row_datapoint[i] for i in range(5, len(row_datapoint))])\n query_session_counter += 1\n\n # Store query as newest query\n session_queries.append(query)\n session_unique_queries[query_id] = query\n else:\n # We have seen this query before, handle corner cases\n\n # Same query id, determine difference if there is one.\n prev_query = session_unique_queries[query_id]\n\n # Queries are identical\n if prev_query.identical_queries(row_datapoint):\n # Simply move the position of the query to the top of the list.\n session_queries.pop(session_queries.index(prev_query))\n session_queries.append(prev_query)\n\n elif prev_query.distinct_queries(row_datapoint):\n # Same query, different documents, simply append them to the end of the list\n # and move query to front.\n prev_query.add_documents([row_datapoint[i] for i in range(5, len(row_datapoint))])\n session_queries.pop(session_queries.index(prev_query))\n session_queries.append(prev_query)\n else:\n # Same documents, only some documents are the same.\n # Create a new query object from the current row.\n # Create query object\n query = Query(session_id=query_session_counter, time_passed=row_datapoint[1], query_id='###', region_id=row_datapoint[4], documents=[row_datapoint[i] for i in range(5, len(row_datapoint))])\n query_session_counter += 1\n\n # Only store query object as newest query.\n session_queries.append(query)\n else:\n # Process click\n # Find latest query where click is present.\n document_clicked = row_datapoint[3]\n\n # Start from latest query\n for p_query in session_queries[::-1]:\n r = p_query.has_click(document_clicked)\n if r != -1:\n # Found click\n click = Click(session_id=p_query.session_id, time_passed=row_datapoint[1], document_id=document_clicked, query_id=p_query.query_id, rank=r)\n # Store click\n p_query.clicks.append(click)\n break\n else:\n print 'Document clicked is {0} in session {1}'.format(document_clicked, row_datapoint[0])\n session_index += 1\n if session_index < len(yandex_data):\n sess = yandex_data[session_index][0]\n else:\n sess = None\n\n all_queries.extend(session_queries)\n index = session_index\n \n return all_queries",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
ece53a14a5835b1cfd58c3d1820f64effbe33034 | 6,671 | ipynb | Jupyter Notebook | notebooks/thesis_functions/visualization.ipynb | aerosara/thesis | 55bd84e8d4b4bffa8f7526bd5b94ddef80911f99 | [
"MIT"
] | null | null | null | notebooks/thesis_functions/visualization.ipynb | aerosara/thesis | 55bd84e8d4b4bffa8f7526bd5b94ddef80911f99 | [
"MIT"
] | null | null | null | notebooks/thesis_functions/visualization.ipynb | aerosara/thesis | 55bd84e8d4b4bffa8f7526bd5b94ddef80911f99 | [
"MIT"
] | null | null | null | 41.69375 | 173 | 0.514316 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
ece53f34c5a4fb0b207210ef6c695a3284160729 | 7,640 | ipynb | Jupyter Notebook | notebooks/samples/105 - Regression with DataConversion.ipynb | tongwen11/mmlspark | 088567242e6e09a114a29a456f00b068f124506e | [
"MIT"
] | null | null | null | notebooks/samples/105 - Regression with DataConversion.ipynb | tongwen11/mmlspark | 088567242e6e09a114a29a456f00b068f124506e | [
"MIT"
] | null | null | null | notebooks/samples/105 - Regression with DataConversion.ipynb | tongwen11/mmlspark | 088567242e6e09a114a29a456f00b068f124506e | [
"MIT"
] | 1 | 2019-06-14T23:41:09.000Z | 2019-06-14T23:41:09.000Z | 31.056911 | 104 | 0.589529 | [
[
[
"## 105 - Training Regressions\n\nThis example notebook is similar to\n[Notebook 102](102 - Regression Example with Flight Delay Dataset.ipynb).\nIn this example, we will demonstrate the use of `DataConversion()` in two\nways. First, to convert the data type of several columns after the dataset\nhas been read in to the Spark DataFrame instead of specifying the data types\nas the file is read in. Second, to convert columns to categorical columns\ninstead of iterating over the columns and applying the `StringIndexer`.\n\nThis sample demonstrates how to use the following APIs:\n- [`TrainRegressor`\n ](http://mmlspark.azureedge.net/docs/pyspark/TrainRegressor.html)\n- [`ComputePerInstanceStatistics`\n ](http://mmlspark.azureedge.net/docs/pyspark/ComputePerInstanceStatistics.html)\n- [`DataConversion`\n ](http://mmlspark.azureedge.net/docs/pyspark/DataConversion.html)\n\nFirst, import the pandas package",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"Next, import the CSV dataset: retrieve the file if needed, save it locally,\nread the data into a pandas dataframe via `read_csv()`, then convert it to\na Spark dataframe.\n\nPrint the schema of the dataframe, and note the columns that are `long`.",
"_____no_output_____"
]
],
[
[
"dataFile = \"On_Time_Performance_2012_9.csv\"\nimport os, urllib\nif not os.path.isfile(dataFile):\n urllib.request.urlretrieve(\"https://mmlspark.azureedge.net/datasets/\"+dataFile, dataFile)\nflightDelay = spark.createDataFrame(pd.read_csv(dataFile))\n# print some basic info\nprint(\"records read: \" + str(flightDelay.count()))\nprint(\"Schema: \")\nflightDelay.printSchema()\nflightDelay.limit(10).toPandas()",
"_____no_output_____"
]
],
[
[
"Use the `DataConversion` transform API to convert the columns listed to\ndouble.\n\nThe `DataConversion` API accepts the following types for the `convertTo`\nparameter:\n* `boolean`\n* `byte`\n* `short`\n* `integer`\n* `long`\n* `float`\n* `double`\n* `string`\n* `toCategorical`\n* `clearCategorical`\n* `date` -- converts a string or long to a date of the format\n \"yyyy-MM-dd HH:mm:ss\" unless another format is specified by\nthe `dateTimeFormat` parameter.\n\nAgain, print the schema and note that the columns are now `double`\ninstead of long.",
"_____no_output_____"
]
],
[
[
"from mmlspark import DataConversion\nflightDelay = DataConversion(col=\"Quarter,Month,DayofMonth,DayOfWeek,\"\n + \"OriginAirportID,DestAirportID,\"\n + \"CRSDepTime,CRSArrTime\",\n convertTo=\"double\") \\\n .transform(flightDelay)\nflightDelay.printSchema()\nflightDelay.limit(10).toPandas()",
"_____no_output_____"
]
],
[
[
"Split the datasest into train and test sets.",
"_____no_output_____"
]
],
[
[
"train, test = flightDelay.randomSplit([0.75, 0.25])",
"_____no_output_____"
]
],
[
[
"Create a regressor model and train it on the dataset.\n\nFirst, use `DataConversion` to convert the columns `Carrier`, `DepTimeBlk`,\nand `ArrTimeBlk` to categorical data. Recall that in Notebook 102, this\nwas accomplished by iterating over the columns and converting the strings\nto index values using the `StringIndexer` API. The `DataConversion` API\nsimplifies the task by allowing you to specify all columns that will have\nthe same end type in a single command.\n\nCreate a LinearRegression model using the Limited-memory BFGS solver\n(`l-bfgs`), an `ElasticNet` mixing parameter of `0.3`, and a `Regularization`\nof `0.1`.\n\nTrain the model with the `TrainRegressor` API fit on the training dataset.",
"_____no_output_____"
]
],
[
[
"from mmlspark import TrainRegressor, TrainedRegressorModel\nfrom pyspark.ml.regression import LinearRegression\n\ntrainCat = DataConversion(col=\"Carrier,DepTimeBlk,ArrTimeBlk\",\n convertTo=\"toCategorical\") \\\n .transform(train)\ntestCat = DataConversion(col=\"Carrier,DepTimeBlk,ArrTimeBlk\",\n convertTo=\"toCategorical\") \\\n .transform(test)\nlr = LinearRegression().setSolver(\"l-bfgs\").setRegParam(0.1) \\\n .setElasticNetParam(0.3)\nmodel = TrainRegressor(model=lr, labelCol=\"ArrDelay\").fit(trainCat)\nmodel.write().overwrite().save(\"flightDelayModel.mml\")",
"_____no_output_____"
]
],
[
[
"Score the regressor on the test data.",
"_____no_output_____"
]
],
[
[
"flightDelayModel = TrainedRegressorModel.load(\"flightDelayModel.mml\")\nscoredData = flightDelayModel.transform(testCat)\nscoredData.limit(10).toPandas()",
"_____no_output_____"
]
],
[
[
"Compute model metrics against the entire scored dataset",
"_____no_output_____"
]
],
[
[
"from mmlspark import ComputeModelStatistics\nmetrics = ComputeModelStatistics().transform(scoredData)\nmetrics.toPandas()",
"_____no_output_____"
]
],
[
[
"Finally, compute and show statistics on individual predictions in the test\ndataset, demonstrating the usage of `ComputePerInstanceStatistics`",
"_____no_output_____"
]
],
[
[
"from mmlspark import ComputePerInstanceStatistics\nevalPerInstance = ComputePerInstanceStatistics().transform(scoredData)\nevalPerInstance.select(\"ArrDelay\", \"Scores\", \"L1_loss\", \"L2_loss\") \\\n .limit(10).toPandas()",
"_____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"
]
] |
ece546a9f87154777a547c20ee8f625a7561b3ca | 10,726 | ipynb | Jupyter Notebook | 14-warmup-solution_dataframe_and_series.ipynb | hanisaf/advanced-data-management-and-analytics | e7bffda5cad91374a14df1a65f95e6a25f72cc41 | [
"MIT"
] | 6 | 2020-04-13T19:22:18.000Z | 2021-04-20T18:20:13.000Z | 14-warmup-solution_dataframe_and_series.ipynb | hanisaf/advanced-data-management-and-analytics | e7bffda5cad91374a14df1a65f95e6a25f72cc41 | [
"MIT"
] | null | null | null | 14-warmup-solution_dataframe_and_series.ipynb | hanisaf/advanced-data-management-and-analytics | e7bffda5cad91374a14df1a65f95e6a25f72cc41 | [
"MIT"
] | 10 | 2020-05-12T01:02:32.000Z | 2022-02-28T17:04:37.000Z | 19.396022 | 90 | 0.440052 | [
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"population_dict = {'California': 38332521,\n 'Texas': 26448193,\n 'New York': 19651127,\n 'Florida': 19552860,\n 'Illinois': 12882135}\npopulation = pd.Series(population_dict)\npopulation",
"_____no_output_____"
]
],
[
[
"- How many entries are there in `population`\n- What are the values?\n- What is the index of the series\n- What is the population of `Florida`\n- Extract the subseries of Texas, New York, and Florida",
"_____no_output_____"
]
],
[
[
"len(population)",
"_____no_output_____"
],
[
"population.size",
"_____no_output_____"
],
[
"population.count()",
"_____no_output_____"
],
[
"list(population.values)",
"_____no_output_____"
],
[
"list(population)",
"_____no_output_____"
],
[
"population.to_list()",
"_____no_output_____"
],
[
"population.index",
"_____no_output_____"
],
[
"list(population.index)",
"_____no_output_____"
],
[
"population['Florida']",
"_____no_output_____"
],
[
"population['Texas':'Florida']",
"_____no_output_____"
],
[
"area_dict = {'California': 423967, 'Texas': 695662, 'New York': 141297,\n 'Florida': 170312, 'Illinois': 149995}\narea = pd.Series(area_dict)\narea",
"_____no_output_____"
]
],
[
[
"- Create a data frame of two columns, population and area\n- What is the index of the data frame\n- What are the columns of the data frame\n- How many entries are there in the data frame",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame( {'population':population, 'area':area } )\ndf",
"_____no_output_____"
],
[
"df.index",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"len(df.index)",
"_____no_output_____"
],
[
"len(df.columns)",
"_____no_output_____"
],
[
"len(df.index) * len(df.columns)",
"_____no_output_____"
],
[
"rows, cols = df.shape",
"_____no_output_____"
],
[
"rows * cols",
"_____no_output_____"
],
[
"len(df)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"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"
]
] |
ece557c6386cb4ddf4efe5dcfa5fe5fb26961420 | 149,751 | ipynb | Jupyter Notebook | part3/Noisy_logits.ipynb | ccha23/miml | 6a41de1c0bb41d38e3cdc6e9c27363215b7729b9 | [
"MIT"
] | 1 | 2021-08-17T15:16:11.000Z | 2021-08-17T15:16:11.000Z | part3/Noisy_logits.ipynb | ccha23/miml | 6a41de1c0bb41d38e3cdc6e9c27363215b7729b9 | [
"MIT"
] | null | null | null | part3/Noisy_logits.ipynb | ccha23/miml | 6a41de1c0bb41d38e3cdc6e9c27363215b7729b9 | [
"MIT"
] | null | null | null | 220.222059 | 89,968 | 0.892542 | [
[
[
"$$\n\\def\\abs#1{\\left\\lvert #1 \\right\\rvert}\n\\def\\Set#1{\\left\\{ #1 \\right\\}}\n\\def\\mc#1{\\mathcal{#1}}\n\\def\\M#1{\\boldsymbol{#1}}\n\\def\\R#1{\\mathsf{#1}}\n\\def\\RM#1{\\boldsymbol{\\mathsf{#1}}}\n\\def\\op#1{\\operatorname{#1}}\n\\def\\E{\\op{E}}\n\\def\\d{\\mathrm{\\mathstrut d}}\n\\DeclareMathOperator{\\Tr}{Tr}\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\n\\def\\norm#1{\\left\\lVert #1 \\right\\rVert}\n$$",
"_____no_output_____"
],
[
"# What is adversarial attack and why we care about it?",
"_____no_output_____"
],
[
"Despite the effectiveness on a variety of tasks, deep neural networks can be very vulnerable to adversarial attacks. In security-critical domains like facial recognition authorization and autonomous vehicles, such vulnerability against adversarial attacks makes the model highly unreliable. \n\nAn adversarial attack tries to add an imperceptible perturbation to the sample so that a trained neural network would classify it incorrectly. The following is an example of adversarial attack.\n\n<img src=\"https://i.loli.net/2021/08/10/ngphSTutRjLbErD.jpg\" alt=\"drawing\" width=\"400\" align=\"center\"/>\n\n",
"_____no_output_____"
],
[
"## Adversarial Attacks\n\n### Categories of Attacks\n#### Poisoning Attack and Evasion Attack\nPoisoning attacks involve manipulating the training process. The manipulation can happen on the training set (by replacing original samples or inserting fake samples) or the training algorithm itself (by changing the logic of the training algorithm). Such attacks either directly cause poor performance of the trained model or make the model fail on certain samples so as to construct a backdoor for future use.\n\nEvasion attacks aim to manipulate the benign samples $\\M x$ by a small perturbation $\\M \\delta$ so that a trained model can no longer classify it correctly. Usually, such perturbations are so small that a human observer cannot notice them. In other words, the perturbed sample \"evades\" from the classification of the model.\n\n#### Targeted Attack and Non-Targeted Attack\nA targeted attack tries to perturb the benign samples $\\M x$ so that the trained model classifies it as a given certain class $t\\in \\mc Y$. A non-targeted attack only tries to perturb the benign samples $\\M x$ so that the trained model classifies them incorrectly. \n\n#### White-Box Attack and Black-Box Attack\nFor white-box attacks, the attacker has access to all the knowledge of the targeted model. For neural networks, the attacker knows all the information about the network structure, parameters, gradients, etc. \n\nFor black-box attacks, the attacker only knows the outputs of the model when feeding inputs into it. In practice, black-box attacks usually rely on generating adversarial perturbations from another model that the attacker has full access to. \n\nBlack-box attacks are more usual in applications, but the robustness against white-box attacks is the ultimate goal of a robust model because it reveals the fundamental weakness of neuron networks. Thus, most of the study of adversarial robustness focuses on white-box, non-targeted, evasion attacks.",
"_____no_output_____"
],
[
"### Examples of White-box Attacking Algorithms\nMost white-box attacking algorithms are based on using the gradient calculated by the model to perturb the samples. Two typical examples are Fast Gradient Sign Method (FGSM) attack and its multi-step variant, Projected Gradient Descent (PGD) attack. FGSM attack generates the perturbation as\n$$\\begin{align}\n \\M \\delta = \\epsilon\\text{sgn}\\nabla_{\\M x}L(\\M x, y),\n\\end{align}$$\nwhere $\\epsilon$ controls the perturbation size. The adversarial sample is \n$$\\begin{align}\n \\M x' = \\M x + \\M \\delta.\n\\end{align}$$\nFGSM attack can be seen as trying to maximizing (single step) the loss of the model. \n\nPGD attack tries perform the same task, but in a iterative way (at the cost of higher computational time):\n$$\\begin{align}\n \\M x^{t+1} = \\Pi_{\\M x+\\epsilon}\\left(\\M x^t + \\alpha\\text{sgn}\\nabla_{\\M x}L(\\M x, y)\\right),\n\\end{align}$$\nwhere $\\alpha$ is the step size. $\\M x^t$ denote the generated adversarial sample in step $t$, with $\\M x^0$ being the original sample. $\\Pi$ refers to a projection operation that clips the generated adversarial sample into the valid region: the $\\epsilon$-ball around $\\M x$, which is $\\{\\M x':\\norm{\\M x'-\\M x}\\leq \\epsilon \\}$.\n\nIn practice, a PGD attack with a relatively small adversarial power $\\epsilon$ (small enough to be neglected by human observers) is able to reduce the accuracy of a well-trained model to nearly zero. Because of such effectiveness, researchers often use PGD attacks as a basic check of the adversarial robustness of their models.\n",
"_____no_output_____"
],
[
"#### Implementation of FGSM attack",
"_____no_output_____"
]
],
[
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# NOTE: This is a hack to get around \"User-agent\" limitations when downloading MNIST datasets\n# see, https://github.com/pytorch/vision/issues/3497 for more information\nfrom six.moves import urllib\nopener = urllib.request.build_opener()\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\nurllib.request.install_opener(opener)",
"_____no_output_____"
]
],
[
[
"##### Inputs\n- **epsilons** - List of epsilon values to use for the run. It is\n important to keep 0 in the list because it represents the model\n performance on the original test set. Also, intuitively we would\n expect the larger the epsilon, the more noticeable the perturbations\n but the more effective the attack in terms of degrading model\n accuracy. Since the data range here is $[0,1]$, no epsilon\n value should exceed 1.\n\n- **pretrained_model** - path to the pretrained MNIST model which was\n trained with [pytorch/examples/mnist ](https://github.com/pytorch/examples/tree/master/mnist).\n For simplicity, download the pretrained model [here](https://drive.google.com/drive/folders/1fn83DF14tWmit0RTKWRhPq5uVXt73e0h?usp=sharing).\n\n- **use_cuda** - boolean flag to use CUDA if desired and available.\n Note, a GPU with CUDA is not critical for this tutorial as a CPU will\n not take much time.",
"_____no_output_____"
]
],
[
[
"epsilons = [0, .05, .1, .15, .2, .25, .3]\npretrained_model = \"lenet_mnist_model.pth\"\nuse_cuda=True",
"_____no_output_____"
]
],
[
[
"##### Model Under Attack\n\nAs mentioned, the model under attack is the same MNIST model from\n[pytorch/examples/mnist](https://github.com/pytorch/examples/tree/master/mnist).\nYou may train and save your own MNIST model or you can download and use\nthe provided model. The *Net* definition and test dataloader here have\nbeen copied from the MNIST example. The purpose of this section is to\ndefine the model and dataloader, then initialize the model and load the\npretrained weights.\n",
"_____no_output_____"
]
],
[
[
"# LeNet Model definition\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, 10)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 320)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)\n\n# MNIST Test dataset and dataloader declaration\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, download=True, transform=transforms.Compose([\n transforms.ToTensor(),\n ])), \n batch_size=1, shuffle=True)\n\n# Define what device we are using\nprint(\"CUDA Available: \",torch.cuda.is_available())\ndevice = torch.device(\"cuda\" if (use_cuda and torch.cuda.is_available()) else \"cpu\")\n\n# Initialize the network\nmodel = Net().to(device)\n\n# Load the pretrained model\nmodel.load_state_dict(torch.load(pretrained_model, map_location='cpu'))\n\n# Set the model in evaluation mode. In this case this is for the Dropout layers\nmodel.eval()",
"CUDA Available: True\n"
]
],
[
[
"##### FGSM Attack\n\nNow, we can define the function that creates the adversarial examples by\nperturbing the original inputs. The ``fgsm_attack`` function takes three\ninputs, *image* is the original clean image ($x$), *epsilon* is\nthe pixel-wise perturbation amount ($\\epsilon$), and *data_grad*\nis gradient of the loss w.r.t the input image\n($\\nabla_{x} L(\\mathbf{\\theta}, \\mathbf{x}, y)$). The function\nthen creates perturbed image as\n\n\\begin{align}perturbed\\_image = image + epsilon*sign(data\\_grad) = x + \\epsilon * sign(\\nabla_{x} L(\\mathbf{\\theta}, \\mathbf{x}, y))\\end{align}\n\nFinally, in order to maintain the original range of the data, the\nperturbed image is clipped to range $[0,1]$.\n",
"_____no_output_____"
]
],
[
[
"# FGSM attack code\ndef fgsm_attack(image, epsilon, data_grad):\n # Collect the element-wise sign of the data gradient\n sign_data_grad = data_grad.sign()\n # Create the perturbed image by adjusting each pixel of the input image\n perturbed_image = image + epsilon*sign_data_grad\n # Adding clipping to maintain [0,1] range\n perturbed_image = torch.clamp(perturbed_image, 0, 1)\n # Return the perturbed image\n return perturbed_image",
"_____no_output_____"
]
],
[
[
"##### Testing Function\n\nFinally, the central result of this tutorial comes from the ``test``\nfunction. Each call to this test function performs a full test step on\nthe MNIST test set and reports a final accuracy. However, notice that\nthis function also takes an *epsilon* input. This is because the\n``test`` function reports the accuracy of a model that is under attack\nfrom an adversary with strength $\\epsilon$. More specifically, for\neach sample in the test set, the function computes the gradient of the\nloss w.r.t the input data ($data\\_grad$), creates a perturbed\nimage with ``fgsm_attack`` ($perturbed\\_data$), then checks to see\nif the perturbed example is adversarial. In addition to testing the\naccuracy of the model, the function also saves and returns some\nsuccessful adversarial examples to be visualized later.\n",
"_____no_output_____"
]
],
[
[
"def test( model, device, test_loader, epsilon ):\n\n # Accuracy counter\n correct = 0\n adv_examples = []\n\n # Loop over all examples in test set\n for data, target in test_loader:\n\n # Send the data and label to the device\n data, target = data.to(device), target.to(device)\n\n # Set requires_grad attribute of tensor. Important for Attack\n data.requires_grad = True\n\n # Forward pass the data through the model\n output = model(data)\n init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n\n # If the initial prediction is wrong, dont bother attacking, just move on\n if init_pred.item() != target.item():\n continue\n\n # Calculate the loss\n loss = F.nll_loss(output, target)\n\n # Zero all existing gradients\n model.zero_grad()\n\n # Calculate gradients of model in backward pass\n loss.backward()\n\n # Collect datagrad\n data_grad = data.grad.data\n\n # Call FGSM Attack\n perturbed_data = fgsm_attack(data, epsilon, data_grad)\n\n # Re-classify the perturbed image\n output = model(perturbed_data)\n\n # Check for success\n final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n if final_pred.item() == target.item():\n correct += 1\n # Special case for saving 0 epsilon examples\n if (epsilon == 0) and (len(adv_examples) < 5):\n adv_ex = perturbed_data.squeeze().detach().cpu().numpy()\n adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )\n else:\n # Save some adv examples for visualization later\n if len(adv_examples) < 5:\n adv_ex = perturbed_data.squeeze().detach().cpu().numpy()\n adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )\n\n # Calculate final accuracy for this epsilon\n final_acc = correct/float(len(test_loader))\n print(\"Epsilon: {}\\tTest Accuracy = {} / {} = {}\".format(epsilon, correct, len(test_loader), final_acc))\n\n # Return the accuracy and an adversarial example\n return final_acc, adv_examples",
"_____no_output_____"
]
],
[
[
"##### Run Attack\n\nThe last part of the implementation is to actually run the attack. Here,\nwe run a full test step for each epsilon value in the *epsilons* input.\nFor each epsilon we also save the final accuracy and some successful\nadversarial examples to be plotted in the coming sections. Notice how\nthe printed accuracies decrease as the epsilon value increases. Also,\nnote the $\\epsilon=0$ case represents the original test accuracy,\nwith no attack.\n",
"_____no_output_____"
]
],
[
[
"accuracies = []\nexamples = []\n\n# Run test for each epsilon\nfor eps in epsilons:\n acc, ex = test(model, device, test_loader, eps)\n accuracies.append(acc)\n examples.append(ex)",
"Epsilon: 0\tTest Accuracy = 9810 / 10000 = 0.981\nEpsilon: 0.05\tTest Accuracy = 9426 / 10000 = 0.9426\nEpsilon: 0.1\tTest Accuracy = 8510 / 10000 = 0.851\nEpsilon: 0.15\tTest Accuracy = 6826 / 10000 = 0.6826\nEpsilon: 0.2\tTest Accuracy = 4303 / 10000 = 0.4303\nEpsilon: 0.25\tTest Accuracy = 2087 / 10000 = 0.2087\nEpsilon: 0.3\tTest Accuracy = 871 / 10000 = 0.0871\n"
]
],
[
[
"##### Results\n\nAccuracy vs Epsilon\n\nThe first result is the accuracy versus epsilon plot. As alluded to\nearlier, as epsilon increases we expect the test accuracy to decrease.\nThis is because larger epsilons mean we take a larger step in the\ndirection that will maximize the loss. Notice the trend in the curve is\nnot linear even though the epsilon values are linearly spaced. For\nexample, the accuracy at $\\epsilon=0.05$ is only about 4% lower\nthan $\\epsilon=0$, but the accuracy at $\\epsilon=0.2$ is 25%\nlower than $\\epsilon=0.15$. Also, notice the accuracy of the model\nhits random accuracy for a 10-class classifier between\n$\\epsilon=0.25$ and $\\epsilon=0.3$.\n",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(5,5))\nplt.plot(epsilons, accuracies, \"*-\")\nplt.yticks(np.arange(0, 1.1, step=0.1))\nplt.xticks(np.arange(0, .35, step=0.05))\nplt.title(\"Accuracy vs Epsilon\")\nplt.xlabel(\"Epsilon\")\nplt.ylabel(\"Accuracy\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"##### Sample Adversarial Examples\n\nRemember the idea of no free lunch? In this case, as epsilon increases\nthe test accuracy decreases **BUT** the perturbations become more easily\nperceptible. In reality, there is a tradeoff between accuracy\ndegredation and perceptibility that an attacker must consider. Here, we\nshow some examples of successful adversarial examples at each epsilon\nvalue. Each row of the plot shows a different epsilon value. The first\nrow is the $\\epsilon=0$ examples which represent the original\n“clean” images with no perturbation. The title of each image shows the\n“original classification -> adversarial classification.” Notice, the\nperturbations start to become evident at $\\epsilon=0.15$ and are\nquite evident at $\\epsilon=0.3$. However, in all cases humans are\nstill capable of identifying the correct class despite the added noise.\n\n\n",
"_____no_output_____"
]
],
[
[
"# Plot several examples of adversarial samples at each epsilon\ncnt = 0\nplt.figure(figsize=(8,10))\nfor i in range(len(epsilons)):\n for j in range(len(examples[i])):\n cnt += 1\n plt.subplot(len(epsilons),len(examples[0]),cnt)\n plt.xticks([], [])\n plt.yticks([], [])\n if j == 0:\n plt.ylabel(\"Eps: {}\".format(epsilons[i]), fontsize=14)\n orig,adv,ex = examples[i][j]\n plt.title(\"{} -> {}\".format(orig, adv))\n plt.imshow(ex, cmap=\"gray\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Adversarial Training with Perturbed Examples\nTo defend adversarial attacks, a direct idea is to add perturbations during the training process. Mardy et al. \\cite{madry2017} proposed to formulate a robust optimization problem to minimize the adversarial risk instead of the usual empirical risk:\n$$\\begin{align}\n \\min_{\\theta} \\E_{(\\M x, y)\\in \\mc D} \\left[\\max_{\\norm{\\M\\delta}_p<\\epsilon}L(\\M x+\\M\\delta, y)\\right].\n\\end{align}$$\nThe inner maximization tries to find perturbed samples that produce a high loss, which is also the goal of PGD attacks. The outer minimization problem tries to find the model parameters that minimize the adversarial loss given by the inner adversaries. \n\nThis robust optimization approach effectively trains more robust models. It has been a benchmark for evaluating the adversarial robustness of models and is often seen as the standard way of adversarial training. Based on this method, many variants were proposed in the following years. They involve using a more sophisticated regularizer or adaptively adjusting the adversarial power. Those methods that add perturbations during training share a common disadvantage of high computational cost.",
"_____no_output_____"
],
[
"## Adversarial Training with Stochastic Networks\nStochastic networks refer to the neuron networks that involve random noise layers. Liu et al. proposed Random Self Ensemble (RSE). Their method injects spherical Gaussian noise into different layers of a network and uses the ensemble of multiple forward pass as the final output. The variance of their added noise is treated as a hyper-parameter to be tuned. RSE shows good robustness against PGD attack and C\\&W attack. \n\nSimilar to RSE, He et al. proposed Parametric Noise Injection (PNI). Rather than fixed variance, they applied an additional intensity parameter to control the variance of the noise. This intensity parameter is trained together with the model parameters. \n\nInspired by the idea of trainable noise, Eustratiadis et al. proposed Weight-Covariance Alignment (WCA) method \\cite{wca}. This method adds trainable Gaussian noise to the activation of the penultimate layer of the network. Let $\\M g_{\\theta}:\\mathcal X\\rightarrow \\mathbb R^D$ be the neural network parameterized by $\\theta$ except the final layer and $f_{\\M W, \\M b}:\\mathbb R^D \\rightarrow \\mathbb R^K$ be the final linear layer parameterized by weight matrix $\\M W^{K\\times D}$ and bias vector $\\M b^{K\\times 1}$, where $K=\\abs{\\mc Y}$ is the number of classes . This WCA method adds a Gaussian noise $\\M u \\sim \\mathcal N_{0, \\M\\Sigma}$ to the output of penultimate layer $\\M g_{\\theta}(x)$, where $\\M\\Sigma^{D\\times D}$ is the covariance matrix. Thus, the final output becomes\n $$\\begin{align}\n f_{\\M W, \\M b}\\left(\\M g_\\theta(\\M x)\\right) = \\M W\\left(\\M g_\\theta (\\M x)+\\M u\\right) + \\M b.\n \\end{align}$$\n \nThe loss function is defined as\n $$\\begin{align}\n L=L_{\\text{CE}} + L_{\\text{WCA}}+ \\lambda \\sum_{y\\in \\mathcal{Y}}\\M W_y^{\\intercal} \\M W_y,\n \\end{align}$$\nwhere $L_{\\text{CE}}$ is the usual cross-entropy loss, and $L_{\\text{WCA}}$ is a term that encourage the noise and the weight of last layer to be aligned with each other. The third term is gives $l^2$ penalty to $\\M W_y$ with large magnitude. The WCA regularizer is defined as\n $$\\begin{align}\n L_{\\text{WCA}} = -\\log\\sum_{y\\in \\mathcal{Y}}\\M W_y \\M\\Sigma\\M W_y^\\intercal .\n \\end{align}$$\nwhere $\\M W_y$ is the weight vector of the last layer that is associated with class $y$. \n\nThe WCA regularizer encourages the weights associated with the last layer to be well aligned with the covariance matrix of the noise. Larger trained variance corresponding to one feature means this feature is harder to perturb, so putting more weight on such features will force the final layer to focus more on these robust features. \n\nModels trained with WCA show better performance against PGD attacks on various datasets comparing with the aforementioned approaches. In addition, because of the fact that WCA does not involve generating adversarial samples, the computational time is significantly lower than adversarial training with perturbations. The method we propose is inspired by this WCA method. But instead of adding noise to the penultimate layer, we directly add noise to the output of the final layer.",
"_____no_output_____"
],
[
"## Training a neural network with noisy logits",
"_____no_output_____"
],
[
"We consider training a model with a noisy representation $\\R{Z}$ satisfying the Markov chain:\n\n$$\\R{X}\\to \\R{Z} \\to \\hat{\\R{Y}}$$\n\nHence, the estimate for $P_{\\R{Y}|\\R{X}}$ is given by $P_{\\R{Y}|\\R{Z}}$ and $P_{\\R{Z}|\\R{X}}$ as\n$$P_{\\hat{\\R{Y}}|\\R{X}} (y|x) = E\\left[\\left.P_{\\hat{\\R{Y}}|\\R{Z}}(y|\\R{Z}) \\right|\\R{X}=x\\right].$$\n",
"_____no_output_____"
],
[
"In particular, we propose to set $\\R{Z}$ to be the noisy logits of $\\hat{\\R{Y}}$, i.e.,\n$P_{\\hat{Y}|\\R{Z}}$ is defined by the pmf obtained with the usual softmax function\n$$\np_{\\hat{\\R{Y}}|\\RM{z}} (y|\\M{z}) := \\frac{\\exp(z_y)}{\\sum_{y'\\in \\mathcal{Y}} \\exp(z_{y'})},\n$$\nso $z_y$ is the logit for class $y$.",
"_____no_output_____"
],
[
"The noisy logit is defined as\n$$\n\\R{Z} = \\RM{z}:=[g(y|\\R{X})+\\R{u}_y]_{y\\in \\mathcal{Y}}\n$$\nwhere\n$$g(y|x)\\in \\mathbb{R}$$\nfor $(x,y)\\in \\mathcal{X}\\times \\mathcal{Y}$\nis computed by a neural network to be trained, and $\\R{u}_y\\sim \\mathcal{N}_{0,\\sigma_y^2}$ for $y\\in \\mathcal{Y}$ are independent gaussian random variables with variance $\\sigma_y^2>0$. For simplicity, \n$$\n$$\\begin{align}\n\\M{g}(x)&:= [g(y|x)]_{y\\in \\mathcal{Y}}\\\\\n\\RM{u}&:=[\\R{u}_y]_{y\\in \\mathcal{Y}}\\\\\n\\M{\\Sigma}&:=\\M{\\sigma} \\M{I} \\M{\\sigma}^\\intercal \\quad \\text{with }\\M{\\sigma}:=[\n\\sigma_y]_{y\\in \\mathcal{Y}},\n\\end{align}$$\n$$ which are referred to as the (noiseless) logits, additive noise (vector) and its (diagonal) covariance matrix respectively. Hence, $P_{\\R{Z}|\\R{X}}$ is defined by the multivariate gaussian density function\n$$\np_{\\RM{z}|\\R{X}}(\\M{z}|x) = \\mathcal{N}_{\\M{g}(x),\\Sigma}(\\M{z})\n$$\nfor $x\\in \\mathcal{X}$ and $\\M{z}\\in \\mathbb{R}^{\\abs{\\mathcal{Y}}}$. ",
"_____no_output_____"
],
[
"The loss function used for training the neural network is derived from\n\n$$\nL := E\\left[-\\log p_{\\hat{\\R{Y}}|\\R{X}}(\\R{Y}|\\R{X})\\right] - \\log \\sum_{y\\in \\mathcal{Y}}\\sigma_y^2 + \\lambda\\left(\\sum_{y\\in \\mathcal{Y}}\\sigma_y^2\\right)\n$$\n",
"_____no_output_____"
]
]
] | [
"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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
ece55ad3c537ba0a4f8bd6386cd3306e302969c8 | 822,259 | ipynb | Jupyter Notebook | notebooks/Climate_Velocities/oa_vel_10decades.ipynb | chazbethelbrescia/pei2020 | a031da26fbbca9fcf06a17ac15a54e1e83569661 | [
"MIT"
] | null | null | null | notebooks/Climate_Velocities/oa_vel_10decades.ipynb | chazbethelbrescia/pei2020 | a031da26fbbca9fcf06a17ac15a54e1e83569661 | [
"MIT"
] | null | null | null | notebooks/Climate_Velocities/oa_vel_10decades.ipynb | chazbethelbrescia/pei2020 | a031da26fbbca9fcf06a17ac15a54e1e83569661 | [
"MIT"
] | null | null | null | 889.890693 | 146,956 | 0.951711 | [
[
[
"# Decadal Omega Aragonite Velocity (21st Century)\n# (Surface irr 0.1 W/m^2)",
"_____no_output_____"
]
],
[
[
"import xgcm\nimport xarray as xr\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import cm\nimport matplotlib.colors as mcolors\nfrom matplotlib.patches import Patch\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\nfrom matplotlib import pyplot as plt\nfrom matplotlib import gridspec\nfrom cartopy import crs as ccrs\nimport cartopy.feature as cfeature",
"_____no_output_____"
],
[
"%matplotlib inline",
"_____no_output_____"
],
[
"%reload_ext autoreload\n%autoreload 2\nfrom chazbpei2020.preprocessing import *",
"_____no_output_____"
]
],
[
[
"## RCP85 Ensemble Average",
"_____no_output_____"
]
],
[
[
"# irr0.1 Omega Arag for ensemble average (preprocessed)\ndirectory = '~/chazbpei2020/data/processed/Omega_Arag/RCP85/'\nfilename = 'omega_arag_irr_0.1Wm2_ensAvg_1950_2100.nc'\noa_path = directory+filename\nds = xr.open_dataset(oa_path).rename({'XT_OCEAN': 'xt_ocean',\n 'YT_OCEAN': 'yt_ocean',\n 'TIME': 'time',\n 'OMEGA_ARAG_IRR': 'omega_arag'})",
"_____no_output_____"
]
],
[
[
"## Grid calculations",
"_____no_output_____"
]
],
[
[
"# default behavior is to extrapolite grid position to the left\nds_full = xgcm.generate_grid_ds(ds, {'X':'xt_ocean', 'Y':'yt_ocean'})",
"_____no_output_____"
],
[
"# Create grid object (periodic along X-axis)\ngrid = xgcm.Grid(ds_full, periodic=['X'], \n coords={'X': {'center': 'xt_ocean', 'left': 'xt_ocean_left'},\n 'Y': {'center': 'yt_ocean', 'left': 'yt_ocean_left'},\n 'T': {'center': 'time'}})",
"_____no_output_____"
],
[
"# Compute cartesian distances\ngrid_calculations(grid, ds_full)",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## Decadal Mean Omega Arag",
"_____no_output_____"
]
],
[
[
"# Calculate the time-mean Omega Arag for 10 decades of simulation\n# 2000s through 2090s labeled 0-9\nda_oa_annual = ds_full.omega_arag.groupby('time.year').mean(dim='time', skipna=True)\nda_oa_mean = []\n\ndecade = 2000\nfor i in range(10):\n dec_mean = decadal_mean(da_oa_annual, decade)\n da_oa_mean.append(dec_mean)\n decade += 10",
"/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/common.py:671: FutureWarning: This DataArray contains multi-dimensional coordinates. In the future, the dimension order of these coordinates will be restored as well unless you specify restore_coord_dims=False.\n return self._groupby_cls(\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## Zonal Gradient of Mean Omega Arag (ºC / km)",
"_____no_output_____"
]
],
[
[
"# Compute zonal (along x-axis) gradient of irr0.1 Omega Arag\ndoa_dx = []\nfor i in range(10):\n x_grad = grid.diff(da_oa_mean[i], 'X', boundary='fill', \n fill_value=np.nan) / (ds_full.dxg / 1000).squeeze()\n doa_dx.append(x_grad)",
"_____no_output_____"
]
],
[
[
"## Meridional Gradient Omega Arag (ºC / km)",
"_____no_output_____"
]
],
[
[
"# Compute meridional (along y-axis) gradient of irr0.1 Omega Arag\ndoa_dy = []\nfor i in range(10):\n y_grad = grid.diff(da_oa_mean[i], 'Y', boundary='fill',\n fill_value=np.nan) / (ds_full.dyg / 1000).squeeze()\n # Flip direction in southern hemisphere so directions are poleward\n y_grad[0:90] = -y_grad[0:90]\n doa_dy.append(y_grad)",
"_____no_output_____"
]
],
[
[
"## Gradient Magnitude of Omega Arag (ºC / km)",
"_____no_output_____"
]
],
[
[
"# Calculate magnitude of spatial gradients\n# Create datasets for each decade\nlon = ds_full.xt_ocean.data\nlat = ds_full.yt_ocean.data\ndoa_ds = []\nfor i in range(10):\n dx2 = np.square(doa_dx[i]).data\n dy2 = np.square(doa_dy[i]).data\n grad = np.sqrt(dx2+dy2)\n gradient = xr.DataArray(grad, dims=['yt_ocean','xt_ocean'], coords=[lat,lon])\n doa_ds.append(gradient)",
"_____no_output_____"
]
],
[
[
"### Regular Plot",
"_____no_output_____"
]
],
[
[
"# Plot Omega Arag gradient for each decade\ncrs = ccrs.Robinson(central_longitude=180)\nsrc=ccrs.PlateCarree()\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[16,6],\n subplot_kw={'projection':crs})\n\ndecade = 2000\nfor row in range(nrows):\n for col in range(ncols):\n ax = axs[row,col]\n clevs = np.arange(0, 2.01e-3, 5e-4)\n doa_ds[row*5 + col].plot(ax=ax, levels=clevs, transform=src, robust=True)\n ax.set_title(str(decade)+'s Gradient')\n ax.set_global()\n decade += 10\n\nfig.suptitle('RCP85 Ensemble Average, Gradient of irr0.1 $\\Omega$ Arag ($\\Omega$ / km)',\n fontsize=22)\nfig.savefig(\"./oa_vel_10figs/oa_gradient_decadal_10\")",
"_____no_output_____"
]
],
[
[
"### Latitudinal Mean Gradient",
"_____no_output_____"
]
],
[
[
"# Plot latitudinal mean zonal irr0.1 Omega Arag gradient\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[12,8], \n sharex=True, sharey=True)\n\ndecade = 2000\nfor row in range(nrows):\n for col in range(ncols):\n ax = axs[row,col]\n i = row*5 + col\n X = doa_ds[i].mean(dim='xt_ocean', skipna=True).squeeze()[5:175]\n Y = doa_ds[i]['yt_ocean'][5:175]\n ax.plot(X,Y,'r')\n ax.set_title(str(decade)+'s',loc='center',fontsize=14)\n ax.set_ylim(-90,90)\n ax.set_xlim(0,1.51e-3)\n ax.set_ylabel('Latitude')\n ax.set_xlabel('Gradient ($\\Omega$/km)')\n ax.set_yticks(np.arange(-90,91,30))\n ax.set_xticks(np.arange(0,1.51e-3,5e-4))\n # Only label outer axes\n ax.label_outer()\n ax.ticklabel_format(axis='x', style='sci', scilimits=[0,0])\n\n decade += 10\n\nfig.suptitle('RCP85 Ensemble Average, Zonal Gradient of irr0.1 $\\Omega$ Arag ($\\Omega$ / km)',\n fontsize=20)\nfig.savefig(\"./oa_vel_10figs/oa_gradient_stats_10\")",
"/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n"
]
],
[
[
"### Contour Plot",
"_____no_output_____"
]
],
[
[
"# Plot Omega Arag gradient for each decade -- Contour Plot\ncrs = ccrs.Robinson(central_longitude=180)\nsrc=ccrs.PlateCarree()\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[16,5],\n subplot_kw={'projection':crs})\n\ndecade = 2000\nclevs = np.arange(0, 2.1e-3, 2e-4)\nfor row in range(nrows):\n for col in range(ncols):\n ax = axs[row,col]\n i = row*5 + col\n im = ax.contourf(lon,lat,doa_ds[i].data,levels=clevs, \n transform=src, robust=True)\n ax.set_title(str(decade)+'s Gradient')\n if col==ncols-1:\n cbar = plt.colorbar(im,ax=ax,orientation='vertical',fraction=0.05,pad=0.05)\n cbar.set_label('$\\Omega$ Arag Gradient')\n decade += 10\n\nfig.suptitle('RCP85 Ensemble Average, irr0.1 $\\Omega$ Arag Gradient ($\\Omega$ / km)',\n fontsize=22)\nfig.savefig(\"./oa_vel_10figs/oa_gradient_decadal_10\")",
"/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/cartopy/mpl/geoaxes.py:1508: UserWarning: The following kwargs were not used by contour: 'robust'\n result = matplotlib.axes.Axes.contourf(self, *args, **kwargs)\n"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## irr0.1 Omega Arag Change",
"_____no_output_____"
],
[
"### Decadal Omega Arag Change (ºC / decade)",
"_____no_output_____"
],
[
"### Calculate Using Linear Regression (best model)",
"_____no_output_____"
]
],
[
[
"# If Datasets are already saved\ndecade = 2000\ndoa_dt = []\nfor i in range(10):\n oa_path = './delta_omega_arag_irr/'+str(decade)+'s'\n da_decade = xr.open_dataarray(oa_path).T\n doa_dt.append(da_decade)\n decade+=10",
"_____no_output_____"
]
],
[
[
"### Regular Plot",
"_____no_output_____"
]
],
[
[
"# Plot decadal Omega Arag change using best-fit linear model\ncrs = ccrs.Robinson(central_longitude=180)\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[16,6],\n subplot_kw={'projection':crs})\n\ndecade = 2000\nclevs=np.arange(-0.6,0.6,0.1)\nfor row in range(nrows):\n for col in range(ncols):\n ax = axs[row,col]\n doa_dt[row*5+col].plot(ax=ax, cmap='plasma', levels=clevs,\n transform=ccrs.PlateCarree(), robust=True)\n ax.set_title(str(decade)+'s $\\Delta$ $\\Omega$Arag')\n decade+=10\n\nfig.suptitle('RCP85 Ensemble Average, irr0.1 $\\Delta$$\\Omega$ Arag ($\\Omega$ / decade)',\n fontsize=22)\nfig.savefig(\"./oa_vel_10figs/oa_change_decadal_10\")",
"_____no_output_____"
]
],
[
[
"### Contour Plot",
"_____no_output_____"
]
],
[
[
"# Plot decadal Omega Arag change using best-fit linear model\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[16,5],\n subplot_kw={'projection':crs})\n\ndecade = 2000\n# clevs=[-1.0, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4]\nclevs = np.arange(-0.6, 0.6, 0.1)\nfor row in range(nrows):\n for col in range(ncols):\n ax = axs[row,col]\n i = row*5 + col\n im = ax.contourf(lon,lat, doa_dt[i], levels=clevs, cmap='plasma',\n transform=src, robust=True)\n ax.set_title(str(decade)+'s $\\Delta$ $\\Omega$Arag')\n if col==ncols-1:\n cbar = plt.colorbar(im,ax=ax,orientation='vertical',fraction=0.05,pad=0.05)\n cbar.set_label('$\\Delta$ $\\Omega$ Arag ($\\Omega$ / decade)')\n decade+=10\n\nfig.suptitle('RCP85 Ensemble Average, irr0.1 $\\Delta$$\\Omega$ Arag ($\\Omega$ / decade)',\n fontsize=22)\nfig.savefig(\"./oa_vel_10figs/oa_change_decadal_10\")",
"_____no_output_____"
]
],
[
[
"### Latitudinal Mean Omega Arag Change",
"_____no_output_____"
]
],
[
[
"# Plot latitudinal mean zonal irr0.1 Omega Arag Change\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[12,8], \n sharex=True, sharey=True)\n\ndecade = 2000\nfor row in range(nrows):\n for col in range(ncols):\n ax = axs[row,col]\n i = row*5 + col\n X = doa_dt[i].mean(dim='xt_ocean', skipna=True).squeeze()[5:175]\n Y = doa_dt[i]['yt_ocean'][5:175]\n ax.plot(X,Y,'r')\n ax.set_title(str(decade)+'s',loc='center',fontsize=14)\n ax.set_ylim(-90,90)\n ax.set_xlim(-0.2, 0.05)\n ax.set_yticks(np.arange(-90,91,30))\n ax.set_xticks(np.arange(-0.2, 0.05, 0.1))\n ax.set_ylabel('Latitude')\n ax.set_xlabel('$\\Delta$ $\\Omega$ Arag ($\\Omega$ / decade)')\n # Only label outer axes\n ax.label_outer()\n decade += 10\n \n\nfig.suptitle('RCP85 Ensemble Average, Mean Zonal $\\Delta$ $\\Omega$ Arag at irr0.1 ($\\Omega$ / km)',\n fontsize=20)\nfig.savefig(\"./oa_vel_10figs/oa_change_stats_10\")",
"/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n"
]
],
[
[
"---",
"_____no_output_____"
],
[
"## Zonal k01 Omega Arag Velocity (km/decade)",
"_____no_output_____"
]
],
[
[
"# Calculate zonal Omega Arag velocity\n# Using linear regression over each decade for Omega Arag change over time,\n# and time-mean decadal Omega Arag for spatial gradient\nx_velocity = []\nfor i in range(10):\n dOA_dt = doa_dt[i].squeeze().T.data\n dOA_dx = doa_dx[i].squeeze().T.data\n x_vel = dOA_dt/dOA_dx\n\n # Create DataArray\n x_vel = xr.DataArray(x_vel, dims=['xt_ocean','yt_ocean'], coords=[lon,lat]).T\n x_vel = x_vel.where(x_vel.loc[:,:] < np.inf)\n x_velocity.append(x_vel)",
"/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/dataarray.py:1924: FutureWarning: This DataArray contains multi-dimensional coordinates. In the future, these coordinates will be transposed as well unless you specify transpose_coords=False.\n return self.transpose()\n<ipython-input-19-4fde45925f6b>:8: RuntimeWarning: divide by zero encountered in true_divide\n x_vel = dOA_dt/dOA_dx\n"
]
],
[
[
"## Meridional Omega Arag Velocity (km/decade)",
"_____no_output_____"
]
],
[
[
"# Calculate meridional Omega Arag velocity\n# Using linear regression over each decade for Omega Arag change over time,\n# and time-mean decadal Omega Arag for spatial gradient\ny_velocity = []\nfor i in range(10):\n dOA_dt = doa_dt[i].squeeze().T.data\n dOA_dy = doa_dy[i].squeeze().T.data\n y_vel = dOA_dt/dOA_dy\n\n # Create DataArray\n y_vel = xr.DataArray(y_vel, dims=['xt_ocean','yt_ocean'], coords=[lon,lat]).T\n y_vel = y_vel.where(y_vel.loc[:,:] != np.inf)\n y_velocity.append(y_vel)",
"<ipython-input-20-88471d1031d0>:8: RuntimeWarning: divide by zero encountered in true_divide\n y_vel = dOA_dt/dOA_dy\n<ipython-input-20-88471d1031d0>:8: RuntimeWarning: divide by zero encountered in true_divide\n y_vel = dOA_dt/dOA_dy\n"
]
],
[
[
"## Omega Arag Velocity (km/decade)",
"_____no_output_____"
]
],
[
[
"# Calculate the magnitude for Omega Arag velocity \nlon = ds_full.xt_ocean.data\nlat = ds_full.yt_ocean.data\nvelocity = []\nfor i in range(10):\n # Calculate the magnitude for Omega Arag velocity \n dOA_dt = doa_dt[i].squeeze().T.data\n dOA_ds = doa_ds[i].squeeze().T.data\n vel = abs(dOA_dt/dOA_ds)\n\n # Create DataArray\n vel = xr.DataArray(vel, dims=['xt_ocean','yt_ocean'], coords=[lon,lat], name='velocity').T\n vel = vel.where(vel.loc[:,:] != np.inf)\n velocity.append(vel)",
"_____no_output_____"
]
],
[
[
"### Regular Plot",
"_____no_output_____"
]
],
[
[
"# Plot Omega Arag velocity magnitude (km/decade) for each decade\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[16,5],\n subplot_kw={'projection':crs})\ndecade = 2000\nfor row in range(nrows):\n for col in range(ncols):\n clevs = [0,25,50,100,250,500,1000,2500,5000]\n ax = axs[row,col]\n velocity[row*5 + col].plot(ax=ax, levels=clevs, cmap='rainbow',\n transform=src, robust=True)\n ax.set_title(str(decade)+'s')\n decade+=10\n \nfig.suptitle('RCP85 Ensemble Average, irr0.1 $\\Omega$ Arag Velocity (km / decade)',\n fontsize=20)\nfig.savefig(\"./oa_vel_10figs/oa_vel_decadal_10\")",
"_____no_output_____"
]
],
[
[
"### Latitudinal Mean Velocity",
"_____no_output_____"
]
],
[
[
"# Plot latitudinal mean irr0.1 Omega Arag Velocity\ncrs = ccrs.Robinson(central_longitude=180)\nnrows=2\nncols=5\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=[12,8], \n sharex=True, sharey=True)\n\ndecade = 2000\nfor row in range(nrows):\n for col in range(ncols):\n ax = axs[row,col]\n i = row*5 + col\n X = velocity[i].mean(dim='xt_ocean', skipna=True).squeeze()[5:175]\n Y = velocity[i]['yt_ocean'][5:175]\n ax.plot(X,Y,'r')\n ax.set_title(str(decade)+'s',fontsize=14)\n ax.set_ylim(-90,90)\n ax.set_xlim(0, 2.5e3)\n ax.set_ylabel('Latitude',fontsize=14)\n ax.set_xlabel('Velocity (km/dec)')\n ax.set_yticks(np.arange(-90,91,30))\n ax.set_xticks(np.arange(0,2001,1000))\n # Only label outer axes\n ax.label_outer()\n# ax.ticklabel_format(axis='x', style='sci', scilimits=[0,0])\n\n decade += 10\n\nfig.suptitle('RCP85 Ensemble Average, Zonal $\\Omega$ Arag Velocity by Decade', \n fontsize=20)\nfig.savefig(\"./oa_vel_10figs/oa_vel_stats_10\")",
"/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n/home/aos/chazb/miniconda3/envs/chazbpei2020/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice\n return np.nanmean(a, axis=axis, dtype=dtype)\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece561ee39fc967cc6dc26d3cedd7f9a126c9c41 | 9,971 | ipynb | Jupyter Notebook | docs/examples/pytorch/pytorch-various-readers.ipynb | paulbisso/DALI | e5ebc9a6185facfae43dafd4098c43d192a6292e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | docs/examples/pytorch/pytorch-various-readers.ipynb | paulbisso/DALI | e5ebc9a6185facfae43dafd4098c43d192a6292e | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-12-21T21:47:50.000Z | 2018-12-21T21:47:50.000Z | docs/examples/pytorch/pytorch-various-readers.ipynb | paulbisso/DALI | e5ebc9a6185facfae43dafd4098c43d192a6292e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 32.373377 | 133 | 0.521212 | [
[
[
"# Using PyTorch DALI plugin: using various readers\n\n### Overview\n\nThis example shows how different readers could be used to interact with PyTorch. It shows how flexible DALI is.\n\nThe following readers are used in this example:\n\n- MXNetReader\n- CaffeReader\n- FileReader\n- TFRecordReader\n\nFor details on how to use them please see other [examples](..).",
"_____no_output_____"
],
[
"Let us start from defining some global constants",
"_____no_output_____"
]
],
[
[
"# MXNet RecordIO\ndb_folder = \"/data/imagenet/train-480-val-256-recordio/\"\n\n# Caffe LMDB\nlmdb_folder = \"/data/imagenet/train-lmdb-256x256\"\n\n# image dir with plain jpeg files\nimage_dir = \"../images\"\n\n# TFRecord\ntfrecord = \"/data/imagenet/train-val-tfrecord-480/train-00001-of-01024\"\ntfrecord_idx = \"idx_files/train-00001-of-01024.idx\"\ntfrecord2idx_script = \"tfrecord2idx\"\n\nN = 8 # number of GPUs\nBATCH_SIZE = 128 # batch size per GPU\nITERATIONS = 32\nIMAGE_SIZE = 3",
"_____no_output_____"
]
],
[
[
"Create idx file by calling `tfrecord2idx` script",
"_____no_output_____"
]
],
[
[
"from subprocess import call\nimport os.path\n\nif not os.path.exists(\"idx_files\"):\n os.mkdir(\"idx_files\")\n\nif not os.path.isfile(tfrecord_idx):\n call([tfrecord2idx_script, tfrecord, tfrecord_idx])",
"_____no_output_____"
]
],
[
[
"Let us define:\n- common part of pipeline, other pipelines will inherit it",
"_____no_output_____"
]
],
[
[
"from nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.ops as ops\nimport nvidia.dali.types as types\n\nclass CommonPipeline(Pipeline):\n def __init__(self, batch_size, num_threads, device_id):\n super(CommonPipeline, self).__init__(batch_size, num_threads, device_id)\n\n self.decode = ops.nvJPEGDecoder(device = \"mixed\", output_type = types.RGB)\n self.resize = ops.Resize(device = \"gpu\",\n image_type = types.RGB,\n interp_type = types.INTERP_LINEAR)\n self.cmn = ops.CropMirrorNormalize(device = \"gpu\",\n output_dtype = types.FLOAT,\n crop = (227, 227),\n image_type = types.RGB,\n mean = [128., 128., 128.],\n std = [1., 1., 1.])\n self.uniform = ops.Uniform(range = (0.0, 1.0))\n self.resize_rng = ops.Uniform(range = (256, 480))\n\n def base_define_graph(self, inputs, labels):\n images = self.decode(inputs)\n images = self.resize(images, resize_shorter = self.resize_rng())\n output = self.cmn(images, crop_pos_x = self.uniform(),\n crop_pos_y = self.uniform())\n return (output, labels.gpu())",
"_____no_output_____"
]
],
[
[
"- MXNetReaderPipeline",
"_____no_output_____"
]
],
[
[
"from nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.ops as ops\nimport nvidia.dali.types as types\n\nclass MXNetReaderPipeline(CommonPipeline):\n def __init__(self, batch_size, num_threads, device_id, num_gpus):\n super(MXNetReaderPipeline, self).__init__(batch_size, num_threads, device_id)\n self.input = ops.MXNetReader(path = [db_folder+\"train.rec\"], index_path=[db_folder+\"train.idx\"],\n random_shuffle = True, shard_id = device_id, num_shards = num_gpus)\n\n def define_graph(self):\n images, labels = self.input(name=\"Reader\")\n return self.base_define_graph(images, labels)",
"_____no_output_____"
]
],
[
[
"- CaffeReadPipeline",
"_____no_output_____"
]
],
[
[
"class CaffeReadPipeline(CommonPipeline):\n def __init__(self, batch_size, num_threads, device_id, num_gpus):\n super(CaffeReadPipeline, self).__init__(batch_size, num_threads, device_id)\n self.input = ops.CaffeReader(path = lmdb_folder,\n random_shuffle = True, shard_id = device_id, num_shards = num_gpus)\n\n def define_graph(self):\n images, labels = self.input(name=\"Reader\")\n return self.base_define_graph(images, labels)",
"_____no_output_____"
]
],
[
[
"- FileReadPipeline",
"_____no_output_____"
]
],
[
[
"class FileReadPipeline(CommonPipeline):\n def __init__(self, batch_size, num_threads, device_id, num_gpus):\n super(FileReadPipeline, self).__init__(batch_size, num_threads, device_id)\n self.input = ops.FileReader(file_root = image_dir)\n\n def define_graph(self):\n images, labels = self.input(name=\"Reader\")\n return self.base_define_graph(images, labels)",
"_____no_output_____"
]
],
[
[
"- TFRecordPipeline",
"_____no_output_____"
]
],
[
[
"import nvidia.dali.tfrecord as tfrec\n\nclass TFRecordPipeline(CommonPipeline):\n def __init__(self, batch_size, num_threads, device_id, num_gpus):\n super(TFRecordPipeline, self).__init__(batch_size, num_threads, device_id)\n self.input = ops.TFRecordReader(path = tfrecord, \n index_path = tfrecord_idx,\n features = {\"image/encoded\" : tfrec.FixedLenFeature((), tfrec.string, \"\"),\n \"image/class/label\": tfrec.FixedLenFeature([1], tfrec.int64, -1)\n })\n\n def define_graph(self):\n inputs = self.input(name=\"Reader\")\n images = inputs[\"image/encoded\"]\n labels = inputs[\"image/class/label\"]\n return self.base_define_graph(images, labels)",
"_____no_output_____"
]
],
[
[
"Let us create pipelines and pass them to PyTorch generic iterator",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom nvidia.dali.plugin.pytorch import DALIGenericIterator\n\npipe_types = [[MXNetReaderPipeline, (0, 999)], \n [CaffeReadPipeline, (0, 999)],\n [FileReadPipeline, (0, 1)], \n [TFRecordPipeline, (1, 1000)]]\nfor pipe_t in pipe_types:\n pipe_name, label_range = pipe_t\n print (\"RUN: \" + pipe_name.__name__)\n pipes = [pipe_name(batch_size=BATCH_SIZE, num_threads=2, device_id = device_id, num_gpus = N) for device_id in range(N)]\n pipes[0].build()\n dali_iter = DALIGenericIterator(pipes, ['data', 'label'], pipes[0].epoch_size(\"Reader\"))\n\n for i, data in enumerate(dali_iter):\n if i >= ITERATIONS:\n break\n # Testing correctness of labels\n for d in data:\n label = d[\"label\"]\n image = d[\"data\"]\n ## labels need to be integers\n assert(np.equal(np.mod(label, 1), 0).all())\n ## labels need to be in range pipe_name[2]\n assert((label >= label_range[0]).all())\n assert((label <= label_range[1]).all())\n print(\"OK : \" + pipe_name.__name__)",
"RUN: MXNetReaderPipeline\nOK : MXNetReaderPipeline\nRUN: CaffeReadPipeline\nOK : CaffeReadPipeline\nRUN: FileReadPipeline\nOK : FileReadPipeline\nRUN: TFRecordPipeline\nOK : TFRecordPipeline\n"
]
]
] | [
"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"
]
] |
ece56591123a6ffd835c5e2ace8bafc4022d5f75 | 1,780 | ipynb | Jupyter Notebook | Chapter-Topic-Modeling/Topic Modeling.ipynb | Yue1Harriet1Huang/hands-on-nlp-with-keras-and-pytorch | 463ce37c1db0174069c3ca3dd9d2a292e063bbca | [
"MIT"
] | null | null | null | Chapter-Topic-Modeling/Topic Modeling.ipynb | Yue1Harriet1Huang/hands-on-nlp-with-keras-and-pytorch | 463ce37c1db0174069c3ca3dd9d2a292e063bbca | [
"MIT"
] | null | null | null | Chapter-Topic-Modeling/Topic Modeling.ipynb | Yue1Harriet1Huang/hands-on-nlp-with-keras-and-pytorch | 463ce37c1db0174069c3ca3dd9d2a292e063bbca | [
"MIT"
] | null | null | null | 29.180328 | 303 | 0.608989 | [
[
[
"## Finding Association",
"_____no_output_____"
],
[
"### 1. Measure pair-wise association\n\n#### (1) Point-wise Mutual Information: the odds of them coocurring versus them being independent \n\n(Do\tevents\tx\tand\ty\tco-occur\tmore\tthan\tif\tthey\twere\tindependent)\n\nP(word, context)/P(w)P(c)\n\n#### What is it good for?\nit reduces the effect of frequent words/stop-words (certain context words are just frequenty occuring - it does not necessarily mean that it is related to me) - nominalized by the marginal probability of occuring in general\n\n#### What is it short for?\n- it biases to the infrequent context words (certain words are very rare to occur (small marginal probability), when it happens with me (also a rare event) - not necessarily mean that it is related to me either) - nominalized by an increased marginal probability (raise to an exponent of 0.75) \n\nreference: [Jurafsky: Vector Semantics](https://web.stanford.edu/~jurafsky/li15/lec3.vector.pdf)",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown"
]
] |
ece566cdeb800d633e7da48fe244efe63319d739 | 685,608 | ipynb | Jupyter Notebook | 03_Python_Finance.ipynb | devscie/PythonFinance | 3185092a5da511533d074a905c1421046a09e7b7 | [
"MIT"
] | null | null | null | 03_Python_Finance.ipynb | devscie/PythonFinance | 3185092a5da511533d074a905c1421046a09e7b7 | [
"MIT"
] | null | null | null | 03_Python_Finance.ipynb | devscie/PythonFinance | 3185092a5da511533d074a905c1421046a09e7b7 | [
"MIT"
] | null | null | null | 321.127869 | 113,382 | 0.897961 | [
[
[
"# 03 - Python Finance\n\n**Capitulo 03**: A partir das cotações de ações e do ÍNDICE BOVESPA do Yahoo Finance obtidas, podemos calcular a correlação entre o Dólar e o Índice Bovespa, também calcular o IBOVESPA dolarizado.",
"_____no_output_____"
],
[
"## 1. Importando bibliotecas\n\nInstalando o YFinance\n",
"_____no_output_____"
]
],
[
[
"!pip install yfinance --upgrade --no-cache-dir",
"Collecting yfinance\n Downloading https://files.pythonhosted.org/packages/7a/e8/b9d7104d3a4bf39924799067592d9e59119fcfc900a425a12e80a3123ec8/yfinance-0.1.55.tar.gz\nRequirement already satisfied, skipping upgrade: pandas>=0.24 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.1.5)\nRequirement already satisfied, skipping upgrade: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.19.5)\nRequirement already satisfied, skipping upgrade: requests>=2.20 in /usr/local/lib/python3.7/dist-packages (from yfinance) (2.23.0)\nRequirement already satisfied, skipping upgrade: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance) (0.0.9)\nCollecting lxml>=4.5.1\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/cf/4d/6537313bf58fe22b508f08cf3eb86b29b6f9edf68e00454224539421073b/lxml-4.6.3-cp37-cp37m-manylinux1_x86_64.whl (5.5MB)\n\u001b[K |████████████████████████████████| 5.5MB 7.5MB/s \n\u001b[?25hRequirement already satisfied, skipping upgrade: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->yfinance) (2018.9)\nRequirement already satisfied, skipping upgrade: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24->yfinance) (2.8.1)\nRequirement already satisfied, skipping upgrade: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (2.10)\nRequirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (1.24.3)\nRequirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (3.0.4)\nRequirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->yfinance) (2020.12.5)\nRequirement already satisfied, skipping upgrade: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.24->yfinance) (1.15.0)\nBuilding wheels for collected packages: yfinance\n Building wheel for yfinance (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for yfinance: filename=yfinance-0.1.55-py2.py3-none-any.whl size=22616 sha256=34962453207ea5eb9a9b2c83dcc15197c6289d7c002fa61e46c99c1cb700ab7c\n Stored in directory: /tmp/pip-ephem-wheel-cache-dw0zazdl/wheels/04/98/cc/2702a4242d60bdc14f48b4557c427ded1fe92aedf257d4565c\nSuccessfully built yfinance\nInstalling collected packages: lxml, yfinance\n Found existing installation: lxml 4.2.6\n Uninstalling lxml-4.2.6:\n Successfully uninstalled lxml-4.2.6\nSuccessfully installed lxml-4.6.3 yfinance-0.1.55\n"
]
],
[
[
"Importando o YFinance e sobrescrevendo os métodos do pandas_datareader",
"_____no_output_____"
]
],
[
[
"import yfinance as yf\nyf.pdr_override()",
"_____no_output_____"
]
],
[
[
"Importando as Bibliotecas",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pandas_datareader.data as web\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"## 2. Obtendo e tratando os dados\n\nBaixando as cotações do Yahoo Finance para o Índice Bovespa",
"_____no_output_____"
]
],
[
[
"tickers = [\"^BVSP\", \"USDBRL=X\"]\n#carteira = web.get_data_yahoo(tickers)[\"Close\"]\ncarteira = yf.download(tickers, start=\"2007-01-01\")[\"Close\"] #correlação",
"[*********************100%***********************] 2 of 2 completed\n"
]
],
[
[
"Exibindo as cotações mais antigas",
"_____no_output_____"
]
],
[
[
"carteira",
"_____no_output_____"
],
[
"carteira #correlação",
"_____no_output_____"
],
[
"carteira = carteira.dropna() #limpeza campos vazios\ncarteira",
"_____no_output_____"
],
[
"carteira.columns = [\"DOLAR\", \"IBOV\"]\ncarteira",
"_____no_output_____"
]
],
[
[
"## 3. Resultados",
"_____no_output_____"
]
],
[
[
"carteira.plot(subplots=True, figsize=(22,8));",
"_____no_output_____"
],
[
"carteira.plot(subplots=True, figsize=(22,8)); #correlação",
"_____no_output_____"
],
[
"sns.set() #seaborn\ncarteira.plot(subplots=True, figsize=(22,8));",
"_____no_output_____"
],
[
"carteira.corr()",
"_____no_output_____"
],
[
"sns.heatmap(carteira.corr(), annot=True)",
"_____no_output_____"
],
[
"#janelas de observação de correlação\n#a cada 252 dias do ano move a janela e calcula correlação\ncarteira[\"DOLAR\"].rolling(252).corr(carteira[\"IBOV\"]).plot(figsize=(22,8))",
"_____no_output_____"
],
[
"carteira[\"IBOV_DOLARIZADO\"] = (carteira['IBOV'] / carteira[\"DOLAR\"])\ncarteira",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"sns.set() #seaborn\ncarteira.plot(subplots=True, figsize=(22,8));",
"_____no_output_____"
]
],
[
[
"## 4. Análise",
"_____no_output_____"
],
[
"**Obtendo e tratando os dados**",
"_____no_output_____"
]
],
[
[
"tickers = \"^BVSP USDBRL=X\"\ncarteira = yf.download(tickers, start=\"2007-01-01\")[\"Close\"]",
"[*********************100%***********************] 2 of 2 completed\n"
],
[
"carteira",
"_____no_output_____"
],
[
"carteira = carteira.dropna()\ncarteira",
"_____no_output_____"
],
[
"carteira.columns = [\"DOLAR\", \"IBOV\"]\ncarteira",
"_____no_output_____"
]
],
[
[
"**Resultados**",
"_____no_output_____"
]
],
[
[
"sns.set()\ncarteira.plot(subplots=True, figsize=(22,8));",
"_____no_output_____"
],
[
"retornos = carteira.pct_change()[1:]\nretornos",
"_____no_output_____"
],
[
"retornos.describe()",
"_____no_output_____"
],
[
"sns.heatmap(retornos.corr(), annot=True);",
"_____no_output_____"
],
[
"retornos[\"DOLAR\"].rolling(252).corr(retornos[\"IBOV\"]).plot(figsize=(22,8))",
"_____no_output_____"
],
[
"carteira[\"IBOV_DOLARIZADO\"] = (carteira[\"IBOV\"] / carteira[\"DOLAR\"])\ncarteira",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"sns.pairplot(retornos);",
"_____no_output_____"
],
[
"",
"_____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",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece56d56c3fb60a58a5720294ca56d5a6228cdfd | 161,912 | ipynb | Jupyter Notebook | sta141b/2018/discussion04.ipynb | clarkfitzg/teaching-notes | a795263bf7d1b5083fb8efbd4460166a65d50545 | [
"BSD-3-Clause-Clear"
] | 28 | 2017-03-31T03:15:13.000Z | 2020-09-21T19:58:35.000Z | sta141b/2018/discussion04.ipynb | hemiaocui/teaching-notes | a795263bf7d1b5083fb8efbd4460166a65d50545 | [
"BSD-3-Clause-Clear"
] | null | null | null | sta141b/2018/discussion04.ipynb | hemiaocui/teaching-notes | a795263bf7d1b5083fb8efbd4460166a65d50545 | [
"BSD-3-Clause-Clear"
] | 33 | 2018-01-12T04:17:08.000Z | 2021-11-24T04:31:05.000Z | 103.194391 | 30,196 | 0.770493 | [
[
[
"# Week 4 Discussion\n\n## Infographic\n\n* [Python Plotting for EDA](http://pythonplot.com/): Side-by-side comparison of the major visualization libraries.\n\n## Links\n\n* [The Python Visualization Landscape](https://www.youtube.com/watch?v=FytuB8nFHPQ): A recent talk about visualization libraries for Python.\n* [A Dramatic Tour through Python's Data Visualization Landscape](https://dsaber.com/2016/10/02/a-dramatic-tour-through-pythons-data-visualization-landscape-including-ggplot-and-altair/): Examples that show why you should know matplotlib, but should use some other library to make most of your plots. From Oct 2016, so a little outdated.\n* [matplotlib Arist Tutorial](https://matplotlib.org/users/artists.html): If you want a deeper understanding of matplotlib.\n\n## Notes",
"_____no_output_____"
],
[
"How can we make plots in Python?\n\nPackage | Family | Depends On\n---------------|------------|-----------\n[matplotlib][] | matplotlib |\n[seaborn][] | matplotlib | matplotlib\n[pandas][] | matplotlib | matplotlib\n[plotnine][] | ggplot | matplotlib\n[ggpy][] | ggplot | matplotlib\n[altair][] | browser | d3.js\n[plotly][] | browser | d3.js\n[mpld3][] | browser | d3.js\n[bokeh][] | browser |\n[bqplot][] | browser | jupyter\n[vega][] | browser | jupyter + d3.js\n\n[matplotlib]: https://matplotlib.org/\n[seaborn]: https://seaborn.pydata.org/\n[pandas]: http://pandas.pydata.org/pandas-docs/stable/visualization.html\n[plotnine]: http://plotnine.readthedocs.io/\n[ggpy]: http://yhat.github.io/ggpy/\n[altair]: https://altair-viz.github.io/\n[plotly]: https://plot.ly/python/\n[mpld3]: http://mpld3.github.io/\n[bokeh]: https://bokeh.pydata.org/\n[bqplot]: https://github.com/bloomberg/bqplot\n[vega]: https://github.com/vega/ipyvega\n\nAnd more...",
"_____no_output_____"
],
[
"So what should you actually use?\n\n__Seaborn__ is stable. __Plotnine__ is convenient if you already know ggplot.\n\nUderstanding __matplotlib__ is useful, but using matplotlib to create plots is painful. The most important thing to know is matplotlib's jargon:\n\n* _Figure_: Container for plots.\n* _Axes_: Container for components of a plot (\"primitives\"). In other words, this is a single plot.\n* _Axis_: Container for components of an axis. This is a single axis.\n* _Tick_: A container for tick marks on an axis.\n\nAll of the containers and the primitives are called _Artists_.",
"_____no_output_____"
],
[
"What kind of plots do we usually make?\n\nFirst Feature | Second Feature | Plot\n--------------|----------------|:----\ncategorical | | dot, <span style=\"color: #aaa\">bar</span>, <span style=\"color: #aaa\">pie</span>\ncategorical | categorical | dot, mosaic, <span style=\"color: #aaa\">bar</span>\nnumerical | | box, density, histogram\nnumerical | categorical | box, density\nnumerical | numerical | line, scatter, smooth scatter\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport pandas as pd\nimport plotnine as gg\nimport seaborn as sns\n\ndogs = pd.read_feather(\"data/dogs.feather\")\ndogs.head()",
"/usr/lib/python3.6/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.\n from pandas.core import datetools\n"
]
],
[
[
"Dogs data from [Information is Beautiful](https://informationisbeautiful.net/visualizations/best-in-show-whats-the-top-data-dog/).",
"_____no_output_____"
],
[
"Quick notes on Pandas:",
"_____no_output_____"
]
],
[
[
"dogs[\"breed\"] # get column by name\n\ndogs.breed # get column by name\n\ndogs.loc[:, \"breed\"] # get rows and columns by name or by Boolean value\n\ndogs.iloc[:, [0, 3]] # get rows and columns by position (index)",
"_____no_output_____"
],
[
"dogs.dtypes",
"_____no_output_____"
],
[
"has_spaniel = dogs[\"breed\"].str.contains(\"Spaniel\") # treat breed column as a string\ndogs.loc[has_spaniel, :]",
"_____no_output_____"
]
],
[
[
"### Dot Plots\n\nPlot the number of dogs in each category.",
"_____no_output_____"
]
],
[
[
"# Pandas\ncounts = dogs[\"category\"].value_counts()\n\nax = counts.plot(style = \"o\")\nax.set(title = \"Dog Categories\", xlabel = \"Category\", ylabel = \"Count\")",
"_____no_output_____"
],
[
"# Seaborn\ncounts = dogs[\"category\"].value_counts()\n# Pandas calls the rownames an \"index\"\n\nax = sns.stripplot(x = counts.index, y = counts)\nax.set(title = \"Dog Categories\", xlabel = \"Category\", ylabel = \"Count\")\nax.set_xticklabels(ax.get_xticklabels(), rotation = 45)",
"_____no_output_____"
],
[
"# Plotnine\n\np = gg.ggplot(dogs, gg.aes(x = \"category\", color = \"kids\")) + gg.geom_point(stat = \"count\")\np + gg.labs(title = \"Dog Categories\", x = \"Category\", y = \"Count\")",
"_____no_output_____"
]
],
[
[
"### Box Plots\n\nPlot the distribution of dog longevity, grouped by category.",
"_____no_output_____"
]
],
[
[
"# Pandas\n\nax = dogs.boxplot(by = \"category\", column = \"longevity\", rot = 45)\n# Set title and axis labels.\nax.set(title = \"Dog Longevity\", xlabel = \"Category\", ylabel = \"Years\")\n# Hide grouping title Pandas adds.\nax.get_figure().suptitle(\"\")\n\n# There is also .plot.box(), but it seems to be buggy.",
"_____no_output_____"
],
[
"# Seaborn\n\nax = sns.boxplot(x = \"category\", y = \"longevity\", data = dogs)\nax.set(title = \"Dog Longevity\", xlabel = \"Category\", ylabel = \"Years\")\nax.set_xticklabels(ax.get_xticklabels(), rotation = 45)",
"_____no_output_____"
],
[
"# Plotnine\n\np = gg.ggplot(dogs, gg.aes(\"category\", \"longevity\")) + gg.geom_boxplot()\np + gg.labs(title = \"Dog Longevity\", x = \"Category\", y = \"Years\")",
"/usr/lib/python3.6/site-packages/plotnine/layer.py:363: UserWarning: stat_boxplot : Removed 37 rows containing non-finite values.\n data = self.stat.compute_layer(data, params, layout)\n"
]
],
[
[
"### Scatter Plots",
"_____no_output_____"
],
[
"Plot popularity against datadog score.",
"_____no_output_____"
]
],
[
[
"# Pandas\n\nax = dogs.plot.scatter(x = \"datadog\", y = \"popularity\")\nax.set(title = \"Best in Show\", xlabel = \"DataDog Score\", ylabel = \"Popularity Rank\")\nylim = reversed(ax.get_ylim())\nax.set_ylim(ylim)",
"_____no_output_____"
],
[
"# Seaborn\n\nax = sns.regplot(x = \"datadog\", y = \"popularity\", data = dogs, fit_reg = False)\nax.set(title = \"Best in Show\", xlabel = \"DataDog Score\", ylabel = \"Popularity Rank\")\nylim = reversed(ax.get_ylim())\nax.set_ylim(ylim)",
"_____no_output_____"
],
[
"# Plotnine\n\np = gg.ggplot(dogs, gg.aes(\"datadog\", \"popularity\")) + gg.geom_point()\np + gg.labs(title = \"Best in Show\", x = \"DataDog Score\", y = \"Popularity Rank\")\np + gg.ylim(95, -5)",
"_____no_output_____"
]
],
[
[
"### Smooth Scatter Plots",
"_____no_output_____"
],
[
"Plot popularity against datadog score as a smooth scatter plot (or similar).",
"_____no_output_____"
]
],
[
[
"# Pandas\n\n# `sharex = False` to fix a bug with xlabel.\nax = dogs.plot.hexbin(x = \"datadog\", y = \"popularity\", gridsize = 10, sharex = False)\nax.set(title = \"Best in Show\", xlabel = \"DataDog Score\", ylabel = \"Popularity Rank\")\nylim = reversed(ax.get_ylim())\nax.set_ylim(ylim)",
"_____no_output_____"
],
[
"# Seaborn\n\ng = sns.jointplot(x = \"datadog\", y = \"popularity\", data = dogs, kind = \"hex\", gridsize = 15, ylim = (95, -5))\ng.set_axis_labels(\"DataDog Score\", \"Popularity Rank\")",
"_____no_output_____"
],
[
"# Plotnine\n\n# Doesn't have geom_hex() yet.\np = gg.ggplot(dogs, gg.aes(\"datadog\", \"popularity\")) + gg.geom_bin2d(bins = 20)\np + gg.labs(title = \"Best in Show\", x = \"DataDog Score\", y = \"Popularity Rank\")\np + gg.ylim(95, -5)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
ece5720d5671291f28211a29fe81e9ea62084a00 | 50,117 | ipynb | Jupyter Notebook | docs_src/text.learner.ipynb | dylan-smith/fastai | 191bcd3c07e23d8269ef95f50384a99e27addee3 | [
"Apache-2.0"
] | 1 | 2019-01-31T08:15:59.000Z | 2019-01-31T08:15:59.000Z | docs_src/text.learner.ipynb | dylan-smith/fastai | 191bcd3c07e23d8269ef95f50384a99e27addee3 | [
"Apache-2.0"
] | null | null | null | docs_src/text.learner.ipynb | dylan-smith/fastai | 191bcd3c07e23d8269ef95f50384a99e27addee3 | [
"Apache-2.0"
] | null | null | null | 51.192033 | 1,281 | 0.610771 | [
[
[
"## NLP model creation and training",
"_____no_output_____"
]
],
[
[
"from fastai.gen_doc.nbdoc import *\nfrom fastai.text import * \n",
"_____no_output_____"
]
],
[
[
"The main thing here is [`RNNLearner`](/text.learner.html#RNNLearner). There are also some utility functions to help create and update text models.",
"_____no_output_____"
],
[
"## Quickly get a learner",
"_____no_output_____"
]
],
[
[
"show_doc(language_model_learner)",
"_____no_output_____"
]
],
[
[
"The model used is given by `arch` and `config`. It can be:\n\n- an [<code>AWD_LSTM</code>](/text.models.html#AWD_LSTM)([Merity et al.](https://arxiv.org/abs/1708.02182))\n- a [<code>Transformer</code>](/text.models.html#Transformer) decoder ([Vaswani et al.](https://arxiv.org/abs/1706.03762))\n- a [<code>TransformerXL</code>](/text.models.html#TransformerXL) ([Dai et al.](https://arxiv.org/abs/1901.02860))\n\nThey each have a default config for language modelling that is in <code>{lower_case_class_name}_lm_config</code> if you want to change the default parameter. At this stage, only the AWD LSTM support `pretrained=True` but we hope to add more pretrained models soon. `drop_mult` is applied to all the dropouts weights of the `config`, `learn_kwargs` are passed to the [`Learner`](/basic_train.html#Learner) initialization.",
"_____no_output_____"
]
],
[
[
"jekyll_note(\"Using QRNN (change the flag in the config of the AWD LSTM) requires to have cuda installed (same version as pytorch is using).\")",
"_____no_output_____"
],
[
"path = untar_data(URLs.IMDB_SAMPLE)\ndata = TextLMDataBunch.from_csv(path, 'texts.csv')\nlearn = language_model_learner(data, AWD_LSTM, drop_mult=0.5)",
"_____no_output_____"
],
[
"show_doc(text_classifier_learner)",
"_____no_output_____"
]
],
[
[
"Here again, the backbone of the model is determined by `arch` and `config`. The input texts are fed into that model by bunch of `bptt` and only the last `max_len` activations are considered. This gives us the backbone of our model. The head then consists of:\n- a layer that concatenates the final outputs of the RNN with the maximum and average of all the intermediate outputs (on the sequence length dimension),\n- blocks of ([`nn.BatchNorm1d`](https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d), [`nn.Dropout`](https://pytorch.org/docs/stable/nn.html#torch.nn.Dropout), [`nn.Linear`](https://pytorch.org/docs/stable/nn.html#torch.nn.Linear), [`nn.ReLU`](https://pytorch.org/docs/stable/nn.html#torch.nn.ReLU)) layers.\n\nThe blocks are defined by the `lin_ftrs` and `drops` arguments. Specifically, the first block will have a number of inputs inferred from the backbone arch and the last one will have a number of outputs equal to data.c (which contains the number of classes of the data) and the intermediate blocks have a number of inputs/outputs determined by `lin_ftrs` (of course a block has a number of inputs equal to the number of outputs of the previous block). The dropouts all have a the same value ps if you pass a float, or the corresponding values if you pass a list. Default is to have an intermediate hidden size of 50 (which makes two blocks model_activation -> 50 -> n_classes) with a dropout of 0.1.",
"_____no_output_____"
]
],
[
[
"path = untar_data(URLs.IMDB_SAMPLE)\ndata = TextClasDataBunch.from_csv(path, 'texts.csv')\nlearn = text_classifier_learner(data, AWD_LSTM, drop_mult=0.5)",
"_____no_output_____"
],
[
"show_doc(RNNLearner)",
"_____no_output_____"
]
],
[
[
"Handles the whole creation from <code>data</code> and a `model` with a text data using a certain `bptt`. The `split_func` is used to properly split the model in different groups for gradual unfreezing and differential learning rates. Gradient clipping of `clip` is optionally applied. `alpha` and `beta` are all passed to create an instance of [`RNNTrainer`](/callbacks.rnn.html#RNNTrainer). Can be used for a language model or an RNN classifier. It also handles the conversion of weights from a pretrained model as well as saving or loading the encoder.",
"_____no_output_____"
]
],
[
[
"show_doc(RNNLearner.get_preds)",
"_____no_output_____"
]
],
[
[
"If `ordered=True`, returns the predictions in the order of the dataset, otherwise they will be ordered by the sampler (from the longest text to the shortest). The other arguments are passed [`Learner.get_preds`](/basic_train.html#Learner.get_preds).",
"_____no_output_____"
]
],
[
[
"show_doc(TextClassificationInterpretation,title_level=3)",
"_____no_output_____"
]
],
[
[
"The darker the word-shading in the below example, the more it contributes to the classification. Results here are without any fitting. After fitting to acceptable accuracy, this class can show you what is being used to produce the classification of a particular case.",
"_____no_output_____"
]
],
[
[
"import matplotlib.cm as cm\n\ntxt_ci = TextClassificationInterpretation.from_learner(learn)\ntest_text = \"Zombiegeddon was perhaps the GREATEST movie i have ever seen!\"\ntxt_ci.show_intrinsic_attention(test_text,cmap=cm.Purples)",
"_____no_output_____"
]
],
[
[
"You can also view the raw attention values with `.intrinsic_attention(text)`",
"_____no_output_____"
]
],
[
[
"txt_ci.intrinsic_attention(test_text)[1]",
"_____no_output_____"
]
],
[
[
"Create a tabulation showing the first `k` texts in top_losses along with their prediction, actual,loss, and probability of actual class. `max_len` is the maximum number of tokens displayed. If `max_len=None`, it will display all tokens.",
"_____no_output_____"
]
],
[
[
"txt_ci.show_top_losses(5)",
"_____no_output_____"
]
],
[
[
"### Loading and saving",
"_____no_output_____"
]
],
[
[
"show_doc(RNNLearner.load_encoder)",
"_____no_output_____"
],
[
"show_doc(RNNLearner.save_encoder)",
"_____no_output_____"
],
[
"show_doc(RNNLearner.load_pretrained)",
"_____no_output_____"
]
],
[
[
"Opens the weights in the `wgts_fname` of `self.model_dir` and the dictionary in `itos_fname` then adapts the pretrained weights to the vocabulary of the <code>data</code>. The two files should be in the models directory of the `learner.path`.",
"_____no_output_____"
],
[
"## Utility functions",
"_____no_output_____"
]
],
[
[
"show_doc(convert_weights)",
"_____no_output_____"
]
],
[
[
"Uses the dictionary `stoi_wgts` (mapping of word to id) of the weights to map them to a new dictionary `itos_new` (mapping id to word).",
"_____no_output_____"
],
[
"## Get predictions",
"_____no_output_____"
]
],
[
[
"show_doc(LanguageLearner, title_level=3)",
"_____no_output_____"
],
[
"show_doc(LanguageLearner.predict)",
"_____no_output_____"
]
],
[
[
"If `no_unk=True` the unknown token is never picked. Words are taken randomly with the distribution of probabilities returned by the model. If `min_p` is not `None`, that value is the minimum probability to be considered in the pool of words. Lowering `temperature` will make the texts less randomized. ",
"_____no_output_____"
]
],
[
[
"show_doc(LanguageLearner.beam_search)",
"_____no_output_____"
]
],
[
[
"## Basic functions to get a model",
"_____no_output_____"
]
],
[
[
"show_doc(get_language_model)",
"_____no_output_____"
],
[
"show_doc(get_text_classifier)",
"_____no_output_____"
]
],
[
[
"This model uses an encoder taken from the `arch` on `config`. This encoder is fed the sequence by successive bits of size `bptt` and we only keep the last `max_seq` outputs for the pooling layers.\n\nThe decoder use a concatenation of the last outputs, a `MaxPooling` of all the outputs and an `AveragePooling` of all the outputs. It then uses a list of `BatchNorm`, `Dropout`, `Linear`, `ReLU` blocks (with no `ReLU` in the last one), using a first layer size of `3*emb_sz` then following the numbers in `n_layers`. The dropouts probabilities are read in `drops`.\n\nNote that the model returns a list of three things, the actual output being the first, the two others being the intermediate hidden states before and after dropout (used by the [`RNNTrainer`](/callbacks.rnn.html#RNNTrainer)). Most loss functions expect one output, so you should use a Callback to remove the other two if you're not using [`RNNTrainer`](/callbacks.rnn.html#RNNTrainer).",
"_____no_output_____"
],
[
"## Undocumented Methods - Methods moved below this line will intentionally be hidden",
"_____no_output_____"
],
[
"## New Methods - Please document or move to the undocumented section",
"_____no_output_____"
]
],
[
[
"show_doc(MultiBatchEncoder.forward)",
"_____no_output_____"
],
[
"show_doc(LanguageLearner.show_results)",
"_____no_output_____"
],
[
"show_doc(MultiBatchEncoder.concat)",
"_____no_output_____"
],
[
"show_doc(MultiBatchEncoder)",
"_____no_output_____"
],
[
"show_doc(decode_spec_tokens)",
"_____no_output_____"
],
[
"show_doc(MultiBatchEncoder.reset)",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece577818f4ce697a23bfa4cec7f7aaae1ffc0c7 | 37,378 | ipynb | Jupyter Notebook | lab2/ex1.ipynb | amiune/QiskitSummerSchool2020 | 70a8d37faa165b99b16f987d57cd525ffdc54a0b | [
"MIT"
] | null | null | null | lab2/ex1.ipynb | amiune/QiskitSummerSchool2020 | 70a8d37faa165b99b16f987d57cd525ffdc54a0b | [
"MIT"
] | null | null | null | lab2/ex1.ipynb | amiune/QiskitSummerSchool2020 | 70a8d37faa165b99b16f987d57cd525ffdc54a0b | [
"MIT"
] | null | null | null | 86.124424 | 16,408 | 0.658248 | [
[
[
"",
"_____no_output_____"
],
[
"# Lab 2: Grover's Algorithm",
"_____no_output_____"
],
[
"In this lab, you will implement Grover's algorithm in `Qiskit` and investigate its behavior following the material presented in lecture 2.\n\nYou might find this chapter of the Qiskit Textbook useful:\n- https://qiskit.org/textbook/ch-algorithms/grover.html\n\nRemember, to run a cell in Jupyter notebooks, you press `Shift` + `Return/Enter` on your keyboard.",
"_____no_output_____"
],
[
"### Installing necessary packages",
"_____no_output_____"
],
[
"Before we begin, you will need to install some prerequisites into your environment. Run the cell below to complete these installations. At the end, the cell outputs will be cleared.",
"_____no_output_____"
]
],
[
[
"!pip install -U -r grading_tools/requirements.txt\n\nfrom IPython.display import clear_output\nclear_output()",
"_____no_output_____"
]
],
[
[
"# Review of Grover's Algorithm",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"You might recall from lecture 2 that Grover's algorithm has three main components. \n1. First, we begin by creating a superposition of all $2^n$ computational basis states by applying a Hadamard ($H$) gate on each qubit starting off in the state $\\vert0\\rangle^{\\otimes n}$. Here, the exponent $\\otimes n$ means that we have a tensor product of the states of $n$ qubits. \n2. Second, we apply an Oracle operator to mark the appropriate elements among the $2^n$ elements. The oracle operator applies a coefficient of $-1$ to each of the marked elements.\n3. Third, we apply a Diffusion operator, or diffuser, which inverts the amplitude of all elements about the average amplitude.\n\nPutting these components together, and applying the Oracle and Diffusion operators $O(\\sqrt{N = 2^n})$ times, Grover's algorithm allows us to successfully determine the elements that were marked by the Oracle operator with high probability. This is shown in the block diagram above, where the quantum circuit for Grover's algorithm is depicted with a measurement in the end to read out the qubits.\n\n# Graded Exercise 1: Implementing Grover's Algorithm\n\nAs you saw in the lecture, it is not hard to implement Grover's algorithm using `Qiskit`. The goal of this lab is to implement Grover's algorithm by creating a quantum circuit that has the marked elements `000001` and `101010`. You will see that the algorithm outputs one of these two marked elements with probability greater than $99\\%$. \n\nLet us build each block step by step.\n\n### 1.) Phase Oracle\nWe start with the phase oracle. You might find it helpful to have a look at the corresponding chapter in the Qiskit textbook: https://qiskit.org/textbook/ch-algorithms/grover.html. However, note that the implementation in the textbook is done on 2 and 3 qubits only, while here we need to apply it to 6 qubits.\n\n**Recall that the action of the phase oracle is to add a phase of $-1$ to all states representing the marked elements, while leaving all other states unchanged.** An easy way to implement the phase oracle is to create an identity matrix on all $n$ qubits (remember that the corresponding dimension of this matrix is $2^n$) and then change those diagonal elements to $-1$ that correspond to the marked elements. Then, you need to convert that unitary into an operator.\n\nWe have created a function below called `phase_oracle` which takes in two arguments. The first argument, $n$, gives the number of qubits in the quantum circuit. The second argument, `indices_to_mark`, is a list of the indices whose elements will be marked by the phase oracle with a phase of $-1$. Using these inputs, create a $2^n\\times2^n$ identity matrix, and apply a phase of $-1$ to the diagonal elements at locations given in `indices_to_mark`. For example, if $0$ is in `indices_to_mark`, that means you need to set the top-left-most diagonal element of the identity matrix to -1.\n\nOnce you complete these steps, apply the unitary operator to the quantum circuit.",
"_____no_output_____"
]
],
[
[
"from qiskit.quantum_info import Operator\nfrom qiskit import QuantumCircuit\nimport numpy as np",
"_____no_output_____"
],
[
"def phase_oracle(n, indices_to_mark, name = 'Oracle'):\n \n # create a quantum circuit on n qubits\n qc = QuantumCircuit(n, name=name)\n\n ### WRITE YOUR CODE BETWEEN THESE LINES - START\n oracle_matrix = np.identity(2**n)\n oracle_matrix[indices_to_mark, indices_to_mark] = -1\n ### WRITE YOUR CODE BETWEEN THESE LINES - END\n\n # convert your matrix (called oracle_matrix) into an operator, and add it to the quantum circuit\n qc.unitary(Operator(oracle_matrix), range(n))\n \n return qc",
"_____no_output_____"
]
],
[
[
"### 2.) Diffusion Operator $V$\n\nNext, we define the diffuser, which we called $V$ in the lecture. Its effect is to reflect all amplitudes about the average amplitude. To do so, we simply call the `phase_oracle` with only the zero state ($\\vert0\\rangle^{\\otimes n}$) as the marked element and sandwich it between Hadamard gates applied to all qubits.",
"_____no_output_____"
]
],
[
[
"def diffuser(n):\n \n # create a quantum circuit on n qubits\n qc = QuantumCircuit(n, name='Diffuser')\n \n ### WRITE YOUR CODE BETWEEN THESE LINES - START\n qc.h(range(n))\n qc.append(phase_oracle(n, [0]), range(n))\n qc.h(range(n))\n ### WRITE YOUR CODE BETWEEN THESE LINES - END\n \n return qc",
"_____no_output_____"
]
],
[
[
"### 3.) Putting it all together\n\nFinally, we combine the functions to construct Grover's algorithm. We need to determine the optimal number of rounds $r$ as described in the lecture.\n\nThis was given by \n\n$$r = \\left\\lfloor\\frac{\\pi}{4}\\sqrt{\\frac{N}{k}}\\right\\rfloor$$\n\nwhere $k$ is the number of marked elements, and $\\lfloor~\\rfloor$ means rounding down to the nearest integer. In the specific example that we consider here, where we have six qubits ($N = 2^6$) and two marked elements ($k = 2$), implying that $r = 4$. You can check this yourself by plugging in the numbers.\n\nIn the lecture, we have also seen a lower bound on the success probability when using $n$ qubits. In this exercise, the success probability should be higher than $99\\%$.\n\nLet's construct a quantum program that finds the marked elements `000001` and `101010` using Grover's algorithm. To do this, we will need to do the following: \n1. We start with a Hadamard gate on all qubits.\n2. Next, we apply $r$ rounds of Grover's algorithm, where each round consists of the application of the phase oracle with the marked elements and the diffuser. The indices for the two marked elements `000001` and `101010` are $1$ and $42$. \n3. Finally, we need to measure all qubits.\n\nThe next lines of code put everything together. **You do not need to modify anything below, but you will need to run the cell to submit your solution.**",
"_____no_output_____"
]
],
[
[
"def Grover(n, indices_of_marked_elements):\n \n # Create a quantum circuit on n qubits\n qc = QuantumCircuit(n, n)\n \n # Determine r\n r = int(np.floor(np.pi/4*np.sqrt(2**n/len(indices_of_marked_elements))))\n print(f'{n} qubits, basis states {indices_of_marked_elements} marked, {r} rounds')\n \n # step 1: apply Hadamard gates on all qubits\n qc.h(range(n))\n \n # step 2: apply r rounds of the phase oracle and the diffuser\n for _ in range(r):\n qc.append(phase_oracle(n, indices_of_marked_elements), range(n))\n qc.append(diffuser(n), range(n))\n \n # step 3: measure all qubits\n qc.measure(range(n), range(n))\n \n return qc\n\nmycircuit = Grover(6, [1, 42])\nmycircuit.draw(output='text')",
"6 qubits, basis states [1, 42] marked, 4 rounds\n"
]
],
[
[
"That's it! Before you submit your solution for grading, you might find it useful to run your quantum circuit and see the measurement outcomes, as well as visualize the statevector at the end.\n\nIn order to run your quantum circuit and get the measurement outcomes, you simply need to run `Qiskit`'s `execute` function as follows.",
"_____no_output_____"
]
],
[
[
"from qiskit import Aer, execute\nsimulator = Aer.get_backend('qasm_simulator')\ncounts = execute(mycircuit, backend=simulator, shots=1000).result().get_counts(mycircuit)\nfrom qiskit.visualization import plot_histogram\nplot_histogram(counts)",
"_____no_output_____"
]
],
[
[
"Then, grade your solution by running the cell below after filling in your name and email address. **Always provide the same name and email as the one you used during registration to ensure consistency.**",
"_____no_output_____"
]
],
[
[
"name = 'Hernan Amiune'\nemail = '[email protected]'\n\n### Do not change the lines below\nfrom qiskit import transpile\nmycircuit_t = transpile(mycircuit, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=0)\nfrom grading_tools import grade\ngrade(answer=mycircuit_t, name=name, email=email, labid='lab2', exerciseid='ex1')",
"lab2/ex1 - 🎉 Correct\n🎊 Hurray! You have a new correct answer! Let's submit it.\nSubmitting the answers for lab2...\n📝 Our records, so far, are:\nCorrect answers: lab1:ex1, lab2:ex1\n"
]
],
[
[
"# Additional reading\n\n- In the exercise above, we implemented the phase oracle and diffuser as matrices without decomposing them into single- and two-qubit gates. To run on real hardware, one will also need to consider how to build these oracles using gates. You can find examples of how the oracles can be built in the Grover's algorithm section of the Qiskit Textbook here: https://qiskit.org/textbook/ch-algorithms/grover.html",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ece57d3492afbaf8438db591850a87893415d68d | 780 | ipynb | Jupyter Notebook | machine_learning/2_regression/assignment/week6/quiz-week6-assignment.ipynb | bomin0624/coursera-university-of-washington | 98c5702ef011445b62a6a498048e8306d669c9a9 | [
"MIT"
] | 354 | 2016-08-26T11:20:16.000Z | 2022-03-24T10:53:55.000Z | machine_learning/2_regression/assignment/week6/.ipynb_checkpoints/quiz-week6-assignment-checkpoint.ipynb | semaahmed/coursera-university-of-washington | ec5a9e7dd9c5b9c070de3f83fb7ba7322fd09093 | [
"MIT"
] | 4 | 2017-09-27T11:21:20.000Z | 2020-07-03T07:52:23.000Z | machine_learning/2_regression/assignment/week6/.ipynb_checkpoints/quiz-week6-assignment-checkpoint.ipynb | semaahmed/coursera-university-of-washington | ec5a9e7dd9c5b9c070de3f83fb7ba7322fd09093 | [
"MIT"
] | 477 | 2016-05-22T16:10:48.000Z | 2022-03-27T18:36:50.000Z | 18.571429 | 68 | 0.534615 | [
[
[
"# Predicting house prices using k-nearest neighbors regression",
"_____no_output_____"
],
[
"<img src=\"images/pic01.png\">\n<img src=\"images/pic02.png\">\n<img src=\"images/pic03.png\">",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown"
]
] |
ece599ac0e022f26eda3b898af0f036cb1577e17 | 50,979 | ipynb | Jupyter Notebook | Scripts/plot_language_frequency.ipynb | Minjae97/Airbnb-Trend-Resaerch | 48234bbf5b6dc66db11a80e22e34a788b017f7d0 | [
"CC0-1.0"
] | null | null | null | Scripts/plot_language_frequency.ipynb | Minjae97/Airbnb-Trend-Resaerch | 48234bbf5b6dc66db11a80e22e34a788b017f7d0 | [
"CC0-1.0"
] | null | null | null | Scripts/plot_language_frequency.ipynb | Minjae97/Airbnb-Trend-Resaerch | 48234bbf5b6dc66db11a80e22e34a788b017f7d0 | [
"CC0-1.0"
] | null | null | null | 53.269592 | 17,988 | 0.576159 | [
[
[
"import pandas as pd\nfrom langdetect import detect\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# df = pd.read_csv('./buenos_aires/buenos_aires_reviews.csv')\ndf = pd.read_csv('./brazil/brazil_reviews.csv')",
"_____no_output_____"
],
[
"df2 = df[df.comments.str[:34] != \"The host canceled this reservation\"]\n# df2['date'] = pd.to_datetime(df2['date'])\ndf2 = df2[:12000]\ndf2",
"_____no_output_____"
],
[
"df3 = df2['comments']\n# dfl = df3.str.len()\n# dfl.mean(axis = 0)",
"_____no_output_____"
],
[
"langs = []\nfor i in df3:\n try:\n langs.append(detect(i))\n except:\n langs.append('Nan')\n continue",
"_____no_output_____"
],
[
"dfnew = df2.copy()\ndfnew['lang'] = langs\ndfnew",
"_____no_output_____"
],
[
"# dfnew = dfnew[(dfnew['lang']=='es') | (dfnew['lang']=='en')]",
"_____no_output_____"
],
[
"date = pd.to_datetime(dfnew['date'])\ndel dfnew['date']\ndfnew = pd.concat((dfnew, date), axis = 1, join='inner')\ndfnew",
"_____no_output_____"
],
[
"df_es = dfnew[(dfnew['lang']=='es')]\ndf_en = dfnew[(dfnew['lang']!='en')]\n\nes_data = df_es.groupby([df_es['date'].dt.year.rename('year'), df_es['date'].dt.month.rename('month')]).agg({'count'}).reset_index();\nen_data = df_en.groupby([df_en['date'].dt.year.rename('year'), df_en['date'].dt.month.rename('month')]).agg({'count'}).reset_index();\n\nes_data['year-month'] = es_data['year'].map(str) +'-'+ es_data['month'].map(str)\nen_data['year-month'] = en_data['year'].map(str) +'-'+ en_data['month'].map(str)\nes_data.columns = ['year', 'month',\"listing_id\", 'id', 'reviewer_id', 'reviewer_name', 'comments', 'lang', 'date', 'year-month']\nen_data.columns = ['year', 'month',\"listing_id\", 'id', 'reviewer_id', 'reviewer_name', 'comments', 'lang', 'date', 'year-month']\n\nes_data['year-month'] = pd.to_datetime(es_data['year-month'], format='%Y-%m')\nen_data['year-month'] = pd.to_datetime(en_data['year-month'], format='%Y-%m')\n\nes_data['sum'] = es_data['id'].cumsum()\nen_data['sum'] = en_data['id'].cumsum()\nes_data\n# en_data.to_csv(r'test.csv')",
"_____no_output_____"
],
[
"# tips = sns.load_dataset('es_data')\n# sns.barplot(x=en_data['year-month'] ,y=en_data['id'], color = 'blue', label = 'en')\n# sns.barplot(x=es_data['year-month'] ,y=es_data['id'], color = 'red', label = 'es')\n\n\n\n# tips = sns.load_dataset('es_data')\n# plt.figure(figsize=(20,6))\nax = sns.lineplot(x=en_data['year-month'] ,y=en_data['sum'], color=\"coral\", label=\"English\")\nax = sns.lineplot(x=es_data['year-month'] ,y=es_data['sum'], color=\"blue\", label=\"Other langs\")\n# ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha=\"right\")\n# plt.tight_layout()\n# plt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece5a7fd0dea1bd86fc701e51a1bfb1d5bd56cdb | 29,787 | ipynb | Jupyter Notebook | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | PrynsTag/My-Pandas-Exercise-Solutions | 0b2f6a209baf1cf60ef5237027df7c1b06b3ada4 | [
"BSD-3-Clause"
] | 2 | 2021-01-21T12:21:14.000Z | 2021-01-21T12:21:29.000Z | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | PrynsTag/My-Pandas-Exercise-Solutions | 0b2f6a209baf1cf60ef5237027df7c1b06b3ada4 | [
"BSD-3-Clause"
] | null | null | null | 04_Apply/US_Crime_Rates/Exercises_with_solutions.ipynb | PrynsTag/My-Pandas-Exercise-Solutions | 0b2f6a209baf1cf60ef5237027df7c1b06b3ada4 | [
"BSD-3-Clause"
] | 2 | 2021-01-20T05:25:24.000Z | 2021-07-05T19:01:56.000Z | 32.697036 | 181 | 0.40098 | [
[
[
"# United States - Crime Rates - 1960 - 2014\n\nCheck out [Crime Rates Exercises Video Tutorial](https://youtu.be/46lmk1JvcWA) to watch a data scientist go through the exercises",
"_____no_output_____"
],
[
"### Introduction:\n\nThis time you will create a data \n\nSpecial thanks to: https://github.com/justmarkham for sharing the dataset and materials.\n\n### Step 1. Import the necessary libraries",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"### Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv). ",
"_____no_output_____"
],
[
"### Step 3. Assign it to a variable called crime.",
"_____no_output_____"
]
],
[
[
"url = \"https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv\"\ncrime = pd.read_csv(url)\ncrime.head()",
"_____no_output_____"
]
],
[
[
"### Step 4. What is the type of the columns?",
"_____no_output_____"
]
],
[
[
"crime.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 55 entries, 0 to 54\nData columns (total 12 columns):\n # Column Non-Null Count Dtype\n--- ------ -------------- -----\n 0 Year 55 non-null int64\n 1 Population 55 non-null int64\n 2 Total 55 non-null int64\n 3 Violent 55 non-null int64\n 4 Property 55 non-null int64\n 5 Murder 55 non-null int64\n 6 Forcible_Rape 55 non-null int64\n 7 Robbery 55 non-null int64\n 8 Aggravated_assault 55 non-null int64\n 9 Burglary 55 non-null int64\n 10 Larceny_Theft 55 non-null int64\n 11 Vehicle_Theft 55 non-null int64\ndtypes: int64(12)\nmemory usage: 5.3 KB\n"
]
],
[
[
"##### Have you noticed that the type of Year is int64. But pandas has a different type to work with Time Series. Let's see it now.\n\n### Step 5. Convert the type of the column Year to datetime64",
"_____no_output_____"
]
],
[
[
"# pd.to_datetime(crime)\ncrime.Year = pd.to_datetime(crime.Year, format='%Y')\ncrime.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 55 entries, 0 to 54\nData columns (total 12 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Year 55 non-null datetime64[ns]\n 1 Population 55 non-null int64 \n 2 Total 55 non-null int64 \n 3 Violent 55 non-null int64 \n 4 Property 55 non-null int64 \n 5 Murder 55 non-null int64 \n 6 Forcible_Rape 55 non-null int64 \n 7 Robbery 55 non-null int64 \n 8 Aggravated_assault 55 non-null int64 \n 9 Burglary 55 non-null int64 \n 10 Larceny_Theft 55 non-null int64 \n 11 Vehicle_Theft 55 non-null int64 \ndtypes: datetime64[ns](1), int64(11)\nmemory usage: 5.3 KB\n"
]
],
[
[
"### Step 6. Set the Year column as the index of the dataframe",
"_____no_output_____"
]
],
[
[
"crime = crime.set_index('Year', drop = True)\ncrime.head()",
"_____no_output_____"
]
],
[
[
"### Step 7. Delete the Total column",
"_____no_output_____"
]
],
[
[
"del crime['Total']\ncrime.head()",
"_____no_output_____"
]
],
[
[
"### Step 8. Group the year by decades and sum the values\n\n#### Pay attention to the Population column number, summing this column is a mistake",
"_____no_output_____"
]
],
[
[
"# To learn more about .resample (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html)\n# To learn more about Offset Aliases (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases)\n\n# Uses resample to sum each decade\ncrimes = crime.resample('10AS').sum()\n\n# Uses resample to get the max value only for the \"Population\" column\npopulation = crime['Population'].resample('10AS').max()\n\n# Updating the \"Population\" column\ncrimes['Population'] = population\n\ncrimes",
"_____no_output_____"
]
],
[
[
"### Step 9. What is the most dangerous decade to live in the US?",
"_____no_output_____"
]
],
[
[
"# apparently the 90s was a pretty dangerous time in the US\ncrime.idxmax(0)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece5d193af54ebc45f7ace3cf804ecf79b4c0720 | 17,811 | ipynb | Jupyter Notebook | Project_05_Materials/.ipynb_checkpoints/Project_05_Pandas_SQL-checkpoint.ipynb | emdemor/PythonDataScienceWithPandas_Exercises | f9ade83f68cd31689e319a30e9bbd6869cdac25e | [
"MIT"
] | 6 | 2021-02-05T07:44:50.000Z | 2022-03-05T20:56:40.000Z | Project_05_Materials/.ipynb_checkpoints/Project_05_Pandas_SQL-checkpoint.ipynb | emdemor/PythonDataScienceWithPandas_Exercises | f9ade83f68cd31689e319a30e9bbd6869cdac25e | [
"MIT"
] | null | null | null | Project_05_Materials/.ipynb_checkpoints/Project_05_Pandas_SQL-checkpoint.ipynb | emdemor/PythonDataScienceWithPandas_Exercises | f9ade83f68cd31689e319a30e9bbd6869cdac25e | [
"MIT"
] | 2 | 2020-12-13T19:08:40.000Z | 2021-11-19T16:11:12.000Z | 19.615639 | 128 | 0.495649 | [
[
[
"# Project 5: Working with Pandas and SQL Databases (Movies Dataset)",
"_____no_output_____"
],
[
"## Creating an SQLite Database",
"_____no_output_____"
]
],
[
[
"import sqlite3 as sq3",
"_____no_output_____"
],
[
"con = sq3.connect(\"movies.db\")",
"_____no_output_____"
],
[
"con",
"_____no_output_____"
],
[
"con.execute(\"Select * FROM sqlite_master\").fetchall()",
"_____no_output_____"
],
[
"con.execute(\"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name\").fetchall()",
"_____no_output_____"
],
[
"con.close()",
"_____no_output_____"
]
],
[
[
"## Loading Data from DataFrames into an SQLite Database",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport json\nimport sqlite3 as sq3",
"_____no_output_____"
],
[
"with open(\"some_movies.json\") as f:\n data = json.load(f)",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"df = pd.json_normalize(data, sep = \"_\")",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"movies = df[[\"id\", \"title\", \"revenue\", \"budget\", \"belongs_to_collection_name\", \"release_date\"]].copy()\nmovies",
"_____no_output_____"
],
[
"movies.info()",
"_____no_output_____"
],
[
"movies.release_date = pd.to_datetime(df.release_date)",
"_____no_output_____"
],
[
"movies.revenue = df.revenue/1000000\nmovies.budget = df.budget/1000000",
"_____no_output_____"
],
[
"movies",
"_____no_output_____"
],
[
"votes = df[[\"id\", \"vote_count\", \"vote_average\"]].copy()\nvotes",
"_____no_output_____"
],
[
"genres = pd.json_normalize(data = data, record_path = \"genres\", meta = \"id\", record_prefix = \"genre_\")\ngenres",
"_____no_output_____"
],
[
"prod = pd.json_normalize(data = data, record_path = \"production_companies\", meta = \"id\", record_prefix = \"comp_\")\nprod",
"_____no_output_____"
],
[
"con = sq3.connect(\"movies.db\")",
"_____no_output_____"
],
[
"con",
"_____no_output_____"
],
[
"movies.to_sql(\"Movies\", con, index = False)",
"_____no_output_____"
],
[
"votes.to_sql(\"Votes\", con, index = False)",
"_____no_output_____"
],
[
"genres.to_sql(\"Genres\", con, index = False)",
"_____no_output_____"
],
[
"prod.to_sql(\"Prod\", con, index = False)",
"_____no_output_____"
],
[
"con.execute(\"Select * FROM sqlite_master\").fetchall()",
"_____no_output_____"
],
[
"con.execute(\"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name\").fetchall()",
"_____no_output_____"
],
[
"con.close()",
"_____no_output_____"
]
],
[
[
"## Loading Data from SQLite Databases into DataFrames",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport sqlite3 as sq3",
"_____no_output_____"
],
[
"con = sq3.connect(\"movies.db\")",
"_____no_output_____"
],
[
"con.execute(\"Select * FROM sqlite_master\").fetchall()",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies\", con).info()",
"_____no_output_____"
],
[
"df = pd.read_sql(\"SELECT * FROM Movies\", con, index_col = \"id\", parse_dates = \"release_date\")\ndf",
"_____no_output_____"
],
[
"df.info()",
"_____no_output_____"
],
[
"genres = pd.read_sql(\"SELECT * FROM Genres\", con, index_col = \"id\")\ngenres",
"_____no_output_____"
],
[
"con.close()",
"_____no_output_____"
]
],
[
[
"## Some Simple SQL Queries",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport sqlite3 as sq3",
"_____no_output_____"
],
[
"con = sq3.connect(\"movies.db\")",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * \\\n FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT id, revenue, release_date FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT sum(revenue) FROM Movies\", con)",
"_____no_output_____"
],
[
"con.execute(\"SELECT sum(revenue) FROM Movies\").fetchall()[0][0]",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT count(title) FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT count(belongs_to_collection_name) FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT count(*) FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT avg(budget) FROM Movies\", con)",
"_____no_output_____"
],
[
"con.close()",
"_____no_output_____"
]
],
[
[
"## Some more SQL Queries",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport sqlite3 as sq3",
"_____no_output_____"
],
[
"con = sq3.connect(\"movies.db\")",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies WHERE id = 597\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies WHERE revenue > 2000\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies WHERE revenue > 1500 AND budget < 200\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT MIN(budget) FROM Movies WHERE revenue > 1250\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT DISTINCT title FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT DISTINCT belongs_to_collection_name FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies ORDER BY budget DESC\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies WHERE belongs_to_collection_name IS NULL\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies WHERE belongs_to_collection_name IS NOT NULL\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies WHERE title LIKE 'Avengers%'\", con)",
"_____no_output_____"
],
[
"con.close()",
"_____no_output_____"
]
],
[
[
"## Join Queries",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport sqlite3 as sq3",
"_____no_output_____"
],
[
"con = sq3.connect(\"movies.db\")",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Movies\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Votes\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * \\\n FROM Movies \\\n JOIN Votes \\\n ON Movies.id=Votes.id\", con)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT Movies.id, Movies.title, Votes.vote_average \\\n FROM Movies \\\n JOIN Votes \\\n ON Movies.id=Votes.id\", con, index_col = \"id\")",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT Movies.id, Movies.title, Votes.vote_average \\\n FROM Movies \\\n JOIN Votes \\\n ON Movies.id=Votes.id \\\n WHERE Votes.vote_average > 8\", con, index_col = \"id\")",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT Movies.id, Movies.title, Movies.budget, Votes.vote_average \\\n FROM Movies \\\n JOIN Votes \\\n ON Movies.id=Votes.id \\\n WHERE Votes.vote_average > 8 \\\n ORDER BY Movies.budget ASC\", con, index_col = \"id\")",
"_____no_output_____"
],
[
"con.close()",
"_____no_output_____"
]
],
[
[
"## Final Case Study",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport sqlite3 as sq3",
"_____no_output_____"
],
[
"con = sq3.connect(\"movies.db\")",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT * FROM Prod\", con)",
"_____no_output_____"
],
[
"df = pd.read_sql(\"SELECT Prod.id, Prod.comp_name, Movies.revenue, Movies.title \\\n FROM Prod \\\n LEFT JOIN Movies \\\n ON Prod.id=Movies.id\", con)\ndf",
"_____no_output_____"
],
[
"df.groupby(\"comp_name\").revenue.sum().sort_values(ascending = False)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT Prod.comp_name \\\n FROM Prod \\\n LEFT JOIN Movies \\\n ON Prod.id=Movies.id \\\n WHERE Movies.title = 'Titanic'\", con)",
"_____no_output_____"
],
[
"df2 = pd.read_sql(\"SELECT Genres.id, Genres.genre_name, Movies.revenue, Movies.title \\\n FROM Genres \\\n LEFT JOIN Movies \\\n ON Genres.id=Movies.id\", con)\ndf2",
"_____no_output_____"
],
[
"df2.groupby(\"genre_name\").revenue.sum().sort_values(ascending = False)",
"_____no_output_____"
],
[
"pd.read_sql(\"SELECT Genres.genre_name \\\n FROM Genres \\\n LEFT JOIN Movies \\\n ON Genres.id=Movies.id \\\n WHERE Movies.title = 'Frozen II'\", con)",
"_____no_output_____"
],
[
"con.close()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"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",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece5d1d141b05ae452b584ec4553235f5402b6bf | 8,564 | ipynb | Jupyter Notebook | foxnews/Untitled.ipynb | cmccvic/CBOnetwork | 5cf8f119cbe0c085a2f4363126222cc652444395 | [
"MIT"
] | null | null | null | foxnews/Untitled.ipynb | cmccvic/CBOnetwork | 5cf8f119cbe0c085a2f4363126222cc652444395 | [
"MIT"
] | null | null | null | foxnews/Untitled.ipynb | cmccvic/CBOnetwork | 5cf8f119cbe0c085a2f4363126222cc652444395 | [
"MIT"
] | null | null | null | 32.195489 | 2,424 | 0.635217 | [
[
[
"from selenium import webdriver\nfrom foxnewsbot import *\nfrom foxprofile import my_email, my_password\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.common.by import By",
"_____no_output_____"
],
[
"driver = webdriver.Chrome()",
"_____no_output_____"
],
[
"login(driver, my_email, my_password)",
"login success!\n"
],
[
"open_page(driver, 'http://www.foxnews.com/opinion/2018/04/01/what-is-easter-and-why-do-christians-celebrate-this-holiday.html')",
"_____no_output_____"
],
[
"driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")",
"_____no_output_____"
],
[
"page_html = driver.page_source",
"_____no_output_____"
],
[
"soup = BeautifulSoup(page_html, 'html')",
"/usr/local/lib/python2.7/site-packages/bs4/__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system (\"html5lib\"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.\n\nThe code that caused this warning is on line 174 of the file /usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py. To get rid of this warning, change code that looks like this:\n\n BeautifulSoup(YOUR_MARKUP})\n\nto this:\n\n BeautifulSoup(YOUR_MARKUP, \"html5lib\")\n\n markup_type=markup_type))\n"
],
[
"mydivs = soup.findAll(\"div\", {\"id\": \"commenting\"})",
"_____no_output_____"
],
[
"mydivs",
"_____no_output_____"
],
[
"comment_url = \"https://spoxy-shard4.spot.im/v2/spot/sp_ANQXRpqH/post/44cb71eb-b87a-47aa-8156-8fe92bf8054f/?elementId=ba314173ff98020a17b6995ce616f0d4&spot_im_platform=desktop&host_url=http%3A%2F%2Fwww.foxnews.com%2Fopinion%2F2018%2F04%2F01%2Fwhat-is-easter-and-why-do-christians-celebrate-this-holiday.html&host_url_64=aHR0cDovL3d3dy5mb3huZXdzLmNvbS9vcGluaW9uLzIwMTgvMDQvMDEvd2hhdC1pcy1lYXN0ZXItYW5kLXdoeS1kby1jaHJpc3RpYW5zLWNlbGVicmF0ZS10aGlzLWhvbGlkYXkuaHRtbA%3D%3D&spot_im_ph__prerender_deferred=true&prerenderDeferred=true&sort_by=newest&spot_im_ih__livefyre_url=44cb71eb-b87a-47aa-8156-8fe92bf8054f&isStarsRatingEnabled=false&enableMessageShare=true&enableAnonymize=true&isConversationLiveBlog=false&enableSeeMoreButton=true\"",
"_____no_output_____"
],
[
"driver.get(comment_url)",
"_____no_output_____"
],
[
"post_msg = driver.find_element_by_css_selector('.ql-editor.ql-blank')",
"_____no_output_____"
],
[
"post_msg.send_keys(\"hhhhhhh\")",
"_____no_output_____"
],
[
"btn = driver.find_element_by_class_name(\"sppre_actions\")",
"_____no_output_____"
],
[
"btn.click()",
"_____no_output_____"
],
[
"for i in range(0, 100):\n# time.sleep(3)\n message = randomword(20)\n post_msg.send_keys(message + str(i))\n btn.click()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece5e3df75a6f749b4b7db072a4deca128e54162 | 595,755 | ipynb | Jupyter Notebook | module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb | jordantcarlisle/DS-Unit-1-Sprint-1-Dealing-With-Data | f28ef06bad324af8583fcbfffc415ee987011a86 | [
"MIT"
] | null | null | null | module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb | jordantcarlisle/DS-Unit-1-Sprint-1-Dealing-With-Data | f28ef06bad324af8583fcbfffc415ee987011a86 | [
"MIT"
] | null | null | null | module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb | jordantcarlisle/DS-Unit-1-Sprint-1-Dealing-With-Data | f28ef06bad324af8583fcbfffc415ee987011a86 | [
"MIT"
] | null | null | null | 44.739787 | 2,875 | 0.268808 | [
[
[
"<a href=\"https://colab.research.google.com/github/jordantcarlisle/DS-Unit-1-Sprint-1-Dealing-With-Data/blob/master/module4-makefeatures/LS_DS_114_Make_Features_Assignment.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"<img align=\"left\" src=\"https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png\" width=200> ",
"_____no_output_____"
],
[
"# ASSIGNMENT\n\n- Replicate the lesson code.\n\n - This means that if you haven't followed along already, type out the things that we did in class. Forcing your fingers to hit each key will help you internalize the syntax of what we're doing.\n - [Lambda Learning Method for DS - By Ryan Herr](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit?usp=sharing)\n- Convert the `term` column from string to integer.\n- Make a column named `loan_status_is_great`. It should contain the integer 1 if `loan_status` is \"Current\" or \"Fully Paid.\" Else it should contain the integer 0.\n\n- Make `last_pymnt_d_month` and `last_pymnt_d_year` columns.",
"_____no_output_____"
]
],
[
[
"##### Begin Working Here #####",
"_____no_output_____"
]
],
[
[
"# **Make features**\n\nObjectives\n\n* Understand the purpose of feature engineering\n* Work with strings in pandas\n* work with dates and times in pandas \n\nLinks \n\n- [Feature Engineering](https://en.wikipedia.org/wiki/Feature_engineering)\n- Python Data Science Handbook\n - [Chapter 3.10](https://jakevdp.github.io/PythonDataScienceHandBook/03.10-working-with-strings.html), Vectorized String Operations\n - [Chapter 3.11](https://jakevdp.github.io/PythonDataScienceHandbook/03.11-working-with-time-series.html), Working with Time Series\n- [Lambda Learning Method for DS - By Ryan Herr](https://docs.google.com/document/d/lub0w9B3Hfip27hF2ZnW3a3z9xAgrUDRReOEo-FHCVs/edit?usp=sharing) \n\n\n\n\n\n\n\n\n\n",
"_____no_output_____"
],
[
"# Weather data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"url = \"https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv\"",
"_____no_output_____"
],
[
"df_weather = pd.read_csv(url) #, parse_dates=True, index_col='Date/Time')\ndf_weather.head()",
"_____no_output_____"
],
[
"df_weather['Date/Time'] = pd.to_datetime(df_weather['Date/Time'])",
"_____no_output_____"
],
[
"df_weather.set_index('Date/Time')",
"_____no_output_____"
],
[
"type(df_weather['Date/Time'])",
"_____no_output_____"
],
[
"x_list = [1,2,3]\nx_arr = np.array([1,2,3])\nx_series = pd.Series([1,2,3])",
"_____no_output_____"
],
[
"# for i in x_list:\n# for i in x_arr: \nfor i in x_series: \n print(i)",
"1\n2\n3\n"
],
[
"df_weather['Weather'].str.contains('Snow')",
"_____no_output_____"
],
[
"df_weather['Weather'].str.contains('Rain')",
"_____no_output_____"
],
[
"is_precipitation = df_weather['Weather'].str.contains('Rain') | df_weather['Weather'].str.contains('Snow')\nis_precipitation",
"_____no_output_____"
],
[
"df_weather['is_precipitation'] = is_precipitation",
"_____no_output_____"
],
[
"df_weather.head()",
"_____no_output_____"
],
[
"df_weather['Visibility (mi)'] = df_weather['Visibility (km)']*0.621",
"_____no_output_____"
],
[
"df_weather.head()",
"_____no_output_____"
],
[
"#df_weather['Weather'].str.split(',', expand=True)",
"_____no_output_____"
]
],
[
[
"# Get LendingClub data\n[Source](https://www.lendingclub.com/info/download-data.action)",
"_____no_output_____"
]
],
[
[
"!wget https://resources.lendingclub.com/LoanStats_2018Q4.csv.zip",
"--2019-09-14 15:50:04-- https://resources.lendingclub.com/LoanStats_2018Q4.csv.zip\nResolving resources.lendingclub.com (resources.lendingclub.com)... 64.48.1.20\nConnecting to resources.lendingclub.com (resources.lendingclub.com)|64.48.1.20|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: unspecified [application/zip]\nSaving to: ‘LoanStats_2018Q4.csv.zip’\n\nLoanStats_2018Q4.cs [ <=>] 21.58M 880KB/s in 25s \n\n2019-09-14 15:50:29 (869 KB/s) - ‘LoanStats_2018Q4.csv.zip’ saved [22631049]\n\n"
],
[
"!unzip LoanStats_2018Q4.csv.zip",
"Archive: LoanStats_2018Q4.csv.zip\n inflating: LoanStats_2018Q4.csv \n"
],
[
"!head LoanStats_2018Q4.csv",
"Notes offered by Prospectus (https://www.lendingclub.com/info/prospectus.action)\n\"id\",\"member_id\",\"loan_amnt\",\"funded_amnt\",\"funded_amnt_inv\",\"term\",\"int_rate\",\"installment\",\"grade\",\"sub_grade\",\"emp_title\",\"emp_length\",\"home_ownership\",\"annual_inc\",\"verification_status\",\"issue_d\",\"loan_status\",\"pymnt_plan\",\"url\",\"desc\",\"purpose\",\"title\",\"zip_code\",\"addr_state\",\"dti\",\"delinq_2yrs\",\"earliest_cr_line\",\"inq_last_6mths\",\"mths_since_last_delinq\",\"mths_since_last_record\",\"open_acc\",\"pub_rec\",\"revol_bal\",\"revol_util\",\"total_acc\",\"initial_list_status\",\"out_prncp\",\"out_prncp_inv\",\"total_pymnt\",\"total_pymnt_inv\",\"total_rec_prncp\",\"total_rec_int\",\"total_rec_late_fee\",\"recoveries\",\"collection_recovery_fee\",\"last_pymnt_d\",\"last_pymnt_amnt\",\"next_pymnt_d\",\"last_credit_pull_d\",\"collections_12_mths_ex_med\",\"mths_since_last_major_derog\",\"policy_code\",\"application_type\",\"annual_inc_joint\",\"dti_joint\",\"verification_status_joint\",\"acc_now_delinq\",\"tot_coll_amt\",\"tot_cur_bal\",\"open_acc_6m\",\"open_act_il\",\"open_il_12m\",\"open_il_24m\",\"mths_since_rcnt_il\",\"total_bal_il\",\"il_util\",\"open_rv_12m\",\"open_rv_24m\",\"max_bal_bc\",\"all_util\",\"total_rev_hi_lim\",\"inq_fi\",\"total_cu_tl\",\"inq_last_12m\",\"acc_open_past_24mths\",\"avg_cur_bal\",\"bc_open_to_buy\",\"bc_util\",\"chargeoff_within_12_mths\",\"delinq_amnt\",\"mo_sin_old_il_acct\",\"mo_sin_old_rev_tl_op\",\"mo_sin_rcnt_rev_tl_op\",\"mo_sin_rcnt_tl\",\"mort_acc\",\"mths_since_recent_bc\",\"mths_since_recent_bc_dlq\",\"mths_since_recent_inq\",\"mths_since_recent_revol_delinq\",\"num_accts_ever_120_pd\",\"num_actv_bc_tl\",\"num_actv_rev_tl\",\"num_bc_sats\",\"num_bc_tl\",\"num_il_tl\",\"num_op_rev_tl\",\"num_rev_accts\",\"num_rev_tl_bal_gt_0\",\"num_sats\",\"num_tl_120dpd_2m\",\"num_tl_30dpd\",\"num_tl_90g_dpd_24m\",\"num_tl_op_past_12m\",\"pct_tl_nvr_dlq\",\"percent_bc_gt_75\",\"pub_rec_bankruptcies\",\"tax_liens\",\"tot_hi_cred_lim\",\"total_bal_ex_mort\",\"total_bc_limit\",\"total_il_high_credit_limit\",\"revol_bal_joint\",\"sec_app_earliest_cr_line\",\"sec_app_inq_last_6mths\",\"sec_app_mort_acc\",\"sec_app_open_acc\",\"sec_app_revol_util\",\"sec_app_open_act_il\",\"sec_app_num_rev_accts\",\"sec_app_chargeoff_within_12_mths\",\"sec_app_collections_12_mths_ex_med\",\"sec_app_mths_since_last_major_derog\",\"hardship_flag\",\"hardship_type\",\"hardship_reason\",\"hardship_status\",\"deferral_term\",\"hardship_amount\",\"hardship_start_date\",\"hardship_end_date\",\"payment_plan_start_date\",\"hardship_length\",\"hardship_dpd\",\"hardship_loan_status\",\"orig_projected_additional_accrued_interest\",\"hardship_payoff_balance_amount\",\"hardship_last_payment_amount\",\"debt_settlement_flag\",\"debt_settlement_flag_date\",\"settlement_status\",\"settlement_date\",\"settlement_amount\",\"settlement_percentage\",\"settlement_term\"\n\"\",\"\",\"10000\",\"10000\",\"10000\",\" 36 months\",\" 10.33%\",\"324.23\",\"B\",\"B1\",\"\",\"< 1 year\",\"MORTGAGE\",\"280000\",\"Not Verified\",\"Dec-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"974xx\",\"OR\",\"6.15\",\"2\",\"Jan-1996\",\"0\",\"18\",\"\",\"14\",\"0\",\"9082\",\"38%\",\"23\",\"w\",\"8289.30\",\"8289.30\",\"2261.0\",\"2261.00\",\"1710.70\",\"550.30\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"324.23\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"671\",\"246828\",\"1\",\"3\",\"2\",\"3\",\"1\",\"48552\",\"62\",\"1\",\"3\",\"4923\",\"46\",\"23900\",\"2\",\"7\",\"1\",\"7\",\"17631\",\"11897\",\"43.1\",\"0\",\"0\",\"158\",\"275\",\"11\",\"1\",\"1\",\"11\",\"\",\"11\",\"\",\"0\",\"3\",\"4\",\"7\",\"7\",\"10\",\"9\",\"11\",\"4\",\"14\",\"0\",\"0\",\"0\",\"4\",\"91.3\",\"28.6\",\"0\",\"0\",\"367828\",\"61364\",\"20900\",\"54912\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"4000\",\"4000\",\"4000\",\" 36 months\",\" 23.40%\",\"155.68\",\"E\",\"E1\",\"Security\",\"3 years\",\"RENT\",\"90000\",\"Source Verified\",\"Dec-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"070xx\",\"NJ\",\"26.33\",\"0\",\"Sep-2006\",\"4\",\"59\",\"\",\"15\",\"0\",\"5199\",\"19.2%\",\"20\",\"w\",\"3423.38\",\"3423.38\",\"1081.96\",\"1081.96\",\"576.62\",\"505.34\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"155.68\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"66926\",\"5\",\"4\",\"3\",\"4\",\"5\",\"61727\",\"86\",\"6\",\"11\",\"1353\",\"68\",\"27100\",\"4\",\"0\",\"4\",\"15\",\"4462\",\"20174\",\"7.9\",\"0\",\"0\",\"147\",\"118\",\"2\",\"2\",\"0\",\"2\",\"\",\"0\",\"\",\"0\",\"5\",\"7\",\"9\",\"9\",\"8\",\"11\",\"12\",\"7\",\"15\",\"0\",\"0\",\"0\",\"9\",\"95\",\"0\",\"0\",\"0\",\"98655\",\"66926\",\"21900\",\"71555\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"5000\",\"5000\",\"5000\",\" 36 months\",\" 17.97%\",\"180.69\",\"D\",\"D1\",\"Administrative\",\"6 years\",\"MORTGAGE\",\"59280\",\"Source Verified\",\"Dec-2018\",\"Late (31-120 days)\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"490xx\",\"MI\",\"10.51\",\"0\",\"Apr-2011\",\"0\",\"\",\"\",\"8\",\"0\",\"4599\",\"19.1%\",\"13\",\"w\",\"4456.17\",\"4456.17\",\"895.96\",\"895.96\",\"543.83\",\"352.13\",\"0.0\",\"0.0\",\"0.0\",\"Jun-2019\",\"180.69\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"110299\",\"0\",\"1\",\"0\",\"2\",\"14\",\"7150\",\"72\",\"0\",\"2\",\"0\",\"35\",\"24100\",\"1\",\"5\",\"0\",\"4\",\"18383\",\"13800\",\"0\",\"0\",\"0\",\"87\",\"92\",\"15\",\"14\",\"2\",\"77\",\"\",\"14\",\"\",\"0\",\"0\",\"3\",\"3\",\"3\",\"4\",\"6\",\"7\",\"3\",\"8\",\"0\",\"0\",\"0\",\"0\",\"100\",\"0\",\"0\",\"0\",\"136927\",\"11749\",\"13800\",\"10000\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"23000\",\"23000\",\"23000\",\" 60 months\",\" 20.89%\",\"620.81\",\"D\",\"D4\",\"Operator\",\"5 years\",\"RENT\",\"68107\",\"Source Verified\",\"Dec-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"672xx\",\"KS\",\"0.52\",\"0\",\"Feb-1997\",\"0\",\"\",\"\",\"5\",\"0\",\"976\",\"13%\",\"10\",\"w\",\"21353.16\",\"21353.16\",\"4307.45\",\"4307.45\",\"1646.84\",\"2660.61\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"620.81\",\"Sep-2019\",\"Aug-2019\",\"1\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"2693\",\"976\",\"0\",\"0\",\"0\",\"0\",\"36\",\"0\",\"\",\"3\",\"4\",\"0\",\"13\",\"7500\",\"2\",\"2\",\"4\",\"4\",\"195\",\"3300\",\"0\",\"0\",\"0\",\"237\",\"262\",\"10\",\"10\",\"0\",\"10\",\"\",\"9\",\"\",\"0\",\"0\",\"1\",\"3\",\"4\",\"3\",\"5\",\"7\",\"1\",\"5\",\"0\",\"0\",\"0\",\"3\",\"100\",\"0\",\"0\",\"0\",\"7500\",\"976\",\"3300\",\"0\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"8000\",\"8000\",\"8000\",\" 36 months\",\" 23.40%\",\"311.35\",\"E\",\"E1\",\"Manager\",\"10+ years\",\"OWN\",\"43000\",\"Source Verified\",\"Dec-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"357xx\",\"AL\",\"33.24\",\"0\",\"Jan-1995\",\"0\",\"\",\"107\",\"8\",\"1\",\"9019\",\"81.3%\",\"16\",\"w\",\"6846.83\",\"6846.83\",\"2163.85\",\"2163.85\",\"1153.17\",\"1010.68\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"311.35\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"169223\",\"0\",\"3\",\"2\",\"2\",\"7\",\"22059\",\"69\",\"0\",\"0\",\"2174\",\"72\",\"11100\",\"1\",\"1\",\"1\",\"2\",\"21153\",\"126\",\"94.5\",\"0\",\"0\",\"148\",\"287\",\"44\",\"7\",\"1\",\"51\",\"\",\"7\",\"\",\"0\",\"1\",\"4\",\"1\",\"2\",\"8\",\"4\",\"7\",\"4\",\"8\",\"0\",\"0\",\"0\",\"2\",\"100\",\"100\",\"1\",\"0\",\"199744\",\"31078\",\"2300\",\"32206\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"32075\",\"32075\",\"32075\",\" 60 months\",\" 11.80%\",\"710.26\",\"B\",\"B4\",\"Nursing Supervisor\",\"10+ years\",\"MORTGAGE\",\"150000\",\"Not Verified\",\"Dec-2018\",\"Current\",\"n\",\"\",\"\",\"credit_card\",\"Credit card refinancing\",\"231xx\",\"VA\",\"22.21\",\"0\",\"Aug-2005\",\"0\",\"\",\"\",\"17\",\"0\",\"19077\",\"32%\",\"24\",\"w\",\"29228.12\",\"29228.12\",\"4940.28\",\"4940.28\",\"2846.88\",\"2093.40\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"710.26\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"272667\",\"1\",\"4\",\"1\",\"1\",\"9\",\"37558\",\"47\",\"1\",\"1\",\"3910\",\"41\",\"59600\",\"1\",\"2\",\"0\",\"3\",\"16039\",\"10446\",\"47.8\",\"0\",\"0\",\"160\",\"70\",\"4\",\"4\",\"2\",\"27\",\"\",\"14\",\"\",\"0\",\"4\",\"10\",\"4\",\"4\",\"8\",\"12\",\"14\",\"10\",\"17\",\"0\",\"0\",\"0\",\"2\",\"100\",\"50\",\"0\",\"0\",\"360433\",\"56635\",\"20000\",\"80125\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"9600\",\"9600\",\"9600\",\" 36 months\",\" 12.98%\",\"323.37\",\"B\",\"B5\",\"\",\"n/a\",\"MORTGAGE\",\"35704\",\"Not Verified\",\"Dec-2018\",\"Current\",\"n\",\"\",\"\",\"home_improvement\",\"Home improvement\",\"401xx\",\"KY\",\"0.84\",\"0\",\"Nov-2003\",\"0\",\"69\",\"\",\"5\",\"0\",\"748\",\"11.5%\",\"23\",\"w\",\"8012.51\",\"8012.51\",\"2287.83\",\"2287.83\",\"1587.49\",\"700.34\",\"0.0\",\"0.0\",\"0.0\",\"Aug-2019\",\"323.37\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"748\",\"0\",\"0\",\"0\",\"0\",\"44\",\"0\",\"\",\"0\",\"3\",\"748\",\"12\",\"6500\",\"0\",\"0\",\"1\",\"3\",\"150\",\"3452\",\"17.8\",\"0\",\"0\",\"181\",\"100\",\"13\",\"13\",\"0\",\"16\",\"\",\"3\",\"\",\"0\",\"1\",\"1\",\"2\",\"2\",\"16\",\"5\",\"7\",\"1\",\"5\",\"0\",\"0\",\"0\",\"0\",\"95.5\",\"0\",\"0\",\"0\",\"6500\",\"748\",\"4200\",\"0\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"30000\",\"30000\",\"30000\",\" 60 months\",\" 18.94%\",\"777.23\",\"D\",\"D2\",\"Postmaster \",\"10+ years\",\"MORTGAGE\",\"90000\",\"Source Verified\",\"Dec-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"713xx\",\"LA\",\"26.52\",\"0\",\"Jun-1987\",\"0\",\"71\",\"75\",\"13\",\"1\",\"12315\",\"24.2%\",\"44\",\"w\",\"19969.40\",\"19969.40\",\"12893.26\",\"12893.26\",\"10030.60\",\"2862.66\",\"0.0\",\"0.0\",\"0.0\",\"Jul-2019\",\"777.23\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"1208\",\"321915\",\"4\",\"4\",\"2\",\"3\",\"3\",\"87153\",\"88\",\"4\",\"5\",\"998\",\"57\",\"50800\",\"2\",\"15\",\"2\",\"10\",\"24763\",\"13761\",\"8.3\",\"0\",\"0\",\"163\",\"378\",\"4\",\"3\",\"3\",\"4\",\"\",\"4\",\"\",\"0\",\"2\",\"4\",\"4\",\"9\",\"27\",\"8\",\"14\",\"4\",\"13\",\"0\",\"0\",\"0\",\"6\",\"95\",\"0\",\"1\",\"0\",\"372872\",\"99468\",\"15000\",\"94072\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n"
]
],
[
[
"# Load LendingClub data\npandas documentation\n-[`read_csv`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html)\n-[`option.display`](https://pandas.pydata.org/pandas-docs/stable/options.html#available-options)\n\n",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv('LoanStats_2018Q4.csv')\ndf.head()",
"/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (0,1,2,3,4,7,13,18,19,24,25,27,28,29,30,31,32,34,36,37,38,39,40,41,42,43,44,46,49,50,51,53,54,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,113,114,115,116,117,118,119,120,121,123,124,125,126,127,128,129,130,131,132,133,134,135,136,138,139,140,141,142,143) have mixed types. Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
],
[
"df = pd.read_csv('LoanStats_2018Q4.csv', header=1)\ndf.head()",
"/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2718: DtypeWarning: Columns (0,123,124,125,128,129,130,133,138,139,140) have mixed types. Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
],
[
"df.tail()",
"_____no_output_____"
],
[
"!tail LoanStats_2018Q4.csv",
"\"\",\"\",\"5600\",\"5600\",\"5600\",\" 36 months\",\" 13.56%\",\"190.21\",\"C\",\"C1\",\"\",\"n/a\",\"RENT\",\"15600\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"credit_card\",\"Credit card refinancing\",\"836xx\",\"ID\",\"15.31\",\"0\",\"Aug-2012\",\"0\",\"\",\"97\",\"9\",\"1\",\"5996\",\"34.5%\",\"11\",\"w\",\"4264.17\",\"4264.17\",\"1891.55\",\"1891.55\",\"1335.83\",\"555.72\",\"0.0\",\"0.0\",\"0.0\",\"Aug-2019\",\"190.21\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"5996\",\"0\",\"0\",\"0\",\"1\",\"20\",\"0\",\"\",\"0\",\"2\",\"3017\",\"35\",\"17400\",\"1\",\"0\",\"0\",\"3\",\"750\",\"4689\",\"45.5\",\"0\",\"0\",\"20\",\"73\",\"13\",\"13\",\"0\",\"13\",\"\",\"20\",\"\",\"0\",\"3\",\"5\",\"4\",\"4\",\"1\",\"9\",\"10\",\"5\",\"9\",\"0\",\"0\",\"0\",\"0\",\"100\",\"25\",\"1\",\"0\",\"17400\",\"5996\",\"8600\",\"0\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"23000\",\"23000\",\"23000\",\" 36 months\",\" 15.02%\",\"797.53\",\"C\",\"C3\",\"Tax Consultant\",\"10+ years\",\"MORTGAGE\",\"75000\",\"Source Verified\",\"Oct-2018\",\"Charged Off\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"352xx\",\"AL\",\"20.95\",\"1\",\"Aug-1985\",\"2\",\"22\",\"\",\"12\",\"0\",\"22465\",\"43.6%\",\"28\",\"w\",\"0.00\",\"0.00\",\"1547.08\",\"1547.08\",\"1025.67\",\"521.41\",\"0.0\",\"0.0\",\"0.0\",\"Dec-2018\",\"797.53\",\"\",\"Nov-2018\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"259658\",\"4\",\"2\",\"3\",\"3\",\"6\",\"18149\",\"86\",\"4\",\"6\",\"12843\",\"56\",\"51500\",\"2\",\"2\",\"5\",\"11\",\"21638\",\"26321\",\"44.1\",\"0\",\"0\",\"12\",\"397\",\"4\",\"4\",\"6\",\"5\",\"22\",\"4\",\"22\",\"0\",\"4\",\"5\",\"7\",\"14\",\"3\",\"9\",\"19\",\"5\",\"12\",\"0\",\"0\",\"0\",\"7\",\"96.4\",\"14.3\",\"0\",\"0\",\"296500\",\"40614\",\"47100\",\"21000\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"10000\",\"10000\",\"10000\",\" 36 months\",\" 15.02%\",\"346.76\",\"C\",\"C3\",\"security guard\",\"5 years\",\"MORTGAGE\",\"38000\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"443xx\",\"OH\",\"13.16\",\"3\",\"Jul-1982\",\"0\",\"6\",\"\",\"11\",\"0\",\"5634\",\"37.1%\",\"16\",\"w\",\"7655.00\",\"7655.00\",\"3459.26\",\"3459.26\",\"2345.00\",\"1114.26\",\"0.0\",\"0.0\",\"0.0\",\"Aug-2019\",\"346.76\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"155\",\"77424\",\"0\",\"1\",\"0\",\"0\",\"34\",\"200\",\"10\",\"1\",\"1\",\"1866\",\"42\",\"15200\",\"2\",\"0\",\"0\",\"2\",\"7039\",\"4537\",\"50.1\",\"0\",\"0\",\"34\",\"434\",\"11\",\"11\",\"3\",\"11\",\"6\",\"17\",\"6\",\"0\",\"3\",\"5\",\"5\",\"6\",\"1\",\"8\",\"11\",\"5\",\"11\",\"0\",\"0\",\"0\",\"1\",\"73.3\",\"40\",\"0\",\"0\",\"91403\",\"9323\",\"9100\",\"2000\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"5000\",\"5000\",\"5000\",\" 36 months\",\" 13.56%\",\"169.83\",\"C\",\"C1\",\"Payoff Clerk\",\"10+ years\",\"MORTGAGE\",\"35360\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"debt_consolidation\",\"Debt consolidation\",\"381xx\",\"TN\",\"11.3\",\"1\",\"Jun-2006\",\"0\",\"21\",\"\",\"9\",\"0\",\"2597\",\"27.3%\",\"15\",\"f\",\"3807.30\",\"3807.30\",\"1694.53\",\"1694.53\",\"1192.70\",\"501.83\",\"0.0\",\"0.0\",\"0.0\",\"Aug-2019\",\"169.83\",\"Sep-2019\",\"Aug-2019\",\"0\",\"\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"1413\",\"69785\",\"0\",\"2\",\"0\",\"1\",\"16\",\"2379\",\"40\",\"3\",\"4\",\"1826\",\"32\",\"9500\",\"0\",\"0\",\"1\",\"5\",\"8723\",\"1174\",\"60.9\",\"0\",\"0\",\"147\",\"85\",\"9\",\"9\",\"2\",\"10\",\"21\",\"9\",\"21\",\"0\",\"1\",\"3\",\"2\",\"2\",\"6\",\"6\",\"7\",\"3\",\"9\",\"0\",\"0\",\"0\",\"3\",\"92.9\",\"50\",\"0\",\"0\",\"93908\",\"4976\",\"3000\",\"6028\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"10000\",\"10000\",\"9750\",\" 36 months\",\" 11.06%\",\"327.68\",\"B\",\"B3\",\"\",\"n/a\",\"RENT\",\"44400\",\"Source Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"credit_card\",\"Credit card refinancing\",\"980xx\",\"WA\",\"11.78\",\"0\",\"Oct-2008\",\"2\",\"40\",\"\",\"15\",\"0\",\"6269\",\"13.1%\",\"25\",\"f\",\"7544.75\",\"7356.13\",\"3261.44\",\"3179.90\",\"2455.25\",\"806.19\",\"0.0\",\"0.0\",\"0.0\",\"Aug-2019\",\"327.68\",\"Sep-2019\",\"Aug-2019\",\"0\",\"53\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"520\",\"16440\",\"3\",\"1\",\"1\",\"1\",\"2\",\"10171\",\"100\",\"2\",\"5\",\"404\",\"28\",\"47700\",\"0\",\"3\",\"5\",\"6\",\"1265\",\"20037\",\"2.3\",\"0\",\"0\",\"61\",\"119\",\"1\",\"1\",\"0\",\"1\",\"\",\"1\",\"40\",\"1\",\"2\",\"4\",\"6\",\"8\",\"3\",\"14\",\"22\",\"4\",\"15\",\"0\",\"0\",\"0\",\"3\",\"92\",\"0\",\"0\",\"0\",\"57871\",\"16440\",\"20500\",\"10171\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\"\",\"\",\"10000\",\"10000\",\"10000\",\" 36 months\",\" 16.91%\",\"356.08\",\"C\",\"C5\",\"Key Accounts Manager\",\"2 years\",\"RENT\",\"80000\",\"Not Verified\",\"Oct-2018\",\"Current\",\"n\",\"\",\"\",\"other\",\"Other\",\"021xx\",\"MA\",\"17.72\",\"1\",\"Sep-2006\",\"0\",\"14\",\"\",\"17\",\"0\",\"1942\",\"30.8%\",\"31\",\"w\",\"7706.67\",\"7706.67\",\"3551.41\",\"3551.41\",\"2293.33\",\"1258.08\",\"0.0\",\"0.0\",\"0.0\",\"Aug-2019\",\"356.08\",\"Sep-2019\",\"Aug-2019\",\"0\",\"25\",\"1\",\"Individual\",\"\",\"\",\"\",\"0\",\"0\",\"59194\",\"0\",\"15\",\"1\",\"1\",\"12\",\"57252\",\"85\",\"0\",\"0\",\"1942\",\"80\",\"6300\",\"0\",\"5\",\"0\",\"1\",\"3482\",\"2058\",\"48.5\",\"0\",\"0\",\"144\",\"142\",\"40\",\"12\",\"0\",\"131\",\"30\",\"\",\"30\",\"3\",\"1\",\"1\",\"1\",\"5\",\"22\",\"2\",\"9\",\"1\",\"17\",\"0\",\"0\",\"0\",\"1\",\"74.2\",\"0\",\"0\",\"0\",\"73669\",\"59194\",\"4000\",\"67369\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"N\",\"\",\"\",\"\",\"\",\"\",\"\"\n\n\nTotal amount funded in policy code 1: 2050909275\nTotal amount funded in policy code 2: 820109297\n"
],
[
"df = pd.read_csv('LoanStats_2018Q4.csv', header=1, skipfooter=2, engine='python')\ndf.head()",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"pd.set_option('display.max_rows', 50)\npd.set_option('display.max_columns', 50)",
"_____no_output_____"
],
[
"df.isnull().sum()",
"_____no_output_____"
],
[
"df.isnull().sum().sort_values(ascending=False)",
"_____no_output_____"
]
],
[
[
"## Work with strings",
"_____no_output_____"
],
[
"For machine learning, we usually want to replace strings with numbers.\nWe can get info about which columbs have a datatype of \"object\" (strings)",
"_____no_output_____"
]
],
[
[
"df.drop(columns=['id', 'member_id', 'desc', 'url'])\n#df.drop(columns=['id', 'member_id', 'desc', 'url'], inplace=True) #not recommended",
"_____no_output_____"
],
[
"df = df.drop(columns=['id', 'member_id', 'desc', 'url'])",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"hardship_cols = [col for col in df.columns if col.startswith('hardship_')]\nhardship_cols",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df = df.drop(columns=hardship_cols)",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df.describe(exclude='number')",
"_____no_output_____"
]
],
[
[
"### Convert int_rate",
"_____no_output_____"
],
[
"Define a function to remove percent signs from strings and convert to floats",
"_____no_output_____"
]
],
[
[
"df['int_rate']",
"_____no_output_____"
],
[
"#really don't understand what this is about\na = '16.91%'\na[:-1]",
"_____no_output_____"
],
[
"a.strip('%')",
"_____no_output_____"
],
[
"b = '%16%.91%'\nb.strip('%')",
"_____no_output_____"
],
[
"b[:-1]",
"_____no_output_____"
],
[
"b.replace('%', '')",
"_____no_output_____"
],
[
"float(b.replace('%', ''))",
"_____no_output_____"
]
],
[
[
"Apply the function to the int_rate column",
"_____no_output_____"
]
],
[
[
"def remove_percent_to_float(x): \n return float(x[:-1])",
"_____no_output_____"
],
[
"remove_percent_to_float_v2 = lambda x: float(x[:-1])",
"_____no_output_____"
],
[
"remove_percent_to_float('16.91%')",
"_____no_output_____"
],
[
"remove_percent_to_float_v2('16.91%')",
"_____no_output_____"
],
[
"a = ['16.91%', '12.23%', '15.75%']\n[remove_percent_to_float(i) for i in a]",
"_____no_output_____"
],
[
"df['int_rate'] = df['int_rate'].apply(remove_percent_to_float)\n#df['int_rate'].apply(lambda x: float(x[:-1]))",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"###Clean emp_title\nLook at top 20 titles",
"_____no_output_____"
]
],
[
[
"df['emp_title'].value_counts(dropna=False).head(20)",
"_____no_output_____"
]
],
[
[
"How often is emp_title null?",
"_____no_output_____"
]
],
[
[
"df['emp_title'].nunique()",
"_____no_output_____"
],
[
"df.describe(exclude='number')",
"_____no_output_____"
]
],
[
[
"Clean the title and handle missing values",
"_____no_output_____"
]
],
[
[
"def clean_title(title):\n if isinstance(title, str):\n return title.strip().lower()\n else:\n return 'unknown'",
"_____no_output_____"
],
[
"df['emp_title'] = df['emp_title'].apply(clean_title)",
"_____no_output_____"
],
[
"df['emp_title'].value_counts(dropna=False).head(20)",
"_____no_output_____"
],
[
"type(np.NaN)",
"_____no_output_____"
]
],
[
[
"###Create emp_title_manager\npandas documentation: str.contains",
"_____no_output_____"
]
],
[
[
"df['emp_title_manager'] = df['emp_title'].str.contains('manager')",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"mask = df['emp_title_manager'] == True\nmanagers = df[mask]\nplebians = df[~mask]",
"_____no_output_____"
],
[
"managers.shape[0]",
"_____no_output_____"
],
[
"plebians.shape[0]",
"_____no_output_____"
],
[
"df.shape[0]",
"_____no_output_____"
],
[
"assert managers.shape[0] + plebians.shape[0] == df.shape[0]",
"_____no_output_____"
]
],
[
[
"##Work with dates",
"_____no_output_____"
],
[
"pandas documentation\n- [to_datetime](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html)\n- [Time/Date Components](https://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-date-components) \"You can access these properties via the .dt accessor\"",
"_____no_output_____"
]
],
[
[
"df['issue_d']",
"_____no_output_____"
],
[
"df['issue_d'] = pd.to_datetime(df['issue_d'], infer_datetime_format=True)",
"_____no_output_____"
],
[
"df['issue_d']",
"_____no_output_____"
],
[
"df['issue_d'].dt.weekday",
"_____no_output_____"
],
[
"df['issue_year'] = df['issue_d'].dt.year\ndf['issue_month'] = df['issue_d'].dt.month",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df['earliest_cr_line'] = pd.to_datetime(df['earliest_cr_line'], infer_datetime_format=True)",
"_____no_output_____"
],
[
"df['days_from_cr_line_to_loan'] = (df['issue_d'] - df['earliest_cr_line']).dt.days",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df['issue_d'].dt.strftime('%Y %B %d')",
"_____no_output_____"
]
],
[
[
"# STRETCH OPTIONS\n\nYou can do more with the LendingClub or Instacart datasets.\n\nLendingClub options:\n- There's one other column in the dataframe with percent signs. Remove them and convert to floats. You'll need to handle missing values.\n- Modify the `emp_title` column to replace titles with 'Other' if the title is not in the top 20. \n- Take initiatve and work on your own ideas!\n\nInstacart options:\n- Read [Instacart Market Basket Analysis, Winner's Interview: 2nd place, Kazuki Onodera](http://blog.kaggle.com/2017/09/21/instacart-market-basket-analysis-winners-interview-2nd-place-kazuki-onodera/), especially the **Feature Engineering** section. (Can you choose one feature from his bulleted lists, and try to engineer it with pandas code?)\n- Read and replicate parts of [Simple Exploration Notebook - Instacart](https://www.kaggle.com/sudalairajkumar/simple-exploration-notebook-instacart). (It's the Python Notebook with the most upvotes for this Kaggle competition.)\n- Take initiative and work on your own ideas!",
"_____no_output_____"
],
[
"You can uncomment and run the cells below to re-download and extract the Instacart data",
"_____no_output_____"
]
],
[
[
"# !wget https://s3.amazonaws.com/instacart-datasets/instacart_online_grocery_shopping_2017_05_01.tar.gz",
"_____no_output_____"
],
[
"# !tar --gunzip --extract --verbose --file=instacart_online_grocery_shopping_2017_05_01.tar.gz",
"_____no_output_____"
],
[
"# %cd instacart_2017_05_01",
"_____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"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
ece5eb6ea1a15143781f1e0918038e5288e7c976 | 499,966 | ipynb | Jupyter Notebook | examples/storage-qpi-report/storage-qpi.ipynb | hashnfv/hashnfv-qtip | 2c79d3361fdb1fcbe67682f8a205011b3ccf5e72 | [
"Apache-2.0"
] | 4 | 2016-11-27T19:21:48.000Z | 2018-01-08T21:49:03.000Z | examples/storage-qpi-report/storage-qpi.ipynb | hashnfv/hashnfv-qtip | 2c79d3361fdb1fcbe67682f8a205011b3ccf5e72 | [
"Apache-2.0"
] | null | null | null | examples/storage-qpi-report/storage-qpi.ipynb | hashnfv/hashnfv-qtip | 2c79d3361fdb1fcbe67682f8a205011b3ccf5e72 | [
"Apache-2.0"
] | 10 | 2017-03-19T07:38:40.000Z | 2018-01-08T21:49:09.000Z | 206.512185 | 128,584 | 0.832723 | [
[
[
"# Storage QPI Report",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport json\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport qgrid\n\nqgrid.nbinstall(overwrite=True)\n\nRESULT_FILE = './zte-apex-virtual.json'\nwith open(RESULT_FILE, 'r') as f:\n result_data = json.load(f)\nmetrics = result_data['report']['metrics']\n\n# TODO(yujunz) move common functiont to qtip package\n\ndef metrics_to_dataframe(metrics):\n \"\"\"convert storperf metrics to DataFrame\"\"\"\n def _convert(metric, value):\n columns = metric.split('.')\n return {\n 'workload_name': columns[0],\n 'queue_depth': columns[2],\n 'block_size': columns[4],\n 'read_write': columns[5],\n 'metric_name': ('.').join(columns[6:]),\n 'value': value\n }\n\n return pd.DataFrame([_convert(*p) for p in metrics.items()])\n\ndef get_metric(metric_name):\n return df[df.metric_name == metric_name]\n\ndef plot_metric(metric_name):\n df_metric = get_metric(metric_name)\n fig = plt.figure(figsize=(16,9))\n\n ax = fig.add_subplot(111, projection='3d')\n for wl, rw, c in zip(['rw', 'rw', 'wr', 'rr'], ['read', 'write', 'write', 'read'], ['r', 'g', 'b', 'y']):\n _df = df_metric[(df_metric.workload_name == wl) & (df_metric.read_write == rw)]\n ax.scatter(_df.block_size, _df.queue_depth, _df['value'], c=c, label='{}.{}'.format(wl, rw))\n\n ax.set_xlabel('block size')\n ax.set_ylabel('queue depth')\n ax.set_zlabel(metric_name)\n ax.legend()\n\ndf = metrics_to_dataframe(metrics)\n\n# filter invalid data\ndf = df[(df.workload_name != '_warm_up') & (df.value != 0.0)]\ndf.block_size = df.block_size.astype(int)\ndf.queue_depth = df.queue_depth.astype(int)",
"_____no_output_____"
]
],
[
[
"## Test Results\n\n### Bandwidth",
"_____no_output_____"
]
],
[
[
"get_metric('bw')",
"_____no_output_____"
],
[
"plot_metric('bw')",
"_____no_output_____"
]
],
[
[
"### IOPS",
"_____no_output_____"
]
],
[
[
"get_metric('iops')",
"_____no_output_____"
],
[
"plot_metric('iops')",
"_____no_output_____"
]
],
[
[
"### Latency",
"_____no_output_____"
]
],
[
[
"get_metric('lat.mean')",
"_____no_output_____"
],
[
"plot_metric('lat.mean')",
"_____no_output_____"
]
],
[
[
"## System Information\n\n### Hardware\n\nTBD\n\n### Software\n\nTBD",
"_____no_output_____"
],
[
"## Test Configuration\n\nTBD",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
ece615df1ef1631ccb9d026c73f7d61df1a321c6 | 22,184 | ipynb | Jupyter Notebook | notebooks/MDSplus/MDSplus_EAST_example.ipynb | Hash--/documents | 86a2ba249a3a478cba9bdcd511d02c4f4302d6fc | [
"MIT"
] | null | null | null | notebooks/MDSplus/MDSplus_EAST_example.ipynb | Hash--/documents | 86a2ba249a3a478cba9bdcd511d02c4f4302d6fc | [
"MIT"
] | null | null | null | notebooks/MDSplus/MDSplus_EAST_example.ipynb | Hash--/documents | 86a2ba249a3a478cba9bdcd511d02c4f4302d6fc | [
"MIT"
] | null | null | null | 59.157333 | 1,350 | 0.736882 | [
[
[
"import MDSplus as mds\n%pylab inline",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"# mds.ipp.ac.cn corresponds to public IP 202.127.204.12\n# Also working : 202.127.204.42, 202.127.205.8\ncnx = mds.Connection('mds.ipp.ac.cn') ",
"_____no_output_____"
],
[
"shot_nb = 55672\ncnx.openTree('east', shot_nb)",
"_____no_output_____"
],
[
"Ip = cnx.get('\\IPM')\nt_Ip = cnx.get('dim_of(\\IPM)')",
"_____no_output_____"
],
[
"plot(t_Ip, Ip, lw=2)\ngrid()\nxlim(0,8)",
"_____no_output_____"
]
],
[
[
"A more pretty (or Pythonesque) approach from Laurent : ",
"_____no_output_____"
]
],
[
[
"def get_signal(signal_name, shot_nb, mdsplus_connection):\n \"\"\"\n Retrieves a signal and its associated time vector \n for a given shot number on EAST\n \"\"\"\n mdsplus_connection.openTree('EAST', shot_nb)\n return mdsplus_connection.get(signal_name), \\\n mdsplus_connection.get('dim_of('+signal_name+')')",
"_____no_output_____"
],
[
"Ip, t_Ip = get_signal('\\IPM', shot_nb, cnx)",
"_____no_output_____"
],
[
"Ne, t_Ne = get_signal('TOP:\\dfsdev', shot_nb, cnx)",
"_____no_output_____"
]
],
[
[
"# A list of various signals",
"_____no_output_____"
],
[
"| __sig_name__ | __description__ |\n|----------|-------------|\n| `\\IPM` | plasma current |\n| `\\dfsdev` | \n| `\\plhi1` | LHCD 1 Incident power |\n| `\\plhi2` | LHCD 2 Incident power |\n| `\\plhr1` | LHCD 1 Reflected power |\n| `\\plhr2` | LHCD 2 Reflected power |\n| `\\nbi1lhv` | BOX1 - LEFT - NBI |\n| `\\nbi2lhv` | BOX2 |\n| `\\nbi1rhv` | BOX1 - RIGHT - NBI |\n| `\\nbi2rhv` | BOX2 |\n| `\\icrf9` | antenna B - Line 1 |\n| `\\icrf10` | |\n| `\\icrf11` | antenna B - Line 2 |\n| `\\icrf12` | |\n| `\\icrf13` |antenna B - Line 3 |\n| `\\icrf14` | |\n| `\\icrf15` |antenna B - Line 4 |\n| `\\icrf16` | |\n| `\\te0_hrs` | Te0 |\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
ece62ae782afab306043d3a582d036d67d6b3626 | 8,020 | ipynb | Jupyter Notebook | fixed_pop_mesa_merge/plot_mesa_fixed_pop.ipynb | celiotine/COSMIC_BSE_analysis | bbab33269e78db6bb176ad873f161e23eecb9063 | [
"MIT"
] | null | null | null | fixed_pop_mesa_merge/plot_mesa_fixed_pop.ipynb | celiotine/COSMIC_BSE_analysis | bbab33269e78db6bb176ad873f161e23eecb9063 | [
"MIT"
] | null | null | null | fixed_pop_mesa_merge/plot_mesa_fixed_pop.ipynb | celiotine/COSMIC_BSE_analysis | bbab33269e78db6bb176ad873f161e23eecb9063 | [
"MIT"
] | null | null | null | 27.372014 | 163 | 0.516209 | [
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np",
"_____no_output_____"
],
[
"## read the bpp (history) data frame\nbpp = pd.read_hdf(\"dat_ThinDisk_14_14.h5\", key=\"bpp\")\nbcm = pd.read_hdf(\"dat_ThinDisk_14_14.h5\", key=\"bcm\")\nbpp.columns",
"_____no_output_____"
],
[
"## get all binary index values]\nid_vals = np.array(bpp.index)\nIDs = np.unique(id_vals)",
"_____no_output_____"
],
[
"## find all HMXB systems that result in BH merger\n## one star is > 30 Msun, other is BH\n\n## THIS MAY TAKE AWHILE TO RUN, BE CAREFUL\n\nHMXB_ids = []\nHMXB_masses = [] ### mass of star at beginning of HMXB\n\nHMXB_df = pd.DataFrame(columns=bpp.columns)\n\n\n## MAKE THIS FASTER\nfor index in IDs:\n for row in range(0, len(bpp.loc[index].bin_num)):\n \n if bpp.loc[index].kstar_1.iloc[row] == 1.0 and bpp.loc[index].kstar_2.iloc[row] == 14.0 \\\n and bpp.loc[index].mass_1.iloc[row] > 15.0:\n \n #HMXB_ids.append(index)\n HMXB_masses.append(bpp.loc[index].mass_1.iloc[0])\n HMXB_df = HMXB_df.append(bpp.loc[index])\n break\n \n elif bpp.loc[index].kstar_1.iloc[row] == 14.0 and bpp.loc[index].kstar_2.iloc[row] == 1.0 \\\n and bpp.loc[index].mass_2.iloc[row] > 15.0:\n\n #HMXB_ids.append(index)\n HMXB_masses.append(bpp.loc[index].mass_2.iloc[0])\n HMXB_df = HMXB_df.append(bpp.loc[index])\n break\n ",
"_____no_output_____"
],
[
"HMXB_df.to_csv()",
"_____no_output_____"
],
[
"print (HMXB_df)",
"_____no_output_____"
],
[
"np.save(\"HMXB_ids_15\", HMXB_ids)\n",
"_____no_output_____"
],
[
"with open(\"HMXB_data_15\", \"wb\") as fp: #Pickling\n pickle.dump(HMXB_data, fp)",
"_____no_output_____"
],
[
"## load saved data from arrays created above\nHMXB_mass_20 = np.load(\"HMXB_ids_20.npy\")\nHMXB_mass_25 = np.load(\"HMXB_ids_25.npy\")\nHMXB_mass_30 = np.load(\"HMXB_ids_30.npy\")\nHMXB_mass_35 = np.load(\"HMXB_ids_35.npy\")\nHMXB_mass_40 = np.load(\"HMXB_ids_40.npy\")\nHMXB_mass_45 = np.load(\"HMXB_ids_45.npy\")\nHMXB_mass_50 = np.load(\"HMXB_ids_50.npy\")",
"_____no_output_____"
],
[
"print (\"Percent HMXBs (M > 20Msun): \" , len(HMXB_mass_20)/len(IDs)*100) ## all of these systems merge\nprint (HMXB_mass_20)",
"_____no_output_____"
],
[
"non_HMXBs = []\n\nfor bin_num in bpp.bin_num:\n if bin_num not in HMXB_mass_20:\n non_HMXBs.append(bin_num)\n",
"_____no_output_____"
],
[
"## function to calculate BH accretion rate and luminosity\ndef calc_acc_luminosity(BH_mass_data, time_data):\n \n c = 2.99e8 ## speed of light in m/s\n Myr = 1e6 ## years per Myr\n secyr = 3.154e7 ## seconds per year\n Msun = 1.989e33 ## grams per solar mass\n \n all_data = []\n \n acc_rate = [] ## BH mass accretion rate in Msun/yr\n luminosity = [] ## BH accretion luminosity in erg/sec\n\n luminosity.append(0)\n acc_rate.append(0)\n\n for i in range(1, len(time_data)):\n \n eta = 1 - np.sqrt(1-(BH_mass_data.iloc[i].iloc[0]/(3*BH_mass_data.iloc[0].iloc[0]))**2)\n \n if (time_data.iloc[i].iloc[0] - time_data.iloc[i-1].iloc[0]) == 0:\n acc_rate.append(acc_rate[i-1])\n luminosity.append(eta*acc_rate[i-1]*c**2*(Msun*10000/secyr))\n continue\n \n \n else:\n acc_rate.append((BH_mass_data.iloc[i].iloc[0] - BH_mass_data.iloc[i-1].iloc[0])/(time_data.iloc[i].iloc[0] - time_data.iloc[i-1].iloc[0])/Myr)\n \n luminosity.append(eta*acc_rate[i]*c**2*(Msun*10000/secyr))\n \n all_data.extend([acc_rate, luminosity])\n return all_data\n",
"_____no_output_____"
],
[
"## plot BH accretion rates and luminosities of HMXBs\n\nfig, ax = plt.subplots(figsize=(8,5))\nfig1, ax1 = plt.subplots(figsize=(8,5))\n\n\n\nfor ID in HMXB_mass_30[:100]:\n binary_acc_data = calc_acc_luminosity(bpp.loc[ID, ['mass_2']], bpp.loc[ID,['tphys']])\n ax.plot(binary_acc_data[0])\n ax1.plot(binary_acc_data[1])\n\nax1.set_xlabel(\"Time (Myr)\", size=13)\nax1.set_ylabel(\"BH Accretion Luminosity (erg/sec)\", size=13)\nax1.set_xlim(1, 7)\nax1.set_ylim(0)\n\nax.set_xlabel(\"Time (Myr)\", size=13)\nax.set_ylabel(\"BH Mass Accretion Rate (Msun/yr)\", size=13)\nax.set_xlim(1, 7)\nax.set_ylim(0)\n\n\nax.set_title(\"HMXBs w/ $M_{donor} > 30 M_\\odot$\" )\nplt.show()",
"_____no_output_____"
],
[
"max_acc_luminosity = []\n\nfor ID in HMXB_mass_50:\n binary_acc_data = calc_acc_luminosity(bpp.loc[ID, ['mass_2']], bpp.loc[ID,['tphys']])\n \n ## FIX: THIS IS NOT CORRECT, INITIAL DONOR MASS IS NOT SAME AS INITIAL HMXB MASS\n max_acc_luminosity.append(max(binary_acc_data[1]))\n ",
"_____no_output_____"
],
[
"np.save(\"initial_donor_mass_50\", initial_donor_mass)\nnp.save(\"max_acc_luminosity_50\", max_acc_luminosity)",
"_____no_output_____"
],
[
"initial_donor_mass_50 = np.load(\"initial_donor_mass_50.npy\")",
"_____no_output_____"
],
[
"print (min(initial_donor_mass_50)) ",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece62b1a99e723c8e774c6ea615d46dda6387f82 | 99,345 | ipynb | Jupyter Notebook | 5-sequence-models/week2/Emoji_v3a.ipynb | alekshiidenhovi/Deep-Learning-Specialization | a58e4c8dbd6a71f41363bfebe4f8fa10ee45e541 | [
"MIT"
] | null | null | null | 5-sequence-models/week2/Emoji_v3a.ipynb | alekshiidenhovi/Deep-Learning-Specialization | a58e4c8dbd6a71f41363bfebe4f8fa10ee45e541 | [
"MIT"
] | null | null | null | 5-sequence-models/week2/Emoji_v3a.ipynb | alekshiidenhovi/Deep-Learning-Specialization | a58e4c8dbd6a71f41363bfebe4f8fa10ee45e541 | [
"MIT"
] | null | null | null | 39.469607 | 8,560 | 0.57717 | [
[
[
"# Emojify! \n\nWelcome to the second assignment of Week 2! You're going to use word vector representations to build an Emojifier. \n🤩 💫 🔥\n\nHave you ever wanted to make your text messages more expressive? Your emojifier app will help you do that. \nRather than writing:\n>\"Congratulations on the promotion! Let's get coffee and talk. Love you!\" \n\nThe emojifier can automatically turn this into:\n>\"Congratulations on the promotion! 👍 Let's get coffee and talk. ☕️ Love you! ❤️\"\n\nYou'll implement a model which inputs a sentence (such as \"Let's go see the baseball game tonight!\") and finds the most appropriate emoji to be used with this sentence (⚾️).\n\n### Using Word Vectors to Improve Emoji Lookups\n* In many emoji interfaces, you need to remember that ❤️ is the \"heart\" symbol rather than the \"love\" symbol. \n * In other words, you'll have to remember to type \"heart\" to find the desired emoji, and typing \"love\" won't bring up that symbol.\n* You can make a more flexible emoji interface by using word vectors!\n* When using word vectors, you'll see that even if your training set explicitly relates only a few words to a particular emoji, your algorithm will be able to generalize and associate additional words in the test set to the same emoji.\n * This works even if those additional words don't even appear in the training set. \n * This allows you to build an accurate classifier mapping from sentences to emojis, even using a small training set. \n\n### What you'll build:\n1. In this exercise, you'll start with a baseline model (Emojifier-V1) using word embeddings.\n2. Then you will build a more sophisticated model (Emojifier-V2) that further incorporates an LSTM. \n\nBy the end of this notebook, you'll be able to:\n\n* Create an embedding layer in Keras with pre-trained word vectors\n* Explain the advantages and disadvantages of the GloVe algorithm\n* Describe how negative sampling learns word vectors more efficiently than other methods\n* Build a sentiment classifier using word embeddings\n* Build and train a more sophisticated classifier using an LSTM\n\n🏀 👑\n\n👆 😎\n\n(^^^ Emoji for \"skills\") ",
"_____no_output_____"
],
[
"## Table of Contents\n\n- [Packages](#0)\n- [1 - Baseline Model: Emojifier-V1](#1)\n - [1.1 - Dataset EMOJISET](#1-1)\n - [1.2 - Overview of the Emojifier-V1](#1-2)\n - [1.3 - Implementing Emojifier-V1](#1-3)\n - [Exercise 1 - sentence_to_avg](#ex-1)\n - [1.4 - Implement the Model](#1-4)\n - [Exercise 2 - model](#ex-2)\n - [1.5 - Examining Test Set Performance](#1-5)\n- [2 - Emojifier-V2: Using LSTMs in Keras](#2)\n - [2.1 - Model Overview](#2-1)\n - [2.2 Keras and Mini-batching](#2-2)\n - [2.3 - The Embedding Layer](#2-3)\n - [Exercise 3 - sentences_to_indices](#ex-3)\n - [Exercise 4 - pretrained_embedding_layer](#ex-4)\n - [2.4 - Building the Emojifier-V2](#2-4)\n - [Exercise 5 - Emojify_V2](#ex-5)\n - [2.5 - Train the Model](#2-5)\n- [3 - Acknowledgments](#3)",
"_____no_output_____"
],
[
"<a name='0'></a>\n## Packages\n\nLet's get started! Run the following cell to load the packages you're going to use. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom emo_utils import *\nimport emoji\nimport matplotlib.pyplot as plt\nfrom test_utils import *\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"<a name='1'></a>\n## 1 - Baseline Model: Emojifier-V1\n\n<a name='1-1'></a>\n### 1.1 - Dataset EMOJISET\n\nLet's start by building a simple baseline classifier. \n\nYou have a tiny dataset (X, Y) where:\n- X contains 127 sentences (strings).\n- Y contains an integer label between 0 and 4 corresponding to an emoji for each sentence.\n\n<img src=\"images/data_set.png\" style=\"width:700px;height:300px;\">\n<caption><center><font color='purple'><b>Figure 1</b>: EMOJISET - a classification problem with 5 classes. A few examples of sentences are given here. </center></caption>\n\nLoad the dataset using the code below. The dataset is split between training (127 examples) and testing (56 examples).",
"_____no_output_____"
]
],
[
[
"X_train, Y_train = read_csv('data/train_emoji.csv')\nX_test, Y_test = read_csv('data/tesss.csv')",
"_____no_output_____"
],
[
"maxLen = len(max(X_train, key=len).split())",
"_____no_output_____"
]
],
[
[
"Run the following cell to print sentences from X_train and corresponding labels from Y_train. \n* Change `idx` to see different examples. \n* Note that due to the font used by iPython notebook, the heart emoji may be colored black rather than red.",
"_____no_output_____"
]
],
[
[
"for idx in range(10):\n print(X_train[idx], label_to_emoji(Y_train[idx]))",
"never talk to me again 😞\nI am proud of your achievements 😄\nIt is the worst day in my life 😞\nMiss you so much ❤️\nfood is life 🍴\nI love you mum ❤️\nStop saying bullshit 😞\ncongratulations on your acceptance 😄\nThe assignment is too long 😞\nI want to go play ⚾\n"
]
],
[
[
"<a name='1-2'></a>\n### 1.2 - Overview of the Emojifier-V1\n\nIn this section, you'll implement a baseline model called \"Emojifier-v1\". \n\n<center>\n<img src=\"images/image_1.png\" style=\"width:900px;height:300px;\">\n <caption><center><font color='purple'><b>Figure 2</b>: Baseline model (Emojifier-V1).</center></caption>\n</center></font>\n\n\n#### Inputs and Outputs\n* The input of the model is a string corresponding to a sentence (e.g. \"I love you\"). \n* The output will be a probability vector of shape (1,5), (indicating that there are 5 emojis to choose from).\n* The (1,5) probability vector is passed to an argmax layer, which extracts the index of the emoji with the highest probability.",
"_____no_output_____"
],
[
"#### One-hot Encoding\n* To get your labels into a format suitable for training a softmax classifier, convert $Y$ from its current shape $(m, 1)$ into a \"one-hot representation\" $(m, 5)$, \n * Each row is a one-hot vector giving the label of one example.\n * Here, `Y_oh` stands for \"Y-one-hot\" in the variable names `Y_oh_train` and `Y_oh_test`: ",
"_____no_output_____"
]
],
[
[
"Y_oh_train = convert_to_one_hot(Y_train, C = 5)\nY_oh_test = convert_to_one_hot(Y_test, C = 5)",
"_____no_output_____"
]
],
[
[
"Now, see what `convert_to_one_hot()` did. Feel free to change `index` to print out different values. ",
"_____no_output_____"
]
],
[
[
"idx = 50\nprint(f\"Sentence '{X_train[50]}' has label index {Y_train[idx]}, which is emoji {label_to_emoji(Y_train[idx])}\", )\nprint(f\"Label index {Y_train[idx]} in one-hot encoding format is {Y_oh_train[idx]}\")",
"Sentence 'I missed you' has label index 0, which is emoji ❤️\nLabel index 0 in one-hot encoding format is [1. 0. 0. 0. 0.]\n"
]
],
[
[
"All the data is now ready to be fed into the Emojify-V1 model. You're ready to implement the model!",
"_____no_output_____"
],
[
"<a name='1-3'></a>\n### 1.3 - Implementing Emojifier-V1\n\nAs shown in Figure 2 (above), the first step is to:\n* Convert each word in the input sentence into their word vector representations.\n* Take an average of the word vectors. \n\nSimilar to this week's previous assignment, you'll use pre-trained 50-dimensional GloVe embeddings. \n\nRun the following cell to load the `word_to_vec_map`, which contains all the vector representations.",
"_____no_output_____"
]
],
[
[
"word_to_index, index_to_word, word_to_vec_map = read_glove_vecs('data/glove.6B.50d.txt')",
"_____no_output_____"
]
],
[
[
"You've loaded:\n- `word_to_index`: dictionary mapping from words to their indices in the vocabulary \n - (400,001 words, with the valid indices ranging from 0 to 400,000)\n- `index_to_word`: dictionary mapping from indices to their corresponding words in the vocabulary\n- `word_to_vec_map`: dictionary mapping words to their GloVe vector representation.\n\nRun the following cell to check if it works:",
"_____no_output_____"
]
],
[
[
"word = \"cucumber\"\nidx = 289846\nprint(\"the index of\", word, \"in the vocabulary is\", word_to_index[word])\nprint(\"the\", str(idx) + \"th word in the vocabulary is\", index_to_word[idx])",
"the index of cucumber in the vocabulary is 113317\nthe 289846th word in the vocabulary is potatos\n"
]
],
[
[
"<a name='ex-1'></a>\n### Exercise 1 - sentence_to_avg\n\nImplement `sentence_to_avg()` \n\nYou'll need to carry out two steps:\n\n1. Convert every sentence to lower-case, then split the sentence into a list of words. \n * `X.lower()` and `X.split()` might be useful. 😉\n2. For each word in the sentence, access its GloVe representation.\n * Then take the average of all of these word vectors.\n * You might use `numpy.zeros()`, which you can read more about [here]('https://numpy.org/doc/stable/reference/generated/numpy.zeros.html').\n \n \n#### Additional Hints\n* When creating the `avg` array of zeros, you'll want it to be a vector of the same shape as the other word vectors in the `word_to_vec_map`. \n * You can choose a word that exists in the `word_to_vec_map` and access its `.shape` field.\n * Be careful not to hard-code the word that you access. In other words, don't assume that if you see the word 'the' in the `word_to_vec_map` within this notebook, that this word will be in the `word_to_vec_map` when the function is being called by the automatic grader.\n\n**Hint**: you can use any one of the word vectors that you retrieved from the input `sentence` to find the shape of a word vector.",
"_____no_output_____"
]
],
[
[
"# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: sentence_to_avg\n\ndef sentence_to_avg(sentence, word_to_vec_map):\n \"\"\"\n Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word\n and averages its value into a single vector encoding the meaning of the sentence.\n \n Arguments:\n sentence -- string, one training example from X\n word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation\n \n Returns:\n avg -- average vector encoding information about the sentence, numpy-array of shape (J,), where J can be any number\n \"\"\"\n # Get a valid word contained in the word_to_vec_map. \n any_word = list(word_to_vec_map.keys())[0]\n \n ### START CODE HERE ###\n # Step 1: Split sentence into list of lower case words (≈ 1 line)\n words = sentence.split(\" \")\n\n # Initialize the average word vector, should have the same shape as your word vectors.\n avg = np.zeros(word_to_vec_map[any_word].shape)\n \n # Initialize count to 0\n count = 0\n \n # Step 2: average the word vectors. You can loop over the words in the list \"words\".\n for w in words:\n # Check that word exists in word_to_vec_map\n if w in word_to_vec_map.keys():\n avg += word_to_vec_map[w]\n # Increment count\n count +=1\n \n if count > 0:\n # Get the average. But only if count > 0\n avg = avg / count\n \n ### END CODE HERE ###\n \n return avg",
"_____no_output_____"
],
[
"# BEGIN UNIT TEST\navg = sentence_to_avg(\"Morrocan couscous is my favorite dish\", word_to_vec_map)\nprint(\"avg = \\n\", avg)\n\ndef sentence_to_avg_test(target):\n # Create a controlled word to vec map\n word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], \n 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n }\n # Convert lists to np.arrays\n for key in word_to_vec_map.keys():\n word_to_vec_map[key] = np.array(word_to_vec_map[key])\n \n avg = target(\"a a_nw c_w a_s\", word_to_vec_map)\n assert tuple(avg.shape) == tuple(word_to_vec_map['a'].shape), \"Check the shape of your avg array\" \n assert np.allclose(avg, [1.25, 2.5]), \"Check that you are finding the 4 words\"\n avg = target(\"love a a_nw c_w a_s\", word_to_vec_map)\n assert np.allclose(avg, [1.25, 2.5]), \"Divide by count, not len(words)\"\n avg = target(\"love\", word_to_vec_map)\n assert np.allclose(avg, [0, 0]), \"Average of no words must give an array of zeros\"\n avg = target(\"c_se foo a a_nw c_w a_s deeplearning c_nw\", word_to_vec_map)\n assert np.allclose(avg, [0.1666667, 2.0]), \"Debug the last example\"\n \n print(\"\\033[92mAll tests passed!\")\n \nsentence_to_avg_test(sentence_to_avg)\n\n# END UNIT TEST",
"avg = \n [ 0.045814 0.622208 -0.505224 0.254314 0.659982 0.1258178\n -0.38804462 0.1024912 -0.112244 0.1010948 -0.2276256 0.2860224\n 0.6257162 0.4314294 0.327584 0.217208 0.0446478 0.2696212\n 0.013836 -0.2176 -0.018952 -0.027592 0.6065966 0.53217332\n 0.497556 -1.091676 -0.681084 0.50463 0.8566372 -0.3245878\n 2.325744 0.133182 -0.466484 0.727842 0.023529 0.342864\n -0.227962 0.866714 -0.02686 -0.404104 0.6931014 0.318708\n -0.4620862 0.1803998 0.2801082 0.432186 0.131258 -0.089002\n 0.11097604 0.255264 ]\n\u001b[92mAll tests passed!\n"
]
],
[
[
"<a name='1-4'></a>\n### 1.4 - Implement the Model\n\nYou now have all the pieces to finish implementing the `model()` function! \nAfter using `sentence_to_avg()` you need to:\n* Pass the average through forward propagation\n* Compute the cost\n* Backpropagate to update the softmax parameters\n\n<a name='ex-2'></a>\n### Exercise 2 - model\n\nImplement the `model()` function described in Figure (2). \n\n* The equations you need to implement in the forward pass and to compute the cross-entropy cost are below:\n* The variable $Y_{oh}$ (\"Y one hot\") is the one-hot encoding of the output labels. \n\n$$ z^{(i)} = Wavg^{(i)} + b$$\n\n$$ a^{(i)} = softmax(z^{(i)})$$\n\n$$ \\mathcal{L}^{(i)} = - \\sum_{k = 0}^{n_y - 1} Y_{oh,k}^{(i)} * log(a^{(i)}_k)$$\n\n**Note**: It is possible to come up with a more efficient vectorized implementation. For now, just use nested for loops to better understand the algorithm, and for easier debugging.\n\nThe function `softmax()` is provided, and has already been imported.",
"_____no_output_____"
]
],
[
[
"# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: model\n\ndef model(X, Y, word_to_vec_map, learning_rate = 0.01, num_iterations = 400):\n \"\"\"\n Model to train word vector representations in numpy.\n \n Arguments:\n X -- input data, numpy array of sentences as strings, of shape (m, 1)\n Y -- labels, numpy array of integers between 0 and 7, numpy-array of shape (m, 1)\n word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation\n learning_rate -- learning_rate for the stochastic gradient descent algorithm\n num_iterations -- number of iterations\n \n Returns:\n pred -- vector of predictions, numpy-array of shape (m, 1)\n W -- weight matrix of the softmax layer, of shape (n_y, n_h)\n b -- bias of the softmax layer, of shape (n_y,)\n \"\"\"\n \n # Get a valid word contained in the word_to_vec_map \n any_word = list(word_to_vec_map.keys())[0]\n \n # Initialize cost. It is needed during grading\n cost = 0\n \n # Define number of training examples\n m = Y.shape[0] # number of training examples\n n_y = len(np.unique(Y)) # number of classes \n n_h = word_to_vec_map[any_word].shape[0] # dimensions of the GloVe vectors \n \n # Initialize parameters using Xavier initialization\n W = np.random.randn(n_y, n_h) / np.sqrt(n_h)\n b = np.zeros((n_y,))\n \n # Convert Y to Y_onehot with n_y classes\n Y_oh = convert_to_one_hot(Y, C = n_y) \n \n # Optimization loop\n for t in range(num_iterations): # Loop over the number of iterations\n for i in range(m): # Loop over the training examples\n \n ### START CODE HERE ### (≈ 4 lines of code)\n # Average the word vectors of the words from the i'th training example\n avg = sentence_to_avg(X[i], word_to_vec_map)\n\n # Forward propagate the avg through the softmax layer. \n # You can use np.dot() to perform the multiplication.\n z = np.dot(W, avg) + b\n a = softmax(z)\n\n # Compute cost using the i'th training label's one hot representation and \"A\" (the output of the softmax)\n cost = - np.sum(Y_oh * np.log(a))\n ### END CODE HERE ###\n \n # Compute gradients \n dz = a - Y_oh[i]\n dW = np.dot(dz.reshape(n_y,1), avg.reshape(1, n_h))\n db = dz\n\n # Update parameters with Stochastic Gradient Descent\n W = W - learning_rate * dW\n b = b - learning_rate * db\n \n if t % 100 == 0:\n print(\"Epoch: \" + str(t) + \" --- cost = \" + str(cost))\n pred = predict(X, Y, W, b, word_to_vec_map) #predict is defined in emo_utils.py\n\n return pred, W, b",
"_____no_output_____"
],
[
"# UNIT TEST\ndef model_test(target):\n # Create a controlled word to vec map\n word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], 'a_n': [3, 4], \n 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n }\n # Convert lists to np.arrays\n for key in word_to_vec_map.keys():\n word_to_vec_map[key] = np.array(word_to_vec_map[key])\n \n # Training set. Sentences composed of a_* words will be of class 0 and sentences composed of c_* words will be of class 1\n X = np.asarray(['a a_s synonym_of_a a_n c_sw', 'a a_s a_n c_sw', 'a_s a a_n', 'synonym_of_a a a_s a_n c_sw', \" a_s a_n\",\n \" a a_s a_n c \", \" a_n a c c c_e\",\n 'c c_nw c_n c c_ne', 'c_e c c_se c_s', 'c_nw c a_s c_e c_e', 'c_e a_nw c_sw', 'c_sw c c_ne c_ne'])\n \n Y = np.asarray([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])\n \n np.random.seed(10)\n pred, W, b = model(X, Y, word_to_vec_map, 0.0025, 110)\n \n assert W.shape == (2, 2), \"W must be of shape 2 x 2\"\n assert np.allclose(pred.transpose(), Y), \"Model must give a perfect accuracy\"\n assert np.allclose(b[0], -1 * b[1]), \"b should be symmetric in this example\"\n \n print(\"\\033[92mAll tests passed!\")\n \nmodel_test(model)",
"Epoch: 0 --- cost = 18.307658343519712\nAccuracy: 0.9166666666666666\nEpoch: 100 --- cost = 27.899156990414884\nAccuracy: 1.0\n\u001b[92mAll tests passed!\n"
]
],
[
[
"Run the next cell to train your model and learn the softmax parameters (W, b). **The training process will take about 5 minutes**",
"_____no_output_____"
]
],
[
[
"np.random.seed(1)\npred, W, b = model(X_train, Y_train, word_to_vec_map)\nprint(pred)",
"Epoch: 0 --- cost = 227.89897172841145\nAccuracy: 0.3560606060606061\nEpoch: 100 --- cost = 483.72861925057543\nAccuracy: 0.9090909090909091\nEpoch: 200 --- cost = 601.5754373989073\nAccuracy: 0.9242424242424242\nEpoch: 300 --- cost = 675.8465490911715\nAccuracy: 0.9393939393939394\n[[3.]\n [2.]\n [3.]\n [0.]\n [4.]\n [0.]\n [3.]\n [2.]\n [3.]\n [1.]\n [3.]\n [3.]\n [1.]\n [3.]\n [2.]\n [3.]\n [2.]\n [3.]\n [1.]\n [2.]\n [3.]\n [0.]\n [2.]\n [2.]\n [2.]\n [1.]\n [3.]\n [3.]\n [3.]\n [4.]\n [0.]\n [3.]\n [4.]\n [2.]\n [0.]\n [3.]\n [2.]\n [2.]\n [3.]\n [4.]\n [2.]\n [2.]\n [0.]\n [2.]\n [3.]\n [0.]\n [3.]\n [2.]\n [4.]\n [3.]\n [0.]\n [3.]\n [3.]\n [3.]\n [4.]\n [2.]\n [1.]\n [1.]\n [1.]\n [0.]\n [3.]\n [1.]\n [0.]\n [0.]\n [0.]\n [3.]\n [4.]\n [4.]\n [2.]\n [2.]\n [1.]\n [2.]\n [0.]\n [3.]\n [2.]\n [2.]\n [0.]\n [0.]\n [3.]\n [1.]\n [2.]\n [1.]\n [1.]\n [2.]\n [4.]\n [3.]\n [3.]\n [2.]\n [4.]\n [0.]\n [0.]\n [3.]\n [3.]\n [3.]\n [3.]\n [2.]\n [0.]\n [1.]\n [2.]\n [3.]\n [0.]\n [2.]\n [2.]\n [2.]\n [3.]\n [3.]\n [2.]\n [3.]\n [4.]\n [1.]\n [1.]\n [3.]\n [3.]\n [4.]\n [1.]\n [2.]\n [1.]\n [1.]\n [3.]\n [1.]\n [0.]\n [4.]\n [0.]\n [3.]\n [3.]\n [4.]\n [4.]\n [1.]\n [4.]\n [3.]\n [0.]\n [2.]]\n"
]
],
[
[
"Great! Your model has pretty high accuracy on the training set. Now see how it does on the test set:",
"_____no_output_____"
],
[
"<a name='1-5'></a>\n### 1.5 - Examining Test Set Performance \n\nNote that the `predict` function used here is defined in `emo_util.spy`.",
"_____no_output_____"
]
],
[
[
"print(\"Training set:\")\npred_train = predict(X_train, Y_train, W, b, word_to_vec_map)\nprint('Test set:')\npred_test = predict(X_test, Y_test, W, b, word_to_vec_map)",
"Training set:\nAccuracy: 0.9545454545454546\nTest set:\nAccuracy: 0.8571428571428571\n"
]
],
[
[
"**Note**:\n* Random guessing would have had 20% accuracy, given that there are 5 classes. (1/5 = 20%).\n* This is pretty good performance after training on only 127 examples. \n\n\n#### The Model Matches Emojis to Relevant Words\nIn the training set, the algorithm saw the sentence \n>\"I love you.\" \n\nwith the label ❤️. \n* You can check that the word \"adore\" does not appear in the training set. \n* Nonetheless, let's see what happens if you write \"I adore you.\"",
"_____no_output_____"
]
],
[
[
"X_my_sentences = np.array([\"i adore you\", \"i love you\", \"funny lol\", \"lets play with a ball\", \"food is ready\", \"not feeling happy\"])\nY_my_labels = np.array([[0], [0], [2], [1], [4],[3]])\n\npred = predict(X_my_sentences, Y_my_labels , W, b, word_to_vec_map)\nprint_predictions(X_my_sentences, pred)",
"Accuracy: 0.8333333333333334\n\ni adore you ❤️\ni love you ❤️\nfunny lol 😄\nlets play with a ball ⚾\nfood is ready 🍴\nnot feeling happy 😄\n"
]
],
[
[
"Amazing! \n* Because *adore* has a similar embedding as *love*, the algorithm has generalized correctly even to a word it has never seen before. \n* Words such as *heart*, *dear*, *beloved* or *adore* have embedding vectors similar to *love*. \n * Feel free to modify the inputs above and try out a variety of input sentences. \n * How well does it work?\n\n#### Word Ordering isn't Considered in this Model\n* Note that the model doesn't get the following sentence correct:\n>\"not feeling happy\" \n\n* This algorithm ignores word ordering, so is not good at understanding phrases like \"not happy.\" \n\n#### Confusion Matrix\n* Printing the confusion matrix can also help understand which classes are more difficult for your model. \n* A confusion matrix shows how often an example whose label is one class (\"actual\" class) is mislabeled by the algorithm with a different class (\"predicted\" class).\n\nPrint the confusion matrix below:",
"_____no_output_____"
]
],
[
[
"# START SKIP FOR GRADING\nprint(Y_test.shape)\nprint(' '+ label_to_emoji(0)+ ' ' + label_to_emoji(1) + ' ' + label_to_emoji(2)+ ' ' + label_to_emoji(3)+' ' + label_to_emoji(4))\nprint(pd.crosstab(Y_test, pred_test.reshape(56,), rownames=['Actual'], colnames=['Predicted'], margins=True))\nplot_confusion_matrix(Y_test, pred_test)\n# END SKIP FOR GRADING",
"(56,)\n ❤️ ⚾ 😄 😞 🍴\nPredicted 0.0 1.0 2.0 3.0 4.0 All\nActual \n0 6 0 0 1 0 7\n1 0 8 0 0 0 8\n2 2 0 16 0 0 18\n3 1 0 2 13 0 16\n4 0 0 1 1 5 7\nAll 9 8 19 15 5 56\n"
]
],
[
[
"<font color='blue'><b>What you should remember:</b>\n- Even with a mere 127 training examples, you can get a reasonably good model for Emojifying. \n - This is due to the generalization power word vectors gives you. \n- Emojify-V1 will perform poorly on sentences such as *\"This movie is not good and not enjoyable\"* \n - It doesn't understand combinations of words.\n - It just averages all the words' embedding vectors together, without considering the ordering of words. \n</font>\n \n**Not to worry! You will build a better algorithm in the next section!**",
"_____no_output_____"
],
[
"<a name='2'></a>\n## 2 - Emojifier-V2: Using LSTMs in Keras \n\nYou're going to build an LSTM model that takes word **sequences** as input! This model will be able to account for word ordering. \n\nEmojifier-V2 will continue to use pre-trained word embeddings to represent words. You'll feed word embeddings into an LSTM, and the LSTM will learn to predict the most appropriate emoji. ",
"_____no_output_____"
],
[
"### Packages\n\nRun the following cell to load the Keras packages you'll need:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport tensorflow\nnp.random.seed(0)\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Input, Dropout, LSTM, Activation\nfrom tensorflow.keras.layers import Embedding\nfrom tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.initializers import glorot_uniform\nnp.random.seed(1)",
"_____no_output_____"
]
],
[
[
"<a name='2-1'></a>\n### 2.1 - Model Overview\n\nHere is the Emojifier-v2 you will implement:\n\n<img src=\"images/emojifier-v2.png\" style=\"width:700px;height:400px;\"> <br>\n<caption><center><font color='purple'><b>Figure 3</b>: Emojifier-V2. A 2-layer LSTM sequence classifier. </center></caption>",
"_____no_output_____"
],
[
"<a name='2-2'></a>\n### 2.2 Keras and Mini-batching \n\nIn this exercise, you want to train Keras using mini-batches. However, most deep learning frameworks require that all sequences in the same mini-batch have the **same length**. \n\nThis is what allows vectorization to work: If you had a 3-word sentence and a 4-word sentence, then the computations needed for them are different (one takes 3 steps of an LSTM, one takes 4 steps) so it's just not possible to do them both at the same time.\n \n#### Padding Handles Sequences of Varying Length\n* The common solution to handling sequences of **different length** is to use padding. Specifically:\n * Set a maximum sequence length\n * Pad all sequences to have the same length. \n \n#### Example of Padding:\n* Given a maximum sequence length of 20, you could pad every sentence with \"0\"s so that each input sentence is of length 20. \n* Thus, the sentence \"I love you\" would be represented as $(e_{I}, e_{love}, e_{you}, \\vec{0}, \\vec{0}, \\ldots, \\vec{0})$. \n* In this example, any sentences longer than 20 words would have to be truncated. \n* One way to choose the maximum sequence length is to just pick the length of the longest sentence in the training set. ",
"_____no_output_____"
],
[
"<a name='2-3'></a>\n### 2.3 - The Embedding Layer\n\nIn Keras, the embedding matrix is represented as a \"layer.\"\n\n* The embedding matrix maps word indices to embedding vectors.\n * The word indices are positive integers.\n * The embedding vectors are dense vectors of fixed size.\n * A \"dense\" vector is the opposite of a sparse vector. It means that most of its values are non-zero. As a counter-example, a one-hot encoded vector is not \"dense.\"\n* The embedding matrix can be derived in two ways:\n * Training a model to derive the embeddings from scratch. \n * Using a pretrained embedding.\n \n#### Using and Updating Pre-trained Embeddings\nIn this section, you'll create an [Embedding()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding) layer in Keras\n\n* You will initialize the Embedding layer with GloVe 50-dimensional vectors. \n* In the code below, you'll observe how Keras allows you to either train or leave this layer fixed. \n * Because your training set is quite small, you'll leave the GloVe embeddings fixed instead of updating them.",
"_____no_output_____"
],
[
"#### Inputs and Outputs to the Embedding Layer\n\n* The `Embedding()` layer's input is an integer matrix of size **(batch size, max input length)**. \n * This input corresponds to sentences converted into lists of indices (integers).\n * The largest integer (the highest word index) in the input should be no larger than the vocabulary size.\n* The embedding layer outputs an array of shape (batch size, max input length, dimension of word vectors).\n\n* The figure shows the propagation of two example sentences through the embedding layer. \n * Both examples have been zero-padded to a length of `max_len=5`.\n * The word embeddings are 50 units in length.\n * The final dimension of the representation is `(2,max_len,50)`. \n\n<img src=\"images/embedding1.png\" style=\"width:700px;height:250px;\">\n<caption><center><font color='purple'><b>Figure 4</b>: Embedding layer</center></caption>",
"_____no_output_____"
],
[
"#### Prepare the Input Sentences\n\n<a name='ex-3'></a>\n### Exercise 3 - sentences_to_indices\n\nImplement `sentences_to_indices`\n\nThis function processes an array of sentences X and returns inputs to the embedding layer:\n\n* Convert each training sentences into a list of indices (the indices correspond to each word in the sentence)\n* Zero-pad all these lists so that their length is the length of the longest sentence.\n \n#### Additional Hints:\n* Note that you may have considered using the `enumerate()` function in the for loop, but for the purposes of passing the autograder, please follow the starter code by initializing and incrementing `j` explicitly.",
"_____no_output_____"
]
],
[
[
"for idx, val in enumerate([\"I\", \"like\", \"learning\"]):\n print(idx, val)",
"0 I\n1 like\n2 learning\n"
],
[
"# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: sentences_to_indices\n\ndef sentences_to_indices(X, word_to_index, max_len):\n \"\"\"\n Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences.\n The output shape should be such that it can be given to `Embedding()` (described in Figure 4). \n \n Arguments:\n X -- array of sentences (strings), of shape (m, 1)\n word_to_index -- a dictionary containing the each word mapped to its index\n max_len -- maximum number of words in a sentence. You can assume every sentence in X is no longer than this. \n \n Returns:\n X_indices -- array of indices corresponding to words in the sentences from X, of shape (m, max_len)\n \"\"\"\n \n m = X.shape[0] # number of training examples\n \n ### START CODE HERE ###\n # Initialize X_indices as a numpy matrix of zeros and the correct shape (≈ 1 line)\n X_indices = np.zeros((m, max_len))\n \n for i in range(m): # loop over training examples\n \n # Convert the ith training sentence in lower case and split is into words. You should get a list of words.\n sentence_words = X[i].lower().split(\" \")\n \n # Initialize j to 0\n j = 0\n \n # Loop over the words of sentence_words\n\n for w in sentence_words:\n # if w exists in the word_to_index dictionary\n if w in word_to_index:\n # Set the (i,j)th entry of X_indices to the index of the correct word.\n X_indices[i, j] = word_to_index[w]\n # Increment j to j + 1\n j = j + 1\n \n ### END CODE HERE ###\n \n return X_indices",
"_____no_output_____"
],
[
"# UNIT TEST\ndef sentences_to_indices_test(target):\n \n # Create a word_to_index dictionary\n word_to_index = {}\n for idx, val in enumerate([\"i\", \"like\", \"learning\", \"deep\", \"machine\", \"love\", \"smile\", '´0.=']):\n word_to_index[val] = idx;\n \n max_len = 4\n sentences = np.array([\"I like deep learning\", \"deep ´0.= love machine\", \"machine learning smile\"]);\n indexes = target(sentences, word_to_index, max_len)\n print(indexes)\n \n assert type(indexes) == np.ndarray, \"Wrong type. Use np arrays in the function\"\n assert indexes.shape == (sentences.shape[0], max_len), \"Wrong shape of ouput matrix\"\n assert np.allclose(indexes, [[0, 1, 3, 2],\n [3, 7, 5, 4],\n [4, 2, 6, 0]]), \"Wrong values. Debug with the given examples\"\n \n print(\"\\033[92mAll tests passed!\")\n \nsentences_to_indices_test(sentences_to_indices)",
"[[0. 1. 3. 2.]\n [3. 7. 5. 4.]\n [4. 2. 6. 0.]]\n\u001b[92mAll tests passed!\n"
]
],
[
[
"**Expected value**\n\n```\n[[0, 1, 3, 2],\n [3, 7, 5, 4],\n [4, 2, 6, 0]]\n```",
"_____no_output_____"
],
[
"Run the following cell to check what `sentences_to_indices()` does, and take a look at your results.",
"_____no_output_____"
]
],
[
[
"X1 = np.array([\"funny lol\", \"lets play baseball\", \"food is ready for you\"])\nX1_indices = sentences_to_indices(X1, word_to_index, max_len=5)\nprint(\"X1 =\", X1)\nprint(\"X1_indices =\\n\", X1_indices)",
"X1 = ['funny lol' 'lets play baseball' 'food is ready for you']\nX1_indices =\n [[155345. 225122. 0. 0. 0.]\n [220930. 286375. 69714. 0. 0.]\n [151204. 192973. 302254. 151349. 394475.]]\n"
]
],
[
[
"#### Build Embedding Layer\n\nNow you'll build the `Embedding()` layer in Keras, using pre-trained word vectors. \n\n* The embedding layer takes as input a list of word indices.\n * `sentences_to_indices()` creates these word indices.\n* The embedding layer will return the word embeddings for a sentence. \n\n<a name='ex-4'></a>\n### Exercise 4 - pretrained_embedding_layer\n\nImplement `pretrained_embedding_layer()` with these steps:\n\n1. Initialize the embedding matrix as a numpy array of zeros.\n * The embedding matrix has a row for each unique word in the vocabulary.\n * There is one additional row to handle \"unknown\" words.\n * So vocab_size is the number of unique words plus one.\n * Each row will store the vector representation of one word. \n * For example, one row may be 50 positions long if using GloVe word vectors.\n * In the code below, `emb_dim` represents the length of a word embedding.\n2. Fill in each row of the embedding matrix with the vector representation of a word\n * Each word in `word_to_index` is a string.\n * word_to_vec_map is a dictionary where the keys are strings and the values are the word vectors.\n3. Define the Keras embedding layer. \n * Use [Embedding()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding). \n * The input dimension is equal to the vocabulary length (number of unique words plus one).\n * The output dimension is equal to the number of positions in a word embedding.\n * Make this layer's embeddings fixed.\n * If you were to set `trainable = True`, then it will allow the optimization algorithm to modify the values of the word embeddings.\n * In this case, you don't want the model to modify the word embeddings.\n4. Set the embedding weights to be equal to the embedding matrix.\n * Note that this is part of the code is already completed for you and does not need to be modified! ",
"_____no_output_____"
]
],
[
[
"# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: pretrained_embedding_layer\n\ndef pretrained_embedding_layer(word_to_vec_map, word_to_index):\n \"\"\"\n Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors.\n \n Arguments:\n word_to_vec_map -- dictionary mapping words to their GloVe vector representation.\n word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words)\n\n Returns:\n embedding_layer -- pretrained layer Keras instance\n \"\"\"\n \n vocab_size = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement)\n any_word = list(word_to_vec_map.keys())[0]\n emb_dim = word_to_vec_map[any_word].shape[0] # define dimensionality of your GloVe word vectors (= 50)\n \n ### START CODE HERE ###\n # Step 1\n # Initialize the embedding matrix as a numpy array of zeros.\n # See instructions above to choose the correct shape.\n emb_matrix = np.zeros((vocab_size, emb_dim))\n \n # Step 2\n # Set each row \"idx\" of the embedding matrix to be \n # the word vector representation of the idx'th word of the vocabulary\n for word, idx in word_to_index.items():\n emb_matrix[idx, :] = word_to_vec_map[word]\n\n # Step 3\n # Define Keras embedding layer with the correct input and output sizes\n # Make it non-trainable.\n embedding_layer = Embedding(vocab_size, emb_dim)\n ### END CODE HERE ###\n\n # Step 4 (already done for you; please do not modify)\n # Build the embedding layer, it is required before setting the weights of the embedding layer. \n embedding_layer.build((None,)) # Do not modify the \"None\". This line of code is complete as-is.\n \n # Set the weights of the embedding layer to the embedding matrix. Your layer is now pretrained.\n embedding_layer.set_weights([emb_matrix])\n \n return embedding_layer",
"_____no_output_____"
],
[
"# UNIT TEST\ndef pretrained_embedding_layer_test(target):\n # Create a controlled word to vec map\n word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], 'a_n': [3, 4], \n 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n }\n # Convert lists to np.arrays\n for key in word_to_vec_map.keys():\n word_to_vec_map[key] = np.array(word_to_vec_map[key])\n \n # Create a word_to_index dictionary\n word_to_index = {}\n for idx, val in enumerate(list(word_to_vec_map.keys())):\n word_to_index[val] = idx;\n \n np.random.seed(1)\n embedding_layer = target(word_to_vec_map, word_to_index)\n \n assert type(embedding_layer) == Embedding, \"Wrong type\"\n assert embedding_layer.input_dim == len(list(word_to_vec_map.keys())) + 1, \"Wrong input shape\"\n assert embedding_layer.output_dim == len(word_to_vec_map['a']), \"Wrong output shape\"\n assert np.allclose(embedding_layer.get_weights(), \n [[[ 3, 3], [ 3, 3], [ 2, 4], [ 3, 2], [ 3, 4],\n [-2, 1], [-2, 2], [-1, 2], [-1, 1], [-1, 0],\n [-2, 0], [-3, 0], [-3, 1], [-3, 2], [ 0, 0]]]), \"Wrong vaulues\"\n print(\"\\033[92mAll tests passed!\")\n \n \npretrained_embedding_layer_test(pretrained_embedding_layer)",
"\u001b[92mAll tests passed!\n"
],
[
"embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)\nprint(\"weights[0][1][1] =\", embedding_layer.get_weights()[0][1][1])\nprint(\"Input_dim\", embedding_layer.input_dim)\nprint(\"Output_dim\",embedding_layer.output_dim)",
"weights[0][1][1] = 0.39031\nInput_dim 400001\nOutput_dim 50\n"
]
],
[
[
"<a name='2-4'></a>\n### 2.4 - Building the Emojifier-V2\n\nNow you're ready to build the Emojifier-V2 model, in which you feed the embedding layer's output to an LSTM network!\n\n<img src=\"images/emojifier-v2.png\" style=\"width:700px;height:400px;\"> <br>\n<caption><center><font color='purple'><b>Figure 3</b>: Emojifier-v2. A 2-layer LSTM sequence classifier. </center></caption></font> \n\n\n<a name='ex-5'></a>\n### Exercise 5 - Emojify_V2\n\nImplement `Emojify_V2()`\n\nThis function builds a Keras graph of the architecture shown in Figure (3). \n\n* The model takes as input an array of sentences of shape (`m`, `max_len`, ) defined by `input_shape`. \n* The model outputs a softmax probability vector of shape (`m`, `C = 5`). \n\n* You may need to use the following Keras layers:\n * [Input()](https://www.tensorflow.org/api_docs/python/tf/keras/Input)\n * Set the `shape` and `dtype` parameters.\n * The inputs are integers, so you can specify the data type as a string, 'int32'.\n * [LSTM()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM)\n * Set the `units` and `return_sequences` parameters.\n * [Dropout()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dropout)\n * Set the `rate` parameter.\n * [Dense()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense)\n * Set the `units`, \n * Note that `Dense()` has an `activation` parameter. For the purposes of passing the autograder, please do not set the activation within `Dense()`. Use the separate `Activation` layer to do so.\n * [Activation()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Activation)\n * You can pass in the activation of your choice as a lowercase string.\n * [Model()](https://www.tensorflow.org/api_docs/python/tf/keras/Model)\n * Set `inputs` and `outputs`.\n\n\n#### Additional Hints\n* Remember that these Keras layers return an object, and you will feed in the outputs of the previous layer as the input arguments to that object. The returned object can be created and called in the same line.\n\n```Python\n# How to use Keras layers in two lines of code\ndense_object = Dense(units = ...)\nX = dense_object(inputs)\n\n# How to use Keras layers in one line of code\nX = Dense(units = ...)(inputs)\n```\n\n* The `embedding_layer` that is returned by `pretrained_embedding_layer` is a layer object that can be called as a function, passing in a single argument (sentence indices).\n\n* Here is some sample code in case you're stuck: 😊\n```Python\nraw_inputs = Input(shape=(maxLen,), dtype='int32')\npreprocessed_inputs = ... # some pre-processing\nX = LSTM(units = ..., return_sequences= ...)(processed_inputs)\nX = Dropout(rate = ..., )(X)\n...\nX = Dense(units = ...)(X)\nX = Activation(...)(X)\nmodel = Model(inputs=..., outputs=...)\n...\n```",
"_____no_output_____"
]
],
[
[
"# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: Emojify_V2\n\ndef Emojify_V2(input_shape, word_to_vec_map, word_to_index):\n \"\"\"\n Function creating the Emojify-v2 model's graph.\n \n Arguments:\n input_shape -- shape of the input, usually (max_len,)\n word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation\n word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words)\n\n Returns:\n model -- a model instance in Keras\n \"\"\"\n \n ### START CODE HERE ###\n # Define sentence_indices as the input of the graph.\n # It should be of shape input_shape and dtype 'int32' (as it contains indices, which are integers).\n sentence_indices = Input(input_shape, dtype='int32')\n \n # Create the embedding layer pretrained with GloVe Vectors (≈1 line)\n embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)\n \n # Propagate sentence_indices through your embedding layer\n # (See additional hints in the instructions).\n embeddings = embedding_layer(sentence_indices)\n \n # Propagate the embeddings through an LSTM layer with 128-dimensional hidden state\n # The returned output should be a batch of sequences.\n X = LSTM(128, return_sequences=True)(embeddings)\n # Add dropout with a probability of 0.5\n X = Dropout(0.5)(X)\n # Propagate X trough another LSTM layer with 128-dimensional hidden state\n # The returned output should be a single hidden state, not a batch of sequences.\n X = LSTM(128)(X)\n # Add dropout with a probability of 0.5\n X = Dropout(0.5)(X)\n # Propagate X through a Dense layer with 5 units\n X = Dense(5)(X)\n # Add a softmax activation\n X = Activation('softmax')(X)\n \n # Create Model instance which converts sentence_indices into X.\n model = Model(inputs=sentence_indices, outputs=X)\n \n ### END CODE HERE ###\n \n return model",
"_____no_output_____"
],
[
"# UNIT TEST\ndef Emojify_V2_test(target):\n # Create a controlled word to vec map\n word_to_vec_map = {'a': [3, 3], 'synonym_of_a': [3, 3], 'a_nw': [2, 4], 'a_s': [3, 2], 'a_n': [3, 4], \n 'c': [-2, 1], 'c_n': [-2, 2],'c_ne': [-1, 2], 'c_e': [-1, 1], 'c_se': [-1, 0], \n 'c_s': [-2, 0], 'c_sw': [-3, 0], 'c_w': [-3, 1], 'c_nw': [-3, 2]\n }\n # Convert lists to np.arrays\n for key in word_to_vec_map.keys():\n word_to_vec_map[key] = np.array(word_to_vec_map[key])\n \n # Create a word_to_index dictionary\n word_to_index = {}\n for idx, val in enumerate(list(word_to_vec_map.keys())):\n word_to_index[val] = idx;\n \n maxLen = 4\n model = target((maxLen,), word_to_vec_map, word_to_index)\n \n expectedModel = [['InputLayer', [(None, 4)], 0], ['Embedding', (None, 4, 2), 30], ['LSTM', (None, 4, 128), 67072, (None, 4, 2), 'tanh', True], ['Dropout', (None, 4, 128), 0, 0.5], ['LSTM', (None, 128), 131584, (None, 4, 128), 'tanh', False], ['Dropout', (None, 128), 0, 0.5], ['Dense', (None, 5), 645, 'linear'], ['Activation', (None, 5), 0]]\n comparator(summary(model), expectedModel)\n \n \nEmojify_V2_test(Emojify_V2)",
"\u001b[32mAll tests passed!\u001b[0m\n"
]
],
[
[
"Run the following cell to create your model and check its summary. \n\n* Because all sentences in the dataset are less than 10 words, `max_len = 10` was chosen. \n* You should see that your architecture uses 20,223,927 parameters, of which 20,000,050 (the word embeddings) are non-trainable, with the remaining 223,877 being trainable. \n* Because your vocabulary size has 400,001 words (with valid indices from 0 to 400,000) there are 400,001\\*50 = 20,000,050 non-trainable parameters. ",
"_____no_output_____"
]
],
[
[
"model = Emojify_V2((maxLen,), word_to_vec_map, word_to_index)\nmodel.summary()",
"Model: \"functional_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_3 (InputLayer) [(None, 10)] 0 \n_________________________________________________________________\nembedding_4 (Embedding) (None, 10, 50) 20000050 \n_________________________________________________________________\nlstm_4 (LSTM) (None, 10, 128) 91648 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 10, 128) 0 \n_________________________________________________________________\nlstm_5 (LSTM) (None, 128) 131584 \n_________________________________________________________________\ndropout_4 (Dropout) (None, 128) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 5) 645 \n_________________________________________________________________\nactivation_1 (Activation) (None, 5) 0 \n=================================================================\nTotal params: 20,223,927\nTrainable params: 20,223,927\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"#### Compile the Model \n\nAs usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics you want to use. Compile your model using `categorical_crossentropy` loss, `adam` optimizer and `['accuracy']` metrics:",
"_____no_output_____"
]
],
[
[
"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"<a name='2-5'></a>\n### 2.5 - Train the Model \n\nIt's time to train your model! Your Emojifier-V2 `model` takes as input an array of shape (`m`, `max_len`) and outputs probability vectors of shape (`m`, `number of classes`). Thus, you have to convert X_train (array of sentences as strings) to X_train_indices (array of sentences as list of word indices), and Y_train (labels as indices) to Y_train_oh (labels as one-hot vectors).",
"_____no_output_____"
]
],
[
[
"X_train_indices = sentences_to_indices(X_train, word_to_index, maxLen)\nY_train_oh = convert_to_one_hot(Y_train, C = 5)",
"_____no_output_____"
]
],
[
[
"Fit the Keras model on `X_train_indices` and `Y_train_oh`, using `epochs = 50` and `batch_size = 32`.",
"_____no_output_____"
]
],
[
[
"model.fit(X_train_indices, Y_train_oh, epochs = 50, batch_size = 32, shuffle=True)",
"Epoch 1/50\n5/5 [==============================] - 2s 340ms/step - loss: 1.5763 - accuracy: 0.2652\nEpoch 2/50\n5/5 [==============================] - 2s 345ms/step - loss: 1.4703 - accuracy: 0.3939\nEpoch 3/50\n5/5 [==============================] - 2s 338ms/step - loss: 1.4189 - accuracy: 0.3333\nEpoch 4/50\n5/5 [==============================] - 2s 325ms/step - loss: 1.3151 - accuracy: 0.4848\nEpoch 5/50\n5/5 [==============================] - 2s 340ms/step - loss: 1.1867 - accuracy: 0.5909\nEpoch 6/50\n5/5 [==============================] - 2s 341ms/step - loss: 1.1082 - accuracy: 0.5000\nEpoch 7/50\n5/5 [==============================] - 2s 323ms/step - loss: 0.9355 - accuracy: 0.6591\nEpoch 8/50\n5/5 [==============================] - 2s 333ms/step - loss: 0.9186 - accuracy: 0.6439\nEpoch 9/50\n5/5 [==============================] - 2s 326ms/step - loss: 0.7914 - accuracy: 0.6970\nEpoch 10/50\n5/5 [==============================] - 2s 334ms/step - loss: 0.7393 - accuracy: 0.7197\nEpoch 11/50\n5/5 [==============================] - 2s 340ms/step - loss: 0.6469 - accuracy: 0.7348\nEpoch 12/50\n5/5 [==============================] - 2s 343ms/step - loss: 0.5031 - accuracy: 0.8258\nEpoch 13/50\n5/5 [==============================] - 2s 326ms/step - loss: 0.4233 - accuracy: 0.8485\nEpoch 14/50\n5/5 [==============================] - 2s 340ms/step - loss: 0.4786 - accuracy: 0.8106\nEpoch 15/50\n5/5 [==============================] - 2s 326ms/step - loss: 0.3518 - accuracy: 0.9015\nEpoch 16/50\n5/5 [==============================] - 2s 335ms/step - loss: 0.3515 - accuracy: 0.8864\nEpoch 17/50\n5/5 [==============================] - 2s 335ms/step - loss: 0.2997 - accuracy: 0.9091\nEpoch 18/50\n5/5 [==============================] - 2s 339ms/step - loss: 0.1869 - accuracy: 0.9470\nEpoch 19/50\n5/5 [==============================] - 2s 339ms/step - loss: 0.2239 - accuracy: 0.9242\nEpoch 20/50\n5/5 [==============================] - 2s 337ms/step - loss: 0.1125 - accuracy: 0.9697\nEpoch 21/50\n5/5 [==============================] - 2s 320ms/step - loss: 0.1427 - accuracy: 0.9470\nEpoch 22/50\n5/5 [==============================] - 2s 326ms/step - loss: 0.4633 - accuracy: 0.8561\nEpoch 23/50\n5/5 [==============================] - 2s 323ms/step - loss: 0.3279 - accuracy: 0.8939\nEpoch 24/50\n5/5 [==============================] - 2s 334ms/step - loss: 0.2614 - accuracy: 0.9167\nEpoch 25/50\n5/5 [==============================] - 2s 338ms/step - loss: 0.2622 - accuracy: 0.9015\nEpoch 26/50\n5/5 [==============================] - 2s 336ms/step - loss: 0.1737 - accuracy: 0.9394\nEpoch 27/50\n5/5 [==============================] - 2s 336ms/step - loss: 0.1334 - accuracy: 0.9621\nEpoch 28/50\n5/5 [==============================] - 2s 340ms/step - loss: 0.0768 - accuracy: 0.9924\nEpoch 29/50\n5/5 [==============================] - 2s 343ms/step - loss: 0.0718 - accuracy: 0.9773\nEpoch 30/50\n5/5 [==============================] - 2s 339ms/step - loss: 0.0767 - accuracy: 0.9848\nEpoch 31/50\n5/5 [==============================] - 2s 325ms/step - loss: 0.0481 - accuracy: 0.9924\nEpoch 32/50\n5/5 [==============================] - 2s 340ms/step - loss: 0.0455 - accuracy: 0.9924\nEpoch 33/50\n5/5 [==============================] - 2s 305ms/step - loss: 0.0288 - accuracy: 1.0000\nEpoch 34/50\n5/5 [==============================] - 2s 320ms/step - loss: 0.0217 - accuracy: 1.0000\nEpoch 35/50\n5/5 [==============================] - 2s 327ms/step - loss: 0.0184 - accuracy: 1.0000\nEpoch 36/50\n5/5 [==============================] - 2s 326ms/step - loss: 0.0120 - accuracy: 1.0000\nEpoch 37/50\n5/5 [==============================] - 2s 323ms/step - loss: 0.0108 - accuracy: 1.0000\nEpoch 38/50\n5/5 [==============================] - 2s 335ms/step - loss: 0.0087 - accuracy: 1.0000\nEpoch 39/50\n5/5 [==============================] - 2s 339ms/step - loss: 0.0068 - accuracy: 1.0000\nEpoch 40/50\n5/5 [==============================] - 2s 338ms/step - loss: 0.0067 - accuracy: 1.0000\nEpoch 41/50\n5/5 [==============================] - 2s 325ms/step - loss: 0.0080 - accuracy: 1.0000\nEpoch 42/50\n5/5 [==============================] - 2s 327ms/step - loss: 0.0074 - accuracy: 1.0000\nEpoch 43/50\n5/5 [==============================] - 2s 326ms/step - loss: 0.0058 - accuracy: 1.0000\nEpoch 44/50\n5/5 [==============================] - 2s 326ms/step - loss: 0.0043 - accuracy: 1.0000\nEpoch 45/50\n5/5 [==============================] - 2s 322ms/step - loss: 0.0058 - accuracy: 1.0000\nEpoch 46/50\n5/5 [==============================] - 2s 336ms/step - loss: 0.0061 - accuracy: 1.0000\nEpoch 47/50\n5/5 [==============================] - 2s 325ms/step - loss: 0.0052 - accuracy: 1.0000\nEpoch 48/50\n5/5 [==============================] - 2s 341ms/step - loss: 0.0076 - accuracy: 1.0000\nEpoch 49/50\n5/5 [==============================] - 2s 353ms/step - loss: 0.0045 - accuracy: 1.0000\nEpoch 50/50\n5/5 [==============================] - 2s 336ms/step - loss: 0.0041 - accuracy: 1.0000\n"
]
],
[
[
"Your model should perform around **90% to 100% accuracy** on the training set. Exact model accuracy may vary! \n\nRun the following cell to evaluate your model on the test set: ",
"_____no_output_____"
]
],
[
[
"X_test_indices = sentences_to_indices(X_test, word_to_index, max_len = maxLen)\nY_test_oh = convert_to_one_hot(Y_test, C = 5)\nloss, acc = model.evaluate(X_test_indices, Y_test_oh)\nprint()\nprint(\"Test accuracy = \", acc)",
"2/2 [==============================] - 0s 2ms/step - loss: 1.3818 - accuracy: 0.7143\n\nTest accuracy = 0.7142857313156128\n"
]
],
[
[
"You should get a test accuracy between 80% and 95%. Run the cell below to see the mislabelled examples: ",
"_____no_output_____"
]
],
[
[
"# This code allows you to see the mislabelled examples\nC = 5\ny_test_oh = np.eye(C)[Y_test.reshape(-1)]\nX_test_indices = sentences_to_indices(X_test, word_to_index, maxLen)\npred = model.predict(X_test_indices)\nfor i in range(len(X_test)):\n x = X_test_indices\n num = np.argmax(pred[i])\n if(num != Y_test[i]):\n print('Expected emoji:'+ label_to_emoji(Y_test[i]) + ' prediction: '+ X_test[i] + label_to_emoji(num).strip())",
"Expected emoji:🍴 prediction: I want to eat\t😞\nExpected emoji:😄 prediction: she got me a nice present\t❤️\nExpected emoji:🍴 prediction: where is the food\t⚾\nExpected emoji:😞 prediction: work is hard\t😄\nExpected emoji:😞 prediction: work is horrible\t😄\nExpected emoji:🍴 prediction: any suggestions for dinner\t😄\nExpected emoji:😄 prediction: you brighten my day\t❤️\nExpected emoji:😞 prediction: she is a bully\t❤️\nExpected emoji:😞 prediction: My life is so boring\t❤️\nExpected emoji:😄 prediction: she said yes\t😞\nExpected emoji:😄 prediction: will you be my valentine\t😞\nExpected emoji:🍴 prediction: See you at the restaurant\t😞\nExpected emoji:😄 prediction: I like to laugh\t❤️\nExpected emoji:😄 prediction: What you did was awesome\t😞\nExpected emoji:😞 prediction: go away\t⚾\nExpected emoji:🍴 prediction: I did not have breakfast 😞\n"
]
],
[
[
"Now you can try it on your own example! Write your own sentence below:",
"_____no_output_____"
]
],
[
[
"# Change the sentence below to see your prediction. Make sure all the words are in the Glove embeddings. \nx_test = np.array(['I cannot play'])\nX_test_indices = sentences_to_indices(x_test, word_to_index, maxLen)\nprint(x_test[0] +' '+ label_to_emoji(np.argmax(model.predict(X_test_indices))))",
"I cannot play ⚾\n"
]
],
[
[
"#### LSTM Version Accounts for Word Order\n* The Emojify-V1 model did not \"not feeling happy\" correctly, but your implementation of Emojify-V2 got it right! \n * If it didn't, be aware that Keras' outputs are slightly random each time, so this is probably why. \n* The current model still isn't very robust at understanding negation (such as \"not happy\")\n * This is because the training set is small and doesn't have a lot of examples of negation. \n * If the training set were larger, the LSTM model would be much better than the Emojify-V1 model at understanding more complex sentences. ",
"_____no_output_____"
],
[
"### Congratulations!\n \nYou've completed this notebook, and harnessed the power of LSTMs to make your words more emotive! ❤️❤️❤️\n\nBy now, you've: \n\n* Created an embedding matrix\n* Observed how negative sampling learns word vectors more efficiently than other methods\n* Experienced the advantages and disadvantages of the GloVe algorithm\n* And built a sentiment classifier using word embeddings! \n\nCool! (or Emojified: 😎😎😎 ) ",
"_____no_output_____"
],
[
"<font color='blue'><b>What you should remember</b>:\n- If you have an NLP task where the training set is small, using word embeddings can help your algorithm significantly. \n- Word embeddings allow your model to work on words in the test set that may not even appear in the training set. \n- Training sequence models in Keras (and in most other deep learning frameworks) requires a few important details:\n - To use mini-batches, the sequences need to be **padded** so that all the examples in a mini-batch have the **same length**. \n - An `Embedding()` layer can be initialized with pretrained values. \n - These values can be either fixed or trained further on your dataset. \n - If however your labeled dataset is small, it's usually not worth trying to train a large pre-trained set of embeddings. \n - `LSTM()` has a flag called `return_sequences` to decide if you would like to return every hidden states or only the last one. \n - You can use `Dropout()` right after `LSTM()` to regularize your network. ",
"_____no_output_____"
],
[
"\n### Input sentences:\n```Python\n\"Congratulations on finishing this assignment and building an Emojifier.\"\n\"We hope you're happy with what you've accomplished in this notebook!\"\n```\n### Output emojis:\n# 😀😀😀😀😀😀\n\n☁ 👋🚀 ☁☁\n\n ✨ BYE-BYE!\n \n☁ ✨ 🎈\n\n ✨ ☁\n \n ✨\n \n ✨\n \n🌾✨💨 🏃 🏠🏢 ",
"_____no_output_____"
],
[
"<a name='3'></a>\n## 3 - Acknowledgments\n\nThanks to Alison Darcy and the Woebot team for their advice on the creation of this assignment. \n* Woebot is a chatbot friend that is ready to speak with you 24/7. \n* Part of Woebot's technology uses word embeddings to understand the emotions of what you say. \n* You can chat with Woebot by going to http://woebot.io\n\n<img src=\"images/woebot.png\" style=\"width:600px;height:300px;\">",
"_____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"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
ece63852471d9a8418dab9d28a73839dcbcfda7c | 5,873 | ipynb | Jupyter Notebook | notebooks/06-causality-identifiability.ipynb | hgrif/causality | ba7ab608a7bd732046f4fac9ede918652845d000 | [
"MIT"
] | 79 | 2018-05-27T21:33:53.000Z | 2022-01-10T10:31:46.000Z | notebooks/06-causality-identifiability.ipynb | hgrif/causality | ba7ab608a7bd732046f4fac9ede918652845d000 | [
"MIT"
] | 4 | 2018-08-06T10:57:07.000Z | 2019-12-19T13:01:21.000Z | notebooks/06-causality-identifiability.ipynb | hgrif/causality | ba7ab608a7bd732046f4fac9ede918652845d000 | [
"MIT"
] | 14 | 2018-07-31T08:35:32.000Z | 2022-01-10T00:53:34.000Z | 23.586345 | 227 | 0.546739 | [
[
[
"# Directional Identifiability\n\nFrom Jonas Peters' lecture 3 on causality at the Broad.\n\nIf we have a presumed causal model of the linear form:\n\n$$Y = \\alpha X + N_y$$\n\nwhere $N_y$ is i.i.d. noise in $Y$, and $X$ and $N_y$ are both independent and non-Gaussian, then we cannot find\n\n$$X = \\beta Y + N_x$$\n\nwhere $N_x$ is i.i.d. noise in $X$ that also satisfies the independence constraints. \n\nIn simpler words, if we assume that the distributions of $X$ and $N_y$ are non-Gaussian, then we will know that the causal model goes from $X \\rightarrow Y$ and not $Y \\rightarrow X$.\n\nLet's simulate this.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'",
"_____no_output_____"
]
],
[
[
"Firstly, we will generate non-Gaussian Xs and Ys.",
"_____no_output_____"
]
],
[
[
"X_ng = np.random.uniform(-1, 1, size=1000)\nalpha = 2\nN_y_ng = np.random.uniform(-0.4, 0.4, size=1000)\ny_ng = alpha * X_ng + N_y_ng",
"_____no_output_____"
]
],
[
[
"Now, let's plot Y against X.",
"_____no_output_____"
]
],
[
[
"plt.scatter(X_ng, y_ng)\nplt.ylabel(\"Y\")\nplt.xlabel(\"X\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"Now, let's also simulate the case where $X$ and $N_y$ are Gaussian-distributed and independent.",
"_____no_output_____"
]
],
[
[
"X_g = np.random.normal(0, 0.5, size=1000)\nalpha_g = 2\nN_y_g = np.random.normal(0, 1, size=1000)\ny_g = alpha_g * X_g + N_y_g",
"_____no_output_____"
],
[
"plt.scatter(X_g, y_g)\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"We will now fit X as a function of Y, and do a residual analysis to see whether our residuals (i.e. noise) are independent of the input (in this case Y). Remember, we are looking to check that the inverse condition holds.",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LinearRegression\nlm = LinearRegression()",
"_____no_output_____"
]
],
[
[
"Firstly, we X as function of Y and obtain a coefficient.",
"_____no_output_____"
]
],
[
[
"lm.fit(y_g.reshape(-1, 1), X_g)\ncoeff_g = lm.coef_",
"_____no_output_____"
]
],
[
[
"We then do the same for the non-Gaussian case.",
"_____no_output_____"
]
],
[
[
"lm.fit(y_ng.reshape(-1, 1), X_ng)\ncoeff_ng = lm.coef_",
"_____no_output_____"
]
],
[
[
"Great! Now that we have the coefficients out, let's move on to the analysis of residuals. We will be checking that the residuals ($X - \\beta Y$) should be independent of $Y$.",
"_____no_output_____"
],
[
"First off, the Gaussian case.",
"_____no_output_____"
]
],
[
[
"residuals_g = X_g - coeff_g * y_g\nplt.scatter(y_g, residuals_g)\nplt.xlabel(\"Y\")\nplt.ylabel(\"residual\")\nplt.title(\"Gaussian\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"We see that there is no trend in the residuals.",
"_____no_output_____"
],
[
"Now, the non-gaussian case.",
"_____no_output_____"
]
],
[
[
"residuals_ng = X_ng - coeff_ng * y_ng\nplt.scatter(y_ng, residuals_ng)\nplt.xlabel(\"Y\")\nplt.ylabel(\"residuals\")\nplt.title(\"non-Gaussian\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"We see that there is a clear trend - residual depends on the value of y in the non-Gaussian case, whereas it does not in the Gaussian case.\n\nThis empirical simulation illustrates how we cannot recover an inverse model where the noise in X ($N_x$) is independent of the value of $Y$. Hence, we have an **identifiable** model under non-Gaussian assumptions.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ece640b343a6be6a32aecaf367f10633c78a1556 | 43,385 | ipynb | Jupyter Notebook | model_training/BERT_Model_SinglePage.ipynb | agiagoulas/page-stream-segmentation | ad3dece4a4ce675e254b675c96443389d55c9cde | [
"MIT"
] | null | null | null | model_training/BERT_Model_SinglePage.ipynb | agiagoulas/page-stream-segmentation | ad3dece4a4ce675e254b675c96443389d55c9cde | [
"MIT"
] | null | null | null | model_training/BERT_Model_SinglePage.ipynb | agiagoulas/page-stream-segmentation | ad3dece4a4ce675e254b675c96443389d55c9cde | [
"MIT"
] | 1 | 2022-02-26T20:44:59.000Z | 2022-02-26T20:44:59.000Z | 33.398768 | 270 | 0.486574 | [
[
[
"<a href=\"https://colab.research.google.com/github/agiagoulas/page-stream-segmentation/blob/master/model_training/BERT_Model_SinglePage.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"!pip install transformers",
"_____no_output_____"
],
[
"import csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom transformers import BertTokenizerFast\nfrom transformers import BertForSequenceClassification, Trainer, TrainingArguments\nimport torch",
"_____no_output_____"
],
[
"from keras.models import load_model, Model\nfrom sklearn import metrics as sklm\nimport numpy as np\nimport keras.backend as K\nimport tensorflow as tf\nimport requests",
"_____no_output_____"
],
[
"def read_csv_data(csvfile):\n texts = []\n labels = []\n doc_names = []\n with open(csvfile, 'r', encoding='UTF-8') as f:\n datareader = csv.reader(f, delimiter=';', quotechar='\"')\n next(datareader)\n for counter, csv_row in enumerate(datareader):\n texts.append(csv_row[1])\n labels.append(1 if csv_row[2] == \"FirstPage\" else 0)\n doc_names.append(csv_row[3])\n return texts, labels, doc_names",
"_____no_output_____"
],
[
"working_dir = \"/sample_dir/\"",
"_____no_output_____"
],
[
"train_texts, train_labels, train_names = read_csv_data(working_dir + \"/tobacco800.train\")\ntest_texts, test_labels, test_names = read_csv_data(working_dir + \"tobacco800.test\")",
"_____no_output_____"
]
],
[
[
"# BERT Training",
"_____no_output_____"
]
],
[
[
"class Tobacco800Dataset(torch.utils.data.Dataset):\n def __init__(self, encodings, labels):\n self.encodings = encodings\n self.labels = labels\n\n def __getitem__(self, idx):\n item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n item['labels'] = torch.tensor(self.labels[idx])\n return item\n\n def __len__(self):\n return len(self.labels)\n \ndef compute_metrics(pred):\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n acc = accuracy_score(labels, preds)\n return {\n 'accuracy': acc,\n }",
"_____no_output_____"
],
[
"tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')",
"_____no_output_____"
],
[
"train_encodings = tokenizer(train_texts, truncation=True, padding=True)\ntest_encodings = tokenizer(test_texts, truncation=True, padding=True)",
"_____no_output_____"
],
[
"train_dataset = Tobacco800Dataset(train_encodings, train_labels)\ntest_dataset = Tobacco800Dataset(test_encodings, test_labels)",
"_____no_output_____"
],
[
"training_args = TrainingArguments(\n output_dir='./results', \n num_train_epochs=20, \n per_device_train_batch_size=16, \n per_device_eval_batch_size=64, \n warmup_steps=500, \n weight_decay=0.01, \n logging_dir='./logs', \n logging_steps=10,\n)",
"_____no_output_____"
],
[
"model = BertForSequenceClassification.from_pretrained('bert-base-uncased')\n\ntrainer = Trainer(\n model=model, \n args=training_args, \n train_dataset=train_dataset, \n compute_metrics=compute_metrics\n)\n\ntrainer.train()",
"_____no_output_____"
],
[
"model.save_pretrained(working_dir + \"bert-model/\")",
"_____no_output_____"
],
[
"trainer.evaluate(eval_dataset=test_dataset)",
"_____no_output_____"
]
],
[
[
"# Bert Predictions",
"_____no_output_____"
]
],
[
[
"loaded_model = BertForSequenceClassification.from_pretrained(working_dir + \"bert-model/\")\ntokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')",
"_____no_output_____"
],
[
"y_predict_bert=[]\nfor item in test_texts:\n inputs = tokenizer(item, padding=True, truncation=True, return_tensors=\"pt\")\n outputs = loaded_model(**inputs)\n y_predict_bert.append(outputs.logits.argmax(-1).item())",
"_____no_output_____"
],
[
"print(y_predict_bert)",
"_____no_output_____"
]
],
[
[
"# Multi-Modal Predictions\n Late Fusion Approach",
"_____no_output_____"
]
],
[
[
"model_img_request = requests.get(\"https://raw.githubusercontent.com/agiagoulas/page-stream-segmentation/master/app/pss/model_img.py\")\nwith open(\"model_img.py\", \"w\") as f:\n f.write(model_img_request.text)\nimport model_img",
"_____no_output_____"
],
[
"img_dim = (224,224)\nmodel_img.img_path_template = working_dir + \"Tobacco800_Small/%s.png\"\ndata_image_test = model_img.read_csv_data(working_dir + \"tobacco800.test\")\nmodel_image = load_model(working_dir + \"Tobacco800_exp2_prev-page_repeat-07.hdf5\")",
"_____no_output_____"
],
[
"prediction_image_test = np.round(model_image.predict(model_img.ImageFeatureGenerator(data_image_test, img_dim, prevpage=True, train=True)))\nprobability_image_test = np.concatenate([1 - prediction_image_test, prediction_image_test], axis = 1)",
"_____no_output_____"
],
[
"prediction_bert_test = np.array(y_predict_bert)\nprobability_bert_test = np.concatenate([1 - prediction_bert_test.reshape(-1,1), prediction_bert_test.reshape(-1,1)], axis=1)",
"_____no_output_____"
],
[
"max_kappa = 0\ntest_exponents = [x / 10 for x in range(1,11)]\nfor i in test_exponents:\n for j in test_exponents:\n y_predict = np.argmax(np.power(probability_image_test, i) * np.power(probability_bert_test, j), axis = 1)\n acc = sklm.accuracy_score(test_labels, y_predict)\n kappa = sklm.cohen_kappa_score(test_labels, y_predict)\n if kappa > max_kappa:\n max_kappa = kappa\n print(str(i) + \" \" + str(j))\n print(\"Accuracy: \" + str(acc))\n print(\"Kappa: \" + str(kappa))",
"0.1 0.1\nAccuracy: 0.9343629343629344\nKappa: 0.8666686854616479\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
ece642a68a2acd5b5982af23935e38811d402c81 | 254,169 | ipynb | Jupyter Notebook | .ipynb_checkpoints/zalando_challenge-checkpoint.ipynb | Nathx/pdf_mapping_berlin | 129942f35bf6b8e1f70e0a39b5db27c82d53992f | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/zalando_challenge-checkpoint.ipynb | Nathx/pdf_mapping_berlin | 129942f35bf6b8e1f70e0a39b5db27c82d53992f | [
"Apache-2.0"
] | null | null | null | .ipynb_checkpoints/zalando_challenge-checkpoint.ipynb | Nathx/pdf_mapping_berlin | 129942f35bf6b8e1f70e0a39b5db27c82d53992f | [
"Apache-2.0"
] | null | null | null | 304.758993 | 111,514 | 0.916131 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom geopy.distance import vincenty\nimport scipy.stats as scs\n%matplotlib inline",
"_____no_output_____"
],
[
"SW_LAT, SW_LON = 52.464011, 13.274099\nNE_LAT, NE_LON = 52.586925, 13.521837",
"_____no_output_____"
],
[
"def convert_coord(x, y):\n lon = SW_LON + x / (np.cos(SW_LAT*np.pi/180) * 111.323)\n lat = SW_LAT + y / 111.323\n return lon, lat",
"_____no_output_____"
],
[
"with open('river_spree.txt', 'r') as f:\n line = f.readline()\n river_spree = []\n while line:\n lat, lon = [float(el) for el in line.strip('\\n').split(',')]\n river_spree.append((lat, lon))\n line = f.readline()",
"_____no_output_____"
],
[
"def dist_to_spree(coords):\n return min(vincenty(coords, river_pt).m for river_pt in river_spree)\n\ndef dist_to_bg(coords):\n bg_coords = 52.516288, 13.377689\n return vincenty(coords, bg_coords).m",
"_____no_output_____"
],
[
"dist_to_bg((SW_LAT, SW_LON))",
"_____no_output_____"
],
[
"np.radians((SW_LAT, SW_LON))",
"_____no_output_____"
],
[
"def bearing(start, end):\n start_lat, start_lon = np.radians(start)\n end_lat, end_lon = np.radians(end)\n delta_lon = np.radians(end[1] - start[1])\n \n br = np.arctan2(np.sin(delta_lon) * np.cos(end_lat), \n np.cos(start_lat) * np.sin(end_lat) - np.sin(start_lat) * np.cos(end_lat) * np.cos(delta_lon))\n br = np.degrees(br) % 360\n return br\n\ndef dist_to_sat(coords):\n ",
"_____no_output_____"
],
[
"class Location(object):\n def __init__(self, coords):\n self.coords = coords\n self.distribution = None\n\n def distance(self, point):\n \"\"\"Returns distance from instance to point of interest.\"\"\"\n pass\n\n def prob(self, point):\n \"\"\"\n Returns probability of finding the candidate at this point.\n \"\"\"\n path_dist = self.distance(point)\n return self.distribution.pdf(path_dist)\n\n\nclass Satellite(Location):\n def __init__(self, coords, ci_range):\n super(Satellite, self).__init__(coords)\n self.distribution = scs.norm(0, ci_range / 1.96)\n self.R = 6371\n\n def distance(self, point):\n sat_start, sat_end = self.coords\n delta_13 = vincenty(sat_start, point).km / self.R\n theta_13 = self.bearing(sat_start, point)\n theta_12 = self.bearing(sat_start, sat_end)\n return np.arcsin(np.sin(delta_13) * np.sin(np.radians(theta_13 - theta_12))) * self.R\n\n def bearing(self, start, end):\n start_lat, start_lon = np.radians(start)\n end_lat, end_lon = np.radians(end)\n delta_lon = np.radians(end[1] - start[1])\n\n br = np.arctan2(np.sin(delta_lon) * np.cos(end_lat),\n np.cos(start_lat) * np.sin(end_lat) - np.sin(start_lat) * np.cos(end_lat) * np.cos(delta_lon))\n br = np.degrees(br) % 360\n return br\n\n\nclass River(Location):\n def __init__(self, coords, ci_range):\n super(River, self).__init__(coords)\n self.lines = self.make_linear(coords)\n self.distribution = scs.norm(0, ci_range / 1.96)\n\n def make_linear(self, coords):\n xy_coords = [self.convert_xy(*lon_lat) for lon_lat in self.coords]\n return zip(xy_coords[:-1], xy_coords[1:])\n\n def distance(self, point):\n xy_point = self.convert_xy(*point)\n return min(self.line_distance(xy_point, line) for line in self.lines)\n\n def line_distance(self, point, line):\n \"\"\"\n Distance from a given point to a segment of the river.\n \"\"\"\n start, end = line\n line_x = end[0] - start[0]\n line_y = end[1] - start[1]\n\n line_length = np.sqrt(line_x**2 + line_y**2)\n\n u = ((point[0] - start[0]) * line_x + (point[1] - start[1]) * line_y) / line_length**2\n\n u = np.clip(u, 0, 1)\n\n x = start[0] + u * line_x\n y = start[1] + u * line_y\n\n dx = x - point[0]\n dy = y - point[1]\n\n dist = np.sqrt(dx*dx + dy*dy)\n\n return dist\n\n def convert_xy(self, lon, lat):\n x = (lon - SW_LON) * np.cos(SW_LAT*np.pi/180) * 111.323\n y = (lat - SW_LAT) * 111.323\n return x, y\n\n\nclass BGate(Location):\n def __init__(self, coords, mean, mode):\n super(BGate, self).__init__(coords)\n self.distribution = self.set_distribution(mean, mode)\n\n def set_distribution(self, mean, mode):\n \"\"\"\n Create lognormal distribution from given mean and mode.\n Distances are converted to km to prevent overflow.\n \"\"\"\n scale = np.exp(mean)\n s = np.sqrt(np.log(scale / float(mode)))\n print \"s: %s, scale: %s\" % (s, scale)\n return scs.lognorm(s=s, scale=scale)\n\n def distance(self, point):\n \"\"\"\n Distances are converted to km to prevent overflow.\n \"\"\"\n return vincenty(point, self.coords[0]).km\n",
"_____no_output_____"
],
[
"river = River(river_spree, 2730)\nprint river.distance(river_spree[0])\nprint river.distance((SW_LAT, SW_LON))",
"0.0\n4.42128287598\n"
],
[
"n = 512\nx = np.linspace(SW_LAT, NE_LAT, n)\ny = np.linspace(SW_LON, NE_LON, n)\nX, Y = np.meshgrid(x, y)",
"_____no_output_____"
],
[
"\nsat_coords = [(52.590117,13.39915), (52.437385,13.553989)]\nsat = Satellite(sat_coords, 2.400)\nsat_probs = [sat.prob((x, y)) for x, y in zip(X.flatten(), Y.flatten())]",
"_____no_output_____"
],
[
"river = River(river_spree, 2.730)\nriver_probs = [river.prob((x, y)) for x, y in zip(X.flatten(), Y.flatten())]",
"_____no_output_____"
],
[
"plt.contourf(X, Y, np.reshape(river_probs, (n, n)), cmap='Blues')\nC = plt.contour(X, Y, np.reshape(river_probs, (n, n)), 5, colors='black', linewidth=.1)",
"_____no_output_____"
],
[
"bg_coords = [(52.516288, 13.377689)]\nbg = BGate(bg_coords, mean=4.7, mode=3.877)",
"s: 1.82891725929, scale: 109.947172452\n"
],
[
"bg_probs = [bg.prob((x, y)) for x, y in zip(X.flatten(), Y.flatten())]",
"_____no_output_____"
],
[
"plt.contourf(X, Y, np.reshape(bg_probs, (n, n)), cmap='Blues')\nC = plt.contour(X, Y, np.reshape(bg_probs, (n, n)), 5, colors='black', linewidth=.1)",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(5,15))\ntot_probs = np.ones((n, n))\nfor i, ind_probs in enumerate([sat_probs, bg_probs, river_probs]):\n ax = fig.add_subplot(3,1,i+1)\n tot_probs *= np.reshape(ind_probs, (n, n))\n plt.contourf(X, Y, tot_probs, cmap='Blues')\n C = plt.contour(X, Y, tot_probs, 5, colors='black', linewidth=.1)",
"_____no_output_____"
],
[
"path = C.collections[0].get_paths()[0]",
"_____no_output_____"
],
[
"import gmplot\ngmap = gmplot.GoogleMapPlotter((SW_LAT + NE_LAT)/2, (SW_LON + NE_LON)/2, 11)\n\nmax_idx = np.argmax(tot_probs)\ngmap.scatter([X.flatten()[max_idx]], [Y.flatten()[max_idx]], c='r', marker=True)\n\nheatmap_idx = pull_heatmap_idx(tot_probs, size=10000)\ngmap.heatmap(X.flatten()[heatmap_idx], Y.flatten()[heatmap_idx], radius=5, threshold=10000, opacity=.4)\ngmap.plot(*zip(*path.vertices))\n\ngmap.draw('mymap.html')",
"_____no_output_____"
],
[
"def get_color_map(levels):\n sm = ScalarMappable(cmap='YlOrRd')\n normed_levels = C.levels / np.max(C.levels)\n colors = 255 * sm.to_rgba(normed_levels)[:, :3]\n print colors\n return ['#%02x%02x%02x' % (r, g, b) for r,g,b in colors]\n\nget_color_map(C.levels)",
"[[ 255. 255. 204.00000304]\n [ 254.00000006 216.69411993 117.67058882]\n [ 252.98431385 140.01177144 59.7176473 ]\n [ 226.10588408 25.38823564 28.23529438]\n [ 128.00000757 0. 38.00000153]]\n"
],
[
"def pull_heatmap_idx(probs, size=10000):\n probs /= np.sum(probs)\n return np.random.choice(np.arange(probs.size), size=size, p=probs.flatten())",
"_____no_output_____"
],
[
"# coding: utf-8\nfrom location import Satellite, River, BGate\nfrom mapper import Mapper\nimport sys\n\n\nif __name__ == '__main__':\n\n print \"Generating objects..\"\n\n bg_coords = [(52.516288, 13.377689)]\n sat_coords = [(52.590117,13.39915), (52.437385,13.553989)]\n\n with open('river_spree.txt', 'r') as f:\n line = f.readline()\n river_coords = []\n while line:\n lat, lon = [float(el) for el in line.strip('\\n').split(',')]\n river_coords.append((lat, lon))\n line = f.readline()\n\n objects = [BGate(bg_coords, mean=4.7, mode=3.877)]\n# Satellite(sat_coords, 2.4),\n# River(river_coords, 2.73)]\n\n mapper = Mapper(objects)\n for obj in objects:\n print \"Creating map for %s..\" % obj.name\n mapper.generate_map([obj], plot_type='lines', size=50000, threshold=1000)\n\n print \"Creating final map..\"\n\n# mapper.generate_map(plot_type='heatmap', size=50000)",
"Generating objects..\nCreating map for brandenburger_gate..\nCreating final map..\n"
],
[
"import mapper\nreload(mapper)\nfrom mapper import Mapper",
"_____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"
]
] |
ece656bbcbedd63b739aae8d6fc2461caa893a76 | 141,674 | ipynb | Jupyter Notebook | Notebooks/Station Map.ipynb | jrleeman/CAPE-SciPy-2017 | 9d0f05c0528059e573fe5238f41dd1cce5f6e0d8 | [
"MIT"
] | 2 | 2018-02-22T11:49:54.000Z | 2019-01-28T01:59:14.000Z | Notebooks/Station Map.ipynb | jrleeman/CAPE-SciPy-2017 | 9d0f05c0528059e573fe5238f41dd1cce5f6e0d8 | [
"MIT"
] | null | null | null | Notebooks/Station Map.ipynb | jrleeman/CAPE-SciPy-2017 | 9d0f05c0528059e573fe5238f41dd1cce5f6e0d8 | [
"MIT"
] | null | null | null | 417.917404 | 132,082 | 0.916774 | [
[
[
"import cartopy.feature as cfeat\nimport cartopy.crs as ccrs\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline",
"_____no_output_____"
],
[
"df = pd.read_fwf('Station_Locations.txt')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"def parse_lat_lon_string(text):\n text = text.split(' ')\n degrees = int(text[0]) + float(text[1][0:2])/100\n if (text[1][-1] == 'S') or (text[1][-1] =='W'):\n degrees *= -1\n return degrees",
"_____no_output_____"
],
[
"df['LAT'] = df['LAT'].map(parse_lat_lon_string, na_action='ignore')\ndf['LON'] = df['LON'].map(parse_lat_lon_string, na_action='ignore')",
"_____no_output_____"
],
[
"# Stations to get data from\nall_stations = ['UIL', 'YLW', 'OTX', 'MFR', 'BOI', 'REV', 'OAK',\n 'LKN', 'VEF', 'NKX', 'TFX', 'GGW', 'RIW', 'RAP',\n 'SLC', 'GJT', 'DNR', 'ABQ', 'FGZ', 'TUS', 'EPZ',\n 'BIS', 'ABR', 'MPX', 'WPL', 'INL', 'YMO', 'GRB',\n 'LBF', 'OAX', 'DDC', 'TOP', 'AMA', 'OUN', 'MAF',\n 'FWD', 'DRT', 'CRP', 'ADN', 'BRO', 'DVN', 'ILX',\n 'SGF', 'LZK', 'SHV', 'LCH', 'JAN', 'LIX', 'BMX',\n 'BNA', 'FFC', 'TLH', 'APX', 'DTX', 'ILN', 'WMW',\n 'GYX', 'BUF', 'ALB', 'CAR', 'YQI', 'CHH', 'OKX',\n 'PIT', 'IAD', 'WAL', 'MHX', 'RNK', 'GSO', 'CHS',\n 'JAX', 'TBW', 'MFL', 'KEY']\n\nlats_all = []\nlongs_all = []\nfor station in all_stations:\n try:\n stn = df[df['ICAO'] == 'K'+station]\n lats_all.append(float(stn['LAT']))\n longs_all.append(float(stn['LON']))\n except:\n print(\"No record \", station)",
"No record YLW\nNo record WPL\nNo record YMO\nNo record ADN\nNo record WMW\nNo record YQI\n"
],
[
"df_soundings = pd.read_csv('Soundings_1992.txt')\nlats_1992 = []\nlongs_1992 = []\nstations = df_soundings['Station'].unique()\nfor station in stations:\n try:\n stn = df[df['ICAO'] == 'K'+station]\n lats_1992.append(float(stn['LAT']))\n longs_1992.append(float(stn['LON']))\n except:\n print(\"No record \", station)",
"No record WPL\nNo record YMO\nNo record ADN\nNo record WMW\nNo record YQI\n"
],
[
"fig = plt.figure(figsize=(10, 8))\nax = fig.add_subplot(1, 1, 1, projection=ccrs.LambertConformal())\n\nax.add_feature(cfeat.LAND)\nax.add_feature(cfeat.OCEAN)\nax.add_feature(cfeat.COASTLINE)\nax.add_feature(cfeat.BORDERS, linestyle=':')\n\n# Grab state borders\nstate_borders = cfeat.NaturalEarthFeature(category='cultural',\n name='admin_1_states_provinces_lakes', scale='50m', facecolor='none') \nax.add_feature(state_borders, linestyle=\"--\", edgecolor='k')\n\nax.plot(longs_all, lats_all, transform=ccrs.PlateCarree(), marker='o', linestyle='None', color='k', label='Current Stations')\nax.plot(longs_1992, lats_1992, transform=ccrs.PlateCarree(), marker='o', linestyle='None', color='tab:red', label='1992 Data Available')\n\nplt.legend(fontsize=16)\n\nplt.savefig('../Plots/Station_Map.png', bbox_inches='tight', dpi=300); ",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece659610d56babccca1add69f40c686830ff8a1 | 73,255 | ipynb | Jupyter Notebook | how-to-use.ipynb | evanfebrianto/night2day | 77ae4ecf15f0b147d23c7bd01a5f8cb75660fdb7 | [
"BSD-2-Clause"
] | null | null | null | how-to-use.ipynb | evanfebrianto/night2day | 77ae4ecf15f0b147d23c7bd01a5f8cb75660fdb7 | [
"BSD-2-Clause"
] | null | null | null | how-to-use.ipynb | evanfebrianto/night2day | 77ae4ecf15f0b147d23c7bd01a5f8cb75660fdb7 | [
"BSD-2-Clause"
] | null | null | null | 50.800971 | 458 | 0.466303 | [
[
[
"<h1><center>Day2Night Image Translation</center></h1>",
"_____no_output_____"
],
[
"<img src=\"./src/title.jpg\">\n\nThis notebook represents easy how-to-use steps in using GAN to change day to night or reversed based on your needs. Please follow all the instructions carefully and make sure the properties are configured based on your needs. \n\nThis code based on <b>Night-to-Day Image Translation for Retrieval-based Localization</b> Asha Anoosheh, Torsten Sattler, Radu Timofte, Marc Pollefeys, Luc van Gool In Arxiv, 2018. https://github.com/AAnoosheh/ToDayGAN",
"_____no_output_____"
],
[
"## 0. Initialization\nBefore started the training process, make sure that the datasets are properly placed inside directories (for training) or the model is in the proper place (for testing)",
"_____no_output_____"
]
],
[
[
"# Install pytorch\n\"\"\"\n Install PyTorch from PyTorch website\n https://pytorch.org/get-started/locally/\n \n Then select the system properties based on configuration below\n \n PyTorch Build -> Stable\n OS ------------> Windows\n Package -------> Pip\n Language ------> Python\n CUDA ----------> (Check in your nvidia-smi)\n\n Then copy the command for pip installation\n in \"Run This Command\" section and paste in the command below\n then run the '!pip install ~' line\n \n !(paste pip install torch~~~.html)\n\"\"\"\n\n!pip install torch~~~.html",
"_____no_output_____"
],
[
"# install package requirements\n!pip install -r requirements.txt",
"_____no_output_____"
]
],
[
[
"## 1. 1. Train\nThis line directly execure the train.py to train the model. Just use the necessary option of commands from the list below.\nSpecify the **name** of your project, then change **niter** and **niter_decay** based on your needs (the 75 Epoch is just default as trained from the original paper). total **Epoch** is niter + niter_decay. The difference between them is the changing learning rate until the end of training. Please also specify the **gpu_id** to use (Just select one if multiple gpu available) ",
"_____no_output_____"
]
],
[
[
"\"\"\"\n --(Arguments) (Default value) -------- (Description) : \n -------------------------------------------------\n --name robotcar_night2day ------------ Name of the experiment. It decides where to store samples and models\n --dataroot ./datasets/train_dataset -- Path to images (should have subfolders trainA, trainB, valA, valB, etc)\n --n_domains 2 ------------------------ Number of domains to transfer among\n --niter 75 --------------------------- # of epochs at starting learning rate (try 50*n_domains)\n --niter_decay 75 --------------------- # of epochs to linearly decay learning rate to zero (try 50*n_domains)\n --loadSize 512 ----------------------- Scale images to this size\n --fineSize 384 ----------------------- Then crop to this size\n --gpu_ids -1 ------------------------- GPU id: e.g. 0, 1, or 2. use -1 for CPU\n\"\"\" \n\n!python train.py --name robotcar_night2day \\\n --dataroot ./datasets/train_dataset \\\n --n_domains 2 \\\n --niter 75 \\\n --niter_decay 75 \\\n --loadSize 512 \\\n --fineSize 384 \\\n --gpu_ids -1",
"------------ Options -------------\nbatchSize: 1\nbeta1: 0.5\ncheckpoints_dir: ./checkpoints\ncontinue_train: False\ndataroot: ./datasets/train_dataset\ndisplay_freq: 100\ndisplay_id: 0\ndisplay_port: 8097\ndisplay_single_pane_ncols: 0\ndisplay_winsize: 256\nfineSize: 384\ngpu_ids: [0]\ninput_nc: 3\nisTrain: True\nlambda_cycle: 10.0\nlambda_forward: 0.0\nlambda_identity: 0.0\nlambda_latent: 0.0\nloadSize: 512\nlr: 0.0002\nmax_dataset_size: inf\nnThreads: 2\nn_domains: 2\nname: robotcar_night2day\nndf: 64\nnetD_n_layers: 4\nnetG_n_blocks: 9\nnetG_n_shared: 0\nngf: 64\nniter: 5\nniter_decay: 5\nno_flip: False\nno_html: False\nnorm: instance\noutput_nc: 3\nphase: train\npool_size: 50\nprint_freq: 100\nresize_or_crop: resize_and_crop\nsave_epoch_freq: 5\nuse_dropout: False\nwhich_epoch: 0\n-------------- End ----------------\n# training images = 90\n---------- Networks initialized -------------\nResnetGenEncoder(\n (model): Sequential(\n (0): ReflectionPad2d((3, 3, 3, 3))\n (1): Conv2d(3, 64, kernel_size=(7, 7), stride=(1, 1))\n (2): InstanceNorm2d(64, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n (5): InstanceNorm2d(128, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (6): PReLU(num_parameters=1)\n (7): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n (8): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (9): PReLU(num_parameters=1)\n (10): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (11): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (12): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (13): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n )\n)\nResnetGenDecoder(\n (model): Sequential(\n (0): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (1): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (2): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (3): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (4): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (5): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1))\n (6): InstanceNorm2d(128, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (7): PReLU(num_parameters=1)\n (8): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1))\n (9): InstanceNorm2d(64, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (10): PReLU(num_parameters=1)\n (11): ReflectionPad2d((3, 3, 3, 3))\n (12): Conv2d(64, 3, kernel_size=(7, 7), stride=(1, 1))\n (13): Tanh()\n )\n)\nCreated 2 Encoder-Decoder pairs\nNumber of parameters per Encoder: 5099143\nNumber of parameters per Deocder: 6565770\nNLayerDiscriminator(\n (model_rgb): SequentialOutput(\n (0): Sequential(\n (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): PReLU(num_parameters=1)\n )\n (1): Sequential(\n (0): Conv2d(64, 129, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(129, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (2): Sequential(\n (0): Conv2d(128, 257, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(257, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (3): Sequential(\n (0): Conv2d(256, 513, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(513, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (4): Sequential(\n (0): Conv2d(512, 512, kernel_size=(4, 4), stride=(1, 1), padding=(2, 2))\n (1): InstanceNorm2d(512, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n (3): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), padding=(2, 2))\n )\n )\n (model_gray): SequentialOutput(\n (0): Sequential(\n (0): Conv2d(1, 64, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): PReLU(num_parameters=1)\n )\n (1): Sequential(\n (0): Conv2d(64, 129, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(129, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (2): Sequential(\n (0): Conv2d(128, 257, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(257, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (3): Sequential(\n (0): Conv2d(256, 513, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(513, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (4): Sequential(\n (0): Conv2d(512, 512, kernel_size=(4, 4), stride=(1, 1), padding=(2, 2))\n (1): InstanceNorm2d(512, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n (3): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), padding=(2, 2))\n )\n )\n (model_grad): SequentialOutput(\n (0): Sequential(\n (0): Conv2d(2, 64, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): PReLU(num_parameters=1)\n )\n (1): Sequential(\n (0): Conv2d(64, 129, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(129, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (2): Sequential(\n (0): Conv2d(128, 257, kernel_size=(4, 4), stride=(2, 2), padding=(2, 2))\n (1): InstanceNorm2d(257, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n )\n (3): Sequential(\n (0): Conv2d(256, 512, kernel_size=(4, 4), stride=(1, 1), padding=(2, 2))\n (1): InstanceNorm2d(512, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (2): PReLU(num_parameters=1)\n (3): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), padding=(2, 2))\n )\n )\n)\nCreated 2 Discriminators\nNumber of parameters per Discriminator: 16698201\n-----------------------------------------------\ncreate web directory ./checkpoints\\robotcar_night2day\\web...\nEnd of epoch 1 / 10 \t Time Taken: 88 sec\n(epoch: 2, iters: 10, time: 1.215) D: 0.177, 0.147 | G: 0.377, 0.465 | Cyc: 0.032, 0.090 | \nEnd of epoch 2 / 10 \t Time Taken: 87 sec\n(epoch: 3, iters: 20, time: 1.206) D: 0.176, 0.132 | G: 0.319, 0.342 | Cyc: 0.035, 0.034 | \nEnd of epoch 3 / 10 \t Time Taken: 87 sec\n(epoch: 4, iters: 30, time: 1.203) D: 0.124, 0.129 | G: 0.357, 0.378 | Cyc: 0.018, 0.018 | \nEnd of epoch 4 / 10 \t Time Taken: 87 sec\n(epoch: 5, iters: 40, time: 1.212) D: 0.232, 0.118 | G: 0.574, 0.405 | Cyc: 0.021, 0.018 | \nsaving the model at the end of epoch 5, iters 450\nEnd of epoch 5 / 10 \t Time Taken: 88 sec\n(epoch: 6, iters: 50, time: 1.216) D: 0.145, 0.119 | G: 0.335, 0.366 | Cyc: 0.014, 0.018 | \nEnd of epoch 6 / 10 \t Time Taken: 87 sec\nupdated learning rate: 0.000160\n(epoch: 7, iters: 60, time: 1.195) D: 0.119, 0.129 | G: 0.381, 0.340 | Cyc: 0.021, 0.012 | \nEnd of epoch 7 / 10 \t Time Taken: 87 sec\nupdated learning rate: 0.000120\n(epoch: 8, iters: 70, time: 1.179) D: 0.089, 0.116 | G: 0.537, 0.338 | Cyc: 0.021, 0.029 | \nEnd of epoch 8 / 10 \t Time Taken: 87 sec\nupdated learning rate: 0.000080\n(epoch: 9, iters: 80, time: 1.228) D: 0.091, 0.101 | G: 0.580, 0.393 | Cyc: 0.019, 0.023 | \nEnd of epoch 9 / 10 \t Time Taken: 87 sec\nupdated learning rate: 0.000040\n(epoch: 10, iters: 90, time: 1.219) D: 0.126, 0.099 | G: 0.364, 0.552 | Cyc: 0.015, 0.010 | \nsaving the model at the end of epoch 10, iters 900\nEnd of epoch 10 / 10 \t Time Taken: 88 sec\nupdated learning rate: 0.000000\n"
]
],
[
[
"## 1. 2. Continue\nThis line directly continue the training process from specified epoch. Make sure the **name** of the project is as the same from the train section. Also make sure the last epoch specified from the **which_epoch** argument. Don't forget to specify **gpu_id** to use (Just select one if multiple gpu available)",
"_____no_output_____"
]
],
[
[
"\"\"\"\n --(Arguments) (Default value) -------- (Description) : \n -------------------------------------------------\n --continue_train --------------------- Continue training: load the latest model\n --which_epoch 0 ---------------------- Which epoch to load if continuing training\n --name robotcar_night2day ------------ Name of the experiment. It decides where to store samples and models\n --dataroot ./datasets/train_dataset -- Path to images (should have subfolders trainA, trainB, valA, valB, etc)\n --n_domains 2 ------------------------ Number of domains to transfer among\n --niter 75 --------------------------- # of epochs at starting learning rate (try 50*n_domains)\n --niter_decay 75 --------------------- # of epochs to linearly decay learning rate to zero (try 50*n_domains)\n --loadSize 512 ----------------------- Scale images to this size\n --fineSize 384 ----------------------- Then crop to this size\n --gpu_ids -1 ------------------------- GPU id: e.g. 0, 1, or 2. use -1 for CPU\n\"\"\" \n\n!python train.py --continue_train \\\n --which_epoch 5 \\\n --name robotcar_night2day \\\n --dataroot ./datasets/train_dataset \\\n --n_domains 2 \\\n --niter 75 \\\n --niter_decay 75 \\\n --loadSize 512 \\\n --fineSize 384 \\\n --gpu_ids -1",
"_____no_output_____"
]
],
[
[
"## 1. 3. Check Train Results\nThis line shows the overall result of the training process. Kindly specify the **project name** for the specific project to show",
"_____no_output_____"
]
],
[
[
"from util.helper import show_training_result\n\nname = 'robotcar_night2day'\nshow_training_result(name)",
"_____no_output_____"
]
],
[
[
"## 2. 1. Test\nThis line directly execure the test.py to test the model. Just use the necessary option of commands from the list below. This part can be separated from the part (1. Train) or (2. Continue), because this can be used anytime as long as you have the trained models. Make sure the **name** and **which_epoch** of the project is the same as the saved model's name and epoch. Don't forget to specify gpu_id to use (Just select one if multiple gpu available)",
"_____no_output_____"
]
],
[
[
"\"\"\"\n --(Arguments) (Default value) ------- (Description) : \n -------------------------------------------------\n --name robotcar_2day ---------------- Name of the experiment. It decides where to store samples and models\n --dataroot ./datasets/test_dataset -- Path to images (should have subfolders trainA, trainB, valA, valB, etc)\n --phase test ------------------------ Train, val, test, etc (determines name of folder to load from)\n --which_epoch 150 ------------------- Which epoch to load for inference?\n --serial_test ----------------------- Read each image once from folders in sequential order\n --n_domains 2 ----------------------- Number of domains to transfer among\n --loadSize 512 ---------------------- Scale images to this size\n --gpu_ids -1 ------------------------ GPU id: e.g. 0, 1, or 2. use -1 for CPU\n\"\"\" \n\n!python test.py --name robotcar_2day \\\n --dataroot ./datasets/test_dataset/ \\\n --n_domains 2 \\\n --which_epoch 150 \\\n --loadSize 512 \\\n --serial_test \\\n --gpu_ids 0",
"------------ Options -------------\naspect_ratio: 1.0\nautoencode: False\nbatchSize: 1\ncheckpoints_dir: ./checkpoints\ndataroot: ./datasets/test_dataset/\ndisplay_id: 0\ndisplay_port: 8097\ndisplay_single_pane_ncols: 0\ndisplay_winsize: 256\nfineSize: 256\ngpu_ids: [0]\nhow_many: 50\ninput_nc: 3\nisTrain: False\nloadSize: 512\nmax_dataset_size: inf\nnThreads: 1\nn_domains: 2\nname: robotcar_2day\nndf: 64\nnetD_n_layers: 4\nnetG_n_blocks: 9\nnetG_n_shared: 0\nngf: 64\nno_flip: False\nnorm: instance\noutput_nc: 3\nphase: test\nreconstruct: False\nresize_or_crop: resize_and_crop\nresults_dir: ./results/\nserial_test: True\nshow_matrix: False\nuse_dropout: False\nwhich_epoch: 150\n-------------- End ----------------\n---------- Networks initialized -------------\nResnetGenEncoder(\n (model): Sequential(\n (0): ReflectionPad2d((3, 3, 3, 3))\n (1): Conv2d(3, 64, kernel_size=(7, 7), stride=(1, 1))\n (2): InstanceNorm2d(64, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n (5): InstanceNorm2d(128, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (6): PReLU(num_parameters=1)\n (7): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n (8): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (9): PReLU(num_parameters=1)\n (10): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (11): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (12): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (13): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n )\n)\nResnetGenDecoder(\n (model): Sequential(\n (0): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (1): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (2): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (3): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (4): ResnetBlock(\n (conv_block): SequentialContext(\n (0): ReflectionPad2d((1, 1, 1, 1))\n (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (2): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (3): PReLU(num_parameters=1)\n (4): ReflectionPad2d((1, 1, 1, 1))\n (5): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1))\n (6): InstanceNorm2d(256, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n )\n )\n (5): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1))\n (6): InstanceNorm2d(128, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (7): PReLU(num_parameters=1)\n (8): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1))\n (9): InstanceNorm2d(64, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)\n (10): PReLU(num_parameters=1)\n (11): ReflectionPad2d((3, 3, 3, 3))\n (12): Conv2d(64, 3, kernel_size=(7, 7), stride=(1, 1))\n (13): Tanh()\n )\n)\nCreated 2 Encoder-Decoder pairs\nNumber of parameters per Encoder: 5099143\nNumber of parameters per Deocder: 6565770\n-----------------------------------------------\nprocess image... ['./datasets/test_dataset\\\\test0\\\\1417176458999821.jpg']\nprocess image... ['./datasets/test_dataset\\\\test1\\\\1418235223450115.jpg']\nprocess image... ['./datasets/test_dataset\\\\test1\\\\1418235314800423.jpg']\nprocess image... ['./datasets/test_dataset\\\\test1\\\\1418235381972526.jpg']\nprocess image... ['./datasets/test_dataset\\\\test1\\\\1418235515771225.jpg']\nprocess image... ['./datasets/test_dataset\\\\test1\\\\1418235783096127.jpg']\n"
]
],
[
[
"## 2. 2. Test result\nThis line shows the overall result of the testing process. Kindly specify the **name** and **epoch** for the specific project to show",
"_____no_output_____"
]
],
[
[
"from util.helper import show_testing_result\n\nname = 'robotcar_2day'\nepoch = 150\nshow_testing_result(name, epoch)",
"_____no_output_____"
]
]
] | [
"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"
]
] |
ece65d03401946193128d54b801d2afe29f8a80c | 116,109 | ipynb | Jupyter Notebook | deepPRC_GFN_UCM_PAPER_APPSCI.ipynb | jlherraiz/deepPRC | 1ad17bdf038fa87445c44d7d1f2793cc6bdda4f5 | [
"MIT"
] | 1 | 2021-06-03T05:32:31.000Z | 2021-06-03T05:32:31.000Z | deepPRC_GFN_UCM_PAPER_APPSCI.ipynb | jlherraiz/deepPRC | 1ad17bdf038fa87445c44d7d1f2793cc6bdda4f5 | [
"MIT"
] | null | null | null | deepPRC_GFN_UCM_PAPER_APPSCI.ipynb | jlherraiz/deepPRC | 1ad17bdf038fa87445c44d7d1f2793cc6bdda4f5 | [
"MIT"
] | null | null | null | 139.890361 | 52,554 | 0.867297 | [
[
[
"<a href=\"https://colab.research.google.com/github/jlherraiz/deepPRC/blob/main/deepPRC_GFN_UCM_PAPER_APPSCI.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# deepPRC - POSITRON RANGE CORRECTION WITH Deep Learning\nCode from the paper \"Deep-Learning Based Positron Range Correction\" Applied Sciences (Special Issue - PET Imaging with Deep Learning) https://www.mdpi.com/journal/applsci/special_issues/pet_imaging\n### J.L.Herraiz et al. GFN - UCM - 2020",
"_____no_output_____"
],
[
"## STEP 0 ) Install all required libraries ",
"_____no_output_____"
]
],
[
[
"!pip install -q opencv-python\n!pip install -q keras-unet",
"_____no_output_____"
]
],
[
[
"## STEP 1 ) Load Libraries",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\ntf.version.VERSION\nimport numpy as np\nimport os\nimport time\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output\nimport cv2\nimport sklearn.model_selection as sk",
"_____no_output_____"
]
],
[
[
"## CHECK GPU",
"_____no_output_____"
]
],
[
[
"tf.config.list_physical_devices('GPU')",
"_____no_output_____"
]
],
[
[
"## IMAGE PARAMETERS",
"_____no_output_____"
]
],
[
[
"Nx = 154\nNy = 154\nNz0 = 80\n\nNt = 8 # Number of simulated volumes\ndx = 0.0280\ndy = 0.0280\ndz = 0.0280 #VOXEL SIZE (cm) ALONG X,Y,Z \n\nNz = Nt*Nz0 # Total number of slices",
"_____no_output_____"
]
],
[
[
"## LOAD IMAGES\n",
"_____no_output_____"
]
],
[
[
"URL = 'https://tomografia.es/data/Ga68_V2_ALL.raw'\nPATH_Ga68_V2 = tf.keras.utils.get_file('Ga68_V2.raw',origin=URL)\nGa68_V2_file = np.fromfile(PATH_Ga68_V2, dtype='float32')\nGa68 = Ga68_V2_file.reshape((Nz,Ny,Nx))\n#Ga68 = np.concatenate((Ga68,Ga68_V2), axis=0)",
"Downloading data from https://tomografia.es/data/Ga68_V2_ALL.raw\n60719104/60712960 [==============================] - 7s 0us/step\n"
],
[
"URL = 'https://tomografia.es/data/F18_V2_ALL.raw'\nPATH_F18_V2 = tf.keras.utils.get_file('F18_V2_ALL.raw',origin=URL)\nF18_V2_file = np.fromfile(PATH_F18_V2, dtype='float32')\nF18 = F18_V2_file.reshape((Nz,Ny,Nx))\n#F18 = np.concatenate((F18,F18_V2), axis=0)",
"Downloading data from https://tomografia.es/data/F18_V2_ALL.raw\n60719104/60712960 [==============================] - 8s 0us/step\n"
]
],
[
[
"## INPUT NORMALIZATION [0..1]\n",
"_____no_output_____"
]
],
[
[
"for k in range(Nz):\n MAX = np.max(Ga68[k,:,:]) # Ga68 is the input --> Normalized to maximum = 1 each slice (both input and output)\n F18[k,:,:] = F18[k,:,:]/MAX\n Ga68[k,:,:] = Ga68[k,:,:]/MAX",
"_____no_output_____"
]
],
[
[
"## INPUT / OUTPUT ",
"_____no_output_____"
],
[
"4-D Array with shape [batch, height, width, channels]",
"_____no_output_____"
]
],
[
[
"inp_np = np.expand_dims(Ga68,axis=-1) \nout_np = np.expand_dims(F18,axis=-1)",
"_____no_output_____"
]
],
[
[
"## SPLIT DATA INTO TRAIN AND VALIDATION",
"_____no_output_____"
]
],
[
[
"x_train, x_val, y_train, y_val = sk.train_test_split(inp_np, out_np, test_size=0.3, shuffle=True)",
"_____no_output_____"
]
],
[
[
"## NUMPY TO TENSOR",
"_____no_output_____"
]
],
[
[
"# NN requires images with number of pixels which can be divided by 2 multiple times --> Changing from 154 to 160\nNx2=160\nNy2=160",
"_____no_output_____"
],
[
"x_train_tf = tf.convert_to_tensor(x_train, tf.float32)\nx_train_tf = tf.image.pad_to_bounding_box(x_train_tf,3,3,Nx2,Ny2)\n\nx_val_tf = tf.convert_to_tensor(x_val, tf.float32)\nx_val_tf = tf.image.pad_to_bounding_box(x_val_tf,3,3,Nx2,Ny2)\n\ny_train_tf = tf.convert_to_tensor(y_train, tf.float32)\ny_train_tf = tf.image.pad_to_bounding_box(y_train_tf,3,3,Nx2,Ny2)\n\ny_val_tf = tf.convert_to_tensor(y_val, tf.float32)\ny_val_tf = tf.image.pad_to_bounding_box(y_val_tf,3,3,Nx2,Ny2)",
"_____no_output_____"
]
],
[
[
"## SHOW EXAMPLE",
"_____no_output_____"
]
],
[
[
"k=54 # SLICE SELECTED\nimages = np.squeeze(np.concatenate((y_val_tf[k,:,:,:],x_val_tf[k,:,:,:]), axis=1))\n\nfig, ax = plt.subplots(figsize=(10,5))\nim = ax.imshow(images,cmap='hot')\n_ = fig.colorbar(im, ax=ax)\n_ = ax.set_xlabel('Sample images: F18 / Ga68 ', fontsize=24)",
"_____no_output_____"
]
],
[
[
"# U-NET",
"_____no_output_____"
]
],
[
[
"from keras_unet.models import custom_unet\nfrom keras_unet.utils import get_augmented",
"-----------------------------------------\nkeras-unet init: TF version is >= 2.0.0 - using `tf.keras` instead of `Keras`\n-----------------------------------------\n"
]
],
[
[
"### DATA AUGMENTATION",
"_____no_output_____"
]
],
[
[
"train_gen = get_augmented(x_train_tf, y_train_tf, batch_size=24,\n data_gen_args = dict(width_shift_range=0.3,height_shift_range=0.3,rotation_range=90.0,\n horizontal_flip=True,vertical_flip=True,fill_mode='nearest'))",
"_____no_output_____"
]
],
[
[
"### MODEL DEFINITION",
"_____no_output_____"
]
],
[
[
"model = custom_unet(\n input_shape=(Nx2, Ny2, x_train_tf.shape[3]),\n use_batch_norm=True,\n activation='swish', #SWISH PROVIDES BETTER RESULTS THAN RELU\n filters=64,\n num_layers=4,\n use_attention=True,\n dropout=0.2,\n output_activation='relu') #RELU IN THE OUTPUT (POSITIVE BUT NOT LIMITED TO [0..1])",
"_____no_output_____"
]
],
[
[
"### NEW OPTIMIZERS ",
"_____no_output_____"
]
],
[
[
"!pip install -q tfa-nightly\nimport tensorflow_addons as tfa\nopt = tfa.optimizers.RectifiedAdam(lr=1e-3)\nopt = tfa.optimizers.Lookahead(opt)\n\n#(Alternative option if the previous section does not work):\n#opt = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, amsgrad=False, name='Adam')",
"_____no_output_____"
],
[
"model.compile(optimizer=opt,loss='MeanAbsoluteError') #l1 NORM",
"_____no_output_____"
],
[
"history = model.fit(train_gen,steps_per_epoch=100, epochs=50, validation_data=(x_val_tf, y_val_tf)) ",
"Epoch 1/5\n240/240 [==============================] - 65s 201ms/step - loss: 0.0090 - val_loss: 0.0083\nEpoch 2/5\n240/240 [==============================] - 49s 203ms/step - loss: 0.0089 - val_loss: 0.0071\nEpoch 3/5\n240/240 [==============================] - 49s 205ms/step - loss: 0.0089 - val_loss: 0.0068\nEpoch 4/5\n240/240 [==============================] - 50s 206ms/step - loss: 0.0086 - val_loss: 0.0070\nEpoch 5/5\n240/240 [==============================] - 50s 207ms/step - loss: 0.0088 - val_loss: 0.0068\n"
]
],
[
[
"### DISPLAY OF RESULTS",
"_____no_output_____"
]
],
[
[
"img_index = 54\ntest = np.expand_dims(x_val_tf[img_index,:,:,:],axis=0)\nestim = model.predict(test)\nGa68_img = np.squeeze(test[:,:,:,0])\nestim_img = np.squeeze(estim[:,:,:,0])\nF18_img = np.squeeze(y_val_tf[img_index,:,:,:])\n\nplt.figure(figsize=(20, 10))\nplt.subplot(1,3,1)\nplt.imshow(Ga68_img, cmap=plt.cm.bone)\nplt.axis('off')\nplt.title('Ga68 (Input)')\n\nplt.subplot(1,3,2)\nplt.imshow(estim_img, cmap=plt.cm.bone)\nplt.axis('off')\nplt.title('Estimated: 68Ga with deepPRC')\n\nplt.subplot(1,3,3)\nplt.imshow(F18_img, cmap=plt.cm.bone)\nplt.axis('off')\nplt.title('F18 (Reference)')",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(20,5))\n\nloss = np.array(history.history['loss'])\nvar_loss = np.array(history.history['val_loss'])\nax.plot(20*np.log(1+loss), 'orange', label='Training Loss')\nax.plot(20*np.log(1+var_loss), 'green', label='Validation loss')\nax.set_ylim([0, 1])\nax.legend()\nfig.show()",
"_____no_output_____"
]
],
[
[
"## SAVE LOSS HISTORY",
"_____no_output_____"
]
],
[
[
"loss = np.array(history.history['loss'])\nvar_loss = np.array(history.history['val_loss'])\nloss_info = np.transpose(100*np.array([loss,var_loss]))\nnp.savetxt( \"LOSS.csv\", loss_info, fmt='%.3f', delimiter='\\t')",
"_____no_output_____"
]
],
[
[
"## SAVE MODEL",
"_____no_output_____"
]
],
[
[
"# Save the entire model as a HDF5 file.\nmodel.save('deepPRC.h5') ",
"_____no_output_____"
]
],
[
[
"## LOAD MODEL",
"_____no_output_____"
]
],
[
[
"new_model = tf.keras.models.load_model('deepPRC.h5',compile=False) # LOADING KERAS MODEL",
"_____no_output_____"
]
],
[
[
"## EXAMPLE OF APPLICATION TO A SPECIFIC VOLUME (TEST) We use the initial case (not used for training/validation) ",
"_____no_output_____"
]
],
[
[
"test_np = np.zeros([Nz0,Nx,Ny])\nmaximo = np.zeros([Nz0])\nfor k in range(Nz0): \n MAX = np.max(Ga68[k,:,:]) # Ga68 is the input --> Normalized to maximum = 1 each slice (both input and output)\n Ga68[k,:,:] = Ga68[k,:,:]/MAX\n maximo[k]=MAX #We keep the normalization values to restore them at the end\n\ntest_np = np.expand_dims(test_np,axis=-1) \ntest_tf = tf.convert_to_tensor(test_np, tf.float32)\ntest_tf = tf.image.pad_to_bounding_box(test_tf,3,3,Nx2,Ny2) #Padding to make the size easily divisible by 2\n#test_tf2 = 2.0*case_tf2-1.0",
"_____no_output_____"
],
[
"import time\nt0 = time.time()\nestim_img = np.zeros((Nz0,Nx2,Ny2))\nfor k in range(Nz0):\n test = np.expand_dims(test_tf[k,:,:,:],axis=0)\n estim = new_model.predict(test)\n estim_img[k,:,:] = np.squeeze(estim)*maximo[k]\n \nprint(\"Time required for the whole PRC of the Test Volume = \",time.time()-t0,\" seconds\") # TIME REQUIRED",
"Time required for the whole PRC of the Test Volume = 3.679273843765259 seconds\n"
],
[
"d = np.array(Ga68[0:Nz0,:,:],'float32')\nf=open(\"Image_Ga68.raw\",\"wb\")\nf.write(d)\nf.close()",
"_____no_output_____"
],
[
"d = np.array(F18[0:Nz0,:,:],'float32')\nf=open(\"Image_F18.raw\",\"wb\")\nf.write(d)\nf.close()",
"_____no_output_____"
],
[
"d = np.array(estim_img[0:Nz0,3:157,3:157],'float32')\nf=open(\"Image_Ga68_deepPRC.raw\",\"wb\")\nf.write(d)\nf.close()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
ece65e410d78adb5c7985992b9d5918575bb2961 | 11,170 | ipynb | Jupyter Notebook | Section 4/Review CoEPrA 2006.ipynb | TinasheS/python1 | 176c2edd401a4830fd777f60aaa59998044cbbb4 | [
"MIT"
] | 8 | 2018-03-13T22:47:54.000Z | 2022-02-27T13:32:07.000Z | Section 4/Review CoEPrA 2006.ipynb | TinasheS/python1 | 176c2edd401a4830fd777f60aaa59998044cbbb4 | [
"MIT"
] | 1 | 2018-07-19T08:54:20.000Z | 2018-07-19T08:54:20.000Z | Section 4/Review CoEPrA 2006.ipynb | TinasheS/python1 | 176c2edd401a4830fd777f60aaa59998044cbbb4 | [
"MIT"
] | 24 | 2018-10-27T02:34:39.000Z | 2021-10-02T16:56:00.000Z | 20.383212 | 100 | 0.515398 | [
[
[
"## Predicting molecules properties using biologial data\n\n### Import the CoEPrA.csv\n\nThe dataset is obtained from the [CoEPrA Repository](http://CoEPrA.org)",
"_____no_output_____"
]
],
[
[
"#Import the libraries\nimport numpy as np\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score",
"_____no_output_____"
],
[
"filename = \"CoEPrA.csv\"\nraw_data = open(filename, 'rt')\ndata = np.loadtxt(raw_data, delimiter=\",\")",
"_____no_output_____"
],
[
"data.shape",
"_____no_output_____"
],
[
"#We separate out the independent variable into X \n#and dependent variable into y\nX=data[:,0:5787]\ny=data[:,5787]",
"_____no_output_____"
],
[
"#We split the data into train and test using train_test_split\nX_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)",
"_____no_output_____"
],
[
"print(X_trn.shape)\nprint(y_trn.shape)\nprint(X_tst.shape)\nprint(y_tst.shape)",
"(71, 5787)\n(71,)\n(18, 5787)\n(18,)\n"
]
],
[
[
"### Linear Regression without Regularization",
"_____no_output_____"
]
],
[
[
"# Create linear regression object\nregr = linear_model.LinearRegression()\n# Train the model using the training sets\nregr.fit(X_trn, y_trn)",
"_____no_output_____"
],
[
"# Make predictions using the testing set\ny_pred = regr.predict(X_trn)",
"_____no_output_____"
],
[
"# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(y_trn, y_pred))",
"Mean squared error: 0.00\n"
]
],
[
[
"#### We get a zero training error",
"_____no_output_____"
]
],
[
[
"#K-Fold Cross validation \nscores = cross_val_score(regr, X_trn, y_trn, scoring='neg_mean_squared_error', cv=5)",
"_____no_output_____"
],
[
"print(np.mean(scores))",
"-1.2942806730857002e+17\n"
]
],
[
[
"#### We get a really high mean squared error",
"_____no_output_____"
]
],
[
[
"# Make predictions using the testing set\ny_pred_tst = regr.predict(X_tst)\n# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(y_tst, y_pred_tst))",
"Mean squared error: 115262556605687856.00\n"
]
],
[
[
"#### We get a really high test error",
"_____no_output_____"
],
[
"### L1 / Lasso Regularization ",
"_____no_output_____"
]
],
[
[
"regr = linear_model.Lasso(alpha=0.3, max_iter=1000000)\nregr.fit(X_trn, y_trn)",
"_____no_output_____"
]
],
[
[
"#### Checking the weights",
"_____no_output_____"
]
],
[
[
"print(regr.coef_)",
"[-0. 0. -0. ... -0. -0. 0.]\n"
]
],
[
[
"#### Many coffecients become zero",
"_____no_output_____"
]
],
[
[
"#Index of all non zero coffecients \nindex=np.nonzero(regr.coef_)\nprint(index[0])",
"[ 64 136 445 451 653 715 760 787 858 1236 1358 1422 1430 1732\n 1737 1874 1879 2065 2247 2374 2380 2581 2644 2689 2708 2890 3224 3351\n 3666 3931 3994 4002 4221 4303 4510 4573 4574 4637 4645 4819 4952 5153\n 5154 5280 5589 5595 5648 5732]\n"
],
[
"#New feature matrix with only selelcted features\nX_trn_filter=X_trn[:,index[0]]",
"_____no_output_____"
],
[
"#New shape\nX_trn_filter.shape",
"_____no_output_____"
],
[
"# Make predictions using the testing set\ny_pred = regr.predict(X_trn)",
"_____no_output_____"
],
[
"# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(y_trn, y_pred))",
"Mean squared error: 0.05\n"
],
[
"#K-Fold Cross validation \nscores = cross_val_score(regr, X_trn, y_trn, scoring='neg_mean_squared_error', cv=5)",
"_____no_output_____"
],
[
"print(np.mean(scores))",
"-1.1615211159922365\n"
],
[
"# Make predictions using the testing set\ny_pred_tst = regr.predict(X_tst)\n# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(y_tst, y_pred_tst))",
"Mean squared error: 0.69\n"
]
],
[
[
"#### Overfitting has reduced",
"_____no_output_____"
],
[
"### L2 Ridge Regularization",
"_____no_output_____"
]
],
[
[
"#Using the filtered features we obtainied from L1\nregr = linear_model.Ridge(alpha=0.8,max_iter=1000000)\nregr.fit(X_trn_filter, y_trn)\n# Make predictions using the testing set\ny_pred = regr.predict(X_trn_filter)",
"_____no_output_____"
],
[
"# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(y_trn, y_pred))",
"Mean squared error: 0.03\n"
],
[
"scores = cross_val_score(regr, X_trn_filter, y_trn, scoring='neg_mean_squared_error', cv=5)\nprint(np.mean(scores))",
"-1.2017669016778143\n"
]
],
[
[
"#### Cross validation values does not change much ",
"_____no_output_____"
]
],
[
[
"#Filtering the test features\nX_tst_filter=X_tst[:,index[0]]",
"_____no_output_____"
],
[
"# Make predictions using the testing set\ny_pred_tst = regr.predict(X_tst_filter)\n# The mean squared error\nprint(\"Mean squared error: %.2f\"\n % mean_squared_error(y_tst, y_pred_tst))",
"Mean squared error: 1.80\n"
]
]
] | [
"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"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece6650e019d9c2cb82253aa376d84d38024160a | 4,671 | ipynb | Jupyter Notebook | docs/notebooks/atomic/linux/defense_evasion/SDLIN-201110081941.ipynb | onesorzer0es/Security-Datasets | 6a0eec7d9a2ec6026c6ba239ad647c4f59d2a6ef | [
"MIT"
] | 294 | 2020-08-27T01:41:47.000Z | 2021-06-28T00:17:15.000Z | docs/notebooks/atomic/linux/defense_evasion/SDLIN-201110081941.ipynb | onesorzer0es/Security-Datasets | 6a0eec7d9a2ec6026c6ba239ad647c4f59d2a6ef | [
"MIT"
] | 18 | 2020-09-01T14:51:13.000Z | 2021-06-22T14:12:04.000Z | docs/notebooks/atomic/linux/defense_evasion/SDLIN-201110081941.ipynb | onesorzer0es/Security-Datasets | 6a0eec7d9a2ec6026c6ba239ad647c4f59d2a6ef | [
"MIT"
] | 48 | 2020-08-31T07:30:05.000Z | 2021-06-28T00:17:37.000Z | 23.953846 | 307 | 0.538857 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
ece666c1d2cb6b041896286218f4b86c1cdf7c25 | 205,477 | ipynb | Jupyter Notebook | Model backlog/Deep Learning/ResNet50/[101th] - Fine-tune - ResNet50 - Complete Adam2.ipynb | dimitreOliveira/iMet-Collection-2019-FGVC6 | 4f22485b9ec5ef3696d6532185a5ea90f9cf7489 | [
"MIT"
] | 1 | 2021-01-21T01:20:27.000Z | 2021-01-21T01:20:27.000Z | Model backlog/Deep Learning/ResNet50/[101th] - Fine-tune - ResNet50 - Complete Adam2.ipynb | dimitreOliveira/iMet-Collection-2019-FGVC6 | 4f22485b9ec5ef3696d6532185a5ea90f9cf7489 | [
"MIT"
] | null | null | null | Model backlog/Deep Learning/ResNet50/[101th] - Fine-tune - ResNet50 - Complete Adam2.ipynb | dimitreOliveira/iMet-Collection-2019-FGVC6 | 4f22485b9ec5ef3696d6532185a5ea90f9cf7489 | [
"MIT"
] | 1 | 2020-11-18T23:44:21.000Z | 2020-11-18T23:44:21.000Z | 124.682646 | 77,596 | 0.770982 | [
[
[
"import os\nimport cv2\nimport math\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, fbeta_score\nfrom keras import optimizers\nfrom keras import backend as K\nfrom keras.models import Sequential, Model\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler, EarlyStopping\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, Activation, BatchNormalization, GlobalAveragePooling2D, Input\n\n# Set seeds to make the experiment more reproducible.\nfrom tensorflow import set_random_seed\nfrom numpy.random import seed\nset_random_seed(0)\nseed(0)\n\n%matplotlib inline\nsns.set(style=\"whitegrid\")\nwarnings.filterwarnings(\"ignore\")",
"Using TensorFlow backend.\n"
],
[
"train = pd.read_csv('../input/imet-2019-fgvc6/train.csv')\nlabels = pd.read_csv('../input/imet-2019-fgvc6/labels.csv')\ntest = pd.read_csv('../input/imet-2019-fgvc6/sample_submission.csv')\n\ntrain[\"attribute_ids\"] = train[\"attribute_ids\"].apply(lambda x:x.split(\" \"))\ntrain[\"id\"] = train[\"id\"].apply(lambda x: x + \".png\")\ntest[\"id\"] = test[\"id\"].apply(lambda x: x + \".png\")\n\nprint('Number of train samples: ', train.shape[0])\nprint('Number of test samples: ', test.shape[0])\nprint('Number of labels: ', labels.shape[0])\ndisplay(train.head())\ndisplay(labels.head())",
"Number of train samples: 109237\nNumber of test samples: 7443\nNumber of labels: 1103\n"
]
],
[
[
"### Model parameters",
"_____no_output_____"
]
],
[
[
"# Model parameters\nBATCH_SIZE = 128\nEPOCHS = 30\nLEARNING_RATE = 0.0001\nHEIGHT = 64\nWIDTH = 64\nCANAL = 3\nN_CLASSES = labels.shape[0]\nES_PATIENCE = 5\nDECAY_DROP = 0.5\nDECAY_EPOCHS = 10\nclasses = list(map(str, range(N_CLASSES)))",
"_____no_output_____"
],
[
"def f2_score_thr(threshold=0.5):\n def f2_score(y_true, y_pred):\n beta = 2\n y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), threshold), K.floatx())\n\n true_positives = K.sum(K.clip(y_true * y_pred, 0, 1), axis=1)\n predicted_positives = K.sum(K.clip(y_pred, 0, 1), axis=1)\n possible_positives = K.sum(K.clip(y_true, 0, 1), axis=1)\n\n precision = true_positives / (predicted_positives + K.epsilon())\n recall = true_positives / (possible_positives + K.epsilon())\n\n return K.mean(((1+beta**2)*precision*recall) / ((beta**2)*precision+recall+K.epsilon()))\n return f2_score\n\n\ndef custom_f2(y_true, y_pred):\n beta = 2\n\n tp = np.sum((y_true == 1) & (y_pred == 1))\n tn = np.sum((y_true == 0) & (y_pred == 0))\n fp = np.sum((y_true == 0) & (y_pred == 1))\n fn = np.sum((y_true == 1) & (y_pred == 0))\n \n p = tp / (tp + fp + K.epsilon())\n r = tp / (tp + fn + K.epsilon())\n\n f2 = (1+beta**2)*p*r / (p*beta**2 + r + 1e-15)\n\n return f2\n\ndef step_decay(epoch):\n initial_lrate = LEARNING_RATE\n drop = DECAY_DROP\n epochs_drop = DECAY_EPOCHS\n lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))\n \n return lrate",
"_____no_output_____"
],
[
"train_datagen=ImageDataGenerator(rescale=1./255, validation_split=0.25)\n\ntrain_generator=train_datagen.flow_from_dataframe(\n dataframe=train,\n directory=\"../input/imet-2019-fgvc6/train\",\n x_col=\"id\",\n y_col=\"attribute_ids\",\n batch_size=BATCH_SIZE,\n shuffle=True,\n class_mode=\"categorical\",\n classes=classes,\n target_size=(HEIGHT, WIDTH),\n subset='training')\n\nvalid_generator=train_datagen.flow_from_dataframe(\n dataframe=train,\n directory=\"../input/imet-2019-fgvc6/train\",\n x_col=\"id\",\n y_col=\"attribute_ids\",\n batch_size=BATCH_SIZE,\n shuffle=True,\n class_mode=\"categorical\", \n classes=classes,\n target_size=(HEIGHT, WIDTH),\n subset='validation')\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_dataframe( \n dataframe=test,\n directory = \"../input/imet-2019-fgvc6/test\", \n x_col=\"id\",\n target_size=(HEIGHT, WIDTH),\n batch_size=1,\n shuffle=False,\n class_mode=None)",
"Found 81928 images belonging to 1103 classes.\nFound 27309 images belonging to 1103 classes.\nFound 7443 images.\n"
]
],
[
[
"### Model",
"_____no_output_____"
]
],
[
[
"def create_model(input_shape, n_out):\n input_tensor = Input(shape=input_shape)\n base_model = applications.ResNet50(weights=None, include_top=False,\n input_tensor=input_tensor)\n base_model.load_weights('../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5')\n\n x = GlobalAveragePooling2D()(base_model.output)\n x = Dropout(0.5)(x)\n x = Dense(1024, activation='relu')(x)\n x = Dropout(0.5)(x)\n final_output = Dense(n_out, activation='sigmoid', name='final_output')(x)\n model = Model(input_tensor, final_output)\n \n return model",
"_____no_output_____"
],
[
"# warm up model\n# first: train only the top layers (which were randomly initialized)\nmodel = create_model(input_shape=(HEIGHT, WIDTH, CANAL), n_out=N_CLASSES)\n\nfor layer in model.layers:\n layer.trainable = False\n\nfor i in range(-5,0):\n model.layers[i].trainable = True\n \noptimizer = optimizers.Adam(lr=LEARNING_RATE)\nmetrics = [\"accuracy\", \"categorical_accuracy\"]\nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=ES_PATIENCE)\ncallbacks = [es]\nmodel.compile(optimizer=optimizer, loss=\"binary_crossentropy\", metrics=metrics)\nmodel.summary()",
"WARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\nWARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 64, 64, 3) 0 \n__________________________________________________________________________________________________\nconv1_pad (ZeroPadding2D) (None, 70, 70, 3) 0 input_1[0][0] \n__________________________________________________________________________________________________\nconv1 (Conv2D) (None, 32, 32, 64) 9472 conv1_pad[0][0] \n__________________________________________________________________________________________________\nbn_conv1 (BatchNormalization) (None, 32, 32, 64) 256 conv1[0][0] \n__________________________________________________________________________________________________\nactivation_1 (Activation) (None, 32, 32, 64) 0 bn_conv1[0][0] \n__________________________________________________________________________________________________\npool1_pad (ZeroPadding2D) (None, 34, 34, 64) 0 activation_1[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 16, 16, 64) 0 pool1_pad[0][0] \n__________________________________________________________________________________________________\nres2a_branch2a (Conv2D) (None, 16, 16, 64) 4160 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2a (BatchNormalizati (None, 16, 16, 64) 256 res2a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_2 (Activation) (None, 16, 16, 64) 0 bn2a_branch2a[0][0] \n__________________________________________________________________________________________________\nres2a_branch2b (Conv2D) (None, 16, 16, 64) 36928 activation_2[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2b (BatchNormalizati (None, 16, 16, 64) 256 res2a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_3 (Activation) (None, 16, 16, 64) 0 bn2a_branch2b[0][0] \n__________________________________________________________________________________________________\nres2a_branch2c (Conv2D) (None, 16, 16, 256) 16640 activation_3[0][0] \n__________________________________________________________________________________________________\nres2a_branch1 (Conv2D) (None, 16, 16, 256) 16640 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2c (BatchNormalizati (None, 16, 16, 256) 1024 res2a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn2a_branch1 (BatchNormalizatio (None, 16, 16, 256) 1024 res2a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 16, 16, 256) 0 bn2a_branch2c[0][0] \n bn2a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_4 (Activation) (None, 16, 16, 256) 0 add_1[0][0] \n__________________________________________________________________________________________________\nres2b_branch2a (Conv2D) (None, 16, 16, 64) 16448 activation_4[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2a (BatchNormalizati (None, 16, 16, 64) 256 res2b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_5 (Activation) (None, 16, 16, 64) 0 bn2b_branch2a[0][0] \n__________________________________________________________________________________________________\nres2b_branch2b (Conv2D) (None, 16, 16, 64) 36928 activation_5[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2b (BatchNormalizati (None, 16, 16, 64) 256 res2b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_6 (Activation) (None, 16, 16, 64) 0 bn2b_branch2b[0][0] \n__________________________________________________________________________________________________\nres2b_branch2c (Conv2D) (None, 16, 16, 256) 16640 activation_6[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2c (BatchNormalizati (None, 16, 16, 256) 1024 res2b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 16, 16, 256) 0 bn2b_branch2c[0][0] \n activation_4[0][0] \n__________________________________________________________________________________________________\nactivation_7 (Activation) (None, 16, 16, 256) 0 add_2[0][0] \n__________________________________________________________________________________________________\nres2c_branch2a (Conv2D) (None, 16, 16, 64) 16448 activation_7[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2a (BatchNormalizati (None, 16, 16, 64) 256 res2c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_8 (Activation) (None, 16, 16, 64) 0 bn2c_branch2a[0][0] \n__________________________________________________________________________________________________\nres2c_branch2b (Conv2D) (None, 16, 16, 64) 36928 activation_8[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2b (BatchNormalizati (None, 16, 16, 64) 256 res2c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 16, 16, 64) 0 bn2c_branch2b[0][0] \n__________________________________________________________________________________________________\nres2c_branch2c (Conv2D) (None, 16, 16, 256) 16640 activation_9[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2c (BatchNormalizati (None, 16, 16, 256) 1024 res2c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_3 (Add) (None, 16, 16, 256) 0 bn2c_branch2c[0][0] \n activation_7[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 16, 16, 256) 0 add_3[0][0] \n__________________________________________________________________________________________________\nres3a_branch2a (Conv2D) (None, 8, 8, 128) 32896 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 8, 8, 128) 0 bn3a_branch2a[0][0] \n__________________________________________________________________________________________________\nres3a_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_11[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 8, 8, 128) 0 bn3a_branch2b[0][0] \n__________________________________________________________________________________________________\nres3a_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_12[0][0] \n__________________________________________________________________________________________________\nres3a_branch1 (Conv2D) (None, 8, 8, 512) 131584 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn3a_branch1 (BatchNormalizatio (None, 8, 8, 512) 2048 res3a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_4 (Add) (None, 8, 8, 512) 0 bn3a_branch2c[0][0] \n bn3a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 8, 8, 512) 0 add_4[0][0] \n__________________________________________________________________________________________________\nres3b_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_13[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 8, 8, 128) 0 bn3b_branch2a[0][0] \n__________________________________________________________________________________________________\nres3b_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_14[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_15 (Activation) (None, 8, 8, 128) 0 bn3b_branch2b[0][0] \n__________________________________________________________________________________________________\nres3b_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_15[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_5 (Add) (None, 8, 8, 512) 0 bn3b_branch2c[0][0] \n activation_13[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 8, 8, 512) 0 add_5[0][0] \n__________________________________________________________________________________________________\nres3c_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_16[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_17 (Activation) (None, 8, 8, 128) 0 bn3c_branch2a[0][0] \n__________________________________________________________________________________________________\nres3c_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_17[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_18 (Activation) (None, 8, 8, 128) 0 bn3c_branch2b[0][0] \n__________________________________________________________________________________________________\nres3c_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_18[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_6 (Add) (None, 8, 8, 512) 0 bn3c_branch2c[0][0] \n activation_16[0][0] \n__________________________________________________________________________________________________\nactivation_19 (Activation) (None, 8, 8, 512) 0 add_6[0][0] \n__________________________________________________________________________________________________\nres3d_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_19[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_20 (Activation) (None, 8, 8, 128) 0 bn3d_branch2a[0][0] \n__________________________________________________________________________________________________\nres3d_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_20[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_21 (Activation) (None, 8, 8, 128) 0 bn3d_branch2b[0][0] \n__________________________________________________________________________________________________\nres3d_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_21[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_7 (Add) (None, 8, 8, 512) 0 bn3d_branch2c[0][0] \n activation_19[0][0] \n__________________________________________________________________________________________________\nactivation_22 (Activation) (None, 8, 8, 512) 0 add_7[0][0] \n__________________________________________________________________________________________________\nres4a_branch2a (Conv2D) (None, 4, 4, 256) 131328 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_23 (Activation) (None, 4, 4, 256) 0 bn4a_branch2a[0][0] \n__________________________________________________________________________________________________\nres4a_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_23[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_24 (Activation) (None, 4, 4, 256) 0 bn4a_branch2b[0][0] \n__________________________________________________________________________________________________\nres4a_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_24[0][0] \n__________________________________________________________________________________________________\nres4a_branch1 (Conv2D) (None, 4, 4, 1024) 525312 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn4a_branch1 (BatchNormalizatio (None, 4, 4, 1024) 4096 res4a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_8 (Add) (None, 4, 4, 1024) 0 bn4a_branch2c[0][0] \n bn4a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_25 (Activation) (None, 4, 4, 1024) 0 add_8[0][0] \n__________________________________________________________________________________________________\nres4b_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_25[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_26 (Activation) (None, 4, 4, 256) 0 bn4b_branch2a[0][0] \n__________________________________________________________________________________________________\nres4b_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_26[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_27 (Activation) (None, 4, 4, 256) 0 bn4b_branch2b[0][0] \n__________________________________________________________________________________________________\nres4b_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_27[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_9 (Add) (None, 4, 4, 1024) 0 bn4b_branch2c[0][0] \n activation_25[0][0] \n__________________________________________________________________________________________________\nactivation_28 (Activation) (None, 4, 4, 1024) 0 add_9[0][0] \n__________________________________________________________________________________________________\nres4c_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_28[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_29 (Activation) (None, 4, 4, 256) 0 bn4c_branch2a[0][0] \n__________________________________________________________________________________________________\nres4c_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_29[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_30 (Activation) (None, 4, 4, 256) 0 bn4c_branch2b[0][0] \n__________________________________________________________________________________________________\nres4c_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_30[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_10 (Add) (None, 4, 4, 1024) 0 bn4c_branch2c[0][0] \n activation_28[0][0] \n__________________________________________________________________________________________________\nactivation_31 (Activation) (None, 4, 4, 1024) 0 add_10[0][0] \n__________________________________________________________________________________________________\nres4d_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_31[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_32 (Activation) (None, 4, 4, 256) 0 bn4d_branch2a[0][0] \n__________________________________________________________________________________________________\nres4d_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_32[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_33 (Activation) (None, 4, 4, 256) 0 bn4d_branch2b[0][0] \n__________________________________________________________________________________________________\nres4d_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_33[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_11 (Add) (None, 4, 4, 1024) 0 bn4d_branch2c[0][0] \n activation_31[0][0] \n__________________________________________________________________________________________________\nactivation_34 (Activation) (None, 4, 4, 1024) 0 add_11[0][0] \n__________________________________________________________________________________________________\nres4e_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_34[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4e_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_35 (Activation) (None, 4, 4, 256) 0 bn4e_branch2a[0][0] \n__________________________________________________________________________________________________\nres4e_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_35[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4e_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_36 (Activation) (None, 4, 4, 256) 0 bn4e_branch2b[0][0] \n__________________________________________________________________________________________________\nres4e_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_36[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4e_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_12 (Add) (None, 4, 4, 1024) 0 bn4e_branch2c[0][0] \n activation_34[0][0] \n__________________________________________________________________________________________________\nactivation_37 (Activation) (None, 4, 4, 1024) 0 add_12[0][0] \n__________________________________________________________________________________________________\nres4f_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_37[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4f_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_38 (Activation) (None, 4, 4, 256) 0 bn4f_branch2a[0][0] \n__________________________________________________________________________________________________\nres4f_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_38[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4f_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_39 (Activation) (None, 4, 4, 256) 0 bn4f_branch2b[0][0] \n__________________________________________________________________________________________________\nres4f_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_39[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4f_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_13 (Add) (None, 4, 4, 1024) 0 bn4f_branch2c[0][0] \n activation_37[0][0] \n__________________________________________________________________________________________________\nactivation_40 (Activation) (None, 4, 4, 1024) 0 add_13[0][0] \n__________________________________________________________________________________________________\nres5a_branch2a (Conv2D) (None, 2, 2, 512) 524800 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2a (BatchNormalizati (None, 2, 2, 512) 2048 res5a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_41 (Activation) (None, 2, 2, 512) 0 bn5a_branch2a[0][0] \n__________________________________________________________________________________________________\nres5a_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_41[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2b (BatchNormalizati (None, 2, 2, 512) 2048 res5a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_42 (Activation) (None, 2, 2, 512) 0 bn5a_branch2b[0][0] \n__________________________________________________________________________________________________\nres5a_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_42[0][0] \n__________________________________________________________________________________________________\nres5a_branch1 (Conv2D) (None, 2, 2, 2048) 2099200 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2c (BatchNormalizati (None, 2, 2, 2048) 8192 res5a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn5a_branch1 (BatchNormalizatio (None, 2, 2, 2048) 8192 res5a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_14 (Add) (None, 2, 2, 2048) 0 bn5a_branch2c[0][0] \n bn5a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_43 (Activation) (None, 2, 2, 2048) 0 add_14[0][0] \n__________________________________________________________________________________________________\nres5b_branch2a (Conv2D) (None, 2, 2, 512) 1049088 activation_43[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2a (BatchNormalizati (None, 2, 2, 512) 2048 res5b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_44 (Activation) (None, 2, 2, 512) 0 bn5b_branch2a[0][0] \n__________________________________________________________________________________________________\nres5b_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_44[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2b (BatchNormalizati (None, 2, 2, 512) 2048 res5b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_45 (Activation) (None, 2, 2, 512) 0 bn5b_branch2b[0][0] \n__________________________________________________________________________________________________\nres5b_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_45[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2c (BatchNormalizati (None, 2, 2, 2048) 8192 res5b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_15 (Add) (None, 2, 2, 2048) 0 bn5b_branch2c[0][0] \n activation_43[0][0] \n__________________________________________________________________________________________________\nactivation_46 (Activation) (None, 2, 2, 2048) 0 add_15[0][0] \n__________________________________________________________________________________________________\nres5c_branch2a (Conv2D) (None, 2, 2, 512) 1049088 activation_46[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2a (BatchNormalizati (None, 2, 2, 512) 2048 res5c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_47 (Activation) (None, 2, 2, 512) 0 bn5c_branch2a[0][0] \n__________________________________________________________________________________________________\nres5c_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_47[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2b (BatchNormalizati (None, 2, 2, 512) 2048 res5c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_48 (Activation) (None, 2, 2, 512) 0 bn5c_branch2b[0][0] \n__________________________________________________________________________________________________\nres5c_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_48[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2c (BatchNormalizati (None, 2, 2, 2048) 8192 res5c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_16 (Add) (None, 2, 2, 2048) 0 bn5c_branch2c[0][0] \n activation_46[0][0] \n__________________________________________________________________________________________________\nactivation_49 (Activation) (None, 2, 2, 2048) 0 add_16[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 2048) 0 activation_49[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 2048) 0 global_average_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 1024) 2098176 dropout_1[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 1024) 0 dense_1[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1103) 1130575 dropout_2[0][0] \n==================================================================================================\nTotal params: 26,816,463\nTrainable params: 3,228,751\nNon-trainable params: 23,587,712\n__________________________________________________________________________________________________\n"
]
],
[
[
"#### Train top layers",
"_____no_output_____"
]
],
[
[
"STEP_SIZE_TRAIN = train_generator.n//train_generator.batch_size\nSTEP_SIZE_VALID = valid_generator.n//valid_generator.batch_size\nhistory = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=EPOCHS,\n callbacks=callbacks,\n verbose=2,\n max_queue_size=16, workers=3, use_multiprocessing=True)",
"WARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nEpoch 1/30\n - 485s - loss: 0.0559 - acc: 0.9826 - categorical_accuracy: 0.0365 - val_loss: 0.0769 - val_acc: 0.9971 - val_categorical_accuracy: 0.0102\nEpoch 2/30\n - 472s - loss: 0.0196 - acc: 0.9968 - categorical_accuracy: 0.0673 - val_loss: 0.0280 - val_acc: 0.9971 - val_categorical_accuracy: 0.0101\nEpoch 3/30\n - 469s - loss: 0.0171 - acc: 0.9970 - categorical_accuracy: 0.0823 - val_loss: 0.0175 - val_acc: 0.9971 - val_categorical_accuracy: 0.0101\nEpoch 4/30\n - 451s - loss: 0.0158 - acc: 0.9971 - categorical_accuracy: 0.0939 - val_loss: 0.0156 - val_acc: 0.9971 - val_categorical_accuracy: 0.0086\nEpoch 5/30\n - 454s - loss: 0.0150 - acc: 0.9971 - categorical_accuracy: 0.1022 - val_loss: 0.0153 - val_acc: 0.9971 - val_categorical_accuracy: 0.0103\nEpoch 6/30\n - 457s - loss: 0.0146 - acc: 0.9971 - categorical_accuracy: 0.1047 - val_loss: 0.0155 - val_acc: 0.9971 - val_categorical_accuracy: 0.0116\nEpoch 7/30\n - 448s - loss: 0.0140 - acc: 0.9972 - categorical_accuracy: 0.1114 - val_loss: 0.0155 - val_acc: 0.9971 - val_categorical_accuracy: 0.0105\nEpoch 8/30\n - 458s - loss: 0.0138 - acc: 0.9972 - categorical_accuracy: 0.1147 - val_loss: 0.0155 - val_acc: 0.9972 - val_categorical_accuracy: 0.0101\nEpoch 9/30\n - 465s - loss: 0.0135 - acc: 0.9972 - categorical_accuracy: 0.1166 - val_loss: 0.0156 - val_acc: 0.9971 - val_categorical_accuracy: 0.0701\nEpoch 10/30\n - 456s - loss: 0.0131 - acc: 0.9972 - categorical_accuracy: 0.1181 - val_loss: 0.0155 - val_acc: 0.9971 - val_categorical_accuracy: 0.0099\nEpoch 00010: early stopping\n"
]
],
[
[
"#### Fine-tune the complete model",
"_____no_output_____"
]
],
[
[
"for layer in model.layers:\n layer.trainable = True\n\nmetrics = [\"accuracy\", \"categorical_accuracy\"]\nlrate = LearningRateScheduler(step_decay)\nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=(ES_PATIENCE))\ncallbacks = [es, lrate]\noptimizer = optimizers.Adam(lr=0.0001)\nmodel.compile(optimizer=optimizer, loss=\"binary_crossentropy\", metrics=metrics)\nmodel.summary()",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 64, 64, 3) 0 \n__________________________________________________________________________________________________\nconv1_pad (ZeroPadding2D) (None, 70, 70, 3) 0 input_1[0][0] \n__________________________________________________________________________________________________\nconv1 (Conv2D) (None, 32, 32, 64) 9472 conv1_pad[0][0] \n__________________________________________________________________________________________________\nbn_conv1 (BatchNormalization) (None, 32, 32, 64) 256 conv1[0][0] \n__________________________________________________________________________________________________\nactivation_1 (Activation) (None, 32, 32, 64) 0 bn_conv1[0][0] \n__________________________________________________________________________________________________\npool1_pad (ZeroPadding2D) (None, 34, 34, 64) 0 activation_1[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 16, 16, 64) 0 pool1_pad[0][0] \n__________________________________________________________________________________________________\nres2a_branch2a (Conv2D) (None, 16, 16, 64) 4160 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2a (BatchNormalizati (None, 16, 16, 64) 256 res2a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_2 (Activation) (None, 16, 16, 64) 0 bn2a_branch2a[0][0] \n__________________________________________________________________________________________________\nres2a_branch2b (Conv2D) (None, 16, 16, 64) 36928 activation_2[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2b (BatchNormalizati (None, 16, 16, 64) 256 res2a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_3 (Activation) (None, 16, 16, 64) 0 bn2a_branch2b[0][0] \n__________________________________________________________________________________________________\nres2a_branch2c (Conv2D) (None, 16, 16, 256) 16640 activation_3[0][0] \n__________________________________________________________________________________________________\nres2a_branch1 (Conv2D) (None, 16, 16, 256) 16640 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbn2a_branch2c (BatchNormalizati (None, 16, 16, 256) 1024 res2a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn2a_branch1 (BatchNormalizatio (None, 16, 16, 256) 1024 res2a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 16, 16, 256) 0 bn2a_branch2c[0][0] \n bn2a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_4 (Activation) (None, 16, 16, 256) 0 add_1[0][0] \n__________________________________________________________________________________________________\nres2b_branch2a (Conv2D) (None, 16, 16, 64) 16448 activation_4[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2a (BatchNormalizati (None, 16, 16, 64) 256 res2b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_5 (Activation) (None, 16, 16, 64) 0 bn2b_branch2a[0][0] \n__________________________________________________________________________________________________\nres2b_branch2b (Conv2D) (None, 16, 16, 64) 36928 activation_5[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2b (BatchNormalizati (None, 16, 16, 64) 256 res2b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_6 (Activation) (None, 16, 16, 64) 0 bn2b_branch2b[0][0] \n__________________________________________________________________________________________________\nres2b_branch2c (Conv2D) (None, 16, 16, 256) 16640 activation_6[0][0] \n__________________________________________________________________________________________________\nbn2b_branch2c (BatchNormalizati (None, 16, 16, 256) 1024 res2b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_2 (Add) (None, 16, 16, 256) 0 bn2b_branch2c[0][0] \n activation_4[0][0] \n__________________________________________________________________________________________________\nactivation_7 (Activation) (None, 16, 16, 256) 0 add_2[0][0] \n__________________________________________________________________________________________________\nres2c_branch2a (Conv2D) (None, 16, 16, 64) 16448 activation_7[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2a (BatchNormalizati (None, 16, 16, 64) 256 res2c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_8 (Activation) (None, 16, 16, 64) 0 bn2c_branch2a[0][0] \n__________________________________________________________________________________________________\nres2c_branch2b (Conv2D) (None, 16, 16, 64) 36928 activation_8[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2b (BatchNormalizati (None, 16, 16, 64) 256 res2c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 16, 16, 64) 0 bn2c_branch2b[0][0] \n__________________________________________________________________________________________________\nres2c_branch2c (Conv2D) (None, 16, 16, 256) 16640 activation_9[0][0] \n__________________________________________________________________________________________________\nbn2c_branch2c (BatchNormalizati (None, 16, 16, 256) 1024 res2c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_3 (Add) (None, 16, 16, 256) 0 bn2c_branch2c[0][0] \n activation_7[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 16, 16, 256) 0 add_3[0][0] \n__________________________________________________________________________________________________\nres3a_branch2a (Conv2D) (None, 8, 8, 128) 32896 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 8, 8, 128) 0 bn3a_branch2a[0][0] \n__________________________________________________________________________________________________\nres3a_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_11[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 8, 8, 128) 0 bn3a_branch2b[0][0] \n__________________________________________________________________________________________________\nres3a_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_12[0][0] \n__________________________________________________________________________________________________\nres3a_branch1 (Conv2D) (None, 8, 8, 512) 131584 activation_10[0][0] \n__________________________________________________________________________________________________\nbn3a_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn3a_branch1 (BatchNormalizatio (None, 8, 8, 512) 2048 res3a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_4 (Add) (None, 8, 8, 512) 0 bn3a_branch2c[0][0] \n bn3a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 8, 8, 512) 0 add_4[0][0] \n__________________________________________________________________________________________________\nres3b_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_13[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 8, 8, 128) 0 bn3b_branch2a[0][0] \n__________________________________________________________________________________________________\nres3b_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_14[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_15 (Activation) (None, 8, 8, 128) 0 bn3b_branch2b[0][0] \n__________________________________________________________________________________________________\nres3b_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_15[0][0] \n__________________________________________________________________________________________________\nbn3b_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_5 (Add) (None, 8, 8, 512) 0 bn3b_branch2c[0][0] \n activation_13[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 8, 8, 512) 0 add_5[0][0] \n__________________________________________________________________________________________________\nres3c_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_16[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_17 (Activation) (None, 8, 8, 128) 0 bn3c_branch2a[0][0] \n__________________________________________________________________________________________________\nres3c_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_17[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_18 (Activation) (None, 8, 8, 128) 0 bn3c_branch2b[0][0] \n__________________________________________________________________________________________________\nres3c_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_18[0][0] \n__________________________________________________________________________________________________\nbn3c_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_6 (Add) (None, 8, 8, 512) 0 bn3c_branch2c[0][0] \n activation_16[0][0] \n__________________________________________________________________________________________________\nactivation_19 (Activation) (None, 8, 8, 512) 0 add_6[0][0] \n__________________________________________________________________________________________________\nres3d_branch2a (Conv2D) (None, 8, 8, 128) 65664 activation_19[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2a (BatchNormalizati (None, 8, 8, 128) 512 res3d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_20 (Activation) (None, 8, 8, 128) 0 bn3d_branch2a[0][0] \n__________________________________________________________________________________________________\nres3d_branch2b (Conv2D) (None, 8, 8, 128) 147584 activation_20[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2b (BatchNormalizati (None, 8, 8, 128) 512 res3d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_21 (Activation) (None, 8, 8, 128) 0 bn3d_branch2b[0][0] \n__________________________________________________________________________________________________\nres3d_branch2c (Conv2D) (None, 8, 8, 512) 66048 activation_21[0][0] \n__________________________________________________________________________________________________\nbn3d_branch2c (BatchNormalizati (None, 8, 8, 512) 2048 res3d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_7 (Add) (None, 8, 8, 512) 0 bn3d_branch2c[0][0] \n activation_19[0][0] \n__________________________________________________________________________________________________\nactivation_22 (Activation) (None, 8, 8, 512) 0 add_7[0][0] \n__________________________________________________________________________________________________\nres4a_branch2a (Conv2D) (None, 4, 4, 256) 131328 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_23 (Activation) (None, 4, 4, 256) 0 bn4a_branch2a[0][0] \n__________________________________________________________________________________________________\nres4a_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_23[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_24 (Activation) (None, 4, 4, 256) 0 bn4a_branch2b[0][0] \n__________________________________________________________________________________________________\nres4a_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_24[0][0] \n__________________________________________________________________________________________________\nres4a_branch1 (Conv2D) (None, 4, 4, 1024) 525312 activation_22[0][0] \n__________________________________________________________________________________________________\nbn4a_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn4a_branch1 (BatchNormalizatio (None, 4, 4, 1024) 4096 res4a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_8 (Add) (None, 4, 4, 1024) 0 bn4a_branch2c[0][0] \n bn4a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_25 (Activation) (None, 4, 4, 1024) 0 add_8[0][0] \n__________________________________________________________________________________________________\nres4b_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_25[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_26 (Activation) (None, 4, 4, 256) 0 bn4b_branch2a[0][0] \n__________________________________________________________________________________________________\nres4b_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_26[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_27 (Activation) (None, 4, 4, 256) 0 bn4b_branch2b[0][0] \n__________________________________________________________________________________________________\nres4b_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_27[0][0] \n__________________________________________________________________________________________________\nbn4b_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_9 (Add) (None, 4, 4, 1024) 0 bn4b_branch2c[0][0] \n activation_25[0][0] \n__________________________________________________________________________________________________\nactivation_28 (Activation) (None, 4, 4, 1024) 0 add_9[0][0] \n__________________________________________________________________________________________________\nres4c_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_28[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_29 (Activation) (None, 4, 4, 256) 0 bn4c_branch2a[0][0] \n__________________________________________________________________________________________________\nres4c_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_29[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_30 (Activation) (None, 4, 4, 256) 0 bn4c_branch2b[0][0] \n__________________________________________________________________________________________________\nres4c_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_30[0][0] \n__________________________________________________________________________________________________\nbn4c_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_10 (Add) (None, 4, 4, 1024) 0 bn4c_branch2c[0][0] \n activation_28[0][0] \n__________________________________________________________________________________________________\nactivation_31 (Activation) (None, 4, 4, 1024) 0 add_10[0][0] \n__________________________________________________________________________________________________\nres4d_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_31[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4d_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_32 (Activation) (None, 4, 4, 256) 0 bn4d_branch2a[0][0] \n__________________________________________________________________________________________________\nres4d_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_32[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4d_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_33 (Activation) (None, 4, 4, 256) 0 bn4d_branch2b[0][0] \n__________________________________________________________________________________________________\nres4d_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_33[0][0] \n__________________________________________________________________________________________________\nbn4d_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4d_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_11 (Add) (None, 4, 4, 1024) 0 bn4d_branch2c[0][0] \n activation_31[0][0] \n__________________________________________________________________________________________________\nactivation_34 (Activation) (None, 4, 4, 1024) 0 add_11[0][0] \n__________________________________________________________________________________________________\nres4e_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_34[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4e_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_35 (Activation) (None, 4, 4, 256) 0 bn4e_branch2a[0][0] \n__________________________________________________________________________________________________\nres4e_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_35[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4e_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_36 (Activation) (None, 4, 4, 256) 0 bn4e_branch2b[0][0] \n__________________________________________________________________________________________________\nres4e_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_36[0][0] \n__________________________________________________________________________________________________\nbn4e_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4e_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_12 (Add) (None, 4, 4, 1024) 0 bn4e_branch2c[0][0] \n activation_34[0][0] \n__________________________________________________________________________________________________\nactivation_37 (Activation) (None, 4, 4, 1024) 0 add_12[0][0] \n__________________________________________________________________________________________________\nres4f_branch2a (Conv2D) (None, 4, 4, 256) 262400 activation_37[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2a (BatchNormalizati (None, 4, 4, 256) 1024 res4f_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_38 (Activation) (None, 4, 4, 256) 0 bn4f_branch2a[0][0] \n__________________________________________________________________________________________________\nres4f_branch2b (Conv2D) (None, 4, 4, 256) 590080 activation_38[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2b (BatchNormalizati (None, 4, 4, 256) 1024 res4f_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_39 (Activation) (None, 4, 4, 256) 0 bn4f_branch2b[0][0] \n__________________________________________________________________________________________________\nres4f_branch2c (Conv2D) (None, 4, 4, 1024) 263168 activation_39[0][0] \n__________________________________________________________________________________________________\nbn4f_branch2c (BatchNormalizati (None, 4, 4, 1024) 4096 res4f_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_13 (Add) (None, 4, 4, 1024) 0 bn4f_branch2c[0][0] \n activation_37[0][0] \n__________________________________________________________________________________________________\nactivation_40 (Activation) (None, 4, 4, 1024) 0 add_13[0][0] \n__________________________________________________________________________________________________\nres5a_branch2a (Conv2D) (None, 2, 2, 512) 524800 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2a (BatchNormalizati (None, 2, 2, 512) 2048 res5a_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_41 (Activation) (None, 2, 2, 512) 0 bn5a_branch2a[0][0] \n__________________________________________________________________________________________________\nres5a_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_41[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2b (BatchNormalizati (None, 2, 2, 512) 2048 res5a_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_42 (Activation) (None, 2, 2, 512) 0 bn5a_branch2b[0][0] \n__________________________________________________________________________________________________\nres5a_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_42[0][0] \n__________________________________________________________________________________________________\nres5a_branch1 (Conv2D) (None, 2, 2, 2048) 2099200 activation_40[0][0] \n__________________________________________________________________________________________________\nbn5a_branch2c (BatchNormalizati (None, 2, 2, 2048) 8192 res5a_branch2c[0][0] \n__________________________________________________________________________________________________\nbn5a_branch1 (BatchNormalizatio (None, 2, 2, 2048) 8192 res5a_branch1[0][0] \n__________________________________________________________________________________________________\nadd_14 (Add) (None, 2, 2, 2048) 0 bn5a_branch2c[0][0] \n bn5a_branch1[0][0] \n__________________________________________________________________________________________________\nactivation_43 (Activation) (None, 2, 2, 2048) 0 add_14[0][0] \n__________________________________________________________________________________________________\nres5b_branch2a (Conv2D) (None, 2, 2, 512) 1049088 activation_43[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2a (BatchNormalizati (None, 2, 2, 512) 2048 res5b_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_44 (Activation) (None, 2, 2, 512) 0 bn5b_branch2a[0][0] \n__________________________________________________________________________________________________\nres5b_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_44[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2b (BatchNormalizati (None, 2, 2, 512) 2048 res5b_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_45 (Activation) (None, 2, 2, 512) 0 bn5b_branch2b[0][0] \n__________________________________________________________________________________________________\nres5b_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_45[0][0] \n__________________________________________________________________________________________________\nbn5b_branch2c (BatchNormalizati (None, 2, 2, 2048) 8192 res5b_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_15 (Add) (None, 2, 2, 2048) 0 bn5b_branch2c[0][0] \n activation_43[0][0] \n__________________________________________________________________________________________________\nactivation_46 (Activation) (None, 2, 2, 2048) 0 add_15[0][0] \n__________________________________________________________________________________________________\nres5c_branch2a (Conv2D) (None, 2, 2, 512) 1049088 activation_46[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2a (BatchNormalizati (None, 2, 2, 512) 2048 res5c_branch2a[0][0] \n__________________________________________________________________________________________________\nactivation_47 (Activation) (None, 2, 2, 512) 0 bn5c_branch2a[0][0] \n__________________________________________________________________________________________________\nres5c_branch2b (Conv2D) (None, 2, 2, 512) 2359808 activation_47[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2b (BatchNormalizati (None, 2, 2, 512) 2048 res5c_branch2b[0][0] \n__________________________________________________________________________________________________\nactivation_48 (Activation) (None, 2, 2, 512) 0 bn5c_branch2b[0][0] \n__________________________________________________________________________________________________\nres5c_branch2c (Conv2D) (None, 2, 2, 2048) 1050624 activation_48[0][0] \n__________________________________________________________________________________________________\nbn5c_branch2c (BatchNormalizati (None, 2, 2, 2048) 8192 res5c_branch2c[0][0] \n__________________________________________________________________________________________________\nadd_16 (Add) (None, 2, 2, 2048) 0 bn5c_branch2c[0][0] \n activation_46[0][0] \n__________________________________________________________________________________________________\nactivation_49 (Activation) (None, 2, 2, 2048) 0 add_16[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 2048) 0 activation_49[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 2048) 0 global_average_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 1024) 2098176 dropout_1[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 1024) 0 dense_1[0][0] \n__________________________________________________________________________________________________\nfinal_output (Dense) (None, 1103) 1130575 dropout_2[0][0] \n==================================================================================================\nTotal params: 26,816,463\nTrainable params: 26,763,343\nNon-trainable params: 53,120\n__________________________________________________________________________________________________\n"
],
[
"STEP_SIZE_TRAIN = train_generator.n//train_generator.batch_size\nSTEP_SIZE_VALID = valid_generator.n//valid_generator.batch_size\n\nhistory = model.fit_generator(generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=EPOCHS,\n callbacks=callbacks,\n verbose=2,\n max_queue_size=16, workers=3, use_multiprocessing=True)",
"Epoch 1/30\n - 516s - loss: 0.0120 - acc: 0.9973 - categorical_accuracy: 0.1489 - val_loss: 0.0120 - val_acc: 0.9973 - val_categorical_accuracy: 0.1729\nEpoch 2/30\n - 494s - loss: 0.0113 - acc: 0.9973 - categorical_accuracy: 0.1736 - val_loss: 0.0118 - val_acc: 0.9973 - val_categorical_accuracy: 0.1718\nEpoch 3/30\n - 493s - loss: 0.0109 - acc: 0.9974 - categorical_accuracy: 0.1834 - val_loss: 0.0113 - val_acc: 0.9974 - val_categorical_accuracy: 0.1733\nEpoch 4/30\n - 482s - loss: 0.0102 - acc: 0.9975 - categorical_accuracy: 0.2105 - val_loss: 0.0110 - val_acc: 0.9974 - val_categorical_accuracy: 0.1900\nEpoch 5/30\n - 491s - loss: 0.0101 - acc: 0.9975 - categorical_accuracy: 0.2087 - val_loss: 0.0108 - val_acc: 0.9974 - val_categorical_accuracy: 0.1906\nEpoch 6/30\n - 497s - loss: 0.0101 - acc: 0.9975 - categorical_accuracy: 0.2178 - val_loss: 0.0105 - val_acc: 0.9974 - val_categorical_accuracy: 0.2145\nEpoch 7/30\n - 486s - loss: 0.0093 - acc: 0.9976 - categorical_accuracy: 0.2425 - val_loss: 0.0104 - val_acc: 0.9974 - val_categorical_accuracy: 0.2107\nEpoch 8/30\n - 499s - loss: 0.0094 - acc: 0.9976 - categorical_accuracy: 0.2444 - val_loss: 0.0104 - val_acc: 0.9974 - val_categorical_accuracy: 0.2063\nEpoch 9/30\n - 495s - loss: 0.0093 - acc: 0.9976 - categorical_accuracy: 0.2411 - val_loss: 0.0103 - val_acc: 0.9974 - val_categorical_accuracy: 0.2243\nEpoch 10/30\n - 486s - loss: 0.0084 - acc: 0.9977 - categorical_accuracy: 0.2764 - val_loss: 0.0100 - val_acc: 0.9975 - val_categorical_accuracy: 0.2268\nEpoch 11/30\n - 498s - loss: 0.0083 - acc: 0.9978 - categorical_accuracy: 0.2882 - val_loss: 0.0102 - val_acc: 0.9974 - val_categorical_accuracy: 0.2265\nEpoch 12/30\n - 494s - loss: 0.0083 - acc: 0.9978 - categorical_accuracy: 0.2920 - val_loss: 0.0100 - val_acc: 0.9975 - val_categorical_accuracy: 0.2371\nEpoch 13/30\n - 486s - loss: 0.0075 - acc: 0.9979 - categorical_accuracy: 0.3210 - val_loss: 0.0100 - val_acc: 0.9975 - val_categorical_accuracy: 0.2395\nEpoch 14/30\n - 496s - loss: 0.0075 - acc: 0.9979 - categorical_accuracy: 0.3226 - val_loss: 0.0102 - val_acc: 0.9974 - val_categorical_accuracy: 0.2387\nEpoch 15/30\n - 495s - loss: 0.0075 - acc: 0.9979 - categorical_accuracy: 0.3255 - val_loss: 0.0102 - val_acc: 0.9974 - val_categorical_accuracy: 0.2262\nEpoch 16/30\n - 486s - loss: 0.0068 - acc: 0.9981 - categorical_accuracy: 0.3542 - val_loss: 0.0103 - val_acc: 0.9974 - val_categorical_accuracy: 0.2469\nEpoch 17/30\n - 493s - loss: 0.0068 - acc: 0.9981 - categorical_accuracy: 0.3549 - val_loss: 0.0103 - val_acc: 0.9974 - val_categorical_accuracy: 0.2562\nEpoch 00017: early stopping\n"
]
],
[
[
"### Complete model graph loss",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"whitegrid\")\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharex='col', figsize=(20,7))\n\n\nax1.plot(history.history['loss'], label='Train loss')\nax1.plot(history.history['val_loss'], label='Validation loss')\nax1.legend(loc='best')\nax1.set_title('Loss')\n\nax2.plot(history.history['acc'], label='Train Accuracy')\nax2.plot(history.history['val_acc'], label='Validation accuracy')\nax2.legend(loc='best')\nax2.set_title('Accuracy')\n\nax3.plot(history.history['categorical_accuracy'], label='Train Cat Accuracy')\nax3.plot(history.history['val_categorical_accuracy'], label='Validation Cat Accuracy')\nax3.legend(loc='best')\nax3.set_title('Cat Accuracy')\n\nplt.xlabel('Epochs')\nsns.despine()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Find best threshold value",
"_____no_output_____"
]
],
[
[
"lastFullValPred = np.empty((0, N_CLASSES))\nlastFullValLabels = np.empty((0, N_CLASSES))\n\nfor i in range(STEP_SIZE_VALID+1):\n im, lbl = next(valid_generator)\n scores = model.predict(im, batch_size=valid_generator.batch_size)\n lastFullValPred = np.append(lastFullValPred, scores, axis=0)\n lastFullValLabels = np.append(lastFullValLabels, lbl, axis=0)\n \nprint(lastFullValPred.shape, lastFullValLabels.shape)",
"(27309, 1103) (27309, 1103)\n"
],
[
"def find_best_fixed_threshold(preds, targs, do_plot=True):\n score = []\n thrs = np.arange(0, 0.5, 0.01)\n for thr in thrs:\n score.append(custom_f2(targs, (preds > thr).astype(int)))\n score = np.array(score)\n pm = score.argmax()\n best_thr, best_score = thrs[pm], score[pm].item()\n print(f'thr={best_thr:.3f}', f'F2={best_score:.3f}')\n if do_plot:\n plt.plot(thrs, score)\n plt.vlines(x=best_thr, ymin=score.min(), ymax=score.max())\n plt.text(best_thr+0.03, best_score-0.01, f'$F_{2}=${best_score:.3f}', fontsize=14);\n plt.show()\n return best_thr, best_score\n\nthreshold, best_score = find_best_fixed_threshold(lastFullValPred, lastFullValLabels, do_plot=True)",
"thr=0.160 F2=0.460\n"
]
],
[
[
"### Apply model to test set and output predictions",
"_____no_output_____"
]
],
[
[
"test_generator.reset()\nSTEP_SIZE_TEST = test_generator.n//test_generator.batch_size\npreds = model.predict_generator(test_generator, steps=STEP_SIZE_TEST)",
"_____no_output_____"
],
[
"predictions = []\nfor pred_ar in preds:\n valid = []\n for idx, pred in enumerate(pred_ar):\n if pred > threshold:\n valid.append(idx)\n if len(valid) == 0:\n valid.append(np.argmax(pred_ar))\n predictions.append(valid)",
"_____no_output_____"
],
[
"filenames = test_generator.filenames\nlabel_map = {valid_generator.class_indices[k] : k for k in valid_generator.class_indices}\n\nresults = pd.DataFrame({'id':filenames, 'attribute_ids':predictions})\nresults['id'] = results['id'].map(lambda x: str(x)[:-4])\nresults['attribute_ids'] = results['attribute_ids'].apply(lambda x: list(map(label_map.get, x)))\nresults[\"attribute_ids\"] = results[\"attribute_ids\"].apply(lambda x: ' '.join(x))\nresults.to_csv('submission.csv',index=False)\nresults.head(10)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
ece67befa8154938fea49ea7c09c28a5066cd80f | 24,141 | ipynb | Jupyter Notebook | dev/41_tabular_model.ipynb | muellerzr/fastai_dev-1 | 7931f7b1ce2eb8d09474e0e7368ff7f4896c8e6c | [
"Apache-2.0"
] | null | null | null | dev/41_tabular_model.ipynb | muellerzr/fastai_dev-1 | 7931f7b1ce2eb8d09474e0e7368ff7f4896c8e6c | [
"Apache-2.0"
] | null | null | null | dev/41_tabular_model.ipynb | muellerzr/fastai_dev-1 | 7931f7b1ce2eb8d09474e0e7368ff7f4896c8e6c | [
"Apache-2.0"
] | null | null | null | 30.596958 | 129 | 0.429643 | [
[
[
"#export\nfrom local.torch_basics import *\nfrom local.test import *\nfrom local.tabular.core import *",
"_____no_output_____"
],
[
"from local.notebook.showdoc import *",
"_____no_output_____"
],
[
"torch.cuda.set_device(5)",
"_____no_output_____"
],
[
"#default_exp tabular.model",
"_____no_output_____"
]
],
[
[
"# Tabular model\n\n> A basic model that can be used on tabular data",
"_____no_output_____"
],
[
"## Model",
"_____no_output_____"
]
],
[
[
"def emb_sz_rule(n_cat): \n \"Rule of thumb to pick embedding size corresponding to `n_cat`\"\n return min(600, round(1.6 * n_cat**0.56))",
"_____no_output_____"
],
[
"def _one_emb_sz(classes, n, sz_dict=None):\n \"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`.\"\n sz_dict = ifnone(sz_dict, {})\n n_cat = len(classes[n])\n sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb\n return n_cat,sz",
"_____no_output_____"
],
[
"def get_emb_sz(to, sz_dict=None):\n \"Get default embedding size from `TabularPreprocessor` `proc` or the ones in `sz_dict`\"\n return [_one_emb_sz(to.procs.classes, n, sz_dict) for n in to.cat_names]",
"_____no_output_____"
],
[
"class TabularModel(Module):\n \"Basic model for tabular data.\"\n def __init__(self, emb_szs, n_cont, out_sz, layers, ps=None, embed_p=0., y_range=None, use_bn=True, bn_final=False):\n ps = ifnone(ps, [0]*len(layers))\n if not is_listy(ps): ps = [ps]*len(layers)\n self.embeds = nn.ModuleList([Embedding(ni, nf) for ni,nf in emb_szs])\n self.emb_drop = nn.Dropout(embed_p)\n self.bn_cont = nn.BatchNorm1d(n_cont)\n n_emb = sum(e.embedding_dim for e in self.embeds)\n self.n_emb,self.n_cont,self.y_range = n_emb,n_cont,y_range\n sizes = [n_emb + n_cont] + layers + [out_sz]\n actns = [nn.ReLU(inplace=True) for _ in range(len(sizes)-2)] + [None]\n _layers = [LinBnDrop(sizes[i], sizes[i+1], bn=use_bn and i!=0, p=p, act=a)\n for i,(p,a) in enumerate(zip([0.]+ps,actns))]\n if bn_final: _layers.append(nn.BatchNorm1d(sizes[-1]))\n self.layers = nn.Sequential(*_layers)\n \n def forward(self, x_cat, x_cont):\n if self.n_emb != 0:\n x = [e(x_cat[:,i]) for i,e in enumerate(self.embeds)]\n x = torch.cat(x, 1)\n x = self.emb_drop(x)\n if self.n_cont != 0:\n x_cont = self.bn_cont(x_cont)\n x = torch.cat([x, x_cont], 1) if self.n_emb != 0 else x_cont\n x = self.layers(x)\n if self.y_range is not None:\n x = (self.y_range[1]-self.y_range[0]) * torch.sigmoid(x) + self.y_range[0]\n return x",
"_____no_output_____"
]
],
[
[
"## Integration example with training",
"_____no_output_____"
]
],
[
[
"from local.data.all import *\nfrom local.tabular.core import *\nfrom local.optimizer import *\nfrom local.learner import *\nfrom local.metrics import *\nfrom local.callback.all import *",
"_____no_output_____"
],
[
"path = untar_data(URLs.ADULT_SAMPLE)\ndf = pd.read_csv(path/'adult.csv')",
"_____no_output_____"
],
[
"cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']\ncont_names = ['age', 'fnlwgt', 'education-num']\nprocs = [Categorify, FillMissing, Normalize]\nsplits = RandomSplitter()(range_of(df))",
"_____no_output_____"
],
[
"to = TabularPandas(df, procs, cat_names, cont_names, y_names=\"salary\", splits=splits)",
"_____no_output_____"
],
[
"trn_dl = TabDataLoader(to.train, bs=64, num_workers=0, shuffle=True, drop_last=True)\nval_dl = TabDataLoader(to.valid, bs=128, num_workers=0)\ndbunch = DataBunch(trn_dl, val_dl)\ndbunch.show_batch()",
"_____no_output_____"
],
[
"model = TabularModel(get_emb_sz(to), len(to.cont_names), 2, [200,100])",
"_____no_output_____"
],
[
"opt_func = partial(Adam, wd=0.01, eps=1e-5)\nlearn = Learner(dbunch, model, CrossEntropyLossFlat(), opt_func=opt_func, metrics=accuracy)",
"_____no_output_____"
],
[
"learn.fit_one_cycle(1)",
"_____no_output_____"
],
[
"#export\n@typedispatch\ndef show_results(x:Tabular, y:Tabular, samples, outs, ctxs=None, max_n=10, **kwargs):\n df = x.all_cols[:max_n]\n df[to.y_names+'_pred'] = y[to.y_names][:max_n].values\n display_df(df)",
"_____no_output_____"
],
[
"learn.show_results()",
"_____no_output_____"
]
],
[
[
"## Export -",
"_____no_output_____"
]
],
[
[
"#hide\nfrom local.notebook.export import notebook2script\nnotebook2script(all_fs=True)",
"Converted 00_test.ipynb.\nConverted 01_core_foundation.ipynb.\nConverted 01a_core_utils.ipynb.\nConverted 01b_core_dispatch.ipynb.\nConverted 01c_core_transform.ipynb.\nConverted 02_core_script.ipynb.\nConverted 03_torchcore.ipynb.\nConverted 03a_layers.ipynb.\nConverted 04_data_load.ipynb.\nConverted 05_data_core.ipynb.\nConverted 06_data_transforms.ipynb.\nConverted 07_data_block.ipynb.\nConverted 08_vision_core.ipynb.\nConverted 09_vision_augment.ipynb.\nConverted 09a_vision_data.ipynb.\nConverted 10_pets_tutorial.ipynb.\nConverted 11_vision_models_xresnet.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_learner.ipynb.\nConverted 13a_metrics.ipynb.\nConverted 14_callback_schedule.ipynb.\nConverted 14a_callback_data.ipynb.\nConverted 15_callback_hook.ipynb.\nConverted 15a_vision_models_unet.ipynb.\nConverted 16_callback_progress.ipynb.\nConverted 17_callback_tracker.ipynb.\nConverted 18_callback_fp16.ipynb.\nConverted 19_callback_mixup.ipynb.\nConverted 20_interpret.ipynb.\nConverted 20a_distributed.ipynb.\nConverted 21_vision_learner.ipynb.\nConverted 22_tutorial_imagenette.ipynb.\nConverted 23_tutorial_transfer_learning.ipynb.\nConverted 30_text_core.ipynb.\nConverted 31_text_data.ipynb.\nConverted 32_text_models_awdlstm.ipynb.\nConverted 33_text_models_core.ipynb.\nConverted 34_callback_rnn.ipynb.\nConverted 35_tutorial_wikitext.ipynb.\nConverted 36_text_models_qrnn.ipynb.\nConverted 37_text_learner.ipynb.\nConverted 38_tutorial_ulmfit.ipynb.\nConverted 40_tabular_core.ipynb.\nConverted 41_tabular_model.ipynb.\nConverted 42_tabular_rapids.ipynb.\nConverted 50_data_block_examples.ipynb.\nConverted 60_medical_imaging.ipynb.\nConverted 65_medical_text.ipynb.\nConverted 70_callback_wandb.ipynb.\nConverted 71_callback_tensorboard.ipynb.\nConverted 90_notebook_core.ipynb.\nConverted 91_notebook_export.ipynb.\nConverted 92_notebook_showdoc.ipynb.\nConverted 93_notebook_export2html.ipynb.\nConverted 94_notebook_test.ipynb.\nConverted 95_index.ipynb.\nConverted 96_data_external.ipynb.\nConverted 97_utils_test.ipynb.\nConverted notebook2jekyll.ipynb.\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece684221e4f1444539228fb3571799f33f5f756 | 273,366 | ipynb | Jupyter Notebook | jupyter/tinkering/tinkering_RSA_MNE.ipynb | MaryZolfaghar/SPLT_EEG | 1c5ddfde4c1a97ec5d3aa974ef66f98508400f00 | [
"Apache-2.0"
] | null | null | null | jupyter/tinkering/tinkering_RSA_MNE.ipynb | MaryZolfaghar/SPLT_EEG | 1c5ddfde4c1a97ec5d3aa974ef66f98508400f00 | [
"Apache-2.0"
] | null | null | null | jupyter/tinkering/tinkering_RSA_MNE.ipynb | MaryZolfaghar/SPLT_EEG | 1c5ddfde4c1a97ec5d3aa974ef66f98508400f00 | [
"Apache-2.0"
] | null | null | null | 781.045714 | 79,520 | 0.949624 | [
[
[
"# Authors: Jean-Remi King <[email protected]>\n# Jaakko Leppakangas <[email protected]>\n# Alexandre Gramfort <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\nimport numpy as np\nfrom pandas import read_csv\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.manifold import MDS\n\nimport mne\nfrom mne.io import read_raw_fif, concatenate_raws\nfrom mne.datasets import visual_92_categories\n\n\nprint(__doc__)\n\ndata_path = visual_92_categories.data_path()\n\n# Define stimulus - trigger mapping\nfname = op.join(data_path, 'visual_stimuli.csv')\nconds = read_csv(fname)\nprint(conds.head(5))",
"Automatically created module for IPython interactive environment\n trigger condition human face animal natural\n0 0 human bodypart 1 0 1 1\n1 1 human bodypart 1 0 1 1\n2 2 human bodypart 1 0 1 1\n3 3 human bodypart 1 0 1 1\n4 4 human bodypart 1 0 1 1\n"
],
[
"max_trigger = 24\nconds = conds[:max_trigger] # take only the first 24 rows",
"_____no_output_____"
],
[
"conditions = []\nfor c in conds.values:\n cond_tags = list(c[:2])\n cond_tags += [('not-' if i == 0 else '') + conds.columns[k]\n for k, i in enumerate(c[2:], 2)]\n conditions.append('/'.join(map(str, cond_tags)))\nprint(conditions[:10])",
"['0/human bodypart/human/not-face/animal/natural', '1/human bodypart/human/not-face/animal/natural', '2/human bodypart/human/not-face/animal/natural', '3/human bodypart/human/not-face/animal/natural', '4/human bodypart/human/not-face/animal/natural', '5/human bodypart/human/not-face/animal/natural', '6/human bodypart/human/not-face/animal/natural', '7/human bodypart/human/not-face/animal/natural', '8/human bodypart/human/not-face/animal/natural', '9/human bodypart/human/not-face/animal/natural']\n"
],
[
"event_id = dict(zip(conditions, conds.trigger + 1))\nevent_id['0/human bodypart/human/not-face/animal/natural']",
"_____no_output_____"
],
[
"n_runs = 4 # 4 for full data (use less to speed up computations)\nfname = op.join(data_path, 'sample_subject_%i_tsss_mc.fif')\nraws = [read_raw_fif(fname % block, verbose='error')\n for block in range(n_runs)] # ignore filename warnings\nraw = concatenate_raws(raws)\n\nevents = mne.find_events(raw, min_duration=.002)\n\nevents = events[events[:, 2] <= max_trigger]",
"4142 events found\nEvent IDs: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18\n 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36\n 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54\n 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72\n 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90\n 91 92 93 200 222 244]\n"
],
[
"picks = mne.pick_types(raw.info, meg=True)\nepochs = mne.Epochs(raw, events=events, event_id=event_id, baseline=None,\n picks=picks, tmin=-.1, tmax=.500, preload=True)",
"720 matching events found\nNo baseline correction applied\nNot setting metadata\n0 projection items activated\nLoading data for 720 events and 601 original time points ...\n0 bad epochs dropped\n"
],
[
"epochs['face'].average().plot()\nepochs['not-face'].average().plot()",
"_____no_output_____"
],
[
"# Classify using the average signal in the window 50ms to 300ms\n# to focus the classifier on the time interval with best SNR.\nclf = make_pipeline(StandardScaler(),\n LogisticRegression(C=1, solver='liblinear',\n multi_class='auto'))\nX = epochs.copy().crop(0.05, 0.3).get_data().mean(axis=2)\ny = epochs.events[:, 2]\n\nclasses = set(y)\ncv = StratifiedKFold(n_splits=5, random_state=0, shuffle=True)\n\n# Compute confusion matrix for each cross-validation fold\ny_pred = np.zeros((len(y), len(classes)))\nfor train, test in cv.split(X, y):\n # Fit\n clf.fit(X[train], y[train])\n # Probabilistic prediction (necessary for ROC-AUC scoring metric)\n y_pred[test] = clf.predict_proba(X[test])",
"_____no_output_____"
],
[
"confusion = np.zeros((len(classes), len(classes)))\nfor ii, train_class in enumerate(classes):\n for jj in range(ii, len(classes)):\n confusion[ii, jj] = roc_auc_score(y == train_class, y_pred[:, jj])\n confusion[jj, ii] = confusion[ii, jj]",
"_____no_output_____"
],
[
"labels = [''] * 5 + ['face'] + [''] * 11 + ['bodypart'] + [''] * 6\nfig, ax = plt.subplots(1)\nim = ax.matshow(confusion, cmap='RdBu_r', clim=[0.3, 0.7])\nax.set_yticks(range(len(classes)))\nax.set_yticklabels(labels)\nax.set_xticks(range(len(classes)))\nax.set_xticklabels(labels, rotation=40, ha='left')\nax.axhline(11.5, color='k')\nax.axvline(11.5, color='k')\nplt.colorbar(im)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1)\nmds = MDS(2, random_state=0, dissimilarity='precomputed')\nchance = 0.5\nsummary = mds.fit_transform(chance - confusion)\ncmap = plt.get_cmap('rainbow')\ncolors = ['r', 'b']\nnames = list(conds['condition'].values)\nfor color, name in zip(colors, set(names)):\n sel = np.where([this_name == name for this_name in names])[0]\n size = 500 if name == 'human face' else 100\n ax.scatter(summary[sel, 0], summary[sel, 1], s=size,\n facecolors=color, label=name, edgecolors='k')\nax.axis('off')\nax.legend(loc='lower right', scatterpoints=1, ncol=2)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece687df5b1cab20d8948a4e0feb8adb221fd8bc | 133,842 | ipynb | Jupyter Notebook | notebooks/People/Generating Populations.ipynb | BillmanH/exoplanets | 92656bf8c917c6e07d91f82a7cd0b75679ffa680 | [
"MIT"
] | 14 | 2021-03-03T19:27:46.000Z | 2022-03-21T16:24:45.000Z | notebooks/People/Generating Populations.ipynb | BillmanH/exoplanets | 92656bf8c917c6e07d91f82a7cd0b75679ffa680 | [
"MIT"
] | 6 | 2021-08-14T17:17:58.000Z | 2021-09-28T14:34:56.000Z | notebooks/People/Generating Populations.ipynb | BillmanH/exoplanets | 92656bf8c917c6e07d91f82a7cd0b75679ffa680 | [
"MIT"
] | null | null | null | 263.988166 | 26,463 | 0.602382 | [
[
[
"# Generating Populations and Species\nAssuming that the civilization is on the verge of moving from a phaze 0 to phase 1 civ.\n* baseline species\n* n populations (pops)\n* population varience (within the norms of the species)\n* allegiance groups to factions",
"_____no_output_____"
],
[
"Starting with an example user form data",
"_____no_output_____"
]
],
[
[
"\r\nfrom numpy import random, round, interp, linspace\r\nimport pickle\r\nfrom sklearn.cluster import KMeans\r\nimport altair as alt\r\nimport sys, os\r\nfrom sklearn.cluster import KMeans\r\n\r\nimport pandas as pd\r\n",
"_____no_output_____"
]
],
[
[
"origional `data` comes from the user via the form in `forms.py`",
"_____no_output_____"
]
],
[
[
"starting_attributes = ['conformity', 'literacy', 'aggression', 'constitution']\r\n\r\ndata = {\r\n 'conformity':0.4,\r\n 'literacy':0.7,\r\n 'aggression':0.5,\r\n 'constitution':0.4,\r\n 'starting_pop': 100\r\n}\r\n\r\ndef build_species(data):\r\n species = {}\r\n for attr in starting_attributes:\r\n species[attr] = data[attr]\r\n return species\r\n \r\nspecies = build_species(data)\r\nspecies\r\n",
"_____no_output_____"
],
[
"sys.path.append('..')\r\nimport helpers.dbquery as db\r\nimport helpers.functions as f",
"_____no_output_____"
]
],
[
[
"## Creating groups of populations, all with different attributes\r\n\r\nPopulations vary based on conformity, some populations are more literate, some are more aggressive. ",
"_____no_output_____"
]
],
[
[
"pop_std = .2 * (1-species['conformity'])\r\nprint(\"the population conformity: \", pop_std)\r\n\r\ndef vary_pops(species):\r\n pop = {}\r\n for k in list(species.keys()):\r\n pop[k] = abs(round(random.normal(species[k], pop_std),3))\r\n return pop\r\n\r\npops = pd.DataFrame([vary_pops(species) for i in range(data['starting_pop'])])\r\npops",
"the population conformity: 0.12\n"
]
],
[
[
"The end result is that population factions are grouped by the idealogical differences of the people in them. This gives each faction a distinct culture. ",
"_____no_output_____"
],
[
"## Dividing pops into factions\r\n\r\nI feel like there isn't a way to pick an ideal number of factions procedurally, so until I think of something better I'm just going to go with an arbitrary range based on `population_conformity`.\r\n\r\nThe amount of different nations is relative to `1-population_conformity` and then scaled out over a number of steps defined as `n_steps`",
"_____no_output_____"
]
],
[
[
"n_steps = 6\r\n\r\ndef get_n_factions(n_steps):\r\n x = interp(\r\n (1-data[\"conformity\"]),\r\n linspace(0, 1, num=n_steps),\r\n [i for i in range(n_steps)]\r\n )\r\n return int(round(x))\r\n\r\nget_n_factions(n_steps)",
"_____no_output_____"
],
[
"kmeans = KMeans(n_clusters=n_steps).fit(pops[starting_attributes])\r\npops['faction_no'] = kmeans.labels_",
"_____no_output_____"
],
[
"factions = pd.DataFrame(kmeans.cluster_centers_, columns=starting_attributes)\r\nfactions['name'] = factions['conformity'].apply(lambda x: f.make_word(1))\r\nfactions",
"_____no_output_____"
]
],
[
[
"So individual `pops` vary slightly, relative to the `conformity`. And `conformity` also determines the number of factions in the group. ",
"_____no_output_____"
]
],
[
[
"chart = alt.Chart(pops).mark_circle().encode(x='literacy',y='aggression',color='faction_no:N')\r\nchart",
"_____no_output_____"
]
],
[
[
"The cluster centers can represent the 'zeitgeist' of that faction's culture. ",
"_____no_output_____"
],
[
"# Other population attributes",
"_____no_output_____"
],
[
"## Other attributes that get added\r\nThese items aren't used to calculate factions as they refer to resources, not values. These are calculated at the creation of a `pop` and later can be updated. \r\n\r\n* `industry` = `aggression` + `constitution`\r\n* `wealth` = sum(`literacy` + `industry`)/2\r\n\r\n",
"_____no_output_____"
]
],
[
[
"pops['industry'] = (pops['aggression'] + pops['constitution'])/2\r\npops['wealth'] = (pops['literacy'] + pops['industry'])/2\r\npops['target_score'] = (1-pops['conformity']) - pops['aggression']\r\npops",
"_____no_output_____"
],
[
"chart = alt.Chart(pops).mark_circle().encode(x='wealth',y='industry',color='faction_no:N')\r\nchart",
"_____no_output_____"
],
[
"chart = alt.Chart(\r\n pops.reset_index(drop=False)\r\n ).mark_bar(size=4).encode(\r\n x=alt.X('index:N', sort='-y'),\r\n y='wealth',\r\n color='faction_no:N').properties(width=600,title='Some populations make better targets than others')\r\nchart",
"_____no_output_____"
],
[
"chart.encode(\r\n x=alt.X('faction_no:N', sort='-y'),\r\n y='wealth',\r\n \r\n color='faction_no:N').properties(title='Some factions have greater wealth')",
"_____no_output_____"
],
[
"# chart_pivot = pops.unstack().reset_index(drop=False).rename(columns={'level_0':'attribute', 'level_1':'item', 0:'value'})\r\n# chart_pivot",
"_____no_output_____"
]
],
[
[
"# Faction Loyalty\r\n* More aggressive pops will have less loyalty. \r\n* populations with values more distant to the faction will have less loyalty. \r\n\r\nHow do you calculate the difference between values of two groups?",
"_____no_output_____"
]
],
[
[
"def compare_values(values,gr1,gr2):\r\n distance = []\r\n for v in values:\r\n distance.append(abs(gr1.get(v,0)-gr2.get(v,0)))\r\n return sum(distance)/len(distance)\r\n\r\ncompare_values(starting_attributes,\r\n pops.loc[0].to_dict(),\r\n pops.loc[2].to_dict())",
"_____no_output_____"
]
],
[
[
"The average of the distance between values indicates the idealogical separation between two peoples. The same can be used to measure a people and it's faction, as well as the animosity between two factions. \r\n\r\ncompare values determines how similar groups are, then `1-compare` is how distant they are. This is used to place the starting loyalty. ",
"_____no_output_____"
]
],
[
[
"def get_faction_loyalty(x):\r\n g1 = pops.loc[x].to_dict()\r\n f2 = factions.loc[int(g1['faction_no'])].to_dict()\r\n return compare_values(starting_attributes,g1,f2)\r\n\r\n\r\npops['faction_loyalty'] = [(1-get_faction_loyalty(i)) for i in pops.index]\r\n\r\nalt.Chart(pops).mark_point().encode(\r\n x=alt.X('aggression:Q', sort='-y'),\r\n y=alt.Y('faction_loyalty:Q',scale=alt.Scale(domain=(0.8, 1))),\r\n color='faction_no:N').properties(title='Depending on the conformity, and aggression of people, the loyalty could be high or low.')\r\n",
"_____no_output_____"
]
],
[
[
"Beware of populations that have high aggression and low faction loyalty",
"_____no_output_____"
],
[
"This applies to factions as well. \r\n\r\nNote that this doesn't need to be stored, it can be calculated on the fly so long as the `values` for each party are available. ",
"_____no_output_____"
]
],
[
[
"[[(f1['name'],f2['name'],1-compare_values(starting_attributes,f1,f2))\r\n for f1 in factions.to_dict(\"records\")] \r\n for f2 in factions.to_dict(\"records\")]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
ece68d3cef197a26d332677612aedf45dd990702 | 13,505 | ipynb | Jupyter Notebook | Fall-19/ProblemSet4/Assignment_4_new_solutions.ipynb | sungsy12345/ENVECON-118 | b2b62f49115f37e3a3c1f13b7ac6a3550c4c0600 | [
"BSD-3-Clause"
] | 2 | 2020-09-10T13:45:34.000Z | 2021-11-01T21:41:59.000Z | Fall-19/ProblemSet4/Assignment_4_new_solutions.ipynb | sungsy12345/ENVECON-118 | b2b62f49115f37e3a3c1f13b7ac6a3550c4c0600 | [
"BSD-3-Clause"
] | 1 | 2021-01-22T17:02:59.000Z | 2021-06-20T14:03:54.000Z | Fall-19/ProblemSet4/Assignment_4_new_solutions.ipynb | sungsy12345/ENVECON-118 | b2b62f49115f37e3a3c1f13b7ac6a3550c4c0600 | [
"BSD-3-Clause"
] | 7 | 2019-11-06T20:55:27.000Z | 2021-06-20T08:14:41.000Z | 50.962264 | 942 | 0.67227 | [
[
[
"# Big Assignment 4",
"_____no_output_____"
],
[
"### A number of organizations and governments are considering policies to supply students with access to free computers, in an effort to boost learning outcomes. Suppose that you want to learn about the effect of having a free computer on test scores. For a sample of high school students, you collect data on test scores (`test` ), parent’s income (`inc`), and whether they have a computer at home (`comp`).",
"_____no_output_____"
],
[
"### Part A:\n#### Suppose that a local organization held a lottery, and offered computers at random to a number of students, indicated by freecomp. Suppose that among the population who were not offered a free computer, 60% have a computer, whereas after the lottery, 90% of people offered a computer had a computer. Compare the specifications",
"_____no_output_____"
],
[
"\\begin{align}\ntest=\\beta_0+\\beta_1comp+u\n\\end{align}",
"_____no_output_____"
],
[
"#### or",
"_____no_output_____"
],
[
"\\begin{align}\ntest=\\beta_0+\\beta_1freecomp+u\n\\end{align}\n",
"_____no_output_____"
],
[
"#### Both tell you something different about the effect of computers on test scores. Describe the limitations of each approach.",
"_____no_output_____"
],
[
"#### ANSWER:\n\n The first specification \n\\begin{align}\ntest= \\beta_0+\\beta_1 comp+u\n\\end{align}\n describes the effect of having a computer on test scores, while the second specification\n\\begin{align}\ntest= \\beta_0+\\beta_1 freecomp+u\n\\end{align}\n\n describes the effect of being offered a computer on test scores. In other words, the first specification is explicitly about ownership of a computer, irrespective of whether or not one had one before the random distribution, while the second specification is interested in the individual having been offered a computer, irrespective of whether or not one had one before the random distribution, and with no conclusion yet as to whether the individual accepted the computer.\n\n Regarding limitations: In the first specification, one might be worried about unobservables that are correlated with having computer that are also correlated with test scores. For example, students who are more driven academically and try harder on tests may also be those who will pressure their parents to purchase them computers to work on. Meanwhile, in the second specification, we don’t learn what the effect of computers are on test scores. Instead, we learn about the effect of the program’s offer, which may not exactly be our interest.\n",
"_____no_output_____"
],
[
"### Part B: \n#### You are concerned that household income may be correlated with test scores for a variety of reasons. Suggest an alternate specification that holds income constant, and discuss how you anticipate it changing inference using each estimated $\\beta_1$ above.",
"_____no_output_____"
],
[
"#### ANSWER:\n\n\nOur specifications are now\n\\begin{align}\ntest= \\beta_0+\\beta_1 comp+\\beta_2 income+u\n\\end{align}\nand \n\\begin{align}\ntest= \\beta_0+\\beta_1 freecomp+\\beta_2 income+u\n\\end{align}\n\nFor specification 1, the exclusion of income from the specification previously was likely leading to omitted variable bias for beta 1, such that our estimate for beta 1 now suffers from less bias.\n\nFor specification 2, because freecomp is random, we know that E[u|T]=0 will be true in expectation but not always in samples, such that including more control variables can reduce bias. However, we usually don’t expect that adding a control will change the estimate of interest here. Including control variables will also increase the precision of estimates.\n",
"_____no_output_____"
],
[
"### Part C:\n#### Propose a “Treatment on the treated” estimator for the free computer lottery.",
"_____no_output_____"
],
[
"#### ANSWER:\n\nA treatment on the treated estimator for the effect of owning a computer can be written as follows:\n\\begin{align}\n\\frac{\\overline{(test)_P}-\\overline{(test)_{NP}}}{\\overline{(comp)_P}-\\overline{(comp)_{NP}} }\n\\end{align}\nwhere P is assigned to group receiving and offer for a computer,NP is assigned to the group not receiving an offer for a computer, and comp is the proportion owning a computer.\n\n",
"_____no_output_____"
],
[
"### Part D: \n#### You think computers might have two different effects on test scores. On the one hand, they are a productive tool which can help learning. On the other hand, they open up recreational opportunities (like social networking) which may not be very useful for learning. As a result, you wonder what the effects of a free computer would be if you could hold recreational screentime constant. That is, you would like to estimate\n\\begin{align}\ntest=\\beta_0+\\beta_1freecomp+\\beta_2screentime+u\n\\end{align}",
"_____no_output_____"
],
[
"#### However, in practice you cannot observe screentime. You have two options: \n\n#### - either you can just use whether they have a smart phone as a proxy variable for screentime (variable `Smartphone`), \n\n#### -or you can ask the students to report how much screentime they spend per day (`repscreentime`).\n#### Describe algebraically how each approach will affect estimation of $\\beta_1$ and $\\beta_2$ in the equation for part D, and the analogue to MLR4 which is necessary to grant unbiased estimates. Discuss different potential forms for any measurement error, and the likely consequences of that measurement error.",
"_____no_output_____"
],
[
"#### ANSWER: \n\nWe start out with our original model:\n\\begin{align}\ntest=\\beta_0+\\beta_1freecomp+\\beta_2screentime+u\n\\end{align}\nCase 1: Using `smartphone` represents the case described in Wooldridge 9.2 – Using Proxy Variables for Unobserved Explanatory Variables. `smartphone` is a proxy variable for `screentime`, which means we have\n\n\\begin{align}\nscreentime=\\delta_0+\\delta_2smartphone+\\nu_2\n\\end{align}\n\nwhere $\\nu_2$ is an error due to the fact that `screentime` and `smartphone` are not related. If we plug in smartphone into the original model, then whether the proxy delivers consistent estimators depends on assumptions about $u$ and $\\nu_2$.\n\n(1) $u$ is uncorrelated with freecomp, screentime and smartphone, which are fairly standard assumptions implying that E$[u|freecomp, screentime, smartphone] = 0$.\n\n(2)$\\nu_2$ is uncorrelated with freecomp and smartphone. Assuming that $\\nu_2$ is uncorrelated with freecomp requires smartphone to be a good proxy for screentime, which we can see by writing these assumptions in terms of conditional expectations\n\\begin{align}\nE[screentime│freecomp,smartphone]=E[screentime│smartphone]\\\\\n= \\delta_0+\\delta_2 smartphone\n\\end{align}\n\nwhich is to say that once we control for smartphones, the expected value of screentime does not depend on freecomp. This may or may not be a reasonable assumption. But if we do assume this, then by plugging in we see that\n\n\\begin{align}\ny=(\\beta_0+\\beta_2\\delta_0 )+\\beta_1 freecomp+ \\beta_2 \\delta_2 smartphone+u+\\beta_2 \\nu_2\n\\end{align}\n\nthe composite error can be written as $e = u + \\beta_2 \\nu_2$. Since both $u$ and $v_2$ have zero mean and each is uncorrelated with `freecomp` and `smartphone`, $e$ also has zero mean and is uncorrelated with `freecomp` and `smartphone`. We can write the above as \n\\begin{align}\ny=\\alpha_0+\\beta_1 freecomp+ \\alpha_2 smartphone+e\n\\end{align}\n\nThus, when we run the regression of our y on freecomp and smartphone, we will not recover unbiased estimators of $\\beta_0$ and $\\beta_2$, but we will instead get unbiased estimators of $\\alpha_0$, $\\beta_1$, and $\\alpha_2$.\n\nIf instead screentime was related to all observed variables by\n\\begin{align}\nscreentime= \\delta_0+\\delta_1 freecomp+\\delta_2 smartphone+\\nu_2\n\\end{align}\n\nwhere $\\nu_2$ has zero mean and is uncorrelated with `freecomp` and `smartphone`. Substituting the above equation into the equation with y on the LHS, we have\n\\begin{align}\ny=(\\beta_0+\\beta_2 \\delta_0 )+(\\beta_1+\\beta_2 \\delta_1)freecomp+ \\beta_2 \\delta_2 smartphone+u+\\beta_2 \\nu_2\n\\end{align}\nsuch that the probability limit of estimated $\\beta_1 = \\beta_1 + \\beta_2 \\delta_1$, so we can still get an upward bias for `freecomp` if `smartphone` is not a good proxy.\n\nCase 2: Using repscreentime represents the case described in Wooldridge 9.4b.We can have measurement error of \n\\begin{align}\ne_2=repscreentime-screentime\n\\end{align}\nand we assume $E[e_2] = 0$. An important assumption is that u is uncorrelated with freecomp, repscreentime, and screentime. Usually $e_2$ is assumed to be uncorrelated with freecomp. However, the key issue is whether $e_2$ is uncorrelated with repscreentime. If it is uncorrelated, then the OLS regression of y on freecomp and repscreentime produces consistent estimators, which can be seen by writing\n\\begin{align}\ny=\\beta_0+\\beta_1 freecomp+\\beta_2 repscreentime+u-\\beta_2 e_2\n\\end{align}\n\nwhere $u$ and $e_2$ are both uncorrelated with all the explanatory variables. Under the CEV assumption that measurement error is uncorrelated with the unobserved explanatory variable, OLS will be biased and inconsistent, because $e_1$ is correlated with repscreentime, which means that all OLS estimators will be biased. There will also be attenuation bias on $\\beta_2$.\n",
"_____no_output_____"
],
[
"### Part E:\n\n#### Suppose instead that the organization offered free computers to the students whose parent’s income was in the bottom 20% of the school. Write down a regression equation which will implement a regression-discontinuity estimator to learn the impact of receiving a free computer. Discuss why results from that estimator may be different from the results from the randomized lottery in part A.\n",
"_____no_output_____"
],
[
"#### ANSWER:\n\nTo learn the impact of receiving a free computer, we can implement the following equation:\n\\begin{align}\ntest= \\beta_0+\\beta_1 bottom20_i+\\beta_2 income_i+\\beta_3 bottom20_i*income_i+u_i\n\\end{align}\n\nwhere `bottom20` is an indicator variable for being a student whose parent’s income was in the bottom 20% of the school, and income is the income percentile that the individual’s parents fall into within the school. \n\nResults from this estimator may be different from the randomized lottery in part A for a number of reasons. For one, results may be different depending on the linearity between income and test scores, which would motivate us to limit our data to observations around the threshold.We are estimating the treatment effect on a different local population: in the RCT TOT estimator, we get a LATE on compliers, while in the RD we get a LATE on the people around the threshold. We might also be concerned about other policies that may have been enacted at or close to the threshold.Finally, we would be worried about possible gaming around the threshold, which would motivate us to see if there are more individuals reporting just under or at 20% compared to right above 20%. We will also want to know how well the cutoff was respected, while in the RCT presumably the protocols regarding offers being made or not made were well respected.\n\n",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
ece693ebede0f60c655a9cbecca324787c6e777d | 18,396 | ipynb | Jupyter Notebook | recommendation/youtube/coleta_de_dados_search.ipynb | vallinoto/portfolio | 3d44a317118478c319d4b0b7b6a9702cebaeb841 | [
"MIT"
] | null | null | null | recommendation/youtube/coleta_de_dados_search.ipynb | vallinoto/portfolio | 3d44a317118478c319d4b0b7b6a9702cebaeb841 | [
"MIT"
] | null | null | null | recommendation/youtube/coleta_de_dados_search.ipynb | vallinoto/portfolio | 3d44a317118478c319d4b0b7b6a9702cebaeb841 | [
"MIT"
] | null | null | null | 37.238866 | 94 | 0.458687 | [
[
[
"import pandas as pd\nimport numpy as np\nimport re\nimport time\n\nimport requests as rq\nimport bs4 as bs4 # beautifulsoup4\nimport json",
"_____no_output_____"
],
[
"queries = [\"machine+learning\", \"data+science\", \"kaggle\"]\nurl = \"https://www.youtube.com/results?search_query={query}&sp=CAI%253D&p={page}\"",
"_____no_output_____"
]
],
[
[
"# Coleta dos dados",
"_____no_output_____"
]
],
[
[
"for query in queries:\n for page in range(1,101):\n urll = url.format(query=query, page=page)\n print(urll)\n response = rq.get(urll)\n \n with open(\"./dados_brutos/{}_{}.html\".format(query, page), 'w+') as output:\n output.write(response.text)\n time.sleep(2)",
"https://www.youtube.com/results?search_query=machine+learning&sp=CAI%253D&p=1\n"
]
],
[
[
"# Processamento dos dados brutos",
"_____no_output_____"
]
],
[
[
"for query in queries:\n for page in range(1,2):\n with open(\"./dados_brutos/{}_{}.html\".format(query, page), 'r+') as inp:\n page_html = inp.read()\n \n parsed = bs4.BeautifulSoup(page_html)\n \n tags = parsed.findAll(\"a\")\n \n for e in tags:\n if e.has_attr(\"aria-describedby\"):\n link = e['href']\n title = e['title']\n with open(\"parsed_videos.json\", 'a+') as output:\n data = {\"link\": link, \"title\": title, \"query\": query}\n output.write(\"{}\\n\".format(json.dumps(data)))\n ",
"_____no_output_____"
]
],
[
[
"# Verificação do resultado",
"_____no_output_____"
]
],
[
[
"df = pd.read_json(\"parsed_videos.json\", lines=True)",
"_____no_output_____"
],
[
"df.sort_values(\"title\")",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece6b6f2ed3f8731cbe70bc0154b2f411c6b7378 | 39,905 | ipynb | Jupyter Notebook | examples/loading_data.ipynb | jasonlines/sktime-workshop-shapelets | de18963af56a0f062b0a69cc6560611912a6778f | [
"BSD-3-Clause"
] | 2 | 2021-01-19T05:10:50.000Z | 2021-01-22T18:39:56.000Z | examples/loading_data.ipynb | jasonlines/sktime-workshop-shapelets | de18963af56a0f062b0a69cc6560611912a6778f | [
"BSD-3-Clause"
] | 1 | 2019-11-05T16:48:00.000Z | 2019-11-05T16:48:00.000Z | examples/loading_data.ipynb | jasonlines/sktime-workshop-shapelets | de18963af56a0f062b0a69cc6560611912a6778f | [
"BSD-3-Clause"
] | 1 | 2019-11-05T16:34:32.000Z | 2019-11-05T16:34:32.000Z | 30.139728 | 743 | 0.396341 | [
[
[
"# Loading data in sktime\n\n[Github weblink](https://github.com/alan-turing-institute/sktime/blob/master/examples/loading_data.ipynb)",
"_____no_output_____"
],
[
"Data for use with sktime should be stored in pandas DataFrame objects with cases represented by rows and series data for each dimension of a problem stored in columns (the specifics of the data structure are described in more detail in the section below). Data can be loaded into the sktime format through various means, such as loading directly from a bespoke sktime file format (.ts) or supported file formats provided by other existing data sources (such as ARFF and .tsv). Further, data can also be loaded through other means into a long-table format and then converted to the sktime format using a provided method. \n\nBelow is a brief description of the .ts file format, an introduction of how data are stored in dataframes for sktime, and examples of loading data from a variety of file formats. ",
"_____no_output_____"
]
],
[
[
"from sktime.utils.load_data import load_from_tsfile_to_dataframe",
"_____no_output_____"
]
],
[
[
"## Representing data with .ts files\n\nThe most typical use case is to load data from a locally stored .ts file. The .ts file format has been created for representing problems in a standard format for use with sktime. These files include two main parts: \n* header information\n* data \n\nThe header information is used to facilitate simple representation of the data through including metadata about the structure of the problem. The header contains the following: \n\n @problemName <problem name>\n @timeStamps <true/false> \n @univariate <true/false>\n @classLabel <true/false> <space delimted list of possible class values>\n @data\n \nThe data for the problem should begin after the @data tag. In the simplest case where @timestamps is false, values for a series are expressed in a comma-separated list and the index of each value is relative to its position in the list (0, 1, ..., m). A _case_ may contain 1 to many dimensions, where cases are line-delimited and dimensions within a case are colon (:) delimited. For example:\n\n 2,3,2,4:4,3,2,2\n 13,12,32,12:22,23,12,32\n 4,4,5,4:3,2,3,2\n\nThis example data has 3 _cases_, where each case has 2 _dimensions_ with 4 observations per dimension. Missing readings can be specified using ?, or for sparse datasets, readings can be specified by setting @timestamps to true and representing the data with tuples in the form of (timestamp, value). For example, the first case in the example above could be specified in this representation as: \n\n (0,2),(1,3)(2,2)(3,4):(0,4),(1,3),(2,2),(3,2)\n\nEquivalently, \n\n 2,5,?,?,?,?,?,5,?,?,?,?,4 \n\ncould be represnted with timestamps as:\n\n (0,2),(0,5),(7,5),(12,4)\n \nFor classification problems, the class label for a case should be specified in the last dimension and @classLabel should be in the header information to specify the set of possible class values. For example, if a case consists of a single dimension and has a class value of 1 it would be specified as:\n\n 1,4,23,34:1\n\n## Storing data in a pandas DataFrame\n\nThe core data structure for storing datasets in sktime is a pandas DataFrame, where rows of the dataframe correspond to cases, and columns correspond to dimensions of the problem. The readings within each column of the dataframe are stored as pandas Series objects; the use of Series facilitates simple storage of sparse data or series with non-integer timestamps (such as dates). Further, if the loaded problem is a classification problem, the standard loading functionality within sktime will return the class values in a separate index-aligned numpy array (with an option to combine X and Y into a single dataframe for high-level task construction). For example, for a problem with n cases that each have data across c dimensions:\n\n DataFrame: \n index | dim_0 | dim_1 | ... | dim_c-1\n 0 | pd.Series | pd.Series | pd.Series | pd.Series\n 1 | pd.Series | pd.Series | pd.Series | pd.Series\n ... | ... | ... | ... | ... \n n | pd.Series | pd.Series | pd.Series | pd.Series\n\nAnd if the data is a classification problem, a separate (index-aligned) array will be returned with the class labels:\n\n index | class_val \n 0 | int \n 1 | int \n ... | ...\n n | int \n",
"_____no_output_____"
],
[
"## Loading from .ts file to pandas DataFrame\n\nA dataset can be loaded from a .ts file using the following method in sktime.utils.load_data.py:\n \n load_from_tsfile_to_dataframe(full_file_path_and_name, replace_missing_vals_with='NaN')\n \nThis can be demonstrated using the Gunpoint problem that is included in sktime under sktime/datasets/data",
"_____no_output_____"
]
],
[
[
"from sktime.utils.load_data import load_from_tsfile_to_dataframe\n\ntrain_x, train_y = load_from_tsfile_to_dataframe(\"../sktime/datasets/data/GunPoint/GunPoint_TRAIN.ts\") \ntest_x, test_y = load_from_tsfile_to_dataframe(\"../sktime/datasets/data/GunPoint/GunPoint_TEST.ts\") ",
"_____no_output_____"
]
],
[
[
"Train and test partitions of the GunPoint problem have been loaded into dataframes with associated arrays for class values. As an example, below are the first 5 rows from the train_x and train_y:",
"_____no_output_____"
]
],
[
[
"train_x.head()",
"_____no_output_____"
],
[
"train_y[0:5]",
"_____no_output_____"
]
],
[
[
"## Loading from Weka ARFF files\n\nIt is also possible to load data from Weka's attribute-relation file format (ARFF) files. This is the data format used by researchers at the University of East Anglia (available from www.timeseriesclassification.com ). The `load_from_arff_to_dataframe` method in `sktime.utils.load_data` supports reading both univariate and multivariate problems. Examples are shown below using the GunPoint problem again (this time loading from ARFF) and also the multivariate BasicMotions problem. \n\n### Loading the univariate GunPoint problem from ARFF",
"_____no_output_____"
]
],
[
[
"from sktime.utils.load_data import load_from_arff_to_dataframe\n\nX, y = load_from_arff_to_dataframe(\"../sktime/datasets/data/GunPoint/GunPoint_TRAIN.arff\")\nX.head()",
"_____no_output_____"
]
],
[
[
"### Loading the multivariate BasicMotions problem from ARFF",
"_____no_output_____"
]
],
[
[
"X, y = load_from_arff_to_dataframe(\"../sktime/datasets/data/BasicMotions/BasicMotions_TRAIN.arff\")\nX.head()",
"_____no_output_____"
]
],
[
[
"## Loading from UCR .tsv Format Files\n\nA further option is to load data into sktime from tab separated value (.tsv) files, as used by researchers at the University of Riverside, California (available at https://www.cs.ucr.edu/~eamonn/time_series_data_2018 ). The `load_from_ucr_tsv_to_dataframe` method in `sktime.utils.load_data` supports reading univariate problems. An example with GunPoint is given below to demonstrate equivilence with loading from ARFF and .ts file formats. \n\n### Loading the univariate GunPoint problem from .tsv",
"_____no_output_____"
]
],
[
[
"from sktime.utils.load_data import load_from_ucr_tsv_to_dataframe\n\nX, y = load_from_ucr_tsv_to_dataframe(\"../sktime/datasets/data/GunPoint/GunPoint_TRAIN.tsv\")\nX.head()",
"_____no_output_____"
]
],
[
[
"## Using long-format data with sktime \n\nIt is also possible to use data from sources other than .ts and .arff files by manually shaping the data into the format described above. For convenience, a helper function is also provided to convert long-format data into sktime-formatted data in the `from_long_to_nested` method in `sktime.utils.load_data` (with assumptions made on how the data is initially formatted). \n\nThe method converts rows from a long-table schema data frame assuming each row contains information for: \n\n`case_id, dimension_id, reading_id, value`\n\nwhere `case_id` is an id to identify a specific case in the data, `dimension_id` is an integer between 0 and d-1 for d dimensions in the data, `reading_id` is the index of this observation for the associated `case_id` and `dimension_id`, and `value` is the actual value of the observation. E.g.:\n\n | case_id | dim_id | reading_id | value\n ------------------------------------------------\n 0 | int | int | int | double \n 1 | int | int | int | double\n 2 | int | int | int | double\n 3 | int | int | int | double\n\nTo demonstrate this functionality the method below creates a dataset with a given number of cases, dimensions and observations:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\ndef generate_example_long_table(num_cases=50, series_len=20, num_dims=2):\n\n rows_per_case = series_len*num_dims\n total_rows = num_cases*series_len*num_dims\n\n case_ids = np.empty(total_rows, dtype=np.int)\n idxs = np.empty(total_rows, dtype=np.int)\n dims = np.empty(total_rows, dtype=np.int)\n vals = np.random.rand(total_rows)\n\n for i in range(total_rows):\n case_ids[i] = int(i/rows_per_case)\n rem = i%rows_per_case\n dims[i] = int(rem/series_len)\n idxs[i] = rem%series_len\n\n df = pd.DataFrame()\n df['case_id'] = pd.Series(case_ids)\n df['dim_id'] = pd.Series(dims)\n df['reading_id'] = pd.Series(idxs)\n df['value'] = pd.Series(vals)\n return df",
"_____no_output_____"
]
],
[
[
"The following example generates a long-format table with 50 cases, each with 4 dimensions of length 20:",
"_____no_output_____"
]
],
[
[
"X = generate_example_long_table(num_cases=50, series_len=20, num_dims=4)\nX.head()",
"_____no_output_____"
],
[
"X.tail()",
"_____no_output_____"
]
],
[
[
"As shown below, applying the `from_long_to_nested` method returns a sktime-formatted dataset with individual dimensions represented by columns of the output dataframe:",
"_____no_output_____"
]
],
[
[
"from sktime.utils.load_data import from_long_to_nested \nX_nested = from_long_to_nested(X)\nX_nested.head()",
"_____no_output_____"
],
[
"X_nested.iloc[0][0].head()",
"_____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"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece6cf17b2499010a6912bc5b7193fa97299fa1d | 388,192 | ipynb | Jupyter Notebook | 5.Data-Manipulation-Numpy.ipynb | dsciencelabs/Py-Ebook | c9665929137e61ae6fdf922d23a52585b62eaac0 | [
"MIT"
] | null | null | null | 5.Data-Manipulation-Numpy.ipynb | dsciencelabs/Py-Ebook | c9665929137e61ae6fdf922d23a52585b62eaac0 | [
"MIT"
] | null | null | null | 5.Data-Manipulation-Numpy.ipynb | dsciencelabs/Py-Ebook | c9665929137e61ae6fdf922d23a52585b62eaac0 | [
"MIT"
] | null | null | null | 145.663039 | 337,642 | 0.898576 | [
[
[
"# Numpy \n\n\n\n* Basic library used in scientific calculations\n\n* Linear algebra, machine learning, data science\n\n* Multi-dimensional arrays\n\n* Fast access to multidimensional arrays\n\n* The difference from the lists is having a fixed size.\n\n\n",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"a = np.array([1,2,3,4,5]) # 1st-degree array, vector",
"_____no_output_____"
],
[
"type(a)",
"_____no_output_____"
],
[
"a.shape ",
"_____no_output_____"
],
[
"a.ndim # return the dimension of an array",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"print(a[0])\nprint(a[3])\nprint(a[2])",
"1\n4\n3\n"
],
[
"a[2] = 8\n\nprint(a)",
"[1 2 8 4 5]\n"
],
[
"b = np.array([[1,2,3,4],\n [5,6,7,8]]) #2nd-degree array",
"_____no_output_____"
],
[
"b",
"_____no_output_____"
],
[
"b.ndim",
"_____no_output_____"
],
[
"b.shape # 2nd-degree array with 2 row, 4 col.",
"_____no_output_____"
],
[
"b",
"_____no_output_____"
],
[
"print(b[0,0]) \nprint(b[1,0]) \nprint(b[1,1]) #1st item of 1st row",
"1\n5\n6\n"
],
[
"print(b[0,0],b[1,0],b[1,1])",
"1 5 6\n"
],
[
"c = np.array([[1,2,3],\n [4,5,6],\n [7,8,9]])",
"_____no_output_____"
],
[
"c",
"_____no_output_____"
],
[
"c.ndim",
"_____no_output_____"
],
[
"c.shape",
"_____no_output_____"
],
[
"d = np.array([[[1,2,3],\n [4,5,6],\n [7,8,9]]])",
"_____no_output_____"
],
[
"d",
"_____no_output_____"
],
[
"d.ndim # 3-dimension array",
"_____no_output_____"
],
[
"d.shape",
"_____no_output_____"
],
[
"d[0,1,1]",
"_____no_output_____"
]
],
[
[
"### Arrays with Special Values",
"_____no_output_____"
]
],
[
[
"#Zero Array\n\n\ns = np.zeros((2,2))\n\nprint(s)",
"[[0. 0.]\n [0. 0.]]\n"
],
[
"s2 = np.ones((2,3)).astype(\"int64\").dtype\n\nprint(s2)",
"int64\n"
],
[
"s2 = np.ones((2,3))\nprint(s2)",
"[[1. 1. 1.]\n [1. 1. 1.]]\n"
],
[
"\ns3 = np.full((3,3),8)\n\nprint(s3)",
"[[8 8 8]\n [8 8 8]\n [8 8 8]]\n"
],
[
"# It creates a series of randomly determined elements according to the state of the memory.\n\ns4 = np.empty((4,5))\n\nprint(s4)",
"[[9.27679712e-312 6.27463370e-322 0.00000000e+000 0.00000000e+000\n 1.42417900e-306]\n [5.30276956e+180 1.57076922e-076 4.57487963e-071 4.66499561e-086\n 3.35959356e-143]\n [6.01433264e+175 6.93885958e+218 5.56218858e+180 3.94356143e+180\n 3.72782491e-057]\n [7.80064249e-043 6.52055591e-042 9.35008708e-067 4.41198586e-143\n 1.50008929e+248]]\n"
],
[
"#diagonal array\n\ns5 = np.eye(4)\n\nprint(s5)",
"[[1. 0. 0. 0.]\n [0. 1. 0. 0.]\n [0. 0. 1. 0.]\n [0. 0. 0. 1.]]\n"
],
[
"s7 = np.arange(0,10,1) \n\nprint(s7)",
"[0 1 2 3 4 5 6 7 8 9]\n"
],
[
"s8 = np.linspace(2,3,5)\n\nprint(s8)",
"[2. 2.25 2.5 2.75 3. ]\n"
],
[
"s6 = np.random.random((5,5)) \n\nprint(s6)",
"[[0.76340755 0.53471369 0.46762585 0.85171004 0.95582832]\n [0.70299103 0.15913386 0.7042347 0.38874101 0.93434943]\n [0.78667396 0.61890382 0.4776483 0.22138073 0.45374143]\n [0.57427484 0.7634074 0.71862918 0.15050893 0.37722183]\n [0.27245849 0.2875156 0.25576563 0.28632725 0.64980458]]\n"
],
[
"array_random = np.random.randint(5,10, size = 10)\narray_random.shape ",
"_____no_output_____"
],
[
"np.random.randint(5,10, size= (4,4))",
"_____no_output_____"
],
[
"#reshape\n\nd2 = np.random.randint(5,10, size = (5,3))\n\nprint(d2)\n\nprint(d2.shape)",
"[[7 6 6]\n [7 7 9]\n [8 6 8]\n [9 5 8]\n [8 7 9]]\n(5, 3)\n"
],
[
"d2.reshape(3,5) #The original matrix and the new one must have the same number of items.",
"_____no_output_____"
],
[
"d2.reshape(15,1)",
"_____no_output_____"
],
[
"d3 = np.random.randint(5,10, size = (5,3))\n\nprint(d3)",
"[[9 9 8]\n [5 8 6]\n [5 5 7]\n [9 7 8]\n [9 9 7]]\n"
],
[
"d3 = d3.ravel()\n\nprint(d3)",
"[9 9 8 5 8 6 5 5 7 9 7 8 9 9 7]\n"
],
[
"d3.shape",
"_____no_output_____"
],
[
"d3.dtype",
"_____no_output_____"
],
[
"d3.astype(\"int64\").dtype\nd3",
"_____no_output_____"
],
[
"d3 = d3.reshape(3,5)",
"_____no_output_____"
],
[
"d3",
"_____no_output_____"
],
[
"d3.max()",
"_____no_output_____"
],
[
"d3.min()",
"_____no_output_____"
],
[
"d3[::-1]",
"_____no_output_____"
],
[
"news = np.random.randint(1,100,10)\n\nprint(news)",
"[79 20 99 85 42 69 54 24 42 10]\n"
],
[
"type(news)",
"_____no_output_____"
],
[
"news.ndim",
"_____no_output_____"
],
[
"news.shape",
"_____no_output_____"
],
[
"news.argmax()",
"_____no_output_____"
],
[
"news.argmin()",
"_____no_output_____"
],
[
"news.mean()",
"_____no_output_____"
]
],
[
[
"## Stacking",
"_____no_output_____"
]
],
[
[
"a = np.array([[1,2,3],[4,5,6]])\n\nb = np.array([[6,5,4], [3,2,1]])",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"b",
"_____no_output_____"
],
[
"np.vstack((a,b)) #vertical stacking",
"_____no_output_____"
],
[
"np.hstack((a,b)) #horizontal stacking",
"_____no_output_____"
]
],
[
[
"## Concatenation",
"_____no_output_____"
]
],
[
[
"myArray = np.array([0,1,2,3,4,5,6,7,8,9]).reshape(5,2)\n\nprint(myArray)",
"[[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]\n"
],
[
"print(np.concatenate([myArray,myArray], axis = 0)) #vertical ",
"[[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]\n [0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]\n"
],
[
"print(np.concatenate([myArray,myArray], axis = 1)) #horizontal",
"[[0 1 0 1]\n [2 3 2 3]\n [4 5 4 5]\n [6 7 6 7]\n [8 9 8 9]]\n"
]
],
[
[
"## Slicing",
"_____no_output_____"
]
],
[
[
"a = np.array([[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12]])\n\nb = a[:2, 1:3] \n\nprint(b)",
"[[2 3]\n [6 7]]\n"
],
[
"print(a[0,1])",
"2\n"
],
[
"b[0,0] = 77 \n\nprint(a[0,1])",
"77\n"
],
[
"a",
"_____no_output_____"
],
[
"line1 = a[1,:] \nline2 = a[1:2, :] \nline3 = a[[1],:] ",
"_____no_output_____"
],
[
"print(line1, line1.shape)\nprint(line2, line2.shape)\nprint(line3, line3.shape)",
"[5 6 7 8] (4,)\n[[5 6 7 8]] (1, 4)\n[[5 6 7 8]] (1, 4)\n"
],
[
"a",
"_____no_output_____"
],
[
"col1 = a[:,1]\ncol2 = a[:, 1:2]\n\nprint(col1, col1.shape)\nprint(col2, col2.shape)",
"[77 6 10] (3,)\n[[77]\n [ 6]\n [10]] (3, 1)\n"
],
[
"col2.ndim",
"_____no_output_____"
],
[
"col1.ndim",
"_____no_output_____"
],
[
"t = np.array([[1,2],\n [3,4],\n [5,6]])\n\nprint(t[[0,1,2],[0,1,0]]) ",
"[1 4 5]\n"
],
[
"print(np.array([t[0,0], t[1,1], t[2,0]]))",
"[1 4 5]\n"
],
[
"s = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])\n\nprint(s)",
"[[ 1 2 3]\n [ 4 5 6]\n [ 7 8 9]\n [10 11 12]]\n"
],
[
"indis = np.array([0,2,0,1])",
"_____no_output_____"
],
[
"indis",
"_____no_output_____"
],
[
"print(s[np.arange(4), indis]) #([0,1,2,3],[0,2,0,1]) ",
"[ 1 6 7 11]\n"
]
],
[
[
"## Aritmetic Operations",
"_____no_output_____"
]
],
[
[
"x = np.array([[1,2],[3,4]], dtype= np.float64)\ny = np.array([[5,6],[7,8]], dtype= np.float64)\n\n\nprint(x+y)\n\nprint(np.add(x,y))",
"_____no_output_____"
],
[
"print(x-y)\n\nprint(np.subtract(x,y))",
"_____no_output_____"
],
[
"print(x*y)\n\nprint(np.subtract(x,y))",
"[[ 5. 12.]\n [21. 32.]]\n[[-4. -4.]\n [-4. -4.]]\n"
],
[
"print(np.dot(x,y)) #This function returns the dot product of two arrays.",
"[[19. 22.]\n [43. 50.]]\n"
],
[
"# (2,3) ve (3,2)\n# (2,2) ve (2,3)",
"_____no_output_____"
],
[
"print(x/y)\n\nprint(np.divide(x,y))",
"[[0.2 0.33333333]\n [0.42857143 0.5 ]]\n[[0.2 0.33333333]\n [0.42857143 0.5 ]]\n"
],
[
"s = np.array([[4,9],[16,81]], dtype = np.float64)\n\nprint(np.sqrt(s))",
"[[2. 3.]\n [4. 9.]]\n"
],
[
"s = np.array([[4,9],[16,81]], dtype = np.float64)\n\nprint(np.square(s))",
"[[ 16. 81.]\n [ 256. 6561.]]\n"
],
[
"#Calculate the exponential of all elements in the input array\n\ns = np.array([[4,9],[16,81]], dtype = np.float64)\nprint(np.exp(s))",
"_____no_output_____"
],
[
"v = np.array([10,100,1000,10000,100000,1000000])\n\nprint(np.log(v))",
"[ 2.30258509 4.60517019 6.90775528 9.21034037 11.51292546 13.81551056]\n"
],
[
"t = np.array([np.pi/6, np.pi/2, np.pi/3])\n\nnp.sin(t)",
"_____no_output_____"
]
],
[
[
"### Dot Product\n\n\ncredit: https://algebra1course.files.wordpress.com/",
"_____no_output_____"
]
],
[
[
"x = np.array([[1,2],[3,4]])\ny = np.array([[5,6],[7,8]])\n\na = np.array([9,10])\nb = np.array([11,12])\n\n\nprint(a.dot(b))\n\nprint(np.dot(a,b))",
"219\n219\n"
],
[
"print(x.dot(a))\n\nprint(np.dot(a,x))",
"[29 67]\n[39 58]\n"
],
[
"\nprint(y.dot(b))\n\nprint(np.dot(y,b))",
"[127 173]\n[127 173]\n"
],
[
"x = np.array([[1,2],[3,4]])\n\nprint(np.sum(x))\n\nprint(np.sum(x, axis = 0))\n\nprint(np.sum(x, axis = 1))",
"10\n[4 6]\n[3 7]\n"
]
],
[
[
"## Transpose",
"_____no_output_____"
]
],
[
[
"x = np.array([[1,2],\n [3,4]])\n\n\nprint(x.T)",
"[[1 3]\n [2 4]]\n"
],
[
"v = np.array([[1,2,3]])\n\n\nprint(v.T)",
"[[1]\n [2]\n [3]]\n"
],
[
"\nt = np.array([[1,2,3]])\n\n\nprint(t)\n\nprint(t.shape)\n\nprint(t.T)\n\nv = t.T\n\nprint(v.shape)",
"[[1 2 3]]\n(1, 3)\n[[1]\n [2]\n [3]]\n(3, 1)\n"
],
[
"#Data Type Conversion\n\nx = np.array([1,2,2.5])\n\nprint(x)\n\nx = x.astype(int)\n\nprint(x)",
"[1. 2. 2.5]\n[1 2 2]\n"
],
[
"#Dimension Expansion\n\ny = np.array([1,2])\n\nprint(y.shape)\n\ny = np.expand_dims(y, axis = 0)\n\nprint(y.shape)\n\ny = np.expand_dims(y, axis = 0)\n\nprint(y.shape)\n\ny = np.expand_dims(y, axis = 0)\n\nprint(y.shape)\nprint(type(y))\nprint(y.ndim)\nprint(y.reshape(2,1,1,1))",
"(2,)\n(1, 2)\n(1, 1, 2)\n(1, 1, 1, 2)\n<class 'numpy.ndarray'>\n4\n[[[[1]]]\n\n\n [[[2]]]]\n"
],
[
"x = np.array([1,2])\n\nprint(x.shape)\n\nx = np.expand_dims(x, axis = 1)\n\nprint(x.shape)\n\nx = np.expand_dims(x, axis = 1)\n\nprint(x.shape)\n\nx = np.expand_dims(x, axis = 1)\n\nprint(x.shape)",
"(2,)\n(2, 1)\n(2, 1, 1)\n(2, 1, 1, 1)\n"
]
]
] | [
"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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece6d0282e47115091338d81576f7c958a1901b9 | 4,244 | ipynb | Jupyter Notebook | db2json.ipynb | DB2-Samples/Db2re | 6904cebb97d71ac4ba432eca9f97588a44e0e3bf | [
"Apache-2.0"
] | 7 | 2018-11-19T05:05:51.000Z | 2020-11-23T07:52:09.000Z | db2json.ipynb | DB2-Samples/Db2re | 6904cebb97d71ac4ba432eca9f97588a44e0e3bf | [
"Apache-2.0"
] | 1 | 2021-06-20T06:32:05.000Z | 2021-06-20T06:39:23.000Z | db2json.ipynb | DB2-Samples/Db2re | 6904cebb97d71ac4ba432eca9f97588a44e0e3bf | [
"Apache-2.0"
] | 18 | 2018-10-09T14:33:58.000Z | 2021-09-26T20:42:53.000Z | 19.46789 | 106 | 0.457587 | [
[
[
"# Db2 Jupyter Notebook Macros",
"_____no_output_____"
],
[
"## JSON to BSON",
"_____no_output_____"
]
],
[
[
"%%sql macro j2b\n if {argc} != 1\n echo Syntax: %j2b(value)\n exit\n endif\nSYSTOOLS.JSON2BSON({1})",
"_____no_output_____"
]
],
[
[
"## BSON to JSON",
"_____no_output_____"
]
],
[
[
"%%sql macro b2j\n if {argc} != 1\n echo Syntax: %b2j(value)\n exit\n endif\nSYSTOOLS.BSON2JSON({1})",
"_____no_output_____"
]
],
[
[
"## JSON String Column",
"_____no_output_____"
]
],
[
[
"%%sql macro js\n if {argc} = 3\n TRIM(LEFT(JSON_VAL({1},'{2}','s:{3}'),{3}))\n else\n echo Syntax: #js( json_column, field ,column_size] )\n exit\n endif",
"_____no_output_____"
]
],
[
[
"## JSON Integer Column",
"_____no_output_____"
]
],
[
[
"%%sql macro ji\n if {argc} = 2\n JSON_VAL({1},'{2}','i')\n else \n echo Syntax: #ji( [json_column,] field )\n exit\n endif",
"_____no_output_____"
]
],
[
[
"## JSON Decimal Column",
"_____no_output_____"
]
],
[
[
"%%sql macro jd\n if {argc} = 3\n CAST (JSON_VAL({1},'{2}','n') AS DECIMAL({3}))\n else\n echo Syntax: #jd( json_column, field ,'precision,scale')\n exit\n endif",
"_____no_output_____"
]
],
[
[
"## JSON Date Column",
"_____no_output_____"
]
],
[
[
"%%sql macro jdate\n if {argc} = 2 \n CAST (JSON_VAL({1},'{2}','s:10') AS DATE)\n else\n echo Syntax: #jdate( [json_column,] field )\n exit\n endif",
"_____no_output_____"
]
],
[
[
"## JSON Array Macro",
"_____no_output_____"
]
],
[
[
"%%sql macro jsonarray \nif {argc} < 4\n echo Syntax: jsonarray(table_name, pk, json_column, array [,where=\"optional where clause\"])\n exit\nendif\nvar table {1}\nvar pk {2}\nvar js_column {3}\nvar array {4}\n\njsonarray(pk,item) as \n (\n select {pk},systools.json2bson(items.value) \n from {table}, \n table( systools.json_table({js_column},'{array}','s:2048') ) as items\n if {where} <> null\n where {where} \n endif \n )",
"_____no_output_____"
]
],
[
[
"#### Credits: IBM 2018, George Baklarz [[email protected]]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
ece6dce1fc357e7340f7c36a239b32df34c0d4db | 444,425 | ipynb | Jupyter Notebook | preprocess/check-ICCV-MAI-image-size.ipynb | deepcam-cn/3D-CNN-BERT-COVID19 | 58adc7d570a016b48c48829e26b1f326bba91d4a | [
"MIT"
] | 1 | 2021-07-15T17:53:41.000Z | 2021-07-15T17:53:41.000Z | preprocess/check-ICCV-MAI-image-size.ipynb | deepcam-cn/3D-CNN-BERT-COVID19 | 58adc7d570a016b48c48829e26b1f326bba91d4a | [
"MIT"
] | null | null | null | preprocess/check-ICCV-MAI-image-size.ipynb | deepcam-cn/3D-CNN-BERT-COVID19 | 58adc7d570a016b48c48829e26b1f326bba91d4a | [
"MIT"
] | null | null | null | 53.726426 | 3,465 | 0.611001 | [
[
[
"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport shutil\nfrom tqdm import tqdm",
"_____no_output_____"
],
[
"covidx_dir = '/media/ubuntu/MyHDataStor2/datasets/COVID-19/ICCV-MIA/'\ncovidx_img_dir= covidx_dir \n\nprint(covidx_dir)\nprint(covidx_img_dir)",
"/media/ubuntu/MyHDataStor2/datasets/COVID-19/ICCV-MIA/\n/media/ubuntu/MyHDataStor2/datasets/COVID-19/ICCV-MIA/\n"
],
[
"subsets = ['train','val']\nclasses = [\"covid\",\"non-covid\"]\n\ncount = 0 \n\nfor subset in subsets: \n\n for c in classes:\n \n print(\"subset = {}, class = {}\".format(subset,c))\n scans = os.listdir(covidx_img_dir+\"{}/{}/\".format(subset,c) )\n #print(scans)\n\n pbar = tqdm(total = len(scans))\n for s in scans: \n \n pbar.update()\n \n files = os.listdir(covidx_img_dir+\"{}/{}/{}\".format(subset,c,s) )\n print(files)\n \n for f in files: \n \n f_full = covidx_img_dir+\"{}/{}/{}/{}\".format(subset,c,s,f) \n if f.startswith('._'):\n continue \n \n img = cv2.imread(f_full, cv2.IMREAD_UNCHANGED)\n #print(img.shape) \n \n if img is None: \n print(\"file {} has problem\".format(f_full))\n input(\"dbg image file\")\n continue \n \n if img.shape != (512,512):\n \n print(\"file {} shape = {}\".format(f_full,img.shape)) \n img = cv2.resize(img,(512,512),cv2.INTER_LINEAR)\n cv2.imwrite(f_full,img)\n count += 1 \n\nprint(count) \n",
"\n 0%| | 0/687 [00:00<?, ?it/s]\u001b[A"
],
[
"#use the following code on test datset \nsubsets = [\"subset{}\".format(x) for x in range(1,9)]\nprint(subsets) \n",
"['subset1', 'subset2', 'subset3', 'subset4', 'subset5', 'subset6', 'subset7', 'subset8']\n"
],
[
"subsets = ['subset6']\n\nfor subset in subsets: \n \n count = 0 \n subset_dir = 'test/' + subset \n #print(subset_dir) \n scan_dirs = os.listdir(covidx_img_dir+subset_dir)\n \n pbar = tqdm(total=len(scan_dirs))\n \n for s in scan_dirs:\n \n pbar.update() \n \n s_dir = subset_dir + '/' + s \n #print(s_dir) \n files = os.listdir(covidx_img_dir+s_dir) \n files = [x for x in files if not x.startswith('.')] \n files.sort(key=lambda x: int(x.split('.')[0]) ) \n #print(files) \n for f in files: \n f_full = covidx_img_dir+ s_dir + '/' + f \n #print(f_path) \n img = cv2.imread(f_full, cv2.IMREAD_UNCHANGED)\n #print(img.shape)\n if img is None: \n print(\"file {} has problem\".format(f_full))\n input(\"dbg image file\") \n continue \n if img.shape != (512,512): \n print(\"file {} shape = {}\".format(f_full,img.shape)) \n img = cv2.resize(img,(512,512),cv2.INTER_LINEAR)\n cv2.imwrite(f_full,img)\n count += 1 \n\n print(\"subset = {}, count = {}\".format(subset,count))\n \n \n ",
"\n\n\n\n\n\n\n\n\n\n 0%| | 0/450 [00:00<?, ?it/s]\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A\u001b[A"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
ece6f69e21645ee10a01ec6ec21c6ce5d349519a | 87,469 | ipynb | Jupyter Notebook | notebooks/reward_learning/ddl.ipynb | abhishekunique/RND-ashwin | f8bcf3c593df2dacc0efba0875533be71ccb5011 | [
"MIT"
] | null | null | null | notebooks/reward_learning/ddl.ipynb | abhishekunique/RND-ashwin | f8bcf3c593df2dacc0efba0875533be71ccb5011 | [
"MIT"
] | 7 | 2020-09-25T22:41:46.000Z | 2022-03-12T00:37:25.000Z | notebooks/reward_learning/ddl.ipynb | abhishekunique/RND-ashwin | f8bcf3c593df2dacc0efba0875533be71ccb5011 | [
"MIT"
] | null | null | null | 98.835028 | 51,684 | 0.817684 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport pickle\nimport gzip\nimport tensorflow as tf\nimport glob\nimport math\nimport skimage\nimport json\nfrom matplotlib.patches import Rectangle",
"_____no_output_____"
],
[
"from softlearning.replay_pools.utils import get_replay_pool_from_variant\n\ndef get_grid_vals(env, n_samples):\n n_samples = 50\n obs_space = env.observation_space['state_observation']\n xs = np.linspace(obs_space.low[0], obs_space.high[0], n_samples)\n ys = np.linspace(obs_space.low[1], obs_space.high[1], n_samples)\n xys = np.meshgrid(xs, ys)\n return np.array(xys).transpose(1, 2, 0).reshape((n_samples * n_samples, 2)), xys\n\ndef get_replay_pool(checkpoint, checkpoint_dir):\n from softlearning.replay_pools.utils import get_replay_pool_from_variant\n\n variant = checkpoint['variant']\n train_env = checkpoint['training_environment']\n replay_pool = get_replay_pool_from_variant(variant, train_env)\n\n replay_pool_path = os.path.join(checkpoint_dir, 'replay_pool.pkl')\n replay_pool.load_experience(replay_pool_path)\n return replay_pool\n\ndef plot_trajectories(checkpoint, checkpoint_dir, num_trajectories=10):\n replay_pool = get_replay_pool(checkpoint, checkpoint_dir)\n trajectories = replay_pool.last_n_batch(100 * num_trajectories)['observations']['state_observation'] \\\n .reshape(num_trajectories, 100, -1)\n for i in range(num_trajectories):\n plt.plot(trajectories[i,:,0], trajectories[i,:,1], color='w', linewidth=1)",
"_____no_output_____"
]
],
[
[
"## Specify the Experiment Directory",
"_____no_output_____"
]
],
[
[
"common_dir = '/Users/kevintli/rail/data/ray_results'\nuniverse = 'gym'\ndomain = 'Point2D'\ntask = 'Maze-v0'",
"_____no_output_____"
],
[
"base_path = os.path.join(common_dir, universe, domain, task)\nexps = sorted(list(glob.iglob(os.path.join(base_path, '*'))))\nfor i, exp in enumerate(exps):\n print(f'{i} \\t {exp.replace(base_path, \"\")}')\n \nexp_choice = int(input('\\n Which experiment do you want to analyze? (ENTER A NUMBER) \\t'))\n\nexp_path = exps[exp_choice]\nprint('\\n')\nseeds = sorted(list(glob.iglob(os.path.join(exp_path, '*'))))\nseeds = [seed for seed in seeds if os.path.isdir(seed)]\nfor i, seed in enumerate(seeds):\n print(f'{i} \\t {seed.replace(exp_path, \"\")}')\n \n# TODO: Extend to analyzing all seeds\nseed_choice = int(input('\\n Which seed do you want to analyze? (ENTER A NUMBER) \\t'))\n\nseed_path = seeds[seed_choice]\n\nprint('PATH:\\n', seed_path)",
"0 \t /2020-05-27T16-46-37-ddl_maze\n1 \t /2020-05-27T18-08-07-ddl_maze_count\n2 \t /2020-05-28T15-34-01-dynamics_aware_vice\n\n Which experiment do you want to analyze? (ENTER A NUMBER) \t1\n\n\n0 \t /id=b10d1e58-seed=5665_2020-05-27_18-08-08m_k02ani\n1 \t /id=b10db96c-seed=2276_2020-05-27_18-08-083tnxtdfm\n2 \t /id=b10e2a3c-seed=8785_2020-05-27_18-08-082a4988sb\n3 \t /id=b10e9e4a-seed=9604_2020-05-27_18-08-086u1x903v\n4 \t /id=b111f374-seed=8761_2020-05-27_18-08-088ahet3e6\n5 \t /id=b11364c0-seed=6292_2020-05-27_18-08-08k1txd1bx\n6 \t /id=b11aefec-seed=2893_2020-05-27_18-08-09_vlnjkb9\n7 \t /id=b11b69c2-seed=2745_2020-05-27_18-08-09a2k9l1i5\n8 \t /id=b1222924-seed=3131_2020-05-27_20-21-51vik2awem\n9 \t /id=b122a0e8-seed=9098_2020-05-27_20-23-31loo8zrsu\n10 \t /id=b12a836c-seed=511_2020-05-27_20-25-01b16f1kt4\n11 \t /id=b12af266-seed=9778_2020-05-27_20-25-03upld8wzv\n12 \t /id=b135346a-seed=3899_2020-05-27_20-43-39om47n0aq\n13 \t /id=b139866e-seed=5587_2020-05-27_20-44-35__q3ymuj\n14 \t /id=b13acb1e-seed=5625_2020-05-27_22-11-57zo2l3xcb\n15 \t /id=b13c1780-seed=2967_2020-05-27_22-14-23rmh5pmcv\n\n Which seed do you want to analyze? (ENTER A NUMBER) \t0\nPATH:\n /Users/kevintli/rail/data/ray_results/gym/Point2D/Maze-v0/2020-05-27T18-08-07-ddl_maze_count/id=b10d1e58-seed=5665_2020-05-27_18-08-08m_k02ani\n"
],
[
"# Print hyperparameters\n\nwith open(os.path.join(seed_path, 'params.pkl'), 'rb') as f:\n params = pickle.load(f)\n\n# print(json.dumps(params, indent=4))\nhyperparams = {\n 'use_count_reward': params['environment_params']['training']['kwargs'].get('use_count_reward', False),\n 'discount': params['algorithm_params']['kwargs']['discount'],\n 'ext_reward_coeff': params['algorithm_params']['kwargs']['ext_reward_coeff']\n}\nfor name, value in hyperparams.items():\n print(f\"{name}: {value}\")",
"use_count_reward: True\ndiscount: 0.99\next_reward_coeff: 0.5\n"
]
],
[
[
"## Specify the Checkpoint",
"_____no_output_____"
]
],
[
[
"checkpoint_to_analyze = 200",
"_____no_output_____"
],
[
"checkpoint_dir = os.path.join(seed_path, f'checkpoint_{checkpoint_to_analyze}')\nwith open(os.path.join(checkpoint_dir, 'checkpoint.pkl'), 'rb') as f:\n checkpoint = pickle.load(f)",
"pygame 1.9.4\nHello from the pygame community. https://www.pygame.org/contribute.html\n"
]
],
[
[
"## Load and Visualize Distance Function",
"_____no_output_____"
]
],
[
[
"checkpoint.keys()",
"_____no_output_____"
],
[
"# Load the distance function, goal, and environment, \n# then make distance predictions at points on a 50x50 grid\ndistance_fn = checkpoint['distance_estimator']\ntrain_env = checkpoint['training_environment']\ntarget_pos = train_env.unwrapped._get_obs()['state_desired_goal']\n\nn_samples = 50\ngrid_vals, _ = get_grid_vals(train_env, n_samples)\ngoal_vals = np.repeat(target_pos[None], n_samples * n_samples, axis=0)\ndists = distance_fn.predict([grid_vals, goal_vals])",
"_____no_output_____"
],
[
"# Plot a contour map of distance predictions across the environment\nplt.figure(figsize=(8, 8))\nfrom matplotlib.patches import Rectangle\n\nplt.imshow(train_env.render('rgb_array', width=32, height=32),\n extent=(-4, 4, -4, 4), origin='lower', alpha=0.25, zorder=3)\n\ngrid_vals, xys = get_grid_vals(train_env, 50)\nplt.gca().invert_yaxis()\nplt.contourf(xys[0], xys[1], dists.reshape(xys[0].shape), levels=20, zorder=1)\nplt.colorbar(fraction=0.046, pad=0.04)\n\nplot_trajectories(checkpoint, checkpoint_dir)\n\nif task == 'BoxWall-v1':\n currentAxis = plt.gca()\n currentAxis.add_patch(Rectangle((-2, -2), 4, 4,\n alpha=1, fill=None, linewidth=4))\n \nplt.scatter(*target_pos, marker='*', s=250, color='white', zorder=2)\n\nplt.title(f'd(s, g) for {domain + task} Task @ Checkpoint #{checkpoint_to_analyze}\\n'\n + f'Target Pos: {target_pos}')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Plot Evolution of Distance Function over Many Checkpoints",
"_____no_output_____"
]
],
[
[
"def plot_distance_to_goal(distance_fn, train_env, n_samples=50):\n grid_vals, xys = get_grid_vals(train_env, n_samples)\n dists = distance_fn.predict([grid_vals, goal_vals])\n \n# plt.figure(figsize=(8, 8))\n from matplotlib.patches import Rectangle\n\n plt.imshow(train_env.render('rgb_array', width=32, height=32),\n extent=(-4, 4, -4, 4), origin='lower', alpha=0.25, zorder=3)\n\n plt.gca().invert_yaxis()\n plt.contourf(xys[0], xys[1], dists.reshape(xys[0].shape), levels=20, zorder=1)\n plt.colorbar(fraction=0.046, pad=0.04)\n\n plt.scatter(*target_pos, marker='*', s=250, color='white', zorder=2)",
"_____no_output_____"
],
[
"def plot_grid(imgs, labels=None):\n n_images = len(imgs)\n n_columns = np.sqrt(n_images)\n n_rows = np.ceil(n_images / n_columns) + 1\n plt.figure(figsize=(5 * n_columns, 5 * n_rows))\n for i, img in enumerate(imgs):\n plt.subplot(n_rows, n_columns, i+1)\n plt.axis('off')\n plt.imshow(img)\n if labels is not None:\n plt.title(labels[i], fontsize=20)\n plt.show()",
"_____no_output_____"
],
[
"checkpoint_paths = list(glob.iglob(os.path.join(seed_path, 'checkpoint_*')))\n# Sort by the checkpoint number at the end\ncheckpoint_paths = sorted(checkpoint_paths, key=lambda s: int(s.split(\"_\")[-1]))",
"_____no_output_____"
],
[
"n_plots = len(checkpoint_paths)\nn_columns = int(np.sqrt(n_plots) + 1)\nn_rows = np.ceil(n_plots / n_columns)\nplt.figure(figsize=(5 * n_columns, 5 * n_rows))\n\nimgs = []\nfor i, path in enumerate(checkpoint_paths):\n with open(os.path.join(path, 'checkpoint.pkl'), 'rb') as f:\n checkpoint = pickle.load(f)\n distance_fn = checkpoint['distance_estimator']\n train_env = checkpoint['training_environment']\n plt.subplot(n_rows, n_columns, i+1, aspect=1)\n plot_distance_to_goal(distance_fn, train_env)\n plt.title(int(path.split(\"_\")[-1]), fontsize=20)\n \nplt.show()",
"_____no_output_____"
]
],
[
[
"## Generate GIF of Distance over Time",
"_____no_output_____"
]
],
[
[
"checkpoint_paths = list(glob.iglob(os.path.join(seed_path, 'checkpoint_*')))\n# Sort by the checkpoint number at the end\ncheckpoint_paths = sorted(checkpoint_paths, key=lambda s: int(s.split(\"_\")[-1]))\n\nimgs = []\nfor i, path in enumerate(checkpoint_paths):\n fig = plt.figure(figsize=(8, 8))\n with open(os.path.join(path, 'checkpoint.pkl'), 'rb') as f:\n checkpoint = pickle.load(f)\n distance_fn = checkpoint['distance_estimator']\n train_env = checkpoint['training_environment']\n plot_distance_to_goal(distance_fn, train_env)\n plt.title(int(path.split(\"_\")[-1]), fontsize=20)\n fig.canvas.draw()\n data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n imgs.append(data)",
"_____no_output_____"
],
[
"import imageio\nimageio.mimsave('./test.gif', imgs, duration=1.0)",
"_____no_output_____"
]
],
[
[
"## Plot Ground Truth Rewards",
"_____no_output_____"
]
],
[
[
"feed_dict = {\n 'state_achieved_goal': grid_vals,\n 'state_desired_goal': np.full(grid_vals.shape, fill_value=2)\n}\ntrain_env.unwrapped.reward_type = 'sparse'\ngtr = train_env.unwrapped.compute_rewards(None, feed_dict)\nplt.figure(figsize=(8, 8))\n\nfrom matplotlib.patches import Rectangle\n\nplt.gca().invert_yaxis()\n\nplt.contourf(xys[0], xys[1], gtr.reshape(xys[0].shape))\nplt.colorbar(fraction=0.046, pad=0.04)\n\nplt.scatter([2], [2], color='r')\n\nif task == 'BoxWall-v1':\n currentAxis = plt.gca()\n currentAxis.add_patch(Rectangle((-2, -2), 4, 4,\n alpha=1, fill=None, linewidth=4))\n\nplt.title(f'Ground Truth Reward for {domain + task} Task @ Checkpoint #{checkpoint_to_analyze}')\n\nplt.scatter(*target_pos, marker='*', s=250, color='white')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Qs Visualization",
"_____no_output_____"
]
],
[
[
"# Load the checkpoint\ncheckpoint_to_analyze = 200\ncheckpoint_dir = os.path.join(seed_path, f'checkpoint_{checkpoint_to_analyze}')\n\nwith open(os.path.join(checkpoint_dir, 'checkpoint.pkl'), 'rb') as f:\n checkpoint = pickle.load(f)",
"_____no_output_____"
],
[
"variant = checkpoint['variant']\nenv = checkpoint['training_environment']\ntarget_pos = env.unwrapped._get_obs()['state_desired_goal']",
"_____no_output_____"
],
[
"from softlearning.value_functions.utils import get_Q_function_from_variant",
"_____no_output_____"
],
[
"# Initialize a double value function and load weights from the checkpoint file\nQs = get_Q_function_from_variant(variant, env)\n\nfor i, Q in enumerate(Qs):\n weights_path = os.path.join(checkpoint_dir, f'Qs_{i}')\n Q.load_weights(weights_path)",
"_____no_output_____"
],
[
"# Sample n actions from the full action space.\n# We will plot the worst-case Q value over all of these actions (?)\nn_action_samples = 20\nsample_actions = np.vstack([env.action_space.sample() for _ in range(n_action_samples)])",
"_____no_output_____"
],
[
"# Create a 50x50 grid of coordinates to evaluate\nn_samples = 50\ngrid_vals, xys = get_grid_vals(env, n_samples)",
"_____no_output_____"
],
[
"# Compute Q values at each coordinate\nvalue_estimates = []\nfor pos in grid_vals:\n value_estimates.append(\n np.min([Q.predict([sample_actions,\n np.repeat(pos, n_action_samples).reshape((n_action_samples, -1))])\n for Q in Qs])\n )",
"_____no_output_____"
],
[
"# Plot a contour map of value estimates\nplt.figure(figsize=(8, 8))\nfrom matplotlib.patches import Rectangle\n\nplt.imshow(train_env.render('rgb_array', width=32, height=32),\n extent=(-4, 4, -4, 4), origin='lower', alpha=0.25, zorder=3)\nplt.gca().invert_yaxis()\nplt.contourf(xys[0], xys[1], np.array(value_estimates).reshape(xys[0].shape))\nplt.colorbar(fraction=0.046, pad=0.04)\n\nif task == 'BoxWall-v1':\n currentAxis = plt.gca()\n currentAxis.add_patch(Rectangle((-2, -2), 4, 4,\n alpha=1, fill=None, linewidth=4))\n \nplot_trajectories(checkpoint, checkpoint_dir)\n\nplt.scatter(*target_pos, marker='*', s=250, color='white')\nplt.title(f'Value function estimates for {domain + task} Task @ Checkpoint #{checkpoint_to_analyze}\\n'\n + f'Target Pos: {target_pos}')\nplt.show()",
"_____no_output_____"
],
[
"np.repeat(grid_vals[0], n_action_samples).reshape((n_action_samples, -1))",
"_____no_output_____"
]
],
[
[
"## Visualize Embedding Function",
"_____no_output_____"
]
],
[
[
"embedding_fn = checkpoint['distance_estimator']\ntrain_env = checkpoint['training_environment']\ntarget_pos = train_env.unwrapped._get_obs()['state_desired_goal']\n\nn_samples = 50\ngrid_vals = get_grid_vals(train_env, n_samples)\ngoal_vals = np.repeat(target_pos[None], n_samples * n_samples, axis=0)\ndists = np.linalg.norm(embedding_fn.predict(goal_vals) - embedding_fn.predict(grid_vals), axis=-1)",
"_____no_output_____"
],
[
"plt.figure(figsize=(8, 8))\nfrom matplotlib.patches import Rectangle\n\nplt.imshow(train_env.render('rgb_array', width=256, height=256),\n extent=(-4, 4, -4, 4), origin='lower', alpha=0.25, zorder=3)\n\nplt.gca().invert_yaxis()\nplt.contourf(xys[0], xys[1], dists.reshape(xys[0].shape), levels=300, zorder=1)\nplt.colorbar(fraction=0.046, pad=0.04)\n \nplt.scatter(*target_pos, marker='*', s=250, color='white', zorder=2)\n\nplt.title(f'|phi(g) - phi(s)| for {domain + task} Task @ Checkpoint #{checkpoint_to_analyze}\\n'\n + f'Target Pos: {target_pos}')\nplt.show()",
"_____no_output_____"
],
[
"embedded_goal = embedding_fn.predict(target_pos[None])",
"_____no_output_____"
],
[
"radii = np.arange(0.5, 9, 0.5)\npts_by_radius = []\nfor r in radii:\n embedded_pts = []\n for theta in np.arange(0, 2 * np.pi + np.pi / 30, np.pi / 30):\n dx = r * np.cos(theta)\n dy = r * np.sin(theta)\n pt = target_pos + np.array([dx, dy])\n x, y = pt\n if -4 <= x and x <= 4 and -4 <= y and y <= 4:\n embedded_pt = embedding_fn.predict(pt[None])\n embedded_pts.append(embedded_pt)\n pts_by_radius.append(np.vstack(embedded_pts))",
"_____no_output_____"
],
[
"border_pts = []\nborder_range = np.arange(-4 + 0.1, 4 - 0.1, 0.1).reshape(-1, 1)\nborder_pts.append(np.hstack(\n (np.ones(border_range.shape) * (4 - 0.1), border_range)\n))\nborder_pts.append(np.hstack(\n (np.ones(border_range.shape) * (-4 + 0.1), border_range)\n))\nborder_pts.append(np.hstack(\n (border_range, np.ones(border_range.shape) * (-4 + 0.1))\n))\nborder_pts.append(np.hstack(\n (border_range, np.ones(border_range.shape) * (4 - 0.1))\n))\nborder_pts = np.vstack(border_pts)",
"_____no_output_____"
],
[
"embedded_border = embedding_fn.predict(border_pts)",
"_____no_output_____"
],
[
"plt.figure(figsize=(8, 8))\nplt.scatter(embedded_goal[0][0], embedded_goal[0][1])\nfor pts in pts_by_radius:\n plt.plot(pts[:, 0], pts[:, 1])\nplt.legend(radii)\nplt.title('Trajectory in Embedding Space')\n\nplt.plot(embedded_trajectory[:, 0], embedded_trajectory[:, 1], 'black')\n# plt.quiver(embedded_trajectory[:-1, 0],\n# embedded_trajectory[:-1, 1],\n# embedded_actions[:, 0],\n# embedded_actions[:, 1],\n# color='black',\n# alpha=0.5,\n# linewidth=2,\n# headwidth=4)",
"_____no_output_____"
],
[
"plt.figure(figsize=(8, 8))\n\nplt.imshow(train_env.render('rgb_array', width=256, height=256),\n extent=(-4, 4, -4, 4), origin='lower', alpha=0.25, zorder=3)\nplt.scatter(*target_pos, marker='*', s=250, color='white', zorder=2)\n\ntrajectory = sample_trajectory['observations']['state_observation']\nnext_obs = sample_trajectory['next_observations']['state_observation']\nactions = next_obs - trajectory\nplt.plot(trajectory[:, 0], trajectory[:, 1], 'black')\n\nradii = np.arange(0.5, 9, 0.5)\ncircles = []\nfor r in radii:\n pts = []\n for theta in np.arange(0, 2 * np.pi + np.pi / 30, np.pi / 30):\n dx = r * np.cos(theta)\n dy = r * np.sin(theta)\n pt = target_pos + np.array([dx, dy])\n x, y = pt\n if -4 <= x and x <= 4 and -4 <= y and y <= 4:\n pts.append(np.array([[x, y]]))\n circles.append(np.vstack(pts))\n\nfor circle in circles:\n plt.plot(circle[:, 0], circle[:, 1])\n \nplt.gca().invert_yaxis()\n\nplt.title(f'|phi(g) - phi(s)| for {domain + task} Task @ Checkpoint #{checkpoint_to_analyze}\\n'\n + f'Target Pos: {target_pos}')\nplt.show()",
"_____no_output_____"
],
[
"checkpoint.keys()",
"_____no_output_____"
],
[
"from softlearning.replay_pools.utils import get_replay_pool_from_variant\n\nvariant = checkpoint['variant']\ntrain_env = checkpoint['training_environment']\nreplay_pool = get_replay_pool_from_variant(variant, train_env)\n\nreplay_pool_path = os.path.join(checkpoint_dir, 'replay_pool.pkl')\nreplay_pool.load_experience(replay_pool_path)",
"_____no_output_____"
],
[
"sample_trajectory = replay_pool.last_n_batch(100)",
"_____no_output_____"
],
[
"embedded_trajectory = embedding_fn.predict(sample_trajectory['observations']['state_observation'])\nembedded_actions = embedded_trajectory[1:, :] - embedded_trajectory[:-1, :]",
"_____no_output_____"
]
]
] | [
"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"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece702013878acf005d754507653d1467b47b530 | 11,143 | ipynb | Jupyter Notebook | funflow-tutorial/notebooks/Tutorial2.ipynb | tweag/funflow2 | 95409d5b030070609910914aa3e36c677e60d061 | [
"MIT"
] | 10 | 2020-11-18T20:59:39.000Z | 2021-11-28T07:20:07.000Z | funflow-tutorial/notebooks/Tutorial2.ipynb | tweag/funflow2 | 95409d5b030070609910914aa3e36c677e60d061 | [
"MIT"
] | 35 | 2020-11-18T10:07:29.000Z | 2021-07-21T14:53:22.000Z | funflow-tutorial/notebooks/Tutorial2.ipynb | tweag/funflow2 | 95409d5b030070609910914aa3e36c677e60d061 | [
"MIT"
] | null | null | null | 34.391975 | 414 | 0.609441 | [
[
[
"# Developer's Guide\n\n`funflow` provides a few task types (`SimpleTask`, `StoreTask`, and `DockerTask`) that will suffice for many pipelines, but the package facilitates creation of new task types as needed.\n\nThis tutorial aims to help prospective `funflow` developers get started with task type creation.",
"_____no_output_____"
],
[
"## 1. Creating your own task\n\nIn this tutorial, we will create a task called `CustomTask` by defining its type. We will define our own flow type, and write the functions needed to to run it.",
"_____no_output_____"
],
[
"### Defining the new task\n\nTo define a task for our users, we first have to define a type that represents the task.\n\n> A task is represented by a generalized algebraic data type (GADT) of kind `* -> * -> *`.",
"_____no_output_____"
]
],
[
[
"-- Required language extensions\n{-# LANGUAGE GADTs, StandaloneDeriving #-}\n\n-- Define the representation of a custom task with some String and Int parameters\ndata CustomTask i o where\n CustomTask :: String -> Int -> CustomTask String String\n\n-- Necessary in order to display it\nderiving instance (Show i, Show o) => Show (CustomTask i o)",
"_____no_output_____"
]
],
[
[
"Here, we create a type `CustomTask` with type constructor `CustomTask i o`, and a value constructor `CustomTask` of type `String -> Int -> CustomTask String String`.\n\n`String -> Int -> SomeCustomTask String String` means thatby providing a `String` and an `Int`, the function will give a task that takes a `String` as input and produces a `String` as output.\n\nA new task can be created by using the value constructor:",
"_____no_output_____"
]
],
[
[
"-- An example of instantiation\nCustomTask \"someText\" 42",
"_____no_output_____"
]
],
[
[
"However, a value created this way is a _task_, not a _flow_. To use this value in a flow, we need some more work.",
"_____no_output_____"
],
[
"### From a task to a flow\nThe `Flow` type in fact comes from restricting the more general `ExtendedFlow` type, specifying a fixed collection of task types to support.\nThese tasks types are those defined here in funflow: `SimpleTask`, `StoreTask`, and `DockerTask`, which are declared as `RequiredStrands` in `Funflow.Flow`.\n\nIn other words, a pipeline/workflow typed specifically as `Flow` may comprise tasks of these three types (and only these three), capturing the notion that it's these types with which a `Flow` is compatible. In order to manipulate a flow that can run our _custom_ task (i.e., a value of a new task type), we need to create our own new _flow_ type using `ExtendedFlow`, which is also defined in `Funflow.Flow`:",
"_____no_output_____"
]
],
[
[
"{-# LANGUAGE DataKinds, RankNTypes #-}\nimport Funflow.Flow (ExtendedFlow)\n\ntype MyFlow input output = ExtendedFlow '[ '(\"custom\", CustomTask) ] input output",
"_____no_output_____"
]
],
[
[
"> Prefixing the leading bracket or parenthesis, i.e. `'[ ... ]` and `'( ... )`, denotes a _type-level_ list or tuple, respectively. This syntax is supported by the `OverloadedLabels` extension and is used to distinguish between the ordinary `[]` and `()` are _data_ constructors, building values rather than types. \n> \n> So with `'[ '(\"custom\", CustomTask) ]`, we build a type-level list of type-level tuple, \"labeling\" our custom task type with a name.\n> \n> In `kernmantle`, such a tuple is called a _strand_, and the label facilitates disambiguation among different tasks with the same type.\n\nNow that we have our own type of flow that uses our custom task, we can define how a value of our custom task should be _stranded_, using [`kernmantle`](https://github.com/tweag/kernmantle):",
"_____no_output_____"
]
],
[
[
"{-# LANGUAGE OverloadedLabels #-}\nimport Control.Kernmantle.Rope (strand)\n\nsomeCustomFlow :: String -> Int -> MyFlow String String\nsomeCustomFlow x y = strand #custom (CustomTask x y)",
"_____no_output_____"
]
],
[
[
"This function is called a _smart constructor_.\nIt facilitates the creation of a flow for a user without having to think about strands.\n\nThe `#custom` value is a Haskell label, and must match the string label associated to our task type in the flow type definition (here `\"custom\"`).",
"_____no_output_____"
]
],
[
[
"myFlow :: MyFlow String String\nmyFlow = someCustomFlow \"woop!\" 7",
"_____no_output_____"
]
],
[
[
"### Interpret a task\n\nA strength of `funflow` is separation of the _representation_ of a computation (task) from _implementation_ of that task. More concretely, once it's created a task value has fixed input and output types, but __what it _does___ is not fixed. To specify that, we write an _interpreter function_.\n\nAn interpreter function is executed __before _running_ the flow__.\nIt takes a value of the task type that matches a particular _strand_ (identified by the strand's label) and produces an actual implementation of the task, in compliance with the task's fixed input and output types.\n\nIn our case, we could define that our custom task `CustomTask n s` appends `n` times the string `s` to the input (which is a `String`):",
"_____no_output_____"
]
],
[
[
"import Control.Arrow (Arrow, arr)\n\n-- Helper function that repeats a string n times\nduplicate :: String -> Int -> String\nduplicate s n = concat (replicate n s)\n\n-- Our interpreter\ninterpretCustomTask :: (Arrow a) => CustomTask i o -> a i o\ninterpretCustomTask customTask = case customTask of\n CustomTask s n -> arr (\\input -> input ++ duplicate s n)",
"_____no_output_____"
]
],
[
[
"What happens here is:\n\n1. We get the `customTask` of our type `CustomTask`.\n2. We consider the possible values.\n As we've defined it, `CustomTask` has only one value constructor, but in general a GADT may have multiple value constructors.\n3. Since our function is pure, we can simply wrap it inside of an `Arrow` using `arr`.\n\n`\\input -> input ++ duplicate s n` is the actual function that will be executed when running the pipeline.\n\n> In funflow, pure computation should be wrapped in a `Arrow` while IO operations should wrapped in a `Kleisli IO`.\n> \n> Wrapping in an `Arrow` is done by using `arr`, while wrapping in a `Kleisli IO` is done by using `liftKleisliIO`.\n\n`funflow`'s interpreter functions are defined in the `Funflow.Run` module and can serve as examples as you write your own interpreter functions.",
"_____no_output_____"
],
[
"### Run your custom flow\n\nNow that we have defined a way to run our task, we might as well run our pipeline!\n\nTo run a pipeline typed as `Flow`, funflow provides `runFlow`. Since we've built--in order to include our custom task type--a different type of pipeline (`MyFlow`), though, in order to leverage `runFlow` we first need an additional step. We will use the `weave'` function from `kernmantle`.\n\n> In `kernmantle`, intepreting a task with a function is called _weaving_ a strand.\n>\n> There are multiple function available to weave strands (`weave`, `weave'`, `weave''`, `weaveK`).\n> Almost always, the one you want is `weave'`.",
"_____no_output_____"
]
],
[
[
"import Control.Kernmantle.Rope ((&), weave')\nimport Funflow.Flow (Flow)\n\nweaveMyFlow myFlow = myFlow & weave' #custom interpretCustomTask",
"_____no_output_____"
]
],
[
[
"> `kernmantle`'s `&` operator allows us to \"weave in,\" or \"chain,\" multiple strands, e.g.:\n> ```haskell\n> weaveMyFlow myFlow = myFlow & weave' #custom1 interpretCustomTask1 & weave' #custom2 interpretCustomTask2\n> ```\n\nNow, we can run the resulting flow:",
"_____no_output_____"
]
],
[
[
":opt no-lint\nimport Funflow.Run (runFlow)\n\nrunMyFlow :: MyFlow i o -> i -> IO o\nrunMyFlow myFlow input = runFlow (weaveMyFlow myFlow) input",
"_____no_output_____"
],
[
"runMyFlow myFlow \"Kangaroo goes \" :: IO String",
"_____no_output_____"
]
],
[
[
"> We have to specify the type of the result `IO String` because of some issues with type inference when using GADTs.",
"_____no_output_____"
],
[
"## Going further\n\nSee more about `kernmantle` here: https://github.com/tweag/kernmantle",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
ece7088b5c5beecf804f9ee0d9a260ad3bdb2a78 | 8,576 | ipynb | Jupyter Notebook | code/notebooks/covariance/Covariance Analysis.ipynb | yurong-yang/PorousMediaGan | 48c343381b0c6d1db63f0a826b49b94324339f94 | [
"MIT"
] | 1 | 2021-04-05T08:31:18.000Z | 2021-04-05T08:31:18.000Z | code/notebooks/covariance/Covariance Analysis.ipynb | yurong-yang/PorousMediaGan | 48c343381b0c6d1db63f0a826b49b94324339f94 | [
"MIT"
] | null | null | null | code/notebooks/covariance/Covariance Analysis.ipynb | yurong-yang/PorousMediaGan | 48c343381b0c6d1db63f0a826b49b94324339f94 | [
"MIT"
] | null | null | null | 24.225989 | 150 | 0.538013 | [
[
[
"## Covariance Analysis\n\nBased on the computation of the two-point covariance, we will compute three properties:\n - Slope of the Covariance at the origin $\\frac{dS^{(1)}_2(r)}{dr}|_{r=0}$\n - The specific surface area $S_V$\n - Chord length for each phase $l^{(i)}_C$",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nfrom scipy.optimize import curve_fit\nimport json",
"_____no_output_____"
],
[
"#strings to output and input locations\nbeadpack_dic = {\n \"out_direc\": \"../../../analysis/covariance/beadpack/\",\n \"seed_min\": 43,\n \"seed_max\": 64\n}\n\nberea_dic = {\n \"out_direc\": \"../../../analysis/covariance/berea/\",\n \"seed_min\": 43,\n \"seed_max\": 64\n}\n\nketton_dic = {\n \"out_direc\": \"../../../analysis/covariance/ketton/\",\n \"seed_min\": 43,\n \"seed_max\": 64\n}\ndata_dic = ketton_dic\nout_direc = data_dic[\"out_direc\"]",
"_____no_output_____"
]
],
[
[
"## Data Loading \n\nWe load data using pandas from the given directory of the covariances.",
"_____no_output_____"
]
],
[
[
"orig_cov_pph = pd.read_csv(out_direc+\"orig_pph.csv\")\norig_cov_gph = pd.read_csv(out_direc+\"orig_gph.csv\")",
"_____no_output_____"
]
],
[
[
"We now compute the slope at the origin of the radial averaged covariance to evaluate the specific surface area.",
"_____no_output_____"
],
[
"$$S_V = -4 \\frac{dS^{(1)}_2(r)}{dr}|_{r=0}$$",
"_____no_output_____"
],
[
"We do this by fittin a straight line at the origin and fixing the intercept at $S^{(1)}_2(0)=\\phi$\nTherefore the equation we are fitting is:\n\n$$y = ax + \\phi$$",
"_____no_output_____"
]
],
[
[
"def radial_average(cov):\n avg = np.mean(cov, axis=0)\n return avg\n\n\ndef straight_line_at_origin(porosity):\n def func(x, a):\n return a * x + porosity\n return func",
"_____no_output_____"
],
[
"original_average_pph = radial_average(orig_cov_pph.values.T)\noriginal_average_gph = radial_average(orig_cov_gph.values.T)\n",
"_____no_output_____"
],
[
"N = 5\nslope_pph, slope_pph_cov = curve_fit(straight_line_at_origin(original_average_pph[0]), np.array(list(range(0,N))), original_average_pph[0:N])\nslope_gph, slope_gph_cov = curve_fit(straight_line_at_origin(original_average_gph[0]), np.array(list(range(0,N))), original_average_gph[0:N])\nprint (slope_pph, slope_gph)\n\nspecific_surface_orig = -4*slope_pph\nprint (specific_surface_orig)",
"[-0.01369403] [-0.01367592]\n[0.05477614]\n"
]
],
[
[
"Finally we estimate the chord length of both phases by computing:\n\n$$l^{(i)}_C=-\\frac{\\phi^{(i)}}{\\frac{dS^{(i)}_2(r)}{dr}|_{r=0}}$$",
"_____no_output_____"
]
],
[
[
"chord_length_pph = -original_average_pph[0]/slope_pph\nchord_length_gph = -original_average_gph[0]/slope_gph\nprint (chord_length_pph, chord_length_gph)",
"[9.26403769] [63.84489292]\n"
],
[
"orig_data = {\n \"slope_gph\": float(slope_gph), \"slope_pph\": float(slope_pph), \n \"specific_surface\": float(specific_surface_orig), \n \"chord_length_pph\": float(chord_length_pph), \"chord_length_gph\":float(chord_length_gph)}",
"_____no_output_____"
],
[
"covariance_values = {}\ncovariance_values[\"orig\"] = orig_data",
"_____no_output_____"
]
],
[
[
"## Synthetic Samples Computation\n\nWe now perform the same computation for the synthetic samples",
"_____no_output_____"
]
],
[
[
"for i in np.array(list(range(data_dic[\"seed_min\"], data_dic[\"seed_max\"]))):\n cov_pph = pd.read_csv(out_direc+\"S_\"+str(i)+\"_pph.csv\")\n cov_gph = pd.read_csv(out_direc+\"S_\"+str(i)+\"_gph.csv\")\n \n average_pph = radial_average(cov_pph.values.T)\n average_gph = radial_average(cov_gph.values.T)\n \n slope_pph, slope_pph_cov = curve_fit(straight_line_at_origin(average_pph[0]), np.array(list(range(0,N))), average_pph[0:N])\n slope_gph, slope_gph_cov = curve_fit(straight_line_at_origin(average_gph[0]), np.array(list(range(0,N))), average_gph[0:N])\n\n \n specific_surface = -4*slope_pph\n\n \n chord_length_pph = -average_pph[0]/slope_pph\n chord_length_gph = -average_gph[0]/slope_gph\n\n data = {\n \"slope_gph\": float(slope_gph), \"slope_pph\": float(slope_pph), \n \"specific_surface\": float(specific_surface), \n \"chord_length_pph\": float(chord_length_pph), \"chord_length_gph\":float(chord_length_gph)}\n covariance_values[\"S_\"+str(i)] = data",
"_____no_output_____"
]
],
[
[
"## Data Output to JSON\nAnd finally we dump everything to a json file that let's us use this data in future graphs and analysis.",
"_____no_output_____"
]
],
[
[
"with open(out_direc+\"covariance_data.json\", \"w\") as f:\n json.dump(covariance_values, f)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece70e97715df49158661d0066940aa0dc8244d9 | 39,905 | ipynb | Jupyter Notebook | MRNet_EDA_ns.ipynb | nswitanek/mrnet-fastai | dfc7cbeb74ada91641b46cdbf38e2c85955402eb | [
"Apache-2.0"
] | 16 | 2019-04-17T20:46:58.000Z | 2021-01-09T02:43:50.000Z | MRNet_EDA_ns.ipynb | nswitanek/mrnet-fastai | dfc7cbeb74ada91641b46cdbf38e2c85955402eb | [
"Apache-2.0"
] | 10 | 2019-04-18T04:43:28.000Z | 2019-05-17T15:47:43.000Z | MRNet_EDA_ns.ipynb | nswitanek/mrnet-fastai | dfc7cbeb74ada91641b46cdbf38e2c85955402eb | [
"Apache-2.0"
] | 7 | 2019-04-18T00:00:22.000Z | 2021-08-22T17:31:17.000Z | 32.816612 | 260 | 0.31773 | [
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom fastai.core import *\n\n%matplotlib notebook",
"_____no_output_____"
],
[
"! ls -R ",
"LICENSE MRNet_EDA.ipynb README.md\r\n"
],
[
"data_path = Path('../data')\ntrain_path = data_path/'smalltrain'/'train'\nvalid_path = data_path/'smallvalid'/'valid'",
"_____no_output_____"
],
[
"train_abnl = pd.read_csv(data_path/'train-abnormal.csv', header=None,\n names=['Case', 'Abnormal'], \n dtype={'Case': str, 'Abnormal': np.int64})\nprint(train_abnl.groupby('Abnormal').count())\ntrain_abnl.head()",
" Case\nAbnormal \n0 217\n1 913\n"
],
[
"train_acl = pd.read_csv(data_path/'train-acl.csv', header=None,\n names=['Case', 'ACL_tear'], \n dtype={'Case': str, 'ACL_tear': np.int64})\nprint(train_acl.groupby('ACL_tear').count())\ntrain_acl.head()",
" Case\nACL_tear \n0 922\n1 208\n"
],
[
"train_meniscus = pd.read_csv(data_path/'train-meniscus.csv', header=None,\n names=['Case', 'Meniscus_tear'], \n dtype={'Case': str, 'Meniscus_tear': np.int64})\nprint(train_meniscus.groupby('Meniscus_tear').count())\ntrain_meniscus.head()",
" Case\nMeniscus_tear \n0 733\n1 397\n"
]
],
[
[
"### Co-occurrence of ACL and Meniscus tears",
"_____no_output_____"
]
],
[
[
"train = pd.merge(train_abnl, train_acl, on='Case')",
"_____no_output_____"
],
[
"train = pd.merge(train, train_meniscus, on='Case')",
"_____no_output_____"
],
[
"display(train.head())\ndisplay(train.groupby(['Abnormal','ACL_tear','Meniscus_tear']).count())",
"_____no_output_____"
]
],
[
[
"Note that cases considered Abnormal but without either ACL or Meniscus tear are the most common category, and ACL tears without Meniscus tear is the least common case in the training sample.",
"_____no_output_____"
],
[
"## Load stacks/sequences of images from each plane\nFiles are saved as NumPy arrays. Scans were taken from each of three planes, axial, coronal, and sagittal. For each plane, the scan results in a set of images. \n\nFirst, let's check for variation in the number of images per sequence, and in the image dimensions.",
"_____no_output_____"
]
],
[
[
"def collect_stack_dims(case_df, data_path=train_path):\n cases = list(case_df.Case)\n data = []\n for case in cases:\n row = [case]\n for plane in ['axial', 'coronal', 'sagittal']:\n fpath = data_path/plane/'{}.npy'.format(case)\n try: \n s,w,h = np.load(fpath).shape \n row.extend([s,w,h])\n except FileNotFoundError:\n continue\n# print('{}: {}'.format(case,row))\n if len(row)==10: data.append(row)\n columns=['Case',\n 'axial_s','axial_w','axial_h',\n 'coronal_s','coronal_w','coronal_h',\n 'sagittal_s','sagittal_w','sagittal_h',\n ]\n data_dict = {}\n for i,k in enumerate(columns): data_dict[k] = [row[i] for row in data]\n return pd.DataFrame(data_dict)",
"_____no_output_____"
],
[
"dimdf = collect_stack_dims(train)",
"_____no_output_____"
],
[
"dimdf.describe()",
"_____no_output_____"
]
],
[
[
"The number of images in a set varies from case (patient) to case, and the dimensions of each image is the same, 256x256. In the sample of data collected here, axial sequences range in length from 22 to 51; coronal, from 18 to 46; sagittal, from 19 to 46.",
"_____no_output_____"
]
],
[
[
"def load_one_stack(case, data_path=train_path, plane='coronal'):\n fpath = data_path/plane/'{}.npy'.format(case)\n return np.load(fpath)\n\ndef load_stacks(case):\n x = {}\n planes = ['axial', 'coronal', 'sagittal']\n for i, plane in enumerate(planes):\n x[plane] = load_one_stack(case, plane=plane)\n return x",
"_____no_output_____"
],
[
"case = train_abnl.Case[0]\nx = load_one_stack(case, plane='coronal')\nprint(x.shape)\nprint(x.max())",
"(36, 256, 256)\n255\n"
],
[
"x_multi = load_stacks(case)\nx_multi",
"_____no_output_____"
],
[
"from ipywidgets import interactive\nfrom IPython.display import display\n\nplt.style.use('grayscale')\n\nclass KneePlot():\n def __init__(self, x, figsize=(10, 10)):\n self.x = x\n self.slice_range = (0, self.x.shape[0] - 1)\n self.resize(figsize)\n \n def _plot_slice(self, im_slice):\n fig, ax = plt.subplots(1, 1, figsize=self.figsize)\n ax.imshow(self.x[im_slice, :, :])\n plt.show()\n\n def resize(self, figsize):\n self.figsize = figsize\n self.interactive_plot = interactive(self._plot_slice, im_slice=self.slice_range)\n self.output = self.interactive_plot.children[-1]\n self.output.layout.height = '{}px'.format(60 * self.figsize[1])\n\n def show(self):\n display(self.interactive_plot)\n",
"_____no_output_____"
],
[
"plot = KneePlot(x)\nplot.show()\n",
"_____no_output_____"
],
[
"plot.resize(figsize=(12, 12))\nplot.show()\n",
"_____no_output_____"
],
[
"from ipywidgets import interact, Dropdown, IntSlider\n\nclass MultiKneePlot():\n def __init__(self, x_multi, figsize=(10, 10)):\n self.x = x_multi\n self.planes = ['coronal', 'sagittal', 'axial']\n self.slice_nums = {plane: self.x[plane].shape[0] for plane in self.planes}\n self.figsize = figsize\n \n def _plot_slices(self, plane, im_slice): \n fig, ax = plt.subplots(1, 1, figsize=self.figsize)\n ax.imshow(self.x[plane][im_slice, :, :])\n plt.show()\n \n def draw(self):\n planes_widget = Dropdown(options=self.planes)\n plane_init = self.planes[0]\n slice_init = self.slice_nums[plane_init] - 1\n slices_widget = IntSlider(min=0, max=slice_init, value=slice_init//2)\n def update_slices_widget(*args):\n slices_widget.max = self.slice_nums[planes_widget.value] - 1\n slices_widget.value = slices_widget.max // 2\n planes_widget.observe(update_slices_widget, 'value')\n interact(self._plot_slices, plane=planes_widget, im_slice=slices_widget)\n \n def resize(self, figsize): self.figsize = figsize\n",
"_____no_output_____"
],
[
"plot_multi = MultiKneePlot(x_multi)\nplot_multi.draw()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece710bca7869a17fd5609386be28c5f87bfe9b9 | 75,843 | ipynb | Jupyter Notebook | notebooks/br/Lotomania.ipynb | xmnlab/lottery | f45f752006b85959321fc628ad954f5f23878c33 | [
"MIT"
] | null | null | null | notebooks/br/Lotomania.ipynb | xmnlab/lottery | f45f752006b85959321fc628ad954f5f23878c33 | [
"MIT"
] | null | null | null | notebooks/br/Lotomania.ipynb | xmnlab/lottery | f45f752006b85959321fc628ad954f5f23878c33 | [
"MIT"
] | null | null | null | 84.176471 | 8,308 | 0.785597 | [
[
[
"# Lotomania",
"_____no_output_____"
],
[
"## Informações\n\n### Como jogar\nA Lotomania é fácil de jogar e de ganhar: basta escolher 50 números e então concorrer a prêmios para acertos de 20, 19, 18, 17, 16, 15 ou nenhum número.\nAlém da opção de marcar no volante, você ainda pode marcar menos que 50 números e deixar que o sistema complete o jogo para você; não marcar nada e deixar que o sistema escolha todos os números na Surpresinha e/ou concorrer com a mesma aposta por 2, 4 ou 8 concursos consecutivos com a Teimosinha. Outra opção é efetuar uma nova aposta com o sistema selecionando os outros 50 números não registrados no jogo original, através da Aposta-Espelho.\n\n### Apostas\n\nO preço da aposta é único e custa apenas R\\$ 1,50.\n\n### Sorteios\n\nOs sorteios são realizados às terças-feiras e às sextas-feiras, às 20h.\n\n### Premiação\n\nO prêmio bruto corresponde a 45,3\\% da arrecadação, já computado o adicional destinado ao Ministério do Esporte. Dessa porcentagem são distribuídos:\n- 45\\% entre os acertadores dos 20 números sorteados - 1ª faixa;\n- 16\\% entre os acertadores de 19 dos 20 números sorteados - 2ª faixa;\n- 10\\% entre os acertadores de 18 dos 20 números sorteados - 3ª faixa;\n- 7\\% entre os acertadores de 17 dos 20 números sorteados - 4ª faixa;\n- 7\\% entre os acertadores de 16 dos 20 números sorteados - 5ª faixa;\n- 7\\% entre os acertadores de 15 dos 20 números sorteados - 6ª faixa;\n- 8\\% entre os acertadores de nenhum dos 20 números sorteados - 7ª faixa;\n\n### Recebimento de prêmios\n\nVocê pode receber seu prêmio em qualquer casa lotérica credenciada ou nas agências da Caixa. Caso o prêmio líquido seja superior a R\\$ 1.332,78 (bruto de R\\$ 1.903,98) o pagamento pode ser realizado somente nas agências da Caixa. Valores iguais ou acima de R\\$ 10.000,00 são pagos após 2 dias de sua apresentação na agência da Caixa.\n\n### Acumulação\n\nNão existindo aposta premiada na 7ª faixa (0 acerto), o prêmio acumula para o concurso subsequente, na 1ª faixa de premiação (20 acertos). Nas demais faixas, o prêmio acumula na respectiva faixa de premiação.\n\n### Tabela de preços\n\n|Aposta única|Valor em R\\$|\n|::|::|\n|50 números|1,50|\n\n### Probabilidade\n\n|Faixas|Probabilidade|\n|::|::|\n|20 números|1/11.372.635|\n|19 números|1/352.551|\n|18 números|1/24.235|\n|17 números|1/2.776|\n|16 números|1/472|\n|15 números|1/112|\n|00 números|1/11.372.635|\n",
"_____no_output_____"
]
],
[
[
"from matplotlib import pyplot as plt\n\n# local\nfrom lottery.strategy import LoteryStrategyBase\n\nimport pandas as pd\nimport numpy as np\nimport random",
"_____no_output_____"
]
],
[
[
"## Data Cleaning",
"_____no_output_____"
]
],
[
[
"data_path = 'data/lotomania.txt'\ndf = pd.read_csv(\n data_path, names=['id', 'date'] + list(range(20))\n).drop_duplicates().sort_values('id').reset_index(drop=True)\ndf.info() ",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1835 entries, 0 to 1834\nData columns (total 22 columns):\nid 1835 non-null int64\ndate 1835 non-null object\n0 1835 non-null int64\n1 1835 non-null int64\n2 1835 non-null int64\n3 1835 non-null int64\n4 1835 non-null int64\n5 1835 non-null int64\n6 1835 non-null int64\n7 1835 non-null int64\n8 1835 non-null int64\n9 1835 non-null int64\n10 1835 non-null int64\n11 1835 non-null int64\n12 1835 non-null int64\n13 1835 non-null int64\n14 1835 non-null int64\n15 1835 non-null int64\n16 1835 non-null int64\n17 1835 non-null int64\n18 1835 non-null int64\n19 1835 non-null int64\ndtypes: int64(21), object(1)\nmemory usage: 315.5+ KB\n"
],
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"## Strategies",
"_____no_output_____"
]
],
[
[
"class HighFrequencyStrategy(LoteryStrategyBase):\n \"\"\"\n \n \"\"\"\n def pick_numbers(self, df_train: pd.DataFrame=None) -> [int]:\n \"\"\"\n Pick number for the next game\n \n :param df_train: dataframe with training data\n :return: list of numbers\n \"\"\"\n if df_train is None:\n df_train = self.data[self.k_results]\n \n values_train = pd.Series(df_train.values.flatten())\n se_choice = values_train.value_counts()[:self.n_choices]\n \n return sorted(se_choice.index.values.tolist())",
"_____no_output_____"
],
[
"class LowFrequencyStrategy(LoteryStrategyBase):\n \"\"\"\n \n \"\"\"\n def pick_numbers(self, df_train: pd.DataFrame=None) -> [int]:\n \"\"\"\n Pick number for the next game\n \n :param df_train: dataframe with training data\n :return: list of numbers\n \"\"\"\n if df_train is None:\n df_train = self.data[self.k_results]\n \n values_train = pd.Series(df_train.values.flatten())\n se_choice = values_train.value_counts()[-self.n_choices:]\n \n return sorted(se_choice.index.values.tolist())",
"_____no_output_____"
],
[
"class MedianFrequencyStrategy(LoteryStrategyBase):\n def pick_numbers(self, df_train: pd.DataFrame=None) -> [int]:\n \"\"\"\n Pick number for the next game\n \n :param df_train: dataframe with training data\n :return: list of numbers\n \"\"\"\n if df_train is None:\n df_train = self.data[self.k_results]\n\n values_train = pd.Series(df_train.values.flatten())\n se_choice = values_train.value_counts()\n i = int((se_choice.size - self.n_choices)/2)\n se_choice = se_choice[i:i+self.n_choices]\n \n return sorted(se_choice.index.values.tolist())",
"_____no_output_____"
],
[
"class RandomStrategy(LoteryStrategyBase):\n def pick_numbers(self, df_train: pd.DataFrame=None) -> [int]:\n \"\"\"\n Pick number for the next game\n \n :param df_train: dataframe with training data\n :return: list of numbers\n \"\"\"\n return sorted(\n random.sample(range(self.vmin, self.vmax), self.n_choices)\n )",
"_____no_output_____"
],
[
"class PickedMatchedLast3Strategy(LoteryStrategyBase):\n def pick_numbers(self, df_train: pd.DataFrame=None) -> [int]:\n \"\"\"\n Pick number for the next game\n \n :param df_train: dataframe with training data\n :return: list of numbers\n \"\"\"\n if df_train is None:\n df_train = self.data[self.k_results]\n\n \n se_last = (\n df_train.tail(1).values.flatten().tolist(),\n df_train.tail(2).head(1).values.flatten().tolist(),\n df_train.tail(3).head(1).values.flatten().tolist()\n )\n\n # number frequency\n se_counts = pd.Series(df_train.values.flatten()).value_counts()\n se_counts.name = 'counts'\n df_counts = pd.DataFrame(se_counts).reset_index().rename(\n columns={'index': 'num'}\n )\n\n choice = se_counts[:50].index.tolist()\n\n # comparison between last 3 results\n matched = (\n set(se_last[0]) & set(se_last[1]),\n set(se_last[1]) & set(se_last[2]),\n set(se_last[0]) & set(se_last[2])\n )\n\n matched_joined = matched[0] | matched[1] | matched[2]\n\n choice = sorted(se_counts.index.tolist())\n\n # remove the matched number from the las 3 results\n for i in matched_joined:\n choice.pop(choice.index(i))\n\n return choice[-50:]\n ",
"_____no_output_____"
],
[
"class MixSimpleStrategy(LoteryStrategyBase):\n strategies = None # list\n \n def __init__(self, *args, strategies: list, **kwargs):\n # should be informed more than 1 strategy class\n assert len(strategies) > 1\n \n self.strategies = [\n s(*args, **kwargs) for s in strategies\n ]\n \n super().__init__(*args, **kwargs)\n \n def pick_numbers(self, df_train: pd.DataFrame=None) -> [int]:\n \"\"\"\n Pick number for the next game\n \n :param df_train: dataframe with training data\n :return: list of numbers\n \"\"\"\n results = [\n s.pick_numbers(df_train) for s in self.strategies\n ]\n \n final_numbers_raw = None\n \n for i in range(len(results)-1):\n for j in range(i, len(results)):\n nums = set(results[i]) & set(results[j])\n if final_numbers_raw is None:\n final_numbers_raw = nums\n else:\n final_numbers_raw = final_numbers_raw | nums\n \n final_numbers = list(final_numbers_raw)[:self.n_choices]\n \n # assert number of numbers picked\n assert len(final_numbers) == self.n_choices\n \n return final_numbers",
"_____no_output_____"
],
[
"lotomania_settings = dict(\n n_picked=20,\n n_choices=50,\n vmin=0,\n vmax=99,\n n_train=10,\n hits_to_win=(0, 15, 16, 17, 18, 19, 20)\n)\nn_samples = 1000\nnext_game_numbers = []",
"_____no_output_____"
]
],
[
[
"### Test High Frequency Strategy",
"_____no_output_____"
]
],
[
[
"model = HighFrequencyStrategy(data=df.tail(n_samples), **lotomania_settings)\n\nprint('Win results: ', model.win_results())\nprint('Next choice:', model.pick_numbers())\n\nmodel.stats()\nmodel.plot_stats()",
"Win results: 8/990 (0.8080808080808081 %)\nNext choice: [0, 1, 2, 3, 4, 6, 8, 9, 15, 16, 17, 19, 21, 26, 29, 31, 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 47, 48, 49, 53, 54, 55, 58, 60, 63, 66, 67, 70, 73, 74, 76, 77, 78, 79, 80, 82, 85, 87, 92, 93]\n results\ncount 990.000000\nmean 9.966667\nstd 2.030082\nmin 4.000000\n25% 9.000000\n50% 10.000000\n75% 11.000000\nmax 16.000000\n"
]
],
[
[
"### Test Low Frequency Strategy",
"_____no_output_____"
]
],
[
[
"model = LowFrequencyStrategy(data=df.tail(n_samples), **lotomania_settings)\n\nprint('Win results: ', model.win_results())\nprint('Next choice:', model.pick_numbers())\n\nmodel.stats()\nmodel.plot_stats()",
"Win results: 14/990 (1.4141414141414141 %)\nNext choice: [5, 7, 10, 11, 12, 13, 14, 18, 20, 22, 23, 24, 25, 27, 28, 30, 32, 33, 34, 42, 46, 50, 51, 52, 56, 57, 59, 61, 62, 64, 65, 68, 69, 71, 72, 75, 81, 83, 84, 86, 88, 89, 90, 91, 94, 95, 96, 97, 98, 99]\n results\ncount 990.000000\nmean 9.902020\nstd 2.083567\nmin 3.000000\n25% 8.000000\n50% 10.000000\n75% 11.000000\nmax 17.000000\n"
]
],
[
[
"### Test Median Frequency",
"_____no_output_____"
]
],
[
[
"model = MedianFrequencyStrategy(data=df.tail(n_samples), **lotomania_settings)\n\nprint('Win results: ', model.win_results())\nprint('Next choice:', model.pick_numbers())\n\nmodel.stats()\nmodel.plot_stats()",
"Win results: 11/990 (1.1111111111111112 %)\nNext choice: [0, 1, 7, 9, 10, 11, 18, 19, 20, 21, 23, 24, 27, 28, 30, 35, 36, 37, 38, 39, 42, 44, 45, 46, 47, 48, 50, 53, 55, 57, 60, 63, 64, 65, 67, 68, 69, 74, 76, 78, 80, 81, 82, 83, 86, 90, 91, 92, 95, 97]\n results\ncount 990.000000\nmean 9.922222\nstd 2.029363\nmin 3.000000\n25% 9.000000\n50% 10.000000\n75% 11.000000\nmax 15.000000\n"
]
],
[
[
"### Test Picked Matched Last 3 Strategy",
"_____no_output_____"
]
],
[
[
"model = PickedMatchedLast3Strategy(data=df.tail(n_samples), **lotomania_settings)\n\nprint('Win results: ', model.win_results())\nprint('Next choice:', model.pick_numbers())\n\nmodel.stats()\nmodel.plot_stats()",
"Win results: 13/990 (1.3131313131313131 %)\nNext choice: [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 56, 57, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 71, 72, 73, 74, 75, 76, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 95, 96, 97, 98, 99]\n results\ncount 990.000000\nmean 9.821212\nstd 1.974907\nmin 4.000000\n25% 8.250000\n50% 10.000000\n75% 11.000000\nmax 16.000000\n"
]
],
[
[
"### Mix Simples Strategy",
"_____no_output_____"
]
],
[
[
"model = MixSimpleStrategy(\n data=df.tail(n_samples), \n strategies=[\n LowFrequencyStrategy, \n MedianFrequencyStrategy, \n PickedMatchedLast3Strategy\n ], **lotomania_settings\n)\n\nprint('Win results: ', model.win_results())\nprint('Next choice:', model.pick_numbers())\n\nmodel.stats()\nmodel.plot_stats()",
"Win results: 13/990 (1.3131313131313131 %)\nNext choice: [0, 1, 5, 7, 9, 10, 11, 12, 13, 14, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 30, 32, 33, 34, 35, 36, 37, 38, 39, 42, 44, 45, 46, 47, 48, 50, 51, 52, 53, 55, 56, 57, 59, 60, 61, 62, 63, 64, 65, 67]\n results\ncount 990.000000\nmean 10.011111\nstd 2.051628\nmin 3.000000\n25% 9.000000\n50% 10.000000\n75% 11.000000\nmax 16.000000\n"
]
],
[
[
"### Random Strategy",
"_____no_output_____"
]
],
[
[
"model = RandomStrategy(data=df.tail(n_samples), **lotomania_settings)\n\nprint('Win results: ', model.win_results())\nprint('Next choice:', model.pick_numbers())\n\nmodel.stats()\nmodel.plot_stats()",
"Win results: 11/990 (1.1111111111111112 %)\nNext choice: [2, 6, 10, 11, 12, 13, 16, 18, 19, 21, 23, 27, 28, 29, 31, 32, 36, 39, 41, 42, 43, 44, 45, 46, 47, 50, 51, 52, 56, 57, 59, 63, 64, 65, 68, 69, 70, 72, 74, 77, 82, 84, 85, 88, 89, 90, 93, 95, 97, 98]\n results\ncount 990.000000\nmean 9.939394\nstd 2.002618\nmin 4.000000\n25% 9.000000\n50% 10.000000\n75% 11.000000\nmax 17.000000\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece719a86b40884f510088c7fadcacf6235f8aeb | 142,330 | ipynb | Jupyter Notebook | .ipynb_checkpoints/P1-checkpoint.ipynb | carlospanal/CarND-LaneLines-P1 | 36505251a257156b1c36d4bc9aba848677b1f56b | [
"MIT"
] | null | null | null | .ipynb_checkpoints/P1-checkpoint.ipynb | carlospanal/CarND-LaneLines-P1 | 36505251a257156b1c36d4bc9aba848677b1f56b | [
"MIT"
] | null | null | null | .ipynb_checkpoints/P1-checkpoint.ipynb | carlospanal/CarND-LaneLines-P1 | 36505251a257156b1c36d4bc9aba848677b1f56b | [
"MIT"
] | null | null | null | 180.392902 | 114,992 | 0.888239 | [
[
[
"# Self-Driving Car Engineer Nanodegree\n\n\n## Project: **Finding Lane Lines on the Road** \n***\nIn this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n\nOnce you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n\nIn addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n\n---\nLet's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n\n**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n\n---",
"_____no_output_____"
],
[
"**The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**\n\n---\n\n<figure>\n <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n </figcaption>\n</figure>\n <p></p> \n<figure>\n <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n </figcaption>\n</figure>",
"_____no_output_____"
],
[
"**Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** ",
"_____no_output_____"
],
[
"## Import Packages",
"_____no_output_____"
]
],
[
[
"#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nimport glob\nfrom pylab import rcParams\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Read in an Image",
"_____no_output_____"
]
],
[
[
"#reading in an image\nexampleImage = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(exampleImage), 'with dimensions:', exampleImage.shape)\nplt.imshow(exampleImage) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')",
"This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)\n"
]
],
[
[
"## Helper Functions",
"_____no_output_____"
]
],
[
[
"import math\n\ndef grayscale(img):\n \"\"\"Convert intial RGB image to grayscale\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\nlastLeftLine = None\nlastRightLine = None\ndef draw_lines(img, lines, color=[0, 255, 0], thickness=4, ):\n global lastLeftLine\n global lastRightLine\n leftX = []\n leftY = []\n rightX = []\n rightY = []\n \n for line in lines:\n for x1,y1,x2,y2 in line:\n lineSlope = (y2 - y1)/(x2 - x1)\n if abs(lineSlope) < 0.5:\n continue\n if lineSlope < 0:\n leftX.extend([x1, x2])\n leftY.extend([y1, y2])\n else:\n rightX.extend([x1, x2])\n rightY.extend([y1, y2])\n \n if len(leftX) == 0:\n leftLine = lastLeftLine\n else:\n leftParameters = np.polyfit( leftY, leftX, 1)\n leftLine = np.poly1d(leftParameters)\n lastLeftLine = leftLine\n if len(rightX) == 0:\n rightLine = lastRightLine\n else:\n rightParameters = np.polyfit( rightY, rightX, 1)\n rightLine = np.poly1d(rightParameters)\n lastRightLine = rightLine\n \n maxY = img.shape[0]\n minY = int(img.shape[0]* 330 / 540)\n \n leftXStart = int(leftLine(maxY))\n leftXEnd = int(leftLine(minY))\n rightXStart = int(rightLine(maxY))\n rightXEnd = int(rightLine(minY))\n \n cv2.line(img, (leftXStart, maxY), (leftXEnd, minY), color, thickness)\n cv2.line(img, (rightXStart, maxY), (rightXEnd, minY), color, thickness)\n \ndef draw_lines_not_averaged(img, lines, color=[0, 255, 0], thickness=2):\n \"\"\"\n This is an initial version of draw_lines that doesn't calculate average lines.\n This version is not currently used in the pipeline\n \"\"\"\n for line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\" \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines)\n return line_img\n\n\ndef weighted_img(img, initial_img, α=0.8, β=1., γ=0.):\n\n return cv2.addWeighted(initial_img, α, img, β, γ)",
"_____no_output_____"
]
],
[
[
"## Test Images\n\nBuild your pipeline to work on the images in the directory \"test_images\" \n**You should make sure your pipeline works well on these images before you try the videos.**",
"_____no_output_____"
]
],
[
[
"import os\nos.listdir(\"test_images/\")",
"_____no_output_____"
]
],
[
[
"# Build a Lane Finding Pipeline\n\n",
"_____no_output_____"
],
[
"Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n\nTry tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.",
"_____no_output_____"
]
],
[
[
"\"\"\" \n This is not the definitive pipeline. It works the same way, but this one takes a list of images as an input.\n\"\"\"\n\nimages = [cv2.imread(file) for file in glob.glob(\"test_images/*.jpg\")]\ngrayMap = [grayscale(i) for i in images]\nsmoothedImages = [gaussian_blur(i, 5) for i in grayMap]\ncannyMap = [canny(i, 50, 150) for i in images]\n\nvertices = np.array([[(450,320),(510, 320), (900, 539), (130,539)]], dtype=np.int32)\ncannyRegionMap = [region_of_interest(i, vertices) for i in cannyMap]\nhoughMap = [hough_lines(i, 1, 0.034, 15, 25, 35) for i in cannyRegionMap]\n # Draw the lines on the edge image\noriginalPlusHough = [cv2.addWeighted(lanes, 0.8, image, 1, 0) for lanes, image in zip(houghMap, images)]\n\noutNameList = map(lambda x: \"out_\" + x , os.listdir(\"test_images/\"))\n[cv2.imwrite(os.path.join(\"test_images_output/\", name), image) for name, image in zip(outNameList,originalPlusHough)]",
"_____no_output_____"
],
[
"\"\"\"\n I created this widget to ease parameters selection for hough_lines function.\n Right now, it's showing averaged lines. \n You can use draw_lines_not_averaged instead of draw_lines inside hough_lines function in order to\n see the original hough lines as they were shown during development.\n I could draw lines over the original image, but I did this way because at some point I realized that it\n was easier for me to see both images side by side, as I was already plotting the overlaped version.\n \n\"\"\"\nfrom ipywidgets import interact\n\n@interact(\n imageIndex=(0, 5, 1),\n rho=(1, 10, 1),\n theta=(1, 180),\n threshold=(0, 100),\n minLineLength=(0, 100),\n maxLineGap=(0, 100)\n)\ndef lane_sliders(imageIndex=0, rho=1, theta=90, threshold=15, min_line_length=25, max_line_gap=35):\n hough_image = hough_lines(cannyRegionMap[imageIndex], rho, np.pi/theta, threshold, min_line_length, max_line_gap)\n orig_image = images[imageIndex]\n plot_image = np.concatenate((orig_image, hough_image), axis=1)\n plt.rcParams[\"figure.figsize\"] = (20,30)\n plt.imshow(plot_image)",
"_____no_output_____"
]
],
[
[
"## Test on Videos\n\nYou know what's cooler than drawing lanes over images? Drawing lanes over video!\n\nWe can test our solution on two provided videos:\n\n`solidWhiteRight.mp4`\n\n`solidYellowLeft.mp4`\n\n**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n\n**If you get an error that looks like this:**\n```\nNeedDownloadError: Need ffmpeg exe. \nYou can download it by calling: \nimageio.plugins.ffmpeg.download()\n```\n**Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**",
"_____no_output_____"
]
],
[
[
"# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML",
"_____no_output_____"
]
],
[
[
"# DEFINITIVE PIPELINE",
"_____no_output_____"
]
],
[
[
"def process_image(image):\n\n grayMap = grayscale(image)\n smoothedImage = gaussian_blur(grayMap, 5)\n\n cannyMap = canny(smoothedImage, 50, 150)\n \n maxYRegion = image.shape[0]\n minYRegion = int(image.shape[0]* 330 / 540)\n leftXRegion1 = int(image.shape[1]* 130 / 960)\n leftXRegion2 = int(image.shape[1]* 440 / 960)\n rightXRegion1 = int(image.shape[1]* 520 / 960)\n rightXRegion2 = int(image.shape[1]* 900 / 960)\n\n vertices = np.array([[\n (leftXRegion2, minYRegion),\n (rightXRegion1, minYRegion), \n (rightXRegion2, maxYRegion), \n (leftXRegion1, maxYRegion)\n ]], dtype=np.int32)\n \n cannyRegionMap = region_of_interest(cannyMap, vertices)\n\n houghMap = hough_lines(cannyRegionMap, 1, 0.034, 15, 25, 35)\n result = cv2.addWeighted(houghMap, 0.8, image, 1, 0)\n \n return result\n \n \"\"\" this alternative code can be used to draw opaque lines\"\"\"\n # hough_thresholds = (grayscale(houghMap)[:,:] > 0)\n # result = np.copy(image)\n # result[hough_thresholds] = [0,255,0]",
"_____no_output_____"
]
],
[
[
"Let's try the one with the solid white lane on the right first ...",
"_____no_output_____"
]
],
[
[
"white_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n#clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n%time white_clip.write_videofile(white_output, audio=False)",
"\rt: 0%| | 0/221 [00:00<?, ?it/s, now=None]"
]
],
[
[
"Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.",
"_____no_output_____"
]
],
[
[
"HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))",
"_____no_output_____"
]
],
[
[
"## Improve the draw_lines() function\n\n**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n\n**Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**",
"_____no_output_____"
],
[
"Now for the one with the solid yellow lane on the left. This one's more tricky!",
"_____no_output_____"
]
],
[
[
"yellow_output = 'test_videos_output/solidYellowLeft.mp4'\n\n##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\n%time yellow_clip.write_videofile(yellow_output, audio=False)",
"\rt: 0%| | 0/681 [00:00<?, ?it/s, now=None]"
],
[
"HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))",
"_____no_output_____"
]
],
[
[
"## Optional Challenge \n# * I didn't finish this challenge\n\nTry your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!",
"_____no_output_____"
]
],
[
[
"challenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\nclip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\n%time challenge_clip.write_videofile(challenge_output, audio=False)",
"\rt: 0%| | 0/251 [00:00<?, ?it/s, now=None]"
],
[
"HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece736fa55e0c4408062139a52fd4465f7d6c337 | 146,961 | ipynb | Jupyter Notebook | intro_to_pytorch/Part 7 - Loading Image Data (Exercises).ipynb | Hammania689/pytorch_udacity_challenge | 0c4b0b87260ebf9de275a10ab1bbea5d262ecd82 | [
"MIT"
] | null | null | null | intro_to_pytorch/Part 7 - Loading Image Data (Exercises).ipynb | Hammania689/pytorch_udacity_challenge | 0c4b0b87260ebf9de275a10ab1bbea5d262ecd82 | [
"MIT"
] | null | null | null | intro_to_pytorch/Part 7 - Loading Image Data (Exercises).ipynb | Hammania689/pytorch_udacity_challenge | 0c4b0b87260ebf9de275a10ab1bbea5d262ecd82 | [
"MIT"
] | null | null | null | 493.157718 | 129,404 | 0.924436 | [
[
[
"# Loading Image Data\n\nSo far we've been working with fairly artificial datasets that you wouldn't typically be using in real projects. Instead, you'll likely be dealing with full-sized images like you'd get from smart phone cameras. In this notebook, we'll look at how to load images and use them to train neural networks.\n\nWe'll be using a [dataset of cat and dog photos](https://www.kaggle.com/c/dogs-vs-cats) available from Kaggle. Here are a couple example images:\n\n<img src='assets/dog_cat.png'>\n\nWe'll use this dataset to train a neural network that can differentiate between cats and dogs. These days it doesn't seem like a big accomplishment, but five years ago it was a serious challenge for computer vision systems.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torchvision import datasets, transforms\n\nimport helper",
"_____no_output_____"
]
],
[
[
"The easiest way to load image data is with `datasets.ImageFolder` from `torchvision` ([documentation](http://pytorch.org/docs/master/torchvision/datasets.html#imagefolder)). In general you'll use `ImageFolder` like so:\n\n```python\ndataset = datasets.ImageFolder('path/to/data', transform=transform)\n```\n\nwhere `'path/to/data'` is the file path to the data directory and `transform` is a list of processing steps built with the [`transforms`](http://pytorch.org/docs/master/torchvision/transforms.html) module from `torchvision`. ImageFolder expects the files and directories to be constructed like so:\n```\nroot/dog/xxx.png\nroot/dog/xxy.png\nroot/dog/xxz.png\n\nroot/cat/123.png\nroot/cat/nsdf3.png\nroot/cat/asd932_.png\n```\n\nwhere each class has it's own directory (`cat` and `dog`) for the images. The images are then labeled with the class taken from the directory name. So here, the image `123.png` would be loaded with the class label `cat`. You can download the dataset already structured like this [from here](https://s3.amazonaws.com/content.udacity-data.com/nd089/Cat_Dog_data.zip). I've also split it into a training set and test set.\n\n### Transforms\n\nWhen you load in the data with `ImageFolder`, you'll need to define some transforms. For example, the images are different sizes but we'll need them to all be the same size for training. You can either resize them with `transforms.Resize()` or crop with `transforms.CenterCrop()`, `transforms.RandomResizedCrop()`, etc. We'll also need to convert the images to PyTorch tensors with `transforms.ToTensor()`. Typically you'll combine these transforms into a pipeline with `transforms.Compose()`, which accepts a list of transforms and runs them in sequence. It looks something like this to scale, then crop, then convert to a tensor:\n\n```python\ntransform = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor()])\n\n```\n\nThere are plenty of transforms available, I'll cover more in a bit and you can read through the [documentation](http://pytorch.org/docs/master/torchvision/transforms.html). \n\n### Data Loaders\n\nWith the `ImageFolder` loaded, you have to pass it to a [`DataLoader`](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader). The `DataLoader` takes a dataset (such as you would get from `ImageFolder`) and returns batches of images and the corresponding labels. You can set various parameters like the batch size and if the data is shuffled after each epoch.\n\n```python\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)\n```\n\nHere `dataloader` is a [generator](https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/). To get data out of it, you need to loop through it or convert it to an iterator and call `next()`.\n\n```python\n# Looping through it, get a batch on each loop \nfor images, labels in dataloader:\n pass\n\n# Get one batch\nimages, labels = next(iter(dataloader))\n```\n \n>**Exercise:** Load images from the `Cat_Dog_data/train` folder, define a few transforms, then build the dataloader.",
"_____no_output_____"
]
],
[
[
"data_dir = '/home/ham/data/Cat_Dog_data/train'\n\ntransform = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor()]) # TODO: compose transforms here\ndataset = datasets.ImageFolder(data_dir,transform) # TODO: create the ImageFolder\ndataloader = torch.utils.data.DataLoader(dataset,batch_size=32, shuffle=True) # TODO: use the ImageFolder dataset to create the DataLoader",
"_____no_output_____"
],
[
"# Run this to test your data loader\nimages, labels = next(iter(dataloader))\nhelper.imshow(images[0], normalize=False)",
"_____no_output_____"
]
],
[
[
"If you loaded the data correctly, you should see something like this (your image will be different):\n\n<img src='assets/cat_cropped.png' width=244>",
"_____no_output_____"
],
[
"## Data Augmentation\n\nA common strategy for training neural networks is to introduce randomness in the input data itself. For example, you can randomly rotate, mirror, scale, and/or crop your images during training. This will help your network generalize as it's seeing the same images but in different locations, with different sizes, in different orientations, etc.\n\nTo randomly rotate, scale and crop, then flip your images you would define your transforms like this:\n\n```python\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], \n [0.5, 0.5, 0.5])])\n```\n\nYou'll also typically want to normalize images with `transforms.Normalize`. You pass in a list of means and list of standard deviations, then the color channels are normalized like so\n\n```input[channel] = (input[channel] - mean[channel]) / std[channel]```\n\nSubtracting `mean` centers the data around zero and dividing by `std` squishes the values to be between -1 and 1. Normalizing helps keep the network work weights near zero which in turn makes backpropagation more stable. Without normalization, networks will tend to fail to learn.\n\nYou can find a list of all [the available transforms here](http://pytorch.org/docs/0.3.0/torchvision/transforms.html). When you're testing however, you'll want to use images that aren't altered (except you'll need to normalize the same way). So, for validation/test images, you'll typically just resize and crop.\n\n>**Exercise:** Define transforms for training data and testing data below.",
"_____no_output_____"
]
],
[
[
"data_dir = '/home/ham/data/Cat_Dog_data'\n\n# TODO: Define transforms for the training data and testing data\n\ntrain_transforms = transform([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor()])\n\ntest_transforms = transform([transforms.Resize(225),\n transforms.CenterCrop(224),\n transforms.ToTensor()])\n\n\n# Pass transforms in here, then run the next cell to see how the transforms look\ntrain_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\ntest_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)\n\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=32)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=32)",
"_____no_output_____"
],
[
"# change this to the trainloader or testloader \ndata_iter = iter(testloader)\n\nimages, labels = next(data_iter)\nfig, axes = plt.subplots(figsize=(10,4), ncols=4)\nfor ii in range(4):\n ax = axes[ii]\n helper.imshow(images[ii], ax=ax, normalize=False)",
"_____no_output_____"
]
],
[
[
"Your transformed images should look something like this.\n\n<center>Training examples:</center>\n<img src='assets/train_examples.png' width=500px>\n\n<center>Testing examples:</center>\n<img src='assets/test_examples.png' width=500px>",
"_____no_output_____"
],
[
"At this point you should be able to load data for training and testing. Now, you should try building a network that can classify cats vs dogs. This is quite a bit more complicated than before with the MNIST and Fashion-MNIST datasets. To be honest, you probably won't get it to work with a fully-connected network, no matter how deep. These images have three color channels and at a higher resolution (so far you've seen 28x28 images which are tiny).\n\nIn the next part, I'll show you how to use a pre-trained network to build a model that can actually solve this problem.",
"_____no_output_____"
]
],
[
[
"# Optional TODO: Attempt to build a network to classify cats vs dogs from this dataset",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
ece7403b4c40c7056f4fbe26c86f4d117c9833e3 | 27,386 | ipynb | Jupyter Notebook | 4_model_evaluation.ipynb | ataraxno/transfer_learning_grenv | 03745194aaddaaf7f348d1da781e7642de0b11a7 | [
"Apache-2.0"
] | null | null | null | 4_model_evaluation.ipynb | ataraxno/transfer_learning_grenv | 03745194aaddaaf7f348d1da781e7642de0b11a7 | [
"Apache-2.0"
] | null | null | null | 4_model_evaluation.ipynb | ataraxno/transfer_learning_grenv | 03745194aaddaaf7f348d1da781e7642de0b11a7 | [
"Apache-2.0"
] | null | null | null | 33.074879 | 308 | 0.573176 | [
[
[
"import sys\nsys.path.append('../')",
"_____no_output_____"
],
[
"import time\nimport os\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.utils import resample\nfrom sklearn.metrics import mean_squared_error\n\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\ntf.__version__",
"_____no_output_____"
],
[
"gpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n try:\n # Currently, memory growth needs to be the same across GPUs\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n except RuntimeError as e:\n # Memory growth must be set before GPUs have been initialized\n print(e)",
"2 Physical GPUs, 2 Logical GPUs\n"
],
[
"from tensorflow.keras.metrics import Metric\nclass RSquare(Metric):\n \"\"\"Compute R^2 score.\n This is also called as coefficient of determination.\n It tells how close are data to the fitted regression line.\n - Highest score can be 1.0 and it indicates that the predictors\n perfectly accounts for variation in the target.\n - Score 0.0 indicates that the predictors do not\n account for variation in the target.\n - It can also be negative if the model is worse.\n Usage:\n ```python\n actuals = tf.constant([1, 4, 3], dtype=tf.float32)\n preds = tf.constant([2, 4, 4], dtype=tf.float32)\n result = tf.keras.metrics.RSquare()\n result.update_state(actuals, preds)\n print('R^2 score is: ', r1.result().numpy()) # 0.57142866\n ```\n \"\"\"\n\n def __init__(self, name='r_square', dtype=tf.float32):\n super(RSquare, self).__init__(name=name, dtype=dtype)\n self.squared_sum = self.add_weight(\"squared_sum\", initializer=\"zeros\")\n self.sum = self.add_weight(\"sum\", initializer=\"zeros\")\n self.res = self.add_weight(\"residual\", initializer=\"zeros\")\n self.count = self.add_weight(\"count\", initializer=\"zeros\")\n\n def update_state(self, y_true, y_pred):\n y_true = tf.convert_to_tensor(y_true, tf.float32)\n y_pred = tf.convert_to_tensor(y_pred, tf.float32)\n self.squared_sum.assign_add(tf.reduce_sum(y_true**2))\n self.sum.assign_add(tf.reduce_sum(y_true))\n self.res.assign_add(\n tf.reduce_sum(tf.square(tf.subtract(y_true, y_pred))))\n self.count.assign_add(tf.cast(tf.shape(y_true)[0], tf.float32))\n\n def result(self):\n mean = self.sum / self.count\n total = self.squared_sum - 2 * self.sum * mean + self.count * mean**2\n return 1 - (self.res / total)\n\n def reset_states(self):\n # The state of the metric will be reset at the start of each epoch.\n self.squared_sum.assign(0.0)\n self.sum.assign(0.0)\n self.res.assign(0.0)\n self.count.assign(0.0)",
"_____no_output_____"
],
[
"import matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.ticker import (LinearLocator, MultipleLocator, FormatStrFormatter)\nfrom matplotlib.dates import MONDAY\nfrom matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter\nfrom matplotlib import gridspec\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n%matplotlib inline",
"_____no_output_____"
],
[
"plt.rcParams['figure.figsize'] = ((8/2.54), (6/2.54))\nplt.rcParams[\"font.family\"] = \"Arial\"\nplt.rcParams[\"mathtext.default\"] = \"rm\"\nplt.rcParams.update({'font.size': 11})\nMARKER_SIZE = 15\ncmap_m = [\"#f4a6ad\", \"#f6957e\", \"#fccfa2\", \"#8de7be\", \"#86d6f2\", \"#24a9e4\", \"#b586e0\", \"#d7f293\"]\ncmap = [\"#e94d5b\", \"#ef4d28\", \"#f9a54f\", \"#25b575\", \"#1bb1e7\", \"#1477a2\", \"#a662e5\", \"#c2f442\"]\n\nplt.rcParams['axes.spines.top'] = False\n# plt.rcParams['axes.edgecolor'] = \nplt.rcParams['axes.linewidth'] = 1\nplt.rcParams['lines.linewidth'] = 1.5\nplt.rcParams['xtick.major.width'] = 1\nplt.rcParams['xtick.minor.width'] = 1\nplt.rcParams['ytick.major.width'] = 1\nplt.rcParams['ytick.minor.width'] = 1",
"_____no_output_____"
],
[
"def make_patch_spines_invisible(ax):\n ax.set_frame_on(True)\n ax.patch.set_visible(False)\n for sp in ax.spines.values():\n sp.set_visible(False)",
"_____no_output_____"
]
],
[
[
"## Data preparation",
"_____no_output_____"
],
[
"### Hyperparameters",
"_____no_output_____"
]
],
[
[
"BEST_PATHS = ['./models/best_MLP.h5', \n './models/best_LSTM.h5',\n './models/best_AE_LSTM.h5',\n './models/best_BiLSTM.h5',\n './models/best_AE_BiLSTM.h5']\nTRANS_BEST_PATHS = ['./models/trans_MLP.h5', \n './models/trans_LSTM.h5',\n './models/trans_AE_LSTM.h5',\n './models/trans_BiLSTM.h5',\n './models/trans_AE_BiLSTM.h5']\nRAW_BEST_PATHS = ['./models/raw_MLP.h5', \n './models/raw_LSTM.h5',\n './models/raw_AE_LSTM.h5',\n './models/raw_BiLSTM.h5',\n './models/raw_AE_BiLSTM.h5']",
"_____no_output_____"
]
],
[
[
"### data loading",
"_____no_output_____"
]
],
[
[
"l = np.load('./env_set/dataset.npz')\ntrain_input = l['train_input']\ntrain_label = l['train_label']\ntest_input = l['test_input']\ntest_label = l['test_label']\nMAXS = l['MAXS']\nMINS = l['MINS']\n\nTIME_STEPS = l['TIME_STEPS']\nOUTPUT_SIZE = l['OUTPUT_SIZE']\nNUM_FEATURES = train_input.shape[-1]",
"_____no_output_____"
],
[
"print(train_input.shape)\nprint(train_label.shape)\nprint()\nprint(test_input.shape)\nprint(test_label.shape)",
"(41025, 24, 5)\n(41025, 24, 5)\n\n(16119, 24, 5)\n(16119, 24, 5)\n"
],
[
"BATCH_SIZE = 32\ntest_dataset = tf.data.Dataset.from_tensor_slices((test_input, test_label))\ntest_dataset = test_dataset.batch(BATCH_SIZE)",
"_____no_output_____"
]
],
[
[
"# Model loading",
"_____no_output_____"
]
],
[
[
"class RetrainLayer(tf.keras.layers.Layer):\n def __init__(self, num_hidden, activation=tf.nn.relu):\n super(RetrainLayer, self).__init__()\n self.num_hidden = num_hidden\n \n self.dense = tf.keras.layers.Dense(self.num_hidden, activation=activation, kernel_initializer='he_uniform')\n \n def call(self, inp):\n return self.dense(inp)",
"_____no_output_____"
],
[
"class Encoder(tf.keras.layers.Layer):\n def __init__(self, num_hiddens, encoding_size):\n super(Encoder, self).__init__()\n \n self.num_hiddens = num_hiddens\n self.encoding_size = encoding_size\n \n self.denses = [tf.keras.layers.Dense(self.num_hiddens[_], activation=tf.nn.relu, kernel_initializer='he_uniform')\n for _ in range(len(self.num_hiddens))]\n \n self.output_layer = tf.keras.layers.Dense(self.encoding_size, activation=tf.nn.sigmoid)\n \n def call(self, inp):\n for _ in range(len(self.num_hiddens)):\n inp = self.denses[_](inp)\n \n return self.output_layer(inp) ",
"_____no_output_____"
],
[
"class Decoder(tf.keras.layers.Layer):\n def __init__(self, num_hiddens, original_size):\n super(Decoder, self).__init__()\n \n self.num_hiddens = num_hiddens[::-1]\n self.original_size = original_size\n \n self.denses = [tf.keras.layers.Dense(self.num_hiddens[_], activation=tf.nn.relu, kernel_initializer='he_uniform')\n for _ in range(len(self.num_hiddens))]\n \n def call(self, inp):\n for _ in range(len(self.num_hiddens)):\n inp = self.denses[_](inp)\n \n return inp",
"_____no_output_____"
],
[
"class Autoencoder(tf.keras.Model):\n def __init__(self, num_hiddens, encoding_size, original_size):\n super(Autoencoder, self).__init__()\n self.num_hiddens = num_hiddens\n self.encoding_size = encoding_size\n self.original_size = original_size\n \n self.in_retrain_layer = RetrainLayer(self.num_hiddens[0])\n self.encoder = Encoder(self.num_hiddens, self.encoding_size)\n self.decoder = Decoder(self.num_hiddens, self.original_size)\n self.out_retrain_layer = RetrainLayer(self.original_size, activation = tf.nn.sigmoid)\n \n def call(self, inp, need_code=False, decoding=None):\n inp = self.in_retrain_layer(inp)\n encoded_values = self.encoder(inp)\n if decoding is not None:\n decoding = self.decoder(decoding)\n return self.out_retrain_layer(decoding)\n if not need_code:\n encoded_values = self.decoder(encoded_values)\n return self.out_retrain_layer(encoded_values)\n else:\n return encoded_values",
"_____no_output_____"
],
[
"num_hiddens = [32, 16]\nencoding_size = 8\noriginal_size = 5\nautoencoder = Autoencoder(num_hiddens, encoding_size, original_size)",
"_____no_output_____"
],
[
"autoencoder.load_weights('./checkpoints/trained_AE')",
"_____no_output_____"
],
[
"mlp_model = tf.keras.models.load_model(BEST_PATHS[0])\nlstm_model = tf.keras.models.load_model(BEST_PATHS[1])\nbilstm_model = tf.keras.models.load_model(BEST_PATHS[3])\nae_lstm_model = tf.keras.models.load_model(BEST_PATHS[2])\nae_bilstm_model = tf.keras.models.load_model(BEST_PATHS[4])",
"_____no_output_____"
],
[
"autoencoder.trainable = True",
"_____no_output_____"
]
],
[
[
"# Model evaluation w/o transfer",
"_____no_output_____"
]
],
[
[
"mlp_pred = mlp_model.predict(test_dataset)\nlstm_pred = lstm_model.predict(test_dataset)\nbilstm_pred = bilstm_model.predict(test_dataset)",
"_____no_output_____"
],
[
"encoded_test_input = []\nencoded_test_label = []\nfor step, (inp, tar) in enumerate(test_dataset):\n encoded_test_input.append(autoencoder(inp, True))\n encoded_test_label.append(autoencoder(tar, True))\nencoded_test_input = np.concatenate(encoded_test_input, axis=0)\nencoded_test_label = np.concatenate(encoded_test_label, axis=0)\nencoded_test_dataset = tf.data.Dataset.from_tensor_slices((encoded_test_input, encoded_test_label))\nencoded_test_dataset = encoded_test_dataset.batch(BATCH_SIZE)",
"WARNING:tensorflow:Layer autoencoder is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because it's dtype defaults to floatx.\n\nIf you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.\n\nTo change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.\n\n"
],
[
"_ = ae_lstm_model.predict(encoded_test_dataset)\nae_lstm_pred = autoencoder(train_input[0:1, :, :], decoding=_)\n_ = ae_bilstm_model.predict(encoded_test_dataset)\nae_bilstm_pred = autoencoder(train_input[0:1, :, :], decoding=_)",
"_____no_output_____"
],
[
"test_label = tf.cast((MAXS-MINS)*test_label + MINS, tf.float32).numpy()\nmlp_pred = tf.cast((MAXS-MINS)*mlp_pred + MINS, tf.float32).numpy()\nlstm_pred = tf.cast((MAXS-MINS)*lstm_pred + MINS, tf.float32).numpy()\nbilstm_pred = tf.cast((MAXS-MINS)*bilstm_pred + MINS, tf.float32).numpy()\nae_lstm_pred = tf.cast((MAXS-MINS)*ae_lstm_pred + MINS, tf.float32).numpy()\nae_bilstm_pred = tf.cast((MAXS-MINS)*ae_bilstm_pred + MINS, tf.float32).numpy()",
"_____no_output_____"
],
[
"pd.DataFrame(test_label.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/test_label.csv')\npd.DataFrame(mlp_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/mlp_pred.csv')\npd.DataFrame(lstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/lstm_pred.csv')\npd.DataFrame(bilstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/bilstm_pred.csv')\npd.DataFrame(ae_lstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/ae_lstm_pred.csv')\npd.DataFrame(ae_bilstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/ae_bilstm_pred.csv')",
"_____no_output_____"
]
],
[
[
"# Model evaluation w/ transfer",
"_____no_output_____"
]
],
[
[
"l = np.load('./env_set/val_dataset.npz')\ntrain_input = l['train_input']\ntrain_label = l['train_label']\ntest_input = l['test_input']\ntest_label = l['test_label']\nMAXS = l['MAXS']\nMINS = l['MINS']\n\nTIME_STEPS = l['TIME_STEPS']\nOUTPUT_SIZE = l['OUTPUT_SIZE']\nNUM_FEATURES = train_input.shape[-1]",
"_____no_output_____"
],
[
"print(train_input.shape)\nprint(train_label.shape)\nprint()\nprint(test_input.shape)\nprint(test_label.shape)",
"_____no_output_____"
],
[
"BATCH_SIZE = 32\ntest_dataset = tf.data.Dataset.from_tensor_slices((test_input, test_label))\ntest_dataset = test_dataset.batch(BATCH_SIZE)",
"_____no_output_____"
],
[
"mlp_pred = mlp_model.predict(test_dataset)\nlstm_pred = lstm_model.predict(test_dataset)\nbilstm_pred = bilstm_model.predict(test_dataset)",
"_____no_output_____"
],
[
"encoded_test_input = []\nencoded_test_label = []\nfor step, (inp, tar) in enumerate(test_dataset):\n encoded_test_input.append(autoencoder(inp, True))\n encoded_test_label.append(autoencoder(tar, True))\nencoded_test_input = np.concatenate(encoded_test_input, axis=0)\nencoded_test_label = np.concatenate(encoded_test_label, axis=0)\nencoded_test_dataset = tf.data.Dataset.from_tensor_slices((encoded_test_input, encoded_test_label))\nencoded_test_dataset = encoded_test_dataset.batch(BATCH_SIZE)",
"_____no_output_____"
],
[
"_ = ae_lstm_model.predict(encoded_test_dataset)\nae_lstm_pred = autoencoder(train_input[0:1, :, :], decoding=_)\n_ = ae_bilstm_model.predict(encoded_test_dataset)\nae_bilstm_pred = autoencoder(train_input[0:1, :, :], decoding=_)",
"_____no_output_____"
],
[
"test_label = tf.cast((MAXS-MINS)*test_label + MINS, tf.float32).numpy()\nmlp_pred = tf.cast((MAXS-MINS)*mlp_pred + MINS, tf.float32).numpy()\nlstm_pred = tf.cast((MAXS-MINS)*lstm_pred + MINS, tf.float32).numpy()\nbilstm_pred = tf.cast((MAXS-MINS)*bilstm_pred + MINS, tf.float32).numpy()\nae_lstm_pred = tf.cast((MAXS-MINS)*ae_lstm_pred + MINS, tf.float32).numpy()\nae_bilstm_pred = tf.cast((MAXS-MINS)*ae_bilstm_pred + MINS, tf.float32).numpy()",
"_____no_output_____"
],
[
"pd.DataFrame(test_label.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_test_label.csv')\npd.DataFrame(mlp_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_mlp_pred.csv')\npd.DataFrame(lstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_lstm_pred.csv')\npd.DataFrame(bilstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_bilstm_pred.csv')\npd.DataFrame(ae_lstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_ae_lstm_pred.csv')\npd.DataFrame(ae_bilstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_ae_bilstm_pred.csv')",
"_____no_output_____"
],
[
"l = np.load('./env_set/val_dataset.npz')\ntrain_input = l['train_input']\ntrain_label = l['train_label']\ntest_input = l['test_input']\ntest_label = l['test_label']\nMAXS = l['MAXS']\nMINS = l['MINS']\n\nTIME_STEPS = l['TIME_STEPS']\nOUTPUT_SIZE = l['OUTPUT_SIZE']\nNUM_FEATURES = train_input.shape[-1]",
"_____no_output_____"
],
[
"print(train_input.shape)\nprint(train_label.shape)\nprint()\nprint(test_input.shape)\nprint(test_label.shape)",
"_____no_output_____"
],
[
"BATCH_SIZE = 32\ntest_dataset = tf.data.Dataset.from_tensor_slices((test_input, test_label))\ntest_dataset = test_dataset.batch(BATCH_SIZE)",
"_____no_output_____"
],
[
"num_hiddens = [32, 16]\nencoding_size = 8\noriginal_size = 5\ntrans_ae = Autoencoder(num_hiddens, encoding_size, original_size)",
"_____no_output_____"
],
[
"trans_ae.load_weights('./models/trans_ae')\nprint('transfered AE is ready.')",
"_____no_output_____"
],
[
"tr_mlp_model = tf.keras.models.load_model(TRANS_BEST_PATHS[0])\ntr_lstm_model = tf.keras.models.load_model(TRANS_BEST_PATHS[1])\ntr_bilstm_model = tf.keras.models.load_model(TRANS_BEST_PATHS[3])\ntr_ae_lstm_model = tf.keras.models.load_model(TRANS_BEST_PATHS[2])\ntr_ae_bilstm_model = tf.keras.models.load_model(TRANS_BEST_PATHS[4])",
"_____no_output_____"
],
[
"trans_ae.trainable = True",
"_____no_output_____"
],
[
"tr_mlp_pred = tr_mlp_model.predict(test_dataset)\ntr_lstm_pred = tr_lstm_model.predict(test_dataset)\ntr_bilstm_pred = tr_bilstm_model.predict(test_dataset)",
"_____no_output_____"
],
[
"encoded_test_input = []\nencoded_test_label = []\nfor step, (inp, tar) in enumerate(test_dataset):\n encoded_test_input.append(trans_ae(inp, True))\n encoded_test_label.append(trans_ae(tar, True))\nencoded_test_input = np.concatenate(encoded_test_input, axis=0)\nencoded_test_label = np.concatenate(encoded_test_label, axis=0)\nencoded_test_dataset = tf.data.Dataset.from_tensor_slices((encoded_test_input, encoded_test_label))\nencoded_test_dataset = encoded_test_dataset.batch(BATCH_SIZE)",
"_____no_output_____"
],
[
"_ = tr_ae_lstm_model.predict(encoded_test_dataset)\ntr_ae_lstm_pred = trans_ae(train_input[0:1, :, :], decoding=_)\n_ = tr_ae_bilstm_model.predict(encoded_test_dataset)\ntr_ae_bilstm_pred = trans_ae(train_input[0:1, :, :], decoding=_)",
"_____no_output_____"
],
[
"test_label = tf.cast((MAXS-MINS)*test_label + MINS, tf.float32).numpy()\ntr_mlp_pred = tf.cast((MAXS-MINS)*tr_mlp_pred + MINS, tf.float32).numpy()\ntr_lstm_pred = tf.cast((MAXS-MINS)*tr_lstm_pred + MINS, tf.float32).numpy()\ntr_bilstm_pred = tf.cast((MAXS-MINS)*tr_bilstm_pred + MINS, tf.float32).numpy()\ntr_ae_lstm_pred = tf.cast((MAXS-MINS)*tr_ae_lstm_pred + MINS, tf.float32).numpy()\ntr_ae_bilstm_pred = tf.cast((MAXS-MINS)*tr_ae_bilstm_pred + MINS, tf.float32).numpy()",
"_____no_output_____"
],
[
"pd.DataFrame(test_label.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_tr_test_label.csv')\npd.DataFrame(tr_mlp_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_tr_mlp_pred.csv')\npd.DataFrame(tr_lstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_tr_lstm_pred.csv')\npd.DataFrame(tr_bilstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_tr_bilstm_pred.csv')\npd.DataFrame(tr_ae_lstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_tr_ae_lstm_pred.csv')\npd.DataFrame(tr_ae_bilstm_pred.reshape(-1, 5), columns=['T_in', 'T_out', 'RH_in', 'CO2', 'Rad']).to_csv('./results/val_tr_ae_bilstm_pred.csv')",
"_____no_output_____"
]
],
[
[
"# Model evaluation w/ transfer (tom)",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
ece7494333021d1eb92c1015664d034f610bbf14 | 1,026,690 | ipynb | Jupyter Notebook | analysis_followers.ipynb | peguerosdc/pegawards | 3248a579e361c4f664a3b451a38b1e42719c6ca3 | [
"MIT"
] | null | null | null | analysis_followers.ipynb | peguerosdc/pegawards | 3248a579e361c4f664a3b451a38b1e42719c6ca3 | [
"MIT"
] | null | null | null | analysis_followers.ipynb | peguerosdc/pegawards | 3248a579e361c4f664a3b451a38b1e42719c6ca3 | [
"MIT"
] | null | null | null | 2,444.5 | 329,256 | 0.709056 | [
[
[
"# Analysis of Followers",
"_____no_output_____"
]
],
[
[
"import glob\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nfrom matplotlib import pyplot as plt\nsns.set_theme(style=\"darkgrid\")",
"_____no_output_____"
]
],
[
[
"First, read all the files belonging to the followers and group them by id to sum their counts",
"_____no_output_____"
]
],
[
[
"df = pd.concat([pd.read_csv(f, index_col=0) for f in glob.glob('./data/*_followers.csv')], ignore_index=False)\n# group them by id to sum the counts\ndf = df.groupby([\"id\"]).sum()\n# store the total amount of interactions\ndf[\"total\"] = df[\"quote_count\"] + df[\"reply_count\"] + df[\"retweet_count\"] + df[\"like_count\"]\n# make data anonymous\ndf = df.reset_index().drop(columns=[\"id\"])\ndf",
"_____no_output_____"
]
],
[
[
"Inspect the distributions for each interaction",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(15,7))\n_ = sns.boxplot(data=df, ax=ax)\n_ = sns.stripplot(data=df, color=\".3\", ax=ax)",
"_____no_output_____"
]
],
[
[
"We are not interested in people without interactions (which are a lot) and there are outliers in the upper limit that need to be filtered.\nLet's get the distribution for each filtered quantity independently.",
"_____no_output_____"
]
],
[
[
"def find_outliers_limit(df, col, z=1.5):\n q25, q75 = np.percentile(df[col], 25), np.percentile(df[col], 75)\n iqr = q75 - q25\n cut_off = iqr * z\n lower, upper = q25 - cut_off, q75 + cut_off\n return lower,upper\n\ndef get_outliers_filter(data, col):\n lower, upper = find_outliers_limit(data, col)\n return (data[col] < lower) | (data[col] > upper)\n\ndef remove_with_iqr(df, col):\n return df[ ~get_outliers_filter(df,col) ]\n\ndef remove_dummy(df, col):\n thresholds = {\n \"reply_count\" : 100,\n \"retweet_count\" : 100,\n \"like_count\" : 200,\n \"total\" : 300\n }\n return df[( df[col] < thresholds[col] )]\n\n# remove zeros\ndf = df[ (df[\"total\"]>0) ]\n# remove outliers with \ncols=[\"reply_count\", \"like_count\", \"total\"]\nfor col in cols:\n df = remove_dummy(df, col)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(ncols=len(df.columns))\nplt.subplots_adjust(right=3, wspace=1)\nfor i, col in enumerate(df.columns):\n sns.boxplot(y=df[col], ax = ax[i])\n sns.stripplot(y=df[col], color=\".3\", ax=ax[i])",
"_____no_output_____"
],
[
"from matplotlib.ticker import MaxNLocator\nfig, axs = plt.subplots(2, 3, figsize=(19,16))\naxs[1,2].set_visible(False)\n\n# for likes\nax = axs[0,0]\nbins = np.arange(0,160,1)\n#sns.histplot(data=df, x=\"like_count\", bins=bins, alpha=0.4, ax=ax, kde=True)\nsns.kdeplot(data=df, x=\"like_count\", ax=ax, fill=True)\n_ = ax.set_xlim(0,200)\nax.xaxis.set_major_locator(MaxNLocator(integer=True))\n\n# for replies\nax = axs[0,1]\nbins = np.arange(0,85,1)\n##sns.histplot(data=df, x=\"reply_count\", bins=bins, stat=\"probability\", alpha=0.4, ax=ax)\nsns.kdeplot(data=df, x=\"reply_count\", ax=ax, fill=True)\n_ = ax.set_xlim(0,85)\n\n# for quotes\nax = axs[0,2]\nbins = np.arange(0,2,0.5)\n#sns.histplot(data=df, x=\"quote_count\", bins=bins, stat=\"probability\", alpha=0.4, ax=ax)\nsns.kdeplot(data=df, x=\"quote_count\", ax=ax, fill=True)\n_ = ax.set_xlim(0,2)\n\n# for retweets\nax = axs[1,0]\nbins = np.arange(0,2,0.5)\n#sns.histplot(data=df, x=\"retweet_count\", bins=bins, stat=\"probability\", alpha=0.4, ax=ax)\nsns.kdeplot(data=df, x=\"retweet_count\", ax=ax, fill=True)\n\n# for total\nax = axs[1,1]\nbins = np.arange(0,250,1)\n#sns.histplot(data=df, x=\"total\", bins=bins, stat=\"probability\", alpha=0.4, ax=ax)\nsns.kdeplot(data=df, x=\"total\", ax=ax, fill=True)\n_ = ax.set_xlim(0,250)",
"_____no_output_____"
],
[
"sns.pairplot(df, diag_kind=\"kde\")",
"_____no_output_____"
]
],
[
[
"TODO:\n- Usar pairplto para cambiar el bineado \n - https://stackoverflow.com/questions/56384137/custom-binning-in-seaborn-pairplot\n - https://stackoverflow.com/questions/59696426/how-to-change-the-number-of-bins-in-seaborns-pairplot-function",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
ece74fc80843671d26e98c7d9783284a33811b96 | 4,354 | ipynb | Jupyter Notebook | homeworks/assignments/stats_practice.ipynb | ggerlach1/BIOF085 | 650345c62e0d6bdeb43da82bd1265d9283a1bb3a | [
"MIT"
] | null | null | null | homeworks/assignments/stats_practice.ipynb | ggerlach1/BIOF085 | 650345c62e0d6bdeb43da82bd1265d9283a1bb3a | [
"MIT"
] | null | null | null | homeworks/assignments/stats_practice.ipynb | ggerlach1/BIOF085 | 650345c62e0d6bdeb43da82bd1265d9283a1bb3a | [
"MIT"
] | null | null | null | 29.026667 | 118 | 0.49977 | [
[
[
"### NOTES: Broad instructions are commented with \"###\", \n### shorter instructions and questions with \"#\".\n### Code will not run until TODOs are filled in!",
"_____no_output_____"
],
[
"### imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.stats as sc",
"_____no_output_____"
],
[
"### load data using pandas (load_csv)\ndata = # TODO: finish this line\n\ndata.head() # look at the data. \ndata.shape # and its shape/size\n# What features are included? What are their types? Which ones might be related?",
"_____no_output_____"
],
[
"### get descriptive stats for a continuous variable column\n# is there a useful way to group the data?\ndata.groupby(['']) # TODO: finish this line to get means for each group",
"_____no_output_____"
],
[
"### visualize descriptive stats\n# This example uses boxplots, but other visualizations might also work well\n\na = # TODO: finish this line. select a subgroup of the data to view stats for \nb = # TODO: finish this line. select a subgroup of the data to view stats for \n\nfig,ax = plt.subplots(1,2,figsize=(10,5))\nax[0].boxplot(data[a]['']) # TODO: finish this line. what is the dep variable?\nax[1].boxplot(data[b]['']) # TODO: finish this line. what is the dep variable?",
"_____no_output_____"
],
[
"### statistical test to compare two groups \n# how are the two groups (a and b defined above) best compared? \n# are the data for these groups independent? \nsc.ttest_ind(data[a][''], data[b][''],nan_policy='omit') # TODO: finish this line. what is being compared?\n",
"_____no_output_____"
],
[
"### visualize a relationship between two variables\n# plot a scatterplot of two variables.\nplt.scatter(data[''],data['']) # TODO: finish this line. what is being plotted?\nplt.xlabel(\"Var1\") # feel free to rename \"Var1\" and \"Var2\" to the correct variable names.\nplt.ylabel(\"Var2\")",
"_____no_output_____"
],
[
"### linear regression of two variables\n# fit linear regression \nlinreg = sc.linregress(data[''],data['']) # TODO: finish this line\nprint(\"R = \"+str(linreg.rvalue))\n\n# how well does it fit?",
"_____no_output_____"
],
[
"### what other tests, statistical summaries, or visualizations could be useful?\n\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece75955503b65a0ce7d1ce4fb69ba5b8f9c83a0 | 95,918 | ipynb | Jupyter Notebook | climate_starter.ipynb | Astrowizard/sqlalchemy-challenge | db4b2d0b05307052a8ee265e71b70c58b8cb174b | [
"ADSL"
] | null | null | null | climate_starter.ipynb | Astrowizard/sqlalchemy-challenge | db4b2d0b05307052a8ee265e71b70c58b8cb174b | [
"ADSL"
] | null | null | null | climate_starter.ipynb | Astrowizard/sqlalchemy-challenge | db4b2d0b05307052a8ee265e71b70c58b8cb174b | [
"ADSL"
] | null | null | null | 79.402318 | 21,652 | 0.713161 | [
[
[
"%matplotlib inline\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"import datetime as dt",
"_____no_output_____"
]
],
[
[
"# Reflect Tables into SQLAlchemy ORM",
"_____no_output_____"
]
],
[
[
"# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func",
"_____no_output_____"
],
[
"engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")",
"_____no_output_____"
],
[
"# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)",
"_____no_output_____"
],
[
"# We can view all of the classes that automap found\nBase.classes.keys()",
"_____no_output_____"
],
[
"# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station",
"_____no_output_____"
],
[
"# Create our session (link) from Python to the DB\nsession = Session(engine)",
"_____no_output_____"
]
],
[
[
"# Exploratory Climate Analysis",
"_____no_output_____"
]
],
[
[
"# Design a query to retrieve the last 12 months of precipitation data and plot the results\n\n# Calculate the date 1 year ago from the last data point in the database\n\n# Perform a query to retrieve the data and precipitation scores\n\n# Save the query results as a Pandas DataFrame and set the index to the date column\n\n# Sort the dataframe by date\n\n# Use Pandas Plotting with Matplotlib to plot the data\nq = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n\nlast_day = q[0]\n\nlast_day = dt.datetime.strptime(last_day, '%Y-%m-%d')\n\none_year = last_day - dt.timedelta(days=365)\n\nq1 = session.query(Measurement.prcp,Measurement.date).\\\n filter(Measurement.date >= one_year.date().strftime('%Y-%m-%d'))\n\ndf = pd.DataFrame(q1,columns=['Precipitation','Date'])\ndf = df.set_index('Date')\ndf.fillna(0)\ndf.plot()",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"# Use Pandas to calcualte the summary statistics for the precipitation data\ndf.describe()",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"# Design a query to show how many stations are available in this dataset?\nsession.query(Station).count()",
"_____no_output_____"
],
[
"last_day",
"_____no_output_____"
],
[
"# What are the most active stations? (i.e. what stations have the most rows)?\n# List the stations and the counts in descending order.\nq = session.query(Station.name,Measurement.station,func.count(Measurement.station)).\\\n filter(Station.station == Measurement.station).\\\n group_by(Measurement.station).\\\n order_by(func.count(Measurement.station).desc())\nfor i in q:\n print(i)\n \nhigh_measurement = session.query(Measurement.station).\\\n filter(Station.station == Measurement.station).\\\n group_by(Measurement.station).\\\n order_by(func.count(Measurement.station).desc()).first()",
"('WAIHEE 837.5, HI US', 'USC00519281', 2772)\n('WAIKIKI 717.2, HI US', 'USC00519397', 2724)\n('KANEOHE 838.1, HI US', 'USC00513117', 2709)\n('WAIMANALO EXPERIMENTAL FARM, HI US', 'USC00519523', 2669)\n('MANOA LYON ARBO 785.2, HI US', 'USC00516128', 2612)\n('KUALOA RANCH HEADQUARTERS 886.9, HI US', 'USC00514830', 2202)\n('HONOLULU OBSERVATORY 702.2, HI US', 'USC00511918', 1979)\n('PEARL CITY, HI US', 'USC00517948', 1372)\n('UPPER WAHIAWA 874.3, HI US', 'USC00518838', 511)\n"
],
[
"# Using the station id from the previous query, calculate the lowest temperature recorded, \n# highest temperature recorded, and average temperature most active station?\nq = session.query(func.avg(Measurement.tobs),func.min(Measurement.tobs),func.max(Measurement.tobs))\\\n .filter(Measurement.station == high_measurement[0])\n\nfor i in q:\n print(i)",
"(71.66378066378067, 54.0, 85.0)\n"
],
[
"# Choose the station with the highest number of temperature observations.\n# Query the last 12 months of temperature observation data for this station and plot the results as a histogram\n\nq1 = session.query(Measurement.tobs,Measurement.date).\\\n filter(Measurement.date >= one_year.date().strftime('%Y-%m-%d'))\ndf = pd.DataFrame(q1,columns=['Temperature','Date'])\ndf.dropna()\ndf.plot.hist()",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"# This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' \n# and return the minimum, average, and maximum temperatures for that range of dates\ndef calc_temps(start_date, end_date):\n \"\"\"TMIN, TAVG, and TMAX for a list of dates.\n \n Args:\n start_date (string): A date string in the format %Y-%m-%d\n end_date (string): A date string in the format %Y-%m-%d\n \n Returns:\n TMIN, TAVE, and TMAX\n \"\"\"\n \n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date)\n\n# function usage example\nprint(calc_temps('2012-02-28', '2012-03-05'))",
"SELECT min(measurement.tobs) AS min_1, avg(measurement.tobs) AS avg_1, max(measurement.tobs) AS max_1 \nFROM measurement \nWHERE measurement.date >= ? AND measurement.date <= ?\n"
],
[
"# Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax \n# for your trip using the previous year's data for those same dates.\nstart = '2015-02-12'\nend = '2015-02-15'\n\nt = calc_temps(start,end)\nptp = t[0][2] - t[0][0]\ntavg = t[0][1]",
"_____no_output_____"
],
[
"#Plot the results from your previous query as a bar chart. \n#Use \"Trip Avg Temp\" as your Title\n#Use the average temperature for the y value\n#Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr)\nplt.bar(1,tavg,color='r',alpha = .5,width=.05,tick_label=['AVG'])\nplt.errorbar(1,tavg,yerr=ptp)",
"_____no_output_____"
],
[
"# Calculate the total amount of rainfall per weather station for your trip dates using the previous year's matching dates.\n# Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation\n\ndef cal_prcp(start, end):\n return session.query(Measurement.station,Station.name,Station.latitude,Station.longitude,Station.elevation).\\\n filter(Station.station == Measurement.station).\\\n filter(Measurement.date >= start).\\\n filter(Measurement.date >= end).\\\n order_by(Measurement.prcp.desc())",
"_____no_output_____"
],
[
"r = cal_prcp('2017-05-19','2017-05-25')\n\nfor i in r:\n print (i)",
"('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00519397', 'WAIKIKI 717.2, HI US', 21.2716, -157.8168, 3.0)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00513117', 'KANEOHE 838.1, HI US', 21.4234, -157.8015, 14.6)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00519281', 'WAIHEE 837.5, HI US', 21.45167, -157.84888999999998, 32.9)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00514830', 'KUALOA RANCH HEADQUARTERS 886.9, HI US', 21.5213, -157.8374, 7.0)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00517948', 'PEARL CITY, HI US', 21.3934, -157.9751, 11.9)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00519523', 'WAIMANALO EXPERIMENTAL FARM, HI US', 21.33556, -157.71139, 19.5)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n('USC00516128', 'MANOA LYON ARBO 785.2, HI US', 21.3331, -157.8025, 152.4)\n"
]
],
[
[
"## Optional Challenge Assignment",
"_____no_output_____"
]
],
[
[
"# Create a query that will calculate the daily normals \n# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)\n\ndef daily_normals(date):\n \"\"\"Daily Normals.\n \n Args:\n date (str): A date string in the format '%m-%d'\n \n Returns:\n A list of tuples containing the daily normals, tmin, tavg, and tmax\n \n \"\"\"\n \n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n return session.query(*sel).filter(func.strftime(\"%m-%d\", Measurement.date) == date).all()\n \ndaily_normals(\"01-01\")",
"_____no_output_____"
],
[
"# calculate the daily normals for your trip\n# push each tuple of calculations into a list called `normals`\n\n# Set the start and end date of the trip\n\n# Use the start and end date to create a range of dates\n\n# Stip off the year and save a list of %m-%d strings\n\n# Loop through the list of %m-%d strings and calculate the normals for each date\n",
"_____no_output_____"
],
[
"# Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index\n",
"_____no_output_____"
],
[
"# Plot the daily normals as an area plot with `stacked=False`\n",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
ece75e59e6470c3bf3378795d000f7bd831adfff | 25,585 | ipynb | Jupyter Notebook | nmt/Khasi-English_kha-eng.ipynb | WangXingqiu/machine-translation | ba6e9556645c777d8a15dbb3bec11521a75744a9 | [
"MIT"
] | 3 | 2020-12-16T03:58:09.000Z | 2021-06-06T07:25:35.000Z | nmt/Khasi-English_kha-eng.ipynb | WangXingqiu/machine-translation | ba6e9556645c777d8a15dbb3bec11521a75744a9 | [
"MIT"
] | null | null | null | nmt/Khasi-English_kha-eng.ipynb | WangXingqiu/machine-translation | ba6e9556645c777d8a15dbb3bec11521a75744a9 | [
"MIT"
] | 2 | 2020-12-20T03:18:06.000Z | 2021-06-06T07:25:55.000Z | 29.140091 | 342 | 0.542935 | [
[
[
"# 基于注意力的神经机器翻译",
"_____no_output_____"
],
[
"此笔记本训练一个将卡西语翻译为英语的序列到序列(sequence to sequence,简写为 seq2seq)模型。此例子难度较高,需要对序列到序列模型的知识有一定了解。\n\n训练完此笔记本中的模型后,你将能够输入一个卡西语句子,例如 *\"Long jaijai\"*,并返回其英语翻译 *\"Be cool.\"*\n\n对于一个简单的例子来说,翻译质量令人满意。但是更有趣的可能是生成的注意力图:它显示在翻译过程中,输入句子的哪些部分受到了模型的注意。\n\n<img src=\"https://tensorflow.google.cn/images/spanish-english.png\" alt=\"spanish-english attention plot\">\n\n请注意:运行这个例子用一个 P100 GPU 需要花大约 10 分钟。",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom sklearn.model_selection import train_test_split\n\nimport unicodedata\nimport re\nimport numpy as np\nimport os\nimport io\nimport time",
"_____no_output_____"
]
],
[
[
"## 下载和准备数据集\n\n我们将使用 http://www.manythings.org/anki/ 提供的一个语言数据集。这个数据集包含如下格式的语言翻译对:\n\n```\nMay I borrow this book?\t¿Puedo tomar prestado este libro?\n```\n\n这个数据集中有很多种语言可供选择。我们将使用英语 - 卡西语数据集。为方便使用,我们在谷歌云上提供了此数据集的一份副本。但是你也可以自己下载副本。下载完数据集后,我们将采取下列步骤准备数据:\n\n1. 给每个句子添加一个 *开始* 和一个 *结束* 标记(token)。\n2. 删除特殊字符以清理句子。\n3. 创建一个单词索引和一个反向单词索引(即一个从单词映射至 id 的词典和一个从 id 映射至单词的词典)。\n4. 将每个句子填充(pad)到最大长度。",
"_____no_output_____"
]
],
[
[
"'''\n# 下载文件\npath_to_zip = tf.keras.utils.get_file(\n 'spa-eng.zip', origin='http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip',\n extract=True)\n\npath_to_file = os.path.dirname(path_to_zip)+\"/spa-eng/spa.txt\"\n'''\npath_to_file = \"./lan/kha.txt\"",
"_____no_output_____"
],
[
"# 将 unicode 文件转换为 ascii\ndef unicode_to_ascii(s):\n return ''.join(c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn')\n\n\ndef preprocess_sentence(w):\n w = unicode_to_ascii(w.lower().strip())\n\n # 在单词与跟在其后的标点符号之间插入一个空格\n # 例如: \"he is a boy.\" => \"he is a boy .\"\n # 参考:https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation\n w = re.sub(r\"([?.!,¿])\", r\" \\1 \", w)\n w = re.sub(r'[\" \"]+', \" \", w)\n\n # 除了 (a-z, A-Z, \".\", \"?\", \"!\", \",\"),将所有字符替换为空格\n w = re.sub(r\"[^a-zA-Z?.!,¿]+\", \" \", w)\n\n w = w.rstrip().strip()\n\n # 给句子加上开始和结束标记\n # 以便模型知道何时开始和结束预测\n w = '<start> ' + w + ' <end>'\n return w",
"_____no_output_____"
],
[
"en_sentence = u\"May I borrow this book?\"\nsp_sentence = u\"¿Puedo tomar prestado este libro?\"\nprint(preprocess_sentence(en_sentence))\nprint(preprocess_sentence(sp_sentence).encode('utf-8'))",
"_____no_output_____"
],
[
"# 1. 去除重音符号\n# 2. 清理句子\n# 3. 返回这样格式的单词对:[ENGLISH, SPANISH]\ndef create_dataset(path, num_examples):\n lines = io.open(path, encoding='UTF-8').read().strip().split('\\n')\n\n word_pairs = [[preprocess_sentence(w) for w in l.split('\\t')] for l in lines[:num_examples]]\n\n return zip(*word_pairs)",
"_____no_output_____"
],
[
"en, sp = create_dataset(path_to_file, None)\nprint(en[-1])\nprint(sp[-1])",
"_____no_output_____"
],
[
"def max_length(tensor):\n return max(len(t) for t in tensor)",
"_____no_output_____"
],
[
"def tokenize(lang):\n lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(\n filters='')\n lang_tokenizer.fit_on_texts(lang)\n\n tensor = lang_tokenizer.texts_to_sequences(lang)\n\n tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor,\n padding='post')\n\n return tensor, lang_tokenizer",
"_____no_output_____"
],
[
"def load_dataset(path, num_examples=None):\n # 创建清理过的输入输出对\n targ_lang, inp_lang = create_dataset(path, num_examples)\n\n input_tensor, inp_lang_tokenizer = tokenize(inp_lang)\n target_tensor, targ_lang_tokenizer = tokenize(targ_lang)\n\n return input_tensor, target_tensor, inp_lang_tokenizer, targ_lang_tokenizer",
"_____no_output_____"
]
],
[
[
"### 限制数据集的大小以加快实验速度(可选)\n\n在超过 10 万个句子的完整数据集上训练需要很长时间。为了更快地训练,我们可以将数据集的大小限制为 3 万个句子(当然,翻译质量也会随着数据的减少而降低):",
"_____no_output_____"
]
],
[
[
"# 尝试实验不同大小的数据集\nnum_examples = 30000\ninput_tensor, target_tensor, inp_lang, targ_lang = load_dataset(path_to_file, num_examples)\n\n# 计算目标张量的最大长度 (max_length)\nmax_length_targ, max_length_inp = max_length(target_tensor), max_length(input_tensor)",
"_____no_output_____"
],
[
"# 采用 80 - 20 的比例切分训练集和验证集\ninput_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)\n\n# 显示长度\nprint(len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val))",
"_____no_output_____"
],
[
"def convert(lang, tensor):\n for t in tensor:\n if t!=0:\n print (\"%d ----> %s\" % (t, lang.index_word[t]))",
"_____no_output_____"
],
[
"print (\"Input Language; index to word mapping\")\nconvert(inp_lang, input_tensor_train[0])\nprint ()\nprint (\"Target Language; index to word mapping\")\nconvert(targ_lang, target_tensor_train[0])",
"_____no_output_____"
]
],
[
[
"### 创建一个 tf.data 数据集",
"_____no_output_____"
]
],
[
[
"BUFFER_SIZE = len(input_tensor_train)\nBATCH_SIZE = 64\nsteps_per_epoch = len(input_tensor_train)//BATCH_SIZE\nembedding_dim = 256\nunits = 1024\nvocab_inp_size = len(inp_lang.word_index)+1\nvocab_tar_size = len(targ_lang.word_index)+1\n\ndataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)\ndataset = dataset.batch(BATCH_SIZE, drop_remainder=True)",
"_____no_output_____"
],
[
"example_input_batch, example_target_batch = next(iter(dataset))\nexample_input_batch.shape, example_target_batch.shape",
"_____no_output_____"
]
],
[
[
"## 编写编码器 (encoder) 和解码器 (decoder) 模型\n\n实现一个基于注意力的编码器 - 解码器模型。关于这种模型,你可以阅读 TensorFlow 的 [神经机器翻译 (序列到序列) 教程](https://github.com/tensorflow/nmt)。本示例采用一组更新的 API。此笔记本实现了上述序列到序列教程中的 [注意力方程式](https://github.com/tensorflow/nmt#background-on-the-attention-mechanism)。下图显示了注意力机制为每个输入单词分配一个权重,然后解码器将这个权重用于预测句子中的下一个单词。下图和公式是 [Luong 的论文](https://arxiv.org/abs/1508.04025v5)中注意力机制的一个例子。\n\n<img src=\"https://tensorflow.google.cn/images/seq2seq/attention_mechanism.jpg\" width=\"500\" alt=\"attention mechanism\">\n\n输入经过编码器模型,编码器模型为我们提供形状为 *(批大小,最大长度,隐藏层大小)* 的编码器输出和形状为 *(批大小,隐藏层大小)* 的编码器隐藏层状态。\n\n下面是所实现的方程式:\n\n<img src=\"https://tensorflow.google.cn/images/seq2seq/attention_equation_0.jpg\" alt=\"attention equation 0\" width=\"800\">\n<img src=\"https://tensorflow.google.cn/images/seq2seq/attention_equation_1.jpg\" alt=\"attention equation 1\" width=\"800\">\n\n本教程的编码器采用 [Bahdanau 注意力](https://arxiv.org/pdf/1409.0473.pdf)。在用简化形式编写之前,让我们先决定符号:\n\n* FC = 完全连接(密集)层\n* EO = 编码器输出\n* H = 隐藏层状态\n* X = 解码器输入\n\n以及伪代码:\n\n* `score = FC(tanh(FC(EO) + FC(H)))`\n* `attention weights = softmax(score, axis = 1)`。 Softmax 默认被应用于最后一个轴,但是这里我们想将它应用于 *第一个轴*, 因为分数 (score) 的形状是 *(批大小,最大长度,隐藏层大小)*。最大长度 (`max_length`) 是我们的输入的长度。因为我们想为每个输入分配一个权重,所以 softmax 应该用在这个轴上。\n* `context vector = sum(attention weights * EO, axis = 1)`。选择第一个轴的原因同上。\n* `embedding output` = 解码器输入 X 通过一个嵌入层。\n* `merged vector = concat(embedding output, context vector)`\n* 此合并后的向量随后被传送到 GRU\n\n每个步骤中所有向量的形状已在代码的注释中阐明:",
"_____no_output_____"
]
],
[
[
"class Encoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):\n super(Encoder, self).__init__()\n self.batch_sz = batch_sz\n self.enc_units = enc_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.enc_units,\n return_sequences=True,\n return_state=True,\n recurrent_initializer='glorot_uniform')\n\n def call(self, x, hidden):\n x = self.embedding(x)\n output, state = self.gru(x, initial_state = hidden)\n return output, state\n\n def initialize_hidden_state(self):\n return tf.zeros((self.batch_sz, self.enc_units))",
"_____no_output_____"
],
[
"encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n\n# 样本输入\nsample_hidden = encoder.initialize_hidden_state()\nsample_output, sample_hidden = encoder(example_input_batch, sample_hidden)\nprint ('Encoder output shape: (batch size, sequence length, units) {}'.format(sample_output.shape))\nprint ('Encoder Hidden state shape: (batch size, units) {}'.format(sample_hidden.shape))",
"_____no_output_____"
],
[
"class BahdanauAttention(tf.keras.layers.Layer):\n def __init__(self, units):\n super(BahdanauAttention, self).__init__()\n self.W1 = tf.keras.layers.Dense(units)\n self.W2 = tf.keras.layers.Dense(units)\n self.V = tf.keras.layers.Dense(1)\n\n def call(self, query, values):\n # 隐藏层的形状 == (批大小,隐藏层大小)\n # hidden_with_time_axis 的形状 == (批大小,1,隐藏层大小)\n # 这样做是为了执行加法以计算分数 \n hidden_with_time_axis = tf.expand_dims(query, 1)\n\n # 分数的形状 == (批大小,最大长度,1)\n # 我们在最后一个轴上得到 1, 因为我们把分数应用于 self.V\n # 在应用 self.V 之前,张量的形状是(批大小,最大长度,单位)\n score = self.V(tf.nn.tanh(\n self.W1(values) + self.W2(hidden_with_time_axis)))\n\n # 注意力权重 (attention_weights) 的形状 == (批大小,最大长度,1)\n attention_weights = tf.nn.softmax(score, axis=1)\n\n # 上下文向量 (context_vector) 求和之后的形状 == (批大小,隐藏层大小)\n context_vector = attention_weights * values\n context_vector = tf.reduce_sum(context_vector, axis=1)\n\n return context_vector, attention_weights",
"_____no_output_____"
],
[
"attention_layer = BahdanauAttention(10)\nattention_result, attention_weights = attention_layer(sample_hidden, sample_output)\n\nprint(\"Attention result shape: (batch size, units) {}\".format(attention_result.shape))\nprint(\"Attention weights shape: (batch_size, sequence_length, 1) {}\".format(attention_weights.shape))",
"_____no_output_____"
],
[
"class Decoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):\n super(Decoder, self).__init__()\n self.batch_sz = batch_sz\n self.dec_units = dec_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.dec_units,\n return_sequences=True,\n return_state=True,\n recurrent_initializer='glorot_uniform')\n self.fc = tf.keras.layers.Dense(vocab_size)\n\n # 用于注意力\n self.attention = BahdanauAttention(self.dec_units)\n\n def call(self, x, hidden, enc_output):\n # 编码器输出 (enc_output) 的形状 == (批大小,最大长度,隐藏层大小)\n context_vector, attention_weights = self.attention(hidden, enc_output)\n\n # x 在通过嵌入层后的形状 == (批大小,1,嵌入维度)\n x = self.embedding(x)\n\n # x 在拼接 (concatenation) 后的形状 == (批大小,1,嵌入维度 + 隐藏层大小)\n x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n\n # 将合并后的向量传送到 GRU\n output, state = self.gru(x)\n\n # 输出的形状 == (批大小 * 1,隐藏层大小)\n output = tf.reshape(output, (-1, output.shape[2]))\n\n # 输出的形状 == (批大小,vocab)\n x = self.fc(output)\n\n return x, state, attention_weights",
"_____no_output_____"
],
[
"decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)\n\nsample_decoder_output, _, _ = decoder(tf.random.uniform((64, 1)),\n sample_hidden, sample_output)\n\nprint ('Decoder output shape: (batch_size, vocab size) {}'.format(sample_decoder_output.shape))",
"_____no_output_____"
]
],
[
[
"## 定义优化器和损失函数",
"_____no_output_____"
]
],
[
[
"optimizer = tf.keras.optimizers.Adam()\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True, reduction='none')\n\ndef loss_function(real, pred):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_mean(loss_)",
"_____no_output_____"
]
],
[
[
"## 检查点(基于对象保存)",
"_____no_output_____"
]
],
[
[
"checkpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(optimizer=optimizer,\n encoder=encoder,\n decoder=decoder)",
"_____no_output_____"
]
],
[
[
"## 训练\n\n1. 将 *输入* 传送至 *编码器*,编码器返回 *编码器输出* 和 *编码器隐藏层状态*。\n2. 将编码器输出、编码器隐藏层状态和解码器输入(即 *开始标记*)传送至解码器。\n3. 解码器返回 *预测* 和 *解码器隐藏层状态*。\n4. 解码器隐藏层状态被传送回模型,预测被用于计算损失。\n5. 使用 *教师强制 (teacher forcing)* 决定解码器的下一个输入。\n6. *教师强制* 是将 *目标词* 作为 *下一个输入* 传送至解码器的技术。\n7. 最后一步是计算梯度,并将其应用于优化器和反向传播。",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef train_step(inp, targ, enc_hidden):\n loss = 0\n\n with tf.GradientTape() as tape:\n enc_output, enc_hidden = encoder(inp, enc_hidden)\n\n dec_hidden = enc_hidden\n\n dec_input = tf.expand_dims([targ_lang.word_index['<start>']] * BATCH_SIZE, 1)\n\n # 教师强制 - 将目标词作为下一个输入\n for t in range(1, targ.shape[1]):\n # 将编码器输出 (enc_output) 传送至解码器\n predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)\n\n loss += loss_function(targ[:, t], predictions)\n\n # 使用教师强制\n dec_input = tf.expand_dims(targ[:, t], 1)\n\n batch_loss = (loss / int(targ.shape[1]))\n\n variables = encoder.trainable_variables + decoder.trainable_variables\n\n gradients = tape.gradient(loss, variables)\n\n optimizer.apply_gradients(zip(gradients, variables))\n\n return batch_loss",
"_____no_output_____"
],
[
"EPOCHS = 10\n\nfor epoch in range(EPOCHS):\n start = time.time()\n\n enc_hidden = encoder.initialize_hidden_state()\n total_loss = 0\n\n for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)):\n batch_loss = train_step(inp, targ, enc_hidden)\n total_loss += batch_loss\n\n if batch % 100 == 0:\n print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1,\n batch,\n batch_loss.numpy()))\n # 每 2 个周期(epoch),保存(检查点)一次模型\n if (epoch + 1) % 2 == 0:\n checkpoint.save(file_prefix = checkpoint_prefix)\n\n print('Epoch {} Loss {:.4f}'.format(epoch + 1,\n total_loss / steps_per_epoch))\n print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))",
"_____no_output_____"
]
],
[
[
"## 翻译\n\n* 评估函数类似于训练循环,不同之处在于在这里我们不使用 *教师强制*。每个时间步的解码器输入是其先前的预测、隐藏层状态和编码器输出。\n* 当模型预测 *结束标记* 时停止预测。\n* 存储 *每个时间步的注意力权重*。\n\n请注意:对于一个输入,编码器输出仅计算一次。",
"_____no_output_____"
]
],
[
[
"def evaluate(sentence):\n attention_plot = np.zeros((max_length_targ, max_length_inp))\n\n sentence = preprocess_sentence(sentence)\n\n inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]\n inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],\n maxlen=max_length_inp,\n padding='post')\n inputs = tf.convert_to_tensor(inputs)\n\n result = ''\n\n hidden = [tf.zeros((1, units))]\n enc_out, enc_hidden = encoder(inputs, hidden)\n\n dec_hidden = enc_hidden\n dec_input = tf.expand_dims([targ_lang.word_index['<start>']], 0)\n\n for t in range(max_length_targ):\n predictions, dec_hidden, attention_weights = decoder(dec_input,\n dec_hidden,\n enc_out)\n\n # 存储注意力权重以便后面制图\n attention_weights = tf.reshape(attention_weights, (-1, ))\n attention_plot[t] = attention_weights.numpy()\n\n predicted_id = tf.argmax(predictions[0]).numpy()\n\n result += targ_lang.index_word[predicted_id] + ' '\n\n if targ_lang.index_word[predicted_id] == '<end>':\n return result, sentence, attention_plot\n\n # 预测的 ID 被输送回模型\n dec_input = tf.expand_dims([predicted_id], 0)\n\n return result, sentence, attention_plot",
"_____no_output_____"
],
[
"# 注意力权重制图函数\ndef plot_attention(attention, sentence, predicted_sentence):\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1)\n ax.matshow(attention, cmap='viridis')\n\n fontdict = {'fontsize': 14}\n\n ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)\n ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)\n\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n plt.show()",
"_____no_output_____"
],
[
"def translate(sentence):\n result, sentence, attention_plot = evaluate(sentence)\n\n print('Input: %s' % (sentence))\n print('Predicted translation: {}'.format(result))\n\n attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]\n plot_attention(attention_plot, sentence.split(' '), result.split(' '))",
"_____no_output_____"
]
],
[
[
"## 恢复最新的检查点并验证",
"_____no_output_____"
]
],
[
[
"# 恢复检查点目录 (checkpoint_dir) 中最新的检查点\ncheckpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))",
"_____no_output_____"
],
[
"translate(u'hace mucho frio aqui.')",
"_____no_output_____"
],
[
"translate(u'esta es mi vida.')",
"_____no_output_____"
],
[
"translate(u'¿todavia estan en casa?')",
"_____no_output_____"
],
[
"# 错误的翻译\ntranslate(u'trata de averiguarlo.')",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
ece760081d09051d08e2a17ec8413d8246f4f5ba | 37,002 | ipynb | Jupyter Notebook | examples/notebooks/segmentation-tutorial.ipynb | TeAmP0is0N/catalyst | 445e366266196a2f1076cc7fa2438d66dfa58c14 | [
"Apache-2.0"
] | 1 | 2020-09-24T00:34:06.000Z | 2020-09-24T00:34:06.000Z | examples/notebooks/segmentation-tutorial.ipynb | TeAmP0is0N/catalyst | 445e366266196a2f1076cc7fa2438d66dfa58c14 | [
"Apache-2.0"
] | null | null | null | examples/notebooks/segmentation-tutorial.ipynb | TeAmP0is0N/catalyst | 445e366266196a2f1076cc7fa2438d66dfa58c14 | [
"Apache-2.0"
] | 1 | 2020-09-24T00:34:07.000Z | 2020-09-24T00:34:07.000Z | 26.930131 | 272 | 0.532377 | [
[
[
"# Catalyst segmentation tutorial\n\nAuthors: [Roman Tezikov](https://github.com/TezRomacH), [Dmitry Bleklov](https://github.com/Bekovmi), [Sergey Kolesnikov](https://github.com/Scitator)\n\n[](https://github.com/catalyst-team/catalyst)\n\n### Colab setup\n\nFirst of all, do not forget to change the runtime type to GPU. <br/>\nTo do so click `Runtime` -> `Change runtime type` -> Select `\"Python 3\"` and `\"GPU\"` -> click `Save`. <br/>\nAfter that you can click `Runtime` -> `Run all` and watch the tutorial.\n",
"_____no_output_____"
],
[
"\n## Requirements\n\nDownload and install the latest versions of catalyst and other libraries required for this tutorial.",
"_____no_output_____"
]
],
[
[
"# this variable will be used in `runner.train` and by default we disable FP16 mode\nis_fp16_used = False\nis_alchemy_used = False",
"_____no_output_____"
],
[
"# for augmentations\n!pip install albumentations==0.4.3\n\n# for pretrained segmentation models for PyTorch\n!pip install segmentation-models-pytorch==0.1.0\n\n# for TTA\n!pip install ttach==0.0.2\n\n################\n# Catalyst itself\n!pip install -U catalyst\n# For specific version of catalyst, uncomment:\n# ! pip install git+http://github.com/catalyst-team/catalyst.git@{master/commit_hash}\n################\n\n# for tensorboard\n!pip install tensorflow\n\n# for alchemy experiment logging integration, uncomment this 2 lines below\n# !pip install -U alchemy\n# is_alchemy_used = True\n\n# if Your machine support Apex FP16, uncomment this 3 lines below\n# !git clone https://github.com/NVIDIA/apex\n# !pip install -v --no-cache-dir --global-option=\"--cpp_ext\" --global-option=\"--cuda_ext\" ./apex\n# is_fp16_used = True",
"_____no_output_____"
]
],
[
[
"### Colab extras – Plotly\n\nTo intergate visualization library `plotly` to colab, run cell below",
"_____no_output_____"
]
],
[
[
"import IPython\n\ndef configure_plotly_browser_state():\n display(IPython.core.display.HTML('''\n <script src=\"/static/components/requirejs/require.js\"></script>\n <script>\n requirejs.config({\n paths: {\n base: '/static/base',\n plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',\n },\n });\n </script>\n '''))\n\n\nIPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)",
"_____no_output_____"
]
],
[
[
"## Setting up GPUs",
"_____no_output_____"
]
],
[
[
"from typing import Callable, List, Tuple\n\nimport os\nimport torch\nimport catalyst\n\nfrom catalyst.dl import utils\n\nprint(f\"torch: {torch.__version__}, catalyst: {catalyst.__version__}\")\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" # \"\" - CPU, \"0\" - 1 GPU, \"0,1\" - MultiGPU\n\nSEED = 42\nutils.set_global_seed(SEED)\nutils.prepare_cudnn(deterministic=True)",
"_____no_output_____"
]
],
[
[
"# Reproducibility\n\n[](https://github.com/catalyst-team/alchemy)\n\nTo make your research more reproducible and easy to monitor, Catalyst has an integration with [Alchemy](https://alchemy.host) – experiment tracking tool for deep learning.\n\nTo use monitoring, goto [Alchemy](https://alchemy.host/) and get your personal token.",
"_____no_output_____"
]
],
[
[
"# for alchemy experiment logging integration, uncomment this 2 lines below\n# !pip install -U alchemy\n# is_alchemy_used = True",
"_____no_output_____"
],
[
"if is_alchemy_used:\n monitoring_params = {\n \"token\": None, # insert your personal token here\n \"project\": \"segmentation_example\",\n \"group\": \"first_trials\",\n \"experiment\": \"first_experiment\",\n }\n assert monitoring_params[\"token\"] is not None\nelse:\n monitoring_params = None",
"_____no_output_____"
]
],
[
[
"-------",
"_____no_output_____"
],
[
"## Dataset\n\nAs a dataset we will take Carvana - binary segmentation for the \"car\" class.",
"_____no_output_____"
],
[
"> If you are on MacOS and you don’t have `wget`, you can install it with: `brew install wget`.",
"_____no_output_____"
],
[
"After Catalyst installation, `download-gdrive` function become available to download objects from Google Drive.\nWe use it to download datasets.\n\nusage: `download-gdrive {FILE_ID} {FILENAME}`",
"_____no_output_____"
]
],
[
[
"%%bash\n\ndownload-gdrive 1iYaNijLmzsrMlAdMoUEhhJuo-5bkeAuj segmentation_data.zip\nextract-archive segmentation_data.zip &>/dev/null",
"_____no_output_____"
],
[
"from pathlib import Path\n\nROOT = Path(\"segmentation_data/\")\n\ntrain_image_path = ROOT / \"train\"\ntrain_mask_path = ROOT / \"train_masks\"\ntest_image_path = ROOT / \"test\"",
"_____no_output_____"
]
],
[
[
"Collect images and masks into variables.",
"_____no_output_____"
]
],
[
[
"ALL_IMAGES = sorted(train_image_path.glob(\"*.jpg\"))\nlen(ALL_IMAGES)",
"_____no_output_____"
],
[
"ALL_MASKS = sorted(train_mask_path.glob(\"*.gif\"))\nlen(ALL_MASKS)",
"_____no_output_____"
],
[
"import random\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage.io import imread as gif_imread\nfrom catalyst import utils\n\n\ndef show_examples(name: str, image: np.ndarray, mask: np.ndarray):\n plt.figure(figsize=(10, 14))\n plt.subplot(1, 2, 1)\n plt.imshow(image)\n plt.title(f\"Image: {name}\")\n\n plt.subplot(1, 2, 2)\n plt.imshow(mask)\n plt.title(f\"Mask: {name}\")\n\n\ndef show(index: int, images: List[Path], masks: List[Path], transforms=None) -> None:\n image_path = images[index]\n name = image_path.name\n\n image = utils.imread(image_path)\n mask = gif_imread(masks[index])\n\n if transforms is not None:\n temp = transforms(image=image, mask=mask)\n image = temp[\"image\"]\n mask = temp[\"mask\"]\n\n show_examples(name, image, mask)\n\ndef show_random(images: List[Path], masks: List[Path], transforms=None) -> None:\n length = len(images)\n index = random.randint(0, length - 1)\n show(index, images, masks, transforms)",
"_____no_output_____"
]
],
[
[
"You can restart the cell below to see more examples.",
"_____no_output_____"
]
],
[
[
"show_random(ALL_IMAGES, ALL_MASKS)",
"_____no_output_____"
]
],
[
[
"The dataset below reads images and masks and optionally applies augmentation to them.",
"_____no_output_____"
]
],
[
[
"from typing import List\n\nfrom torch.utils.data import Dataset\n\n\nclass SegmentationDataset(Dataset):\n def __init__(\n self,\n images: List[Path],\n masks: List[Path] = None,\n transforms=None\n ) -> None:\n self.images = images\n self.masks = masks\n self.transforms = transforms\n\n def __len__(self) -> int:\n return len(self.images)\n\n def __getitem__(self, idx: int) -> dict:\n image_path = self.images[idx]\n image = utils.imread(image_path)\n \n result = {\"image\": image}\n \n if self.masks is not None:\n mask = gif_imread(self.masks[idx])\n result[\"mask\"] = mask\n \n if self.transforms is not None:\n result = self.transforms(**result)\n \n result[\"filename\"] = image_path.name\n\n return result",
"_____no_output_____"
]
],
[
[
"-------",
"_____no_output_____"
],
[
"### Augmentations",
"_____no_output_____"
],
[
"[](https://github.com/albu/albumentations)\n\nThe [albumentation](https://github.com/albu/albumentations) library works with images and masks at the same time, which is what we need.",
"_____no_output_____"
]
],
[
[
"import albumentations as albu\nfrom albumentations.pytorch import ToTensor\n\n\ndef pre_transforms(image_size=224):\n return [albu.Resize(image_size, image_size, p=1)]\n\n\ndef hard_transforms():\n result = [\n albu.RandomRotate90(),\n albu.Cutout(),\n albu.RandomBrightnessContrast(\n brightness_limit=0.2, contrast_limit=0.2, p=0.3\n ),\n albu.GridDistortion(p=0.3),\n albu.HueSaturationValue(p=0.3)\n ]\n\n return result\n \n\ndef resize_transforms(image_size=224):\n BORDER_CONSTANT = 0\n pre_size = int(image_size * 1.5)\n\n random_crop = albu.Compose([\n albu.SmallestMaxSize(pre_size, p=1),\n albu.RandomCrop(\n image_size, image_size, p=1\n )\n\n ])\n\n rescale = albu.Compose([albu.Resize(image_size, image_size, p=1)])\n\n random_crop_big = albu.Compose([\n albu.LongestMaxSize(pre_size, p=1),\n albu.RandomCrop(\n image_size, image_size, p=1\n )\n\n ])\n\n # Converts the image to a square of size image_size x image_size\n result = [\n albu.OneOf([\n random_crop,\n rescale,\n random_crop_big\n ], p=1)\n ]\n\n return result\n \ndef post_transforms():\n # we use ImageNet image normalization\n # and convert it to torch.Tensor\n return [albu.Normalize(), ToTensor()]\n \ndef compose(transforms_to_compose):\n # combine all augmentations into single pipeline\n result = albu.Compose([\n item for sublist in transforms_to_compose for item in sublist\n ])\n return result",
"_____no_output_____"
],
[
"train_transforms = compose([\n resize_transforms(), \n hard_transforms(), \n post_transforms()\n])\nvalid_transforms = compose([pre_transforms(), post_transforms()])\n\nshow_transforms = compose([resize_transforms(), hard_transforms()])",
"_____no_output_____"
]
],
[
[
"Let's look at the augmented results. <br/>\nYou can restart the cell below to see more examples of augmentations.",
"_____no_output_____"
]
],
[
[
"show_random(ALL_IMAGES, ALL_MASKS, transforms=show_transforms)",
"_____no_output_____"
]
],
[
[
"-------",
"_____no_output_____"
],
[
"## Loaders",
"_____no_output_____"
]
],
[
[
"import collections\nfrom sklearn.model_selection import train_test_split\n\nfrom torch.utils.data import DataLoader\n\ndef get_loaders(\n images: List[Path],\n masks: List[Path],\n random_state: int,\n valid_size: float = 0.2,\n batch_size: int = 32,\n num_workers: int = 4,\n train_transforms_fn = None,\n valid_transforms_fn = None,\n) -> dict:\n\n indices = np.arange(len(images))\n\n # Let's divide the data set into train and valid parts.\n train_indices, valid_indices = train_test_split(\n indices, test_size=valid_size, random_state=random_state, shuffle=True\n )\n\n np_images = np.array(images)\n np_masks = np.array(masks)\n\n # Creates our train dataset\n train_dataset = SegmentationDataset(\n images = np_images[train_indices].tolist(),\n masks = np_masks[train_indices].tolist(),\n transforms = train_transforms_fn\n )\n\n # Creates our valid dataset\n valid_dataset = SegmentationDataset(\n images = np_images[valid_indices].tolist(),\n masks = np_masks[valid_indices].tolist(),\n transforms = valid_transforms_fn\n )\n\n # Catalyst uses normal torch.data.DataLoader\n train_loader = DataLoader(\n train_dataset,\n batch_size=batch_size,\n shuffle=True,\n num_workers=num_workers,\n drop_last=True,\n )\n\n valid_loader = DataLoader(\n valid_dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_workers,\n drop_last=True,\n )\n\n # And excpect to get an OrderedDict of loaders\n loaders = collections.OrderedDict()\n loaders[\"train\"] = train_loader\n loaders[\"valid\"] = valid_loader\n\n return loaders",
"_____no_output_____"
],
[
"if is_fp16_used:\n batch_size = 64\nelse:\n batch_size = 32\n\nprint(f\"batch_size: {batch_size}\")\n\nloaders = get_loaders(\n images=ALL_IMAGES,\n masks=ALL_MASKS,\n random_state=SEED,\n train_transforms_fn=train_transforms,\n valid_transforms_fn=valid_transforms,\n batch_size=batch_size\n)",
"_____no_output_____"
]
],
[
[
"-------",
"_____no_output_____"
],
[
"## Experiment\n### Model\n\nCatalyst has [several segmentation models](https://github.com/catalyst-team/catalyst/blob/master/catalyst/contrib/models/segmentation/__init__.py#L16) (Unet, Linknet, FPN, PSPnet and their versions with pretrain from Resnet).\n\n> You can read more about them in [our blog post](https://github.com/catalyst-team/catalyst-info#catalyst-info-1-segmentation-models).\n\nBut for now let's take the model from [segmentation_models.pytorch](https://github.com/qubvel/segmentation_models.pytorch) (SMP for short). The same segmentation architectures have been implemented in this repository, but there are many more pre-trained encoders.\n\n[](https://github.com/qubvel/segmentation_models.pytorch)",
"_____no_output_____"
]
],
[
[
"import segmentation_models_pytorch as smp\n\n# We will use Feature Pyramid Network with pre-trained ResNeXt50 backbone\nmodel = smp.FPN(encoder_name=\"resnext50_32x4d\", classes=1)",
"_____no_output_____"
]
],
[
[
"### Model training\n\nWe will optimize loss as the sum of IoU, Dice and BCE, specifically this function: $IoU + Dice + 0.8*BCE$.\n",
"_____no_output_____"
]
],
[
[
"from torch import nn\n\nfrom catalyst.contrib.nn import DiceLoss, IoULoss\n\n# we have multiple criterions\ncriterion = {\n \"dice\": DiceLoss(),\n \"iou\": IoULoss(),\n \"bce\": nn.BCEWithLogitsLoss()\n}",
"_____no_output_____"
],
[
"from torch import optim\n\nfrom catalyst.contrib.nn import RAdam, Lookahead\n\nlearning_rate = 0.001\nencoder_learning_rate = 0.0005\n\n# Since we use a pre-trained encoder, we will reduce the learning rate on it.\nlayerwise_params = {\"encoder*\": dict(lr=encoder_learning_rate, weight_decay=0.00003)}\n\n# This function removes weight_decay for biases and applies our layerwise_params\nmodel_params = utils.process_model_params(model, layerwise_params=layerwise_params)\n\n# Catalyst has new SOTA optimizers out of box\nbase_optimizer = RAdam(model_params, lr=learning_rate, weight_decay=0.0003)\noptimizer = Lookahead(base_optimizer)\n\nscheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.25, patience=2)",
"_____no_output_____"
],
[
"from catalyst.dl import SupervisedRunner\n\nnum_epochs = 3\nlogdir = \"./logs/segmentation\"\n\ndevice = utils.get_device()\nprint(f\"device: {device}\")\n\nif is_fp16_used:\n fp16_params = dict(opt_level=\"O1\") # params for FP16\nelse:\n fp16_params = None\n\nprint(f\"FP16 params: {fp16_params}\")\n\n\n# by default SupervisedRunner uses \"features\" and \"targets\",\n# in our case we get \"image\" and \"mask\" keys in dataset __getitem__\nrunner = SupervisedRunner(device=device, input_key=\"image\", input_target_key=\"mask\")",
"_____no_output_____"
]
],
[
[
"### Monitoring in tensorboard",
"_____no_output_____"
],
[
"If you do not have a Tensorboard opened after you have run the cell below, try running the cell again.",
"_____no_output_____"
]
],
[
[
"%load_ext tensorboard\n%tensorboard --logdir {logdir}",
"_____no_output_____"
]
],
[
[
"### Running train-loop",
"_____no_output_____"
]
],
[
[
"from catalyst.dl.callbacks import DiceCallback, IouCallback, \\\n CriterionCallback, MetricAggregationCallback\n\ncallbacks = [\n # Each criterion is calculated separately.\n CriterionCallback(\n input_key=\"mask\",\n prefix=\"loss_dice\",\n criterion_key=\"dice\"\n ),\n CriterionCallback(\n input_key=\"mask\",\n prefix=\"loss_iou\",\n criterion_key=\"iou\"\n ),\n CriterionCallback(\n input_key=\"mask\",\n prefix=\"loss_bce\",\n criterion_key=\"bce\"\n ),\n\n # And only then we aggregate everything into one loss.\n MetricAggregationCallback(\n prefix=\"loss\",\n mode=\"weighted_sum\", # can be \"sum\", \"weighted_sum\" or \"mean\"\n # because we want weighted sum, we need to add scale for each loss\n metrics={\"loss_dice\": 1.0, \"loss_iou\": 1.0, \"loss_bce\": 0.8},\n ),\n\n # metrics\n DiceCallback(input_key=\"mask\"),\n IouCallback(input_key=\"mask\"),\n]\n\nif is_alchemy_used:\n from catalyst.dl import AlchemyLogger\n callbacks.append(AlchemyLogger(**monitoring_params))\n\nrunner.train(\n model=model,\n criterion=criterion,\n optimizer=optimizer,\n scheduler=scheduler,\n # our dataloaders\n loaders=loaders,\n # We can specify the callbacks list for the experiment;\n callbacks=callbacks,\n # path to save logs\n logdir=logdir,\n num_epochs=num_epochs,\n # save our best checkpoint by IoU metric\n main_metric=\"iou\",\n # IoU needs to be maximized.\n minimize_metric=False,\n # for FP16. It uses the variable from the very first cell\n fp16=fp16_params,\n # prints train logs\n verbose=True,\n)",
"_____no_output_____"
]
],
[
[
"### Training analysis\n\nThe `utils.plot_metrics` method reads tensorboard logs from the logdir and plots beautiful metrics with `plotly` package.",
"_____no_output_____"
]
],
[
[
"# tensorboard should be enought, uncomment to check plotly version\n# it can take a while (colab's issue)\n# utils.plot_metrics(\n# logdir=logdir, \n# # specify which metrics we want to plot\n# metrics=[\"loss\", \"accuracy01\", \"auc/_mean\", \"f1_score\", \"_base/lr\"]\n# )",
"_____no_output_____"
]
],
[
[
"## Model inference\n\nLet's look at the model's predictions.\n",
"_____no_output_____"
]
],
[
[
"TEST_IMAGES = sorted(test_image_path.glob(\"*.jpg\"))\n\n# create test dataset\ntest_dataset = SegmentationDataset(\n TEST_IMAGES, \n transforms=valid_transforms\n)\n\nnum_workers: int = 4\n\ninfer_loader = DataLoader(\n test_dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_workers\n)\n\n# this get predictions for the whole loader\npredictions = np.vstack(list(map(\n lambda x: x[\"logits\"].cpu().numpy(), \n runner.predict_loader(loader=infer_loader, resume=f\"{logdir}/checkpoints/best.pth\")\n)))\n\nprint(type(predictions))\nprint(predictions.shape)",
"_____no_output_____"
],
[
"threshold = 0.5\nmax_count = 5\n\nfor i, (features, logits) in enumerate(zip(test_dataset, predictions)):\n image = utils.tensor_to_ndimage(features[\"image\"])\n\n mask_ = torch.from_numpy(logits[0]).sigmoid()\n mask = utils.detach(mask_ > threshold).astype(\"float\")\n \n show_examples(name=\"\", image=image, mask=mask)\n \n if i >= max_count:\n break",
"_____no_output_____"
]
],
[
[
"## Model tracing\n\nCatalyst allows you to use Runner to make [tracing](https://pytorch.org/docs/stable/jit.html) models.\n\n> How to do this in the Config API, we wrote in [our blog (issue \\#2)](https://github.com/catalyst-team/catalyst-info#catalyst-info-2-tracing-with-torchjit)\n\nFor this purpose it is necessary to pass in a method `trace ` model and a batch on which `predict_batch ` will be executed:",
"_____no_output_____"
]
],
[
[
"batch = next(iter(loaders[\"valid\"]))\n# saves to `logdir` and returns a `ScriptModule` class\nrunner.trace(model=model, batch=batch, logdir=logdir, fp16=is_fp16_used)\n\n!ls {logdir}/trace/",
"_____no_output_____"
]
],
[
[
"After this, you can easily load the model and predict anything!",
"_____no_output_____"
]
],
[
[
"from catalyst.dl.utils import trace\n\nif is_fp16_used:\n model = trace.load_traced_model(\n f\"{logdir}/trace/traced-forward-opt_O1.pth\", \n device=\"cuda\", \n opt_level=\"O1\"\n )\nelse:\n model = trace.load_traced_model(\n f\"{logdir}/trace/traced-forward.pth\", \n device=\"cpu\"\n )",
"_____no_output_____"
],
[
"model_input = batch[\"image\"].to(\"cuda\" if is_fp16_used else \"cpu\")\nmodel(model_input)",
"_____no_output_____"
]
],
[
[
"### Advanced: Custom Callbacks\n\nLet's plot the heatmap of predicted masks.",
"_____no_output_____"
]
],
[
[
"import collections\n\nfrom catalyst.dl import Callback, CallbackOrder, IRunner\n\n\nclass CustomInferCallback(Callback):\n def __init__(self):\n super().__init__(CallbackOrder.Internal)\n self.heatmap = None\n self.counter = 0\n\n def on_loader_start(self, runner: IRunner):\n self.predictions = None\n self.counter = 0\n\n def on_batch_end(self, runner: IRunner):\n # data from the Dataloader\n # image, mask = runner.input[\"image\"], runner.input[\"mask\"]\n logits = runner.output[\"logits\"]\n probabilities = torch.sigmoid(logits)\n\n self.heatmap = (\n probabilities \n if self.heatmap is None \n else self.heatmap + probabilities\n )\n self.counter += len(probabilities)\n\n def on_loader_end(self, runner: IRunner):\n self.heatmap = self.heatmap.sum(axis=0)\n self.heatmap /= self.counter",
"_____no_output_____"
],
[
"from collections import OrderedDict\nfrom catalyst.dl.callbacks import CheckpointCallback\n\n\ninfer_loaders = {\"infer\": loaders[\"valid\"]}\nmodel = smp.FPN(encoder_name=\"resnext50_32x4d\", classes=1)\n\ndevice = utils.get_device()\nif is_fp16_used:\n fp16_params = dict(opt_level=\"O1\") # params for FP16\nelse:\n fp16_params = None\n\nrunner = SupervisedRunner(device=device, input_key=\"image\", input_target_key=\"mask\")\nrunner.infer(\n model=model,\n loaders=infer_loaders,\n callbacks=OrderedDict([\n (\"loader\", CheckpointCallback(resume=f\"{logdir}/checkpoints/best.pth\")),\n (\"infer\", CustomInferCallback())\n ]),\n fp16=fp16_params,\n)",
"_____no_output_____"
],
[
"import matplotlib\n%matplotlib inline \nimport matplotlib.pyplot as plt\n\nheatmap = utils.detach(runner.runner.callbacks[\"infer\"].heatmap[0])\nplt.figure(figsize=(20, 9))\nplt.imshow(heatmap, cmap=\"hot\", interpolation=\"nearest\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Advanced: test-time augmentations (TTA)\n\nThere is [ttach](https://github.com/qubvel/ttach) is a new awesome library for test-time augmentation for segmentation or classification tasks.",
"_____no_output_____"
]
],
[
[
"import ttach as tta\n\n# D4 makes horizontal and vertical flips + rotations for [0, 90, 180, 270] angels.\n# and then merges the result masks with merge_mode=\"mean\"\ntta_model = tta.SegmentationTTAWrapper(model, tta.aliases.d4_transform(), merge_mode=\"mean\")\n\ntta_runner = SupervisedRunner(\n model=tta_model,\n device=utils.get_device(),\n input_key=\"image\"\n)",
"_____no_output_____"
],
[
"infer_loader = DataLoader(\n test_dataset,\n batch_size=1,\n shuffle=False,\n num_workers=num_workers\n)\n\nbatch = next(iter(infer_loader))\n\n# predict_batch will automatically move the batch to the Runner's device\ntta_predictions = tta_runner.predict_batch(batch)\n\n# shape is `batch_size x channels x height x width`\nprint(tta_predictions[\"logits\"].shape)",
"_____no_output_____"
]
],
[
[
"Let's see our mask after TTA",
"_____no_output_____"
]
],
[
[
"threshold = 0.5\n\nimage = utils.tensor_to_ndimage(batch[\"image\"][0])\n\nmask_ = tta_predictions[\"logits\"][0, 0].sigmoid()\nmask = utils.detach(mask_ > threshold).astype(\"float\")\n\nshow_examples(name=\"\", image=image, mask=mask)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece760e8435c81c47b7fed0712779811ece1267a | 11,554 | ipynb | Jupyter Notebook | notebooks/04 src.models.train_model.py.ipynb | AzemaBaptiste/SoundLandscape | a9a27606301dd3c9000474960668ea11bada1452 | [
"BSD-3-Clause"
] | 1 | 2019-05-13T22:05:06.000Z | 2019-05-13T22:05:06.000Z | notebooks/04 src.models.train_model.py.ipynb | AzemaBaptiste/SoundLandscape | a9a27606301dd3c9000474960668ea11bada1452 | [
"BSD-3-Clause"
] | null | null | null | notebooks/04 src.models.train_model.py.ipynb | AzemaBaptiste/SoundLandscape | a9a27606301dd3c9000474960668ea11bada1452 | [
"BSD-3-Clause"
] | null | null | null | 40.118056 | 113 | 0.51506 | [
[
[
"import sys\n\nsys.path.insert(0, \"C:/Users/julie/PycharmProjects/SoundLandscape/\")",
"_____no_output_____"
],
[
"# -*- coding: utf-8 -*-\nimport os\nimport cv2\nimport pickle\n\nimport numpy as np\n\nimport face_recognition\n\nimport keras_metrics\nfrom keras.applications import MobileNet\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Dense, Dropout\nfrom keras.layers import Flatten, GlobalAveragePooling2D, Activation\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.mobilenet import preprocess_input\n\nfrom src import settings\n\n\nclass TrainFaceDetector(object):\n \"\"\"Module to predict the name & location of someone in a picture.\"\"\"\n\n def __init__(self,):\n \"\"\"Initiator.\"\"\"\n self.face_name = list()\n self.face_encoding = list()\n\n def fit(self, images_paths):\n \"\"\"Build an encoding for each people in the data directory.\n\n :param images_paths: (list) paths of all the images\n \"\"\"\n for path in images_paths:\n name = path.split(os.path.sep)[-1].split(\".\")[0]\n vars()[name] = face_recognition.load_image_file(path)\n vars()[name + \"_encoding\"] = face_recognition.face_encodings(vars()[name])[0]\n self.face_encoding.append(vars()[name + \"_encoding\"])\n self.face_name.append(name)\n pickle.dump(self.face_encoding, open(settings.ENCO_MODEL_PATH, \"wb\"))\n pickle.dump(self.face_name, open(settings.NAME_MODEL_PATH, \"wb\"))\n pickle.dump(self, open(settings.FACE_MODEL_PATH, \"wb\"))\n\n def predict(self, image):\n \"\"\"Predict the location and the name of people in the image.\n\n :param image: (np.array) image in gray\n :return: (list) (list) names & locations\n \"\"\"\n if not isinstance(image, np.ndarray):\n image = np.asarray(image, dtype=np.uint8)\n image.setflags(write=True)\n names = list()\n locations = face_recognition.face_locations(image)\n encodings = face_recognition.face_encodings(image, locations)\n for encoding in encodings:\n matches = face_recognition.compare_faces(self.face_encoding, encoding)\n name = \"Unknown\"\n if True in matches:\n first_match_index = matches.index(True)\n name = self.face_name[first_match_index]\n names.append(name)\n\n return names, locations\n\n\nclass TrainMoodDetector(object):\n \"\"\"Module to predict the mood & location of someone in a picture.\"\"\"\n\n def __init__(self):\n \"\"\"Initiator.\"\"\"\n self.classes = [\"angry\", \"disgust\", \"fear\", \"happy\", \"sad\", \"surprise\", \"neutral\"]\n self.model = self.__model__()\n\n def __model__(self):\n \"\"\"Build & compile the keras model.\n\n :return: (Keras.Sequential) model deep\n \"\"\"\n model = Sequential()\n model.add(Conv2D(64, (5, 5), activation='relu', input_shape=(48, 48, 1)))\n model.add(MaxPooling2D(pool_size=(5, 5), strides=(2, 2)))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(AveragePooling2D(pool_size=(3, 3), strides=(2, 2)))\n model.add(Conv2D(128, (3, 3), activation='relu'))\n model.add(Conv2D(128, (3, 3), activation='relu'))\n model.add(AveragePooling2D(pool_size=(3, 3), strides=(2, 2)))\n model.add(Flatten())\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(0.2))\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.2))\n model.add(Dense(len(self.classes), activation='softmax'))\n metrics = ['accuracy', keras_metrics.precision(), keras_metrics.recall()]\n model.compile(loss='categorical_crossentropy', optimizer=\"Adam\", metrics=metrics)\n\n return model\n\n @staticmethod\n def process_image_area(image, location):\n \"\"\"Select the area, and process it.\n\n :param image: (np.array) image\n :param location: (list) area of the face\n :return: (np.array) image for the prediction\n \"\"\"\n top, right, bottom, left = location\n face = image[top:bottom, left:right]\n face_resized = cv2.resize(face, (48, 48))\n face_resized_gray = cv2.cvtColor(face_resized, cv2.COLOR_BGR2GRAY)\n\n return face_resized_gray[np.newaxis, :, :, np.newaxis] / 255\n\n def fit(self, data_path):\n \"\"\"Build model to predict the mood from an image.\n\n :param data_path: (str) path of the images.\n \"\"\"\n # TODO\n\n def predict(self, image):\n \"\"\"Predict the mood of each people in the image.\n\n :param image: (np.array) image\n :return: (str) mood\n \"\"\"\n moods = list()\n locations = face_recognition.face_locations(image)\n for location in locations:\n processed_img = self.process_image_area(image, location)\n prediction = self.model.predict(processed_img)\n max_idx = np.argmax(prediction[0])\n mood = self.classes[max_idx]\n moods.append(mood)\n\n return moods, locations\n\n\nclass TrainLandscapeDetector(object):\n \"\"\"Module to predict the pred.\"\"\"\n\n def __init__(self):\n \"\"\"Initiator.\"\"\"\n self.number_classes = 7\n self.batch_size = 128\n self.epochs = 20\n self.loss = self.__loss__()\n self.class_mode = self.loss.split(\"_\")[0]\n self.model = self.__model__()\n self.train_data = ImageDataGenerator()\n self.test_data = ImageDataGenerator()\n self.labels = self.__labels__()\n\n def __loss__(self):\n \"\"\"Find loss function based on the number of classes.\n\n :return: (str) loss\n \"\"\"\n return \"categorical_crossentropy\" if self.number_classes > 2 else \"binary_crossentropy\"\n\n def build_generator(self, data_path):\n \"\"\"Build generator to train the model.\n\n :param data_path: (str) path of the images\n \"\"\"\n data_generator = ImageDataGenerator(\n preprocessing_function=preprocess_input, horizontal_flip=True,\n width_shift_range=0.2, height_shift_range=0.2\n )\n self.train_data = data_generator.flow_from_directory(\n data_path + \"/train\", target_size=(224, 224), color_mode='rgb',\n batch_size=self.batch_size, class_mode=self.class_mode, shuffle=True\n )\n self.test_data = data_generator.flow_from_directory(\n data_path + \"/test\", target_size=(224, 224), color_mode='rgb',\n batch_size=self.batch_size, class_mode=self.class_mode, shuffle=False\n )\n\n def __labels__(self):\n \"\"\"Get images labels.\n\n :return: (dict) all images categories\n \"\"\"\n return dict((v, k) for k, v in self.train_data.class_indices.items())\n\n def __model__(self):\n \"\"\"Build & compile model keras.\n\n :return: (Keras.Sequential) model deep\n \"\"\"\n # TODO refactor this shit code\n mobilenet = MobileNet(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\n init = mobilenet.output\n pool1 = GlobalAveragePooling2D()(init)\n l1 = Dense(1024)(pool1)\n act1 = Activation(activation=\"relu\")(l1)\n drop1 = Dropout(0.2)(act1)\n l2 = Dense(self.number_classes)(drop1)\n output = Activation(activation=\"softmax\")(l2)\n model = Model(inputs=mobilenet.input, outputs=output)\n for layer in model.layers[:-6]:\n layer.trainable = False\n metrics = ['accuracy', keras_metrics.precision(), keras_metrics.recall()]\n model.compile(optimizer='Adam', loss=self.loss, metrics=metrics)\n\n return model\n\n def fit(self, data_path):\n \"\"\"Build model to predict the pred type from an image.\n\n :param data_path: (str) path of the images.\n \"\"\"\n self.build_generator(data_path)\n self.model.fit_generator(\n generator=self.train_data, validation_data=self.test_data, epochs=self.epochs, verbose=2\n )\n\n def predict(self, image):\n \"\"\"Predict the pred type of the image.\n\n :param image: (np.array) image\n :return: (str) pred type\n \"\"\"\n prediction = self.model.predict(image)\n classe = np.argmax(prediction, axis=1)\n\n return self.labels[classe]\n\n\nif __name__ == '__main__':\n import glob\n import os\n paths = glob.glob(os.path.join(settings.IMAGE_FACE_PATH, \"*\"))\n TrainFaceDetector().fit(paths)\n",
"Using TensorFlow backend.\n"
]
]
] | [
"code"
] | [
[
"code",
"code"
]
] |
ece76b57c3b75322d12df417cfbd62f620e99a01 | 583 | ipynb | Jupyter Notebook | numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 2/02_03/.ipynb_checkpoints/linspace-checkpoint.ipynb | saint1729/in-learning | fe58495846f05e2dcd15d1dbb6ff87535d35d6c5 | [
"MIT"
] | null | null | null | numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 2/02_03/.ipynb_checkpoints/linspace-checkpoint.ipynb | saint1729/in-learning | fe58495846f05e2dcd15d1dbb6ff87535d35d6c5 | [
"MIT"
] | null | null | null | numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 2/02_03/.ipynb_checkpoints/linspace-checkpoint.ipynb | saint1729/in-learning | fe58495846f05e2dcd15d1dbb6ff87535d35d6c5 | [
"MIT"
] | null | null | null | 17.666667 | 64 | 0.530017 | [
[
[
"<h1>linspace(), zeros(), ones(), and NumPy data types</h1>",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown"
]
] |
ece77b0221f814ebcd6047b7eea137768531f4fa | 23,836 | ipynb | Jupyter Notebook | What-the-data - Terawatt - 2 - Simulation.ipynb | Nikolai-Hlubek/terawatt | 33aeb944ecc5a4310b9b0faa24e5d32f0d2248f1 | [
"MIT"
] | 1 | 2016-09-26T13:09:44.000Z | 2016-09-26T13:09:44.000Z | What-the-data - Terawatt - 2 - Simulation.ipynb | Nikolai-Hlubek/terawatt | 33aeb944ecc5a4310b9b0faa24e5d32f0d2248f1 | [
"MIT"
] | null | null | null | What-the-data - Terawatt - 2 - Simulation.ipynb | Nikolai-Hlubek/terawatt | 33aeb944ecc5a4310b9b0faa24e5d32f0d2248f1 | [
"MIT"
] | null | null | null | 27.911007 | 193 | 0.508139 | [
[
[
"# Projekt Terawatt\n\n*von Team Coding Agents*\n\n\n----\n\n\n## Simulation",
"_____no_output_____"
]
],
[
[
"import iplantuml\nimport datetime\nimport terawatt_model\n\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport plotly.graph_objs as go\n# run at the start of every ipython notebook to use plotly.offline\n# this injects the plotly.js source files into the notebook\ninit_notebook_mode(connected=True)\n\nfrom IPython.display import IFrame\nimport numpy",
"_____no_output_____"
]
],
[
[
"### System with set of input and outputs",
"_____no_output_____"
]
],
[
[
"import random\n\n# Timeconsuming calculation\n\nsun = terawatt_model.Sun()\nphotovoltaic = terawatt_model.Photovoltaic()\ncar1 = terawatt_model.Car()\ncar2 = terawatt_model.Car()\nprovider = terawatt_model.Provider()\nbattery = terawatt_model.Battery()\nelectrolysis = terawatt_model.Electrolysis()\nmethanization = terawatt_model.Methanization()\ncogeneration = terawatt_model.Cogeneration()\ntime_start = datetime.datetime(2016, 9, 24, 0, 0, 0, 0)\n\nstart = dict(\n car1_energy = random.randint(0, car1.energy_max.electrical),\n charge_car1 = random.randint(0, 19),\n car2_energy = random.randint(0, car2.energy_max.electrical),\n charge_car2 = random.randint(0, 20),\n battery_energy = random.randint(0, battery.energy_max.electrical),\n)\n\n# Unrandomize\nstart['car1_energy'] = 7000\nstart['charge_car1'] = 8\nstart['car2_energy'] = 12000\nstart['charge_car2'] = 18\nstart['battery_energy'] = 29200\n\n\ncar1.energy_now.electrical = start['car1_energy']\ncar2.energy_now.electrical = start['car2_energy']\nbattery.battery_current_energy = start['battery_energy']",
"_____no_output_____"
],
[
"print('Energy - Start of day')\nprint('Car 1 - electrical energy', round(car1.energy_now.electrical), 'Wh')\nprint('Car 1 - start of charge', start['charge_car1'])\nprint('Car 2 - electrical energy', round(car2.energy_now.electrical), 'Wh')\nprint('Car 2 - start of charge', start['charge_car2'])\nprint('Battery - electrical energy', round(battery.battery_current_energy), 'Wh')\nprint('Cogeneration - Methane', round(cogeneration.energy_now.chemical), 'Wh')\nprint('Provider - electrical energy', round(provider.energy_consumed.electrical), 'Wh')",
"Energy - Start of day\nCar 1 - electrical energy 7000 Wh\nCar 1 - start of charge 8\nCar 2 - electrical energy 12000 Wh\nCar 2 - start of charge 18\nBattery - electrical energy 29200 Wh\nCogeneration - Methane 0 Wh\nProvider - electrical energy 0 Wh\n"
],
[
"t = []\nr1 = []\nr2 = []\nr3 = []\nr4 = []\nr5 = []\nr6 = []\nr7 = []\n# Run for timestep\nfor dt in range(0, 3600*24-1, terawatt_model.timestep):\n time = time_start + datetime.timedelta(0,dt) # days, seconds\n \n power = sun.update(time=time)\n power = photovoltaic.update(power, time=time)\n \n power = battery.update(power, state='consume')\n power = electrolysis.update(power, state='both', power_requested=methanization.get_power_in_max())\n power = methanization.update(power, state='both', power_requested=methanization.get_power_out_max())\n power = cogeneration.update(power, state='consume')\n \n # Consumers\n power_requested = terawatt_model.Power()\n if start['charge_car1'] <= time.hour <= start['charge_car1'] + 4:\n # cannot compare against full charge. Due to incremental energies we never reach full charge exactly.\n if car1.energy_now.electrical < 0.99*car1.energy_max.electrical:\n power_requested.electrical += car1.get_power_in_max().electrical\n \n if start['charge_car2'] <= time.hour <= start['charge_car2'] + 4:\n if car2.energy_now.electrical < 0.99*car2.energy_max.electrical:\n power_requested.electrical += car2.get_power_in_max().electrical\n \n power_requested.chemical += cogeneration.power_conversion_electrical_to_chemical(power_requested.electrical).chemical\n power = cogeneration.update(power, state='provide', power_requested=power_requested)\n power_requested.electrical -= power.electrical\n power = battery.update(power, state='provide', power_requested=power_requested)\n\n if start['charge_car1'] <= time.hour <= start['charge_car1'] + 4:\n power = car1.update(power)\n if start['charge_car2'] <= time.hour <= start['charge_car2'] + 4:\n power = car2.update(power)\n\n power = provider.update(power)\n \n # Store only each minute\n if dt%60:\n t.append(time)\n r1.append(photovoltaic.power.electrical)\n r2.append(battery.energy_now.electrical)\n r3.append(car1.energy_now.electrical)\n r4.append(car2.energy_now.electrical)\n r5.append(electrolysis.energy_now.chemical)\n r6.append(cogeneration.energy_now.chemical)\n r7.append(cogeneration.power.electrical)",
"_____no_output_____"
]
],
[
[
"### System with set of input and outputs",
"_____no_output_____"
]
],
[
[
"print('Energy - End of day')\nprint('Car 1 - electrical energy', round(car1.energy_now.electrical), 'Wh')\nprint('Car 1 - start of charge', start['charge_car1'])\nprint('Car 2 - electrical energy', round(car2.energy_now.electrical), 'Wh')\nprint('Car 2 - start of charge', start['charge_car2'])\nprint('Battery - electrical energy', round(battery.energy_now.electrical), 'Wh')\nprint('Cogeneration - Methane', round(cogeneration.energy_now.chemical), 'Wh')\nprint('Provider - electrical energy', round(provider.energy_consumed.electrical), 'Wh')",
"Energy - End of day\nCar 1 - electrical energy 21780 Wh\nCar 1 - start of charge 8\nCar 2 - electrical energy 21781 Wh\nCar 2 - start of charge 18\nBattery - electrical energy 19960 Wh\nCogeneration - Methane 94 Wh\nProvider - electrical energy 0 Wh\n"
],
[
"# Create a trace\ntrace1 = go.Scatter(\n x = t,\n y = r1,\n name = 'Photovoltaic charging power',\n)\ntrace2 = go.Scatter(\n x = t,\n y = r2,\n name = 'Buffer battery energy',\n yaxis='y2',\n)\ntrace3 = go.Scatter(\n x = t,\n y = r3,\n name = 'Car 1 battery energy',\n yaxis='y2',\n)\ntrace4 = go.Scatter(\n x = t,\n y = r4,\n name = 'Car 2 battery energy',\n line = dict( color = 'black', dash = 4 ),\n yaxis='y2',\n)\ntrace5 = go.Scatter(\n x = t,\n y = r5,\n name = 'Electrolysis chemical energy',\n line = dict( color = 'red' ),\n yaxis='y2',\n)\ntrace6 = go.Scatter(\n x = t,\n y = r6,\n name = 'Cogeneration chemical energy',\n line = dict( color = 'violett'),\n yaxis='y2',\n)\ntrace7 = go.Scatter(\n x = t,\n y = r7,\n name = 'Cogeneration power',\n)\ndata = [trace1, trace2, trace3, trace4, trace5, trace6, trace7]\n\nlayout = go.Layout(\n xaxis=go.XAxis(title='Time of day'),\n yaxis=go.YAxis(title='W'),\n yaxis2=go.YAxis(\n title='Wh',\n #titlefont={color:'rgb(148, 103, 189)'},\n #tickfont={color:'rgb(148, 103, 189)'},\n overlaying='y',\n side='right'\n )\n)\nfig = go.Figure(data=data, layout=layout)\nplot(fig, filename='pictures/cars_delayed_charging_random_load_3.html', include_plotlyjs=True, show_link=False)",
"_____no_output_____"
],
[
"IFrame('pictures/cars_delayed_charging_random_load_3.html', width=900, height=500)",
"_____no_output_____"
]
],
[
[
"### Undisciplined agents (red : not enough fuel)",
"_____no_output_____"
]
],
[
[
"import json\nimport os\n\nwith open(os.path.join('terawatt_simulation', 'agents_undisciplined.dat')) as json_data:\n data = json.load(json_data)\n\n\nz = []\nx = []\nfor i,data_agent in enumerate(data):\n c1 = []\n c2 = []\n x.append(str(data_agent[1]['car1_distance_work'])+' km '+str(data_agent[1]['charge_car1_start'])+' h') #+str(i*2))\n x.append(str(data_agent[1]['car2_distance_work'])+' km '+str(data_agent[1]['charge_car2_start'])+' h') #+str(i*2+1)) \n for d in data_agent:\n c1.append(int(d['car1_drive_success']))\n c2.append(int(d['car2_drive_success']))\n z.append(c1)\n z.append(c2)\n\ncolorscale = [[0, 'red'], [1, '#001f3f']]\nhm = [\n go.Heatmap(\n z=numpy.transpose(z),\n x=numpy.transpose(x),\n colorscale=colorscale,\n showscale=False,\n ),\n# go.Scatter(\n# x = ['91 km 19 h','91 km 19 h'],\n# y = [0, len(z[1])],\n# )\n]\n\nlayout = go.Layout(\n xaxis = dict( tickangle=90),\n)\n\nfigure = dict(data=hm, layout=layout)\n\nplot(figure, filename='pictures/agents_undisciplined.html', include_plotlyjs=True, show_link=False)",
"_____no_output_____"
],
[
"IFrame('pictures/agents_undisciplined.html', width=700, height=400)",
"_____no_output_____"
]
],
[
[
"### Cooperating agents (red : not enough fuel)",
"_____no_output_____"
]
],
[
[
"import json\nimport os\n\nwith open(os.path.join('terawatt_simulation', 'agents_cooperation.dat')) as json_data:\n data = json.load(json_data)\n\n\nz = []\nx = []\nfor i,data_agent in enumerate(data):\n c1 = []\n c2 = []\n x.append(str(data_agent[1]['car1_distance_work'])+' km '+str(data_agent[1]['charge_car1_start'])+' h') #+str(i*2))\n x.append(str(data_agent[1]['car2_distance_work'])+' km '+str(data_agent[1]['max_energy_timestamp']/3600)+' h') #+str(i*2+1)) \n for d in data_agent:\n c1.append(int(d['car1_drive_success']))\n c2.append(int(d['car2_drive_success']))\n z.append(c1)\n z.append(c2)\n\ncolorscale = [[0, 'red'], [1, '#001f3f']]\nhm = [\n go.Heatmap(\n z=numpy.transpose(z),\n x=numpy.transpose(x),\n colorscale=colorscale,\n showscale=False,\n )\n]\n\nlayout = go.Layout(\n xaxis = dict( tickangle=90),\n)\n\nfigure = dict(data=hm, layout=layout)\n\nplot(figure, filename='pictures/agents_cooperation.html', include_plotlyjs=True, show_link=False)",
"_____no_output_____"
],
[
"IFrame('pictures/agents_cooperation.html', width=700, height=400)",
"_____no_output_____"
]
],
[
[
"### Undisciplined agents - Deficit by provider",
"_____no_output_____"
]
],
[
[
"import json\nimport os\n\nwith open(os.path.join('terawatt_simulation_real_data', 'agents_undisciplined_provider.dat')) as json_data:\n data = json.load(json_data)\n\n\nz = []\nx = []\nfor i,data_agent in enumerate(data):\n c1 = []\n c2 = []\n x.append(str(data_agent[1]['car1_distance_work'])+' km '+str(data_agent[1]['charge_car1_start'])+' h') #+str(i*2))\n x.append(str(data_agent[1]['car2_distance_work'])+' km '+str(data_agent[1]['charge_car2_start'])+' h') #+str(i*2+1)) \n for d in data_agent:\n c1.append(float(d['car1_energy']))\n c2.append(float(d['car2_energy']))\n z.append(c1)\n z.append(c2)\n\ncolorscale = [[1, '#001f3f'], [0, 'red']]\nhm = [\n go.Heatmap(\n z=numpy.transpose(z),\n x=numpy.transpose(x),\n #colorscale=colorscale,\n #showscale=False,\n )\n]\n\nlayout = go.Layout(\n xaxis = dict( tickangle=90),\n)\n\nfigure = dict(data=hm, layout=layout)\n\nplot(figure, filename='pictures/agents_undisciplined_provider.html', include_plotlyjs=True, show_link=False)",
"_____no_output_____"
],
[
"IFrame('pictures/agents_undisciplined_provider.html', width=700, height=400)",
"_____no_output_____"
]
],
[
[
"### Cooperating agents - Deficit by provider",
"_____no_output_____"
]
],
[
[
"import json\nimport os\n\nwith open(os.path.join('terawatt_simulation', 'agents_cooperation_provider.dat')) as json_data:\n data = json.load(json_data)\n\n\nz = []\n#x = []\nfor i,data_agent in enumerate(data):\n c1 = []\n c2 = []\n #x.append(str(data_agent[1]['car1_distance_work'])+' km '+str(data_agent[1]['charge_car1_start'])+' h') #+str(i*2))\n #x.append(str(data_agent[1]['car2_distance_work'])+' km '+str(data_agent[1]['max_energy_timestamp']/3600)+' h') #+str(i*2+1))\n for d in data_agent:\n c1.append(float(d['car1_energy']))\n c2.append(float(d['car2_energy']))\n z.append(c1)\n z.append(c2)\n\ncolorscale = [[1, '#001f3f'], [0, 'red']]\nhm = [\n go.Heatmap(\n z=numpy.transpose(z),\n x=numpy.transpose(x),\n #colorscale=colorscale,\n #showscale=False,\n )\n]\n\nlayout = go.Layout(\n xaxis = dict( tickangle=90),\n)\n\nfigure = dict(data=hm, layout=layout)\n\nplot(figure, filename='pictures/agents_cooperation_provider.html', include_plotlyjs=True, show_link=False)",
"_____no_output_____"
],
[
"IFrame('pictures/agents_cooperation_provider.html', width=700, height=400)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
ece789868f4427a5973432e4f59d5534ac39aeed | 68,236 | ipynb | Jupyter Notebook | Learn/Python/Fundamental/Data Quality with Python for Beginner/Data Quality with Python for Beginner.ipynb | Fathonidear22/DQLab-1 | 798d54a52c4c5f698235522b64a24feb346b8c0e | [
"MIT"
] | 22 | 2021-04-06T02:20:44.000Z | 2022-03-23T11:47:26.000Z | Learn/Python/Fundamental/Data Quality with Python for Beginner/Data Quality with Python for Beginner.ipynb | Fathonidear22/DQLab-1 | 798d54a52c4c5f698235522b64a24feb346b8c0e | [
"MIT"
] | 1 | 2021-02-08T04:58:25.000Z | 2021-02-08T04:58:25.000Z | Learn/Python/Fundamental/Data Quality with Python for Beginner/Data Quality with Python for Beginner.ipynb | Fathonidear22/DQLab-1 | 798d54a52c4c5f698235522b64a24feb346b8c0e | [
"MIT"
] | 50 | 2021-03-31T10:32:55.000Z | 2022-03-15T11:04:35.000Z | 126.362963 | 42,115 | 0.671654 | [
[
[
"# [Importing Data](https://academy.dqlab.id/main/livecode/166/322/1513)",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport io \nimport pandas_profiling \nretail_raw = pd.read_csv('https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/retail_raw_reduced_data_quality.csv')",
"_____no_output_____"
]
],
[
[
"# [Inspeksi tipe data](https://academy.dqlab.id/main/livecode/166/322/1514)",
"_____no_output_____"
]
],
[
[
"# Cetak tipe data di setiap kolom retail_raw\nprint(retail_raw.dtypes)",
"order_id int64\norder_date object\ncustomer_id int64\ncity object\nprovince object\nproduct_id object\nbrand object\nquantity float64\nitem_price float64\ndtype: object\n"
]
],
[
[
"# [Descriptive Statistics - Part 1](https://academy.dqlab.id/main/livecode/166/322/1515)",
"_____no_output_____"
]
],
[
[
"# Kolom city\nlength_city = len(retail_raw['city'])\nprint('Length kolom city:', length_city)\n\n# Tugas Praktek: Kolom product_id\nlength_product_id = len(retail_raw['product_id'])\nprint('Length kolom product_id:', length_product_id)",
"Length kolom city: 5000\nLength kolom product_id: 5000\n"
]
],
[
[
"# [Descriptive Statistics - Part 2](https://academy.dqlab.id/main/livecode/166/322/1517)",
"_____no_output_____"
]
],
[
[
"# Count kolom city\ncount_city = retail_raw['city'].count()\nprint('Count kolom count_city:', count_city)\n\n# Tugas praktek: count kolom product_id\ncount_product_id = retail_raw['product_id'].count()\nprint('Count kolom product_id:', count_product_id)",
"Count kolom count_city: 4984\nCount kolom product_id: 4989\n"
]
],
[
[
"# [Descriptive Statistics - Part 3](https://academy.dqlab.id/main/livecode/166/322/1519)",
"_____no_output_____"
]
],
[
[
"# Missing value pada kolom city\nnumber_of_missing_values_city = length_city - count_city\nfloat_of_missing_values_city = float(number_of_missing_values_city/length_city)\npct_of_missing_values_city = '{0:.1f}%'.format(float_of_missing_values_city * 100)\nprint('Persentase missing value kolom city:', pct_of_missing_values_city)\n\n# Tugas praktek: Missing value pada kolom product_id\nnumber_of_missing_values_product_id = length_product_id - count_product_id\nfloat_of_missing_values_product_id = float(number_of_missing_values_product_id/length_product_id)\npct_of_missing_values_product_id = '{0:.1f}%'.format(float_of_missing_values_product_id * 100)\nprint('Persentase missing value kolom product_id:', pct_of_missing_values_product_id)",
"Persentase missing value kolom city: 0.3%\nPersentase missing value kolom product_id: 0.2%\n"
]
],
[
[
"# [Descriptive Statistics - Part 4](https://academy.dqlab.id/main/livecode/166/322/1521)",
"_____no_output_____"
]
],
[
[
"# Deskriptif statistics kolom quantity\nprint('Kolom quantity')\nprint('Minimum value: ', retail_raw['quantity'].min())\nprint('Maximum value: ', retail_raw['quantity'].max())\nprint('Mean value: ', retail_raw['quantity'].mean())\nprint('Mode value: ', retail_raw['quantity'].mode())\nprint('Median value: ', retail_raw['quantity'].median())\nprint('Standard Deviation value: ', retail_raw['quantity'].std())\n\n# Tugas praktek: Deskriptif statistics kolom item_price\nprint('')\nprint('Kolom item_price')\nprint('Minimum value: ', retail_raw['item_price'].min())\nprint('Maximum value: ', retail_raw['item_price'].max())\nprint('Mean value: ', retail_raw['item_price'].mean())\nprint('Median value: ', retail_raw['item_price'].median())\nprint('Standard Deviation value: ', retail_raw['item_price'].std())",
"Kolom quantity\nMinimum value: 1.0\nMaximum value: 720.0\nMean value: 11.423987164059366\nMode value: 0 1.0\ndtype: float64\nMedian value: 5.0\nStandard Deviation value: 29.442025010811317\n\nKolom item_price\nMinimum value: 26000.0\nMaximum value: 29762000.0\nMean value: 933742.7311008623\nMedian value: 604000.0\nStandard Deviation value: 1030829.8104242863\n"
]
],
[
[
"# [Descriptive Statistics - Part 5](https://academy.dqlab.id/main/livecode/166/322/1523)",
"_____no_output_____"
]
],
[
[
"# Quantile statistics kolom quantity\nprint('Kolom quantity:')\nprint(retail_raw['quantity'].quantile([0.25, 0.5, 0.75]))\n\n# Tugas praktek: Quantile statistics kolom item_price\nprint('')\nprint('Kolom item_price:')\nprint(retail_raw['item_price'].quantile([0.25, 0.5, 0.75]))",
"Kolom quantity:\n0.25 2.0\n0.50 5.0\n0.75 12.0\nName: quantity, dtype: float64\n\nKolom item_price:\n0.25 450000.0\n0.50 604000.0\n0.75 1045000.0\nName: item_price, dtype: float64\n"
]
],
[
[
"# [Descriptive Statistics - Part 6](https://academy.dqlab.id/main/livecode/166/322/1526)",
"_____no_output_____"
]
],
[
[
"print('Korelasi quantity dengan item_price')\nprint(retail_raw[['quantity', 'item_price']].corr())",
"Korelasi quantity dengan item_price\n quantity item_price\nquantity 1.000000 -0.133936\nitem_price -0.133936 1.000000\n"
]
],
[
[
"# [Missing Data](https://academy.dqlab.id/main/livecode/166/323/1529)",
"_____no_output_____"
]
],
[
[
"# Check kolom yang memiliki missing data\nprint('Check kolom yang memiliki missing data:')\nprint(retail_raw.isnull().any())\n\n# Filling the missing value (imputasi)\nprint('\\nFilling the missing value (imputasi):')\nprint(retail_raw['quantity'].fillna(retail_raw['quantity'].mean()))\n\n# Drop missing value\nprint('\\nDrop missing value:')\nprint(retail_raw['quantity'].dropna())",
"Check kolom yang memiliki missing data:\norder_id False\norder_date False\ncustomer_id False\ncity True\nprovince True\nproduct_id True\nbrand False\nquantity True\nitem_price True\ndtype: bool\n\nFilling the missing value (imputasi):\n0 10.0\n1 2.0\n2 8.0\n3 4.0\n4 2.0\n ... \n4995 2.0\n4996 3.0\n4997 4.0\n4998 8.0\n4999 1.0\nName: quantity, Length: 5000, dtype: float64\n\nDrop missing value:\n0 10.0\n1 2.0\n2 8.0\n3 4.0\n4 2.0\n ... \n4995 2.0\n4996 3.0\n4997 4.0\n4998 8.0\n4999 1.0\nName: quantity, Length: 4986, dtype: float64\n"
]
],
[
[
"# [Tugas Praktek](https://academy.dqlab.id/main/livecode/166/323/1530)",
"_____no_output_____"
]
],
[
[
"print(retail_raw['item_price'].fillna(retail_raw['item_price'].mean()))",
"0 7.400000e+05\n1 6.040000e+05\n2 1.045000e+06\n3 2.050000e+05\n4 9.337427e+05\n ... \n4995 4.500000e+05\n4996 1.465000e+06\n4997 7.470000e+05\n4998 6.950000e+05\n4999 1.045000e+06\nName: item_price, Length: 5000, dtype: float64\n"
]
],
[
[
"# [Outliers](https://academy.dqlab.id/main/livecode/166/323/1534)",
"_____no_output_____"
]
],
[
[
"# Q1, Q3, dan IQR\nQ1 = retail_raw['quantity'].quantile(0.25)\nQ3 = retail_raw['quantity'].quantile(0.75)\nIQR = Q3 - Q1\n\n# Check ukuran (baris dan kolom) sebelum data yang outliers dibuang\nprint('Shape awal: ', retail_raw.shape)\n\n# Removing outliers\nretail_raw = retail_raw[~((retail_raw['quantity'] < (Q1 - 1.5 * IQR)) | (retail_raw['quantity'] > (Q3 + 1.5 * IQR)))]\n\n# Check ukuran (baris dan kolom) setelah data yang outliers dibuang\nprint('Shape akhir: ', retail_raw.shape)",
"Shape awal: (5000, 9)\nShape akhir: (4699, 9)\n"
]
],
[
[
"# [Tugas Praktek](https://academy.dqlab.id/main/livecode/166/323/1535)",
"_____no_output_____"
]
],
[
[
"# Q1, Q3, dan IQR\nQ1 = retail_raw['item_price'].quantile(0.25)\nQ3 = retail_raw['item_price'].quantile(0.75)\nIQR = Q3 - Q1\n\n# Check ukuran (baris dan kolom) sebelum data yang outliers dibuang\nprint('Shape awal: ', retail_raw.shape)\n\n# Removing outliers\nretail_raw = retail_raw[~((retail_raw['item_price'] < (Q1 - 1.5 * IQR)) | (retail_raw['item_price'] > (Q3 + 1.5 * IQR)))]\n\n# Check ukuran (baris dan kolom) setelah data yang outliers dibuang\nprint('Shape akhir: ', retail_raw.shape)",
"Shape awal: (4699, 9)\nShape akhir: (4379, 9)\n"
]
],
[
[
"# [Tugas Praktek](https://academy.dqlab.id/main/livecode/166/323/1537)",
"_____no_output_____"
]
],
[
[
"# Check ukuran (baris dan kolom) sebelum data duplikasi dibuang\nprint('Shape awal: ', retail_raw.shape)\n\n# Buang data yang terduplikasi\nretail_raw.drop_duplicates(inplace=True)\n\n# Check ukuran (baris dan kolom) setelah data duplikasi dibuang\nprint('Shape akhir: ', retail_raw.shape)",
"Shape awal: (4379, 9)\nShape akhir: (4373, 9)\n"
]
],
[
[
"# [Case Studi: Data Profiling](https://academy.dqlab.id/main/livecode/166/324/1532)",
"_____no_output_____"
]
],
[
[
"# Baca dataset uncleaned_raw.csv\nuncleaned_raw = pd.read_csv('https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/uncleaned_raw.csv')\n\n#inspeksi dataframe uncleaned_raw\nprint('Lima data teratas:')\nprint(uncleaned_raw.head())\n\n#Check kolom yang mengandung missing value\nprint('\\nKolom dengan missing value:')\nprint(uncleaned_raw.isnull().any())\n\n#Persentase missing value\nlength_qty = len(uncleaned_raw['Quantity'])\ncount_qty = uncleaned_raw['Quantity'].count()\n\n#mengurangi length dengan count\nnumber_of_missing_values_qty = length_qty - count_qty\n\n#mengubah ke bentuk float\nfloat_of_missing_values_qty = float(number_of_missing_values_qty / length_qty)\n\n#mengubah ke dalam bentuk persen\npct_of_missing_values_qty = '{0:.1f}%'.format(float_of_missing_values_qty*100)\n\n#print hasil percent dari missing value\nprint('Persentase missing value kolom Quantity:', pct_of_missing_values_qty)\n\n#Mengisi missing value tersebut dengan mean dari kolom tersebut\nuncleaned_raw['Quantity'] = uncleaned_raw['Quantity'].fillna(uncleaned_raw['Quantity'].mean())",
"Lima data teratas:\n InvoiceNo Description Quantity InvoiceDate \\\n0 536365 WHITE HANGING HEART T-LIGHT HOLDER 6.0 12/01/10 08.26 \n1 536366 WHITE METAL LANTERN 6.0 12/01/10 08.26 \n2 536367 CREAM CUPID HEARTS COAT HANGER 8.0 12/01/10 08.26 \n3 536368 KNITTED UNION FLAG HOT WATER BOTTLE 6.0 12/01/10 08.26 \n4 536369 RED WOOLLY HOTTIE WHITE HEART. 6.0 12/01/10 08.26 \n\n UnitPrice CustomerID City \n0 29000 17850 Surabaya \n1 41000 17850 Surabaya \n2 18000 17850 Surabaya \n3 38000 17850 Jakarta \n4 27000 17850 Medan \n\nKolom dengan missing value:\nInvoiceNo False\nDescription False\nQuantity True\nInvoiceDate False\nUnitPrice False\nCustomerID False\nCity False\ndtype: bool\nPersentase missing value kolom Quantity: 4.0%\n"
]
],
[
[
"# [Case Study: Data Cleansing - Part 1](https://academy.dqlab.id/main/livecode/166/324/2602)",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\n#Mengetahui kolom yang memiliki outliers!\nuncleaned_raw.boxplot()\nplt.show()",
"_____no_output_____"
]
],
[
[
" # [Case Study: Data Cleansing - Part 2](https://academy.dqlab.id/main/livecode/166/324/2603)",
"_____no_output_____"
]
],
[
[
"#Check IQR\nQ1 = uncleaned_raw['UnitPrice'].quantile(0.25)\nQ3 = uncleaned_raw['UnitPrice'].quantile(0.75)\nIQR = Q3 - Q1\n\n#removing outliers\nuncleaned_raw = uncleaned_raw[~((uncleaned_raw[['UnitPrice']] < (Q1 - 1.5 * IQR)) | (uncleaned_raw[['UnitPrice']] > (Q3 + 1.5 * IQR)))]\n\n#check for duplication\nprint(uncleaned_raw.duplicated(subset=None))\n\n#remove duplication\nuncleaned_raw = uncleaned_raw.drop_duplicates()",
"0 False\n1 False\n2 False\n3 False\n4 False\n ... \n500 True\n501 True\n502 True\n503 True\n504 True\nLength: 505, dtype: bool\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece79012a56d3f3afa3ceb12634349e8c4602a38 | 15,725 | ipynb | Jupyter Notebook | bokeh.ipynb | Christian-Hirsch/bokeh-viz | 2c1bd17fc9bf7265b08252e592add8a2b30204e2 | [
"MIT"
] | null | null | null | bokeh.ipynb | Christian-Hirsch/bokeh-viz | 2c1bd17fc9bf7265b08252e592add8a2b30204e2 | [
"MIT"
] | null | null | null | bokeh.ipynb | Christian-Hirsch/bokeh-viz | 2c1bd17fc9bf7265b08252e592add8a2b30204e2 | [
"MIT"
] | null | null | null | 31.576305 | 413 | 0.573291 | [
[
[
"# Deploying interactive Bokeh visualizations",
"_____no_output_____"
],
[
"[Bokeh](https://bokeh.pydata.org/en/latest/) is powerful library for creating plots and charts in python. You will probably already have played with [matplotlib](https://matplotlib.org/) or [seaborn](https://seaborn.pydata.org/), but Bokeh makes it ridiculously easy to have the user interact with your charts.",
"_____no_output_____"
],
[
"In this notebook, we provide a step-by-step guide on how to create a line plot with bokeh that can be deployed as web app with ease. This is a special extended version of a [tool](https://github.com/laurafroelich/swung_viz_log/blob/master/code/holoMagic.py) that Duncan, Jo, Laura, Sean and I developed during the [2018 Subsurface Hackathon](https://agilescientific.com/events/subsurface2018) in Copenhagen.",
"_____no_output_____"
],
[
"The code is modified from the wonderful [stocks](https://github.com/bokeh/bokeh/tree/master/examples/app/stocks) and [weather](https://github.com/bokeh/bokeh/tree/master/examples/app/weather) examples in the bokeh gallery.",
"_____no_output_____"
],
[
"## Drilling down the rabbit hole",
"_____no_output_____"
],
[
"The context for our example comes from visualising log data in oil well explorations. Our final goal is to set up the following visualization. Don't worry, we'll go through the single parts in a second.",
"_____no_output_____"
],
[
"<img src='./bokeh.png'></img>",
"_____no_output_____"
],
[
"What is shown on the left is a plot of a quantity measured by a drilling head as it moves down into different formations. The quantity being measured is typically being referred to as *Curve*. Here, we show a curve for a measure of radioactivity, but in the drop-down menu the user can choose a different one.",
"_____no_output_____"
],
[
"The *group* refers to a subsample of the depth-axis with specific geological properties. Hence, selecting a group corresponds roughly to subsetting the data.",
"_____no_output_____"
],
[
"Finally, the *Well* specifies which of possibly several exploration sites should be investigated.",
"_____no_output_____"
],
[
"Next to the plot we show basic associated summary statistics, such as maximum, minimum, mean and standard deviation.",
"_____no_output_____"
],
[
"The complete code is in the python scripts [holoMagic.py](./holoMagic.py) and [holoHelper.py](./holoHelper.py).",
"_____no_output_____"
],
[
"## Bokeh visualizations",
"_____no_output_____"
],
[
"First, we import pandas, numpy and several bokeh objects. We also need helper functions that will be explained later if you want to know all the details.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n\nfrom bokeh.io import curdoc\nfrom bokeh.layouts import row, column\nfrom bokeh.models import ColumnDataSource, Select, PreText\n\nfrom holoHelper import get_dataset, make_plot, select_top_base, update_text, update_plot",
"_____no_output_____"
]
],
[
[
"Now, we specify where to find the data and which statistics to look at. These statistics are displayed in ``PreText`` bokeh objects.",
"_____no_output_____"
]
],
[
[
"#file names and considered stats\nDATA_PATH = \"../data/EAGE2018/\"\nwld_fname = \"{}well_log_data.txt\".format(DATA_PATH)\n\n###Set up the statistics text fields\nSTAT_NAMES = ['Max ', 'Min ', 'Mean ', 'Std ']\nstats = [PreText(text=prop, width=500, height=1) for prop in STAT_NAMES]",
"_____no_output_____"
]
],
[
[
"Besides the text fields, we also need the drop down menus. For the purpose of this tutorial, we hardwire them into the code.",
"_____no_output_____"
]
],
[
[
"#Titles and initial valuesfor drop-downs\nTITLES = ['Curve', 'Group', 'Well']\nINITS = ['Gamma', 'AA', 'A']\n\n#Options to choose from\nCURVE_OPTIONS = ['Gamma', 'Res']\nGROUP_OPTIONS = ['HH', 'GG', 'FF', 'EE', 'DD', 'CC', 'BB', 'AA', 'All']\nWELL_OPTIONS = ['X-27', 'I_A', 'D', 'B', 'B_AT2', 'B_A', 'AA', 'A']\nOPTIONS = [CURVE_OPTIONS, GROUP_OPTIONS, WELL_OPTIONS]\n\n#Define drop-down menus\nselects = [Select(value=init, title=title, options= option) for init, title, option in zip(INITS, TITLES, OPTIONS)]",
"_____no_output_____"
]
],
[
[
"When the user makes a selection in the drop-down menu, this should correspond to a change in the plot and the statistics. Therefore, we attach the function `update_plot_text` to the `on_change` event of the drop-down menus.",
"_____no_output_____"
]
],
[
[
"def update_plot_text(attrname, old, new):\n curve, group, well = [select.value for select in selects]\n\n top,base = select_top_base(group, well)\n\n update_text(top, base, curve, well, stats)\n update_plot(top, base, curve, well, source)\n \nfor select in selects:\n select.on_change('value', update_plot_text)",
"_____no_output_____"
]
],
[
[
"Now, all that is left to be done is to construct the plot and everything to the root of the current document. There you go!",
"_____no_output_____"
]
],
[
[
"source = get_dataset(INITS[0], INITS[2])\nplot = make_plot(source, INITS[0])\ncontrols = column(*selects, *stats)\n\ncurdoc().add_root(row(plot, controls))\ncurdoc().title = \"Log quality visualisation\"",
"_____no_output_____"
]
],
[
[
"If you put the code into ``log_quality.py``, you can deploy the bokeh server via ``bokeh serve --show log_quality.py``. The [bokeh docs](https://bokeh.pydata.org/en/latest/docs/user_guide/server.html) give you all the further details you might be interested.",
"_____no_output_____"
],
[
"## Helper functions",
"_____no_output_____"
],
[
"So you are still passionate to learn more about bokeh? Then, let's look at the helper functions in detail. We import the usual suspects.",
"_____no_output_____"
]
],
[
[
"from bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nfrom bokeh.palettes import Blues4\n\nimport pandas as pd\nimport numpy as np\nimport json",
"_____no_output_____"
]
],
[
[
"We also specify the file path and the statistics to be considered.",
"_____no_output_____"
]
],
[
[
"#File path\nDATA_PATH = \"../data/EAGE2018/\"\nwld_fname = \"{}well_log_data.txt\".format(DATA_PATH)\ngroup_fname = \"{}EAGE_Hackathon_2018_Well_\".format(DATA_PATH)\n\n#considered statistics\nSTAT_NAMES = ['Max ', 'Min ', 'Mean ', 'Std ']\n\n#Fix the maximum possible depth\nMAX_DEPTH=5000",
"_____no_output_____"
]
],
[
[
"We convert the json files into a pandas dataframe.",
"_____no_output_____"
]
],
[
[
"#convert json data into pandas\nwith open(wld_fname, 'r') as f:\n j_data = json.load(f)\n\nfor i, item in enumerate(j_data):\n if i == 0:\n p_data = pd.DataFrame(item)\n else:\n p_data = p_data.append(pd.DataFrame(item))",
"_____no_output_____"
]
],
[
[
"The first helper function selects the relevant pieces of the large pandas dataframe and puts them into a bokeh `Source` object.",
"_____no_output_____"
]
],
[
[
"def get_dataset(curve, well, top=0, base=MAX_DEPTH):\n \"\"\"Prepare dataset for plotting\n\n Select curve data from a well in a group bounded by a specified top and base\n # Arguments\n curve: curve to be considered\n well: well to be considered\n top: top coordinates of the group to be considered\n base: base coordinates of the group to be considered\n # Returns\n A bokeh Source object containing the pandas data\n \"\"\"\n src = p_data[(p_data['Depth']>top) & (p_data['Depth']<base)]\n cur_df = (src[src['Well'] == well])[['Depth', curve]]\n cur_df=cur_df.set_index('Depth').copy()\n cur_df.columns = ['val']\n\n #reverse depth direction for drawing\n cur_df=cur_df.sort_index()\n cur_df.index = -cur_df.index\n\n return ColumnDataSource(data=cur_df)",
"_____no_output_____"
]
],
[
[
"Once we have a bokeh `Source` object, we push it through the plotting pipeline.",
"_____no_output_____"
]
],
[
[
"def make_plot(current, curve, plot_width=800, plot_height=1000, alpha=.3, font_style=\"bold\"):\n \"\"\"Show plot of current data \n\n Compute plot of current data \n # Arguments\n current: bokeh Source object containing the current data\n curve: curve to be plotted\n plot_width: width of plot\n plot_heigth: height of plot\n alpha: alpha-value of plot\n font_style: font style for plot\n # Returns\n A plot object for the current data\n \"\"\"\n\n #plot the figure\n plot = figure( plot_width=plot_width, plot_height=plot_height, tools=\"\", toolbar_location=None)\n plot.line(y='Depth', x='val', source=current, color=Blues4[1])\n\n #set plot meta_data\n plot.yaxis.axis_label = \"Depth\"\n plot.axis.axis_label_text_font_style = font_style\n plot.grid.grid_line_alpha = alpha\n\n return plot",
"_____no_output_____"
]
],
[
[
"The groups are given as names, so that we need to read out their starting and and depth from a database.",
"_____no_output_____"
]
],
[
[
"def select_top_base(group, well):\n \"\"\"Extract top and base coordinates\n \n Extract top and base coordinates for a specified group and well\n # Arguments\n group: group for which top and base coords are to be queried\n well: well to be considered\n # Returns\n A pair consisting of the top and base coordinate of the specified group\n \"\"\"\n\n group_file = \"{}EAGE_Hackathon_2018_{}{}{}\".format(DATA_PATH,\"Well_\", well,\".csv\")\n group_df = pd.read_csv(group_file)\n\n base = MAX_DEPTH\n top = 0\n if group!='All':\n base_top = group_df[(group_df['name'] == group) & (group_df['Surface'] == 'group')]\n top_sel = base_top[base_top['Obs#'] == 'Top']['MD']\n base_sel = base_top[base_top['Obs#'] == 'Base']['MD']\n if len(top_sel)>0:\n top = top_sel.values[0]\n if len(base_sel)>0:\n base = base_sel.values[0]\n return top, base",
"_____no_output_____"
]
],
[
[
"Updating the plot is refreshingly simple as we only need to update the attached source.",
"_____no_output_____"
]
],
[
[
"def update_plot(curve, well, top, base, source):\n \"\"\"Updates the plot\n\n Updates the plotted curve after user interaction\n # Arguments\n curve: curve to be considered\n well: well to be considered\n top: top coordinates of the group to be considered\n base: base coordinates of the group to be considered\n source: source object to be modified\n \"\"\"\n new_source = get_dataset(curve, well, top, base)\n source.data.update(new_source.data)",
"_____no_output_____"
]
],
[
[
"To update the text, we construct a new pandas dataframe and then recompute the statistics.",
"_____no_output_____"
]
],
[
[
"def update_text(curve, well, top, base, stats):\n \"\"\"Updates the plot\n\n Updates the displayed statistics after user interaction\n # Arguments\n curve: curve to be considered\n well: well to be considered\n top: top coordinates of the group to be considered\n base: base coordinates of the group to be considered\n stats: text fields to be modified\n \"\"\"\n src = p_data[(p_data['Depth']>top) & (p_data['Depth']<base)]\n df = src[src['Well'] == well]\n df = df[curve]\n\n stat_vals = [df.max(), df.min(), df.mean(), df.std()]\n for stat, name, stat_val in zip(stats, STAT_NAMES, stat_vals):\n stat.text = \"{0}{1:.2f}\".format(name, stat_val) ",
"_____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",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
ece79f27a13e5c716b8d11aa4a00851a76076c79 | 185,429 | ipynb | Jupyter Notebook | Recommendations_with_IBM.ipynb | rahul385/Recommendations-with-IBM | 15292c5ee06f1e49ff2772554fb15f8622f89e86 | [
"MIT"
] | null | null | null | Recommendations_with_IBM.ipynb | rahul385/Recommendations-with-IBM | 15292c5ee06f1e49ff2772554fb15f8622f89e86 | [
"MIT"
] | null | null | null | Recommendations_with_IBM.ipynb | rahul385/Recommendations-with-IBM | 15292c5ee06f1e49ff2772554fb15f8622f89e86 | [
"MIT"
] | null | null | null | 43.193338 | 16,896 | 0.545222 | [
[
[
"# Recommendations with IBM\n\n\n## Table of Contents\n\nI. [Exploratory Data Analysis](#Exploratory-Data-Analysis)<br>\nII. [Rank Based Recommendations](#Rank)<br>\nIII. [User-User Based Collaborative Filtering](#User-User)<br>\nIV. [Content Based Recommendations (EXTRA - NOT REQUIRED)](#Content-Recs)<br>\nV. [Matrix Factorization](#Matrix-Fact)<br>\nVI. [Extras & Concluding](#conclusions)",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom unit_tests import project_test as t\n#import Unit_Tests\\project_test as t\nimport pickle\nfrom pandas_profiling import ProfileReport\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport re\n\n# nltk\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nnltk.download(['punkt', 'wordnet', 'stopwords',\n 'averaged_perceptron_tagger'])",
"[nltk_data] Downloading package punkt to\n[nltk_data] C:\\Users\\RahulGupta\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n[nltk_data] Downloading package wordnet to\n[nltk_data] C:\\Users\\RahulGupta\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package wordnet is already up-to-date!\n[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\RahulGupta\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] C:\\Users\\RahulGupta\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package averaged_perceptron_tagger is already up-to-\n[nltk_data] date!\n"
],
[
"df = pd.read_csv('data/user-item-interactions.csv')\ndf_content = pd.read_csv('data/articles_community.csv')\ndel df['Unnamed: 0']\ndel df_content['Unnamed: 0']\n\n# Show df to get an idea of the data\ndf.head()",
"_____no_output_____"
],
[
"# Show df_content to get an idea of the data\ndf_content.head()",
"_____no_output_____"
]
],
[
[
"### <a class=\"anchor\" id=\"Exploratory-Data-Analysis\">Part I : Exploratory Data Analysis</a>",
"_____no_output_____"
]
],
[
[
"# Count user interaction\nuser_interaction = df.email.value_counts(dropna=False)",
"_____no_output_____"
],
[
"# Distribution of how many articles a user interacts with in the dataset\nplt.figure()\nplt.hist(user_interaction.values, bins=100)\nplt.title('Distribution of how many articles a user interacts with in the dataset')\nplt.xlabel('interactions')\nplt.ylabel('count')\nplt.show()",
"_____no_output_____"
],
[
"#Profiling Report 1\nprofile=ProfileReport(df,title=\"profiling report\",explorative=True)\nprofile.to_file(\"df.html\")\n\n#Profiling Report 2\nprofile=ProfileReport(df_content,title=\"profiling report\",explorative=True)\nprofile.to_file(\"df_content.html\")",
"_____no_output_____"
],
[
"df.email.value_counts()",
"_____no_output_____"
],
[
"np.percentile(df.email.value_counts(),50)",
"_____no_output_____"
],
[
"# Fill in the median and maximum number of user_article interactios below\n\nmedian_val = np.percentile(df.email.value_counts(),50) # 50% of individuals interact with ____ number of articles or fewer.\nmax_views_by_user = 364 # The maximum number of user-article interactions by any 1 user is ______.",
"_____no_output_____"
]
],
[
[
"#### Explore and remove duplicate articles from the **df_content** dataframe. ",
"_____no_output_____"
]
],
[
[
"# Display duplicate rows\ndf_content[df_content.article_id.duplicated()]",
"_____no_output_____"
],
[
"# Remove duplicate rows\nprint(df_content.shape)\n\ndf_content=df_content[~df_content.article_id.duplicated()]\n\nprint('\\n',df_content.shape)",
"(1056, 5)\n\n (1051, 5)\n"
],
[
"# unique_articles\ndf.article_id.nunique()",
"_____no_output_____"
],
[
"# total_articles\ndf_content.article_id.nunique()",
"_____no_output_____"
],
[
"# unique_users\ndf.email.nunique()",
"_____no_output_____"
],
[
"# number of user-article interactions\ndf.shape[0]",
"_____no_output_____"
]
],
[
[
"#### Find the following:\n\n**a.** The number of unique articles that have an interaction with a user. \n**b.** The number of unique articles in the dataset (whether they have any interactions or not).<br>\n**c.** The number of unique users in the dataset. (excluding null values) <br>\n**d.** The number of user-article interactions in the dataset.",
"_____no_output_____"
]
],
[
[
"unique_articles = 714 # The number of unique articles that have at least one interaction\ntotal_articles = 1051 #The number of unique articles on the IBM platform\nunique_users = 5148 # The number of unique users\nuser_article_interactions = 45993 # The number of user-article interactions",
"_____no_output_____"
]
],
[
[
"#### Find the most viewed **article_id**, as well as how often it was viewed.",
"_____no_output_____"
]
],
[
[
"df.article_id=df.article_id.astype(str)",
"_____no_output_____"
],
[
"df.email.groupby(df.article_id).size().sort_values(ascending=False)",
"_____no_output_____"
],
[
"most_viewed_article_id = '1429.0' # The most viewed article in the dataset as a string with one value following the decimal \nmax_views = 937 # The most viewed article in the dataset was viewed how many times?",
"_____no_output_____"
],
[
"sol_1_dict = {\n '`50% of individuals have _____ or fewer interactions.`': median_val,\n '`The total number of user-article interactions in the dataset is ______.`': user_article_interactions,\n '`The maximum number of user-article interactions by any 1 user is ______.`': max_views_by_user,\n '`The most viewed article in the dataset was viewed _____ times.`': max_views,\n '`The article_id of the most viewed article is ______.`': most_viewed_article_id,\n '`The number of unique articles that have at least 1 rating ______.`': unique_articles,\n '`The number of unique users in the dataset is ______`': unique_users,\n '`The number of unique articles on the IBM platform`': total_articles\n}\n\n# Test the dictionary against the solution\nt.sol_1_test(sol_1_dict)",
"It looks like you have everything right here! Nice job!\n"
]
],
[
[
"#### The `email_mapper` function seemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belonged to a single user (which is how they are stored using the function below).",
"_____no_output_____"
]
],
[
[
"# Map the user email to a user_id column and remove the email column\n\ndef email_mapper():\n coded_dict = dict()\n cter = 1\n email_encoded = []\n \n for val in df['email']:\n if val not in coded_dict:\n coded_dict[val] = cter\n cter+=1\n \n email_encoded.append(coded_dict[val])\n return email_encoded\n\nemail_encoded = email_mapper()\ndel df['email']\ndf['user_id'] = email_encoded\n\n# show header\ndf.head()",
"_____no_output_____"
]
],
[
[
"### <a class=\"anchor\" id=\"Rank\">Part II: Rank-Based Recommendations</a>",
"_____no_output_____"
]
],
[
[
"def get_top_articles(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n \n top_articles=list(df.title.value_counts().index)[:n]\n \n return top_articles # Return the top article titles from df (not df_content)\n\ndef get_top_article_ids(n, df=df):\n '''\n INPUT:\n n - (int) the number of top articles to return\n df - (pandas dataframe) df as defined at the top of the notebook \n \n OUTPUT:\n top_articles - (list) A list of the top 'n' article titles \n \n '''\n\n top_articles=list(df.article_id.value_counts().index)[:n]\n \n return top_articles # Return the top article ids",
"_____no_output_____"
],
[
"# Test the function by returning the top 5, 10, and 20 articles\n#top_5 = get_top_articles(5)\ntop_10 = get_top_articles(10)\ntop_20 = get_top_articles(20)\n\n# Test each of the three lists from above\nt.sol_2_test(get_top_articles)",
"Your top_5 looks like the solution list! Nice job.\nYour top_10 looks like the solution list! Nice job.\nYour top_20 looks like the solution list! Nice job.\n"
]
],
[
[
"### <a class=\"anchor\" id=\"User-User\">Part III: User-User Based Collaborative Filtering</a>\n\n* Each **user** should only appear in each **row** once.\n\n\n* Each **article** should only show up in one **column**. \n\n\n* If a user has interacted with an article, then place a 1 where the user-row meets for that article-column. It does not matter how many times a user has interacted with the article, all entries where a user has interacted with an article should be a 1. \n\n\n* If a user has not interacted with an item, then place a zero where the user-row meets for that article-column.",
"_____no_output_____"
]
],
[
[
"# create the user-article matrix with 1's and 0's\n\ndef create_user_item_matrix(df):\n '''\n INPUT:\n df - pandas dataframe with article_id, title, user_id columns\n \n OUTPUT:\n user_item - user item matrix \n \n Description:\n Return a matrix with user ids as rows and article ids on the columns with 1 values where a user interacted with \n an article and a 0 otherwise\n '''\n user_item=pd.pivot_table(df,index='user_id',aggfunc=np.max,columns='article_id',fill_value=0)\n \n for i in range(user_item.shape[0]):\n for j in range(user_item.shape[1]):\n if user_item.iloc[i,j]!=0:\n user_item.iloc[i,j]=1\n \n # Drop multi-level index\n user_item.columns = user_item.columns.droplevel()\n \n # Convert datatype of columns from str to int\n for i in user_item.columns:\n user_item[i]=user_item[i].astype(int)\n \n return user_item # return the user_item matrix \n\nuser_item = create_user_item_matrix(df)",
"_____no_output_____"
],
[
"user_item.head()",
"_____no_output_____"
],
[
"## Tests:\nassert user_item.shape[0] == 5149, \"Oops! The number of users in the user-article matrix doesn't look right.\"\nassert user_item.shape[1] == 714, \"Oops! The number of articles in the user-article matrix doesn't look right.\"\nassert user_item.sum(axis=1)[1] == 36, \"Oops! The number of articles seen by user 1 doesn't look right.\"\nprint(\"You have passed our quick tests! Please proceed!\")",
"You have passed our quick tests! Please proceed!\n"
],
[
"# create the user-article dictionary\n\ndef create_user_article_dict():\n '''\n INPUT: None\n OUTPUT: user_dict - a dictionary where each key is a user_id and the value is an array of articles interacted with.\n \n Creates the movies_seen dictionary\n '''\n \n # create a dictionary where the key is each user and the value is list of 'article_id' that user has interacted with.\n user_dict={}\n for row in user_item.index.values:\n temp_list=[]\n for col in list(user_item.columns):\n if user_item.loc[row,col]>0:\n temp_list.append(col)\n user_dict[row]=temp_list\n \n return user_dict # return the user_item dictionary\n\nuser_dict = create_user_article_dict()",
"_____no_output_____"
],
[
"# create the user-user matrix that holds number of common articles between each pair of users.\n\ndef create_user_user_matrix():\n '''\n INPUT: None\n OUTPUT: user_user_ - a dictionary where each key is a user_id and the value is an array of articles interacted with.\n \n Creates the movies_seen dictionary\n '''\n \n # Create a dataframe that holds number of common articles between each pair of users\n user_user_matrix=pd.DataFrame(data=np.zeros((user_item.shape[0],user_item.shape[0])),columns=user_item.index)\n\n for i in list(user_item.index):\n for j in list(user_item.index):\n user_user_matrix.loc[i,j]=len(np.intersect1d(user_dict[i],user_dict[j],assume_unique=True))\n \n return user_user_matrix # return the user_user matrix",
"_____no_output_____"
],
[
"#user_user_matrix = create_user_user_matrix()\n#user_user_matrix.to_pickle('user_common_article')\n\n# It takes a long time to create user_user_matrix.\n# Pickled this file on disk to avoid time taken during re-runs and debugging.\n\n# Reading pickled file holding user_user_matrix\nuser_user_matrix=pd.read_pickle('user_common_article')\nuser_user_matrix.head()",
"_____no_output_____"
],
[
"def find_similar_users(user_id, user_user_matrix=user_user_matrix):\n '''\n INPUT:\n user_id - (int) a user_id\n user_user_matrix - (pandas dataframe) matrix that holds number of common articles between each pair of users.\n \n OUTPUT:\n similar_users - (list) an ordered list where the closest users are listed first\n \n Description:\n Computes the similarity of every pair of users\n '''\n \n most_similar_users=list(user_user_matrix[user_id].sort_values(ascending=False).index)[1:]\n \n return most_similar_users # return a list of the users in order from most to least similar",
"_____no_output_____"
],
[
"# Do a spot check of the function\nprint(\"The 10 most similar users to user 1 are: {}\".format(find_similar_users(1)[:10]))\nprint(\"The 5 most similar users to user 3933 are: {}\".format(find_similar_users(3933)[:5]))\nprint(\"The 3 most similar users to user 46 are: {}\".format(find_similar_users(46)[:3]))",
"The 10 most similar users to user 1 are: [3933, 23, 3782, 203, 4459, 3870, 131, 4201, 46, 5041]\nThe 5 most similar users to user 3933 are: [3933, 3782, 23, 4459, 203]\nThe 3 most similar users to user 46 are: [4201, 23, 3782]\n"
]
],
[
[
"#### Now that we have a function that provides the most similar users to each user, we will use these users to find articles that can be recommended.",
"_____no_output_____"
]
],
[
[
"def get_article_names(article_ids, df=df):\n '''\n INPUT:\n article_ids - (list) a list of article ids\n df - (pandas dataframe) df as defined at the top of the notebook\n \n OUTPUT:\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the title column)\n '''\n \n article_names=list(df[df.article_id.isin(article_ids)].title.groupby(df.title).size().index.values)\n \n return article_names # Return the article names associated with list of article ids\n\n\ndef get_user_articles(user_id, user_item=user_item):\n '''\n INPUT:\n user_id - (int) a user id\n user_item - (pandas dataframe) matrix of users by articles: \n 1's when a user has interacted with an article, 0 otherwise\n \n OUTPUT:\n article_ids - (list) a list of the article ids seen by the user\n article_names - (list) a list of article names associated with the list of article ids \n (this is identified by the doc_full_name column in df_content)\n \n Description:\n Provides a list of the article_ids and article titles that have been seen by a user\n '''\n article_ids=user_dict[user_id]\n \n article_names=get_article_names(article_ids)\n \n return article_ids, article_names # return the ids and names\n\n\ndef user_user_recs(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user\n \n Description:\n Loops through the users based on closeness to the input user_id\n For each user - finds articles the user hasn't seen before and provides them as recs\n Does this until m recommendations are found\n \n Notes:\n Users who are the same closeness are chosen arbitrarily as the 'next' user\n \n For the user where the number of recommended articles starts below m \n and ends exceeding m, the last items are chosen arbitrarily\n \n '''\n art=[]\n for i in find_similar_users(user_id):\n art.extend(np.setdiff1d(user_dict[i],user_dict[user_id]))\n if len(set(art))>m:\n break\n recs=list(set(art[:m]))\n \n return recs # return recommendations for this user_id ",
"_____no_output_____"
],
[
"# Check Results\nget_article_names(user_user_recs(1, 10)) # Return 10 recommendations for user 1",
"_____no_output_____"
],
[
"# List of articles seen by user 1\nget_user_articles(1)[1]",
"_____no_output_____"
],
[
"# Test the functions here\n\nassert set(get_article_names(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis']), \"Oops! Your the get_article_names function doesn't work quite how we expect.\"\nassert set(get_article_names(['1320.0', '232.0', '844.0'])) == set(['housing (2015): united states demographic measures','self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook']), \"Oops! Your the get_article_names function doesn't work quite how we expect.\"\nassert set(get_user_articles(20)[0]) == set(['1320.0', '232.0', '844.0'])\nassert set(get_user_articles(20)[1]) == set(['housing (2015): united states demographic measures', 'self-service data preparation with ibm data refinery','use the cloudant-spark connector in python notebook'])\nassert set(get_user_articles(2)[0]) == set(['1024.0', '1176.0', '1305.0', '1314.0', '1422.0', '1427.0'])\nassert set(get_user_articles(2)[1]) == set(['using deep learning to reconstruct high-resolution audio', 'build a python app on the streaming analytics service', 'gosales transactions for naive bayes model', 'healthcare python streaming application demo', 'use r dataframes & ibm watson natural language understanding', 'use xgboost, scikit-learn & ibm watson machine learning apis'])\nprint(\"If this is all you see, you passed all of our tests! Nice job!\")",
"If this is all you see, you passed all of our tests! Nice job!\n"
]
],
[
[
"Now we are going to improve the consistency of the **user_user_recs** function from above.\n\nInstead of arbitrarily choosing articles from the user where the number of recommended articles starts below m and ends exceeding m, we will choose articles with the articles with the most total interactions before choosing those with fewer total interactions. This ranking should be what would be obtained from the **top_articles** function.",
"_____no_output_____"
]
],
[
[
"def user_user_recs_part2(user_id, m=10):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n \n OUTPUT:\n recs - (list) a list of recommendations for the user by article id\n rec_names - (list) a list of recommendations for the user by article title\n \n Notes:\n * Choose the users that have the most total article interactions \n before choosing those with fewer article interactions.\n\n * Choose articles with the articles with the most total interactions \n before choosing those with fewer total interactions. \n \n '''\n rec_names=list(df[df.article_id.isin(user_user_recs(user_id))].title.value_counts().index)\n recs= list(set(df[df.title.isin(rec_names)].article_id.values))\n \n return recs, rec_names",
"_____no_output_____"
],
[
"# Quick spot check\n\nrec_ids, rec_names = user_user_recs_part2(20, 10)\nprint(\"The top 10 recommendations for user 20 are the following article ids:\")\nprint(rec_ids)\nprint()\nprint(\"The top 10 recommendations for user 20 are the following article names:\")\nprint(rec_names)",
"The top 10 recommendations for user 20 are the following article ids:\n['1296.0', '1053.0', '1271.0', '1324.0', '727.0', '1186.0', '495.0', '53.0', '1396.0', '793.0']\n\nThe top 10 recommendations for user 20 are the following article names:\n['customer demographics and sales', 'access mysql with python', 'times world university ranking analysis', 'fortune 100 companies', 'ibm watson facebook posts for 2015', 'connect to db2 warehouse on cloud and db2 using scala', 'introducing streams designer', 'top 10 machine learning algorithms for beginners', '10 powerful features on watson data platform, no coding necessary', 'from python nested lists to multidimensional numpy arrays']\n"
],
[
"# List of articles seen by user 20\n# Make sure that these articles don't appear in the recommended list of articles\nget_user_articles(20)[1]",
"_____no_output_____"
],
[
"def all_recommendations():\n '''\n INPUT \n num_recs (int) the (max) number of recommendations for each user\n OUTPUT\n all_recs - a dictionary where each key is a user_id and the value is an array of recommended movie titles\n '''\n all_recs={}\n for i in list(user_user_matrix.columns):\n all_recs[i]=user_user_recs_part2(i)[0]\n \n return all_recs\n\nall_recs = all_recommendations()",
"_____no_output_____"
],
[
"all_recs[4]",
"_____no_output_____"
],
[
"# Check for users with no recommendations\n# Should be empty list of recommendations have been made for all users\nno_recs=[]\nfor i,v in all_recs.items():\n if len(v)==0:\n no_recs.append(i)\nno_recs",
"_____no_output_____"
]
],
[
[
"`5.` Use the functions from above to correctly fill in the solutions to the dictionary below. Then test against the solution.",
"_____no_output_____"
]
],
[
[
"print(find_similar_users(1)[0])\nprint(find_similar_users(131)[10])",
"3933\n242\n"
],
[
"### Tests with a dictionary of results\n\nuser1_most_sim = 3933\nuser131_10th_sim = 242 # Find the 10th most similar user to user 131",
"_____no_output_____"
],
[
"## Dictionary Test Here\nsol_5_dict = {\n 'The user that is most similar to user 1.': user1_most_sim, \n 'The user that is the 10th most similar to user 131': user131_10th_sim,\n}\n\nt.sol_5_test(sol_5_dict)",
"This all looks good! Nice job!\n"
]
],
[
[
"`6.` Using existing functions, provide the top 10 recommended articles for a new user below.",
"_____no_output_____"
]
],
[
[
"new_user = '0.0'\n\n# As a new user, they have no observed articles. Provide a list of the top 10 article ids as recommendations\nnew_user_recs = get_top_article_ids(10)",
"_____no_output_____"
],
[
"assert set(new_user_recs) == set(['1314.0','1429.0','1293.0','1427.0','1162.0','1364.0','1304.0','1170.0','1431.0','1330.0']), \"Oops! It makes sense that in this case we would want to recommend the most popular articles, because we don't know anything about these users.\"\n\nprint(\"That's right! Nice job!\")",
"That's right! Nice job!\n"
]
],
[
[
"### <a class=\"anchor\" id=\"Matrix-Fact\">Part IV: Content Based Recommendations</a>\n\nAnother method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. We can consider content to be the doc_body, doc_description, or doc_full_name. There isn't one way to create a content based recommendation, especially considering that each of these columns hold content related information.",
"_____no_output_____"
]
],
[
[
"def tokenize(text):\n \"\"\"Function to tokenize an article title\n\n Args:\n text (str) title\n\n return:\n tokens (list) a list of words\n\n \"\"\"\n\n # normalize case and remove punctuation\n text = re.sub(r\"[^a-zA-Z0-9]\", \" \", text.lower())\n\n # tokenize text\n tokens = word_tokenize(text)\n\n # lemmatize and remove stop words\n stop_words = stopwords.words(\"english\")\n lemmatizer = WordNetLemmatizer()\n tokens = [lemmatizer.lemmatize(word) for word in tokens\n if word not in stop_words]\n # remove short words\n tokens = [token for token in tokens if len(token) > 2]\n\n return tokens",
"_____no_output_____"
],
[
"def create_article_content_dataframe(df=df, df_content=df_content):\n '''\n INPUT:\n df - pandas dataframe describe user interaction with the articles\n df_content - pandas dataframe describe articles on the platform\n \n OUTPUT:\n df_total - pandas dataframe contains all articles in the platform\n article_content - pandas dataframe describe the content of each\n article on the platform\n\n Description:\n Return a pandas dataframe containing all the articles in the platform\n with thier titles and a pandas dataframe describes the content of each\n article base on the article title.\n '''\n\n # Get a dataframe of the full articles\n df_1 = df[['article_id', 'title']]\n df_2 = pd.DataFrame({'article_id': df_content.article_id.values,\n 'title': df_content. doc_full_name})\n df_total = pd.concat([df_1, df_2], ignore_index=True)\n \n df_total.article_id=df_total.article_id.astype(float)\n df.article_id=df.article_id.astype(float)\n df_content.article_id=df_content.article_id.astype(float)\n \n df_total.drop_duplicates(subset=['article_id'], inplace=True)\n df_total.sort_values(by='article_id', inplace=True)\n df_total.reset_index(drop=True, inplace=True)\n\n # TfidfVectorizer\n vectorizer = TfidfVectorizer(tokenizer=tokenize)\n df_vec = pd.DataFrame(vectorizer.fit_transform(\n df_total.title.values).toarray(),\n columns=[*vectorizer.vocabulary_])\n\n # concat df_total and df_vec\n df_articles = pd.concat([df_total, df_vec], axis=1)\n \n return df_total, df_articles\n\n\ndf_total, df_articles = create_article_content_dataframe()",
"F:\\Anaconda\\lib\\site-packages\\pandas\\core\\generic.py:5168: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n self[name] = value\n"
],
[
"df_total.head()",
"_____no_output_____"
],
[
"df_articles.head()",
"_____no_output_____"
],
[
"def create_article_similarity_dataframe(df=df_articles):\n '''\n INPUT:\n df - pandas dataframe describe articles content\n OUTPUT:\n article_content - pandas dataframe describe articles similarities\n\n Description:\n Return a pandas dataframe that describe the articles similarities\n using the dot product.\n '''\n\n # subset articles content\n article_content = np.array(df_articles.iloc[:, 2:])\n\n # Take the dot product to obtain a article x article matrix of similarities\n dot_prod_article = article_content.dot(np.transpose(article_content))\n\n # checks the dot product\n assert dot_prod_article.shape[0] == len(df_articles)\n assert dot_prod_article.shape[1] == len(df_articles)\n\n # make a Dataframe\n article_similarity = pd.DataFrame(dot_prod_article,\n index=df_articles.article_id,\n columns=df_articles.article_id)\n\n return article_similarity\n\n\narticle_similarity = create_article_similarity_dataframe()",
"_____no_output_____"
],
[
"article_similarity.head()",
"_____no_output_____"
],
[
"def top_user_articles(user_id, df=df):\n '''\n INPUT:\n user_id - (int) a user id\n user_item - (pandas dataframe) dataframe of user interaction\n\n OUTPUT:\n article_ids - (list) a sorted list of the article ids seen by the user\n\n Description:\n Provides a list of the article_ids sorted by interactions number\n '''\n\n df_user = df[df.user_id == user_id]\n df_user = df_user.groupby('article_id').count()\n df_user.sort_values('user_id', ascending=False, inplace=True)\n\n count_article = df_user.user_id.unique()\n article_ids = []\n for k in count_article:\n ids = df_user[df_user.user_id == k].index\n article_ids.append(list(ids))\n\n return article_ids",
"_____no_output_____"
],
[
"def make_content_recs(user_id, m=10, df_smly=article_similarity, thd=1):\n '''\n INPUT:\n user_id - (int) a user id\n m - (int) the number of recommendations you want for the user\n df_smly - (pandas dataframe) pandas dataframe that describe the articles\n similarities using the dot product\n\n OUTPUT:\n recs - (list) a list of recommendations for the user by article id\n rec_names - (list) a list of recommendations for the user by article title\n '''\n\n list_ids = top_user_articles(user_id)\n recs = []\n\n for ids in list_ids:\n top_articles = article_similarity.loc[ids].sum()\n top_articles.sort_values(ascending=False, inplace=True)\n top_articles = top_articles[top_articles >= thd]\n article_not_recs = np.setdiff1d(np.array(top_articles.index),\n np.array(recs))\n recs.extend(list(article_not_recs))\n\n # If there are more than\n if len(recs) > m:\n break\n\n recs = recs[:10]\n rec_names = get_article_names(recs, df=df_total)\n\n return recs, rec_names",
"_____no_output_____"
]
],
[
[
"#### In order to build content-based Recommendations, I have used the titlr variable to compute similarities between articles. Given a user id, we can make recommendations by looking for most similar articles to the articles seen by the user.",
"_____no_output_____"
]
],
[
[
"# Get user id who only has interacted with article id '1434.0'\ndf_1434 = df[df.article_id == 1434.0].groupby('user_id').count()\nuser_1434 = df_1434.sort_values('article_id').index[0]\n\n# Make recomendation\nmake_content_recs(user_1434)",
"_____no_output_____"
]
],
[
[
"### <a class=\"anchor\" id=\"Matrix-Fact\">Part V: Matrix Factorization</a>",
"_____no_output_____"
]
],
[
[
"# quick look at the user_item matrix created earlier\nuser_item.head()",
"_____no_output_____"
]
],
[
[
"#### In this situation, we can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix.",
"_____no_output_____"
],
[
"##### There are no missing values in the data so we can use the traditional SVD. If there were any missing values, traditional SVD would not have converged and errored out. In that case we would have used FunkSVD to handle missing values",
"_____no_output_____"
]
],
[
[
"# Perform SVD on the User-Item Matrix Here\nu, s, vt = np.linalg.svd(user_item,full_matrices=False)",
"_____no_output_____"
],
[
"s1=np.diag(s)\nu.shape,s1.shape,vt.shape",
"_____no_output_____"
]
],
[
[
"#### Now for the tricky part, how do we choose the number of latent features to use? Running the below cell, we can see that as the number of latent features increases, we obtain a lower error rate on making predictions for the 1 and 0 values in the user-item matrix.",
"_____no_output_____"
]
],
[
[
"num_latent_feats = np.arange(10,700+10,20)\nsum_errs = []\n\nfor k in num_latent_feats:\n # restructure with k latent features\n s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :]\n \n # take dot product\n user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))\n \n # compute error for each prediction to actual value\n diffs = np.subtract(user_item, user_item_est)\n \n # total errors and keep track of them\n err = np.sum(np.sum(np.abs(diffs)))\n sum_errs.append(err)\n \n \nplt.plot(num_latent_feats, 1 - np.array(sum_errs)/df.shape[0]);\nplt.xlabel('Number of Latent Features');\nplt.ylabel('Accuracy');\nplt.title('Accuracy vs. Number of Latent Features');",
"_____no_output_____"
]
],
[
[
"#### From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in the cell below. \n\nTo understand the impact on accuracy of the training and test sets of data with different numbers of latent features, find the following:\n\n* How many users can we make predictions for in the test set? \n* How many users are we not able to make predictions for because of the cold start problem?\n* How many articles can we make predictions for in the test set? \n* How many articles are we not able to make predictions for because of the cold start problem?",
"_____no_output_____"
]
],
[
[
"df_train = df.head(40000)\ndf_test = df.tail(5993)\n\ndef create_test_and_train_user_item(df_train, df_test):\n '''\n INPUT:\n df_train - training dataframe\n df_test - test dataframe\n \n OUTPUT:\n user_item_train - a user-item matrix of the training dataframe \n (unique users for each row and unique articles for each column)\n user_item_test - a user-item matrix of the testing dataframe \n (unique users for each row and unique articles for each column)\n test_idx - all of the test user ids\n test_arts - all of the test article ids\n \n '''\n user_item_train=create_user_item_matrix(df_train)\n \n user_item_test=create_user_item_matrix(df_test)\n \n test_idx=user_item_test.index.values\n \n test_arts=user_item_test.columns.values\n \n return user_item_train, user_item_test, test_idx, test_arts\n\nuser_item_train, user_item_test, test_idx, test_arts = create_test_and_train_user_item(df_train, df_test)",
"_____no_output_____"
],
[
"len(np.setdiff1d(user_item_test.index, user_item_train.index))",
"_____no_output_____"
],
[
"len(np.intersect1d(test_idx, user_item_train.index))",
"_____no_output_____"
],
[
"len(np.intersect1d(user_item_test.columns, user_item_train.columns))",
"_____no_output_____"
],
[
"len(np.setdiff1d(user_item_test.columns, user_item_train.columns))",
"_____no_output_____"
],
[
"# Spot check\nsol_4_dict = {\n 'How many users can we make predictions for in the test set?': 20, \n 'How many users in the test set are we not able to make predictions for because of the cold start problem?': 662 , \n 'How many movies can we make predictions for in the test set?': 574,\n 'How many movies in the test set are we not able to make predictions for because of the cold start problem?': 0\n}\n\nt.sol_4_test(sol_4_dict)",
"Awesome job! That's right! All of the test movies are in the training data, but there are only 20 test users that were also in the training set. All of the other users that are in the test set we have no data on. Therefore, we cannot make predictions for these users using SVD.\n"
]
],
[
[
"#### Now use the **user_item_train** dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the **user_item_test** dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on the accuracy on the test data.",
"_____no_output_____"
]
],
[
[
"# Number of rows in user_item_test for which prediction can be made\nlen(np.intersect1d(test_idx, user_item_train.index))",
"_____no_output_____"
],
[
"# Rows in dataset user_item_test for which prediction can be made\nuser_item_train[user_item_train.index.isin(list(np.intersect1d(test_idx, user_item_train.index)))]",
"_____no_output_____"
],
[
"# fit SVD on the user_item_train matrix\nu_train, s_train, vt_train = np.linalg.svd(user_item_train,full_matrices=False)\ns_train_1=np.diag(s_train)\nu_train.shape, s_train_1.shape, vt_train.shape",
"_____no_output_____"
],
[
"# Users and articles in user_item_train matrix\ntrain_idx = np.array(user_item_train.index)\ntrain_arts = np.array(user_item_train.columns)\n\n# Users and articles of test set in training set\ntest_idx_set = np.intersect1d(test_idx, train_idx)\ntest_arts_set = np.intersect1d(test_arts, train_arts)\n\n# Users and articles positions of test subset in training matrix\ntrain_indexes = np.where(np.in1d(train_idx, test_idx_set))[0]\ntrain_articles = np.where(np.in1d(train_arts, test_arts_set))[0]\n\n# Users positions of test subset in test matrix\ntest_indexes = np.where(np.in1d(test_idx, test_idx_set))[0]",
"_____no_output_____"
],
[
"# Find subset of User_Item Matrix containing only user and articles that are shared by train and test set\nu_item_test_set = user_item_test.iloc[test_indexes,:]\nu_item_train_set = user_item_train.iloc[train_indexes, train_articles]",
"_____no_output_____"
],
[
"num_latent_feats = np.arange(10, 500, 20)\nsum_errs = []\n\nfor k in num_latent_feats:\n \n # Restructure train matrices using k features\n s_train_k, u_train_k, vt_train_k = np.diag(s_train[:k]), u_train[:, :k], vt_train[:k, :]\n \n # Restructure test matrices using k features\n s_test_k, u_test_k, vt_test_k = s_train_k, u_train_k[train_indexes,:], vt_train_k[:,train_articles]\n \n # Calculate dot product\n u_item_test_set_pred = np.around(np.dot(np.dot(u_test_k, s_test_k), vt_test_k))\n \n # Error (prediction - actual values)\n error = np.subtract(u_item_test_set, u_item_test_set_pred)\n \n # Total errors\n total_error = np.sum(np.sum(np.abs(error)))\n sum_errs.append(total_error)\n \n\n# Plot test accuracy and latent features\nn_interactions_set = u_item_test_set.shape[0] * u_item_test_set.shape[1]\nplt.plot(num_latent_feats, 1 - np.array(sum_errs) / n_interactions_set);\nplt.xlabel('Latent Features');\nplt.ylabel('Accuracy');\nplt.title('Test Accuracy vs Latent Features');",
"_____no_output_____"
]
],
[
[
"#### Conclusion:\n\n* Test accuracy decreases as a number of latent factors increases, but training accuracy increases. In this situation, the accuracy is not appropriate, because predicted interactions between users and articles are very few (imbalanced).\n\n\n* User based collaborative filtering recommendation can use user's historical interact to suggest articles. And matrix Factorization recommendation can clearly explain why the articles are recommended, but they cannot be used for new users. Only 20 users of total 682 users are old users and can be recommended because they are common between the training set and test set.\n\n\n* In order to improve the above issue, Ranked based recommendation can be used for new user and solve the cold start problems. and also content based recommendation also can be used for the users with few interact. A/B testing can be used to find out which model is better.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
ece7a083555799c6c09119b3671e5774cbc608bb | 1,892 | ipynb | Jupyter Notebook | notebooks/movie_making.ipynb | ptosco/nglview | 1a03ec66844128a14080d6f7f0a902545423fe83 | [
"MIT"
] | 161 | 2020-07-28T14:05:57.000Z | 2022-03-31T08:38:06.000Z | notebooks/movie_making.ipynb | ptosco/nglview | 1a03ec66844128a14080d6f7f0a902545423fe83 | [
"MIT"
] | 123 | 2020-07-27T15:02:27.000Z | 2022-03-30T18:31:51.000Z | notebooks/movie_making.ipynb | ptosco/nglview | 1a03ec66844128a14080d6f7f0a902545423fe83 | [
"MIT"
] | 42 | 2020-07-28T09:50:06.000Z | 2022-03-11T18:50:22.000Z | 21.258427 | 71 | 0.537526 | [
[
[
"from IPython.display import Image",
"_____no_output_____"
],
[
"import nglview as nv\nfrom nglview.contrib.movie import MovieMaker\nimport pytraj as pt\n\ntraj = pt.load(nv.datafiles.XTC, nv.datafiles.PDB)[:5]\nview = nv.show_pytraj(traj, default=False)\nview.center()\nview.add_surface('protein', opacity=0.5, color='residueindex')\nview.control.orient([15.69986420582941,\n 114.8276262266868,\n 48.816742057652796,\n 0,\n -18.22863682402078,\n -46.5629522451937,\n 115.38869989652724,\n 0,\n 123.43490126182644,\n -21.481422658119275,\n 10.831316500165215,\n 0,\n -39.1268284890941,\n -46.69809684423501,\n -44.63013982367478,\n 1])\nview",
"_____no_output_____"
],
[
"# require: `pip install moviepy`\n\nmovie = MovieMaker(view, in_memory=True, output='abc.gif')\nmovie.make()",
"_____no_output_____"
],
[
"Image('./abc.gif')",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
ece7a37a4072759ca8d742091ed93b173514977a | 43,921 | ipynb | Jupyter Notebook | AI_Class/021/Dnn1.ipynb | easycastle/Cpprhtn-s_Deep_Learning | 98276236a83faa62533b35c7fb6a71a9fd51b3d2 | [
"MIT"
] | 20 | 2021-02-03T11:10:12.000Z | 2022-01-22T12:37:18.000Z | AI_Class/021/Dnn1.ipynb | easycastle/Cpprhtn-s_Deep_Learning | 98276236a83faa62533b35c7fb6a71a9fd51b3d2 | [
"MIT"
] | null | null | null | AI_Class/021/Dnn1.ipynb | easycastle/Cpprhtn-s_Deep_Learning | 98276236a83faa62533b35c7fb6a71a9fd51b3d2 | [
"MIT"
] | 7 | 2021-02-03T12:52:41.000Z | 2022-03-08T01:13:34.000Z | 111.474619 | 22,720 | 0.732087 | [
[
[
"# Dnn 실습\n\n주어진 코드는 import lib, data와 Modeling 파트입니다.\n\n타이타닉 데이터셋을 사용했습니다.\n\n이제껏 배워왔던 내용들을 기반으로 Dnn 모델을 구축해보세요.\n\n- 목표 : 정확도 85 넘기기",
"_____no_output_____"
],
[
"### Import library & data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"df = sns.load_dataset('titanic')",
"_____no_output_____"
]
],
[
[
"## EDA\n\n목차의 KNN내용 참고",
"_____no_output_____"
],
[
"## Modeling",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense",
"_____no_output_____"
],
[
"model = Sequential()\nmodel.add(Dense(16, input_shape=(,), activation=''))\nmodel.add(Dense(16, activation=''))\nmodel.add(Dense((1), activation=''))\nmodel.compile(loss='mse', optimizer='', metrics=['accuracy'])\nmodel.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 256) 2304 \n_________________________________________________________________\ndense_1 (Dense) (None, 256) 65792 \n_________________________________________________________________\ndense_2 (Dense) (None, 16) 4112 \n_________________________________________________________________\ndense_3 (Dense) (None, 16) 272 \n_________________________________________________________________\ndense_4 (Dense) (None, 10) 170 \n=================================================================\nTotal params: 72,650\nTrainable params: 72,650\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=30)",
"Train on 571 samples, validate on 143 samples\nEpoch 1/100\n571/571 [==============================] - 0s 234us/step - loss: 0.2347 - accuracy: 0.6007 - val_loss: 0.2207 - val_accuracy: 0.6084\nEpoch 2/100\n571/571 [==============================] - 0s 27us/step - loss: 0.2037 - accuracy: 0.7040 - val_loss: 0.1933 - val_accuracy: 0.7483\nEpoch 3/100\n571/571 [==============================] - 0s 30us/step - loss: 0.1850 - accuracy: 0.7758 - val_loss: 0.1779 - val_accuracy: 0.7692\nEpoch 4/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1752 - accuracy: 0.7776 - val_loss: 0.1685 - val_accuracy: 0.7902\nEpoch 5/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1690 - accuracy: 0.7793 - val_loss: 0.1636 - val_accuracy: 0.7902\nEpoch 6/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1658 - accuracy: 0.7793 - val_loss: 0.1603 - val_accuracy: 0.7902\nEpoch 7/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1637 - accuracy: 0.7776 - val_loss: 0.1572 - val_accuracy: 0.7902\nEpoch 8/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1620 - accuracy: 0.7811 - val_loss: 0.1538 - val_accuracy: 0.7902\nEpoch 9/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1609 - accuracy: 0.7811 - val_loss: 0.1516 - val_accuracy: 0.7902\nEpoch 10/100\n571/571 [==============================] - 0s 30us/step - loss: 0.1598 - accuracy: 0.7811 - val_loss: 0.1505 - val_accuracy: 0.7902\nEpoch 11/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1593 - accuracy: 0.7828 - val_loss: 0.1494 - val_accuracy: 0.7902\nEpoch 12/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1583 - accuracy: 0.7828 - val_loss: 0.1480 - val_accuracy: 0.7902\nEpoch 13/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1577 - accuracy: 0.7863 - val_loss: 0.1464 - val_accuracy: 0.7972\nEpoch 14/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1573 - accuracy: 0.7863 - val_loss: 0.1458 - val_accuracy: 0.7972\nEpoch 15/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1568 - accuracy: 0.7863 - val_loss: 0.1436 - val_accuracy: 0.8042\nEpoch 16/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1561 - accuracy: 0.7863 - val_loss: 0.1437 - val_accuracy: 0.8042\nEpoch 17/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1555 - accuracy: 0.7898 - val_loss: 0.1428 - val_accuracy: 0.8112\nEpoch 18/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1553 - accuracy: 0.7916 - val_loss: 0.1417 - val_accuracy: 0.8322\nEpoch 19/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1547 - accuracy: 0.7951 - val_loss: 0.1407 - val_accuracy: 0.8252\nEpoch 20/100\n571/571 [==============================] - 0s 33us/step - loss: 0.1543 - accuracy: 0.8021 - val_loss: 0.1402 - val_accuracy: 0.8322\nEpoch 21/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1539 - accuracy: 0.8021 - val_loss: 0.1395 - val_accuracy: 0.8322\nEpoch 22/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1535 - accuracy: 0.8021 - val_loss: 0.1391 - val_accuracy: 0.8322\nEpoch 23/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1532 - accuracy: 0.8039 - val_loss: 0.1384 - val_accuracy: 0.8322\nEpoch 24/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1530 - accuracy: 0.8039 - val_loss: 0.1381 - val_accuracy: 0.8322\nEpoch 25/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1528 - accuracy: 0.8039 - val_loss: 0.1370 - val_accuracy: 0.8322\nEpoch 26/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1526 - accuracy: 0.8056 - val_loss: 0.1374 - val_accuracy: 0.8462\nEpoch 27/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1522 - accuracy: 0.8074 - val_loss: 0.1364 - val_accuracy: 0.8462\nEpoch 28/100\n571/571 [==============================] - 0s 30us/step - loss: 0.1520 - accuracy: 0.8074 - val_loss: 0.1359 - val_accuracy: 0.8462\nEpoch 29/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1515 - accuracy: 0.8074 - val_loss: 0.1362 - val_accuracy: 0.8462\nEpoch 30/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1514 - accuracy: 0.8074 - val_loss: 0.1352 - val_accuracy: 0.8462\nEpoch 31/100\n571/571 [==============================] - 0s 33us/step - loss: 0.1512 - accuracy: 0.8109 - val_loss: 0.1349 - val_accuracy: 0.8462\nEpoch 32/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1509 - accuracy: 0.8091 - val_loss: 0.1343 - val_accuracy: 0.8462\nEpoch 33/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1508 - accuracy: 0.8074 - val_loss: 0.1341 - val_accuracy: 0.8462\nEpoch 34/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1505 - accuracy: 0.8109 - val_loss: 0.1344 - val_accuracy: 0.8462\nEpoch 35/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1503 - accuracy: 0.8109 - val_loss: 0.1334 - val_accuracy: 0.8462\nEpoch 36/100\n571/571 [==============================] - 0s 36us/step - loss: 0.1501 - accuracy: 0.8109 - val_loss: 0.1334 - val_accuracy: 0.8462\nEpoch 37/100\n571/571 [==============================] - 0s 35us/step - loss: 0.1500 - accuracy: 0.8091 - val_loss: 0.1334 - val_accuracy: 0.8462\nEpoch 38/100\n571/571 [==============================] - 0s 47us/step - loss: 0.1498 - accuracy: 0.8091 - val_loss: 0.1328 - val_accuracy: 0.8462\nEpoch 39/100\n571/571 [==============================] - 0s 41us/step - loss: 0.1496 - accuracy: 0.8074 - val_loss: 0.1332 - val_accuracy: 0.8462\nEpoch 40/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1495 - accuracy: 0.8091 - val_loss: 0.1325 - val_accuracy: 0.8462\nEpoch 41/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1492 - accuracy: 0.8109 - val_loss: 0.1323 - val_accuracy: 0.8462\nEpoch 42/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1492 - accuracy: 0.8109 - val_loss: 0.1321 - val_accuracy: 0.8462\nEpoch 43/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1492 - accuracy: 0.8144 - val_loss: 0.1317 - val_accuracy: 0.8462\nEpoch 44/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1491 - accuracy: 0.8109 - val_loss: 0.1319 - val_accuracy: 0.8462\nEpoch 45/100\n571/571 [==============================] - 0s 30us/step - loss: 0.1488 - accuracy: 0.8144 - val_loss: 0.1320 - val_accuracy: 0.8462\nEpoch 46/100\n571/571 [==============================] - 0s 34us/step - loss: 0.1489 - accuracy: 0.8091 - val_loss: 0.1313 - val_accuracy: 0.8462\nEpoch 47/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1485 - accuracy: 0.8126 - val_loss: 0.1314 - val_accuracy: 0.8462\nEpoch 48/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1486 - accuracy: 0.8109 - val_loss: 0.1312 - val_accuracy: 0.8462\nEpoch 49/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1486 - accuracy: 0.8126 - val_loss: 0.1311 - val_accuracy: 0.8462\nEpoch 50/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1485 - accuracy: 0.8126 - val_loss: 0.1307 - val_accuracy: 0.8462\nEpoch 51/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1481 - accuracy: 0.8109 - val_loss: 0.1309 - val_accuracy: 0.8462\nEpoch 52/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1480 - accuracy: 0.8126 - val_loss: 0.1302 - val_accuracy: 0.8462\nEpoch 53/100\n571/571 [==============================] - 0s 30us/step - loss: 0.1478 - accuracy: 0.8144 - val_loss: 0.1302 - val_accuracy: 0.8462\nEpoch 54/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1480 - accuracy: 0.8074 - val_loss: 0.1311 - val_accuracy: 0.8462\nEpoch 55/100\n571/571 [==============================] - 0s 30us/step - loss: 0.1479 - accuracy: 0.8144 - val_loss: 0.1301 - val_accuracy: 0.8392\nEpoch 56/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1477 - accuracy: 0.8126 - val_loss: 0.1299 - val_accuracy: 0.8462\nEpoch 57/100\n571/571 [==============================] - 0s 32us/step - loss: 0.1474 - accuracy: 0.8144 - val_loss: 0.1301 - val_accuracy: 0.8462\nEpoch 58/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1475 - accuracy: 0.8144 - val_loss: 0.1304 - val_accuracy: 0.8462\nEpoch 59/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1476 - accuracy: 0.8109 - val_loss: 0.1305 - val_accuracy: 0.8462\nEpoch 60/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1475 - accuracy: 0.8144 - val_loss: 0.1307 - val_accuracy: 0.8462\nEpoch 61/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1471 - accuracy: 0.8144 - val_loss: 0.1297 - val_accuracy: 0.8462\nEpoch 62/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1474 - accuracy: 0.8144 - val_loss: 0.1298 - val_accuracy: 0.8462\nEpoch 63/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1471 - accuracy: 0.8144 - val_loss: 0.1294 - val_accuracy: 0.8462\nEpoch 64/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1470 - accuracy: 0.8144 - val_loss: 0.1293 - val_accuracy: 0.8462\nEpoch 65/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1468 - accuracy: 0.8144 - val_loss: 0.1296 - val_accuracy: 0.8462\nEpoch 66/100\n571/571 [==============================] - 0s 31us/step - loss: 0.1467 - accuracy: 0.8144 - val_loss: 0.1299 - val_accuracy: 0.8462\nEpoch 67/100\n571/571 [==============================] - 0s 30us/step - loss: 0.1469 - accuracy: 0.8144 - val_loss: 0.1296 - val_accuracy: 0.8462\nEpoch 68/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1469 - accuracy: 0.8144 - val_loss: 0.1296 - val_accuracy: 0.8462\nEpoch 69/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1466 - accuracy: 0.8126 - val_loss: 0.1292 - val_accuracy: 0.8462\nEpoch 70/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1465 - accuracy: 0.8126 - val_loss: 0.1296 - val_accuracy: 0.8462\nEpoch 71/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1462 - accuracy: 0.8144 - val_loss: 0.1295 - val_accuracy: 0.8462\nEpoch 72/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1462 - accuracy: 0.8144 - val_loss: 0.1293 - val_accuracy: 0.8462\nEpoch 73/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1462 - accuracy: 0.8144 - val_loss: 0.1296 - val_accuracy: 0.8462\nEpoch 74/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1460 - accuracy: 0.8144 - val_loss: 0.1289 - val_accuracy: 0.8462\nEpoch 75/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1461 - accuracy: 0.8144 - val_loss: 0.1289 - val_accuracy: 0.8462\nEpoch 76/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1459 - accuracy: 0.8144 - val_loss: 0.1287 - val_accuracy: 0.8462\nEpoch 77/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1461 - accuracy: 0.8144 - val_loss: 0.1297 - val_accuracy: 0.8462\nEpoch 78/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1458 - accuracy: 0.8144 - val_loss: 0.1291 - val_accuracy: 0.8462\nEpoch 79/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1457 - accuracy: 0.8144 - val_loss: 0.1288 - val_accuracy: 0.8462\nEpoch 80/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1458 - accuracy: 0.8144 - val_loss: 0.1291 - val_accuracy: 0.8462\nEpoch 81/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1458 - accuracy: 0.8144 - val_loss: 0.1291 - val_accuracy: 0.8462\nEpoch 82/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1457 - accuracy: 0.8144 - val_loss: 0.1290 - val_accuracy: 0.8462\nEpoch 83/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1455 - accuracy: 0.8144 - val_loss: 0.1286 - val_accuracy: 0.8462\nEpoch 84/100\n571/571 [==============================] - 0s 29us/step - loss: 0.1455 - accuracy: 0.8144 - val_loss: 0.1284 - val_accuracy: 0.8462\nEpoch 85/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1455 - accuracy: 0.8144 - val_loss: 0.1289 - val_accuracy: 0.8462\nEpoch 86/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1454 - accuracy: 0.8144 - val_loss: 0.1284 - val_accuracy: 0.8462\nEpoch 87/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1452 - accuracy: 0.8144 - val_loss: 0.1287 - val_accuracy: 0.8462\nEpoch 88/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1454 - accuracy: 0.8144 - val_loss: 0.1292 - val_accuracy: 0.8462\nEpoch 89/100\n571/571 [==============================] - 0s 28us/step - loss: 0.1452 - accuracy: 0.8144 - val_loss: 0.1281 - val_accuracy: 0.8462\nEpoch 90/100\n571/571 [==============================] - 0s 34us/step - loss: 0.1452 - accuracy: 0.8161 - val_loss: 0.1292 - val_accuracy: 0.8462\nEpoch 91/100\n571/571 [==============================] - 0s 39us/step - loss: 0.1453 - accuracy: 0.8144 - val_loss: 0.1291 - val_accuracy: 0.8462\nEpoch 92/100\n571/571 [==============================] - 0s 36us/step - loss: 0.1452 - accuracy: 0.8161 - val_loss: 0.1287 - val_accuracy: 0.8462\nEpoch 93/100\n571/571 [==============================] - 0s 40us/step - loss: 0.1451 - accuracy: 0.8179 - val_loss: 0.1285 - val_accuracy: 0.8462\nEpoch 94/100\n571/571 [==============================] - 0s 34us/step - loss: 0.1452 - accuracy: 0.8144 - val_loss: 0.1288 - val_accuracy: 0.8462\nEpoch 95/100\n571/571 [==============================] - 0s 44us/step - loss: 0.1452 - accuracy: 0.8144 - val_loss: 0.1278 - val_accuracy: 0.8462\nEpoch 96/100\n571/571 [==============================] - 0s 40us/step - loss: 0.1448 - accuracy: 0.8179 - val_loss: 0.1284 - val_accuracy: 0.8462\nEpoch 97/100\n571/571 [==============================] - 0s 45us/step - loss: 0.1451 - accuracy: 0.8144 - val_loss: 0.1291 - val_accuracy: 0.8462\nEpoch 98/100\n571/571 [==============================] - 0s 35us/step - loss: 0.1450 - accuracy: 0.8144 - val_loss: 0.1284 - val_accuracy: 0.8462\nEpoch 99/100\n571/571 [==============================] - 0s 39us/step - loss: 0.1447 - accuracy: 0.8144 - val_loss: 0.1286 - val_accuracy: 0.8462\nEpoch 100/100\n571/571 [==============================] - 0s 39us/step - loss: 0.1449 - accuracy: 0.8161 - val_loss: 0.1280 - val_accuracy: 0.8462\n"
],
[
"pd.DataFrame(history.history).plot(figsize=(12, 5))\nplt.grid(True)\nplt.gca().set_ylim(0, 1)\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
ece7a9a285b0c3c9654d6b14285e239a08ea56ed | 56,694 | ipynb | Jupyter Notebook | ML-MAJOR-MAR-ML03B3 (2).ipynb | CoderNikhil-007/Machine-learning-model-for-women-s-clothing | 4e121e6e04e9249da1ff90a712b87aca2faf127b | [
"MIT"
] | null | null | null | ML-MAJOR-MAR-ML03B3 (2).ipynb | CoderNikhil-007/Machine-learning-model-for-women-s-clothing | 4e121e6e04e9249da1ff90a712b87aca2faf127b | [
"MIT"
] | null | null | null | ML-MAJOR-MAR-ML03B3 (2).ipynb | CoderNikhil-007/Machine-learning-model-for-women-s-clothing | 4e121e6e04e9249da1ff90a712b87aca2faf127b | [
"MIT"
] | null | null | null | 39.953488 | 10,984 | 0.606008 | [
[
[
"# Analysis:\n\n1.Describe the data\n \n a.Descriptive statistics, data type, etc.\n\n2.Analyze the text comment/ review and share the findings\n \n Convert the ratings into 2 classes\n \n a.Class: Bad when Rating <=3\n \n b.Class: Good otherwise\n\n3.Develop a model to predict the Rating class (created above)\n Focus on steps to build a model\n\n4.Which algorithm can be used and why\n Share the findings of the model.",
"_____no_output_____"
]
],
[
[
"#importing all the essential modules:\nimport numpy as np\nimport pandas as pd\nimport nltk\nimport random\nimport os\nfrom os import path\nfrom PIL import Image\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom subprocess import check_output\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nimport re\nfrom nltk.stem import PorterStemmer\n\nimport statsmodels.api as sm\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom nltk.sentiment.util import *\nfrom nltk.util import ngrams\nfrom collections import Counter\nfrom gensim.models import word2vec\nimport seaborn as sns\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import confusion_matrix\nimport sklearn.metrics as mt\nfrom plotly import tools\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\n%matplotlib inline\nfrom collections import Counter\nfrom nltk.tokenize import RegexpTokenizer\nfrom stop_words import get_stop_words\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk import sent_tokenize, word_tokenize\nfrom wordcloud import WordCloud, STOPWORDS\nimport re\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas_profiling\n\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"# Accessing datafile \ndf = pd.read_csv(\"Womens_Clothing_E_Commerce_Reviews.csv\")\ndf=df.drop(['Unnamed: 0'],axis=1)\ndf.head()",
"_____no_output_____"
],
[
"#checking all columns\ndf.columns",
"_____no_output_____"
],
[
"# showing datatpes of whole dataset\ndf.dtypes",
"_____no_output_____"
],
[
"# dropping unnecesary columns \ndf.drop(df.columns[0],inplace=True,axis=1)\n\n# Delete missing observations for following variables\nfor x in [\"Division Name\",\"Department Name\",\"Class Name\",\"Review Text\"]:\n df = df[df[x].notnull()]\n \n# Extracting Missing Count and Unique Count by Column\nunique_count = []\nfor x in df.columns:\n unique_count.append([x,len(df[x].unique()),df[x].isnull().sum()])\n\nprint(\"Missing Values: {}\".format(df.isnull().sum().sum())) #missing values\nprint(\"Dataframe Dimension: {} Rows, {} Columns\".format(*df.shape))\n\n# Create New Variables: \n# Word Length\ndf[\"Word Count\"] = df['Review Text'].str.split().apply(len)\n# Character Length\ndf[\"Character Count\"] = df['Review Text'].apply(len)",
"Missing Values: 2966\nDataframe Dimension: 22628 Rows, 9 Columns\n"
],
[
"#describing al statistical values\ndf.describe()\n",
"_____no_output_____"
]
],
[
[
"# Description of the data",
"_____no_output_____"
]
],
[
[
"#Create bin to store ages\nage_bin= np.arange(18, 100, 5)\n#Average age\nage_avg = np.average(df['Age'])\n#age standard devation\nage_std = np.std(df['Age'])\n\n#Create histogram\nplt.hist(df['Age'], bins = age_bin, alpha = 0.8, edgecolor='black', linewidth =1.5, color ='darkblue', density= 1)\n\n#Add a fit\ny = mpl.normpdf( age_bin, age_avg, age_std)\nl = plt.plot(age_bin, y, 'r--', linewidth=1)\n\n#Set x axis ticks to match bins\nplt.xticks(age_bin)\n\n#Add labels and title\nplt.xlabel(\"Age\")\nplt.ylabel(\"Age Probability Density\")\nplt.title(\"Age Distribution\")\n\n#Add average line\nplt.axvline(age_avg, color='green', linestyle = 'dashed', linewidth= 2)\n\n#Use grey background\nplt.style.use('bmh')\n\n#Display histogram\nplt.show()",
"_____no_output_____"
]
],
[
[
"From the plot above, the histogram is skewed to the right, there appears to be a normal distribution of the ages. The average age is somewhere around 40. The main demographic of the\nIt is possible that some users are faking their age, in particular those aged 90+. They might be removed in cleaning the datase",
"_____no_output_____"
]
],
[
[
"#Create bin for rating\nrating_bin = np.arange(1, 6, 1)\n\n#Create histogram\nplt.hist(df['Rating'], bins = rating_bin, alpha = 0.8, edgecolor='black', linewidth =1.5, color ='darkblue', density= 1)\n\n#Add labels and title\nplt.xlabel(\"Rating\")\nplt.ylabel(\"Rating Probability Density\")\nplt.title(\"Rating Distribution\")\n\n#Set x axis ticks to match bins\nplt.xticks(rating_bin)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"The histogram is clearly skewed to the left. The majority of reviews are positive.\n",
"_____no_output_____"
]
],
[
[
"#Create wedges and corresponding labels for column in dataframe.\ndef NameCount (df_in, column):\n #Store unique entries \n names = df_in[column].unique()\n #remove nans\n names = [x for x in names if str(x) != 'nan']\n #Create array to store values\n count = np.empty(len(names))\n #Store recurrence of each value\n for i in range(len(names)):\n count[i] = df[(df[column] == names[i])].shape[0]\n return names, count",
"_____no_output_____"
],
[
"#Division\ndiv_name, div_count = NameCount(df, 'Division Name')\n#Department \ndep_name, dep_count = NameCount(df, 'Department Name')\n#Class\nclass_name, class_count = NameCount(df, 'Class Name')\nplt.pie(div_count, labels=div_name, autopct='%1.1f%%', shadow=True, radius= 1)\nplt.title(\"Division\", fontsize = 20)\nplt.show()",
"_____no_output_____"
]
],
[
[
"as we can see from PIE chart 59.1% contains Genreal Division,\n 6.3% contains Intimates divison and\n 34.6% contains General petite",
"_____no_output_____"
]
],
[
[
"plt.pie(dep_count, labels=dep_name, autopct='%1.1f%%', shadow=True, radius= 1)\nplt.title(\"Department\", fontsize = 20)\nplt.show()",
"_____no_output_____"
]
],
[
[
"AS we can see from graph (1)16.2% Bottoms, (2.)27.2%Dresses, (3.)44.4% Tops, (4.)7.3%Intimate, (5.)0.5% Trend, (6.)4.4% Jackets in Department Section",
"_____no_output_____"
],
[
"# Analyzing the text comment/ review\n",
"_____no_output_____"
]
],
[
[
"#Taking random text such as Revies and Title\npd.set_option('max_colwidth', 500)\ndf[[\"Title\",\"Review Text\", \"Rating\"]].sample(7)",
"_____no_output_____"
],
[
"#installing wordcloud lib if not insatlled\n#import sys\n#!{sys.executable} -m pip install wordcloud",
"_____no_output_____"
],
[
"from nltk.stem.lancaster import LancasterStemmer\nfrom nltk.stem.porter import PorterStemmer\nfrom wordcloud import WordCloud, STOPWORDS\n#ps = LancasterStemmer()\nps = PorterStemmer()\n\ntokenizer = RegexpTokenizer(r'\\w+')\nstop_words = set(stopwords.words('english'))\n\ndef preprocessing(data):\n txt = data.str.lower().str.cat(sep=' ') #1\n words = tokenizer.tokenize(txt) #2\n words = [w for w in words if not w in stop_words] #3\n #words = [ps.stem(w) for w in words] #4\n return words",
"_____no_output_____"
],
[
"import nltk\nnltk.download('vader_lexicon')",
"_____no_output_____"
],
[
"# Pre-Processing\nSIA = SentimentIntensityAnalyzer()\ndf[\"Review Text\"]= df[\"Review Text\"].astype(str)\n\n# Applying Model, Variable Creation\ndf['Polarity Score']=df[\"Review Text\"].apply(lambda x:SIA.polarity_scores(x)['compound'])\ndf['Neutral Score']=df[\"Review Text\"].apply(lambda x:SIA.polarity_scores(x)['neu'])\ndf['Negative Score']=df[\"Review Text\"].apply(lambda x:SIA.polarity_scores(x)['neg'])\ndf['Positive Score']=df[\"Review Text\"].apply(lambda x:SIA.polarity_scores(x)['pos'])\n\n# Converting 0 to 1 Decimal Score to a Categorical Variable\ndf['Sentiment']=''\ndf.loc[df['Polarity Score']>0,'Sentiment']='Positive'\ndf.loc[df['Polarity Score']==0,'Sentiment']='Neutral'\ndf.loc[df['Polarity Score']<0,'Sentiment']='Negative'",
"_____no_output_____"
],
[
"def percentstandardize_barplot(x,y,hue, data, ax=None, order= None):\n \"\"\"\n Standardize by percentage the data using pandas functions, then plot using Seaborn.\n Function arguments are and extention of Seaborns'.\n \"\"\"\n sns.barplot(x= x, y=y, hue=hue, ax=ax, order=order,\n data=(data[[x, hue]]\n .reset_index(drop=True)\n .groupby([x])[hue]\n .value_counts(normalize=True)\n .rename('Percentage').mul(100)\n .reset_index()\n .sort_values(hue)))\n plt.title(\"Percentage Frequency of {} by {}\".format(hue,x))\n plt.ylabel(\"Percentage %\")",
"_____no_output_____"
],
[
"huevar = \"Recommended IND\"\nxvar = \"Sentiment\"\nf, axes = plt.subplots(1,2,figsize=(12,5))\nsns.countplot(x=xvar, hue=huevar,data=df, ax=axes[0], order=[\"Negative\",\"Neutral\",\"Positive\"])\naxes[0].set_title(\"Occurence of {}\\nby {}\".format(xvar, huevar))\naxes[0].set_ylabel(\"Count\")\npercentstandardize_barplot(x=xvar,y=\"Percentage\", hue=huevar,data=df, ax=axes[1])\naxes[1].set_title(\"Percentage Normalized Occurence of {}\\nby {}\".format(xvar, huevar))\naxes[1].set_ylabel(\"% Percentage by {}\".format(huevar))\nplt.show()",
"_____no_output_____"
]
],
[
[
"# According to Graph:\n\nNearly 80% sentiment are positive having Recommended IND as 1.\n\nBelow 20% sentiment are positive having Recommended IND as 0.\n\nBelow 60% sentiment are neutral having Recommended IND as 1.\n\nNearly 50% sentiment are neutral having Recommended IND as 0.\n\nAbove 30% sentiment are negative having Recommended IND as 1.\n\nAbove 60% sentiment are negative having Recommended IND as 0.",
"_____no_output_____"
]
],
[
[
"f, axes = plt.subplots(2,2, figsize=[9,9])\nsns.countplot(x=\"Sentiment\", data=df, ax=axes[0,0], order=[\"Negative\",\"Neutral\",\"Positive\"])\naxes[0,0].set_xlabel(\"Sentiment\")\naxes[0,0].set_ylabel(\"Count\")\naxes[0,0].set_title(\"Overall Sentiment Occurrence\")\n\nsns.countplot(x=\"Rating\", data=df, ax=axes[0,1])\naxes[0,1].set_xlabel(\"Rating\")\naxes[0,1].set_ylabel(\"\")\naxes[0,1].set_title(\"Overall Raiting Occurrence\")\n\npercentstandardize_barplot(x=\"Rating\",y=\"Percentage\",hue=\"Sentiment\",data=df, ax=axes[1,0])\naxes[1,0].set_xlabel(\"Rating\")\naxes[1,0].set_ylabel(\"Percentage %\")\naxes[1,0].set_title(\"Standardized Percentage Raiting Frequency\\nby Sentiment\")\n\npercentstandardize_barplot(x=\"Sentiment\",y=\"Percentage\",hue=\"Rating\",data=df, ax=axes[1,1])\naxes[1,1].set_ylabel(\"Occurrence Frequency\")\naxes[1,1].set_title(\"Standardized Percentage Sentiment Frequency\\nby Raiting\")\naxes[1,1].set_xlabel(\"Sentiment\")\naxes[1,1].set_ylabel(\"\")\n\nf.suptitle(\"Distribution of Sentiment Score and Rating for Customer Reviews\", fontsize=14)\nf.tight_layout()\nf.subplots_adjust(top=0.92)\nplt.show()",
"_____no_output_____"
]
],
[
[
"# From the Graph:\n\n1)More than 20,000 are positive sentiments. || (4) 12,000+ have rating of 5. ||(7)Very few neutral sentiments has a rating of 5 \n\n2)Less than 2500 are neagtive sentiments. || (5) rarting of 4 ranges from 4,000 to 6,000.||(8)about 40% of Negative sentiments has a rarting of 1 \n\n3)very few Neutral sentiments. || (6)Nearly 100% of positive sentiments has rating 5.||(9)Nearly 60% positive sentiments tends to have 5 rating ",
"_____no_output_____"
],
[
"10)Nearly 10% of Neutral sentiments tend to have 5 rating\n\n11)About 30% of Neutral sentiments tend to have 3 rating\n\n12)Less than 15% Negative sentiments tend to have 5 rating(in this case it is highest)\n\n13)less than 30% Negative sentiments tend to have 3 rating(in this case it is highest)",
"_____no_output_____"
]
],
[
[
"# Tweakable Variables (Note to Change Order Arguement if Xvar is changed)\nxvar = \"Sentiment\"\nhuevar = \"Department Name\"\nrowvar = \"Recommended IND\"\n\n# Plot\nf, axes = plt.subplots(2,2,figsize=(10,10), sharex=False,sharey=False)\nfor i,x in enumerate(set(df[rowvar][df[rowvar].notnull()])):\n percentstandardize_barplot(x=xvar,y=\"Percentage\", hue=huevar,data=df[df[rowvar] == x],\n ax=axes[i,0], order=[\"Negative\",\"Neutral\",\"Positive\"])\n percentstandardize_barplot(x=xvar,y=\"Percentage\", hue=\"Rating\",data=df[df[rowvar] == x],\n ax=axes[i,1], order=[\"Negative\",\"Neutral\",\"Positive\"])\n\n# Plot Aesthetics\naxes[1,0].legend_.remove()\naxes[1,1].legend_.remove()\naxes[0,1].set_ylabel(\"\")\naxes[1,1].set_ylabel(\"\")\naxes[0,0].set_xlabel(\"\")\naxes[0,1].set_xlabel(\"\")\naxes[0,0].set_ylabel(\"Recommended = FALSE\\nPercentage %\")\naxes[1,0].set_ylabel(\"Recommended = TRUE\\nPercentage %\")\naxes[1,1].set_title(\"\")\n\n# Common title and ylabel\nf.text(0.0, 0.5, 'Subplot Rows\\nSliced by Recommended', va='center', rotation='vertical', fontsize=12)\nf.suptitle(\"Review Sentiment by Department Name and Raiting\\nSubplot Rows Slice Data by Recommended\", fontsize=16)\nf.tight_layout()\nf.subplots_adjust(top=0.93)\nplt.show()",
"_____no_output_____"
]
],
[
[
"# According to Graph:\n\n1)Positive Sentiments:more than 40% recommendations are for tops And about 30% for Dresses\n\n2)Negative Sentiments:more than 40% recommendations are for tops And less than 30% for Dresses\n\n3)Neutral Sentiments:more than 40% recommendations are for tops And less than 30% for Dresses",
"_____no_output_____"
],
[
"4)Positive Sentiments:more than 40% recommnedation has a rating of 3\n\n5)Negative Sentiments:about 35% recommnedation has a rating of 3\n\n6)Neutral Sentiments:about 35% recommnedation has a rating of 3 ",
"_____no_output_____"
]
],
[
[
"# Sentiment Positivity Score by Positive Feedback Count\nax = sns.jointplot(x= df[\"Positive Feedback Count\"], y=df[\"Positive Score\"], kind='reg', color='r')\nplt.show()",
"_____no_output_____"
],
[
"#import sys\n#!{sys.executable} -m pip install plotly",
"_____no_output_____"
],
[
"cv = df['Class Name'].value_counts()\ndf1=df['Rating'].value_counts().to_frame()\navgdf1 = df.groupby('Class Name').agg({'Rating': np.average})\n\ntrace = go.Scatter3d( x = avgdf1.index,\n y = avgdf1['Rating'],\n z = cv[avgdf1.index],\n mode = 'markers',\n marker = dict(size=10,color=avgdf1['Rating']),\n hoverinfo =\"text\",\n text=\"Class: \"+avgdf1.index+\" \\ Average Rating: \"+avgdf1['Rating'].map(' {:,.2f}'.format).apply(str)+\" \\ Number of Reviewers: \"+cv[avgdf1.index].apply(str)\n )\n\ndata = [trace]\nlayout = go.Layout(title=\"Average Rating & Class & Number of Reviewers\",\n scene = dict(\n xaxis = dict(title='Class'),\n yaxis = dict(title='Average Rating'),\n zaxis = dict(title='Number of Sales'),),\n margin = dict(l=30, r=30, b=30, t=30))\nfig = go.Figure(data=data, layout=layout)\npy.iplot(fig)\nplt.savefig('3D_Scatter.png')",
"_____no_output_____"
]
],
[
[
"# According to this 3D Graph:\n\n1.class Dresses has an avg rating of 4.14 and reviewed by 6000+ people.\n\n2.class Knits has an avg rating of 4.15 and reviewed by 4000+ people.\n\n3.class Blouses has an avg rating of 4.14 and reviewed by 2983 people.\n\n4.class Jeans has an avg rating of 4.35 and reviewed by 1104 people.\n\n5.class Trends has an avg rating of 3.84 and reviewed by 118 people.\n\n6.class pants has an avg rating of 4.26 and reviewed by 1300+ people.\n\nETC....",
"_____no_output_____"
],
[
"# Converting the ratings into 2 classes\nClass: Bad when Rating <=3\nClass: Good otherwise",
"_____no_output_____"
]
],
[
[
"df[\"Class\"] = \"Bad\"\ndf.loc[df.Rating >= 3,[\"Class\"]] = \"Good\"",
"_____no_output_____"
],
[
"for i in df.columns[df.isna().any()].tolist():\n print(i,'has',df[df[i].isna()==True].shape[0],'Null Values')",
"_____no_output_____"
],
[
"df['Rating'].unique()",
"_____no_output_____"
],
[
"def ret(rating):\n if rating>3:\n return 'Good'\n else:\n return 'Bad'",
"_____no_output_____"
],
[
"df = pd.read_csv(\"Womens_Clothing_E_Commerce_Reviews.csv\")\ndf['Review Text']=df['Review Text'].astype(str)\ndf['Review Length']=df['Review Text'].apply(len)",
"_____no_output_____"
],
[
"import nltk\nnltk.download('punkt')",
"_____no_output_____"
],
[
"top_N = 100\n#convert list of list into text\n#a=''.join(str(r) for v in df_usa['title'] for r in v)\n\na = df['Review Text'].str.lower().str.cat(sep=' ')\n\n# removes punctuation,numbers and returns list of words\nb = re.sub('[^A-Za-z]+', ' ', a)\n\n#remove all the stopwords from the text\nstop_words = list(get_stop_words('en')) \nnltk_words = list(stopwords.words('english')) \nstop_words.extend(nltk_words)\n\nword_tokens = word_tokenize(b)\nfiltered_sentence = [w for w in word_tokens if not w in stop_words]\nfiltered_sentence = []\nfor w in word_tokens:\n if w not in stop_words:\n filtered_sentence.append(w)\n\n# Remove characters which have length less than 2 \nwithout_single_chr = [word for word in filtered_sentence if len(word) > 2]\n\n# Remove numbers\ncleaned_data_title = [word for word in without_single_chr if not word.isnumeric()] \n\n# Calculate frequency distribution\nword_dist = nltk.FreqDist(cleaned_data_title)\nrslt = pd.DataFrame(word_dist.most_common(top_N),\n columns=['Word', 'Frequency'])",
"_____no_output_____"
]
],
[
[
"# Data Analysis",
"_____no_output_____"
]
],
[
[
"df[\"Class\"] = \"Bad\"\ndf.loc[df.Rating > 3,[\"Class\"]] = \"Good\"",
"_____no_output_____"
],
[
"df=df.dropna(axis=0,how='any')\nrating_class = df[(df['Rating'] >3) | (df['Rating']<=3)]\nX_review=rating_class['Review Text']\ny=rating_class['Class']",
"_____no_output_____"
],
[
"import string\ndef text_process(review):\n nopunc=[word for word in review if word not in string.punctuation]\n nopunc=''.join(nopunc)\n return [word for word in nopunc.split() if word.lower() not in stopwords.words('english')]",
"_____no_output_____"
],
[
"from sklearn.feature_extraction.text import CountVectorizer\nbow_transformer=CountVectorizer(analyzer=text_process).fit(X_review)",
"_____no_output_____"
],
[
"print(len(bow_transformer.vocabulary_))",
"_____no_output_____"
],
[
"X_review = bow_transformer.transform(X_review)",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_review, y, test_size=0.3, random_state=101)",
"_____no_output_____"
]
],
[
[
"#### Data Training",
"_____no_output_____"
]
],
[
[
"from sklearn.naive_bayes import MultinomialNB\nnb = MultinomialNB()\nnb.fit(X_train, y_train)",
"_____no_output_____"
],
[
"predict=nb.predict(X_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import confusion_matrix, classification_report\nprint(confusion_matrix(y_test, predict))\nprint('\\n')\nprint(classification_report(y_test, predict))",
"_____no_output_____"
]
],
[
[
"## Model Testing",
"_____no_output_____"
],
[
"A Good review example",
"_____no_output_____"
]
],
[
[
"rating_positive=df['Review Text'][3]\nrating_positive",
"_____no_output_____"
],
[
"#prediction\nrating_positive_transformed = bow_transformer.transform([rating_positive])\nnb.predict(rating_positive_transformed)[0]",
"_____no_output_____"
],
[
"#actual\ndf['Class'][3]",
"_____no_output_____"
]
],
[
[
"A Bad review example",
"_____no_output_____"
]
],
[
[
"rating_negative=df['Review Text'][61]\nrating_negative",
"_____no_output_____"
],
[
"#prediction\nrating_negative_transformed = bow_transformer.transform([rating_negative])\nnb.predict(rating_negative_transformed)[0]",
"_____no_output_____"
],
[
"#actual\ndf['Class'][61]",
"_____no_output_____"
]
],
[
[
"Randaom Data",
"_____no_output_____"
]
],
[
[
"rating_random=df['Review Text'][43]\nrating_random",
"_____no_output_____"
],
[
"#prediction\nrating_random_transformed = bow_transformer.transform([rating_negative])\nnb.predict(rating_random_transformed)[0]",
"_____no_output_____"
],
[
"#Actual\ndf['Class'][43]",
"_____no_output_____"
]
],
[
[
"# Algorithm used and why:\n \nWe have used naive bayes classifier as it is a classification technique based on Bayes’ Theorem with an assumption of independence among predictors. Naive Bayes model is easy to build and particularly useful for very large datasets. Along with simplicity, Naive Bayes is known to outperform even the most-sophisticated classification methods. It proves to be quite robust to irrelevant features, which it ignores. It learns and predicts very fast and it does not require lots of storage. So, why is it then called naive? The naive was added to the account for one assumption that is required for Bayes to work optimally: all features must be independent of each other. In reality, this is usually not the case; however, it still returns very good accuracy in practice even when the independent assumption does not hold.",
"_____no_output_____"
],
[
"Text classification/ Spam Filtering/ Sentiment Analysis: Naive Bayes classifiers are mostly used in text classification (due to their better results in multi-class problems and independence rule) have a higher success rate as compared to other algorithms. As a result, it is widely used in Spam filtering (identify spam e-mail) and Sentiment Analysis (in social media analysis, to identify positive and negative customer sentiments)",
"_____no_output_____"
],
[
"We have also used multivariate method for data analysis\nMultivariate analysis provides a more accurate view of the behavior between variables that are highly correlated, and can detect potential problems in a product or process.",
"_____no_output_____"
],
[
"# Algorithm Advantages:\n\nIt is easy to apply and predicts the class of test data set fast. It also performs well in multi-class prediction\nWhen the assumption of independence holds, a Naive Bayes classifier performs better compared to the other models like logistic regression as you need less training data.\nIt performs well in the case of categorical input variables compared to a numerical variable(s). For the numerical variable, a normal distribution is assumed (bell curve, which is a strong assumption).",
"_____no_output_____"
],
[
"# We have achieved the desired model with 88% accuracy which predicts the Rating class.\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"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
ece7ad53bed7573984c92e00f7fbc649fca1770d | 57,533 | ipynb | Jupyter Notebook | 02 - Pandas Introduction/Part 02 - More Pandas.ipynb | JIsaiah/EML-Workshop-042020 | 5dbe573c2ec6d0e419cea49f1818458f890550da | [
"MIT"
] | null | null | null | 02 - Pandas Introduction/Part 02 - More Pandas.ipynb | JIsaiah/EML-Workshop-042020 | 5dbe573c2ec6d0e419cea49f1818458f890550da | [
"MIT"
] | null | null | null | 02 - Pandas Introduction/Part 02 - More Pandas.ipynb | JIsaiah/EML-Workshop-042020 | 5dbe573c2ec6d0e419cea49f1818458f890550da | [
"MIT"
] | null | null | null | 32.54129 | 93 | 0.279144 | [
[
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"# Read data",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"./data/clean_apps.csv\", index_col=\"x\")\ndf.head()",
"_____no_output_____"
]
],
[
[
"# Filter",
"_____no_output_____"
]
],
[
[
"df[df.mfr == \"K\"]",
"_____no_output_____"
]
],
[
[
"# Map, Apply, Transform",
"_____no_output_____"
]
],
[
[
"df.vitamins.unique()",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"df.type.value_counts()",
"_____no_output_____"
],
[
"def remove_symbol(x):\n return x.replace(\"FDA_\", \"\")\n\ndf.vitamins = df.vitamins.apply(remove_symbol)\ndf.head()",
"_____no_output_____"
],
[
"def normalisation(x):\n return x - x.mean()\n\ndf.rating = df.rating.transform(normalisation)\ndf.head()",
"_____no_output_____"
],
[
"mapper = {\n \"C\": 0,\n \"H\": 1\n}\n\ndf.type = df.type.map(mapper)\ndf.head()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
ece7adf98a06052d06b259e5cd3c3f3b095a78ab | 185,501 | ipynb | Jupyter Notebook | jupyter/SparkOcrStoreResultsToPdfWithTextLayoutWithFallback.ipynb | sandeepnair2812/JohnSnowLabs-spark-ocr-workshop | efa13af5b451bead895cca8cd7fd87d828b07392 | [
"OML",
"Linux-OpenIB"
] | null | null | null | jupyter/SparkOcrStoreResultsToPdfWithTextLayoutWithFallback.ipynb | sandeepnair2812/JohnSnowLabs-spark-ocr-workshop | efa13af5b451bead895cca8cd7fd87d828b07392 | [
"OML",
"Linux-OpenIB"
] | null | null | null | jupyter/SparkOcrStoreResultsToPdfWithTextLayoutWithFallback.ipynb | sandeepnair2812/JohnSnowLabs-spark-ocr-workshop | efa13af5b451bead895cca8cd7fd87d828b07392 | [
"OML",
"Linux-OpenIB"
] | null | null | null | 366.602767 | 30,824 | 0.94724 | [
[
[
"# Example of usage Spark OCR for recognize text from Image and selectable PDF's and store results to PDF with text layout",
"_____no_output_____"
],
[
"## Install spark-ocr python packge\nNeed specify path to `spark-ocr-assembly-[version].jar` or `secret`",
"_____no_output_____"
]
],
[
[
"secret = \"\"\nlicense = \"\"\nversion = secret.split(\"-\")[0]\nspark_ocr_jar_path = \"../../target/scala-2.11\"",
"_____no_output_____"
],
[
"%%bash\nif python -c 'import google.colab' &> /dev/null; then\n echo \"Run on Google Colab!\"\n echo \"Install Open JDK\"\n apt-get install -y openjdk-8-jdk-headless -qq > /dev/null\n java -version\nfi",
"_____no_output_____"
],
[
"import sys\nimport os\n\nif 'google.colab' in sys.modules:\n os.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\n os.environ[\"PATH\"] = os.environ[\"JAVA_HOME\"] + \"/bin:\" + os.environ[\"PATH\"]",
"_____no_output_____"
],
[
"# install from PYPI using secret\n%pip install spark-ocr==$version --user --extra-index-url=https://pypi.johnsnowlabs.com/$secret --upgrade",
"_____no_output_____"
],
[
"# or install from local path\n%pip install --user ../../python/dist/spark-ocr-1.2.0.tar.gz",
"Processing /Users/nmelnik/IdeaProjects/spark-ocr/python/dist/spark-ocr-1.2.0.tar.gz\nRequirement already satisfied: numpy==1.17.4 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from spark-ocr==1.2.0) (1.17.4)\nRequirement already satisfied: pillow==6.2.1 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from spark-ocr==1.2.0) (6.2.1)\nRequirement already satisfied: py4j==0.10.7 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from spark-ocr==1.2.0) (0.10.7)\nRequirement already satisfied: pyspark==2.4.4 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from spark-ocr==1.2.0) (2.4.4)\nRequirement already satisfied: python-levenshtein==0.12.0 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from spark-ocr==1.2.0) (0.12.0)\nRequirement already satisfied: scikit-image==0.16.2 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from spark-ocr==1.2.0) (0.16.2)\nRequirement already satisfied: spark-nlp==2.4.2 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from spark-ocr==1.2.0) (2.4.2)\nRequirement already satisfied: setuptools in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from python-levenshtein==0.12.0->spark-ocr==1.2.0) (46.0.0)\nRequirement already satisfied: imageio>=2.3.0 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from scikit-image==0.16.2->spark-ocr==1.2.0) (2.8.0)\nRequirement already satisfied: PyWavelets>=0.4.0 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from scikit-image==0.16.2->spark-ocr==1.2.0) (1.1.1)\nRequirement already satisfied: scipy>=0.19.0 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from scikit-image==0.16.2->spark-ocr==1.2.0) (1.4.1)\nRequirement already satisfied: networkx>=2.0 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from scikit-image==0.16.2->spark-ocr==1.2.0) (2.4)\nRequirement already satisfied: matplotlib!=3.0.0,>=2.0.0 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from scikit-image==0.16.2->spark-ocr==1.2.0) (3.2.0)\nRequirement already satisfied: decorator>=4.3.0 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from networkx>=2.0->scikit-image==0.16.2->spark-ocr==1.2.0) (4.4.2)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2->spark-ocr==1.2.0) (2.4.6)\nRequirement already satisfied: python-dateutil>=2.1 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2->spark-ocr==1.2.0) (2.8.1)\nRequirement already satisfied: cycler>=0.10 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2->spark-ocr==1.2.0) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2->spark-ocr==1.2.0) (1.1.0)\nRequirement already satisfied: six>=1.5 in /Users/nmelnik/Library/Python/3.7/lib/python/site-packages (from python-dateutil>=2.1->matplotlib!=3.0.0,>=2.0.0->scikit-image==0.16.2->spark-ocr==1.2.0) (1.14.0)\nBuilding wheels for collected packages: spark-ocr\n Building wheel for spark-ocr (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for spark-ocr: filename=spark_ocr-1.2.0-py3-none-any.whl size=5012116 sha256=b79c63e97b4235bbb3c7e061d6a42840bb1886c0351fa6e52262964bfe8333f3\n Stored in directory: /Users/nmelnik/Library/Caches/pip/wheels/8f/18/a8/6a746cb146272537dd3c50b17baa2711dab0a33acc5ed77549\nSuccessfully built spark-ocr\nInstalling collected packages: spark-ocr\n Attempting uninstall: spark-ocr\n Found existing installation: spark-ocr 1.1.2\n Uninstalling spark-ocr-1.1.2:\n Successfully uninstalled spark-ocr-1.1.2\nSuccessfully installed spark-ocr-1.2.0\nNote: you may need to restart the kernel to use updated packages.\n"
]
],
[
[
"## Initialization of spark session",
"_____no_output_____"
]
],
[
[
"from pyspark.sql import SparkSession\nfrom sparkocr import start\n\nif license:\n os.environ['JSL_OCR_LICENSE'] = license\n\nspark = start(secret=secret, jar_path=spark_ocr_jar_path)\nspark",
"SparkConf Configured, Starting to listen on port: 56355\nJAR PATH:/usr/local/lib/python3.7/site-packages/sparkmonitor/listener.jar\n"
]
],
[
[
"## Import OCR transformers",
"_____no_output_____"
]
],
[
[
"from sparkocr.transformers import *\nfrom sparkocr.enums import *\nfrom pyspark.ml import PipelineModel\nfrom sparkocr.utils import display_image",
"_____no_output_____"
]
],
[
[
"## Define OCR transformers and pipeline",
"_____no_output_____"
]
],
[
[
"def pipeline():\n \n # If text PDF extract text\n pdf_to_text = PdfToText() \\\n .setInputCol(\"content\") \\\n .setOutputCol(\"text\") \\\n .setSplitPage(False)\n \n # If image pdf, extract image\n pdf_to_image = PdfToImage() \\\n .setInputCol(\"content\") \\\n .setOutputCol(\"image\") \\\n .setKeepInput(True)\n \n # Run OCR\n ocr = ImageToText() \\\n .setInputCol(\"image\") \\\n .setOutputCol(\"text\") \\\n .setConfidenceThreshold(60) \\\n .setIgnoreResolution(False) \\\n .setPageSegMode(PageSegmentationMode.SPARSE_TEXT)\n \n # Render results to PDF\n textToPdf = TextToPdf() \\\n .setInputCol(\"positions\") \\\n .setInputImage(\"image\") \\\n .setOutputCol(\"pdf\")\n\n pipeline = PipelineModel(stages=[\n pdf_to_text,\n pdf_to_image,\n ocr,\n textToPdf\n ])\n \n return pipeline",
"_____no_output_____"
]
],
[
[
"## Read PDF document as binary file",
"_____no_output_____"
]
],
[
[
"import pkg_resources\npdf_example = pkg_resources.resource_filename('sparkocr', 'resources/ocr/pdfs/multiplepages/*')\npdf_example_df = spark.read.format(\"binaryFile\").load(pdf_example).cache()",
"_____no_output_____"
]
],
[
[
"## Run OCR pipelines",
"_____no_output_____"
]
],
[
[
"result = pipeline().transform(pdf_example_df).cache()",
"_____no_output_____"
]
],
[
[
"## Store results to pdf file",
"_____no_output_____"
]
],
[
[
"pdf = result.select(\"pdf\").head().pdf\npdfFile = open(\"result.pdf\", \"wb\")\npdfFile.write(pdf)\npdfFile.close()",
"_____no_output_____"
]
],
[
[
"## Convert pdf to image and display ",
"_____no_output_____"
]
],
[
[
"image_df = PdfToImage() \\\n .setInputCol(\"pdf\") \\\n .setOutputCol(\"image\") \\\n .transform(result.select(\"pdf\", \"path\"))\nfor r in image_df.collect():\n display_image(r.image)",
"Image:\n origin: file:/Users/nmelnik/Library/Python/3.7/lib/python/site-packages/sparkocr/resources/ocr/pdfs/multiplepages/text_3_pages.pdf \n width: 2480\n height: 3507\n mode: 10\n"
],
[
"result.unpersist()",
"_____no_output_____"
],
[
"%%bash\nrm -r -f result.pdf",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
ece7b16298e028e48b1c2264c219833142b54e78 | 16,518 | ipynb | Jupyter Notebook | docs/plugins/tasks/version_control/gitlab.ipynb | jrokeach/nornir | 6659e29a9f9e4ecb9a055c834007b08b4665fce5 | [
"Apache-2.0"
] | 1 | 2020-07-19T19:54:54.000Z | 2020-07-19T19:54:54.000Z | docs/plugins/tasks/version_control/gitlab.ipynb | emilgaripov/nornir | f4a4925ded87c09fa25f4f0faf911f93a4cb3cdd | [
"Apache-2.0"
] | null | null | null | docs/plugins/tasks/version_control/gitlab.ipynb | emilgaripov/nornir | f4a4925ded87c09fa25f4f0faf911f93a4cb3cdd | [
"Apache-2.0"
] | 1 | 2020-05-26T13:36:18.000Z | 2020-05-26T13:36:18.000Z | 23.973875 | 266 | 0.472999 | [
[
[
"# Gitlab",
"_____no_output_____"
]
],
[
[
"from nornir.plugins.tasks.version_control import gitlab\nprint(gitlab.__doc__)",
"\n Exposes some of the Gitlab API functionality for operations on files\n in a Gitlab repository.\n\n Example:\n\n nornir.run(files.gitlab,\n action=\"create\",\n url=\"https://gitlab.localhost.com\",\n token=\"ABCD1234\",\n repository=\"test\",\n filename=\"config\",\n ref=\"master\")\n\n Arguments:\n dry_run: Whether to apply changes or not\n url: Gitlab instance URL\n token: Personal access token\n repository: source/destination repository\n filename: source/destination file name\n content: content to write\n action: ``create``, ``update``, ``get``\n branch: destination branch\n destination: local destination filename (only used in get action)\n ref: branch, commit hash or tag (only used in get action)\n commit_message: commit message\n\n Returns:\n Result object with the following attributes set:\n * changed (``bool``):\n * diff (``str``): unified diff\n\n \n"
]
],
[
[
"## Example 1 : create a file in a git repository on a gitlab server\n\nIn this example we will create a new file in a git repository on a gitlab server.\n\nThe contents that we will write to the file is a arbitrary string, in a real world scenario this could be the running configuration of a device that we fetched using napalm or through another method.\n\nFirst let's import the necessary methods & tasks, then we will create a variable called `content` which is an arbitrary string.",
"_____no_output_____"
]
],
[
[
"from nornir import InitNornir\nfrom nornir.plugins.tasks.version_control import gitlab\nfrom nornir.plugins.tasks.commands import remote_command\nfrom nornir.plugins.functions.text import print_result\n\ninventory = {\n \"plugin\": \"nornir.plugins.inventory.simple.SimpleInventory\",\n \"options\": {\n \"host_file\": \"gitlab_data/inventory/hosts.yaml\"\n }\n}\n\nn = InitNornir(inventory=inventory)\n\ncontent = \"\"\"127.0.0.1\\t\\tlocalhost\n255.255.255.255\\tbroadcasthost\n::1\\t\\tlocalhost\n\"\"\"",
"_____no_output_____"
]
],
[
[
"And create a new file called `hosts` in the repository `test` on the `master` branch.",
"_____no_output_____"
]
],
[
[
"import requests_mock\nfrom functools import wraps\n\ndef wrap_gitlab(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n with requests_mock.Mocker() as m:\n if kwargs.get(\"ref\", None):\n kwargs[\"branch\"] = kwargs[\"ref\"]\n m.get(url=f\"{kwargs['url']}/api/v4/projects?search={kwargs['repository']}\", status_code=200, json=[{\"name\":\"test\",\"id\":1}])\n m.post(url=f\"{kwargs['url']}/api/v4/projects/1/repository/files/{kwargs['filename']}\", status_code=201)\n m.get(url=f\"{kwargs['url']}/api/v4/projects/1/repository/files/{kwargs['filename']}?ref={kwargs['branch']}\",status_code=200, json={\"content\":\"MTI3LjAuMC4xCQlsb2NhbGhvc3QKMjU1LjI1NS4yNTUuMjU1CWJyb2FkY2FzdGhvc3QKOjoxCQls\\nb2NhbGhvc3QK\\n\"})\n m.put(url=f\"{kwargs['url']}/api/v4/projects/1/repository/files/{kwargs['filename']}\", status_code=200)\n return f(*args, **kwargs)\n return wrapper\n\ngitlab = wrap_gitlab(gitlab)",
"_____no_output_____"
],
[
"result = n.run(\n gitlab,\n action=\"create\",\n url=\"http://localhost:8080\",\n token = \"SuperSecretToken\",\n repository=\"test\",\n branch=\"master\",\n filename=\"hosts\",\n #content=results[\"dev5.no_group\"][0]\n content=content,\n commit_message=\"Nornir is AWESOME!\"\n)",
"_____no_output_____"
]
],
[
[
"The result of the task shows us a diff of the created `hosts` file and the content we provided.",
"_____no_output_____"
]
],
[
[
"print_result(result)",
"\u001b[1m\u001b[36mgitlab**************************************************************************"
]
],
[
[
"## Example 2 : update an existing file in a git repository on a gitlab server",
"_____no_output_____"
],
[
"In this example we will update the contents of the hosts file that we created in the previous step. The new contents could come again from a remote host or device, but in this case we will use an arbitrary value for the new contents of the file.",
"_____no_output_____"
]
],
[
[
"result = n.run(\n gitlab,\n action=\"update\",\n url=\"http://localhost:8080\",\n token=\"SuperSecretToken\",\n repository=\"test\",\n branch=\"master\",\n filename=\"hosts\",\n content=f\"{content}8.8.8.8\\t\\tgoogledns\",\n commit_message=\"Added new line to hosts file\"\n)",
"_____no_output_____"
]
],
[
[
"The result of the task should show us a diff of the changes that we made.",
"_____no_output_____"
]
],
[
[
"print_result(result)",
"\u001b[1m\u001b[36mgitlab**************************************************************************"
]
],
[
[
"## Example 3: get a file from a gitlab repository\n",
"_____no_output_____"
],
[
"In this example we will get/download a file from a repository in gitlab. The contents of this file could be a staged configuration of a device or a service on a device. This configuration could then be pushed to the device.\n\nIn our example we will download the file `hosts` from the `master` branch and save it as `/tmp/hosts`.\nThe `ref` parameter can also be a commit hash or tag.",
"_____no_output_____"
]
],
[
[
"result = n.run(\n gitlab,\n action=\"get\",\n url=\"http://localhost:8080\",\n token=\"SuperSecretToken\",\n repository=\"test\",\n ref=\"master\",\n filename=\"hosts\",\n destination=\"/tmp/hosts\"\n)\n",
"_____no_output_____"
]
],
[
[
"The result should show us a new file `/tmp/hosts` being created on the local system.",
"_____no_output_____"
]
],
[
[
"print_result(result)",
"\u001b[1m\u001b[36mgitlab**************************************************************************"
]
]
] | [
"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"
],
[
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.