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
list
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
list
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
list
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
list
cell_types
list
cell_type_groups
list
cb2423b88c36c776935e5ec4c2bfd442257e27f6
327,405
ipynb
Jupyter Notebook
embedded/nb_gd_vs_ngd.ipynb
informationgeometryML/informationgeometryML.github.io
dc6d1b959925a033e55d4d3b975b5882fcff19f6
[ "MIT", "BSD-3-Clause" ]
null
null
null
embedded/nb_gd_vs_ngd.ipynb
informationgeometryML/informationgeometryML.github.io
dc6d1b959925a033e55d4d3b975b5882fcff19f6
[ "MIT", "BSD-3-Clause" ]
1
2021-12-01T07:10:20.000Z
2021-12-01T07:10:21.000Z
embedded/nb_gd_vs_ngd.ipynb
informationgeometryML/informationgeometryML.github.io
dc6d1b959925a033e55d4d3b975b5882fcff19f6
[ "MIT", "BSD-3-Clause" ]
null
null
null
1,488.204545
320,588
0.960312
[ [ [ "%matplotlib inline\nfrom jax.config import config; config.update(\"jax_enable_x64\", True)\nimport jax.numpy as jnp\nfrom jax import grad, jit, value_and_grad\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import ticker, colors", "_____no_output_____" ], [ "@jit\ndef loss_lik(mu,v):\n b1 = 0.5; b2 = 0.01;\n a1 = 2.0; a2 = 5.0;\n ls = b1*(mu**2+v-2.0*a1*mu+a1**2)+b2*((mu**3+3.0*mu*v)-3.0*a2*(mu**2+v)+3.0*(a2**2)*mu-a2**3)+4.0/v\n return ls\n\n@jit\ndef loss_pre(params):\n (mu,s) = params\n return loss_lik(mu,1.0/s) + jnp.log(s)/2\n\nloss_f_pre = jit(value_and_grad(loss_pre))", "_____no_output_____" ], [ "def gd(init_params, loss_fun, step_size, num_iters):\n J_history = np.zeros(num_iters+1)\n mu_hist, s_hist = np.zeros(num_iters+1), np.zeros(num_iters+1) #For plotting \n \n cur_params = init_params\n for i in range(num_iters):\n \n (val,g) = loss_fun(cur_params) #Euclidean gradient\n mu_hist[i] = cur_params[0]\n s_hist[i] = cur_params[1] \n J_history[i] = val\n \n cur_params = cur_params - step_size* g #GD\n\n (val,_) = loss_fun(cur_params)\n J_history[num_iters] = val\n mu_hist[num_iters] = cur_params[0]\n s_hist[num_iters] = cur_params[1] \n\n return J_history, mu_hist, s_hist", "_____no_output_____" ], [ "def ngd_pre(init_params, loss_fun, step_size, num_iters):\n J_history = np.zeros(num_iters+1)\n mu_hist, s_hist = np.zeros(num_iters+1), np.zeros(num_iters+1) #For plotting \n \n cur_params = init_params\n for i in range(num_iters):\n (mu,s)=cur_params\n (val,(g_mu,g_s)) = loss_fun(cur_params)\n ng = jnp.array( [g_mu/s, 2.0*(s**2)*g_s ] ) #Natural gradient\n\n mu_hist[i] = cur_params[0]\n s_hist[i] = cur_params[1] \n J_history[i] = val\n \n cur_params = cur_params - step_size* ng #NGD\n \n (val,_) = loss_fun(cur_params)\n J_history[num_iters] = val\n mu_hist[num_iters] = cur_params[0]\n s_hist[num_iters] = cur_params[1] \n\n return J_history, mu_hist, s_hist", "_____no_output_____" ], [ "#Setup of meshgrid of theta values\nmu_list, s_list = np.meshgrid(np.linspace(-10,10,200),np.logspace(-1,0.2,800))\n\n#Computing the cost function for each theta combination\nzs = np.array( [loss_pre( jnp.array([mu,s]) ) \n for mu,s in zip(np.ravel(mu_list), np.ravel(s_list)) ] )\nZ = zs.reshape(mu_list.shape)\nmu_0 = -8.0\ns_0 = 1.0\nmax_num_iters = 200", "_____no_output_____" ], [ "init_params = jnp.array([mu_0,s_0])\ngd_pre_history, mu_gd_pre_hist, s_gd_pre_hist = gd(init_params, loss_f_pre, step_size = 1e-2, \n num_iters=max_num_iters)\nanglesx_gd_pre = np.array(mu_gd_pre_hist)[1:] - np.array(mu_gd_pre_hist)[:-1]\nanglesy_gd_pre = np.array(s_gd_pre_hist)[1:] - np.array(s_gd_pre_hist)[:-1]", "_____no_output_____" ], [ "init_params = jnp.array([mu_0,s_0])\nngd_pre_history, mu_ngd_pre_hist, s_ngd_pre_hist = ngd_pre(init_params, loss_f_pre, step_size = 1e-2, \n num_iters=max_num_iters)\nanglesx_ngd_pre = np.array(mu_ngd_pre_hist)[1:] - np.array(mu_ngd_pre_hist)[:-1]\nanglesy_ngd_pre = np.array(s_ngd_pre_hist)[1:] - np.array(s_ngd_pre_hist)[:-1]", "_____no_output_____" ], [ "fig = plt.figure(figsize = (16,8))\nax = fig.add_subplot(1, 2, 1)\n\nax.contour(mu_list, s_list, Z, 50, cmap = 'jet')\n\nax.quiver(mu_gd_pre_hist[:-1], s_gd_pre_hist[:-1], anglesx_gd_pre, anglesy_gd_pre, \n label='GD $(\\mu,s)$', scale_units = 'xy', angles = 'xy', scale = 1, color = 'g', alpha = .9)\n\nax.quiver(mu_ngd_pre_hist[:-1], s_ngd_pre_hist[:-1], anglesx_ngd_pre, anglesy_ngd_pre, \n label='NGD $(\\mu,s)$', scale_units = 'xy', angles = 'xy', scale = 1, color = 'r', alpha = .9)\n\nax.set_xlabel('$\\mu$', fontsize=18)\nax.set_ylabel('$s$', fontsize=18)\nax.legend(loc='upper right', fontsize=18)\n\nax = fig.add_subplot(1, 2, 2)\nax.plot(np.array(list(range(0, max_num_iters+1))),gd_pre_history,label='GD $(\\mu,s)$',color='g')\nax.plot(np.array(list(range(0, max_num_iters+1))),ngd_pre_history,label='NGD $(\\mu,s)$',color='r')\nax.legend(loc='upper right', fontsize=18)\nax.set_xlabel('# of iters', fontsize=18)\nax.set_ylabel('loss', fontsize=18)\n\n\n\nplt.tight_layout()\nplt.savefig('gd_vs_ngd.png')\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb24256937b03159e142bd15dee1c05256e210f8
12,906
ipynb
Jupyter Notebook
weeks/05-deep-learning.ipynb
jmduarte/capstone-particle-physics-domain
5b9f68865fbd32b87e5a29b911aba204ec1b4e12
[ "Apache-2.0" ]
4
2021-03-04T11:26:52.000Z
2021-10-08T03:26:26.000Z
weeks/05-deep-learning.ipynb
jmduarte/capstone-particle-physics-domain
5b9f68865fbd32b87e5a29b911aba204ec1b4e12
[ "Apache-2.0" ]
2
2021-09-09T21:48:38.000Z
2021-09-10T03:27:00.000Z
weeks/05-deep-learning.ipynb
jmduarte/capstone-particle-physics-domain
5b9f68865fbd32b87e5a29b911aba204ec1b4e12
[ "Apache-2.0" ]
12
2020-09-15T12:23:21.000Z
2022-03-31T03:42:55.000Z
36.151261
288
0.586549
[ [ [ "Week 5 Notebook: Building a Deep Learning Model\n===============================================================\n\nNow, we'll look at a deep learning model based on low-level track features.", "_____no_output_____" ] ], [ [ "import tensorflow.keras as keras\nimport numpy as np\nfrom sklearn.metrics import roc_curve, auc\nimport matplotlib.pyplot as plt\nimport uproot\nimport tensorflow", "_____no_output_____" ], [ "import yaml\n\nwith open('definitions.yml') as file:\n # The FullLoader parameter handles the conversion from YAML\n # scalar values to Python the dictionary format\n definitions = yaml.load(file, Loader=yaml.FullLoader)\n \nfeatures = definitions['features']\nspectators = definitions['spectators']\nlabels = definitions['labels']\n\nnfeatures = definitions['nfeatures']\nnspectators = definitions['nspectators']\nnlabels = definitions['nlabels']\nntracks = definitions['ntracks']", "_____no_output_____" ] ], [ [ "## Data Generators\n\nA quick aside on data generators. As training on large datasets is a key component of many deep learning approaches (and especially in high energy physics), and these datasets no longer fit in memory, it is imporatant to write a data generator which can automatically fetch data.\n\nHere we modify one from: https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly", "_____no_output_____" ] ], [ [ "from DataGenerator import DataGenerator\nhelp(DataGenerator)", "_____no_output_____" ], [ "# load training and validation generators \ntrain_files = ['root://eospublic.cern.ch//eos/opendata/cms/datascience/HiggsToBBNtupleProducerTool/HiggsToBBNTuple_HiggsToBB_QCD_RunII_13TeV_MC/train/ntuple_merged_10.root']\nval_files = ['root://eospublic.cern.ch//eos/opendata/cms/datascience/HiggsToBBNtupleProducerTool/HiggsToBBNTuple_HiggsToBB_QCD_RunII_13TeV_MC/train/ntuple_merged_11.root']\n\n\ntrain_generator = DataGenerator(train_files, features, labels, spectators, batch_size=1024, n_dim=ntracks, \n remove_mass_pt_window=False, \n remove_unlabeled=True, max_entry=8000)\n\nval_generator = DataGenerator(val_files, features, labels, spectators, batch_size=1024, n_dim=ntracks, \n remove_mass_pt_window=False, \n remove_unlabeled=True, max_entry=2000)", "_____no_output_____" ] ], [ [ "## Test Data Generator\nNote that the track array has a different \"shape.\" There are also less than the requested `batch_size=1024` because we remove unlabeled samples.", "_____no_output_____" ] ], [ [ "X, y = train_generator[1]\nprint(X.shape)\nprint(y.shape)", "_____no_output_____" ] ], [ [ "Note this generator can be optimized further (storing the data file locally, etc.). It's important to note that I/O is often a bottleneck for training big networks.", "_____no_output_____" ], [ "## Fully Connected Neural Network Classifier", "_____no_output_____" ] ], [ [ "from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Dense, BatchNormalization, Flatten\nimport tensorflow.keras.backend as K\n\n# define dense keras model\ninputs = Input(shape=(ntracks, nfeatures,), name='input') \nx = BatchNormalization(name='bn_1')(inputs)\nx = Flatten(name='flatten_1')(x)\nx = Dense(64, name='dense_1', activation='relu')(x)\nx = Dense(32, name='dense_2', activation='relu')(x)\nx = Dense(32, name='dense_3', activation='relu')(x)\noutputs = Dense(nlabels, name='output', activation='softmax')(x)\nkeras_model_dense = Model(inputs=inputs, outputs=outputs)\nkeras_model_dense.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nprint(keras_model_dense.summary())", "_____no_output_____" ], [ "# define callbacks\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=5)\nreduce_lr = ReduceLROnPlateau(patience=5, factor=0.5)\nmodel_checkpoint = ModelCheckpoint('keras_model_dense_best.h5', monitor='val_loss', save_best_only=True)\ncallbacks = [early_stopping, model_checkpoint, reduce_lr]\n\n# fit keras model\nhistory_dense = keras_model_dense.fit(train_generator,\n validation_data=val_generator,\n steps_per_epoch=len(train_generator),\n validation_steps=len(val_generator),\n max_queue_size=5,\n epochs=20,\n shuffle=False,\n callbacks=callbacks,\n verbose=0)\n# reload best weights\nkeras_model_dense.load_weights('keras_model_dense_best.h5')", "_____no_output_____" ], [ "plt.figure()\nplt.plot(history_dense.history['loss'], label='Loss')\nplt.plot(history_dense.history['val_loss'], label='Val. loss')\nplt.xlabel('Epoch')\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "## Deep Sets Classifier\n\nThis model uses the `Dense` layer of Keras, but really it's more like the Deep Sets architecture applied to jets, the so-caled Particle-flow network approach{cite:p}`Komiske:2018cqr,NIPS2017_6931`.\nWe are applying the same fully connected neural network to each track. \nThen the `GlobalAveragePooling1D` layer sums over the tracks (actually it takes the mean). ", "_____no_output_____" ] ], [ [ "from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Dense, BatchNormalization, GlobalAveragePooling1D\nimport tensorflow.keras.backend as K\n\n# define Deep Sets model with Dense Keras layer\ninputs = Input(shape=(ntracks, nfeatures,), name='input') \nx = BatchNormalization(name='bn_1')(inputs)\nx = Dense(64, name='dense_1', activation='relu')(x)\nx = Dense(32, name='dense_2', activation='relu')(x)\nx = Dense(32, name='dense_3', activation='relu')(x)\n# sum over tracks\nx = GlobalAveragePooling1D(name='pool_1')(x)\nx = Dense(100, name='dense_4', activation='relu')(x)\noutputs = Dense(nlabels, name='output', activation='softmax')(x)\nkeras_model_deepset = Model(inputs=inputs, outputs=outputs)\nkeras_model_deepset.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nprint(keras_model_deepset.summary())", "_____no_output_____" ], [ "# define callbacks\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=5)\nreduce_lr = ReduceLROnPlateau(patience=5, factor=0.5)\nmodel_checkpoint = ModelCheckpoint('keras_model_deepset_best.h5', monitor='val_loss', save_best_only=True)\ncallbacks = [early_stopping, model_checkpoint, reduce_lr]\n\n# fit keras model\nhistory_deepset = keras_model_deepset.fit(train_generator, \n validation_data=val_generator, \n steps_per_epoch=len(train_generator), \n validation_steps=len(val_generator),\n max_queue_size=5,\n epochs=20, \n shuffle=False,\n callbacks=callbacks, \n verbose=0)\n# reload best weights\nkeras_model_deepset.load_weights('keras_model_deepset_best.h5')", "_____no_output_____" ], [ "plt.figure()\nplt.plot(history_deepset.history['loss'], label='Loss')\nplt.plot(history_deepset.history['val_loss'], label='Val. loss')\nplt.xlabel('Epoch')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "# load testing file\ntest_files = ['root://eospublic.cern.ch//eos/opendata/cms/datascience/HiggsToBBNtupleProducerTool/HiggsToBBNTuple_HiggsToBB_QCD_RunII_13TeV_MC/test/ntuple_merged_0.root']\ntest_generator = DataGenerator(test_files, features, labels, spectators, batch_size=1024, n_dim=ntracks, \n remove_mass_pt_window=True, \n remove_unlabeled=True)", "_____no_output_____" ], [ "# run model inference on test data set\npredict_array_dense = []\npredict_array_deepset = []\nlabel_array_test = []\n\nfor t in test_generator:\n label_array_test.append(t[1])\n predict_array_dense.append(keras_model_dense.predict(t[0]))\n predict_array_deepset.append(keras_model_deepset.predict(t[0]))\n \n \npredict_array_dense = np.concatenate(predict_array_dense, axis=0)\npredict_array_deepset = np.concatenate(predict_array_deepset, axis=0)\nlabel_array_test = np.concatenate(label_array_test, axis=0)\n\n\n# create ROC curves\nfpr_dense, tpr_dense, threshold_dense = roc_curve(label_array_test[:,1], predict_array_dense[:,1])\nfpr_deepset, tpr_deepset, threshold_deepset = roc_curve(label_array_test[:,1], predict_array_deepset[:,1])\n \n# plot ROC curves\nplt.figure()\nplt.plot(tpr_dense, fpr_dense, lw=2.5, label=\"Dense, AUC = {:.1f}%\".format(auc(fpr_dense, tpr_dense)*100))\nplt.plot(tpr_deepset, fpr_deepset, lw=2.5, label=\"Deep Sets, AUC = {:.1f}%\".format(auc(fpr_deepset, tpr_deepset)*100))\nplt.xlabel(r'True positive rate')\nplt.ylabel(r'False positive rate')\nplt.semilogy()\nplt.ylim(0.001, 1)\nplt.xlim(0, 1)\nplt.grid(True)\nplt.legend(loc='upper left')\nplt.show()", "_____no_output_____" ] ], [ [ "We see the more structurally-aware Deep Sets model does better than a simple fully conneted neural network appraoch.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cb242f3192e909b48d767fd3fc20902e63b38967
6,181
ipynb
Jupyter Notebook
003_Python_List_Methods/010_Python_List_copy().ipynb
Maxc390/python-discrete-structures
f7bc7d7caed16f357cc712630b562182355e072b
[ "MIT" ]
175
2021-06-28T03:51:13.000Z
2022-03-25T06:29:14.000Z
003_Python_List_Methods/010_Python_List_copy().ipynb
Wangcx225/02_Python_Datatypes
57828db90aa8d960c62612ed33bb985483442e8a
[ "MIT" ]
null
null
null
003_Python_List_Methods/010_Python_List_copy().ipynb
Wangcx225/02_Python_Datatypes
57828db90aa8d960c62612ed33bb985483442e8a
[ "MIT" ]
164
2021-06-28T03:54:15.000Z
2022-03-25T08:08:53.000Z
22.724265
208
0.524349
[ [ [ "<small><small><i>\nAll the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/02_Python_Datatypes/tree/main/003_Python_List_Methods)**\n</i></small></small>", "_____no_output_____" ], [ "# Python List `copy()`\n\nThe **`copy()`** method returns a shallow copy of the list.\n\nA **[list](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List.ipynb)** can be copied using the **`=`** operator. For example,", "_____no_output_____" ] ], [ [ "old_list = [1, 2, 3]\nnew_list = old_list\nprint('old_list:', old_list)\nprint('new_list:', new_list)", "old_list: [1, 2, 3]\nnew_list: [1, 2, 3]\n" ] ], [ [ "The problem with copying lists in this way is that if you modify **`new_list`**, **`old_list`** is also modified. It is because the new list is referencing or pointing to the same **`old_list`** object.", "_____no_output_____" ] ], [ [ "old_list = [1, 2, 3]\nnew_list = old_list\n\n# add an element to list\nnew_list.append('a')\n\nprint('New List:', new_list)\nprint('Old List:', old_list)", "New List: [1, 2, 3, 'a']\nOld List: [1, 2, 3, 'a']\n" ] ], [ [ "However, if you need the original list unchanged when the new list is modified, you can use the **`copy()`** method.\n\n>Related tutorial: **[Python Shallow Copy Vs Deep Copy](https://github.com/milaan9/02_Python_Datatypes/blob/main/003_Python_List_Methods/Python_Shallow_Copy_and_Deep_Copy.ipynb)**", "_____no_output_____" ], [ "**Syntax**:\n\n```python\nnew_list = list.copy()\n```", "_____no_output_____" ], [ "## `copy()` Parameters\n\nThe **`copy()`** method doesn't take any parameters.", "_____no_output_____" ], [ "## Return Value from `copy()`\n\nThe **`copy()`** method returns a new list. It doesn't modify the original list.", "_____no_output_____" ] ], [ [ "# Example 1: Copying a List\n\n# mixed list\nmy_list = ['cat', 0, 6.7]\n\n# copying a list\nnew_list = my_list.copy()\n\nprint('Copied List:', new_list)", "Copied List: ['cat', 0, 6.7]\n" ] ], [ [ "If you modify the **`new_list`** in the above example, **`my_list`** will not be modified.", "_____no_output_____" ] ], [ [ "# Copy List Using Slicing Syntax\n\n# shallow copy using the slicing syntax\n\n# mixed list\nlist = ['cat', 0, 6.7]\n\n# copying a list using slicing\nnew_list = list[:]\n\n# Adding an element to the new list\nnew_list.append('dog')\n\n# Printing new and old list\nprint('Old List:', list)\nprint('New List:', new_list)", "Old List: ['cat', 0, 6.7]\nNew List: ['cat', 0, 6.7, 'dog']\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb2435b8109c6cb0de3609413e92a8aa3833a1f3
257,807
ipynb
Jupyter Notebook
Question_21_30/solutions_py/solution_024.ipynb
tsutaj/Gasyori100knock
3b78839cf2218259d9a943b26c28312cf19b4648
[ "MIT" ]
1
2020-09-11T10:08:04.000Z
2020-09-11T10:08:04.000Z
Question_21_30/solutions_py/solution_024.ipynb
tsutaj/Gasyori100knock
3b78839cf2218259d9a943b26c28312cf19b4648
[ "MIT" ]
null
null
null
Question_21_30/solutions_py/solution_024.ipynb
tsutaj/Gasyori100knock
3b78839cf2218259d9a943b26c28312cf19b4648
[ "MIT" ]
null
null
null
2,502.980583
128,500
0.965044
[ [ [ "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "img = cv2.imread(\"../imori_gamma.jpg\")\nH, W, ch = img.shape\nplt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\nplt.show()", "_____no_output_____" ], [ "c = 1\ng = 2.2\n\nm = np.max(img)\noutput_img = img / m\noutput_img = (1/c * output_img) ** (1/g)\noutput_img *= m\n\noutput_img = np.clip(output_img, 0, 255).astype(\"uint8\")", "_____no_output_____" ], [ "plt.imshow(cv2.cvtColor(output_img, cv2.COLOR_BGR2RGB))\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
cb244381cedbf7039e94a6da6e6dea08409f7fab
5,358
ipynb
Jupyter Notebook
Jaro_distance_calculator.ipynb
FerhatYilmaz1986/Customer_reviews_with_NLP
3eb2253060733fe03cb04eb9fe4bd493f6e256c3
[ "MIT" ]
1
2020-07-17T14:06:40.000Z
2020-07-17T14:06:40.000Z
Jaro_distance_calculator.ipynb
FerhatYilmaz1986/Customer_reviews_with_NLP
3eb2253060733fe03cb04eb9fe4bd493f6e256c3
[ "MIT" ]
null
null
null
Jaro_distance_calculator.ipynb
FerhatYilmaz1986/Customer_reviews_with_NLP
3eb2253060733fe03cb04eb9fe4bd493f6e256c3
[ "MIT" ]
1
2020-03-09T12:53:40.000Z
2020-03-09T12:53:40.000Z
22.512605
196
0.424225
[ [ [ "#Import libraries\nimport re\nimport pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "#This function cleans text \ndef cleantext(text):\n clean = re.sub('[^a-zA-z]', '', text)\n clean = clean.upper()\n return clean \n\n", "_____no_output_____" ], [ "#Create test data\ndf = {'Chars' : ['f1','f1 23', 'fde @ 1 2 3']}\ndf['Clean'] = [*map(cleantext,df['Chars'])]\ndf['MoreChars'] = ['f 1','f 2', 'fde @ 1 2 3']", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "#Jaro distance function\n \nfrom __future__ import division\n \n \ndef jaro(s, t):\n s_len = len(s)\n t_len = len(t)\n \n if s_len == 0 and t_len == 0:\n return 1\n \n match_distance = (max(s_len, t_len) // 2) - 1\n \n s_matches = [False] * s_len\n t_matches = [False] * t_len\n \n matches = 0\n transpositions = 0\n \n for i in range(s_len):\n start = max(0, i - match_distance)\n end = min(i + match_distance + 1, t_len)\n \n for j in range(start, end):\n if t_matches[j]:\n continue\n if s[i] != t[j]:\n continue\n s_matches[i] = True\n t_matches[j] = True\n matches += 1\n break\n \n if matches == 0:\n return 0\n \n k = 0\n for i in range(s_len):\n if not s_matches[i]:\n continue\n while not t_matches[k]:\n k += 1\n if s[i] != t[k]:\n transpositions += 1\n k += 1\n \n return ((matches / s_len) +\n (matches / t_len) +\n ((matches - transpositions / 2) / matches)) / 3\n \n \ndef main():\n '''Tests'''\n \n for s, t in [('JOHN', 'JOHNNY'),\n ('PYTHON', 'PYSPARK'),\n ('NEW YORK', 'NEW JERSEY')]:\n print(\"jaro(%r, %r) = %.10f\" % (s, t, jaro(s, t)))\n \n \nif __name__ == '__main__':\n main()\n", "jaro('JOHN', 'JOHNNY') = 0.8888888889\njaro('PYTHON', 'PYSPARK') = 0.5396825397\njaro('NEW YORK', 'NEW JERSEY') = 0.7083333333\n" ], [ "#Calculate score for test data\ndf['Score'] = [*map(jaro,df['Chars'],df['MoreChars'])]\ndf", "_____no_output_____" ], [ "\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
cb24522565c6949ecf29a7a9b09e09a0c455bae5
76,684
ipynb
Jupyter Notebook
Mod1/app_saude_cap_5/cuidadoComsaude.ipynb
spedison/Curso_igti_ML
0410c2b2d06dd55aedfddec9853a4bfa6e4ad309
[ "CC0-1.0" ]
null
null
null
Mod1/app_saude_cap_5/cuidadoComsaude.ipynb
spedison/Curso_igti_ML
0410c2b2d06dd55aedfddec9853a4bfa6e4ad309
[ "CC0-1.0" ]
null
null
null
Mod1/app_saude_cap_5/cuidadoComsaude.ipynb
spedison/Curso_igti_ML
0410c2b2d06dd55aedfddec9853a4bfa6e4ad309
[ "CC0-1.0" ]
null
null
null
76,684
76,684
0.652339
[ [ [ "#Estre programa contém os código demonstrados na aula sobre Aplicação de ML+IoT para o Healthcare(previsão de arritmia)", "_____no_output_____" ], [ "#importando o banco de dados a ser utilizado (comando necessário para o google colab)\nfrom google.colab import files\nuploaded = files.upload()", "_____no_output_____" ], [ "#importando as bibliotecas\nimport pandas as pd #biblioteca utilizada para tratar os dados em formato de dataframe\nimport numpy as np # biblioteca utilizada para tratar vetores e matrizesimport matplotlib.pyplot as plt #utilizapa para construir os gráficos em um formato similar ao \"Matlab\"\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder #utilizada para realizar o preprocessamento dos dados\nfrom sklearn.model_selection import train_test_split #utilizada para realizar o divisão entre dados para treinamento e teste\nfrom sklearn.metrics import confusion_matrix, accuracy_score #utilizada para verificar a acurácia do modelo construído\nfrom sklearn.naive_bayes import GaussianNB # utilizada para construir o modelo de classificação naive_bayes\nimport seaborn as sns #utilizada para constuir os gráficos em uma forma mais \"bonita\"\nimport matplotlib.pyplot as plt #biblioteca para realizar a construção dos gráficos\nfrom sklearn.svm import SVC #utilizada para importar o algoritmo SVM", "/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n" ], [ "from google.colab import drive\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "#lendo o dataset no formato de um dataframe através da função read do pandas\nnomeArquivo = '/content/drive/My Drive/Colab Notebooks/IGTI/app_saude/data.csv' \ndataset = pd.read_csv(nomeArquivo, sep=',') #realiza a leitura do banco de dados", "_____no_output_____" ], [ "#print do dataset\ndataset.head() # são 76 colunas, mas nem todas serão utilizadas para realizar a previsão de doença cardíaca", "_____no_output_____" ], [ "dataset.shape # mostra a dimensão do dataset", "_____no_output_____" ], [ "#conhecendo o dataset\ndataset.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 617 entries, 0 to 616\nData columns (total 76 columns):\n_id 617 non-null int64\nccf 617 non-null int64\nage 617 non-null int64\nsex 617 non-null int64\npain location 617 non-null int64\npain w exertion 617 non-null int64\nrelieved after rest 613 non-null float64\npncaden 0 non-null float64\nchest pain type 617 non-null int64\nresting bp s 558 non-null float64\nhypertension 583 non-null float64\ncholesterol 587 non-null float64\nsmoker 230 non-null float64\ncigarettes per day 202 non-null float64\nyears of smoking 190 non-null float64\nfasting blood sugar 527 non-null float64\ndiabetes 72 non-null float64\nfamily hist 195 non-null float64\nresting ecg 615 non-null float64\nekg month 564 non-null float64\nekg day 563 non-null float64\nekg yr 564 non-null float64\ndigitalis 551 non-null float64\nbeta blocker 553 non-null float64\nnitrates 554 non-null float64\ncalcium channel blocker 556 non-null float64\ndiuretic 537 non-null float64\nexercise protocol 505 non-null float64\nduration of exercise 561 non-null float64\nthaltime 233 non-null float64\nmets achieved 512 non-null float64\nmax heart rate 562 non-null float64\nresting heart rate 561 non-null float64\npeak exercise bp 1 554 non-null float64\npeak exercise bp 2 554 non-null float64\ndummy 1 558 non-null float64\nresting bp d 558 non-null float64\nexercise angina 562 non-null float64\nxhypo 559 non-null float64\noldpeak 555 non-null float64\nST slope 309 non-null float64\nST height at rest 474 non-null float64\nST heaight at peak 475 non-null float64\nflouroscopy 11 non-null float64\ndummy 2 0 non-null float64\ndummy 3 1 non-null float64\nresting ejection fraction 28 non-null float64\nrest wall motion abnormality 30 non-null float64\nexercise ejection fraction 2 non-null float64\nexercsie wall motion 5 non-null float64\nthal 142 non-null float64\ndummy 4 130 non-null float64\ndummy 5 44 non-null float64\ndummy 6 1 non-null float64\ncath month 606 non-null float64\ncath day 608 non-null float64\ncath yr 608 non-null float64\ntarget 617 non-null int64\nlmt 342 non-null float64\nladprox 381 non-null float64\nladdist 371 non-null float64\ndiag 341 non-null float64\ncxmain 382 non-null float64\nramus 332 non-null float64\nom1 346 non-null float64\nom2 327 non-null float64\nrcaprox 372 non-null float64\nrcadist 347 non-null float64\ndummy 7 598 non-null float64\ndummy 8 598 non-null float64\ndummy 9 598 non-null float64\ndummy 10 598 non-null float64\ndummy 11 601 non-null float64\ndummy 12 311 non-null float64\ndummy 13 119 non-null float64\ndummy 14 617 non-null object\ndtypes: float64(67), int64(8), object(1)\nmemory usage: 366.5+ KB\n" ] ], [ [ "**Existem vários dados nulos**", "_____no_output_____" ] ], [ [ "#tratando os dados nulos\ndataset.fillna(dataset.mean(), inplace=True) #substitui os dados que estão como NAN pela média dos valores na coluna\ndataset.head(3)", "_____no_output_____" ] ], [ [ "**Preparando os dados**", "_____no_output_____" ] ], [ [ "dataset_to_array = np.array(dataset) #transforma o dataframe em array para facilitar a escolha dos dados a serem utilizados", "_____no_output_____" ], [ "target = dataset_to_array[:,57] # esse é o vetor de saída (target)\ntarget= target.astype('int') #indica o tipo de dados\n# target[target>0] = 1 # 0 para o coração saudável e 1 para problema detectado\ntarget", "_____no_output_____" ] ], [ [ "**Iniciando a previsão**", "_____no_output_____" ] ], [ [ "#dados coletados pelos sensores\ndataset_sensor = np.column_stack(( \n dataset_to_array[:,11], # pressão sanguínea em repouso\n dataset_to_array[:,33], # frequencia máxima atingida\n dataset_to_array[:,34], # frequencia cardíaca em repouso\n dataset_to_array[:,35], # pico de pressão sanguínea durante exercício \n dataset_to_array[:,36], # pico de pressão sanguínea durante exercício \n dataset_to_array[:,38] # pressão sanguínea em repouso\n ))\n\nprint(dataset_sensor)\n## dataset_sensor_teste = np.column_stack((\n## [ i[0] for i in dataset_sensor if i[0] != np.empty and i[1] != np.empty and i[2] != np.empty_like and i[3] != np.empty_like and i[4] != np.empty_like and i[5] != np.empty_like ],\n## [ i[1] for i in dataset_sensor if i[0] != np.empty and i[1] != np.empty_like and i[2] != np.empty_like and i[3] != np.empty_like and i[4] != np.empty_like and i[5] != np.empty_like ],\n## [ i[2] for i in dataset_sensor if i[0] != np.empty and i[1] != np.empty_like and i[2] != np.empty_like and i[3] != np.empty_like and i[4] != np.empty_like and i[5] != np.empty_like ],\n## [ i[3] for i in dataset_sensor if i[0] != np.empty and i[1] != np.empty_like and i[2] != np.empty_like and i[3] != np.empty_like and i[4] != np.empty_like and i[5] != np.empty_like ],\n## [ i[4] for i in dataset_sensor if i[0] != np.empty and i[1] != np.empty_like and i[2] != np.empty_like and i[3] != np.empty_like and i[4] != np.empty_like and i[5] != np.empty_like ],\n## [ i[5] for i in dataset_sensor if i[0] != np.empty and i[1] != np.empty_like and i[2] != np.empty_like and i[3] != np.empty_like and i[4] != np.empty_like and i[5] != np.empty_like ]\n## ))\nprint(\"=====\")\n# print(dataset_sensor_teste)\n## print(\"-------------------------------\")\n## print(dataset_sensor.shape)\n## print(dataset_sensor_teste.shape)\n## print(\"-------------------------------\")\n##print(dataset_sensor.info())", "[[289.0 200.0 110.0 140.0 86.0 0.0]\n [180.0 220.0 106.0 160.0 90.0 0.0]\n [283.0 180.0 100.0 130.0 80.0 0.0]\n ...\n [223.0 210.0 100.0 122.0 70.0 0.0]\n [385.0 173.46570397111913 91.64440433212997 132.37275985663084\n 82.80465949820788 0.028622540250447227]\n [254.0 164.0 110.0 120.0 80.0 0.0]]\n=====\n" ], [ "#dataset com os dados médicos do paciente\ndataset_medico = np.column_stack((dataset_to_array[:,4] , # localização da dor\n dataset_to_array[:,6] , # alivio após o cansaço\n dataset_to_array[:,9] , # tipo de dor \n dataset_to_array[:,39], # angina induzida pelo exercício (1 = sim; 0 = nao) \n dataset.age, # idade \n dataset.sex , # sexo\n dataset.hypertension # hipertensão\n ))\nprint(dataset_medico)\nprint(dataset_medico.shape)", "[[1 0.0 140.0 ... 40 1 0.0]\n [1 0.0 160.0 ... 49 0 1.0]\n [1 0.0 130.0 ... 37 1 0.0]\n ...\n [1 1.0 122.0 ... 55 1 1.0]\n [1 1.0 132.37275985663084 ... 58 1 0.0]\n [1 0.0 120.0 ... 62 1 1.0]]\n(617, 7)\n" ], [ "#concatena as duas bases de dados\nprint(\"Medico : \", dataset_medico.shape)\nprint(\"Sensor : \", dataset_sensor.shape)\ndataset_paciente=np.concatenate((dataset_medico,dataset_sensor),axis=1)\nprint(dataset_paciente)\n\nprint(\"Resultado\", dataset_paciente.shape)", "Medico : (617, 7)\nSensor : (617, 6)\n[[1 0.0 140.0 ... 140.0 86.0 0.0]\n [1 0.0 160.0 ... 160.0 90.0 0.0]\n [1 0.0 130.0 ... 130.0 80.0 0.0]\n ...\n [1 1.0 122.0 ... 122.0 70.0 0.0]\n [1 1.0 132.37275985663084 ... 132.37275985663084 82.80465949820788\n 0.028622540250447227]\n [1 0.0 120.0 ... 120.0 80.0 0.0]]\nResultado (617, 13)\n" ], [ "print(\"Paciente: \", dataset_paciente.shape)\nprint(\"Target: \", target.shape)", "Paciente: (617, 13)\nTarget: (617,)\n" ], [ "#encontrando os dados para treinamento e teste\nX_train, X_test, y_train, y_test = train_test_split(dataset_paciente, target, random_state = 223)\nprint(\"X treino : \", X_train.shape)\nprint(\"X test : \", X_test.shape)", "X treino : (462, 13)\nX test : (155, 13)\n" ], [ "#cria o objeto SVM\nmodelSVM = SVC(kernel = 'linear', verbose=True) #escolha do kernel polinomial", "_____no_output_____" ], [ "#aplica o treinamento ao modelo\nmodelSVM.fit(X_train, y_train)\n", "[LibSVM]" ] ], [ [ "**Analisando a performance do modelo**", "_____no_output_____" ] ], [ [ "previsao = modelSVM.predict(X_test) #aplica o modelo para os dados de teste", "_____no_output_____" ], [ "#encontra a acuracia do modelo de previsão utilizando o SVM \naccuracia = accuracy_score(y_test, previsao)\nprint (\"Acuracia utilizando o SVM :\" , accuracia , \"\\nEm porcentagem : \", round(accuracia*100) , \"%\\n\")", "Acuracia utilizando o SVM : 0.5419354838709678 \nEm porcentagem : 54.0 %\n\n" ], [ "#criando a matriz de confusão\nimport pandas as pd\nimport seaborn as sn\nimport matplotlib.pyplot as plt\n\ncm = confusion_matrix(y_test, previsao) #gera a matriz de confusão\ndf_cm = pd.DataFrame(cm, index = [i for i in \"01234\"],columns = [i for i in \"01234\"]) #cria o df com as classes\nplt.figure(figsize = (10,7)) #indica o tamanho da figura \nsn.heatmap(df_cm, annot=True) #plota a figura\n", "_____no_output_____" ] ], [ [ "**Modificando o Dataset**", "_____no_output_____" ] ], [ [ "#vamos escolher apenas 13 atributos para realizar a previsão de doenças cardíacas\n\ndataset_to_array = np.array(dataset)\nlabel = dataset_to_array[:,57] # \"Target\" classes binárias 0 e 1\nlabel = label.astype('int')\nlabel[label>0] = 1 # Quando os dados são 0 está saldável e 1 doente", "_____no_output_____" ], [ "label", "_____no_output_____" ], [ "#encontrando os dados para treinamento e teste\nX_train, X_test, y_train, y_test = train_test_split(dataset_paciente, label, random_state = 223)", "_____no_output_____" ], [ "#cria o objeto SVM\nmodelSVM = SVC(kernel = 'linear', verbose=True, degree=3) #escolha do kernel polinomial :: linear, poly, rbf", "_____no_output_____" ], [ "#aplica o treinamento ao modelo\nmodelSVM.fit(X_train, y_train)\n", "[LibSVM]" ], [ "previsao = modelSVM.predict(X_test) #aplica o modelo para os dados de teste", "_____no_output_____" ], [ "#encontra a acuracia do modelo de previsão utilizando o SVM \naccuracia = accuracy_score(y_test, previsao)\nprint (\"Acuracia utilizando o SVM :\" , accuracia , \"\\nEm porcentagem : \", round(accuracia*100) , \"%\\n\")", "Acuracia utilizando o SVM : 0.7419354838709677 \nEm porcentagem : 74.0 %\n\n" ], [ "#criando a matriz de confusão\nimport pandas as pd\nimport seaborn as sn\nimport matplotlib.pyplot as plt\n\ncm = confusion_matrix(y_test, previsao) #gera a matriz de confusão\ndf_cm = pd.DataFrame(cm, index = [i for i in \"01\"],columns = [i for i in \"01\"]) #cria o df com as classes\nplt.figure(figsize = (10,7)) #indica o tamanho da figura \nsn.heatmap(df_cm, annot=True) #plota a figura\n", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\n \ny_pred = previsao\ny_true = y_test\nprint(accuracy_score(y_true, y_pred))\n\nprint(classification_report(y_true, y_pred))\n\n##accuracy_score(y_true, y_pred, normalize=False)", "0.7419354838709677\n precision recall f1-score support\n\n 0 0.77 0.59 0.67 69\n 1 0.73 0.86 0.79 86\n\n accuracy 0.74 155\n macro avg 0.75 0.73 0.73 155\nweighted avg 0.75 0.74 0.74 155\n\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb2470bb38a326783472932b20bb525529776880
350,249
ipynb
Jupyter Notebook
notebooks/.ipynb_checkpoints/3planets_underlying_e_dist-checkpoint.ipynb
ssagear/metallicity
62a301d9c6bb3b37a395dc6f8c3130e836f9e095
[ "MIT" ]
2
2021-03-04T02:50:36.000Z
2021-11-14T10:55:44.000Z
notebooks/.ipynb_checkpoints/3planets_underlying_e_dist-checkpoint.ipynb
ssagear/metallicity
62a301d9c6bb3b37a395dc6f8c3130e836f9e095
[ "MIT" ]
null
null
null
notebooks/.ipynb_checkpoints/3planets_underlying_e_dist-checkpoint.ipynb
ssagear/metallicity
62a301d9c6bb3b37a395dc6f8c3130e836f9e095
[ "MIT" ]
null
null
null
185.023244
51,768
0.907934
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tqdm import tqdm\nfrom astropy.table import Table\nimport astropy.units as u\nimport os\n\n# Using `batman` to create & fit fake transit\nimport batman\n\n# Using astropy BLS and scipy curve_fit to fit transit\nfrom astropy.timeseries import BoxLeastSquares\n\n# Using emcee & corner to find and plot (e, w) distribution with MCMC\nimport emcee\nimport corner\n\n# Using dynesty to do the same with nested sampling\nimport dynesty\n\nimport scipy.constants as c\n\n# And importing `photoeccentric`\nimport photoeccentric as ph\n\n%load_ext autoreload\n%autoreload 2\n\n# pandas display option\npd.set_option('display.float_format', lambda x: '%.5f' % x)\n\n", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ] ], [ [ "1. Choose 3 planets with e from a Gaussian distrbution with (0.5, 0.2)\n2. Fit them using photoeccentric, find fit e and w\n3. Implement Van Eylen equation to find underlying e dist on surface", "_____no_output_____" ] ], [ [ "true_es = np.random.normal(loc=0.5, scale=0.2, size=3)\ntrue_ws = np.random.uniform(low=-90, high=270, size=3)", "_____no_output_____" ], [ "true_es", "_____no_output_____" ], [ "nwalk = 64\nnsteps = 1000\nndiscard = 500\narrlen = (nsteps-ndiscard)*nwalk\n\nsmass_kg = 1.9885e30 # Solar mass (kg)\nsrad_m = 696.34e6 # Solar radius (m)", "_____no_output_____" ], [ "muirhead_data = pd.read_csv(\"datafiles/Muirhead2013_isochrones/muirhead_data_incmissing.txt\", sep=\" \")\n\n# ALL Kepler planets from exo archive\nplanets = pd.read_csv('datafiles/exoplanetarchive/cumulative_kois.csv')\n\n# Take the Kepler planet archive entries for the planets in Muirhead et al. 2013 sample\nspectplanets = pd.read_csv('spectplanets.csv')\n\n# Kepler-Gaia Data\nkpgaia = Table.read('datafiles/Kepler-Gaia/kepler_dr2_4arcsec.fits', format='fits').to_pandas();\n\n# Kepler-Gaia data for only the objects in our sample\nmuirhead_gaia = pd.read_csv(\"muirhead_gaia.csv\")\n\n# Combined spectroscopy data + Gaia/Kepler data for our sample\nmuirhead_comb = pd.read_csv('muirhead_comb.csv')\n\n# Only targets from table above with published luminosities from Gaia\nmuirhead_comb_lums = pd.read_csv('muirhead_comb_lums.csv')", "/Users/ssagear/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3418: TableReplaceWarning: converted column 'r_result_flag' from integer to float\n exec(code_obj, self.user_global_ns, self.user_ns)\n/Users/ssagear/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3418: TableReplaceWarning: converted column 'r_modality_flag' from integer to float\n exec(code_obj, self.user_global_ns, self.user_ns)\n/Users/ssagear/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3418: TableReplaceWarning: converted column 'teff_err1' from integer to float\n exec(code_obj, self.user_global_ns, self.user_ns)\n/Users/ssagear/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3418: TableReplaceWarning: converted column 'teff_err2' from integer to float\n exec(code_obj, self.user_global_ns, self.user_ns)\n" ], [ "# Kepler ID for Kepler-1582 b\nkepid = 9710326\nkepname = spectplanets.loc[spectplanets['kepid'] == kepid].kepler_name.values[0]\n\nkp737b = muirhead_comb.loc[muirhead_comb['KIC'] == kepid]\n\nKOI = 947", "_____no_output_____" ], [ "isodf = pd.read_csv(\"datafiles/isochrones/iso_lums_\" + str(kepid) + \".csv\")", "_____no_output_____" ], [ "mstar = isodf[\"mstar\"].mean()\nmstar_err = isodf[\"mstar\"].std()\n\nrstar = isodf[\"radius\"].mean()\nrstar_err = isodf[\"radius\"].std()", "_____no_output_____" ], [ "rho_star, mass, radius = ph.find_density_dist_symmetric(mstar, mstar_err, rstar, rstar_err, arrlen)", "_____no_output_____" ], [ "period, period_uerr, period_lerr, rprs, rprs_uerr, rprs_lerr, a_arc, a_uerr_arc, a_lerr_arc, i, e_arc, w_arc = ph.planet_params_from_archive(spectplanets, kepname)\n\n# We calculate a_rs to ensure that it's consistent with the spec/Gaia stellar density.\na_rs = ph.calc_a(period*86400.0, mstar*smass_kg, rstar*srad_m)\na_rs_err = np.mean((a_uerr_arc, a_lerr_arc))\n\nprint('Stellar mass (Msun): ', mstar, 'Stellar radius (Rsun): ', rstar)\nprint('Period (Days): ', period, 'Rp/Rs: ', rprs)\nprint('a/Rs: ', a_rs)\nprint('i (deg): ', i)", "Stellar mass (Msun): 0.48797798116154106 Stellar radius (Rsun): 0.4690682721275218\nPeriod (Days): 28.59914031 Rp/Rs: 0.036375\na/Rs: 65.99499728728715\ni (deg): 89.99\n" ], [ "inc = 89.99", "_____no_output_____" ] ], [ [ "## First Planet", "_____no_output_____" ] ], [ [ "# 30 minute cadence\ncadence = 0.02142857142857143\n\ntime = np.arange(-300, 300, cadence)", "_____no_output_____" ], [ "e", "_____no_output_____" ], [ "w", "_____no_output_____" ], [ "# Define e and w, calculate flux from transit model\ne = true_es[0]\nw = true_ws[0]\nflux = ph.integratedlc(time, period, rprs, a_rs, e, i, w, 0.0)\n\n# Adding some gaussian noise on the order of Kepler noise (by eyeball)\nnoise = np.random.normal(0,0.0001,len(time))\nnflux = flux+noise\n\nflux_err = np.array([0.0001]*len(nflux))", "_____no_output_____" ], [ "plt.errorbar(time, nflux, yerr=flux_err, fmt='o')\nplt.xlabel('Time')\nplt.ylabel('Flux')\nplt.xlim(-0.5, 0.5)\nplt.axvline(0.0, c='r', label='Transit midpoint')\nplt.legend()", "_____no_output_____" ], [ "transitmpt = 0\n\nmidpoints = np.unique(np.sort(np.concatenate((np.arange(transitmpt, time[0], -period), np.arange(transitmpt, time[-1], period)))))", "_____no_output_____" ] ], [ [ "## Fitting the transit", "_____no_output_____" ] ], [ [ "# Remove Out of Transit Data\n\nttime = []\ntflux = []\ntflux_err = []\n\nfor i in range(len(midpoints)):\n\n m, b, t1bjd, t1, fnorm, fe1 = ph.do_linfit(time, nflux, flux_err, midpoints[i], 11, 5)\n ttime.append(t1bjd)\n tflux.append(fnorm)\n tflux_err.append(fe1)\n \n\nttime = np.array(ttime).flatten()\ntflux = np.array(tflux).flatten()\ntflux_err = np.array(tflux_err).flatten()\n\ntflux = np.nan_to_num(tflux, nan=1.0)\ntflux_err = np.nan_to_num(tflux_err, nan=np.nanmedian(tflux_err))", "_____no_output_____" ], [ "priortransform = [3., 27., 1., 0., 15., 64., 2., 88., 0.1, transitmpt]\nnbuffer = 11\n\ndres, perDists, rpDists, arsDists, incDists, t0Dist = ph.fit_keplc_dynesty(KOI, midpoints, ttime, tflux, tflux_err, priortransform, arrlen, nbuffer, spectplanets, muirhead_comb)\n", "\r0it [00:00, ?it/s]" ], [ "#perDists", "_____no_output_____" ], [ "np.savetxt('S1periods.csv', perDists, delimiter=',')\nnp.savetxt('S1rprs.csv', rpDists, delimiter=',')\nnp.savetxt('S1ars.csv', arsDists, delimiter=',')\nnp.savetxt('S1inc.csv', incDists, delimiter=',')\n\nnp.savetxt('S1t0.csv', t0Dist, delimiter=',')", "_____no_output_____" ], [ "t0Dists = t0Dist", "_____no_output_____" ], [ "per_f = ph.mode(perDists)\nrprs_f = ph.mode(rpDists)\na_f = ph.mode(arsDists)\ni_f = ph.mode(incDists)\nt0_f = ph.mode(t0Dists)", "_____no_output_____" ], [ "# Create a light curve with the fit parameters\nfit1 = ph.integratedlc_fitter(ttime, per_f, rprs_f, a_f, i_f, t0_f)", "_____no_output_____" ], [ "plt.errorbar(ttime, tflux, yerr=tflux_err, c='blue', alpha=0.5, label='Original LC')\nplt.plot(ttime, fit1, c='red', alpha=1.0, label='Fit LC')\n#plt.xlim(-0.1, 0.1)\nplt.legend()\n\nprint('Stellar mass (Msun): ', mstar, 'Stellar radius (Rsun): ', rstar)\n\nprint('\\n')\n\nprint('Input params:')\nprint('Rp/Rs: ', rprs)\nprint('a/Rs: ', a_rs)\nprint('i (deg): ', i)\n\nprint('\\n')\n\nprint('Fit params:')\nprint('Rp/Rs: ', rprs_f)\nprint('a/Rs: ', a_f)\nprint('i (deg): ', i_f)", "Stellar mass (Msun): 0.48797798116154106 Stellar radius (Rsun): 0.4690682721275218\n\n\nInput params:\nRp/Rs: 0.036375\na/Rs: 65.99499728728715\ni (deg): 20\n\n\nFit params:\nRp/Rs: 0.03644493510744964\na/Rs: 65.38274949677151\ni (deg): 89.87177768963167\n" ] ], [ [ "### Determining T14 and T23", "_____no_output_____" ] ], [ [ "pdist = perDists\nrdist = rpDists\nadist = arsDists\nidist = incDists\nt0dist = t0Dists", "_____no_output_____" ], [ "T14dist = ph.get_T14(pdist, rdist, adist, idist)\nT14errs = ph.get_sigmas(T14dist)\n\nT23dist = ph.get_T23(pdist, rdist, adist, idist)\nT23errs = ph.get_sigmas(T23dist)", "/Users/ssagear/Dropbox (UFL)/Research/MetallicityProject/photoeccentric/photoeccentric/photoeccentric.py:61: RuntimeWarning: invalid value encountered in sqrt\n T14[j] = (p[j]/np.pi)*np.arcsin(rs_a[j]*(np.sqrt(((1+rprs[j])**2)-b[j]**2))/np.sin(i[j]*(np.pi/180.0))) #Equation 14 in exoplanet textbook\n/Users/ssagear/Dropbox (UFL)/Research/MetallicityProject/photoeccentric/photoeccentric/photoeccentric.py:113: RuntimeWarning: invalid value encountered in sqrt\n T23[j] = (p[j]/np.pi)*np.arcsin(rs_a[j]*(np.sqrt(((1-rprs[j])**2)-b[j]**2))/np.sin(i[j]*(np.pi/180.0))) #Equation 14 in exoplanet textbook\n" ] ], [ [ "# Get $g$", "_____no_output_____" ] ], [ [ "gs, rho_c = ph.get_g_distribution(rho_star, pdist, rdist, T14dist, T23dist)\n\ng_mean = ph.mode(gs)\ng_sigma = np.mean(np.abs(ph.get_sigmas(gs)))", "_____no_output_____" ], [ "g_mean", "_____no_output_____" ], [ "g_sigma", "_____no_output_____" ], [ "#Guesses\nw_guess = 0.0\ne_guess = 0.0\n\nsolnx = (w_guess, e_guess)\npos = solnx + 1e-4 * np.random.randn(32, 2)\nnwalkers, ndim = pos.shape", "_____no_output_____" ], [ "sampler = emcee.EnsembleSampler(nwalkers, ndim, ph.log_probability, args=(g_mean, g_sigma), threads=4)\nsampler.run_mcmc(pos, 5000, progress=True);", " 0%| | 0/5000 [00:00<?, ?it/s]/Users/ssagear/anaconda3/lib/python3.8/site-packages/emcee/moves/red_blue.py:99: RuntimeWarning: invalid value encountered in double_scalars\n lnpdiff = f + nlp - state.log_prob[j]\n100%|██████████| 5000/5000 [00:04<00:00, 1240.90it/s]\n" ], [ "labels = [\"w\", \"e\"]\n\nflat_samples = sampler.get_chain(discard=100, thin=15, flat=True)\nfig = corner.corner(flat_samples, labels=labels, title_kwargs={\"fontsize\": 12}, truths=[w, e], plot_contours=True)", "_____no_output_____" ] ], [ [ "## Second Planet", "_____no_output_____" ] ], [ [ "# 30 minute cadence\ncadence = 0.02142857142857143\n\ntime = np.arange(-300, 300, cadence)", "_____no_output_____" ], [ "i\n", "_____no_output_____" ], [ "# Define e and w, calculate flux from transit model\ne = true_es[1]\nw = true_ws[1]\nflux = ph.integratedlc(time, period, rprs, a_rs, e, i, w, 0.0)", "_____no_output_____" ], [ "inc", "_____no_output_____" ], [ "# Adding some gaussian noise on the order of Kepler noise (by eyeball)\nnoise = np.random.normal(0,0.0001,len(time))\nnflux = flux+noise\n\nflux_err = np.array([0.0001]*len(nflux))", "_____no_output_____" ], [ "plt.errorbar(time, flux, yerr=flux_err, fmt='o')\nplt.xlabel('Time')\nplt.ylabel('Flux')\nplt.xlim(-0.5, 0.5)\nplt.axvline(0.0, c='r', label='Transit midpoint')\nplt.legend()", "_____no_output_____" ], [ "transitmpt = 0\n\nmidpoints = np.unique(np.sort(np.concatenate((np.arange(transitmpt, time[0], -period), np.arange(transitmpt, time[-1], period)))))", "_____no_output_____" ] ], [ [ "## Fitting the transit", "_____no_output_____" ] ], [ [ "# Remove Out of Transit Data\n\nttime = []\ntflux = []\ntflux_err = []\n\nfor i in range(len(midpoints)):\n\n m, b, t1bjd, t1, fnorm, fe1 = ph.do_linfit(time, nflux, flux_err, midpoints[i], 11, 5)\n ttime.append(t1bjd)\n tflux.append(fnorm)\n tflux_err.append(fe1)\n \n\nttime = np.array(ttime).flatten()\ntflux = np.array(tflux).flatten()\ntflux_err = np.array(tflux_err).flatten()\n\ntflux = np.nan_to_num(tflux, nan=1.0)\ntflux_err = np.nan_to_num(tflux_err, nan=np.nanmedian(tflux_err))", "_____no_output_____" ], [ "priortransform = [3., 27., 1., 0., 15., 64., 2., 88., 0.1, transitmpt]\nnbuffer = 11\n\nms, bs, timesBJD, timesPhase, fluxNorm, fluxErrs, perDists, rpDists, arsDists, incDists, t0Dist = ph.fit_keplc_dynesty(KOI, midpoints, ttime, tflux, tflux_err, priortransform, arrlen, nbuffer, spectplanets, muirhead_comb)\n", "\r0it [00:00, ?it/s]" ], [ "perDists", "_____no_output_____" ], [ "np.savetxt('Speriods.csv', perDists, delimiter=',')\nnp.savetxt('Srprs.csv', rpDists, delimiter=',')\nnp.savetxt('Sars.csv', arsDists, delimiter=',')\nnp.savetxt('Sinc.csv', incDists, delimiter=',')\n\nnp.savetxt('St0.csv', t0Dists, delimiter=',')", "_____no_output_____" ], [ "per_f = ph.mode(perDists)\nrprs_f = ph.mode(rpDists)\na_f = ph.mode(arsDists)\ni_f = ph.mode(incDists)\nt0_f = ph.mode(t0Dists)", "_____no_output_____" ], [ "# Create a light curve with the fit parameters\nfit1 = ph.integratedlc_fitter(time1, per_f, rprs_f, a_f, i_f, t0_f)", "_____no_output_____" ], [ "plt.errorbar(time1, nflux1, yerr=fluxerr1, c='blue', alpha=0.5, label='Original LC')\nplt.plot(time1, fit1, c='red', alpha=1.0, label='Fit LC')\n#plt.xlim(-0.1, 0.1)\nplt.legend()\n\nprint('Stellar mass (Msun): ', mstar, 'Stellar radius (Rsun): ', rstar)\n\nprint('\\n')\n\nprint('Input params:')\nprint('Rp/Rs: ', rprs)\nprint('a/Rs: ', a_rs)\nprint('i (deg): ', i)\n\nprint('\\n')\n\nprint('Fit params:')\nprint('Rp/Rs: ', rprs_f)\nprint('a/Rs: ', a_f)\nprint('i (deg): ', i_f)", "_____no_output_____" ] ], [ [ "### Determining T14 and T23", "_____no_output_____" ] ], [ [ "T14dist = ph.get_T14(pdist, rdist, adist, idist)\nT14errs = ph.get_sigmas(T14dist)\n\nT23dist = ph.get_T23(pdist, rdist, adist, idist)\nT23errs = ph.get_sigmas(T23dist)", "_____no_output_____" ] ], [ [ "# Get $g$", "_____no_output_____" ] ], [ [ "gs, rho_c = ph.get_g_distribution(rho_star, pdist, rdist, T14dist, T23dist)\n\ng_mean = ph.mode(gs)\ng_sigma = np.mean(np.abs(ph.get_sigmas(gs)))", "_____no_output_____" ], [ "g_mean", "_____no_output_____" ], [ "g_sigma", "_____no_output_____" ], [ "#Guesses\nw_guess = 0.0\ne_guess = 0.0\n\nsolnx = (w_guess, e_guess)\npos = solnx + 1e-4 * np.random.randn(32, 2)\nnwalkers, ndim = pos.shape", "_____no_output_____" ], [ "sampler = emcee.EnsembleSampler(nwalkers, ndim, ph.log_probability, args=(g_mean, g_sigma), threads=4)\nsampler.run_mcmc(pos, 5000, progress=True);", " 0%| | 0/5000 [00:00<?, ?it/s]/Users/ssagear/anaconda3/lib/python3.8/site-packages/emcee/moves/red_blue.py:99: RuntimeWarning: invalid value encountered in double_scalars\n lnpdiff = f + nlp - state.log_prob[j]\n100%|██████████| 5000/5000 [00:04<00:00, 1215.65it/s]\n" ], [ "labels = [\"w\", \"e\"]\n\nflat_samples = sampler.get_chain(discard=100, thin=15, flat=True)\nfig = corner.corner(flat_samples, labels=labels, title_kwargs={\"fontsize\": 12}, truths=[w, e], plot_contours=True)", "_____no_output_____" ] ], [ [ "## Third Planet", "_____no_output_____" ] ], [ [ "# 30 minute cadence\ncadence = 0.02142857142857143\n\ntime = np.arange(-300, 300, cadence)", "_____no_output_____" ], [ "# Define e and w, calculate flux from transit model\ne = true_es[2]\nw = true_ws[2]\nflux = ph.integratedlc(time, period, rprs, a_rs, e, i, w, 0.0)\n\n# Adding some gaussian noise on the order of Kepler noise (by eyeball)\nnoise = np.random.normal(0,0.0001,len(time))\nnflux = flux+noise\n\nflux_err = np.array([0.0001]*len(nflux))", "_____no_output_____" ], [ "plt.errorbar(time, nflux, yerr=flux_err, fmt='o')\nplt.xlabel('Time')\nplt.ylabel('Flux')\nplt.xlim(-0.5, 0.5)\nplt.axvline(0.0, c='r', label='Transit midpoint')\nplt.legend()", "_____no_output_____" ], [ "transitmpt = 0\n\nmidpoints = np.unique(np.sort(np.concatenate((np.arange(transitmpt, time[0], -period), np.arange(transitmpt, time[-1], period)))))", "_____no_output_____" ] ], [ [ "## Fitting the transit", "_____no_output_____" ] ], [ [ "# Remove Out of Transit Data\n\nttime = []\ntflux = []\ntflux_err = []\n\nfor i in range(len(midpoints)):\n\n m, b, t1bjd, t1, fnorm, fe1 = ph.do_linfit(time, nflux, flux_err, midpoints[i], 11, 5)\n ttime.append(t1bjd)\n tflux.append(fnorm)\n tflux_err.append(fe1)\n \n\nttime = np.array(ttime).flatten()\ntflux = np.array(tflux).flatten()\ntflux_err = np.array(tflux_err).flatten()\n\ntflux = np.nan_to_num(tflux, nan=1.0)\ntflux_err = np.nan_to_num(tflux_err, nan=np.nanmedian(tflux_err))", "_____no_output_____" ], [ "priortransform = [3., 27., 1., 0., 15., 64., 2., 88., 0.1, transitmpt]\nnbuffer = 11\n\nms, bs, timesBJD, timesPhase, fluxNorm, fluxErrs, perDists, rpDists, arsDists, incDists, t0Dist = ph.fit_keplc_dynesty(KOI, midpoints, ttime, tflux, tflux_err, priortransform, arrlen, nbuffer, spectplanets, muirhead_comb)\n", "\r0it [00:00, ?it/s]" ], [ "perDists", "_____no_output_____" ], [ "np.savetxt('Speriods.csv', perDists, delimiter=',')\nnp.savetxt('Srprs.csv', rpDists, delimiter=',')\nnp.savetxt('Sars.csv', arsDists, delimiter=',')\nnp.savetxt('Sinc.csv', incDists, delimiter=',')\n\nnp.savetxt('St0.csv', t0Dists, delimiter=',')", "_____no_output_____" ], [ "per_f = ph.mode(perDists)\nrprs_f = ph.mode(rpDists)\na_f = ph.mode(arsDists)\ni_f = ph.mode(incDists)\nt0_f = ph.mode(t0Dists)", "_____no_output_____" ], [ "# Create a light curve with the fit parameters\nfit1 = ph.integratedlc_fitter(time1, per_f, rprs_f, a_f, i_f, t0_f)", "_____no_output_____" ], [ "plt.errorbar(time1, nflux1, yerr=fluxerr1, c='blue', alpha=0.5, label='Original LC')\nplt.plot(time1, fit1, c='red', alpha=1.0, label='Fit LC')\n#plt.xlim(-0.1, 0.1)\nplt.legend()\n\nprint('Stellar mass (Msun): ', mstar, 'Stellar radius (Rsun): ', rstar)\n\nprint('\\n')\n\nprint('Input params:')\nprint('Rp/Rs: ', rprs)\nprint('a/Rs: ', a_rs)\nprint('i (deg): ', i)\n\nprint('\\n')\n\nprint('Fit params:')\nprint('Rp/Rs: ', rprs_f)\nprint('a/Rs: ', a_f)\nprint('i (deg): ', i_f)", "_____no_output_____" ] ], [ [ "### Determining T14 and T23", "_____no_output_____" ] ], [ [ "T14dist = ph.get_T14(pdist, rdist, adist, idist)\nT14errs = ph.get_sigmas(T14dist)\n\nT23dist = ph.get_T23(pdist, rdist, adist, idist)\nT23errs = ph.get_sigmas(T23dist)", "_____no_output_____" ] ], [ [ "# Get $g$", "_____no_output_____" ] ], [ [ "gs, rho_c = ph.get_g_distribution(rho_star, pdist, rdist, T14dist, T23dist)\n\ng_mean = ph.mode(gs)\ng_sigma = np.mean(np.abs(ph.get_sigmas(gs)))", "_____no_output_____" ], [ "g_mean", "_____no_output_____" ], [ "g_sigma", "_____no_output_____" ], [ "#Guesses\nw_guess = 0.0\ne_guess = 0.0\n\nsolnx = (w_guess, e_guess)\npos = solnx + 1e-4 * np.random.randn(32, 2)\nnwalkers, ndim = pos.shape", "_____no_output_____" ], [ "sampler = emcee.EnsembleSampler(nwalkers, ndim, ph.log_probability, args=(g_mean, g_sigma), threads=4)\nsampler.run_mcmc(pos, 5000, progress=True);", " 0%| | 0/5000 [00:00<?, ?it/s]/Users/ssagear/anaconda3/lib/python3.8/site-packages/emcee/moves/red_blue.py:99: RuntimeWarning: invalid value encountered in double_scalars\n lnpdiff = f + nlp - state.log_prob[j]\n100%|██████████| 5000/5000 [00:04<00:00, 1215.65it/s]\n" ], [ "labels = [\"w\", \"e\"]\n\nflat_samples = sampler.get_chain(discard=100, thin=15, flat=True)\nfig = corner.corner(flat_samples, labels=labels, title_kwargs={\"fontsize\": 12}, truths=[w, e], plot_contours=True)", "_____no_output_____" ] ], [ [ "Probability Grid", "_____no_output_____" ] ], [ [ "mumesh = np.linspace(0, 1, 100)\nsigmesh = np.linspace(0.01, 0.3, 100)", "_____no_output_____" ], [ "mus, sigmas = np.meshgrid(mumesh, sigmesh)", "_____no_output_____" ], [ "# Vet 100 values from each e distribution\nfit_es = [np.random.normal(loc=0.2, scale=0.05, size=100), np.random.normal(loc=0.3, scale=0.05, size=100), np.random.normal(loc=0.4, scale=0.05, size=100)]\nfit_ws = [np.random.normal(loc=90, scale=10, size=100), np.random.normal(loc=-90, scale=10, size=100), np.random.normal(loc=0.0, scale=10, size=100)]", "_____no_output_____" ], [ "import scipy", "_____no_output_____" ], [ "# for each planet\n\n", "_____no_output_____" ], [ "# Planet 1: true_es[0]\npethetasum1 = np.zeros((100,100))\n\n# Calculating p(obs|theta) for 10,000 grid points, for N posterior values for 1 panet\n\nfor n1 in tqdm(range(len(mus))): # For each grid point x\n for n2 in range(len(mus[0])): # For each grid point y\n mu_test = mus[n1][n2]\n sig_test = sigmas[n1][n2] # x, y of grid point\n \n for N in range(len(fit_es[0])): # For each posterior value (out of 100)\n pethetasum1[n1][n2] += scipy.stats.norm.pdf(fit_es[0][N], loc=mu_test, scale=sig_test)", "100%|██████████| 100/100 [01:35<00:00, 1.05it/s]\n" ], [ "fig, ax = plt.subplots(figsize=(6,6))\n\nax.imshow(pethetasum1, extent=[0, 1, 0.01, 0.3], aspect = 'auto')\nax.set_xlabel('mean eccentricity')\nax.set_ylabel('sigma')", "_____no_output_____" ], [ "# Planet 2: true_es[1]\npethetasum2 = np.zeros((100,100))\n\n# Calculating p(obs|theta) for 10,000 grid points, for N posterior values for 1 panet\n\nfor n1 in tqdm(range(len(mus))): # For each grid point x\n for n2 in range(len(mus[0])): # For each grid point y\n mu_test = mus[n1][n2]\n sig_test = sigmas[n1][n2] # x, y of grid point\n \n for N in range(len(fit_es[1])): # For each posterior value (out of 100)\n pethetasum2[n1][n2] += scipy.stats.norm.pdf(fit_es[1][N], loc=mu_test, scale=sig_test)", "100%|██████████| 100/100 [01:35<00:00, 1.05it/s]\n" ], [ "fig, ax = plt.subplots(figsize=(6,6))\n\nax.imshow(pethetasum2, extent=[0, 1, 0.01, 0.3], aspect = 'auto')\nax.set_xlabel('mean eccentricity')\nax.set_ylabel('sigma')", "_____no_output_____" ], [ "# Planet 2: true_es[1]\npethetasum3 = np.zeros((100,100))\n\n# Calculating p(obs|theta) for 10,000 grid points, for N posterior values for 1 panet\n\nfor n1 in tqdm(range(len(mus))): # For each grid point x\n for n2 in range(len(mus[0])): # For each grid point y\n mu_test = mus[n1][n2]\n sig_test = sigmas[n1][n2] # x, y of grid point\n \n for N in range(len(fit_es[1])): # For each posterior value (out of 100)\n pethetasum3[n1][n2] += scipy.stats.norm.pdf(fit_es[2][N], loc=mu_test, scale=sig_test)", "100%|██████████| 100/100 [01:35<00:00, 1.05it/s]\n" ], [ "fig, ax = plt.subplots(figsize=(6,6))\n\nax.imshow(pethetasum3, extent=[0, 1, 0.01, 0.3], aspect = 'auto')\nax.set_xlabel('mean eccentricity')\nax.set_ylabel('sigma')", "_____no_output_____" ], [ "P = pethetasum1*pethetasum2*pethetasum3\nP = P/np.sqrt(100*100)", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(6,6))\n\nax.imshow(P, extent=[0, 1, 0.01, 0.3], aspect = 'auto')\nax.set_xlabel('mean eccentricity')\nax.set_ylabel('sigma')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb24817fd32da0b8800a429bdadb0280276dd580
43,218
ipynb
Jupyter Notebook
site/en/r2/guide/saved_model.ipynb
NexusXi/docs
7c8aea728a4eca4ee719fe6cca36ee95eb7ad40d
[ "Apache-2.0" ]
4
2019-08-20T11:59:23.000Z
2020-01-12T13:42:50.000Z
site/en/r2/guide/saved_model.ipynb
NexusXi/docs
7c8aea728a4eca4ee719fe6cca36ee95eb7ad40d
[ "Apache-2.0" ]
null
null
null
site/en/r2/guide/saved_model.ipynb
NexusXi/docs
7c8aea728a4eca4ee719fe6cca36ee95eb7ad40d
[ "Apache-2.0" ]
null
null
null
36.22632
468
0.545722
[ [ [ "##### Copyright 2018 The TensorFlow Authors.", "_____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_____" ] ], [ [ "# Using the SavedModel format", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/beta/guide/saved_model\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/guide/saved_model.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r2/guide/saved_model.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/r2/guide/saved_model.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>", "_____no_output_____" ], [ "A SavedModel contains a complete TensorFlow program, including weights and computation. It does not require the original model building code to run, which makes it useful for sharing or deploying (with [TFLite](https://tensorflow.org/lite), [TensorFlow.js](https://js.tensorflow.org/), [TensorFlow Serving](https://www.tensorflow.org/tfx/serving/tutorials/Serving_REST_simple), or [TFHub](https://tensorflow.org/hub)).\n\nIf you have code for a model in Python and want to load weights into it, see the [guide to training checkpoints](./checkpoints.ipynb).\n\n\n\nFor a quick introduction, this section exports a pre-trained Keras model and serves image classification requests with it. The rest of the guide will fill in details and discuss other ways to create SavedModels.", "_____no_output_____" ] ], [ [ "from __future__ import absolute_import, division, print_function, unicode_literals\ntry:\n %tensorflow_version 2.x # Colab only.\nexcept Exception:\n pass\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nimport numpy as np", "_____no_output_____" ], [ "file = tf.keras.utils.get_file(\n \"grace_hopper.jpg\",\n \"https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg\")\nimg = tf.keras.preprocessing.image.load_img(file, target_size=[224, 224])\nplt.imshow(img)\nplt.axis('off')\nx = tf.keras.preprocessing.image.img_to_array(img)\nx = tf.keras.applications.mobilenet.preprocess_input(\n x[tf.newaxis,...])", "_____no_output_____" ] ], [ [ "We'll use an image of Grace Hopper as a running example, and a Keras pre-trained image classification model since it's easy to use. Custom models work too, and are covered in detail later.", "_____no_output_____" ] ], [ [ "#tf.keras.applications.vgg19.decode_predictions\nlabels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')\nimagenet_labels = np.array(open(labels_path).read().splitlines())", "_____no_output_____" ], [ "pretrained_model = tf.keras.applications.MobileNet()\nresult_before_save = pretrained_model(x)\nprint()\n\ndecoded = imagenet_labels[np.argsort(result_before_save)[0,::-1][:5]+1]\n\nprint(\"Result before saving:\\n\", decoded)", "_____no_output_____" ] ], [ [ "The top prediction for this image is \"military uniform\".", "_____no_output_____" ] ], [ [ "tf.saved_model.save(pretrained_model, \"/tmp/mobilenet/1/\")", "_____no_output_____" ] ], [ [ "The save-path follows a convention used by TensorFlow Serving where the last path component (`1/` here) is a version number for your model - it allows tools like Tensorflow Serving to reason about the relative freshness.\n\nSavedModels have named functions called signatures. Keras models export their forward pass under the `serving_default` signature key. The [SavedModel command line interface](#saved_model_cli) is useful for inspecting SavedModels on disk:", "_____no_output_____" ] ], [ [ "!saved_model_cli show --dir /tmp/mobilenet/1 --tag_set serve --signature_def serving_default", "_____no_output_____" ] ], [ [ "We can load the SavedModel back into Python with `tf.saved_model.load` and see how Admiral Hopper's image is classified.", "_____no_output_____" ] ], [ [ "loaded = tf.saved_model.load(\"/tmp/mobilenet/1/\")\nprint(list(loaded.signatures.keys())) # [\"serving_default\"]", "_____no_output_____" ] ], [ [ "Imported signatures always return dictionaries.", "_____no_output_____" ] ], [ [ "infer = loaded.signatures[\"serving_default\"]\nprint(infer.structured_outputs)", "_____no_output_____" ] ], [ [ "Running inference from the SavedModel gives the same result as the original model.", "_____no_output_____" ] ], [ [ "labeling = infer(tf.constant(x))[pretrained_model.output_names[0]]\n\ndecoded = imagenet_labels[np.argsort(labeling)[0,::-1][:5]+1]\n\nprint(\"Result after saving and loading:\\n\", decoded)", "_____no_output_____" ] ], [ [ "## Serving the model\n\nSavedModels are usable from Python, but production environments typically use a dedicated service for inference. This is easy to set up from a SavedModel using TensorFlow Serving.\n\nSee the [TensorFlow Serving REST tutorial](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/tutorials/Serving_REST_simple.ipynb) for more details about serving, including instructions for installing `tensorflow_model_server` in a notebook or on your local machine. As a quick sketch, to serve the `mobilenet` model exported above just point the model server at the SavedModel directory:\n\n```bash\nnohup tensorflow_model_server \\\n --rest_api_port=8501 \\\n --model_name=mobilenet \\\n --model_base_path=\"/tmp/mobilenet\" >server.log 2>&1\n```\n\n Then send a request.\n\n```python\n!pip install requests\nimport json\nimport numpy\nimport requests\ndata = json.dumps({\"signature_name\": \"serving_default\",\n \"instances\": x.tolist()})\nheaders = {\"content-type\": \"application/json\"}\njson_response = requests.post('http://localhost:8501/v1/models/mobilenet:predict',\n data=data, headers=headers)\npredictions = numpy.array(json.loads(json_response.text)[\"predictions\"])\n```\n\nThe resulting `predictions` are identical to the results from Python.", "_____no_output_____" ], [ "### SavedModel format\n\nA SavedModel is a directory containing serialized signatures and the state needed to run them, including variable values and vocabularies.\n", "_____no_output_____" ] ], [ [ "!ls /tmp/mobilenet/1 # assets\tsaved_model.pb\tvariables", "_____no_output_____" ] ], [ [ "The `saved_model.pb` file contains a set of named signatures, each identifying a function.\n\nSavedModels may contain multiple sets of signatures (multiple MetaGraphs, identified with the `tag_set` argument to `saved_model_cli`), but this is rare. APIs which create multiple sets of signatures include [`tf.Estimator.experimental_export_all_saved_models`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#experimental_export_all_saved_models) and in TensorFlow 1.x `tf.saved_model.Builder`.", "_____no_output_____" ] ], [ [ "!saved_model_cli show --dir /tmp/mobilenet/1 --tag_set serve", "_____no_output_____" ] ], [ [ "The `variables` directory contains a standard training checkpoint (see the [guide to training checkpoints](./checkpoints.ipynb)).", "_____no_output_____" ] ], [ [ "!ls /tmp/mobilenet/1/variables", "_____no_output_____" ] ], [ [ "The `assets` directory contains files used by the TensorFlow graph, for example text files used to initialize vocabulary tables. It is unused in this example.\n\nSavedModels may have an `assets.extra` directory for any files not used by the TensorFlow graph, for example information for consumers about what to do with the SavedModel. TensorFlow itself does not use this directory.", "_____no_output_____" ], [ "### Exporting custom models\n\nIn the first section, `tf.saved_model.save` automatically determined a signature for the `tf.keras.Model` object. This worked because Keras `Model` objects have an unambiguous method to export and known input shapes. `tf.saved_model.save` works just as well with low-level model building APIs, but you will need to indicate which function to use as a signature if you're planning to serve a model.", "_____no_output_____" ] ], [ [ "class CustomModule(tf.Module):\n\n def __init__(self):\n super(CustomModule, self).__init__()\n self.v = tf.Variable(1.)\n\n @tf.function\n def __call__(self, x):\n return x * self.v\n\n @tf.function(input_signature=[tf.TensorSpec([], tf.float32)])\n def mutate(self, new_v):\n self.v.assign(new_v)\n\nmodule = CustomModule()", "_____no_output_____" ] ], [ [ "This module has two methods decorated with `tf.function`. While these functions will be included in the SavedModel and available if the SavedModel is reloaded via `tf.saved_model.load` into a Python program, without explicitly declaring the serving signature tools like Tensorflow Serving and `saved_model_cli` cannot access them.\n\n`module.mutate` has an `input_signature`, and so there is enough information to save its computation graph in the SavedModel already. `__call__` has no signature and so this method needs to be called before saving.", "_____no_output_____" ] ], [ [ "module(tf.constant(0.))\ntf.saved_model.save(module, \"/tmp/module_no_signatures\")", "_____no_output_____" ] ], [ [ "For functions without an `input_signature`, any input shapes used before saving will be available after loading. Since we called `__call__` with just a scalar, it will accept only scalar values.", "_____no_output_____" ] ], [ [ "imported = tf.saved_model.load(\"/tmp/module_no_signatures\")\nassert 3. == imported(tf.constant(3.)).numpy()\nimported.mutate(tf.constant(2.))\nassert 6. == imported(tf.constant(3.)).numpy()", "_____no_output_____" ] ], [ [ "The function will not accept new shapes like vectors.\n\n```python\nimported(tf.constant([3.]))\n```\n\n<pre>\nValueError: Could not find matching function to call for canonicalized inputs ((<tf.Tensor 'args_0:0' shape=(1,) dtype=float32>,), {}). Only existing signatures are [((TensorSpec(shape=(), dtype=tf.float32, name=u'x'),), {})].\n</pre>", "_____no_output_____" ], [ "`get_concrete_function` lets you add input shapes to a function without calling it. It takes `tf.TensorSpec` objects in place of `Tensor` arguments, indicating the shapes and dtypes of inputs. Shapes can either be `None`, indicating that any shape is acceptable, or a list of axis sizes. If an axis size is `None` then any size is acceptable for that axis. `tf.TensorSpecs` can also have names, which default to the function's argument keywords (\"x\" here).", "_____no_output_____" ] ], [ [ "module.__call__.get_concrete_function(x=tf.TensorSpec([None], tf.float32))\ntf.saved_model.save(module, \"/tmp/module_no_signatures\")\nimported = tf.saved_model.load(\"/tmp/module_no_signatures\")\nassert [3.] == imported(tf.constant([3.])).numpy()", "_____no_output_____" ] ], [ [ "Functions and variables attached to objects like `tf.keras.Model` and `tf.Module` are available on import, but many Python types and attributes are lost. The Python program itself is not saved in the SavedModel.\n\nWe didn't identify any of the functions we exported as a signature, so it has none.", "_____no_output_____" ] ], [ [ "!saved_model_cli show --dir /tmp/module_no_signatures --tag_set serve", "_____no_output_____" ] ], [ [ "## Identifying a signature to export\n\nTo indicate that a function should be a signature, specify the `signatures` argument when saving.", "_____no_output_____" ] ], [ [ "call = module.__call__.get_concrete_function(tf.TensorSpec(None, tf.float32))\ntf.saved_model.save(module, \"/tmp/module_with_signature\", signatures=call)", "_____no_output_____" ] ], [ [ "Notice that we first converted the `tf.function` to a `ConcreteFunction` with `get_concrete_function`. This is necessary because the function was created without a fixed `input_signature`, and so did not have a definite set of `Tensor` inputs associated with it.", "_____no_output_____" ] ], [ [ "!saved_model_cli show --dir /tmp/module_with_signature --tag_set serve --signature_def serving_default", "_____no_output_____" ], [ "imported = tf.saved_model.load(\"/tmp/module_with_signature\")\nsignature = imported.signatures[\"serving_default\"]\nassert [3.] == signature(x=tf.constant([3.]))[\"output_0\"].numpy()\nimported.mutate(tf.constant(2.))\nassert [6.] == signature(x=tf.constant([3.]))[\"output_0\"].numpy()\nassert 2. == imported.v.numpy()", "_____no_output_____" ] ], [ [ "We exported a single signature, and its key defaulted to \"serving_default\". To export multiple signatures, pass a dictionary.", "_____no_output_____" ] ], [ [ "@tf.function(input_signature=[tf.TensorSpec([], tf.string)])\ndef parse_string(string_input):\n return imported(tf.strings.to_number(string_input))\n\nsignatures = {\"serving_default\": parse_string,\n \"from_float\": imported.signatures[\"serving_default\"]}\n\ntf.saved_model.save(imported, \"/tmp/module_with_multiple_signatures\", signatures)", "_____no_output_____" ], [ "!saved_model_cli show --dir /tmp/module_with_multiple_signatures --tag_set serve", "_____no_output_____" ] ], [ [ "`saved_model_cli` can also run SavedModels directly from the command line.", "_____no_output_____" ] ], [ [ "!saved_model_cli run --dir /tmp/module_with_multiple_signatures --tag_set serve --signature_def serving_default --input_exprs=\"string_input='3.'\"\n!saved_model_cli run --dir /tmp/module_with_multiple_signatures --tag_set serve --signature_def from_float --input_exprs=\"x=3.\"", "_____no_output_____" ] ], [ [ "## Fine-tuning imported models\n\nVariable objects are available, and we can backprop through imported functions.", "_____no_output_____" ] ], [ [ "optimizer = tf.optimizers.SGD(0.05)\n\ndef train_step():\n with tf.GradientTape() as tape:\n loss = (10. - imported(tf.constant(2.))) ** 2\n variables = tape.watched_variables()\n grads = tape.gradient(loss, variables)\n optimizer.apply_gradients(zip(grads, variables))\n return loss", "_____no_output_____" ], [ "for _ in range(10):\n # \"v\" approaches 5, \"loss\" approaches 0\n print(\"loss={:.2f} v={:.2f}\".format(train_step(), imported.v.numpy()))", "_____no_output_____" ] ], [ [ "## Control flow in SavedModels\n\nAnything that can go in a `tf.function` can go in a SavedModel. With [AutoGraph](./autograph.ipynb) this includes conditional logic which depends on Tensors, specified with regular Python control flow.", "_____no_output_____" ] ], [ [ "@tf.function(input_signature=[tf.TensorSpec([], tf.int32)])\ndef control_flow(x):\n if x < 0:\n tf.print(\"Invalid!\")\n else:\n tf.print(x % 3)\n\nto_export = tf.Module()\nto_export.control_flow = control_flow\ntf.saved_model.save(to_export, \"/tmp/control_flow\")", "_____no_output_____" ], [ "imported = tf.saved_model.load(\"/tmp/control_flow\")\nimported.control_flow(tf.constant(-1)) # Invalid!\nimported.control_flow(tf.constant(2)) # 2\nimported.control_flow(tf.constant(3)) # 0", "_____no_output_____" ] ], [ [ "## SavedModels from Estimators\n\nEstimators export SavedModels through [`tf.Estimator.export_saved_model`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#export_saved_model). See the [guide to Estimator](https://www.tensorflow.org/guide/estimators) for details.", "_____no_output_____" ] ], [ [ "input_column = tf.feature_column.numeric_column(\"x\")\nestimator = tf.estimator.LinearClassifier(feature_columns=[input_column])\n\ndef input_fn():\n return tf.data.Dataset.from_tensor_slices(\n ({\"x\": [1., 2., 3., 4.]}, [1, 1, 0, 0])).repeat(200).shuffle(64).batch(16)\nestimator.train(input_fn)\n\nserving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(\n tf.feature_column.make_parse_example_spec([input_column]))\nexport_path = estimator.export_saved_model(\n \"/tmp/from_estimator/\", serving_input_fn)", "_____no_output_____" ] ], [ [ "This SavedModel accepts serialized `tf.Example` protocol buffers, which are useful for serving. But we can also load it with `tf.saved_model.load` and run it from Python.", "_____no_output_____" ] ], [ [ "imported = tf.saved_model.load(export_path)\n\ndef predict(x):\n example = tf.train.Example()\n example.features.feature[\"x\"].float_list.value.extend([x])\n return imported.signatures[\"predict\"](\n examples=tf.constant([example.SerializeToString()]))", "_____no_output_____" ], [ "print(predict(1.5))\nprint(predict(3.5))", "_____no_output_____" ] ], [ [ "`tf.estimator.export.build_raw_serving_input_receiver_fn` allows you to create input functions which take raw tensors rather than `tf.train.Example`s.", "_____no_output_____" ], [ "## Load a SavedModel in C++\n\nThe C++ version of the SavedModel [loader](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/cc/saved_model/loader.h) provides an API to load a SavedModel from a path, while allowing SessionOptions and RunOptions. You have to specify the tags associated with the graph to be loaded. The loaded version of SavedModel is referred to as SavedModelBundle and contains the MetaGraphDef and the session within which it is loaded.\n\n```C++\nconst string export_dir = ...\nSavedModelBundle bundle;\n...\nLoadSavedModel(session_options, run_options, export_dir, {kSavedModelTagTrain},\n &bundle);\n```", "_____no_output_____" ], [ "<a id=saved_model_cli/>\n\n## Details of the SavedModel command line interface\n\nYou can use the SavedModel Command Line Interface (CLI) to inspect and\nexecute a SavedModel.\nFor example, you can use the CLI to inspect the model's `SignatureDef`s.\nThe CLI enables you to quickly confirm that the input\nTensor dtype and shape match the model. Moreover, if you\nwant to test your model, you can use the CLI to do a sanity check by\npassing in sample inputs in various formats (for example, Python\nexpressions) and then fetching the output.\n\n\n### Install the SavedModel CLI\n\nBroadly speaking, you can install TensorFlow in either of the following\ntwo ways:\n\n* By installing a pre-built TensorFlow binary.\n* By building TensorFlow from source code.\n\nIf you installed TensorFlow through a pre-built TensorFlow binary,\nthen the SavedModel CLI is already installed on your system\nat pathname `bin\\saved_model_cli`.\n\nIf you built TensorFlow from source code, you must run the following\nadditional command to build `saved_model_cli`:\n\n```\n$ bazel build tensorflow/python/tools:saved_model_cli\n```\n\n### Overview of commands\n\nThe SavedModel CLI supports the following two commands on a\n`MetaGraphDef` in a SavedModel:\n\n* `show`, which shows a computation on a `MetaGraphDef` in a SavedModel.\n* `run`, which runs a computation on a `MetaGraphDef`.\n\n\n### `show` command\n\nA SavedModel contains one or more `MetaGraphDef`s, identified by their tag-sets.\nTo serve a model, you\nmight wonder what kind of `SignatureDef`s are in each model, and what are their\ninputs and outputs. The `show` command let you examine the contents of the\nSavedModel in hierarchical order. Here's the syntax:\n\n```\nusage: saved_model_cli show [-h] --dir DIR [--all]\n[--tag_set TAG_SET] [--signature_def SIGNATURE_DEF_KEY]\n```\n\nFor example, the following command shows all available\nMetaGraphDef tag-sets in the SavedModel:\n\n```\n$ saved_model_cli show --dir /tmp/saved_model_dir\nThe given SavedModel contains the following tag-sets:\nserve\nserve, gpu\n```\n\nThe following command shows all available `SignatureDef` keys in\na `MetaGraphDef`:\n\n```\n$ saved_model_cli show --dir /tmp/saved_model_dir --tag_set serve\nThe given SavedModel `MetaGraphDef` contains `SignatureDefs` with the\nfollowing keys:\nSignatureDef key: \"classify_x2_to_y3\"\nSignatureDef key: \"classify_x_to_y\"\nSignatureDef key: \"regress_x2_to_y3\"\nSignatureDef key: \"regress_x_to_y\"\nSignatureDef key: \"regress_x_to_y2\"\nSignatureDef key: \"serving_default\"\n```\n\nIf a `MetaGraphDef` has *multiple* tags in the tag-set, you must specify\nall tags, each tag separated by a comma. For example:\n\n<pre>\n$ saved_model_cli show --dir /tmp/saved_model_dir --tag_set serve,gpu\n</pre>\n\nTo show all inputs and outputs TensorInfo for a specific `SignatureDef`, pass in\nthe `SignatureDef` key to `signature_def` option. This is very useful when you\nwant to know the tensor key value, dtype and shape of the input tensors for\nexecuting the computation graph later. For example:\n\n```\n$ saved_model_cli show --dir \\\n/tmp/saved_model_dir --tag_set serve --signature_def serving_default\nThe given SavedModel SignatureDef contains the following input(s):\n inputs['x'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, 1)\n name: x:0\nThe given SavedModel SignatureDef contains the following output(s):\n outputs['y'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, 1)\n name: y:0\nMethod name is: tensorflow/serving/predict\n```\n\nTo show all available information in the SavedModel, use the `--all` option.\nFor example:\n\n<pre>\n$ saved_model_cli show --dir /tmp/saved_model_dir --all\nMetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:\n\nsignature_def['classify_x2_to_y3']:\n The given SavedModel SignatureDef contains the following input(s):\n inputs['inputs'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, 1)\n name: x2:0\n The given SavedModel SignatureDef contains the following output(s):\n outputs['scores'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, 1)\n name: y3:0\n Method name is: tensorflow/serving/classify\n\n...\n\nsignature_def['serving_default']:\n The given SavedModel SignatureDef contains the following input(s):\n inputs['x'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, 1)\n name: x:0\n The given SavedModel SignatureDef contains the following output(s):\n outputs['y'] tensor_info:\n dtype: DT_FLOAT\n shape: (-1, 1)\n name: y:0\n Method name is: tensorflow/serving/predict\n</pre>\n\n\n### `run` command\n\nInvoke the `run` command to run a graph computation, passing\ninputs and then displaying (and optionally saving) the outputs.\nHere's the syntax:\n\n```\nusage: saved_model_cli run [-h] --dir DIR --tag_set TAG_SET --signature_def\n SIGNATURE_DEF_KEY [--inputs INPUTS]\n [--input_exprs INPUT_EXPRS]\n [--input_examples INPUT_EXAMPLES] [--outdir OUTDIR]\n [--overwrite] [--tf_debug]\n```\n\nThe `run` command provides the following three ways to pass inputs to the model:\n\n* `--inputs` option enables you to pass numpy ndarray in files.\n* `--input_exprs` option enables you to pass Python expressions.\n* `--input_examples` option enables you to pass `tf.train.Example`.\n\n#### `--inputs`\n\nTo pass input data in files, specify the `--inputs` option, which takes the\nfollowing general format:\n\n```bsh\n--inputs <INPUTS>\n```\n\nwhere *INPUTS* is either of the following formats:\n\n* `<input_key>=<filename>`\n* `<input_key>=<filename>[<variable_name>]`\n\nYou may pass multiple *INPUTS*. If you do pass multiple inputs, use a semicolon\nto separate each of the *INPUTS*.\n\n`saved_model_cli` uses `numpy.load` to load the *filename*.\nThe *filename* may be in any of the following formats:\n\n* `.npy`\n* `.npz`\n* pickle format\n\nA `.npy` file always contains a numpy ndarray. Therefore, when loading from\na `.npy` file, the content will be directly assigned to the specified input\ntensor. If you specify a *variable_name* with that `.npy` file, the\n*variable_name* will be ignored and a warning will be issued.\n\nWhen loading from a `.npz` (zip) file, you may optionally specify a\n*variable_name* to identify the variable within the zip file to load for\nthe input tensor key. If you don't specify a *variable_name*, the SavedModel\nCLI will check that only one file is included in the zip file and load it\nfor the specified input tensor key.\n\nWhen loading from a pickle file, if no `variable_name` is specified in the\nsquare brackets, whatever that is inside the pickle file will be passed to the\nspecified input tensor key. Otherwise, the SavedModel CLI will assume a\ndictionary is stored in the pickle file and the value corresponding to\nthe *variable_name* will be used.\n\n\n#### `--input_exprs`\n\nTo pass inputs through Python expressions, specify the `--input_exprs` option.\nThis can be useful for when you don't have data\nfiles lying around, but still want to sanity check the model with some simple\ninputs that match the dtype and shape of the model's `SignatureDef`s.\nFor example:\n\n```bsh\n`<input_key>=[[1],[2],[3]]`\n```\n\nIn addition to Python expressions, you may also pass numpy functions. For\nexample:\n\n```bsh\n`<input_key>=np.ones((32,32,3))`\n```\n\n(Note that the `numpy` module is already available to you as `np`.)\n\n\n#### `--input_examples`\n\nTo pass `tf.train.Example` as inputs, specify the `--input_examples` option.\nFor each input key, it takes a list of dictionary, where each dictionary is an\ninstance of `tf.train.Example`. The dictionary keys are the features and the\nvalues are the value lists for each feature.\nFor example:\n\n```bsh\n`<input_key>=[{\"age\":[22,24],\"education\":[\"BS\",\"MS\"]}]`\n```\n\n#### Save output\n\nBy default, the SavedModel CLI writes output to stdout. If a directory is\npassed to `--outdir` option, the outputs will be saved as `.npy` files named after\noutput tensor keys under the given directory.\n\nUse `--overwrite` to overwrite existing output files.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
cb2496944f0ac319225f5b8c85fe88c7d7e47eca
18,849
ipynb
Jupyter Notebook
code/TestConnection.ipynb
uwescience/SQL-geospatial-tutorial
279cf760a003b4f0201079fae51c96aab28f0171
[ "CC-BY-4.0" ]
6
2017-06-12T23:34:43.000Z
2021-04-29T17:53:50.000Z
code/TestConnection.ipynb
uwescience/SQL-geospatial-tutorial
279cf760a003b4f0201079fae51c96aab28f0171
[ "CC-BY-4.0" ]
6
2017-06-14T06:24:24.000Z
2017-06-23T22:43:07.000Z
code/TestConnection.ipynb
uwescience/SQL-geospatial-tutorial
279cf760a003b4f0201079fae51c96aab28f0171
[ "CC-BY-4.0" ]
3
2017-06-15T16:46:44.000Z
2018-06-26T12:19:42.000Z
165.342105
2,018
0.702531
[ [ [ "# loading the special sql extension\n%load_ext sql", "_____no_output_____" ], [ "# connecting to a database which lives on the Amazon Cloud\n# need to substitute password with the one provided in the email!!!\n%sql postgresql://aws_dssg:datascience2016@dssg2017.csya4zsfb6y4.us-east-1.rds.amazonaws.com:5432-east-1.rds.amazonaws.com/dssg2016", "Format: (postgresql|mysql)://username:password@hostname/dbname, or one of dict_keys([])\n" ], [ "# running a simple SQL command\n%sql select * from seattlecrimeincidents limit 10;", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cb2498a0031f00bf68379db9996709b0129da500
72,861
ipynb
Jupyter Notebook
CNN Research Notebook.ipynb
ychennay/attention-facial-recognition
e97a9703f28b89dd829a45af79bf10ba5dde0d52
[ "MIT" ]
9
2020-02-18T13:22:29.000Z
2021-01-13T11:53:29.000Z
CNN Research Notebook.ipynb
ychennay/attention-facial-recognition
e97a9703f28b89dd829a45af79bf10ba5dde0d52
[ "MIT" ]
null
null
null
CNN Research Notebook.ipynb
ychennay/attention-facial-recognition
e97a9703f28b89dd829a45af79bf10ba5dde0d52
[ "MIT" ]
1
2021-01-13T17:32:33.000Z
2021-01-13T17:32:33.000Z
65.640541
15,496
0.691907
[ [ [ "# Import Dependencies", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings('ignore')\nimport keras\nimport matplotlib.pyplot as plt", "Using TensorFlow backend.\n" ] ], [ [ "## Define Types", "_____no_output_____" ] ], [ [ "from typing import Tuple\nImageShape = Tuple[int, int]\nGrayScaleImageShape = Tuple[int, int, int]", "_____no_output_____" ] ], [ [ "# MNIST Sandbox Baseline Example", "_____no_output_____" ], [ "This sandbox example is meant mostly to establish a few baselines for model performance to compare against, and also to get the basic Keras neural network architecture set up. I split the training and testing data and then one-hot encode the targets (one column per target, so ten columns after encoding).", "_____no_output_____" ] ], [ [ "from keras.datasets import mnist\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "from typing import Tuple\nimport numpy as np\nDataset = Tuple[np.ndarray, np.ndarray]\n\n#download mnist data and split into train and test sets\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\nprint(f\"The shape of X_train is {X_train.shape}\")\nprint(f\"The shape of y_train is {y_train.shape}\")\nprint(f\"The shape of X_test is {X_test.shape}\")\nprint(f\"The shape of y_test is {y_test.shape} - some example targets: {y_test[:5]}\")\nmnist_image_shape: ImageShape = X_train.shape[1:]\nprint(mnist_image_shape)", "The shape of X_train is (60000, 28, 28)\nThe shape of y_train is (60000,)\nThe shape of X_test is (10000, 28, 28)\nThe shape of y_test is (10000,) - some example targets: [7 2 1 0 4]\n(28, 28)\n" ], [ "from keras.utils import to_categorical\n\nOneHotEncodedTarget = np.ndarray\nCategories = int\nencoded_y_train: OneHotEncodedTarget = to_categorical(y_train)\nencoded_y_test: OneHotEncodedTarget = to_categorical(y_test)\nprint(f\"One-hot encoding y_train {y_train.shape} -> {encoded_y_train.shape}\")\nprint(f\"One-hot encoding y_test {y_test.shape} -> {encoded_y_test.shape}\")\n\nK: Categories = encoded_y_test.shape[1]", "One-hot encoding y_train (60000,) -> (60000, 10)\nOne-hot encoding y_test (10000,) -> (10000, 10)\n" ] ], [ [ "# Vanilla CNN Implementation", "_____no_output_____" ], [ "Build a vanilla CNN implementation, with two convolutional layers, 64 and 32 filters each, with kernel size of `3 x 3`. Then the values are flattened and fed into the final softmax classification dense layer for predictions.", "_____no_output_____" ] ], [ [ "from keras.models import Sequential, Model\nfrom keras.layers import Dense, Conv2D, Flatten, Input\nfrom tensorflow.python.framework.ops import Tensor\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# define model architecture and hyperparameters\nNUM_FILTERS_L1 = 64\nNUM_FILTERS_L2 = 32\nKERNEL_SIZE = 3\n\n# the images are 28 x 28 (pixel size) x 1 (grayscale - if RGB, then 3)\ninput_dims: GrayScaleImageShape = (28,28,1)\n\ndef build_vanilla_cnn(filters_layer1:int, filters_layer2:int, kernel_size:int, input_dims: GrayScaleImageShape)-> Model:\n inputs: Tensor = Input(shape=input_dims)\n x: Tensor = Conv2D(filters=filters_layer1, kernel_size=kernel_size, activation='relu')(inputs)\n x: Tensor = Conv2D(filters=filters_layer2, kernel_size=kernel_size, activation='relu')(x)\n x: Tensor = Flatten()(x)\n predictions = Dense(K, activation=\"softmax\")(x)\n print(predictions)\n\n #compile model using accuracy to measure model performance\n model: Model = Model(inputs=inputs, outputs=predictions)\n model.compile(optimizer='adam', loss=\"categorical_crossentropy\", metrics=['accuracy'])\n return model\n\nmodel: Model = build_vanilla_cnn(NUM_FILTERS_L1, NUM_FILTERS_L2, KERNEL_SIZE, input_dims)", "Tensor(\"dense_3/Softmax:0\", shape=(?, 10), dtype=float32)\n" ] ], [ [ "## Helper Function to Expand Tensor Dimensions By 1", "_____no_output_____" ] ], [ [ "X_train.reshape((60000,1,28,28))\n\ndef expand_tensor_shape(X_train: np.ndarray)-> np.ndarray:\n new_shape: Tuple = X_train.shape + (1,)\n \n# new_tensor = X_train.reshape(new_shape).reshape((-1,1,28,28))\n new_tensor = X_train.reshape(new_shape)\n print(f\"Expanding shape from {X_train.shape} to {new_tensor.shape}\")\n return new_tensor\n\nX_train_expanded: np.ndarray = expand_tensor_shape(X_train)\nX_test_expanded: np.ndarray = expand_tensor_shape(X_test)\n \n \n# train model and retrieve history\n# from keras.callbacks import History\n# history: History = model.fit(X_train_expanded, encoded_y_train, \n# validation_data=(X_test_expanded, encoded_y_test), epochs=2, batch_size=2058)", "Expanding shape from (60000, 28, 28) to (60000, 28, 28, 1)\nExpanding shape from (10000, 28, 28) to (10000, 28, 28, 1)\n" ] ], [ [ "## Global Average Pooling Layer\n\nOutput shape of convolutional layer is typically `batch size x number of filters x width x height`. The GAP layer will take the average of the width/height axis and return a vector of length equal to the number of filters.", "_____no_output_____" ] ], [ [ "from keras import backend as K", "_____no_output_____" ], [ "np.reshape(X_train_expanded, (-1,1,28,28)).shape", "_____no_output_____" ], [ "from keras.layers import Dense, Conv2D, Flatten, Input, MaxPool2D", "_____no_output_____" ], [ "###### from keras.layers import Layer, Lambda, Input\nfrom tensorflow.python.framework.ops import Tensor\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Conv2D, Flatten, Input, MaxPool2D\nfrom tensorflow.python.framework.ops import Tensor\ndef global_average_pooling(x: Layer):\n return K.mean(x, axis = (2,3))\n\ndef global_average_pooling_shape(input_shape):\n # return the dimensions corresponding with batch size and number of filters\n return (input_shape[0], input_shape[-1])\n\ndef build_global_average_pooling_layer(function, output_shape):\n return Lambda(pooling_function, output_shape)\n\ninputs: Tensor = Input(shape=(28,28,1))\nx: Tensor = Conv2D(filters=32, kernel_size=5, activation='relu')(inputs)\n# x: Tensor = MaxPool2D()(x)\n# x: Tensor = Conv2D(filters=64, kernel_size=5, activation='relu')(x)\nx: Tensor = Lambda(lambda x: K.mean(x, axis=(1,2)), output_shape=global_average_pooling_shape)(x)\n# x: Tensor = Dense(128, activation=\"relu\")(x)\npredictions: Tensor = Dense(10, activation=\"softmax\")(x)\nmodel: Model = Model(inputs=inputs, outputs=predictions)\nmodel.summary()\nmodel.compile(optimizer='adam', loss=\"categorical_crossentropy\", metrics=['accuracy'])\nfrom keras.callbacks import History\nhistory: History = model.fit(X_train_expanded, encoded_y_train, \n validation_data=(X_test_expanded, encoded_y_test), epochs=100, batch_size=5126)", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) (None, 28, 28, 1) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 24, 24, 32) 832 \n_________________________________________________________________\nlambda_1 (Lambda) (None, 32) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 10) 330 \n=================================================================\nTotal params: 1,162.0\nTrainable params: 1,162.0\nNon-trainable params: 0.0\n_________________________________________________________________\nTrain on 60000 samples, validate on 10000 samples\nEpoch 1/100\n60000/60000 [==============================] - 5s - loss: 6.9768 - acc: 0.0942 - val_loss: 4.3748 - val_acc: 0.0978\nEpoch 2/100\n60000/60000 [==============================] - 5s - loss: 3.3634 - acc: 0.0858 - val_loss: 2.5592 - val_acc: 0.1437\nEpoch 3/100\n60000/60000 [==============================] - 6s - loss: 2.5739 - acc: 0.0908 - val_loss: 2.3753 - val_acc: 0.0980\nEpoch 4/100\n60000/60000 [==============================] - 6s - loss: 2.3633 - acc: 0.1137 - val_loss: 2.2549 - val_acc: 0.1373\nEpoch 5/100\n60000/60000 [==============================] - 6s - loss: 2.2353 - acc: 0.1205 - val_loss: 2.1695 - val_acc: 0.1765\nEpoch 6/100\n60000/60000 [==============================] - 6s - loss: 2.1458 - acc: 0.1797 - val_loss: 2.0833 - val_acc: 0.1997\nEpoch 7/100\n60000/60000 [==============================] - 7s - loss: 2.0661 - acc: 0.2243 - val_loss: 2.0146 - val_acc: 0.2675\nEpoch 8/100\n60000/60000 [==============================] - 7s - loss: 1.9997 - acc: 0.2866 - val_loss: 1.9549 - val_acc: 0.3238\nEpoch 9/100\n60000/60000 [==============================] - 7s - loss: 1.9400 - acc: 0.3411 - val_loss: 1.8985 - val_acc: 0.3675\nEpoch 10/100\n60000/60000 [==============================] - 7s - loss: 1.8843 - acc: 0.3772 - val_loss: 1.8459 - val_acc: 0.4216\nEpoch 11/100\n60000/60000 [==============================] - 7s - loss: 1.8285 - acc: 0.4098 - val_loss: 1.7896 - val_acc: 0.4348\nEpoch 12/100\n60000/60000 [==============================] - 7s - loss: 1.7714 - acc: 0.4373 - val_loss: 1.7330 - val_acc: 0.4615\nEpoch 13/100\n60000/60000 [==============================] - 6s - loss: 1.7167 - acc: 0.4590 - val_loss: 1.6803 - val_acc: 0.4677\nEpoch 14/100\n60000/60000 [==============================] - 7s - loss: 1.6663 - acc: 0.4762 - val_loss: 1.6348 - val_acc: 0.4737\nEpoch 15/100\n60000/60000 [==============================] - 7s - loss: 1.6211 - acc: 0.4913 - val_loss: 1.5894 - val_acc: 0.5145\nEpoch 16/100\n60000/60000 [==============================] - 6s - loss: 1.5786 - acc: 0.5081 - val_loss: 1.5476 - val_acc: 0.5200\nEpoch 17/100\n60000/60000 [==============================] - 7s - loss: 1.5394 - acc: 0.5226 - val_loss: 1.5062 - val_acc: 0.5409\nEpoch 18/100\n60000/60000 [==============================] - 7s - loss: 1.5026 - acc: 0.5362 - val_loss: 1.4688 - val_acc: 0.5518\nEpoch 19/100\n60000/60000 [==============================] - 7s - loss: 1.4656 - acc: 0.5511 - val_loss: 1.4327 - val_acc: 0.5611\nEpoch 20/100\n60000/60000 [==============================] - 7s - loss: 1.4324 - acc: 0.5623 - val_loss: 1.3981 - val_acc: 0.5679\nEpoch 21/100\n60000/60000 [==============================] - 7s - loss: 1.3992 - acc: 0.5735 - val_loss: 1.3634 - val_acc: 0.5926\nEpoch 22/100\n60000/60000 [==============================] - 7s - loss: 1.3662 - acc: 0.5861 - val_loss: 1.3278 - val_acc: 0.6079\nEpoch 23/100\n60000/60000 [==============================] - 7s - loss: 1.3357 - acc: 0.5987 - val_loss: 1.2963 - val_acc: 0.6019\nEpoch 24/100\n60000/60000 [==============================] - 7s - loss: 1.3060 - acc: 0.6063 - val_loss: 1.2654 - val_acc: 0.6233\nEpoch 25/100\n60000/60000 [==============================] - 7s - loss: 1.2761 - acc: 0.6216 - val_loss: 1.2373 - val_acc: 0.6224\nEpoch 26/100\n60000/60000 [==============================] - 7s - loss: 1.2490 - acc: 0.6269 - val_loss: 1.2076 - val_acc: 0.6373\nEpoch 27/100\n60000/60000 [==============================] - 6s - loss: 1.2217 - acc: 0.6381 - val_loss: 1.1771 - val_acc: 0.6549\nEpoch 28/100\n60000/60000 [==============================] - 7s - loss: 1.1946 - acc: 0.6498 - val_loss: 1.1507 - val_acc: 0.6625\nEpoch 29/100\n60000/60000 [==============================] - 7s - loss: 1.1705 - acc: 0.6570 - val_loss: 1.1220 - val_acc: 0.6878\nEpoch 30/100\n60000/60000 [==============================] - 6s - loss: 1.1457 - acc: 0.6672 - val_loss: 1.0987 - val_acc: 0.6810\nEpoch 31/100\n60000/60000 [==============================] - 7s - loss: 1.1228 - acc: 0.6702 - val_loss: 1.0761 - val_acc: 0.7052\nEpoch 32/100\n60000/60000 [==============================] - 7s - loss: 1.1012 - acc: 0.6811 - val_loss: 1.0534 - val_acc: 0.6992\nEpoch 33/100\n60000/60000 [==============================] - 7s - loss: 1.0790 - acc: 0.6898 - val_loss: 1.0358 - val_acc: 0.6848\nEpoch 34/100\n60000/60000 [==============================] - 7s - loss: 1.0602 - acc: 0.6938 - val_loss: 1.0097 - val_acc: 0.7075\nEpoch 35/100\n60000/60000 [==============================] - 7s - loss: 1.0395 - acc: 0.7027 - val_loss: 0.9923 - val_acc: 0.7181\nEpoch 36/100\n60000/60000 [==============================] - 6s - loss: 1.0215 - acc: 0.7089 - val_loss: 0.9722 - val_acc: 0.7313\nEpoch 37/100\n60000/60000 [==============================] - 7s - loss: 1.0040 - acc: 0.7160 - val_loss: 0.9545 - val_acc: 0.7237\nEpoch 38/100\n60000/60000 [==============================] - 7s - loss: 0.9888 - acc: 0.7174 - val_loss: 0.9346 - val_acc: 0.7467\nEpoch 39/100\n60000/60000 [==============================] - 7s - loss: 0.9706 - acc: 0.7267 - val_loss: 0.9182 - val_acc: 0.7474\nEpoch 40/100\n60000/60000 [==============================] - 6s - loss: 0.9554 - acc: 0.7314 - val_loss: 0.9063 - val_acc: 0.7419\nEpoch 41/100\n60000/60000 [==============================] - 7s - loss: 0.9402 - acc: 0.7340 - val_loss: 0.8900 - val_acc: 0.7597\nEpoch 42/100\n60000/60000 [==============================] - 6s - loss: 0.9273 - acc: 0.7399 - val_loss: 0.8740 - val_acc: 0.7593\nEpoch 43/100\n60000/60000 [==============================] - 7s - loss: 0.9132 - acc: 0.7449 - val_loss: 0.8614 - val_acc: 0.7590\nEpoch 44/100\n60000/60000 [==============================] - 7s - loss: 0.9001 - acc: 0.7478 - val_loss: 0.8468 - val_acc: 0.7638\nEpoch 45/100\n60000/60000 [==============================] - 7s - loss: 0.8875 - acc: 0.7530 - val_loss: 0.8359 - val_acc: 0.7683\nEpoch 46/100\n60000/60000 [==============================] - 7s - loss: 0.8764 - acc: 0.7545 - val_loss: 0.8251 - val_acc: 0.7746\nEpoch 47/100\n60000/60000 [==============================] - 6s - loss: 0.8659 - acc: 0.7582 - val_loss: 0.8163 - val_acc: 0.7788\nEpoch 48/100\n60000/60000 [==============================] - 6s - loss: 0.8557 - acc: 0.7617 - val_loss: 0.8051 - val_acc: 0.7811\nEpoch 49/100\n60000/60000 [==============================] - 6s - loss: 0.8462 - acc: 0.7627 - val_loss: 0.7947 - val_acc: 0.7791\nEpoch 50/100\n60000/60000 [==============================] - 6s - loss: 0.8383 - acc: 0.7662 - val_loss: 0.7873 - val_acc: 0.7821\nEpoch 51/100\n60000/60000 [==============================] - 7s - loss: 0.8262 - acc: 0.7707 - val_loss: 0.7774 - val_acc: 0.7849\nEpoch 52/100\n60000/60000 [==============================] - 7s - loss: 0.8174 - acc: 0.7722 - val_loss: 0.7658 - val_acc: 0.7945\nEpoch 53/100\n60000/60000 [==============================] - 6s - loss: 0.8089 - acc: 0.7752 - val_loss: 0.7568 - val_acc: 0.7924\nEpoch 54/100\n60000/60000 [==============================] - 6s - loss: 0.7997 - acc: 0.7789 - val_loss: 0.7467 - val_acc: 0.7988\nEpoch 55/100\n60000/60000 [==============================] - 6s - loss: 0.7913 - acc: 0.7809 - val_loss: 0.7396 - val_acc: 0.8003\nEpoch 56/100\n60000/60000 [==============================] - 6s - loss: 0.7842 - acc: 0.7834 - val_loss: 0.7320 - val_acc: 0.7993\nEpoch 57/100\n60000/60000 [==============================] - 6s - loss: 0.7758 - acc: 0.7841 - val_loss: 0.7230 - val_acc: 0.8034\nEpoch 58/100\n60000/60000 [==============================] - 7s - loss: 0.7696 - acc: 0.7849 - val_loss: 0.7161 - val_acc: 0.8054\nEpoch 59/100\n60000/60000 [==============================] - 6s - loss: 0.7612 - acc: 0.7893 - val_loss: 0.7125 - val_acc: 0.8020\nEpoch 60/100\n60000/60000 [==============================] - 6s - loss: 0.7543 - acc: 0.7921 - val_loss: 0.7062 - val_acc: 0.8066\nEpoch 61/100\n60000/60000 [==============================] - 7s - loss: 0.7487 - acc: 0.7917 - val_loss: 0.6959 - val_acc: 0.8111\nEpoch 62/100\n60000/60000 [==============================] - 7s - loss: 0.7413 - acc: 0.7949 - val_loss: 0.6893 - val_acc: 0.8127\nEpoch 63/100\n60000/60000 [==============================] - 7s - loss: 0.7340 - acc: 0.7984 - val_loss: 0.6845 - val_acc: 0.8123\nEpoch 64/100\n60000/60000 [==============================] - 7s - loss: 0.7280 - acc: 0.7985 - val_loss: 0.6766 - val_acc: 0.8143\nEpoch 65/100\n60000/60000 [==============================] - 7s - loss: 0.7225 - acc: 0.7997 - val_loss: 0.6694 - val_acc: 0.8178\nEpoch 66/100\n60000/60000 [==============================] - 6s - loss: 0.7170 - acc: 0.8009 - val_loss: 0.6652 - val_acc: 0.8184\nEpoch 67/100\n60000/60000 [==============================] - 6s - loss: 0.7120 - acc: 0.8022 - val_loss: 0.6617 - val_acc: 0.8182\nEpoch 68/100\n60000/60000 [==============================] - 6s - loss: 0.7068 - acc: 0.8032 - val_loss: 0.6553 - val_acc: 0.8237\nEpoch 69/100\n60000/60000 [==============================] - 6s - loss: 0.7014 - acc: 0.8053 - val_loss: 0.6489 - val_acc: 0.8224\nEpoch 70/100\n60000/60000 [==============================] - 6s - loss: 0.6937 - acc: 0.8083 - val_loss: 0.6426 - val_acc: 0.8230\nEpoch 71/100\n60000/60000 [==============================] - 6s - loss: 0.6879 - acc: 0.8100 - val_loss: 0.6414 - val_acc: 0.8223\nEpoch 72/100\n60000/60000 [==============================] - 7s - loss: 0.6869 - acc: 0.8084 - val_loss: 0.6366 - val_acc: 0.8258\nEpoch 73/100\n60000/60000 [==============================] - 6s - loss: 0.6800 - acc: 0.8115 - val_loss: 0.6277 - val_acc: 0.8274\nEpoch 74/100\n60000/60000 [==============================] - 6s - loss: 0.6751 - acc: 0.8137 - val_loss: 0.6249 - val_acc: 0.8278\nEpoch 75/100\n60000/60000 [==============================] - 7s - loss: 0.6702 - acc: 0.8148 - val_loss: 0.6212 - val_acc: 0.8285\nEpoch 76/100\n60000/60000 [==============================] - 6s - loss: 0.6669 - acc: 0.8151 - val_loss: 0.6162 - val_acc: 0.8301\nEpoch 77/100\n60000/60000 [==============================] - 7s - loss: 0.6610 - acc: 0.8176 - val_loss: 0.6136 - val_acc: 0.8268\nEpoch 78/100\n60000/60000 [==============================] - 7s - loss: 0.6565 - acc: 0.8184 - val_loss: 0.6097 - val_acc: 0.8290\nEpoch 79/100\n60000/60000 [==============================] - 7s - loss: 0.6518 - acc: 0.8195 - val_loss: 0.6002 - val_acc: 0.8342\nEpoch 80/100\n60000/60000 [==============================] - 7s - loss: 0.6455 - acc: 0.8223 - val_loss: 0.5985 - val_acc: 0.8351\nEpoch 81/100\n60000/60000 [==============================] - 7s - loss: 0.6423 - acc: 0.8238 - val_loss: 0.5986 - val_acc: 0.8324\nEpoch 82/100\n60000/60000 [==============================] - 8s - loss: 0.6404 - acc: 0.8232 - val_loss: 0.5925 - val_acc: 0.8345\nEpoch 83/100\n60000/60000 [==============================] - 7s - loss: 0.6359 - acc: 0.8245 - val_loss: 0.5882 - val_acc: 0.8350\nEpoch 84/100\n60000/60000 [==============================] - 7s - loss: 0.6314 - acc: 0.8262 - val_loss: 0.5828 - val_acc: 0.8401\nEpoch 85/100\n60000/60000 [==============================] - 7s - loss: 0.6274 - acc: 0.8269 - val_loss: 0.5807 - val_acc: 0.8410\nEpoch 86/100\n60000/60000 [==============================] - 7s - loss: 0.6240 - acc: 0.8278 - val_loss: 0.5744 - val_acc: 0.8419\nEpoch 87/100\n60000/60000 [==============================] - 7s - loss: 0.6190 - acc: 0.8294 - val_loss: 0.5707 - val_acc: 0.8446\nEpoch 88/100\n60000/60000 [==============================] - 7s - loss: 0.6166 - acc: 0.8304 - val_loss: 0.5678 - val_acc: 0.8433\nEpoch 89/100\n60000/60000 [==============================] - 7s - loss: 0.6120 - acc: 0.8313 - val_loss: 0.5652 - val_acc: 0.8433\nEpoch 90/100\n60000/60000 [==============================] - 7s - loss: 0.6082 - acc: 0.8322 - val_loss: 0.5585 - val_acc: 0.8501\nEpoch 91/100\n60000/60000 [==============================] - 6s - loss: 0.6042 - acc: 0.8342 - val_loss: 0.5562 - val_acc: 0.8522\nEpoch 92/100\n60000/60000 [==============================] - 7s - loss: 0.6035 - acc: 0.8336 - val_loss: 0.5552 - val_acc: 0.8471\nEpoch 93/100\n60000/60000 [==============================] - 7s - loss: 0.5998 - acc: 0.8350 - val_loss: 0.5585 - val_acc: 0.8478\nEpoch 94/100\n60000/60000 [==============================] - 7s - loss: 0.5968 - acc: 0.8343 - val_loss: 0.5460 - val_acc: 0.8515\nEpoch 95/100\n60000/60000 [==============================] - 7s - loss: 0.5894 - acc: 0.8379 - val_loss: 0.5444 - val_acc: 0.8518\nEpoch 96/100\n60000/60000 [==============================] - 8s - loss: 0.5874 - acc: 0.8382 - val_loss: 0.5442 - val_acc: 0.8492\nEpoch 97/100\n60000/60000 [==============================] - 7s - loss: 0.5847 - acc: 0.8388 - val_loss: 0.5379 - val_acc: 0.8563\nEpoch 98/100\n60000/60000 [==============================] - 7s - loss: 0.5823 - acc: 0.8391 - val_loss: 0.5384 - val_acc: 0.8563\nEpoch 99/100\n60000/60000 [==============================] - 7s - loss: 0.5815 - acc: 0.8391 - val_loss: 0.5382 - val_acc: 0.8512\nEpoch 100/100\n60000/60000 [==============================] - 7s - loss: 0.5796 - acc: 0.8395 - val_loss: 0.5268 - val_acc: 0.8584\n" ] ], [ [ "## Save the Class Activation Model Weights", "_____no_output_____" ] ], [ [ "import cv2\n\nfrom keras.layers import Layer, Lambda\ndef global_average_pooling(x: Layer):\n return K.mean(x, axis = (2,3))\n\ndef global_average_pooling_shape(input_shape):\n # return only the first two dimensions (batch size and number of filters)\n return input_shape[0:2]\n\ndef build_global_average_pooling_layer(function, output_shape):\n return Lambda(pooling_function, output_shape)\n\n\ndef get_output_layer(model, layer_name):\n # get the symbolic outputs of each \"key\" layer (we gave them unique names).\n layer_dict = dict([(layer.name, layer) for layer in model.layers])\n layer = layer_dict[layer_name]\n return layer", "_____no_output_____" ], [ "# persist mode\n\nsave_filepath: str = \"basic_cam.h5\"\nmodel.save(save_filepath)", "_____no_output_____" ], [ "first_image = X_train[5]\nfirst_image = first_image.reshape(28,28,1)\nimg = np.array(first_image).reshape(1, 28, 28, 1)\nimg.shape\nplt.imshow(img.reshape((28,28)))\n#img = np.array([np.transpose(np.float32(first_image), (2, 0, 1))])", "_____no_output_____" ] ], [ [ "## Load Basic Model\n(since the model files are so large, they cannot be pushed to Github- just email me for a copy of the `.h5` model files)", "_____no_output_____" ] ], [ [ "from keras.models import load_model\n\nmodel = load_model(\"basic_cam.h5\")", "_____no_output_____" ], [ "dense_10_layer: Layer = model.layers[-1]\ndense_10_weights = dense_10_layer.get_weights()[0]\nprint(f\"Dense 10 weights: {dense_10_weights.shape}\")\ndense_128_layer: Layer = model.layers[-2]\ndense_128_weights = dense_128_layer.get_weights()[0]\nprint(f\"Dense 128 weights: {dense_128_weights.shape}\")", "_____no_output_____" ] ], [ [ "## Map the Final Class Activation Map Back to the Original Input Shapes and Visualize", "_____no_output_____" ] ], [ [ "import keras.backend as K\nclass_weights = model.layers[-1].get_weights()[0]\nfinal_conv_layer = get_output_layer(model, \"conv2d_1\")\n\nget_output = K.function([model.layers[0].input], [final_conv_layer.output, model.layers[-1].output])\n[conv_outputs, predictions] = get_output([img])\nconv_outputs = conv_outputs[0,:,:,:]\nprint(conv_outputs.shape)\nprint(class_weights.shape)\n\ndef make_cam(conv_outputs, class_weights, original_shape, target_class):\n cam = np.zeros(dtype=np.float32, shape = conv_outputs.shape[0:2])\n for i, w in enumerate(class_weights[:, target_class]):\n cam += w * conv_outputs[:,:,i]\n cam /= np.max(cam)\n return cv2.resize(cam, (28, 28))\n\ndef make_heatmap(cam):\n heatmap = cv2.applyColorMap(np.uint8(255*cam), cv2.COLORMAP_JET)\n heatmap[np.where(cam < 0.1)] = 0\n return heatmap\n\n\ncam = make_cam(conv_outputs, class_weights, original_shape=(28,28), target_class=2)\nfalse_cam = make_cam(conv_outputs, class_weights, original_shape=(28,28), target_class=4)\nfalse2_cam = make_cam(conv_outputs, class_weights, original_shape=(28,28), target_class=5)\n\nheatmap = make_heatmap(cam)\nfalse_heatmap = make_heatmap(false_cam)\nfalse2_heatmap = make_heatmap(false2_cam)\n\nnew_img = heatmap*0.5 + img\nfinal_img = new_img.reshape((28,28,3))\n\n# f, axarr = plt.subplots(2,1)\n# axarr[0,0].imshow(heatmap)\n# axarr[0,1].imshow(img.reshape(28,28))\n\nimgs = [heatmap, img.reshape(28,28)]\nfig, axes = plt.subplots(nrows=1, ncols=4, figsize=(15, 15))\naxes[0].imshow(heatmap)\naxes[0].set_title(\"Activation Map for 2\")\naxes[1].imshow(false_heatmap)\naxes[1].set_title(\"Activation Map for 4\")\naxes[2].imshow(false2_heatmap)\naxes[2].set_title(\"Activation Map for 5\")\naxes[3].imshow(img.reshape((28,28)))\naxes[3].set_title(\"True Image\")", "(24, 24, 32)\n(32, 10)\n" ], [ "import matplotlib.pyplot as plt\nplt.imshow(img.reshape((28,28)))", "_____no_output_____" ], [ "cam /= np.max(cam)", "_____no_output_____" ], [ "import keras.backend as K\nfrom tensorflow.python.framework.ops import Tensor\n\ndense_weights = model.layers[-2].get_weights()[0]\n\nsoftmax_weights = model.layers[-1].get_weights()[0]\n\ndense_weights.shape\nsoftmax_weights.shape\n\nfinal_conv_layer = get_output_layer(model, \"conv2d_28\")\nfinal_conv_layer.output", "_____no_output_____" ], [ "import keras.backend as K\nfrom tensorflow.python.framework.ops import Tensor\nclass_weights: np.ndarray = model.layers[-1].get_weights()[0] # class weights is of shape 32 x 10 (number of filter outputs x classes)\nprint(f\"Class weights is shape {class_weights.shape}\")\nfinal_conv_layer: Conv2D = get_output_layer(model, \"conv2d_28\")\n\ninput_tensor: Tensor = model.layers[0].input\nfinal_conv_layer_output: Tensor = final_conv_layer.output\nmodel_class_weights: Tensor = model.layers[-1].output\n \n# K.function is a function factory that accepts arbitrary input layers and outputs arbitrary output layers\nget_output = K.function([input_tensor], [final_conv_layer_output, model_class_weights])\n\n[conv_outputs, predictions] = get_output([img])\nprint(\"Conv2D output shape:\", conv_outputs.shape) # should match the shape of the outputs from the Conv2D layer\nprint(\"Predictions:\", predictions.shape)\nnp.argmax(predictions)\n\nconv_outputs = conv_outputs[0,:,:,:]\n# [conv_outputs, predictions] = get_output([img])\n# conv_outputs = conv_outputs[0, :, :, :]", "Class weights is shape (128, 10)\nConv2D output shape: (1, 8, 8, 64)\nPredictions: (1, 10)\n" ], [ "class_weights.shape", "_____no_output_____" ], [ "# Create the class activation map\n\nclass_activation_map = np.zeros(dtype=np.float32, shape=conv_outputs.shape[1:3])\nclass_activation_map.shape", "_____no_output_____" ], [ "#Reshape to the network input shape (3, w, h).\nimg = np.array([np.transpose(np.float32(original_img), (2, 0, 1))])\n\n#Get the 512 input weights to the softmax.\nclass_weights = model.layers[-1].get_weights()[0]\nfinal_conv_layer = get_output_layer(model, \"conv5_3\")\nget_output = K.function([model.layers[0].input], \\\n [final_conv_layer.output, \nmodel.layers[-1].output])\n[conv_outputs, predictions] = get_output([img])\nconv_outputs = conv_outputs[0, :, :, :]\n\n#Create the class activation map.\ncam = np.zeros(dtype = np.float32, shape = conv_outputs.shape[1:3])\ntarget_class = 1\nfor i, w in enumerate(class_weights[:, target_class]):\n cam += w * conv_outputs[i, :, :]", "_____no_output_____" ] ], [ [ "# Everything Below This Section Is Doodling", "_____no_output_____" ] ], [ [ "image_path = \noriginal_img = cv2.imread(image_path, 1)\nwidth, height, _ = original_image.shape", "_____no_output_____" ], [ "def build_vanilla_cnn(filters_layer1:int, filters_layer2:int, kernel_size:int, input_dims: GrayScaleImageShape)-> Model:\n inputs: Tensor = Input(shape=input_dims)\n x: Tensor = Conv2D(filters=filters_layer1, kernel_size=kernel_size, activation='relu')(inputs)\n x: Tensor = Conv2D(filters=filters_layer2, kernel_size=kernel_size, activation='relu')(x)\n x: Tensor = build_global_average_pooling_layer(global_average_pooling, )\n predictions = Dense(K, activation=\"softmax\")(x)\n print(predictions)\n\n #compile model using accuracy to measure model performance\n model: Model = Model(inputs=inputs, outputs=predictions)\n model.compile(optimizer='adam', loss=\"categorical_crossentropy\", metrics=['accuracy'])\n return model", "_____no_output_____" ], [ "from keras.layers import merge\n\ndef build_model(input_dim):\n inputs = Input(shape=input_dim)\n\n # ATTENTION PART STARTS HERE\n attention_probs = Dense(input_dim, activation='softmax', name='attention_vec')(inputs)\n attention_mul = merge([inputs, attention_probs], output_shape=32, name='attention_mul', mode='mul')\n # ATTENTION PART FINISHES HERE\n\n attention_mul = Dense(64)(attention_mul)\n output = Dense(1, activation='sigmoid')(attention_mul)\n model = Model(input=[inputs], output=output)\n return model\n\ninputs = Input(shape=input_dims)\nattention_probs = Dense(input_dims, activation='softmax', name='attention_vec')(inputs)", "_____no_output_____" ] ], [ [ "## Compile and Fit Model", "_____no_output_____" ] ], [ [ "X_train.reshape((60000,1,28,28))\n\ndef expand_tensor_shape(X_train: np.ndarray)-> np.ndarray:\n new_shape: Tuple = X_train.shape + (1,)\n print(f\"Expanding shape from {X_train.shape} to {new_shape}\")\n return X_train.reshape(new_shape)\n\nX_train_expanded: np.ndarray = expand_tensor_shape(X_train)\nX_test_expanded: np.ndarray = expand_tensor_shape(X_test)", "Expanding shape from (60000, 28, 28) to (60000, 28, 28, 1)\nExpanding shape from (10000, 28, 28) to (10000, 28, 28, 1)\n" ] ], [ [ "# FEI Face Dataset", "_____no_output_____" ] ], [ [ "from PIL.JpegImagePlugin import JpegImageFile\n\nimage: JpegImageFile = load_img('1-01.jpg')", "_____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", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb24a58273944906873559fa995168e2df103b67
38,402
ipynb
Jupyter Notebook
seurat_dimension_reduction/main_regression_feature_expansion.ipynb
xiaoyanLi629/Finance_quant_machine_learning
a0a3a3f67aaff1f1250172664d9f556beadc94c7
[ "MIT" ]
null
null
null
seurat_dimension_reduction/main_regression_feature_expansion.ipynb
xiaoyanLi629/Finance_quant_machine_learning
a0a3a3f67aaff1f1250172664d9f556beadc94c7
[ "MIT" ]
null
null
null
seurat_dimension_reduction/main_regression_feature_expansion.ipynb
xiaoyanLi629/Finance_quant_machine_learning
a0a3a3f67aaff1f1250172664d9f556beadc94c7
[ "MIT" ]
null
null
null
47.882793
1,503
0.589917
[ [ [ "import os\nimport glob\nimport math\nimport time\nimport pandas as pd\nimport numpy as np\nimport scipy as sc\nfrom sklearn.model_selection import KFold\nimport warnings\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import TensorDataset, DataLoader\nimport torch\nimport torch.nn as nn\nimport random\nimport seaborn as sns; sns.set_theme()\nimport torch.nn.functional as F\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom matplotlib.pyplot import figure\nfrom IPython import display\nfrom pandas.plotting import scatter_matrix\nfrom sklearn.metrics import r2_score\nfrom sklearn import svm\nfrom numpy import std\nfrom numpy import mean\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import RepeatedStratifiedKFold\nfrom matplotlib import cm\nfrom sklearn.metrics import confusion_matrix", "_____no_output_____" ], [ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")", "_____no_output_____" ], [ "warnings.filterwarnings('ignore')\npd.set_option('max_columns', 300)", "_____no_output_____" ], [ "train_test_seurat = pd.read_csv('./integrate.csv')", "_____no_output_____" ], [ "train_test_seurat = train_test_seurat.T", "_____no_output_____" ], [ "train_test_seurat_std = train_test_seurat.std()\ncolumn_names = list(train_test_seurat.columns)\ncolumns_remove = []\nfor i in range(train_test_seurat.shape[1]):\n if train_test_seurat_std[i] == 0:\n columns_remove.append(column_names[i])", "_____no_output_____" ], [ "train_test_seurat = train_test_seurat.drop(columns_remove, axis=1)", "_____no_output_____" ], [ "train_test_seurat[columns_remove[0]] = train_test_seurat.iloc[:, 0]", "_____no_output_____" ], [ "train_test_seurat.shape", "_____no_output_____" ], [ "train_seurat = train_test_seurat.iloc[:90000, :]\ntest_seurat = train_test_seurat.iloc[90000:, :]", "_____no_output_____" ] ], [ [ "Load train and test data", "_____no_output_____" ], [ "# 1. Load data and preprocessing", "_____no_output_____" ], [ "## 1.1 Load train and test data", "_____no_output_____" ] ], [ [ "train = pd.read_csv('./MLR_Project_train.csv')\ntest = pd.read_csv('./MLR_Project_test.csv')", "_____no_output_____" ] ], [ [ "Show the data format and dimension", "_____no_output_____" ] ], [ [ "train.head()", "_____no_output_____" ], [ "test.head()", "_____no_output_____" ] ], [ [ "## 1.3 Show the maximum return of train and test", "_____no_output_____" ] ], [ [ "train_max = np.sum(train['TARGET'][train['TARGET']>0])\ntest_max = np.sum(test['TARGET'][test['TARGET']>0])\n\nprint('Maximum return of training set:', train_max)\nprint('Maximum return of testing set:', test_max)", "_____no_output_____" ], [ "reg = Ridge(alpha=0.5).fit(pd.DataFrame(train_seurat.iloc[:, :]), train['TARGET'])\npred = reg.predict(pd.DataFrame(train_seurat.iloc[:, :]))\n\npred_test = reg.predict(pd.DataFrame(test_seurat.iloc[:, :]))\n\ntrain_res = np.sum(train['TARGET'][pred>0])\ntest_res = np.sum(test['TARGET'][pred_test>0])", "_____no_output_____" ], [ "print(f'Train naive random selection percentage return: {train_res/train_max*100}%')\nprint(f'Test naive random selection percentage return: {test_res/test_max*100}%')", "_____no_output_____" ] ], [ [ "### 1.3.1 Remove the Unnamed columns in dataframe", "_____no_output_____" ] ], [ [ "train = train.loc[:, ~train.columns.str.contains('^Unnamed')]\ntest = test.loc[:, ~test.columns.str.contains('^Unnamed')]", "_____no_output_____" ], [ "train.shape", "_____no_output_____" ], [ "train_ = pd.DataFrame()\n\nfor i in range(train.shape[1]-1):\n for j in range(train.shape[1]-1):\n train_[str(i)+'_'+str(j)+'_feat'] = train.iloc[:, i] * train.iloc[:, j]\n \ntrain_target = pd.DataFrame(train['TARGET'])\n\ntrain = train.drop(['TARGET'], axis = 1)\n\ntrain = pd.concat([train, train_], axis = 1)\n\ntrain['TARGET'] = train_target", "_____no_output_____" ], [ "test_ = pd.DataFrame()\n\nfor i in range(test.shape[1]-1):\n for j in range(test.shape[1]-1):\n test_[str(i)+'_'+str(j)+'_feat'] = test.iloc[:, i] * test.iloc[:, j]\n \ntest_target = pd.DataFrame(test['TARGET'])\n\ntest = test.drop(['TARGET'], axis = 1)\n\ntest = pd.concat([test, test_], axis = 1)\n\ntest['TARGET'] = test_target", "_____no_output_____" ] ], [ [ "## 5.5 Autoencoder Resnet model", "_____no_output_____" ] ], [ [ "input_features = train.drop(['TARGET'], axis=1).to_numpy()\noutput_features = pd.DataFrame((np.sign(train['TARGET'])+1)//2).to_numpy()\n\nX_test = test.drop(['TARGET'], axis=1).to_numpy()\nY_test = pd.DataFrame((np.sign(test['TARGET'])+1)//2).to_numpy()\n\nX_train, X_val, Y_train, Y_val = train_test_split(input_features, output_features, test_size=0.2, random_state=42)\n\n####\ntrain_data, val_data = train_test_split(train, test_size=0.2, random_state=42)\ntest_data = test\n####\n\nauto_train_max = np.sum(train_data['TARGET'][train_data['TARGET']>0])\nauto_val_max = np.sum(val_data['TARGET'][val_data['TARGET']>0])\nauto_test_max = np.sum(test['TARGET'][test['TARGET']>0])\n\nprint('Train X shape:', X_train.shape)\nprint('Validation X shape:', X_val.shape)\nprint('Test X shape:', X_test.shape)\n\nprint('Train Y shape:', Y_train.shape)\nprint('Val Y shape:', Y_val.shape)\nprint('Test Y shape:', Y_test.shape)\n\nprint('train_max:', auto_train_max)\nprint('val_max:', auto_val_max)\nprint('test_max:', auto_test_max)", "_____no_output_____" ], [ "train_input = torch.from_numpy(X_train)\ntrain_output = torch.from_numpy(Y_train)\nval_input = torch.from_numpy(X_val)\nval_output = torch.from_numpy(Y_val)\ntest_input = torch.from_numpy(X_test)\ntest_output = torch.from_numpy(Y_test)\n\ntrain_input = torch.unsqueeze(train_input, 1)\nval_input = torch.unsqueeze(val_input, 1)\ntest_input = torch.unsqueeze(test_input, 1)\n\ntrain_input = train_input.float()\ntrain_output = train_output.float()\nval_input = val_input.float()\nval_output = val_output.float()\ntest_input = test_input.float()\ntest_output = test_output.float()\n\ninput_feature = train_input.shape[1]\noutput_feature = 1\n\n# print('input_feature:', input_feature)\n# print('output_feature:', output_feature)", "_____no_output_____" ], [ "train_input = train_input.to(device)\ntrain_output = train_output.to(device)\nval_input = val_input.to(device)\nval_output = val_output.to(device)\ntest_input = test_input.to(device)\ntest_output = test_output.to(device)", "_____no_output_____" ], [ "def seed_everything(seed=1234):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n\nseed_everything()", "_____no_output_____" ], [ "# auto-encoder model\n# base model\nclass Autoencoder(nn.Module):\n def __init__(self):\n super(Autoencoder, self).__init__()\n self.linear1 = nn.Linear(input_feature, input_feature//2)\n self.linear2 = nn.Linear(input_feature//2, input_feature//4)\n self.linear3 = nn.Linear(input_feature//4, input_feature//16)\n self.linear4 = nn.Linear(input_feature//16, input_feature//16)\n \n self.linear5 = nn.Linear(input_feature//16, input_feature//16)\n self.linear6 = nn.Linear(input_feature//16, input_feature//16)\n \n self.batchnorm_1 = nn.BatchNorm1d(input_feature//2)\n self.batchnorm_2 = nn.BatchNorm1d(input_feature//4)\n self.batchnorm_3 = nn.BatchNorm1d(input_feature//16)\n self.linear = nn.Linear(input_feature//16, 1)\n \n nn.init.constant_(self.linear1.weight, 0.1)\n nn.init.constant_(self.linear2.weight, 0.1)\n nn.init.constant_(self.linear3.weight, 0.1)\n nn.init.constant_(self.linear4.weight, 0.1)\n nn.init.constant_(self.linear.weight, 0.1)\n self.relu = nn.ReLU()\n# self.leakyrelu = nn.LeakyReLU(0.1)\n self.dropout = nn.Dropout(0.15)\n \n self.softmax = nn.Softmax()\n \n\n def forward(self, x):\n x = self.linear1(x)\n# x = self.batchnorm_1(x)\n x = self.relu(x)\n x = self.dropout(x)\n \n x = self.linear2(x)\n# x = self.batchnorm_2(x)\n x = self.relu(x)\n# x = self.dropout(x)\n \n x = self.linear3(x)\n# x = self.batchnorm_3(x)\n x = self.relu(x)\n \n x = self.linear6(x)\n x = self.relu(x)\n \n output = self.linear(x)\n \n return output.float()", "_____no_output_____" ], [ "batch_size = 100000\ntrain_ds = TensorDataset(train_input, train_output)\ntrain_dl = DataLoader(train_ds, batch_size= batch_size, shuffle=False)", "_____no_output_____" ], [ "%matplotlib inline\ndef fit(num_epochs, model, loss_fn, train_input, train_output, val_input, val_output, test_input, test_output, model_path):\n best_loss = float('inf')\n train_pred_output = []\n val_pred_output = []\n train_error = []\n val_error = []\n test_error = []\n epochs = []\n \n train_returns = []\n val_returns = []\n test_returns = []\n \n train_sum = []\n val_sum = []\n test_sum = []\n\n for epoch in range(num_epochs):\n for x,y in train_dl:\n model = model.train()\n opt.zero_grad()\n pred = model(x)\n y = torch.reshape(y, (y.shape[0], 1))\n loss = loss_fn(pred, y)\n loss.backward()\n opt.step()\n\n if epoch % 50 == 0:\n \n model = model.eval()\n \n train_pred = model(train_input)\n train_pred_index = (torch.sign(train_pred)+1)//2\n train_output = torch.reshape(train_output, (train_output.shape[0], 1))\n train_loss = loss_fn(train_output, train_pred)\n # train_loss = loss_fn(train_pred, train_output.long().squeeze())\n train_loss = train_loss.cpu().detach().numpy()\n \n val_pred = model(val_input)\n val_pred_index = (torch.sign(val_pred)+1)//2\n val_output = torch.reshape(val_output, (val_output.shape[0], 1))\n val_loss = loss_fn(val_output, val_pred)\n # val_loss = loss_fn(val_pred, val_output.long().squeeze())\n val_loss = val_loss.cpu().detach().numpy()\n \n test_pred = model(test_input)\n test_pred_index = (torch.sign(test_pred)+1)//2\n test_output = torch.reshape(test_output, (test_output.shape[0], 1))\n test_loss = loss_fn(test_output, test_pred)\n # test_loss = loss_fn(test_pred, test_output.long().squeeze())\n test_loss = test_loss.cpu().detach().numpy()\n \n epochs.append(epoch)\n train_error.append(math.log(train_loss+1))\n val_error.append(math.log(val_loss+1))\n test_error.append(math.log(test_loss+1))\n \n# figure, ax = plt.subplots(1, 2, figsize = (20, 7))\n# ax = ax.flatten()\n \n# figure, ax = plt.subplots(1, 4, figsize = (22, 5))\n# ax = ax.flatten()\n \n# plt.grid(False)\n # train_conf = confusion_matrix(train_output, train_pred_index)\n# g1 = sns.heatmap(train_conf, cmap=\"YlGnBu\",cbar=False, ax=ax[0], annot = True)\n# g1.set_ylabel('True Target')\n# g1.set_xlabel('Predict Target')\n# g1.set_title('Train dataset')\n\n# plt.grid(False)\n # val_conf = confusion_matrix(val_output, val_pred_index)\n# g2 = sns.heatmap(val_conf, cmap=\"YlGnBu\",cbar=False, ax=ax[1], annot = True)\n# g2.set_ylabel('True Target')\n# g2.set_xlabel('Predict Target')\n# g2.set_title('Val dataset')\n \n# plt.grid(False)\n # test_conf = confusion_matrix(test_output, test_pred_index)\n# g3 = sns.heatmap(test_conf, cmap=\"YlGnBu\",cbar=False, ax=ax[2], annot = True)\n# g3.set_ylabel('True Target')\n# g3.set_xlabel('Predict Target')\n# g3.set_title('Test dataset')\n \n train_pred_np = train_pred_index.cpu().detach().numpy()\n train_output_np = train_output.cpu().detach().numpy()\n val_pred_np = val_pred_index.cpu().detach().numpy()\n val_output_np = val_output.cpu().detach().numpy()\n test_pred_np = test_pred_index.cpu().detach().numpy()\n test_output_np = test_output.cpu().detach().numpy()\n \n# train_max_value = max(max(train_output_np), max(train_pred_np))\n# train_min_value = min(min(train_output_np), min(train_pred_np))\n# val_max_value = max(max(val_output_np), max(val_pred_np))\n# val_min_value = min(min(val_output_np), min(val_pred_np))\n# test_max_value = max(max(test_output_np), max(test_pred_np))\n# test_min_value = min(min(test_output_np), min(test_pred_np))\n \n# ax[0].scatter(train_output_np, train_pred_np, s = 20, alpha=0.3, c='blue')\n# ax[1].scatter(val_output_np, val_pred_np, s = 20, alpha=0.3, c='red')\n# ax[2].scatter(test_output_np, test_pred_np, s = 20, alpha=0.3, c='green')\n \n# ax[0].plot(epochs, train_error, c='blue')\n# ax[0].plot(epochs, val_error, c='red')\n# ax[0].plot(epochs, test_error, c='green')\n# ax[0].set_title('Errors vs Epochs', fontsize=15)\n# ax[0].set_xlabel('Epoch', fontsize=10)\n# ax[0].set_ylabel('Errors', fontsize=10)\n\n# ax[0].legend(['train', 'valid', 'test'])\n \n# ax[0].set_xlim([train_min_value, train_max_value])\n# ax[0].set_ylim([train_min_value, train_max_value])\n# ax[0].set_title('Trainig data', fontsize=15)\n# ax[0].set_xlabel('Target', fontsize=10)\n# ax[0].set_ylabel('Prediction', fontsize=10)\n# ax[0].plot([train_min_value, train_max_value], [train_min_value, train_max_value], 'k-')\n \n# ax[1].set_xlim([val_min_value, val_max_value])\n# ax[1].set_ylim([val_min_value, val_max_value])\n# ax[1].set_title('Validation data', fontsize=15)\n# ax[1].set_xlabel('Target', fontsize=10)\n# ax[1].set_ylabel('Prediction', fontsize=10)\n# ax[1].plot([val_min_value, val_max_value], [val_min_value, val_max_value], 'k-')\n \n# ax[2].set_xlim([test_min_value, test_max_value])\n# ax[2].set_ylim([test_min_value, test_max_value])\n# ax[2].set_title('Testing data', fontsize=15)\n# ax[2].set_xlabel('Target', fontsize=10)\n# ax[2].set_ylabel('Prediction', fontsize=10)\n# ax[2].plot([test_min_value, test_max_value], [test_min_value, test_max_value], 'k-')\n \n# ax[3].plot(epochs, train_error, c='blue')\n# ax[3].plot(epochs, val_error, c='red')\n# ax[3].plot(epochs, test_error, c='green')\n# ax[3].set_title('Training and Validation error', fontsize=15)\n# ax[3].set_xlabel('Epochs', fontsize=10)\n# ax[3].set_ylabel('MSE error', fontsize=10)\n \n# display.clear_output(wait=True)\n# display.display(pl.gcf())\n \n# print('Epoch ', epoch, 'Train_loss: ', train_loss*1000, ' Validation_loss: ', val_loss*100, ' Test_loss: ', test_loss*100)\n # print(train_pred_np.shape, train_pred_np)\n # print(train_pred, train_pred_np)\n train_pred_np = np.squeeze(train_pred_np)\n val_pred_np = np.squeeze(val_pred_np)\n test_pred_np = np.squeeze(test_pred_np)\n \n train_res = np.sum(train_data['TARGET'][train_pred_np>0])\n train_output_check = np.squeeze(train_output_np)\n train_check = np.sum(train_data['TARGET'][train_output_check>0])\n \n val_res = np.sum(val_data['TARGET'][val_pred_np>0])\n val_output_check = np.squeeze(val_output_np)\n val_check = np.sum(val_data['TARGET'][val_output_check>0])\n \n test_res = np.sum(test_data['TARGET'][test_pred_np>0])\n test_output_check = np.squeeze(test_output_np)\n test_check = np.sum(test_data['TARGET'][test_output_check>0])\n \n# train_returns.append(train_res)\n# val_returns.append(val_res)\n# test_returns.append(test_res)\n \n# ax[1].plot(epochs, train_returns, c='blu`e')\n# ax[1].plot(epochs, val_returns, c='red')\n# ax[1].plot(epochs, test_returns, c='green')\n# ax[1].legend(['train', 'valid', 'test'])\n# ax[1].set_title('Return vs Epochs', fontsize=15)\n# ax[1].set_xlabel('Epoch', fontsize=10)\n# ax[1].set_ylabel('Returns', fontsize=10)\n\n# display.clear_output(wait=True)\n# display.display(pl.gcf())\n \n train_sum.append(train_res)\n val_sum.append(val_res)\n test_sum.append(test_res)\n # print(f'Checks: {train_check/auto_train_max*100}%, {val_check/auto_val_max*100}%, {test_check/auto_test_max*100}%')\n# print(f'Maximum sum train return {train_res}, Total train return: {auto_train_max}, Maximum train percentage return: {train_res/auto_train_max*100}%')\n# print(f'Maximum sum train return {val_res}, Total train return: {auto_val_max}, Maximum train percentage return: {val_res/auto_val_max*100}%')\n# print(f'Maximum sum test return {test_res}, Total test return: {auto_test_max}, Maximum test percentage return: {test_res/auto_test_max*100}%')\n# print('Epoch:', epoch, 'Train loss:', train_loss, 'Val loss:', val_loss, 'Test loss:', test_loss)\n print(f'Epoch: {epoch}, Train loss: {train_loss}, Train return: {train_res/auto_train_max*100}%, Val loss: {val_loss}, Val return: {val_res/auto_val_max*100}%, Test loss: {test_loss}, Test return: {test_res/auto_test_max*100}%')\n \n if val_loss < best_loss:\n torch.save(model.state_dict(), model_path)\n best_loss = val_loss\n \n# train_pred_output.append([train_pred.cpu().detach().numpy(), train_output.cpu().detach().numpy()])\n# val_pred_output.append([val_pred.cpu().detach().numpy(), val_output.cpu().detach().numpy()])\n return train_sum, val_sum, test_sum\n", "_____no_output_____" ], [ "num_epochs = 20000\nlearning_rate = 0.001\nloss_fn = F.mse_loss\n\nseed_everything()\n\nmodel = Autoencoder()\nmodel = model.to(device)\nopt = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)\ntrain_sum_1, val_sum_1, test_sum_1 = fit(num_epochs, model, loss_fn, train_input, train_output, val_input, val_output, test_input, test_output, 'model_path_cnn')\n# fig.savefig(\"auto_encoder.png\", bbox_inches='tight', dpi=600)", "_____no_output_____" ], [ "# model = Autoencoder_model()\n# model.load_state_dict(torch.load(model_path))\n# model.eval()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb24a8003949634e489f262a9958cc8294710c97
221,064
ipynb
Jupyter Notebook
EE488_DCASE2020_Baseline.ipynb
jhChoi1997/github-slideshow
fa715b18e078abf49f40a7131800df44f881d2ea
[ "MIT" ]
null
null
null
EE488_DCASE2020_Baseline.ipynb
jhChoi1997/github-slideshow
fa715b18e078abf49f40a7131800df44f881d2ea
[ "MIT" ]
3
2022-01-20T05:26:32.000Z
2022-01-20T06:07:01.000Z
EE488_DCASE2020_Baseline.ipynb
jhChoi1997/github-slideshow
fa715b18e078abf49f40a7131800df44f881d2ea
[ "MIT" ]
null
null
null
64.506566
248
0.589173
[ [ [ "<a href=\"https://colab.research.google.com/github/jhChoi1997/github-slideshow/blob/main/EE488_DCASE2020_Baseline.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!gdown https://drive.google.com/uc?id=1BpQ1G6IV4EIVx6YMWomejb19oSE52E_C\n!gdown https://drive.google.com/uc?id=1p0aANQlQRKqM9FGhkV3j2h55PJUOgEXg\n!unzip valve.zip -d ./valve/", "Downloading...\nFrom: https://drive.google.com/uc?id=1BpQ1G6IV4EIVx6YMWomejb19oSE52E_C\nTo: /content/params.yaml\n100% 847/847 [00:00<00:00, 2.20MB/s]\nDownloading...\nFrom: https://drive.google.com/uc?id=1p0aANQlQRKqM9FGhkV3j2h55PJUOgEXg\nTo: /content/valve.zip\n100% 812M/812M [00:03<00:00, 226MB/s]\nArchive: valve.zip\n inflating: ./valve/normal_id_00_00000000.wav \n inflating: ./valve/normal_id_00_00000001.wav \n inflating: ./valve/normal_id_00_00000002.wav \n inflating: ./valve/normal_id_00_00000003.wav \n inflating: ./valve/normal_id_00_00000004.wav \n inflating: ./valve/normal_id_00_00000005.wav \n inflating: ./valve/normal_id_00_00000006.wav \n inflating: ./valve/normal_id_00_00000007.wav \n inflating: ./valve/normal_id_00_00000008.wav \n inflating: ./valve/normal_id_00_00000009.wav \n inflating: ./valve/normal_id_00_00000010.wav \n inflating: ./valve/normal_id_00_00000011.wav \n inflating: ./valve/normal_id_00_00000012.wav \n inflating: ./valve/normal_id_00_00000013.wav \n inflating: ./valve/normal_id_00_00000014.wav \n inflating: ./valve/normal_id_00_00000015.wav \n inflating: ./valve/normal_id_00_00000016.wav \n inflating: ./valve/normal_id_00_00000017.wav \n inflating: ./valve/normal_id_00_00000018.wav \n inflating: ./valve/normal_id_00_00000019.wav \n inflating: ./valve/normal_id_00_00000020.wav \n inflating: ./valve/normal_id_00_00000021.wav \n inflating: ./valve/normal_id_00_00000022.wav \n inflating: ./valve/normal_id_00_00000023.wav \n inflating: ./valve/normal_id_00_00000024.wav \n inflating: ./valve/normal_id_00_00000025.wav \n inflating: ./valve/normal_id_00_00000026.wav \n inflating: ./valve/normal_id_00_00000027.wav \n inflating: ./valve/normal_id_00_00000028.wav \n inflating: ./valve/normal_id_00_00000029.wav \n inflating: ./valve/normal_id_00_00000030.wav \n inflating: ./valve/normal_id_00_00000031.wav \n inflating: ./valve/normal_id_00_00000032.wav \n inflating: ./valve/normal_id_00_00000033.wav \n inflating: ./valve/normal_id_00_00000034.wav \n inflating: ./valve/normal_id_00_00000035.wav \n inflating: ./valve/normal_id_00_00000036.wav \n inflating: ./valve/normal_id_00_00000037.wav \n inflating: ./valve/normal_id_00_00000038.wav \n inflating: ./valve/normal_id_00_00000039.wav \n inflating: ./valve/normal_id_00_00000040.wav \n inflating: ./valve/normal_id_00_00000041.wav \n inflating: ./valve/normal_id_00_00000042.wav \n inflating: ./valve/normal_id_00_00000043.wav \n inflating: ./valve/normal_id_00_00000044.wav \n inflating: ./valve/normal_id_00_00000045.wav \n inflating: ./valve/normal_id_00_00000046.wav \n inflating: ./valve/normal_id_00_00000047.wav \n inflating: ./valve/normal_id_00_00000048.wav \n inflating: ./valve/normal_id_00_00000049.wav \n inflating: ./valve/normal_id_00_00000050.wav \n inflating: ./valve/normal_id_00_00000051.wav \n inflating: ./valve/normal_id_00_00000052.wav \n inflating: ./valve/normal_id_00_00000053.wav \n inflating: ./valve/normal_id_00_00000054.wav \n inflating: ./valve/normal_id_00_00000055.wav \n inflating: ./valve/normal_id_00_00000056.wav \n inflating: ./valve/normal_id_00_00000057.wav \n inflating: ./valve/normal_id_00_00000058.wav \n inflating: ./valve/normal_id_00_00000059.wav \n inflating: ./valve/normal_id_00_00000060.wav \n inflating: ./valve/normal_id_00_00000061.wav \n inflating: ./valve/normal_id_00_00000062.wav \n inflating: ./valve/normal_id_00_00000063.wav \n inflating: ./valve/normal_id_00_00000064.wav \n inflating: ./valve/normal_id_00_00000065.wav \n inflating: ./valve/normal_id_00_00000066.wav \n inflating: ./valve/normal_id_00_00000067.wav \n inflating: ./valve/normal_id_00_00000068.wav \n inflating: ./valve/normal_id_00_00000069.wav \n inflating: ./valve/normal_id_00_00000070.wav \n inflating: ./valve/normal_id_00_00000071.wav \n inflating: ./valve/normal_id_00_00000072.wav \n inflating: ./valve/normal_id_00_00000073.wav \n inflating: ./valve/normal_id_00_00000074.wav \n inflating: ./valve/normal_id_00_00000075.wav \n inflating: ./valve/normal_id_00_00000076.wav \n inflating: ./valve/normal_id_00_00000077.wav \n inflating: ./valve/normal_id_00_00000078.wav \n inflating: ./valve/normal_id_00_00000079.wav \n inflating: ./valve/normal_id_00_00000080.wav \n inflating: ./valve/normal_id_00_00000081.wav \n inflating: ./valve/normal_id_00_00000082.wav \n inflating: ./valve/normal_id_00_00000083.wav \n inflating: ./valve/normal_id_00_00000084.wav \n inflating: ./valve/normal_id_00_00000085.wav \n inflating: ./valve/normal_id_00_00000086.wav \n inflating: ./valve/normal_id_00_00000087.wav \n inflating: ./valve/normal_id_00_00000088.wav \n inflating: ./valve/normal_id_00_00000089.wav \n inflating: ./valve/normal_id_00_00000090.wav \n inflating: ./valve/normal_id_00_00000091.wav \n inflating: ./valve/normal_id_00_00000092.wav \n inflating: ./valve/normal_id_00_00000093.wav \n inflating: ./valve/normal_id_00_00000094.wav \n inflating: ./valve/normal_id_00_00000095.wav \n inflating: ./valve/normal_id_00_00000096.wav \n inflating: ./valve/normal_id_00_00000097.wav \n inflating: ./valve/normal_id_00_00000098.wav \n inflating: ./valve/normal_id_00_00000099.wav \n inflating: ./valve/normal_id_00_00000100.wav \n inflating: ./valve/normal_id_00_00000101.wav \n inflating: ./valve/normal_id_00_00000102.wav \n inflating: ./valve/normal_id_00_00000103.wav \n inflating: ./valve/normal_id_00_00000104.wav \n inflating: ./valve/normal_id_00_00000105.wav \n inflating: ./valve/normal_id_00_00000106.wav \n inflating: ./valve/normal_id_00_00000107.wav \n inflating: ./valve/normal_id_00_00000108.wav \n inflating: ./valve/normal_id_00_00000109.wav \n inflating: ./valve/normal_id_00_00000110.wav \n inflating: ./valve/normal_id_00_00000111.wav \n inflating: ./valve/normal_id_00_00000112.wav \n inflating: ./valve/normal_id_00_00000113.wav \n inflating: ./valve/normal_id_00_00000114.wav \n inflating: ./valve/normal_id_00_00000115.wav \n inflating: ./valve/normal_id_00_00000116.wav \n inflating: ./valve/normal_id_00_00000117.wav \n inflating: ./valve/normal_id_00_00000118.wav \n inflating: ./valve/normal_id_00_00000119.wav \n inflating: ./valve/normal_id_00_00000120.wav \n inflating: ./valve/normal_id_00_00000121.wav \n inflating: ./valve/normal_id_00_00000122.wav \n inflating: ./valve/normal_id_00_00000123.wav \n inflating: ./valve/normal_id_00_00000124.wav \n inflating: ./valve/normal_id_00_00000125.wav \n inflating: ./valve/normal_id_00_00000126.wav \n inflating: ./valve/normal_id_00_00000127.wav \n inflating: ./valve/normal_id_00_00000128.wav \n inflating: ./valve/normal_id_00_00000129.wav \n inflating: ./valve/normal_id_00_00000130.wav \n inflating: ./valve/normal_id_00_00000131.wav \n inflating: ./valve/normal_id_00_00000132.wav \n inflating: ./valve/normal_id_00_00000133.wav \n inflating: ./valve/normal_id_00_00000134.wav \n inflating: ./valve/normal_id_00_00000135.wav \n inflating: ./valve/normal_id_00_00000136.wav \n inflating: ./valve/normal_id_00_00000137.wav \n inflating: ./valve/normal_id_00_00000138.wav \n inflating: ./valve/normal_id_00_00000139.wav \n inflating: ./valve/normal_id_00_00000140.wav \n inflating: ./valve/normal_id_00_00000141.wav \n inflating: ./valve/normal_id_00_00000142.wav \n inflating: ./valve/normal_id_00_00000143.wav \n inflating: ./valve/normal_id_00_00000144.wav \n inflating: ./valve/normal_id_00_00000145.wav \n inflating: ./valve/normal_id_00_00000146.wav \n inflating: ./valve/normal_id_00_00000147.wav \n inflating: ./valve/normal_id_00_00000148.wav \n inflating: ./valve/normal_id_00_00000149.wav \n inflating: ./valve/normal_id_00_00000150.wav \n inflating: ./valve/normal_id_00_00000151.wav \n inflating: ./valve/normal_id_00_00000152.wav \n inflating: ./valve/normal_id_00_00000153.wav \n inflating: ./valve/normal_id_00_00000154.wav \n inflating: ./valve/normal_id_00_00000155.wav \n inflating: ./valve/normal_id_00_00000156.wav \n inflating: ./valve/normal_id_00_00000157.wav \n inflating: ./valve/normal_id_00_00000158.wav \n inflating: ./valve/normal_id_00_00000159.wav \n inflating: ./valve/normal_id_00_00000160.wav \n inflating: ./valve/normal_id_00_00000161.wav \n inflating: ./valve/normal_id_00_00000162.wav \n inflating: ./valve/normal_id_00_00000163.wav \n inflating: ./valve/normal_id_00_00000164.wav \n inflating: ./valve/normal_id_00_00000165.wav \n inflating: ./valve/normal_id_00_00000166.wav \n inflating: ./valve/normal_id_00_00000167.wav \n inflating: ./valve/normal_id_00_00000168.wav \n inflating: ./valve/normal_id_00_00000169.wav \n inflating: ./valve/normal_id_00_00000170.wav \n inflating: ./valve/normal_id_00_00000171.wav \n inflating: ./valve/normal_id_00_00000172.wav \n inflating: ./valve/normal_id_00_00000173.wav \n inflating: ./valve/normal_id_00_00000174.wav \n inflating: ./valve/normal_id_00_00000175.wav \n inflating: ./valve/normal_id_00_00000176.wav \n inflating: ./valve/normal_id_00_00000177.wav \n inflating: ./valve/normal_id_00_00000178.wav \n inflating: ./valve/normal_id_00_00000179.wav \n inflating: ./valve/normal_id_00_00000180.wav \n inflating: ./valve/normal_id_00_00000181.wav \n inflating: ./valve/normal_id_00_00000182.wav \n inflating: ./valve/normal_id_00_00000183.wav \n inflating: ./valve/normal_id_00_00000184.wav \n inflating: ./valve/normal_id_00_00000185.wav \n inflating: ./valve/normal_id_00_00000186.wav \n inflating: ./valve/normal_id_00_00000187.wav \n inflating: ./valve/normal_id_00_00000188.wav \n inflating: ./valve/normal_id_00_00000189.wav \n inflating: ./valve/normal_id_00_00000190.wav \n inflating: ./valve/normal_id_00_00000191.wav \n inflating: ./valve/normal_id_00_00000192.wav \n inflating: ./valve/normal_id_00_00000193.wav \n inflating: ./valve/normal_id_00_00000194.wav \n inflating: ./valve/normal_id_00_00000195.wav \n inflating: ./valve/normal_id_00_00000196.wav \n inflating: ./valve/normal_id_00_00000197.wav \n inflating: ./valve/normal_id_00_00000198.wav \n inflating: ./valve/normal_id_00_00000199.wav \n inflating: ./valve/normal_id_00_00000200.wav \n inflating: ./valve/normal_id_00_00000201.wav \n inflating: ./valve/normal_id_00_00000202.wav \n inflating: ./valve/normal_id_00_00000203.wav \n inflating: ./valve/normal_id_00_00000204.wav \n inflating: ./valve/normal_id_00_00000205.wav \n inflating: ./valve/normal_id_00_00000206.wav \n inflating: ./valve/normal_id_00_00000207.wav \n inflating: ./valve/normal_id_00_00000208.wav \n inflating: ./valve/normal_id_00_00000209.wav \n inflating: ./valve/normal_id_00_00000210.wav \n inflating: ./valve/normal_id_00_00000211.wav \n inflating: ./valve/normal_id_00_00000212.wav \n inflating: ./valve/normal_id_00_00000213.wav \n inflating: ./valve/normal_id_00_00000214.wav \n inflating: ./valve/normal_id_00_00000215.wav \n inflating: ./valve/normal_id_00_00000216.wav \n inflating: ./valve/normal_id_00_00000217.wav \n inflating: ./valve/normal_id_00_00000218.wav \n inflating: ./valve/normal_id_00_00000219.wav \n inflating: ./valve/normal_id_00_00000220.wav \n inflating: ./valve/normal_id_00_00000221.wav \n inflating: ./valve/normal_id_00_00000222.wav \n inflating: ./valve/normal_id_00_00000223.wav \n inflating: ./valve/normal_id_00_00000224.wav \n inflating: ./valve/normal_id_00_00000225.wav \n inflating: ./valve/normal_id_00_00000226.wav \n inflating: ./valve/normal_id_00_00000227.wav \n inflating: ./valve/normal_id_00_00000228.wav \n inflating: ./valve/normal_id_00_00000229.wav \n inflating: ./valve/normal_id_00_00000230.wav \n inflating: ./valve/normal_id_00_00000231.wav \n inflating: ./valve/normal_id_00_00000232.wav \n inflating: ./valve/normal_id_00_00000233.wav \n inflating: ./valve/normal_id_00_00000234.wav \n inflating: ./valve/normal_id_00_00000235.wav \n inflating: ./valve/normal_id_00_00000236.wav \n inflating: ./valve/normal_id_00_00000237.wav \n inflating: ./valve/normal_id_00_00000238.wav \n inflating: ./valve/normal_id_00_00000239.wav \n inflating: ./valve/normal_id_00_00000240.wav \n inflating: ./valve/normal_id_00_00000241.wav \n inflating: ./valve/normal_id_00_00000242.wav \n inflating: ./valve/normal_id_00_00000243.wav \n inflating: ./valve/normal_id_00_00000244.wav \n inflating: ./valve/normal_id_00_00000245.wav \n inflating: ./valve/normal_id_00_00000246.wav \n inflating: ./valve/normal_id_00_00000247.wav \n inflating: ./valve/normal_id_00_00000248.wav \n inflating: ./valve/normal_id_00_00000249.wav \n inflating: ./valve/normal_id_00_00000250.wav \n inflating: ./valve/normal_id_00_00000251.wav \n inflating: ./valve/normal_id_00_00000252.wav \n inflating: ./valve/normal_id_00_00000253.wav \n inflating: ./valve/normal_id_00_00000254.wav \n inflating: ./valve/normal_id_00_00000255.wav \n inflating: ./valve/normal_id_00_00000256.wav \n inflating: ./valve/normal_id_00_00000257.wav \n inflating: ./valve/normal_id_00_00000258.wav \n inflating: ./valve/normal_id_00_00000259.wav \n inflating: ./valve/normal_id_00_00000260.wav \n inflating: ./valve/normal_id_00_00000261.wav \n inflating: ./valve/normal_id_00_00000262.wav \n inflating: ./valve/normal_id_00_00000263.wav \n inflating: ./valve/normal_id_00_00000264.wav \n inflating: ./valve/normal_id_00_00000265.wav \n inflating: ./valve/normal_id_00_00000266.wav \n inflating: ./valve/normal_id_00_00000267.wav \n inflating: ./valve/normal_id_00_00000268.wav \n inflating: ./valve/normal_id_00_00000269.wav \n inflating: ./valve/normal_id_00_00000270.wav \n inflating: ./valve/normal_id_00_00000271.wav \n inflating: ./valve/normal_id_00_00000272.wav \n inflating: ./valve/normal_id_00_00000273.wav \n inflating: ./valve/normal_id_00_00000274.wav \n inflating: ./valve/normal_id_00_00000275.wav \n inflating: ./valve/normal_id_00_00000276.wav \n inflating: ./valve/normal_id_00_00000277.wav \n inflating: ./valve/normal_id_00_00000278.wav \n inflating: ./valve/normal_id_00_00000279.wav \n inflating: ./valve/normal_id_00_00000280.wav \n inflating: ./valve/normal_id_00_00000281.wav \n inflating: ./valve/normal_id_00_00000282.wav \n inflating: ./valve/normal_id_00_00000283.wav \n inflating: ./valve/normal_id_00_00000284.wav \n inflating: ./valve/normal_id_00_00000285.wav \n inflating: ./valve/normal_id_00_00000286.wav \n inflating: ./valve/normal_id_00_00000287.wav \n inflating: ./valve/normal_id_00_00000288.wav \n inflating: ./valve/normal_id_00_00000289.wav \n inflating: ./valve/normal_id_00_00000290.wav \n inflating: ./valve/normal_id_00_00000291.wav \n inflating: ./valve/normal_id_00_00000292.wav \n inflating: ./valve/normal_id_00_00000293.wav \n inflating: ./valve/normal_id_00_00000294.wav \n inflating: ./valve/normal_id_00_00000295.wav \n inflating: ./valve/normal_id_00_00000296.wav \n inflating: ./valve/normal_id_00_00000297.wav \n inflating: ./valve/normal_id_00_00000298.wav \n inflating: ./valve/normal_id_00_00000299.wav \n inflating: ./valve/normal_id_00_00000300.wav \n inflating: ./valve/normal_id_00_00000301.wav \n inflating: ./valve/normal_id_00_00000302.wav \n inflating: ./valve/normal_id_00_00000303.wav \n inflating: ./valve/normal_id_00_00000304.wav \n inflating: ./valve/normal_id_00_00000305.wav \n inflating: ./valve/normal_id_00_00000306.wav \n inflating: ./valve/normal_id_00_00000307.wav \n inflating: ./valve/normal_id_00_00000308.wav \n inflating: ./valve/normal_id_00_00000309.wav \n inflating: ./valve/normal_id_00_00000310.wav \n inflating: ./valve/normal_id_00_00000311.wav \n inflating: ./valve/normal_id_00_00000312.wav \n inflating: ./valve/normal_id_00_00000313.wav \n inflating: ./valve/normal_id_00_00000314.wav \n inflating: ./valve/normal_id_00_00000315.wav \n inflating: ./valve/normal_id_00_00000316.wav \n inflating: ./valve/normal_id_00_00000317.wav \n inflating: ./valve/normal_id_00_00000318.wav \n inflating: ./valve/normal_id_00_00000319.wav \n inflating: ./valve/normal_id_00_00000320.wav \n inflating: ./valve/normal_id_00_00000321.wav \n inflating: ./valve/normal_id_00_00000322.wav \n inflating: ./valve/normal_id_00_00000323.wav \n inflating: ./valve/normal_id_00_00000324.wav \n inflating: ./valve/normal_id_00_00000325.wav \n inflating: ./valve/normal_id_00_00000326.wav \n inflating: ./valve/normal_id_00_00000327.wav \n inflating: ./valve/normal_id_00_00000328.wav \n inflating: ./valve/normal_id_00_00000329.wav \n inflating: ./valve/normal_id_00_00000330.wav \n inflating: ./valve/normal_id_00_00000331.wav \n inflating: ./valve/normal_id_00_00000332.wav \n inflating: ./valve/normal_id_00_00000333.wav \n inflating: ./valve/normal_id_00_00000334.wav \n inflating: ./valve/normal_id_00_00000335.wav \n inflating: ./valve/normal_id_00_00000336.wav \n inflating: ./valve/normal_id_00_00000337.wav \n inflating: ./valve/normal_id_00_00000338.wav \n inflating: ./valve/normal_id_00_00000339.wav \n inflating: ./valve/normal_id_00_00000340.wav \n inflating: ./valve/normal_id_00_00000341.wav \n inflating: ./valve/normal_id_00_00000342.wav \n inflating: ./valve/normal_id_00_00000343.wav \n inflating: ./valve/normal_id_00_00000344.wav \n inflating: ./valve/normal_id_00_00000345.wav \n inflating: ./valve/normal_id_00_00000346.wav \n inflating: ./valve/normal_id_00_00000347.wav \n inflating: ./valve/normal_id_00_00000348.wav \n inflating: ./valve/normal_id_00_00000349.wav \n inflating: ./valve/normal_id_00_00000350.wav \n inflating: ./valve/normal_id_00_00000351.wav \n inflating: ./valve/normal_id_00_00000352.wav \n inflating: ./valve/normal_id_00_00000353.wav \n inflating: ./valve/normal_id_00_00000354.wav \n inflating: ./valve/normal_id_00_00000355.wav \n inflating: ./valve/normal_id_00_00000356.wav \n inflating: ./valve/normal_id_00_00000357.wav \n inflating: ./valve/normal_id_00_00000358.wav \n inflating: ./valve/normal_id_00_00000359.wav \n inflating: ./valve/normal_id_00_00000360.wav \n inflating: ./valve/normal_id_00_00000361.wav \n inflating: ./valve/normal_id_00_00000362.wav \n inflating: ./valve/normal_id_00_00000363.wav \n inflating: ./valve/normal_id_00_00000364.wav \n inflating: ./valve/normal_id_00_00000365.wav \n inflating: ./valve/normal_id_00_00000366.wav \n inflating: ./valve/normal_id_00_00000367.wav \n inflating: ./valve/normal_id_00_00000368.wav \n inflating: ./valve/normal_id_00_00000369.wav \n inflating: ./valve/normal_id_00_00000370.wav \n inflating: ./valve/normal_id_00_00000371.wav \n inflating: ./valve/normal_id_00_00000372.wav \n inflating: ./valve/normal_id_00_00000373.wav \n inflating: ./valve/normal_id_00_00000374.wav \n inflating: ./valve/normal_id_00_00000375.wav \n inflating: ./valve/normal_id_00_00000376.wav \n inflating: ./valve/normal_id_00_00000377.wav \n inflating: ./valve/normal_id_00_00000378.wav \n inflating: ./valve/normal_id_00_00000379.wav \n inflating: ./valve/normal_id_00_00000380.wav \n inflating: ./valve/normal_id_00_00000381.wav \n inflating: ./valve/normal_id_00_00000382.wav \n inflating: ./valve/normal_id_00_00000383.wav \n inflating: ./valve/normal_id_00_00000384.wav \n inflating: ./valve/normal_id_00_00000385.wav \n inflating: ./valve/normal_id_00_00000386.wav \n inflating: ./valve/normal_id_00_00000387.wav \n inflating: ./valve/normal_id_00_00000388.wav \n inflating: ./valve/normal_id_00_00000389.wav \n inflating: ./valve/normal_id_00_00000390.wav \n inflating: ./valve/normal_id_00_00000391.wav \n inflating: ./valve/normal_id_00_00000392.wav \n inflating: ./valve/normal_id_00_00000393.wav \n inflating: ./valve/normal_id_00_00000394.wav \n inflating: ./valve/normal_id_00_00000395.wav \n inflating: ./valve/normal_id_00_00000396.wav \n inflating: ./valve/normal_id_00_00000397.wav \n inflating: ./valve/normal_id_00_00000398.wav \n inflating: ./valve/normal_id_00_00000399.wav \n inflating: ./valve/normal_id_00_00000400.wav \n inflating: ./valve/normal_id_00_00000401.wav \n inflating: ./valve/normal_id_00_00000402.wav \n inflating: ./valve/normal_id_00_00000403.wav \n inflating: ./valve/normal_id_00_00000404.wav \n inflating: ./valve/normal_id_00_00000405.wav \n inflating: ./valve/normal_id_00_00000406.wav \n inflating: ./valve/normal_id_00_00000407.wav \n inflating: ./valve/normal_id_00_00000408.wav \n inflating: ./valve/normal_id_00_00000409.wav \n inflating: ./valve/normal_id_00_00000410.wav \n inflating: ./valve/normal_id_00_00000411.wav \n inflating: ./valve/normal_id_00_00000412.wav \n inflating: ./valve/normal_id_00_00000413.wav \n inflating: ./valve/normal_id_00_00000414.wav \n inflating: ./valve/normal_id_00_00000415.wav \n inflating: ./valve/normal_id_00_00000416.wav \n inflating: ./valve/normal_id_00_00000417.wav \n inflating: ./valve/normal_id_00_00000418.wav \n inflating: ./valve/normal_id_00_00000419.wav \n inflating: ./valve/normal_id_00_00000420.wav \n inflating: ./valve/normal_id_00_00000421.wav \n inflating: ./valve/normal_id_00_00000422.wav \n inflating: ./valve/normal_id_00_00000423.wav \n inflating: ./valve/normal_id_00_00000424.wav \n inflating: ./valve/normal_id_00_00000425.wav \n inflating: ./valve/normal_id_00_00000426.wav \n inflating: ./valve/normal_id_00_00000427.wav \n inflating: ./valve/normal_id_00_00000428.wav \n inflating: ./valve/normal_id_00_00000429.wav \n inflating: ./valve/normal_id_00_00000430.wav \n inflating: ./valve/normal_id_00_00000431.wav \n inflating: ./valve/normal_id_00_00000432.wav \n inflating: ./valve/normal_id_00_00000433.wav \n inflating: ./valve/normal_id_00_00000434.wav \n inflating: ./valve/normal_id_00_00000435.wav \n inflating: ./valve/normal_id_00_00000436.wav \n inflating: ./valve/normal_id_00_00000437.wav \n inflating: ./valve/normal_id_00_00000438.wav \n inflating: ./valve/normal_id_00_00000439.wav \n inflating: ./valve/normal_id_00_00000440.wav \n inflating: ./valve/normal_id_00_00000441.wav \n inflating: ./valve/normal_id_00_00000442.wav \n inflating: ./valve/normal_id_00_00000443.wav \n inflating: ./valve/normal_id_00_00000444.wav \n inflating: ./valve/normal_id_00_00000445.wav \n inflating: ./valve/normal_id_00_00000446.wav \n inflating: ./valve/normal_id_00_00000447.wav \n inflating: ./valve/normal_id_00_00000448.wav \n inflating: ./valve/normal_id_00_00000449.wav \n inflating: ./valve/normal_id_00_00000450.wav \n inflating: ./valve/normal_id_00_00000451.wav \n inflating: ./valve/normal_id_00_00000452.wav \n inflating: ./valve/normal_id_00_00000453.wav \n inflating: ./valve/normal_id_00_00000454.wav \n inflating: ./valve/normal_id_00_00000455.wav \n inflating: ./valve/normal_id_00_00000456.wav \n inflating: ./valve/normal_id_00_00000457.wav \n inflating: ./valve/normal_id_00_00000458.wav \n inflating: ./valve/normal_id_00_00000459.wav \n inflating: ./valve/normal_id_00_00000460.wav \n inflating: ./valve/normal_id_00_00000461.wav \n inflating: ./valve/normal_id_00_00000462.wav \n inflating: ./valve/normal_id_00_00000463.wav \n inflating: ./valve/normal_id_00_00000464.wav \n inflating: ./valve/normal_id_00_00000465.wav \n inflating: ./valve/normal_id_00_00000466.wav \n inflating: ./valve/normal_id_00_00000467.wav \n inflating: ./valve/normal_id_00_00000468.wav \n inflating: ./valve/normal_id_00_00000469.wav \n inflating: ./valve/normal_id_00_00000470.wav \n inflating: ./valve/normal_id_00_00000471.wav \n inflating: ./valve/normal_id_00_00000472.wav \n inflating: ./valve/normal_id_00_00000473.wav \n inflating: ./valve/normal_id_00_00000474.wav \n inflating: ./valve/normal_id_00_00000475.wav \n inflating: ./valve/normal_id_00_00000476.wav \n inflating: ./valve/normal_id_00_00000477.wav \n inflating: ./valve/normal_id_00_00000478.wav \n inflating: ./valve/normal_id_00_00000479.wav \n inflating: ./valve/normal_id_00_00000480.wav \n inflating: ./valve/normal_id_00_00000481.wav \n inflating: ./valve/normal_id_00_00000482.wav \n inflating: ./valve/normal_id_00_00000483.wav \n inflating: ./valve/normal_id_00_00000484.wav \n inflating: ./valve/normal_id_00_00000485.wav \n inflating: ./valve/normal_id_00_00000486.wav \n inflating: ./valve/normal_id_00_00000487.wav \n inflating: ./valve/normal_id_00_00000488.wav \n inflating: ./valve/normal_id_00_00000489.wav \n inflating: ./valve/normal_id_00_00000490.wav \n inflating: ./valve/normal_id_00_00000491.wav \n inflating: ./valve/normal_id_00_00000492.wav \n inflating: ./valve/normal_id_00_00000493.wav \n inflating: ./valve/normal_id_00_00000494.wav \n inflating: ./valve/normal_id_00_00000495.wav \n inflating: ./valve/normal_id_00_00000496.wav \n inflating: ./valve/normal_id_00_00000497.wav \n inflating: ./valve/normal_id_00_00000498.wav \n inflating: ./valve/normal_id_00_00000499.wav \n inflating: ./valve/normal_id_00_00000500.wav \n inflating: ./valve/normal_id_00_00000501.wav \n inflating: ./valve/normal_id_00_00000502.wav \n inflating: ./valve/normal_id_00_00000503.wav \n inflating: ./valve/normal_id_00_00000504.wav \n inflating: ./valve/normal_id_00_00000505.wav \n inflating: ./valve/normal_id_00_00000506.wav \n inflating: ./valve/normal_id_00_00000507.wav \n inflating: ./valve/normal_id_00_00000508.wav \n inflating: ./valve/normal_id_00_00000509.wav \n inflating: ./valve/normal_id_00_00000510.wav \n inflating: ./valve/normal_id_00_00000511.wav \n inflating: ./valve/normal_id_00_00000512.wav \n inflating: ./valve/normal_id_00_00000513.wav \n inflating: ./valve/normal_id_00_00000514.wav \n inflating: ./valve/normal_id_00_00000515.wav \n inflating: ./valve/normal_id_00_00000516.wav \n inflating: ./valve/normal_id_00_00000517.wav \n inflating: ./valve/normal_id_00_00000518.wav \n inflating: ./valve/normal_id_00_00000519.wav \n inflating: ./valve/normal_id_00_00000520.wav \n inflating: ./valve/normal_id_00_00000521.wav \n inflating: ./valve/normal_id_00_00000522.wav \n inflating: ./valve/normal_id_00_00000523.wav \n inflating: ./valve/normal_id_00_00000524.wav \n inflating: ./valve/normal_id_00_00000525.wav \n inflating: ./valve/normal_id_00_00000526.wav \n inflating: ./valve/normal_id_00_00000527.wav \n inflating: ./valve/normal_id_00_00000528.wav \n inflating: ./valve/normal_id_00_00000529.wav \n inflating: ./valve/normal_id_00_00000530.wav \n inflating: ./valve/normal_id_00_00000531.wav \n inflating: ./valve/normal_id_00_00000532.wav \n inflating: ./valve/normal_id_00_00000533.wav \n inflating: ./valve/normal_id_00_00000534.wav \n inflating: ./valve/normal_id_00_00000535.wav \n inflating: ./valve/normal_id_00_00000536.wav \n inflating: ./valve/normal_id_00_00000537.wav \n inflating: ./valve/normal_id_00_00000538.wav \n inflating: ./valve/normal_id_00_00000539.wav \n inflating: ./valve/normal_id_00_00000540.wav \n inflating: ./valve/normal_id_00_00000541.wav \n inflating: ./valve/normal_id_00_00000542.wav \n inflating: ./valve/normal_id_00_00000543.wav \n inflating: ./valve/normal_id_00_00000544.wav \n inflating: ./valve/normal_id_00_00000545.wav \n inflating: ./valve/normal_id_00_00000546.wav \n inflating: ./valve/normal_id_00_00000547.wav \n inflating: ./valve/normal_id_00_00000548.wav \n inflating: ./valve/normal_id_00_00000549.wav \n inflating: ./valve/normal_id_00_00000550.wav \n inflating: ./valve/normal_id_00_00000551.wav \n inflating: ./valve/normal_id_00_00000552.wav \n inflating: ./valve/normal_id_00_00000553.wav \n inflating: ./valve/normal_id_00_00000554.wav \n inflating: ./valve/normal_id_00_00000555.wav \n inflating: ./valve/normal_id_00_00000556.wav \n inflating: ./valve/normal_id_00_00000557.wav \n inflating: ./valve/normal_id_00_00000558.wav \n inflating: ./valve/normal_id_00_00000559.wav \n inflating: ./valve/normal_id_00_00000560.wav \n inflating: ./valve/normal_id_00_00000561.wav \n inflating: ./valve/normal_id_00_00000562.wav \n inflating: ./valve/normal_id_00_00000563.wav \n inflating: ./valve/normal_id_00_00000564.wav \n inflating: ./valve/normal_id_00_00000565.wav \n inflating: ./valve/normal_id_00_00000566.wav \n inflating: ./valve/normal_id_00_00000567.wav \n inflating: ./valve/normal_id_00_00000568.wav \n inflating: ./valve/normal_id_00_00000569.wav \n inflating: ./valve/normal_id_00_00000570.wav \n inflating: ./valve/normal_id_00_00000571.wav \n inflating: ./valve/normal_id_00_00000572.wav \n inflating: ./valve/normal_id_00_00000573.wav \n inflating: ./valve/normal_id_00_00000574.wav \n inflating: ./valve/normal_id_00_00000575.wav \n inflating: ./valve/normal_id_00_00000576.wav \n inflating: ./valve/normal_id_00_00000577.wav \n inflating: ./valve/normal_id_00_00000578.wav \n inflating: ./valve/normal_id_00_00000579.wav \n inflating: ./valve/normal_id_00_00000580.wav \n inflating: ./valve/normal_id_00_00000581.wav \n inflating: ./valve/normal_id_00_00000582.wav \n inflating: ./valve/normal_id_00_00000583.wav \n inflating: ./valve/normal_id_00_00000584.wav \n inflating: ./valve/normal_id_00_00000585.wav \n inflating: ./valve/normal_id_00_00000586.wav \n inflating: ./valve/normal_id_00_00000587.wav \n inflating: ./valve/normal_id_00_00000588.wav \n inflating: ./valve/normal_id_00_00000589.wav \n inflating: ./valve/normal_id_00_00000590.wav \n inflating: ./valve/normal_id_00_00000591.wav \n inflating: ./valve/normal_id_00_00000592.wav \n inflating: ./valve/normal_id_00_00000593.wav \n inflating: ./valve/normal_id_00_00000594.wav \n inflating: ./valve/normal_id_00_00000595.wav \n inflating: ./valve/normal_id_00_00000596.wav \n inflating: ./valve/normal_id_00_00000597.wav \n inflating: ./valve/normal_id_00_00000598.wav \n inflating: ./valve/normal_id_00_00000599.wav \n inflating: ./valve/normal_id_00_00000600.wav \n inflating: ./valve/normal_id_00_00000601.wav \n inflating: ./valve/normal_id_00_00000602.wav \n inflating: ./valve/normal_id_00_00000603.wav \n inflating: ./valve/normal_id_00_00000604.wav \n inflating: ./valve/normal_id_00_00000605.wav \n inflating: ./valve/normal_id_00_00000606.wav \n inflating: ./valve/normal_id_00_00000607.wav \n inflating: ./valve/normal_id_00_00000608.wav \n inflating: ./valve/normal_id_00_00000609.wav \n inflating: ./valve/normal_id_00_00000610.wav \n inflating: ./valve/normal_id_00_00000611.wav \n inflating: ./valve/normal_id_00_00000612.wav \n inflating: ./valve/normal_id_00_00000613.wav \n inflating: ./valve/normal_id_00_00000614.wav \n inflating: ./valve/normal_id_00_00000615.wav \n inflating: ./valve/normal_id_00_00000616.wav \n inflating: ./valve/normal_id_00_00000617.wav \n inflating: ./valve/normal_id_00_00000618.wav \n inflating: ./valve/normal_id_00_00000619.wav \n inflating: ./valve/normal_id_00_00000620.wav \n inflating: ./valve/normal_id_00_00000621.wav \n inflating: ./valve/normal_id_00_00000622.wav \n inflating: ./valve/normal_id_00_00000623.wav \n inflating: ./valve/normal_id_00_00000624.wav \n inflating: ./valve/normal_id_00_00000625.wav \n inflating: ./valve/normal_id_00_00000626.wav \n inflating: ./valve/normal_id_00_00000627.wav \n inflating: ./valve/normal_id_00_00000628.wav \n inflating: ./valve/normal_id_00_00000629.wav \n inflating: ./valve/normal_id_00_00000630.wav \n inflating: ./valve/normal_id_00_00000631.wav \n inflating: ./valve/normal_id_00_00000632.wav \n inflating: ./valve/normal_id_00_00000633.wav \n inflating: ./valve/normal_id_00_00000634.wav \n inflating: ./valve/normal_id_00_00000635.wav \n inflating: ./valve/normal_id_00_00000636.wav \n inflating: ./valve/normal_id_00_00000637.wav \n inflating: ./valve/normal_id_00_00000638.wav \n inflating: ./valve/normal_id_00_00000639.wav \n inflating: ./valve/normal_id_00_00000640.wav \n inflating: ./valve/normal_id_00_00000641.wav \n inflating: ./valve/normal_id_00_00000642.wav \n inflating: ./valve/normal_id_00_00000643.wav \n inflating: ./valve/normal_id_00_00000644.wav \n inflating: ./valve/normal_id_00_00000645.wav \n inflating: ./valve/normal_id_00_00000646.wav \n inflating: ./valve/normal_id_00_00000647.wav \n inflating: ./valve/normal_id_00_00000648.wav \n inflating: ./valve/normal_id_00_00000649.wav \n inflating: ./valve/normal_id_00_00000650.wav \n inflating: ./valve/normal_id_00_00000651.wav \n inflating: ./valve/normal_id_00_00000652.wav \n inflating: ./valve/normal_id_00_00000653.wav \n inflating: ./valve/normal_id_00_00000654.wav \n inflating: ./valve/normal_id_00_00000655.wav \n inflating: ./valve/normal_id_00_00000656.wav \n inflating: ./valve/normal_id_00_00000657.wav \n inflating: ./valve/normal_id_00_00000658.wav \n inflating: ./valve/normal_id_00_00000659.wav \n inflating: ./valve/normal_id_00_00000660.wav \n inflating: ./valve/normal_id_00_00000661.wav \n inflating: ./valve/normal_id_00_00000662.wav \n inflating: ./valve/normal_id_00_00000663.wav \n inflating: ./valve/normal_id_00_00000664.wav \n inflating: ./valve/normal_id_00_00000665.wav \n inflating: ./valve/normal_id_00_00000666.wav \n inflating: ./valve/normal_id_00_00000667.wav \n inflating: ./valve/normal_id_00_00000668.wav \n inflating: ./valve/normal_id_00_00000669.wav \n inflating: ./valve/normal_id_00_00000670.wav \n inflating: ./valve/normal_id_00_00000671.wav \n inflating: ./valve/normal_id_00_00000672.wav \n inflating: ./valve/normal_id_00_00000673.wav \n inflating: ./valve/normal_id_00_00000674.wav \n inflating: ./valve/normal_id_00_00000675.wav \n inflating: ./valve/normal_id_00_00000676.wav \n inflating: ./valve/normal_id_00_00000677.wav \n inflating: ./valve/normal_id_00_00000678.wav \n inflating: ./valve/normal_id_00_00000679.wav \n inflating: ./valve/normal_id_00_00000680.wav \n inflating: ./valve/normal_id_00_00000681.wav \n inflating: ./valve/normal_id_00_00000682.wav \n inflating: ./valve/normal_id_00_00000683.wav \n inflating: ./valve/normal_id_00_00000684.wav \n inflating: ./valve/normal_id_00_00000685.wav \n inflating: ./valve/normal_id_00_00000686.wav \n inflating: ./valve/normal_id_00_00000687.wav \n inflating: ./valve/normal_id_00_00000688.wav \n inflating: ./valve/normal_id_00_00000689.wav \n inflating: ./valve/normal_id_00_00000690.wav \n inflating: ./valve/normal_id_00_00000691.wav \n inflating: ./valve/normal_id_00_00000692.wav \n inflating: ./valve/normal_id_00_00000693.wav \n inflating: ./valve/normal_id_00_00000694.wav \n inflating: ./valve/normal_id_00_00000695.wav \n inflating: ./valve/normal_id_00_00000696.wav \n inflating: ./valve/normal_id_00_00000697.wav \n inflating: ./valve/normal_id_00_00000698.wav \n inflating: ./valve/normal_id_00_00000699.wav \n inflating: ./valve/normal_id_00_00000700.wav \n inflating: ./valve/normal_id_00_00000701.wav \n inflating: ./valve/normal_id_00_00000702.wav \n inflating: ./valve/normal_id_00_00000703.wav \n inflating: ./valve/normal_id_00_00000704.wav \n inflating: ./valve/normal_id_00_00000705.wav \n inflating: ./valve/normal_id_00_00000706.wav \n inflating: ./valve/normal_id_00_00000707.wav \n inflating: ./valve/normal_id_00_00000708.wav \n inflating: ./valve/normal_id_00_00000709.wav \n inflating: ./valve/normal_id_00_00000710.wav \n inflating: ./valve/normal_id_00_00000711.wav \n inflating: ./valve/normal_id_00_00000712.wav \n inflating: ./valve/normal_id_00_00000713.wav \n inflating: ./valve/normal_id_00_00000714.wav \n inflating: ./valve/normal_id_00_00000715.wav \n inflating: ./valve/normal_id_00_00000716.wav \n inflating: ./valve/normal_id_00_00000717.wav \n inflating: ./valve/normal_id_00_00000718.wav \n inflating: ./valve/normal_id_00_00000719.wav \n inflating: ./valve/normal_id_00_00000720.wav \n inflating: ./valve/normal_id_00_00000721.wav \n inflating: ./valve/normal_id_00_00000722.wav \n inflating: ./valve/normal_id_00_00000723.wav \n inflating: ./valve/normal_id_00_00000724.wav \n inflating: ./valve/normal_id_00_00000725.wav \n inflating: ./valve/normal_id_00_00000726.wav \n inflating: ./valve/normal_id_00_00000727.wav \n inflating: ./valve/normal_id_00_00000728.wav \n inflating: ./valve/normal_id_00_00000729.wav \n inflating: ./valve/normal_id_00_00000730.wav \n inflating: ./valve/normal_id_00_00000731.wav \n inflating: ./valve/normal_id_00_00000732.wav \n inflating: ./valve/normal_id_00_00000733.wav \n inflating: ./valve/normal_id_00_00000734.wav \n inflating: ./valve/normal_id_00_00000735.wav \n inflating: ./valve/normal_id_00_00000736.wav \n inflating: ./valve/normal_id_00_00000737.wav \n inflating: ./valve/normal_id_00_00000738.wav \n inflating: ./valve/normal_id_00_00000739.wav \n inflating: ./valve/normal_id_00_00000740.wav \n inflating: ./valve/normal_id_00_00000741.wav \n inflating: ./valve/normal_id_00_00000742.wav \n inflating: ./valve/normal_id_00_00000743.wav \n inflating: ./valve/normal_id_00_00000744.wav \n inflating: ./valve/normal_id_00_00000745.wav \n inflating: ./valve/normal_id_00_00000746.wav \n inflating: ./valve/normal_id_00_00000747.wav \n inflating: ./valve/normal_id_00_00000748.wav \n inflating: ./valve/normal_id_00_00000749.wav \n inflating: ./valve/normal_id_00_00000750.wav \n inflating: ./valve/normal_id_00_00000751.wav \n inflating: ./valve/normal_id_00_00000752.wav \n inflating: ./valve/normal_id_00_00000753.wav \n inflating: ./valve/normal_id_00_00000754.wav \n inflating: ./valve/normal_id_00_00000755.wav \n inflating: ./valve/normal_id_00_00000756.wav \n inflating: ./valve/normal_id_00_00000757.wav \n inflating: ./valve/normal_id_00_00000758.wav \n inflating: ./valve/normal_id_00_00000759.wav \n inflating: ./valve/normal_id_00_00000760.wav \n inflating: ./valve/normal_id_00_00000761.wav \n inflating: ./valve/normal_id_00_00000762.wav \n inflating: ./valve/normal_id_00_00000763.wav \n inflating: ./valve/normal_id_00_00000764.wav \n inflating: ./valve/normal_id_00_00000765.wav \n inflating: ./valve/normal_id_00_00000766.wav \n inflating: ./valve/normal_id_00_00000767.wav \n inflating: ./valve/normal_id_00_00000768.wav \n inflating: ./valve/normal_id_00_00000769.wav \n inflating: ./valve/normal_id_00_00000770.wav \n inflating: ./valve/normal_id_00_00000771.wav \n inflating: ./valve/normal_id_00_00000772.wav \n inflating: ./valve/normal_id_00_00000773.wav \n inflating: ./valve/normal_id_00_00000774.wav \n inflating: ./valve/normal_id_00_00000775.wav \n inflating: ./valve/normal_id_00_00000776.wav \n inflating: ./valve/normal_id_00_00000777.wav \n inflating: ./valve/normal_id_00_00000778.wav \n inflating: ./valve/normal_id_00_00000779.wav \n inflating: ./valve/normal_id_00_00000780.wav \n inflating: ./valve/normal_id_00_00000781.wav \n inflating: ./valve/normal_id_00_00000782.wav \n inflating: ./valve/normal_id_00_00000783.wav \n inflating: ./valve/normal_id_00_00000784.wav \n inflating: ./valve/normal_id_00_00000785.wav \n inflating: ./valve/normal_id_00_00000786.wav \n inflating: ./valve/normal_id_00_00000787.wav \n inflating: ./valve/normal_id_00_00000788.wav \n inflating: ./valve/normal_id_00_00000789.wav \n inflating: ./valve/normal_id_00_00000790.wav \n inflating: ./valve/normal_id_00_00000791.wav \n inflating: ./valve/normal_id_00_00000792.wav \n inflating: ./valve/normal_id_00_00000793.wav \n inflating: ./valve/normal_id_00_00000794.wav \n inflating: ./valve/normal_id_00_00000795.wav \n inflating: ./valve/normal_id_00_00000796.wav \n inflating: ./valve/normal_id_00_00000797.wav \n inflating: ./valve/normal_id_00_00000798.wav \n inflating: ./valve/normal_id_00_00000799.wav \n inflating: ./valve/normal_id_00_00000800.wav \n inflating: ./valve/normal_id_00_00000801.wav \n inflating: ./valve/normal_id_00_00000802.wav \n inflating: ./valve/normal_id_00_00000803.wav \n inflating: ./valve/normal_id_00_00000804.wav \n inflating: ./valve/normal_id_00_00000805.wav \n inflating: ./valve/normal_id_00_00000806.wav \n inflating: ./valve/normal_id_00_00000807.wav \n inflating: ./valve/normal_id_00_00000808.wav \n inflating: ./valve/normal_id_00_00000809.wav \n inflating: ./valve/normal_id_00_00000810.wav \n inflating: ./valve/normal_id_00_00000811.wav \n inflating: ./valve/normal_id_00_00000812.wav \n inflating: ./valve/normal_id_00_00000813.wav \n inflating: ./valve/normal_id_00_00000814.wav \n inflating: ./valve/normal_id_00_00000815.wav \n inflating: ./valve/normal_id_00_00000816.wav \n inflating: ./valve/normal_id_00_00000817.wav \n inflating: ./valve/normal_id_00_00000818.wav \n inflating: ./valve/normal_id_00_00000819.wav \n inflating: ./valve/normal_id_00_00000820.wav \n inflating: ./valve/normal_id_00_00000821.wav \n inflating: ./valve/normal_id_00_00000822.wav \n inflating: ./valve/normal_id_00_00000823.wav \n inflating: ./valve/normal_id_00_00000824.wav \n inflating: ./valve/normal_id_00_00000825.wav \n inflating: ./valve/normal_id_00_00000826.wav \n inflating: ./valve/normal_id_00_00000827.wav \n inflating: ./valve/normal_id_00_00000828.wav \n inflating: ./valve/normal_id_00_00000829.wav \n inflating: ./valve/normal_id_00_00000830.wav \n inflating: ./valve/normal_id_00_00000831.wav \n inflating: ./valve/normal_id_00_00000832.wav \n inflating: ./valve/normal_id_00_00000833.wav \n inflating: ./valve/normal_id_00_00000834.wav \n inflating: ./valve/normal_id_00_00000835.wav \n inflating: ./valve/normal_id_00_00000836.wav \n inflating: ./valve/normal_id_00_00000837.wav \n inflating: ./valve/normal_id_00_00000838.wav \n inflating: ./valve/normal_id_00_00000839.wav \n inflating: ./valve/normal_id_00_00000840.wav \n inflating: ./valve/normal_id_00_00000841.wav \n inflating: ./valve/normal_id_00_00000842.wav \n inflating: ./valve/normal_id_00_00000843.wav \n inflating: ./valve/normal_id_00_00000844.wav \n inflating: ./valve/normal_id_00_00000845.wav \n inflating: ./valve/normal_id_00_00000846.wav \n inflating: ./valve/normal_id_00_00000847.wav \n inflating: ./valve/normal_id_00_00000848.wav \n inflating: ./valve/normal_id_00_00000849.wav \n inflating: ./valve/normal_id_00_00000850.wav \n inflating: ./valve/normal_id_00_00000851.wav \n inflating: ./valve/normal_id_00_00000852.wav \n inflating: ./valve/normal_id_00_00000853.wav \n inflating: ./valve/normal_id_00_00000854.wav \n inflating: ./valve/normal_id_00_00000855.wav \n inflating: ./valve/normal_id_00_00000856.wav \n inflating: ./valve/normal_id_00_00000857.wav \n inflating: ./valve/normal_id_00_00000858.wav \n inflating: ./valve/normal_id_00_00000859.wav \n inflating: ./valve/normal_id_00_00000860.wav \n inflating: ./valve/normal_id_00_00000861.wav \n inflating: ./valve/normal_id_00_00000862.wav \n inflating: ./valve/normal_id_00_00000863.wav \n inflating: ./valve/normal_id_00_00000864.wav \n inflating: ./valve/normal_id_00_00000865.wav \n inflating: ./valve/normal_id_00_00000866.wav \n inflating: ./valve/normal_id_00_00000867.wav \n inflating: ./valve/normal_id_00_00000868.wav \n inflating: ./valve/normal_id_00_00000869.wav \n inflating: ./valve/normal_id_00_00000870.wav \n inflating: ./valve/normal_id_00_00000871.wav \n inflating: ./valve/normal_id_00_00000872.wav \n inflating: ./valve/normal_id_00_00000873.wav \n inflating: ./valve/normal_id_00_00000874.wav \n inflating: ./valve/normal_id_00_00000875.wav \n inflating: ./valve/normal_id_00_00000876.wav \n inflating: ./valve/normal_id_00_00000877.wav \n inflating: ./valve/normal_id_00_00000878.wav \n inflating: ./valve/normal_id_00_00000879.wav \n inflating: ./valve/normal_id_00_00000880.wav \n inflating: ./valve/normal_id_00_00000881.wav \n inflating: ./valve/normal_id_00_00000882.wav \n inflating: ./valve/normal_id_00_00000883.wav \n inflating: ./valve/normal_id_00_00000884.wav \n inflating: ./valve/normal_id_00_00000885.wav \n inflating: ./valve/normal_id_00_00000886.wav \n inflating: ./valve/normal_id_00_00000887.wav \n inflating: ./valve/normal_id_00_00000888.wav \n inflating: ./valve/normal_id_00_00000889.wav \n inflating: ./valve/normal_id_00_00000890.wav \n inflating: ./valve/normal_id_02_00000000.wav \n inflating: ./valve/normal_id_02_00000001.wav \n inflating: ./valve/normal_id_02_00000002.wav \n inflating: ./valve/normal_id_02_00000003.wav \n inflating: ./valve/normal_id_02_00000004.wav \n inflating: ./valve/normal_id_02_00000005.wav \n inflating: ./valve/normal_id_02_00000006.wav \n inflating: ./valve/normal_id_02_00000007.wav \n inflating: ./valve/normal_id_02_00000008.wav \n inflating: ./valve/normal_id_02_00000009.wav \n inflating: ./valve/normal_id_02_00000010.wav \n inflating: ./valve/normal_id_02_00000011.wav \n inflating: ./valve/normal_id_02_00000012.wav \n inflating: ./valve/normal_id_02_00000013.wav \n inflating: ./valve/normal_id_02_00000014.wav \n inflating: ./valve/normal_id_02_00000015.wav \n inflating: ./valve/normal_id_02_00000016.wav \n inflating: ./valve/normal_id_02_00000017.wav \n inflating: ./valve/normal_id_02_00000018.wav \n inflating: ./valve/normal_id_02_00000019.wav \n inflating: ./valve/normal_id_02_00000020.wav \n inflating: ./valve/normal_id_02_00000021.wav \n inflating: ./valve/normal_id_02_00000022.wav \n inflating: ./valve/normal_id_02_00000023.wav \n inflating: ./valve/normal_id_02_00000024.wav \n inflating: ./valve/normal_id_02_00000025.wav \n inflating: ./valve/normal_id_02_00000026.wav \n inflating: ./valve/normal_id_02_00000027.wav \n inflating: ./valve/normal_id_02_00000028.wav \n inflating: ./valve/normal_id_02_00000029.wav \n inflating: ./valve/normal_id_02_00000030.wav \n inflating: ./valve/normal_id_02_00000031.wav \n inflating: ./valve/normal_id_02_00000032.wav \n inflating: ./valve/normal_id_02_00000033.wav \n inflating: ./valve/normal_id_02_00000034.wav \n inflating: ./valve/normal_id_02_00000035.wav \n inflating: ./valve/normal_id_02_00000036.wav \n inflating: ./valve/normal_id_02_00000037.wav \n inflating: ./valve/normal_id_02_00000038.wav \n inflating: ./valve/normal_id_02_00000039.wav \n inflating: ./valve/normal_id_02_00000040.wav \n inflating: ./valve/normal_id_02_00000041.wav \n inflating: ./valve/normal_id_02_00000042.wav \n inflating: ./valve/normal_id_02_00000043.wav \n inflating: ./valve/normal_id_02_00000044.wav \n inflating: ./valve/normal_id_02_00000045.wav \n inflating: ./valve/normal_id_02_00000046.wav \n inflating: ./valve/normal_id_02_00000047.wav \n inflating: ./valve/normal_id_02_00000048.wav \n inflating: ./valve/normal_id_02_00000049.wav \n inflating: ./valve/normal_id_02_00000050.wav \n inflating: ./valve/normal_id_02_00000051.wav \n inflating: ./valve/normal_id_02_00000052.wav \n inflating: ./valve/normal_id_02_00000053.wav \n inflating: ./valve/normal_id_02_00000054.wav \n inflating: ./valve/normal_id_02_00000055.wav \n inflating: ./valve/normal_id_02_00000056.wav \n inflating: ./valve/normal_id_02_00000057.wav \n inflating: ./valve/normal_id_02_00000058.wav \n inflating: ./valve/normal_id_02_00000059.wav \n inflating: ./valve/normal_id_02_00000060.wav \n inflating: ./valve/normal_id_02_00000061.wav \n inflating: ./valve/normal_id_02_00000062.wav \n inflating: ./valve/normal_id_02_00000063.wav \n inflating: ./valve/normal_id_02_00000064.wav \n inflating: ./valve/normal_id_02_00000065.wav \n inflating: ./valve/normal_id_02_00000066.wav \n inflating: ./valve/normal_id_02_00000067.wav \n inflating: ./valve/normal_id_02_00000068.wav \n inflating: ./valve/normal_id_02_00000069.wav \n inflating: ./valve/normal_id_02_00000070.wav \n inflating: ./valve/normal_id_02_00000071.wav \n inflating: ./valve/normal_id_02_00000072.wav \n inflating: ./valve/normal_id_02_00000073.wav \n inflating: ./valve/normal_id_02_00000074.wav \n inflating: ./valve/normal_id_02_00000075.wav \n inflating: ./valve/normal_id_02_00000076.wav \n inflating: ./valve/normal_id_02_00000077.wav \n inflating: ./valve/normal_id_02_00000078.wav \n inflating: ./valve/normal_id_02_00000079.wav \n inflating: ./valve/normal_id_02_00000080.wav \n inflating: ./valve/normal_id_02_00000081.wav \n inflating: ./valve/normal_id_02_00000082.wav \n inflating: ./valve/normal_id_02_00000083.wav \n inflating: ./valve/normal_id_02_00000084.wav \n inflating: ./valve/normal_id_02_00000085.wav \n inflating: ./valve/normal_id_02_00000086.wav \n inflating: ./valve/normal_id_02_00000087.wav \n inflating: ./valve/normal_id_02_00000088.wav \n inflating: ./valve/normal_id_02_00000089.wav \n inflating: ./valve/normal_id_02_00000090.wav \n inflating: ./valve/normal_id_02_00000091.wav \n inflating: ./valve/normal_id_02_00000092.wav \n inflating: ./valve/normal_id_02_00000093.wav \n inflating: ./valve/normal_id_02_00000094.wav \n inflating: ./valve/normal_id_02_00000095.wav \n inflating: ./valve/normal_id_02_00000096.wav \n inflating: ./valve/normal_id_02_00000097.wav \n inflating: ./valve/normal_id_02_00000098.wav \n inflating: ./valve/normal_id_02_00000099.wav \n inflating: ./valve/normal_id_02_00000100.wav \n inflating: ./valve/normal_id_02_00000101.wav \n inflating: ./valve/normal_id_02_00000102.wav \n inflating: ./valve/normal_id_02_00000103.wav \n inflating: ./valve/normal_id_02_00000104.wav \n inflating: ./valve/normal_id_02_00000105.wav \n inflating: ./valve/normal_id_02_00000106.wav \n inflating: ./valve/normal_id_02_00000107.wav \n inflating: ./valve/normal_id_02_00000108.wav \n inflating: ./valve/normal_id_02_00000109.wav \n inflating: ./valve/normal_id_02_00000110.wav \n inflating: ./valve/normal_id_02_00000111.wav \n inflating: ./valve/normal_id_02_00000112.wav \n inflating: ./valve/normal_id_02_00000113.wav \n inflating: ./valve/normal_id_02_00000114.wav \n inflating: ./valve/normal_id_02_00000115.wav \n inflating: ./valve/normal_id_02_00000116.wav \n inflating: ./valve/normal_id_02_00000117.wav \n inflating: ./valve/normal_id_02_00000118.wav \n inflating: ./valve/normal_id_02_00000119.wav \n inflating: ./valve/normal_id_02_00000120.wav \n inflating: ./valve/normal_id_02_00000121.wav \n inflating: ./valve/normal_id_02_00000122.wav \n inflating: ./valve/normal_id_02_00000123.wav \n inflating: ./valve/normal_id_02_00000124.wav \n inflating: ./valve/normal_id_02_00000125.wav \n inflating: ./valve/normal_id_02_00000126.wav \n inflating: ./valve/normal_id_02_00000127.wav \n inflating: ./valve/normal_id_02_00000128.wav \n inflating: ./valve/normal_id_02_00000129.wav \n inflating: ./valve/normal_id_02_00000130.wav \n inflating: ./valve/normal_id_02_00000131.wav \n inflating: ./valve/normal_id_02_00000132.wav \n inflating: ./valve/normal_id_02_00000133.wav \n inflating: ./valve/normal_id_02_00000134.wav \n inflating: ./valve/normal_id_02_00000135.wav \n inflating: ./valve/normal_id_02_00000136.wav \n inflating: ./valve/normal_id_02_00000137.wav \n inflating: ./valve/normal_id_02_00000138.wav \n inflating: ./valve/normal_id_02_00000139.wav \n inflating: ./valve/normal_id_02_00000140.wav \n inflating: ./valve/normal_id_02_00000141.wav \n inflating: ./valve/normal_id_02_00000142.wav \n inflating: ./valve/normal_id_02_00000143.wav \n inflating: ./valve/normal_id_02_00000144.wav \n inflating: ./valve/normal_id_02_00000145.wav \n inflating: ./valve/normal_id_02_00000146.wav \n inflating: ./valve/normal_id_02_00000147.wav \n inflating: ./valve/normal_id_02_00000148.wav \n inflating: ./valve/normal_id_02_00000149.wav \n inflating: ./valve/normal_id_02_00000150.wav \n inflating: ./valve/normal_id_02_00000151.wav \n inflating: ./valve/normal_id_02_00000152.wav \n inflating: ./valve/normal_id_02_00000153.wav \n inflating: ./valve/normal_id_02_00000154.wav \n inflating: ./valve/normal_id_02_00000155.wav \n inflating: ./valve/normal_id_02_00000156.wav \n inflating: ./valve/normal_id_02_00000157.wav \n inflating: ./valve/normal_id_02_00000158.wav \n inflating: ./valve/normal_id_02_00000159.wav \n inflating: ./valve/normal_id_02_00000160.wav \n inflating: ./valve/normal_id_02_00000161.wav \n inflating: ./valve/normal_id_02_00000162.wav \n inflating: ./valve/normal_id_02_00000163.wav \n inflating: ./valve/normal_id_02_00000164.wav \n inflating: ./valve/normal_id_02_00000165.wav \n inflating: ./valve/normal_id_02_00000166.wav \n inflating: ./valve/normal_id_02_00000167.wav \n inflating: ./valve/normal_id_02_00000168.wav \n inflating: ./valve/normal_id_02_00000169.wav \n inflating: ./valve/normal_id_02_00000170.wav \n inflating: ./valve/normal_id_02_00000171.wav \n inflating: ./valve/normal_id_02_00000172.wav \n inflating: ./valve/normal_id_02_00000173.wav \n inflating: ./valve/normal_id_02_00000174.wav \n inflating: ./valve/normal_id_02_00000175.wav \n inflating: ./valve/normal_id_02_00000176.wav \n inflating: ./valve/normal_id_02_00000177.wav \n inflating: ./valve/normal_id_02_00000178.wav \n inflating: ./valve/normal_id_02_00000179.wav \n inflating: ./valve/normal_id_02_00000180.wav \n inflating: ./valve/normal_id_02_00000181.wav \n inflating: ./valve/normal_id_02_00000182.wav \n inflating: ./valve/normal_id_02_00000183.wav \n inflating: ./valve/normal_id_02_00000184.wav \n inflating: ./valve/normal_id_02_00000185.wav \n inflating: ./valve/normal_id_02_00000186.wav \n inflating: ./valve/normal_id_02_00000187.wav \n inflating: ./valve/normal_id_02_00000188.wav \n inflating: ./valve/normal_id_02_00000189.wav \n inflating: ./valve/normal_id_02_00000190.wav \n inflating: ./valve/normal_id_02_00000191.wav \n inflating: ./valve/normal_id_02_00000192.wav \n inflating: ./valve/normal_id_02_00000193.wav \n inflating: ./valve/normal_id_02_00000194.wav \n inflating: ./valve/normal_id_02_00000195.wav \n inflating: ./valve/normal_id_02_00000196.wav \n inflating: ./valve/normal_id_02_00000197.wav \n inflating: ./valve/normal_id_02_00000198.wav \n inflating: ./valve/normal_id_02_00000199.wav \n inflating: ./valve/normal_id_02_00000200.wav \n inflating: ./valve/normal_id_02_00000201.wav \n inflating: ./valve/normal_id_02_00000202.wav \n inflating: ./valve/normal_id_02_00000203.wav \n inflating: ./valve/normal_id_02_00000204.wav \n inflating: ./valve/normal_id_02_00000205.wav \n inflating: ./valve/normal_id_02_00000206.wav \n inflating: ./valve/normal_id_02_00000207.wav \n inflating: ./valve/normal_id_02_00000208.wav \n inflating: ./valve/normal_id_02_00000209.wav \n inflating: ./valve/normal_id_02_00000210.wav \n inflating: ./valve/normal_id_02_00000211.wav \n inflating: ./valve/normal_id_02_00000212.wav \n inflating: ./valve/normal_id_02_00000213.wav \n inflating: ./valve/normal_id_02_00000214.wav \n inflating: ./valve/normal_id_02_00000215.wav \n inflating: ./valve/normal_id_02_00000216.wav \n inflating: ./valve/normal_id_02_00000217.wav \n inflating: ./valve/normal_id_02_00000218.wav \n inflating: ./valve/normal_id_02_00000219.wav \n inflating: ./valve/normal_id_02_00000220.wav \n inflating: ./valve/normal_id_02_00000221.wav \n inflating: ./valve/normal_id_02_00000222.wav \n inflating: ./valve/normal_id_02_00000223.wav \n inflating: ./valve/normal_id_02_00000224.wav \n inflating: ./valve/normal_id_02_00000225.wav \n inflating: ./valve/normal_id_02_00000226.wav \n inflating: ./valve/normal_id_02_00000227.wav \n inflating: ./valve/normal_id_02_00000228.wav \n inflating: ./valve/normal_id_02_00000229.wav \n inflating: ./valve/normal_id_02_00000230.wav \n inflating: ./valve/normal_id_02_00000231.wav \n inflating: ./valve/normal_id_02_00000232.wav \n inflating: ./valve/normal_id_02_00000233.wav \n inflating: ./valve/normal_id_02_00000234.wav \n inflating: ./valve/normal_id_02_00000235.wav \n inflating: ./valve/normal_id_02_00000236.wav \n inflating: ./valve/normal_id_02_00000237.wav \n inflating: ./valve/normal_id_02_00000238.wav \n inflating: ./valve/normal_id_02_00000239.wav \n inflating: ./valve/normal_id_02_00000240.wav \n inflating: ./valve/normal_id_02_00000241.wav \n inflating: ./valve/normal_id_02_00000242.wav \n inflating: ./valve/normal_id_02_00000243.wav \n inflating: ./valve/normal_id_02_00000244.wav \n inflating: ./valve/normal_id_02_00000245.wav \n inflating: ./valve/normal_id_02_00000246.wav \n inflating: ./valve/normal_id_02_00000247.wav \n inflating: ./valve/normal_id_02_00000248.wav \n inflating: ./valve/normal_id_02_00000249.wav \n inflating: ./valve/normal_id_02_00000250.wav \n inflating: ./valve/normal_id_02_00000251.wav \n inflating: ./valve/normal_id_02_00000252.wav \n inflating: ./valve/normal_id_02_00000253.wav \n inflating: ./valve/normal_id_02_00000254.wav \n inflating: ./valve/normal_id_02_00000255.wav \n inflating: ./valve/normal_id_02_00000256.wav \n inflating: ./valve/normal_id_02_00000257.wav \n inflating: ./valve/normal_id_02_00000258.wav \n inflating: ./valve/normal_id_02_00000259.wav \n inflating: ./valve/normal_id_02_00000260.wav \n inflating: ./valve/normal_id_02_00000261.wav \n inflating: ./valve/normal_id_02_00000262.wav \n inflating: ./valve/normal_id_02_00000263.wav \n inflating: ./valve/normal_id_02_00000264.wav \n inflating: ./valve/normal_id_02_00000265.wav \n inflating: ./valve/normal_id_02_00000266.wav \n inflating: ./valve/normal_id_02_00000267.wav \n inflating: ./valve/normal_id_02_00000268.wav \n inflating: ./valve/normal_id_02_00000269.wav \n inflating: ./valve/normal_id_02_00000270.wav \n inflating: ./valve/normal_id_02_00000271.wav \n inflating: ./valve/normal_id_02_00000272.wav \n inflating: ./valve/normal_id_02_00000273.wav \n inflating: ./valve/normal_id_02_00000274.wav \n inflating: ./valve/normal_id_02_00000275.wav \n inflating: ./valve/normal_id_02_00000276.wav \n inflating: ./valve/normal_id_02_00000277.wav \n inflating: ./valve/normal_id_02_00000278.wav \n inflating: ./valve/normal_id_02_00000279.wav \n inflating: ./valve/normal_id_02_00000280.wav \n inflating: ./valve/normal_id_02_00000281.wav \n inflating: ./valve/normal_id_02_00000282.wav \n inflating: ./valve/normal_id_02_00000283.wav \n inflating: ./valve/normal_id_02_00000284.wav \n inflating: ./valve/normal_id_02_00000285.wav \n inflating: ./valve/normal_id_02_00000286.wav \n inflating: ./valve/normal_id_02_00000287.wav \n inflating: ./valve/normal_id_02_00000288.wav \n inflating: ./valve/normal_id_02_00000289.wav \n inflating: ./valve/normal_id_02_00000290.wav \n inflating: ./valve/normal_id_02_00000291.wav \n inflating: ./valve/normal_id_02_00000292.wav \n inflating: ./valve/normal_id_02_00000293.wav \n inflating: ./valve/normal_id_02_00000294.wav \n inflating: ./valve/normal_id_02_00000295.wav \n inflating: ./valve/normal_id_02_00000296.wav \n inflating: ./valve/normal_id_02_00000297.wav \n inflating: ./valve/normal_id_02_00000298.wav \n inflating: ./valve/normal_id_02_00000299.wav \n inflating: ./valve/normal_id_02_00000300.wav \n inflating: ./valve/normal_id_02_00000301.wav \n inflating: ./valve/normal_id_02_00000302.wav \n inflating: ./valve/normal_id_02_00000303.wav \n inflating: ./valve/normal_id_02_00000304.wav \n inflating: ./valve/normal_id_02_00000305.wav \n inflating: ./valve/normal_id_02_00000306.wav \n inflating: ./valve/normal_id_02_00000307.wav \n inflating: ./valve/normal_id_02_00000308.wav \n inflating: ./valve/normal_id_02_00000309.wav \n inflating: ./valve/normal_id_02_00000310.wav \n inflating: ./valve/normal_id_02_00000311.wav \n inflating: ./valve/normal_id_02_00000312.wav \n inflating: ./valve/normal_id_02_00000313.wav \n inflating: ./valve/normal_id_02_00000314.wav \n inflating: ./valve/normal_id_02_00000315.wav \n inflating: ./valve/normal_id_02_00000316.wav \n inflating: ./valve/normal_id_02_00000317.wav \n inflating: ./valve/normal_id_02_00000318.wav \n inflating: ./valve/normal_id_02_00000319.wav \n inflating: ./valve/normal_id_02_00000320.wav \n inflating: ./valve/normal_id_02_00000321.wav \n inflating: ./valve/normal_id_02_00000322.wav \n inflating: ./valve/normal_id_02_00000323.wav \n inflating: ./valve/normal_id_02_00000324.wav \n inflating: ./valve/normal_id_02_00000325.wav \n inflating: ./valve/normal_id_02_00000326.wav \n inflating: ./valve/normal_id_02_00000327.wav \n inflating: ./valve/normal_id_02_00000328.wav \n inflating: ./valve/normal_id_02_00000329.wav \n inflating: ./valve/normal_id_02_00000330.wav \n inflating: ./valve/normal_id_02_00000331.wav \n inflating: ./valve/normal_id_02_00000332.wav \n inflating: ./valve/normal_id_02_00000333.wav \n inflating: ./valve/normal_id_02_00000334.wav \n inflating: ./valve/normal_id_02_00000335.wav \n inflating: ./valve/normal_id_02_00000336.wav \n inflating: ./valve/normal_id_02_00000337.wav \n inflating: ./valve/normal_id_02_00000338.wav \n inflating: ./valve/normal_id_02_00000339.wav \n inflating: ./valve/normal_id_02_00000340.wav \n inflating: ./valve/normal_id_02_00000341.wav \n inflating: ./valve/normal_id_02_00000342.wav \n inflating: ./valve/normal_id_02_00000343.wav \n inflating: ./valve/normal_id_02_00000344.wav \n inflating: ./valve/normal_id_02_00000345.wav \n inflating: ./valve/normal_id_02_00000346.wav \n inflating: ./valve/normal_id_02_00000347.wav \n inflating: ./valve/normal_id_02_00000348.wav \n inflating: ./valve/normal_id_02_00000349.wav \n inflating: ./valve/normal_id_02_00000350.wav \n inflating: ./valve/normal_id_02_00000351.wav \n inflating: ./valve/normal_id_02_00000352.wav \n inflating: ./valve/normal_id_02_00000353.wav \n inflating: ./valve/normal_id_02_00000354.wav \n inflating: ./valve/normal_id_02_00000355.wav \n inflating: ./valve/normal_id_02_00000356.wav \n inflating: ./valve/normal_id_02_00000357.wav \n inflating: ./valve/normal_id_02_00000358.wav \n inflating: ./valve/normal_id_02_00000359.wav \n inflating: ./valve/normal_id_02_00000360.wav \n inflating: ./valve/normal_id_02_00000361.wav \n inflating: ./valve/normal_id_02_00000362.wav \n inflating: ./valve/normal_id_02_00000363.wav \n inflating: ./valve/normal_id_02_00000364.wav \n inflating: ./valve/normal_id_02_00000365.wav \n inflating: ./valve/normal_id_02_00000366.wav \n inflating: ./valve/normal_id_02_00000367.wav \n inflating: ./valve/normal_id_02_00000368.wav \n inflating: ./valve/normal_id_02_00000369.wav \n inflating: ./valve/normal_id_02_00000370.wav \n inflating: ./valve/normal_id_02_00000371.wav \n inflating: ./valve/normal_id_02_00000372.wav \n inflating: ./valve/normal_id_02_00000373.wav \n inflating: ./valve/normal_id_02_00000374.wav \n inflating: ./valve/normal_id_02_00000375.wav \n inflating: ./valve/normal_id_02_00000376.wav \n inflating: ./valve/normal_id_02_00000377.wav \n inflating: ./valve/normal_id_02_00000378.wav \n inflating: ./valve/normal_id_02_00000379.wav \n inflating: ./valve/normal_id_02_00000380.wav \n inflating: ./valve/normal_id_02_00000381.wav \n inflating: ./valve/normal_id_02_00000382.wav \n inflating: ./valve/normal_id_02_00000383.wav \n inflating: ./valve/normal_id_02_00000384.wav \n inflating: ./valve/normal_id_02_00000385.wav \n inflating: ./valve/normal_id_02_00000386.wav \n inflating: ./valve/normal_id_02_00000387.wav \n inflating: ./valve/normal_id_02_00000388.wav \n inflating: ./valve/normal_id_02_00000389.wav \n inflating: ./valve/normal_id_02_00000390.wav \n inflating: ./valve/normal_id_02_00000391.wav \n inflating: ./valve/normal_id_02_00000392.wav \n inflating: ./valve/normal_id_02_00000393.wav \n inflating: ./valve/normal_id_02_00000394.wav \n inflating: ./valve/normal_id_02_00000395.wav \n inflating: ./valve/normal_id_02_00000396.wav \n inflating: ./valve/normal_id_02_00000397.wav \n inflating: ./valve/normal_id_02_00000398.wav \n inflating: ./valve/normal_id_02_00000399.wav \n inflating: ./valve/normal_id_02_00000400.wav \n inflating: ./valve/normal_id_02_00000401.wav \n inflating: ./valve/normal_id_02_00000402.wav \n inflating: ./valve/normal_id_02_00000403.wav \n inflating: ./valve/normal_id_02_00000404.wav \n inflating: ./valve/normal_id_02_00000405.wav \n inflating: ./valve/normal_id_02_00000406.wav \n inflating: ./valve/normal_id_02_00000407.wav \n inflating: ./valve/normal_id_02_00000408.wav \n inflating: ./valve/normal_id_02_00000409.wav \n inflating: ./valve/normal_id_02_00000410.wav \n inflating: ./valve/normal_id_02_00000411.wav \n inflating: ./valve/normal_id_02_00000412.wav \n inflating: ./valve/normal_id_02_00000413.wav \n inflating: ./valve/normal_id_02_00000414.wav \n inflating: ./valve/normal_id_02_00000415.wav \n inflating: ./valve/normal_id_02_00000416.wav \n inflating: ./valve/normal_id_02_00000417.wav \n inflating: ./valve/normal_id_02_00000418.wav \n inflating: ./valve/normal_id_02_00000419.wav \n inflating: ./valve/normal_id_02_00000420.wav \n inflating: ./valve/normal_id_02_00000421.wav \n inflating: ./valve/normal_id_02_00000422.wav \n inflating: ./valve/normal_id_02_00000423.wav \n inflating: ./valve/normal_id_02_00000424.wav \n inflating: ./valve/normal_id_02_00000425.wav \n inflating: ./valve/normal_id_02_00000426.wav \n inflating: ./valve/normal_id_02_00000427.wav \n inflating: ./valve/normal_id_02_00000428.wav \n inflating: ./valve/normal_id_02_00000429.wav \n inflating: ./valve/normal_id_02_00000430.wav \n inflating: ./valve/normal_id_02_00000431.wav \n inflating: ./valve/normal_id_02_00000432.wav \n inflating: ./valve/normal_id_02_00000433.wav \n inflating: ./valve/normal_id_02_00000434.wav \n inflating: ./valve/normal_id_02_00000435.wav \n inflating: ./valve/normal_id_02_00000436.wav \n inflating: ./valve/normal_id_02_00000437.wav \n inflating: ./valve/normal_id_02_00000438.wav \n inflating: ./valve/normal_id_02_00000439.wav \n inflating: ./valve/normal_id_02_00000440.wav \n inflating: ./valve/normal_id_02_00000441.wav \n inflating: ./valve/normal_id_02_00000442.wav \n inflating: ./valve/normal_id_02_00000443.wav \n inflating: ./valve/normal_id_02_00000444.wav \n inflating: ./valve/normal_id_02_00000445.wav \n inflating: ./valve/normal_id_02_00000446.wav \n inflating: ./valve/normal_id_02_00000447.wav \n inflating: ./valve/normal_id_02_00000448.wav \n inflating: ./valve/normal_id_02_00000449.wav \n inflating: ./valve/normal_id_02_00000450.wav \n inflating: ./valve/normal_id_02_00000451.wav \n inflating: ./valve/normal_id_02_00000452.wav \n inflating: ./valve/normal_id_02_00000453.wav \n inflating: ./valve/normal_id_02_00000454.wav \n inflating: ./valve/normal_id_02_00000455.wav \n inflating: ./valve/normal_id_02_00000456.wav \n inflating: ./valve/normal_id_02_00000457.wav \n inflating: ./valve/normal_id_02_00000458.wav \n inflating: ./valve/normal_id_02_00000459.wav \n inflating: ./valve/normal_id_02_00000460.wav \n inflating: ./valve/normal_id_02_00000461.wav \n inflating: ./valve/normal_id_02_00000462.wav \n inflating: ./valve/normal_id_02_00000463.wav \n inflating: ./valve/normal_id_02_00000464.wav \n inflating: ./valve/normal_id_02_00000465.wav \n inflating: ./valve/normal_id_02_00000466.wav \n inflating: ./valve/normal_id_02_00000467.wav \n inflating: ./valve/normal_id_02_00000468.wav \n inflating: ./valve/normal_id_02_00000469.wav \n inflating: ./valve/normal_id_02_00000470.wav \n inflating: ./valve/normal_id_02_00000471.wav \n inflating: ./valve/normal_id_02_00000472.wav \n inflating: ./valve/normal_id_02_00000473.wav \n inflating: ./valve/normal_id_02_00000474.wav \n inflating: ./valve/normal_id_02_00000475.wav \n inflating: ./valve/normal_id_02_00000476.wav \n inflating: ./valve/normal_id_02_00000477.wav \n inflating: ./valve/normal_id_02_00000478.wav \n inflating: ./valve/normal_id_02_00000479.wav \n inflating: ./valve/normal_id_02_00000480.wav \n inflating: ./valve/normal_id_02_00000481.wav \n inflating: ./valve/normal_id_02_00000482.wav \n inflating: ./valve/normal_id_02_00000483.wav \n inflating: ./valve/normal_id_02_00000484.wav \n inflating: ./valve/normal_id_02_00000485.wav \n inflating: ./valve/normal_id_02_00000486.wav \n inflating: ./valve/normal_id_02_00000487.wav \n inflating: ./valve/normal_id_02_00000488.wav \n inflating: ./valve/normal_id_02_00000489.wav \n inflating: ./valve/normal_id_02_00000490.wav \n inflating: ./valve/normal_id_02_00000491.wav \n inflating: ./valve/normal_id_02_00000492.wav \n inflating: ./valve/normal_id_02_00000493.wav \n inflating: ./valve/normal_id_02_00000494.wav \n inflating: ./valve/normal_id_02_00000495.wav \n inflating: ./valve/normal_id_02_00000496.wav \n inflating: ./valve/normal_id_02_00000497.wav \n inflating: ./valve/normal_id_02_00000498.wav \n inflating: ./valve/normal_id_02_00000499.wav \n inflating: ./valve/normal_id_02_00000500.wav \n inflating: ./valve/normal_id_02_00000501.wav \n inflating: ./valve/normal_id_02_00000502.wav \n inflating: ./valve/normal_id_02_00000503.wav \n inflating: ./valve/normal_id_02_00000504.wav \n inflating: ./valve/normal_id_02_00000505.wav \n inflating: ./valve/normal_id_02_00000506.wav \n inflating: ./valve/normal_id_02_00000507.wav \n inflating: ./valve/normal_id_02_00000508.wav \n inflating: ./valve/normal_id_02_00000509.wav \n inflating: ./valve/normal_id_02_00000510.wav \n inflating: ./valve/normal_id_02_00000511.wav \n inflating: ./valve/normal_id_02_00000512.wav \n inflating: ./valve/normal_id_02_00000513.wav \n inflating: ./valve/normal_id_02_00000514.wav \n inflating: ./valve/normal_id_02_00000515.wav \n inflating: ./valve/normal_id_02_00000516.wav \n inflating: ./valve/normal_id_02_00000517.wav \n inflating: ./valve/normal_id_02_00000518.wav \n inflating: ./valve/normal_id_02_00000519.wav \n inflating: ./valve/normal_id_02_00000520.wav \n inflating: ./valve/normal_id_02_00000521.wav \n inflating: ./valve/normal_id_02_00000522.wav \n inflating: ./valve/normal_id_02_00000523.wav \n inflating: ./valve/normal_id_02_00000524.wav \n inflating: ./valve/normal_id_02_00000525.wav \n inflating: ./valve/normal_id_02_00000526.wav \n inflating: ./valve/normal_id_02_00000527.wav \n inflating: ./valve/normal_id_02_00000528.wav \n inflating: ./valve/normal_id_02_00000529.wav \n inflating: ./valve/normal_id_02_00000530.wav \n inflating: ./valve/normal_id_02_00000531.wav \n inflating: ./valve/normal_id_02_00000532.wav \n inflating: ./valve/normal_id_02_00000533.wav \n inflating: ./valve/normal_id_02_00000534.wav \n inflating: ./valve/normal_id_02_00000535.wav \n inflating: ./valve/normal_id_02_00000536.wav \n inflating: ./valve/normal_id_02_00000537.wav \n inflating: ./valve/normal_id_02_00000538.wav \n inflating: ./valve/normal_id_02_00000539.wav \n inflating: ./valve/normal_id_02_00000540.wav \n inflating: ./valve/normal_id_02_00000541.wav \n inflating: ./valve/normal_id_02_00000542.wav \n inflating: ./valve/normal_id_02_00000543.wav \n inflating: ./valve/normal_id_02_00000544.wav \n inflating: ./valve/normal_id_02_00000545.wav \n inflating: ./valve/normal_id_02_00000546.wav \n inflating: ./valve/normal_id_02_00000547.wav \n inflating: ./valve/normal_id_02_00000548.wav \n inflating: ./valve/normal_id_02_00000549.wav \n inflating: ./valve/normal_id_02_00000550.wav \n inflating: ./valve/normal_id_02_00000551.wav \n inflating: ./valve/normal_id_02_00000552.wav \n inflating: ./valve/normal_id_02_00000553.wav \n inflating: ./valve/normal_id_02_00000554.wav \n inflating: ./valve/normal_id_02_00000555.wav \n inflating: ./valve/normal_id_02_00000556.wav \n inflating: ./valve/normal_id_02_00000557.wav \n inflating: ./valve/normal_id_02_00000558.wav \n inflating: ./valve/normal_id_02_00000559.wav \n inflating: ./valve/normal_id_02_00000560.wav \n inflating: ./valve/normal_id_02_00000561.wav \n inflating: ./valve/normal_id_02_00000562.wav \n inflating: ./valve/normal_id_02_00000563.wav \n inflating: ./valve/normal_id_02_00000564.wav \n inflating: ./valve/normal_id_02_00000565.wav \n inflating: ./valve/normal_id_02_00000566.wav \n inflating: ./valve/normal_id_02_00000567.wav \n inflating: ./valve/normal_id_02_00000568.wav \n inflating: ./valve/normal_id_02_00000569.wav \n inflating: ./valve/normal_id_02_00000570.wav \n inflating: ./valve/normal_id_02_00000571.wav \n inflating: ./valve/normal_id_02_00000572.wav \n inflating: ./valve/normal_id_02_00000573.wav \n inflating: ./valve/normal_id_02_00000574.wav \n inflating: ./valve/normal_id_02_00000575.wav \n inflating: ./valve/normal_id_02_00000576.wav \n inflating: ./valve/normal_id_02_00000577.wav \n inflating: ./valve/normal_id_02_00000578.wav \n inflating: ./valve/normal_id_02_00000579.wav \n inflating: ./valve/normal_id_02_00000580.wav \n inflating: ./valve/normal_id_02_00000581.wav \n inflating: ./valve/normal_id_02_00000582.wav \n inflating: ./valve/normal_id_02_00000583.wav \n inflating: ./valve/normal_id_02_00000584.wav \n inflating: ./valve/normal_id_02_00000585.wav \n inflating: ./valve/normal_id_02_00000586.wav \n inflating: ./valve/normal_id_02_00000587.wav \n inflating: ./valve/normal_id_02_00000588.wav \n inflating: ./valve/normal_id_02_00000589.wav \n inflating: ./valve/normal_id_02_00000590.wav \n inflating: ./valve/normal_id_02_00000591.wav \n inflating: ./valve/normal_id_02_00000592.wav \n inflating: ./valve/normal_id_02_00000593.wav \n inflating: ./valve/normal_id_02_00000594.wav \n inflating: ./valve/normal_id_02_00000595.wav \n inflating: ./valve/normal_id_02_00000596.wav \n inflating: ./valve/normal_id_02_00000597.wav \n inflating: ./valve/normal_id_02_00000598.wav \n inflating: ./valve/normal_id_02_00000599.wav \n inflating: ./valve/normal_id_02_00000600.wav \n inflating: ./valve/normal_id_02_00000601.wav \n inflating: ./valve/normal_id_02_00000602.wav \n inflating: ./valve/normal_id_02_00000603.wav \n inflating: ./valve/normal_id_02_00000604.wav \n inflating: ./valve/normal_id_02_00000605.wav \n inflating: ./valve/normal_id_02_00000606.wav \n inflating: ./valve/normal_id_02_00000607.wav \n inflating: ./valve/normal_id_04_00000000.wav \n inflating: ./valve/normal_id_04_00000001.wav \n inflating: ./valve/normal_id_04_00000002.wav \n inflating: ./valve/normal_id_04_00000003.wav \n inflating: ./valve/normal_id_04_00000004.wav \n inflating: ./valve/normal_id_04_00000005.wav \n inflating: ./valve/normal_id_04_00000006.wav \n inflating: ./valve/normal_id_04_00000007.wav \n inflating: ./valve/normal_id_04_00000008.wav \n inflating: ./valve/normal_id_04_00000009.wav \n inflating: ./valve/normal_id_04_00000010.wav \n inflating: ./valve/normal_id_04_00000011.wav \n inflating: ./valve/normal_id_04_00000012.wav \n inflating: ./valve/normal_id_04_00000013.wav \n inflating: ./valve/normal_id_04_00000014.wav \n inflating: ./valve/normal_id_04_00000015.wav \n inflating: ./valve/normal_id_04_00000016.wav \n inflating: ./valve/normal_id_04_00000017.wav \n inflating: ./valve/normal_id_04_00000018.wav \n inflating: ./valve/normal_id_04_00000019.wav \n inflating: ./valve/normal_id_04_00000020.wav \n inflating: ./valve/normal_id_04_00000021.wav \n inflating: ./valve/normal_id_04_00000022.wav \n inflating: ./valve/normal_id_04_00000023.wav \n inflating: ./valve/normal_id_04_00000024.wav \n inflating: ./valve/normal_id_04_00000025.wav \n inflating: ./valve/normal_id_04_00000026.wav \n inflating: ./valve/normal_id_04_00000027.wav \n inflating: ./valve/normal_id_04_00000028.wav \n inflating: ./valve/normal_id_04_00000029.wav \n inflating: ./valve/normal_id_04_00000030.wav \n inflating: ./valve/normal_id_04_00000031.wav \n inflating: ./valve/normal_id_04_00000032.wav \n inflating: ./valve/normal_id_04_00000033.wav \n inflating: ./valve/normal_id_04_00000034.wav \n inflating: ./valve/normal_id_04_00000035.wav \n inflating: ./valve/normal_id_04_00000036.wav \n inflating: ./valve/normal_id_04_00000037.wav \n inflating: ./valve/normal_id_04_00000038.wav \n inflating: ./valve/normal_id_04_00000039.wav \n inflating: ./valve/normal_id_04_00000040.wav \n inflating: ./valve/normal_id_04_00000041.wav \n inflating: ./valve/normal_id_04_00000042.wav \n inflating: ./valve/normal_id_04_00000043.wav \n inflating: ./valve/normal_id_04_00000044.wav \n inflating: ./valve/normal_id_04_00000045.wav \n inflating: ./valve/normal_id_04_00000046.wav \n inflating: ./valve/normal_id_04_00000047.wav \n inflating: ./valve/normal_id_04_00000048.wav \n inflating: ./valve/normal_id_04_00000049.wav \n inflating: ./valve/normal_id_04_00000050.wav \n inflating: ./valve/normal_id_04_00000051.wav \n inflating: ./valve/normal_id_04_00000052.wav \n inflating: ./valve/normal_id_04_00000053.wav \n inflating: ./valve/normal_id_04_00000054.wav \n inflating: ./valve/normal_id_04_00000055.wav \n inflating: ./valve/normal_id_04_00000056.wav \n inflating: ./valve/normal_id_04_00000057.wav \n inflating: ./valve/normal_id_04_00000058.wav \n inflating: ./valve/normal_id_04_00000059.wav \n inflating: ./valve/normal_id_04_00000060.wav \n inflating: ./valve/normal_id_04_00000061.wav \n inflating: ./valve/normal_id_04_00000062.wav \n inflating: ./valve/normal_id_04_00000063.wav \n inflating: ./valve/normal_id_04_00000064.wav \n inflating: ./valve/normal_id_04_00000065.wav \n inflating: ./valve/normal_id_04_00000066.wav \n inflating: ./valve/normal_id_04_00000067.wav \n inflating: ./valve/normal_id_04_00000068.wav \n inflating: ./valve/normal_id_04_00000069.wav \n inflating: ./valve/normal_id_04_00000070.wav \n inflating: ./valve/normal_id_04_00000071.wav \n inflating: ./valve/normal_id_04_00000072.wav \n inflating: ./valve/normal_id_04_00000073.wav \n inflating: ./valve/normal_id_04_00000074.wav \n inflating: ./valve/normal_id_04_00000075.wav \n inflating: ./valve/normal_id_04_00000076.wav \n inflating: ./valve/normal_id_04_00000077.wav \n inflating: ./valve/normal_id_04_00000078.wav \n inflating: ./valve/normal_id_04_00000079.wav \n inflating: ./valve/normal_id_04_00000080.wav \n inflating: ./valve/normal_id_04_00000081.wav \n inflating: ./valve/normal_id_04_00000082.wav \n inflating: ./valve/normal_id_04_00000083.wav \n inflating: ./valve/normal_id_04_00000084.wav \n inflating: ./valve/normal_id_04_00000085.wav \n inflating: ./valve/normal_id_04_00000086.wav \n inflating: ./valve/normal_id_04_00000087.wav \n inflating: ./valve/normal_id_04_00000088.wav \n inflating: ./valve/normal_id_04_00000089.wav \n inflating: ./valve/normal_id_04_00000090.wav \n inflating: ./valve/normal_id_04_00000091.wav \n inflating: ./valve/normal_id_04_00000092.wav \n inflating: ./valve/normal_id_04_00000093.wav \n inflating: ./valve/normal_id_04_00000094.wav \n inflating: ./valve/normal_id_04_00000095.wav \n inflating: ./valve/normal_id_04_00000096.wav \n inflating: ./valve/normal_id_04_00000097.wav \n inflating: ./valve/normal_id_04_00000098.wav \n inflating: ./valve/normal_id_04_00000099.wav \n inflating: ./valve/normal_id_04_00000100.wav \n inflating: ./valve/normal_id_04_00000101.wav \n inflating: ./valve/normal_id_04_00000102.wav \n inflating: ./valve/normal_id_04_00000103.wav \n inflating: ./valve/normal_id_04_00000104.wav \n inflating: ./valve/normal_id_04_00000105.wav \n inflating: ./valve/normal_id_04_00000106.wav \n inflating: ./valve/normal_id_04_00000107.wav \n inflating: ./valve/normal_id_04_00000108.wav \n inflating: ./valve/normal_id_04_00000109.wav \n inflating: ./valve/normal_id_04_00000110.wav \n inflating: ./valve/normal_id_04_00000111.wav \n inflating: ./valve/normal_id_04_00000112.wav \n inflating: ./valve/normal_id_04_00000113.wav \n inflating: ./valve/normal_id_04_00000114.wav \n inflating: ./valve/normal_id_04_00000115.wav \n inflating: ./valve/normal_id_04_00000116.wav \n inflating: ./valve/normal_id_04_00000117.wav \n inflating: ./valve/normal_id_04_00000118.wav \n inflating: ./valve/normal_id_04_00000119.wav \n inflating: ./valve/normal_id_04_00000120.wav \n inflating: ./valve/normal_id_04_00000121.wav \n inflating: ./valve/normal_id_04_00000122.wav \n inflating: ./valve/normal_id_04_00000123.wav \n inflating: ./valve/normal_id_04_00000124.wav \n inflating: ./valve/normal_id_04_00000125.wav \n inflating: ./valve/normal_id_04_00000126.wav \n inflating: ./valve/normal_id_04_00000127.wav \n inflating: ./valve/normal_id_04_00000128.wav \n inflating: ./valve/normal_id_04_00000129.wav \n inflating: ./valve/normal_id_04_00000130.wav \n inflating: ./valve/normal_id_04_00000131.wav \n inflating: ./valve/normal_id_04_00000132.wav \n inflating: ./valve/normal_id_04_00000133.wav \n inflating: ./valve/normal_id_04_00000134.wav \n inflating: ./valve/normal_id_04_00000135.wav \n inflating: ./valve/normal_id_04_00000136.wav \n inflating: ./valve/normal_id_04_00000137.wav \n inflating: ./valve/normal_id_04_00000138.wav \n inflating: ./valve/normal_id_04_00000139.wav \n inflating: ./valve/normal_id_04_00000140.wav \n inflating: ./valve/normal_id_04_00000141.wav \n inflating: ./valve/normal_id_04_00000142.wav \n inflating: ./valve/normal_id_04_00000143.wav \n inflating: ./valve/normal_id_04_00000144.wav \n inflating: ./valve/normal_id_04_00000145.wav \n inflating: ./valve/normal_id_04_00000146.wav \n inflating: ./valve/normal_id_04_00000147.wav \n inflating: ./valve/normal_id_04_00000148.wav \n inflating: ./valve/normal_id_04_00000149.wav \n inflating: ./valve/normal_id_04_00000150.wav \n inflating: ./valve/normal_id_04_00000151.wav \n inflating: ./valve/normal_id_04_00000152.wav \n inflating: ./valve/normal_id_04_00000153.wav \n inflating: ./valve/normal_id_04_00000154.wav \n inflating: ./valve/normal_id_04_00000155.wav \n inflating: ./valve/normal_id_04_00000156.wav \n inflating: ./valve/normal_id_04_00000157.wav \n inflating: ./valve/normal_id_04_00000158.wav \n inflating: ./valve/normal_id_04_00000159.wav \n inflating: ./valve/normal_id_04_00000160.wav \n inflating: ./valve/normal_id_04_00000161.wav \n inflating: ./valve/normal_id_04_00000162.wav \n inflating: ./valve/normal_id_04_00000163.wav \n inflating: ./valve/normal_id_04_00000164.wav \n inflating: ./valve/normal_id_04_00000165.wav \n inflating: ./valve/normal_id_04_00000166.wav \n inflating: ./valve/normal_id_04_00000167.wav \n inflating: ./valve/normal_id_04_00000168.wav \n inflating: ./valve/normal_id_04_00000169.wav \n inflating: ./valve/normal_id_04_00000170.wav \n inflating: ./valve/normal_id_04_00000171.wav \n inflating: ./valve/normal_id_04_00000172.wav \n inflating: ./valve/normal_id_04_00000173.wav \n inflating: ./valve/normal_id_04_00000174.wav \n inflating: ./valve/normal_id_04_00000175.wav \n inflating: ./valve/normal_id_04_00000176.wav \n inflating: ./valve/normal_id_04_00000177.wav \n inflating: ./valve/normal_id_04_00000178.wav \n inflating: ./valve/normal_id_04_00000179.wav \n inflating: ./valve/normal_id_04_00000180.wav \n inflating: ./valve/normal_id_04_00000181.wav \n inflating: ./valve/normal_id_04_00000182.wav \n inflating: ./valve/normal_id_04_00000183.wav \n inflating: ./valve/normal_id_04_00000184.wav \n inflating: ./valve/normal_id_04_00000185.wav \n inflating: ./valve/normal_id_04_00000186.wav \n inflating: ./valve/normal_id_04_00000187.wav \n inflating: ./valve/normal_id_04_00000188.wav \n inflating: ./valve/normal_id_04_00000189.wav \n inflating: ./valve/normal_id_04_00000190.wav \n inflating: ./valve/normal_id_04_00000191.wav \n inflating: ./valve/normal_id_04_00000192.wav \n inflating: ./valve/normal_id_04_00000193.wav \n inflating: ./valve/normal_id_04_00000194.wav \n inflating: ./valve/normal_id_04_00000195.wav \n inflating: ./valve/normal_id_04_00000196.wav \n inflating: ./valve/normal_id_04_00000197.wav \n inflating: ./valve/normal_id_04_00000198.wav \n inflating: ./valve/normal_id_04_00000199.wav \n inflating: ./valve/normal_id_04_00000200.wav \n inflating: ./valve/normal_id_04_00000201.wav \n inflating: ./valve/normal_id_04_00000202.wav \n inflating: ./valve/normal_id_04_00000203.wav \n inflating: ./valve/normal_id_04_00000204.wav \n inflating: ./valve/normal_id_04_00000205.wav \n inflating: ./valve/normal_id_04_00000206.wav \n inflating: ./valve/normal_id_04_00000207.wav \n inflating: ./valve/normal_id_04_00000208.wav \n inflating: ./valve/normal_id_04_00000209.wav \n inflating: ./valve/normal_id_04_00000210.wav \n inflating: ./valve/normal_id_04_00000211.wav \n inflating: ./valve/normal_id_04_00000212.wav \n inflating: ./valve/normal_id_04_00000213.wav \n inflating: ./valve/normal_id_04_00000214.wav \n inflating: ./valve/normal_id_04_00000215.wav \n inflating: ./valve/normal_id_04_00000216.wav \n inflating: ./valve/normal_id_04_00000217.wav \n inflating: ./valve/normal_id_04_00000218.wav \n inflating: ./valve/normal_id_04_00000219.wav \n inflating: ./valve/normal_id_04_00000220.wav \n inflating: ./valve/normal_id_04_00000221.wav \n inflating: ./valve/normal_id_04_00000222.wav \n inflating: ./valve/normal_id_04_00000223.wav \n inflating: ./valve/normal_id_04_00000224.wav \n inflating: ./valve/normal_id_04_00000225.wav \n inflating: ./valve/normal_id_04_00000226.wav \n inflating: ./valve/normal_id_04_00000227.wav \n inflating: ./valve/normal_id_04_00000228.wav \n inflating: ./valve/normal_id_04_00000229.wav \n inflating: ./valve/normal_id_04_00000230.wav \n inflating: ./valve/normal_id_04_00000231.wav \n inflating: ./valve/normal_id_04_00000232.wav \n inflating: ./valve/normal_id_04_00000233.wav \n inflating: ./valve/normal_id_04_00000234.wav \n inflating: ./valve/normal_id_04_00000235.wav \n inflating: ./valve/normal_id_04_00000236.wav \n inflating: ./valve/normal_id_04_00000237.wav \n inflating: ./valve/normal_id_04_00000238.wav \n inflating: ./valve/normal_id_04_00000239.wav \n inflating: ./valve/normal_id_04_00000240.wav \n inflating: ./valve/normal_id_04_00000241.wav \n inflating: ./valve/normal_id_04_00000242.wav \n inflating: ./valve/normal_id_04_00000243.wav \n inflating: ./valve/normal_id_04_00000244.wav \n inflating: ./valve/normal_id_04_00000245.wav \n inflating: ./valve/normal_id_04_00000246.wav \n inflating: ./valve/normal_id_04_00000247.wav \n inflating: ./valve/normal_id_04_00000248.wav \n inflating: ./valve/normal_id_04_00000249.wav \n inflating: ./valve/normal_id_04_00000250.wav \n inflating: ./valve/normal_id_04_00000251.wav \n inflating: ./valve/normal_id_04_00000252.wav \n inflating: ./valve/normal_id_04_00000253.wav \n inflating: ./valve/normal_id_04_00000254.wav \n inflating: ./valve/normal_id_04_00000255.wav \n inflating: ./valve/normal_id_04_00000256.wav \n inflating: ./valve/normal_id_04_00000257.wav \n inflating: ./valve/normal_id_04_00000258.wav \n inflating: ./valve/normal_id_04_00000259.wav \n inflating: ./valve/normal_id_04_00000260.wav \n inflating: ./valve/normal_id_04_00000261.wav \n inflating: ./valve/normal_id_04_00000262.wav \n inflating: ./valve/normal_id_04_00000263.wav \n inflating: ./valve/normal_id_04_00000264.wav \n inflating: ./valve/normal_id_04_00000265.wav \n inflating: ./valve/normal_id_04_00000266.wav \n inflating: ./valve/normal_id_04_00000267.wav \n inflating: ./valve/normal_id_04_00000268.wav \n inflating: ./valve/normal_id_04_00000269.wav \n inflating: ./valve/normal_id_04_00000270.wav \n inflating: ./valve/normal_id_04_00000271.wav \n inflating: ./valve/normal_id_04_00000272.wav \n inflating: ./valve/normal_id_04_00000273.wav \n inflating: ./valve/normal_id_04_00000274.wav \n inflating: ./valve/normal_id_04_00000275.wav \n inflating: ./valve/normal_id_04_00000276.wav \n inflating: ./valve/normal_id_04_00000277.wav \n inflating: ./valve/normal_id_04_00000278.wav \n inflating: ./valve/normal_id_04_00000279.wav \n inflating: ./valve/normal_id_04_00000280.wav \n inflating: ./valve/normal_id_04_00000281.wav \n inflating: ./valve/normal_id_04_00000282.wav \n inflating: ./valve/normal_id_04_00000283.wav \n inflating: ./valve/normal_id_04_00000284.wav \n inflating: ./valve/normal_id_04_00000285.wav \n inflating: ./valve/normal_id_04_00000286.wav \n inflating: ./valve/normal_id_04_00000287.wav \n inflating: ./valve/normal_id_04_00000288.wav \n inflating: ./valve/normal_id_04_00000289.wav \n inflating: ./valve/normal_id_04_00000290.wav \n inflating: ./valve/normal_id_04_00000291.wav \n inflating: ./valve/normal_id_04_00000292.wav \n inflating: ./valve/normal_id_04_00000293.wav \n inflating: ./valve/normal_id_04_00000294.wav \n inflating: ./valve/normal_id_04_00000295.wav \n inflating: ./valve/normal_id_04_00000296.wav \n inflating: ./valve/normal_id_04_00000297.wav \n inflating: ./valve/normal_id_04_00000298.wav \n inflating: ./valve/normal_id_04_00000299.wav \n inflating: ./valve/normal_id_04_00000300.wav \n inflating: ./valve/normal_id_04_00000301.wav \n inflating: ./valve/normal_id_04_00000302.wav \n inflating: ./valve/normal_id_04_00000303.wav \n inflating: ./valve/normal_id_04_00000304.wav \n inflating: ./valve/normal_id_04_00000305.wav \n inflating: ./valve/normal_id_04_00000306.wav \n inflating: ./valve/normal_id_04_00000307.wav \n inflating: ./valve/normal_id_04_00000308.wav \n inflating: ./valve/normal_id_04_00000309.wav \n inflating: ./valve/normal_id_04_00000310.wav \n inflating: ./valve/normal_id_04_00000311.wav \n inflating: ./valve/normal_id_04_00000312.wav \n inflating: ./valve/normal_id_04_00000313.wav \n inflating: ./valve/normal_id_04_00000314.wav \n inflating: ./valve/normal_id_04_00000315.wav \n inflating: ./valve/normal_id_04_00000316.wav \n inflating: ./valve/normal_id_04_00000317.wav \n inflating: ./valve/normal_id_04_00000318.wav \n inflating: ./valve/normal_id_04_00000319.wav \n inflating: ./valve/normal_id_04_00000320.wav \n inflating: ./valve/normal_id_04_00000321.wav \n inflating: ./valve/normal_id_04_00000322.wav \n inflating: ./valve/normal_id_04_00000323.wav \n inflating: ./valve/normal_id_04_00000324.wav \n inflating: ./valve/normal_id_04_00000325.wav \n inflating: ./valve/normal_id_04_00000326.wav \n inflating: ./valve/normal_id_04_00000327.wav \n inflating: ./valve/normal_id_04_00000328.wav \n inflating: ./valve/normal_id_04_00000329.wav \n inflating: ./valve/normal_id_04_00000330.wav \n inflating: ./valve/normal_id_04_00000331.wav \n inflating: ./valve/normal_id_04_00000332.wav \n inflating: ./valve/normal_id_04_00000333.wav \n inflating: ./valve/normal_id_04_00000334.wav \n inflating: ./valve/normal_id_04_00000335.wav \n inflating: ./valve/normal_id_04_00000336.wav \n inflating: ./valve/normal_id_04_00000337.wav \n inflating: ./valve/normal_id_04_00000338.wav \n inflating: ./valve/normal_id_04_00000339.wav \n inflating: ./valve/normal_id_04_00000340.wav \n inflating: ./valve/normal_id_04_00000341.wav \n inflating: ./valve/normal_id_04_00000342.wav \n inflating: ./valve/normal_id_04_00000343.wav \n inflating: ./valve/normal_id_04_00000344.wav \n inflating: ./valve/normal_id_04_00000345.wav \n inflating: ./valve/normal_id_04_00000346.wav \n inflating: ./valve/normal_id_04_00000347.wav \n inflating: ./valve/normal_id_04_00000348.wav \n inflating: ./valve/normal_id_04_00000349.wav \n inflating: ./valve/normal_id_04_00000350.wav \n inflating: ./valve/normal_id_04_00000351.wav \n inflating: ./valve/normal_id_04_00000352.wav \n inflating: ./valve/normal_id_04_00000353.wav \n inflating: ./valve/normal_id_04_00000354.wav \n inflating: ./valve/normal_id_04_00000355.wav \n inflating: ./valve/normal_id_04_00000356.wav \n inflating: ./valve/normal_id_04_00000357.wav \n inflating: ./valve/normal_id_04_00000358.wav \n inflating: ./valve/normal_id_04_00000359.wav \n inflating: ./valve/normal_id_04_00000360.wav \n inflating: ./valve/normal_id_04_00000361.wav \n inflating: ./valve/normal_id_04_00000362.wav \n inflating: ./valve/normal_id_04_00000363.wav \n inflating: ./valve/normal_id_04_00000364.wav \n inflating: ./valve/normal_id_04_00000365.wav \n inflating: ./valve/normal_id_04_00000366.wav \n inflating: ./valve/normal_id_04_00000367.wav \n inflating: ./valve/normal_id_04_00000368.wav \n inflating: ./valve/normal_id_04_00000369.wav \n inflating: ./valve/normal_id_04_00000370.wav \n inflating: ./valve/normal_id_04_00000371.wav \n inflating: ./valve/normal_id_04_00000372.wav \n inflating: ./valve/normal_id_04_00000373.wav \n inflating: ./valve/normal_id_04_00000374.wav \n inflating: ./valve/normal_id_04_00000375.wav \n inflating: ./valve/normal_id_04_00000376.wav \n inflating: ./valve/normal_id_04_00000377.wav \n inflating: ./valve/normal_id_04_00000378.wav \n inflating: ./valve/normal_id_04_00000379.wav \n inflating: ./valve/normal_id_04_00000380.wav \n inflating: ./valve/normal_id_04_00000381.wav \n inflating: ./valve/normal_id_04_00000382.wav \n inflating: ./valve/normal_id_04_00000383.wav \n inflating: ./valve/normal_id_04_00000384.wav \n inflating: ./valve/normal_id_04_00000385.wav \n inflating: ./valve/normal_id_04_00000386.wav \n inflating: ./valve/normal_id_04_00000387.wav \n inflating: ./valve/normal_id_04_00000388.wav \n inflating: ./valve/normal_id_04_00000389.wav \n inflating: ./valve/normal_id_04_00000390.wav \n inflating: ./valve/normal_id_04_00000391.wav \n inflating: ./valve/normal_id_04_00000392.wav \n inflating: ./valve/normal_id_04_00000393.wav \n inflating: ./valve/normal_id_04_00000394.wav \n inflating: ./valve/normal_id_04_00000395.wav \n inflating: ./valve/normal_id_04_00000396.wav \n inflating: ./valve/normal_id_04_00000397.wav \n inflating: ./valve/normal_id_04_00000398.wav \n inflating: ./valve/normal_id_04_00000399.wav \n inflating: ./valve/normal_id_04_00000400.wav \n inflating: ./valve/normal_id_04_00000401.wav \n inflating: ./valve/normal_id_04_00000402.wav \n inflating: ./valve/normal_id_04_00000403.wav \n inflating: ./valve/normal_id_04_00000404.wav \n inflating: ./valve/normal_id_04_00000405.wav \n inflating: ./valve/normal_id_04_00000406.wav \n inflating: ./valve/normal_id_04_00000407.wav \n inflating: ./valve/normal_id_04_00000408.wav \n inflating: ./valve/normal_id_04_00000409.wav \n inflating: ./valve/normal_id_04_00000410.wav \n inflating: ./valve/normal_id_04_00000411.wav \n inflating: ./valve/normal_id_04_00000412.wav \n inflating: ./valve/normal_id_04_00000413.wav \n inflating: ./valve/normal_id_04_00000414.wav \n inflating: ./valve/normal_id_04_00000415.wav \n inflating: ./valve/normal_id_04_00000416.wav \n inflating: ./valve/normal_id_04_00000417.wav \n inflating: ./valve/normal_id_04_00000418.wav \n inflating: ./valve/normal_id_04_00000419.wav \n inflating: ./valve/normal_id_04_00000420.wav \n inflating: ./valve/normal_id_04_00000421.wav \n inflating: ./valve/normal_id_04_00000422.wav \n inflating: ./valve/normal_id_04_00000423.wav \n inflating: ./valve/normal_id_04_00000424.wav \n inflating: ./valve/normal_id_04_00000425.wav \n inflating: ./valve/normal_id_04_00000426.wav \n inflating: ./valve/normal_id_04_00000427.wav \n inflating: ./valve/normal_id_04_00000428.wav \n inflating: ./valve/normal_id_04_00000429.wav \n inflating: ./valve/normal_id_04_00000430.wav \n inflating: ./valve/normal_id_04_00000431.wav \n inflating: ./valve/normal_id_04_00000432.wav \n inflating: ./valve/normal_id_04_00000433.wav \n inflating: ./valve/normal_id_04_00000434.wav \n inflating: ./valve/normal_id_04_00000435.wav \n inflating: ./valve/normal_id_04_00000436.wav \n inflating: ./valve/normal_id_04_00000437.wav \n inflating: ./valve/normal_id_04_00000438.wav \n inflating: ./valve/normal_id_04_00000439.wav \n inflating: ./valve/normal_id_04_00000440.wav \n inflating: ./valve/normal_id_04_00000441.wav \n inflating: ./valve/normal_id_04_00000442.wav \n inflating: ./valve/normal_id_04_00000443.wav \n inflating: ./valve/normal_id_04_00000444.wav \n inflating: ./valve/normal_id_04_00000445.wav \n inflating: ./valve/normal_id_04_00000446.wav \n inflating: ./valve/normal_id_04_00000447.wav \n inflating: ./valve/normal_id_04_00000448.wav \n inflating: ./valve/normal_id_04_00000449.wav \n inflating: ./valve/normal_id_04_00000450.wav \n inflating: ./valve/normal_id_04_00000451.wav \n inflating: ./valve/normal_id_04_00000452.wav \n inflating: ./valve/normal_id_04_00000453.wav \n inflating: ./valve/normal_id_04_00000454.wav \n inflating: ./valve/normal_id_04_00000455.wav \n inflating: ./valve/normal_id_04_00000456.wav \n inflating: ./valve/normal_id_04_00000457.wav \n inflating: ./valve/normal_id_04_00000458.wav \n inflating: ./valve/normal_id_04_00000459.wav \n inflating: ./valve/normal_id_04_00000460.wav \n inflating: ./valve/normal_id_04_00000461.wav \n inflating: ./valve/normal_id_04_00000462.wav \n inflating: ./valve/normal_id_04_00000463.wav \n inflating: ./valve/normal_id_04_00000464.wav \n inflating: ./valve/normal_id_04_00000465.wav \n inflating: ./valve/normal_id_04_00000466.wav \n inflating: ./valve/normal_id_04_00000467.wav \n inflating: ./valve/normal_id_04_00000468.wav \n inflating: ./valve/normal_id_04_00000469.wav \n inflating: ./valve/normal_id_04_00000470.wav \n inflating: ./valve/normal_id_04_00000471.wav \n inflating: ./valve/normal_id_04_00000472.wav \n inflating: ./valve/normal_id_04_00000473.wav \n inflating: ./valve/normal_id_04_00000474.wav \n inflating: ./valve/normal_id_04_00000475.wav \n inflating: ./valve/normal_id_04_00000476.wav \n inflating: ./valve/normal_id_04_00000477.wav \n inflating: ./valve/normal_id_04_00000478.wav \n inflating: ./valve/normal_id_04_00000479.wav \n inflating: ./valve/normal_id_04_00000480.wav \n inflating: ./valve/normal_id_04_00000481.wav \n inflating: ./valve/normal_id_04_00000482.wav \n inflating: ./valve/normal_id_04_00000483.wav \n inflating: ./valve/normal_id_04_00000484.wav \n inflating: ./valve/normal_id_04_00000485.wav \n inflating: ./valve/normal_id_04_00000486.wav \n inflating: ./valve/normal_id_04_00000487.wav \n inflating: ./valve/normal_id_04_00000488.wav \n inflating: ./valve/normal_id_04_00000489.wav \n inflating: ./valve/normal_id_04_00000490.wav \n inflating: ./valve/normal_id_04_00000491.wav \n inflating: ./valve/normal_id_04_00000492.wav \n inflating: ./valve/normal_id_04_00000493.wav \n inflating: ./valve/normal_id_04_00000494.wav \n inflating: ./valve/normal_id_04_00000495.wav \n inflating: ./valve/normal_id_04_00000496.wav \n inflating: ./valve/normal_id_04_00000497.wav \n inflating: ./valve/normal_id_04_00000498.wav \n inflating: ./valve/normal_id_04_00000499.wav \n inflating: ./valve/normal_id_04_00000500.wav \n inflating: ./valve/normal_id_04_00000501.wav \n inflating: ./valve/normal_id_04_00000502.wav \n inflating: ./valve/normal_id_04_00000503.wav \n inflating: ./valve/normal_id_04_00000504.wav \n inflating: ./valve/normal_id_04_00000505.wav \n inflating: ./valve/normal_id_04_00000506.wav \n inflating: ./valve/normal_id_04_00000507.wav \n inflating: ./valve/normal_id_04_00000508.wav \n inflating: ./valve/normal_id_04_00000509.wav \n inflating: ./valve/normal_id_04_00000510.wav \n inflating: ./valve/normal_id_04_00000511.wav \n inflating: ./valve/normal_id_04_00000512.wav \n inflating: ./valve/normal_id_04_00000513.wav \n inflating: ./valve/normal_id_04_00000514.wav \n inflating: ./valve/normal_id_04_00000515.wav \n inflating: ./valve/normal_id_04_00000516.wav \n inflating: ./valve/normal_id_04_00000517.wav \n inflating: ./valve/normal_id_04_00000518.wav \n inflating: ./valve/normal_id_04_00000519.wav \n inflating: ./valve/normal_id_04_00000520.wav \n inflating: ./valve/normal_id_04_00000521.wav \n inflating: ./valve/normal_id_04_00000522.wav \n inflating: ./valve/normal_id_04_00000523.wav \n inflating: ./valve/normal_id_04_00000524.wav \n inflating: ./valve/normal_id_04_00000525.wav \n inflating: ./valve/normal_id_04_00000526.wav \n inflating: ./valve/normal_id_04_00000527.wav \n inflating: ./valve/normal_id_04_00000528.wav \n inflating: ./valve/normal_id_04_00000529.wav \n inflating: ./valve/normal_id_04_00000530.wav \n inflating: ./valve/normal_id_04_00000531.wav \n inflating: ./valve/normal_id_04_00000532.wav \n inflating: ./valve/normal_id_04_00000533.wav \n inflating: ./valve/normal_id_04_00000534.wav \n inflating: ./valve/normal_id_04_00000535.wav \n inflating: ./valve/normal_id_04_00000536.wav \n inflating: ./valve/normal_id_04_00000537.wav \n inflating: ./valve/normal_id_04_00000538.wav \n inflating: ./valve/normal_id_04_00000539.wav \n inflating: ./valve/normal_id_04_00000540.wav \n inflating: ./valve/normal_id_04_00000541.wav \n inflating: ./valve/normal_id_04_00000542.wav \n inflating: ./valve/normal_id_04_00000543.wav \n inflating: ./valve/normal_id_04_00000544.wav \n inflating: ./valve/normal_id_04_00000545.wav \n inflating: ./valve/normal_id_04_00000546.wav \n inflating: ./valve/normal_id_04_00000547.wav \n inflating: ./valve/normal_id_04_00000548.wav \n inflating: ./valve/normal_id_04_00000549.wav \n inflating: ./valve/normal_id_04_00000550.wav \n inflating: ./valve/normal_id_04_00000551.wav \n inflating: ./valve/normal_id_04_00000552.wav \n inflating: ./valve/normal_id_04_00000553.wav \n inflating: ./valve/normal_id_04_00000554.wav \n inflating: ./valve/normal_id_04_00000555.wav \n inflating: ./valve/normal_id_04_00000556.wav \n inflating: ./valve/normal_id_04_00000557.wav \n inflating: ./valve/normal_id_04_00000558.wav \n inflating: ./valve/normal_id_04_00000559.wav \n inflating: ./valve/normal_id_04_00000560.wav \n inflating: ./valve/normal_id_04_00000561.wav \n inflating: ./valve/normal_id_04_00000562.wav \n inflating: ./valve/normal_id_04_00000563.wav \n inflating: ./valve/normal_id_04_00000564.wav \n inflating: ./valve/normal_id_04_00000565.wav \n inflating: ./valve/normal_id_04_00000566.wav \n inflating: ./valve/normal_id_04_00000567.wav \n inflating: ./valve/normal_id_04_00000568.wav \n inflating: ./valve/normal_id_04_00000569.wav \n inflating: ./valve/normal_id_04_00000570.wav \n inflating: ./valve/normal_id_04_00000571.wav \n inflating: ./valve/normal_id_04_00000572.wav \n inflating: ./valve/normal_id_04_00000573.wav \n inflating: ./valve/normal_id_04_00000574.wav \n inflating: ./valve/normal_id_04_00000575.wav \n inflating: ./valve/normal_id_04_00000576.wav \n inflating: ./valve/normal_id_04_00000577.wav \n inflating: ./valve/normal_id_04_00000578.wav \n inflating: ./valve/normal_id_04_00000579.wav \n inflating: ./valve/normal_id_04_00000580.wav \n inflating: ./valve/normal_id_04_00000581.wav \n inflating: ./valve/normal_id_04_00000582.wav \n inflating: ./valve/normal_id_04_00000583.wav \n inflating: ./valve/normal_id_04_00000584.wav \n inflating: ./valve/normal_id_04_00000585.wav \n inflating: ./valve/normal_id_04_00000586.wav \n inflating: ./valve/normal_id_04_00000587.wav \n inflating: ./valve/normal_id_04_00000588.wav \n inflating: ./valve/normal_id_04_00000589.wav \n inflating: ./valve/normal_id_04_00000590.wav \n inflating: ./valve/normal_id_04_00000591.wav \n inflating: ./valve/normal_id_04_00000592.wav \n inflating: ./valve/normal_id_04_00000593.wav \n inflating: ./valve/normal_id_04_00000594.wav \n inflating: ./valve/normal_id_04_00000595.wav \n inflating: ./valve/normal_id_04_00000596.wav \n inflating: ./valve/normal_id_04_00000597.wav \n inflating: ./valve/normal_id_04_00000598.wav \n inflating: ./valve/normal_id_04_00000599.wav \n inflating: ./valve/normal_id_04_00000600.wav \n inflating: ./valve/normal_id_04_00000601.wav \n inflating: ./valve/normal_id_04_00000602.wav \n inflating: ./valve/normal_id_04_00000603.wav \n inflating: ./valve/normal_id_04_00000604.wav \n inflating: ./valve/normal_id_04_00000605.wav \n inflating: ./valve/normal_id_04_00000606.wav \n inflating: ./valve/normal_id_04_00000607.wav \n inflating: ./valve/normal_id_04_00000608.wav \n inflating: ./valve/normal_id_04_00000609.wav \n inflating: ./valve/normal_id_04_00000610.wav \n inflating: ./valve/normal_id_04_00000611.wav \n inflating: ./valve/normal_id_04_00000612.wav \n inflating: ./valve/normal_id_04_00000613.wav \n inflating: ./valve/normal_id_04_00000614.wav \n inflating: ./valve/normal_id_04_00000615.wav \n inflating: ./valve/normal_id_04_00000616.wav \n inflating: ./valve/normal_id_04_00000617.wav \n inflating: ./valve/normal_id_04_00000618.wav \n inflating: ./valve/normal_id_04_00000619.wav \n inflating: ./valve/normal_id_04_00000620.wav \n inflating: ./valve/normal_id_04_00000621.wav \n inflating: ./valve/normal_id_04_00000622.wav \n inflating: ./valve/normal_id_04_00000623.wav \n inflating: ./valve/normal_id_04_00000624.wav \n inflating: ./valve/normal_id_04_00000625.wav \n inflating: ./valve/normal_id_04_00000626.wav \n inflating: ./valve/normal_id_04_00000627.wav \n inflating: ./valve/normal_id_04_00000628.wav \n inflating: ./valve/normal_id_04_00000629.wav \n inflating: ./valve/normal_id_04_00000630.wav \n inflating: ./valve/normal_id_04_00000631.wav \n inflating: ./valve/normal_id_04_00000632.wav \n inflating: ./valve/normal_id_04_00000633.wav \n inflating: ./valve/normal_id_04_00000634.wav \n inflating: ./valve/normal_id_04_00000635.wav \n inflating: ./valve/normal_id_04_00000636.wav \n inflating: ./valve/normal_id_04_00000637.wav \n inflating: ./valve/normal_id_04_00000638.wav \n inflating: ./valve/normal_id_04_00000639.wav \n inflating: ./valve/normal_id_04_00000640.wav \n inflating: ./valve/normal_id_04_00000641.wav \n inflating: ./valve/normal_id_04_00000642.wav \n inflating: ./valve/normal_id_04_00000643.wav \n inflating: ./valve/normal_id_04_00000644.wav \n inflating: ./valve/normal_id_04_00000645.wav \n inflating: ./valve/normal_id_04_00000646.wav \n inflating: ./valve/normal_id_04_00000647.wav \n inflating: ./valve/normal_id_04_00000648.wav \n inflating: ./valve/normal_id_04_00000649.wav \n inflating: ./valve/normal_id_04_00000650.wav \n inflating: ./valve/normal_id_04_00000651.wav \n inflating: ./valve/normal_id_04_00000652.wav \n inflating: ./valve/normal_id_04_00000653.wav \n inflating: ./valve/normal_id_04_00000654.wav \n inflating: ./valve/normal_id_04_00000655.wav \n inflating: ./valve/normal_id_04_00000656.wav \n inflating: ./valve/normal_id_04_00000657.wav \n inflating: ./valve/normal_id_04_00000658.wav \n inflating: ./valve/normal_id_04_00000659.wav \n inflating: ./valve/normal_id_04_00000660.wav \n inflating: ./valve/normal_id_04_00000661.wav \n inflating: ./valve/normal_id_04_00000662.wav \n inflating: ./valve/normal_id_04_00000663.wav \n inflating: ./valve/normal_id_04_00000664.wav \n inflating: ./valve/normal_id_04_00000665.wav \n inflating: ./valve/normal_id_04_00000666.wav \n inflating: ./valve/normal_id_04_00000667.wav \n inflating: ./valve/normal_id_04_00000668.wav \n inflating: ./valve/normal_id_04_00000669.wav \n inflating: ./valve/normal_id_04_00000670.wav \n inflating: ./valve/normal_id_04_00000671.wav \n inflating: ./valve/normal_id_04_00000672.wav \n inflating: ./valve/normal_id_04_00000673.wav \n inflating: ./valve/normal_id_04_00000674.wav \n inflating: ./valve/normal_id_04_00000675.wav \n inflating: ./valve/normal_id_04_00000676.wav \n inflating: ./valve/normal_id_04_00000677.wav \n inflating: ./valve/normal_id_04_00000678.wav \n inflating: ./valve/normal_id_04_00000679.wav \n inflating: ./valve/normal_id_04_00000680.wav \n inflating: ./valve/normal_id_04_00000681.wav \n inflating: ./valve/normal_id_04_00000682.wav \n inflating: ./valve/normal_id_04_00000683.wav \n inflating: ./valve/normal_id_04_00000684.wav \n inflating: ./valve/normal_id_04_00000685.wav \n inflating: ./valve/normal_id_04_00000686.wav \n inflating: ./valve/normal_id_04_00000687.wav \n inflating: ./valve/normal_id_04_00000688.wav \n inflating: ./valve/normal_id_04_00000689.wav \n inflating: ./valve/normal_id_04_00000690.wav \n inflating: ./valve/normal_id_04_00000691.wav \n inflating: ./valve/normal_id_04_00000692.wav \n inflating: ./valve/normal_id_04_00000693.wav \n inflating: ./valve/normal_id_04_00000694.wav \n inflating: ./valve/normal_id_04_00000695.wav \n inflating: ./valve/normal_id_04_00000696.wav \n inflating: ./valve/normal_id_04_00000697.wav \n inflating: ./valve/normal_id_04_00000698.wav \n inflating: ./valve/normal_id_04_00000699.wav \n inflating: ./valve/normal_id_04_00000700.wav \n inflating: ./valve/normal_id_04_00000701.wav \n inflating: ./valve/normal_id_04_00000702.wav \n inflating: ./valve/normal_id_04_00000703.wav \n inflating: ./valve/normal_id_04_00000704.wav \n inflating: ./valve/normal_id_04_00000705.wav \n inflating: ./valve/normal_id_04_00000706.wav \n inflating: ./valve/normal_id_04_00000707.wav \n inflating: ./valve/normal_id_04_00000708.wav \n inflating: ./valve/normal_id_04_00000709.wav \n inflating: ./valve/normal_id_04_00000710.wav \n inflating: ./valve/normal_id_04_00000711.wav \n inflating: ./valve/normal_id_04_00000712.wav \n inflating: ./valve/normal_id_04_00000713.wav \n inflating: ./valve/normal_id_04_00000714.wav \n inflating: ./valve/normal_id_04_00000715.wav \n inflating: ./valve/normal_id_04_00000716.wav \n inflating: ./valve/normal_id_04_00000717.wav \n inflating: ./valve/normal_id_04_00000718.wav \n inflating: ./valve/normal_id_04_00000719.wav \n inflating: ./valve/normal_id_04_00000720.wav \n inflating: ./valve/normal_id_04_00000721.wav \n inflating: ./valve/normal_id_04_00000722.wav \n inflating: ./valve/normal_id_04_00000723.wav \n inflating: ./valve/normal_id_04_00000724.wav \n inflating: ./valve/normal_id_04_00000725.wav \n inflating: ./valve/normal_id_04_00000726.wav \n inflating: ./valve/normal_id_04_00000727.wav \n inflating: ./valve/normal_id_04_00000728.wav \n inflating: ./valve/normal_id_04_00000729.wav \n inflating: ./valve/normal_id_04_00000730.wav \n inflating: ./valve/normal_id_04_00000731.wav \n inflating: ./valve/normal_id_04_00000732.wav \n inflating: ./valve/normal_id_04_00000733.wav \n inflating: ./valve/normal_id_04_00000734.wav \n inflating: ./valve/normal_id_04_00000735.wav \n inflating: ./valve/normal_id_04_00000736.wav \n inflating: ./valve/normal_id_04_00000737.wav \n inflating: ./valve/normal_id_04_00000738.wav \n inflating: ./valve/normal_id_04_00000739.wav \n inflating: ./valve/normal_id_04_00000740.wav \n inflating: ./valve/normal_id_04_00000741.wav \n inflating: ./valve/normal_id_04_00000742.wav \n inflating: ./valve/normal_id_04_00000743.wav \n inflating: ./valve/normal_id_04_00000744.wav \n inflating: ./valve/normal_id_04_00000745.wav \n inflating: ./valve/normal_id_04_00000746.wav \n inflating: ./valve/normal_id_04_00000747.wav \n inflating: ./valve/normal_id_04_00000748.wav \n inflating: ./valve/normal_id_04_00000749.wav \n inflating: ./valve/normal_id_04_00000750.wav \n inflating: ./valve/normal_id_04_00000751.wav \n inflating: ./valve/normal_id_04_00000752.wav \n inflating: ./valve/normal_id_04_00000753.wav \n inflating: ./valve/normal_id_04_00000754.wav \n inflating: ./valve/normal_id_04_00000755.wav \n inflating: ./valve/normal_id_04_00000756.wav \n inflating: ./valve/normal_id_04_00000757.wav \n inflating: ./valve/normal_id_04_00000758.wav \n inflating: ./valve/normal_id_04_00000759.wav \n inflating: ./valve/normal_id_04_00000760.wav \n inflating: ./valve/normal_id_04_00000761.wav \n inflating: ./valve/normal_id_04_00000762.wav \n inflating: ./valve/normal_id_04_00000763.wav \n inflating: ./valve/normal_id_04_00000764.wav \n inflating: ./valve/normal_id_04_00000765.wav \n inflating: ./valve/normal_id_04_00000766.wav \n inflating: ./valve/normal_id_04_00000767.wav \n inflating: ./valve/normal_id_04_00000768.wav \n inflating: ./valve/normal_id_04_00000769.wav \n inflating: ./valve/normal_id_04_00000770.wav \n inflating: ./valve/normal_id_04_00000771.wav \n inflating: ./valve/normal_id_04_00000772.wav \n inflating: ./valve/normal_id_04_00000773.wav \n inflating: ./valve/normal_id_04_00000774.wav \n inflating: ./valve/normal_id_04_00000775.wav \n inflating: ./valve/normal_id_04_00000776.wav \n inflating: ./valve/normal_id_04_00000777.wav \n inflating: ./valve/normal_id_04_00000778.wav \n inflating: ./valve/normal_id_04_00000779.wav \n inflating: ./valve/normal_id_04_00000780.wav \n inflating: ./valve/normal_id_04_00000781.wav \n inflating: ./valve/normal_id_04_00000782.wav \n inflating: ./valve/normal_id_04_00000783.wav \n inflating: ./valve/normal_id_04_00000784.wav \n inflating: ./valve/normal_id_04_00000785.wav \n inflating: ./valve/normal_id_04_00000786.wav \n inflating: ./valve/normal_id_04_00000787.wav \n inflating: ./valve/normal_id_04_00000788.wav \n inflating: ./valve/normal_id_04_00000789.wav \n inflating: ./valve/normal_id_04_00000790.wav \n inflating: ./valve/normal_id_04_00000791.wav \n inflating: ./valve/normal_id_04_00000792.wav \n inflating: ./valve/normal_id_04_00000793.wav \n inflating: ./valve/normal_id_04_00000794.wav \n inflating: ./valve/normal_id_04_00000795.wav \n inflating: ./valve/normal_id_04_00000796.wav \n inflating: ./valve/normal_id_04_00000797.wav \n inflating: ./valve/normal_id_04_00000798.wav \n inflating: ./valve/normal_id_04_00000799.wav \n inflating: ./valve/normal_id_04_00000800.wav \n inflating: ./valve/normal_id_04_00000801.wav \n inflating: ./valve/normal_id_04_00000802.wav \n inflating: ./valve/normal_id_04_00000803.wav \n inflating: ./valve/normal_id_04_00000804.wav \n inflating: ./valve/normal_id_04_00000805.wav \n inflating: ./valve/normal_id_04_00000806.wav \n inflating: ./valve/normal_id_04_00000807.wav \n inflating: ./valve/normal_id_04_00000808.wav \n inflating: ./valve/normal_id_04_00000809.wav \n inflating: ./valve/normal_id_04_00000810.wav \n inflating: ./valve/normal_id_04_00000811.wav \n inflating: ./valve/normal_id_04_00000812.wav \n inflating: ./valve/normal_id_04_00000813.wav \n inflating: ./valve/normal_id_04_00000814.wav \n inflating: ./valve/normal_id_04_00000815.wav \n inflating: ./valve/normal_id_04_00000816.wav \n inflating: ./valve/normal_id_04_00000817.wav \n inflating: ./valve/normal_id_04_00000818.wav \n inflating: ./valve/normal_id_04_00000819.wav \n inflating: ./valve/normal_id_04_00000820.wav \n inflating: ./valve/normal_id_04_00000821.wav \n inflating: ./valve/normal_id_04_00000822.wav \n inflating: ./valve/normal_id_04_00000823.wav \n inflating: ./valve/normal_id_04_00000824.wav \n inflating: ./valve/normal_id_04_00000825.wav \n inflating: ./valve/normal_id_04_00000826.wav \n inflating: ./valve/normal_id_04_00000827.wav \n inflating: ./valve/normal_id_04_00000828.wav \n inflating: ./valve/normal_id_04_00000829.wav \n inflating: ./valve/normal_id_04_00000830.wav \n inflating: ./valve/normal_id_04_00000831.wav \n inflating: ./valve/normal_id_04_00000832.wav \n inflating: ./valve/normal_id_04_00000833.wav \n inflating: ./valve/normal_id_04_00000834.wav \n inflating: ./valve/normal_id_04_00000835.wav \n inflating: ./valve/normal_id_04_00000836.wav \n inflating: ./valve/normal_id_04_00000837.wav \n inflating: ./valve/normal_id_04_00000838.wav \n inflating: ./valve/normal_id_04_00000839.wav \n inflating: ./valve/normal_id_04_00000840.wav \n inflating: ./valve/normal_id_04_00000841.wav \n inflating: ./valve/normal_id_04_00000842.wav \n inflating: ./valve/normal_id_04_00000843.wav \n inflating: ./valve/normal_id_04_00000844.wav \n inflating: ./valve/normal_id_04_00000845.wav \n inflating: ./valve/normal_id_04_00000846.wav \n inflating: ./valve/normal_id_04_00000847.wav \n inflating: ./valve/normal_id_04_00000848.wav \n inflating: ./valve/normal_id_04_00000849.wav \n inflating: ./valve/normal_id_04_00000850.wav \n inflating: ./valve/normal_id_04_00000851.wav \n inflating: ./valve/normal_id_04_00000852.wav \n inflating: ./valve/normal_id_04_00000853.wav \n inflating: ./valve/normal_id_04_00000854.wav \n inflating: ./valve/normal_id_04_00000855.wav \n inflating: ./valve/normal_id_04_00000856.wav \n inflating: ./valve/normal_id_04_00000857.wav \n inflating: ./valve/normal_id_04_00000858.wav \n inflating: ./valve/normal_id_04_00000859.wav \n inflating: ./valve/normal_id_04_00000860.wav \n inflating: ./valve/normal_id_04_00000861.wav \n inflating: ./valve/normal_id_04_00000862.wav \n inflating: ./valve/normal_id_04_00000863.wav \n inflating: ./valve/normal_id_04_00000864.wav \n inflating: ./valve/normal_id_04_00000865.wav \n inflating: ./valve/normal_id_04_00000866.wav \n inflating: ./valve/normal_id_04_00000867.wav \n inflating: ./valve/normal_id_04_00000868.wav \n inflating: ./valve/normal_id_04_00000869.wav \n inflating: ./valve/normal_id_04_00000870.wav \n inflating: ./valve/normal_id_04_00000871.wav \n inflating: ./valve/normal_id_04_00000872.wav \n inflating: ./valve/normal_id_04_00000873.wav \n inflating: ./valve/normal_id_04_00000874.wav \n inflating: ./valve/normal_id_04_00000875.wav \n inflating: ./valve/normal_id_04_00000876.wav \n inflating: ./valve/normal_id_04_00000877.wav \n inflating: ./valve/normal_id_04_00000878.wav \n inflating: ./valve/normal_id_04_00000879.wav \n inflating: ./valve/normal_id_04_00000880.wav \n inflating: ./valve/normal_id_04_00000881.wav \n inflating: ./valve/normal_id_04_00000882.wav \n inflating: ./valve/normal_id_04_00000883.wav \n inflating: ./valve/normal_id_04_00000884.wav \n inflating: ./valve/normal_id_04_00000885.wav \n inflating: ./valve/normal_id_04_00000886.wav \n inflating: ./valve/normal_id_04_00000887.wav \n inflating: ./valve/normal_id_04_00000888.wav \n inflating: ./valve/normal_id_04_00000889.wav \n inflating: ./valve/normal_id_04_00000890.wav \n inflating: ./valve/normal_id_04_00000891.wav \n inflating: ./valve/normal_id_04_00000892.wav \n inflating: ./valve/normal_id_04_00000893.wav \n inflating: ./valve/normal_id_04_00000894.wav \n inflating: ./valve/normal_id_04_00000895.wav \n inflating: ./valve/normal_id_04_00000896.wav \n inflating: ./valve/normal_id_04_00000897.wav \n inflating: ./valve/normal_id_04_00000898.wav \n inflating: ./valve/normal_id_04_00000899.wav \n inflating: ./valve/normal_id_06_00000000.wav \n inflating: ./valve/normal_id_06_00000001.wav \n inflating: ./valve/normal_id_06_00000002.wav \n inflating: ./valve/normal_id_06_00000003.wav \n inflating: ./valve/normal_id_06_00000004.wav \n inflating: ./valve/normal_id_06_00000005.wav \n inflating: ./valve/normal_id_06_00000006.wav \n inflating: ./valve/normal_id_06_00000007.wav \n inflating: ./valve/normal_id_06_00000008.wav \n inflating: ./valve/normal_id_06_00000009.wav \n inflating: ./valve/normal_id_06_00000010.wav \n inflating: ./valve/normal_id_06_00000011.wav \n inflating: ./valve/normal_id_06_00000012.wav \n inflating: ./valve/normal_id_06_00000013.wav \n inflating: ./valve/normal_id_06_00000014.wav \n inflating: ./valve/normal_id_06_00000015.wav \n inflating: ./valve/normal_id_06_00000016.wav \n inflating: ./valve/normal_id_06_00000017.wav \n inflating: ./valve/normal_id_06_00000018.wav \n inflating: ./valve/normal_id_06_00000019.wav \n inflating: ./valve/normal_id_06_00000020.wav \n inflating: ./valve/normal_id_06_00000021.wav \n inflating: ./valve/normal_id_06_00000022.wav \n inflating: ./valve/normal_id_06_00000023.wav \n inflating: ./valve/normal_id_06_00000024.wav \n inflating: ./valve/normal_id_06_00000025.wav \n inflating: ./valve/normal_id_06_00000026.wav \n inflating: ./valve/normal_id_06_00000027.wav \n inflating: ./valve/normal_id_06_00000028.wav \n inflating: ./valve/normal_id_06_00000029.wav \n inflating: ./valve/normal_id_06_00000030.wav \n inflating: ./valve/normal_id_06_00000031.wav \n inflating: ./valve/normal_id_06_00000032.wav \n inflating: ./valve/normal_id_06_00000033.wav \n inflating: ./valve/normal_id_06_00000034.wav \n inflating: ./valve/normal_id_06_00000035.wav \n inflating: ./valve/normal_id_06_00000036.wav \n inflating: ./valve/normal_id_06_00000037.wav \n inflating: ./valve/normal_id_06_00000038.wav \n inflating: ./valve/normal_id_06_00000039.wav \n inflating: ./valve/normal_id_06_00000040.wav \n inflating: ./valve/normal_id_06_00000041.wav \n inflating: ./valve/normal_id_06_00000042.wav \n inflating: ./valve/normal_id_06_00000043.wav \n inflating: ./valve/normal_id_06_00000044.wav \n inflating: ./valve/normal_id_06_00000045.wav \n inflating: ./valve/normal_id_06_00000046.wav \n inflating: ./valve/normal_id_06_00000047.wav \n inflating: ./valve/normal_id_06_00000048.wav \n inflating: ./valve/normal_id_06_00000049.wav \n inflating: ./valve/normal_id_06_00000050.wav \n inflating: ./valve/normal_id_06_00000051.wav \n inflating: ./valve/normal_id_06_00000052.wav \n inflating: ./valve/normal_id_06_00000053.wav \n inflating: ./valve/normal_id_06_00000054.wav \n inflating: ./valve/normal_id_06_00000055.wav \n inflating: ./valve/normal_id_06_00000056.wav \n inflating: ./valve/normal_id_06_00000057.wav \n inflating: ./valve/normal_id_06_00000058.wav \n inflating: ./valve/normal_id_06_00000059.wav \n inflating: ./valve/normal_id_06_00000060.wav \n inflating: ./valve/normal_id_06_00000061.wav \n inflating: ./valve/normal_id_06_00000062.wav \n inflating: ./valve/normal_id_06_00000063.wav \n inflating: ./valve/normal_id_06_00000064.wav \n inflating: ./valve/normal_id_06_00000065.wav \n inflating: ./valve/normal_id_06_00000066.wav \n inflating: ./valve/normal_id_06_00000067.wav \n inflating: ./valve/normal_id_06_00000068.wav \n inflating: ./valve/normal_id_06_00000069.wav \n inflating: ./valve/normal_id_06_00000070.wav \n inflating: ./valve/normal_id_06_00000071.wav \n inflating: ./valve/normal_id_06_00000072.wav \n inflating: ./valve/normal_id_06_00000073.wav \n inflating: ./valve/normal_id_06_00000074.wav \n inflating: ./valve/normal_id_06_00000075.wav \n inflating: ./valve/normal_id_06_00000076.wav \n inflating: ./valve/normal_id_06_00000077.wav \n inflating: ./valve/normal_id_06_00000078.wav \n inflating: ./valve/normal_id_06_00000079.wav \n inflating: ./valve/normal_id_06_00000080.wav \n inflating: ./valve/normal_id_06_00000081.wav \n inflating: ./valve/normal_id_06_00000082.wav \n inflating: ./valve/normal_id_06_00000083.wav \n inflating: ./valve/normal_id_06_00000084.wav \n inflating: ./valve/normal_id_06_00000085.wav \n inflating: ./valve/normal_id_06_00000086.wav \n inflating: ./valve/normal_id_06_00000087.wav \n inflating: ./valve/normal_id_06_00000088.wav \n inflating: ./valve/normal_id_06_00000089.wav \n inflating: ./valve/normal_id_06_00000090.wav \n inflating: ./valve/normal_id_06_00000091.wav \n inflating: ./valve/normal_id_06_00000092.wav \n inflating: ./valve/normal_id_06_00000093.wav \n inflating: ./valve/normal_id_06_00000094.wav \n inflating: ./valve/normal_id_06_00000095.wav \n inflating: ./valve/normal_id_06_00000096.wav \n inflating: ./valve/normal_id_06_00000097.wav \n inflating: ./valve/normal_id_06_00000098.wav \n inflating: ./valve/normal_id_06_00000099.wav \n inflating: ./valve/normal_id_06_00000100.wav \n inflating: ./valve/normal_id_06_00000101.wav \n inflating: ./valve/normal_id_06_00000102.wav \n inflating: ./valve/normal_id_06_00000103.wav \n inflating: ./valve/normal_id_06_00000104.wav \n inflating: ./valve/normal_id_06_00000105.wav \n inflating: ./valve/normal_id_06_00000106.wav \n inflating: ./valve/normal_id_06_00000107.wav \n inflating: ./valve/normal_id_06_00000108.wav \n inflating: ./valve/normal_id_06_00000109.wav \n inflating: ./valve/normal_id_06_00000110.wav \n inflating: ./valve/normal_id_06_00000111.wav \n inflating: ./valve/normal_id_06_00000112.wav \n inflating: ./valve/normal_id_06_00000113.wav \n inflating: ./valve/normal_id_06_00000114.wav \n inflating: ./valve/normal_id_06_00000115.wav \n inflating: ./valve/normal_id_06_00000116.wav \n inflating: ./valve/normal_id_06_00000117.wav \n inflating: ./valve/normal_id_06_00000118.wav \n inflating: ./valve/normal_id_06_00000119.wav \n inflating: ./valve/normal_id_06_00000120.wav \n inflating: ./valve/normal_id_06_00000121.wav \n inflating: ./valve/normal_id_06_00000122.wav \n inflating: ./valve/normal_id_06_00000123.wav \n inflating: ./valve/normal_id_06_00000124.wav \n inflating: ./valve/normal_id_06_00000125.wav \n inflating: ./valve/normal_id_06_00000126.wav \n inflating: ./valve/normal_id_06_00000127.wav \n inflating: ./valve/normal_id_06_00000128.wav \n inflating: ./valve/normal_id_06_00000129.wav \n inflating: ./valve/normal_id_06_00000130.wav \n inflating: ./valve/normal_id_06_00000131.wav \n inflating: ./valve/normal_id_06_00000132.wav \n inflating: ./valve/normal_id_06_00000133.wav \n inflating: ./valve/normal_id_06_00000134.wav \n inflating: ./valve/normal_id_06_00000135.wav \n inflating: ./valve/normal_id_06_00000136.wav \n inflating: ./valve/normal_id_06_00000137.wav \n inflating: ./valve/normal_id_06_00000138.wav \n inflating: ./valve/normal_id_06_00000139.wav \n inflating: ./valve/normal_id_06_00000140.wav \n inflating: ./valve/normal_id_06_00000141.wav \n inflating: ./valve/normal_id_06_00000142.wav \n inflating: ./valve/normal_id_06_00000143.wav \n inflating: ./valve/normal_id_06_00000144.wav \n inflating: ./valve/normal_id_06_00000145.wav \n inflating: ./valve/normal_id_06_00000146.wav \n inflating: ./valve/normal_id_06_00000147.wav \n inflating: ./valve/normal_id_06_00000148.wav \n inflating: ./valve/normal_id_06_00000149.wav \n inflating: ./valve/normal_id_06_00000150.wav \n inflating: ./valve/normal_id_06_00000151.wav \n inflating: ./valve/normal_id_06_00000152.wav \n inflating: ./valve/normal_id_06_00000153.wav \n inflating: ./valve/normal_id_06_00000154.wav \n inflating: ./valve/normal_id_06_00000155.wav \n inflating: ./valve/normal_id_06_00000156.wav \n inflating: ./valve/normal_id_06_00000157.wav \n inflating: ./valve/normal_id_06_00000158.wav \n inflating: ./valve/normal_id_06_00000159.wav \n inflating: ./valve/normal_id_06_00000160.wav \n inflating: ./valve/normal_id_06_00000161.wav \n inflating: ./valve/normal_id_06_00000162.wav \n inflating: ./valve/normal_id_06_00000163.wav \n inflating: ./valve/normal_id_06_00000164.wav \n inflating: ./valve/normal_id_06_00000165.wav \n inflating: ./valve/normal_id_06_00000166.wav \n inflating: ./valve/normal_id_06_00000167.wav \n inflating: ./valve/normal_id_06_00000168.wav \n inflating: ./valve/normal_id_06_00000169.wav \n inflating: ./valve/normal_id_06_00000170.wav \n inflating: ./valve/normal_id_06_00000171.wav \n inflating: ./valve/normal_id_06_00000172.wav \n inflating: ./valve/normal_id_06_00000173.wav \n inflating: ./valve/normal_id_06_00000174.wav \n inflating: ./valve/normal_id_06_00000175.wav \n inflating: ./valve/normal_id_06_00000176.wav \n inflating: ./valve/normal_id_06_00000177.wav \n inflating: ./valve/normal_id_06_00000178.wav \n inflating: ./valve/normal_id_06_00000179.wav \n inflating: ./valve/normal_id_06_00000180.wav \n inflating: ./valve/normal_id_06_00000181.wav \n inflating: ./valve/normal_id_06_00000182.wav \n inflating: ./valve/normal_id_06_00000183.wav \n inflating: ./valve/normal_id_06_00000184.wav \n inflating: ./valve/normal_id_06_00000185.wav \n inflating: ./valve/normal_id_06_00000186.wav \n inflating: ./valve/normal_id_06_00000187.wav \n inflating: ./valve/normal_id_06_00000188.wav \n inflating: ./valve/normal_id_06_00000189.wav \n inflating: ./valve/normal_id_06_00000190.wav \n inflating: ./valve/normal_id_06_00000191.wav \n inflating: ./valve/normal_id_06_00000192.wav \n inflating: ./valve/normal_id_06_00000193.wav \n inflating: ./valve/normal_id_06_00000194.wav \n inflating: ./valve/normal_id_06_00000195.wav \n inflating: ./valve/normal_id_06_00000196.wav \n inflating: ./valve/normal_id_06_00000197.wav \n inflating: ./valve/normal_id_06_00000198.wav \n inflating: ./valve/normal_id_06_00000199.wav \n inflating: ./valve/normal_id_06_00000200.wav \n inflating: ./valve/normal_id_06_00000201.wav \n inflating: ./valve/normal_id_06_00000202.wav \n inflating: ./valve/normal_id_06_00000203.wav \n inflating: ./valve/normal_id_06_00000204.wav \n inflating: ./valve/normal_id_06_00000205.wav \n inflating: ./valve/normal_id_06_00000206.wav \n inflating: ./valve/normal_id_06_00000207.wav \n inflating: ./valve/normal_id_06_00000208.wav \n inflating: ./valve/normal_id_06_00000209.wav \n inflating: ./valve/normal_id_06_00000210.wav \n inflating: ./valve/normal_id_06_00000211.wav \n inflating: ./valve/normal_id_06_00000212.wav \n inflating: ./valve/normal_id_06_00000213.wav \n inflating: ./valve/normal_id_06_00000214.wav \n inflating: ./valve/normal_id_06_00000215.wav \n inflating: ./valve/normal_id_06_00000216.wav \n inflating: ./valve/normal_id_06_00000217.wav \n inflating: ./valve/normal_id_06_00000218.wav \n inflating: ./valve/normal_id_06_00000219.wav \n inflating: ./valve/normal_id_06_00000220.wav \n inflating: ./valve/normal_id_06_00000221.wav \n inflating: ./valve/normal_id_06_00000222.wav \n inflating: ./valve/normal_id_06_00000223.wav \n inflating: ./valve/normal_id_06_00000224.wav \n inflating: ./valve/normal_id_06_00000225.wav \n inflating: ./valve/normal_id_06_00000226.wav \n inflating: ./valve/normal_id_06_00000227.wav \n inflating: ./valve/normal_id_06_00000228.wav \n inflating: ./valve/normal_id_06_00000229.wav \n inflating: ./valve/normal_id_06_00000230.wav \n inflating: ./valve/normal_id_06_00000231.wav \n inflating: ./valve/normal_id_06_00000232.wav \n inflating: ./valve/normal_id_06_00000233.wav \n inflating: ./valve/normal_id_06_00000234.wav \n inflating: ./valve/normal_id_06_00000235.wav \n inflating: ./valve/normal_id_06_00000236.wav \n inflating: ./valve/normal_id_06_00000237.wav \n inflating: ./valve/normal_id_06_00000238.wav \n inflating: ./valve/normal_id_06_00000239.wav \n inflating: ./valve/normal_id_06_00000240.wav \n inflating: ./valve/normal_id_06_00000241.wav \n inflating: ./valve/normal_id_06_00000242.wav \n inflating: ./valve/normal_id_06_00000243.wav \n inflating: ./valve/normal_id_06_00000244.wav \n inflating: ./valve/normal_id_06_00000245.wav \n inflating: ./valve/normal_id_06_00000246.wav \n inflating: ./valve/normal_id_06_00000247.wav \n inflating: ./valve/normal_id_06_00000248.wav \n inflating: ./valve/normal_id_06_00000249.wav \n inflating: ./valve/normal_id_06_00000250.wav \n inflating: ./valve/normal_id_06_00000251.wav \n inflating: ./valve/normal_id_06_00000252.wav \n inflating: ./valve/normal_id_06_00000253.wav \n inflating: ./valve/normal_id_06_00000254.wav \n inflating: ./valve/normal_id_06_00000255.wav \n inflating: ./valve/normal_id_06_00000256.wav \n inflating: ./valve/normal_id_06_00000257.wav \n inflating: ./valve/normal_id_06_00000258.wav \n inflating: ./valve/normal_id_06_00000259.wav \n inflating: ./valve/normal_id_06_00000260.wav \n inflating: ./valve/normal_id_06_00000261.wav \n inflating: ./valve/normal_id_06_00000262.wav \n inflating: ./valve/normal_id_06_00000263.wav \n inflating: ./valve/normal_id_06_00000264.wav \n inflating: ./valve/normal_id_06_00000265.wav \n inflating: ./valve/normal_id_06_00000266.wav \n inflating: ./valve/normal_id_06_00000267.wav \n inflating: ./valve/normal_id_06_00000268.wav \n inflating: ./valve/normal_id_06_00000269.wav \n inflating: ./valve/normal_id_06_00000270.wav \n inflating: ./valve/normal_id_06_00000271.wav \n inflating: ./valve/normal_id_06_00000272.wav \n inflating: ./valve/normal_id_06_00000273.wav \n inflating: ./valve/normal_id_06_00000274.wav \n inflating: ./valve/normal_id_06_00000275.wav \n inflating: ./valve/normal_id_06_00000276.wav \n inflating: ./valve/normal_id_06_00000277.wav \n inflating: ./valve/normal_id_06_00000278.wav \n inflating: ./valve/normal_id_06_00000279.wav \n inflating: ./valve/normal_id_06_00000280.wav \n inflating: ./valve/normal_id_06_00000281.wav \n inflating: ./valve/normal_id_06_00000282.wav \n inflating: ./valve/normal_id_06_00000283.wav \n inflating: ./valve/normal_id_06_00000284.wav \n inflating: ./valve/normal_id_06_00000285.wav \n inflating: ./valve/normal_id_06_00000286.wav \n inflating: ./valve/normal_id_06_00000287.wav \n inflating: ./valve/normal_id_06_00000288.wav \n inflating: ./valve/normal_id_06_00000289.wav \n inflating: ./valve/normal_id_06_00000290.wav \n inflating: ./valve/normal_id_06_00000291.wav \n inflating: ./valve/normal_id_06_00000292.wav \n inflating: ./valve/normal_id_06_00000293.wav \n inflating: ./valve/normal_id_06_00000294.wav \n inflating: ./valve/normal_id_06_00000295.wav \n inflating: ./valve/normal_id_06_00000296.wav \n inflating: ./valve/normal_id_06_00000297.wav \n inflating: ./valve/normal_id_06_00000298.wav \n inflating: ./valve/normal_id_06_00000299.wav \n inflating: ./valve/normal_id_06_00000300.wav \n inflating: ./valve/normal_id_06_00000301.wav \n inflating: ./valve/normal_id_06_00000302.wav \n inflating: ./valve/normal_id_06_00000303.wav \n inflating: ./valve/normal_id_06_00000304.wav \n inflating: ./valve/normal_id_06_00000305.wav \n inflating: ./valve/normal_id_06_00000306.wav \n inflating: ./valve/normal_id_06_00000307.wav \n inflating: ./valve/normal_id_06_00000308.wav \n inflating: ./valve/normal_id_06_00000309.wav \n inflating: ./valve/normal_id_06_00000310.wav \n inflating: ./valve/normal_id_06_00000311.wav \n inflating: ./valve/normal_id_06_00000312.wav \n inflating: ./valve/normal_id_06_00000313.wav \n inflating: ./valve/normal_id_06_00000314.wav \n inflating: ./valve/normal_id_06_00000315.wav \n inflating: ./valve/normal_id_06_00000316.wav \n inflating: ./valve/normal_id_06_00000317.wav \n inflating: ./valve/normal_id_06_00000318.wav \n inflating: ./valve/normal_id_06_00000319.wav \n inflating: ./valve/normal_id_06_00000320.wav \n inflating: ./valve/normal_id_06_00000321.wav \n inflating: ./valve/normal_id_06_00000322.wav \n inflating: ./valve/normal_id_06_00000323.wav \n inflating: ./valve/normal_id_06_00000324.wav \n inflating: ./valve/normal_id_06_00000325.wav \n inflating: ./valve/normal_id_06_00000326.wav \n inflating: ./valve/normal_id_06_00000327.wav \n inflating: ./valve/normal_id_06_00000328.wav \n inflating: ./valve/normal_id_06_00000329.wav \n inflating: ./valve/normal_id_06_00000330.wav \n inflating: ./valve/normal_id_06_00000331.wav \n inflating: ./valve/normal_id_06_00000332.wav \n inflating: ./valve/normal_id_06_00000333.wav \n inflating: ./valve/normal_id_06_00000334.wav \n inflating: ./valve/normal_id_06_00000335.wav \n inflating: ./valve/normal_id_06_00000336.wav \n inflating: ./valve/normal_id_06_00000337.wav \n inflating: ./valve/normal_id_06_00000338.wav \n inflating: ./valve/normal_id_06_00000339.wav \n inflating: ./valve/normal_id_06_00000340.wav \n inflating: ./valve/normal_id_06_00000341.wav \n inflating: ./valve/normal_id_06_00000342.wav \n inflating: ./valve/normal_id_06_00000343.wav \n inflating: ./valve/normal_id_06_00000344.wav \n inflating: ./valve/normal_id_06_00000345.wav \n inflating: ./valve/normal_id_06_00000346.wav \n inflating: ./valve/normal_id_06_00000347.wav \n inflating: ./valve/normal_id_06_00000348.wav \n inflating: ./valve/normal_id_06_00000349.wav \n inflating: ./valve/normal_id_06_00000350.wav \n inflating: ./valve/normal_id_06_00000351.wav \n inflating: ./valve/normal_id_06_00000352.wav \n inflating: ./valve/normal_id_06_00000353.wav \n inflating: ./valve/normal_id_06_00000354.wav \n inflating: ./valve/normal_id_06_00000355.wav \n inflating: ./valve/normal_id_06_00000356.wav \n inflating: ./valve/normal_id_06_00000357.wav \n inflating: ./valve/normal_id_06_00000358.wav \n inflating: ./valve/normal_id_06_00000359.wav \n inflating: ./valve/normal_id_06_00000360.wav \n inflating: ./valve/normal_id_06_00000361.wav \n inflating: ./valve/normal_id_06_00000362.wav \n inflating: ./valve/normal_id_06_00000363.wav \n inflating: ./valve/normal_id_06_00000364.wav \n inflating: ./valve/normal_id_06_00000365.wav \n inflating: ./valve/normal_id_06_00000366.wav \n inflating: ./valve/normal_id_06_00000367.wav \n inflating: ./valve/normal_id_06_00000368.wav \n inflating: ./valve/normal_id_06_00000369.wav \n inflating: ./valve/normal_id_06_00000370.wav \n inflating: ./valve/normal_id_06_00000371.wav \n inflating: ./valve/normal_id_06_00000372.wav \n inflating: ./valve/normal_id_06_00000373.wav \n inflating: ./valve/normal_id_06_00000374.wav \n inflating: ./valve/normal_id_06_00000375.wav \n inflating: ./valve/normal_id_06_00000376.wav \n inflating: ./valve/normal_id_06_00000377.wav \n inflating: ./valve/normal_id_06_00000378.wav \n inflating: ./valve/normal_id_06_00000379.wav \n inflating: ./valve/normal_id_06_00000380.wav \n inflating: ./valve/normal_id_06_00000381.wav \n inflating: ./valve/normal_id_06_00000382.wav \n inflating: ./valve/normal_id_06_00000383.wav \n inflating: ./valve/normal_id_06_00000384.wav \n inflating: ./valve/normal_id_06_00000385.wav \n inflating: ./valve/normal_id_06_00000386.wav \n inflating: ./valve/normal_id_06_00000387.wav \n inflating: ./valve/normal_id_06_00000388.wav \n inflating: ./valve/normal_id_06_00000389.wav \n inflating: ./valve/normal_id_06_00000390.wav \n inflating: ./valve/normal_id_06_00000391.wav \n inflating: ./valve/normal_id_06_00000392.wav \n inflating: ./valve/normal_id_06_00000393.wav \n inflating: ./valve/normal_id_06_00000394.wav \n inflating: ./valve/normal_id_06_00000395.wav \n inflating: ./valve/normal_id_06_00000396.wav \n inflating: ./valve/normal_id_06_00000397.wav \n inflating: ./valve/normal_id_06_00000398.wav \n inflating: ./valve/normal_id_06_00000399.wav \n inflating: ./valve/normal_id_06_00000400.wav \n inflating: ./valve/normal_id_06_00000401.wav \n inflating: ./valve/normal_id_06_00000402.wav \n inflating: ./valve/normal_id_06_00000403.wav \n inflating: ./valve/normal_id_06_00000404.wav \n inflating: ./valve/normal_id_06_00000405.wav \n inflating: ./valve/normal_id_06_00000406.wav \n inflating: ./valve/normal_id_06_00000407.wav \n inflating: ./valve/normal_id_06_00000408.wav \n inflating: ./valve/normal_id_06_00000409.wav \n inflating: ./valve/normal_id_06_00000410.wav \n inflating: ./valve/normal_id_06_00000411.wav \n inflating: ./valve/normal_id_06_00000412.wav \n inflating: ./valve/normal_id_06_00000413.wav \n inflating: ./valve/normal_id_06_00000414.wav \n inflating: ./valve/normal_id_06_00000415.wav \n inflating: ./valve/normal_id_06_00000416.wav \n inflating: ./valve/normal_id_06_00000417.wav \n inflating: ./valve/normal_id_06_00000418.wav \n inflating: ./valve/normal_id_06_00000419.wav \n inflating: ./valve/normal_id_06_00000420.wav \n inflating: ./valve/normal_id_06_00000421.wav \n inflating: ./valve/normal_id_06_00000422.wav \n inflating: ./valve/normal_id_06_00000423.wav \n inflating: ./valve/normal_id_06_00000424.wav \n inflating: ./valve/normal_id_06_00000425.wav \n inflating: ./valve/normal_id_06_00000426.wav \n inflating: ./valve/normal_id_06_00000427.wav \n inflating: ./valve/normal_id_06_00000428.wav \n inflating: ./valve/normal_id_06_00000429.wav \n inflating: ./valve/normal_id_06_00000430.wav \n inflating: ./valve/normal_id_06_00000431.wav \n inflating: ./valve/normal_id_06_00000432.wav \n inflating: ./valve/normal_id_06_00000433.wav \n inflating: ./valve/normal_id_06_00000434.wav \n inflating: ./valve/normal_id_06_00000435.wav \n inflating: ./valve/normal_id_06_00000436.wav \n inflating: ./valve/normal_id_06_00000437.wav \n inflating: ./valve/normal_id_06_00000438.wav \n inflating: ./valve/normal_id_06_00000439.wav \n inflating: ./valve/normal_id_06_00000440.wav \n inflating: ./valve/normal_id_06_00000441.wav \n inflating: ./valve/normal_id_06_00000442.wav \n inflating: ./valve/normal_id_06_00000443.wav \n inflating: ./valve/normal_id_06_00000444.wav \n inflating: ./valve/normal_id_06_00000445.wav \n inflating: ./valve/normal_id_06_00000446.wav \n inflating: ./valve/normal_id_06_00000447.wav \n inflating: ./valve/normal_id_06_00000448.wav \n inflating: ./valve/normal_id_06_00000449.wav \n inflating: ./valve/normal_id_06_00000450.wav \n inflating: ./valve/normal_id_06_00000451.wav \n inflating: ./valve/normal_id_06_00000452.wav \n inflating: ./valve/normal_id_06_00000453.wav \n inflating: ./valve/normal_id_06_00000454.wav \n inflating: ./valve/normal_id_06_00000455.wav \n inflating: ./valve/normal_id_06_00000456.wav \n inflating: ./valve/normal_id_06_00000457.wav \n inflating: ./valve/normal_id_06_00000458.wav \n inflating: ./valve/normal_id_06_00000459.wav \n inflating: ./valve/normal_id_06_00000460.wav \n inflating: ./valve/normal_id_06_00000461.wav \n inflating: ./valve/normal_id_06_00000462.wav \n inflating: ./valve/normal_id_06_00000463.wav \n inflating: ./valve/normal_id_06_00000464.wav \n inflating: ./valve/normal_id_06_00000465.wav \n inflating: ./valve/normal_id_06_00000466.wav \n inflating: ./valve/normal_id_06_00000467.wav \n inflating: ./valve/normal_id_06_00000468.wav \n inflating: ./valve/normal_id_06_00000469.wav \n inflating: ./valve/normal_id_06_00000470.wav \n inflating: ./valve/normal_id_06_00000471.wav \n inflating: ./valve/normal_id_06_00000472.wav \n inflating: ./valve/normal_id_06_00000473.wav \n inflating: ./valve/normal_id_06_00000474.wav \n inflating: ./valve/normal_id_06_00000475.wav \n inflating: ./valve/normal_id_06_00000476.wav \n inflating: ./valve/normal_id_06_00000477.wav \n inflating: ./valve/normal_id_06_00000478.wav \n inflating: ./valve/normal_id_06_00000479.wav \n inflating: ./valve/normal_id_06_00000480.wav \n inflating: ./valve/normal_id_06_00000481.wav \n inflating: ./valve/normal_id_06_00000482.wav \n inflating: ./valve/normal_id_06_00000483.wav \n inflating: ./valve/normal_id_06_00000484.wav \n inflating: ./valve/normal_id_06_00000485.wav \n inflating: ./valve/normal_id_06_00000486.wav \n inflating: ./valve/normal_id_06_00000487.wav \n inflating: ./valve/normal_id_06_00000488.wav \n inflating: ./valve/normal_id_06_00000489.wav \n inflating: ./valve/normal_id_06_00000490.wav \n inflating: ./valve/normal_id_06_00000491.wav \n inflating: ./valve/normal_id_06_00000492.wav \n inflating: ./valve/normal_id_06_00000493.wav \n inflating: ./valve/normal_id_06_00000494.wav \n inflating: ./valve/normal_id_06_00000495.wav \n inflating: ./valve/normal_id_06_00000496.wav \n inflating: ./valve/normal_id_06_00000497.wav \n inflating: ./valve/normal_id_06_00000498.wav \n inflating: ./valve/normal_id_06_00000499.wav \n inflating: ./valve/normal_id_06_00000500.wav \n inflating: ./valve/normal_id_06_00000501.wav \n inflating: ./valve/normal_id_06_00000502.wav \n inflating: ./valve/normal_id_06_00000503.wav \n inflating: ./valve/normal_id_06_00000504.wav \n inflating: ./valve/normal_id_06_00000505.wav \n inflating: ./valve/normal_id_06_00000506.wav \n inflating: ./valve/normal_id_06_00000507.wav \n inflating: ./valve/normal_id_06_00000508.wav \n inflating: ./valve/normal_id_06_00000509.wav \n inflating: ./valve/normal_id_06_00000510.wav \n inflating: ./valve/normal_id_06_00000511.wav \n inflating: ./valve/normal_id_06_00000512.wav \n inflating: ./valve/normal_id_06_00000513.wav \n inflating: ./valve/normal_id_06_00000514.wav \n inflating: ./valve/normal_id_06_00000515.wav \n inflating: ./valve/normal_id_06_00000516.wav \n inflating: ./valve/normal_id_06_00000517.wav \n inflating: ./valve/normal_id_06_00000518.wav \n inflating: ./valve/normal_id_06_00000519.wav \n inflating: ./valve/normal_id_06_00000520.wav \n inflating: ./valve/normal_id_06_00000521.wav \n inflating: ./valve/normal_id_06_00000522.wav \n inflating: ./valve/normal_id_06_00000523.wav \n inflating: ./valve/normal_id_06_00000524.wav \n inflating: ./valve/normal_id_06_00000525.wav \n inflating: ./valve/normal_id_06_00000526.wav \n inflating: ./valve/normal_id_06_00000527.wav \n inflating: ./valve/normal_id_06_00000528.wav \n inflating: ./valve/normal_id_06_00000529.wav \n inflating: ./valve/normal_id_06_00000530.wav \n inflating: ./valve/normal_id_06_00000531.wav \n inflating: ./valve/normal_id_06_00000532.wav \n inflating: ./valve/normal_id_06_00000533.wav \n inflating: ./valve/normal_id_06_00000534.wav \n inflating: ./valve/normal_id_06_00000535.wav \n inflating: ./valve/normal_id_06_00000536.wav \n inflating: ./valve/normal_id_06_00000537.wav \n inflating: ./valve/normal_id_06_00000538.wav \n inflating: ./valve/normal_id_06_00000539.wav \n inflating: ./valve/normal_id_06_00000540.wav \n inflating: ./valve/normal_id_06_00000541.wav \n inflating: ./valve/normal_id_06_00000542.wav \n inflating: ./valve/normal_id_06_00000543.wav \n inflating: ./valve/normal_id_06_00000544.wav \n inflating: ./valve/normal_id_06_00000545.wav \n inflating: ./valve/normal_id_06_00000546.wav \n inflating: ./valve/normal_id_06_00000547.wav \n inflating: ./valve/normal_id_06_00000548.wav \n inflating: ./valve/normal_id_06_00000549.wav \n inflating: ./valve/normal_id_06_00000550.wav \n inflating: ./valve/normal_id_06_00000551.wav \n inflating: ./valve/normal_id_06_00000552.wav \n inflating: ./valve/normal_id_06_00000553.wav \n inflating: ./valve/normal_id_06_00000554.wav \n inflating: ./valve/normal_id_06_00000555.wav \n inflating: ./valve/normal_id_06_00000556.wav \n inflating: ./valve/normal_id_06_00000557.wav \n inflating: ./valve/normal_id_06_00000558.wav \n inflating: ./valve/normal_id_06_00000559.wav \n inflating: ./valve/normal_id_06_00000560.wav \n inflating: ./valve/normal_id_06_00000561.wav \n inflating: ./valve/normal_id_06_00000562.wav \n inflating: ./valve/normal_id_06_00000563.wav \n inflating: ./valve/normal_id_06_00000564.wav \n inflating: ./valve/normal_id_06_00000565.wav \n inflating: ./valve/normal_id_06_00000566.wav \n inflating: ./valve/normal_id_06_00000567.wav \n inflating: ./valve/normal_id_06_00000568.wav \n inflating: ./valve/normal_id_06_00000569.wav \n inflating: ./valve/normal_id_06_00000570.wav \n inflating: ./valve/normal_id_06_00000571.wav \n inflating: ./valve/normal_id_06_00000572.wav \n inflating: ./valve/normal_id_06_00000573.wav \n inflating: ./valve/normal_id_06_00000574.wav \n inflating: ./valve/normal_id_06_00000575.wav \n inflating: ./valve/normal_id_06_00000576.wav \n inflating: ./valve/normal_id_06_00000577.wav \n inflating: ./valve/normal_id_06_00000578.wav \n inflating: ./valve/normal_id_06_00000579.wav \n inflating: ./valve/normal_id_06_00000580.wav \n inflating: ./valve/normal_id_06_00000581.wav \n inflating: ./valve/normal_id_06_00000582.wav \n inflating: ./valve/normal_id_06_00000583.wav \n inflating: ./valve/normal_id_06_00000584.wav \n inflating: ./valve/normal_id_06_00000585.wav \n inflating: ./valve/normal_id_06_00000586.wav \n inflating: ./valve/normal_id_06_00000587.wav \n inflating: ./valve/normal_id_06_00000588.wav \n inflating: ./valve/normal_id_06_00000589.wav \n inflating: ./valve/normal_id_06_00000590.wav \n inflating: ./valve/normal_id_06_00000591.wav \n inflating: ./valve/normal_id_06_00000592.wav \n inflating: ./valve/normal_id_06_00000593.wav \n inflating: ./valve/normal_id_06_00000594.wav \n inflating: ./valve/normal_id_06_00000595.wav \n inflating: ./valve/normal_id_06_00000596.wav \n inflating: ./valve/normal_id_06_00000597.wav \n inflating: ./valve/normal_id_06_00000598.wav \n inflating: ./valve/normal_id_06_00000599.wav \n inflating: ./valve/normal_id_06_00000600.wav \n inflating: ./valve/normal_id_06_00000601.wav \n inflating: ./valve/normal_id_06_00000602.wav \n inflating: ./valve/normal_id_06_00000603.wav \n inflating: ./valve/normal_id_06_00000604.wav \n inflating: ./valve/normal_id_06_00000605.wav \n inflating: ./valve/normal_id_06_00000606.wav \n inflating: ./valve/normal_id_06_00000607.wav \n inflating: ./valve/normal_id_06_00000608.wav \n inflating: ./valve/normal_id_06_00000609.wav \n inflating: ./valve/normal_id_06_00000610.wav \n inflating: ./valve/normal_id_06_00000611.wav \n inflating: ./valve/normal_id_06_00000612.wav \n inflating: ./valve/normal_id_06_00000613.wav \n inflating: ./valve/normal_id_06_00000614.wav \n inflating: ./valve/normal_id_06_00000615.wav \n inflating: ./valve/normal_id_06_00000616.wav \n inflating: ./valve/normal_id_06_00000617.wav \n inflating: ./valve/normal_id_06_00000618.wav \n inflating: ./valve/normal_id_06_00000619.wav \n inflating: ./valve/normal_id_06_00000620.wav \n inflating: ./valve/normal_id_06_00000621.wav \n inflating: ./valve/normal_id_06_00000622.wav \n inflating: ./valve/normal_id_06_00000623.wav \n inflating: ./valve/normal_id_06_00000624.wav \n inflating: ./valve/normal_id_06_00000625.wav \n inflating: ./valve/normal_id_06_00000626.wav \n inflating: ./valve/normal_id_06_00000627.wav \n inflating: ./valve/normal_id_06_00000628.wav \n inflating: ./valve/normal_id_06_00000629.wav \n inflating: ./valve/normal_id_06_00000630.wav \n inflating: ./valve/normal_id_06_00000631.wav \n inflating: ./valve/normal_id_06_00000632.wav \n inflating: ./valve/normal_id_06_00000633.wav \n inflating: ./valve/normal_id_06_00000634.wav \n inflating: ./valve/normal_id_06_00000635.wav \n inflating: ./valve/normal_id_06_00000636.wav \n inflating: ./valve/normal_id_06_00000637.wav \n inflating: ./valve/normal_id_06_00000638.wav \n inflating: ./valve/normal_id_06_00000639.wav \n inflating: ./valve/normal_id_06_00000640.wav \n inflating: ./valve/normal_id_06_00000641.wav \n inflating: ./valve/normal_id_06_00000642.wav \n inflating: ./valve/normal_id_06_00000643.wav \n inflating: ./valve/normal_id_06_00000644.wav \n inflating: ./valve/normal_id_06_00000645.wav \n inflating: ./valve/normal_id_06_00000646.wav \n inflating: ./valve/normal_id_06_00000647.wav \n inflating: ./valve/normal_id_06_00000648.wav \n inflating: ./valve/normal_id_06_00000649.wav \n inflating: ./valve/normal_id_06_00000650.wav \n inflating: ./valve/normal_id_06_00000651.wav \n inflating: ./valve/normal_id_06_00000652.wav \n inflating: ./valve/normal_id_06_00000653.wav \n inflating: ./valve/normal_id_06_00000654.wav \n inflating: ./valve/normal_id_06_00000655.wav \n inflating: ./valve/normal_id_06_00000656.wav \n inflating: ./valve/normal_id_06_00000657.wav \n inflating: ./valve/normal_id_06_00000658.wav \n inflating: ./valve/normal_id_06_00000659.wav \n inflating: ./valve/normal_id_06_00000660.wav \n inflating: ./valve/normal_id_06_00000661.wav \n inflating: ./valve/normal_id_06_00000662.wav \n inflating: ./valve/normal_id_06_00000663.wav \n inflating: ./valve/normal_id_06_00000664.wav \n inflating: ./valve/normal_id_06_00000665.wav \n inflating: ./valve/normal_id_06_00000666.wav \n inflating: ./valve/normal_id_06_00000667.wav \n inflating: ./valve/normal_id_06_00000668.wav \n inflating: ./valve/normal_id_06_00000669.wav \n inflating: ./valve/normal_id_06_00000670.wav \n inflating: ./valve/normal_id_06_00000671.wav \n inflating: ./valve/normal_id_06_00000672.wav \n inflating: ./valve/normal_id_06_00000673.wav \n inflating: ./valve/normal_id_06_00000674.wav \n inflating: ./valve/normal_id_06_00000675.wav \n inflating: ./valve/normal_id_06_00000676.wav \n inflating: ./valve/normal_id_06_00000677.wav \n inflating: ./valve/normal_id_06_00000678.wav \n inflating: ./valve/normal_id_06_00000679.wav \n inflating: ./valve/normal_id_06_00000680.wav \n inflating: ./valve/normal_id_06_00000681.wav \n inflating: ./valve/normal_id_06_00000682.wav \n inflating: ./valve/normal_id_06_00000683.wav \n inflating: ./valve/normal_id_06_00000684.wav \n inflating: ./valve/normal_id_06_00000685.wav \n inflating: ./valve/normal_id_06_00000686.wav \n inflating: ./valve/normal_id_06_00000687.wav \n inflating: ./valve/normal_id_06_00000688.wav \n inflating: ./valve/normal_id_06_00000689.wav \n inflating: ./valve/normal_id_06_00000690.wav \n inflating: ./valve/normal_id_06_00000691.wav \n inflating: ./valve/normal_id_06_00000692.wav \n inflating: ./valve/normal_id_06_00000693.wav \n inflating: ./valve/normal_id_06_00000694.wav \n inflating: ./valve/normal_id_06_00000695.wav \n inflating: ./valve/normal_id_06_00000696.wav \n inflating: ./valve/normal_id_06_00000697.wav \n inflating: ./valve/normal_id_06_00000698.wav \n inflating: ./valve/normal_id_06_00000699.wav \n inflating: ./valve/normal_id_06_00000700.wav \n inflating: ./valve/normal_id_06_00000701.wav \n inflating: ./valve/normal_id_06_00000702.wav \n inflating: ./valve/normal_id_06_00000703.wav \n inflating: ./valve/normal_id_06_00000704.wav \n inflating: ./valve/normal_id_06_00000705.wav \n inflating: ./valve/normal_id_06_00000706.wav \n inflating: ./valve/normal_id_06_00000707.wav \n inflating: ./valve/normal_id_06_00000708.wav \n inflating: ./valve/normal_id_06_00000709.wav \n inflating: ./valve/normal_id_06_00000710.wav \n inflating: ./valve/normal_id_06_00000711.wav \n inflating: ./valve/normal_id_06_00000712.wav \n inflating: ./valve/normal_id_06_00000713.wav \n inflating: ./valve/normal_id_06_00000714.wav \n inflating: ./valve/normal_id_06_00000715.wav \n inflating: ./valve/normal_id_06_00000716.wav \n inflating: ./valve/normal_id_06_00000717.wav \n inflating: ./valve/normal_id_06_00000718.wav \n inflating: ./valve/normal_id_06_00000719.wav \n inflating: ./valve/normal_id_06_00000720.wav \n inflating: ./valve/normal_id_06_00000721.wav \n inflating: ./valve/normal_id_06_00000722.wav \n inflating: ./valve/normal_id_06_00000723.wav \n inflating: ./valve/normal_id_06_00000724.wav \n inflating: ./valve/normal_id_06_00000725.wav \n inflating: ./valve/normal_id_06_00000726.wav \n inflating: ./valve/normal_id_06_00000727.wav \n inflating: ./valve/normal_id_06_00000728.wav \n inflating: ./valve/normal_id_06_00000729.wav \n inflating: ./valve/normal_id_06_00000730.wav \n inflating: ./valve/normal_id_06_00000731.wav \n inflating: ./valve/normal_id_06_00000732.wav \n inflating: ./valve/normal_id_06_00000733.wav \n inflating: ./valve/normal_id_06_00000734.wav \n inflating: ./valve/normal_id_06_00000735.wav \n inflating: ./valve/normal_id_06_00000736.wav \n inflating: ./valve/normal_id_06_00000737.wav \n inflating: ./valve/normal_id_06_00000738.wav \n inflating: ./valve/normal_id_06_00000739.wav \n inflating: ./valve/normal_id_06_00000740.wav \n inflating: ./valve/normal_id_06_00000741.wav \n inflating: ./valve/normal_id_06_00000742.wav \n inflating: ./valve/normal_id_06_00000743.wav \n inflating: ./valve/normal_id_06_00000744.wav \n inflating: ./valve/normal_id_06_00000745.wav \n inflating: ./valve/normal_id_06_00000746.wav \n inflating: ./valve/normal_id_06_00000747.wav \n inflating: ./valve/normal_id_06_00000748.wav \n inflating: ./valve/normal_id_06_00000749.wav \n inflating: ./valve/normal_id_06_00000750.wav \n inflating: ./valve/normal_id_06_00000751.wav \n inflating: ./valve/normal_id_06_00000752.wav \n inflating: ./valve/normal_id_06_00000753.wav \n inflating: ./valve/normal_id_06_00000754.wav \n inflating: ./valve/normal_id_06_00000755.wav \n inflating: ./valve/normal_id_06_00000756.wav \n inflating: ./valve/normal_id_06_00000757.wav \n inflating: ./valve/normal_id_06_00000758.wav \n inflating: ./valve/normal_id_06_00000759.wav \n inflating: ./valve/normal_id_06_00000760.wav \n inflating: ./valve/normal_id_06_00000761.wav \n inflating: ./valve/normal_id_06_00000762.wav \n inflating: ./valve/normal_id_06_00000763.wav \n inflating: ./valve/normal_id_06_00000764.wav \n inflating: ./valve/normal_id_06_00000765.wav \n inflating: ./valve/normal_id_06_00000766.wav \n inflating: ./valve/normal_id_06_00000767.wav \n inflating: ./valve/normal_id_06_00000768.wav \n inflating: ./valve/normal_id_06_00000769.wav \n inflating: ./valve/normal_id_06_00000770.wav \n inflating: ./valve/normal_id_06_00000771.wav \n inflating: ./valve/normal_id_06_00000772.wav \n inflating: ./valve/normal_id_06_00000773.wav \n inflating: ./valve/normal_id_06_00000774.wav \n inflating: ./valve/normal_id_06_00000775.wav \n inflating: ./valve/normal_id_06_00000776.wav \n inflating: ./valve/normal_id_06_00000777.wav \n inflating: ./valve/normal_id_06_00000778.wav \n inflating: ./valve/normal_id_06_00000779.wav \n inflating: ./valve/normal_id_06_00000780.wav \n inflating: ./valve/normal_id_06_00000781.wav \n inflating: ./valve/normal_id_06_00000782.wav \n inflating: ./valve/normal_id_06_00000783.wav \n inflating: ./valve/normal_id_06_00000784.wav \n inflating: ./valve/normal_id_06_00000785.wav \n inflating: ./valve/normal_id_06_00000786.wav \n inflating: ./valve/normal_id_06_00000787.wav \n inflating: ./valve/normal_id_06_00000788.wav \n inflating: ./valve/normal_id_06_00000789.wav \n inflating: ./valve/normal_id_06_00000790.wav \n inflating: ./valve/normal_id_06_00000791.wav \n inflating: ./valve/normal_id_06_00000792.wav \n inflating: ./valve/normal_id_06_00000793.wav \n inflating: ./valve/normal_id_06_00000794.wav \n inflating: ./valve/normal_id_06_00000795.wav \n inflating: ./valve/normal_id_06_00000796.wav \n inflating: ./valve/normal_id_06_00000797.wav \n inflating: ./valve/normal_id_06_00000798.wav \n inflating: ./valve/normal_id_06_00000799.wav \n inflating: ./valve/normal_id_06_00000800.wav \n inflating: ./valve/normal_id_06_00000801.wav \n inflating: ./valve/normal_id_06_00000802.wav \n inflating: ./valve/normal_id_06_00000803.wav \n inflating: ./valve/normal_id_06_00000804.wav \n inflating: ./valve/normal_id_06_00000805.wav \n inflating: ./valve/normal_id_06_00000806.wav \n inflating: ./valve/normal_id_06_00000807.wav \n inflating: ./valve/normal_id_06_00000808.wav \n inflating: ./valve/normal_id_06_00000809.wav \n inflating: ./valve/normal_id_06_00000810.wav \n inflating: ./valve/normal_id_06_00000811.wav \n inflating: ./valve/normal_id_06_00000812.wav \n inflating: ./valve/normal_id_06_00000813.wav \n inflating: ./valve/normal_id_06_00000814.wav \n inflating: ./valve/normal_id_06_00000815.wav \n inflating: ./valve/normal_id_06_00000816.wav \n inflating: ./valve/normal_id_06_00000817.wav \n inflating: ./valve/normal_id_06_00000818.wav \n inflating: ./valve/normal_id_06_00000819.wav \n inflating: ./valve/normal_id_06_00000820.wav \n inflating: ./valve/normal_id_06_00000821.wav \n inflating: ./valve/normal_id_06_00000822.wav \n inflating: ./valve/normal_id_06_00000823.wav \n inflating: ./valve/normal_id_06_00000824.wav \n inflating: ./valve/normal_id_06_00000825.wav \n inflating: ./valve/normal_id_06_00000826.wav \n inflating: ./valve/normal_id_06_00000827.wav \n inflating: ./valve/normal_id_06_00000828.wav \n inflating: ./valve/normal_id_06_00000829.wav \n inflating: ./valve/normal_id_06_00000830.wav \n inflating: ./valve/normal_id_06_00000831.wav \n inflating: ./valve/normal_id_06_00000832.wav \n inflating: ./valve/normal_id_06_00000833.wav \n inflating: ./valve/normal_id_06_00000834.wav \n inflating: ./valve/normal_id_06_00000835.wav \n inflating: ./valve/normal_id_06_00000836.wav \n inflating: ./valve/normal_id_06_00000837.wav \n inflating: ./valve/normal_id_06_00000838.wav \n inflating: ./valve/normal_id_06_00000839.wav \n inflating: ./valve/normal_id_06_00000840.wav \n inflating: ./valve/normal_id_06_00000841.wav \n inflating: ./valve/normal_id_06_00000842.wav \n inflating: ./valve/normal_id_06_00000843.wav \n inflating: ./valve/normal_id_06_00000844.wav \n inflating: ./valve/normal_id_06_00000845.wav \n inflating: ./valve/normal_id_06_00000846.wav \n inflating: ./valve/normal_id_06_00000847.wav \n inflating: ./valve/normal_id_06_00000848.wav \n inflating: ./valve/normal_id_06_00000849.wav \n inflating: ./valve/normal_id_06_00000850.wav \n inflating: ./valve/normal_id_06_00000851.wav \n inflating: ./valve/normal_id_06_00000852.wav \n inflating: ./valve/normal_id_06_00000853.wav \n inflating: ./valve/normal_id_06_00000854.wav \n inflating: ./valve/normal_id_06_00000855.wav \n inflating: ./valve/normal_id_06_00000856.wav \n inflating: ./valve/normal_id_06_00000857.wav \n inflating: ./valve/normal_id_06_00000858.wav \n inflating: ./valve/normal_id_06_00000859.wav \n inflating: ./valve/normal_id_06_00000860.wav \n inflating: ./valve/normal_id_06_00000861.wav \n inflating: ./valve/normal_id_06_00000862.wav \n inflating: ./valve/normal_id_06_00000863.wav \n inflating: ./valve/normal_id_06_00000864.wav \n inflating: ./valve/normal_id_06_00000865.wav \n inflating: ./valve/normal_id_06_00000866.wav \n inflating: ./valve/normal_id_06_00000867.wav \n inflating: ./valve/normal_id_06_00000868.wav \n inflating: ./valve/normal_id_06_00000869.wav \n inflating: ./valve/normal_id_06_00000870.wav \n inflating: ./valve/normal_id_06_00000871.wav \n inflating: ./valve/normal_id_06_00000872.wav \n inflating: ./valve/normal_id_06_00000873.wav \n inflating: ./valve/normal_id_06_00000874.wav \n inflating: ./valve/normal_id_06_00000875.wav \n inflating: ./valve/normal_id_06_00000876.wav \n inflating: ./valve/normal_id_06_00000877.wav \n inflating: ./valve/normal_id_06_00000878.wav \n inflating: ./valve/normal_id_06_00000879.wav \n inflating: ./valve/normal_id_06_00000880.wav \n inflating: ./valve/normal_id_06_00000881.wav \n inflating: ./valve/normal_id_06_00000882.wav \n inflating: ./valve/normal_id_06_00000883.wav \n inflating: ./valve/normal_id_06_00000884.wav \n inflating: ./valve/normal_id_06_00000885.wav \n inflating: ./valve/normal_id_06_00000886.wav \n inflating: ./valve/normal_id_06_00000887.wav \n inflating: ./valve/normal_id_06_00000888.wav \n inflating: ./valve/normal_id_06_00000889.wav \n inflating: ./valve/normal_id_06_00000890.wav \n inflating: ./valve/normal_id_06_00000891.wav \n" ], [ "import os\nimport time\nimport librosa\nimport librosa.core\nimport librosa.feature\nimport yaml\nimport glob\n", "_____no_output_____" ], [ "def yaml_load():\n with open('params.yaml') as stream:\n param = yaml.safe_load(stream)\n return param\n\ndef file_load(wav_name):\n try:\n return librosa.load(wav_name, sr=None, mono=False)\n except:\n print('file_broken or not exists!! : {}'.format(wav_name))\n", "_____no_output_____" ], [ "param = yaml_load()\n\nos.makedirs(param['model_dir'], exist_ok=True)\n\ndataset_dir = os.path.abspath(param['dataset_dir'])\nmachine_type = os.path.split(dataset_dir)[1]\nmodel_file_path = '{model}/model_{machine_type}.'.format\n\nprint(dataset_dir)\nprint(machine_type)\nprint(model_file_path)", "/content/valve\n('/content', 'valve')\n<built-in method format of str object at 0x7fe33568fd00>\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ] ]
cb24b1e2265c663eae28a50c753d1f9d2c7de3cb
9,708
ipynb
Jupyter Notebook
6. Random Networks and Statistics (Student).ipynb
sk-rai/Network-Analysis_made-Simple
9eabfd637640df38d087b490142474f3dafc7d5d
[ "MIT" ]
null
null
null
6. Random Networks and Statistics (Student).ipynb
sk-rai/Network-Analysis_made-Simple
9eabfd637640df38d087b490142474f3dafc7d5d
[ "MIT" ]
null
null
null
6. Random Networks and Statistics (Student).ipynb
sk-rai/Network-Analysis_made-Simple
9eabfd637640df38d087b490142474f3dafc7d5d
[ "MIT" ]
null
null
null
29.153153
301
0.574475
[ [ [ "# Introduction\n\nSo... you've got some interesting property of the network uncovered. Is it real? How can you trust that what you've found **didn't arise by random chance**?\n\nOne useful way of thinking by using generative models of random graphs. By \"generative\" and \"random\", we mean that the graph was generated using some statistical random model underlying it. This is essentially in the \"Bayesian\" tradition of modelling.\n\nThe alternative is a non-parametric way of thinking. This is where we don't assume some model that generated the data, and instead performs randomization on the data on hand to calculate statistics. Here, we assume that our randomization procedure is an appropriate random model for the network.", "_____no_output_____" ], [ "## Statistics Primer\n\n**Discrete Distributions:**\n\n- Bernoulli: probability p of success in 1 try (e.g. one flip of coin).\n- Binomial: probability p of success given n number of tries. `n * bernoulli trials` follows binomial distribution.\n- Poisson: processes with a per-unit rate.\n\n**Continuous Distributions:**\n\n- Uniform: equal probability over the range of probable values. Can also be made discrete.\n- Normal: everyone's favourite.\n\nWe can also make up an arbitrary distribution of our own. :-)", "_____no_output_____" ], [ "## Statistical Test of Significance of Busy Routes\n\nIf we think back to the graph made in the previous notebook, what kind of process might one imagine that gave rise to the data?\n\n**brainstorm session...**\n\nGroup work.", "_____no_output_____" ], [ "## Discrete uniform distribution over all routes\n\nAssumptions of this model:\n\n1. Riders choose start station with uniform probability.\n2. They then choose a destination station with uniform probability.\n3. They ride it and the data are recorded.\n\nUnder this model, what is the distribution of number of rides taken throughout the ? We can probably solve this analytically, but since we have ultra-cheap computational capabilities at our fingertips, might as well do it the brute-force way.", "_____no_output_____" ] ], [ [ "import networkx as nx\n\nG = nx.read_gpickle('datasets/divvy_2013/divvy_graph.pkl')\ntotal_trips = sum([d['count'] for _,_,d in G.edges(data=True)])\nprint(total_trips)", "_____no_output_____" ] ], [ [ "### Exercise\n\nCalculate the expected number of trips between any two stations, assuming self-loops are allowed.", "_____no_output_____" ], [ "### Exercise\n\nCan you plot a histogram of the number of trips taken on each route?", "_____no_output_____" ], [ "### Exercise\n\nCan you figure out the 2.5th, 97.5th, and 100th percentile of this distribution?\n\nHint: You may wish to use `numpy`'s `percentile` function.", "_____no_output_____" ] ], [ [ "import numpy as np", "_____no_output_____" ] ], [ [ "Computing the interval between the 2.5th to the 97.5th percentile effectively gives you a centered 95% mass of the distribution. Knowing this range can be quite useful in other data analysis cases.", "_____no_output_____" ], [ "### Live Class Exercise\n\nTogether, we will implement a random model for the number of trips that are taken between two stations.\n\nIn this procedure, we will copy the nodes graph `G` into a new graph `G_random`. This can be done by:\n\n G_random = nx.Graph()\n G_random.add_nodes_from(G.nodes(data=True))\n \nFollowing that, we will manually map-reduce this computation.", "_____no_output_____" ] ], [ [ "# Grab all the nodes from G.\nG_random = nx.Graph()\nG_random.add_nodes_from(G.nodes(data=True))\nG_random.nodes(data=True)", "_____no_output_____" ], [ "# Implement the procedure by brute force. You will find it takes a bit of time.......... but because we have so many people \n# in the class, we can brute force parallelize this :-).\nfrom random import sample, choice\nimport math\n\nn = 40 # the total number of students with Python 3.4 installed.\n\nfor i in range(math.ceil(total_trips/n)):\n if i % 1000 == 0:\n print(i)\n n1 = choice(G_random.nodes())\n n2 = choice(G_random.nodes()) #note: n1 and n2 might well be the same nodes.\n if (n1, n2) not in G_random.edges():\n G_random.add_edge(n1, n2, count=0)\n else:\n G_random.edge[n1][n2]['count'] += 1", "_____no_output_____" ], [ "your_id = 1 # change this number to the ID given to you.\nnx.write_gpickle(G_random, 'datasets/divvy_2013/divvy_random{0}.pkl'.format(your_id))", "_____no_output_____" ], [ "# Load the graphs with randomly re-distributed trip counts as a list of graphs.\nimport os\n\ndef is_pkl(filename):\n \"\"\"\n Checks if a file is a pickled graph.\n \"\"\"\n if filename.split('.')[-1] == 'pkl':\n return True\n else:\n return False\n \ndef is_divvy_random_graph(filename):\n \"\"\"\n Checks if it's a Divvy graph.\n \"\"\"\n if 'divvy_random' in filename:\n return True\n else:\n return False\n \n# Load the data into a list of graphs.\ndivvy_random_graphs = []\nfor f in os.listdir('datasets/divvy_2013'):\n if is_pkl(f) and is_divvy_random_graph(f):\n g = nx.read_gpickle('datasets/divvy_2013/{0}'.format(f))\n graphs.append(g)", "_____no_output_____" ], [ "# Plot the distribution of counts in a re-distributed set of trips.\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nG_random_master = nx.Graph()\n\nfor g in graphs:\n for sc, sk, d in g.edges(data=True):\n if (sc, sk) not in G_random_master.edges():\n G_random_master.add_edge(sc, sk, count=d['count'])\n if (sc, sk) in G_random_master.edges():\n G_random_master.edge[sc][sk]['count'] += d['count']\n\n# Remove edges that have no counts\nfor sc, sk, d in G_random_master.edges(data=True):\n if d['count'] == 0:\n G_random_master.remove_edge(sc, sk)\n\n# Plot the distribution of counts throughout the network\ncounts = [d['count'] for _,_,d in G_random_master.edges(data=True)]\nplt.bar(Counter(counts).keys(), Counter(counts).values())\nplt.show()", "_____no_output_____" ], [ "nx.write_gpickle(G_random_master, 'datasets/divvy_2013/divvy_random_master.pkl')", "_____no_output_____" ] ], [ [ "**Think about it...**\n\nGiven the distribution of trip counts in the randomly re-distributed trips, what can we infer about the popularity of certain routes? Are they likely to have shown up in this random model?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cb24b24080b673b74ae960c1f2be959051d663b7
3,075
ipynb
Jupyter Notebook
Japan SWRs.ipynb
hoostus/prime-harvesting
6606b94ea7859fbf217dbea4ace856e3fa4d154e
[ "BlueOak-1.0.0", "Apache-2.0" ]
23
2016-09-07T06:13:37.000Z
2022-02-17T23:49:03.000Z
Japan SWRs.ipynb
hoostus/prime-harvesting
6606b94ea7859fbf217dbea4ace856e3fa4d154e
[ "BlueOak-1.0.0", "Apache-2.0" ]
null
null
null
Japan SWRs.ipynb
hoostus/prime-harvesting
6606b94ea7859fbf217dbea4ace856e3fa4d154e
[ "BlueOak-1.0.0", "Apache-2.0" ]
12
2016-06-30T17:27:39.000Z
2021-12-12T07:54:27.000Z
27.702703
136
0.541138
[ [ [ "%matplotlib inline\n\nimport pandas\n\nimport metrics\nimport plot\nimport market\nfrom simulate import simulate_withdrawals\nimport withdrawal\nimport harvesting\n\nfrom decimal import Decimal", "_____no_output_____" ], [ "m = market.Japan_1957()\nyears = 25\nstart_year = 1957\nlast_year = 2016-years\n\ndef run(stock_pct):\n swrs = pandas.Series()\n for _ in range(last_year - start_year + 1):\n returns = []\n for one_year in zip(range(years), m.iter_from(start_year + _)):\n annual_returns = one_year[1]\n stocks = annual_returns.stocks - annual_returns.inflation\n bonds = annual_returns.bonds - annual_returns.inflation\n returns.append((stocks * stock_pct) + (bonds * (1-stock_pct)))\n swr = float(metrics.ssr(returns))\n swrs.loc[start_year+_] = swr\n return swrs\n\nplot.plot_n({\n# '0/100' : run(Decimal(0)),\n# '20/80' : run(Decimal(.2)),\n# '40/60' : run(Decimal(.4)),\n '50/50' : run(Decimal(.5)),\n# '60/40' : run(Decimal(.6)),\n# '80/20' : run(Decimal(.8)),\n# '100/0' : run(Decimal(1)), \n}, '', 'Safe Withdrawal Rate by Year (%s-%s)' % (start_year, last_year), add_commas=False)\n", "_____no_output_____" ], [ "run(Decimal(.5)).loc[1991]*100", "_____no_output_____" ], [ "length = 25\nyear = 1990\nvpw = simulate_withdrawals(m.iter_from(year), withdraw=withdrawal.VPW, harvesting=harvesting.make_rebalancer(.5), years=length)\necm = simulate_withdrawals(m.iter_from(year), withdraw=withdrawal.ECM, harvesting=harvesting.PrimeHarvesting, years=length)\nplot.seaborn.tsplot([float(n.withdraw_r) for n in vpw], color='green', legend=True, condition='VPW')\n#plot.seaborn.tsplot([float(n.withdraw_r) for n in ecm], color='red', legend=True, condition='ECM')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
cb24b845085a49c94b210c353939ff9900b52aa1
33,337
ipynb
Jupyter Notebook
older/self_initiated_paper/process_data.ipynb
catubc/widefield
7f6923cfbb290c459aaeabfdb7c1f4bbe4f3a185
[ "MIT" ]
null
null
null
older/self_initiated_paper/process_data.ipynb
catubc/widefield
7f6923cfbb290c459aaeabfdb7c1f4bbe4f3a185
[ "MIT" ]
null
null
null
older/self_initiated_paper/process_data.ipynb
catubc/widefield
7f6923cfbb290c459aaeabfdb7c1f4bbe4f3a185
[ "MIT" ]
null
null
null
34.121801
142
0.411855
[ [ [ "import matplotlib\n#matplotlib.use('Agg')\n%matplotlib tk\n%autosave 180\nimport matplotlib.pyplot as plt\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))\n\nimport matplotlib.cm as cm\nfrom matplotlib import gridspec\nimport parmap\nimport numpy as np\nimport pandas as pd\nimport os\nimport parmap\nimport shutil\nimport cv2\nimport scipy.io as sio\nfrom Specgram import Specgram\nimport csv\n\nimport glob2\n", "_____no_output_____" ], [ "from scipy import stats\nimport scipy\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\n\nclass Visualize():\n \n def __init__(self):\n \n self.clr_ctr = 0\n \n #\n self.animal_names = ['IA1','IA2','IA3','IJ1','IJ2','AQ2']\n \n #\n self.colors = ['black','blue','red','green','magenta','pink','cyan']\n\n #\n self.n_colors = [10,19,23,17,20,48]\n\n #\n self.filter=False\n\n def load_data(self, fname):\n \n self.data = np.load(fname)\n \n\n \n def format_plot(self, ax):\n ''' Formats plots for decision choice with 50% and 0 lines\n '''\n # meta data\n xlims = [-10,10]\n ylims = [0.4,1.0]\n ax.plot([0,0],\n [ylims[0],ylims[1]],\n 'r--',\n linewidth=3,\n color='black',\n alpha=.5)\n\n ax.plot([xlims[0],xlims[1]],\n [0.5,0.5],\n 'r--',\n linewidth=3,\n color='black',\n alpha=.5)\n\n ax.set_xlim(-10,10)\n ax.set_ylim(0.4,1.0)\n\n \n \n def format_plot2(self, ax):\n ''' Format plots for time prediction\n '''\n # meta data\n xlims = [-10,0]\n ylims = [0.0,1.0]\n ax.plot([0,0],\n [ylims[0],ylims[1]],\n 'r--',\n linewidth=3,\n color='black',\n alpha=.5)\n\n ax.plot([xlims[0],xlims[1]],\n [0.1,0.1],\n 'r--',\n linewidth=3,\n color='black',\n alpha=.5)\n\n ax.set_xlim(xlims[0],xlims[1])\n ax.set_ylim(ylims[0],ylims[1])\n # plt.legend(fontsize=20)\n\n \n def plot_decision_choice(self, clr, label, title=None, ax=None):\n \n #\n if ax is None:\n ax=plt.subplot(111)\n \n #\n t = np.arange(-9.5, 10.5, 1)\n \n #\n mean = self.data.mean(1)\n std = np.std(self.data,axis=1)\n ax.plot(t, mean,\n c=clr,\n label = label,\n linewidth=4)\n ax.fill_between(t, mean-std, mean+std, alpha = 0.2)\n\n self.format_plot(ax)\n\n plt.legend(fontsize=20)\n if title is not None:\n plt.title(title)\n \n# def plot_decision_choice(self, clr, label, ax=None):\n \n# #\n# if ax is None:\n# ax=plt.subplot(111)\n \n# #\n# t = np.arange(-9.5, 10.5, 1)\n \n# #\n# mean = self.data.mean(1)\n# std = np.std(self.data,axis=1)\n# ax.plot(t, mean,\n# c=clr,\n# label = label,\n# linewidth=4)\n# ax.fill_between(t, mean-std, mean+std, alpha = 0.2)\n\n# self.format_plot(ax)\n\n# plt.legend(fontsize=20)\n \n \n \n def plot_significant(self, clr, label, animal_id, session):\n \n \n #\n fig=plt.figure()\n ax=plt.subplot(111)\n\n t = np.arange(-9.5, 10.5, 1)\n \n #\n mean = self.data.mean(1)\n std = np.std(self.data,axis=1)\n plt.plot(t, mean,\n c=clr,\n label = label,\n linewidth=4)\n plt.fill_between(t, mean-std, mean+std, alpha = 0.2)\n\n \n # grab end points\n control = np.hstack((self.data[-2:].flatten(),\n self.data[:2].flatten()))\n \n #control = self.data[:3].flatten()\n print (\"controL \", control.shape)\n \n sig = []\n for k in range(self.data.shape[0]):\n if True:\n res = stats.ks_2samp(self.data[k], \n control)\n \n else:\n res = scipy.stats.ttest_1samp(self.data[k], 0.5)\n print (res)\n \n sig.append(res[1])\n \n sig=np.array(sig)[None]\n print (sig)\n thresh = 0.05\n idx = np.where(sig>thresh)\n sig[idx]=np.nan\n vmin = np.nanmin(sig)\n vmax = np.nanmax(sig)\n vmin=0.0\n vmax=0.05\n\n axins = ax.inset_axes((0,.95,1,.05))\n axins.set_xticks([])\n axins.set_yticks([])\n im = axins.imshow(sig,vmin=vmin,vmax=vmax, \n aspect='auto',\n cmap='viridis_r')\n # \n ticks = np.round(np.linspace(vmin, vmax, 4),3)\n print (\"vmin, vmax; \", vmin, vmax, \"ticks: \", ticks)\n fmt = '%1.3f'\n #\n cbar = fig.colorbar(im, ax=ax, shrink=0.4, \n ticks=ticks, format = fmt)\n \n cbar.ax.tick_params(labelsize=16) \n cbar.ax.set_title('Pval', rotation=0,\n fontsize=16)\n \n self.format_plot(ax)\n plt.title(animal_id + \" session: \"+str(session))\n # \n\n def plot_trends(self, clr, label, ax):\n #\n t = np.arange(-9.5, 10.5, 1)\n \n colors = plt.cm.magma(np.linspace(0,1,self.n_colors))\n\n #\n mean = self.data.mean(1)\n std = np.std(self.data,axis=1)\n ax.plot(t, mean,\n c=colors[clr],\n label = label,\n linewidth=4)\n\n self.format_plot(ax)\n \n \n def plot_animal_decision_longitudinal_matrix(self, \n animal_name, \n lockout=False,\n ax=None):\n \n \n if ax is None:\n fig=plt.figure()\n ax=plt.subplot(111)\n #\n root_dir = self.main_dir+animal_name+'/'\n fnames = np.sort(glob2.glob(root_dir+'SVM_scores_'+animal_name+\"*\"))\n\n #\n #fig=plt.figure()\n img =[]\n for fname in fnames:\n if 'lockout' not in fname:\n if lockout==False:\n self.load_data(fname)\n temp = self.data.mean(1)\n else:\n # \n idx = fname.find('SVM_scores_'+animal_name)\n fname2 = fname[:idx+12]+\"_lockout\"+fname[idx+12:]\n self.load_data(fname[:idx+14]+\"_lockout\"+fname[idx+14:])\n temp = self.data.mean(1)\n \n if self.filter:\n temp = self.filter(temp)\n img.append(temp)\n\n img=np.array(img)\n ax.imshow(img)\n \n plt.xticks(np.arange(0,img.shape[1],2),\n np.arange(-9.5,10,2))\n plt.ylabel(\"Study day\")\n plt.title(animal_name)\n plt.suptitle(\"lockout: \"+str(lockout))\n #ticks = np.linspace(vmin,vmax,4)\n #cbar = fig.colorbar(im, ax=axes[5], \n # ticks=ticks)\n \n \n def plot_animal_decision_longitudinal(self, animal_name): \n animal_names = ['IA1','IA2','IA3','IJ1','IJ2','AQ2']\n \n idx=animal_names.index(animal_name)\n \n #\n root_dir = self.main_dir+animal_name+'/'\n fnames = np.sort(glob2.glob(root_dir+'SVM_scores_'+animal_name+\"*\"))\n \n #\n fig=plt.figure()\n ax1=plt.subplot(1,2,1)\n ax1.set_title(\"All\")\n ax2=plt.subplot(1,2,2)\n ax2.set_title(\"Lockout\")\n\n vis.n_colors = self.n_colors[idx]\n ctr=0\n for fname in fnames:\n if 'lockout' not in fname:\n print (fname)\n self.load_data(fname)\n self.plot_trends(ctr,'all',ax1)\n\n idx = fname.find('SVM_scores_'+animal_name)\n fname2 = fname[:idx+12]+\"_lockout\"+fname[idx+12:]\n print (fname2)\n self.load_data(fname[:idx+14]+\"_lockout\"+fname[idx+14:])\n self.plot_trends(ctr,'lockout', ax2)\n ctr+=1\n plt.suptitle(animal_name)\n\n\n def plot_animal_time_longitudinal(self, animal_name): \n animal_names = ['IA1','IA2','IA3','IJ1','IJ2','AQ2']\n \n idx=animal_names.index(animal_name)\n \n #\n root_dir = self.main_dir+animal_name+'/'\n fnames = np.sort(glob2.glob(root_dir+'SVM_scores_'+animal_name+\"*\"))\n \n #\n fig=plt.figure()\n ax1=plt.subplot(1,2,1)\n ax1.set_title(\"All\")\n ax2=plt.subplot(1,2,2)\n ax2.set_title(\"Lockout\")\n\n self.n_colors = self.ncolors[idx]\n ctr=0\n for fname in fnames:\n if 'lockout' not in fname:\n print (fname)\n self.load_data(fname)\n self.plot_trends(ctr,'all',ax1)\n\n idx = fname.find('SVM_scores_'+animal_name)\n fname2 = fname[:idx+12]+\"_lockout\"+fname[idx+12:]\n print (fname2)\n self.load_data(fname[:idx+14]+\"_lockout\"+fname[idx+14:])\n self.plot_trends(ctr,'lockout', ax2)\n ctr+=1\n \n plt.suptitle(animal_name)\n \n \n \n def plot_animal_decision_AUC_longitudinal(self): \n \n #\n ax1=plt.subplot(121)\n ax2=plt.subplot(122)\n #\n for animal_name in self.animal_names:\n #\n root_dir = self.main_dir+animal_name+'/'\n fnames = np.sort(glob2.glob(root_dir+'SVM_scores_'+animal_name+\"*\"))\n\n # time points 0 to 10 for decoding...\n width = [0,10]\n \n # only look at probs > 0.5\n thresh = 0.6\n\n #\n auc1 = []\n auc2 = []\n for fname in fnames:\n if 'lockout' not in fname:\n self.load_data(fname)\n temp = self.data.mean(1)[width[0]:width[1]]\n idx = np.where(temp>thresh)[0]\n temp = temp[idx]\n auc1.append(temp.sum(0))\n\n # load lockout version\n idx = fname.find('SVM_scores_'+animal_name)\n fname2 = fname[:idx+12]+\"_lockout\"+fname[idx+12:]\n self.load_data(fname[:idx+14]+\"_lockout\"+fname[idx+14:])\n temp = self.data.mean(1)[width[0]:width[1]]\n idx = np.where(temp>thresh)[0]\n temp = temp[idx]\n auc2.append(temp.sum(0))\n\n #\n auc1 = np.array(auc1)\n auc2 = np.array(auc2)\n t = np.arange(auc1.shape[0])/(auc1.shape[0]-1)\n\n # \n ax1.plot(t, np.poly1d(np.polyfit(t, auc1, 1))(t),\n linewidth=4,\n c=self.colors[self.clr_ctr],\n label=self.animal_names[self.clr_ctr])\n\n # \n ax2.plot(t, np.poly1d(np.polyfit(t, auc2, 1))(t),\n 'r--', linewidth=4,\n c=self.colors[self.clr_ctr])\n\n self.clr_ctr+=1\n \n ax1.set_xlim(0,1)\n ax2.set_xlim(0,1)\n #ax1.set_ylim(9,13)\n #ax2.set_ylim(9,13)\n ax1.set_title(\"All\")\n ax2.set_title(\"Lockout\")\n ax1.set_xlabel(\"Duration of study\")\n ax2.set_xlabel(\"Duration of study\")\n plt.suptitle(\"AUC fits to SVM decision prediction\", fontsize=20)\n ax1.legend(fontsize=20)\n\n\n def plot_decision_time(self, clr, label, ax=None):\n \n #\n if ax is None:\n ax=plt.subplot(111)\n \n #\n t = np.arange(-9.5, 0.5, 1)\n \n #\n print (self.data.shape)\n \n temp = []\n for k in range(self.data.shape[1]):\n temp.append(self.data[:,k,k])\n temp=np.array(temp)\n \n #\n mean = temp.mean(1)\n std = np.std(temp,axis=1)\n plt.plot(t, mean,\n c=clr,\n label = label,\n linewidth=4)\n plt.fill_between(t, mean-std, mean+std, color=clr, alpha = 0.1)\n \n plt.legend(fontsize=16)\n self.format_plot2(ax)\n\n \n \n def plot_decision_time_animal(self, animal_name): \n \n # select dataset and # of recordings \n t = np.arange(-9.5, 0.5, 1)\n idx=self.animal_names.index(animal_name)\n \n colors = plt.cm.magma(np.linspace(0,1,self.n_colors[idx]))\n\n \n root_dir = self.main_dir+animal_name+'/'\n fnames = np.sort(glob2.glob(root_dir+'conf_10_'+animal_name+\"*\"))\n\n # \n traces1 = []\n traces2 = []\n for fname in fnames:\n if 'lockout' not in fname:\n self.load_data(fname)\n temp = []\n for k in range(self.data.shape[1]):\n temp.append(self.data[:,k,k])\n traces1.append(temp)\n\n # load lockout version\n idx = fname.find('conf_10_'+animal_name)\n fname2 = fname[:idx+11]+\"_lockout\"+fname[idx+11:]\n self.load_data(fname2)\n temp = []\n for k in range(self.data.shape[1]):\n temp.append(self.data[:,k,k])\n traces2.append(temp)\n \n traces1=np.array(traces1)\n traces2=np.array(traces2)\n #print (traces1.shape)\n #\n ax1=plt.subplot(1,2,1)\n ax1.set_title(\"all\")\n for k in range(traces1.shape[0]):\n mean=traces1[k].mean(1)\n #print (mean.shape)\n ax1.plot(t, mean,\n c=colors[k],\n linewidth=4)\n\n self.format_plot2(ax1)\n\n # \n ax2=plt.subplot(1,2,2)\n ax2.set_title(\"lockout\")\n for k in range(traces2.shape[0]):\n mean=traces2[k].mean(1)\n #print (mean.shape)\n ax2.plot(t, mean,\n c=colors[k],\n linewidth=4)\n self.format_plot2(ax2)\n \n plt.suptitle(animal_name)\n\n \n def plot_decision_time_animal_matrix(self, animal_name): \n \n # \n root_dir = self.main_dir+animal_name+'/'\n fnames = np.sort(glob2.glob(root_dir+'conf_10_'+animal_name+\"*\"))\n\n # \n traces1 = []\n traces2 = []\n for fname in fnames:\n if 'lockout' not in fname:\n self.load_data(fname)\n temp = []\n for k in range(self.data.shape[1]):\n temp.append(self.data[:,k,k].mean(0))\n traces1.append(temp)\n\n # load lockout version\n idx = fname.find('conf_10_'+animal_name)\n fname2 = fname[:idx+11]+\"_lockout\"+fname[idx+11:]\n self.load_data(fname2)\n temp = []\n for k in range(self.data.shape[1]):\n temp.append(self.data[:,k,k].mean(0))\n traces2.append(temp)\n \n traces1=np.array(traces1)\n traces2=np.array(traces2)\n print (traces1.shape)\n #\n ax1=plt.subplot(1,4,1)\n ax1.set_title(\"all\")\n ax1.imshow(traces1,vmin=0,vmax=1.0)\n\n # \n ax2=plt.subplot(1,4,2)\n ax2.set_title(\"lockout\")\n ax2.imshow(traces2,vmin=0,vmax=1.0)\n plt.suptitle(animal_name)\n\n #\n ax2=plt.subplot(1,4,3)\n ax2.set_title(\"all - lockout\")\n ax2.imshow(traces1-traces2,vmin=0,vmax=.25)\n plt.suptitle(animal_name)\n \n #\n ax2=plt.subplot(1,4,4)\n ax2.set_title(\"lockout - all\")\n ax2.imshow(traces2-traces1,vmin=0,vmax=.25)\n plt.suptitle(animal_name) \n\n def plot_decision_time_all_matrix(self):\n \n \n vmin = 0\n vmax = 0.75\n axes=[]\n fig=plt.figure()\n for a in range(6):\n axes.append(plt.subplot(2,3,a+1))\n # \n root_dir = self.main_dir+self.animal_names[a]+'/'\n fnames = np.sort(glob2.glob(root_dir+'conf_10_'+self.animal_names[a]+\"*\"))\n\n # \n traces1 = []\n for fname in fnames:\n if 'lockout' not in fname:\n self.load_data(fname)\n temp = []\n for k in range(self.data.shape[1]):\n temp.append(self.data[:,k,k].mean(0))\n if self.filter:\n temp = self.filter_trace(temp)\n traces1.append(temp)\n\n traces1=np.array(traces1)\n axes[a].set_title(self.animal_names[a])\n im = axes[a].imshow(traces1,vmin=vmin,vmax=vmax)\n \n plt.xticks(np.arange(0,traces1.shape[1],2),\n np.arange(-9.5,0,2))\n plt.ylabel(\"Study day\")\n \n ticks = np.linspace(vmin,vmax,4)\n cbar = fig.colorbar(im, ax=axes[5], \n ticks=ticks)\n #cbar.ax.tick_params(labelsize=16) \n #cbar.ax.set_title('Pval', rotation=0,\n # fontsize=16)\n \n\n def filter_trace(self,trace,width=1):\n\n box = np.ones(width)/width\n trace_smooth = np.convolve(trace, box, mode='same')\n\n return trace_smooth\n \n# LEVER PULL\nvis = Visualize()\n\n# lever-related data\nvis.main_dir = '/media/cat/1TB/yuki/yongxu/lever pull/'\n \n#############################################\n############## DECISION TYPE ################\n#############################################\nanimal_id = 'AQ2'\nsession = 10\nfname = vis.main_dir+'/'+animal_id+'/SVM_scores_'+animal_id+'_'+str(session)+'.npy'\n\n# vis.load_data(fname)\n# vis.plot_decision_choice('red','all')\n\n# fname = vis.main_dir+'/'+animal_id+'/SVM_scores_'+animal_id+'_lockout_'+str(session)+'.npy'\n# vis.load_data(fname)\n# vis.plot_decision_choice('blue','lockout')\n\n# # #\n# vis.load_data(fname)\n# vis.plot_significant('red','all',animal_id, session)\n \n# #\n# vis.plot_animal_decision_longitudinal('IA3')\n\n# \n# vis.plot_animal_decision_AUC_longitudinal()\n\n# # # # \nlockout=False\nfor ctr, name in enumerate(vis.animal_names):\n ax=plt.subplot(2,3,ctr+1)\n vis.plot_animal_decision_longitudinal_matrix(name, lockout, ax)\n \n\n#############################################\n############## DECISION TIME ################\n#############################################\n\n#\n#?vis.main_dir = '/media/cat/1TB/yuki/yongxu/lever pull/'\n\n# fname = '/media/cat/1TB/yuki/yongxu/lever pull/IA1/conf_10_IA1_0.npy'\n# vis.load_data(fname)\n# vis.plot_decision_time('red','all')\n\n# animal_name = \"AQ2\"\n# vis.plot_decision_time_animal(animal_name)\n\n# animal_name = 'AQ2'\n# vis.plot_decision_time_animal_matrix(animal_name)\n\n# # \n# vis.filter=False\n# vis.plot_decision_time_all_matrix()\n\n\n\n#############################################\n############## BODY MOVEMENTS ###############\n#############################################\n\n# body movement related data\nvis.main_dir = '/media/cat/1TB/yuki/yongxu/body movement/'\n\n# # \n# body_part = 'right_paw'\n# fname = vis.main_dir+'/SVM_scores_'+body_part+'_1.npy'\n# vis.load_data(fname)\n# vis.plot_decision_choice('red','1', body_part)\n\n# fname = vis.main_dir+'/SVM_scores_'+body_part+'_2.npy'\n# vis.load_data(fname)\n# vis.plot_decision_choice('blue','2', body_part)\n\n# # \n# fname = vis.main_dir+'/conf_10_left_paw.npy'\n# vis.load_data(fname)\n# vis.plot_decision_time('red','left')\n\n# fname = vis.main_dir+'/conf_10_right_paw.npy'\n# vis.load_data(fname)\n# vis.plot_decision_time('blue','right')\n\n# fname = vis.main_dir+'/conf_10_tongue.npy'\n# vis.load_data(fname)\n# vis.plot_decision_time('green','tongue')\n\n\n\n", "_____no_output_____" ], [ "#############################################\n############## DECISION TIME ################\n#############################################\nTO DO\n- 1tail test + Yongxu to provide empoirical distributions\n- AUC: use >0.5% also stat significant points\n - Also maybe only look at time <0.0\n- dataset-non midline filtered ??\n\n\nRNNs\n- \n", "8.0\n" ], [ "# \n", "(10, 101, 128, 128)\n" ], [ "from sklearn.decomposition import PCA\n\ndef pca_denoise(X):\n\n # reshape for PCA\n X = X.reshape(X.shape[0]*X.shape[1], X.shape[2]*X.shape[3])\n \n pca = PCA()\n pca.fit(X)\n \n mu = np.mean(X, axis=0)\n\n nComp =100\n Xnew = np.dot(pca.transform(X)[:,:nComp], pca.components_[:nComp,:])\n Xnew += mu\n\n X_deshaped = Xnew.reshape(X.shape[0],X.shape[1], X.shape[2],X.shape[3])\n \n return X_deshaped\n\n\nX = np.random.rand(10,101,128,128)\nX_denoised = pca_denoise(X_2D)\n", "_____no_output_____" ], [ "# # grab stm data\n# X = np.random.rand(10,101,128,128)\n# print (X.shape)\n\n# # reshape for PCA\n# X_2D = X.reshape(X.shape[0]*X.shape[1], X.shape[2]*X.shape[3])\n# print (X_2D.shape)\n\n# # Run pca\n# print (\"DATA IN: \", X_2D.shape)\n# X_denoised = pca_denoise(X_2D)\n# print (\"DATA OUT: \", X_denoised.shape)\n\n# X_deshaped = X_denoised.reshape(X.shape[0],X.shape[1], X.shape[2],X.shape[3])\n# print (\"Final data: \", X_deshaped.shape)", "(10, 101, 128, 128)\n(1010, 16384)\nDATA IN: (1010, 16384)\nDATA OUT: (1010, 16384)\nFinal data: (10, 101, 128, 128)\n" ], [ "import torch\nfrom torch import nn\nfrom torch.autograd import Variable\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")", "_____no_output_____" ], [ "\n# \nX = np.random.rand(10,101,128,128)\ndata_in = data_in.reshape(X.shape[0]*X.shape[1],X.shape[2]*X.shape[3])\nprint (\" Data going into GPU SVD: \", data_in.shape)\n\n# move data to device\na = torch.from_numpy(np.float32(data_in)).float().to(device)\nprint (\"Input array size: \", a.shape)\nprint (\"...starting GPU-svd\")\nu, s, v = torch.svd(a)\n\nprint (\"u: \", u.shape)\nprint (\"s: \", s.shape)\nprint (\"v: \", v.shape)\n\n# scale temporal component by singular vals\n\ntorch.save(v,root_dir+'v_gpu.pt')\ntorch.save(s,root_dir+'s_gpu.pt')\ntorch.save(u,root_dir+'u_gpu.pt')\n\nv = v.cpu().data.numpy()\ns = s.cpu().data.numpy()\nu = u.cpu().data.numpy()\n\nnp.save(root_dir+'v.npy',v)\nnp.save(root_dir+'s.npy',s)\nnp.save(root_dir+'u.npy',u)\n\nVs = (v*s).transpose(1,0).reshape(-1,128,128)\nnp.save(root_dir+'Vs.npy',Vs)\n\n\nprint (\"Vs: \", Vs.shape)\nprint (\"u: \", u.shape)\nprint (\"DONE\")\n\n\n# Data in: (39050, 128, 128)\n# Data going into GPU SVD: (39050, 16384)\n# Input array size: torch.Size([39050, 16384])\n# ...starting GPU-svd\n# u: torch.Size([39050, 16384])\n# s: torch.Size([16384])\n# v: torch.Size([16384, 16384])\n# Vs: (16384, 128, 128)\n# u: (39050, 16384)\n# DONE", " Data going into GPU SVD: (1010, 16384)\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb24f199a4cb5980c98dd094848dde5598b7475c
7,928
ipynb
Jupyter Notebook
Textbook/Introduction.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
d580a8e27ba937fc8401ac6d0714b6488ac8bbb6
[ "MIT" ]
null
null
null
Textbook/Introduction.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
d580a8e27ba937fc8401ac6d0714b6488ac8bbb6
[ "MIT" ]
null
null
null
Textbook/Introduction.ipynb
hunterluepke/Learn-Python-for-Stats-and-Econ
d580a8e27ba937fc8401ac6d0714b6488ac8bbb6
[ "MIT" ]
null
null
null
82.583333
1,183
0.734107
[ [ [ "# Learn Python for Economic Computation: A Crash Course\n\nhttps://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ\n\n> James Caton\n>\n> [email protected]\n>\n> Cameron Harwick\n>\n> [email protected]\n\n### Table of Contents\n\n\n[Introduction](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Introduction.ipynb)\n\n[Chapter 1: The Essentials](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%201%20-%20The%20Essentials.ipynb)\n\n[Chapter 2: Working with Lists](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%202%20-%20Working%20With%20Lists.ipynb)\n\n[Chapter 3: Building Functions](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%203%20-%20Building%20Functions.ipynb)\n\n[Chapter 4: Classes and Methods](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%204%20-%20Classes%20and%20Methods.ipynb)\n\n[Chapter 5: Introduction to numpy, pandas, and matplotlib](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%205%20-%20Introduction%20to%20numpy%2C%20pandas%2C%20and%20matplotlib.ipynb)\n\n[Chapter 6: Importing, Cleaning, and Analyzing Data](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%206%20-%20Importing%2C%20Cleaning%2C%20and%20Analyzing%20Data.ipynb)\n\n[Chapter 7: Building an OLS Regression Model](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%207%20-%20Building%20an%20OLS%20Regression%20Model.ipynb)\n\n[Chapter 8: Advanced Data Analysis](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ/blob/master/Textbook/Chapter%208%20-%20Advanced%20Data%20Analysis.ipynb)\n\n\n## Introduction: Learn Python for Economic Computation\n\nMore than ever, programming skills are essential for professional success. This is true whether your work is in business or in academia. Further, programming is often not enough. You must also be able to work with statistical software or libraries. While many books exist to teach you how to program, there are none that I know of that do a good job of providing training in statistic and econometrics while also providing good programming habits.\n\n## The Beginning\n\nIn learning to program, it is good to have a strong grasp of the fundamental pieces of programming before moving on to complex structures. Many will learn to use moduels - libraries - without understanding the fundamentals of Python. For those like ourselves who use Python for a variety of tasks - especially agent-based modeling and data processing and visualization - it is useful to incur the upfront cost of learning the prgoramming fundamentals. Not long after Jim first began learning to program in Python, he was benefited by Cameron who was already familiar with programming syntax and who also wanted to learn the language. We explored Python with small projects, both of us growing comfortable with the language. The building blocks we learned in the process will be used to help you grow comfortable with Python as well. This book is the fruit of our own development.\n\nThe aim of this book is to quickly provide the skills necessary to use python for the purpose of economic computation. The book is constructed for those who are just learning Python. Each example in the text and each problem at the end of every chapter will help you develop programming fluency. You will learn by doing. Even if you do not feel like you understand the programs that you build, it is important for you to _reconstruct every script_ presented in the book. As you build programs, we encourage you to consider different means by which you could create a similar program and also to consider how you might develop the script. \n\nYou will learn how to work with objects and functions that are essential to data management and statistical programming. These include working with basic math functions, lists, dictionaries, tuples, if-statements, \"for-loops\", classes, and reading and writing files in Python. As we develop understanding of the core interface, we will also build a statistical packages.\n\nFirst, you will learn how to install Python quickly and easily. \n\n### Why Python?\n\nYou may wonder why you should learn Python as compared to R or MATLAB. Although R and MATLAB are both powerful, they are not well-suited for general purpose programming in the way that Java or C++ are. Python does meet this criterion. Python is intuitive, not differing as much as R from the syntax and structure of traditional programming languages. If you learn Python for data analysis, you will also have a head-start on programming for other purposes like web design, natural language processing, graphical user interfaces, and so on. By the time you finish this book, you will be well prepared to develop a practice that includes a broad set of applications.\n\n### Installation\n\nIn this book, we will use Python 3. All examples will be generated from Spyder, the Integrated Development Environment provided in Anaconda. Download the Anaconda package at:\n\n> https://www.anaconda.com/distribution/#download-section\n\nDownload the latest installer for Python 3. If you know your system is 64-bit, choose the 64-bit installer. Otherwise, choose the 32-bit installer. **If you have not installed Python on your system before, check the option “Add Anaconda to the system Path environment variable.** This option is “Not recommended” by the installation as it gives Anaconda preference over previously installed software. For our purposes, this should not be a problem. Once you have completed the installation, if you would like to install any package, open the command line (in Windows this is PowerShell) and type conda install package-name where package-name is replaced with the package you wish to install. For example, you can install numpy with conda install numpy. If a package is not available in Anaconda, you can install it using pip install package-name. The latest version of Anaconda will recognize a library installed in this manner. It is sometimes possible to install unofficial releases of packages with Anaconda, but this will not be necessary for the material covered. Unless otherwise specified, the packages we will be using are included in with the Anaconda installation.\n\nWhen you are ready to build your first program, open Spyder. You can find it by using the search function for your operating system. I recommend that you place it somewhere on your desktop or pin it to your taskbar.\n\nPython Scripts\nAs you follow along with the book, you may prefer to view the .py scripts in your text editor. All scripts can be found at [the github](https://github.com/jlcatonjr/Learn-Python-for-Stats-and-Econ) for this book.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
cb24fb54e126cd8edc3582ad0a902c8977be24b9
1,234
ipynb
Jupyter Notebook
hacker-rank/Python/Collections/DefaultDict.ipynb
izan-majeed/archives
89af2a24f4a6f07bda8ee38d99ae8667d42727f4
[ "Apache-2.0" ]
null
null
null
hacker-rank/Python/Collections/DefaultDict.ipynb
izan-majeed/archives
89af2a24f4a6f07bda8ee38d99ae8667d42727f4
[ "Apache-2.0" ]
null
null
null
hacker-rank/Python/Collections/DefaultDict.ipynb
izan-majeed/archives
89af2a24f4a6f07bda8ee38d99ae8667d42727f4
[ "Apache-2.0" ]
null
null
null
20.915254
71
0.5
[ [ [ "#When the list class is passed as the default_factory argument\n#then a defaultdict is created with the values that are list\n\nfrom collections import defaultdict\n\nn, m = map(int, input().split())\nA = defaultdict(list)\n\nfor i in range(n):\n A[input()].append(i+1)\n\nB = [input() for _ in range(m)]\n\nfor i in B:\n if i in A.keys():\n print (\" \".join(map(str,A[i])))\n else:\n print(-1)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
cb25017f6bdf46922def69b8eb0a11f3748f69a1
141,582
ipynb
Jupyter Notebook
JumptoPython/Part_7_Regular Expression(Regex)/07-2_Regular_Expressions_Start.ipynb
dongrami0425/Python_OpenCV-Study
c7faee4f63720659280c3222ba5abfe27740d1f4
[ "MIT" ]
null
null
null
JumptoPython/Part_7_Regular Expression(Regex)/07-2_Regular_Expressions_Start.ipynb
dongrami0425/Python_OpenCV-Study
c7faee4f63720659280c3222ba5abfe27740d1f4
[ "MIT" ]
null
null
null
JumptoPython/Part_7_Regular Expression(Regex)/07-2_Regular_Expressions_Start.ipynb
dongrami0425/Python_OpenCV-Study
c7faee4f63720659280c3222ba5abfe27740d1f4
[ "MIT" ]
null
null
null
80.857796
26,484
0.843264
[ [ [ "# 정규 표현식 시작하기", "_____no_output_____" ], [ "## 정규 표현식의 기초, 메타 문자\n\n정규 표현식에서 사용하는 메타 문자(meta characters)에는 다음과 같은 것이 있다. \n\n※ 메타 문자란 원래 그 문자가 가진 뜻이 아닌 특별한 용도로 사용하는 문자를 말한다. \n\n - 사용하는 메타 문자: \n . ^ $ * + ? { } [ ] \\ | ( ) \n\n정규 표현식에 위 메타 문자를 사용하면 특별한 의미를 갖게 된다. \n\n자, 그러면 가장 간단한 정규 표현식부터 시작해 각 메타 문자의 의미와 사용법을 알아보자. ", "_____no_output_____" ], [ "## 문자 클래스 [ ]\n\n우리가 가장 먼저 살펴볼 메타 문자는 바로 문자 클래스(character class)인 [ ]이다. 문자 클래스로 만들어진 정규식은 \"[ ] 사이의 문자들과 매치\"라는 의미를 갖는다. \n\n\n>※ 문자 클래스를 만드는 메타 문자인 [ ] 사이에는 어떤 문자도 들어갈 수 있다. \n\n\n즉 정규 표현식이 [abc]라면 이 표현식의 의미는 \"a, b, c 중 한 개의 문자와 매치\"를 뜻한다. 이해를 돕기 위해 문자열 \"a\", \"before\", \"dude\"가 정규식 [abc]와 어떻게 매치되는지 살펴보자. \n\n>- \"a\"는 정규식과 일치하는 문자인 \"a\"가 있으므로 매치 \n>- \"before\"는 정규식과 일치하는 문자인 \"b\"가 있으므로 매치 \n>- \"dude\"는 정규식과 일치하는 문자인 a, b, c 중 어느 하나도 포함하고 있지 않으므로 매치되지 않음 \n\n[ ] 안의 두 문자 사이에 하이픈(-)을 사용하면 두 문자 사이의 범위(From - To)를 의미한다. 예를 들어 [a-c]라는 정규 표현식은 [abc]와 동일하고 [0-5]는 [012345]와 동일하다. \n\n다음은 하이픈(-)을 사용한 문자 클래스의 사용 예이다. \n\n>- [a-zA-Z] : 알파벳 모두 \n>- [0-9] : 숫자 \n \n문자 클래스([ ]) 안에는 어떤 문자나 메타 문자도 사용할수 있지만 주의해야 할 메타 문자가 1가지 있다. 그것은 바로 ^인데, 문자 클래스 안에 ^ 메타 문자를 사용할 경우에는 반대(not)라는 의미를 갖는다. 예를 들어 [^0-9]라는 정규 표현식은 숫자가 아닌 문자만 매치된다. ", "_____no_output_____" ], [ "### [자주 사용하는 문자 클래스]\n\n[0-9] 또는 [a-zA-Z] 등은 무척 자주 사용하는 정규 표현식이다. 이렇게 자주 사용하는 정규식은 별도의 표기법으로 표현할 수 있다. 다음을 기억해 두자.\n\n>- \\d - 숫자와 매치, [0-9]와 동일한 표현식이다.\n\n>- \\D - 숫자가 아닌 것과 매치, [^0-9]와 동일한 표현식이다.\n\n>- \\s - whitespace 문자와 매치, [ \\t\\n\\r\\f\\v]와 동일한 표현식이다. 맨 앞의 빈 칸은 공백문자(space)를 의미한다.\n\n>- \\S - whitespace 문자가 아닌 것과 매치, [^ \\t\\n\\r\\f\\v]와 동일한 표현식이다.\n\n>- \\w - 문자+숫자(alphanumeric)와 매치, [a-zA-Z0-9_]와 동일한 표현식이다.\n\n>- \\W - 문자+숫자(alphanumeric)가 아닌 문자와 매치, [^a-zA-Z0-9_]와 동일한 표현식이다.\n\n\n대문자로 사용된 것은 소문자의 반대임을 추측할 수 있다.", "_____no_output_____" ], [ "## Dot(.)\n정규 표현식의 Dot(.) 메타 문자는 줄바꿈 문자인 \\n을 제외한 모든 문자와 매치됨을 의미한다.\n\n>※ 나중에 배우겠지만 정규식을 작성할 때 re.DOTALL 옵션을 주면 \\n 문자와도 매치된다.\n\n다음 정규식을 보자.\n\n>a.b\n\n위 정규식의 의미는 다음과 같다.\n\n>\"a + 모든문자 + b\"\n\n즉 a와 b라는 문자 사이에 어떤 문자가 들어가도 모두 매치된다는 의미이다.\n\n이해를 돕기 위해 문자열 \"aab\", \"a0b\", \"abc\"가 정규식 a.b와 어떻게 매치되는지 살펴보자.\n\n>- -\"aab\"는 가운데 문자 \"a\"가 모든 문자를 의미하는 .과 일치하므로 정규식과 매치된다.\n>- \"a0b\"는 가운데 문자 \"0\"가 모든 문자를 의미하는 .과 일치하므로 정규식과 매치된다.\n>- \"abc\"는 \"a\"문자와 \"b\"문자 사이에 어떤 문자라도 하나는있어야 하는 이 정규식과 일치하지 않으므로 매치되지 않는다.\n\n다음 정규식을 보자.\n\n>a[.]b\n\n이 정규식의 의미는 다음과 같다.\n\n>\"a + Dot(.)문자 + b\"\n\n따라서 정규식 a[.]b는 \"a.b\" 문자열과 매치되고, \"a0b\" 문자열과는 매치되지 않는다.\n\n※ 만약 앞에서 살펴본 문자 클래스([]) 내에 Dot(.) 메타 문자가 사용된다면 이것은 \"모든 문자\"라는 의미가 아닌 문자 . 그대로를 의미한다. 혼동하지 않도록 주의하자.", "_____no_output_____" ], [ "## 반복 (*)\n다음 정규식을 보자.\n\n> ca*t\n\n이 정규식에는 반복을 의미하는 * 메타 문자가 사용되었다. 여기에서 사용한 *은 * 바로 앞에 있는 문자 a가 0부터 무한대로 반복될 수 있다는 의미이다.\n\n※ 여기에서 * 메타 문자의 반복 개수가 무한대라고 표현했는데 사실 메모리 제한으로 2억 개 정도만 가능하다고 한다.\n\n즉 다음과 같은 문자열이 모두 매치된다.\n\n![image.png](attachment:image.png)", "_____no_output_____" ], [ "## 반복 (+)\n반복을 나타내는 또 다른 메타 문자로 +가 있다. +는 최소 1번 이상 반복될 때 사용한다. 즉 *가 반복 횟수 0부터라면 +는 반복 횟수 1부터인 것이다.\n\n다음 정규식을 보자.\n\n>ca+t\n\n위 정규식의 의미는 다음과 같다.\n\n>\"c + a(1번 이상 반복) + t\"\n\n위 정규식에 대한 매치여부는 다음 표와 같다.\n\n![image.png](attachment:image.png)", "_____no_output_____" ], [ "## 반복 ({m,n}, ?)\n여기에서 잠깐 생각해 볼 게 있다. 반복 횟수를 3회만 또는 1회부터 3회까지만으로 제한하고 싶을 수도 있지 않을까?\n\n{ } 메타 문자를 사용하면 반복 횟수를 고정할 수 있다. {m, n} 정규식을 사용하면 반복 횟수가 m부터 n까지 매치할 수 있다. 또한 m 또는 n을 생략할 수도 있다. 만약 {3,}처럼 사용하면 반복 횟수가 3 이상인 경우이고 {,3}처럼 사용하면 반복 횟수가 3 이하를 의미한다. 생략된 m은 0과 동일하며, 생략된 n은 무한대(2억 개 미만)의 의미를 갖는다.\n\n※ {1,}은 +와 동일하고, {0,}은 *와 동일하다.\n\n{ }을 사용한 몇 가지 정규식을 살펴보자.\n\n### {m}\n\n>ca{2}t\n\n위 정규식의 의미는 다음과 같다.\n\n>\"c + a(반드시 2번 반복) + t\"\n\n위 정규식에 대한 매치여부는 다음 표와 같다.\n\n![image.png](attachment:image.png)\n\n### {m, n}\n\n>ca{2,5}t\n\n위 정규식의 의미는 다음과 같다:\n\n>\"c + a(2~5회 반복) + t\"\n\n위 정규식에 대한 매치여부는 다음 표와 같다.\n![image.png](attachment:image.png)", "_____no_output_____" ], [ "### ?\n\n반복은 아니지만 이와 비슷한 개념으로 ? 이 있다. ? 메타문자가 의미하는 것은 {0, 1} 이다.\n\n다음 정규식을 보자.\n\nab?c\n위 정규식의 의미는 다음과 같다:\n\n\"a + b(있어도 되고 없어도 된다) + c\"\n\n위 정규식에 대한 매치여부는 다음 표와 같다.\n\n![image.png](attachment:image.png)\n\n즉 b 문자가 있거나 없거나 둘 다 매치되는 경우이다.\n\n*, +, ? 메타 문자는 모두 {m, n} 형태로 고쳐 쓰는 것이 가능하지만 가급적 이해하기 쉽고 표현도 간결한 *, +, ? 메타 문자를 사용하는 것이 좋다.\n\n지금까지 아주 기초적인 정규 표현식에 대해서 알아보았다. 알아야 할 것들이 아직 많이 남아 있지만 그에 앞에서 파이썬으로 이러한 정규 표현식을 어떻게 사용할 수 있는지 먼저 알아보기로 하자.", "_____no_output_____" ], [ "## 파이썬에서 정규 표현식을 지원하는 re 모듈\n\n파이썬은 정규 표현식을 지원하기 위해 re(regular expression의 약어) 모듈을 제공한다. re 모듈은 파이썬을 설치할 때 자동으로 설치되는 기본 라이브러리로 사용 방법은 다음과 같다.\n\n> import re \n> p = re.compile('ab*') \n\nre.compile을 사용하여 정규 표현식(위 예에서는 ab*)을 컴파일한다. re.compile의 결과로 돌려주는 객체 p(컴파일된 패턴 객체)를 사용하여 그 이후의 작업을 수행할 것이다.\n\n※ 정규식을 컴파일할 때 특정 옵션을 주는 것도 가능한데, 이에 대해서는 뒤에서 자세히 살펴본다. \n※ 패턴이란 정규식을 컴파일한 결과이다.", "_____no_output_____" ] ], [ [ "import re", "_____no_output_____" ], [ "p=re.compile('ab*')", "_____no_output_____" ], [ "m=p.match('abbbb') # 해당 함수는 바로 다음내용에 설명.", "_____no_output_____" ], [ "print(m) # 매치됨.", "<_sre.SRE_Match object; span=(0, 5), match='abbbb'>\n" ] ], [ [ "## 정규식을 이용한 문자열 검색\n이제 컴파일된 패턴 객체를 사용하여 문자열 검색을 수행해 보자. 컴파일된 패턴 객체는 다음과 같은 4가지 메서드를 제공한다. \n\n![image.png](attachment:image.png)\n\nmatch, search는 정규식과 매치될 때는 match 객체를 돌려주고, 매치되지 않을 때는 None을 돌려준다. 이들 메서드에 대한 간단한 예를 살펴보자.\n\n※ match 객체란 정규식의 검색 결과로 돌려주는 객체이다.\n\n우선 다음과 같은 패턴을 만들어 보자.\n\n> import re \n> p = re.compile('[a-z]+') ", "_____no_output_____" ], [ "### match\nmatch 메서드는 문자열의 처음부터 정규식과 매치되는지 조사한다. 위 패턴에 match 메서드를 수행해 보자.", "_____no_output_____" ] ], [ [ "import re", "_____no_output_____" ], [ "p=re.compile('[a-z]+')", "_____no_output_____" ], [ "m=p.match('python')", "_____no_output_____" ], [ "print(m)", "<_sre.SRE_Match object; span=(0, 6), match='python'>\n" ] ], [ [ "\"python\" 문자열은 [a-z]+ 정규식에 부합되므로 match 객체를 돌려준다.\n\n", "_____no_output_____" ] ], [ [ "m=p.match('3 python')", "_____no_output_____" ], [ "print(m)", "None\n" ] ], [ [ "\"3 python\" 문자열은 처음에 나오는 문자 3이 정규식 [a-z]+에 부합되지 않으므로 None을 돌려준다.\n\nmatch의 결과로 match 객체 또는 None을 돌려주기 때문에 파이썬 정규식 프로그램은 보통 다음과 같은 흐름으로 작성한다.\n", "_____no_output_____" ] ], [ [ "p = re.compile('[a-z]+')\nm = p.match( 'string goes here' )", "_____no_output_____" ], [ "if m: # 객체에 아무 내용이 없는 none이면 false\n print('Match found: ', m.group())\nelse:\n print('No match')", "Match found: string\n" ] ], [ [ "즉 match의 결괏값이 있을 때만 그다음 작업을 수행하겠다는 것이다.\n\n", "_____no_output_____" ], [ "### search\n컴파일된 패턴 객체 p를 가지고 이번에는 search 메서드를 수행해 보자.", "_____no_output_____" ] ], [ [ "m=p.search(\"python\")", "_____no_output_____" ], [ "print(m)", "<_sre.SRE_Match object; span=(0, 6), match='python'>\n" ] ], [ [ "\"python\" 문자열에 search 메서드를 수행하면 match 메서드를 수행했을 때와 동일하게 매치된다.", "_____no_output_____" ] ], [ [ "m=p.search(\"3 python\")", "_____no_output_____" ], [ "print(m)", "<_sre.SRE_Match object; span=(2, 8), match='python'>\n" ] ], [ [ "\"3 python\" 문자열의 첫 번째 문자는 \"3\"이지만 search는 문자열의 처음부터 검색하는 것이 아니라 문자열 전체를 검색하기 때문에 \"3 \" 이후의 \"python\" 문자열과 매치된다.\n\n이렇듯 match 메서드와 search 메서드는 문자열의 처음부터 검색할지의 여부에 따라 다르게 사용해야 한다.", "_____no_output_____" ], [ "### findall\n\n이번에는 findall 메서드를 수행해 보자.\n\n", "_____no_output_____" ] ], [ [ "result=p.findall(\"life is too shor\")", "_____no_output_____" ], [ "print(result)", "['life', 'is', 'too', 'shor']\n" ] ], [ [ "\"life is too short\" 문자열의 'life', 'is', 'too', 'short' 단어를 각각 [a-z]+ 정규식과 매치해서 리스트로 돌려준다.", "_____no_output_____" ], [ "### finditer\n이번에는 finditer 메서드를 수행해 보자.", "_____no_output_____" ] ], [ [ "result=p.finditer(\"life is too short\")", "_____no_output_____" ], [ "print(result)", "<callable_iterator object at 0x000001B9DAF652B0>\n" ], [ "for r in result : print(r)", "<_sre.SRE_Match object; span=(0, 4), match='life'>\n<_sre.SRE_Match object; span=(5, 7), match='is'>\n<_sre.SRE_Match object; span=(8, 11), match='too'>\n<_sre.SRE_Match object; span=(12, 17), match='short'>\n" ] ], [ [ "finditer는 findall과 동일하지만 그 결과로 반복 가능한 객체(iterator object)를 돌려준다. 반복 가능한 객체가 포함하는 각각의 요소는 match 객체이다.", "_____no_output_____" ], [ "## match 객체의 메서드\n\n자, 이제 match 메서드와 search 메서드를 수행한 결과로 돌려준 match 객체에 대해 알아보자. 앞에서 정규식을 사용한 문자열 검색을 수행하면서 아마도 다음과 같은 궁금증이 생겼을 것이다. \n \n- 어떤 문자열이 매치되었는가? \n- 매치된 문자열의 인덱스는 어디서부터 어디까지인가? \n\nmatch 객체의 메서드를 사용하면 이 같은 궁금증을 해결할 수 있다. 다음 표를 보자. \n\nmethod\t목적 \ngroup()\t매치된 문자열을 돌려준다. \nstart()\t매치된 문자열의 시작 위치를 돌려준다. \nend()\t매치된 문자열의 끝 위치를 돌려준다. \nspan()\t매치된 문자열의 (시작, 끝)에 해당하는 튜플을 돌려준다. \n\n다음 예로 확인해 보자. \n\n", "_____no_output_____" ] ], [ [ "m=p.match(\"python\")", "_____no_output_____" ], [ "m.group()", "_____no_output_____" ], [ "m.start()", "_____no_output_____" ], [ "m.end()", "_____no_output_____" ], [ "m.span()", "_____no_output_____" ] ], [ [ "예상한 대로 결괏값이 출력되는 것을 확인할 수 있다. match 메서드를 수행한 결과로 돌려준 match 객체의 start()의 결괏값은 항상 0일 수밖에 없다. 왜냐하면 match 메서드는 항상 문자열의 시작부터 조사하기 때문이다.\n\n만약 search 메서드를 사용했다면 start() 값은 다음과 같이 다르게 나올 것이다.", "_____no_output_____" ] ], [ [ "m=p.search('3 python')", "_____no_output_____" ], [ "m.group()", "_____no_output_____" ], [ "m.start()", "_____no_output_____" ], [ "m.end()", "_____no_output_____" ], [ "m.span()", "_____no_output_____" ] ], [ [ "[모듈 단위로 수행하기]\n\n지금까지 우리는 re.compile을 사용하여 컴파일된 패턴 객체로 그 이후의 작업을 수행했다. re 모듈은 이것을 좀 축약한 형태로 사용할 수 있는 방법을 제공한다. 다음 예를 보자.", "_____no_output_____" ] ], [ [ "p=re.compile('[a-z]+')", "_____no_output_____" ], [ "m=p.match(\"python\")", "_____no_output_____" ] ], [ [ "위 코드가 축약된 형태는 다음과 같다.\n\n", "_____no_output_____" ] ], [ [ "m=re.match(\"[a-z]+\", \"python\")", "_____no_output_____" ], [ "m.start()", "_____no_output_____" ] ], [ [ "위 예처럼 사용하면 컴파일과 match 메서드를 한 번에 수행할 수 있다. 보통 한 번 만든 패턴 객체를 여러번 사용해야 할 때는 이 방법보다 re.compile을 사용하는 것이 편하다.", "_____no_output_____" ], [ "## 컴파일 옵션\n\n정규식을 컴파일할 때 다음 옵션을 사용할 수 있다.\n\n- DOTALL(S) - . 이 줄바꿈 문자를 포함하여 모든 문자와 매치할 수 있도록 한다.\n- IGNORECASE(I) - 대소문자에 관계없이 매치할 수 있도록 한다.\n- MULTILINE(M) - 여러줄과 매치할 수 있도록 한다. (^, $ 메타문자의 사용과 관계가 있는 옵션이다)\n- VERBOSE(X) - verbose 모드를 사용할 수 있도록 한다. (정규식을 보기 편하게 만들수 있고 주석등을 사용할 수 있게된다.)\n\n옵션을 사용할 때는 re.DOTALL처럼 전체 옵션 이름을 써도 되고 re.S처럼 약어를 써도 된다.", "_____no_output_____" ], [ "### DOTALL, S\n\n. 메타 문자는 줄바꿈 문자(\\n)를 제외한 모든 문자와 매치되는 규칙이 있다. 만약 \\n 문자도 포함하여 매치하고 싶다면 re.DOTALL 또는 re.S 옵션을 사용해 정규식을 컴파일하면 된다.\n\n다음 예를 보자.", "_____no_output_____" ] ], [ [ "import re", "_____no_output_____" ], [ "p=re.compile('a.b')", "_____no_output_____" ], [ "m=p.match(\"a\\nb\")", "_____no_output_____" ], [ "print(m)", "None\n" ] ], [ [ "정규식이 a.b인 경우 문자열 a\\nb는 매치되지 않음을 알 수 있다. 왜냐하면 \\n은 . 메타 문자와 매치되지 않기 때문이다. \\n 문자와도 매치되게 하려면 다음과 같이 re.DOTALL 옵션을 사용해야 한다.", "_____no_output_____" ] ], [ [ "p=re.compile('a.b', re.DOTALL)", "_____no_output_____" ], [ "m=p.match('a\\nb')", "_____no_output_____" ], [ "print(m)", "<_sre.SRE_Match object; span=(0, 3), match='a\\nb'>\n" ] ], [ [ "보통 re.DOTALL 옵션은 여러 줄로 이루어진 문자열에서 \\n에 상관없이 검색할 때 많이 사용한다.", "_____no_output_____" ], [ "### IGNORECASE, I\n\nre.IGNORECASE 또는 re.I 옵션은 대소문자 구별 없이 매치를 수행할 때 사용하는 옵션이다. 다음 예제를 보자.", "_____no_output_____" ] ], [ [ "p=re.compile('[a-z]',re.I)", "_____no_output_____" ], [ "p.match(\"python\")", "_____no_output_____" ], [ "p.match(\"Python\")", "_____no_output_____" ], [ "p.match(\"PYTHON\")", "_____no_output_____" ] ], [ [ "[a-z] 정규식은 소문자만을 의미하지만 re.I 옵션으로 대소문자 구별 없이 매치된다.", "_____no_output_____" ], [ "### MULTILINE, M\n\n\n![image.png](attachment:image.png)", "_____no_output_____" ] ], [ [ "import re", "_____no_output_____" ], [ "p=re.compile(\"^python\\s\\w+\")", "_____no_output_____" ], [ "data = '''python one\nlife is too short\npython two\nyou need python\npython three'''", "_____no_output_____" ], [ "print(p.findall(data))", "['python one']\n" ] ], [ [ "정규식 ^python\\s\\w+은 python이라는 문자열로 시작하고 그 뒤에 whitespace, 그 뒤에 단어가 와야 한다는 의미이다. 검색할 문자열 data는 여러 줄로 이루어져 있다.\n\n이 스크립트를 실행하면 위와 같은 결과를 돌려준다.", "_____no_output_____" ], [ "^ 메타 문자에 의해 python이라는 문자열을 사용한 첫 번째 줄만 매치된 것이다.\n\n하지만 ^ 메타 문자를 문자열 전체의 처음이 아니라 각 라인의 처음으로 인식시키고 싶은 경우도 있을 것이다. 이럴 때 사용할 수 있는 옵션이 바로 re.MULTILINE 또는 re.M이다. 위 코드를 다음과 같이 수정해 보자.", "_____no_output_____" ] ], [ [ "p=re.compile(\"^python\\s\\w+\", re.MULTILINE)", "_____no_output_____" ], [ "data = '''python one\nlife is too short\npython two\nyou need python\npython three'''", "_____no_output_____" ], [ "print(p.findall(data))", "['python one', 'python two', 'python three']\n" ] ], [ [ "re.MULTILINE 옵션으로 인해 ^ 메타 문자가 문자열 전체가 아닌 각 줄의 처음이라는 의미를 갖게 되었다. \n이 스크립트를 실행하면 위와 같은 결과가 출력된다.", "_____no_output_____" ], [ "즉 re.MULTILINE 옵션은 ^, $ 메타 문자를 문자열의 각 줄마다 적용해 주는 것이다.", "_____no_output_____" ], [ "### VERBOSE, X\n", "_____no_output_____" ], [ "지금껏 알아본 정규식은 매우 간단하지만 정규식 전문가들이 만든 정규식을 보면 거의 암호수준이다. 정규식을 이해하려면 하나하나 조심스럽게 뜯어보아야만 한다. \n이렇게 이해하기 어려운 정규식을 주석 또는 줄 단위로 구분할 수 있다면 얼마나 보기 좋고 이해하기 쉬울까? 방법이 있다. 바로 re.VERBOSE 또는 re.X 옵션을 사용하면 된다.\n\n다음 예를 보자.", "_____no_output_____" ] ], [ [ "charref = re.compile(r'&[#](0[0-7]+|[0-9]+|x[0-9a-fA-F]+);')", "_____no_output_____" ] ], [ [ "위 정규식이 쉽게 이해되는가? 이제 다음 예를 보자.\n\n", "_____no_output_____" ] ], [ [ "charref = re.compile(r\"\"\"\n &[#] # Start of a numeric entity reference\n (\n 0[0-7]+ # Octal form\n | [0-9]+ # Decimal form\n | x[0-9a-fA-F]+ # Hexadecimal form\n )\n ; # Trailing semicolon\n\"\"\", re.VERBOSE)", "_____no_output_____" ] ], [ [ "첫 번째와 두 번째 예를 비교해 보면 컴파일된 패턴 객체인 charref는 모두 동일한 역할을 한다. 하지만 정규식이 복잡할 경우 두 번째처럼 주석을 적고 여러 줄로 표현하는 것이 훨씬 가독성이 좋다는 것을 알 수 있다.\n\nre.VERBOSE 옵션을 사용하면 문자열에 사용된 whitespace는 컴파일할 때 제거된다(단 [ ] 안에 사용한 whitespace는 제외). 그리고 줄 단위로 #기호를 사용하여 주석문을 작성할 수 있다.", "_____no_output_____" ], [ "## 백슬래시 문제\n\n정규 표현식을 파이썬에서 사용할 때 혼란을 주는 요소가 한 가지 있는데, 바로 백슬래시(\\)이다.\n\n예를 들어 어떤 파일 안에 있는 \"\\section\" 문자열을 찾기 위한 정규식을 만든다고 가정해 보자.\n\n>\\section\n\n이 정규식은 \\s 문자가 whitespace로 해석되어 의도한 대로 매치가 이루어지지 않는다.\n\n위 표현은 다음과 동일한 의미이다.\n\n>[ \\t\\n\\r\\f\\v]ection\n\n의도한 대로 매치하고 싶다면 다음과 같이 변경해야 한다.\n\n> \\\\\\section\n\n즉 위 정규식에서 사용한 \\ 문자가 문자열 자체임을 알려 주기 위해 백슬래시 2개를 사용하여 이스케이프 처리를 해야 한다.\n\n따라서 위 정규식을 컴파일하려면 다음과 같이 작성해야 한다.", "_____no_output_____" ] ], [ [ "p=re.compile(\"\\\\section\")", "_____no_output_____" ] ], [ [ "그런데 여기에서 또 하나의 문제가 발견된다. 위처럼 정규식을 만들어서 컴파일하면 실제 파이썬 정규식 엔진에는 파이썬 문자열 리터럴 규칙에 따라 \\\\이 \\로 변경되어 \\section이 전달된다.\n\n※ 이 문제는 위와 같은 정규식을 파이썬에서 사용할 때만 발생한다(파이썬의 리터럴 규칙). 유닉스의 grep, vi 등에서는 이러한 문제가 없다.\n\n결국 정규식 엔진에 \\\\ 문자를 전달하려면 파이썬은 \\\\\\\\처럼 백슬래시를 4개나 사용해야 한다.", "_____no_output_____" ] ], [ [ "p = re.compile('\\\\\\\\section')\n", "_____no_output_____" ] ], [ [ "이렇게 해야만 원하는 결과를 얻을 수 있다. 하지만 너무 복잡하지 않은가?\n\n만약 위와 같이 \\를 사용한 표현이 계속 반복되는 정규식이라면 너무 복잡해서 이해하기 쉽지않을 것이다. 이러한 문제로 인해 파이썬 정규식에는 Raw String 규칙이 생겨나게 되었다. 즉 컴파일해야 하는 정규식이 Raw String임을 알려 줄 수 있도록 파이썬 문법을 만든 것이다. 그 방법은 다음과 같다.", "_____no_output_____" ] ], [ [ " p = re.compile(r'\\\\section')", "_____no_output_____" ] ], [ [ "위와 같이 정규식 문자열 앞에 r 문자를 삽입하면 이 정규식은 Raw String 규칙에 의하여 백슬래시 2개 대신 1개만 써도 2개를 쓴 것과 동일한 의미를 갖게 된다.\n\n※ 만약 백슬래시를 사용하지 않는 정규식이라면 r의 유무에 상관없이 동일한 정규식이 될 것이다.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb2504461a1c45364be5fb355ddc39f066d58c85
75,968
ipynb
Jupyter Notebook
Distributed Machine Learning with Apache Spark/cs110_lab3b_text_analysis_and_entity_resolution.ipynb
blackcisne10/Distributed-Machine-Learning-with-Apache-Spark
7e7b601b8689025595cbf86bba1915662c5a91f9
[ "Apache-2.0" ]
1
2019-05-14T14:01:33.000Z
2019-05-14T14:01:33.000Z
Distributed Machine Learning with Apache Spark/cs110_lab3b_text_analysis_and_entity_resolution.ipynb
blackcisne10/Distributed-Machine-Learning-with-Apache-Spark
7e7b601b8689025595cbf86bba1915662c5a91f9
[ "Apache-2.0" ]
null
null
null
Distributed Machine Learning with Apache Spark/cs110_lab3b_text_analysis_and_entity_resolution.ipynb
blackcisne10/Distributed-Machine-Learning-with-Apache-Spark
7e7b601b8689025595cbf86bba1915662c5a91f9
[ "Apache-2.0" ]
null
null
null
37,984
75,967
0.712089
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb250d181f8c7687f35ea43f06bd82a84108df1b
666,485
ipynb
Jupyter Notebook
notebooks/Sentiment ARIMA.ipynb
brandonmalexander/btc_prediction
f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79
[ "MIT" ]
null
null
null
notebooks/Sentiment ARIMA.ipynb
brandonmalexander/btc_prediction
f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79
[ "MIT" ]
null
null
null
notebooks/Sentiment ARIMA.ipynb
brandonmalexander/btc_prediction
f5ed6292ca300f0d62f2ee2f1a9c46e55e731e79
[ "MIT" ]
null
null
null
526.865613
177,272
0.924384
[ [ [ "# Import libraries\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom scipy import stats\nimport statsmodels.api as sm\nimport warnings\nfrom itertools import product\nfrom datetime import datetime\nwarnings.filterwarnings('ignore')\nplt.style.use('seaborn-poster')\nimport requests\nfrom pandas.io.json import json_normalize\nimport math\nimport random\nimport decimal\nimport scipy.linalg\nimport numpy.random as nrand", "C:\\Users\\Edward\\Documents\\Anaconda3\\lib\\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" ], [ "from selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nimport pandas as pd\n\ndef get_reddit_data(subreddit, date):\n \"\"\"\n Gets top 26 frontpage titles from 'subreddit' on 'date\n :param subreddit: ex: 'r/bitcoin'\n :param date: in 'YYYYMMDD'\n :return titles: a list of strings of titles\n \"\"\"\n titles = []\n\n url = \"https://web.archive.org/web/\" + date + \"/reddit.com/\" + subreddit\n #print(url)\n driver.get(url)\n\n try:\n sitetable = driver.find_element_by_id(\"siteTable\")\n posts = sitetable.find_elements_by_tag_name(\"div\")\n\n for post in posts:\n if len(post.find_elements_by_class_name(\"title\")) > 0:\n title = post.find_element_by_class_name(\"title\").text\n titles.append(title)\n titles = set(titles)\n return titles\n except NoSuchElementException:\n return ['0'] * 26\n\n\ndef format_date(date): # for way-way-back machine urls\n \"\"\"\n Reformats date so that wayback machine will like it\n :param date: in datetime64\n :return:\n \"\"\"\n year = str(date.year)\n month = str(date.month)\n if len(month) < 2:\n month = \"0\" + month\n day = str(date.day)\n if len(day) < 2:\n day = \"0\" + day\n return year + month + day\n\n\n# def get_reddit_dataframe(begin, fin, subreddit, writefile):\n# \"\"\"\n# Makes a big dataframe indexed by a DatetimeIndex for every day from begin to fin. Values are top reddit posts, columns\n# separate titles on a given day/row.\n# :param begin: starting date of dataframe\n# :param fin: ending date of dataframe\n# :param subreddit: subreddit to scrape\n# :return: none\n# \"\"\"\n# timeindex = pd.DatetimeIndex(freq='d', start=begin, end=fin)\n# data = pd.DataFrame()\n# for date in timeindex:\n# fdate = format_date(date)\n# titles = get_reddit_data(subreddit, fdate)\n# i = 1\n# for title in titles: # probably can do this without a for loop\n# data.at[date, i] = title\n# i += 1\n# data.to_csv()\n\n\n# driver = webdriver.Firefox()\n# subreddit = 'r/bitcoin'\n# begin = '2018-01-31'\n# fin = '2018-02-13'\n# #writefile = 'data/text/2018_2_14_832.csv'\n\n# #get_reddit_dataframe(begin, fin, subreddit, writefile)\n\n# driver.quit()\n\n# #pd.read_csv(filepath_or_buffer='test_data/redditData.csv', infer_datetime_format=True)", "_____no_output_____" ], [ "fdate='2018-01-31'\n#get_reddit_data(subreddit, fdate)", "_____no_output_____" ], [ "sent= pd.read_csv('reddit_sentiment_data.csv')\nsent['Avg'] = sent.mean(axis=1)\nsent['Date']=sent['Unnamed: 0']\nsent=sent[['Date','Avg']]\nimport datetime\nsent['Date']=pd.to_datetime(sent['Date'], format='%Y/%m/%d')\nsent.index=sent['Date']\nsent=sent[['Avg']]\nprices= sent#########\nprices['Weighted Price']=prices['Avg']\nprices=prices[['Weighted Price']]\nprices.head()", "_____no_output_____" ], [ "# Resampling to daily frequency\nprices_daily = prices.resample('d').mean()\n\n# Resampling to monthly frequency\nprices_month = prices.resample('M').mean()\n# Resampling to annual frequency\nprices_annual = prices.resample('A-DEC').mean()\n\n# Resampling to quarterly frequency\nprices_Q = prices.resample('Q-DEC').mean()", "_____no_output_____" ], [ "b=requests.get('https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD')\nA=json_normalize(b.json())\ndata= A['dataset.data'].all()\ndf = pd.DataFrame(data)\ndf.columns=A['dataset.column_names'].all()\ndate=df['Date']\ndf=df[::-1]\n#df.reindex(index=range(0,len(date)))\ndf.index= range(0,len(date))\nworth=df[['Date','Weighted Price']]\nimport datetime\nworth['Date']=pd.to_datetime(worth['Date'], format='%Y/%m/%d')\nworth.index=worth['Date']\nworth=worth[['Weighted Price']]\nworth=worth.loc['2015-02-01':'2018-02-09']\n# # N=100\n# # movmean=[]\n# # movstd=[]\n# # for p in range(N,len(prices)):\n# # A= np.mean(prices[p-N:p])\n# # movmean.append(A)\n# # X=np.std(prices[p-N:p])\n# # movstd.append(X)\n# # plt.plot(movmean,label = 'Moving Mean')\n# # plt.plot(movstd, label = 'Moving Standard Deviation')\n", "_____no_output_____" ], [ "rolworth = worth.rolling(window=1,center=True).mean()\nrolprice = prices.rolling(window=100,center=True).mean()\nfig = plt.figure(figsize=[30, 10])\nfig, ax1 = plt.subplots()\n\nax2 = ax1.twinx()\na2=ax2.plot(rolworth, color='red', label='Moving Price Avg')\na1=ax1.plot(rolprice, color='blue', label='Amplified Moving Sentiment Avg')\nax1.set_xlabel('Time')\nax1.set_ylabel('Sentiment Data', color='b')\nax2.set_ylabel('Bitcoin Price (USD)', color='r')\n\nlns = a1+a2\nlabs = [l.get_label() for l in lns]\nax1.legend(lns, labs, loc=2)\n\nplt.show()", "_____no_output_____" ], [ "rolworth = worth.rolling(window=10,center=True).mean()\nrolworthstd=worth.rolling(window=50,center=True).std()\nplt.plot(worth,label='Unfiltered')\nplt.plot(rolworth,color='red', label='Moving Price AVG')\nplt.plot(rolworthstd, color='blue', label='Moving Price STD')\nplt.title('Bitcoin Rolling Mean & Standard Deviation')\nplt.xlabel('Year-Month')\nplt.ylabel('Bitcoin Price USD')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "##################\nprices_trains=prices[0:round(len(prices)*.87)]\nprices=prices_trains\nprices", "_____no_output_____" ], [ "fig = plt.figure(figsize=[20, 13])\nplt.suptitle('Bitcoin Exchange (Mean) at Different Time Intervals ', fontsize=22)\n\nplt.subplot(221)\nplt.plot(prices_daily['Weighted Price'])\nplt.ylabel('Price ($)')\nplt.xlabel('Time (Daily Intervals)')\nplt.subplot(222)\nplt.plot(prices_month['Weighted Price'])\nplt.ylabel('Price ($)')\nplt.xlabel('Time (Monthly Intervals)')\nplt.subplot(223)\nplt.plot(prices_annual['Weighted Price'])\nplt.ylabel('Price ($)')\nplt.xlabel('Time (Annual Intervals)')\nplt.subplot(224)\nplt.plot(prices_Q['Weighted Price'])\nplt.ylabel('Price ($)')\nplt.xlabel('Time (Quarterly Intervals)')\nplt.show()", "_____no_output_____" ], [ "sm.tsa.seasonal_decompose(prices_month['Weighted Price']).plot()\nplt.show()", "_____no_output_____" ] ], [ [ "Non-Stationary Data is data that has constantly changing mean, variance, and covariances over time. (Trends, cycles, random walks (Brownian Motion Approximation) \n\nRandom Walk= Y[t]=Y[t-1] + E. Variance approaches infinity W/R to time with E being a distributed white noise stoichastic characteristic \n\nRandom Walk with Drift = Y[t]=Y[t-1] + E + a, a= drift\n\nDeterministic Trend = Y[t]= Bt + E + a: \n\nDicky-Fuller: Ho = Data is Non Stationary (there is a unit root). Reject null Hypothesis when P<.05 (Stationary) \nhttps://stats.stackexchange.com/questions/29121/intuitive-explanation-of-unit-root\n\nDetrending and development of a Stationary Relationship:\nY[t]- Y[t-1] = E + a\n\nY[t]- Bt = E + a:\n\nBoxCox Tranforms: Creating a Normal Shape for Datum ", "_____no_output_____" ] ], [ [ "#Normalize the month price data \nprices_month['Weighted_Price_box'], lmbda = stats.boxcox(prices_month['Weighted Price'])\n#Determine if this Data is Stationary \nprint(\"Dickey–Fuller test: p=%f\" % sm.tsa.stattools.adfuller(prices_month['Weighted Price'])[1])\n#non stationary ", "Dickey–Fuller test: p=0.000857\n" ], [ "## Converting to Stationary Data and then Re-examing with Stationary Test\nn=12 # 12 month differentiation\n#Y[t]- Y[t-1] = E (normal) + a\nprices_month['prices_box_diff'] = prices_month['Weighted_Price_box'] - prices_month.Weighted_Price_box.shift(n)\nprint(\"Dickey–Fuller test: p=%f\" % sm.tsa.stattools.adfuller(prices_month.prices_box_diff[n:])[1])\n#stationary", "Dickey–Fuller test: p=0.004792\n" ], [ "#Regular Non Seasonal Differention\nprices_month['prices_box_diff2'] = prices_month.prices_box_diff - prices_month.prices_box_diff.shift(1)\nprint(\"Dickey–Fuller test: p=%f\" % sm.tsa.stattools.adfuller(prices_month.prices_box_diff2[13:])[1])", "Dickey–Fuller test: p=0.000000\n" ] ], [ [ "AutoCorrelation: Similarity that exists between time series vs. lagged time series \nIe calculating the relationship between two times series, however these are the same time series where one is lagged \n\nHOW MUCH DOES PAST DATA IMPACT FUTURE DATA (Lagged Correlation) - Stock momentum ", "_____no_output_____" ] ], [ [ "\nax = plt.subplot(211)\n\n#perform test on normalized and differentiated (stationary) data\n#AutoCorrelation\nsm.graphics.tsa.plot_acf(prices_month.prices_box_diff2[13:].values.squeeze(), lags=20, ax=ax)\n\nax = plt.subplot(212)\n#Partial AutoCorrelation \nsm.graphics.tsa.plot_pacf(prices_month.prices_box_diff2[13:].values.squeeze(), lags=20, ax=ax)\n\n", "_____no_output_____" ], [ "fig = plt.figure(figsize=[30, 10])\nfrom pandas import concat\nfrom matplotlib import pyplot\nfrom pandas.plotting import scatter_matrix\nvalues=prices['Weighted Price']\nlags = 8\nvalues = prices['Weighted Price'] #collected prices values \ncolumns = [values] #create list \nfor i in range(1,(lags + 1)): #run for loop for 1 to 8 lag iterations/examinations\n\tcolumns.append(values.shift(i)) #shift the data according to each lag then add to the set\ndataframe = concat(columns, axis=1) #concactinate all these columns \ncolumns = ['t+1']\nfor i in range(1,(lags + 1)):\n \tcolumns.append('t-' + str(i)) #creats columns title t-(lag#)\ndataframe.columns = columns #set as columns\npyplot.figure(1)\nfor i in range(1,(lags + 1)): # plot data\n \tax = pyplot.subplot(240 + i)\n \tax.set_title('t+1 vs t-' + str(i))\n \tpyplot.scatter(x=dataframe['t+1'].values, y=dataframe['t-'+str(i)].values)\n\npyplot.show()\n", "_____no_output_____" ], [ "\n\n ", "_____no_output_____" ] ], [ [ "- ARIMA:Auto Regressive Integrated Moving Average \n- AutoRegressive- using past variable of time to predict future (lags of stationarized series)\n- Integrated- Time series is differenced to be stationarized\n- Moving Average- lags of forecast error \n- A stationary series has no trend, its variations around its mean have a constant amplitude, and it wiggles in a consistent fashion \n- Autocorrelations are the same for stationary data\n- The ARIMA forecasting equation for a stationary time series is a linear (i.e., regression-type) equation in which the predictors consist of lags of the dependent variable and/or lags of the forecast errors\n- PREDICTED Y= weight of previous values + weight of previous errors\n\nRequired Prior Knowledge:\n\n-Box-Jenkins Model \n\n\n\nARIMA(P,D,Q) model:\n- used on random walk autoregressive models, exponential smoothing \nP= # of autoregressive terms (lag observations) \nD= # of nonseasonal differences needed for stationarity: how much differencing is occuring \nQ= # of lagged forecast errors [moving average window]\n\n1. Identification: Of all the data, select a portion of the Model the best summarizes the data\n Is the data stationary, and how many differences are needed to make it stationary\n FOR Time Series: x3 x2 x1 \n \n ACF= True Corr of x2 & x1 = (corr(x3,x2)) + PACF(X2,x1)\n PACF(X2,x1) = ACF- (corr(x3,x2))\n ACF- Corr(Observation, Lagged Observation)\n PACF- Corr(Observation, Lagged Observation) \n \n Values that cross the 95% interval are significant \n \n AR- if ACF has trail off, hard cutoff PACF (p) \n MA- if PACF has trail off, hard cutoff ACF (q)\n\nStationary= statistical properties are all constant over time. \n Autocorrleations (prior deviations from mean) are constant\n \n\n \n \n \n\n", "_____no_output_____" ] ], [ [ "#Initial approximation of parameters\nQs = range(0, 2)\nqs = range(0, 3)\nPs = range(0, 3)\nps = range(0, 3)\nD=1\nd=1\nparameters = product(ps, qs, Ps, Qs)\nparameters_list = list(parameters)\nlen(parameters_list)\n", "_____no_output_____" ], [ "# Model Determination \nresults = []\nbest_aic = float(\"inf\")\nwarnings.filterwarnings('ignore')\nfor param in parameters_list: #run through each grouping of parameters (54 total combos)\n try:\n model=sm.tsa.statespace.SARIMAX(prices_month.Weighted_Price_box, order=(param[0], d, param[1]), \n seasonal_order=(param[2], D, param[3], 12)).fit(disp=-1)\n except ValueError:\n print('wrong parameters:', param)\n continue\n aic = model.aic\n if aic < best_aic:\n best_model = model\n best_aic = aic\n best_param = param\n results.append([param, model.aic])", "wrong parameters: (0, 0, 0, 0)\nwrong parameters: (0, 0, 0, 1)\nwrong parameters: (0, 0, 1, 1)\nwrong parameters: (0, 0, 2, 0)\nwrong parameters: (0, 0, 2, 1)\nwrong parameters: (0, 1, 0, 1)\nwrong parameters: (0, 1, 1, 1)\nwrong parameters: (0, 1, 2, 0)\nwrong parameters: (0, 1, 2, 1)\nwrong parameters: (0, 2, 0, 1)\nwrong parameters: (0, 2, 1, 1)\nwrong parameters: (0, 2, 2, 0)\nwrong parameters: (0, 2, 2, 1)\nwrong parameters: (1, 0, 0, 1)\nwrong parameters: (1, 0, 1, 1)\nwrong parameters: (1, 0, 2, 0)\nwrong parameters: (1, 0, 2, 1)\nwrong parameters: (1, 1, 0, 1)\nwrong parameters: (1, 1, 1, 1)\nwrong parameters: (1, 1, 2, 0)\nwrong parameters: (1, 1, 2, 1)\nwrong parameters: (1, 2, 0, 1)\nwrong parameters: (1, 2, 1, 1)\nwrong parameters: (1, 2, 2, 0)\nwrong parameters: (1, 2, 2, 1)\nwrong parameters: (2, 0, 0, 1)\nwrong parameters: (2, 0, 1, 1)\nwrong parameters: (2, 0, 2, 0)\nwrong parameters: (2, 0, 2, 1)\nwrong parameters: (2, 1, 0, 0)\nwrong parameters: (2, 1, 0, 1)\nwrong parameters: (2, 1, 1, 0)\nwrong parameters: (2, 1, 1, 1)\nwrong parameters: (2, 1, 2, 0)\nwrong parameters: (2, 1, 2, 1)\nwrong parameters: (2, 2, 0, 1)\nwrong parameters: (2, 2, 1, 1)\nwrong parameters: (2, 2, 2, 0)\nwrong parameters: (2, 2, 2, 1)\n" ], [ "# Best Models\nresult_table = pd.DataFrame(results)\nresult_table.columns = ['parameters', 'aic']\nprint(result_table.sort_values(by = 'aic', ascending=True).head())\nprint(best_model.summary())", " parameters aic\n2 (0, 1, 1, 0) -212.812096\n6 (1, 0, 1, 0) -212.059678\n0 (0, 0, 1, 0) -211.211003\n12 (2, 0, 1, 0) -210.400839\n8 (1, 1, 1, 0) -210.274080\n Statespace Model Results \n==========================================================================================\nDep. Variable: Weighted_Price_box No. Observations: 37\nModel: SARIMAX(0, 1, 1)x(1, 1, 0, 12) Log Likelihood 109.406\nDate: Sun, 22 Apr 2018 AIC -212.812\nTime: 01:19:24 BIC -207.979\nSample: 02-28-2015 HQIC -211.108\n - 02-28-2018 \nCovariance Type: opg \n==============================================================================\n coef std err z P>|z| [0.025 0.975]\n------------------------------------------------------------------------------\nma.L1 -0.6648 0.116 -5.750 0.000 -0.891 -0.438\nar.S.L12 -0.7475 0.122 -6.121 0.000 -0.987 -0.508\nsigma2 4.179e-06 1.49e-06 2.804 0.005 1.26e-06 7.1e-06\n===================================================================================\nLjung-Box (Q): 12.17 Jarque-Bera (JB): 0.20\nProb(Q): 0.97 Prob(JB): 0.91\nHeteroskedasticity (H): 3.04 Skew: 0.21\nProb(H) (two-sided): 0.14 Kurtosis: 2.86\n===================================================================================\n\nWarnings:\n[1] Covariance matrix calculated using the outer product of gradients (complex-step).\n" ], [ "# Inverse Box-Cox Transformation Function\ndef invboxcox(y,lmbda):\n if lmbda == 0:\n return(np.exp(y))\n else:\n return(np.exp(np.log(lmbda*y+1)/lmbda))\n", "_____no_output_____" ], [ "# Prediction\nfrom datetime import datetime\ndf_month2 = prices_month[['Weighted Price']]\ndate_list = [datetime(2017, 6, 30), datetime(2017, 7, 31), datetime(2017, 8, 31), datetime(2017, 9, 30), \n datetime(2017, 10, 31), datetime(2017, 11, 30), datetime(2017, 12, 31), datetime(2018, 6, 30),datetime(2018,7, 30),datetime(2018,8, 30)]\nfuture = pd.DataFrame(index=date_list, columns= prices_month.columns)\n\ndf_month2 = pd.concat([df_month2, future])\ndf_month2['forecast'] = invboxcox(best_model.predict(start=1, end=1500), lmbda)\nplt.figure(figsize=(15,7))\nplt.plot(df_month2['Weighted Price'],label='Measured (Current) Sentiment')\ndf_month2.forecast.plot(color='r', ls='--', label='Predicted Sentiment')\nplt.legend()\nplt.title('Bitcoin \"Sentiment\", By Months')\nplt.ylabel('Sentiment Data')\n\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb25100ab02b0234dca6ebc23b00311a3a005b7f
9,625
ipynb
Jupyter Notebook
Topic 5 Abstract data structures/Untitled3.ipynb
classroomtechtools/ib_dp_course
ccd31d3e52a491b692a40362c1e4a793338a2c33
[ "MIT" ]
null
null
null
Topic 5 Abstract data structures/Untitled3.ipynb
classroomtechtools/ib_dp_course
ccd31d3e52a491b692a40362c1e4a793338a2c33
[ "MIT" ]
null
null
null
Topic 5 Abstract data structures/Untitled3.ipynb
classroomtechtools/ib_dp_course
ccd31d3e52a491b692a40362c1e4a793338a2c33
[ "MIT" ]
null
null
null
35.516605
455
0.592104
[ [ [ "# Abstract Data Structures: Thinking recursively\n\n## 5.1.1 Identify a situation that requires the use of recursive thinking\n\nWhat is this recursive thing? It's a very practical way of establishing an abstract pattern in our thinking. There are a class of problems that require thinking in a more abstract manner, and trying to identify this pattern of thinking is the subject of this section.\n\nFirst, let's talk about **non-recursive** or **iterative** way of thinking. That's like a procedure, such as brushing your teeth, or the sequence of events on any given day in history.\n\nWe'll start with this previous function that we wrote that continuously asks the user for valid input", "_____no_output_____" ] ], [ [ "// We'll generate 5 integers, finally returning \"Y\" on the fifth attempt\nQUEUE = Queue.from_x_characters(4, min=\"A\", max=\"X\")\nQUEUE.enqueue(\"Y\")\n\nsub input(PROMPT)\n out PROMPT\n\n // pop off the stack and if it's a 10, we finally got a yes\n VALUE = QUEUE.dequeue()\n if VALUE = 1 then\n return \"Y\"\n else\n return VALUE\n end if\nend sub\n\nsub ask_until_valid_nonrecursive(PROMPT, POSSIBLES)\n // loop infinitely until \"break\"\n loop while true\n RESPONSE = input(PROMPT)\n if RESPONSE in POSSIBLES then\n // valid response\n break // loop stops\n else\n // invalid response\n output RESPONSE, \" is not valid!\"\n end if\n output RESPONSE, \" Aahhhhh\"\n return RESPONSE\nend sub\n\nask_until_valid_nonrecursive(\"Yes?: \", [\"Y\"])", "_____no_output_____" ] ], [ [ "This function works just fine. However, there is a way to write this function in a recursive manner. It's a simple example that does not have much use, but we just need to understand what is meant when we say to solve something with recursion. It's basically a function calling itself. Consider this code:", "_____no_output_____" ] ], [ [ "def ask_until_valid_recursive(prompt: str, possible_answers: list):\n response = input(prompt)\n if response in possible_answers:\n # valid\n return response\n # invalid: recurse!\n ask_until_valid_recursive(prompt, possible_answers)\n \nask_until_valid_recursive(\"Get it?\", ['Y', 'N'])", "_____no_output_____" ] ], [ [ "Basically this function \"falls back\" on itself. Instead of going in a loop, the code continues the same way a loop does, by further calling itself, and repeating this process until something valid is found.\n\nRight, so let's discover a limit to this recursion thing by seeing what happens when nothing valid is every found.", "_____no_output_____" ] ], [ [ "ask_until_valid_recursive('Nothing you type will be valid: ', []) # infinite loop", "_____no_output_____" ] ], [ [ "In the above call, we have not defined anything as being valid, and so this program will go on forever constantly prompting you to type something. Actually … not quite forever. Although it is technically an infinite loop, the fact of the matter is that there are resource limitations, and it will eventually fail. Let's see it fail by typing a recursive function that never ends:", "_____no_output_____" ] ], [ [ "def recurse_forever(prompt):\n recurse_forever(prompt)\n\nrecurse_forever(\"Error\")", "_____no_output_____" ] ], [ [ "Run the above, and it displays `RecursionError: maximum recursion depth exceeded`. This means that the code we ran failed, and in this case it's because of something called a \"stack overflow\" which is to say that Python doesn't have enough memory to continue keep doing the same thing over and over again, and so fails.\n\nBut this `ask_until_valid` example is not really an example that requires recursive thinking, because the version that we had worked just fine with an interative approach (and maybe was easier to understand). So what kind of problem does require recursion? It's in a case in which the problem breaks down into an algorthim that depends on previous steps being completed, and depending on **base cases** where the recursion will inevidibly end up.\n\nFor that, we'll take another loop at making the fibinocci sequence. We need to understand what this sequence of numbers is, which is provided in this formula:\n\n ↓ pattern ↓ base cases\n\n$F_n = F_{n-1} + F_{n-2}$, where $F_1 = 1$, and $F_0 = 0$.\n\nThat is to say that a number `n` is defined as the \"F of (n-1) plus F of (n-2)\", but \"F of 1 is 1\" and F of 0 is 0\"\n\nThe solution to calculate this in a procedural way is this:", "_____no_output_____" ] ], [ [ "def fibonnoci_iterative(how_many):\n \"\"\" return the how_many-th number of fibonocci numbers \"\"\"\n \n # base cases:\n result = [0, 1]\n \n for n in range(2, how_many): # we already have the first two\n \n # pattern:\n new = result[n-2] + result[n-1]\n result.append(new)\n \n return result\n\nfor result in fibonnoci_iterative(10):\n print(result, end=\" \")", "_____no_output_____" ], [ "def fibonnoci_recurse(n):\n \"\"\" return the fibonocci numbers at index n \"\"\" \n \n # base cases:\n if n == 0:\n return 0\n elif n == 1:\n return 1\n \n # pattern\n return fibonnoci_recurse(n - 1) + fibonnoci_recurse(n - 2)\n\ndef fibonnoci_recurse_n_terms(how_many):\n result = []\n for i in range(how_many):\n value = fibonnoci_recurse(i)\n result.append(value)\n return result\n\nfor item in fibonnoci_recurse_n_terms(10):\n print(item, end=\" \")", "_____no_output_____" ] ], [ [ "Okay, so we have some of the theory down. We can see that recusion can be used to solve problems when the problem can be described in terms of itself. We have also seen the case where base cases are required to ensure that we don't have an infinite loop. \n\n## 5.1.2 Identify recursive thinking in a specified problem solution\n\nBut let's get more specific in understanding the kinds of problems that recursion is great at solving. Above, there were two solutions presented, one that was iterative and the other that was recursive. One could argue that the iterative solution is simpler and more understandable. There is no doubt, however, that the recursive solution is far slower. ", "_____no_output_____" ] ], [ [ "%%timeit\nlist(fibonnoci_iterative(10))", "_____no_output_____" ], [ "%%timeit\nlist(fibonnoci_recurse_n_terms(10))", "_____no_output_____" ] ], [ [ "The above times how long it takes for the code to execute. The recursive solution is just painfully slow compared to the iterative approach. \n\nSo what kind of problem is better solved iteratively?\n\nLet's imagine that the school is organizing a day at Sunway Lagoon with the whole school. The lead teacher gives his phone number to all of the teachers who attend that day, and they are told to call the him whenever something happens. ", "_____no_output_____" ] ] ]
[ "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", "code" ], [ "markdown" ] ]
cb251bf248cc6a66b7d722dbb47cb2bcac84dae4
47,398
ipynb
Jupyter Notebook
lecture22_gaussians/lecture22_demos_and_notes.ipynb
alexhuth/ndap-fa2018
c4ba67ccabb77a844172c0ec14f877e25a3efded
[ "BSD-3-Clause" ]
29
2018-08-28T15:54:52.000Z
2021-10-08T22:52:53.000Z
lecture22_gaussians/lecture22_demos_and_notes.ipynb
alexhuth/ndap-fa2018
c4ba67ccabb77a844172c0ec14f877e25a3efded
[ "BSD-3-Clause" ]
null
null
null
lecture22_gaussians/lecture22_demos_and_notes.ipynb
alexhuth/ndap-fa2018
c4ba67ccabb77a844172c0ec14f877e25a3efded
[ "BSD-3-Clause" ]
27
2018-09-15T22:57:23.000Z
2020-07-22T21:09:07.000Z
149.993671
8,364
0.911853
[ [ [ "%matplotlib inline\nimport numpy as np\nfrom matplotlib import pyplot as plt", "_____no_output_____" ], [ "rands = np.random.rand(100, 10000)\nrand_means = rands.mean(axis=0)\nrand_means.shape", "_____no_output_____" ], [ "plt.hist(rands.ravel(), 100);", "_____no_output_____" ], [ "plt.hist(rand_means, 50);", "_____no_output_____" ], [ "# let's get weird with it\nrands2 = np.random.rand(100, 100000) ** 3\nrand_means2 = rands2.mean(0)", "_____no_output_____" ], [ "plt.hist(rands2.ravel(), 100);", "_____no_output_____" ], [ "plt.hist(rand_means2, 50);", "_____no_output_____" ], [ "# let's look at sample variance", "_____no_output_____" ], [ "gauss_rands = np.random.randn(20, 1000000)", "_____no_output_____" ], [ "real_variance = ((gauss_rands - gauss_rands.mean(axis=0))**2).sum(axis=0) / 20\nreal_variance2 = gauss_rands.var(axis=0)", "_____no_output_____" ], [ "np.allclose(real_variance, real_variance2)", "_____no_output_____" ], [ "plt.hist(real_variance, 100);", "_____no_output_____" ], [ "real_variance.mean()", "_____no_output_____" ], [ "# compute sample variance\nsample_variance = ((gauss_rands - gauss_rands.mean(axis=0))**2).sum(axis=0) / (20 - 1)\nsample_variance2 = gauss_rands.var(axis=0, ddof=1)", "_____no_output_____" ], [ "plt.hist(sample_variance, 100);", "_____no_output_____" ], [ "sample_variance.mean()", "_____no_output_____" ], [ "sample_variance2.mean()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb251ca941765ee97b2ee5967b24599776f58e8e
94,968
ipynb
Jupyter Notebook
SageMaker Project.ipynb
vickymei/udacity-mle-sentiment-analysis
d945c2003aeb96813a4abbf16f22d1d6c620c118
[ "MIT" ]
1
2020-05-12T20:08:24.000Z
2020-05-12T20:08:24.000Z
SageMaker Project.ipynb
vickymei/udacity-mle-sentiment-analysis
d945c2003aeb96813a4abbf16f22d1d6c620c118
[ "MIT" ]
null
null
null
SageMaker Project.ipynb
vickymei/udacity-mle-sentiment-analysis
d945c2003aeb96813a4abbf16f22d1d6c620c118
[ "MIT" ]
null
null
null
49.07907
1,155
0.610679
[ [ [ "# Creating a Sentiment Analysis Web App\n## Using PyTorch and SageMaker\n\n_Deep Learning Nanodegree Program | Deployment_\n\n---\n\nNow that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to enter a movie review. The web page will then send the review off to our deployed model which will predict the sentiment of the entered review.\n\n## Instructions\n\nSome template code has already been provided for you, and you will need to implement additional functionality to successfully complete this notebook. You will not need to modify the included code beyond what is requested. Sections that begin with '**TODO**' in the header indicate that you need to complete or implement some portion within them. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `# TODO: ...` comment. Please be sure to read the instructions carefully!\n\nIn addition to implementing code, there will be questions for you to answer which relate to the task and your implementation. Each section where you will answer a question is preceded by a '**Question:**' header. Carefully read each question and provide your answer below the '**Answer:**' header by editing the Markdown cell.\n\n> **Note**: Code and Markdown cells can be executed using the **Shift+Enter** keyboard shortcut. In addition, a cell can be edited by typically clicking it (double-click for Markdown cells) or by pressing **Enter** while it is highlighted.\n\n## General Outline\n\nRecall the general outline for SageMaker projects using a notebook instance.\n\n1. Download or otherwise retrieve the data.\n2. Process / Prepare the data.\n3. Upload the processed data to S3.\n4. Train a chosen model.\n5. Test the trained model (typically using a batch transform job).\n6. Deploy the trained model.\n7. Use the deployed model.\n\nFor this project, you will be following the steps in the general outline with some modifications. \n\nFirst, you will not be testing the model in its own step. You will still be testing the model, however, you will do it by deploying your model and then using the deployed model by sending the test data to it. One of the reasons for doing this is so that you can make sure that your deployed model is working correctly before moving forward.\n\nIn addition, you will deploy and use your trained model a second time. In the second iteration you will customize the way that your trained model is deployed by including some of your own code. In addition, your newly deployed model will be used in the sentiment analysis web app.", "_____no_output_____" ], [ "## Step 1: Downloading the data\n\nAs in the XGBoost in SageMaker notebook, we will be using the [IMDb dataset](http://ai.stanford.edu/~amaas/data/sentiment/)\n\n> Maas, Andrew L., et al. [Learning Word Vectors for Sentiment Analysis](http://ai.stanford.edu/~amaas/data/sentiment/). In _Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies_. Association for Computational Linguistics, 2011.", "_____no_output_____" ] ], [ [ "%mkdir ../data\n!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data", "--2020-02-17 18:03:52-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\nResolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10\nConnecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 84125825 (80M) [application/x-gzip]\nSaving to: ‘../data/aclImdb_v1.tar.gz’\n\n../data/aclImdb_v1. 100%[===================>] 80.23M 24.2MB/s in 4.1s \n\n2020-02-17 18:03:56 (19.6 MB/s) - ‘../data/aclImdb_v1.tar.gz’ saved [84125825/84125825]\n\n" ] ], [ [ "## Step 2: Preparing and Processing the data\n\nAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a training set and a testing set.", "_____no_output_____" ] ], [ [ "import os\nimport glob\n\ndef read_imdb_data(data_dir='../data/aclImdb'):\n data = {}\n labels = {}\n \n for data_type in ['train', 'test']:\n data[data_type] = {}\n labels[data_type] = {}\n \n for sentiment in ['pos', 'neg']:\n data[data_type][sentiment] = []\n labels[data_type][sentiment] = []\n \n path = os.path.join(data_dir, data_type, sentiment, '*.txt')\n files = glob.glob(path)\n \n for f in files:\n with open(f) as review:\n data[data_type][sentiment].append(review.read())\n # Here we represent a positive review by '1' and a negative review by '0'\n labels[data_type][sentiment].append(1 if sentiment == 'pos' else 0)\n \n assert len(data[data_type][sentiment]) == len(labels[data_type][sentiment]), \\\n \"{}/{} data size does not match labels size\".format(data_type, sentiment)\n \n return data, labels", "_____no_output_____" ], [ "data, labels = read_imdb_data()\nprint(\"IMDB reviews: train = {} pos / {} neg, test = {} pos / {} neg\".format(\n len(data['train']['pos']), len(data['train']['neg']),\n len(data['test']['pos']), len(data['test']['neg'])))", "IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg\n" ] ], [ [ "Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records.", "_____no_output_____" ] ], [ [ "from sklearn.utils import shuffle\n\ndef prepare_imdb_data(data, labels):\n \"\"\"Prepare training and test sets from IMDb movie reviews.\"\"\"\n \n #Combine positive and negative reviews and labels\n data_train = data['train']['pos'] + data['train']['neg']\n data_test = data['test']['pos'] + data['test']['neg']\n labels_train = labels['train']['pos'] + labels['train']['neg']\n labels_test = labels['test']['pos'] + labels['test']['neg']\n \n #Shuffle reviews and corresponding labels within training and test sets\n data_train, labels_train = shuffle(data_train, labels_train)\n data_test, labels_test = shuffle(data_test, labels_test)\n \n # Return a unified training data, test data, training labels, test labets\n return data_train, data_test, labels_train, labels_test", "_____no_output_____" ], [ "train_X, test_X, train_y, test_y = prepare_imdb_data(data, labels)\nprint(\"IMDb reviews (combined): train = {}, test = {}\".format(len(train_X), len(test_X)))", "IMDb reviews (combined): train = 25000, test = 25000\n" ] ], [ [ "Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loaded correctly.", "_____no_output_____" ] ], [ [ "print(train_X[100])\nprint(train_y[100])", "Dick Foran and Peggy Moran, who were so good together in THE MUMMY'S HAND, return for this very minor Universal Horror offering. But this time, instead of having Wallace Ford as the comedic sidekick \"Babe,\" we get Fuzzy Knight substituting as a silly buddy named \"Stuff\". But the results are nowhere near as charming, and the scare level is virtually nil.<br /><br />Dick is a businessman who gets the idea of spearheading a treasure hunt on a remote island inside a spooky old castle. Peggy is one of the gang who comes along for the ride. But there is a tall and skinny John Carradine lookalike in a black cape and big hat known as \"The Phantom\" who crashes the party in pursuit of the buried fortune himself.<br /><br />This \"phantom\" is not very mysterious, and no effort is made to even try and keep his rather average guy face in the shadows to create any tension or spookiness. It's always nice to see perky Moran, but otherwise you can chalk this up as one of Universal's instantly forgettable misfires.\n0\n" ] ], [ [ "The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis.", "_____no_output_____" ] ], [ [ "import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\n\nimport re\nfrom bs4 import BeautifulSoup\n\ndef review_to_words(review):\n nltk.download(\"stopwords\", quiet=True)\n stemmer = PorterStemmer()\n \n text = BeautifulSoup(review, \"html.parser\").get_text() # Remove HTML tags\n text = re.sub(r\"[^a-zA-Z0-9]\", \" \", text.lower()) # Convert to lower case\n words = text.split() # Split string into words\n words = [w for w in words if w not in stopwords.words(\"english\")] # Remove stopwords\n words = [PorterStemmer().stem(w) for w in words] # stem\n \n return words", "_____no_output_____" ] ], [ [ "The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set.", "_____no_output_____" ] ], [ [ "# TODO: Apply review_to_words to a review (train_X[100] or any other review)\nreview_to_words(train_X[100])", "_____no_output_____" ] ], [ [ "**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do to the input?", "_____no_output_____" ], [ "**Answer:**\n1. remove html elements\n2. stemming\n3. stopwords removal \n4. lower case all the words", "_____no_output_____" ], [ "The method below applies the `review_to_words` method to each of the reviews in the training and testing datasets. In addition it caches the results. This is because performing this processing step can take a long time. This way if you are unable to complete the notebook in the current session, you can come back without needing to process the data a second time.", "_____no_output_____" ] ], [ [ "import pickle\n\ncache_dir = os.path.join(\"../cache\", \"sentiment_analysis\") # where to store cache files\nos.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists\n\ndef preprocess_data(data_train, data_test, labels_train, labels_test,\n cache_dir=cache_dir, cache_file=\"preprocessed_data.pkl\"):\n \"\"\"Convert each review to words; read from cache if available.\"\"\"\n\n # If cache_file is not None, try to read from it first\n cache_data = None\n if cache_file is not None:\n try:\n with open(os.path.join(cache_dir, cache_file), \"rb\") as f:\n cache_data = pickle.load(f)\n print(\"Read preprocessed data from cache file:\", cache_file)\n except:\n pass # unable to read from cache, but that's okay\n \n # If cache is missing, then do the heavy lifting\n if cache_data is None:\n # Preprocess training and test data to obtain words for each review\n #words_train = list(map(review_to_words, data_train))\n #words_test = list(map(review_to_words, data_test))\n words_train = [review_to_words(review) for review in data_train]\n words_test = [review_to_words(review) for review in data_test]\n \n # Write to cache file for future runs\n if cache_file is not None:\n cache_data = dict(words_train=words_train, words_test=words_test,\n labels_train=labels_train, labels_test=labels_test)\n with open(os.path.join(cache_dir, cache_file), \"wb\") as f:\n pickle.dump(cache_data, f)\n print(\"Wrote preprocessed data to cache file:\", cache_file)\n else:\n # Unpack data loaded from cache file\n words_train, words_test, labels_train, labels_test = (cache_data['words_train'],\n cache_data['words_test'], cache_data['labels_train'], cache_data['labels_test'])\n \n return words_train, words_test, labels_train, labels_test", "_____no_output_____" ], [ "# Preprocess data\ntrain_X, test_X, train_y, test_y = preprocess_data(train_X, test_X, train_y, test_y)", "Wrote preprocessed data to cache file: preprocessed_data.pkl\n" ] ], [ [ "## Transform the data\n\nIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of course, some of the words that appear in the reviews occur very infrequently and so likely don't contain much information for the purposes of sentiment analysis. The way we will deal with this problem is that we will fix the size of our working vocabulary and we will only include the words that appear most frequently. We will then combine all of the infrequent words into a single category and, in our case, we will label it as `1`.\n\nSince we will be using a recurrent neural network, it will be convenient if the length of each review is the same. To do this, we will fix a size for our reviews and then pad short reviews with the category 'no word' (which we will label `0`) and truncate long reviews.", "_____no_output_____" ], [ "### (TODO) Create a word dictionary\n\nTo begin with, we need to construct a way to map words that appear in the reviews to integers. Here we fix the size of our vocabulary (including the 'no word' and 'infrequent' categories) to be `5000` but you may wish to change this to see how it affects the model.\n\n> **TODO:** Complete the implementation for the `build_dict()` method below. Note that even though the vocab_size is set to `5000`, we only want to construct a mapping for the most frequently appearing `4998` words. This is because we want to reserve the special labels `0` for 'no word' and `1` for 'infrequent word'.", "_____no_output_____" ] ], [ [ "import numpy as np\n\ndef build_dict(data, vocab_size = 5000):\n \"\"\"Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer.\"\"\"\n \n # TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and that a\n # sentence is a list of words.\n \n word_count = {} # A dict storing the words that appear in the reviews along with how often they occur\n for review in data:\n for word in review:\n if word in word_count:\n word_count[word] += 1\n else:\n word_count[word] = 1\n \n # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and\n # sorted_words[-1] is the least frequently appearing word.\n sorted_dict = sorted(word_count.items(), key = lambda x:x[1], reverse = True)\n sorted_words = [w for w, v in sorted_dict]\n sorted_dict = None\n \n word_dict = {} # This is what we are building, a dictionary that translates words into integers\n for idx, word in enumerate(sorted_words[:vocab_size - 2]): # The -2 is so that we save room for the 'no word'\n word_dict[word] = idx + 2 # 'infrequent' labels\n \n return word_dict", "_____no_output_____" ], [ "word_dict = build_dict(train_X)", "_____no_output_____" ] ], [ [ "**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set?", "_____no_output_____" ], [ "**Answer:**['movi', 'film', 'one', 'like', 'time']", "_____no_output_____" ] ], [ [ "# TODO: Use this space to determine the five most frequently appearing words in the training set.\nimport numpy as np\n\ndef most_freq(data, vocab_size = 5000):\n \"\"\"Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer.\"\"\"\n \n # TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and that a\n # sentence is a list of words.\n \n word_count = {} # A dict storing the words that appear in the reviews along with how often they occur\n for review in data:\n for word in review:\n if word in word_count:\n word_count[word] += 1\n else:\n word_count[word] = 1\n \n # TODO: Sort the words found in `data` so that sorted_words[0] is the most frequently appearing word and\n # sorted_words[-1] is the least frequently appearing word.\n sorted_dict = sorted(word_count.items(), key = lambda x:x[1], reverse = True)\n sorted_words = [w for w, v in sorted_dict]\n sorted_dict = None\n \n return sorted_words[:5]\n\nmost_freq(train_X)", "_____no_output_____" ] ], [ [ "### Save `word_dict`\n\nLater on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use.", "_____no_output_____" ] ], [ [ "data_dir = '../data/pytorch' # The folder we will use for storing data\nif not os.path.exists(data_dir): # Make sure that the folder exists\n os.makedirs(data_dir)", "_____no_output_____" ], [ "with open(os.path.join(data_dir, 'word_dict.pkl'), \"wb\") as f:\n pickle.dump(word_dict, f)", "_____no_output_____" ] ], [ [ "### Transform the reviews\n\nNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`.", "_____no_output_____" ] ], [ [ "def convert_and_pad(word_dict, sentence, pad=500):\n NOWORD = 0 # We will use 0 to represent the 'no word' category\n INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict\n \n working_sentence = [NOWORD] * pad\n \n for word_index, word in enumerate(sentence[:pad]):\n if word in word_dict:\n working_sentence[word_index] = word_dict[word]\n else:\n working_sentence[word_index] = INFREQ\n \n return working_sentence, min(len(sentence), pad)\n\ndef convert_and_pad_data(word_dict, data, pad=500):\n result = []\n lengths = []\n \n for sentence in data:\n converted, leng = convert_and_pad(word_dict, sentence, pad)\n result.append(converted)\n lengths.append(leng)\n \n return np.array(result), np.array(lengths)", "_____no_output_____" ], [ "train_X, train_X_len = convert_and_pad_data(word_dict, train_X)\ntest_X, test_X_len = convert_and_pad_data(word_dict, test_X)", "_____no_output_____" ] ], [ [ "As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set?", "_____no_output_____" ] ], [ [ "# Use this cell to examine one of the processed reviews to make sure everything is working as intended.\nprint(train_X[100], train_X_len[100])", "[1621 1 1 1 7 223 3270 228 468 1082 925 102 517 6\n 235 3225 1597 1539 3035 2796 10 1 3157 3966 580 1386 157 465\n 523 1182 668 581 758 454 1763 1 1621 4104 10 180 1 1929\n 1235 1407 915 887 3012 72 1414 1 4 1128 45 314 877 3155\n 1 227 3712 1 247 4915 116 1735 502 3880 1401 835 3736 2301\n 1364 3880 397 528 34 14 54 191 173 770 78 214 1545 331\n 949 3012 131 208 11 1 1 834 1 4 925 3011 2151 1\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0] 98\n" ] ], [ [ "**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem?", "_____no_output_____" ], [ "**Answer:** It's standard to process both training and testing set in the same way. And only training data is used to built the dictionary. ", "_____no_output_____" ], [ "## Step 3: Upload the data to S3\n\nAs in the XGBoost notebook, we will need to upload the training dataset to S3 in order for our training code to access it. For now we will save it locally and we will upload to S3 later on.\n\n### Save the processed training dataset locally\n\nIt is important to note the format of the data that we are saving as we will need to know it when we write the training code. In our case, each row of the dataset has the form `label`, `length`, `review[500]` where `review[500]` is a sequence of `500` integers representing the words in the review.", "_____no_output_____" ] ], [ [ "import pandas as pd\n \npd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \\\n .to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)", "_____no_output_____" ] ], [ [ "### Uploading the training data\n\n\nNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model.", "_____no_output_____" ] ], [ [ "import sagemaker\n\nsagemaker_session = sagemaker.Session()\n\nbucket = sagemaker_session.default_bucket()\nprefix = 'sagemaker/sentiment_rnn'\n\nrole = sagemaker.get_execution_role()", "_____no_output_____" ], [ "input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)", "_____no_output_____" ] ], [ [ "**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also in the S3 training bucket) and that we will need to make sure it gets saved in the model directory.", "_____no_output_____" ], [ "## Step 4: Build and Train the PyTorch Model\n\nIn the XGBoost notebook we discussed what a model is in the SageMaker framework. In particular, a model comprises three objects\n\n - Model Artifacts,\n - Training Code, and\n - Inference Code,\n \neach of which interact with one another. In the XGBoost example we used training and inference code that was provided by Amazon. Here we will still be using containers provided by Amazon with the added benefit of being able to include our own custom code.\n\nWe will start by implementing our own neural network in PyTorch along with a training script. For the purposes of this project we have provided the necessary model object in the `model.py` file, inside of the `train` folder. You can see the provided implementation by running the cell below.", "_____no_output_____" ] ], [ [ "!pygmentize train/model.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.nn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\r\n\u001b[34mclass\u001b[39;49;00m \u001b[04m\u001b[32mLSTMClassifier\u001b[39;49;00m(nn.Module):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m This is the simple RNN model we will be using to perform Sentiment Analysis.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32m__init__\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, embedding_dim, hidden_dim, vocab_size):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Initialize the model by settingg up the various layers.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n \u001b[36msuper\u001b[39;49;00m(LSTMClassifier, \u001b[36mself\u001b[39;49;00m).\u001b[32m__init__\u001b[39;49;00m()\r\n\r\n \u001b[36mself\u001b[39;49;00m.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=\u001b[34m0\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.lstm = nn.LSTM(embedding_dim, hidden_dim)\r\n \u001b[36mself\u001b[39;49;00m.dense = nn.Linear(in_features=hidden_dim, out_features=\u001b[34m1\u001b[39;49;00m)\r\n \u001b[36mself\u001b[39;49;00m.sig = nn.Sigmoid()\r\n \r\n \u001b[36mself\u001b[39;49;00m.word_dict = \u001b[36mNone\u001b[39;49;00m\r\n\r\n \u001b[34mdef\u001b[39;49;00m \u001b[32mforward\u001b[39;49;00m(\u001b[36mself\u001b[39;49;00m, x):\r\n \u001b[33m\"\"\"\u001b[39;49;00m\r\n\u001b[33m Perform a forward pass of our model on some input.\u001b[39;49;00m\r\n\u001b[33m \"\"\"\u001b[39;49;00m\r\n x = x.t()\r\n lengths = x[\u001b[34m0\u001b[39;49;00m,:]\r\n reviews = x[\u001b[34m1\u001b[39;49;00m:,:]\r\n embeds = \u001b[36mself\u001b[39;49;00m.embedding(reviews)\r\n lstm_out, _ = \u001b[36mself\u001b[39;49;00m.lstm(embeds)\r\n out = \u001b[36mself\u001b[39;49;00m.dense(lstm_out)\r\n out = out[lengths - \u001b[34m1\u001b[39;49;00m, \u001b[36mrange\u001b[39;49;00m(\u001b[36mlen\u001b[39;49;00m(lengths))]\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mself\u001b[39;49;00m.sig(out.squeeze())\r\n" ] ], [ [ "The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training script so that if we wish to modify them we do not need to modify the script itself. We will see how to do this later on. To start we will write some of the training code in the notebook so that we can more easily diagnose any issues that arise.\n\nFirst we will load a small portion of the training data set to use as a sample. It would be very time consuming to try and train the model completely in the notebook as we do not have access to a gpu and the compute instance that we are using is not particularly powerful. However, we can work on a small bit of the data to get a feel for how our training script is behaving.", "_____no_output_____" ] ], [ [ "import torch\nimport torch.utils.data\n\n# Read in only the first 250 rows\ntrain_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250)\n\n# Turn the input pandas dataframe into tensors\ntrain_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze()\ntrain_sample_X = torch.from_numpy(train_sample.drop([0], axis=1).values).long()\n\n# Build the dataset\ntrain_sample_ds = torch.utils.data.TensorDataset(train_sample_X, train_sample_y)\n# Build the dataloader\ntrain_sample_dl = torch.utils.data.DataLoader(train_sample_ds, batch_size=50)", "_____no_output_____" ] ], [ [ "### (TODO) Writing the training method\n\nNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later.", "_____no_output_____" ] ], [ [ "def train(model, train_loader, epochs, optimizer, loss_fn, device):\n for epoch in range(1, epochs + 1):\n model.train()\n total_loss = 0\n for batch in train_loader: \n batch_X, batch_y = batch\n \n batch_X = batch_X.to(device)\n batch_y = batch_y.to(device)\n \n # TODO: Complete this train method to train the model provided.\n optimizer.zero_grad()\n out = model.forward(batch_X)\n loss = loss_fn(out, batch_y)\n loss.backward()\n optimizer.step()\n \n total_loss += loss.data.item()\n print(\"Epoch: {}, BCELoss: {}\".format(epoch, total_loss / len(train_loader)))", "_____no_output_____" ] ], [ [ "Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early when they are easier to diagnose.", "_____no_output_____" ] ], [ [ "import torch.optim as optim\nfrom train.model import LSTMClassifier\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = LSTMClassifier(32, 100, 5000).to(device)\noptimizer = optim.Adam(model.parameters())\nloss_fn = torch.nn.BCELoss()\n\ntrain(model, train_sample_dl, 5, optimizer, loss_fn, device)", "Epoch: 1, BCELoss: 0.6982725143432618\nEpoch: 2, BCELoss: 0.6882477641105652\nEpoch: 3, BCELoss: 0.6797678351402283\nEpoch: 4, BCELoss: 0.6705798029899597\nEpoch: 5, BCELoss: 0.6596575975418091\n" ] ], [ [ "In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one) for a `requirements.txt` file and install any required Python libraries, after which the training script will be run.", "_____no_output_____" ], [ "### (TODO) Training the model\n\nWhen a PyTorch model is constructed in SageMaker, an entry point must be specified. This is the Python file which will be executed when the model is trained. Inside of the `train` directory is a file called `train.py` which has been provided and which contains most of the necessary code to train our model. The only thing that is missing is the implementation of the `train()` method which you wrote earlier in this notebook.\n\n**TODO**: Copy the `train()` method written above and paste it into the `train/train.py` file where required.\n\nThe way that SageMaker passes hyperparameters to the training script is by way of arguments. These arguments can then be parsed and used in the training script. To see how this is done take a look at the provided `train/train.py` file.", "_____no_output_____" ] ], [ [ "from sagemaker.pytorch import PyTorch\n\nestimator = PyTorch(entry_point=\"train.py\",\n source_dir=\"train\",\n role=role,\n framework_version='0.4.0',\n train_instance_count=1,\n train_instance_type='ml.p2.xlarge',\n hyperparameters={\n 'epochs': 10,\n 'hidden_dim': 200,\n })", "_____no_output_____" ], [ "estimator.fit({'training': input_data})", "2020-02-17 21:36:37 Starting - Starting the training job...\n2020-02-17 21:36:38 Starting - Launching requested ML instances...\n2020-02-17 21:37:36 Starting - Preparing the instances for training.........\n2020-02-17 21:38:50 Downloading - Downloading input data...\n2020-02-17 21:39:25 Training - Downloading the training image...\n2020-02-17 21:39:55 Training - Training image download completed. Training in progress.\u001b[34mbash: cannot set terminal process group (-1): Inappropriate ioctl for device\u001b[0m\n\u001b[34mbash: no job control in this shell\u001b[0m\n\u001b[34m2020-02-17 21:39:56,470 sagemaker-containers INFO Imported framework sagemaker_pytorch_container.training\u001b[0m\n\u001b[34m2020-02-17 21:39:56,494 sagemaker_pytorch_container.training INFO Block until all host DNS lookups succeed.\u001b[0m\n\u001b[34m2020-02-17 21:39:57,115 sagemaker_pytorch_container.training INFO Invoking user training script.\u001b[0m\n\u001b[34m2020-02-17 21:39:57,344 sagemaker-containers INFO Module train does not provide a setup.py. \u001b[0m\n\u001b[34mGenerating setup.py\u001b[0m\n\u001b[34m2020-02-17 21:39:57,344 sagemaker-containers INFO Generating setup.cfg\u001b[0m\n\u001b[34m2020-02-17 21:39:57,345 sagemaker-containers INFO Generating MANIFEST.in\u001b[0m\n\u001b[34m2020-02-17 21:39:57,345 sagemaker-containers INFO Installing module with the following command:\u001b[0m\n\u001b[34m/usr/bin/python -m pip install -U . -r requirements.txt\u001b[0m\n\u001b[34mProcessing /opt/ml/code\u001b[0m\n\u001b[34mCollecting pandas (from -r requirements.txt (line 1))\u001b[0m\n\u001b[34m Downloading https://files.pythonhosted.org/packages/74/24/0cdbf8907e1e3bc5a8da03345c23cbed7044330bb8f73bb12e711a640a00/pandas-0.24.2-cp35-cp35m-manylinux1_x86_64.whl (10.0MB)\u001b[0m\n\u001b[34mCollecting numpy (from -r requirements.txt (line 2))\n Downloading https://files.pythonhosted.org/packages/52/e6/1715e592ef47f28f3f50065322423bb75619ed2f7c24be86380ecc93503c/numpy-1.18.1-cp35-cp35m-manylinux1_x86_64.whl (19.9MB)\u001b[0m\n\u001b[34mCollecting nltk (from -r requirements.txt (line 3))\n Downloading https://files.pythonhosted.org/packages/f6/1d/d925cfb4f324ede997f6d47bea4d9babba51b49e87a767c170b77005889d/nltk-3.4.5.zip (1.5MB)\u001b[0m\n\u001b[34mCollecting beautifulsoup4 (from -r requirements.txt (line 4))\n Downloading https://files.pythonhosted.org/packages/cb/a1/c698cf319e9cfed6b17376281bd0efc6bfc8465698f54170ef60a485ab5d/beautifulsoup4-4.8.2-py3-none-any.whl (106kB)\u001b[0m\n\u001b[34mCollecting html5lib (from -r requirements.txt (line 5))\n Downloading https://files.pythonhosted.org/packages/a5/62/bbd2be0e7943ec8504b517e62bab011b4946e1258842bc159e5dfde15b96/html5lib-1.0.1-py2.py3-none-any.whl (117kB)\u001b[0m\n\u001b[34mRequirement already satisfied, skipping upgrade: python-dateutil>=2.5.0 in /usr/local/lib/python3.5/dist-packages (from pandas->-r requirements.txt (line 1)) (2.7.5)\u001b[0m\n\u001b[34mCollecting pytz>=2011k (from pandas->-r requirements.txt (line 1))\n Downloading https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl (509kB)\u001b[0m\n\u001b[34mRequirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.5/dist-packages (from nltk->-r requirements.txt (line 3)) (1.11.0)\u001b[0m\n\u001b[34mCollecting soupsieve>=1.2 (from beautifulsoup4->-r requirements.txt (line 4))\n Downloading https://files.pythonhosted.org/packages/81/94/03c0f04471fc245d08d0a99f7946ac228ca98da4fa75796c507f61e688c2/soupsieve-1.9.5-py2.py3-none-any.whl\u001b[0m\n\u001b[34mCollecting webencodings (from html5lib->-r requirements.txt (line 5))\n Downloading https://files.pythonhosted.org/packages/f4/24/2a3e3df732393fed8b3ebf2ec078f05546de641fe1b667ee316ec1dcf3b7/webencodings-0.5.1-py2.py3-none-any.whl\u001b[0m\n\u001b[34mBuilding wheels for collected packages: nltk, train\n Running setup.py bdist_wheel for nltk: started\u001b[0m\n\u001b[34m Running setup.py bdist_wheel for nltk: finished with status 'done'\n Stored in directory: /root/.cache/pip/wheels/96/86/f6/68ab24c23f207c0077381a5e3904b2815136b879538a24b483\n Running setup.py bdist_wheel for train: started\n Running setup.py bdist_wheel for train: finished with status 'done'\n Stored in directory: /tmp/pip-ephem-wheel-cache-mb9ae02t/wheels/35/24/16/37574d11bf9bde50616c67372a334f94fa8356bc7164af8ca3\u001b[0m\n\u001b[34mSuccessfully built nltk train\u001b[0m\n\u001b[34mInstalling collected packages: numpy, pytz, pandas, nltk, soupsieve, beautifulsoup4, webencodings, html5lib, train\n Found existing installation: numpy 1.15.4\n Uninstalling numpy-1.15.4:\n Successfully uninstalled numpy-1.15.4\u001b[0m\n\u001b[34mSuccessfully installed beautifulsoup4-4.8.2 html5lib-1.0.1 nltk-3.4.5 numpy-1.18.1 pandas-0.24.2 pytz-2019.3 soupsieve-1.9.5 train-1.0.0 webencodings-0.5.1\u001b[0m\n\u001b[34mYou are using pip version 18.1, however version 20.0.2 is available.\u001b[0m\n\u001b[34mYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\u001b[34m2020-02-17 21:40:09,665 sagemaker-containers INFO Invoking user script\n\u001b[0m\n\u001b[34mTraining Env:\n\u001b[0m\n\u001b[34m{\n \"hyperparameters\": {\n \"epochs\": 10,\n \"hidden_dim\": 200\n },\n \"log_level\": 20,\n \"framework_module\": \"sagemaker_pytorch_container.training:main\",\n \"module_name\": \"train\",\n \"channel_input_dirs\": {\n \"training\": \"/opt/ml/input/data/training\"\n },\n \"current_host\": \"algo-1\",\n \"module_dir\": \"s3://sagemaker-us-east-2-248217655556/sagemaker-pytorch-2020-02-17-21-36-36-650/source/sourcedir.tar.gz\",\n \"output_intermediate_dir\": \"/opt/ml/output/intermediate\",\n \"output_data_dir\": \"/opt/ml/output/data\",\n \"network_interface_name\": \"eth0\",\n \"hosts\": [\n \"algo-1\"\n ],\n \"input_config_dir\": \"/opt/ml/input/config\",\n \"additional_framework_parameters\": {},\n \"input_dir\": \"/opt/ml/input\",\n \"output_dir\": \"/opt/ml/output\",\n \"model_dir\": \"/opt/ml/model\",\n \"num_cpus\": 4,\n \"resource_config\": {\n \"current_host\": \"algo-1\",\n \"hosts\": [\n \"algo-1\"\n ],\n \"network_interface_name\": \"eth0\"\n },\n \"job_name\": \"sagemaker-pytorch-2020-02-17-21-36-36-650\",\n \"user_entry_point\": \"train.py\",\n \"input_data_config\": {\n \"training\": {\n \"RecordWrapperType\": \"None\",\n \"TrainingInputMode\": \"File\",\n \"S3DistributionType\": \"FullyReplicated\"\n }\n },\n \"num_gpus\": 1\u001b[0m\n\u001b[34m}\n\u001b[0m\n\u001b[34mEnvironment variables:\n\u001b[0m\n\u001b[34mSM_CHANNEL_TRAINING=/opt/ml/input/data/training\u001b[0m\n\u001b[34mSM_HPS={\"epochs\":10,\"hidden_dim\":200}\u001b[0m\n\u001b[34mSM_NETWORK_INTERFACE_NAME=eth0\u001b[0m\n\u001b[34mSM_USER_ENTRY_POINT=train.py\u001b[0m\n\u001b[34mSM_FRAMEWORK_MODULE=sagemaker_pytorch_container.training:main\u001b[0m\n\u001b[34mSM_OUTPUT_DATA_DIR=/opt/ml/output/data\u001b[0m\n\u001b[34mSM_OUTPUT_DIR=/opt/ml/output\u001b[0m\n\u001b[34mSM_LOG_LEVEL=20\u001b[0m\n\u001b[34mSM_OUTPUT_INTERMEDIATE_DIR=/opt/ml/output/intermediate\u001b[0m\n\u001b[34mSM_NUM_CPUS=4\u001b[0m\n\u001b[34mSM_CURRENT_HOST=algo-1\u001b[0m\n\u001b[34mSM_INPUT_DATA_CONFIG={\"training\":{\"RecordWrapperType\":\"None\",\"S3DistributionType\":\"FullyReplicated\",\"TrainingInputMode\":\"File\"}}\u001b[0m\n\u001b[34mSM_HOSTS=[\"algo-1\"]\u001b[0m\n\u001b[34mSM_INPUT_CONFIG_DIR=/opt/ml/input/config\u001b[0m\n\u001b[34mSM_RESOURCE_CONFIG={\"current_host\":\"algo-1\",\"hosts\":[\"algo-1\"],\"network_interface_name\":\"eth0\"}\u001b[0m\n\u001b[34mSM_HP_EPOCHS=10\u001b[0m\n\u001b[34mSM_INPUT_DIR=/opt/ml/input\u001b[0m\n\u001b[34mSM_FRAMEWORK_PARAMS={}\u001b[0m\n\u001b[34mSM_TRAINING_ENV={\"additional_framework_parameters\":{},\"channel_input_dirs\":{\"training\":\"/opt/ml/input/data/training\"},\"current_host\":\"algo-1\",\"framework_module\":\"sagemaker_pytorch_container.training:main\",\"hosts\":[\"algo-1\"],\"hyperparameters\":{\"epochs\":10,\"hidden_dim\":200},\"input_config_dir\":\"/opt/ml/input/config\",\"input_data_config\":{\"training\":{\"RecordWrapperType\":\"None\",\"S3DistributionType\":\"FullyReplicated\",\"TrainingInputMode\":\"File\"}},\"input_dir\":\"/opt/ml/input\",\"job_name\":\"sagemaker-pytorch-2020-02-17-21-36-36-650\",\"log_level\":20,\"model_dir\":\"/opt/ml/model\",\"module_dir\":\"s3://sagemaker-us-east-2-248217655556/sagemaker-pytorch-2020-02-17-21-36-36-650/source/sourcedir.tar.gz\",\"module_name\":\"train\",\"network_interface_name\":\"eth0\",\"num_cpus\":4,\"num_gpus\":1,\"output_data_dir\":\"/opt/ml/output/data\",\"output_dir\":\"/opt/ml/output\",\"output_intermediate_dir\":\"/opt/ml/output/intermediate\",\"resource_config\":{\"current_host\":\"algo-1\",\"hosts\":[\"algo-1\"],\"network_interface_name\":\"eth0\"},\"user_entry_point\":\"train.py\"}\u001b[0m\n\u001b[34mSM_MODULE_NAME=train\u001b[0m\n\u001b[34mSM_MODEL_DIR=/opt/ml/model\u001b[0m\n\u001b[34mSM_HP_HIDDEN_DIM=200\u001b[0m\n\u001b[34mSM_MODULE_DIR=s3://sagemaker-us-east-2-248217655556/sagemaker-pytorch-2020-02-17-21-36-36-650/source/sourcedir.tar.gz\u001b[0m\n\u001b[34mSM_CHANNELS=[\"training\"]\u001b[0m\n\u001b[34mSM_USER_ARGS=[\"--epochs\",\"10\",\"--hidden_dim\",\"200\"]\u001b[0m\n\u001b[34mSM_NUM_GPUS=1\u001b[0m\n\u001b[34mPYTHONPATH=/usr/local/bin:/usr/lib/python35.zip:/usr/lib/python3.5:/usr/lib/python3.5/plat-x86_64-linux-gnu:/usr/lib/python3.5/lib-dynload:/usr/local/lib/python3.5/dist-packages:/usr/lib/python3/dist-packages\n\u001b[0m\n\u001b[34mInvoking script with the following command:\n\u001b[0m\n\u001b[34m/usr/bin/python -m train --epochs 10 --hidden_dim 200\n\n\u001b[0m\n\u001b[34mUsing device cuda.\u001b[0m\n\u001b[34mGet train data loader.\u001b[0m\n" ] ], [ [ "## Step 5: Testing the model\n\nAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly.\n\n## Step 6: Deploy the model for testing\n\nNow that we have trained our model, we would like to test it to see how it performs. Currently our model takes input of the form `review_length, review[500]` where `review[500]` is a sequence of `500` integers which describe the words present in the review, encoded using `word_dict`. Fortunately for us, SageMaker provides built-in inference code for models with simple inputs such as this.\n\nThere is one thing that we need to provide, however, and that is a function which loads the saved model. This function must be called `model_fn()` and takes as its only parameter a path to the directory where the model artifacts are stored. This function must also be present in the python file which we specified as the entry point. In our case the model loading function has been provided and so no changes need to be made.\n\n**NOTE**: When the built-in inference code is run it must import the `model_fn()` method from the `train.py` file. This is why the training code is wrapped in a main guard ( ie, `if __name__ == '__main__':` )\n\nSince we don't need to change anything in the code that was uploaded during training, we can simply deploy the current model as-is.\n\n**NOTE:** When deploying a model you are asking SageMaker to launch an compute instance that will wait for data to be sent to it. As a result, this compute instance will continue to run until *you* shut it down. This is important to know since the cost of a deployed endpoint depends on how long it has been running for.\n\nIn other words **If you are no longer using a deployed endpoint, shut it down!**\n\n**TODO:** Deploy the trained model.", "_____no_output_____" ] ], [ [ "# TODO: Deploy the trained model\npredictor = estimator.deploy(initial_instance_count = 1, instance_type = 'ml.m4.xlarge')", "-----------!" ] ], [ [ "## Step 7 - Use the model for testing\n\nOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is.", "_____no_output_____" ] ], [ [ "test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1)", "_____no_output_____" ], [ "# We split the data into chunks and send each chunk seperately, accumulating the results.\n\ndef predict(data, rows=512):\n split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))\n predictions = np.array([])\n for array in split_array:\n predictions = np.append(predictions, predictor.predict(array))\n \n return predictions", "_____no_output_____" ], [ "predictions = predict(test_X.values)\npredictions = [round(num) for num in predictions]", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(test_y, predictions)", "_____no_output_____" ] ], [ [ "**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis?", "_____no_output_____" ], [ "**Answer:**It's better precision and it makes sense for the following reasons\n1. RNN model will learn from early input and build up prediction power. \n2. Sentimental analysis is context dependent project, and RNN suits better for this purpose. \n3. The order of text (word) matters. ", "_____no_output_____" ], [ "### (TODO) More testing\n\nWe now have a trained model which has been deployed and which we can send processed reviews to and which returns the predicted sentiment. However, ultimately we would like to be able to send our model an unprocessed review. That is, we would like to send the review itself as a string. For example, suppose we wish to send the following review to our model.", "_____no_output_____" ] ], [ [ "test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.'", "_____no_output_____" ] ], [ [ "The question we now need to answer is, how do we send this review to our model?\n\nRecall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews.\n - Removed any html tags and stemmed the input\n - Encoded the review as a sequence of integers using `word_dict`\n \nIn order process the review we will need to repeat these two steps.\n\n**TODO**: Using the `review_to_words` and `convert_and_pad` methods from section one, convert `test_review` into a numpy array `test_data` suitable to send to our model. Remember that our model expects input of the form `review_length, review[500]`.", "_____no_output_____" ] ], [ [ "# TODO: Convert test_review into a form usable by the model and save the results in test_data\ntest_data = review_to_words(test_review)\ntest_data = [np.array(convert_and_pad(word_dict, test_data)[0])]", "_____no_output_____" ] ], [ [ "Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review.", "_____no_output_____" ] ], [ [ "predictor.predict(test_data)", "_____no_output_____" ] ], [ [ "Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive.", "_____no_output_____" ], [ "### Delete the endpoint\n\nOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delete it.", "_____no_output_____" ] ], [ [ "estimator.delete_endpoint()", "_____no_output_____" ] ], [ [ "## Step 6 (again) - Deploy the model for the web app\n\nNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.\n\nAs we saw above, by default the estimator which we created, when deployed, will use the entry script and directory which we provided when creating the model. However, since we now wish to accept a string as input and our model expects a processed review, we need to write some custom inference code.\n\nWe will store the code that we write in the `serve` directory. Provided in this directory is the `model.py` file that we used to construct our model, a `utils.py` file which contains the `review_to_words` and `convert_and_pad` pre-processing functions which we used during the initial data processing, and `predict.py`, the file which will contain our custom inference code. Note also that `requirements.txt` is present which will tell SageMaker what Python libraries are required by our custom inference code.\n\nWhen deploying a PyTorch model in SageMaker, you are expected to provide four functions which the SageMaker inference container will use.\n - `model_fn`: This function is the same function that we used in the training script and it tells SageMaker how to load our model.\n - `input_fn`: This function receives the raw serialized input that has been sent to the model's endpoint and its job is to de-serialize and make the input available for the inference code.\n - `output_fn`: This function takes the output of the inference code and its job is to serialize this output and return it to the caller of the model's endpoint.\n - `predict_fn`: The heart of the inference script, this is where the actual prediction is done and is the function which you will need to complete.\n\nFor the simple website that we are constructing during this project, the `input_fn` and `output_fn` methods are relatively straightforward. We only require being able to accept a string as input and we expect to return a single value as output. You might imagine though that in a more complex application the input or output may be image data or some other binary data which would require some effort to serialize.\n\n### (TODO) Writing inference code\n\nBefore writing our custom inference code, we will begin by taking a look at the code which has been provided.", "_____no_output_____" ] ], [ [ "!pygmentize serve/predict.py", "\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36margparse\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mjson\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mos\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpickle\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msys\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36msagemaker_containers\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mpandas\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mpd\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mnumpy\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnp\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.nn\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36mnn\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.optim\u001b[39;49;00m \u001b[34mas\u001b[39;49;00m \u001b[04m\u001b[36moptim\u001b[39;49;00m\r\n\u001b[34mimport\u001b[39;49;00m \u001b[04m\u001b[36mtorch.utils.data\u001b[39;49;00m\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mmodel\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m LSTMClassifier\r\n\r\n\u001b[34mfrom\u001b[39;49;00m \u001b[04m\u001b[36mutils\u001b[39;49;00m \u001b[34mimport\u001b[39;49;00m review_to_words, convert_and_pad\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mmodel_fn\u001b[39;49;00m(model_dir):\r\n \u001b[33m\"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\u001b[39;49;00m\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mLoading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n\r\n \u001b[37m# First, load the parameters used to create the model.\u001b[39;49;00m\r\n model_info = {}\r\n model_info_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel_info.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_info_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model_info = torch.load(f)\r\n\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mmodel_info: {}\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m.format(model_info))\r\n\r\n \u001b[37m# Determine the device and construct the model.\u001b[39;49;00m\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n model = LSTMClassifier(model_info[\u001b[33m'\u001b[39;49;00m\u001b[33membedding_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mhidden_dim\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m], model_info[\u001b[33m'\u001b[39;49;00m\u001b[33mvocab_size\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m])\r\n\r\n \u001b[37m# Load the store model parameters.\u001b[39;49;00m\r\n model_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mmodel.pth\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(model_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.load_state_dict(torch.load(f))\r\n\r\n \u001b[37m# Load the saved word_dict.\u001b[39;49;00m\r\n word_dict_path = os.path.join(model_dir, \u001b[33m'\u001b[39;49;00m\u001b[33mword_dict.pkl\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mwith\u001b[39;49;00m \u001b[36mopen\u001b[39;49;00m(word_dict_path, \u001b[33m'\u001b[39;49;00m\u001b[33mrb\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m) \u001b[34mas\u001b[39;49;00m f:\r\n model.word_dict = pickle.load(f)\r\n\r\n model.to(device).eval()\r\n\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m\"\u001b[39;49;00m\u001b[33mDone loading model.\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m model\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32minput_fn\u001b[39;49;00m(serialized_input_data, content_type):\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mDeserializing the input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mif\u001b[39;49;00m content_type == \u001b[33m'\u001b[39;49;00m\u001b[33mtext/plain\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m:\r\n data = serialized_input_data.decode(\u001b[33m'\u001b[39;49;00m\u001b[33mutf-8\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m data\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mRequested unsupported ContentType in content_type: \u001b[39;49;00m\u001b[33m'\u001b[39;49;00m + content_type)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32moutput_fn\u001b[39;49;00m(prediction_output, accept):\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mSerializing the generated output.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \u001b[34mreturn\u001b[39;49;00m \u001b[36mstr\u001b[39;49;00m(prediction_output)\r\n\r\n\u001b[34mdef\u001b[39;49;00m \u001b[32mpredict_fn\u001b[39;49;00m(input_data, model):\r\n \u001b[34mprint\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mInferring sentiment of input data.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n\r\n device = torch.device(\u001b[33m\"\u001b[39;49;00m\u001b[33mcuda\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m \u001b[34mif\u001b[39;49;00m torch.cuda.is_available() \u001b[34melse\u001b[39;49;00m \u001b[33m\"\u001b[39;49;00m\u001b[33mcpu\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\r\n \r\n \u001b[34mif\u001b[39;49;00m model.word_dict \u001b[35mis\u001b[39;49;00m \u001b[36mNone\u001b[39;49;00m:\r\n \u001b[34mraise\u001b[39;49;00m \u001b[36mException\u001b[39;49;00m(\u001b[33m'\u001b[39;49;00m\u001b[33mModel has not been loaded properly, no word_dict.\u001b[39;49;00m\u001b[33m'\u001b[39;49;00m)\r\n \r\n \u001b[37m# TODO: Process input_data so that it is ready to be sent to our model.\u001b[39;49;00m\r\n \u001b[37m# You should produce two variables:\u001b[39;49;00m\r\n \u001b[37m# data_X - A sequence of length 500 which represents the converted review\u001b[39;49;00m\r\n \u001b[37m# data_len - The length of the review\u001b[39;49;00m\r\n \r\n data_X, data_len = convert_and_pad(model.word_dict, review_to_words(input_data))\r\n\r\n \u001b[37m# Using data_X and data_len we construct an appropriate input tensor. Remember\u001b[39;49;00m\r\n \u001b[37m# that our model expects input data of the form 'len, review[500]'.\u001b[39;49;00m\r\n data_pack = np.hstack((data_len, data_X))\r\n data_pack = data_pack.reshape(\u001b[34m1\u001b[39;49;00m, -\u001b[34m1\u001b[39;49;00m)\r\n \r\n data = torch.from_numpy(data_pack)\r\n data = data.to(device)\r\n\r\n \u001b[37m# Make sure to put the model into evaluation mode\u001b[39;49;00m\r\n model.eval()\r\n\r\n \u001b[37m# TODO: Compute the result of applying the model to the input data. The variable `result` should\u001b[39;49;00m\r\n \u001b[37m# be a numpy array which contains a single integer which is either 1 or 0\u001b[39;49;00m\r\n \u001b[34mwith\u001b[39;49;00m torch.no_grad():\r\n output = model.forward(data)\r\n \r\n result = np.round(output.numpy())\r\n\r\n \u001b[34mreturn\u001b[39;49;00m result\r\n" ] ], [ [ "As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory.\n\n**TODO**: Complete the `predict_fn()` method in the `serve/predict.py` file.", "_____no_output_____" ], [ "### Deploying the model\n\nNow that the custom inference code has been written, we will create and deploy our model. To begin with, we need to construct a new PyTorchModel object which points to the model artifacts created during training and also points to the inference code that we wish to use. Then we can call the deploy method to launch the deployment container.\n\n**NOTE**: The default behaviour for a deployed PyTorch model is to assume that any input passed to the predictor is a `numpy` array. In our case we want to send a string so we need to construct a simple wrapper around the `RealTimePredictor` class to accomodate simple strings. In a more complicated situation you may want to provide a serialization object, for example if you wanted to sent image data.", "_____no_output_____" ] ], [ [ "from sagemaker.predictor import RealTimePredictor\nfrom sagemaker.pytorch import PyTorchModel\n\nclass StringPredictor(RealTimePredictor):\n def __init__(self, endpoint_name, sagemaker_session):\n super(StringPredictor, self).__init__(endpoint_name, sagemaker_session, content_type='text/plain')\n\nmodel = PyTorchModel(model_data=estimator.model_data,\n role = role,\n framework_version='0.4.0',\n entry_point='predict.py',\n source_dir='serve',\n predictor_cls=StringPredictor)\npredictor = model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "-----------!" ] ], [ [ "### Testing the model\n\nNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is that the amount of time it takes for our model to process the input and then perform inference is quite long and so testing the entire data set would be prohibitive.", "_____no_output_____" ] ], [ [ "import glob\n\ndef test_reviews(data_dir='../data/aclImdb', stop=250):\n \n results = []\n ground = []\n \n # We make sure to test both positive and negative reviews \n for sentiment in ['pos', 'neg']:\n \n path = os.path.join(data_dir, 'test', sentiment, '*.txt')\n files = glob.glob(path)\n \n files_read = 0\n \n print('Starting ', sentiment, ' files')\n \n # Iterate through the files and send them to the predictor\n for f in files:\n with open(f) as review:\n # First, we store the ground truth (was the review positive or negative)\n if sentiment == 'pos':\n ground.append(1)\n else:\n ground.append(0)\n # Read in the review and convert to 'utf-8' for transmission via HTTP\n review_input = review.read().encode('utf-8')\n # Send the review to the predictor and store the results\n results.append(float(predictor.predict(review_input)))\n \n # Sending reviews to our endpoint one at a time takes a while so we\n # only send a small number of reviews\n files_read += 1\n if files_read == stop:\n break\n \n return ground, results", "_____no_output_____" ], [ "ground, results = test_reviews()", "Starting pos files\nStarting neg files\n" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(ground, results)", "_____no_output_____" ] ], [ [ "As an additional test, we can try sending the `test_review` that we looked at earlier.", "_____no_output_____" ] ], [ [ "predictor.predict(test_review)", "_____no_output_____" ] ], [ [ "Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back.", "_____no_output_____" ], [ "## Step 7 (again): Use the model for the web app\n\n> **TODO:** This entire section and the next contain tasks for you to complete, mostly using the AWS console.\n\nSo far we have been accessing our model endpoint by constructing a predictor object which uses the endpoint and then just using the predictor object to perform inference. What if we wanted to create a web app which accessed our model? The way things are set up currently makes that not possible since in order to access a SageMaker endpoint the app would first have to authenticate with AWS using an IAM role which included access to SageMaker endpoints. However, there is an easier way! We just need to use some additional AWS services.\n\n<img src=\"Web App Diagram.svg\">\n\nThe diagram above gives an overview of how the various services will work together. On the far right is the model which we trained above and which is deployed using SageMaker. On the far left is our web app that collects a user's movie review, sends it off and expects a positive or negative sentiment in return.\n\nIn the middle is where some of the magic happens. We will construct a Lambda function, which you can think of as a straightforward Python function that can be executed whenever a specified event occurs. We will give this function permission to send and recieve data from a SageMaker endpoint.\n\nLastly, the method we will use to execute the Lambda function is a new endpoint that we will create using API Gateway. This endpoint will be a url that listens for data to be sent to it. Once it gets some data it will pass that data on to the Lambda function and then return whatever the Lambda function returns. Essentially it will act as an interface that lets our web app communicate with the Lambda function.\n\n### Setting up a Lambda function\n\nThe first thing we are going to do is set up a Lambda function. This Lambda function will be executed whenever our public API has data sent to it. When it is executed it will receive the data, perform any sort of processing that is required, send the data (the review) to the SageMaker endpoint we've created and then return the result.\n\n#### Part A: Create an IAM Role for the Lambda function\n\nSince we want the Lambda function to call a SageMaker endpoint, we need to make sure that it has permission to do so. To do this, we will construct a role that we can later give the Lambda function.\n\nUsing the AWS Console, navigate to the **IAM** page and click on **Roles**. Then, click on **Create role**. Make sure that the **AWS service** is the type of trusted entity selected and choose **Lambda** as the service that will use this role, then click **Next: Permissions**.\n\nIn the search box type `sagemaker` and select the check box next to the **AmazonSageMakerFullAccess** policy. Then, click on **Next: Review**.\n\nLastly, give this role a name. Make sure you use a name that you will remember later on, for example `LambdaSageMakerRole`. Then, click on **Create role**.\n\n#### Part B: Create a Lambda function\n\nNow it is time to actually create the Lambda function.\n\nUsing the AWS Console, navigate to the AWS Lambda page and click on **Create a function**. When you get to the next page, make sure that **Author from scratch** is selected. Now, name your Lambda function, using a name that you will remember later on, for example `sentiment_analysis_func`. Make sure that the **Python 3.6** runtime is selected and then choose the role that you created in the previous part. Then, click on **Create Function**.\n\nOn the next page you will see some information about the Lambda function you've just created. If you scroll down you should see an editor in which you can write the code that will be executed when your Lambda function is triggered. In our example, we will use the code below. \n\n```python\n# We need to use the low-level library to interact with SageMaker since the SageMaker API\n# is not available natively through Lambda.\nimport boto3\n\ndef lambda_handler(event, context):\n\n # The SageMaker runtime is what allows us to invoke the endpoint that we've created.\n runtime = boto3.Session().client('sagemaker-runtime')\n\n # Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given\n response = runtime.invoke_endpoint(EndpointName = '**ENDPOINT NAME HERE**', # The name of the endpoint we created\n ContentType = 'text/plain', # The data format that is expected\n Body = event['body']) # The actual review\n\n # The response is an HTTP response whose body contains the result of our inference\n result = response['Body'].read().decode('utf-8')\n\n return {\n 'statusCode' : 200,\n 'headers' : { 'Content-Type' : 'text/plain', 'Access-Control-Allow-Origin' : '*' },\n 'body' : result\n }\n```\n\nOnce you have copy and pasted the code above into the Lambda code editor, replace the `**ENDPOINT NAME HERE**` portion with the name of the endpoint that we deployed earlier. You can determine the name of the endpoint using the code cell below.", "_____no_output_____" ] ], [ [ "predictor.endpoint", "_____no_output_____" ] ], [ [ "Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function.\n\n### Setting up API Gateway\n\nNow that our Lambda function is set up, it is time to create a new API using API Gateway that will trigger the Lambda function we have just created.\n\nUsing AWS Console, navigate to **Amazon API Gateway** and then click on **Get started**.\n\nOn the next page, make sure that **New API** is selected and give the new api a name, for example, `sentiment_analysis_api`. Then, click on **Create API**.\n\nNow we have created an API, however it doesn't currently do anything. What we want it to do is to trigger the Lambda function that we created earlier.\n\nSelect the **Actions** dropdown menu and click **Create Method**. A new blank method will be created, select its dropdown menu and select **POST**, then click on the check mark beside it.\n\nFor the integration point, make sure that **Lambda Function** is selected and click on the **Use Lambda Proxy integration**. This option makes sure that the data that is sent to the API is then sent directly to the Lambda function with no processing. It also means that the return value must be a proper response object as it will also not be processed by API Gateway.\n\nType the name of the Lambda function you created earlier into the **Lambda Function** text entry box and then click on **Save**. Click on **OK** in the pop-up box that then appears, giving permission to API Gateway to invoke the Lambda function you created.\n\nThe last step in creating the API Gateway is to select the **Actions** dropdown and click on **Deploy API**. You will need to create a new Deployment stage and name it anything you like, for example `prod`.\n\nYou have now successfully set up a public API to access your SageMaker model. Make sure to copy or write down the URL provided to invoke your newly created public API as this will be needed in the next step. This URL can be found at the top of the page, highlighted in blue next to the text **Invoke URL**.", "_____no_output_____" ], [ "## Step 4: Deploying our web app\n\nNow that we have a publicly available API, we can start using it in a web app. For our purposes, we have provided a simple static html file which can make use of the public api you created earlier.\n\nIn the `website` folder there should be a file called `index.html`. Download the file to your computer and open that file up in a text editor of your choice. There should be a line which contains **\\*\\*REPLACE WITH PUBLIC API URL\\*\\***. Replace this string with the url that you wrote down in the last step and then save the file.\n\nNow, if you open `index.html` on your local computer, your browser will behave as a local web server and you can use the provided site to interact with your SageMaker model.\n\nIf you'd like to go further, you can host this html file anywhere you'd like, for example using github or hosting a static site on Amazon's S3. Once you have done this you can share the link with anyone you'd like and have them play with it too!\n\n> **Important Note** In order for the web app to communicate with the SageMaker endpoint, the endpoint has to actually be deployed and running. This means that you are paying for it. Make sure that the endpoint is running when you want to use the web app but that you shut it down when you don't need it, otherwise you will end up with a surprisingly large AWS bill.\n\n**TODO:** Make sure that you include the edited `index.html` file in your project submission.", "_____no_output_____" ], [ "Now that your web app is working, trying playing around with it and see how well it works.\n\n**Question**: Give an example of a review that you entered into your web app. What was the predicted sentiment of your example review?", "_____no_output_____" ], [ "**Answer:**I tried something simple 'This is a good movie' And the result is positive. \nI got another movie review from internet --- \"The questions are fascinating, the performances are great and the emotions are jacked up to the point of discomfort. This is certainly the best work of Plaza's film career. \"\nAnd it's positive as well. Looks like the web app is working fine!", "_____no_output_____" ], [ "### Delete the endpoint\n\nRemember to always shut down your endpoint if you are no longer using it. You are charged for the length of time that the endpoint is running so if you forget and leave it on you could end up with an unexpectedly large bill.", "_____no_output_____" ] ], [ [ "predictor.delete_endpoint()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
cb2522e259932832528353a7cc422b4fa46ad60c
21,965
ipynb
Jupyter Notebook
2nd-ML100Days/homework/D-033/Day_033_HW.ipynb
qwerzxcv98/100Day-ML-Marathon
3c86cd083b086a1e4b7a55a41b127909c7860f79
[ "MIT" ]
3
2019-08-22T15:19:11.000Z
2019-08-24T00:54:54.000Z
2nd-ML100Days/homework/D-033/Day_033_HW.ipynb
magikerwin1993/100Day-ML-Marathon
3c86cd083b086a1e4b7a55a41b127909c7860f79
[ "MIT" ]
null
null
null
2nd-ML100Days/homework/D-033/Day_033_HW.ipynb
magikerwin1993/100Day-ML-Marathon
3c86cd083b086a1e4b7a55a41b127909c7860f79
[ "MIT" ]
1
2019-07-18T01:52:04.000Z
2019-07-18T01:52:04.000Z
238.75
20,105
0.934578
[ [ [ "## 練習時間", "_____no_output_____" ], [ "請觀看李宏毅教授以神奇寶貝進化 CP 值預測的範例,解說何謂機器學習與過擬合。並回答以下問題", "_____no_output_____" ] ], [ [ "from IPython.display import YouTubeVideo\nYouTubeVideo(\"fegAeph9UaA\", width=720, height=480)", "_____no_output_____" ] ], [ [ "### 1. 模型的泛化能力 (generalization) 是指什麼? \n 即模型在未知環境表現程度,泛化能力好的模型越能適應未看過的資料。\n\n### 2. 分類問題與回歸問題分別可用的目標函數有哪些?\n 分類問題:sigomid/softmax cross entropy\n 回歸問題:L1/L2 norm", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
cb25252fb68245c04c64dc26428d32cfa024f004
6,563
ipynb
Jupyter Notebook
Metode Numerik/4. Metode Iterasi Sederhana.ipynb
rakhid16/Ngampus-
d4034a6ea990b302c33cb39e3e695b0da0beec7c
[ "MIT" ]
null
null
null
Metode Numerik/4. Metode Iterasi Sederhana.ipynb
rakhid16/Ngampus-
d4034a6ea990b302c33cb39e3e695b0da0beec7c
[ "MIT" ]
null
null
null
Metode Numerik/4. Metode Iterasi Sederhana.ipynb
rakhid16/Ngampus-
d4034a6ea990b302c33cb39e3e695b0da0beec7c
[ "MIT" ]
null
null
null
23.355872
83
0.506171
[ [ [ "### Impor modul math", "_____no_output_____" ] ], [ [ "from math import log", "_____no_output_____" ] ], [ [ "### Minta <i>input</i>", "_____no_output_____" ] ], [ [ "e = 2.718281828459045235360287471352\nx = float(input(\"Masukkan nilai x : \"))\ntotSal = float(input(\"Masukkan toleransi kesalahan : \"))", "Masukkan nilai x : 3\nMasukkan toleransi kesalahan : 0.00000001\n" ] ], [ [ "### Masukkan rumus fungsi dan rumus galat ke dalam variabel", "_____no_output_____" ] ], [ [ "gx = log(x**2+8) # BISA DIGANTI DENGAN FUNGSI YANG LAIN\nerr = ((gx-x)/gx)*100 ", "_____no_output_____" ] ], [ [ "### Jika nilai error kurang dari 0 maka nilai error tersebut dikali dengan -1", "_____no_output_____" ] ], [ [ "if (err < 0):\n err=err*(-1)", "_____no_output_____" ] ], [ [ "### buat fungsi untuk mencetak nilai", "_____no_output_____" ] ], [ [ "def cetak():\n print(\"Nilai x : \", x)\n print(\"Nilai gx : \",gx)\n print(\"Error-rate : \", err)\n print(\"\")\ncetak()", "Nilai x : 3.0\nNilai gx : 2.833213344056216\nError-rate : 5.886837159428347\n\n" ] ], [ [ "### Lakukan iterasi sampai nilai error lebih kecil dari toleransi kesalahan", "_____no_output_____" ] ], [ [ "while(err>totSal):\n x=gx\n gx = log(x**2+8) # BISA DIGANTI DENGAN FUNGSI YANG LAIN\n err = ((gx-x)/gx)*100 \n \n if (err < 0):\n err=err*(-1)\n \n cetak()", "Nilai x : 2.833213344056216\nNilai gx : 2.774280905498397\nError-rate : 2.1242419410745366\n\nNilai x : 2.774280905498397\nNilai gx : 2.7534463290326796\nError-rate : 0.756672692183422\n\nNilai x : 2.7534463290326796\nNilai gx : 2.7460821750916136\nError-rate : 0.26816946731830277\n\nNilai x : 2.7460821750916136\nNilai gx : 2.7434795896146094\nError-rate : 0.09486440091831713\n\nNilai x : 2.7434795896146094\nNilai gx : 2.742559851182632\nError-rate : 0.03353576519326834\n\nNilai x : 2.742559851182632\nNilai gx : 2.742234827335726\nError-rate : 0.011852516920357898\n\nNilai x : 2.742234827335726\nNilai gx : 2.7421199688495235\nError-rate : 0.0041886747300377185\n\nNilai x : 2.7421199688495235\nNilai gx : 2.742079379707308\nError-rate : 0.0014802322104769774\n\nNilai x : 2.742079379707308\nNilai gx : 2.7420650361696732\nError-rate : 0.000523092539592003\n\nNilai x : 2.7420650361696732\nNilai gx : 2.742059967400126\nError-rate : 0.00018485261472989\n\nNilai x : 2.742059967400126\nNilai gx : 2.7420581761807936\nError-rate : 6.532389968870696e-05\n\nNilai x : 2.7420581761807936\nNilai gx : 2.742057543193529\nError-rate : 2.3084390274634812e-05\n\nNilai x : 2.742057543193529\nNilai gx : 2.742057319506309\nError-rate : 8.157642010863094e-06\n\nNilai x : 2.742057319506309\nNilai gx : 2.7420572404589496\nError-rate : 2.8827756823783855e-06\n\nNilai x : 2.7420572404589496\nNilai gx : 2.7420572125249216\nError-rate : 1.018725205733539e-06\n\nNilai x : 2.7420572125249216\nNilai gx : 2.742057202653499\nError-rate : 3.6000061489398504e-07\n\nNilai x : 2.742057202653499\nNilai gx : 2.7420571991651013\nError-rate : 1.2721826415100639e-07\n\nNilai x : 2.7420571991651013\nNilai gx : 2.7420571979323594\nError-rate : 4.4956826921109315e-08\n\nNilai x : 2.7420571979323594\nNilai gx : 2.7420571974967287\nError-rate : 1.588700057269933e-08\n\nNilai x : 2.7420571974967287\nNilai gx : 2.7420571973427843\nError-rate : 5.614194077429353e-09\n\n" ] ], [ [ "### Cetak nilai taksiran X", "_____no_output_____" ] ], [ [ "print(\"Nilai akar yg dicari : \", x)", "Nilai akar yg dicari : 2.7420571974967287\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" ] ]
cb2526780817698f2a5dd865c3d701c15f818f26
27,397
ipynb
Jupyter Notebook
myHDL_DigLogicFundamentals/.ipynb_checkpoints/myHDL_Latches-checkpoint.ipynb
PyLCARS/PythonUberHDL
f7ae2293d6efaca7986d62540798cdf061383d06
[ "BSD-3-Clause" ]
31
2017-10-09T12:15:14.000Z
2022-02-28T09:05:21.000Z
myHDL_DigLogicFundamentals/myHDL_Latches.ipynb
cfelton/PythonUberHDL
f7ae2293d6efaca7986d62540798cdf061383d06
[ "BSD-3-Clause" ]
null
null
null
myHDL_DigLogicFundamentals/myHDL_Latches.ipynb
cfelton/PythonUberHDL
f7ae2293d6efaca7986d62540798cdf061383d06
[ "BSD-3-Clause" ]
12
2018-02-09T15:36:20.000Z
2021-04-20T21:39:12.000Z
27.098912
648
0.432529
[ [ [ "\\title{Digital Latches with myHDL}\n\\author{Steven K Armour}\n\\maketitle", "_____no_output_____" ], [ "# Refs\n@book{brown_vranesic_2014, place={New York, NY}, edition={3}, title={Fundamentals of digital logic with Verilog design}, publisher={McGraw-Hill}, author={Brown, Stephen and Vranesic, Zvonko G}, year={2014} },\n@book{lameres_2017, title={Introduction to logic circuits & logic design with Verilog}, publisher={springer}, author={LaMeres, Brock J}, year={2017} }", "_____no_output_____" ], [ "# Acknowledgments\n\nAuthor of **myHDL** [Jan Decaluwe](http://www.myhdl.org/users/jandecaluwe.html) and the author of the **myHDL Peeker** [XESS Corp.](https://github.com/xesscorp/myhdlpeek)\n\n[**Draw.io**](https://www.draw.io/)\n\n**Xilinx**", "_____no_output_____" ], [ "# Python Libraries Utilized", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nfrom sympy import *\ninit_printing()\n\nfrom myhdl import *\nfrom myhdlpeek import *\nimport random\n\n#python file of convince tools. Should be located with this notebook\nfrom sympy_myhdl_tools import *", "_____no_output_____" ] ], [ [ "# Latches vs Flip-Flops\n\nLatches and Flip-Flops are both metastaple logic circuit tobologies in that once loaded with a state they hold that state information till that state is upset by a new state or a reset command. But the diffrance between the two is that Flip-Flops are clock controlled devices built upon Latches where as Latches are not clock dependent", "_____no_output_____" ], [ "# SR-Latch", "_____no_output_____" ], [ "## Symbol and Internals\nThe Symbol for a SR-Latch and one representation of it's internals is shown below\n<img style=\"float: center;\" src=\"SRLatchSymbolInternal.jpg\">", "_____no_output_____" ], [ "## Definition", "_____no_output_____" ], [ "## State Diagram", "_____no_output_____" ], [ "## myHDL SR-Latch Gate and Testing\n", "_____no_output_____" ], [ "Need Help Getting this Latch via Combo Cirucits working geting AlwayCombError in using out signal as argument in out signals next state out", "_____no_output_____" ] ], [ [ "def LatchCombo(S_in, rst, Q_out):\n \n\n @always_comb\n def logic():\n Q_out.next=(not rst) and (S_in or Q_out)\n return logic", "_____no_output_____" ], [ "Peeker.clear()\nS_in, rst, Q_out=[Signal(bool(0)) for _ in range(3)]\nPeeker(S_in, 'S_in'); Peeker(rst, 'rst')\nPeeker(Q_out, 'Q_out')\n\nDUT=LatchCombo(S_in=S_in, rst=rst, Q_out=Q_out)\n\ninputs=[S_in, rst]\nsim=Simulation(DUT, Combo_TB(inputs), *Peeker.instances()).run() \nPeeker.to_wavedrom(start_time=0, stop_time=2*2**len(inputs), tock=True,\n title='AND 2 gate simulation',\n caption=f'after clock cycle {2**len(inputs)-1} ->random input')", "_____no_output_____" ] ], [ [ "## myHDL SR-Latch Behavioral and Testing", "_____no_output_____" ] ], [ [ "def SRLatch(S_in, rst, Q_out, Qn_out):\n @always_comb\n def logic():\n if S_in and rst==0:\n Q_out.next=1\n Qn_out.next=0\n \n elif S_in==0 and rst:\n Q_out.next=0\n Qn_out.next=1\n\n elif S_in and rst:\n Q_out.next=0\n Qn_out.next=0\n\n return logic", "_____no_output_____" ], [ "S_in, rst, Q_out, Qn_out=[Signal(bool(0)) for _ in range(4)]\nPeeker.clear()\n\nPeeker(S_in, 'S_in'); Peeker(rst, 'rst')\nPeeker(Q_out, 'Q_out'); Peeker(Qn_out, 'Qn_out')\n\nDUT=SRLatch(S_in=S_in, rst=rst, Q_out=Q_out, Qn_out=Qn_out)\ninputs=[S_in, rst]\nsim=Simulation(DUT, Combo_TB(inputs), *Peeker.instances()).run() \nPeeker.to_wavedrom(start_time=0, stop_time=2*2**len(inputs), tock=True,\n title='SRLatch Behavioral simulation',\n caption=f'after clock cycle {2**len(inputs)-1} ->random input')\n", "<class 'myhdl.StopSimulation'>: No more events\n" ], [ "MakeDFfromPeeker(Peeker.to_wavejson(start_time=0, stop_time=2**len(inputs) -1))", "_____no_output_____" ] ], [ [ "## myHDL SR-Latch Behavioral HDL Synthesis", "_____no_output_____" ] ], [ [ "toVerilog(SRLatch, S_in, rst, Q_out, Qn_out)\n#toVHDL(SRLatch, S_in, rst, Q_out, Qn_out)\n_=VerilogTextReader('SRLatch')", "***Verilog modual from SRLatch.v***\n\n // File: SRLatch.v\n// Generated by MyHDL 0.9.0\n// Date: Thu Oct 26 00:40:43 2017\n\n\n`timescale 1ns/10ps\n\nmodule SRLatch (\n S_in,\n rst,\n Q_out,\n Qn_out\n);\n\n\ninput S_in;\ninput rst;\noutput Q_out;\nreg Q_out;\noutput Qn_out;\nreg Qn_out;\n\n\n\n\n\n\nalways @(rst, S_in) begin: SRLATCH_LOGIC\n if ((S_in && (rst == 0))) begin\n Q_out = 1;\n Qn_out = 0;\n end\n else if (((S_in == 0) && rst)) begin\n Q_out = 0;\n Qn_out = 1;\n end\n else if ((S_in && rst)) begin\n Q_out = 0;\n Qn_out = 0;\n end\nend\n\nendmodule\n\n" ] ], [ [ "The following shows the **Xilinx**'s _Vivado 2016.1_ RTL generated schematic of our Behaviorla SRLatch from the synthesised verilog code. We can see that the systhizied version is quite apstract from fig lakdfjkaj. \n<img style=\"float: center;\" src=\"SRLatchBehaviroalRTLSch.PNG\">", "_____no_output_____" ], [ "# Gated SR-Latch", "_____no_output_____" ], [ "## myHDL SR-Latch Behavioral and Testing", "_____no_output_____" ] ], [ [ "def GSRLatch(S_in, rst, ena, Q_out, Qn_out):\n @always_comb\n def logic():\n if ena:\n if S_in and rst==0:\n Q_out.next=1\n Qn_out.next=0\n\n elif S_in==0 and rst:\n Q_out.next=0\n Qn_out.next=1\n\n elif S_in and rst:\n Q_out.next=0\n Qn_out.next=0\n else:\n pass\n\n return logic", "_____no_output_____" ], [ "S_in, rst, ena, Q_out, Qn_out=[Signal(bool(0)) for _ in range(5)]\nPeeker.clear()\n\nPeeker(S_in, 'S_in'); Peeker(rst, 'rst'); Peeker(ena, 'ena')\nPeeker(Q_out, 'Q_out'); Peeker(Qn_out, 'Qn_out')\n\nDUT=GSRLatch(S_in=S_in, rst=rst, ena=ena, Q_out=Q_out, Qn_out=Qn_out)\ninputs=[S_in, rst, ena]\nsim=Simulation(DUT, Combo_TB(inputs), *Peeker.instances()).run() \nPeeker.to_wavedrom(start_time=0, stop_time=2*2**len(inputs), tock=True,\n title='GSRLatch Behavioral simulation',\n caption=f'after clock cycle {2**len(inputs)-1} ->random input')\n", "<class 'myhdl.StopSimulation'>: No more events\n" ], [ "MakeDFfromPeeker(Peeker.to_wavejson(start_time=0, stop_time=2**len(inputs) -1))", "_____no_output_____" ] ], [ [ "## myHDL SR-Latch Behavioral HDL Synthesis", "_____no_output_____" ] ], [ [ "toVerilog(GSRLatch, S_in, rst, ena, Q_out, Qn_out)\n#toVHDL(GSRLatch, S_in, rst,ena, Q_out, Qn_out)\n_=VerilogTextReader('GSRLatch')", "***Verilog modual from GSRLatch.v***\n\n // File: GSRLatch.v\n// Generated by MyHDL 0.9.0\n// Date: Thu Oct 26 00:40:44 2017\n\n\n`timescale 1ns/10ps\n\nmodule GSRLatch (\n S_in,\n rst,\n ena,\n Q_out,\n Qn_out\n);\n\n\ninput S_in;\ninput rst;\ninput ena;\noutput Q_out;\nreg Q_out;\noutput Qn_out;\nreg Qn_out;\n\n\n\n\n\n\nalways @(ena, S_in, rst) begin: GSRLATCH_LOGIC\n if (ena) begin\n if ((S_in && (rst == 0))) begin\n Q_out = 1;\n Qn_out = 0;\n end\n else if (((S_in == 0) && rst)) begin\n Q_out = 0;\n Qn_out = 1;\n end\n else if ((S_in && rst)) begin\n Q_out = 0;\n Qn_out = 0;\n end\n end\n else begin\n // pass\n end\nend\n\nendmodule\n\n" ] ], [ [ "The following shows the **Xilinx**'s _Vivado 2016.1_ RTL generated schematic of our Behaviorla Gated SRLatch from the synthesised verilog code. We can see that the systhizied version is quite apstract from fig lakdfjkaj. \n<img style=\"float: center;\" src=\"GSRLatchBehaviroalRTLSch.PNG\">", "_____no_output_____" ], [ "# D-Latch", "_____no_output_____" ], [ "## myHDL Behavioral D-Latch and Testing", "_____no_output_____" ] ], [ [ "def DLatch(D_in, ena, Q_out, Qn_out):\n #Normal Qn_out is not specifed since a not gate is so easily implimented\n @always_comb\n def logic():\n if ena:\n Q_out.next=D_in\n Qn_out.next=not D_in\n return logic", "_____no_output_____" ], [ "D_in, ena, Q_out, Qn_out=[Signal(bool(0)) for _ in range(4)]\n\nPeeker.clear()\n\nPeeker(D_in, 'D_in'); Peeker(ena, 'ena')\nPeeker(Q_out, 'Q_out'); Peeker(Qn_out, 'Qn_out')\n\nDUT=DLatch(D_in=D_in, ena=ena, Q_out=Q_out, Qn_out=Qn_out)\ninputs=[D_in, ena]\nsim=Simulation(DUT, Combo_TB(inputs), *Peeker.instances()).run() \nPeeker.to_wavedrom(start_time=0, stop_time=2*2**len(inputs), tock=True,\n title='DLatch Behavioral simulation',\n caption=f'after clock cycle {2**len(inputs)-1} ->random input')\n", "<class 'myhdl.StopSimulation'>: No more events\n" ], [ "MakeDFfromPeeker(Peeker.to_wavejson(start_time=0, stop_time=2**len(inputs) -1))", "_____no_output_____" ] ], [ [ "## myHDL DLatch Behavioral HDL Synthesis", "_____no_output_____" ] ], [ [ "toVerilog(DLatch, D_in, ena, Q_out, Qn_out)\n#toVHDL(DLatch,D_in, ena, Q_out, Qn_out)\n_=VerilogTextReader('DLatch')", "***Verilog modual from DLatch.v***\n\n // File: DLatch.v\n// Generated by MyHDL 0.9.0\n// Date: Thu Oct 26 00:40:46 2017\n\n\n`timescale 1ns/10ps\n\nmodule DLatch (\n D_in,\n ena,\n Q_out,\n Qn_out\n);\n\n\ninput D_in;\ninput ena;\noutput Q_out;\nreg Q_out;\noutput Qn_out;\nreg Qn_out;\n\n\n\n\n\n\nalways @(ena, D_in) begin: DLATCH_LOGIC\n if (ena) begin\n Q_out = D_in;\n Qn_out = (!D_in);\n end\nend\n\nendmodule\n\n" ] ], [ [ "The following shows the **Xilinx**'s _Vivado 2016.1_ RTL generated schematic of our myHDL Dlatch with a exsplisit $\\bar{Q}$ verilog code. Note that becouse $\\bar{Q}$ is not normal declared in HDL code Vivado produced two RTL DLatchs and used a NOT Gate to acount for the negated output\n<img style=\"float: center;\" src=\"DLatchBehavioralRTLSch.PNG\">", "_____no_output_____" ], [ "# Examples", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "raw", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "raw", "raw" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
cb2533166c7c209704d6f1820dd00b93c874473e
7,345
ipynb
Jupyter Notebook
ezmode/pytti-tools_vqgan.ipynb
pytti-tools/pytti-notebook
a04ea6aaf00d0f825392f1e0ec455cb0063de751
[ "MIT" ]
48
2022-01-27T22:00:32.000Z
2022-03-26T08:59:03.000Z
ezmode/pytti-tools_vqgan.ipynb
pytti-tools/pytti-notebook
a04ea6aaf00d0f825392f1e0ec455cb0063de751
[ "MIT" ]
33
2022-01-26T20:21:09.000Z
2022-03-30T21:26:03.000Z
ezmode/pytti-tools_vqgan.ipynb
pytti-tools/pytti-notebook
a04ea6aaf00d0f825392f1e0ec455cb0063de751
[ "MIT" ]
18
2022-01-27T22:00:35.000Z
2022-03-20T19:12:33.000Z
26.046099
131
0.528387
[ [ [ "%%capture\n# { display-mode: 'form' }\n\n# @title PyTTI-Tools [EzMode]: VQGAN\n\n# @markdown ## Setup\n\n# @markdown This may take a few minutes. \n\n## 1. Install stuff\n\ntry: \n import pytti\nexcept ImportError:\n !pip install kornia pytorch-lightning transformers\n !pip install jupyter loguru einops PyGLM ftfy regex tqdm hydra-core exrex\n !pip install seaborn adjustText bunch matplotlib-label-lines\n !pip install --upgrade gdown\n\n !pip install --upgrade git+https://github.com/pytti-tools/AdaBins.git\n !pip install --upgrade git+https://github.com/pytti-tools/GMA.git\n !pip install --upgrade git+https://github.com/pytti-tools/taming-transformers.git\n !pip install --upgrade git+https://github.com/openai/CLIP.git\n !pip install --upgrade git+https://github.com/pytti-tools/pytti-core.git\n\n # These are notebook specific\n !pip install --upgrade natsort\n\ntry:\n import mmc\nexcept:\n # install mmc\n !git clone https://github.com/dmarx/Multi-Modal-Comparators\n !pip install poetry\n !cd Multi-Modal-Comparators; poetry build\n !cd Multi-Modal-Comparators; pip install dist/mmc*.whl\n !python Multi-Modal-Comparators/src/mmc/napm_installs/__init__.py\n\nfrom natsort import natsorted\nfrom omegaconf import OmegaConf\nfrom pathlib import Path\n\nimport mmc.loaders\n!python -m pytti.warmup\n\nnotebook_params = {}\n\ndef get_output_paths():\n outv = [str(p.resolve()) for p in Path('outputs/').glob('**/*.png')]\n #outv.sort()\n outv = natsorted(outv)\n return outv", "_____no_output_____" ], [ "resume = True # @param {type:\"boolean\"}\n\nif resume:\n inits = get_output_paths()\n if inits:\n notebook_params.update({\n 'init_image':inits[-1],\n })", "_____no_output_____" ], [ "# @markdown ## Basic Settings\n\nprompts = \"a photograph of albert einstein\" # @param {type:\"string\"}\nheight = 512 # @param {type:\"integer\"}\nwidth = 512 # @param {type:\"integer\"}\n\ncell_params = {\n \"scenes\": prompts,\n \"height\":height,\n \"width\":width,\n}\n\nnotebook_params.update(cell_params)", "_____no_output_____" ], [ "# @markdown ## Advanced Settings\n\nvqgan_model = \"coco\" # @param [\"coco\",\"sflickr\",\"imagenet\",\"wikiart\",\"openimages\"]\n\ncell_params = {\n \"vqgan_model\": vqgan_model,\n}\n\nnotebook_params.update(cell_params)", "_____no_output_____" ], [ "invariants = \"\"\"\n## Invariant settings ##\n\nsteps_per_frame: 50\nsteps_per_scene: 500\n\npixel_size: 1\n\nimage_model: VQGAN\n\nuse_mmc: true\nmmc_models:\n- architecture: clip\n publisher: openai\n id: ViT-B/16\n\"\"\"", "_____no_output_____" ], [ "from omegaconf import OmegaConf\nfrom pathlib import Path\n\ncfg_invariants = OmegaConf.create(invariants)\nnb_cfg = OmegaConf.create(notebook_params)\nconf = OmegaConf.merge(cfg_invariants, nb_cfg)\n\nwith open(\"config/conf/this_run.yaml\", \"w\") as f:\n outstr = \"# @package _global_\\n\"\n outstr += OmegaConf.to_yaml(conf)\n print(outstr)\n f.write(\n outstr\n )\n\n\n#Path(\"config/conf/ezmode/\").mkdir(parents=True, exist_ok=True)", "_____no_output_____" ], [ "## Do the run\n! python -m pytti.workhorse conf=this_run", "_____no_output_____" ], [ "# @title Show Outputs\nfrom IPython.display import Image, display\n\noutputs = list(Path('outputs/').glob('**/*.png'))\noutputs.sort()\nim_path = str(outputs[-1])\n\nImage(im_path, height=height, width=width)", "_____no_output_____" ], [ "# @markdown compile images into a video of the generative process\n\nfrom PIL import Image as pilImage\nfrom subprocess import Popen, PIPE\nfrom tqdm.notebook import tqdm\n\nfps = 12 # @param {type:'number'}\n\nfpaths = get_output_paths()\n\nframes = []\n\nfor filename in tqdm(fpaths):\n frames.append(pilImage.open(filename))\n\ncmd_in = ['ffmpeg', '-y', '-f', 'image2pipe', '-vcodec', 'png', '-r', str(fps), '-i', '-']\ncmd_out = ['-vcodec', 'libx264', '-r', str(fps), '-pix_fmt', 'yuv420p', '-crf', '1', '-preset', 'veryslow', f'output.mp4']\n\ncmd = cmd_in + cmd_out\n\np = Popen(cmd, stdin=PIPE)\nfor im in tqdm(frames):\n im.save(p.stdin, 'PNG')\np.stdin.close()\n\nprint(\"Encoding video...\")\np.wait()\nprint(\"Video saved to output.mp4.\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb254004866897303a19b07f57880c2c9d259b1f
9,962
ipynb
Jupyter Notebook
05_Merge/Housing Market/Exercises.ipynb
zoharri/pandas_exercises
7bb3808de3125c51a0e80cc33a92f8c67a9825f6
[ "BSD-3-Clause" ]
null
null
null
05_Merge/Housing Market/Exercises.ipynb
zoharri/pandas_exercises
7bb3808de3125c51a0e80cc33a92f8c67a9825f6
[ "BSD-3-Clause" ]
null
null
null
05_Merge/Housing Market/Exercises.ipynb
zoharri/pandas_exercises
7bb3808de3125c51a0e80cc33a92f8c67a9825f6
[ "BSD-3-Clause" ]
null
null
null
24.004819
174
0.365991
[ [ [ "# Housing Market", "_____no_output_____" ], [ "### Introduction:\n\nThis time we will create our own dataset with fictional numbers to describe a house market. As we are going to create random data don't try to reason of the numbers.\n\n### Step 1. Import the necessary libraries", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ] ], [ [ "### Step 2. Create 3 differents Series, each of length 100, as follows: \n1. The first a random number from 1 to 4 \n2. The second a random number from 1 to 3\n3. The third a random number from 10,000 to 30,000", "_____no_output_____" ] ], [ [ "s1 = pd.Series(np.random.randint(1, high=5, size=100, dtype='l'))\ns2 = pd.Series(np.random.randint(1, high=4, size=100, dtype='l'))\ns3 = pd.Series(np.random.randint(10000 , high=30001, size=100, dtype='l'))", "_____no_output_____" ] ], [ [ "### Step 3. Let's create a DataFrame by joinning the Series by column", "_____no_output_____" ] ], [ [ "df = pd.concat([s1,s2,s3], axis=1)\ndf.head()", "_____no_output_____" ] ], [ [ "### Step 4. Change the name of the columns to bedrs, bathrs, price_sqr_meter", "_____no_output_____" ] ], [ [ "df = df.rename(columns = {0: 'bedrs', 1: 'bathrs', 2: 'price_sqr_meter'})\ndf.head()", "_____no_output_____" ] ], [ [ "### Step 5. Create a one column DataFrame with the values of the 3 Series and assign it to 'bigcolumn'", "_____no_output_____" ] ], [ [ "bigcolumn = pd.DataFrame(pd.concat([s1,s2,s3]))", "_____no_output_____" ] ], [ [ "### Step 6. Oops, it seems it is going only until index 99. Is it true?", "_____no_output_____" ] ], [ [ "len(bigcolumn)", "_____no_output_____" ] ], [ [ "### Step 7. Reindex the DataFrame so it goes from 0 to 299", "_____no_output_____" ] ], [ [ "bigcolumn = bigcolumn.reset_index(drop=True)\nbigcolumn", "_____no_output_____" ] ] ]
[ "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" ] ]
cb25500d8decd46a1c090d311a4813d15ef4c109
21,829
ipynb
Jupyter Notebook
_doc/notebooks/td2a_ml/td2a_clustering.ipynb
Jerome-maker/ensae_teaching_cs
43ea044361ee60c00c85aea354a7b25c21c0fd07
[ "MIT" ]
73
2015-05-12T13:12:11.000Z
2021-12-21T11:44:29.000Z
_doc/notebooks/td2a_ml/td2a_clustering.ipynb
Pandinosaurus/ensae_teaching_cs
3bc80f29d93c30de812e34c314bc96e6a4f0d025
[ "MIT" ]
90
2015-06-23T11:11:35.000Z
2021-03-31T22:09:15.000Z
_doc/notebooks/td2a_ml/td2a_clustering.ipynb
Pandinosaurus/ensae_teaching_cs
3bc80f29d93c30de812e34c314bc96e6a4f0d025
[ "MIT" ]
65
2015-01-13T08:23:55.000Z
2022-02-11T22:42:07.000Z
44.367886
732
0.348481
[ [ [ "# 2A.ml - Clustering\n\nCe notebook utilise les données des vélos de Chicago [Divvy Data](https://www.divvybikes.com/system-data). Il s'inspire du challenge créée pour découvrir les habitudes des habitantes de la ville [City Bike](http://www.xavierdupre.fr/app/ensae_projects/helpsphinx/challenges/city_bike.html). L'idée est d'explorer plusieurs algorithmes de clustering et de voire comment trafiquer les données pour les faire marcher et en tirer quelques apprentissages.", "_____no_output_____" ] ], [ [ "from jyquickhelper import add_notebook_menu\nadd_notebook_menu()", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "## Les données\n\nElles ont été prétraitées selon le notebook [Bike Pattern 2](http://www.xavierdupre.fr/app/ensae_projects/helpsphinx/notebooks/city_bike_solution_cluster_start.html). Elles représentent la distribution du nombre de vélos partant (*startdist*) et arrivant (*stopdist*). On utilise le clustering pour découvrir les différents usages des habitants de Chicago avec pour intuition le fait que les habitants de Chicago utilise majoritairement les vélos pour aller et venir entre leur appartement et leur lieu de travail. Cette même idée mais à Paris est illustrée par ce billet de blog : [Busy areas in Paris](http://www.xavierdupre.fr/blog/2013-09-26_nojs.html).", "_____no_output_____" ] ], [ [ "from pyensae.datasource import download_data\nfile = download_data(\"features_bike_chicago.zip\")\nfile", "_____no_output_____" ], [ "import pandas\nfeatures = pandas.read_csv(\"features_bike_chicago.txt\", sep=\"\\t\", encoding=\"utf-8\", low_memory=False, header=[0,1])\nfeatures.columns = [\"station_id\", \"station_name\", \"weekday\"] + list(features.columns[3:])\nfeatures.head()", "_____no_output_____" ] ], [ [ "## Exercice 1 : petits clusters\n\nQue faire des petits clusters ?", "_____no_output_____" ], [ "## Exercice 2 : autres types de clustering\n\nOn essaye des algorithmes de clustering qui n'imposent pas de choisir un nombre de clusters initial.\n\n1. On essaye [DBScan](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html). Est-ce que cela fonctionne ? Si non pourquoi ?\n2. Et si vous savez pourquoi, vous trouverez une solution d'y remédier.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
cb255af0e1585f516fd0f3d0497419d0b906d22e
149,183
ipynb
Jupyter Notebook
Example_ML_fishing_detection.ipynb
mnksmith/oceana_illegalfishing
14f00568649b6bf1eb299fe1936369a33bca1671
[ "MIT" ]
null
null
null
Example_ML_fishing_detection.ipynb
mnksmith/oceana_illegalfishing
14f00568649b6bf1eb299fe1936369a33bca1671
[ "MIT" ]
null
null
null
Example_ML_fishing_detection.ipynb
mnksmith/oceana_illegalfishing
14f00568649b6bf1eb299fe1936369a33bca1671
[ "MIT" ]
null
null
null
120.893841
51,056
0.836992
[ [ [ "# Example Script for Logistic Regression for Fishing Detection", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom patsy import dmatrices\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.model_selection import cross_val_score\n", "_____no_output_____" ] ], [ [ "Load data. This dataset contains coordinates, speeds, and courses for fishing vessels, hand labeled to be fishing or not fishing.", "_____no_output_____" ] ], [ [ "data = np.load('/Users/mnksmith/Documents/Oceana_MPA_data/kristina_trawl_Trawlers.measures.labels.npz')\ndf = pd.DataFrame(data['x'])\nlist(df)", "_____no_output_____" ] ], [ [ "## Some preliminary exploration:", "_____no_output_____" ] ], [ [ "df.groupby('is_fishing').mean()", "_____no_output_____" ], [ "plt.figure()\nplt.tight_layout()\nplt.subplot(1,2,1)\nplt.xlim(0,20)\nfishy = df.loc[df.is_fishing==1]\nunfishy = df.loc[df.is_fishing==0]\n#plt.hist(fishy.speed, range=(0,20))\nplt.hist([fishy['speed'],unfishy['speed']], stacked=True, range = (0,20))\nplt.subplot(1,2,2)\n#measure_speed = 1.0 - min(1, speed-over-ground / 17)\nplt.hist([fishy['measure_speed'],unfishy['measure_speed']], stacked=True, range = (0,1))\nplt.show()", "/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/core/fromnumeric.py:52: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead\n return getattr(obj, method)(*args, **kwds)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:780: RuntimeWarning: invalid value encountered in greater_equal\n keep = (tmp_a >= first_edge)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:781: RuntimeWarning: invalid value encountered in less_equal\n keep &= (tmp_a <= last_edge)\n" ] ], [ [ "The \"measure_speed\" feature is equivalent to the speed-over-ground, capped at 17 knots.", "_____no_output_____" ] ], [ [ "plt.figure()\nplt.tight_layout()\nplt.subplot(1,2,1)\nplt.hist([fishy['course'],unfishy['course']], stacked=True, range = (0,20))\nplt.subplot(1,2,2)\n#measure_course = course-over-ground / 360)\nplt.hist([fishy['measure_course'],unfishy['measure_course']], stacked=True, range = (0,1))\nplt.show()", "/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/core/fromnumeric.py:52: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead\n return getattr(obj, method)(*args, **kwds)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:780: RuntimeWarning: invalid value encountered in greater_equal\n keep = (tmp_a >= first_edge)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:781: RuntimeWarning: invalid value encountered in less_equal\n keep &= (tmp_a <= last_edge)\n" ] ], [ [ "The \"measure_course\" feature is equivalent to the course-over-ground, divided by 360.", "_____no_output_____" ] ], [ [ "plt.figure()\nplt.xlim(0,1)\nplt.hist([fishy['measure_coursestddev_21600'],unfishy['measure_coursestddev_21600']], stacked=True, bins=20, range=(0,1))\nplt.show()", "/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/core/fromnumeric.py:52: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead\n return getattr(obj, method)(*args, **kwds)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:780: RuntimeWarning: invalid value encountered in greater_equal\n keep = (tmp_a >= first_edge)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:781: RuntimeWarning: invalid value encountered in less_equal\n keep &= (tmp_a <= last_edge)\n" ], [ "plt.figure()\nplt.xlim(0,0.25)\nplt.hist([fishy['measure_speedstddev_21600'],unfishy['measure_speedstddev_21600']], stacked=True, bins=20, range=(0,0.2))\nplt.show()", "/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/core/fromnumeric.py:52: FutureWarning: reshape is deprecated and will raise in a subsequent release. Please use .values.reshape(...) instead\n return getattr(obj, method)(*args, **kwds)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:780: RuntimeWarning: invalid value encountered in greater_equal\n keep = (tmp_a >= first_edge)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:781: RuntimeWarning: invalid value encountered in less_equal\n keep &= (tmp_a <= last_edge)\n" ], [ "plt.figure()\nplt.xlim(0,1)\nplt.hist([fishy['measure_speedavg_21600'].values,unfishy['measure_speedavg_21600'].values], stacked=True, bins=20, range=(0,1))\nplt.xlabel('Measure Speed')\n#plt.show()\nplt.savefig('example_feature.png', dpi=300)", "/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:780: RuntimeWarning: invalid value encountered in greater_equal\n keep = (tmp_a >= first_edge)\n/Users/mnksmith/anaconda/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py:781: RuntimeWarning: invalid value encountered in less_equal\n keep &= (tmp_a <= last_edge)\n" ], [ "df = fishy[['measure_speedavg_21600']].reset_index()\ndf['measure_speedavg_21600_not_Fishing'] = unfishy['measure_speedavg_21600']\ndf.head(10)", "_____no_output_____" ], [ "# Create a Pandas Excel writer using XlsxWriter as the engine.\nwriter = pd.ExcelWriter('MPA_feature_example.xlsx', engine='xlsxwriter')\n\n# Convert the dataframe to an XlsxWriter Excel object.\ndf.to_excel(writer, sheet_name='Sheet1')\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()", "_____no_output_____" ] ], [ [ "Now plot a scatter matrix to look for corellations between some select features", "_____no_output_____" ] ], [ [ "df_slim = df[['measure_speedavg_21600','measure_speedstddev_21600','measure_coursestddev_21600']].copy()\npd.plotting.scatter_matrix(df_slim, c = 'y', figsize = [8, 8], s=150, marker = 'D')", "_____no_output_____" ] ], [ [ "## Logistic Regression Model\n\nEach of the key features (average speed, standard deviation of speed, and standard deviation of course) are averaged over 0.5, 1, 3, 6, 12, and 24 hours to fill out the list of features. Powers (up to 6) of each of these features are included to uncover non-linear behavior. For example, from the plots above it is clear that vessels moving very slowly or very quickly are less likely to be fishing, while there's a \"sweet spot\" in the middle. A linear fit will not capture this behavior.", "_____no_output_____" ] ], [ [ "times = [1800,3600,10800,21600,43200,86400]\nfor p in range(2,7):\n for time in times:\n avgspd = 'measure_speedavg_' + str(time)\n stdspd = 'measure_speedstddev_' + str(time) + '_log'\n stdcs = 'measure_coursestddev_' + str(time) + '_log'\n avgspd_p = 'measure_speedavg_' + str(time) + '_' + str(p)\n stdspd_p = 'measure_speedstddev_' + str(time) + '_log_' + str(p)\n stdcs_p = 'measure_coursestddev_' + str(time) + '_log_' + str(p)\n \n df[avgspd_p] = pow(df[avgspd],p)\n df[stdspd_p] = pow(df[stdspd],p)\n df[stdcs_p] = pow(df[stdcs],p)\n \nlist(df)", "_____no_output_____" ], [ "y, X = dmatrices('is_fishing ~ measure_speedavg_1800 + measure_speedavg_3600 + measure_speedavg_10800 + \\\n measure_speedavg_21600 + measure_speedavg_43200 + measure_speedavg_86400 + \\\n measure_speedstddev_1800_log + measure_speedstddev_3600_log + measure_speedstddev_10800_log + \\\n measure_speedstddev_21600_log + measure_speedstddev_43200_log + measure_speedstddev_86400_log + \\\n measure_coursestddev_1800_log + measure_coursestddev_3600_log + measure_coursestddev_10800_log + \\\n measure_coursestddev_21600_log + measure_coursestddev_43200_log + measure_coursestddev_86400_log + \\\n measure_speedavg_1800_2 + measure_speedavg_3600_2 + measure_speedavg_10800_2 + \\\n measure_speedavg_21600_2 + measure_speedavg_43200_2 + measure_speedavg_86400_2 + \\\n measure_speedstddev_1800_log_2 + measure_speedstddev_3600_log_2 + measure_speedstddev_10800_log_2 + \\\n measure_speedstddev_21600_log_2 + measure_speedstddev_43200_log_2 + measure_speedstddev_86400_log_2 + \\\n measure_coursestddev_1800_log_2 + measure_coursestddev_3600_log_2 + measure_coursestddev_10800_log_2 + \\\n measure_coursestddev_21600_log_2 + measure_coursestddev_43200_log_2 + measure_coursestddev_86400_log_2 + \\\n measure_speedavg_1800_3 + measure_speedavg_3600_3 + measure_speedavg_10800_3 + \\\n measure_speedavg_21600_3 + measure_speedavg_43200_3 + measure_speedavg_86400_3 + \\\n measure_speedstddev_1800_log_3 + measure_speedstddev_3600_log_3 + measure_speedstddev_10800_log_3 + \\\n measure_speedstddev_21600_log_3 + measure_speedstddev_43200_log_3 + measure_speedstddev_86400_log_3 + \\\n measure_coursestddev_1800_log_3 + measure_coursestddev_3600_log_3 + measure_coursestddev_10800_log_3 + \\\n measure_coursestddev_21600_log_3 + measure_coursestddev_43200_log_3 + measure_coursestddev_86400_log_3 + \\\n measure_speedavg_1800_4 + measure_speedavg_3600_4 + measure_speedavg_10800_4 + \\\n measure_speedavg_21600_4 + measure_speedavg_43200_4 + measure_speedavg_86400_4 + \\\n measure_speedstddev_1800_log_4 + measure_speedstddev_3600_log_4 + measure_speedstddev_10800_log_4 + \\\n measure_speedstddev_21600_log_4 + measure_speedstddev_43200_log_4 + measure_speedstddev_86400_log_4 + \\\n measure_coursestddev_1800_log_4 + measure_coursestddev_3600_log_4 + measure_coursestddev_10800_log_4 + \\\n measure_coursestddev_21600_log_4 + measure_coursestddev_43200_log_4 + measure_coursestddev_86400_log_4 + \\\n measure_speedavg_1800_5 + measure_speedavg_3600_5 + measure_speedavg_10800_5 + \\\n measure_speedavg_21600_5 + measure_speedavg_43200_5 + measure_speedavg_86400_5 + \\\n measure_speedstddev_1800_log_5 + measure_speedstddev_3600_log_5 + measure_speedstddev_10800_log_5 + \\\n measure_speedstddev_21600_log_5 + measure_speedstddev_43200_log_5 + measure_speedstddev_86400_log_5 + \\\n measure_coursestddev_1800_log_5 + measure_coursestddev_3600_log_5 + measure_coursestddev_10800_log_5 + \\\n measure_coursestddev_21600_log_5 + measure_coursestddev_43200_log_5 + measure_coursestddev_86400_log_5 + \\\n measure_speedavg_1800_6 + measure_speedavg_3600_6 + measure_speedavg_10800_6 + \\\n measure_speedavg_21600_6 + measure_speedavg_43200_6 + measure_speedavg_86400_6 + \\\n measure_speedstddev_1800_log_6 + measure_speedstddev_3600_log_6 + measure_speedstddev_10800_log_6 + \\\n measure_speedstddev_21600_log_6 + measure_speedstddev_43200_log_6 + measure_speedstddev_86400_log_6 + \\\n measure_coursestddev_1800_log_6 + measure_coursestddev_3600_log_6 + measure_coursestddev_10800_log_6 + \\\n measure_coursestddev_21600_log_6 + measure_coursestddev_43200_log_6 + measure_coursestddev_86400_log_6' ,\n df, return_type=\"dataframe\")\nprint(X.columns)\ny = np.ravel(y)", "Index(['Intercept', 'measure_speedavg_1800', 'measure_speedavg_3600',\n 'measure_speedavg_10800', 'measure_speedavg_21600',\n 'measure_speedavg_43200', 'measure_speedavg_86400',\n 'measure_speedstddev_1800_log', 'measure_speedstddev_3600_log',\n 'measure_speedstddev_10800_log',\n ...\n 'measure_speedstddev_10800_log_6', 'measure_speedstddev_21600_log_6',\n 'measure_speedstddev_43200_log_6', 'measure_speedstddev_86400_log_6',\n 'measure_coursestddev_1800_log_6', 'measure_coursestddev_3600_log_6',\n 'measure_coursestddev_10800_log_6', 'measure_coursestddev_21600_log_6',\n 'measure_coursestddev_43200_log_6', 'measure_coursestddev_86400_log_6'],\n dtype='object', length=109)\n" ], [ "model = LogisticRegression()\nmodel = model.fit(X, y)\nmodel.score(X, y)", "_____no_output_____" ] ], [ [ "Using the powers of each feature I lifted a 78% accuracy to 88%", "_____no_output_____" ] ], [ [ "y.mean()", "_____no_output_____" ] ], [ [ "If I guessed \"0\" every time, I'd get 52% accuracy.\n\nNow splitting the whole thing into train and test datasets to evaluate the model:", "_____no_output_____" ] ], [ [ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=432)\nmodel.fit(X_train, y_train)\npredictions = model.predict(X_test)\nprobas = model.predict_proba(X_test)", "_____no_output_____" ], [ "print(metrics.accuracy_score(y_test, predictions))\nprint(metrics.roc_auc_score(y_test, probas[:, 1]))", "0.8764549692796937\n0.9419180250539522\n" ] ], [ [ "The accuracy is still 88% on the validation dataset, the same as when we trained and tested on the same set.", "_____no_output_____" ] ], [ [ "print(metrics.confusion_matrix(y_test, predictions))\nprint(metrics.classification_report(y_test, predictions))", "[[28710 4911]\n [ 3060 28097]]\n precision recall f1-score support\n\n 0.0 0.90 0.85 0.88 33621\n 1.0 0.85 0.90 0.88 31157\n\navg / total 0.88 0.88 0.88 64778\n\n" ], [ "scores = cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10)\nprint(scores.mean())", "0.8603727355352178\n" ] ], [ [ "Over a 10-fold cross-validation, the accuracy dips slightly, to 86%", "_____no_output_____" ] ], [ [ "fpr, tpr, _ = metrics.roc_curve(y_test,probas[:,1])\nplt.plot(fpr,tpr)\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.ylim(0,1)\nplt.xlim(0,1)\n#plt.show()\n\nplt.savefig('roc_curve.png', dpi=300)", "_____no_output_____" ] ], [ [ "Finally, a ROC-curve showing how well the model performs in terms of precision and accuracy.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb255f4733e1cf5fb4463fbe836fd0a0e07eade9
19,553
ipynb
Jupyter Notebook
pandas/pandas_solutions.ipynb
ginjuuu/QuantEcon
7379c9cb1265e3cb0baec58fcfa322f8d8c573bd
[ "BSD-3-Clause" ]
11
2018-05-02T22:12:14.000Z
2021-11-18T01:07:33.000Z
pandas/pandas_solutions.ipynb
ginjuuu/QuantEcon
7379c9cb1265e3cb0baec58fcfa322f8d8c573bd
[ "BSD-3-Clause" ]
null
null
null
pandas/pandas_solutions.ipynb
ginjuuu/QuantEcon
7379c9cb1265e3cb0baec58fcfa322f8d8c573bd
[ "BSD-3-Clause" ]
13
2017-11-11T22:38:22.000Z
2022-02-21T20:33:03.000Z
119.22561
16,132
0.872705
[ [ [ "# quant-econ Solutions: Pandas", "_____no_output_____" ], [ "Solutions for http://quant-econ.net/py/pandas.html", "_____no_output_____" ], [ "## Exercise 1", "_____no_output_____" ], [ "Show the plot inline in the browser:", "_____no_output_____" ] ], [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "Run some imports:", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport datetime as dt\nfrom pandas_datareader import data,wb\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "Now the main code", "_____no_output_____" ] ], [ [ "ticker_list = {'INTC': 'Intel',\n 'MSFT': 'Microsoft',\n 'IBM': 'IBM',\n 'BHP': 'BHP',\n 'TM': 'Toyota',\n 'AAPL': 'Apple',\n 'AMZN': 'Amazon',\n 'BA': 'Boeing',\n 'QCOM': 'Qualcomm',\n 'KO': 'Coca-Cola',\n 'GOOG': 'Google',\n 'SNE': 'Sony',\n 'PTR': 'PetroChina'}\n\nstart = dt.datetime(2013, 1, 1)\nend = dt.datetime.today()\n\nprice_change = {}\n\nfor ticker in ticker_list:\n prices = data.DataReader(ticker, 'yahoo', start, end)\n closing_prices = prices['Close']\n change = 100 * (closing_prices[-1] - closing_prices[0]) / closing_prices[0]\n name = ticker_list[ticker]\n price_change[name] = change\n\npc = pd.Series(price_change)\npc.sort_values(inplace=True)\nfig, ax = plt.subplots(figsize=(10,8))\npc.plot(kind='bar', ax=ax)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb2578ef0624f3ccb94276336ee38a7862198f13
43,691
ipynb
Jupyter Notebook
01. Python/01. Basics/11 Python Program Lexical Structure.ipynb
rostamimahdi1997/CS-Tutorial
19aeba72f012dab16a0db4a4ece308af401e769b
[ "MIT" ]
1
2022-02-21T11:51:34.000Z
2022-02-21T11:51:34.000Z
Python/01. Basics/11 Python Program Lexical Structure.ipynb
saramazaheri/CS-Tutorial
0dbd98e37c7445116fbeb3ebfed5931a013c4a17
[ "MIT" ]
null
null
null
Python/01. Basics/11 Python Program Lexical Structure.ipynb
saramazaheri/CS-Tutorial
0dbd98e37c7445116fbeb3ebfed5931a013c4a17
[ "MIT" ]
null
null
null
43,691
43,691
0.661051
[ [ [ "<img src=\"../../images/banners/python-basics.png\" width=\"600\"/>", "_____no_output_____" ], [ "# <img src=\"../../images/logos/python.png\" width=\"23\"/> Python Program Lexical Structure \n\nYou have now covered Python variables, operators, and data types in depth, and you’ve seen quite a bit of example code. Up to now, the code has consisted of short individual statements, simply assigning objects to variables or displaying values.\n\nBut you want to do more than just define data and display it! Let’s start arranging code into more complex groupings.", "_____no_output_____" ], [ "## <img src=\"../../images/logos/toc.png\" width=\"20\"/> Table of Contents \n* [Python Statements](#python_statements)\n* [Line Continuation](#line_continuation)\n * [Implicit Line Continuation](#implicit_line_continuation)\n * [Parentheses](#parentheses)\n * [Curly Braces](#curly_braces)\n * [Square Brackets](#square_brackets)\n * [Explicit Line Continuation](#explicit_line_continuation)\n* [Multiple Statements Per Line](#multiple_statements_per_line)\n* [Comments](#comments)\n* [Whitespace](#whitespace)\n* [Whitespace as Indentation](#whitespace_as_indentation)\n* [<img src=\"../../images/logos/checkmark.png\" width=\"20\"/> Conclusion](#<img_src=\"../../images/logos/checkmark.png\"_width=\"20\"/>_conclusion)\n\n---", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"python_statements\"></a>\n## Python Statements\n\nStatements are the basic units of instruction that the Python interpreter parses and processes. In general, the interpreter executes statements sequentially, one after the next as it encounters them. (You will see in the next tutorial on conditional statements that it is possible to alter this behavior.)", "_____no_output_____" ], [ "In a REPL session, statements are executed as they are typed in, until the interpreter is terminated. When you execute a script file, the interpreter reads statements from the file and executes them until end-of-file is encountered.", "_____no_output_____" ], [ "Python programs are typically organized with one statement per line. In other words, each statement occupies a single line, with the end of the statement delimited by the newline character that marks the end of the line. The majority of the examples so far in this tutorial series have followed this pattern:", "_____no_output_____" ] ], [ [ "print('Hello, World!')", "Hello, World!\n" ], [ "x = [1, 2, 3]\nprint(x[1:2])", "[2]\n" ] ], [ [ "<a class=\"anchor\" id=\"line_continuation\"></a>\n## Line Continuation\n\nSuppose a single statement in your Python code is especially long. For example, you may have an assignment statement with many terms:", "_____no_output_____" ] ], [ [ "person1_age = 42\nperson2_age = 16\nperson3_age = 71", "_____no_output_____" ], [ "someone_is_of_working_age = (person1_age >= 18 and person1_age <= 65) or (person2_age >= 18 and person2_age <= 65) or (person3_age >= 18 and person3_age <= 65)\nsomeone_is_of_working_age", "_____no_output_____" ] ], [ [ "Or perhaps you are defining a lengthy nested list:", "_____no_output_____" ] ], [ [ "a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]\na", "_____no_output_____" ] ], [ [ "You’ll notice that these statements are too long to fit in your browser window, and the browser is forced to render the code blocks with horizontal scroll bars. You may find that irritating. (You have our apologies—these examples are presented that way to make the point. It won’t happen again.)", "_____no_output_____" ], [ "It is equally frustrating when lengthy statements like these are contained in a script file. Most editors can be configured to wrap text, so that the ends of long lines are at least visible and don’t disappear out the right edge of the editor window. But the wrapping doesn’t necessarily occur in logical locations that enhance readability:", "_____no_output_____" ], [ "<img src=\"./images/line-wrap.webp\" alt=\"line-wrap\" width=500 align=\"center\" />", "_____no_output_____" ], [ "Excessively long lines of code are generally considered poor practice. In fact, there is an official [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008) put forth by the Python Software Foundation, and one of its stipulations is that the [maximum line length](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) in Python code should be 79 characters.", "_____no_output_____" ], [ "> **Note:** The **Style Guide for Python Code** is also referred to as **PEP 8**. PEP stands for Python Enhancement Proposal. PEPs are documents that contain details about features, standards, design issues, general guidelines, and information relating to Python. For more information, see the Python Software Foundation [Index of PEPs](https://www.python.org/dev/peps).", "_____no_output_____" ], [ "As code becomes more complex, statements will on occasion unavoidably grow long. To maintain readability, you should break them up into parts across several lines. But you can’t just split a statement whenever and wherever you like. Unless told otherwise, the interpreter assumes that a newline character terminates a statement. If the statement isn’t syntactically correct at that point, an exception is raised:", "_____no_output_____" ] ], [ [ "someone_is_of_working_age = person1_age >= 18 and person1_age <= 65 or", "_____no_output_____" ] ], [ [ "In Python code, a statement can be continued from one line to the next in two different ways: implicit and explicit line continuation.", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"implicit_line_continuation\"></a>\n### Implicit Line Continuation\n\nThis is the more straightforward technique for line continuation, and the one that is preferred according to PEP 8.", "_____no_output_____" ], [ "Any statement containing opening parentheses (`'('`), brackets (`'['`), or curly braces (`'{'`) is presumed to be incomplete until all matching parentheses, brackets, and braces have been encountered. Until then, the statement can be implicitly continued across lines without raising an error.", "_____no_output_____" ], [ "For example, the nested list definition from above can be made much more readable using implicit line continuation because of the open brackets:", "_____no_output_____" ] ], [ [ "a = [\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25]\n]", "_____no_output_____" ], [ "a", "_____no_output_____" ] ], [ [ "A long expression can also be continued across multiple lines by wrapping it in grouping parentheses. PEP 8 explicitly advocates using parentheses in this manner when appropriate:", "_____no_output_____" ] ], [ [ "someone_is_of_working_age = (\n (person1_age >= 18 and person1_age <= 65)\n or (person2_age >= 18 and person2_age <= 65)\n or (person3_age >= 18 and person3_age <= 65)\n)", "_____no_output_____" ], [ "someone_is_of_working_age", "_____no_output_____" ] ], [ [ "If you need to continue a statement across multiple lines, it is usually possible to use implicit line continuation to do so. This is because parentheses, brackets, and curly braces appear so frequently in Python syntax:", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"parentheses\"></a>\n#### Parentheses\n\n- Expression grouping", "_____no_output_____" ] ], [ [ "x = (\n 1 + 2\n + 3 + 4\n + 5 + 6\n)", "_____no_output_____" ], [ "x", "_____no_output_____" ] ], [ [ "- Function call (functions will be covered later)", "_____no_output_____" ] ], [ [ "print(\n 'foo',\n 'bar',\n 'baz'\n)", "foo bar baz\n" ] ], [ [ "- Method call (methods will be covered later)", "_____no_output_____" ] ], [ [ "'abc'.center(\n 9,\n '-'\n)", "_____no_output_____" ] ], [ [ "- Tuple definition", "_____no_output_____" ] ], [ [ "t = (\n 'a', 'b',\n 'c', 'd'\n)", "_____no_output_____" ] ], [ [ "<a class=\"anchor\" id=\"curly_braces\"></a>\n#### Curly Braces", "_____no_output_____" ], [ "- Dictionary definition", "_____no_output_____" ] ], [ [ "d = {\n 'a': 1,\n 'b': 2\n}", "_____no_output_____" ] ], [ [ "- Set definition", "_____no_output_____" ] ], [ [ "x1 = {\n 'foo',\n 'bar',\n 'baz'\n}", "_____no_output_____" ] ], [ [ "<a class=\"anchor\" id=\"square_brackets\"></a>\n#### Square Brackets", "_____no_output_____" ], [ "- List definition", "_____no_output_____" ] ], [ [ "a = [\n 'foo', 'bar',\n 'baz', 'qux'\n]", "_____no_output_____" ] ], [ [ "- Indexing", "_____no_output_____" ] ], [ [ "a[\n 1\n]", "_____no_output_____" ] ], [ [ "- Slicing", "_____no_output_____" ] ], [ [ "a[\n 1:2\n]", "_____no_output_____" ] ], [ [ "- Dictionary key reference", "_____no_output_____" ] ], [ [ "d[\n 'b'\n]", "_____no_output_____" ] ], [ [ "> **Note:** Just because something is syntactically allowed, it doesn’t mean you should do it. Some of the examples above would not typically be recommended. Splitting indexing, slicing, or dictionary key reference across lines, in particular, would be unusual. But you can consider it if you can make a good argument that it enhances readability.", "_____no_output_____" ], [ "Remember that if there are multiple parentheses, brackets, or curly braces, then implicit line continuation is in effect until they are all closed:", "_____no_output_____" ] ], [ [ "a = [\n [\n ['foo', 'bar'],\n [1, 2, 3]\n ],\n {1, 3, 5},\n {\n 'a': 1,\n 'b': 2\n }\n]", "_____no_output_____" ], [ "a", "_____no_output_____" ] ], [ [ "Note how line continuation and judicious use of indentation can be used to clarify the nested structure of the list.", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"explicit_line_continuation\"></a>\n### Explicit Line Continuation", "_____no_output_____" ], [ "In cases where implicit line continuation is not readily available or practicable, there is another option. This is referred to as explicit line continuation or explicit line joining.", "_____no_output_____" ], [ "Ordinarily, a newline character (which you get when you press _Enter_ on your keyboard) indicates the end of a line. If the statement is not complete by that point, Python will raise a SyntaxError exception:", "_____no_output_____" ] ], [ [ "s =", "_____no_output_____" ], [ "x = 1 + 2 +", "_____no_output_____" ] ], [ [ "To indicate explicit line continuation, you can specify a backslash (`\\`) character as the final character on the line. In that case, Python ignores the following newline, and the statement is effectively continued on next line:", "_____no_output_____" ] ], [ [ "s = \\\n'Hello, World!'", "_____no_output_____" ], [ "s", "_____no_output_____" ], [ "x = 1 + 2 \\\n + 3 + 4 \\\n + 5 + 6", "_____no_output_____" ], [ "x", "_____no_output_____" ] ], [ [ "**Note that the backslash character must be the last character on the line. Not even whitespace is allowed after it:**", "_____no_output_____" ] ], [ [ "# You can't see it, but there is a space character following the \\ here:\ns = \\ ", "_____no_output_____" ] ], [ [ "Again, PEP 8 recommends using explicit line continuation only when implicit line continuation is not feasible.", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"multiple_statements_per_line\"></a>\n## Multiple Statements Per Line\n\nMultiple statements may occur on one line, if they are separated by a semicolon (`;`) character:", "_____no_output_____" ] ], [ [ "x = 1; y = 2; z = 3", "_____no_output_____" ], [ "print(x); print(y); print(z)", "1\n2\n3\n" ] ], [ [ "Stylistically, this is generally frowned upon, and [PEP 8 expressly discourages it](https://www.python.org/dev/peps/pep-0008/?#other-recommendations). There might be situations where it improves readability, but it usually doesn’t. In fact, it often isn’t necessary. The following statements are functionally equivalent to the example above, but would be considered more typical Python code:", "_____no_output_____" ] ], [ [ "x, y, z = 1, 2, 3", "_____no_output_____" ], [ "print(x, y, z, sep='\\n')", "1\n2\n3\n" ] ], [ [ "> The term **Pythonic** refers to code that adheres to generally accepted common guidelines for readability and “best” use of idiomatic Python. When someone says code is not Pythonic, they are implying that it does not express the programmer’s intent as well as might otherwise be done in Python. Thus, the code is probably not as readable as it could be to someone who is fluent in Python.", "_____no_output_____" ], [ "If you find your code has multiple statements on a line, there is probably a more Pythonic way to write it. But again, if you think it’s appropriate or enhances readability, you should feel free to do it.", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"comments\"></a>\n## Comments\n\nIn Python, the hash character (`#`) signifies a comment. The interpreter will ignore everything from the hash character through the end of that line:", "_____no_output_____" ] ], [ [ "a = ['foo', 'bar', 'baz'] # I am a comment.", "_____no_output_____" ], [ "a", "_____no_output_____" ] ], [ [ "If the first non-whitespace character on the line is a hash, the entire line is effectively ignored:", "_____no_output_____" ] ], [ [ "# I am a comment.\n # I am too.", "_____no_output_____" ] ], [ [ "Naturally, a hash character inside a string literal is protected, and does not indicate a comment:", "_____no_output_____" ] ], [ [ "a = 'foobar # I am *not* a comment.'\na", "_____no_output_____" ] ], [ [ "A comment is just ignored, so what purpose does it serve? Comments give you a way to attach explanatory detail to your code:", "_____no_output_____" ] ], [ [ "# Calculate and display the area of a circle.\npi = 3.1415926536\nr = 12.35", "_____no_output_____" ], [ "area = pi * (r ** 2)", "_____no_output_____" ], [ "print('The area of a circle with radius', r, 'is', area)", "The area of a circle with radius 12.35 is 479.163565508706\n" ] ], [ [ "Up to now, your Python coding has consisted mostly of short, isolated REPL sessions. In that setting, the need for comments is pretty minimal. Eventually, you will develop larger applications contained across multiple script files, and comments will become increasingly important.", "_____no_output_____" ], [ "Good commenting makes the intent of your code clear at a glance when someone else reads it, or even when you yourself read it. Ideally, you should strive to write code that is as clear, concise, and self-explanatory as possible. But there will be times that you will make design or implementation decisions that are not readily obvious from the code itself. That is where commenting comes in. Good code explains how; good comments explain why.", "_____no_output_____" ], [ "Comments can be included within implicit line continuation:", "_____no_output_____" ] ], [ [ "x = (1 + 2 # I am a comment.\n + 3 + 4 # Me too.\n + 5 + 6)", "_____no_output_____" ], [ "x", "_____no_output_____" ], [ "a = [\n 'foo', 'bar', # Me three.\n 'baz', 'qux'\n]", "_____no_output_____" ], [ "a", "_____no_output_____" ] ], [ [ "But recall that explicit line continuation requires the backslash character to be the last character on the line. Thus, a comment can’t follow afterward:", "_____no_output_____" ] ], [ [ "x = 1 + 2 + \\ # I wish to be comment, but I'm not.", "_____no_output_____" ] ], [ [ "What if you want to add a comment that is several lines long? Many programming languages provide a syntax for multiline comments (also called block comments). For example, in C and Java, comments are delimited by the tokens `/*` and `*/`. The text contained within those delimiters can span multiple lines:\n\n```c\n/*\n[This is not Python!]\n\nInitialize the value for radius of circle.\n\nThen calculate the area of the circle\nand display the result to the console.\n*/\n```", "_____no_output_____" ], [ "Python doesn’t explicitly provide anything analogous to this for creating multiline block comments. To create a block comment, you would usually just begin each line with a hash character:", "_____no_output_____" ] ], [ [ "# Initialize value for radius of circle.\n#\n# Then calculate the area of the circle\n# and display the result to the console.\n\npi = 3.1415926536\nr = 12.35\n\narea = pi * (r ** 2)\n\nprint('The area of a circle with radius', r, 'is', area)", "The area of a circle with radius 12.35 is 479.163565508706\n" ] ], [ [ "However, for code in a script file, there is technically an alternative.", "_____no_output_____" ], [ "You saw above that when the interpreter parses code in a script file, it ignores a string literal (or any literal, for that matter) if it appears as statement by itself. More precisely, a literal isn’t ignored entirely: the interpreter sees it and parses it, but doesn’t do anything with it. Thus, a string literal on a line by itself can serve as a comment. Since a triple-quoted string can span multiple lines, it can effectively function as a multiline comment.", "_____no_output_____" ], [ "Consider this script file (name it `foo.py` for example):", "_____no_output_____" ] ], [ [ "\"\"\"Initialize value for radius of circle.\n\nThen calculate the area of the circle\nand display the result to the console.\n\"\"\"\n\npi = 3.1415926536\nr = 12.35\n\narea = pi * (r ** 2)\n\nprint('The area of a circle with radius', r, 'is', area)", "The area of a circle with radius 12.35 is 479.163565508706\n" ] ], [ [ "When this script is run, the output appears as follows:\n\n```bash\npython foo.py\nThe area of a circle with radius 12.35 is 479.163565508706\n```", "_____no_output_____" ], [ "The triple-quoted string is not displayed and doesn’t change the way the script executes in any way. It effectively constitutes a multiline block comment.", "_____no_output_____" ], [ "Although this works (and was once put forth as a Python programming tip by Guido himself), PEP 8 actually recommends against it. The reason for this appears to be because of a special Python construct called the **docstring**. A docstring is a special comment at the beginning of a user-defined function that documents the function’s behavior. Docstrings are typically specified as triple-quoted string comments, so PEP 8 recommends that other [block comments](https://www.python.org/dev/peps/pep-0008/?#block-comments) in Python code be designated the usual way, with a hash character at the start of each line.", "_____no_output_____" ], [ "However, as you are developing code, if you want a quick and dirty way to comment out as section of code temporarily for experimentation, you may find it convenient to wrap the code in triple quotes.", "_____no_output_____" ], [ "> You will learn more about docstrings in the upcoming tutorial on functions in Python.", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"whitespace\"></a>\n## Whitespace\n\nWhen parsing code, the Python interpreter breaks the input up into tokens. Informally, tokens are just the language elements that you have seen so far: identifiers, keywords, literals, and operators.", "_____no_output_____" ], [ "Typically, what separates tokens from one another is whitespace: blank characters that provide empty space to improve readability. The most common whitespace characters are the following:\n\n|Character| ASCII Code |Literal Expression|\n|:--|:--|:--|\n|space| `32` `(0x20)` |`' '`|\n|tab| `9` `(0x9)` |`'\\t'`|\n|newline| `10` `(0xa)` |`'\\n'`|", "_____no_output_____" ], [ "There are other somewhat outdated ASCII whitespace characters such as line feed and form feed, as well as some very esoteric Unicode characters that provide whitespace. But for present purposes, whitespace usually means a space, tab, or newline.", "_____no_output_____" ] ], [ [ "x = 3\nx=2", "_____no_output_____" ] ], [ [ "Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved:", "_____no_output_____" ] ], [ [ "x=3;y=12\nx+y", "_____no_output_____" ], [ "(x==3)and(x<y)", "_____no_output_____" ], [ "a=['foo','bar','baz']\na", "_____no_output_____" ], [ "d={'foo':3,'bar':4}\nd", "_____no_output_____" ], [ "x,y,z='foo',14,21.1\n(x,y,z)", "_____no_output_____" ], [ "z='foo'\"bar\"'baz'#Comment\nz", "_____no_output_____" ] ], [ [ "Every one of the statements above has no whitespace at all, and the interpreter handles them all fine. That’s not to say that you should write them that way though. Judicious use of whitespace almost always enhances readability, and your code should typically include some. Compare the following code fragments:", "_____no_output_____" ] ], [ [ "value1=100\nvalue2=200\nv=(value1>=0)and(value1<value2)", "_____no_output_____" ], [ "value1 = 100\nvalue2 = 200\nv = (value1 >= 0) and (value1 < value2)", "_____no_output_____" ] ], [ [ "Most people would likely find that the added whitespace in the second example makes it easier to read. On the other hand, you could probably find a few who would prefer the first example. To some extent, it is a matter of personal preference. But there are standards for [whitespace in expressions and statements](https://www.python.org/dev/peps/pep-0008/?#whitespace-in-expressions-and-statements) put forth in PEP 8, and you should strongly consider adhering to them as much as possible.", "_____no_output_____" ] ], [ [ "x = (1, )", "_____no_output_____" ] ], [ [ "> Note: You can juxtapose string literals, with or without whitespace:\n>\n```python\n>>> s = \"foo\"'bar''''baz'''\n>>> s\n'foobarbaz'\n\n>>> s = 'foo' \"bar\" '''baz'''\n>>> s\n'foobarbaz'\n```\n> The effect is concatenation, exactly as though you had used the + operator.", "_____no_output_____" ], [ "In Python, whitespace is generally only required when it is necessary to distinguish one token from the next. This is most common when one or both tokens are an identifier or keyword.", "_____no_output_____" ], [ "For example, in the following case, whitespace is needed to separate the identifier `s` from the keyword `in`:", "_____no_output_____" ] ], [ [ "s = 'bar'", "_____no_output_____" ], [ "s in ['foo', 'bar', 'baz']", "_____no_output_____" ], [ "sin ['foo', 'bar', 'baz']", "_____no_output_____" ] ], [ [ "Here is an example where whitespace is required to distinguish between the identifier `y` and the numeric constant `20`: ", "_____no_output_____" ] ], [ [ "y is 20", "_____no_output_____" ], [ "y is20", "_____no_output_____" ] ], [ [ "In this example, whitespace is needed between two keywords:", "_____no_output_____" ] ], [ [ "'qux' not in ['foo', 'bar', 'baz']", "_____no_output_____" ], [ "'qux' notin ['foo', 'bar', 'baz']", "_____no_output_____" ] ], [ [ "Running identifiers or keywords together fools the interpreter into thinking you are referring to a different token than you intended: `sin`, `is20`, and `notin`, in the examples above.", "_____no_output_____" ], [ "Running identifiers or keywords together fools the interpreter into thinking you are referring to a different token than you intended: sin, is20, and notin, in the examples above.", "_____no_output_____" ], [ "All this tends to be rather academic because it isn’t something you’ll likely need to think about much. Instances where whitespace is necessary tend to be intuitive, and you’ll probably just do it by second nature.", "_____no_output_____" ], [ "You should use whitespace where it isn’t strictly necessary as well to enhance readability. Ideally, you should follow the guidelines in PEP 8.", "_____no_output_____" ], [ "> **Deep Dive: Fortran and Whitespace**\n>\n>The earliest versions of Fortran, one of the first programming languages created, were designed so that all whitespace was completely ignored. Whitespace characters could be optionally included or omitted virtually anywhere—between identifiers and reserved words, and even in the middle of identifiers and reserved words.\n>\n>For example, if your Fortran code contained a variable named total, any of the following would be a valid statement to assign it the value 50:\n>\n```fortran\ntotal = 50\nto tal = 50\nt o t a l=5 0\n```\n>This was meant as a convenience, but in retrospect it is widely regarded as overkill. It often resulted in code that was difficult to read. Worse yet, it potentially led to code that did not execute correctly.\n>\n>Consider this tale from NASA in the 1960s. A Mission Control Center orbit computation program written in Fortran was supposed to contain the following line of code:\n>\n```fortran\nDO 10 I = 1,100\n```\n>In the Fortran dialect used by NASA at that time, the code shown introduces a loop, a construct that executes a body of code repeatedly. (You will learn about loops in Python in two future tutorials on definite and indefinite iteration).\n>\n>Unfortunately, this line of code ended up in the program instead:\n>\n```fortran\nDO 10 I = 1.100\n```\n> If you have a difficult time seeing the difference, don’t feel too bad. It took the NASA programmer a couple weeks to notice that there is a period between `1` and `100` instead of a comma. Because the Fortran compiler ignored whitespace, `DO 10 I` was taken to be a variable name, and the statement `DO 10 I = 1.100` resulted in assigning `1.100` to a variable called `DO10I` instead of introducing a loop.\n>\n> Some versions of the story claim that a Mercury rocket was lost because of this error, but that is evidently a myth. It did apparently cause inaccurate data for some time, though, before the programmer spotted the error.\n>\n>Virtually all modern programming languages have chosen not to go this far with ignoring whitespace.", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"whitespace_as_indentation\"></a>\n## Whitespace as Indentation\n\nThere is one more important situation in which whitespace is significant in Python code. Indentation—whitespace that appears to the left of the first token on a line—has very special meaning.", "_____no_output_____" ], [ "In most interpreted languages, leading whitespace before statements is ignored. For example, consider this Windows Command Prompt session:\n\n```bash\n$ echo foo\nfoo\n$ echo foo\nfoo\n```", "_____no_output_____" ], [ "> **Note:** In a Command Prompt window, the echo command displays its arguments to the console, like the `print()` function in Python. Similar behavior can be observed from a terminal window in macOS or Linux.", "_____no_output_____" ], [ "In the second statement, four space characters are inserted to the left of the echo command. But the result is the same. The interpreter ignores the leading whitespace and executes the same command, echo foo, just as it does when the leading whitespace is absent.", "_____no_output_____" ], [ "Now try more or less the same thing with the Python interpreter:\n\n```python\n>>> print('foo')\nfoo\n>>> print('foo')\n\nSyntaxError: unexpected indent\n```", "_____no_output_____" ], [ "> **Note:** Running the above code in jupyter notebook does not raise an error as jupyter notebook ignores the whitespaces at the start of a single line command.", "_____no_output_____" ], [ "Say what? Unexpected indent? The leading whitespace before the second `print()` statement causes a `SyntaxError` exception!", "_____no_output_____" ], [ "In Python, indentation is not ignored. Leading whitespace is used to compute a line’s indentation level, which in turn is used to determine grouping of statements. As yet, you have not needed to group statements, but that will change in the next tutorial with the introduction of control structures.", "_____no_output_____" ], [ "Until then, be aware that leading whitespace matters.", "_____no_output_____" ], [ "<a class=\"anchor\" id=\"conclusion\"></a>\n## <img src=\"../../images/logos/checkmark.png\" width=\"20\"/> Conclusion \n\nThis tutorial introduced you to Python program lexical structure. You learned what constitutes a valid Python **statement** and how to use **implicit** and **explicit line continuation** to write a statement that spans multiple lines. You also learned about commenting Python code, and about use of whitespace to enhance readability.", "_____no_output_____" ], [ "Next, you will learn how to group statements into more complex decision-making constructs using **conditional statements**.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb25808d480998493879be94509b2934d0b7ddbe
5,192
ipynb
Jupyter Notebook
examples/load-data/load-data-snowflake.ipynb
saturncloud/examples
e87b4c49f9562d85a631cbaa9fe4205e96088231
[ "BSD-3-Clause" ]
11
2020-08-18T09:55:38.000Z
2022-03-03T15:01:16.000Z
examples/load-data/load-data-snowflake.ipynb
saturncloud/examples
e87b4c49f9562d85a631cbaa9fe4205e96088231
[ "BSD-3-Clause" ]
195
2020-08-18T19:22:02.000Z
2022-03-31T15:55:18.000Z
examples/load-data/load-data-snowflake.ipynb
saturncloud/examples
e87b4c49f9562d85a631cbaa9fe4205e96088231
[ "BSD-3-Clause" ]
3
2020-12-09T14:45:24.000Z
2021-10-06T18:20:47.000Z
44.376068
473
0.653505
[ [ [ "# Load Data From Snowflake", "_____no_output_____" ], [ "![Snowflake Logo](https://saturn-public-assets.s3.us-east-2.amazonaws.com/example-resources/snowflake.png \"doc-image\")", "_____no_output_____" ], [ "## Overview\n<a href=\"https://www.snowflake.com/\" target='_blank' rel='noopener'>Snowflake</a> is a data platform built for the cloud that allows for fast SQL queries. This example shows how to query data in Snowflake and pull into Saturn Cloud for data science work. We will rely on the <a href=\"https://docs.snowflake.com/en/user-guide/python-connector.html\" target='_blank' rel='noopener'>Snowflake Connector for Python</a> to connect and issue queries from Python code.\n\nThe images that come with Saturn come with the Snowflake Connector for Python installed. If you are building your own images and want to work with Snowflake, you should include `snowflake-connector-python` in your environment.\n\nBefore starting this, you should create a Jupyter server resource. See our [quickstart](https://saturncloud.io/docs/start_in_ten/) if you don't know how to do this yet.\n\n## Process\n\n### Add Your Snowflake Credentials to Saturn Cloud\nSign in to your Saturn Cloud account and select **Credentials** from the menu on the left.\n\n<img src=\"https://saturn-public-assets.s3.us-east-2.amazonaws.com/example-resources/saturn-credentials-arrow.jpeg\" style=\"width:200px;\" alt=\"Saturn Cloud left menu with arrow pointing to Credentials tab\" class=\"doc-image\">\n\nThis is where you will add your Snowflake credential information. *This is a secure storage location, and it will not be available to the public or other users without your consent.*\n\nAt the top right corner of this page, you will find the **New** button. Click here, and you will be taken to the Credentials Creation form. \n\n![Screenshot of Saturn Cloud Create Credentials form](https://saturn-public-assets.s3.us-east-2.amazonaws.com/example-resources/credentials.jpg \"doc-image\")\n\nYou will be adding three credentials items: your Snowflake account id, username, and password. Complete the form one time for each item. \n\n| Credential | Type | Name| Variable Name |\n|---|---|---|---|\n| Snowflake account | Environment Variable | `snowflake-account` | `SNOWFLAKE_ACCOUNT` \n| Snowflake username | Environment Variable |`snowflake-user` | `SNOWFLAKE_USER`\n| Snowflake user password | Environment Variable |`snowflake-password` | `SNOWFLAKE_PASSWORD`\n\nEnter your values into the *Value* section of the credential creation form. The credential names are recommendations; feel free to change them as needed for your workflow.\n\nIf you are having trouble finding your Snowflake account id, it is the first part of the URL you use to sign into Snowflake. If you use the url `https://AA99999.us-east-2.aws.snowflakecomputing.com/console/login` to login, your account id is `AA99999`.\n\nWith this complete, your Snowflake credentials will be accessible by Saturn Cloud resources! You will need to restart any Jupyter Server or Dask Clusters for the credentials to populate to those resources.\n\n### Connect to Data\n\nFrom a notebook where you want to connect to Snowflake, you can use the credentials as environment variables and provide any additional arguments, if necessary.", "_____no_output_____" ] ], [ [ "import os\n\nimport snowflake.connector\n\nconn_info = {\n \"account\": os.environ[\"SNOWFLAKE_ACCOUNT\"],\n \"user\": os.environ[\"SNOWFLAKE_USER\"],\n \"password\": os.environ[\"SNOWFLAKE_PASSWORD\"],\n \"warehouse\": \"MY_WAREHOUSE\",\n \"database\": \"MY_DATABASE\",\n \"schema\": \"MY_SCHEMA\",\n}\n\nconn = snowflake.connector.connect(**conn_info)", "_____no_output_____" ] ], [ [ "If you changed the *variable name* of any of your credentials, simply change them here for them to populate properly.\n\nNow you can simply query the database as you would on a local machine.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
cb25826a7d7838efd5a6323207eb9b76b7417829
79,970
ipynb
Jupyter Notebook
11_spatial_transformer_tutorial.ipynb
spencerpomme/torchlight
254a461b30436ac23e64d5ce59e43a1672b76304
[ "MIT" ]
null
null
null
11_spatial_transformer_tutorial.ipynb
spencerpomme/torchlight
254a461b30436ac23e64d5ce59e43a1672b76304
[ "MIT" ]
null
null
null
11_spatial_transformer_tutorial.ipynb
spencerpomme/torchlight
254a461b30436ac23e64d5ce59e43a1672b76304
[ "MIT" ]
null
null
null
159.94
62,608
0.868538
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\nSpatial Transformer Networks Tutorial\n=====================================\n**Author**: `Ghassen HAMROUNI <https://github.com/GHamrouni>`_\n\n.. figure:: /_static/img/stn/FSeq.png\n\nIn this tutorial, you will learn how to augment your network using\na visual attention mechanism called spatial transformer\nnetworks. You can read more about the spatial transformer\nnetworks in the `DeepMind paper <https://arxiv.org/abs/1506.02025>`__\n\nSpatial transformer networks are a generalization of differentiable\nattention to any spatial transformation. Spatial transformer networks\n(STN for short) allow a neural network to learn how to perform spatial\ntransformations on the input image in order to enhance the geometric\ninvariance of the model.\nFor example, it can crop a region of interest, scale and correct\nthe orientation of an image. It can be a useful mechanism because CNNs\nare not invariant to rotation and scale and more general affine\ntransformations.\n\nOne of the best things about STN is the ability to simply plug it into\nany existing CNN with very little modification.\n\n", "_____no_output_____" ] ], [ [ "# License: BSD\n# Author: Ghassen Hamrouni\n\nfrom __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nfrom torchvision import datasets, transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.ion() # interactive mode", "_____no_output_____" ] ], [ [ "Loading the data\n----------------\n\nIn this post we experiment with the classic MNIST dataset. Using a\nstandard convolutional network augmented with a spatial transformer\nnetwork.\n\n", "_____no_output_____" ] ], [ [ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Training dataset\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST(root='data/', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])), batch_size=64, shuffle=True, num_workers=4)\n# Test dataset\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST(root='data/', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])), batch_size=64, shuffle=True, num_workers=4)", "Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\nDownloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\nDownloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\nDownloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\nProcessing...\nDone!\n" ] ], [ [ "Depicting spatial transformer networks\n--------------------------------------\n\nSpatial transformer networks boils down to three main components :\n\n- The localization network is a regular CNN which regresses the\n transformation parameters. The transformation is never learned\n explicitly from this dataset, instead the network learns automatically\n the spatial transformations that enhances the global accuracy.\n- The grid generator generates a grid of coordinates in the input\n image corresponding to each pixel from the output image.\n- The sampler uses the parameters of the transformation and applies\n it to the input image.\n\n.. figure:: /_static/img/stn/stn-arch.png\n\n.. Note::\n We need the latest version of PyTorch that contains\n affine_grid and grid_sample modules.\n\n\n", "_____no_output_____" ] ], [ [ "class 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 # Spatial transformer localization-network\n self.localization = nn.Sequential(\n nn.Conv2d(1, 8, kernel_size=7),\n nn.MaxPool2d(2, stride=2),\n nn.ReLU(True),\n nn.Conv2d(8, 10, kernel_size=5),\n nn.MaxPool2d(2, stride=2),\n nn.ReLU(True)\n )\n\n # Regressor for the 3 * 2 affine matrix\n self.fc_loc = nn.Sequential(\n nn.Linear(10 * 3 * 3, 32),\n nn.ReLU(True),\n nn.Linear(32, 3 * 2)\n )\n\n # Initialize the weights/bias with identity transformation\n self.fc_loc[2].weight.data.zero_()\n self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float))\n\n # Spatial transformer network forward function\n def stn(self, x):\n xs = self.localization(x)\n xs = xs.view(-1, 10 * 3 * 3)\n theta = self.fc_loc(xs)\n theta = theta.view(-1, 2, 3)\n\n grid = F.affine_grid(theta, x.size())\n x = F.grid_sample(x, grid)\n\n return x\n\n def forward(self, x):\n # transform the input\n x = self.stn(x)\n\n # Perform the usual forward pass\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\nmodel = Net().to(device)", "_____no_output_____" ] ], [ [ "Training the model\n------------------\n\nNow, let's use the SGD algorithm to train the model. The network is\nlearning the classification task in a supervised way. In the same time\nthe model is learning STN automatically in an end-to-end fashion.\n\n", "_____no_output_____" ] ], [ [ "optimizer = optim.SGD(model.parameters(), lr=0.01)\n\n\ndef train(epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % 500 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n#\n# A simple test procedure to measure STN the performances on MNIST.\n#\n\n\ndef test():\n with torch.no_grad():\n model.eval()\n test_loss = 0\n correct = 0\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n\n # sum up batch loss\n test_loss += F.nll_loss(output, target, size_average=False).item()\n # get the index of the max log-probability\n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'\n .format(test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))", "_____no_output_____" ] ], [ [ "Visualizing the STN results\n---------------------------\n\nNow, we will inspect the results of our learned visual attention\nmechanism.\n\nWe define a small helper function in order to visualize the\ntransformations while training.\n\n", "_____no_output_____" ] ], [ [ "def convert_image_np(inp):\n \"\"\"Convert a Tensor to numpy image.\"\"\"\n inp = inp.numpy().transpose((1, 2, 0))\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n inp = std * inp + mean\n inp = np.clip(inp, 0, 1)\n return inp\n\n# We want to visualize the output of the spatial transformers layer\n# after the training, we visualize a batch of input images and\n# the corresponding transformed batch using STN.\n\n\ndef visualize_stn():\n with torch.no_grad():\n # Get a batch of training data\n data = next(iter(test_loader))[0].to(device)\n\n input_tensor = data.cpu()\n transformed_input_tensor = model.stn(data).cpu()\n\n in_grid = convert_image_np(\n torchvision.utils.make_grid(input_tensor))\n\n out_grid = convert_image_np(\n torchvision.utils.make_grid(transformed_input_tensor))\n\n # Plot the results side-by-side\n f, axarr = plt.subplots(1, 2)\n axarr[0].imshow(in_grid)\n axarr[0].set_title('Dataset Images')\n\n axarr[1].imshow(out_grid)\n axarr[1].set_title('Transformed Images')\n\n\nfor epoch in range(1, 20 + 1):\n train(epoch)\n test()\n\n# Visualize the STN transformation on some input batch\nvisualize_stn()\n\nplt.ioff()\nplt.show()", "Train Epoch: 1 [0/60000 (0%)]\tLoss: 2.317265\nTrain Epoch: 1 [32000/60000 (53%)]\tLoss: 0.738026\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb2590e94ccf1c509cc6f148781a172626bb0436
24,889
ipynb
Jupyter Notebook
notebooks/classification/Neural network.ipynb
cleanunicorn/fashion-mnist
448b6d33a19a4b6ba89b0a22d53f26d31fb424c4
[ "MIT" ]
null
null
null
notebooks/classification/Neural network.ipynb
cleanunicorn/fashion-mnist
448b6d33a19a4b6ba89b0a22d53f26d31fb424c4
[ "MIT" ]
null
null
null
notebooks/classification/Neural network.ipynb
cleanunicorn/fashion-mnist
448b6d33a19a4b6ba89b0a22d53f26d31fb424c4
[ "MIT" ]
1
2021-09-06T03:15:16.000Z
2021-09-06T03:15:16.000Z
42.764605
4,684
0.593515
[ [ [ "%matplotlib inline\n", "_____no_output_____" ], [ "import torch\nimport torch.nn as nn\nimport matplotlib.pyplot as pt\nimport numpy as np\n\ndevice = torch.device('cpu')\n\n# if torch.cuda.is_available() > 0:\n# print(\"Using GPU\")\n# device = torch.device('cuda')\n# else:\n# print(\"Using CPU\")", "_____no_output_____" ], [ "# Sizes of layers and batch size\nn_in, n_h, n_out = 784, 200, 10", "_____no_output_____" ], [ "# Load test data\n\nimport pandas as pd\n\ndata = pd.read_csv(\"./train.csv\").values\n\n# \nprint(\"Data length: {}\".format(len(data)))\n\n# training dataset\ntrain_size = len(data)\ntrain_data = data[0:train_size, 1:]\ntrain_label = data[0:train_size,0]\n\n# testing data\n# xtest = data[21000:, 1:]\n# actual_label = data[21000:, 0]", "Data length: 42000\n" ], [ "test_index = 0\n\nd = train_data[test_index]\nd.shape=(28,28)\npt.imshow(255-d,cmap='gray')\npt.show()", "_____no_output_____" ] ], [ [ "### Training ", "_____no_output_____" ] ], [ [ "%%time\n# print(len(trainloader))\n\n# Create model\nmodel = nn.Sequential(\n nn.Linear(n_in, n_h),\n nn.ReLU(),\n nn.Linear(n_h, n_out),\n nn.Sigmoid()\n)\n\n# if torch.cuda.is_available() > 0:\nmodel.to(device)\n\n# Criterion\ncriterion = torch.nn.MSELoss()\n# criterion = nn.CrossEntropyLoss()\n\n# Optimizer function\noptimizer = torch.optim.SGD(model.parameters(), lr=0.001)\n\n# Cast as double\nmodel.double()\n\n# Generate correct results\ncorrect_results = []\nfor i in range(train_size):\n correct = []\n for ci in range(10):\n if train_label[i] == ci:\n correct.append(1)\n else:\n correct.append(0)\n correct = torch.from_numpy(np.array(correct).astype(float)).to(device)\n correct_results.append(correct)\n\n# Train\nstats_step = 5000\nfor epoch in range(20):\n running_loss = 0.0\n \n print(\"epoch: {}\".format(epoch))\n \n for i, data in enumerate(train_data, 0):\n # Load input\n input = torch.from_numpy(data.astype(float)).to(device)\n \n # Generate prediction\n prediction = model(input)\n \n # Correct result\n correct = correct_results[i]\n \n # Compute loss\n loss = criterion(prediction, correct)\n\n # Zero the gradients\n optimizer.zero_grad()\n \n # Perform a backward pass\n loss.backward()\n \n # Update parameters\n optimizer.step()\n \n # Print stats\n running_loss += loss.item()\n if (i % stats_step == 0) and (i > 0):\n print(\"[{}] loss: {}\".format(i, running_loss / stats_step))\n running_loss = 0", "epoch: 0\n[5000] loss: 0.08443897385801673\n[10000] loss: 0.07238239994006218\n[15000] loss: 0.06838011152572177\n[20000] loss: 0.067749574535047\n[25000] loss: 0.0672565799288743\n[30000] loss: 0.06491287572208082\n[35000] loss: 0.06281795144077003\n[40000] loss: 0.06068375709742644\nepoch: 1\n[5000] loss: 0.05897358498494777\n[10000] loss: 0.05980399995432821\n[15000] loss: 0.0581566582131322\n[20000] loss: 0.057798753923296774\n[25000] loss: 0.05502325309740843\n[30000] loss: 0.053453063121645265\n[35000] loss: 0.05272032273397122\n[40000] loss: 0.051085313344987913\nepoch: 2\n[5000] loss: 0.05013699505721219\n[10000] loss: 0.04930938820244464\n[15000] loss: 0.04309774818060343\n[20000] loss: 0.04259904995055509\n[25000] loss: 0.041737495217212484\n[30000] loss: 0.04097819300129548\n[35000] loss: 0.04115129624640428\n[40000] loss: 0.03973798949835453\nepoch: 3\n[5000] loss: 0.03738859885083407\n[10000] loss: 0.0369726333700325\n[15000] loss: 0.032564151343975216\n[20000] loss: 0.03195294875765799\n[25000] loss: 0.031669474888930065\n[30000] loss: 0.031947806716890105\n[35000] loss: 0.03071975116377539\n[40000] loss: 0.029317932221446796\nepoch: 4\n[5000] loss: 0.02853593331134086\n[10000] loss: 0.029745651371399767\n[15000] loss: 0.028791005774741717\n[20000] loss: 0.028434348349224366\n[25000] loss: 0.028569501638752062\n[30000] loss: 0.029147298223243717\n[35000] loss: 0.02898170470020628\n[40000] loss: 0.02725534713073197\nepoch: 5\n[5000] loss: 0.026720095865542817\n[10000] loss: 0.028527077085638966\n[15000] loss: 0.02746070764976989\n[20000] loss: 0.027312691270550006\n[25000] loss: 0.027680938597134542\n[30000] loss: 0.028002036146068825\n[35000] loss: 0.027178773209813767\n[40000] loss: 0.02637835331290808\nepoch: 6\n[5000] loss: 0.02607914837565362\n[10000] loss: 0.02758683380359609\n[15000] loss: 0.026318294995804233\n[20000] loss: 0.02621539282971283\n[25000] loss: 0.026419852565452366\n[30000] loss: 0.02666582367841326\n[35000] loss: 0.02650567341114691\n[40000] loss: 0.0256529965331183\nepoch: 7\n[5000] loss: 0.02468214136128707\n[10000] loss: 0.026841872278110065\n[15000] loss: 0.025531757391184358\n[20000] loss: 0.025385635489852898\n[25000] loss: 0.026007299687040308\n[30000] loss: 0.025989260860805077\n[35000] loss: 0.024355316977236034\n[40000] loss: 0.02227113586467968\nepoch: 8\n[5000] loss: 0.01930006293384331\n[10000] loss: 0.019665399687899793\n[15000] loss: 0.018776855642958768\n[20000] loss: 0.018023230822345603\n[25000] loss: 0.018597005581080735\n[30000] loss: 0.018368679081203872\n[35000] loss: 0.017136838693624395\n[40000] loss: 0.0169667627383269\nepoch: 9\n[5000] loss: 0.016211653102497482\n[10000] loss: 0.017064793050445327\n[15000] loss: 0.015938533854938982\n[20000] loss: 0.015994793646681337\n[25000] loss: 0.01673234928555841\n[30000] loss: 0.016827814250711982\n[35000] loss: 0.015607769665014067\n[40000] loss: 0.016185020957305053\nepoch: 10\n[5000] loss: 0.015632176258982305\n[10000] loss: 0.015790073048663963\n[15000] loss: 0.01499891981756208\n[20000] loss: 0.015797544248874168\n[25000] loss: 0.015968325985071745\n[30000] loss: 0.0159817396752001\n[35000] loss: 0.014806073725951458\n[40000] loss: 0.015625302239309906\nepoch: 11\n[5000] loss: 0.014742130604176102\n[10000] loss: 0.015331769296696888\n[15000] loss: 0.014201647203740612\n[20000] loss: 0.014804826830353108\n[25000] loss: 0.01542052007310684\n[30000] loss: 0.015161541038949983\n[35000] loss: 0.014138689041406803\n[40000] loss: 0.014675139053540908\nepoch: 12\n[5000] loss: 0.014096448356080652\n[10000] loss: 0.014875128583896932\n[15000] loss: 0.013990992394206266\n[20000] loss: 0.014181010243879234\n[25000] loss: 0.01484678778224156\n[30000] loss: 0.014815002536038645\n[35000] loss: 0.013699541108592147\n[40000] loss: 0.01427043101266316\nepoch: 13\n[5000] loss: 0.013735958369211121\n[10000] loss: 0.014689037852766268\n[15000] loss: 0.013581867476901025\n[20000] loss: 0.0138814801270412\n[25000] loss: 0.014729368230561122\n[30000] loss: 0.014465604978622235\n[35000] loss: 0.01311625241235603\n[40000] loss: 0.013961091415298417\nepoch: 14\n[5000] loss: 0.013324277256071031\n[10000] loss: 0.014354500261049478\n[15000] loss: 0.012980601413016612\n[20000] loss: 0.013591514729520535\n[25000] loss: 0.01452850007833403\n[30000] loss: 0.013989753890752766\n[35000] loss: 0.013358051446663032\n[40000] loss: 0.013737727598699333\nepoch: 15\n[5000] loss: 0.01316565445250619\n[10000] loss: 0.01398342128803773\n[15000] loss: 0.012972676302791456\n[20000] loss: 0.01319050074143006\n[25000] loss: 0.014362866156387776\n[30000] loss: 0.013772692161302037\n[35000] loss: 0.01299080073854104\n[40000] loss: 0.013564849387826405\nepoch: 16\n[5000] loss: 0.0128417661939612\n[10000] loss: 0.013818624057155256\n[15000] loss: 0.012440320828377021\n[20000] loss: 0.01290336707185941\n[25000] loss: 0.013984864017572648\n[30000] loss: 0.013727437372783882\n[35000] loss: 0.012610223623551487\n[40000] loss: 0.013080908738317654\nepoch: 17\n[5000] loss: 0.012719430051132626\n[10000] loss: 0.01329885014669125\n[15000] loss: 0.012392134940794833\n[20000] loss: 0.012687913996162406\n[25000] loss: 0.013695282912575006\n[30000] loss: 0.013456370562941853\n[35000] loss: 0.012277919187460174\n[40000] loss: 0.013289082027235319\nepoch: 18\n[5000] loss: 0.012610141652022172\n[10000] loss: 0.012862753683690668\n[15000] loss: 0.012019208026023489\n[20000] loss: 0.012637807537728902\n[25000] loss: 0.013297080544592714\n[30000] loss: 0.013113335915284862\n[35000] loss: 0.012060042716293283\n[40000] loss: 0.012836156950747449\nepoch: 19\n[5000] loss: 0.012207529474396867\n[10000] loss: 0.012939677316620567\n[15000] loss: 0.011807223306512541\n[20000] loss: 0.012455984507757792\n[25000] loss: 0.01339175103161663\n[30000] loss: 0.013077330847338593\n[35000] loss: 0.012015029950431822\n[40000] loss: 0.012793864322790349\nCPU times: user 1h 19min 17s, sys: 14.9 s, total: 1h 19min 32s\nWall time: 11min 40s\n" ], [ "# Test model\nfrom PIL import Image\n\nim = Image.open('test1.png')\npix = im.load()\nw, h = im.size\n\npixel_list = []\nfor x in range(0, w):\n for y in range(0, h):\n pixel_list.append(int(255 - sum(pix[y, x][0:3]) / 3))\n \nfor x in range(0, w):\n print()\n for y in range(0, h):\n print(1 if pixel_list[x*28 + y] >= 128 else ' ', end=' ')\n \nprint() \n \ninput = torch.from_numpy(np.array(pixel_list).astype(float)).to(device)\nprediction = model(input)\n\nmax_v = 0\nmax_n = 0\nfor n, v in enumerate(prediction):\n if v > max_v:\n max_n = n\n max_v = v\n\nif max_v < 0.001:\n print(\"Uncertain\")\n \nfor i in prediction:\n print(\"{0:.50f}\".format(i))\n\nprint(\"number = {}\".format(max_n))\n", "\n \n \n \n 1 1 1 1 1 1 1 \n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 \n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 \n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 \n 1 1 1 1 \n 1 1 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 \n \nUncertain\n0.00000000000000129346437587583629088058738852887902\n0.00000000000000000000000000000000001394796264926500\n0.00016695920357699794967475115381461137076257728040\n0.00000400471984005761850121916933797905358005664311\n0.00000000000000000000000000000000000001262079000061\n0.00000000000000000000000005774896438896024478470863\n0.00000000000000000000000000000000000000477143444974\n0.00000000000000045034435664214614974831797296616164\n0.00000000000000385600044318959682319388008615892148\n0.00000000000000000000000134764306040870916934356702\nnumber = 2\n" ], [ "# train_size = len(data)\n# train_data = data[0:train_size, 1:]\n# train_label = data[0:train_size,0]\n\ncertain_correct = 0\ncertain_count = 0\n\nuncertain_correct = 0\nuncertain_count = 0\n\nfor i in range(train_size):\n data = train_data[i]\n input = torch.from_numpy(data.astype(float)).to(device)\n \n prediction = model(input)\n \n max_v = 0\n max_n = 0\n for n, v in enumerate(prediction):\n if v > max_v:\n max_n = n\n max_v = v\n \n if (max_v > 0.001):\n certain_count += 1\n if (max_n == train_label[i]):\n certain_correct += 1\n \n if (max_v < 0.001):\n uncertain_count += 1\n if (max_n == train_label[i]):\n uncertain_correct += 1\n \n if (i % stats_step == 0) and (i > 0):\n print(\"[{}] Certain correct {}\".format(i, certain_correct / certain_count * 100))\n print(\"[{}] Uncertain correct {}\".format(i, uncertain_correct / uncertain_count * 100))\n print(\"[{}] Correct percentage {}\".format(i, (certain_correct + uncertain_correct) / i * 100))\n\nprint(\"Final statistics\")\nprint(\"Certain correct {}\".format(certain_correct / certain_count * 100))\nprint(\"Uncertain correct {}\".format(uncertain_correct / uncertain_count * 100))\nprint(\"Correct percentage {}\".format((certain_correct + uncertain_correct) / train_size * 100))\n\nprint(\"Certain {}\".format(certain_count))\nprint(\"Uncertain {}\".format(uncertain_count))\n\n", "[5000] Certain correct 98.46427776541287\n[5000] Uncertain correct 1.574803149606299\n[5000] Correct percentage 88.64\n[10000] Certain correct 98.38512083750975\n[10000] Uncertain correct 1.761252446183953\n[10000] Correct percentage 88.52\n[15000] Certain correct 98.43715280349605\n[15000] Uncertain correct 2.1999999999999997\n[15000] Correct percentage 88.82\n[20000] Certain correct 98.48291191997777\n[20000] Uncertain correct 2.1934197407776668\n[20000] Correct percentage 88.83\n[25000] Certain correct 98.4332576668002\n[25000] Uncertain correct 2.0126282557221784\n[25000] Correct percentage 88.664\n[30000] Certain correct 98.40068277116035\n[30000] Uncertain correct 2.064220183486239\n[30000] Correct percentage 88.60333333333334\n[35000] Certain correct 98.43288089259036\n[35000] Uncertain correct 2.1739130434782608\n[35000] Correct percentage 88.69428571428571\n[40000] Certain correct 98.47181628392484\n[40000] Uncertain correct 2.2080471050049066\n[40000] Correct percentage 88.665\nFinal statistics\nCertain correct 98.488504680332\nUncertain correct 2.168337607833994\nCorrect percentage 88.65238095238095\nCertain 37711\nUncertain 4289\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb25921b90151e6e1d01d740176249d50c9b43c2
33,315
ipynb
Jupyter Notebook
Data Science and Machine Learning/Thorough Python Data Science Topics/spaCy 3.x Tutorial Transformers Spanish.ipynb
okara83/Becoming-a-Data-Scientist
f09a15f7f239b96b77a2f080c403b2f3e95c9650
[ "MIT" ]
39
2016-11-12T09:20:41.000Z
2020-04-03T15:11:36.000Z
Data Science and Machine Learning/Thorough Python Data Science Topics/spaCy 3.x Tutorial Transformers Spanish.ipynb
okara83/Becoming-a-Data-Scientist
f09a15f7f239b96b77a2f080c403b2f3e95c9650
[ "MIT" ]
null
null
null
Data Science and Machine Learning/Thorough Python Data Science Topics/spaCy 3.x Tutorial Transformers Spanish.ipynb
okara83/Becoming-a-Data-Scientist
f09a15f7f239b96b77a2f080c403b2f3e95c9650
[ "MIT" ]
37
2017-02-25T21:24:07.000Z
2020-04-03T15:11:42.000Z
61.353591
301
0.627285
[ [ [ "# spaCy 3.x Tutorial: Transformers Spanish", "_____no_output_____" ], [ "**(C) 2021 by [Damir Cavar](http://damir.cavar.me/) <<[email protected]>>**", "_____no_output_____" ], [ "**Version:** 1.1, Sept. 2021", "_____no_output_____" ], [ "**License:** [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/) ([CA BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))", "_____no_output_____" ], [ "This is a tutorial about developing simple [spaCy](https://spacy.io/) based NLP components for Spanish.", "_____no_output_____" ], [ "This tutorial was developed as part of my course material for the course L715 Research Seminar on NLU, Knowledge Graphs, and GNNs at [Indiana University at Bloomington](https://www.indiana.edu/).", "_____no_output_____" ], [ "## NLP Pipeline for Spanish", "_____no_output_____" ] ], [ [ "import spacy", "_____no_output_____" ] ], [ [ "If you want to use the GPU in the following, use the following code. It will assign memory allocations to PyTorch, which will be more robust, preventing out-of-memory errors that might occur from competing memory pools (See [spaCy documentation](https://spacy.io/usage/embeddings-transformers)).", "_____no_output_____" ] ], [ [ "from thinc.api import set_gpu_allocator, require_gpu\n\nset_gpu_allocator(\"pytorch\")\nrequire_gpu(0)\nnlp = spacy.load(\"es_dep_news_trf\")", "_____no_output_____" ], [ "for doc in nlp.pipe([\"Este es un texto corto.\", \"Aquí hay algún otro texto.\"]):\n tokvecs = doc._.trf_data.tensors[-1]\n print(tokvecs)", "[[-3.65571797e-01 -1.07624516e-01 -3.75636220e-01 1.49296507e-01\n 2.07939029e-01 4.88051981e-01 3.35931361e-01 -9.16096687e-01\n -8.11563373e-01 3.77223343e-01 -9.96331930e-01 -2.59966522e-01\n -3.50860029e-01 -5.12584150e-01 5.53630054e-01 1.66127264e-01\n 2.06725914e-02 9.80642617e-01 6.24353513e-02 -1.99831963e-01\n 6.89916313e-03 -4.97184284e-02 8.94966483e-01 6.42851710e-01\n 8.40666667e-02 9.79871869e-01 -9.38545287e-01 -3.20128888e-01\n 6.22806311e-01 -8.75478745e-01 1.03287362e-01 9.96363044e-01\n 1.96195722e-01 3.82119298e-01 4.98581856e-01 8.98100257e-01\n -9.44938138e-02 3.71071965e-01 9.48450565e-01 -3.04787070e-01\n -9.88952339e-01 -1.29752010e-01 -6.88679457e-01 6.00430369e-01\n -6.77243173e-01 -3.21298018e-02 9.15745497e-02 4.13944393e-01\n 6.53509423e-02 -9.33000967e-02 -4.53986555e-01 -5.53809702e-01\n -1.58625498e-01 6.77313004e-03 -7.58789340e-03 9.88084733e-01\n 7.22095370e-01 -8.49259198e-01 1.04436286e-01 9.61510599e-01\n -8.06320459e-02 2.10571468e-01 -1.00641429e-01 -5.54830544e-02\n 3.89246382e-02 -2.23701298e-02 3.68152201e-01 3.45435023e-01\n 4.71973941e-02 -9.30428505e-01 -9.62455034e-01 -1.12878770e-01\n -1.66557446e-01 9.82720792e-01 -6.70027018e-01 -1.93863064e-01\n 9.77333963e-01 -5.54500110e-02 -8.90566647e-01 -2.34671608e-01\n 8.50276828e-01 -9.59162191e-02 -1.28325447e-01 -2.16895193e-02\n 2.18496531e-01 -2.62763381e-01 -3.01723212e-01 6.68855786e-01\n -9.32256401e-01 -2.34778747e-01 9.61792231e-01 5.91308400e-02\n -1.97245792e-01 4.13291544e-01 2.05795079e-01 9.47748721e-01\n -3.23913097e-01 -1.10032693e-01 -2.60710835e-01 9.20973241e-01\n -8.99041831e-01 9.99932736e-02 -3.22316140e-01 -7.82670453e-02\n 7.34816074e-01 -2.42073506e-01 5.09823859e-01 3.16527247e-01\n 7.28637636e-01 5.57040572e-01 -2.68893450e-01 4.72471535e-01\n 5.24046183e-01 -1.29420474e-01 8.13758299e-02 -7.46191442e-01\n -5.21147132e-01 3.36757272e-01 7.59283423e-01 -9.85265791e-01\n 2.48418838e-01 9.44984019e-01 -1.34062275e-01 -1.63964387e-02\n 6.19582176e-01 7.09667444e-01 -4.65030491e-01 6.32189035e-01\n -2.42721736e-01 -8.97468925e-01 7.58929193e-01 -1.80443019e-01\n -2.19564080e-01 2.95646608e-01 2.00806577e-02 -4.71989483e-01\n -9.86590624e-01 -1.26375258e-01 5.55884242e-01 -3.86329830e-01\n 8.83474946e-01 7.11500049e-01 5.23246765e-01 3.78891855e-01\n -9.56381321e-01 -9.58720688e-03 9.98792291e-01 1.01797238e-01\n 5.81080914e-01 -9.09821987e-01 5.87347848e-03 -8.41367602e-01\n 7.01496601e-02 -5.03984630e-01 -7.94726253e-01 4.89620864e-01\n 1.28024012e-01 -4.11555052e-01 2.91701585e-01 2.08021849e-01\n -1.47122860e-01 -2.41395772e-01 5.94101310e-01 -2.41577942e-02\n -3.29203069e-01 5.44758976e-01 4.36871909e-02 9.62537467e-01\n 6.70682073e-01 -6.06290847e-02 -4.10261661e-01 -9.37705815e-01\n -2.71193922e-01 1.23378865e-01 8.68973136e-01 -1.44062996e-01\n 7.65463412e-01 -3.30705911e-01 -6.83432639e-01 1.17401026e-01\n 3.77422810e-01 1.99747503e-01 1.13237709e-01 -3.12628262e-02\n 3.58512588e-02 -4.71635833e-02 9.34826791e-01 7.08216190e-01\n -4.69884843e-01 1.64552018e-01 -2.98415840e-01 -3.06626111e-01\n 9.84274447e-02 2.17478856e-01 7.50360894e-04 2.91637391e-01\n -2.57757902e-01 -6.94253564e-01 -9.87900257e-01 4.98012036e-01\n -2.74379849e-01 7.21893728e-01 3.97461429e-02 1.59683704e-01\n -8.26670408e-01 2.97739446e-01 -9.14064527e-01 -9.46466625e-01\n 9.36804771e-01 -1.54025748e-01 7.11410880e-01 1.13424174e-01\n 9.43089545e-01 7.40895033e-01 -4.63686675e-01 1.53245358e-02\n 3.43890041e-01 -2.52247721e-01 6.77870274e-01 -9.12561297e-01\n 5.75544722e-02 1.81297645e-01 -8.88997972e-01 2.13466331e-01\n -7.33275950e-01 -7.61947334e-01 9.85329330e-01 -9.28336143e-01\n -7.82992721e-01 4.56475943e-01 -9.73759711e-01 9.37683880e-01\n 5.56984395e-02 -3.80506426e-01 8.91355574e-01 1.33962721e-01\n -7.82518089e-02 1.55046880e-01 -4.69575316e-01 8.91951740e-01\n -3.22065413e-01 -3.99600863e-01 -1.80818029e-02 5.84684551e-01\n -9.21815932e-01 -4.31548119e-01 -2.29477391e-01 -7.91474700e-01\n 4.82839227e-01 3.81716996e-01 -1.09750643e-01 -9.78513062e-01\n 2.33940378e-01 -9.95840251e-01 -2.83566326e-01 -7.41647959e-01\n -2.22414449e-01 -1.20979868e-01 -6.84317291e-01 -2.17574579e-03\n 8.47305059e-01 8.75607058e-02 -1.83593974e-01 5.45347154e-01\n 7.52832413e-01 5.61583817e-01 5.79510808e-01 -1.46304637e-01\n -5.28079808e-01 4.15984303e-01 3.81820589e-01 8.82670522e-01\n -6.73610568e-01 2.74453372e-01 5.69231510e-01 -5.21686733e-01\n 6.53834820e-01 6.14806950e-01 2.63371944e-01 -3.08897477e-02\n 4.07469124e-01 2.18184486e-01 -8.05295706e-01 -1.77749202e-01\n 9.59701896e-01 -2.67682195e-01 1.06808454e-01 5.76060295e-01\n 2.71968395e-01 -1.21245362e-01 -6.20335877e-01 3.43765616e-01\n -8.59307110e-01 -9.78594646e-02 5.15146971e-01 1.53038055e-01\n 4.25515063e-02 8.50575864e-01 -1.11137114e-01 4.17396389e-02\n -3.92213553e-01 9.36824441e-01 9.24162507e-01 7.29989558e-02\n 4.44284528e-01 -9.80590060e-02 -3.52928728e-01 8.13859344e-01\n 6.07421622e-03 -4.00749370e-02 1.15271052e-03 1.76844254e-01\n -9.51083541e-01 -4.51892346e-01 -7.14815617e-01 -3.01970840e-01\n -9.69615459e-01 4.94808406e-02 3.22231889e-01 5.36776148e-02\n 1.44208938e-01 -4.22007322e-01 2.85312474e-01 -4.10810679e-01\n -2.58741200e-01 -2.66353548e-01 -8.03972840e-01 7.21952245e-02\n 2.66469587e-02 -4.17293191e-01 -7.93219447e-01 -5.93721271e-01\n 9.40350533e-01 8.78930211e-01 -1.45401984e-01 -6.55818164e-01\n 3.81104976e-01 1.92619354e-01 -6.88308835e-01 -4.24569428e-01\n 3.08546990e-01 -2.11999983e-01 -9.76624012e-01 -9.90854621e-01\n -2.78677851e-01 9.87527490e-01 7.66916722e-02 3.47581565e-01\n -3.14375341e-01 8.52731824e-01 -1.98089555e-01 7.16237545e-01\n 1.78064518e-02 9.74123001e-01 -4.65186507e-01 2.08609775e-01\n -3.46140146e-01 1.37393892e-01 -4.18608427e-01 9.04833078e-01\n -9.77553308e-01 3.70517135e-01 6.40444756e-01 -2.99479395e-01\n 5.36896050e-01 -5.42365670e-01 8.93876016e-01 1.71238303e-01\n 3.25051665e-01 -6.83692768e-02 9.47566628e-01 2.23502338e-01\n 1.28007397e-01 -4.39013392e-01 7.29371071e-01 5.80122173e-01\n 1.60991013e-01 1.93330556e-01 4.15374190e-01 -4.05230165e-01\n -1.67887732e-01 9.92646635e-01 4.26575214e-01 5.75522184e-01\n -3.94139975e-01 -4.74152654e-01 9.59558129e-01 8.47097561e-02\n 5.75827479e-01 7.81689405e-01 -9.17572320e-01 -9.48397350e-03\n 3.44001323e-01 -2.42110670e-01 8.88915300e-01 -3.82062256e-01\n -3.16388011e-01 5.58285594e-01 -9.34363425e-01 -8.86448503e-01\n -7.98492879e-02 6.78564683e-02 -2.75958240e-01 -8.92499864e-01\n 9.19419155e-02 5.48995793e-01 -5.09750187e-01 -1.11900503e-02\n -3.45329255e-01 -2.84803569e-01 2.08374858e-01 -2.88501978e-01\n 2.86148757e-01 9.88431573e-01 -8.87313008e-01 8.32601905e-01\n 1.46920562e-01 -2.74985790e-01 -2.94848680e-02 9.85050738e-01\n 9.26489532e-02 7.04995155e-01 -8.25527370e-01 2.02754021e-01\n 2.07417578e-01 -1.28589213e-01 -1.04497567e-01 -1.08794712e-01\n 2.25153118e-01 -8.75763237e-01 3.73952948e-02 -3.04542750e-01\n 5.37292123e-01 9.54275727e-01 1.76041070e-02 -5.81141770e-01\n -4.90218634e-03 4.51150477e-01 7.14712322e-01 6.33145452e-01\n -2.75499940e-01 -3.79053682e-01 9.28335011e-01 2.84026209e-02\n 6.16110079e-02 7.17489362e-01 -2.99274385e-01 -5.67422025e-02\n 1.07738394e-02 9.91921544e-01 -2.13262305e-01 -9.21665847e-01\n 2.39030629e-01 9.99178961e-02 -3.22800487e-01 9.56864893e-01\n -6.61775351e-01 -6.73912019e-02 1.60110071e-01 -1.68280751e-01\n 2.46402636e-01 -9.61510062e-01 1.73513353e-01 -6.87632114e-02\n 9.54308867e-01 -1.67690575e-01 -2.42659077e-02 4.36592177e-02\n 2.18984023e-01 3.51428121e-01 8.69773388e-01 2.64591008e-01\n 5.63620627e-01 4.94211823e-01 -3.25244188e-01 3.88565451e-01\n 9.85834241e-01 5.44263959e-01 3.06539565e-01 4.49674100e-01\n -5.38902164e-01 8.67886782e-01 -4.07317311e-01 -5.32693171e-04\n -3.62665623e-01 -4.02425766e-01 2.69155592e-01 4.89823908e-01\n -2.24906579e-01 9.54492033e-01 -9.92338717e-01 1.13659380e-02\n 3.01636189e-01 6.75682127e-01 5.29388487e-01 -2.65024811e-01\n -4.02964242e-02 5.16384721e-01 -7.15067089e-01 8.21951509e-01\n -1.50267288e-01 1.04370557e-01 -4.77084219e-01 5.49224973e-01\n -5.31942070e-01 1.10505320e-01 -3.79302174e-01 5.62100410e-01\n -4.05915707e-01 9.82801259e-01 -3.07678550e-01 2.75442779e-01\n -6.59782737e-02 6.42992258e-01 -1.35645032e-01 3.40809286e-01\n -5.26242107e-02 -3.14343005e-01 -5.32119982e-02 3.47590089e-01\n 4.96242791e-01 -8.04039836e-01 -1.57734469e-01 3.79304975e-01\n 3.98734249e-02 4.94423866e-01 -2.45514184e-01 7.08256304e-01\n -1.24849960e-01 -9.71974671e-01 -1.57309055e-01 -3.66925865e-01\n -1.83910713e-01 -3.14632237e-01 3.90759259e-01 -9.95942116e-01\n -4.27051067e-01 -3.60209465e-01 2.85941899e-01 5.82739674e-02\n 7.66306818e-01 -3.78300607e-01 8.02355632e-02 8.63827825e-01\n -9.59419250e-01 4.22336191e-01 -9.40609694e-01 2.12635696e-02\n 5.18187404e-01 1.03577524e-01 9.92768288e-01 4.79070157e-01\n -4.44664896e-01 -3.16337675e-01 -2.80373007e-01 -8.38278309e-02\n -1.03751212e-01 1.29570663e-01 4.02129322e-01 6.52520964e-03\n 5.86742640e-01 -6.18706286e-01 1.13454061e-02 6.55157089e-01\n 4.09604311e-01 -7.74533510e-01 -4.98954147e-01 -3.50988209e-01\n -8.98442686e-01 -5.64417779e-01 8.01999807e-01 1.97022244e-01\n -8.62517774e-01 5.45354962e-01 -2.70992160e-01 -3.23586375e-01\n 2.09810644e-01 -6.99633300e-01 3.02912444e-01 1.22977145e-01\n -5.01743019e-01 -4.10694063e-01 6.58517629e-02 -4.98637110e-02\n 3.85053128e-01 3.55618298e-01 -3.63109261e-01 8.04028213e-01\n 9.08511400e-01 -7.21787691e-01 7.97966719e-01 8.66559625e-01\n 4.57298011e-01 -6.45893395e-01 -9.87049699e-01 7.26937771e-01\n -8.61046791e-01 8.26805770e-01 -1.83381006e-01 -3.46418649e-01\n -1.99427977e-01 8.01644176e-02 1.48110598e-01 4.03713316e-01\n 4.96271580e-01 -9.81243670e-01 -1.66302457e-01 -5.77868700e-01\n 5.20907402e-01 -4.81067419e-01 8.67391527e-02 -2.65862226e-01\n 1.03038847e-01 9.68874156e-01 3.46484601e-01 -9.15269554e-01\n -3.92081261e-01 -3.09394270e-01 4.70756978e-01 -1.90122306e-01\n 2.37007827e-01 -5.63903689e-01 5.46860754e-01 4.24101651e-01\n -8.42492133e-02 9.46496427e-02 -9.18883920e-01 5.52024424e-01\n 8.91317248e-01 -9.40643787e-01 -3.31612676e-01 4.19453174e-01\n 3.79434377e-01 3.63289446e-01 -6.57454967e-01 7.74625123e-01\n -6.67560637e-01 5.02988279e-01 4.21449076e-03 3.67397875e-01\n 6.30243301e-01 -9.49669182e-01 6.59588099e-01 5.84266484e-01\n 1.63063303e-01 -5.36781669e-01 -4.64435071e-01 9.76355076e-01\n 8.79530072e-01 -2.66306669e-01 5.67190573e-02 -2.87852705e-01\n 3.36986005e-01 -3.98410037e-02 3.15633029e-01 -8.33909631e-01\n -8.34367454e-01 6.65228426e-01 -6.77625775e-01 -4.99591321e-01\n 6.14019513e-01 8.65919888e-01 -2.30581477e-01 -9.79704022e-01\n -4.30613682e-02 -7.38832235e-01 1.09835394e-01 -9.52448010e-01\n -9.50192213e-01 -5.82085729e-01 3.83199006e-01 -5.05550027e-01\n -3.03739995e-01 -2.08606824e-01 5.64597845e-01 5.58340669e-01\n 2.21026689e-01 1.38232782e-01 3.16258788e-01 3.04289043e-01\n -7.32569396e-01 -6.48373246e-01 5.07155061e-01 -4.71735865e-01\n -9.78389919e-01 1.00678861e-01 -5.53452492e-01 5.25807738e-01\n -2.09639311e-01 6.52877688e-01 -4.03372109e-01 -1.15018882e-01\n -2.39910651e-03 -4.64953184e-01 6.83169127e-01 2.70552784e-01\n -9.88207683e-02 6.08950853e-01 3.06698948e-01 -3.06955546e-01\n -8.90627742e-01 -9.78218913e-01 5.03400862e-01 -8.98602247e-01\n 7.82338738e-01 -3.04989815e-01 -8.10894489e-01 -7.35515356e-01\n -6.80099070e-01 -2.28665575e-01 1.95735902e-01 1.83274508e-01\n -9.49299991e-01 -1.37006655e-01 -2.29970142e-02 7.18032837e-01\n 5.87904006e-02 -4.31567043e-01 3.31464291e-01 -8.90901268e-01\n 9.25785124e-01 -4.85297590e-02 -1.11924648e-01 8.98561299e-01\n 1.29477471e-01 8.32387432e-02 2.26755634e-01 -2.47941390e-01\n -7.54342675e-01 -5.35332382e-01 -2.54363149e-01 -4.81249690e-02\n 6.36148930e-01 -5.66637456e-01 5.52833438e-01 1.84904069e-01\n 5.25046706e-01 2.84800619e-01 -6.70616984e-01 -3.28408420e-01\n 4.44959030e-02 -2.61300504e-01 2.90780902e-01 -4.94646400e-01\n -1.74557179e-01 9.66605246e-01 -3.56273860e-01 -8.61494839e-01\n 5.50797164e-01 8.72061551e-01 -4.61241812e-01 -2.57104605e-01\n 1.54799163e-01 9.44333971e-01 -8.43867362e-02 -1.13794059e-01\n 1.70077369e-01 -3.77456509e-02 -1.70079648e-01 -8.33040774e-01\n 9.78971303e-01 3.30343753e-01 -1.01889230e-01 -8.67770195e-01\n 1.67628020e-01 9.65693057e-01 -2.54604369e-01 -2.80050747e-02]]\n[[ 6.53480768e-01 -1.43840566e-01 -5.99308908e-01 6.01705194e-01\n 4.14600492e-01 5.58124900e-01 6.16649508e-01 -9.58911598e-01\n -7.21340179e-01 6.71095014e-01 -9.93975401e-01 -3.05212647e-01\n -4.39885587e-01 -4.82013077e-01 5.42927265e-01 -2.16811761e-01\n 1.71071067e-01 9.98046339e-01 -9.31750797e-03 -9.24615860e-01\n 3.32869679e-01 2.31550843e-01 7.50117064e-01 2.10605338e-01\n -3.90956372e-01 9.46690261e-01 -5.13182163e-01 8.56032446e-02\n 1.07202880e-01 -9.91394162e-01 1.89924106e-01 9.99128044e-01\n 2.59656429e-01 6.94199085e-01 2.27646858e-01 7.06172407e-01\n -2.35258311e-01 -1.72289059e-01 9.51139808e-01 -2.58006513e-01\n -9.99558270e-01 1.91632971e-01 -6.17979109e-01 5.95547557e-01\n -4.64878142e-01 -3.69711518e-01 -2.09167734e-01 4.02582735e-01\n 1.92522481e-01 -1.84122846e-01 -4.75288302e-01 -5.02848387e-01\n -3.94229174e-01 -5.03578246e-01 1.26959279e-01 9.80339050e-01\n 4.23532993e-01 -3.94520521e-01 1.24427579e-01 9.32251751e-01\n -6.28176611e-04 4.63072956e-01 2.64929950e-01 -7.70356357e-01\n -2.54637655e-03 6.41631484e-01 1.93596646e-01 3.69312733e-01\n 8.31471920e-01 -9.90295589e-01 -9.73626018e-01 -7.26304203e-02\n -3.12374234e-01 9.96985495e-01 -5.06689966e-01 -2.04799771e-01\n 9.93704200e-01 -1.92329660e-01 -9.38747168e-01 8.53953958e-01\n 9.82558727e-01 -2.28915308e-02 -2.86787480e-01 3.59737217e-01\n -1.24773607e-01 -4.39394981e-01 -3.37690473e-01 5.06717503e-01\n -9.89135385e-01 6.47398233e-01 8.62137377e-01 4.45224524e-01\n 1.04466900e-01 4.98279035e-01 3.25767368e-01 8.92373562e-01\n 4.60939497e-01 3.82721901e-01 -2.97080904e-01 8.83571863e-01\n -8.98763120e-01 9.01525095e-03 -2.42172241e-01 -2.24356323e-01\n 5.35127580e-01 -5.09495378e-01 2.32242152e-01 1.28968820e-01\n 6.28178194e-02 9.87263381e-01 -6.18235618e-02 3.14719528e-01\n 2.65031636e-01 -4.43871766e-01 -2.80775100e-01 -9.53422308e-01\n -1.67400002e-01 2.43279248e-01 3.06839287e-01 -9.46033537e-01\n -1.47372395e-01 7.59961486e-01 7.97866061e-02 5.00657082e-01\n 1.80484429e-01 -2.67849654e-01 -8.20261002e-01 7.17718840e-01\n -3.83857310e-01 -8.10699999e-01 9.03721511e-01 -8.06748271e-01\n -8.15849960e-01 1.98202491e-01 -1.43234972e-02 -7.93976963e-01\n -6.23255968e-01 -8.13728720e-02 4.54875737e-01 -2.71383494e-01\n 4.07007843e-01 6.67119622e-01 1.75576955e-01 -1.35835065e-02\n -7.39843488e-01 -9.74286422e-02 9.99695659e-01 1.40150934e-01\n 6.46772504e-01 -6.20493293e-01 2.03654096e-01 -7.87953794e-01\n -1.28258377e-01 -6.83955193e-01 -5.91170006e-02 5.63627958e-01\n 1.02194935e-01 -6.80957139e-01 3.51792336e-01 1.26354635e-01\n -1.98032156e-01 -2.08112270e-01 5.27422905e-01 7.07243383e-02\n -4.07974929e-01 7.51406029e-02 7.88648054e-02 9.97878611e-01\n 5.79290032e-01 -4.48777556e-01 -4.92325246e-01 -9.71678913e-01\n -5.71973681e-01 1.99157670e-01 7.75682986e-01 1.16642430e-01\n 5.16976565e-02 -3.17472070e-01 -1.48769125e-01 1.88342303e-01\n 3.66859585e-01 -1.36763379e-01 -1.10722125e-01 -9.11868215e-02\n 1.35787547e-01 -3.46683502e-01 8.10951829e-01 6.83819294e-01\n 8.35428357e-01 1.25674814e-01 -1.63547799e-01 -9.12604406e-02\n 7.53323659e-02 1.99778453e-01 4.48509276e-01 3.75737578e-01\n -1.44538060e-01 -8.71822238e-02 -9.89837706e-01 3.82812619e-01\n 9.25681889e-02 6.40989542e-01 -7.79645070e-02 1.91279158e-01\n 1.28422722e-01 4.45515722e-01 -9.51950908e-01 -9.77003098e-01\n 9.95302975e-01 -2.86174923e-01 7.67715335e-01 -4.68363732e-01\n 9.59131598e-01 7.76151359e-01 -7.05195665e-02 2.12413799e-02\n 1.45163551e-01 -2.70126581e-01 2.48084173e-01 -9.08273220e-01\n -1.42368777e-02 2.10956931e-01 -9.60512757e-01 9.72365588e-02\n -9.31709528e-01 -5.11940598e-01 9.98985231e-01 -4.73020524e-01\n -9.33967173e-01 -8.82082507e-02 -9.79865372e-01 9.65593457e-01\n 1.33636445e-01 -4.76824224e-01 6.23724461e-01 6.53713226e-01\n -1.23341642e-01 6.45165890e-03 -4.93922740e-01 9.09278333e-01\n -1.01907097e-01 -3.40342492e-01 -3.02612692e-01 7.02561796e-01\n -9.46246266e-01 3.83141451e-05 1.53878853e-01 -5.70410252e-01\n 2.42350280e-01 -1.57281816e-01 -3.77168924e-01 -9.69629765e-01\n -1.25652537e-01 -9.95945513e-01 -2.74230033e-01 -9.37802017e-01\n -2.56746560e-01 -2.74552315e-01 -7.52399266e-01 6.69730306e-02\n 8.59171450e-01 -5.26753485e-01 -1.52547717e-01 3.92196953e-01\n 9.29139078e-01 3.79523009e-01 1.46151826e-01 -2.76938468e-01\n -9.14767027e-01 8.43352854e-01 5.61927080e-01 8.81011546e-01\n -3.18971425e-01 2.83269405e-01 9.22022641e-01 -7.96045423e-01\n -4.66395766e-02 8.29901576e-01 -3.85238342e-02 -8.55218694e-02\n 7.60790706e-01 -6.61293268e-02 -9.27527070e-01 -9.54893529e-02\n 9.49364960e-01 -1.46197006e-01 1.62184060e-01 5.44862926e-01\n -2.20568895e-01 -4.42877382e-01 -3.10056269e-01 4.10097271e-01\n -9.88929391e-01 -6.15669265e-02 7.33475506e-01 1.32826552e-01\n 7.65582561e-01 9.39651072e-01 -3.62870283e-02 1.84962958e-01\n -1.46080837e-01 9.03463721e-01 9.14320111e-01 5.32555401e-01\n 5.60911417e-01 2.67042935e-01 -4.14941579e-01 4.81467158e-01\n -1.35486588e-01 2.60620624e-01 -4.49449569e-02 -2.44983256e-01\n -9.74489331e-01 -2.36528188e-01 -9.21330988e-01 -2.12857112e-01\n -4.81533587e-01 1.35736287e-01 5.75938582e-01 3.71464305e-02\n 1.23660766e-01 -6.94408119e-01 1.86968446e-01 -2.90915549e-01\n 2.04057813e-01 -2.31890142e-01 -7.81619251e-01 -1.42477721e-01\n 2.02686325e-01 -1.97120488e-01 -5.77265263e-01 -6.69108570e-01\n 9.70639884e-01 8.75467241e-01 7.47063398e-01 -9.51474369e-01\n 3.60374153e-01 5.07477596e-02 -5.88564873e-01 -2.87495315e-01\n -1.28460646e-01 1.40093088e-01 -9.16797936e-01 -9.88950491e-01\n -5.07084250e-01 9.81470644e-01 2.51676627e-02 5.74510038e-01\n -2.71957219e-01 8.77842247e-01 1.25364929e-01 4.52052027e-01\n 3.00846368e-01 9.71360624e-01 -3.56680661e-01 4.26516265e-01\n -3.45230460e-01 9.83560383e-02 -4.49216634e-01 9.35175896e-01\n -9.92575586e-01 5.74763536e-01 6.03412390e-01 3.41518044e-01\n 4.59572285e-01 -3.22985321e-01 8.47565293e-01 2.16387853e-01\n -4.00207900e-02 3.64080459e-01 2.07985833e-01 3.34938198e-01\n -1.88395455e-01 -5.55840492e-01 6.89115286e-01 3.69255364e-01\n 1.61630690e-01 -2.05653474e-01 1.54025272e-01 -8.33580673e-01\n -2.62436420e-01 9.92544115e-01 8.28782022e-01 9.40437555e-01\n -6.16837978e-01 -5.58730543e-01 9.64283586e-01 -2.55053878e-01\n 9.48724508e-01 1.54121473e-01 -2.98722357e-01 4.94795525e-03\n -1.08906969e-01 -3.03168952e-01 8.09121013e-01 -6.15429223e-01\n -2.51955271e-01 5.52418232e-01 -9.26207662e-01 -9.56575930e-01\n -3.42989206e-01 9.11422074e-01 -1.40734777e-01 -5.80158710e-01\n 6.73902512e-01 3.74571651e-01 -5.12812138e-01 -3.26718122e-01\n -1.20950580e-01 -1.19002379e-01 2.68685102e-01 -2.63925970e-01\n 4.40779150e-01 9.97162104e-01 -8.14093113e-01 1.11626178e-01\n 2.72265851e-01 2.30729654e-01 3.00073862e-01 9.97884631e-01\n -2.50173599e-01 8.59288692e-01 -1.10879689e-02 -3.77397895e-01\n 2.01889291e-01 8.72697607e-02 6.60893461e-03 4.09054041e-01\n 4.31523323e-01 -4.05589342e-01 1.32426724e-01 -5.69005217e-03\n -2.37045437e-02 9.79710996e-01 -1.52717948e-01 -6.96098685e-01\n 6.34506941e-01 2.36732483e-01 4.71968353e-01 3.65580350e-01\n -2.17404410e-01 -6.48020029e-01 8.92871618e-01 -2.16235425e-02\n 4.80114259e-02 6.63853526e-01 -4.07570273e-01 3.87555808e-02\n -2.99336940e-01 9.82006788e-01 3.96746993e-01 -9.25537288e-01\n -2.98201740e-01 1.24138482e-01 -1.43794343e-01 7.11485147e-01\n -9.23261881e-01 1.15458690e-01 -1.53956592e-01 -1.46507084e-01\n 7.18300402e-01 -9.79947805e-01 3.48612756e-01 6.80506304e-02\n 9.54518735e-01 -6.44823760e-02 1.61978409e-01 -2.18598574e-01\n -3.63215387e-01 5.48862100e-01 7.98676252e-01 2.39096999e-01\n -7.96658248e-02 5.82801104e-01 3.69054496e-01 9.59877893e-02\n 9.92134631e-01 6.53817534e-01 3.64709646e-01 3.28833640e-01\n -6.56786501e-01 9.23739791e-01 -5.18227935e-01 -2.86649048e-01\n -4.08470541e-01 -4.49273258e-01 4.50750738e-01 2.17335701e-01\n -5.74271381e-01 9.49764431e-01 -9.93007004e-01 -3.13631475e-01\n 1.48868635e-01 7.27238834e-01 3.81031841e-01 -2.85510361e-01\n -3.79468083e-01 4.74037498e-01 -5.81229687e-01 8.87125432e-01\n 4.69065756e-01 3.62824798e-01 -5.17864704e-01 4.09145653e-01\n -5.64149380e-01 8.93748850e-02 -9.21833888e-02 3.76489073e-01\n -4.52066287e-02 9.97912049e-01 -1.61779583e-01 -1.61617070e-01\n 1.36089683e-01 2.66072214e-01 2.70340383e-01 5.97113669e-01\n -7.73360729e-02 -4.71004933e-01 -4.69834358e-02 4.16981876e-01\n 5.10431707e-01 -3.61792028e-01 -2.41622359e-01 5.34443080e-01\n -3.94362688e-01 4.30666327e-01 -3.65056396e-01 5.81622064e-01\n -3.39737177e-01 -9.69848156e-01 -2.04049438e-01 -5.10346591e-01\n -2.70490378e-01 -1.35022193e-01 4.63186443e-01 -9.95641887e-01\n -1.19801745e-01 -3.45326781e-01 -2.70965815e-01 1.30707249e-01\n 9.03817892e-01 -3.78290921e-01 -9.22128141e-01 9.11013126e-01\n -9.81526434e-01 5.95102191e-01 -9.83862221e-01 1.29723772e-01\n 2.93395936e-01 -1.19054332e-01 8.80592883e-01 5.83256721e-01\n -4.43496406e-01 -1.22176066e-01 -1.45798456e-02 -7.69618005e-02\n -4.46223557e-01 3.54854792e-01 4.53489304e-01 -2.00369731e-01\n 5.51631391e-01 -8.41839164e-02 2.44591728e-01 -2.20477227e-02\n 8.56854677e-01 -6.02107048e-01 -3.21863592e-01 -2.93120354e-01\n -9.45755780e-01 5.46001911e-01 7.04711914e-01 2.97884941e-01\n -9.55772638e-01 7.85251141e-01 -8.25901031e-02 -1.64549202e-01\n 1.86523229e-01 -9.29881632e-01 8.89390111e-01 4.08733748e-02\n -6.03457212e-01 -2.24382713e-01 -7.28708431e-02 -1.20771393e-01\n 7.81059091e-04 -3.04379702e-01 -3.86796534e-01 8.54297161e-01\n 8.43836963e-01 -2.13526845e-01 9.35394764e-01 8.60443473e-01\n 2.20028877e-01 -4.55017328e-01 -9.97728586e-01 8.75143409e-01\n -9.80313540e-01 9.49911177e-01 -5.08085907e-01 1.46845177e-01\n -3.30147505e-01 -2.25001991e-01 -1.13852359e-01 1.02684699e-01\n 4.52265084e-01 -9.07206714e-01 -1.68277055e-01 -7.90753722e-01\n 5.23591697e-01 -1.48892328e-01 1.07168242e-01 -2.57406563e-01\n 3.63316774e-01 9.85661089e-01 1.53454512e-01 -5.88656869e-03\n 3.58549096e-02 1.10809997e-01 9.67220426e-01 -2.35711560e-01\n 1.91445217e-01 -5.23262918e-01 1.43958271e-01 8.74219298e-01\n 2.60549802e-02 -2.26308361e-01 -9.77246404e-01 1.22812793e-01\n 7.86396205e-01 -9.82300043e-01 -2.17780039e-01 5.34655690e-01\n -2.41512328e-01 4.75935161e-01 -7.23892808e-01 6.81115627e-01\n -3.87305737e-01 3.43532473e-01 -6.70308918e-02 4.38866585e-01\n 7.03952193e-01 -9.93271887e-01 7.15507150e-01 1.72049522e-01\n -8.05568814e-01 -3.86812240e-01 -3.33650202e-01 9.53237414e-01\n 7.35326827e-01 -3.88290018e-01 -1.72073785e-02 -4.49467778e-01\n 4.17541802e-01 4.23419505e-01 -1.08785681e-01 -9.08160329e-01\n -1.98901162e-01 6.33777559e-01 -8.93720865e-01 -7.80397296e-01\n 7.83937395e-01 7.61150479e-01 1.29558891e-01 -9.68210995e-01\n -2.92338226e-02 -5.97831488e-01 5.66274859e-02 -8.63814831e-01\n -9.67700958e-01 -3.66063416e-01 -3.61286074e-01 -4.91873920e-01\n -3.35910231e-01 2.98636436e-01 9.75636840e-01 -7.22507358e-01\n 9.04399250e-03 6.74744695e-02 8.74489099e-02 3.22830379e-01\n -4.14730072e-01 -2.50768751e-01 5.36019146e-01 -4.64690745e-01\n -8.35376441e-01 -5.82643569e-01 -3.64639789e-01 6.17056608e-01\n -5.28438628e-01 7.03191280e-01 -1.45842686e-01 3.26173693e-01\n -9.74124297e-02 -2.46217087e-01 1.46307141e-01 2.84685671e-01\n 8.74361917e-02 -1.94888830e-01 1.18408480e-03 9.24179181e-02\n -7.54835367e-01 -9.48575079e-01 -2.30446756e-02 -9.62321639e-01\n 3.50709528e-01 -1.67062908e-01 -8.05419266e-01 -2.31748194e-01\n -1.86394259e-01 -1.20879516e-01 4.69300032e-01 -3.22014689e-01\n -5.97448587e-01 -8.04672599e-01 -2.18456775e-01 7.12823749e-01\n 3.56639862e-01 -4.36244875e-01 5.03347754e-01 -3.59857231e-01\n 8.65983248e-01 5.70911884e-01 -2.62355864e-01 8.19195569e-01\n -1.10847987e-01 3.19968641e-01 3.21835697e-01 -5.74109197e-01\n -7.11413264e-01 -4.39698428e-01 4.39930141e-01 -2.69719511e-01\n 4.71825063e-01 -1.90925494e-01 7.02949047e-01 9.64460447e-02\n 4.79145497e-01 4.70889062e-01 -3.34349461e-04 1.01382263e-01\n 3.00501704e-01 -3.89367044e-01 4.66856450e-01 -4.79996771e-01\n -1.63787127e-01 9.70711231e-01 -1.49074957e-01 -9.03892994e-01\n 8.21646750e-01 4.59624678e-01 -4.73193556e-01 -1.29303813e-01\n -2.33003765e-01 9.74873781e-01 -4.83652800e-01 -6.27087131e-02\n 5.73657393e-01 7.32318521e-01 1.27654582e-01 -8.99042130e-01\n 9.92357135e-01 1.24270715e-01 -3.12426537e-01 -7.28570521e-01\n 1.80867597e-01 8.53180647e-01 -4.72623147e-02 -1.01852156e-01]]\n" ], [ "for x in doc:\n print(x, x.lemma_, x.pos_, x.tag_, x.dep_, x.shape_, x.is_alpha, x.is_stop)", "Aquí aquí ADV ADV advmod Xxxx True True\nhay haber AUX AUX ROOT xxx True True\nalgún alguno DET DET det xxxx True True\notro otro DET DET det xxxx True True\ntexto texto NOUN NOUN obj xxxx True False\n. . PUNCT PUNCT punct . False False\n" ] ], [ [ "**(C) 2021 by [Damir Cavar](http://damir.cavar.me/) <<[email protected]>>**", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
cb25a201ca2750923ad92f7a726d93d49511af9d
13,172
ipynb
Jupyter Notebook
flash_notebooks/image_classification.ipynb
edgarriba/lightning-flash
62472d7615d95990df92a8a2f92f80af1ab737ac
[ "Apache-2.0" ]
1
2021-05-03T06:42:34.000Z
2021-05-03T06:42:34.000Z
flash_notebooks/image_classification.ipynb
edgarriba/lightning-flash
62472d7615d95990df92a8a2f92f80af1ab737ac
[ "Apache-2.0" ]
null
null
null
flash_notebooks/image_classification.ipynb
edgarriba/lightning-flash
62472d7615d95990df92a8a2f92f80af1ab737ac
[ "Apache-2.0" ]
null
null
null
35.031915
633
0.630504
[ [ [ "<a href=\"https://colab.research.google.com/github/PyTorchLightning/lightning-flash/blob/master/flash_notebooks/image_classification.ipynb\" target=\"_parent\">\n <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n</a>", "_____no_output_____" ], [ "In this notebook, we'll go over the basics of lightning Flash by finetuning/predictin with an ImageClassifier on [Hymenoptera Dataset](https://www.kaggle.com/ajayrana/hymenoptera-data) containing ants and bees images.\n\n# Finetuning\n\nFinetuning consists of four steps:\n \n - 1. Train a source neural network model on a source dataset. For computer vision, it is traditionally the [ImageNet dataset](http://www.image-net.org/search?q=cat). As training is costly, library such as [Torchvion](https://pytorch.org/docs/stable/torchvision/index.html) library supports popular pre-trainer model architectures . In this notebook, we will be using their [resnet-18](https://pytorch.org/hub/pytorch_vision_resnet/).\n \n - 2. Create a new neural network called the target model. Its architecture replicates the source model and parameters, expect the latest layer which is removed. This model without its latest layer is traditionally called a backbone\n \n - 3. Add new layers after the backbone where the latest output size is the number of target dataset categories. Those new layers, traditionally called head will be randomly initialized while backbone will conserve its pre-trained weights from ImageNet.\n \n - 4. Train the target model on a target dataset, such as Hymenoptera Dataset with ants and bees. However, freezing some layers at training start such as the backbone tends to be more stable. In Flash, it can easily be done with `trainer.finetune(..., strategy=\"freeze\")`. It is also common to `freeze/unfreeze` the backbone. In `Flash`, it can be done with `trainer.finetune(..., strategy=\"freeze_unfreeze\")`. If one wants more control on the unfreeze flow, Flash supports `trainer.finetune(..., strategy=MyFinetuningStrategy())` where `MyFinetuningStrategy` is subclassing `pytorch_lightning.callbacks.BaseFinetuning`.\n \n \n\n \n\n---\n - Give us a ⭐ [on Github](https://www.github.com/PytorchLightning/pytorch-lightning/)\n - Check out [Flash documentation](https://lightning-flash.readthedocs.io/en/latest/)\n - Check out [Lightning documentation](https://pytorch-lightning.readthedocs.io/en/latest/)\n - Join us [on Slack](https://join.slack.com/t/pytorch-lightning/shared_invite/zt-f6bl2l0l-JYMK3tbAgAmGRrlNr00f1A)", "_____no_output_____" ] ], [ [ "%%capture\n! pip install git+https://github.com/PyTorchLightning/pytorch-flash.git", "_____no_output_____" ] ], [ [ "### The notebook runtime has to be re-started once Flash is installed.", "_____no_output_____" ] ], [ [ "# https://github.com/streamlit/demo-self-driving/issues/17\nif 'google.colab' in str(get_ipython()):\n import os\n os.kill(os.getpid(), 9)", "_____no_output_____" ], [ "import flash\nfrom flash.data.utils import download_data\nfrom flash.vision import ImageClassificationData, ImageClassifier", "_____no_output_____" ] ], [ [ "## 1. Download data\nThe data are downloaded from a URL, and save in a 'data' directory.", "_____no_output_____" ] ], [ [ "download_data(\"https://pl-flash-data.s3.amazonaws.com/hymenoptera_data.zip\", 'data/')", "_____no_output_____" ] ], [ [ "<h2>2. Load the data</h2>\n\nFlash Tasks have built-in DataModules that you can use to organize your data. Pass in a train, validation and test folders and Flash will take care of the rest.\nCreates a ImageClassificationData object from folders of images arranged in this way:</h4>\n\n\n train/dog/xxx.png\n train/dog/xxy.png\n train/dog/xxz.png\n train/cat/123.png\n train/cat/nsdf3.png\n train/cat/asd932.png\n\n\nNote: Each sub-folder content will be considered as a new class.", "_____no_output_____" ] ], [ [ "datamodule = ImageClassificationData.from_folders(\n train_folder=\"data/hymenoptera_data/train/\",\n val_folder=\"data/hymenoptera_data/val/\",\n test_folder=\"data/hymenoptera_data/test/\",\n)", "_____no_output_____" ] ], [ [ "### 3. Build the model\nCreate the ImageClassifier task. By default, the ImageClassifier task uses a [resnet-18](https://pytorch.org/hub/pytorch_vision_resnet/) backbone to train or finetune your model.\nFor [Hymenoptera Dataset](https://www.kaggle.com/ajayrana/hymenoptera-data) containing ants and bees images, ``datamodule.num_classes`` will be 2.\nBackbone can easily be changed with `ImageClassifier(backbone=\"resnet50\")` or you could provide your own `ImageClassifier(backbone=my_backbone)`", "_____no_output_____" ] ], [ [ "model = ImageClassifier(num_classes=datamodule.num_classes)", "_____no_output_____" ] ], [ [ "### 4. Create the trainer. Run once on data\n\nThe trainer object can be used for training or fine-tuning tasks on new sets of data. \n\nYou can pass in parameters to control the training routine- limit the number of epochs, run on GPUs or TPUs, etc.\n\nFor more details, read the [Trainer Documentation](https://pytorch-lightning.readthedocs.io/en/latest/trainer.html).\n\nIn this demo, we will limit the fine-tuning to run just one epoch using max_epochs=2.", "_____no_output_____" ] ], [ [ "trainer = flash.Trainer(max_epochs=3)", "_____no_output_____" ] ], [ [ "### 5. Finetune the model", "_____no_output_____" ] ], [ [ "trainer.finetune(model, datamodule=datamodule, strategy=\"freeze_unfreeze\")", "_____no_output_____" ] ], [ [ "### 6. Test the model", "_____no_output_____" ] ], [ [ "trainer.test()", "_____no_output_____" ] ], [ [ "### 7. Save it!", "_____no_output_____" ] ], [ [ "trainer.save_checkpoint(\"image_classification_model.pt\")", "_____no_output_____" ] ], [ [ "# Predicting", "_____no_output_____" ], [ "### 1. Load the model from a checkpoint", "_____no_output_____" ] ], [ [ "model = ImageClassifier.load_from_checkpoint(\"https://flash-weights.s3.amazonaws.com/image_classification_model.pt\")", "_____no_output_____" ] ], [ [ "### 2a. Predict what's on a few images! ants or bees?", "_____no_output_____" ] ], [ [ "predictions = model.predict([\n \"data/hymenoptera_data/val/bees/65038344_52a45d090d.jpg\",\n \"data/hymenoptera_data/val/bees/590318879_68cf112861.jpg\",\n \"data/hymenoptera_data/val/ants/540543309_ddbb193ee5.jpg\",\n])\nprint(predictions)", "_____no_output_____" ] ], [ [ "### 2b. Or generate predictions with a whole folder!", "_____no_output_____" ] ], [ [ "datamodule = ImageClassificationData.from_folders(predict_folder=\"data/hymenoptera_data/predict/\")\npredictions = flash.Trainer().predict(model, datamodule=datamodule)\nprint(predictions)", "_____no_output_____" ] ], [ [ "<code style=\"color:#792ee5;\">\n <h1> <strong> Congratulations - Time to Join the Community! </strong> </h1>\n</code>\n\nCongratulations on completing this notebook tutorial! If you enjoyed it and would like to join the Lightning movement, you can do so in the following ways!\n\n### Help us build Flash by adding support for new data-types and new tasks.\nFlash aims at becoming the first task hub, so anyone can get started to great amazing application using deep learning. \nIf you are interested, please open a PR with your contributions !!! \n\n\n### Star [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) on GitHub\nThe easiest way to help our community is just by starring the GitHub repos! This helps raise awareness of the cool tools we're building.\n\n* Please, star [Lightning](https://github.com/PyTorchLightning/pytorch-lightning)\n\n### Join our [Slack](https://join.slack.com/t/pytorch-lightning/shared_invite/zt-f6bl2l0l-JYMK3tbAgAmGRrlNr00f1A)!\nThe best way to keep up to date on the latest advancements is to join our community! Make sure to introduce yourself and share your interests in `#general` channel\n\n### Interested by SOTA AI models ! Check out [Bolt](https://github.com/PyTorchLightning/lightning-bolts)\nBolts has a collection of state-of-the-art models, all implemented in [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) and can be easily integrated within your own projects.\n\n* Please, star [Bolt](https://github.com/PyTorchLightning/lightning-bolts)\n\n### Contributions !\nThe best way to contribute to our community is to become a code contributor! At any time you can go to [Lightning](https://github.com/PyTorchLightning/pytorch-lightning) or [Bolt](https://github.com/PyTorchLightning/lightning-bolts) GitHub Issues page and filter for \"good first issue\". \n\n* [Lightning good first issue](https://github.com/PyTorchLightning/pytorch-lightning/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)\n* [Bolt good first issue](https://github.com/PyTorchLightning/lightning-bolts/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)\n* You can also contribute your own notebooks with useful examples !\n\n### Great thanks from the entire Pytorch Lightning Team for your interest !\n\n<img src=\"https://raw.githubusercontent.com/PyTorchLightning/lightning-flash/18c591747e40a0ad862d4f82943d209b8cc25358/docs/source/_static/images/logo.svg\" width=\"800\" height=\"200\" />", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
cb25aaeda484582e03e75145ad136f30c64ca29d
443,321
ipynb
Jupyter Notebook
Data/Transform/cleaning_ntbks/Indicators_EG.ipynb
kfmatovic716/EU-Economy---Data-Visualization
69075ed2118be65b5e747121fbf52e80994ae626
[ "Apache-2.0" ]
null
null
null
Data/Transform/cleaning_ntbks/Indicators_EG.ipynb
kfmatovic716/EU-Economy---Data-Visualization
69075ed2118be65b5e747121fbf52e80994ae626
[ "Apache-2.0" ]
null
null
null
Data/Transform/cleaning_ntbks/Indicators_EG.ipynb
kfmatovic716/EU-Economy---Data-Visualization
69075ed2118be65b5e747121fbf52e80994ae626
[ "Apache-2.0" ]
3
2021-05-12T05:47:50.000Z
2021-05-24T00:42:00.000Z
36.424369
138
0.348154
[ [ [ "import pandas as pd\nimport pathlib\n\n", "_____no_output_____" ], [ "# Store filepath in a variable\nGDP_path = pathlib.Path(\"../Extraction/GDP_per_capita.csv\")", "_____no_output_____" ], [ "# Read and display the CSV with Pandas\nGDP_file_df = pd.read_csv(GDP_path, encoding=\"ISO-8859-1\")\nGDP_file_df", "_____no_output_____" ], [ "# Delete columns: 1960 through 2004, Indicator Name, and Indicator Code)\n\nGDP_DropC_df = GDP_file_df.drop(GDP_file_df.iloc[:, 2:49], axis = 1)\nGDP_DropC_df.head()", "_____no_output_____" ], [ "# Delete column (2020)\n\nGDP_Drop2020_df = GDP_DropC_df.drop(columns=\"2020\")\nGDP_Drop2020_df.head()", "_____no_output_____" ], [ "# List all the columns in the table\nGDP_Drop2020_df.columns", "_____no_output_____" ], [ "# Load in file\nEU_Country_path = \"../Extraction/EU_Countries.csv\"", "_____no_output_____" ], [ "# Read and display the CSV with Pandas\nEU_file_df = pd.read_csv(EU_Country_path)\nGDP_file_df.head()", "_____no_output_____" ], [ "# Merge two dataframes using a left join\nmerge_GDP_df = pd.merge(\n left=EU_file_df, \n right=GDP_Drop2020_df, \n on=\"Country Code\", \n how=\"left\"\n)\n\nmerge_GDP_df", "_____no_output_____" ], [ "# List all the columns in the table\nmerge_GDP_df.columns", "_____no_output_____" ], [ "# Delete column (Country Name_y)\n\nmerge_GDP_df_Clean = (merge_GDP_df\n.drop(columns=\"Country Name_y\")\n.round(decimals=0))\nmerge_GDP_df_Clean.head()", "_____no_output_____" ], [ "# Rename column (Country Name_x)\nFinal_GDP_df_Clean = merge_GDP_df_Clean.rename(columns={\"Country Name_x\":\"Country Name\"})\nFinal_GDP_df_Clean", "_____no_output_____" ], [ "# Unpivot three dataframes.\n\nFV_GDP_df = pd.melt(Final_GDP_df_Clean,id_vars=[\"Country Name\", \"Country Code\"],var_name = 'Year', value_name = 'GDP')\nFV_GDP_df", "_____no_output_____" ], [ "FV_GDP_Sort_df = FV_GDP_df.sort_values(['Country Name', 'Year' ], ascending=[True, True])\nFV_GDP_Sort_df", "_____no_output_____" ], [ "GDP_lag_df = FV_GDP_Sort_df.groupby(['Country Name'])['GDP'].shift(1)\nGDP_lag_df", "_____no_output_____" ], [ "FV_GDP_Sort_df['lastValue'] = \"\"\nFV_GDP_Sort_df", "_____no_output_____" ], [ "FV_GDP_Sort_df['lastValue'] = GDP_lag_df\nFV_GDP_Sort_df", "_____no_output_____" ], [ "FV_GDP_Sort_df.loc[FV_GDP_Sort_df['lastValue'].isnull(),'lastValue'] = FV_GDP_Sort_df['GDP']\nFV_GDP_Sort_df", "_____no_output_____" ], [ "FV_GDP_Sort_df.to_csv(\"Resources/Clean_GDP.csv\", index=False)", "_____no_output_____" ], [ "# Dependencies\nimport pandas as pd\nimport pathlib", "_____no_output_____" ], [ "# Load in file\nCPI_path = \"../Extraction/CPI.csv\"", "_____no_output_____" ], [ "# Read and display the CSV with Pandas\nCPI_file_df = pd.read_csv(CPI_path)\nCPI_file_df.head()", "_____no_output_____" ], [ "# Delete columns: 1960 through 2004, Indicator Name, and Indicator Code)\n\nCPI_DropC_df = CPI_file_df.drop(CPI_file_df.iloc[:, 2:49], axis = 1)\nCPI_DropC_df.head()", "_____no_output_____" ], [ "# Delete column (2020)\n\nCPI_Drop2020_df = CPI_DropC_df.drop(columns=\"2020\")\nCPI_Drop2020_df.head()", "_____no_output_____" ], [ "# List all the columns in the table\nCPI_Drop2020_df.columns", "_____no_output_____" ], [ "# Merge two dataframes using a left join\nmerge_CPI_df = pd.merge(\n left=EU_file_df, \n right=CPI_Drop2020_df, \n on=\"Country Code\", \n how=\"left\"\n)\n\nmerge_CPI_df", "_____no_output_____" ], [ "# Delete column (Country Name_y)\n\nmerge_CPI_df_Clean = merge_CPI_df.drop(columns=\"Country Name_y\")\nmerge_CPI_df_Clean.head()", "_____no_output_____" ], [ "# Rename column (Country Name_x)\nFinal_CPI_df_Clean = merge_CPI_df_Clean.rename(columns={\"Country Name_x\":\"Country Name\"})\nFinal_CPI_df_Clean", "_____no_output_____" ], [ "Final_CPI_df_ND = Final_CPI_df_Clean.round(decimals=2)\nFinal_CPI_df_ND", "_____no_output_____" ], [ "\nFinal_CPI_pc_df = (Final_CPI_df_ND\n .set_index([\"Country Name\", \"Country Code\"])\n .pct_change(axis='columns')\n .drop(['2005'], axis = 1))\nFinal_CPI_pc_df", "_____no_output_____" ], [ "Final_CPI_pc_NI_df = (Final_CPI_pc_df\n.reset_index()\n.round(decimals=3))\nFinal_CPI_pc_NI_df", "_____no_output_____" ], [ "Final_CPI_pc_NI_df[Final_CPI_pc_NI_df.select_dtypes(include=['number']).columns] *= 100\nFinal_CPI_pc_NI_df", "_____no_output_____" ], [ "# Unpivot three dataframes.\n\nFV_CPI_df = pd.melt(Final_CPI_pc_NI_df,id_vars=[\"Country Name\", \"Country Code\"],var_name = 'Year', value_name = 'CPI')\nFV_CPI_df", "_____no_output_____" ], [ "FV_CPI_Sort_df = FV_CPI_df.sort_values(['Country Name', 'Year' ], ascending=[True, True])\nFV_CPI_Sort_df", "_____no_output_____" ], [ "FV_CPI_Sort_df.to_csv(\"Resources/Clean_CPI.csv\", index=False)", "_____no_output_____" ], [ "# Dependencies\nimport pandas as pd\nimport pathlib", "_____no_output_____" ], [ "# Store filepath in a variable\nUnemployment_path = pathlib.Path(\"../Extraction/unemployment.csv\")", "_____no_output_____" ], [ "Unemployment_file = pd.read_csv(Unemployment_path, encoding=\"ISO-8859-1\")\nUnemployment_file", "_____no_output_____" ], [ "# Delete columns: 1960 through 2004, Indicator Name, and Indicator Code)\n\nUnemp_DropC_df = Unemployment_file.drop(Unemployment_file.iloc[:, 2:49], axis = 1)\nUnemp_DropC_df.head()", "_____no_output_____" ], [ "# Delete column (2020)\n\nUnemp_Drop2020_df = Unemp_DropC_df.drop(columns=\"2020\")\nUnemp_Drop2020_df.head()", "_____no_output_____" ], [ "# List all the columns in the table\nUnemp_Drop2020_df.columns", "_____no_output_____" ], [ "# Merge two dataframes using a left join\nmerge_Unemp_df = pd.merge(\n left=EU_file_df, \n right=Unemp_Drop2020_df, \n on=\"Country Code\", \n how=\"left\"\n)\n\nmerge_Unemp_df", "_____no_output_____" ], [ "# Delete column (Country Name_y)\n\nmerge_Unemp_df_Clean = merge_Unemp_df.drop(columns=\"Country Name_y\")\nmerge_Unemp_df_Clean.head()", "_____no_output_____" ], [ "# Rename column (Country Name_x)\nFinal_Unemp_df_Clean = merge_Unemp_df_Clean.rename(columns={\"Country Name_x\":\"Country Name\"})\nFinal_Unemp_df_Clean", "_____no_output_____" ], [ "FV_Unemp_df_ND = Final_Unemp_df_Clean.round(decimals=2)\nFV_Unemp_df_ND", "_____no_output_____" ], [ "# Unpivot three dataframes.\n\nFV_Unemp_df = pd.melt(FV_Unemp_df_ND,id_vars=[\"Country Name\", \"Country Code\"],var_name = 'Year', value_name = 'Unemployment')\nFV_Unemp_df", "_____no_output_____" ], [ "FV_Unemp_df.sort_values(\"Country Name\")", "_____no_output_____" ], [ "FV_Unemp_df_ND = FV_Unemp_df.round(decimals=2)\nFV_Unemp_df_ND", "_____no_output_____" ], [ "FV_Unemp_df_ND.to_csv(\"Resources/Clean_Unemployment.csv\", index=False)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "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" ] ]
cb25ab7422736d1fb205489118f8290cb58badf8
59,208
ipynb
Jupyter Notebook
examples/symbolic_regression.ipynb
patrick-kidger/diffrax
cec091c5e4cc4311f64ae3aa09a371db5fe766ee
[ "Apache-2.0" ]
377
2022-02-07T11:13:56.000Z
2022-03-31T18:35:51.000Z
examples/symbolic_regression.ipynb
patrick-kidger/diffrax
cec091c5e4cc4311f64ae3aa09a371db5fe766ee
[ "Apache-2.0" ]
25
2022-02-08T23:08:11.000Z
2022-03-30T21:21:18.000Z
examples/symbolic_regression.ipynb
patrick-kidger/diffrax
cec091c5e4cc4311f64ae3aa09a371db5fe766ee
[ "Apache-2.0" ]
15
2022-02-08T04:46:23.000Z
2022-03-30T20:53:10.000Z
166.783099
46,340
0.87929
[ [ [ "# Symbolic Regression", "_____no_output_____" ], [ "This example combines neural differential equations with regularised evolution to discover the equations\n\n$\\frac{\\mathrm{d} x}{\\mathrm{d} t}(t) = \\frac{y(t)}{1 + y(t)}$\n\n$\\frac{\\mathrm{d} y}{\\mathrm{d} t}(t) = \\frac{-x(t)}{1 + x(t)}$\n\ndirectly from data.\n\n**References:**\n\nThis example appears as an example in:\n\n```bibtex\n@phdthesis{kidger2021on,\n title={{O}n {N}eural {D}ifferential {E}quations},\n author={Patrick Kidger},\n year={2021},\n school={University of Oxford},\n}\n```\n\nWhilst drawing heavy inspiration from:\n\n```bibtex\n@inproceedings{cranmer2020discovering,\n title={{D}iscovering {S}ymbolic {M}odels from {D}eep {L}earning with {I}nductive\n {B}iases},\n author={Cranmer, Miles and Sanchez Gonzalez, Alvaro and Battaglia, Peter and\n Xu, Rui and Cranmer, Kyle and Spergel, David and Ho, Shirley},\n booktitle={Advances in Neural Information Processing Systems},\n publisher={Curran Associates, Inc.},\n year={2020},\n}\n\n@software{cranmer2020pysr,\n title={PySR: Fast \\& Parallelized Symbolic Regression in Python/Julia},\n author={Miles Cranmer},\n publisher={Zenodo},\n url={http://doi.org/10.5281/zenodo.4041459},\n year={2020},\n}\n```\n\nThis example is available as a Jupyter notebook [here](https://github.com/patrick-kidger/diffrax/blob/main/examples/symbolic_regression.ipynb).", "_____no_output_____" ] ], [ [ "import tempfile\nfrom typing import List\n\nimport equinox as eqx # https://github.com/patrick-kidger/equinox\nimport jax\nimport jax.numpy as jnp\nimport optax # https://github.com/deepmind/optax\nimport pysr # https://github.com/MilesCranmer/PySR\nimport sympy\n\n\n# Note that PySR, which we use for symbolic regression, uses Julia as a backend.\n# You'll need to install a recent version of Julia if you don't have one.\n# (And can get funny errors if you have a too-old version of Julia already.)\n# You may also need to restart Python after running `pysr.install()` the first time.\npysr.silence_julia_warning()\npysr.install(quiet=True)", "_____no_output_____" ] ], [ [ "Now for a bunch of helpers. We'll use these in a moment; skip over them for now.", "_____no_output_____" ] ], [ [ "def quantise(expr, quantise_to):\n if isinstance(expr, sympy.Float):\n return expr.func(round(float(expr) / quantise_to) * quantise_to)\n elif isinstance(expr, sympy.Symbol):\n return expr\n else:\n return expr.func(*[quantise(arg, quantise_to) for arg in expr.args])\n\n\nclass SymbolicFn(eqx.Module):\n fn: callable\n parameters: jnp.ndarray\n\n def __call__(self, x):\n # Dummy batch/unbatching. PySR assumes its JAX'd symbolic functions act on\n # tensors with a single batch dimension.\n return jnp.squeeze(self.fn(x[None], self.parameters))\n\n\nclass Stack(eqx.Module):\n modules: List[eqx.Module]\n\n def __call__(self, x):\n return jnp.stack([module(x) for module in self.modules], axis=-1)\n\n\ndef expr_size(expr):\n return sum(expr_size(v) for v in expr.args) + 1\n\n\ndef _replace_parameters(expr, parameters, i_ref):\n if isinstance(expr, sympy.Float):\n i_ref[0] += 1\n return expr.func(parameters[i_ref[0]])\n elif isinstance(expr, sympy.Symbol):\n return expr\n else:\n return expr.func(\n *[_replace_parameters(arg, parameters, i_ref) for arg in expr.args]\n )\n\n\ndef replace_parameters(expr, parameters):\n i_ref = [-1] # Distinctly sketchy approach to making this conversion.\n return _replace_parameters(expr, parameters, i_ref)", "_____no_output_____" ] ], [ [ "Okay, let's get started.\n\nWe start by running the [Neural ODE example](./neural_ode.ipynb).\nThen we extract the learnt neural vector field, and symbolically regress across this.\nFinally we fine-tune the resulting symbolic expression.\n", "_____no_output_____" ] ], [ [ "def main(\n symbolic_dataset_size=2000,\n symbolic_num_populations=100,\n symbolic_population_size=20,\n symbolic_migration_steps=4,\n symbolic_mutation_steps=30,\n symbolic_descent_steps=50,\n pareto_coefficient=2,\n fine_tuning_steps=500,\n fine_tuning_lr=3e-3,\n quantise_to=0.01,\n):\n #\n # First obtain a neural approximation to the dynamics.\n # We begin by running the previous example.\n #\n\n # Runs the Neural ODE example.\n # This defines the variables `ts`, `ys`, `model`.\n print(\"Training neural differential equation.\")\n %run neural_ode.ipynb\n\n #\n # Now symbolically regress across the learnt vector field, to obtain a Pareto\n # frontier of symbolic equations, that trades loss against complexity of the\n # equation. Select the \"best\" from this frontier.\n #\n\n print(\"Symbolically regressing across the vector field.\")\n vector_field = model.func.mlp # noqa: F821\n dataset_size, length_size, data_size = ys.shape # noqa: F821\n in_ = ys.reshape(dataset_size * length_size, data_size) # noqa: F821\n in_ = in_[:symbolic_dataset_size]\n out = jax.vmap(vector_field)(in_)\n with tempfile.TemporaryDirectory() as tempdir:\n symbolic_regressor = pysr.PySRRegressor(\n niterations=symbolic_migration_steps,\n ncyclesperiteration=symbolic_mutation_steps,\n populations=symbolic_num_populations,\n npop=symbolic_population_size,\n optimizer_iterations=symbolic_descent_steps,\n optimizer_nrestarts=1,\n procs=1,\n verbosity=0,\n tempdir=tempdir,\n temp_equation_file=True,\n output_jax_format=True,\n )\n symbolic_regressor.fit(in_, out)\n best_equations = symbolic_regressor.get_best()\n expressions = [b.sympy_format for b in best_equations]\n symbolic_fns = [\n SymbolicFn(b.jax_format[\"callable\"], b.jax_format[\"parameters\"])\n for b in best_equations\n ]\n\n #\n # Now the constants in this expression have been optimised for regressing across\n # the neural vector field. This was good enough to obtain the symbolic expression,\n # but won't quite be perfect -- some of the constants will be slightly off.\n #\n # To fix this we now plug our symbolic function back into the original dataset\n # and apply gradient descent.\n #\n\n print(\"Optimising symbolic expression.\")\n\n symbolic_fn = Stack(symbolic_fns)\n flat, treedef = jax.tree_flatten(\n model, is_leaf=lambda x: x is model.func.mlp # noqa: F821\n )\n flat = [symbolic_fn if f is model.func.mlp else f for f in flat] # noqa: F821\n symbolic_model = jax.tree_unflatten(treedef, flat)\n\n @eqx.filter_grad\n def grad_loss(symbolic_model):\n vmap_model = jax.vmap(symbolic_model, in_axes=(None, 0))\n pred_ys = vmap_model(ts, ys[:, 0]) # noqa: F821\n return jnp.mean((ys - pred_ys) ** 2) # noqa: F821\n\n optim = optax.adam(fine_tuning_lr)\n opt_state = optim.init(eqx.filter(symbolic_model, eqx.is_inexact_array))\n\n @eqx.filter_jit\n def make_step(symbolic_model, opt_state):\n grads = grad_loss(symbolic_model)\n updates, opt_state = optim.update(grads, opt_state)\n symbolic_model = eqx.apply_updates(symbolic_model, updates)\n return symbolic_model, opt_state\n\n for _ in range(fine_tuning_steps):\n symbolic_model, opt_state = make_step(symbolic_model, opt_state)\n\n #\n # Finally we round each constant to the nearest multiple of `quantise_to`.\n #\n\n trained_expressions = []\n for module, expression in zip(symbolic_model.func.mlp.modules, expressions):\n expression = replace_parameters(expression, module.parameters.tolist())\n expression = quantise(expression, quantise_to)\n trained_expressions.append(expression)\n\n print(f\"Expressions found: {trained_expressions}\")", "_____no_output_____" ], [ "main()", "Training neural differential equation.\nStep: 0, Loss: 0.1665748506784439, Computation time: 24.18653130531311\nStep: 100, Loss: 0.011155527085065842, Computation time: 0.09058809280395508\nStep: 200, Loss: 0.006481727119535208, Computation time: 0.0928184986114502\nStep: 300, Loss: 0.001382559770718217, Computation time: 0.09850335121154785\nStep: 400, Loss: 0.001073717838153243, Computation time: 0.09830045700073242\nStep: 499, Loss: 0.0007992316968739033, Computation time: 0.09975647926330566\nStep: 0, Loss: 0.02832634374499321, Computation time: 24.61294913291931\nStep: 100, Loss: 0.005440382286906242, Computation time: 0.40324854850769043\nStep: 200, Loss: 0.004360489547252655, Computation time: 0.43680524826049805\nStep: 300, Loss: 0.001799552352167666, Computation time: 0.4346010684967041\nStep: 400, Loss: 0.0017023109830915928, Computation time: 0.437793493270874\nStep: 499, Loss: 0.0011540694395080209, Computation time: 0.42920470237731934\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb25ab8b798daaed2c75cd69344e2a5431546de5
296,861
ipynb
Jupyter Notebook
src/archive/AE.ipynb
RiceD2KLab/TCH_CardiacSignals_F20
ea6e84703086ddb7bfc5ba164aa67acdc9e78b7d
[ "BSD-2-Clause" ]
1
2022-01-27T07:03:20.000Z
2022-01-27T07:03:20.000Z
src/archive/AE.ipynb
RiceD2KLab/TCH_CardiacSignals_F20
ea6e84703086ddb7bfc5ba164aa67acdc9e78b7d
[ "BSD-2-Clause" ]
null
null
null
src/archive/AE.ipynb
RiceD2KLab/TCH_CardiacSignals_F20
ea6e84703086ddb7bfc5ba164aa67acdc9e78b7d
[ "BSD-2-Clause" ]
null
null
null
276.922575
17,451
0.58651
[ [ [ "# %cd /Users/Kunal/Projects/TCH_CardiacSignals_F20/\n", "C:\\Users\\ksrai\\Projects\\TCH_CardiacSignals_F20\\TCH_CardiacSignals_F20\n" ], [ "from numpy.random import seed\nseed(1)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport tensorflow\ntensorflow.random.set_seed(2)\nfrom tensorflow import keras\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.regularizers import l1, l2\nfrom tensorflow.keras.layers import Dense, Flatten, Reshape, Input, InputLayer, Dropout, Conv1D, MaxPooling1D, BatchNormalization, UpSampling1D, Conv1DTranspose\nfrom tensorflow.keras.models import Sequential, Model\nfrom src.preprocess.dim_reduce.patient_split import *\nfrom src.preprocess.heartbeat_split import heartbeat_split\nfrom sklearn.model_selection import train_test_split\n", "_____no_output_____" ], [ "def read_in(file_index, normalized, train, ratio):\n \"\"\"\n Reads in a file and can toggle between normalized and original files\n :param file_index: patient number as string\n :param normalized: binary that determines whether the files should be normalized or not\n :param train: int that determines whether or not we are reading in data to train the model or for encoding\n :param ratio: ratio to split the files into train and test\n :return: returns npy array of patient data across 4 leads\n \"\"\"\n # filepath = os.path.join(\"Working_Data\", \"Normalized_Fixed_Dim_HBs_Idx\" + file_index + \".npy\")\n # filepath = os.path.join(\"Working_Data\", \"1000d\", \"Normalized_Fixed_Dim_HBs_Idx35.npy\")\n filepath = \"Working_Data/Training_Subset/Normalized/two_hbs/Normalized_Fixed_Dim_HBs_Idx\" + str(file_index) + \".npy\"\n\n if normalized == 1:\n if train == 1:\n normal_train, normal_test, abnormal = patient_split_train(filepath, ratio)\n # noise_factor = 0.5\n # noise_train = normal_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=normal_train.shape)\n return normal_train, normal_test\n elif train == 0:\n training, test, full = patient_split_all(filepath, ratio)\n return training, test, full\n elif train == 2:\n train_, test, full = patient_split_all(filepath, ratio)\n noise_factor = 0.5\n noise_train = train_ + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=train_.shape)\n return train_, noise_train, test, full\n else:\n data = np.load(os.path.join(\"Working_Data\", \"Fixed_Dim_HBs_Idx\" + file_index + \".npy\"))\n return data", "_____no_output_____" ], [ "def build_model(sig_shape, encode_size):\n \"\"\"\n Builds a deterministic autoencoder model, returning both the encoder and decoder models\n :param sig_shape: shape of input signal\n :param encode_size: dimension that we want to reduce to\n :return: encoder, decoder models\n \"\"\"\n encoder = Sequential()\n encoder.add(InputLayer(sig_shape))\n encoder.add(Flatten())\n encoder.add(Dense(200, activation='tanh', kernel_initializer='glorot_normal'))\n encoder.add(Dense(125, activation='relu', kernel_initializer='glorot_normal'))\n encoder.add(Dense(100, activation='relu', kernel_initializer='glorot_normal'))\n encoder.add(Dense(50, activation='relu', kernel_initializer='glorot_normal'))\n encoder.add(Dense(25, activation='relu', kernel_initializer='glorot_normal'))\n encoder.add(Dense(encode_size))\n\n # Decoder\n decoder = Sequential()\n decoder.add(InputLayer((encode_size,)))\n decoder.add(Dense(25, activation='relu', kernel_initializer='glorot_normal'))\n decoder.add(Dense(50, activation='relu', kernel_initializer='glorot_normal'))\n decoder.add(Dense(100, activation='relu', kernel_initializer='glorot_normal'))\n decoder.add(Dense(125, activation='relu', kernel_initializer='glorot_normal'))\n decoder.add(Dense(200, activation='tanh', kernel_initializer='glorot_normal'))\n decoder.add(Dense(np.prod(sig_shape), activation='linear'))\n decoder.add(Reshape(sig_shape))\n\n return encoder, decoder", "_____no_output_____" ], [ "def training_ae(num_epochs, reduced_dim, file_index):\n \"\"\"\n Training function for deterministic autoencoder model, saves the encoded and reconstructed arrays\n :param num_epochs: number of epochs to use\n :param reduced_dim: goal dimension\n :param file_index: patient number\n :return: None\n \"\"\"\n normal, abnormal, all = read_in(file_index, 1, 0, 0.3)\n normal_train = normal[:round(len(normal)*.85),:]\n normal_valid = normal[round(len(normal)*.85):,:]\n signal_shape = normal.shape[1:]\n batch_size = round(len(normal) * 0.1)\n\n encoder, decoder = build_model(signal_shape, reduced_dim)\n\n encode = encoder(Input(signal_shape))\n reconstruction = decoder(encode)\n\n inp = Input(signal_shape)\n encode = encoder(inp)\n reconstruction = decoder(encode)\n\n autoencoder = Model(inp, reconstruction)\n opt = keras.optimizers.Adam(learning_rate=0.0008)\n autoencoder.compile(optimizer=opt, loss='mse')\n\n early_stopping = EarlyStopping(patience=10, min_delta=0.0001, mode='min')\n autoencoder = autoencoder.fit(x=normal_train, y=normal_train, epochs=num_epochs, validation_data=(normal_valid, normal_valid), batch_size=batch_size, callbacks=early_stopping)\n\n plt.plot(autoencoder.history['loss'])\n plt.plot(autoencoder.history['val_loss'])\n plt.title('model loss patient' + str(file_index))\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.show()\n # save out the model\n # filename = 'ae_patient_' + str(file_index) + '_dim' + str(reduced_dim) + '_model'\n # autoencoder.save(filename + '.h5')\n # print('Model saved for ' + 'patient ' + str(file_index))\n\n # using AE to encode other data\n encoded = encoder.predict(all)\n reconstruction = decoder.predict(encoded)\n\n # save reconstruction, encoded, and input if needed\n # reconstruction_save = os.path.join(\"Working_Data\", \"reconstructed_ae_\" + str(reduced_dim) + \"d_Idx\" + str(file_index) + \".npy\")\n # encoded_save = os.path.join(\"Working_Data\", \"reduced_ae_\" + str(reduced_dim) + \"d_Idx\" + str(file_index) + \".npy\")\n\n reconstruction_save = \"Working_Data/Training_Subset/Model_Output/reconstructed_2hb_ae_\" + str(file_index) + \".npy\"\n encoded_save = \"Working_Data/Training_Subset/Model_Output/encoded_2hb_ae_\" + str(file_index) + \".npy\"\n\n np.save(reconstruction_save, reconstruction)\n np.save(encoded_save,encoded)\n\n # if training and need to save test split for MSE calculation\n # input_save = os.path.join(\"Working_Data\",\"1000d\", \"original_data_test_ae\" + str(100) + \"d_Idx\" + str(35) + \".npy\")\n # np.save(input_save, test)", "_____no_output_____" ], [ "def run(num_epochs, encoded_dim):\n \"\"\"\n Run training autoencoder over all dims in list\n :param num_epochs: number of epochs to train for\n :param encoded_dim: dimension to run on\n :return None, saves arrays for reconstructed and dim reduced arrays\n \"\"\"\n for patient_ in [1,16,4,11]: #heartbeat_split.indicies:\n print(\"Starting on index: \" + str(patient_))\n training_ae(num_epochs, encoded_dim, patient_)\n print(\"Completed \" + str(patient_) + \" reconstruction and encoding, saved test data to assess performance\")\n\n", "_____no_output_____" ], [ "#################### Training to be done for 100 epochs for all dimensions ############################################\nrun(100, 10)\n\n# run(100,100)", "Starting on index: 1\nEpoch 1/100\n9/9 [==============================] - 0s 47ms/step - loss: 0.8349 - val_loss: 0.4565\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 6/100\n9/9 [==============================] - 0s 23ms/step - loss: 0.1051 - val_loss: 0.2187\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 7/100\n9/9 [==============================] - 0s 24ms/step - loss: 0.1035 - val_loss: 0.2113\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 8/100\n9/9 [==============================] - 0s 29ms/step - loss: 0.1026 - val_loss: 0.2056\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 13/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0950 - val_loss: 0.1888\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 14/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0816 - val_loss: 0.1731\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 15/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0679 - val_loss: 0.1597\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 16/100\n9/9 [==============================] - 0s 21ms/step - loss: 0.0625 - val_loss: 0.1564\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 17/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0610 - val_loss: 0.1558\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 18/100\n9/9 [==============================] - 0s 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\b\b\b\b\b\b\b\b\nEpoch 22/100\n9/9 [==============================] - 0s 24ms/step - loss: 0.0499 - val_loss: 0.1591\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 23/100\n9/9 [==============================] - 0s 24ms/step - loss: 0.0459 - val_loss: 0.1585\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 24/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0431 - val_loss: 0.1561\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 25/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0412 - val_loss: 0.1577\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 26/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0419 - val_loss: 0.1523\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\b\b\b\b\b\b\b\b\nEpoch 29/100\n9/9 [==============================] - 0s 24ms/step - loss: 0.0367 - val_loss: 0.1502\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 30/100\n9/9 [==============================] - 0s 22ms/step - loss: 0.0358 - val_loss: 0.1471\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 31/100\n9/9 [==============================] - 0s 24ms/step - loss: 0.0350 - val_loss: 0.1453\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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/100\n9/9 [==============================] - 0s 24ms/step - loss: 0.0268 - val_loss: 0.1208\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 51/100\n9/9 [==============================] - 0s 32ms/step - loss: 0.0265 - val_loss: 0.1212\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 52/100\n9/9 [==============================] - 0s 23ms/step - loss: 0.0261 - val_loss: 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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 67/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0217 - val_loss: 0.1254\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nCompleted 1 reconstruction and encoding, saved test data to assess performance\nStarting on index: 16\nEpoch 1/100\n9/9 [==============================] - 0s 36ms/step - loss: 0.9154 - val_loss: 0.7378\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\nEpoch 4/100\n9/9 [==============================] - 0s 23ms/step - loss: 0.1740 - val_loss: 0.1032\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 5/100\n9/9 [==============================] - 0s 23ms/step - loss: 0.0906 - val_loss: 0.0548\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 6/100\n9/9 [==============================] - 0s 30ms/step - loss: 0.0526 - val_loss: 0.0373\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 7/100\n9/9 [==============================] - 0s 23ms/step - loss: 0.0395 - val_loss: 0.0321\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 8/100\n9/9 [==============================] - 0s 23ms/step - loss: 0.0356 - val_loss: 0.0302\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\b\nEpoch 17/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0277 - val_loss: 0.0219\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 18/100\n9/9 [==============================] - 0s 24ms/step - loss: 0.0271 - val_loss: 0.0214\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 19/100\n9/9 [==============================] - 0s 25ms/step - loss: 0.0264 - val_loss: 0.0207\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\nEpoch 66/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0175 - val_loss: 0.0157\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 67/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0173 - val_loss: 0.0160\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 68/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0173 - val_loss: 0.0157\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 69/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0171 - val_loss: 0.0155\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 70/100\n9/9 [==============================] - 0s 27ms/step - loss: 0.0169 - val_loss: 0.0154\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 100/100\n9/9 [==============================] - 0s 30ms/step - loss: 0.0130 - val_loss: 0.0137\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nCompleted 16 reconstruction and encoding, saved test data to assess performance\nStarting on index: 4\nEpoch 1/100\n9/9 [==============================] - 0s 52ms/step - loss: 0.9344 - val_loss: 0.7269\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\b\b\b\b\nEpoch 20/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.0452 - val_loss: 0.0696\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 21/100\n9/9 [==============================] - 0s 27ms/step - loss: 0.0451 - val_loss: 0.0696\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 22/100\n9/9 [==============================] - 0s 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\b\b\b\b\b\b\b\b\b\b\b\nEpoch 44/100\n9/9 [==============================] - 0s 27ms/step - loss: 0.0228 - val_loss: 0.0288\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 45/100\n9/9 [==============================] - 0s 30ms/step - loss: 0.0222 - val_loss: 0.0283\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 46/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.0219 - val_loss: 0.0275\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 47/100\n9/9 [==============================] - 0s 27ms/step - loss: 0.0217 - val_loss: 0.0270\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 48/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.0215 - val_loss: 0.0266\b\b\b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/100\n9/9 [==============================] - 0s 29ms/step - loss: 0.0197 - val_loss: 0.0234\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 66/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0196 - val_loss: 0.0234\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 67/100\n9/9 [==============================] - 0s 29ms/step - loss: 0.0196 - val_loss: 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b\b\b\b\b\b\nEpoch 71/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0188 - val_loss: 0.0225\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 72/100\n9/9 [==============================] - 0s 27ms/step - loss: 0.0186 - val_loss: 0.0220\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 73/100\n9/9 [==============================] - 0s 30ms/step - loss: 0.0183 - val_loss: 0.0220\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 74/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0182 - val_loss: 0.0230\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 75/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.0191 - val_loss: 0.0220\b\b\b\b\b\b\b\b\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b\b\b\b\b\b\b\b\nEpoch 83/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0167 - val_loss: 0.0199\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 84/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.0163 - val_loss: 0.0197\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 85/100\n9/9 [==============================] - 0s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b\b\b\b\b\b\b\b\b\b\nEpoch 95/100\n9/9 [==============================] - 0s 26ms/step - loss: 0.0153 - val_loss: 0.0184\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 96/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.0152 - val_loss: 0.0184\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 97/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.0153 - val_loss: 0.0183\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 98/100\n9/9 [==============================] - 0s 29ms/step - loss: 0.0154 - val_loss: 0.0186\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 99/100\n9/9 [==============================] - 0s 29ms/step - loss: 0.0153 - val_loss: 0.0179\b\b\b\b\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b\b\b\b\b\b\b\b\b\b\b\nCompleted 4 reconstruction and encoding, saved test data to assess performance\nStarting on index: 11\nEpoch 1/100\n9/9 [==============================] - 0s 42ms/step - loss: 0.8752 - val_loss: 0.6906\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 2/100\n9/9 [==============================] - 0s 28ms/step - loss: 0.3992 - val_loss: 0.4624\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\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b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b - 0s 35ms/step - loss: 0.0268 - val_loss: 0.1766\nEpoch 90/100\n9/9 [==============================] - 0s 32ms/step - loss: 0.0268 - val_loss: 0.1760\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 91/100\n9/9 [==============================] - 0s 33ms/step - loss: 0.0266 - val_loss: 0.1757\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nEpoch 100/100\n9/9 [==============================] - 0s 30ms/step - loss: 0.0253 - val_loss: 0.1723\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\nCompleted 11 reconstruction and encoding, saved test data to assess performance\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
cb25b0a853937fabfe0bece2f0eb4fbd443cb975
4,739
ipynb
Jupyter Notebook
Dev/S3 connection test.ipynb
vertechcon/jupyter
7fa26c1b8dfe638900ecf5d4c06fd66bd8bf3235
[ "Apache-2.0" ]
null
null
null
Dev/S3 connection test.ipynb
vertechcon/jupyter
7fa26c1b8dfe638900ecf5d4c06fd66bd8bf3235
[ "Apache-2.0" ]
1
2020-07-15T01:53:28.000Z
2020-07-15T01:53:28.000Z
Dev/S3 connection test.ipynb
vertechcon/jupyter
7fa26c1b8dfe638900ecf5d4c06fd66bd8bf3235
[ "Apache-2.0" ]
null
null
null
24.811518
95
0.549905
[ [ [ "# S3 Connection and and test operations", "_____no_output_____" ], [ "[Website for documentation](https://docs.min.io/docs/python-client-api-reference.html) \n", "_____no_output_____" ] ], [ [ "%run /jupyter/importer.py", "Appending finder\n" ], [ "from Libs.Storage import StorageClient", "Libs.Storage.StorageClient\n['/jupyter/Libs/Storage']\nafter split: StorageClient\npath: \n['/jupyter/Libs/Storage']\n/jupyter/Libs/Storage/StorageClient.ipynb\nafter split: StorageClient\npath: \n['/jupyter/Libs/Storage']\n/jupyter/Libs/Storage/StorageClient.ipynb\nimporting Jupyter notebook from /jupyter/Libs/Storage/StorageClient.ipynb\nLibs.Storage.Contracts\n['/jupyter/Libs/Storage']\nafter split: Contracts\npath: \n['/jupyter/Libs/Storage']\n/jupyter/Libs/Storage/Contracts.ipynb\nafter split: Contracts\npath: \n['/jupyter/Libs/Storage']\n/jupyter/Libs/Storage/Contracts.ipynb\nimporting Jupyter notebook from /jupyter/Libs/Storage/Contracts.ipynb\nLibs.Storage.MinioProvider\n['/jupyter/Libs/Storage']\nafter split: MinioProvider\npath: \n['/jupyter/Libs/Storage']\n/jupyter/Libs/Storage/MinioProvider.ipynb\nafter split: MinioProvider\npath: \n['/jupyter/Libs/Storage']\n/jupyter/Libs/Storage/MinioProvider.ipynb\nimporting Jupyter notebook from /jupyter/Libs/Storage/MinioProvider.ipynb\nLibs.ModulesManagement\n['/jupyter/Libs']\nafter split: ModulesManagement\npath: \n['/jupyter/Libs']\n/jupyter/Libs/ModulesManagement.ipynb\nafter split: ModulesManagement\npath: \n['/jupyter/Libs']\n/jupyter/Libs/ModulesManagement.ipynb\nimporting Jupyter notebook from /jupyter/Libs/ModulesManagement.ipynb\nModules found.\n['minio==5.0.10']\nModule already installed.\nConfig\nNone\nafter split: Config\npath: \n['/jupyter']\n/jupyter/Config.ipynb\nafter split: Config\npath: \n['/jupyter']\n/jupyter/Config.ipynb\nimporting Jupyter notebook from /jupyter/Config.ipynb\nModules found.\n['pyyaml==3.13']\nModule already installed.\nLibs.file_utils\n['/jupyter/Libs']\nafter split: file_utils\npath: \n['/jupyter/Libs']\n/jupyter/Libs/file_utils.ipynb\nafter split: file_utils\npath: \n['/jupyter/Libs']\n/jupyter/Libs/file_utils.ipynb\nimporting Jupyter notebook from /jupyter/Libs/file_utils.ipynb\n" ], [ "client = StorageClient.create_client(ctype=StorageClient.ClientType.Minio)", "_____no_output_____" ], [ "client.authenticate()", "_____no_output_____" ], [ "client.list_buckets()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ] ]
cb25caa4b33ec0bdc2bc223372eeb70765bab54d
178,575
ipynb
Jupyter Notebook
Conn Logs/Conn Log Clustering - TCP.ipynb
UVA-DSI-2019-Capstones/UVACyber
9ab75501b5fbb91d86162c657ba50dfc7b07a711
[ "MIT" ]
null
null
null
Conn Logs/Conn Log Clustering - TCP.ipynb
UVA-DSI-2019-Capstones/UVACyber
9ab75501b5fbb91d86162c657ba50dfc7b07a711
[ "MIT" ]
null
null
null
Conn Logs/Conn Log Clustering - TCP.ipynb
UVA-DSI-2019-Capstones/UVACyber
9ab75501b5fbb91d86162c657ba50dfc7b07a711
[ "MIT" ]
2
2018-09-27T22:47:12.000Z
2019-02-05T00:06:54.000Z
207.887078
22,544
0.888596
[ [ [ "import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.decomposition import PCA # Principal Component Analysis module\nfrom sklearn.cluster import KMeans # KMeans clustering \nimport matplotlib.pyplot as plt # Python defacto plotting library\nimport seaborn as sns # More snazzy plotting library\nimport pylab as pl\n%matplotlib inline ", "_____no_output_____" ], [ "#TCP Conn Logs\n# import pandas as pd\n# import os\n# os.chdir(\"/home/rk9cx/HP/\")\n# df = pd.read_csv(\"10_08_conn_logs_tcp.csv\", index_col=False, header=None)\n# df.columns =[\"ts\",\"uid\",\"src_ip\",\"src_port\",\"resp_ip\",\"resp_port\",\"duration\",\"orig_bytes\",\"resp_bytes\",\"conn_state\",\n# \"history\",\"orig_pkts\",\"resp_pkts\",\"tunnel_parents\",\"local\"]\n# cols_num = [\"resp_port\",\"duration\",\"orig_bytes\",\"resp_bytes\",\"orig_pkts\",\"resp_pkts\"]\n# df[cols_num] = df[cols_num].apply(pd.to_numeric, errors='coerce')\n# cols_char = [\"src_ip\",\"resp_ip\"]\n# df[cols_char] = df[cols_char].astype(str)\ndf.head()", "_____no_output_____" ], [ "df_clean = pd.DataFrame(df.groupby('src_ip').agg({'src_port': 'nunique','resp_port': 'nunique', 'resp_ip': 'nunique',\n 'duration': 'mean','orig_bytes':'sum',\n 'resp_bytes':'sum','orig_pkts':'sum',\n 'resp_pkts':'sum'}))\ndf_clean.reset_index(inplace=True)\ndf_clean.head()", "_____no_output_____" ], [ "df_clean = df_clean.dropna()\ndf_clean.shape", "_____no_output_____" ], [ "Y = df_clean.loc[:,df_clean.columns == 'src_ip']\nX = df_clean.loc[:, df_clean.columns != 'src_ip']", "_____no_output_____" ], [ "Nc = range(1, 20)\nkmeans = [KMeans(n_clusters=i) for i in Nc]\nscore = [kmeans[i].fit(X).score(X) for i in range(len(kmeans))]\npl.plot(Nc,score)\npl.xlabel('Number of Clusters')\npl.ylabel('Score')\npl.title('Elbow Curve')\npl.show()", "_____no_output_____" ], [ "#Scaling \nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nX_scaled = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)", "_____no_output_____" ], [ "km = KMeans(n_clusters=3).fit(X_scaled)\ndf_clean['cluster'] = km.labels_\nX_scaled['cluster'] = km.labels_", "_____no_output_____" ], [ "df_clean[\"cluster\"].unique()", "_____no_output_____" ], [ "df_clean.groupby('cluster').size()", "_____no_output_____" ], [ "final_df = df_clean", "_____no_output_____" ], [ "import numpy as np\nimport matplotlib.pyplot as plt\nplt.scatter(df[\"orig_bytes\"], df[\"resp_bytes\"] )", "_____no_output_____" ], [ "plt.scatter(final_df[\"orig_pkts\"], final_df[\"resp_pkts\"] , c=final_df[\"cluster\"])", "_____no_output_____" ], [ "#removing outliers from pkts\np = final_df[\"orig_pkts\"].quantile(0.99)\nq = final_df[\"resp_pkts\"].quantile(0.99)\nr = final_df[\"orig_bytes\"].quantile(0.99)\ns = final_df[\"resp_bytes\"].quantile(0.99)\ntest = final_df.loc[(final_df['orig_pkts'] < p) & (final_df['resp_pkts'] < q) &\n (final_df['orig_bytes'] < r) & (final_df['resp_bytes'] < s),]\ntest.shape", "_____no_output_____" ], [ "fig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('orig_pkts', fontsize = 15)\nax.set_ylabel('resp_pkts', fontsize = 15)\nax.set_title('Clustering', fontsize = 20)\ntargets = [0,1,2]\ncolors = ['r', 'g','y']\nfor target, color in zip(targets,colors):\n indicesToKeep = test['cluster'] == target\n ax.scatter(test.loc[indicesToKeep, 'orig_pkts']\n , test.loc[indicesToKeep, 'resp_pkts']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()", "_____no_output_____" ], [ "fig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('orig_bytes', fontsize = 15)\nax.set_ylabel('resp_bytes', fontsize = 15)\nax.set_title('Clustering', fontsize = 20)\ntargets = [0,1,2]\ncolors = ['r', 'g','y']\nfor target, color in zip(targets,colors):\n indicesToKeep = test['cluster'] == target\n ax.scatter(test.loc[indicesToKeep, 'orig_bytes']\n , test.loc[indicesToKeep, 'resp_bytes']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()", "_____no_output_____" ], [ "#removing outliers from pkts\np = X_scaled[\"orig_pkts\"].quantile(0.90)\nq = X_scaled[\"resp_pkts\"].quantile(0.90)\nr = X_scaled[\"orig_bytes\"].quantile(0.90)\ns = X_scaled[\"resp_bytes\"].quantile(0.90)\ntest = X_scaled.loc[(X_scaled['orig_pkts'] < p) & (X_scaled['orig_pkts'] < q) &\n (X_scaled['orig_bytes'] < r) & (X_scaled['resp_bytes'] < s),]\ntest.shape", "_____no_output_____" ], [ "#plt.scatter(final_df[\"resp_ip\"], final_df[\"resp_port\"] , c=final_df[\"cluster\"])\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('resp_ip', fontsize = 15)\nax.set_ylabel('resp_port', fontsize = 15)\nax.set_title('Clustering', fontsize = 20)\ntargets = [0,1,2]\ncolors = ['r', 'g','y']\nfor target, color in zip(targets,colors):\n indicesToKeep = test['cluster'] == target\n ax.scatter(test.loc[indicesToKeep, 'resp_ip']\n , test.loc[indicesToKeep, 'resp_port']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()", "_____no_output_____" ], [ "#plt.scatter(final_df[\"resp_ip\"], final_df[\"duration\"] , c=final_df[\"cluster\"])\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('resp_ip', fontsize = 15)\nax.set_ylabel('duration', fontsize = 15)\nax.set_title('Clustering', fontsize = 20)\ntargets = [0,1,2]\ncolors = ['r', 'g','y']\nfor target, color in zip(targets,colors):\n indicesToKeep = test['cluster'] == target\n ax.scatter(test.loc[indicesToKeep, 'resp_ip']\n , test.loc[indicesToKeep, 'duration']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()", "_____no_output_____" ], [ "#plt.scatter(final_df[\"resp_port\"], final_df[\"src_port\"] , c=final_df[\"cluster\"])\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('resp_port', fontsize = 15)\nax.set_ylabel('src_port', fontsize = 15)\nax.set_title('Clustering', fontsize = 20)\ntargets = [0,1,2]\ncolors = ['r', 'g','y']\nfor target, color in zip(targets,colors):\n indicesToKeep = test['cluster'] == target\n ax.scatter(test.loc[indicesToKeep, 'resp_port']\n , test.loc[indicesToKeep, 'src_port']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()", "_____no_output_____" ], [ "#plt.scatter(test[\"resp_pkts\"], test[\"resp_bytes\"] , c=test[\"cluster\"])\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nax.set_xlabel('resp_pkts', fontsize = 15)\nax.set_ylabel('resp_bytes', fontsize = 15)\nax.set_title('Clustering', fontsize = 20)\ntargets = [0,1,2]\ncolors = ['r', 'g','y']\nfor target, color in zip(targets,colors):\n indicesToKeep = test['cluster'] == target\n ax.scatter(test.loc[indicesToKeep, 'resp_pkts']\n , test.loc[indicesToKeep, 'resp_bytes']\n , c = color\n , s = 50)\nax.legend(targets)\nax.grid()", "_____no_output_____" ], [ "#UDP Conn Logs\nimport pandas as pd\nimport os\nos.chdir(\"/home/rk9cx/HP/\")\ndf_udp = pd.read_csv(\"10_08_2018_udp.csv\", index_col=False, header=None)\ndf_udp.columns =[\"ts\",\"uid\",\"src_ip\",\"src_port\",\"resp_ip\",\"resp_port\",\"duration\",\"orig_bytes\",\"resp_bytes\",\"conn_state\",\n \"history\",\"orig_pkts\",\"resp_pkts\",\"tunnel_parents\",\"local\"]\ncols_num = [\"resp_port\",\"duration\",\"orig_bytes\",\"resp_bytes\",\"orig_pkts\",\"resp_pkts\"]\ndf_udp[cols_num] = df_udp[cols_num].apply(pd.to_numeric, errors='coerce')\ncols_char = [\"src_ip\",\"resp_ip\"]\ndf_udp[cols_char] = df_udp[cols_char].astype(str)\ndf_udp.dtypes", "_____no_output_____" ], [ "#Other Conn Logs\nimport pandas as pd\nimport os\nos.chdir(\"/home/rk9cx/HP/\")\ndf_other = pd.read_csv(\"10_08_2018_Other.csv\", index_col=False, header=None)\ndf_other.columns =[\"ts\",\"uid\",\"src_ip\",\"src_port\",\"resp_ip\",\"resp_port\",\"duration\",\"orig_bytes\",\"resp_bytes\",\"conn_state\",\n \"history\",\"orig_pkts\",\"resp_pkts\",\"tunnel_parents\",\"local\"]\ncols_num = [\"resp_port\",\"duration\",\"orig_bytes\",\"resp_bytes\",\"orig_pkts\",\"resp_pkts\"]\ndf_other[cols_num] = df_other[cols_num].apply(pd.to_numeric, errors='coerce')\ncols_char = [\"src_ip\",\"resp_ip\"]\ndf_other[cols_char] = df_other[cols_char].astype(str)\ndf_other.dtypes", "_____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" ] ]
cb25cfc75236057a10b898159df08cdd1e99d01f
9,118
ipynb
Jupyter Notebook
Lecture_03.ipynb
dirtScrapper/Stats-110-master
a123692d039193a048ff92f5a7389e97e479eb7e
[ "BSD-3-Clause" ]
null
null
null
Lecture_03.ipynb
dirtScrapper/Stats-110-master
a123692d039193a048ff92f5a7389e97e479eb7e
[ "BSD-3-Clause" ]
null
null
null
Lecture_03.ipynb
dirtScrapper/Stats-110-master
a123692d039193a048ff92f5a7389e97e479eb7e
[ "BSD-3-Clause" ]
null
null
null
38.310924
241
0.468853
[ [ [ "# Lecture 3: Birthday Problem, Properties of Probability", "_____no_output_____" ], [ "## The Birthday Problem\nGiven $k$ people, what is the probability of at least 2 people having the same birthday?\n\nFirst, we need to define the problem:\n\n1. there are 365 days in a year (no leap-years)\n1. births can be on any day with equal probability (birthdays are independent of one another)\n1. treat people as distinguishable, because.\n\n$k \\le 1$ is meaningless, so we will not consider those cases.\n\nNow consider the case where you have more people than there are days in a year. In such a case, \n\n$$ P(k\\ge365) = 1$$\n\nNow think about the event of _no matches_. We can compute this probability using the na&iuml;ve definition of probability:\n\n$$ P(\\text{no match}) = \\frac{365 \\times 364 \\times \\cdots \\times 365-k+1}{365^k} $$\n\nNow the event of _at least one match_ is the complement of _no matches_, so \n\n\\begin{align}\n P(\\text{at least one match}) &= 1 - P(\\text{no match}) \\\\\n &= 1 - \\frac{365 \\times 364 \\times \\cdots \\times 365-k+1}{365^k}\n\\end{align}\n\n", "_____no_output_____" ] ], [ [ "def bday_prob(k):\n def no_match(k):\n num = 1.0\n for n in [(365-e) for e in range(k)]:\n num *= n \n return num / 365**k \n return 1.0 - no_match(k) \n\nprint(\"At k=23 people, the probability of a match is {:0f}, already exceeding 0.5.\".format(bday_prob(23)))\nprint(\"And at k=50 people, the probability of a match is {:0f} is very close to 1.0.\".format(bday_prob(50)))", "At k=23 people, the probability of a match is 0.507297, already exceeding 0.5.\nAnd at k=50 people, the probability of a match is 0.970374 is very close to 1.0.\n" ] ], [ [ "## Properties\n\nLet's derive some properties using nothing but the 2 axioms stated earlier.\n\n### Property 1\n> _The probability of an event $A$ is 1 minus the probability of that event's inverse (or complement)._\n>\n> \\begin\\{align\\}\n> P(A^{c}) &= 1 - P(A) \\\\\\\\\n> \\\\\\\\\n> \\because 1 &= P(S) \\\\\\\\\n> &= P(A \\cup A^{c}) \\\\\\\\\n> &= P(A) + P(A^{c}) & \\quad \\text{since } A \\cap A^{c} = \\emptyset ~~ \\blacksquare\n> \\end\\{align\\}\n\n### Property 2\n\n> _If $A$ is contained within $B$, then the probability of $A$ must be less than or equal to that for $B$._\n>\n> \\begin\\{align\\}\n> \\text{If } A &\\subseteq B \\text{, then } P(A) \\leq P(B) \\\\\\\\\n> \\\\\\\\\n> \\because B &= A \\cup ( B \\cap A^{c}) \\\\\\\\\n> P(B) &= P(A) + P(B \\cap A^{c}) \\\\\\\\\n> \\\\\\\\\n> \\implies P(B) &\\geq P(A) \\text{, since } P(B \\cap A^{c}) \\geq 0 & \\quad \\blacksquare\n> \\end\\{align\\}\n\n### Property 3, or the Inclusion/Exclusion Principle\n\n_The probability of a union of 2 events $A$ and $B$_\n\n> \\begin\\{align\\}\n> P(A \\cup B) &= P(A) + P(B) - P(A \\cap B) \\\\\\\\\n> \\\\\\\\\n> \\text{since } P(A \\cup B) &= P(A \\cup (B \\cap A^{c})) \\\\\\\\\n> &= P(A) + P(B \\cap A^{c}) \\\\\\\\ \n> \\\\\\\\\n> \\text{but note that } P(B) &= P(B \\cap A) + P(B \\cap A^{c}) \\\\\\\\\n> \\text{and since } P(B) - P(A \\cap B) &= P(B \\cap A^{c}) \\\\\\\\\n> \\\\\\\\\n> \\implies P(A \\cup B) &= P(A) + P(B) - P(A \\cap B) ~~~~ \\blacksquare\n> \\end\\{align\\}\n\n![title](images/L0301.png)\n\nThis is the simplest case of the [principle of inclusion/exclusion](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle).\n\nConsidering the 3-event case, we have:\n\n> \\begin\\{align\\}\n> P(A \\cup B \\cup C) &= P(A) + P(B) + P(C) - P(A \\cap B) - P(B \\cap C) - P(A \\cap C) + P(A \\cap B \\cap C)\n> \\end\\{align\\}\n>\n> ...where we sum up all of the separate events;\n> and then subtract each of the pair-wise intersections;\n> and finally add back in that 3-event intersection since that was subtracted in the previous step.\n\n![title](images/L0302.png)\n\nFor the general case, we have:\n\n$$\n P(A_1 \\cup A_2 \\cup \\cdots \\cup A_n) = \\sum_{j=1}^n P(A_{j}) - \\sum_{i<j} P(A_i \\cap A_j) + \\sum_{i<j<k} P(A_i \\cap A_j \\cap A_k) \\cdots + (-1)^{n-1} P(A_1 \\cap A_2 \\cap \\cdots \\cap A_n)\n$$\n\n... where we\n- sum up all of the separate events\n- subtract the sums of all _even-numbered_ index intersections\n- add back the sums of all _odd-numbered_ index intersections", "_____no_output_____" ], [ "## de Montmort's problem (1713)\n\nAgain from a gambling problem, say we have a deck of $n$ cards, labeled 1 through $n$. The deck is thoroughly shuffled. The cards are then flipped over, one at a time. A win is when the card labeled $k$ is the $k^{th}$ card flipped.\n\nWhat is the probability of a win?\n\nLet $A_k$ be the event that card $k$ is the $k^{th}$ card flipped. The probability of a win is when _at least one of the $n$ cards_ is in the correct position. Therefore, what we are interested in is\n\n$$ P(A_1 \\cup A_2 \\cup \\cdots \\cup A_n) $$\n\nNow, consider the following:\n\n\\begin\\{align\\}\n P(A_1) &= \\frac{1}{n} & \\quad \\text{since all outcomes are equally likely} \\\\\\\\\n P(A_1 \\cap A_2) &= \\frac{1}{n} \\left(\\frac{1}{n-1}\\right) = \\frac{(n-2)!}{n!} \\\\\\\\\n &\\vdots \\\\\\\\\n P(A_1 \\cap A_2 \\cap \\cdots \\cap A_k) &= \\frac{(n-k)!}{n!} & \\quad \\text{because, symmetry} \\\\\\\\\n\\end\\{align\\}", "_____no_output_____" ], [ "Which leads us to:\n\n\\begin{align}\n P(A_1 \\cup A_2 \\cup \\cdots \\cup A_k) &= \\binom{n}{1}\\frac{1}{n} - \\binom{n}{2}\\frac{1}{n(n-1)} + \\binom{n}{3}\\frac{1}{n(n-1)(n-2)} - \\cdots \\\\\\\\\n &= n \\frac{1}{n} - \\left(\\frac{n(n-1)}{2!}\\right)\\frac{1}{n(n-1)} + \\left(\\frac{n(n-1)(n-2)}{3!}\\right)\\frac{1}{n(n-1)(n-2)} - \\cdots \\\\\\\\\n &= 1 - \\frac{1}{2!} + \\frac{1}{3!} - \\frac{1}{4!} \\cdots (-1)^{n-1}\\frac{1}{n!} \\\\\\\\\n &= 1 - \\sum_{k=1}^{\\infty} \\frac{(-1)^{k-1}}{k!} \\\\\\\\\n &= 1 - \\frac{1}{e} \\\\\\\\\n \\\\\\\\\n \\text{ since } e^{-1} &= \\frac{(-1)^0}{0!} + \\frac{-1}{1!} + \\frac{(-1)^2}{2!} + \\frac{(-1)^3}{3!} + \\cdots + \\frac{(-1)^n}{n!} ~~~~ \\text{ from the Taylor expansion of } e^{x}\n\\end{align}", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
cb25de24eb2636f86d9d2bec7ef184ef1958578a
1,046
ipynb
Jupyter Notebook
extension/examples/2.ipynb
WatVis/EDAssistant
a4be2849a65abcf2f81f9c01a2172ec67aa38853
[ "BSD-3-Clause" ]
null
null
null
extension/examples/2.ipynb
WatVis/EDAssistant
a4be2849a65abcf2f81f9c01a2172ec67aa38853
[ "BSD-3-Clause" ]
null
null
null
extension/examples/2.ipynb
WatVis/EDAssistant
a4be2849a65abcf2f81f9c01a2172ec67aa38853
[ "BSD-3-Clause" ]
null
null
null
15.848485
34
0.471319
[ [ [ "def zap(x):\n x[1]=\"zap\"", "_____no_output_____" ], [ "a=[1,2,3]\nzap(a)", "_____no_output_____" ], [ "b=a[2]", "_____no_output_____" ], [ "print(b)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
cb25e66e680b7e2196dc2535763f3773ec65d93f
10,827
ipynb
Jupyter Notebook
notebooks/session_5/Episode_1/minipy_edgar1.ipynb
drliangjin/little-python-book
301e9c870dad72371947e4956bee8c44d06eb659
[ "MIT" ]
12
2018-05-04T10:02:04.000Z
2018-06-27T21:40:18.000Z
notebooks/session_5/Episode_1/minipy_edgar1.ipynb
drliangjin/little-python-book
301e9c870dad72371947e4956bee8c44d06eb659
[ "MIT" ]
1
2019-12-27T00:28:49.000Z
2019-12-27T00:28:49.000Z
notebooks/session_5/Episode_1/minipy_edgar1.ipynb
drliangjin/little-python-book
301e9c870dad72371947e4956bee8c44d06eb659
[ "MIT" ]
5
2019-03-13T14:36:16.000Z
2020-01-09T14:05:46.000Z
22.55625
161
0.532188
[ [ [ "# Web Data Extraction (1)\nby Dr Liang Jin\n\n- Step 1: access crawler.idx files from SEC EDGAR\n- Step 2: re-write crawler data to csv files\n- Step 3: retrieve 10K filing information including URLs\n- Step 4: read text from html", "_____no_output_____" ], [ "## Step 0: Setup...", "_____no_output_____" ] ], [ [ "# import packages as usual\nimport os, requests, csv, webbrowser\nfrom urllib.request import urlopen, urlretrieve\nfrom bs4 import BeautifulSoup", "_____no_output_____" ], [ "# define some global variables such as sample periods\nbeg_yr = 2016\nend_yr = 2017", "_____no_output_____" ] ], [ [ "## Step 1: Access Crawler.idx Files...\nSEC stores tons of filings in its archives and fortunately they provide index files. We can access to the index files using following url as an example:\n\n[https://www.sec.gov/Archives/edgar/full-index/](https://www.sec.gov/Archives/edgar/full-index/)\n\nAnd individual crawler.idx files are stored in a structured way:\n\n`https://www.sec.gov/Archives/edgar/full-index/{}/{}/crawler.idx`\nwhere `{ }/{ }` are year and quarter", "_____no_output_____" ] ], [ [ "# create a list containning all the URLs for .idx file\nidx_urls = []\nfor year in range(beg_yr, end_yr+1):\n for qtr in ['QTR1', 'QTR2', 'QTR3', 'QTR4']:\n idx_url = 'https://www.sec.gov/Archives/edgar/full-index/{}/{}/crawler.idx'.format(year, qtr)\n idx_urls.append(idx_url)", "_____no_output_____" ], [ "# check on our URLs\nidx_urls", "_____no_output_____" ], [ "# let's try downloading one of the files\nurlretrieve(idx_urls[0], './example.idx');", "_____no_output_____" ] ], [ [ "### Task 1: Have a look at the downloaded file?", "_____no_output_____" ], [ "## Step 2: Rewrite Crawler data into CSV files...\nThe original Crawler.idx files come with extra information:\n- **Company Name**: hmmm...not really useful\n- **Form Type**: i.e., 10K, 10Q and others\n- **CIK**: Central Index Key, claimed to be unique key to identify entities in SEC universe\n- **Date Filed**: the exact filing date, NOTE, it is not necessary to be the reporting date\n- **URL**: filing page address which contains the link to the actual filing in HTML format\n- **Meta-data** on the crawler.idx itself\n- **Other information** including headers and seperators", "_____no_output_____" ], [ "### Retrieve the data inside the .idx file", "_____no_output_____" ] ], [ [ "# Ok, let's get cracking\nurl = idx_urls[0]\n\n# use requests package to access the contents\nr = requests.get(url)\n\n# then focus on the text data only and split the whole file into lines\nlines = r.text.splitlines()", "_____no_output_____" ] ], [ [ "### Raw data processing", "_____no_output_____" ] ], [ [ "# Let's peek the contents\nlines[:10]", "_____no_output_____" ], [ "# identify the location of the header row\n# its the eighth row, so in Python the index is 7\nheader_loc = 7\n# double check\nlines[header_loc]", "_____no_output_____" ], [ "# retrieve the location of individual columns\nname_loc = lines[header_loc].find('Company Name')\ntype_loc = lines[header_loc].find('Form Type')\ncik_loc = lines[header_loc].find('CIK')\ndate_loc = lines[header_loc].find('Date Filed')\nurl_loc = lines[header_loc].find('URL')", "_____no_output_____" ] ], [ [ "### Re-organise the data", "_____no_output_____" ] ], [ [ "# identify the location of the first row\n# its NO.10 row, so in Python the index is 9\nfirstdata_loc = 9\n# double check\nlines[firstdata_loc]", "_____no_output_____" ], [ "# create an empty list\nrows = []\n\n# loop through lines in .idx file\nfor line in lines[firstdata_loc:]:\n \n # collect the data from the begining until the char before 485BPOS (Form Type)\n # then strip the string, i.e., removing the heading and trailing white spaces\n company_name = line[:type_loc].strip()\n form_type = line[type_loc:cik_loc].strip()\n cik = line[cik_loc:date_loc].strip()\n date_filed = line[date_loc:url_loc].strip()\n page_url = line[url_loc:].strip()\n \n # store these collected data to a row (tuple)\n row = (company_name, form_type, cik, date_filed, page_url)\n # then append this row to the empty list rows\n rows.append(row)", "_____no_output_____" ] ], [ [ "### Task 2: Can you update the codes to store 10-K file only?", "_____no_output_____" ] ], [ [ "# peek again\nrows[:5]", "_____no_output_____" ] ], [ [ "### Write to CSV file", "_____no_output_____" ] ], [ [ "# where to write?\n# define directory to store data\ncsv_dir = './CSV/' # recommend to put this on top\n\n# a future-proof way to create directory\n# only create the folder when there is no existing one\nif not os.path.isdir(csv_dir):\n os.mkdir(csv_dir)", "_____no_output_____" ], [ "# But file names? since we will have multiple files to process eventually\n\n# create file name based on the original idx file\n_ = url.split('/')\n_", "_____no_output_____" ] ], [ [ "How about create a sensible naming scheme can be easily refered to?\n\nHow about something like **2017Q4**?", "_____no_output_____" ] ], [ [ "# get year from idx URL\nfile_yr = url.split('/')[-3]\n\n# get quarter from idx URL\nfile_qtr = url.split('/')[-2][-1]\n\n# Combine year, quarter, and extension to create file name\nfile_name = file_yr + \"Q\" + file_qtr + '.csv'\n\n# then create a path so that we can write the data to local drive\nfile_path = os.path.join(csv_dir, file_name)", "_____no_output_____" ], [ "# Check on the path\nfile_path", "_____no_output_____" ], [ "# create and write to csv file\nwith open(file_path, 'w') as wf:\n writer = csv.writer(wf, delimiter = ',')\n writer.writerows(rows)", "_____no_output_____" ] ], [ [ "### Task 3: Can you loop through idx files from 2016 to 2017?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
cb2638fb6c5e94dac71f785c7eac47df5e11f7d9
130
ipynb
Jupyter Notebook
blktrace_graph_clean.ipynb
Honghe/blktrace_hdfs_and_fio
c9ca776f3460caba28b0d410e1d29b2708573a7d
[ "Apache-2.0" ]
null
null
null
blktrace_graph_clean.ipynb
Honghe/blktrace_hdfs_and_fio
c9ca776f3460caba28b0d410e1d29b2708573a7d
[ "Apache-2.0" ]
null
null
null
blktrace_graph_clean.ipynb
Honghe/blktrace_hdfs_and_fio
c9ca776f3460caba28b0d410e1d29b2708573a7d
[ "Apache-2.0" ]
null
null
null
32.5
75
0.884615
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb2648664d49d65d347f60bdc76f820b2417bef5
397,830
ipynb
Jupyter Notebook
lessons/notebooks/Latent-Variable-Models-and-VB.ipynb
bertdv/BMLIP
58920c0117efb019f2256c9ef3ca6ed65db69544
[ "CC-BY-3.0" ]
10
2019-09-14T17:34:14.000Z
2022-01-22T18:29:11.000Z
lessons/notebooks/Latent-Variable-Models-and-VB.ipynb
charlielu05/BMLIP
70c4c3810e0fdea42d611b6c4aab9003506dc243
[ "CC-BY-3.0" ]
34
2019-08-09T15:49:10.000Z
2021-11-14T10:19:28.000Z
lessons/notebooks/Latent-Variable-Models-and-VB.ipynb
charlielu05/BMLIP
70c4c3810e0fdea42d611b6c4aab9003506dc243
[ "CC-BY-3.0" ]
11
2020-03-18T14:05:09.000Z
2022-01-04T14:35:32.000Z
214.463612
164,910
0.892512
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb264b3a243ff5e7549bf1470d8ad8b88b2030e3
42,172
ipynb
Jupyter Notebook
examples_ja/myWork_001_clustering.ipynb
fkubota/Wildqat
6e9ec982fb7c8ecf175697e92eda9411caef83e5
[ "Apache-2.0" ]
null
null
null
examples_ja/myWork_001_clustering.ipynb
fkubota/Wildqat
6e9ec982fb7c8ecf175697e92eda9411caef83e5
[ "Apache-2.0" ]
null
null
null
examples_ja/myWork_001_clustering.ipynb
fkubota/Wildqat
6e9ec982fb7c8ecf175697e92eda9411caef83e5
[ "Apache-2.0" ]
null
null
null
157.947566
18,484
0.891326
[ [ [ "# Introduction\n- wildqat を使って クラスタリングを行ってみる\n- 簡単のため、クラスタ数は2で行う", "_____no_output_____" ], [ "# Let's import everything I nead :)", "_____no_output_____" ] ], [ [ "import wildqat as wq\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_blobs", "_____no_output_____" ] ], [ [ "# How To\n- wildqatにQUBOを投げる準備として、損失関数を構築する必要がある\n- 今回は損失関数を以下のように定義した\n - `異なるクラスタ間のエッジの長さの総和が最大のとき最小値をとる`\n\n$$\nE_0 = \\sum_{i=1}^{N}\\sum_{j=1}^{N} L(i,j) (q_i - q_j)^2\n$$\n\nあとはいい感じにする\n\n$$\nE_0 = \\sum_{i=1}^{N} \\left \\{ - \\sum_j ^N L(i,j) \\right \\} q_i + \\sum_{i<j}^{N} \\left \\{2 L(i,j) \\right \\} q_i q_j\n$$", "_____no_output_____" ], [ "# Preparation", "_____no_output_____" ] ], [ [ "X, Y = make_blobs(n_samples=200, \n n_features=2, \n cluster_std=2,\n centers=2)\n\nsample = X\n# sample = [[0,0], [0,1], [np.sqrt(3),0]]\n# sample = [[0,0], [0,1], [3,3], [4,1], [1,2], [3,1], [0.5,0.5], [3.5,2]]\n\n\nfig, ax = plt.subplots(figsize=(10*1.73, 10))\nfor point in sample:\n x = point[0]\n y = point[1]\n ax.scatter(x, y, color='black')", "_____no_output_____" ], [ "def L(sample, i, j):\n p1 = sample[i]\n p1x = p1[0]\n p1y = p1[1]\n p2 = sample[j]\n p2x = p2[0]\n p2y = p2[1]\n \n length = np.sqrt((p2x-p1x)**2 + (p2y-p1y)**2)\n return length\n ", "_____no_output_____" ], [ "L(sample, 0,2)", "_____no_output_____" ] ], [ [ "# Calculation", "_____no_output_____" ] ], [ [ "a = wq.opt()\nN = len(sample)\na.qubo = np.zeros((N, N))\nfor i in range(N):\n for j in range(N):\n if i == j:\n Lsum = sum([ L(sample, i, _j) for _j in range(N) ])\n a.qubo[i][i] = - Lsum\n elif i<j:\n# a.qubo[i][j]=2*numbers[i] * numbers[j] + alpha*2\n a.qubo[i][j] = 2 * L(sample, i, j)\n\nfor _ in range(1):\n answer = np.array(a.sa())\n print('answer: ', answer)\n E0 = 0\n for i in range(N):\n for j in range(N):\n# print('valu', L(sample, i, j), answer[i], answer[j])\n E0 += -L(sample, i, j) * (answer[i] - answer[j])**2\n print(E0)\n print('-----------')", "answer: [1 0 0 1 0 0 0 0 1 1 1 1 0 0 1 0 0 1 0 1 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 0 0\n 0 1 0 0 0 1 1 0 1 0 1 0 1 0 1 1 1 0 0 0 0 0 1 1 1 1 1 0 1 0 1 0 1 1 1 0 0\n 1 1 1 1 1 0 0 1 0 1 1 0 0 0 1 0 0 0 0 0 1 0 1 0 1 1 0 0 0 1 0 0 1 1 0 1 0\n 0 1 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 1 0 0 0 0 0 1 0 1 0\n 1 0 0 1 1 1 1 1 1 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 1 0 0 0 1 1 0 0 1 1 0 1\n 1 0 1 0 0 1 1 1 0 0 1 1 0 0 0]\n-283133.9908486351\n-----------\n" ], [ "# fig, ax = plt.subplots(figsize=(10, 10))\nfig, ax = plt.subplots(figsize=(10*1.73, 10))\nfor i, point in enumerate(sample):\n x = point[0]\n y = point[1]\n if answer[i] == 0:\n ax.scatter(x, y, color='red')\n elif answer[i] == 1:\n ax.scatter(x, y, color='blue')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb26620081d36f5a28ba0ecea4a13226f4c0264b
15,834
ipynb
Jupyter Notebook
notebooks/ordered_probit_v2.ipynb
JakartaLaw/bayesianfactormodel
0a75412d965ae2ed5c093315cb27f82d4a578590
[ "MIT" ]
null
null
null
notebooks/ordered_probit_v2.ipynb
JakartaLaw/bayesianfactormodel
0a75412d965ae2ed5c093315cb27f82d4a578590
[ "MIT" ]
null
null
null
notebooks/ordered_probit_v2.ipynb
JakartaLaw/bayesianfactormodel
0a75412d965ae2ed5c093315cb27f82d4a578590
[ "MIT" ]
null
null
null
29.707317
141
0.464444
[ [ [ "import pandas as pd\nimport numpy as np\nfrom numpy import linalg\nimport matplotlib.pyplot as plt\nimport seaborn as sbn\nfrom scipy.stats import invgamma\nimport logging", "_____no_output_____" ], [ "from notebookutils import root_dir; root_dir()", "now in dir: /Users/Jeppe/Projects/BayesFactorModel\n" ], [ "from model.utils import read_clean_kv17, read_testdata1, read_party_keys, matrix, vector, party_name_from_key, generate_Tau_trace_df\nfrom model.distributionplotter import DistributionPlotter\nfrom model.traceplotter import TracePlotter\nfrom model.parameterframe import ParameterFrame\nfrom model.parameters import Parameters", "_____no_output_____" ], [ "np.random.seed(100)", "_____no_output_____" ], [ "data = read_clean_kv17(drop_party_key = True)\nlabels = read_party_keys()", "_____no_output_____" ], [ "data = matrix(data) #making testing different data set simple", "(1215, 15)\n" ], [ "sigma_array = np.array([np.random.normal()**2 for _ in range(15)])\nF = np.matrix([np.random.normal(size=3) for _ in range(1215)])\nBeta = np.matrix(np.random.normal(size=(15,3)))\nYstar = np.matrix(np.random.normal(size=(1215,15)))", "_____no_output_____" ], [ "tau = [- np.inf] + [-2, -0.5, 0.5, 2] + [np.inf]\nTau = dict()\nfor i in range(15):\n Tau[i] = tau", "_____no_output_____" ], [ "import numpy as np\nfrom numpy import linalg\nfrom scipy.stats import invgamma\nfrom scipy.stats import truncnorm\nimport logging\n\nfrom model.utils import vector\n\n\nclass OrderedProbitGibbsSampler():\n\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n def __init__(self, n_factors, data, n_answers):\n\n self.y = data\n self.k = n_factors\n self.p = data.shape[1]\n self.T = data.shape[0]\n self.I_k = np.identity(self.k)\n self.I_p = np.identity(self.p)\n self.n_answers = n_answers\n \n self.v = 0.5\n self.s_sq = 2\n self.C0 = 2\n self.mu0 = 1\n\n self.Beta_list = list()\n self.Sigma_list = list()\n self.F_list = list()\n self.Tau_list = list()\n self.Ystar_list = list()\n \n print('number of variables:', self.p, ' number of observations:', self.T)\n\n def f_t(self, Beta, Sigma, t):\n \"\"\"Posterior of f_t\"\"\"\n\n y_t = self.Ystar[[t]].T\n S_inv = linalg.inv(Sigma * self.I_p)\n\n scale = linalg.inv(self.I_k + np.dot(np.dot(Beta.T, S_inv), Beta))\n loc = vector(np.dot(np.dot(np.dot(scale, Beta.T), S_inv), y_t))\n\n return np.random.multivariate_normal(loc, scale)\n\n def Beta_i(self, Sigma, F, i):\n\n if i < self.k:\n\n C_i = self.C_i(F, Sigma, i)\n m_i = self.m_i(C_i, F, Sigma, i)\n\n B_i = np.random.multivariate_normal(m_i, C_i)\n if B_i[i] < 0:\n # print(B_i[i]) # possible bug\n #B_i = np.random.multivariate_normal(m_i, C_i)\n B_i[i] = 0\n\n if i < self.k:\n B_i = np.append(B_i, np.zeros(self.k - i - 1))\n\n elif i >= self.k:\n\n C_k = self.C_k(F, Sigma, i)\n m_k = self.m_k(C_k, F, Sigma, i)\n\n B_i = np.random.multivariate_normal(m_k, C_k)\n\n else:\n raise ValueError('k is {0}, i is {1} - Beta_i probs'.format(self.k, i))\n\n return vector(B_i)\n\n\n def C_i(self, F, Sigma, i):\n \"\"\"If i <= k \"\"\"\n\n F_i = F.T[:i + 1].T\n sigma_i = Sigma[i]\n identity_i = np.identity(i + 1)\n\n return linalg.inv((1 / self.C0) * identity_i + (1 / sigma_i) * np.dot(F_i.T, F_i))\n\n def C_k(self, F, Sigma, i):\n \"\"\"if i > k\"\"\"\n\n sigma_i = Sigma[i]\n return linalg.inv((1 / self.C0) * self.I_k + (1 / sigma_i) * np.dot(F.T, F))\n\n def m_i(self, C_i, F, Sigma, i):\n \"\"\"If i <= k \"\"\"\n\n F_i = F[:, :i + 1] # 2000 X i\n sigma_i = Sigma[i] # 1 x 1\n ones_i = np.matrix(np.ones(i + 1)).T\n y_i = self.Ystar[:, [i]] #changed to Ystar\n tmp = (1 / self.C0) * self.mu0 * ones_i + (1 / sigma_i) * np.dot(F_i.T, y_i)\n return vector(np.dot(C_i, tmp))\n\n def m_k(self, C_k, F, Sigma, i):\n \"\"\"if i > k\"\"\"\n\n sigma_i = Sigma[i] # 1 x 1\n ones_k = np.matrix(np.ones(self.k)).T\n y_i = self.Ystar[:, [i]] #changed to Ystar\n\n tmp = (1 / self.C0) * self.mu0 * ones_k + (1 / sigma_i) * np.dot(F.T, y_i)\n return vector(np.dot(C_k, tmp))\n\n def calc_Beta(self):\n\n B = np.matrix([self.Beta_i(self.Sigma, self.F, i) for i in range(self.p)])\n self.Beta_list.append(B)\n return B\n\n def calc_F(self):\n\n F = np.matrix([self.f_t(self.Beta, self.Sigma, t) for t in range(self.T)])\n self.add('F', F)\n return F\n\n def calc_Ystar(self):\n \n #defined here to not make multiple call of dot product (specially for Psi)\n Y = self.y\n Psi = self.Psi\n \n Ystar = np.matrix([self.calc_Ystar_i(Psi[i], Y[i]) for i in range(self.T)])\n self.add('Ystar', Ystar)\n return Ystar\n \n def calc_Ystar_i(self, Psi_i, Y_i):\n \n Y_star_i = list()\n for question in range(self.p):\n psi_i_j = Psi_i[0,question]\n y_i_j = self.get_y_i_j(Y_i,question)\n lb, ub = self.get_bounds(y_i_j, question)\n Y_star_i.append(self.calc_Ystar_i_j(lb, ub, psi_i_j)) \n \n return Y_star_i\n\n def calc_Ystar_i_j(self, lower_bound, upper_bound, mean):\n #weird implementation of python required following:\n ub = upper_bound - mean\n lb = lower_bound - mean\n return truncnorm.rvs(a = lb, b = ub, loc = mean, scale = 1)\n\n def get_bounds(self, y_i_j, question):\n \n tau = self.Tau[question]\n upper_bound = tau[y_i_j]\n lower_bound = tau[y_i_j - 1]\n return lower_bound, upper_bound\n \n @staticmethod\n def get_y_i_j(Y_i, question):\n \"\"\"To handle unfortunate 0'es\"\"\"\n res = Y_i[0, question]\n if res == 0:\n res = 3\n \n return res\n \n def calc_Tau(self):\n \n Tau = dict()\n for question in range(self.p):\n Tau[question] = self.calc_Tau_p(question)\n \n self.add('Tau', Tau)\n return Tau\n \n def calc_Tau_p(self, p):\n \"\"\"Cutpoints/answers for given quiestion p\"\"\"\n \n _tau = [self.calc_tau_l_p(p, l) for l in range(1, self.n_answers)]\n return [- np.inf] + _tau + [np.inf]\n \n def calc_tau_l_p(self, p, l):\n \n _ , Ystar_max = self.get_Ystar_min_max(p, l) \n Ystar_min, _ = self.get_Ystar_min_max(p, l + 1)\n l_plus = self.get_tau_l_p(p, l+1)\n l_minus = self.get_tau_l_p(p, l-1)\n _min = min(Ystar_min, l_plus)\n _max = max(Ystar_max, l_minus)\n \n #print('tau', 'p=',p,', l=',l)\n #print(l_plus, Ystar_min)\n #print(l_minus, Ystar_max)\n \n try:\n return np.random.uniform(_min, _max)\n except OverflowError as e:\n print(_min, _max)\n raise e\n \n def get_Ystar_min_max(self, question, answer):\n \"\"\"\n answer is the answer of question (1, 2, 3, 4, 5)\"\"\"\n Y_l = self.y[:,question]\n Ystar_l = self.Ystar[:,question]\n \n #Ystar observation where y_l == 0\n Ystar_legal = []\n \n for i in range(self.T):\n if Y_l[i] == answer :\n Ystar_legal.append(Ystar_l[i])\n return float(min(Ystar_legal)), float(max(Ystar_legal))\n \n def get_tau_l_p(self, p, l):\n return self.Tau[p][l]\n \n @property\n def Beta(self):\n return self.Beta_list[-1]\n\n @property\n def F(self):\n return self.F_list[-1]\n\n @property\n def Sigma(self):\n #return self.Sigma_list[-1]\n return [1 for _ in range(self.p)]\n\n @property\n def Psi(self):\n return np.dot(self.F ,self.Beta.T)\n \n @property\n def Tau(self):\n return self.Tau_list[-1]\n\n @property\n def Ystar(self):\n return self.Ystar_list[-1]\n \n def add(self, param, value):\n \"\"\" add to Sigma_list, Beta_list or F_list\n\n Parameters\n ==========\n param: (str)\n string that should be of {'Sigma', 'F', 'Beta'}\n value: (obj)\n appropriate object for given list\n\n \"\"\"\n\n if param == 'Sigma':\n self.Sigma_list.append(value)\n \n elif param == 'Tau':\n self.Tau_list.append(value)\n \n elif param == 'Ystar':\n self.Ystar_list.append(value)\n\n elif param == 'F':\n self.F_list.append(value)\n\n elif param == 'Beta':\n self.Beta_list.append(value)\n\n else:\n raise ValueError(\"Param must be in {'F', 'Sigma', 'Beta', 'Ystar', 'Tau'}\")\n\n def sampler(self, n_iterations):\n\n logging.info(\"Sampling begins\")\n for i in range(n_iterations):\n\n self.calc_Ystar()\n self.calc_Tau()\n self.calc_F()\n self.calc_Beta()\n if (i % 5 == 0):\n logging.info(\"run {0} simulations\".format(i))\n", "_____no_output_____" ], [ "gs = OrderedProbitGibbsSampler(3, data, n_answers = 5)\ngs.add('Sigma',sigma_array)\ngs.add('F', F)\ngs.add('Beta',Beta)\ngs.add('Tau', Tau)", "number of variables: 15 number of observations: 1215\n" ], [ "gs.sampler(3)", "2018-11-18 15:45:58,553 : INFO : Sampling begins\n2018-11-18 15:46:02,219 : INFO : run 0 simulations\n" ], [ "beta_params = ParameterFrame(gs.Beta_list, 'beta')\nbeta_trace_estimation = beta_params.get_trace_df()\nbeta_trace_estimation.to_pickle('data//probit_v2_estimation_beta_trace_df.pkl')", "_____no_output_____" ], [ "factor = ParameterFrame(gs.F_list, 'factor_estimation')\nfactor_trace_estimation = factor.get_trace_df()\nfactor_trace_estimation.to_pickle('data//probit_v2_estimation_factor_trace_df.pkl')", "_____no_output_____" ], [ "ystar = ParameterFrame(gs.Ystar_list, 'ystar')\nystar_trace_estimation = ystar.get_trace_df()\nystar_trace_estimation.to_pickle('data//probit_v2_ystar_trace_df.pkl')", "_____no_output_____" ], [ "tau_trace = generate_Tau_trace_df(gs.Tau_list)\ntau_trace.to_pickle('data//probit_v2_tau_trace_df.pkl')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb266bd65b5a4cee383240ee27cddb09147c79c6
68,762
ipynb
Jupyter Notebook
Untitled0.ipynb
williamgilpin/netsim
87f6aec828fdb9fae836e7e717c6c0e39139a190
[ "MIT" ]
2
2020-05-30T02:19:04.000Z
2021-12-09T23:07:24.000Z
Untitled0.ipynb
williamgilpin/netsim
87f6aec828fdb9fae836e7e717c6c0e39139a190
[ "MIT" ]
null
null
null
Untitled0.ipynb
williamgilpin/netsim
87f6aec828fdb9fae836e7e717c6c0e39139a190
[ "MIT" ]
1
2022-03-13T04:00:27.000Z
2022-03-13T04:00:27.000Z
399.77907
1,605
0.708022
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb2672826acefdbb366d8a0a9210845066b19bb3
174,713
ipynb
Jupyter Notebook
notebooks/Image Simulation v2.ipynb
bwgref/duet-astro
4fe3358bb927c0f03de1b75c01ddf2379b5771b3
[ "BSD-3-Clause" ]
1
2019-04-15T21:02:57.000Z
2019-04-15T21:02:57.000Z
notebooks/Image Simulation v2.ipynb
bwgref/duet-astro
4fe3358bb927c0f03de1b75c01ddf2379b5771b3
[ "BSD-3-Clause" ]
null
null
null
notebooks/Image Simulation v2.ipynb
bwgref/duet-astro
4fe3358bb927c0f03de1b75c01ddf2379b5771b3
[ "BSD-3-Clause" ]
1
2019-04-17T19:46:42.000Z
2019-04-17T19:46:42.000Z
343.923228
49,964
0.927756
[ [ [ "%load_ext autoreload\n%autoreload 2\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy import units as u\nfrom astroduet.bbmag import bb_abmag_fluence\nfrom astroduet.image_utils import construct_image, find\nfrom astroduet.config import Telescope\nfrom astroduet.background import background_pixel_rate\n\nfrom astroduet.diff_image import py_zogy\nfrom astroduet.image_utils import estimate_background\n\nduet = Telescope()\nduet.info()\n\n\n[bgd_band1, bgd_band2] = background_pixel_rate(duet, low_zodi = True, diag=True)\n\nread_noise = duet.read_noise\n\n\n# Define image simulation parameters\nexposure = 300 * u.s\nframe = np.array([30,30]) # Dimensions of the image I'm simulating in DUET pixels (30x30 ~ 3x3 arcmin)", "-----\n DUET Telescope State: baseline\n Physical Entrance Pupil: 26.0 cm\n Effective EPD: 24.2 cm\n Effective Area: 459.9605804120816 cm2\n Transmission Efficiency: 0.8166518036622619\n \n Pixel size: 6.4 arcsec\n Pointing RMS: 2.5 arcsec\n DIQ RMS: 4.406714876186114 arcsec\n Effective PSF FWHM: 12.5 arcsec\n N_eff: 9.75310538172716\n\n Band 1: {'eff_wave': <Quantity 202.56878682 nm>, 'eff_width': <Quantity 53.32814342 nm>}\n Bandpass 1: [175.90471511 229.23285853] nm\n Band 2: {'eff_wave': <Quantity 281.7531854 nm>, 'eff_width': <Quantity 68.16239088 nm>}\n Bandpass 2: [247.67198996 315.83438085] nm\n\n Dark current: 0.0115 ph / s\n Read noise (RMS per read): 7\n -----\n \n-----\nBackground Computation Integrating over Pixel Area\nTelescope diameter: 26.0 cm\nCollecting Area: 459.9605804120816 cm2\nTransmission Efficiency: 0.8166518036622619\n\n\nPixel Size: 6.4 arcsec\nPixel Area: 40.96000000000001 arcsec2\n\nZodi Level: 77\nBand1 Rate: 0.030369732491096913 ph / s\nBand2 Rate: 0.2478588509265617 ph / s\n-----\n" ], [ "# Define source\nbbtemp = 20000 * u.K\nswiftmag = 18 * u.ABmag\n\nsrc_fluence1, src_fluence2 = bb_abmag_fluence(bbtemp=bbtemp, swiftmag=swiftmag, duet=duet)\nprint(\"Source fluences: {}, {}\".format(src_fluence1,src_fluence2))\nsrc_rate1 = duet.trans_eff * duet.eff_area * src_fluence1\nprint(\"Source rate (band 1): {}\".format(src_rate1))\n\n# Define galaxy\ngalaxy = 'dwarf'\ngal_params = None\n", "Source fluences: 0.032113008404959516 ph / (cm2 s), 0.03029734679215195 ph / (cm2 s)\nSource rate (band 1): 12.062533483610837 ph / s\n" ], [ "# Construct the simulated image\nimage = construct_image(frame, exposure, source=src_rate1,\n gal_type=galaxy, gal_params=gal_params, \n sky_rate=bgd_band1, duet=duet)\n\nplt.figure(figsize=[8,6])\nplt.imshow(image.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()", "_____no_output_____" ], [ "# Single-exposure point source detection\n\n# Run DAOPhot-like Find command\nprint(\"DAOPhot find:\")\npsf_fwhm_pix = duet.psf_fwhm / duet.pixel\n\nstar_tbl, bkg_image, threshold = find(image,psf_fwhm_pix.value,method='daophot',frame='single')\n\nplt.figure(figsize=[16,6])\nplt.subplot(121)\nplt.title('DAOPhot Find')\nplt.imshow(image.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()\nplt.scatter(star_tbl['x'],star_tbl['y'],marker='o',s=1000,facecolors='none',edgecolors='r',lw=1)\n\n# Run find_peaks command\nprint(\"\\nFind peaks:\")\nstar_tbl, bkg_image, threshold = find(image,psf_fwhm_pix.value,method='peaks',frame='single')\n\nplt.subplot(122)\nplt.title('Find Peaks')\nplt.imshow((image-bkg_image).value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()\nplt.scatter(star_tbl['x'],star_tbl['y'],marker='o',s=1000,facecolors='none',edgecolors='r',lw=1)", "DAOPhot find:\n\nFind peaks:\n" ], [ "# Single-exposure photometry\nprint(\"Real source count rate: {}\".format(src_rate1))\n\n# Convert to count rate\nimage_rate = image / exposure\n\nfrom astroduet.image_utils import run_daophot, ap_phot\n\n# Run aperture photometry\nresult, apertures, annulus_apertures = ap_phot(image_rate,star_tbl,read_noise,exposure)\nprint(result['xcenter','ycenter','aperture_sum','aper_sum_bkgsub','aperture_sum_err'])\n\nprint(\"\\n\")\n\n# Run PSF-fitting photometry\nresult, residual_image = run_daophot(image,threshold,star_tbl,niters=1)\nprint(result['x_fit','y_fit','flux_fit','flux_unc'])\n\n# Plots\nplt.figure(figsize=[16,12])\nplt.subplot(221)\nplt.title('Aperture Photometry')\nplt.imshow(image_rate.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()\napertures.plot()\nannulus_apertures.plot()\n\nplt.subplot(223)\nplt.title('DAOPhot PSF-fitting')\nplt.imshow(image_rate.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()\nplt.scatter(result['x_fit'],result['y_fit'],marker='o',s=1000,facecolors='none',edgecolors='r',lw=1)\n\nplt.subplot(224)\nplt.title('DAOPhot Residual Image')\nplt.imshow(residual_image.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()", "Real source count rate: 12.062533483610837 ph / s\nxcenter ycenter aperture_sum aper_sum_bkgsub aperture_sum_err\n pix pix ph / s ph / s ph / s \n------- ------- ------------ --------------- ----------------\n 9 14 3.8008786 0.57289218 0.12852255\n 25 14 140.01173 74.921857 0.68596954\n 15 15 17.345172 8.7921862 0.24832578\n\n\n x_fit y_fit flux_fit flux_unc \n ph ph \n------------------ ------------------ ----------------- -----------------\n 9.718876901240376 14.208044494256884 1241.609775572059 0.0\n 25.36586512034467 14.476453400723804 58185.3695694314 6521.127122884643\n15.010194988347616 14.7137602536282 6566.123183686525 847.0056943425969\n" ], [ "# Part 2, simulate reference image, without source, 5 exposures\n# Currently a perfect co-add\nn_exp = 5\nref_image = construct_image(frame, exposure, \\\n gal_type=galaxy, gal_params=gal_params, source=None, sky_rate=bgd_band1, n_exp=n_exp)\nref_image_rate = ref_image / (n_exp * exposure)\nplt.figure(figsize=[8,6])\nplt.imshow(ref_image_rate.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()", "_____no_output_____" ], [ "# Part 3, make a difference image\n\n# Make a 2D array containing the PSF (oversample then bin up for more accurate PSF)\n\noversample = 5\npixel_size_init = duet.pixel / oversample\n\npsf_model = duet.psf_model(pixel_size=pixel_size_init, x_size=25, y_size=25)\n\npsf_os = psf_model.array\n\n#psf_os = gaussian_psf(psf_fwhm,(25,25),pixel_size_init)\nshape = (5, 5, 5, 5)\npsf_array = psf_os.reshape(shape).sum(-1).sum(1)\n\n# Use ZOGY algorithm to create difference image\nimage_bkg, image_bkg_rms_median = estimate_background(image_rate, sigma=2, method='1D')\nref_bkg, ref_bkg_rms_median = estimate_background(ref_image_rate, sigma=2, method='1D')\nimage_rate_bkgsub, ref_rate_bkgsub = image_rate - image_bkg, ref_image_rate - ref_bkg\n\ns_n, s_r = np.sqrt(image_rate), np.sqrt(ref_image_rate) # 2D uncertainty (sigma) - that is, noise on the background\nsn, sr = np.mean(s_n), np.mean(s_r) # Average uncertainty (sigma)\ndx, dy = 0.1, 0.01 # Astrometric uncertainty (sigma)\ndiff_image, d_psf, s_corr = py_zogy(image_rate_bkgsub.value,\n ref_rate_bkgsub.value,\n psf_array,psf_array,\n s_n.value,s_r.value,\n sn.value,sr.value,dx,dy)\n\ndiff_image *= image_rate_bkgsub.unit\nplt.imshow(diff_image.value)\nplt.colorbar()\nplt.show()", "_____no_output_____" ], [ "# Part 4, find and photometry on the difference image\nprint(\"Real source count rate: {}\".format(src_rate1))\n\n# Run find\nstar_tbl, bkg_image, threshold = find(diff_image,psf_fwhm_pix.value,method='peaks')\nprint('threshold = ', threshold)\n\n# Run aperture photometry\nresult, apertures, annulus_apertures = ap_phot(diff_image,star_tbl,read_noise,exposure)\nresult['percent_error'] = result['aperture_sum_err'] / result['aper_sum_bkgsub'] * 100\nprint(result['xcenter','ycenter','aperture_sum','aper_sum_bkgsub','aperture_sum_err','percent_error'])\n\nprint(\"\\n\")\n\n# Run PSF-fitting photometry\nresult, residual_image = run_daophot(diff_image,threshold,star_tbl,niters=1)\nresult['percent_error'] = result['flux_unc'] / result['flux_fit'] * 100\nprint(result['id','flux_fit','flux_unc','percent_error'])\n\n# Plots\nplt.figure(figsize=[16,12])\nplt.subplot(221)\nplt.title('Aperture Photometry')\nplt.imshow(diff_image.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()\napertures.plot()\nannulus_apertures.plot()\n\nplt.subplot(223)\nplt.title('DAOPhot PSF-fitting')\nplt.imshow(diff_image.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()\nplt.scatter(result['x_fit'],result['y_fit'],marker='o',s=1000,facecolors='none',edgecolors='r',lw=1)\n\nplt.subplot(224)\nplt.title('DAOPhot Residual Image')\nplt.imshow(residual_image.value, cmap='viridis', aspect=1, origin='lower')\nplt.colorbar()", "Real source count rate: 12.062533483610837 ph / s\nthreshold = 0.3225035746938884 ph / s\nxcenter ycenter aperture_sum aper_sum_bkgsub aperture_sum_err percent_error\n pix pix ph / s ph / s ph / s \n------- ------- ------------ --------------- ---------------- -------------\n 15 15 8.9821469 8.6240053 0.18381768 2.1314653\n\n\n id flux_fit flux_unc percent_error \n ph / s ph / s ph / s \n--- ------------------ ------------------- ------------------\n 1 12.088368070265565 0.28305071234036244 2.3415130205755244\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb26794b2e6cb0b0aec71efe6e67f663fbfa77de
1,654
ipynb
Jupyter Notebook
TimeSeriesLSTM.ipynb
thanhhocse96/DeepLearningDemo
d98d0b34a575f519d1c18cbf0e39152b56eabf56
[ "Apache-2.0" ]
null
null
null
TimeSeriesLSTM.ipynb
thanhhocse96/DeepLearningDemo
d98d0b34a575f519d1c18cbf0e39152b56eabf56
[ "Apache-2.0" ]
null
null
null
TimeSeriesLSTM.ipynb
thanhhocse96/DeepLearningDemo
d98d0b34a575f519d1c18cbf0e39152b56eabf56
[ "Apache-2.0" ]
null
null
null
16.54
82
0.478839
[ [ [ "# LSTM & Time Series Prediction\n", "_____no_output_____" ], [ "import numpy as np\n\nimport os", "_____no_output_____" ] ], [ [ "## 1. Chuẩn bị dữ liệu và biểu diễn dữ liệu\n### 1.1. Mô tả về dữ liệu biến động giá trị giữa đồng USD và GBP (bảng Anh) ", "_____no_output_____" ], [ "dataset_path = \"./Datasets/USD_GBP.txt\"", "_____no_output_____" ], [ "### 1.2 Biểu diễn dữ liệu", "_____no_output_____" ], [ "### 1.3 Mục tiêu khảo sát tập dữ liệu & đầu ra của bài toán", "_____no_output_____" ], [ "## 2. Xây dựng mô hình LSTM", "_____no_output_____" ] ] ]
[ "code", "markdown" ]
[ [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
cb267952c8527628de61e2356a480ff9db859c86
18,028
ipynb
Jupyter Notebook
.ipynb_checkpoints/RL mountain car-checkpoint.ipynb
guidoAI/RL_cart_notebook
86764fb43e203ed5a9fc1a718bc3f032cab3e1c0
[ "MIT" ]
null
null
null
.ipynb_checkpoints/RL mountain car-checkpoint.ipynb
guidoAI/RL_cart_notebook
86764fb43e203ed5a9fc1a718bc3f032cab3e1c0
[ "MIT" ]
null
null
null
.ipynb_checkpoints/RL mountain car-checkpoint.ipynb
guidoAI/RL_cart_notebook
86764fb43e203ed5a9fc1a718bc3f032cab3e1c0
[ "MIT" ]
null
null
null
47.819629
892
0.573996
[ [ [ "# Reinforcement learning \n\nIn this Python notebook, we will have you implement a simple reinforcement learning agent for the AI gym mountain car problem. Please first have a look at the description of the task here: <A HREF=\"https://github.com/openai/gym/wiki/MountainCar-v0\" TARGET=\"_blank\">Description</A>", "_____no_output_____" ], [ "## Heuristic agent\nBefore we dive into the use of reinforcement learning of the mountain car task, you will first make a strategy by hand yourself. There are two very good reasons for doing so. \n\nFirst, making such a \"heuristic\" agent will give you a good idea of how difficult the task is, given the observations and actions of the agent. In the case of the mountain car task, the agent has to reach a goal position (located at position $0.5$), by choosing from discrete actions $\\{0,1,2\\}$ corresponding to $\\{$ push left, no acceleration, push right $\\}$. The starting position is in the middle, at position $-0.5$. The left end of the environment has position $-1.2$. The velocity of the agent is limited to the interval $[-0.07, 0.07]$.\n\nSecond, making a heuristic agent gives you a good idea of the difficulty of the task, and what kind of solution you might expect the machine learning method to find (reinforcement learning in the current notebook).\n\nWe will experiment with the original formulation of the car mountain car task. The class we will use is `CMC_original`, which is the same as the normal AI gym version, but with an adapted render-function in order to be able to show the graphics in a Binder notebook. The full code, imported with `import run_cart` in the code block below. You can find it <A HREF=\"https://github.com/guidoAI/RL_cart_notebook/blob/master/run_cart.py\" TARGET=\"_blank\">here</A>. \n\n<FONT COLOR=\"red\">Exercise 1.</FONT>\n<OL>\n <LI>First run the following block, in which an agent is run that takes random actions. Does it succeed in performing the task? Why so? </LI>\n <LI>If we want the agent to move to the right, why then not just drive there? Try this strategy out by replacing the random action in the `act` function with 2, which means to just accelerate to the right. What do you observe, and why?</LI>\n <LI>Write a heuristic method to solve the task. Only make use of the position and velocity in the current time step, as this is what we are going to give to the reinforcement learning agent. Are you able to solve the task? Is your solution optimal you think? Do you think that this will be easy to learn with reinforcement learning?</LI>\n</OL>", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport os\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport run_cart\nimport gym\nimport numpy as np\nimport random\n\n# definition of the agent class\nclass heuristic_agent(object):\n\n def act(self, observation, reward, done):\n \"\"\" - observation[0] = position\n - observation[1] = velocity\n - reward = the reward received from the environment\n - done = whether the agent reached the goal\n \"\"\"\n position = observation[0]\n velocity = observation[1]\n \n # REPLACE THIS CODE WITH A FIXED ACTION OR YOUR HEURISTIC:\n action = random.randint(0,2)\n \n return action\n\n# create the agent:\nagent = heuristic_agent()\n# apply the agent to the task\nreward, rewards = run_cart.run_cart_discrete(agent, env=run_cart.CMC_original(), graphics=True)\nprint('Reward = ' + str(reward))", "Reward = -200.0\n" ] ], [ [ "## Q-learning\nFor this notebook, you will implement a very elementary reinforcement learning method: Q-learning. Please first read up on this method <A HREF=\"https://en.wikipedia.org/wiki/Q-learning\" TARGET=\"_blank\">here</A>. In particular, we will investigate the use of _tabular_ Q-learning, in which the algorithm finds the values for all state-action pairs in the matrix. Since our state is two-dimensional (position and velocity), the state-action space can be discretized without leading to an overly large table. In the code block below, we create the table in the `__init__` function of `Q_learning_agent`, using 10 grid cells per state variable. Also have a look at the start of the `act` function. When we get the two-dimensional state (observation), we transform it to a single state number (row index in the Q state-action table). The table has three columns for the three actions.\n\n<FONT COLOR=\"red\">Exercise 2.</FONT>\n<OL>\n <LI>Fill in the Q-update function in the `act` function. Remember that variables of the agent object have to be reffered to with `self` like `self.alpha` and `self.Q`.</LI>\n <LI>Write the code to take actions under an $\\epsilon$-greedy policy, where $\\epsilon$ is `p_explore` in the code.\n </LI>\n <LI>Run the code to have the agent learn. Is it able to do the task (to check this, run the code block two blocks below in order to run the agent without exploratory actions)? Why / why not? If it does not work, can you then change the code at the bottom to make the agent learn the task properly?</LI>\n</OL>", "_____no_output_____" ] ], [ [ "class Q_learning_agent(object):\n \"\"\"Simple Q-learning agent for the MountainCarv0 task\n https://en.wikipedia.org/wiki/Q-learning\n \"\"\"\n\n n_actions = 3\n\n def __init__(self, min_speed, max_speed, min_position, max_position, alpha = 0.1, gamma = 0.9, p_explore = 0.1):\n \n # number of grids per state variable\n self.n_grid = 10\n self.min_speed = min_speed\n self.max_speed = max_speed\n self.speed_step = (max_speed - min_speed) / self.n_grid\n self.min_position = min_position\n self.max_position = max_position\n self.position_step = (max_position - min_position) / self.n_grid\n # discretizing the 2-variable state results in this number of states:\n self.n_states = int(self.n_grid**2)\n # make an empty Q-matrix\n self.Q = np.zeros([self.n_states, self.n_actions])\n # initialize previous state and action\n self.previous_state = 0\n self.previous_action = 0\n # learning rate\n self.alpha = alpha\n # discount factor:\n self.gamma = gamma\n # e-greedy, p_explore results in a random action:\n self.p_explore = p_explore\n\n def act(self, observation, reward, done, verbose = False):\n \n # Determine the new state:\n pos = observation[0]\n if(pos > self.max_position):\n pos = self.max_position\n elif(pos < self.min_position):\n pos = self.min_position\n obs_pos = int((pos - self.min_position) // self.position_step) \n vel = observation[1]\n if(vel > self.max_speed):\n vel = self.max_speed\n elif(vel < self.min_speed):\n vel = self.min_speed\n obs_vel = int((vel - self.min_speed) // self.speed_step)\n new_state = obs_pos * self.n_grid + obs_vel\n \n if(verbose):\n print(f'Velocity {observation[1]}, position {observation[0]}, (grid {self.speed_step}, \\\n {self.position_step}), state = {new_state}')\n \n # ************************************************\n # FILL IN YOUR CODE HERE FOR THE Q-UPDATE FUNCTION\n # ************************************************\n \n # Update the Q-matrix:\n # self.Q[..., ...] = ...\n \n # determine the new action:\n # FILL IN YOUR CODE FOR SELECTING AN ACTION\n \n # update previous state and action\n self.previous_state = new_state\n self.previous_action = action \n \n # return the action\n return action\n\n \nenv=run_cart.CMC_original()\n\n# set up off-policy learning with p_explore = 1\nmax_velocity = env.max_speed\nmin_velocity = -max_velocity\nagent = Q_learning_agent(min_velocity, max_velocity, env.min_position, env.max_position, \\\n alpha = 0.20, gamma = 0.95, p_explore = 1.0)\nn_episodes = 1000\nreward, rewards = run_cart.run_cart_discrete(agent, env=env, graphics=False, n_episodes=n_episodes)\nprint('Reward per episode = ' + str(reward / n_episodes))", "_____no_output_____" ], [ "n_episodes = 1\nagent.p_explore = 0\nagent.alpha = 0\nreward, rewards = run_cart.run_cart_discrete(agent, env=env, graphics=True, n_episodes=n_episodes)\nprint(f'Reward trained agent {reward}')", "_____no_output_____" ] ], [ [ "## Answers\n\n<FONT COLOR=\"red\">Exercise 1.</FONT>\n<OL>\n <LI>It typically does not succeed. For example, just when it speeds up to the right it then randomly accelerates to the left, and will not reach the goal.</LI>\n <LI>The agent just never gets high enough on the up-slope. The exerted force is not sufficient by itself to counter gravity. The agent will likely have to swing up and down to gain more and more speed, which will finally bring it over the right hill.</LI>\n <LI>The following code block has a solution to the task consisting of a few if / else statements. It always succeeds when starting at the start location. Whether it is the optimal solution is not clear, but it is clear that the state space can be separated quite easily and linked to the appropriate actions. It seems that the task is relatively easy to perform and learning algorithms should be able to do it.</LI>\n</OL>", "_____no_output_____" ] ], [ [ "class heuristic_agent(object):\n \"\"\"Guido's heuristic agent\"\"\"\n\n def act(self, observation, reward, done):\n position = observation[0]\n velocity = observation[1]\n if position < -0.5:\n if velocity < -0.01:\n action = 0\n else:\n action = 2\n else:\n if velocity > 0.01:\n action = 2\n else:\n action = 0\n return action\n \nagent = heuristic_agent()\nreward, rewards = run_cart.run_cart_discrete(agent, env=run_cart.CMC_original(), graphics=True)\nprint('Reward = ' + str(reward))", "_____no_output_____" ] ], [ [ "<FONT COLOR=\"red\">Exercise 2.</FONT>\n<OL>\n <LI>The code for the update equation is as follows: \n `self.Q[self.previous_state, self.previous_action] += self.alpha * (reward + self.gamma * max(self.Q[new_state, :]) - self.Q[self.previous_state, self.previous_action])`</LI>\n <LI>A possible implementation is:\n `if(random.random() $\\lt$ self.p_explore): action = random.randint(0, self.n_actions-1) else: action = np.argmax(self.Q[new_state, :])`</LI>\n <LI>In order to solve it, I made a learning scheme in three parts: off-policy learning with random actions, on-policy learning with less exploration, and on-policy learning with a lower learning rate and even less exploration.</LI>\n</OL>", "_____no_output_____" ] ], [ [ "class Q_learning_agent(object):\n \"\"\"Simple Q-learning agent for the MountainCarv0 task\n https://en.wikipedia.org/wiki/Q-learning\n \"\"\"\n\n n_actions = 3\n\n def __init__(self, min_speed, max_speed, min_position, max_position, alpha = 0.1, gamma = 0.9, p_explore = 0.1):\n \n # number of grids per state variable\n self.n_grid = 10\n self.min_speed = min_speed\n self.max_speed = max_speed\n self.speed_step = (max_speed - min_speed) / self.n_grid\n self.min_position = min_position\n self.max_position = max_position\n self.position_step = (max_position - min_position) / self.n_grid\n # discretizing the 2-variable state results in this number of states:\n self.n_states = int(self.n_grid**2)\n # make an empty Q-matrix\n self.Q = np.zeros([self.n_states, self.n_actions])\n # initialize previous state and action\n self.previous_state = 0\n self.previous_action = 0\n # learning rate\n self.alpha = alpha\n # discount factor:\n self.gamma = gamma\n # e-greedy, p_explore results in a random action:\n self.p_explore = p_explore\n\n def act(self, observation, reward, done, verbose = False):\n \n # Determine the new state:\n pos = observation[0]\n if(pos > self.max_position):\n pos = self.max_position\n elif(pos < self.min_position):\n pos = self.min_position\n obs_pos = int((pos - self.min_position) // self.position_step) \n vel = observation[1]\n if(vel > self.max_speed):\n vel = self.max_speed\n elif(vel < self.min_speed):\n vel = self.min_speed\n obs_vel = int((vel - self.min_speed) // self.speed_step)\n new_state = obs_pos * self.n_grid + obs_vel\n \n if(verbose):\n print(f'Velocity {observation[1]}, position {observation[0]}, (grid {self.speed_step}, \\\n {self.position_step}), state = {new_state}')\n \n # Update the Q-matrix:\n self.Q[self.previous_state, self.previous_action] += self.alpha * \\\n (reward + self.gamma * max(self.Q[new_state, :]) - self.Q[self.previous_state, self.previous_action])\n \n # determine the new action:\n if(random.random() < self.p_explore):\n action = random.randint(0, self.n_actions-1)\n else:\n action = np.argmax(self.Q[new_state, :])\n \n # update previous state and action\n self.previous_state = new_state\n self.previous_action = action \n \n # return the action\n return action\n\n \nenv=run_cart.CMC_original()\n\n# set up off-policy learning with p_explore = 1\nmax_velocity = env.max_speed\nmin_velocity = -max_velocity\nagent = Q_learning_agent(min_velocity, max_velocity, env.min_position, env.max_position, \\\n alpha = 0.20, gamma = 0.95, p_explore = 1.0)\nn_episodes = 1000\nreward, rewards = run_cart.run_cart_discrete(agent, env=env, graphics=False, n_episodes=n_episodes)\nprint('Reward per episode = ' + str(reward / n_episodes))\n\n# on-policy now with e-greedy\nagent.p_explore = 0.05\nreward, rewards = run_cart.run_cart_discrete(agent, env=env, graphics=False, n_episodes=n_episodes)\nprint('Reward per episode = ' + str(reward / n_episodes))\n\nn_episodes = 100\nagent.alpha = 0.05\nagent.p_explore = 0.02\nreward, rewards = run_cart.run_cart_discrete(agent, env=env, graphics=False, n_episodes=n_episodes)\nprint('Reward per episode = ' + str(reward / n_episodes))\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb267dc896046d143de565bf56387f10e157f236
89,527
ipynb
Jupyter Notebook
ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_text_binary_classification_online_container.ipynb
polong-lin/ai-platform-samples
ef7856a7cae667f88bfad5d2260006d1f539141f
[ "Apache-2.0" ]
418
2019-06-26T05:55:42.000Z
2022-03-31T10:46:57.000Z
ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_text_binary_classification_online_container.ipynb
polong-lin/ai-platform-samples
ef7856a7cae667f88bfad5d2260006d1f539141f
[ "Apache-2.0" ]
362
2019-06-26T20:41:17.000Z
2022-02-10T16:02:16.000Z
ai-platform-unified/notebooks/unofficial/gapic/custom/showcase_custom_text_binary_classification_online_container.ipynb
polong-lin/ai-platform-samples
ef7856a7cae667f88bfad5d2260006d1f539141f
[ "Apache-2.0" ]
229
2019-06-29T17:55:33.000Z
2022-03-14T15:52:58.000Z
40.823985
503
0.563238
[ [ [ "# Copyright 2020 Google LLC\n#\n# 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_____" ] ], [ [ "# Vertex client library: Custom training text binary classification model with custom container for online prediction\n\n<table align=\"left\">\n <td>\n <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/community/gapic/custom/showcase_custom_text_binary_classification_online_container.ipynb\">\n <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n </a>\n </td>\n <td>\n <a href=\"https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/community/gapic/custom/showcase_custom_text_binary_classification_online_container.ipynb\">\n <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n View on GitHub\n </a>\n </td>\n</table>\n<br/><br/><br/>", "_____no_output_____" ], [ "## Overview\n\n\nThis tutorial demonstrates how to use the Vertex client library for Python to train using a custom container and deploy a custom text binary classification model for online prediction.", "_____no_output_____" ], [ "### Dataset\n\nThe dataset used for this tutorial is the [IMDB Movie Reviews](https://www.tensorflow.org/datasets/catalog/imdb_reviews) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts whether a review is positive or negative in sentiment.", "_____no_output_____" ], [ "### Objective\n\nIn this tutorial, you create a custom model from a Python script in a custom Docker container using the Vertex client library, and then do a prediction on the deployed model by sending data. You can alternatively create custom models using `gcloud` command-line tool or online using Google Cloud Console.\n\nThe steps performed include:\n\n- Create a Vertex custom job for training a model.\n- Train a TensorFlow model using a custom container.\n- Retrieve and load the model artifacts.\n- View the model evaluation.\n- Upload the model as a Vertex `Model` resource.\n- Deploy the `Model` resource to a serving `Endpoint` resource.\n- Make a prediction.\n- Undeploy the `Model` resource.", "_____no_output_____" ], [ "### Costs\n\nThis tutorial uses billable components of Google Cloud (GCP):\n\n* Vertex AI\n* Cloud Storage\n\nLearn about [Vertex AI\npricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\npricing](https://cloud.google.com/storage/pricing), and use the [Pricing\nCalculator](https://cloud.google.com/products/calculator/)\nto generate a cost estimate based on your projected usage.", "_____no_output_____" ], [ "## Installation\n\nInstall the latest version of Vertex client library.", "_____no_output_____" ] ], [ [ "import os\nimport sys\n\n# Google Cloud Notebook\nif os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n USER_FLAG = \"--user\"\nelse:\n USER_FLAG = \"\"\n\n! pip3 install -U google-cloud-aiplatform $USER_FLAG", "_____no_output_____" ] ], [ [ "Install the latest GA version of *google-cloud-storage* library as well.", "_____no_output_____" ] ], [ [ "! pip3 install -U google-cloud-storage $USER_FLAG", "_____no_output_____" ] ], [ [ "### Restart the kernel\n\nOnce you've installed the Vertex client library and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.", "_____no_output_____" ] ], [ [ "if not os.getenv(\"IS_TESTING\"):\n # Automatically restart kernel after installs\n import IPython\n\n app = IPython.Application.instance()\n app.kernel.do_shutdown(True)", "_____no_output_____" ] ], [ [ "## Before you begin\n\n### GPU runtime\n\n*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n\n### Set up your Google Cloud project\n\n**The following steps are required, regardless of your notebook environment.**\n\n1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n\n2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n\n3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n\n4. [The Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebook.\n\n5. Enter your project ID in the cell below. Then run the cell to make sure the\nCloud SDK uses the right project for all the commands in this notebook.\n\n**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.", "_____no_output_____" ] ], [ [ "PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}", "_____no_output_____" ], [ "if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n # Get your GCP project id from gcloud\n shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n PROJECT_ID = shell_output[0]\n print(\"Project ID:\", PROJECT_ID)", "_____no_output_____" ], [ "! gcloud config set project $PROJECT_ID", "_____no_output_____" ] ], [ [ "#### Region\n\nYou can also change the `REGION` variable, which is used for operations\nthroughout the rest of this notebook. Below are regions supported for Vertex. We recommend that you choose the region closest to you.\n\n- Americas: `us-central1`\n- Europe: `europe-west4`\n- Asia Pacific: `asia-east1`\n\nYou may not use a multi-regional bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see the [Vertex locations documentation](https://cloud.google.com/vertex-ai/docs/general/locations)", "_____no_output_____" ] ], [ [ "REGION = \"us-central1\" # @param {type: \"string\"}", "_____no_output_____" ] ], [ [ "#### Timestamp\n\nIf you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.", "_____no_output_____" ] ], [ [ "from datetime import datetime\n\nTIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")", "_____no_output_____" ] ], [ [ "### Authenticate your Google Cloud account\n\n**If you are using Google Cloud Notebook**, your environment is already authenticated. Skip this step.\n\n**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n\n**Otherwise**, follow these steps:\n\nIn the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n\n**Click Create service account**.\n\nIn the **Service account name** field, enter a name, and click **Create**.\n\nIn the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n\nClick Create. A JSON file that contains your key downloads to your local environment.\n\nEnter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.", "_____no_output_____" ] ], [ [ "# If you are running this notebook in Colab, run this cell and follow the\n# instructions to authenticate your GCP account. This provides access to your\n# Cloud Storage bucket and lets you submit training jobs and prediction\n# requests.\n\n# If on Google Cloud Notebook, then don't execute this code\nif not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n if \"google.colab\" in sys.modules:\n from google.colab import auth as google_auth\n\n google_auth.authenticate_user()\n\n # If you are running this notebook locally, replace the string below with the\n # path to your service account key and run this cell to authenticate your GCP\n # account.\n elif not os.getenv(\"IS_TESTING\"):\n %env GOOGLE_APPLICATION_CREDENTIALS ''", "_____no_output_____" ] ], [ [ "### Create a Cloud Storage bucket\n\n**The following steps are required, regardless of your notebook environment.**\n\nWhen you submit a custom training job using the Vertex client library, you upload a Python package\ncontaining your training code to a Cloud Storage bucket. Vertex runs\nthe code from this package. In this tutorial, Vertex also saves the\ntrained model that results from your job in the same bucket. You can then\ncreate an `Endpoint` resource based on this output in order to serve\nonline predictions.\n\nSet the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization.", "_____no_output_____" ] ], [ [ "BUCKET_NAME = \"gs://[your-bucket-name]\" # @param {type:\"string\"}", "_____no_output_____" ], [ "if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP", "_____no_output_____" ] ], [ [ "**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.", "_____no_output_____" ] ], [ [ "! gsutil mb -l $REGION $BUCKET_NAME", "_____no_output_____" ] ], [ [ "Finally, validate access to your Cloud Storage bucket by examining its contents:", "_____no_output_____" ] ], [ [ "! gsutil ls -al $BUCKET_NAME", "_____no_output_____" ] ], [ [ "### Set up variables\n\nNext, set up some variables used throughout the tutorial.\n### Import libraries and define constants", "_____no_output_____" ], [ "#### Import Vertex client library\n\nImport the Vertex client library into our Python environment.", "_____no_output_____" ] ], [ [ "import time\n\nfrom google.cloud.aiplatform import gapic as aip\nfrom google.protobuf import json_format\nfrom google.protobuf.json_format import MessageToJson, ParseDict\nfrom google.protobuf.struct_pb2 import Struct, Value", "_____no_output_____" ] ], [ [ "#### Vertex constants\n\nSetup up the following constants for Vertex:\n\n- `API_ENDPOINT`: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services.\n- `PARENT`: The Vertex location root path for dataset, model, job, pipeline and endpoint resources.", "_____no_output_____" ] ], [ [ "# API service endpoint\nAPI_ENDPOINT = \"{}-aiplatform.googleapis.com\".format(REGION)\n\n# Vertex location root path for your dataset, model and endpoint resources\nPARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION", "_____no_output_____" ] ], [ [ "#### Hardware Accelerators\n\nSet the hardware accelerators (e.g., GPU), if any, for training and prediction.\n\nSet the variables `TRAIN_GPU/TRAIN_NGPU` and `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Telsa K80 GPUs allocated to each VM, you would specify:\n\n (aip.AcceleratorType.NVIDIA_TESLA_K80, 4)\n\nFor GPU, available accelerators include:\n - aip.AcceleratorType.NVIDIA_TESLA_K80\n - aip.AcceleratorType.NVIDIA_TESLA_P100\n - aip.AcceleratorType.NVIDIA_TESLA_P4\n - aip.AcceleratorType.NVIDIA_TESLA_T4\n - aip.AcceleratorType.NVIDIA_TESLA_V100\n\n\nOtherwise specify `(None, None)` to use a container image to run on a CPU.\n\n*Note*: TF releases before 2.3 for GPU support will fail to load the custom model in this tutorial. It is a known issue and fixed in TF 2.3 -- which is caused by static graph ops that are generated in the serving function. If you encounter this issue on your own custom models, use a container image for TF 2.3 with GPU support.", "_____no_output_____" ] ], [ [ "if os.getenv(\"IS_TESTING_TRAIN_GPU\"):\n TRAIN_GPU, TRAIN_NGPU = (\n aip.AcceleratorType.NVIDIA_TESLA_K80,\n int(os.getenv(\"IS_TESTING_TRAIN_GPU\")),\n )\nelse:\n TRAIN_GPU, TRAIN_NGPU = (None, None)\n\nif os.getenv(\"IS_TESTING_DEPOLY_GPU\"):\n DEPLOY_GPU, DEPLOY_NGPU = (\n aip.AcceleratorType.NVIDIA_TESLA_K80,\n int(os.getenv(\"IS_TESTING_DEPOLY_GPU\")),\n )\nelse:\n DEPLOY_GPU, DEPLOY_NGPU = (None, None)", "_____no_output_____" ] ], [ [ "#### Container (Docker) image\n\nNext, we will set the Docker container images for prediction\n\n- Set the variable `TF` to the TensorFlow version of the container image. For example, `2-1` would be version 2.1, and `1-15` would be version 1.15. The following list shows some of the pre-built images available:\n\n - TensorFlow 1.15\n - `gcr.io/cloud-aiplatform/prediction/tf-cpu.1-15:latest`\n - `gcr.io/cloud-aiplatform/prediction/tf-gpu.1-15:latest`\n - TensorFlow 2.1\n - `gcr.io/cloud-aiplatform/prediction/tf2-cpu.2-1:latest`\n - `gcr.io/cloud-aiplatform/prediction/tf2-gpu.2-1:latest`\n - TensorFlow 2.2\n - `gcr.io/cloud-aiplatform/prediction/tf2-cpu.2-2:latest`\n - `gcr.io/cloud-aiplatform/prediction/tf2-gpu.2-2:latest`\n - TensorFlow 2.3\n - `gcr.io/cloud-aiplatform/prediction/tf2-cpu.2-3:latest`\n - `gcr.io/cloud-aiplatform/prediction/tf2-gpu.2-3:latest`\n - XGBoost\n - `gcr.io/cloud-aiplatform/prediction/xgboost-cpu.1-2:latest`\n - `gcr.io/cloud-aiplatform/prediction/xgboost-cpu.1-1:latest`\n - `gcr.io/cloud-aiplatform/prediction/xgboost-cpu.0-90:latest`\n - `gcr.io/cloud-aiplatform/prediction/xgboost-cpu.0-82:latest`\n - Scikit-learn\n - `gcr.io/cloud-aiplatform/prediction/sklearn-cpu.0-23:latest`\n - `gcr.io/cloud-aiplatform/prediction/sklearn-cpu.0-22:latest`\n - `gcr.io/cloud-aiplatform/prediction/sklearn-cpu.0-20:latest`\n\nFor the latest list, see [Pre-built containers for prediction](https://cloud.google.com/vertex-ai/docs/predictions/pre-built-containers)", "_____no_output_____" ] ], [ [ "if os.getenv(\"IS_TESTING_TF\"):\n TF = os.getenv(\"IS_TESTING_TF\")\nelse:\n TF = \"2-1\"\n\nif TF[0] == \"2\":\n if DEPLOY_GPU:\n DEPLOY_VERSION = \"tf2-gpu.{}\".format(TF)\n else:\n DEPLOY_VERSION = \"tf2-cpu.{}\".format(TF)\nelse:\n if DEPLOY_GPU:\n DEPLOY_VERSION = \"tf-gpu.{}\".format(TF)\n else:\n DEPLOY_VERSION = \"tf-cpu.{}\".format(TF)\n\nDEPLOY_IMAGE = \"gcr.io/cloud-aiplatform/prediction/{}:latest\".format(DEPLOY_VERSION)\n\nprint(\"Deployment:\", DEPLOY_IMAGE, DEPLOY_GPU)", "_____no_output_____" ] ], [ [ "#### Machine Type\n\nNext, set the machine type to use for training and prediction.\n\n- Set the variables `TRAIN_COMPUTE` and `DEPLOY_COMPUTE` to configure the compute resources for the VMs you will use for for training and prediction.\n - `machine type`\n - `n1-standard`: 3.75GB of memory per vCPU.\n - `n1-highmem`: 6.5GB of memory per vCPU\n - `n1-highcpu`: 0.9 GB of memory per vCPU\n - `vCPUs`: number of \\[2, 4, 8, 16, 32, 64, 96 \\]\n\n*Note: The following is not supported for training:*\n\n - `standard`: 2 vCPUs\n - `highcpu`: 2, 4 and 8 vCPUs\n\n*Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs*.", "_____no_output_____" ] ], [ [ "if os.getenv(\"IS_TESTING_TRAIN_MACHINE\"):\n MACHINE_TYPE = os.getenv(\"IS_TESTING_TRAIN_MACHINE\")\nelse:\n MACHINE_TYPE = \"n1-standard\"\n\nVCPU = \"4\"\nTRAIN_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\nprint(\"Train machine type\", TRAIN_COMPUTE)\n\nif os.getenv(\"IS_TESTING_DEPLOY_MACHINE\"):\n MACHINE_TYPE = os.getenv(\"IS_TESTING_DEPLOY_MACHINE\")\nelse:\n MACHINE_TYPE = \"n1-standard\"\n\nVCPU = \"4\"\nDEPLOY_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\nprint(\"Deploy machine type\", DEPLOY_COMPUTE)", "_____no_output_____" ] ], [ [ "# Tutorial\n\nNow you are ready to start creating your own custom model and training for IMDB Movie Reviews.", "_____no_output_____" ], [ "## Set up clients\n\nThe Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server.\n\nYou will use different clients in this tutorial for different steps in the workflow. So set them all up upfront.\n\n- Model Service for `Model` resources.\n- Endpoint Service for deployment.\n- Job Service for batch jobs and custom training.\n- Prediction Service for serving.", "_____no_output_____" ] ], [ [ "# client options same for all services\nclient_options = {\"api_endpoint\": API_ENDPOINT}\n\n\ndef create_job_client():\n client = aip.JobServiceClient(client_options=client_options)\n return client\n\n\ndef create_model_client():\n client = aip.ModelServiceClient(client_options=client_options)\n return client\n\n\ndef create_endpoint_client():\n client = aip.EndpointServiceClient(client_options=client_options)\n return client\n\n\ndef create_prediction_client():\n client = aip.PredictionServiceClient(client_options=client_options)\n return client\n\n\nclients = {}\nclients[\"job\"] = create_job_client()\nclients[\"model\"] = create_model_client()\nclients[\"endpoint\"] = create_endpoint_client()\nclients[\"prediction\"] = create_prediction_client()\n\nfor client in clients.items():\n print(client)", "_____no_output_____" ] ], [ [ "## Train a model\n\nThere are two ways you can train a custom model using a container image:\n\n- **Use a Google Cloud prebuilt container**. If you use a prebuilt container, you will additionally specify a Python package to install into the container image. This Python package contains your code for training a custom model.\n\n- **Use your own custom container image**. If you use your own container, the container needs to contain your code for training a custom model.", "_____no_output_____" ], [ "### Create a Docker file\n\nIn this tutorial, you train a IMDB Movie Reviews model using your own custom container.\n\nTo use your own custom container, you build a Docker file. First, you will create a directory for the container components.", "_____no_output_____" ], [ "### Examine the training package\n\n#### Package layout\n\nBefore you start the training, you will look at how a Python package is assembled for a custom training job. When unarchived, the package contains the following directory/file layout.\n\n- PKG-INFO\n- README.md\n- setup.cfg\n- setup.py\n- trainer\n - \\_\\_init\\_\\_.py\n - task.py\n\nThe files `setup.cfg` and `setup.py` are the instructions for installing the package into the operating environment of the Docker image.\n\nThe file `trainer/task.py` is the Python script for executing the custom training job. *Note*, when we referred to it in the worker pool specification, we replace the directory slash with a dot (`trainer.task`) and dropped the file suffix (`.py`).\n\n#### Package Assembly\n\nIn the following cells, you will assemble the training package.", "_____no_output_____" ] ], [ [ "# Make folder for Python training script\n! rm -rf custom\n! mkdir custom\n\n# Add package information\n! touch custom/README.md\n\nsetup_cfg = \"[egg_info]\\n\\ntag_build =\\n\\ntag_date = 0\"\n! echo \"$setup_cfg\" > custom/setup.cfg\n\nsetup_py = \"import setuptools\\n\\nsetuptools.setup(\\n\\n install_requires=[\\n\\n 'tensorflow_datasets==1.3.0',\\n\\n ],\\n\\n packages=setuptools.find_packages())\"\n! echo \"$setup_py\" > custom/setup.py\n\npkg_info = \"Metadata-Version: 1.0\\n\\nName: IMDB Movie Reviews text binary classification\\n\\nVersion: 0.0.0\\n\\nSummary: Demostration training script\\n\\nHome-page: www.google.com\\n\\nAuthor: Google\\n\\nAuthor-email: [email protected]\\n\\nLicense: Public\\n\\nDescription: Demo\\n\\nPlatform: Vertex\"\n! echo \"$pkg_info\" > custom/PKG-INFO\n\n# Make the training subfolder\n! mkdir custom/trainer\n! touch custom/trainer/__init__.py", "_____no_output_____" ] ], [ [ "#### Task.py contents\n\nIn the next cell, you write the contents of the training script task.py. I won't go into detail, it's just there for you to browse. In summary:\n\n- Gets the directory where to save the model artifacts from the command line (`--model_dir`), and if not specified, then from the environment variable `AIP_MODEL_DIR`.\n- Loads IMDB Movie Reviews dataset from TF Datasets (tfds).\n- Builds a simple RNN model using TF.Keras model API.\n- Compiles the model (`compile()`).\n- Sets a training distribution strategy according to the argument `args.distribute`.\n- Trains the model (`fit()`) with epochs specified by `args.epochs`.\n- Saves the trained model (`save(args.model_dir)`) to the specified model directory.", "_____no_output_____" ] ], [ [ "%%writefile custom/trainer/task.py\n# Single, Mirror and Multi-Machine Distributed Training for IMDB\n\nimport tensorflow_datasets as tfds\nimport tensorflow as tf\nfrom tensorflow.python.client import device_lib\nimport argparse\nimport os\nimport sys\ntfds.disable_progress_bar()\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model-dir', dest='model_dir',\n default=os.getenv('AIP_MODEL_DIR'), type=str, help='Model dir.')\nparser.add_argument('--lr', dest='lr',\n default=1e-4, type=float,\n help='Learning rate.')\nparser.add_argument('--epochs', dest='epochs',\n default=20, type=int,\n help='Number of epochs.')\nparser.add_argument('--steps', dest='steps',\n default=100, type=int,\n help='Number of steps per epoch.')\nparser.add_argument('--distribute', dest='distribute', type=str, default='single',\n help='distributed training strategy')\nargs = parser.parse_args()\n\nprint('Python Version = {}'.format(sys.version))\nprint('TensorFlow Version = {}'.format(tf.__version__))\nprint('TF_CONFIG = {}'.format(os.environ.get('TF_CONFIG', 'Not found')))\nprint(device_lib.list_local_devices())\n\n# Single Machine, single compute device\nif args.distribute == 'single':\n if tf.test.is_gpu_available():\n strategy = tf.distribute.OneDeviceStrategy(device=\"/gpu:0\")\n else:\n strategy = tf.distribute.OneDeviceStrategy(device=\"/cpu:0\")\n# Single Machine, multiple compute device\nelif args.distribute == 'mirror':\n strategy = tf.distribute.MirroredStrategy()\n# Multiple Machine, multiple compute device\nelif args.distribute == 'multi':\n strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()\n\n# Multi-worker configuration\nprint('num_replicas_in_sync = {}'.format(strategy.num_replicas_in_sync))\n\n# Preparing dataset\nBUFFER_SIZE = 10000\nBATCH_SIZE = 64\n\n\ndef make_datasets():\n dataset, info = tfds.load('imdb_reviews/subwords8k', with_info=True,\n as_supervised=True)\n train_dataset, test_dataset = dataset['train'], dataset['test']\n encoder = info.features['text'].encoder\n\n padded_shapes = ([None],())\n return train_dataset.shuffle(BUFFER_SIZE).padded_batch(BATCH_SIZE, padded_shapes), encoder\n\n\ntrain_dataset, encoder = make_datasets()\n\n# Build the Keras model\ndef build_and_compile_rnn_model(encoder):\n model = tf.keras.Sequential([\n tf.keras.layers.Embedding(encoder.vocab_size, 64),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n ])\n model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n optimizer=tf.keras.optimizers.Adam(args.lr),\n metrics=['accuracy'])\n return model\n\n\nwith strategy.scope():\n # Creation of dataset, and model building/compiling need to be within\n # `strategy.scope()`.\n model = build_and_compile_rnn_model(encoder)\n\n# Train the model\nmodel.fit(train_dataset, epochs=args.epochs, steps_per_epoch=args.steps)\nmodel.save(args.model_dir)", "_____no_output_____" ] ], [ [ "#### Write the Docker file contents\n\nYour first step in containerizing your code is to create a Docker file. In your Docker you’ll include all the commands needed to run your container image. It’ll install all the libraries you’re using and set up the entry point for your training code.\n\n1. Install a pre-defined container image from TensorFlow repository for deep learning images.\n2. Copies in the Python training code, to be shown subsequently.\n3. Sets the entry into the Python training script as `trainer/task.py`. Note, the `.py` is dropped in the ENTRYPOINT command, as it is implied.", "_____no_output_____" ] ], [ [ "%%writefile custom/Dockerfile\n\nFROM gcr.io/deeplearning-platform-release/tf2-cpu.2-1\nWORKDIR /root\n\nWORKDIR /\n\n# Copies the trainer code to the docker image.\nCOPY trainer /trainer\n\n# Sets up the entry point to invoke the trainer.\nENTRYPOINT [\"python\", \"-m\", \"trainer.task\"]", "_____no_output_____" ] ], [ [ "#### Build the container locally\n\nNext, you will provide a name for your customer container that you will use when you submit it to the Google Container Registry.", "_____no_output_____" ] ], [ [ "TRAIN_IMAGE = \"gcr.io/\" + PROJECT_ID + \"/imdb:v1\"", "_____no_output_____" ] ], [ [ "Next, build the container.", "_____no_output_____" ] ], [ [ "! docker build custom -t $TRAIN_IMAGE", "_____no_output_____" ] ], [ [ "#### Test the container locally\n\nRun the container within your notebook instance to ensure it’s working correctly. You will run it for 5 epochs.", "_____no_output_____" ] ], [ [ "! docker run $TRAIN_IMAGE --epochs=5", "_____no_output_____" ] ], [ [ "#### Register the custom container\n\nWhen you’ve finished running the container locally, push it to Google Container Registry.", "_____no_output_____" ] ], [ [ "! docker push $TRAIN_IMAGE", "_____no_output_____" ] ], [ [ "#### Store training script on your Cloud Storage bucket\n\nNext, you package the training folder into a compressed tar ball, and then store it in your Cloud Storage bucket.", "_____no_output_____" ] ], [ [ "! rm -f custom.tar custom.tar.gz\n! tar cvf custom.tar custom\n! gzip custom.tar\n! gsutil cp custom.tar.gz $BUCKET_NAME/trainer_imdb.tar.gz", "_____no_output_____" ] ], [ [ "## Prepare your custom job specification\n\nNow that your clients are ready, your first step is to create a Job Specification for your custom training job. The job specification will consist of the following:\n\n- `worker_pool_spec` : The specification of the type of machine(s) you will use for training and how many (single or distributed)\n- `container_spec` : The specification of the custom container.", "_____no_output_____" ], [ "### Prepare your machine specification\n\nNow define the machine specification for your custom training job. This tells Vertex what type of machine instance to provision for the training.\n - `machine_type`: The type of GCP instance to provision -- e.g., n1-standard-8.\n - `accelerator_type`: The type, if any, of hardware accelerator. In this tutorial if you previously set the variable `TRAIN_GPU != None`, you are using a GPU; otherwise you will use a CPU.\n - `accelerator_count`: The number of accelerators.", "_____no_output_____" ] ], [ [ "if TRAIN_GPU:\n machine_spec = {\n \"machine_type\": TRAIN_COMPUTE,\n \"accelerator_type\": TRAIN_GPU,\n \"accelerator_count\": TRAIN_NGPU,\n }\nelse:\n machine_spec = {\"machine_type\": TRAIN_COMPUTE, \"accelerator_count\": 0}", "_____no_output_____" ] ], [ [ "### Prepare your disk specification\n\n(optional) Now define the disk specification for your custom training job. This tells Vertex what type and size of disk to provision in each machine instance for the training.\n\n - `boot_disk_type`: Either SSD or Standard. SSD is faster, and Standard is less expensive. Defaults to SSD.\n - `boot_disk_size_gb`: Size of disk in GB.", "_____no_output_____" ] ], [ [ "DISK_TYPE = \"pd-ssd\" # [ pd-ssd, pd-standard]\nDISK_SIZE = 200 # GB\n\ndisk_spec = {\"boot_disk_type\": DISK_TYPE, \"boot_disk_size_gb\": DISK_SIZE}", "_____no_output_____" ] ], [ [ "### Prepare your container specification\n\nNow define the container specification for your custom training container:\n\n- `image_uri`: The custom container image.\n- `args`: The command-line arguments to pass to the executable that is set as the entry point into the container.\n - `--model-dir` : For our demonstrations, we use this command-line argument to specify where to store the model artifacts.\n - direct: You pass the Cloud Storage location as a command line argument to your training script (set variable `DIRECT = True`), or\n - indirect: The service passes the Cloud Storage location as the environment variable `AIP_MODEL_DIR` to your training script (set variable `DIRECT = False`). In this case, you tell the service the model artifact location in the job specification.\n - `\"--epochs=\" + EPOCHS`: The number of epochs for training.\n - `\"--steps=\" + STEPS`: The number of steps per epoch.", "_____no_output_____" ] ], [ [ "JOB_NAME = \"_custom_container\" + TIMESTAMP\nMODEL_DIR = \"{}/{}\".format(BUCKET_NAME, JOB_NAME)\n\nEPOCHS = 20\nSTEPS = 100\n\nDIRECT = True\nif DIRECT:\n CMDARGS = [\n \"--model-dir=\" + MODEL_DIR,\n \"--epochs=\" + str(EPOCHS),\n \"--steps=\" + str(STEPS),\n ]\nelse:\n CMDARGS = [\n \"--epochs=\" + str(EPOCHS),\n \"--steps=\" + str(STEPS),\n ]\n\ncontainer_spec = {\n \"image_uri\": TRAIN_IMAGE,\n \"args\": CMDARGS,\n}", "_____no_output_____" ] ], [ [ "### Define the worker pool specification\n\nNext, you define the worker pool specification for your custom training job. The worker pool specification will consist of the following:\n\n- `replica_count`: The number of instances to provision of this machine type.\n- `machine_spec`: The hardware specification.\n- `disk_spec` : (optional) The disk storage specification.\n- `container_spec`: The Docker container to install on the VM instance(s).", "_____no_output_____" ] ], [ [ "worker_pool_spec = [\n {\n \"replica_count\": 1,\n \"machine_spec\": machine_spec,\n \"container_spec\": container_spec,\n \"disk_spec\": disk_spec,\n }\n]", "_____no_output_____" ] ], [ [ "### Assemble a job specification\n\nNow assemble the complete description for the custom job specification:\n\n- `display_name`: The human readable name you assign to this custom job.\n- `job_spec`: The specification for the custom job.\n - `worker_pool_specs`: The specification for the machine VM instances.\n - `base_output_directory`: This tells the service the Cloud Storage location where to save the model artifacts (when variable `DIRECT = False`). The service will then pass the location to the training script as the environment variable `AIP_MODEL_DIR`, and the path will be of the form:\n\n <output_uri_prefix>/model", "_____no_output_____" ] ], [ [ "if DIRECT:\n job_spec = {\"worker_pool_specs\": worker_pool_spec}\nelse:\n job_spec = {\n \"worker_pool_specs\": worker_pool_spec,\n \"base_output_directory\": {\"output_uri_prefix\": MODEL_DIR},\n }\n\ncustom_job = {\"display_name\": JOB_NAME, \"job_spec\": job_spec}", "_____no_output_____" ] ], [ [ "### Train the model\n\n\nNow start the training of your custom training job on Vertex. Use this helper function `create_custom_job`, which takes the following parameter:\n\n-`custom_job`: The specification for the custom job.\n\nThe helper function calls job client service's `create_custom_job` method, with the following parameters:\n\n-`parent`: The Vertex location path to `Dataset`, `Model` and `Endpoint` resources.\n-`custom_job`: The specification for the custom job.\n\nYou will display a handful of the fields returned in `response` object, with the two that are of most interest are:\n\n`response.name`: The Vertex fully qualified identifier assigned to this custom training job. You save this identifier for using in subsequent steps.\n\n`response.state`: The current state of the custom training job.", "_____no_output_____" ] ], [ [ "def create_custom_job(custom_job):\n response = clients[\"job\"].create_custom_job(parent=PARENT, custom_job=custom_job)\n print(\"name:\", response.name)\n print(\"display_name:\", response.display_name)\n print(\"state:\", response.state)\n print(\"create_time:\", response.create_time)\n print(\"update_time:\", response.update_time)\n return response\n\n\nresponse = create_custom_job(custom_job)", "_____no_output_____" ] ], [ [ "Now get the unique identifier for the custom job you created.", "_____no_output_____" ] ], [ [ "# The full unique ID for the custom job\njob_id = response.name\n# The short numeric ID for the custom job\njob_short_id = job_id.split(\"/\")[-1]\n\nprint(job_id)", "_____no_output_____" ] ], [ [ "### Get information on a custom job\n\nNext, use this helper function `get_custom_job`, which takes the following parameter:\n\n- `name`: The Vertex fully qualified identifier for the custom job.\n\nThe helper function calls the job client service's`get_custom_job` method, with the following parameter:\n\n- `name`: The Vertex fully qualified identifier for the custom job.\n\nIf you recall, you got the Vertex fully qualified identifier for the custom job in the `response.name` field when you called the `create_custom_job` method, and saved the identifier in the variable `job_id`.", "_____no_output_____" ] ], [ [ "def get_custom_job(name, silent=False):\n response = clients[\"job\"].get_custom_job(name=name)\n if silent:\n return response\n\n print(\"name:\", response.name)\n print(\"display_name:\", response.display_name)\n print(\"state:\", response.state)\n print(\"create_time:\", response.create_time)\n print(\"update_time:\", response.update_time)\n return response\n\n\nresponse = get_custom_job(job_id)", "_____no_output_____" ] ], [ [ "# Deployment\n\nTraining the above model may take upwards of 20 minutes time.\n\nOnce your model is done training, you can calculate the actual time it took to train the model by subtracting `end_time` from `start_time`. For your model, we will need to know the location of the saved model, which the Python script saved in your local Cloud Storage bucket at `MODEL_DIR + '/saved_model.pb'`.", "_____no_output_____" ] ], [ [ "while True:\n response = get_custom_job(job_id, True)\n if response.state != aip.JobState.JOB_STATE_SUCCEEDED:\n print(\"Training job has not completed:\", response.state)\n model_path_to_deploy = None\n if response.state == aip.JobState.JOB_STATE_FAILED:\n break\n else:\n if not DIRECT:\n MODEL_DIR = MODEL_DIR + \"/model\"\n model_path_to_deploy = MODEL_DIR\n print(\"Training Time:\", response.update_time - response.create_time)\n break\n time.sleep(60)\n\nprint(\"model_to_deploy:\", model_path_to_deploy)", "_____no_output_____" ] ], [ [ "## Load the saved model\n\nYour model is stored in a TensorFlow SavedModel format in a Cloud Storage bucket. Now load it from the Cloud Storage bucket, and then you can do some things, like evaluate the model, and do a prediction.\n\nTo load, you use the TF.Keras `model.load_model()` method passing it the Cloud Storage path where the model is saved -- specified by `MODEL_DIR`.", "_____no_output_____" ] ], [ [ "import tensorflow as tf\n\nmodel = tf.keras.models.load_model(MODEL_DIR)", "_____no_output_____" ] ], [ [ "## Evaluate the model\n\nNow let's find out how good the model is.\n\n### Load evaluation data\n\nYou will load the IMDB Movie Review test (holdout) data from `tfds.datasets`, using the method `load()`. This will return the dataset as a tuple of two elements. The first element is the dataset and the second is information on the dataset, which will contain the predefined vocabulary encoder. The encoder will convert words into a numerical embedding, which was pretrained and used in the custom training script.\n\n\nWhen you trained the model, you needed to set a fix input length for your text. For forward feeding batches, the `padded_batch()` property of the corresponding `tf.dataset` was set to pad each input sequence into the same shape for a batch.\n\nFor the test data, you also need to set the `padded_batch()` property accordingly.", "_____no_output_____" ] ], [ [ "import tensorflow_datasets as tfds\n\ndataset, info = tfds.load(\"imdb_reviews/subwords8k\", with_info=True, as_supervised=True)\ntest_dataset = dataset[\"test\"]\nencoder = info.features[\"text\"].encoder\n\nBATCH_SIZE = 64\npadded_shapes = ([None], ())\ntest_dataset = test_dataset.padded_batch(BATCH_SIZE, padded_shapes)", "_____no_output_____" ] ], [ [ "### Perform the model evaluation\n\nNow evaluate how well the model in the custom job did.", "_____no_output_____" ] ], [ [ "model.evaluate(test_dataset)", "_____no_output_____" ] ], [ [ "## Upload the model for serving\n\nNext, you will upload your TF.Keras model from the custom job to Vertex `Model` service, which will create a Vertex `Model` resource for your custom model. During upload, you need to define a serving function to convert data to the format your model expects. If you send encoded data to Vertex, your serving function ensures that the data is decoded on the model server before it is passed as input to your model.\n\n### How does the serving function work\n\nWhen you send a request to an online prediction server, the request is received by a HTTP server. The HTTP server extracts the prediction request from the HTTP request content body. The extracted prediction request is forwarded to the serving function. For Google pre-built prediction containers, the request content is passed to the serving function as a `tf.string`.\n\nThe serving function consists of two parts:\n\n- `preprocessing function`:\n - Converts the input (`tf.string`) to the input shape and data type of the underlying model (dynamic graph).\n - Performs the same preprocessing of the data that was done during training the underlying model -- e.g., normalizing, scaling, etc.\n- `post-processing function`:\n - Converts the model output to format expected by the receiving application -- e.q., compresses the output.\n - Packages the output for the the receiving application -- e.g., add headings, make JSON object, etc.\n\nBoth the preprocessing and post-processing functions are converted to static graphs which are fused to the model. The output from the underlying model is passed to the post-processing function. The post-processing function passes the converted/packaged output back to the HTTP server. The HTTP server returns the output as the HTTP response content.\n\nOne consideration you need to consider when building serving functions for TF.Keras models is that they run as static graphs. That means, you cannot use TF graph operations that require a dynamic graph. If you do, you will get an error during the compile of the serving function which will indicate that you are using an EagerTensor which is not supported.", "_____no_output_____" ], [ "## Get the serving function signature\n\nYou can get the signatures of your model's input and output layers by reloading the model into memory, and querying it for the signatures corresponding to each layer.\n\nWhen making a prediction request, you need to route the request to the serving function instead of the model, so you need to know the input layer name of the serving function -- which you will use later when you make a prediction request.", "_____no_output_____" ] ], [ [ "loaded = tf.saved_model.load(model_path_to_deploy)\n\nserving_input = list(\n loaded.signatures[\"serving_default\"].structured_input_signature[1].keys()\n)[0]\nprint(\"Serving function input:\", serving_input)", "_____no_output_____" ] ], [ [ "### Upload the model\n\nUse this helper function `upload_model` to upload your model, stored in SavedModel format, up to the `Model` service, which will instantiate a Vertex `Model` resource instance for your model. Once you've done that, you can use the `Model` resource instance in the same way as any other Vertex `Model` resource instance, such as deploying to an `Endpoint` resource for serving predictions.\n\nThe helper function takes the following parameters:\n\n- `display_name`: A human readable name for the `Endpoint` service.\n- `image_uri`: The container image for the model deployment.\n- `model_uri`: The Cloud Storage path to our SavedModel artificat. For this tutorial, this is the Cloud Storage location where the `trainer/task.py` saved the model artifacts, which we specified in the variable `MODEL_DIR`.\n\nThe helper function calls the `Model` client service's method `upload_model`, which takes the following parameters:\n\n- `parent`: The Vertex location root path for `Dataset`, `Model` and `Endpoint` resources.\n- `model`: The specification for the Vertex `Model` resource instance.\n\nLet's now dive deeper into the Vertex model specification `model`. This is a dictionary object that consists of the following fields:\n\n- `display_name`: A human readable name for the `Model` resource.\n- `metadata_schema_uri`: Since your model was built without an Vertex `Dataset` resource, you will leave this blank (`''`).\n- `artificat_uri`: The Cloud Storage path where the model is stored in SavedModel format.\n- `container_spec`: This is the specification for the Docker container that will be installed on the `Endpoint` resource, from which the `Model` resource will serve predictions. Use the variable you set earlier `DEPLOY_GPU != None` to use a GPU; otherwise only a CPU is allocated.\n\nUploading a model into a Vertex Model resource returns a long running operation, since it may take a few moments. You call response.result(), which is a synchronous call and will return when the Vertex Model resource is ready.\n\nThe helper function returns the Vertex fully qualified identifier for the corresponding Vertex Model instance upload_model_response.model. You will save the identifier for subsequent steps in the variable model_to_deploy_id.", "_____no_output_____" ] ], [ [ "IMAGE_URI = DEPLOY_IMAGE\n\n\ndef upload_model(display_name, image_uri, model_uri):\n model = {\n \"display_name\": display_name,\n \"metadata_schema_uri\": \"\",\n \"artifact_uri\": model_uri,\n \"container_spec\": {\n \"image_uri\": image_uri,\n \"command\": [],\n \"args\": [],\n \"env\": [{\"name\": \"env_name\", \"value\": \"env_value\"}],\n \"ports\": [{\"container_port\": 8080}],\n \"predict_route\": \"\",\n \"health_route\": \"\",\n },\n }\n response = clients[\"model\"].upload_model(parent=PARENT, model=model)\n print(\"Long running operation:\", response.operation.name)\n upload_model_response = response.result(timeout=180)\n print(\"upload_model_response\")\n print(\" model:\", upload_model_response.model)\n return upload_model_response.model\n\n\nmodel_to_deploy_id = upload_model(\"imdb-\" + TIMESTAMP, IMAGE_URI, model_path_to_deploy)", "_____no_output_____" ] ], [ [ "### Get `Model` resource information\n\nNow let's get the model information for just your model. Use this helper function `get_model`, with the following parameter:\n\n- `name`: The Vertex unique identifier for the `Model` resource.\n\nThis helper function calls the Vertex `Model` client service's method `get_model`, with the following parameter:\n\n- `name`: The Vertex unique identifier for the `Model` resource.", "_____no_output_____" ] ], [ [ "def get_model(name):\n response = clients[\"model\"].get_model(name=name)\n print(response)\n\n\nget_model(model_to_deploy_id)", "_____no_output_____" ] ], [ [ "## Deploy the `Model` resource\n\nNow deploy the trained Vertex custom `Model` resource. This requires two steps:\n\n1. Create an `Endpoint` resource for deploying the `Model` resource to.\n\n2. Deploy the `Model` resource to the `Endpoint` resource.", "_____no_output_____" ], [ "### Create an `Endpoint` resource\n\nUse this helper function `create_endpoint` to create an endpoint to deploy the model to for serving predictions, with the following parameter:\n\n- `display_name`: A human readable name for the `Endpoint` resource.\n\nThe helper function uses the endpoint client service's `create_endpoint` method, which takes the following parameter:\n\n- `display_name`: A human readable name for the `Endpoint` resource.\n\nCreating an `Endpoint` resource returns a long running operation, since it may take a few moments to provision the `Endpoint` resource for serving. You call `response.result()`, which is a synchronous call and will return when the Endpoint resource is ready. The helper function returns the Vertex fully qualified identifier for the `Endpoint` resource: `response.name`.", "_____no_output_____" ] ], [ [ "ENDPOINT_NAME = \"imdb_endpoint-\" + TIMESTAMP\n\n\ndef create_endpoint(display_name):\n endpoint = {\"display_name\": display_name}\n response = clients[\"endpoint\"].create_endpoint(parent=PARENT, endpoint=endpoint)\n print(\"Long running operation:\", response.operation.name)\n\n result = response.result(timeout=300)\n print(\"result\")\n print(\" name:\", result.name)\n print(\" display_name:\", result.display_name)\n print(\" description:\", result.description)\n print(\" labels:\", result.labels)\n print(\" create_time:\", result.create_time)\n print(\" update_time:\", result.update_time)\n return result\n\n\nresult = create_endpoint(ENDPOINT_NAME)", "_____no_output_____" ] ], [ [ "Now get the unique identifier for the `Endpoint` resource you created.", "_____no_output_____" ] ], [ [ "# The full unique ID for the endpoint\nendpoint_id = result.name\n# The short numeric ID for the endpoint\nendpoint_short_id = endpoint_id.split(\"/\")[-1]\n\nprint(endpoint_id)", "_____no_output_____" ] ], [ [ "### Compute instance scaling\n\nYou have several choices on scaling the compute instances for handling your online prediction requests:\n\n- Single Instance: The online prediction requests are processed on a single compute instance.\n - Set the minimum (`MIN_NODES`) and maximum (`MAX_NODES`) number of compute instances to one.\n\n- Manual Scaling: The online prediction requests are split across a fixed number of compute instances that you manually specified.\n - Set the minimum (`MIN_NODES`) and maximum (`MAX_NODES`) number of compute instances to the same number of nodes. When a model is first deployed to the instance, the fixed number of compute instances are provisioned and online prediction requests are evenly distributed across them.\n\n- Auto Scaling: The online prediction requests are split across a scaleable number of compute instances.\n - Set the minimum (`MIN_NODES`) number of compute instances to provision when a model is first deployed and to de-provision, and set the maximum (`MAX_NODES) number of compute instances to provision, depending on load conditions.\n\nThe minimum number of compute instances corresponds to the field `min_replica_count` and the maximum number of compute instances corresponds to the field `max_replica_count`, in your subsequent deployment request.", "_____no_output_____" ] ], [ [ "MIN_NODES = 1\nMAX_NODES = 1", "_____no_output_____" ] ], [ [ "### Deploy `Model` resource to the `Endpoint` resource\n\nUse this helper function `deploy_model` to deploy the `Model` resource to the `Endpoint` resource you created for serving predictions, with the following parameters:\n\n- `model`: The Vertex fully qualified model identifier of the model to upload (deploy) from the training pipeline.\n- `deploy_model_display_name`: A human readable name for the deployed model.\n- `endpoint`: The Vertex fully qualified endpoint identifier to deploy the model to.\n\nThe helper function calls the `Endpoint` client service's method `deploy_model`, which takes the following parameters:\n\n- `endpoint`: The Vertex fully qualified `Endpoint` resource identifier to deploy the `Model` resource to.\n- `deployed_model`: The requirements specification for deploying the model.\n- `traffic_split`: Percent of traffic at the endpoint that goes to this model, which is specified as a dictionary of one or more key/value pairs.\n - If only one model, then specify as **{ \"0\": 100 }**, where \"0\" refers to this model being uploaded and 100 means 100% of the traffic.\n - If there are existing models on the endpoint, for which the traffic will be split, then use `model_id` to specify as **{ \"0\": percent, model_id: percent, ... }**, where `model_id` is the model id of an existing model to the deployed endpoint. The percents must add up to 100.\n\nLet's now dive deeper into the `deployed_model` parameter. This parameter is specified as a Python dictionary with the minimum required fields:\n\n- `model`: The Vertex fully qualified model identifier of the (upload) model to deploy.\n- `display_name`: A human readable name for the deployed model.\n- `disable_container_logging`: This disables logging of container events, such as execution failures (default is container logging is enabled). Container logging is typically enabled when debugging the deployment and then disabled when deployed for production.\n- `dedicated_resources`: This refers to how many compute instances (replicas) that are scaled for serving prediction requests.\n - `machine_spec`: The compute instance to provision. Use the variable you set earlier `DEPLOY_GPU != None` to use a GPU; otherwise only a CPU is allocated.\n - `min_replica_count`: The number of compute instances to initially provision, which you set earlier as the variable `MIN_NODES`.\n - `max_replica_count`: The maximum number of compute instances to scale to, which you set earlier as the variable `MAX_NODES`.\n\n#### Traffic Split\n\nLet's now dive deeper into the `traffic_split` parameter. This parameter is specified as a Python dictionary. This might at first be a tad bit confusing. Let me explain, you can deploy more than one instance of your model to an endpoint, and then set how much (percent) goes to each instance.\n\nWhy would you do that? Perhaps you already have a previous version deployed in production -- let's call that v1. You got better model evaluation on v2, but you don't know for certain that it is really better until you deploy to production. So in the case of traffic split, you might want to deploy v2 to the same endpoint as v1, but it only get's say 10% of the traffic. That way, you can monitor how well it does without disrupting the majority of users -- until you make a final decision.\n\n#### Response\n\nThe method returns a long running operation `response`. We will wait sychronously for the operation to complete by calling the `response.result()`, which will block until the model is deployed. If this is the first time a model is deployed to the endpoint, it may take a few additional minutes to complete provisioning of resources.", "_____no_output_____" ] ], [ [ "DEPLOYED_NAME = \"imdb_deployed-\" + TIMESTAMP\n\n\ndef deploy_model(\n model, deployed_model_display_name, endpoint, traffic_split={\"0\": 100}\n):\n\n if DEPLOY_GPU:\n machine_spec = {\n \"machine_type\": DEPLOY_COMPUTE,\n \"accelerator_type\": DEPLOY_GPU,\n \"accelerator_count\": DEPLOY_NGPU,\n }\n else:\n machine_spec = {\n \"machine_type\": DEPLOY_COMPUTE,\n \"accelerator_count\": 0,\n }\n\n deployed_model = {\n \"model\": model,\n \"display_name\": deployed_model_display_name,\n \"dedicated_resources\": {\n \"min_replica_count\": MIN_NODES,\n \"max_replica_count\": MAX_NODES,\n \"machine_spec\": machine_spec,\n },\n \"disable_container_logging\": False,\n }\n\n response = clients[\"endpoint\"].deploy_model(\n endpoint=endpoint, deployed_model=deployed_model, traffic_split=traffic_split\n )\n\n print(\"Long running operation:\", response.operation.name)\n result = response.result()\n print(\"result\")\n deployed_model = result.deployed_model\n print(\" deployed_model\")\n print(\" id:\", deployed_model.id)\n print(\" model:\", deployed_model.model)\n print(\" display_name:\", deployed_model.display_name)\n print(\" create_time:\", deployed_model.create_time)\n\n return deployed_model.id\n\n\ndeployed_model_id = deploy_model(model_to_deploy_id, DEPLOYED_NAME, endpoint_id)", "_____no_output_____" ] ], [ [ "## Make a online prediction request\n\nNow do a online prediction to your deployed model.", "_____no_output_____" ], [ "### Prepare the request content\n\nSince the dataset is a `tf.dataset`, which acts as a generator, we must use it as an iterator to access the data items in the test data. We do the following to get a single data item from the test data:\n\n- Set the property for the number of batches to draw per iteration to one using the method `take(1)`.\n- Iterate once through the test data -- i.e., we do a break within the for loop.\n- In the single iteration, we save the data item which is in the form of a tuple.\n- The data item will be the first element of the tuple, which you then will convert from an tensor to a numpy array -- `data[0].numpy()`.", "_____no_output_____" ] ], [ [ "import tensorflow_datasets as tfds\n\ndataset, info = tfds.load(\"imdb_reviews/subwords8k\", with_info=True, as_supervised=True)\ntest_dataset = dataset[\"test\"]\n\ntest_dataset.take(1)\nfor data in test_dataset:\n print(data)\n break\n\ntest_item = data[0].numpy()", "_____no_output_____" ] ], [ [ "### Send the prediction request\n\nOk, now you have a test data item. Use this helper function `predict_data`, which takes the following parameters:\n\n- `data`: The test data item is a 64 padded numpy 1D array.\n- `endpoint`: The Vertex AI fully qualified identifier for the endpoint where the model was deployed.\n- `parameters_dict`: Additional parameters for serving.\n\nThis function uses the prediction client service and calls the `predict` method with the following parameters:\n\n- `endpoint`: The Vertex AI fully qualified identifier for the endpoint where the model was deployed.\n- `instances`: A list of instances (data items) to predict.\n- `parameters`: Additional parameters for serving.\n\nTo pass the test data to the prediction service, you must package it for transmission to the serving binary as follows:\n\n 1. Convert the data item from a 1D numpy array to a 1D Python list.\n 2. Convert the prediction request to a serialized Google protobuf (`json_format.ParseDict()`)\n\nEach instance in the prediction request is a dictionary entry of the form:\n\n {input_name: content}\n\n- `input_name`: the name of the input layer of the underlying model.\n- `content`: The data item as a 1D Python list.\n\nSince the `predict()` service can take multiple data items (instances), you will send your single data item as a list of one data item. As a final step, you package the instances list into Google's protobuf format -- which is what we pass to the `predict()` service.\n\nThe `response` object returns a list, where each element in the list corresponds to the corresponding image in the request. You will see in the output for each prediction:\n\n- `predictions` -- the predicated binary sentiment between 0 (negative) and 1 (positive).", "_____no_output_____" ] ], [ [ "def predict_data(data, endpoint, parameters_dict):\n parameters = json_format.ParseDict(parameters_dict, Value())\n\n # The format of each instance should conform to the deployed model's prediction input schema.\n instances_list = [{serving_input: data.tolist()}]\n instances = [json_format.ParseDict(s, Value()) for s in instances_list]\n\n response = clients[\"prediction\"].predict(\n endpoint=endpoint, instances=instances, parameters=parameters\n )\n print(\"response\")\n print(\" deployed_model_id:\", response.deployed_model_id)\n predictions = response.predictions\n print(\"predictions\")\n for prediction in predictions:\n print(\" prediction:\", prediction)\n\n\npredict_data(test_item, endpoint_id, None)", "_____no_output_____" ] ], [ [ "## Undeploy the `Model` resource\n\nNow undeploy your `Model` resource from the serving `Endpoint` resoure. Use this helper function `undeploy_model`, which takes the following parameters:\n\n- `deployed_model_id`: The model deployment identifier returned by the endpoint service when the `Model` resource was deployed to.\n- `endpoint`: The Vertex fully qualified identifier for the `Endpoint` resource where the `Model` is deployed to.\n\nThis function calls the endpoint client service's method `undeploy_model`, with the following parameters:\n\n- `deployed_model_id`: The model deployment identifier returned by the endpoint service when the `Model` resource was deployed.\n- `endpoint`: The Vertex fully qualified identifier for the `Endpoint` resource where the `Model` resource is deployed.\n- `traffic_split`: How to split traffic among the remaining deployed models on the `Endpoint` resource.\n\nSince this is the only deployed model on the `Endpoint` resource, you simply can leave `traffic_split` empty by setting it to {}.", "_____no_output_____" ] ], [ [ "def undeploy_model(deployed_model_id, endpoint):\n response = clients[\"endpoint\"].undeploy_model(\n endpoint=endpoint, deployed_model_id=deployed_model_id, traffic_split={}\n )\n print(response)\n\n\nundeploy_model(deployed_model_id, endpoint_id)", "_____no_output_____" ] ], [ [ "# Cleaning up\n\nTo clean up all GCP resources used in this project, you can [delete the GCP\nproject](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n\nOtherwise, you can delete the individual resources you created in this tutorial:\n\n- Dataset\n- Pipeline\n- Model\n- Endpoint\n- Batch Job\n- Custom Job\n- Hyperparameter Tuning Job\n- Cloud Storage Bucket", "_____no_output_____" ] ], [ [ "delete_dataset = True\ndelete_pipeline = True\ndelete_model = True\ndelete_endpoint = True\ndelete_batchjob = True\ndelete_customjob = True\ndelete_hptjob = True\ndelete_bucket = True\n\n# Delete the dataset using the Vertex fully qualified identifier for the dataset\ntry:\n if delete_dataset and \"dataset_id\" in globals():\n clients[\"dataset\"].delete_dataset(name=dataset_id)\nexcept Exception as e:\n print(e)\n\n# Delete the training pipeline using the Vertex fully qualified identifier for the pipeline\ntry:\n if delete_pipeline and \"pipeline_id\" in globals():\n clients[\"pipeline\"].delete_training_pipeline(name=pipeline_id)\nexcept Exception as e:\n print(e)\n\n# Delete the model using the Vertex fully qualified identifier for the model\ntry:\n if delete_model and \"model_to_deploy_id\" in globals():\n clients[\"model\"].delete_model(name=model_to_deploy_id)\nexcept Exception as e:\n print(e)\n\n# Delete the endpoint using the Vertex fully qualified identifier for the endpoint\ntry:\n if delete_endpoint and \"endpoint_id\" in globals():\n clients[\"endpoint\"].delete_endpoint(name=endpoint_id)\nexcept Exception as e:\n print(e)\n\n# Delete the batch job using the Vertex fully qualified identifier for the batch job\ntry:\n if delete_batchjob and \"batch_job_id\" in globals():\n clients[\"job\"].delete_batch_prediction_job(name=batch_job_id)\nexcept Exception as e:\n print(e)\n\n# Delete the custom job using the Vertex fully qualified identifier for the custom job\ntry:\n if delete_customjob and \"job_id\" in globals():\n clients[\"job\"].delete_custom_job(name=job_id)\nexcept Exception as e:\n print(e)\n\n# Delete the hyperparameter tuning job using the Vertex fully qualified identifier for the hyperparameter tuning job\ntry:\n if delete_hptjob and \"hpt_job_id\" in globals():\n clients[\"job\"].delete_hyperparameter_tuning_job(name=hpt_job_id)\nexcept Exception as e:\n print(e)\n\nif delete_bucket and \"BUCKET_NAME\" in globals():\n ! gsutil rm -r $BUCKET_NAME", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb269303e3a29f7319dd5df21afab3857ec0d979
213,649
ipynb
Jupyter Notebook
notebooks/Parser.ipynb
hjyuan/fuzzingbook
4cf3433ec2883e452f58c992704cfb464c93152e
[ "MIT" ]
null
null
null
notebooks/Parser.ipynb
hjyuan/fuzzingbook
4cf3433ec2883e452f58c992704cfb464c93152e
[ "MIT" ]
null
null
null
notebooks/Parser.ipynb
hjyuan/fuzzingbook
4cf3433ec2883e452f58c992704cfb464c93152e
[ "MIT" ]
null
null
null
29.163118
1,043
0.545806
[ [ [ "# Parsing Inputs\n\nIn the chapter on [Grammars](Grammars.ipynb), we discussed how grammars can be\nused to represent various languages. We also saw how grammars can be used to\ngenerate strings of the corresponding language. Grammars can also perform the\nreverse. That is, given a string, one can decompose the string into its\nconstituent parts that correspond to the parts of grammar used to generate it\n– the _derivation tree_ of that string. These parts (and parts from other similar\nstrings) can later be recombined using the same grammar to produce new strings.\n\nIn this chapter, we use grammars to parse and decompose a given set of valid seed inputs into their corresponding derivation trees. This structural representation allows us to mutate, crossover, and recombine their parts in order to generate new valid, slightly changed inputs (i.e., fuzz)", "_____no_output_____" ] ], [ [ "from bookutils import YouTubeVideo\nYouTubeVideo('k39i9de0L54')", "_____no_output_____" ] ], [ [ "**Prerequisites**\n\n* You should have read the [chapter on grammars](Grammars.ipynb).\n* An understanding of derivation trees from the [chapter on grammar fuzzer](GrammarFuzzer.ipynb)\n is also required.", "_____no_output_____" ], [ "## Synopsis\n<!-- Automatically generated. Do not edit. -->\n\nTo [use the code provided in this chapter](Importing.ipynb), write\n\n```python\n>>> from fuzzingbook.Parser import <identifier>\n```\n\nand then make use of the following features.\n\n\nThis chapter introduces `Parser` classes, parsing a string into a _derivation tree_ as introduced in the [chapter on efficient grammar fuzzing](GrammarFuzzer.ipynb). Two important parser classes are provided:\n\n* [Parsing Expression Grammar parsers](#Parsing-Expression-Grammars) (`PEGParser`). These are very efficient, but limited to specific grammar structure. Notably, the alternatives represent *ordered choice*. That is, rather than choosing all rules that can potentially match, we stop at the first match that succeed.\n* [Earley parsers](#Parsing-Context-Free-Grammars) (`EarleyParser`). These accept any kind of context-free grammars, and explore all parsing alternatives (if any).\n\nUsing any of these is fairly easy, though. First, instantiate them with a grammar:\n\n```python\n>>> from Grammars import US_PHONE_GRAMMAR\n>>> us_phone_parser = EarleyParser(US_PHONE_GRAMMAR)\n```\nThen, use the `parse()` method to retrieve a list of possible derivation trees:\n\n```python\n>>> trees = us_phone_parser.parse(\"(555)987-6543\")\n>>> tree = list(trees)[0]\n>>> display_tree(tree)\n```\nThese derivation trees can then be used for test generation, notably for mutating and recombining existing inputs.\n\n", "_____no_output_____" ] ], [ [ "import bookutils", "_____no_output_____" ], [ "from typing import Dict, List, Tuple, Collection, Set, Iterable, Generator, cast", "_____no_output_____" ], [ "from Fuzzer import Fuzzer # minor dependendcy", "_____no_output_____" ], [ "from Grammars import EXPR_GRAMMAR, START_SYMBOL, RE_NONTERMINAL\nfrom Grammars import is_valid_grammar, syntax_diagram, Grammar", "_____no_output_____" ], [ "from GrammarFuzzer import GrammarFuzzer, display_tree, tree_to_string, dot_escape\nfrom GrammarFuzzer import DerivationTree", "_____no_output_____" ], [ "from ExpectError import ExpectError", "_____no_output_____" ], [ "from IPython.display import display", "_____no_output_____" ], [ "from Timer import Timer", "_____no_output_____" ] ], [ [ "## Why Parsing for Fuzzing?", "_____no_output_____" ], [ "Why would one want to parse existing inputs in order to fuzz? Let us illustrate the problem with an example. Here is a simple program that accepts a CSV file of vehicle details and processes this information.", "_____no_output_____" ] ], [ [ "def process_inventory(inventory):\n res = []\n for vehicle in inventory.split('\\n'):\n ret = process_vehicle(vehicle)\n res.extend(ret)\n return '\\n'.join(res)", "_____no_output_____" ] ], [ [ "The CSV file contains details of one vehicle per line. Each row is processed in `process_vehicle()`.", "_____no_output_____" ] ], [ [ "def process_vehicle(vehicle):\n year, kind, company, model, *_ = vehicle.split(',')\n if kind == 'van':\n return process_van(year, company, model)\n\n elif kind == 'car':\n return process_car(year, company, model)\n\n else:\n raise Exception('Invalid entry')", "_____no_output_____" ] ], [ [ "Depending on the kind of vehicle, the processing changes.", "_____no_output_____" ] ], [ [ "def process_van(year, company, model):\n res = [\"We have a %s %s van from %s vintage.\" % (company, model, year)]\n iyear = int(year)\n if iyear > 2010:\n res.append(\"It is a recent model!\")\n else:\n res.append(\"It is an old but reliable model!\")\n return res", "_____no_output_____" ], [ "def process_car(year, company, model):\n res = [\"We have a %s %s car from %s vintage.\" % (company, model, year)]\n iyear = int(year)\n if iyear > 2016:\n res.append(\"It is a recent model!\")\n else:\n res.append(\"It is an old but reliable model!\")\n return res", "_____no_output_____" ] ], [ [ "Here is a sample of inputs that the `process_inventory()` accepts.", "_____no_output_____" ] ], [ [ "mystring = \"\"\"\\\n1997,van,Ford,E350\n2000,car,Mercury,Cougar\\\n\"\"\"\nprint(process_inventory(mystring))", "_____no_output_____" ] ], [ [ "Let us try to fuzz this program. Given that the `process_inventory()` takes a CSV file, we can write a simple grammar for generating comma separated values, and generate the required CSV rows. For convenience, we fuzz `process_vehicle()` directly.", "_____no_output_____" ] ], [ [ "import string", "_____no_output_____" ], [ "CSV_GRAMMAR: Grammar = {\n '<start>': ['<csvline>'],\n '<csvline>': ['<items>'],\n '<items>': ['<item>,<items>', '<item>'],\n '<item>': ['<letters>'],\n '<letters>': ['<letter><letters>', '<letter>'],\n '<letter>': list(string.ascii_letters + string.digits + string.punctuation + ' \\t\\n')\n}", "_____no_output_____" ] ], [ [ " We need some infrastructure first for viewing the grammar.", "_____no_output_____" ] ], [ [ "syntax_diagram(CSV_GRAMMAR)", "_____no_output_____" ] ], [ [ "We generate `1000` values, and evaluate the `process_vehicle()` with each.", "_____no_output_____" ] ], [ [ "gf = GrammarFuzzer(CSV_GRAMMAR, min_nonterminals=4)\ntrials = 1000\nvalid: List[str] = []\ntime = 0\nfor i in range(trials):\n with Timer() as t:\n vehicle_info = gf.fuzz()\n try:\n process_vehicle(vehicle_info)\n valid.append(vehicle_info)\n except:\n pass\n time += t.elapsed_time()\nprint(\"%d valid strings, that is GrammarFuzzer generated %f%% valid entries from %d inputs\" %\n (len(valid), len(valid) * 100.0 / trials, trials))\nprint(\"Total time of %f seconds\" % time)", "_____no_output_____" ] ], [ [ "This is obviously not working. But why?", "_____no_output_____" ] ], [ [ "gf = GrammarFuzzer(CSV_GRAMMAR, min_nonterminals=4)\ntrials = 10\ntime = 0\nfor i in range(trials):\n vehicle_info = gf.fuzz()\n try:\n print(repr(vehicle_info), end=\"\")\n process_vehicle(vehicle_info)\n except Exception as e:\n print(\"\\t\", e)\n else:\n print()", "_____no_output_____" ] ], [ [ "None of the entries will get through unless the fuzzer can produce either `van` or `car`.\nIndeed, the reason is that the grammar itself does not capture the complete information about the format. So here is another idea. We modify the `GrammarFuzzer` to know a bit about our format.", "_____no_output_____" ] ], [ [ "import copy", "_____no_output_____" ], [ "import random", "_____no_output_____" ], [ "class PooledGrammarFuzzer(GrammarFuzzer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._node_cache = {}\n\n def update_cache(self, key, values):\n self._node_cache[key] = values\n\n def expand_node_randomly(self, node):\n (symbol, children) = node\n assert children is None\n if symbol in self._node_cache:\n if random.randint(0, 1) == 1:\n return super().expand_node_randomly(node)\n return copy.deepcopy(random.choice(self._node_cache[symbol]))\n return super().expand_node_randomly(node)", "_____no_output_____" ] ], [ [ "Let us try again!", "_____no_output_____" ] ], [ [ "gf = PooledGrammarFuzzer(CSV_GRAMMAR, min_nonterminals=4)\ngf.update_cache('<item>', [\n ('<item>', [('car', [])]),\n ('<item>', [('van', [])]),\n])\ntrials = 10\ntime = 0\nfor i in range(trials):\n vehicle_info = gf.fuzz()\n try:\n print(repr(vehicle_info), end=\"\")\n process_vehicle(vehicle_info)\n except Exception as e:\n print(\"\\t\", e)\n else:\n print()", "_____no_output_____" ] ], [ [ "At least we are getting somewhere! It would be really nice if _we could incorporate what we know about the sample data in our fuzzer._ In fact, it would be nice if we could _extract_ the template and valid values from samples, and use them in our fuzzing. How do we do that? The quick answer to this question is: Use a *parser*. ", "_____no_output_____" ], [ "## Using a Parser\n\nGenerally speaking, a _parser_ is the part of a a program that processes (structured) input. The parsers we discuss in this chapter transform an input string into a _derivation tree_ (discussed in the [chapter on efficient grammar fuzzing](GrammarFuzzer.ipynb)). From a user's perspective, all it takes to parse an input is two steps: \n\n1. Initialize the parser with a grammar, as in\n```\nparser = Parser(grammar)\n```\n\n2. Using the parser to retrieve a list of derivation trees:\n\n```python\ntrees = parser.parse(input)\n```\n\nOnce we have parsed a tree, we can use it just as the derivation trees produced from grammar fuzzing.\n\nWe discuss a number of such parsers, in particular\n* [parsing expression grammar parsers](#Parsing-Expression-Grammars) (`PEGParser`), which are very efficient, but limited to specific grammar structure; and\n* [Earley parsers](#Parsing-Context-Free-Grammars) (`EarleyParser`), which accept any kind of context-free grammars.\n\nIf you just want to _use_ parsers (say, because your main focus is testing), you can just stop here and move on [to the next chapter](LangFuzzer.ipynb), where we learn how to make use of parsed inputs to mutate and recombine them. If you want to _understand_ how parsers work, though, this chapter is right for you.", "_____no_output_____" ], [ "## An Ad Hoc Parser\n\nAs we saw in the previous section, programmers often have to extract parts of data that obey certain rules. For example, for *CSV* files, each element in a row is separated by *commas*, and multiple raws are used to store the data.", "_____no_output_____" ], [ "To extract the information, we write an ad hoc parser `simple_parse_csv()`.", "_____no_output_____" ] ], [ [ "def simple_parse_csv(mystring: str) -> DerivationTree:\n children: List[DerivationTree] = []\n tree = (START_SYMBOL, children)\n for i, line in enumerate(mystring.split('\\n')):\n children.append((\"record %d\" % i, [(cell, [])\n for cell in line.split(',')]))\n return tree", "_____no_output_____" ] ], [ [ "We also change the default orientation of the graph to *left to right* rather than *top to bottom* for easier viewing using `lr_graph()`.", "_____no_output_____" ] ], [ [ "def lr_graph(dot):\n dot.attr('node', shape='plain')\n dot.graph_attr['rankdir'] = 'LR'", "_____no_output_____" ] ], [ [ "The `display_tree()` shows the structure of our CSV file after parsing.", "_____no_output_____" ] ], [ [ "tree = simple_parse_csv(mystring)\ndisplay_tree(tree, graph_attr=lr_graph)", "_____no_output_____" ] ], [ [ "This is of course simple. What if we encounter slightly more complexity? Again, another example from the Wikipedia.", "_____no_output_____" ] ], [ [ "mystring = '''\\\n1997,Ford,E350,\"ac, abs, moon\",3000.00\\\n'''\nprint(mystring)", "_____no_output_____" ] ], [ [ "We define a new annotation method `highlight_node()` to mark the nodes that are interesting.", "_____no_output_____" ] ], [ [ "def highlight_node(predicate):\n def hl_node(dot, nid, symbol, ann):\n if predicate(dot, nid, symbol, ann):\n dot.node(repr(nid), dot_escape(symbol), fontcolor='red')\n else:\n dot.node(repr(nid), dot_escape(symbol))\n return hl_node", "_____no_output_____" ] ], [ [ "Using `highlight_node()` we can highlight particular nodes that we were wrongly parsed.", "_____no_output_____" ] ], [ [ "tree = simple_parse_csv(mystring)\nbad_nodes = {5, 6, 7, 12, 13, 20, 22, 23, 24, 25}", "_____no_output_____" ], [ "def hl_predicate(_d, nid, _s, _a): return nid in bad_nodes", "_____no_output_____" ], [ "highlight_err_node = highlight_node(hl_predicate)\ndisplay_tree(tree, log=False, node_attr=highlight_err_node,\n graph_attr=lr_graph)", "_____no_output_____" ] ], [ [ "The marked nodes indicate where our parsing went wrong. We can of course extend our parser to understand quotes. First we define some of the helper functions `parse_quote()`, `find_comma()` and `comma_split()`", "_____no_output_____" ] ], [ [ "def parse_quote(string, i):\n v = string[i + 1:].find('\"')\n return v + i + 1 if v >= 0 else -1", "_____no_output_____" ], [ "def find_comma(string, i):\n slen = len(string)\n while i < slen:\n if string[i] == '\"':\n i = parse_quote(string, i)\n if i == -1:\n return -1\n if string[i] == ',':\n return i\n i += 1\n return -1", "_____no_output_____" ], [ "def comma_split(string):\n slen = len(string)\n i = 0\n while i < slen:\n c = find_comma(string, i)\n if c == -1:\n yield string[i:]\n return\n else:\n yield string[i:c]\n i = c + 1", "_____no_output_____" ] ], [ [ "We can update our `parse_csv()` procedure to use our advanced quote parser.", "_____no_output_____" ] ], [ [ "def parse_csv(mystring):\n children = []\n tree = (START_SYMBOL, children)\n for i, line in enumerate(mystring.split('\\n')):\n children.append((\"record %d\" % i, [(cell, [])\n for cell in comma_split(line)]))\n return tree", "_____no_output_____" ] ], [ [ "Our new `parse_csv()` can now handle quotes correctly.", "_____no_output_____" ] ], [ [ "tree = parse_csv(mystring)\ndisplay_tree(tree, graph_attr=lr_graph)", "_____no_output_____" ] ], [ [ "That of course does not survive long:", "_____no_output_____" ] ], [ [ "mystring = '''\\\n1999,Chevy,\"Venture \\\\\"Extended Edition, Very Large\\\\\"\",,5000.00\\\n'''\nprint(mystring)", "_____no_output_____" ] ], [ [ "A few embedded quotes are sufficient to confuse our parser again.", "_____no_output_____" ] ], [ [ "tree = parse_csv(mystring)\nbad_nodes = {4, 5}\ndisplay_tree(tree, node_attr=highlight_err_node, graph_attr=lr_graph)", "_____no_output_____" ] ], [ [ "Here is another record from that CSV file:", "_____no_output_____" ] ], [ [ "mystring = '''\\\n1996,Jeep,Grand Cherokee,\"MUST SELL!\nair, moon roof, loaded\",4799.00\n'''\nprint(mystring)", "_____no_output_____" ], [ "tree = parse_csv(mystring)\nbad_nodes = {5, 6, 7, 8, 9, 10}\ndisplay_tree(tree, node_attr=highlight_err_node, graph_attr=lr_graph)", "_____no_output_____" ] ], [ [ "Fixing this would require modifying both inner `parse_quote()` and the outer `parse_csv()` procedures. We note that each of these features actually documented in the CSV [RFC 4180](https://tools.ietf.org/html/rfc4180)", "_____no_output_____" ], [ "Indeed, each additional improvement falls apart even with a little extra complexity. The problem becomes severe when one encounters recursive expressions. For example, JSON is a common alternative to CSV files for saving data. Similarly, one may have to parse data from an HTML table instead of a CSV file if one is getting the data from the web.\n\nOne might be tempted to fix it with a little more ad hoc parsing, with a bit of *regular expressions* thrown in. However, that is the [path to insanity](https://stackoverflow.com/a/1732454).", "_____no_output_____" ], [ "It is here that _formal parsers_ shine. The main idea is that, any given set of strings belong to a language, and these languages can be specified by their grammars (as we saw in the [chapter on grammars](Grammars.ipynb)). The great thing about grammars is that they can be _composed_. That is, one can introduce finer and finer details into an internal structure without affecting the external structure, and similarly, one can change the external structure without much impact on the internal structure.", "_____no_output_____" ], [ "## Grammars in Parsing\n\nWe briefly describe grammars in the context of parsing.", "_____no_output_____" ], [ "### Excursion: Grammars and Derivation Trees", "_____no_output_____" ], [ "A grammar, as you have read from the [chapter on grammars](Grammars.ipynb) is a set of _rules_ that explain how the start symbol can be expanded. Each rule has a name, also called a _nonterminal_, and a set of _alternative choices_ in how the nonterminal can be expanded.", "_____no_output_____" ] ], [ [ "A1_GRAMMAR: Grammar = {\n \"<start>\": [\"<expr>\"],\n \"<expr>\": [\"<expr>+<expr>\", \"<expr>-<expr>\", \"<integer>\"],\n \"<integer>\": [\"<digit><integer>\", \"<digit>\"],\n \"<digit>\": [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n}", "_____no_output_____" ], [ "syntax_diagram(A1_GRAMMAR)", "_____no_output_____" ] ], [ [ "In the above expression, the rule `<expr> : [<expr>+<expr>,<expr>-<expr>,<integer>]` corresponds to how the nonterminal `<expr>` might be expanded. The expression `<expr>+<expr>` corresponds to one of the alternative choices. We call this an _alternative_ expansion for the nonterminal `<expr>`. Finally, in an expression `<expr>+<expr>`, each of `<expr>`, `+`, and `<expr>` are _symbols_ in that expansion. A symbol could be either a nonterminal or a terminal symbol based on whether its expansion is available in the grammar.", "_____no_output_____" ], [ "Here is a string that represents an arithmetic expression that we would like to parse, which is specified by the grammar above:", "_____no_output_____" ] ], [ [ "mystring = '1+2'", "_____no_output_____" ] ], [ [ "The _derivation tree_ for our expression from this grammar is given by:", "_____no_output_____" ] ], [ [ "tree = ('<start>', [('<expr>',\n [('<expr>', [('<integer>', [('<digit>', [('1', [])])])]),\n ('+', []),\n ('<expr>', [('<integer>', [('<digit>', [('2',\n [])])])])])])\nassert mystring == tree_to_string(tree)\ndisplay_tree(tree)", "_____no_output_____" ] ], [ [ "While a grammar can be used to specify a given language, there could be multiple\ngrammars that correspond to the same language. For example, here is another \ngrammar to describe the same addition expression.", "_____no_output_____" ] ], [ [ "A2_GRAMMAR: Grammar = {\n \"<start>\": [\"<expr>\"],\n \"<expr>\": [\"<integer><expr_>\"],\n \"<expr_>\": [\"+<expr>\", \"-<expr>\", \"\"],\n \"<integer>\": [\"<digit><integer_>\"],\n \"<integer_>\": [\"<integer>\", \"\"],\n \"<digit>\": [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n}", "_____no_output_____" ], [ "syntax_diagram(A2_GRAMMAR)", "_____no_output_____" ] ], [ [ "The corresponding derivation tree is given by:", "_____no_output_____" ] ], [ [ "tree = ('<start>', [('<expr>', [('<integer>', [('<digit>', [('1', [])]),\n ('<integer_>', [])]),\n ('<expr_>', [('+', []),\n ('<expr>',\n [('<integer>',\n [('<digit>', [('2', [])]),\n ('<integer_>', [])]),\n ('<expr_>', [])])])])])\nassert mystring == tree_to_string(tree)\ndisplay_tree(tree)", "_____no_output_____" ] ], [ [ "Indeed, there could be different classes of grammars that\ndescribe the same language. For example, the first grammar `A1_GRAMMAR`\nis a grammar that sports both _right_ and _left_ recursion, while the\nsecond grammar `A2_GRAMMAR` does not have left recursion in the\nnonterminals in any of its productions, but contains _epsilon_ productions.\n(An epsilon production is a production that has empty string in its right\nhand side.)", "_____no_output_____" ], [ "### End of Excursion", "_____no_output_____" ], [ "### Excursion: Recursion", "_____no_output_____" ], [ "You would have noticed that we reuse the term `<expr>` in its own definition. Using the same nonterminal in its own definition is called *recursion*. There are two specific kinds of recursion one should be aware of in parsing, as we see in the next section.", "_____no_output_____" ], [ "#### Recursion\n\nA grammar is _left recursive_ if any of its nonterminals are left recursive,\nand a nonterminal is directly left-recursive if the left-most symbol of\nany of its productions is itself.", "_____no_output_____" ] ], [ [ "LR_GRAMMAR: Grammar = {\n '<start>': ['<A>'],\n '<A>': ['<A>a', ''],\n}", "_____no_output_____" ], [ "syntax_diagram(LR_GRAMMAR)", "_____no_output_____" ], [ "mystring = 'aaaaaa'\ndisplay_tree(\n ('<start>', [('<A>', [('<A>', [('<A>', []), ('a', [])]), ('a', [])]),\n ('a', [])]))", "_____no_output_____" ] ], [ [ "A grammar is indirectly left-recursive if any\nof the left-most symbols can be expanded using their definitions to\nproduce the nonterminal as the left-most symbol of the expansion. The left\nrecursion is called a _hidden-left-recursion_ if during the series of\nexpansions of a nonterminal, one reaches a rule where the rule contains\nthe same nonterminal after a prefix of other symbols, and these symbols can\nderive the empty string. For example, in `A1_GRAMMAR`, `<integer>` will be\nconsidered hidden-left recursive if `<digit>` could derive an empty string.\n\nRight recursive grammars are defined similarly.\nBelow is the derivation tree for the right recursive grammar that represents the same\nlanguage as that of `LR_GRAMMAR`.", "_____no_output_____" ] ], [ [ "RR_GRAMMAR: Grammar = {\n '<start>': ['<A>'],\n '<A>': ['a<A>', ''],\n}", "_____no_output_____" ], [ "syntax_diagram(RR_GRAMMAR)", "_____no_output_____" ], [ "display_tree(('<start>', [('<A>', [\n ('a', []), ('<A>', [('a', []), ('<A>', [('a', []), ('<A>', [])])])])]\n ))", "_____no_output_____" ] ], [ [ "#### Ambiguity\n\nTo complicate matters further, there could be\nmultiple derivation trees – also called _parses_ – corresponding to the\nsame string from the same grammar. For example, a string `1+2+3` can be parsed\nin two ways as we see below using the `A1_GRAMMAR`", "_____no_output_____" ] ], [ [ "mystring = '1+2+3'\ntree = ('<start>',\n [('<expr>',\n [('<expr>', [('<expr>', [('<integer>', [('<digit>', [('1', [])])])]),\n ('+', []),\n ('<expr>', [('<integer>',\n [('<digit>', [('2', [])])])])]), ('+', []),\n ('<expr>', [('<integer>', [('<digit>', [('3', [])])])])])])\nassert mystring == tree_to_string(tree)\ndisplay_tree(tree)", "_____no_output_____" ], [ "tree = ('<start>',\n [('<expr>', [('<expr>', [('<integer>', [('<digit>', [('1', [])])])]),\n ('+', []),\n ('<expr>',\n [('<expr>', [('<integer>', [('<digit>', [('2', [])])])]),\n ('+', []),\n ('<expr>', [('<integer>', [('<digit>', [('3',\n [])])])])])])])\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ] ], [ [ "There are many ways to resolve ambiguities. One approach taken by *Parsing Expression Grammars* explained in the next section is to specify a particular order of resolution, and choose the first one. Another approach is to simply return all possible derivation trees, which is the approach taken by *Earley parser* we develop later.", "_____no_output_____" ], [ "### End of Excursion", "_____no_output_____" ], [ "## A Parser Class", "_____no_output_____" ], [ "Next, we develop different parsers. To do that, we define a minimal interface for parsing that is obeyed by all parsers. There are two approaches to parsing a string using a grammar.\n\n1. The traditional approach is to use a *lexer* (also called a *tokenizer* or a *scanner*) to first tokenize the incoming string, and feed the grammar one token at a time. The lexer is typically a smaller parser that accepts a *regular language*. The advantage of this approach is that the grammar used by the parser can eschew the details of tokenization. Further, one gets a shallow derivation tree at the end of the parsing which can be directly used for generating the *Abstract Syntax Tree*.\n2. The second approach is to use a tree pruner after the complete parse. With this approach, one uses a grammar that incorporates complete details of the syntax. Next, the nodes corresponding to tokens are pruned and replaced with their corresponding strings as leaf nodes. The utility of this approach is that the parser is more powerful, and further there is no artificial distinction between *lexing* and *parsing*.\n\nIn this chapter, we use the second approach. This approach is implemented in the `prune_tree` method.", "_____no_output_____" ], [ "The *Parser* class we define below provides the minimal interface. The main methods that need to be implemented by the classes implementing this interface are `parse_prefix` and `parse`. The `parse_prefix` returns a tuple, which contains the index until which parsing was completed successfully, and the parse forest until that index. The method `parse` returns a list of derivation trees if the parse was successful.", "_____no_output_____" ] ], [ [ "class Parser:\n \"\"\"Base class for parsing.\"\"\"\n\n def __init__(self, grammar: Grammar, *,\n start_symbol: str = START_SYMBOL,\n log: bool = False,\n coalesce: bool = True,\n tokens: Set[str] = set()) -> None:\n \"\"\"Constructor.\n `grammar` is the grammar to be used for parsing.\n Keyword arguments:\n `start_symbol` is the start symbol (default: '<start>').\n `log` enables logging (default: False).\n `coalesce` defines if tokens should be coalesced (default: True).\n `tokens`, if set, is a set of tokens to be used.\"\"\"\n self._grammar = grammar\n self._start_symbol = start_symbol\n self.log = log\n self.coalesce_tokens = coalesce\n self.tokens = tokens\n\n def grammar(self) -> Grammar:\n \"\"\"Return the grammar of this parser.\"\"\"\n return self._grammar\n\n def start_symbol(self) -> str:\n \"\"\"Return the start symbol of this parser.\"\"\"\n return self._start_symbol\n\n def parse_prefix(self, text: str) -> Tuple[int, Iterable[DerivationTree]]:\n \"\"\"Return pair (cursor, forest) for longest prefix of text. \n To be defined in subclasses.\"\"\"\n raise NotImplementedError\n\n def parse(self, text: str) -> Iterable[DerivationTree]:\n \"\"\"Parse `text` using the grammar. \n Return an iterable of parse trees.\"\"\"\n cursor, forest = self.parse_prefix(text)\n if cursor < len(text):\n raise SyntaxError(\"at \" + repr(text[cursor:]))\n return [self.prune_tree(tree) for tree in forest]\n\n def parse_on(self, text: str, start_symbol: str) -> Generator:\n old_start = self._start_symbol\n try:\n self._start_symbol = start_symbol\n yield from self.parse(text)\n finally:\n self._start_symbol = old_start\n\n def coalesce(self, children: List[DerivationTree]) -> List[DerivationTree]:\n last = ''\n new_lst: List[DerivationTree] = []\n for cn, cc in children:\n if cn not in self._grammar:\n last += cn\n else:\n if last:\n new_lst.append((last, []))\n last = ''\n new_lst.append((cn, cc))\n if last:\n new_lst.append((last, []))\n return new_lst\n\n def prune_tree(self, tree: DerivationTree) -> DerivationTree:\n name, children = tree\n assert isinstance(children, list)\n\n if self.coalesce_tokens:\n children = self.coalesce(cast(List[DerivationTree], children))\n if name in self.tokens:\n return (name, [(tree_to_string(tree), [])])\n else:\n return (name, [self.prune_tree(c) for c in children])", "_____no_output_____" ] ], [ [ "### Excursion: Canonical Grammars", "_____no_output_____" ], [ "The `EXPR_GRAMMAR` we import from the [chapter on grammars](Grammars.ipynb) is oriented towards generation. In particular, the production rules are stored as strings. We need to massage this representation a little to conform to a _canonical representation_ where each token in a rule is represented separately. The `canonical` format uses separate tokens to represent each symbol in an expansion.", "_____no_output_____" ] ], [ [ "CanonicalGrammar = Dict[str, List[List[str]]]", "_____no_output_____" ], [ "import re", "_____no_output_____" ], [ "def single_char_tokens(grammar: Grammar) -> Dict[str, List[List[Collection[str]]]]:\n g_ = {}\n for key in grammar:\n rules_ = []\n for rule in grammar[key]:\n rule_ = []\n for token in rule:\n if token in grammar:\n rule_.append(token)\n else:\n rule_.extend(token)\n rules_.append(rule_)\n g_[key] = rules_\n return g_", "_____no_output_____" ], [ "def canonical(grammar: Grammar) -> CanonicalGrammar:\n def split(expansion):\n if isinstance(expansion, tuple):\n expansion = expansion[0]\n\n return [token for token in re.split(\n RE_NONTERMINAL, expansion) if token]\n\n return {\n k: [split(expression) for expression in alternatives]\n for k, alternatives in grammar.items()\n }", "_____no_output_____" ], [ "CE_GRAMMAR: CanonicalGrammar = canonical(EXPR_GRAMMAR)\nCE_GRAMMAR", "_____no_output_____" ] ], [ [ "We also provide a convenience method for easier display of canonical grammars.", "_____no_output_____" ] ], [ [ "def recurse_grammar(grammar, key, order):\n rules = sorted(grammar[key])\n old_len = len(order)\n for rule in rules:\n for token in rule:\n if token not in grammar: continue\n if token not in order:\n order.append(token)\n new = order[old_len:]\n for ckey in new:\n recurse_grammar(grammar, ckey, order)", "_____no_output_____" ], [ "def show_grammar(grammar, start_symbol=START_SYMBOL):\n order = [start_symbol]\n recurse_grammar(grammar, start_symbol, order)\n return {k: sorted(grammar[k]) for k in order}", "_____no_output_____" ], [ "show_grammar(CE_GRAMMAR)", "_____no_output_____" ] ], [ [ "We provide a way to revert a canonical expression.", "_____no_output_____" ] ], [ [ "def non_canonical(grammar):\n new_grammar = {}\n for k in grammar:\n rules = grammar[k]\n new_rules = []\n for rule in rules:\n new_rules.append(''.join(rule))\n new_grammar[k] = new_rules\n return new_grammar", "_____no_output_____" ], [ "non_canonical(CE_GRAMMAR)", "_____no_output_____" ] ], [ [ "It is easier to work with the `canonical` representation during parsing. Hence, we update our parser class to store the `canonical` representation also.", "_____no_output_____" ] ], [ [ "class Parser(Parser):\n def __init__(self, grammar, **kwargs):\n self._start_symbol = kwargs.get('start_symbol', START_SYMBOL)\n self.log = kwargs.get('log', False)\n self.tokens = kwargs.get('tokens', set())\n self.coalesce_tokens = kwargs.get('coalesce', True)\n canonical_grammar = kwargs.get('canonical', False)\n if canonical_grammar:\n self.cgrammar = single_char_tokens(grammar)\n self._grammar = non_canonical(grammar)\n else:\n self._grammar = dict(grammar)\n self.cgrammar = single_char_tokens(canonical(grammar))\n # we do not require a single rule for the start symbol\n if len(grammar.get(self._start_symbol, [])) != 1:\n self.cgrammar['<>'] = [[self._start_symbol]]", "_____no_output_____" ] ], [ [ "We update the `prune_tree()` to account for the phony start symbol if it was insserted.", "_____no_output_____" ] ], [ [ "class Parser(Parser):\n def prune_tree(self, tree):\n name, children = tree\n if name == '<>':\n assert len(children) == 1\n return self.prune_tree(children[0])\n if self.coalesce_tokens:\n children = self.coalesce(children)\n if name in self.tokens:\n return (name, [(tree_to_string(tree), [])])\n else:\n return (name, [self.prune_tree(c) for c in children])", "_____no_output_____" ] ], [ [ "### End of Excursion", "_____no_output_____" ], [ "## Parsing Expression Grammars\n\nA _[Parsing Expression Grammar](http://bford.info/pub/lang/peg)_ (*PEG*) \\cite{Ford2004} is a type of _recognition based formal grammar_ that specifies the sequence of steps to take to parse a given string.\nA _parsing expression grammar_ is very similar to a _context-free grammar_ (*CFG*) such as the ones we saw in the [chapter on grammars](Grammars.ipynb). As in a CFG, a parsing expression grammar is represented by a set of nonterminals and corresponding alternatives representing how to match each. For example, here is a PEG that matches `a` or `b`.", "_____no_output_____" ] ], [ [ "PEG1 = {\n '<start>': ['a', 'b']\n}", "_____no_output_____" ] ], [ [ "However, unlike the _CFG_, the alternatives represent *ordered choice*. That is, rather than choosing all rules that can potentially match, we stop at the first match that succeed. For example, the below _PEG_ can match `ab` but not `abc` unlike a _CFG_ which will match both. (We call the sequence of ordered choice expressions *choice expressions* rather than alternatives to make the distinction from _CFG_ clear.)", "_____no_output_____" ] ], [ [ "PEG2 = {\n '<start>': ['ab', 'abc']\n}", "_____no_output_____" ] ], [ [ "Each choice in a _choice expression_ represents a rule on how to satisfy that particular choice. The choice is a sequence of symbols (terminals and nonterminals) that are matched against a given text as in a _CFG_.", "_____no_output_____" ], [ "Beyond the syntax of grammar definitions we have seen so far, a _PEG_ can also contain a few additional elements. See the exercises at the end of the chapter for additional information.\n\nThe PEGs model the typical practice in handwritten recursive descent parsers, and hence it may be considered more intuitive to understand.", "_____no_output_____" ], [ "### The Packrat Parser for Predicate Expression Grammars\n\nShort of hand rolling a parser, _Packrat_ parsing is one of the simplest parsing techniques, and is one of the techniques for parsing PEGs.\nThe _Packrat_ parser is so named because it tries to cache all results from simpler problems in the hope that these solutions can be used to avoid re-computation later. We develop a minimal _Packrat_ parser next.", "_____no_output_____" ], [ "We derive from the `Parser` base class first, and we accept the text to be parsed in the `parse()` method, which in turn calls `unify_key()` with the `start_symbol`.\n\n__Note.__ While our PEG parser can produce only a single unambiguous parse tree, other parsers can produce multiple parses for ambiguous grammars. Hence, we return a list of trees (in this case with a single element).", "_____no_output_____" ] ], [ [ "class PEGParser(Parser):\n def parse_prefix(self, text):\n cursor, tree = self.unify_key(self.start_symbol(), text, 0)\n return cursor, [tree]", "_____no_output_____" ] ], [ [ "### Excursion: Implementing `PEGParser`", "_____no_output_____" ], [ "#### Unify Key\nThe `unify_key()` algorithm is simple. If given a terminal symbol, it tries to match the symbol with the current position in the text. If the symbol and text match, it returns successfully with the new parse index `at`.\n\nIf on the other hand, it was given a nonterminal, it retrieves the choice expression corresponding to the key, and tries to match each choice *in order* using `unify_rule()`. If **any** of the rules succeed in being unified with the given text, the parse is considered a success, and we return with the new parse index returned by `unify_rule()`.", "_____no_output_____" ] ], [ [ "class PEGParser(PEGParser):\n \"\"\"Packrat parser for Parsing Expression Grammars (PEGs).\"\"\"\n\n def unify_key(self, key, text, at=0):\n if self.log:\n print(\"unify_key: %s with %s\" % (repr(key), repr(text[at:])))\n if key not in self.cgrammar:\n if text[at:].startswith(key):\n return at + len(key), (key, [])\n else:\n return at, None\n for rule in self.cgrammar[key]:\n to, res = self.unify_rule(rule, text, at)\n if res is not None:\n return (to, (key, res))\n return 0, None", "_____no_output_____" ], [ "mystring = \"1\"\npeg = PEGParser(EXPR_GRAMMAR, log=True)\npeg.unify_key('1', mystring)", "_____no_output_____" ], [ "mystring = \"2\"\npeg.unify_key('1', mystring)", "_____no_output_____" ] ], [ [ "#### Unify Rule\n\nThe `unify_rule()` method is similar. It retrieves the tokens corresponding to the rule that it needs to unify with the text, and calls `unify_key()` on them in sequence. If **all** tokens are successfully unified with the text, the parse is a success.", "_____no_output_____" ] ], [ [ "class PEGParser(PEGParser):\n def unify_rule(self, rule, text, at):\n if self.log:\n print('unify_rule: %s with %s' % (repr(rule), repr(text[at:])))\n results = []\n for token in rule:\n at, res = self.unify_key(token, text, at)\n if res is None:\n return at, None\n results.append(res)\n return at, results", "_____no_output_____" ], [ "mystring = \"0\"\npeg = PEGParser(EXPR_GRAMMAR, log=True)\npeg.unify_rule(peg.cgrammar['<digit>'][0], mystring, 0)", "_____no_output_____" ], [ "mystring = \"12\"\npeg.unify_rule(peg.cgrammar['<integer>'][0], mystring, 0)", "_____no_output_____" ], [ "mystring = \"1 + 2\"\npeg = PEGParser(EXPR_GRAMMAR, log=False)\npeg.parse(mystring)", "_____no_output_____" ] ], [ [ "The two methods are mutually recursive, and given that `unify_key()` tries each alternative until it succeeds, `unify_key` can be called multiple times with the same arguments. Hence, it is important to memoize the results of `unify_key`. Python provides a simple decorator `lru_cache` for memoizing any function call that has hashable arguments. We add that to our implementation so that repeated calls to `unify_key()` with the same argument get cached results.\n\nThis memoization gives the algorithm its name – _Packrat_.", "_____no_output_____" ] ], [ [ "from functools import lru_cache", "_____no_output_____" ], [ "class PEGParser(PEGParser):\n @lru_cache(maxsize=None)\n def unify_key(self, key, text, at=0):\n if key not in self.cgrammar:\n if text[at:].startswith(key):\n return at + len(key), (key, [])\n else:\n return at, None\n for rule in self.cgrammar[key]:\n to, res = self.unify_rule(rule, text, at)\n if res is not None:\n return (to, (key, res))\n return 0, None", "_____no_output_____" ] ], [ [ "We wrap initialization and calling of `PEGParser` in a method `parse()` already implemented in the `Parser` base class that accepts the text to be parsed along with the grammar.", "_____no_output_____" ], [ "### End of Excursion", "_____no_output_____" ], [ "Here are a few examples of our parser in action.", "_____no_output_____" ] ], [ [ "mystring = \"1 + (2 * 3)\"\npeg = PEGParser(EXPR_GRAMMAR)\nfor tree in peg.parse(mystring):\n assert tree_to_string(tree) == mystring\n display(display_tree(tree))", "_____no_output_____" ], [ "mystring = \"1 * (2 + 3.35)\"\nfor tree in peg.parse(mystring):\n assert tree_to_string(tree) == mystring\n display(display_tree(tree))", "_____no_output_____" ] ], [ [ "One should be aware that while the grammar looks like a *CFG*, the language described by a *PEG* may be different. Indeed, only *LL(1)* grammars are guaranteed to represent the same language for both PEGs and other parsers. Behavior of PEGs for other classes of grammars could be surprising \\cite{redziejowski2008}. ", "_____no_output_____" ], [ "## Parsing Context-Free Grammars", "_____no_output_____" ], [ "### Problems with PEG\nWhile _PEGs_ are simple at first sight, their behavior in some cases might be a bit unintuitive. For example, here is an example \\cite{redziejowski2008}:", "_____no_output_____" ] ], [ [ "PEG_SURPRISE: Grammar = {\n \"<A>\": [\"a<A>a\", \"aa\"]\n}", "_____no_output_____" ] ], [ [ "When interpreted as a *CFG* and used as a string generator, it will produce strings of the form `aa, aaaa, aaaaaa` that is, it produces strings where the number of `a` is $ 2*n $ where $ n > 0 $.", "_____no_output_____" ] ], [ [ "strings = []\nfor nn in range(4):\n f = GrammarFuzzer(PEG_SURPRISE, start_symbol='<A>')\n tree = ('<A>', None)\n for _ in range(nn):\n tree = f.expand_tree_once(tree)\n tree = f.expand_tree_with_strategy(tree, f.expand_node_min_cost)\n strings.append(tree_to_string(tree))\n display_tree(tree)\nstrings", "_____no_output_____" ] ], [ [ "However, the _PEG_ parser can only recognize strings of the form $2^n$", "_____no_output_____" ] ], [ [ "peg = PEGParser(PEG_SURPRISE, start_symbol='<A>')\nfor s in strings:\n with ExpectError():\n for tree in peg.parse(s):\n display_tree(tree)\n print(s)", "_____no_output_____" ] ], [ [ "This is not the only problem with _Parsing Expression Grammars_. While *PEGs* are expressive and the *packrat* parser for parsing them is simple and intuitive, *PEGs* suffer from a major deficiency for our purposes. *PEGs* are oriented towards language recognition, and it is not clear how to translate an arbitrary *PEG* to a *CFG*. As we mentioned earlier, a naive re-interpretation of a *PEG* as a *CFG* does not work very well. Further, it is not clear what is the exact relation between the class of languages represented by *PEG* and the class of languages represented by *CFG*. Since our primary focus is *fuzzing* – that is _generation_ of strings – , we next look at _parsers that can accept context-free grammars_.", "_____no_output_____" ], [ "The general idea of *CFG* parser is the following: Peek at the input text for the allowed number of characters, and use these, and our parser state to determine which rules can be applied to complete parsing. We next look at a typical *CFG* parsing algorithm, the Earley Parser.", "_____no_output_____" ], [ "### The Earley Parser", "_____no_output_____" ], [ "The Earley parser is a general parser that is able to parse any arbitrary *CFG*. It was invented by Jay Earley \\cite{Earley1970} for use in computational linguistics. While its computational complexity is $O(n^3)$ for parsing strings with arbitrary grammars, it can parse strings with unambiguous grammars in $O(n^2)$ time, and all *[LR(k)](https://en.wikipedia.org/wiki/LR_parser)* grammars in linear time ($O(n)$ \\cite{Leo1991}). Further improvements – notably handling epsilon rules – were invented by Aycock et al. \\cite{Aycock2002}.", "_____no_output_____" ], [ "Note that one restriction of our implementation is that the start symbol can have only one alternative in its alternative expressions. This is not a restriction in practice because any grammar with multiple alternatives for its start symbol can be extended with a new start symbol that has the original start symbol as its only choice. That is, given a grammar as below,\n\n```\ngrammar = {\n '<start>': ['<A>', '<B>'],\n ...\n}\n```\none may rewrite it as below to conform to the *single-alternative* rule.\n```\ngrammar = {\n '<start>': ['<start_>'],\n '<start_>': ['<A>', '<B>'],\n ...\n}\n```", "_____no_output_____" ], [ "Let us implement a class `EarleyParser`, again derived from `Parser` which implements an Earley parser.", "_____no_output_____" ], [ "### Excursion: Implementing `EarleyParser`", "_____no_output_____" ], [ "We first implement a simpler parser that is a parser for nearly all *CFGs*, but not quite. In particular, our parser does not understand _epsilon rules_ – rules that derive empty string. We show later how the parser can be extended to handle these.", "_____no_output_____" ], [ "We use the following grammar in our examples below.", "_____no_output_____" ] ], [ [ "SAMPLE_GRAMMAR: Grammar = {\n '<start>': ['<A><B>'],\n '<A>': ['a<B>c', 'a<A>'],\n '<B>': ['b<C>', '<D>'],\n '<C>': ['c'],\n '<D>': ['d']\n}\nC_SAMPLE_GRAMMAR = canonical(SAMPLE_GRAMMAR)", "_____no_output_____" ], [ "syntax_diagram(SAMPLE_GRAMMAR)", "_____no_output_____" ] ], [ [ "The basic idea of Earley parsing is the following:\n\n* Start with the alternative expressions corresponding to the START_SYMBOL. These represent the possible ways to parse the string from a high level. Essentially each expression represents a parsing path. Queue each expression in our set of possible parses of the string. The parsed index of an expression is the part of expression that has already been recognized. In the beginning of parse, the parsed index of all expressions is at the beginning. Further, each letter gets a queue of expressions that recognizes that letter at that point in our parse.\n* Examine our queue of possible parses and check if any of them start with a nonterminal. If it does, then that nonterminal needs to be recognized from the input before the given rule can be parsed. Hence, add the alternative expressions corresponding to the nonterminal to the queue. Do this recursively.\n* At this point, we are ready to advance. Examine the current letter in the input, and select all expressions that have that particular letter at the parsed index. These expressions can now advance one step. Advance these selected expressions by incrementing their parsed index and add them to the queue of expressions in line for recognizing the next input letter.\n* If while doing these things, we find that any of the expressions have finished parsing, we fetch its corresponding nonterminal, and advance all expressions that have that nonterminal at their parsed index.\n* Continue this procedure recursively until all expressions that we have queued for the current letter have been processed. Then start processing the queue for the next letter.\n\nWe explain each step in detail with examples in the coming sections.", "_____no_output_____" ], [ "The parser uses dynamic programming to generate a table containing a _forest of possible parses_ at each letter index – the table contains as many columns as there are letters in the input, and each column contains different parsing rules at various stages of the parse.\n\nFor example, given an input `adcd`, the Column 0 would contain the following:\n```\n<start> : ● <A> <B>\n```\nwhich is the starting rule that indicates that we are currently parsing the rule `<start>`, and the parsing state is just before identifying the symbol `<A>`. It would also contain the following which are two alternative paths it could take to complete the parsing.\n\n```\n<A> : ● a <B> c\n<A> : ● a <A>\n```", "_____no_output_____" ], [ "Column 1 would contain the following, which represents the possible completion after reading `a`.\n```\n<A> : a ● <B> c\n<A> : a ● <A>\n<B> : ● b <C>\n<B> : ● <D>\n<A> : ● a <B> c\n<A> : ● a <A>\n<D> : ● d\n```", "_____no_output_____" ], [ "Column 2 would contain the following after reading `d`\n```\n<D> : d ●\n<B> : <D> ●\n<A> : a <B> ● c\n```", "_____no_output_____" ], [ "Similarly, Column 3 would contain the following after reading `c`\n```\n<A> : a <B> c ●\n<start> : <A> ● <B>\n<B> : ● b <C>\n<B> : ● <D>\n<D> : ● d\n```", "_____no_output_____" ], [ "Finally, Column 4 would contain the following after reading `d`, with the `●` at the end of the `<start>` rule indicating that the parse was successful.\n```\n<D> : d ●\n<B> : <D> ●\n<start> : <A> <B> ●\n```", "_____no_output_____" ], [ "As you can see from above, we are essentially filling a table (a table is also called a **chart**) of entries based on each letter we read, and the grammar rules that can be applied. This chart gives the parser its other name -- Chart parsing.", "_____no_output_____" ], [ "#### Columns\n\nWe define the `Column` first. The `Column` is initialized by its own `index` in the input string, and the `letter` at that index. Internally, we also keep track of the states that are added to the column as the parsing progresses.", "_____no_output_____" ] ], [ [ "class Column:\n def __init__(self, index, letter):\n self.index, self.letter = index, letter\n self.states, self._unique = [], {}\n\n def __str__(self):\n return \"%s chart[%d]\\n%s\" % (self.letter, self.index, \"\\n\".join(\n str(state) for state in self.states if state.finished()))", "_____no_output_____" ] ], [ [ "The `Column` only stores unique `states`. Hence, when a new `state` is `added` to our `Column`, we check whether it is already known.", "_____no_output_____" ] ], [ [ "class Column(Column):\n def add(self, state):\n if state in self._unique:\n return self._unique[state]\n self._unique[state] = state\n self.states.append(state)\n state.e_col = self\n return self._unique[state]", "_____no_output_____" ] ], [ [ "#### Items\n\nAn item represents a _parse in progress for a specific rule._ Hence the item contains the name of the nonterminal, and the corresponding alternative expression (`expr`) which together form the rule, and the current position of parsing in this expression -- `dot`.\n\n\n**Note.** If you are familiar with [LR parsing](https://en.wikipedia.org/wiki/LR_parser), you will notice that an item is simply an `LR0` item.", "_____no_output_____" ] ], [ [ "class Item:\n def __init__(self, name, expr, dot):\n self.name, self.expr, self.dot = name, expr, dot", "_____no_output_____" ] ], [ [ "We also provide a few convenience methods. The method `finished()` checks if the `dot` has moved beyond the last element in `expr`. The method `advance()` produces a new `Item` with the `dot` advanced one token, and represents an advance of the parsing. The method `at_dot()` returns the current symbol being parsed.", "_____no_output_____" ] ], [ [ "class Item(Item):\n def finished(self):\n return self.dot >= len(self.expr)\n\n def advance(self):\n return Item(self.name, self.expr, self.dot + 1)\n\n def at_dot(self):\n return self.expr[self.dot] if self.dot < len(self.expr) else None", "_____no_output_____" ] ], [ [ "Here is how an item could be used. We first define our item", "_____no_output_____" ] ], [ [ "item_name = '<B>'\nitem_expr = C_SAMPLE_GRAMMAR[item_name][1]\nan_item = Item(item_name, tuple(item_expr), 0)", "_____no_output_____" ] ], [ [ "To determine where the status of parsing, we use `at_dot()`", "_____no_output_____" ] ], [ [ "an_item.at_dot()", "_____no_output_____" ] ], [ [ "That is, the next symbol to be parsed is `<D>`", "_____no_output_____" ], [ "If we advance the item, we get another item that represents the finished parsing rule `<B>`.", "_____no_output_____" ] ], [ [ "another_item = an_item.advance()", "_____no_output_____" ], [ "another_item.finished()", "_____no_output_____" ] ], [ [ "#### States\n\nFor `Earley` parsing, the state of the parsing is simply one `Item` along with some meta information such as the starting `s_col` and ending column `e_col` for each state. Hence we inherit from `Item` to create a `State`.\nSince we are interested in comparing states, we define `hash()` and `eq()` with the corresponding methods.", "_____no_output_____" ] ], [ [ "class State(Item):\n def __init__(self, name, expr, dot, s_col, e_col=None):\n super().__init__(name, expr, dot)\n self.s_col, self.e_col = s_col, e_col\n\n def __str__(self):\n def idx(var):\n return var.index if var else -1\n\n return self.name + ':= ' + ' '.join([\n str(p)\n for p in [*self.expr[:self.dot], '|', *self.expr[self.dot:]]\n ]) + \"(%d,%d)\" % (idx(self.s_col), idx(self.e_col))\n\n def copy(self):\n return State(self.name, self.expr, self.dot, self.s_col, self.e_col)\n\n def _t(self):\n return (self.name, self.expr, self.dot, self.s_col.index)\n\n def __hash__(self):\n return hash(self._t())\n\n def __eq__(self, other):\n return self._t() == other._t()\n\n def advance(self):\n return State(self.name, self.expr, self.dot + 1, self.s_col)", "_____no_output_____" ] ], [ [ "The usage of `State` is similar to that of `Item`. The only difference is that it is used along with the `Column` to track the parsing state. For example, we initialize the first column as follows:", "_____no_output_____" ] ], [ [ "col_0 = Column(0, None)\nitem_tuple = tuple(*C_SAMPLE_GRAMMAR[START_SYMBOL])\nstart_state = State(START_SYMBOL, item_tuple, 0, col_0)\ncol_0.add(start_state)\nstart_state.at_dot()", "_____no_output_____" ] ], [ [ "The first column is then updated by using `add()` method of `Column`", "_____no_output_____" ] ], [ [ "sym = start_state.at_dot()\nfor alt in C_SAMPLE_GRAMMAR[sym]:\n col_0.add(State(sym, tuple(alt), 0, col_0))\nfor s in col_0.states:\n print(s)", "_____no_output_____" ] ], [ [ "#### The Parsing Algorithm", "_____no_output_____" ], [ "The _Earley_ algorithm starts by initializing the chart with columns (as many as there are letters in the input). We also seed the first column with a state representing the expression corresponding to the start symbol. In our case, the state corresponds to the start symbol with the `dot` at `0` is represented as below. The `●` symbol represents the parsing status. In this case, we have not parsed anything.\n```\n<start>: ● <A> <B>\n```\nWe pass this partial chart to a method for filling the rest of the parse chart.", "_____no_output_____" ], [ "Before starting to parse, we seed the chart with the state representing the ongoing parse of the start symbol.", "_____no_output_____" ] ], [ [ "class EarleyParser(Parser):\n \"\"\"Earley Parser. This parser can parse any context-free grammar.\"\"\"\n\n def __init__(self, grammar: Grammar, **kwargs) -> None:\n super().__init__(grammar, **kwargs)\n self.chart: List = [] # for type checking\n\n def chart_parse(self, words, start):\n alt = tuple(*self.cgrammar[start])\n chart = [Column(i, tok) for i, tok in enumerate([None, *words])]\n chart[0].add(State(start, alt, 0, chart[0]))\n return self.fill_chart(chart)", "_____no_output_____" ] ], [ [ "The main parsing loop in `fill_chart()` has three fundamental operations. `predict()`, `scan()`, and `complete()`. We discuss `predict` next.", "_____no_output_____" ], [ "#### Predicting States\n\nWe have already seeded `chart[0]` with a state `[<A>,<B>]` with `dot` at `0`. Next, given that `<A>` is a nonterminal, we `predict` the possible parse continuations of this state. That is, it could be either `a <B> c` or `A <A>`.\n\nThe general idea of `predict()` is as follows: Say you have a state with name `<A>` from the above grammar, and expression containing `[a,<B>,c]`. Imagine that you have seen `a` already, which means that the `dot` will be on `<B>`. Below, is a representation of our parse status. The left hand side of ● represents the portion already parsed (`a`), and the right hand side represents the portion yet to be parsed (`<B> c`).\n\n```\n<A>: a ● <B> c\n```", "_____no_output_____" ], [ "To recognize `<B>`, we look at the definition of `<B>`, which has different alternative expressions. The `predict()` step adds each of these alternatives to the set of states, with `dot` at `0`.\n\n```\n<A>: a ● <B> c\n<B>: ● b c\n<B>: ● <D>\n```\n\nIn essence, the `predict()` method, when called with the current nonterminal, fetches the alternative expressions corresponding to this nonterminal, and adds these as predicted _child_ states to the _current_ column.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def predict(self, col, sym, state):\n for alt in self.cgrammar[sym]:\n col.add(State(sym, tuple(alt), 0, col))", "_____no_output_____" ] ], [ [ "To see how to use `predict`, we first construct the 0th column as before, and we assign the constructed column to an instance of the EarleyParser.", "_____no_output_____" ] ], [ [ "col_0 = Column(0, None)\ncol_0.add(start_state)\nep = EarleyParser(SAMPLE_GRAMMAR)\nep.chart = [col_0]", "_____no_output_____" ] ], [ [ "It should contain a single state -- `<start> at 0`", "_____no_output_____" ] ], [ [ "for s in ep.chart[0].states:\n print(s)", "_____no_output_____" ] ], [ [ "We apply predict to fill out the 0th column, and the column should contain the possible parse paths.", "_____no_output_____" ] ], [ [ "ep.predict(col_0, '<A>', s)\nfor s in ep.chart[0].states:\n print(s)", "_____no_output_____" ] ], [ [ "#### Scanning Tokens\n\nWhat if rather than a nonterminal, the state contained a terminal symbol such as a letter? In that case, we are ready to make some progress. For example, consider the second state:\n```\n<B>: ● b c\n```\nWe `scan` the next column's letter. Say the next token is `b`.\nIf the letter matches what we have, then create a new state by advancing the current state by one letter.\n\n```\n<B>: b ● c\n```\nThis new state is added to the next column (i.e the column that has the matched letter).", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def scan(self, col, state, letter):\n if letter == col.letter:\n col.add(state.advance())", "_____no_output_____" ] ], [ [ "As before, we construct the partial parse first, this time adding a new column so that we can observe the effects of `scan()`", "_____no_output_____" ] ], [ [ "ep = EarleyParser(SAMPLE_GRAMMAR)\ncol_1 = Column(1, 'a')\nep.chart = [col_0, col_1]", "_____no_output_____" ], [ "new_state = ep.chart[0].states[1]\nprint(new_state)", "_____no_output_____" ], [ "ep.scan(col_1, new_state, 'a')\nfor s in ep.chart[1].states:\n print(s)", "_____no_output_____" ] ], [ [ "#### Completing Processing\n\nWhen we advance, what if we actually `complete()` the processing of the current rule? If so, we want to update not just this state, but also all the _parent_ states from which this state was derived.\nFor example, say we have states as below.\n```\n<A>: a ● <B> c\n<B>: b c ● \n```\nThe state `<B>: b c ●` is now complete. So, we need to advance `<A>: a ● <B> c` one step forward.\n\nHow do we determine the parent states? Note from `predict` that we added the predicted child states to the _same_ column as that of the inspected state. Hence, we look at the starting column of the current state, with the same symbol `at_dot` as that of the name of the completed state.\n\nFor each such parent found, we advance that parent (because we have just finished parsing that non terminal for their `at_dot`) and add the new states to the current column.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def complete(self, col, state):\n return self.earley_complete(col, state)\n\n def earley_complete(self, col, state):\n parent_states = [\n st for st in state.s_col.states if st.at_dot() == state.name\n ]\n for st in parent_states:\n col.add(st.advance())", "_____no_output_____" ] ], [ [ "Here is an example of completed processing. First we complete the Column 0", "_____no_output_____" ] ], [ [ "ep = EarleyParser(SAMPLE_GRAMMAR)\ncol_1 = Column(1, 'a')\ncol_2 = Column(2, 'd')\nep.chart = [col_0, col_1, col_2]\nep.predict(col_0, '<A>', s)\nfor s in ep.chart[0].states:\n print(s)", "_____no_output_____" ] ], [ [ "Then we use `scan()` to populate Column 1", "_____no_output_____" ] ], [ [ "for state in ep.chart[0].states:\n if state.at_dot() not in SAMPLE_GRAMMAR:\n ep.scan(col_1, state, 'a')\nfor s in ep.chart[1].states:\n print(s)", "_____no_output_____" ], [ "for state in ep.chart[1].states:\n if state.at_dot() in SAMPLE_GRAMMAR:\n ep.predict(col_1, state.at_dot(), state)\nfor s in ep.chart[1].states:\n print(s)", "_____no_output_____" ] ], [ [ "Then we use `scan()` again to populate Column 2", "_____no_output_____" ] ], [ [ "for state in ep.chart[1].states:\n if state.at_dot() not in SAMPLE_GRAMMAR:\n ep.scan(col_2, state, state.at_dot())\n\nfor s in ep.chart[2].states:\n print(s)", "_____no_output_____" ] ], [ [ "Now, we can use `complete()`:", "_____no_output_____" ] ], [ [ "for state in ep.chart[2].states:\n if state.finished():\n ep.complete(col_2, state)\n\nfor s in ep.chart[2].states:\n print(s)", "_____no_output_____" ] ], [ [ "#### Filling the Chart\n\nThe main driving loop in `fill_chart()` essentially calls these operations in order. We loop over each column in order.\n* For each column, fetch one state in the column at a time, and check if the state is `finished`. \n * If it is, then we `complete()` all the parent states depending on this state. \n* If the state was not finished, we check to see if the state's current symbol `at_dot` is a nonterminal. \n * If it is a nonterminal, we `predict()` possible continuations, and update the current column with these states. \n * If it was not, we `scan()` the next column and advance the current state if it matches the next letter.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def fill_chart(self, chart):\n for i, col in enumerate(chart):\n for state in col.states:\n if state.finished():\n self.complete(col, state)\n else:\n sym = state.at_dot()\n if sym in self.cgrammar:\n self.predict(col, sym, state)\n else:\n if i + 1 >= len(chart):\n continue\n self.scan(chart[i + 1], state, sym)\n if self.log:\n print(col, '\\n')\n return chart", "_____no_output_____" ] ], [ [ "We now can recognize a given string as belonging to a language represented by a grammar.", "_____no_output_____" ] ], [ [ "ep = EarleyParser(SAMPLE_GRAMMAR, log=True)\ncolumns = ep.chart_parse('adcd', START_SYMBOL)", "_____no_output_____" ] ], [ [ "The chart we printed above only shows completed entries at each index. The parenthesized expression indicates the column just before the first character was recognized, and the ending column.\n\nNotice how the `<start>` nonterminal shows fully parsed status.", "_____no_output_____" ] ], [ [ "last_col = columns[-1]\nfor state in last_col.states:\n if state.name == '<start>':\n print(state)", "_____no_output_____" ] ], [ [ "Since `chart_parse()` returns the completed table, we now need to extract the derivation trees.", "_____no_output_____" ], [ "#### The Parse Method\n\nFor determining how far we have managed to parse, we simply look for the last index from `chart_parse()` where the `start_symbol` was found.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def parse_prefix(self, text):\n self.table = self.chart_parse(text, self.start_symbol())\n for col in reversed(self.table):\n states = [\n st for st in col.states if st.name == self.start_symbol()\n ]\n if states:\n return col.index, states\n return -1, []", "_____no_output_____" ] ], [ [ "Here is the `parse_prefix()` in action.", "_____no_output_____" ] ], [ [ "ep = EarleyParser(SAMPLE_GRAMMAR)\ncursor, last_states = ep.parse_prefix('adcd')\nprint(cursor, [str(s) for s in last_states])", "_____no_output_____" ] ], [ [ "The following is adapted from the excellent reference on Earley parsing by [Loup Vaillant](http://loup-vaillant.fr/tutorials/earley-parsing/).\n", "_____no_output_____" ], [ "Our `parse()` method is as follows. It depends on two methods `parse_forest()` and `extract_trees()` that will be defined next.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def parse(self, text):\n cursor, states = self.parse_prefix(text)\n start = next((s for s in states if s.finished()), None)\n\n if cursor < len(text) or not start:\n raise SyntaxError(\"at \" + repr(text[cursor:]))\n\n forest = self.parse_forest(self.table, start)\n for tree in self.extract_trees(forest):\n yield self.prune_tree(tree)", "_____no_output_____" ] ], [ [ "#### Parsing Paths\n\nThe `parse_paths()` method tries to unify the given expression in `named_expr` with the parsed string. For that, it extracts the last symbol in `named_expr` and checks if it is a terminal symbol. If it is, then it checks the chart at `til` to see if the letter corresponding to the position matches the terminal symbol. If it does, extend our start index by the length of the symbol.\n\nIf the symbol was a nonterminal symbol, then we retrieve the parsed states at the current end column index (`til`) that correspond to the nonterminal symbol, and collect the start index. These are the end column indexes for the remaining expression.\n\nGiven our list of start indexes, we obtain the parse paths from the remaining expression. If we can obtain any, then we return the parse paths. If not, we return an empty list.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def parse_paths(self, named_expr, chart, frm, til):\n def paths(state, start, k, e):\n if not e:\n return [[(state, k)]] if start == frm else []\n else:\n return [[(state, k)] + r\n for r in self.parse_paths(e, chart, frm, start)]\n\n *expr, var = named_expr\n starts = None\n if var not in self.cgrammar:\n starts = ([(var, til - len(var),\n 't')] if til > 0 and chart[til].letter == var else [])\n else:\n starts = [(s, s.s_col.index, 'n') for s in chart[til].states\n if s.finished() and s.name == var]\n\n return [p for s, start, k in starts for p in paths(s, start, k, expr)]", "_____no_output_____" ] ], [ [ "Here is the `parse_paths()` in action", "_____no_output_____" ] ], [ [ "print(SAMPLE_GRAMMAR['<start>'])\nep = EarleyParser(SAMPLE_GRAMMAR)\ncompleted_start = last_states[0]\npaths = ep.parse_paths(completed_start.expr, columns, 0, 4)\nfor path in paths:\n print([list(str(s_) for s_ in s) for s in path])", "_____no_output_____" ] ], [ [ "That is, the parse path for `<start>` given the input `adcd` included recognizing the expression `<A><B>`. This was recognized by the two states: `<A>` from input(0) to input(2) which further involved recognizing the rule `a<B>c`, and the next state `<B>` from input(3) which involved recognizing the rule `<D>`.", "_____no_output_____" ], [ "#### Parsing Forests\n\nThe `parse_forest()` method takes the state which represents the completed parse, and determines the possible ways that its expressions corresponded to the parsed expression. For example, say we are parsing `1+2+3`, and the state has `[<expr>,+,<expr>]` in `expr`. It could have been parsed as either `[{<expr>:1+2},+,{<expr>:3}]` or `[{<expr>:1},+,{<expr>:2+3}]`.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def forest(self, s, kind, chart):\n return self.parse_forest(chart, s) if kind == 'n' else (s, [])\n\n def parse_forest(self, chart, state):\n pathexprs = self.parse_paths(state.expr, chart, state.s_col.index,\n state.e_col.index) if state.expr else []\n return state.name, [[(v, k, chart) for v, k in reversed(pathexpr)]\n for pathexpr in pathexprs]", "_____no_output_____" ], [ "ep = EarleyParser(SAMPLE_GRAMMAR)\nresult = ep.parse_forest(columns, last_states[0])\nresult", "_____no_output_____" ] ], [ [ "#### Extracting Trees", "_____no_output_____" ], [ "What we have from `parse_forest()` is a forest of trees. We need to extract a single tree from that forest. That is accomplished as follows.", "_____no_output_____" ], [ "(For now, we return the first available derivation tree. To do that, we need to extract the parse forest from the state corresponding to `start`.)", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def extract_a_tree(self, forest_node):\n name, paths = forest_node\n if not paths:\n return (name, [])\n return (name, [self.extract_a_tree(self.forest(*p)) for p in paths[0]])\n\n def extract_trees(self, forest):\n yield self.extract_a_tree(forest)", "_____no_output_____" ] ], [ [ "We now verify that our parser can parse a given expression.", "_____no_output_____" ] ], [ [ "A3_GRAMMAR: Grammar = {\n \"<start>\": [\"<bexpr>\"],\n \"<bexpr>\": [\n \"<aexpr><gt><aexpr>\", \"<aexpr><lt><aexpr>\", \"<aexpr>=<aexpr>\",\n \"<bexpr>=<bexpr>\", \"<bexpr>&<bexpr>\", \"<bexpr>|<bexpr>\", \"(<bexrp>)\"\n ],\n \"<aexpr>\":\n [\"<aexpr>+<aexpr>\", \"<aexpr>-<aexpr>\", \"(<aexpr>)\", \"<integer>\"],\n \"<integer>\": [\"<digit><integer>\", \"<digit>\"],\n \"<digit>\": [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"],\n \"<lt>\": ['<'],\n \"<gt>\": ['>']\n}", "_____no_output_____" ], [ "syntax_diagram(A3_GRAMMAR)", "_____no_output_____" ], [ "mystring = '(1+24)=33'\nparser = EarleyParser(A3_GRAMMAR)\nfor tree in parser.parse(mystring):\n assert tree_to_string(tree) == mystring\n display_tree(tree)", "_____no_output_____" ] ], [ [ "We now have a complete parser that can parse almost arbitrary *CFG*. There remains a small corner to fix -- the case of epsilon rules as we will see later.", "_____no_output_____" ], [ "#### Ambiguous Parsing", "_____no_output_____" ], [ "Ambiguous grammars are grammars that can produce multiple derivation trees for some given string. For example, the `A3_GRAMMAR` can parse `1+2+3` in two different ways – `[1+2]+3` and `1+[2+3]`.\n\nExtracting a single tree might be reasonable for unambiguous parses. However, what if the given grammar produces ambiguity when given a string? We need to extract all derivation trees in that case. We enhance our `extract_trees()` method to extract multiple derivation trees.", "_____no_output_____" ] ], [ [ "import itertools as I", "_____no_output_____" ], [ "class EarleyParser(EarleyParser):\n def extract_trees(self, forest_node):\n name, paths = forest_node\n if not paths:\n yield (name, [])\n\n for path in paths:\n ptrees = [self.extract_trees(self.forest(*p)) for p in path]\n for p in I.product(*ptrees):\n yield (name, p)", "_____no_output_____" ] ], [ [ "As before, we verify that everything works.", "_____no_output_____" ] ], [ [ "mystring = '1+2'\nparser = EarleyParser(A1_GRAMMAR)\nfor tree in parser.parse(mystring):\n assert mystring == tree_to_string(tree)\n display_tree(tree)", "_____no_output_____" ] ], [ [ "One can also use a `GrammarFuzzer` to verify that everything works.", "_____no_output_____" ] ], [ [ "gf = GrammarFuzzer(A1_GRAMMAR)\nfor i in range(5):\n s = gf.fuzz()\n print(i, s)\n for tree in parser.parse(s):\n assert tree_to_string(tree) == s", "_____no_output_____" ] ], [ [ "#### The Aycock Epsilon Fix\n\nWhile parsing, one often requires to know whether a given nonterminal can derive an empty string. For example, in the following grammar A can derive an empty string, while B can't. The nonterminals that can derive an empty string are called _nullable_ nonterminals. For example, in the below grammar `E_GRAMMAR_1`, `<A>` is _nullable_, and since `<A>` is one of the alternatives of `<start>`, `<start>` is also _nullable_. But `<B>` is not _nullable_.", "_____no_output_____" ] ], [ [ "E_GRAMMAR_1: Grammar = {\n '<start>': ['<A>', '<B>'],\n '<A>': ['a', ''],\n '<B>': ['b']\n}", "_____no_output_____" ] ], [ [ "One of the problems with the original Earley implementation is that it does not handle rules that can derive empty strings very well. For example, the given grammar should match `a`", "_____no_output_____" ] ], [ [ "EPSILON = ''\nE_GRAMMAR: Grammar = {\n '<start>': ['<S>'],\n '<S>': ['<A><A><A><A>'],\n '<A>': ['a', '<E>'],\n '<E>': [EPSILON]\n}", "_____no_output_____" ], [ "syntax_diagram(E_GRAMMAR)", "_____no_output_____" ], [ "mystring = 'a'\nparser = EarleyParser(E_GRAMMAR)\nwith ExpectError():\n trees = parser.parse(mystring)", "_____no_output_____" ] ], [ [ "Aycock et al.\\cite{Aycock2002} suggests a simple fix. Their idea is to pre-compute the `nullable` set and use it to advance the `nullable` states. However, before we do that, we need to compute the `nullable` set. The `nullable` set consists of all nonterminals that can derive an empty string.", "_____no_output_____" ], [ "Computing the `nullable` set requires expanding each production rule in the grammar iteratively and inspecting whether a given rule can derive the empty string. Each iteration needs to take into account new terminals that have been found to be `nullable`. The procedure stops when we obtain a stable result. This procedure can be abstracted into a more general method `fixpoint`.", "_____no_output_____" ], [ "##### Fixpoint\n\nA `fixpoint` of a function is an element in the function's domain such that it is mapped to itself. For example, 1 is a `fixpoint` of square root because `squareroot(1) == 1`.\n\n(We use `str` rather than `hash` to check for equality in `fixpoint` because the data structure `set`, which we would like to use as an argument has a good string representation but is not hashable).", "_____no_output_____" ] ], [ [ "def fixpoint(f):\n def helper(arg):\n while True:\n sarg = str(arg)\n arg_ = f(arg)\n if str(arg_) == sarg:\n return arg\n arg = arg_\n\n return helper", "_____no_output_____" ] ], [ [ "Remember `my_sqrt()` from [the first chapter](Intro_Testing.ipynb)? We can define `my_sqrt()` using fixpoint.", "_____no_output_____" ] ], [ [ "def my_sqrt(x):\n @fixpoint\n def _my_sqrt(approx):\n return (approx + x / approx) / 2\n\n return _my_sqrt(1)", "_____no_output_____" ], [ "my_sqrt(2)", "_____no_output_____" ] ], [ [ "##### Nullable\n\nSimilarly, we can define `nullable` using `fixpoint`. We essentially provide the definition of a single intermediate step. That is, assuming that `nullables` contain the current `nullable` nonterminals, we iterate over the grammar looking for productions which are `nullable` -- that is, productions where the entire sequence can yield an empty string on some expansion.", "_____no_output_____" ], [ "We need to iterate over the different alternative expressions and their corresponding nonterminals. Hence we define a `rules()` method converts our dictionary representation to this pair format.", "_____no_output_____" ] ], [ [ "def rules(grammar):\n return [(key, choice)\n for key, choices in grammar.items()\n for choice in choices]", "_____no_output_____" ] ], [ [ "The `terminals()` method extracts all terminal symbols from a `canonical` grammar representation.", "_____no_output_____" ] ], [ [ "def terminals(grammar):\n return set(token\n for key, choice in rules(grammar)\n for token in choice if token not in grammar)", "_____no_output_____" ], [ "def nullable_expr(expr, nullables):\n return all(token in nullables for token in expr)", "_____no_output_____" ], [ "def nullable(grammar):\n productions = rules(grammar)\n\n @fixpoint\n def nullable_(nullables):\n for A, expr in productions:\n if nullable_expr(expr, nullables):\n nullables |= {A}\n return (nullables)\n\n return nullable_({EPSILON})", "_____no_output_____" ], [ "for key, grammar in {\n 'E_GRAMMAR': E_GRAMMAR,\n 'E_GRAMMAR_1': E_GRAMMAR_1\n}.items():\n print(key, nullable(canonical(grammar)))", "_____no_output_____" ] ], [ [ "So, once we have the `nullable` set, all that we need to do is, after we have called `predict` on a state corresponding to a nonterminal, check if it is `nullable` and if it is, advance and add the state to the current column.", "_____no_output_____" ] ], [ [ "class EarleyParser(EarleyParser):\n def __init__(self, grammar, **kwargs):\n super().__init__(grammar, **kwargs)\n self.epsilon = nullable(self.cgrammar)\n\n def predict(self, col, sym, state):\n for alt in self.cgrammar[sym]:\n col.add(State(sym, tuple(alt), 0, col))\n if sym in self.epsilon:\n col.add(state.advance())", "_____no_output_____" ], [ "mystring = 'a'\nparser = EarleyParser(E_GRAMMAR)\nfor tree in parser.parse(mystring):\n display_tree(tree)", "_____no_output_____" ] ], [ [ "To ensure that our parser does parse all kinds of grammars, let us try two more test cases.", "_____no_output_____" ] ], [ [ "DIRECTLY_SELF_REFERRING: Grammar = {\n '<start>': ['<query>'],\n '<query>': ['select <expr> from a'],\n \"<expr>\": [\"<expr>\", \"a\"],\n}\nINDIRECTLY_SELF_REFERRING: Grammar = {\n '<start>': ['<query>'],\n '<query>': ['select <expr> from a'],\n \"<expr>\": [\"<aexpr>\", \"a\"],\n \"<aexpr>\": [\"<expr>\"],\n}", "_____no_output_____" ], [ "mystring = 'select a from a'\nfor grammar in [DIRECTLY_SELF_REFERRING, INDIRECTLY_SELF_REFERRING]:\n forest = EarleyParser(grammar).parse(mystring)\n print('recognized', mystring)\n try:\n for tree in forest:\n print(tree_to_string(tree))\n except RecursionError as e:\n print(\"Recursion error\", e)", "_____no_output_____" ] ], [ [ "Why do we get recursion error here? The reason is that, our implementation of `extract_trees()` is eager. That is, it attempts to extract _all_ inner parse trees before it can construct the outer parse tree. When there is a self reference, this results in recursion. Here is a simple extractor that avoids this problem. The idea here is that we randomly and lazily choose a node to expand, which avoids the infinite recursion.", "_____no_output_____" ], [ "#### Tree Extractor", "_____no_output_____" ], [ "As you saw above, one of the problems with attempting to extract all trees is that the parse forest can consist of an infinite number of trees. So, here, we solve that problem by extracting one tree at a time.", "_____no_output_____" ] ], [ [ "class SimpleExtractor:\n def __init__(self, parser, text):\n self.parser = parser\n cursor, states = parser.parse_prefix(text)\n start = next((s for s in states if s.finished()), None)\n if cursor < len(text) or not start:\n raise SyntaxError(\"at \" + repr(cursor))\n self.my_forest = parser.parse_forest(parser.table, start)\n\n def extract_a_node(self, forest_node):\n name, paths = forest_node\n if not paths:\n return ((name, 0, 1), []), (name, [])\n cur_path, i, length = self.choose_path(paths)\n child_nodes = []\n pos_nodes = []\n for s, kind, chart in cur_path:\n f = self.parser.forest(s, kind, chart)\n postree, ntree = self.extract_a_node(f)\n child_nodes.append(ntree)\n pos_nodes.append(postree)\n\n return ((name, i, length), pos_nodes), (name, child_nodes)\n\n def choose_path(self, arr):\n length = len(arr)\n i = random.randrange(length)\n return arr[i], i, length\n\n def extract_a_tree(self):\n pos_tree, parse_tree = self.extract_a_node(self.my_forest)\n return self.parser.prune_tree(parse_tree)", "_____no_output_____" ] ], [ [ "Using it is as folows:", "_____no_output_____" ] ], [ [ "de = SimpleExtractor(EarleyParser(DIRECTLY_SELF_REFERRING), mystring)", "_____no_output_____" ], [ "for i in range(5):\n tree = de.extract_a_tree()\n print(tree_to_string(tree))", "_____no_output_____" ] ], [ [ "On the indirect reference:", "_____no_output_____" ] ], [ [ "ie = SimpleExtractor(EarleyParser(INDIRECTLY_SELF_REFERRING), mystring)", "_____no_output_____" ], [ "for i in range(5):\n tree = ie.extract_a_tree()\n print(tree_to_string(tree))", "_____no_output_____" ] ], [ [ "Note that the `SimpleExtractor` gives no guarantee of the uniqueness of the returned trees. This can however be fixed by keeping track of the particular nodes that were expanded from `pos_tree` variable, and hence, avoiding exploration of the same paths.\n\nFor implementing this, we extract the random stream passing into the `SimpleExtractor`, and use it to control which nodes are explored. Different exploration paths can then form a tree of nodes.", "_____no_output_____" ], [ "We start with the node definition for a single choice. The `self._chosen` is the current choice made, `self.next` holds the next choice done using `self._chosen`. The `self.total` holds the total number of choices that one can have in this node.", "_____no_output_____" ] ], [ [ "class ChoiceNode:\n def __init__(self, parent, total):\n self._p, self._chosen = parent, 0\n self._total, self.next = total, None\n\n def chosen(self):\n assert not self.finished()\n return self._chosen\n\n def __str__(self):\n return '%d(%s/%s %s)' % (self._i, str(self._chosen),\n str(self._total), str(self.next))\n\n def __repr__(self):\n return repr((self._i, self._chosen, self._total))\n\n def increment(self):\n # as soon as we increment, next becomes invalid\n self.next = None\n self._chosen += 1\n if self.finished():\n if self._p is None:\n return None\n return self._p.increment()\n return self\n\n def finished(self):\n return self._chosen >= self._total", "_____no_output_____" ] ], [ [ "Now we come to the enhanced `EnhancedExtractor()`.", "_____no_output_____" ] ], [ [ "class EnhancedExtractor(SimpleExtractor):\n def __init__(self, parser, text):\n super().__init__(parser, text)\n self.choices = ChoiceNode(None, 1)", "_____no_output_____" ] ], [ [ "First we define `choose_path()` that given an array and a choice node, returns the element in array corresponding to the next choice node if it exists, or produces a new choice nodes, and returns that element.", "_____no_output_____" ] ], [ [ "class EnhancedExtractor(EnhancedExtractor):\n def choose_path(self, arr, choices):\n arr_len = len(arr)\n if choices.next is not None:\n if choices.next.finished():\n return None, None, None, choices.next\n else:\n choices.next = ChoiceNode(choices, arr_len)\n next_choice = choices.next.chosen()\n choices = choices.next\n return arr[next_choice], next_choice, arr_len, choices", "_____no_output_____" ] ], [ [ "We define `extract_a_node()` here. While extracting, we have a choice. Should we allow infinite forests, or should we have a finite number of trees with no direct recursion? A direct recursion is when there exists a parent node with the same nonterminal that parsed the same span. We choose here not to extract such trees. They can be added back after parsing.\n\nThis is a recursive procedure that inspects a node, extracts the path required to complete that node. A single path (corresponding to a nonterminal) may again be composed of a sequence of smaller paths. Such paths are again extracted using another call to `extract_a_node()` recursively.\n\nWhat happens when we hit on one of the node recursions we want to avoid? In that case, we return the current choice node, which bubbles up to `extract_a_tree()`. That procedure increments the last choice, which in turn increments up the parents until we reach a choice node that still has options to explore.\n\nWhat if we hit the end of choices for a particular choice node(i.e, we have exhausted paths that can be taken from a node)? In this case also, we return the current choice node, which bubbles up to `extract_a_tree()`.\nThat procedure increments the last choice, which bubbles up to the next choice that has some unexplored paths.", "_____no_output_____" ] ], [ [ "class EnhancedExtractor(EnhancedExtractor):\n def extract_a_node(self, forest_node, seen, choices):\n name, paths = forest_node\n if not paths:\n return (name, []), choices\n\n cur_path, _i, _l, new_choices = self.choose_path(paths, choices)\n if cur_path is None:\n return None, new_choices\n child_nodes = []\n for s, kind, chart in cur_path:\n if kind == 't':\n child_nodes.append((s, []))\n continue\n nid = (s.name, s.s_col.index, s.e_col.index)\n if nid in seen:\n return None, new_choices\n f = self.parser.forest(s, kind, chart)\n ntree, newer_choices = self.extract_a_node(f, seen | {nid}, new_choices)\n if ntree is None:\n return None, newer_choices\n child_nodes.append(ntree)\n new_choices = newer_choices\n return (name, child_nodes), new_choices", "_____no_output_____" ] ], [ [ "The `extract_a_tree()` is a depth first extractor of a single tree. It tries to extract a tree, and if the extraction returns `None`, it means that a particular choice was exhausted, or we hit on a recursion. In that case, we increment the choice, and explore a new path.", "_____no_output_____" ] ], [ [ "class EnhancedExtractor(EnhancedExtractor):\n def extract_a_tree(self):\n while not self.choices.finished():\n parse_tree, choices = self.extract_a_node(self.my_forest, set(), self.choices)\n choices.increment()\n if parse_tree is not None:\n return self.parser.prune_tree(parse_tree)\n return None", "_____no_output_____" ] ], [ [ "Note that the `EnhancedExtractor` only extracts nodes that are not directly recursive. That is, if it finds a node with a nonterminal that covers the same span as that of a parent node with the same nonterminal, it skips the node.", "_____no_output_____" ] ], [ [ "ee = EnhancedExtractor(EarleyParser(INDIRECTLY_SELF_REFERRING), mystring)", "_____no_output_____" ], [ "i = 0\nwhile True:\n i += 1\n t = ee.extract_a_tree()\n if t is None: break\n print(i, t)\n s = tree_to_string(t)\n assert s == mystring", "_____no_output_____" ], [ "istring = '1+2+3+4'\nee = EnhancedExtractor(EarleyParser(A1_GRAMMAR), istring)", "_____no_output_____" ], [ "i = 0\nwhile True:\n i += 1\n t = ee.extract_a_tree()\n if t is None: break\n print(i, t)\n s = tree_to_string(t)\n assert s == istring", "_____no_output_____" ] ], [ [ "#### More Earley Parsing\n\nA number of other optimizations exist for Earley parsers. A fast industrial strength Earley parser implementation is the [Marpa parser](https://jeffreykegler.github.io/Marpa-web-site/). Further, Earley parsing need not be restricted to character data. One may also parse streams (audio and video streams) \\cite{qi2018generalized} using a generalized Earley parser.", "_____no_output_____" ], [ "### End of Excursion", "_____no_output_____" ], [ "Here are a few examples of the Earley parser in action.", "_____no_output_____" ] ], [ [ "mystring = \"1 + (2 * 3)\"\nearley = EarleyParser(EXPR_GRAMMAR)\nfor tree in earley.parse(mystring):\n assert tree_to_string(tree) == mystring\n display(display_tree(tree))", "_____no_output_____" ], [ "mystring = \"1 * (2 + 3.35)\"\nfor tree in earley.parse(mystring):\n assert tree_to_string(tree) == mystring\n display(display_tree(tree))", "_____no_output_____" ] ], [ [ "In contrast to the `PEGParser`, above, the `EarleyParser` can handle arbitrary context-free grammars.", "_____no_output_____" ], [ "### Excursion: Testing the Parsers\n\nWhile we have defined two parser variants, it would be nice to have some confirmation that our parses work well. While it is possible to formally prove that they work, it is much more satisfying to generate random grammars, their corresponding strings, and parse them using the same grammar.", "_____no_output_____" ] ], [ [ "def prod_line_grammar(nonterminals, terminals):\n g = {\n '<start>': ['<symbols>'],\n '<symbols>': ['<symbol><symbols>', '<symbol>'],\n '<symbol>': ['<nonterminals>', '<terminals>'],\n '<nonterminals>': ['<lt><alpha><gt>'],\n '<lt>': ['<'],\n '<gt>': ['>'],\n '<alpha>': nonterminals,\n '<terminals>': terminals\n }\n\n if not nonterminals:\n g['<nonterminals>'] = ['']\n del g['<lt>']\n del g['<alpha>']\n del g['<gt>']\n\n return g", "_____no_output_____" ], [ "syntax_diagram(prod_line_grammar([\"A\", \"B\", \"C\"], [\"1\", \"2\", \"3\"]))", "_____no_output_____" ], [ "def make_rule(nonterminals, terminals, num_alts):\n prod_grammar = prod_line_grammar(nonterminals, terminals)\n\n gf = GrammarFuzzer(prod_grammar, min_nonterminals=3, max_nonterminals=5)\n name = \"<%s>\" % ''.join(random.choices(string.ascii_uppercase, k=3))\n\n return (name, [gf.fuzz() for _ in range(num_alts)])", "_____no_output_____" ], [ "make_rule([\"A\", \"B\", \"C\"], [\"1\", \"2\", \"3\"], 3)", "_____no_output_____" ], [ "from Grammars import unreachable_nonterminals", "_____no_output_____" ], [ "def make_grammar(num_symbols=3, num_alts=3):\n terminals = list(string.ascii_lowercase)\n grammar = {}\n name = None\n for _ in range(num_symbols):\n nonterminals = [k[1:-1] for k in grammar.keys()]\n name, expansions = \\\n make_rule(nonterminals, terminals, num_alts)\n grammar[name] = expansions\n\n grammar[START_SYMBOL] = [name]\n\n # Remove unused parts\n for nonterminal in unreachable_nonterminals(grammar):\n del grammar[nonterminal]\n\n assert is_valid_grammar(grammar)\n\n return grammar", "_____no_output_____" ], [ "make_grammar()", "_____no_output_____" ] ], [ [ "Now we verify if our arbitrary grammars can be used by the Earley parser.", "_____no_output_____" ] ], [ [ "for i in range(5):\n my_grammar = make_grammar()\n print(my_grammar)\n parser = EarleyParser(my_grammar)\n mygf = GrammarFuzzer(my_grammar)\n s = mygf.fuzz()\n print(s)\n for tree in parser.parse(s):\n assert tree_to_string(tree) == s\n display_tree(tree)", "_____no_output_____" ] ], [ [ "With this, we have completed both implementation and testing of *arbitrary* CFG, which can now be used along with `LangFuzzer` to generate better fuzzing inputs.", "_____no_output_____" ], [ "### End of Excursion", "_____no_output_____" ], [ "## Background\n\n\nNumerous parsing techniques exist that can parse a given string using a\ngiven grammar, and produce corresponding derivation tree or trees. However,\nsome of these techniques work only on specific classes of grammars.\nThese classes of grammars are named after the specific kind of parser\nthat can accept grammars of that category. That is, the upper bound for\nthe capabilities of the parser defines the grammar class named after that\nparser.\n\nThe *LL* and *LR* parsing are the main traditions in parsing. Here, *LL* means left-to-right, leftmost derivation, and it represents a top-down approach. On the other hand, and LR (left-to-right, rightmost derivation) represents a bottom-up approach. Another way to look at it is that LL parsers compute the derivation tree incrementally in *pre-order* while LR parsers compute the derivation tree in *post-order* \\cite{pingali2015graphical}).\n\nDifferent classes of grammars differ in the features that are available to\nthe user for writing a grammar of that class. That is, the corresponding\nkind of parser will be unable to parse a grammar that makes use of more\nfeatures than allowed. For example, the `A2_GRAMMAR` is an *LL*\ngrammar because it lacks left recursion, while `A1_GRAMMAR` is not an\n*LL* grammar. This is because an *LL* parser parses\nits input from left to right, and constructs the leftmost derivation of its\ninput by expanding the nonterminals it encounters. If there is a left\nrecursion in one of these rules, an *LL* parser will enter an infinite loop.\n\nSimilarly, a grammar is LL(k) if it can be parsed by an LL parser with k lookahead token, and LR(k) grammar can only be parsed with LR parser with at least k lookahead tokens. These grammars are interesting because both LL(k) and LR(k) grammars have $O(n)$ parsers, and can be used with relatively restricted computational budget compared to other grammars.\n\nThe languages for which one can provide an *LL(k)* grammar is called *LL(k)* languages (where k is the minimum lookahead required). Similarly, *LR(k)* is defined as the set of languages that have an *LR(k)* grammar. In terms of languages, LL(k) $\\subset$ LL(k+1) and LL(k) $\\subset$ LR(k), and *LR(k)* $=$ *LR(1)*. All deterministic *CFLs* have an *LR(1)* grammar. However, there exist *CFLs* that are inherently ambiguous \\cite{ogden1968helpful}, and for these, one can't provide an *LR(1)* grammar.\n\nThe other main parsing algorithms for *CFGs* are GLL \\cite{scott2010gll}, GLR \\cite{tomita1987efficient,tomita2012generalized}, and CYK \\cite{grune2008parsing}.\nThe ALL(\\*) (used by ANTLR) on the other hand is a grammar representation that uses *Regular Expression* like predicates (similar to advanced PEGs – see [Exercise](#Exercise-3:-PEG-Predicates)) rather than a fixed lookahead. Hence, ALL(\\*) can accept a larger class of grammars than CFGs.\n\nIn terms of computational limits of parsing, the main CFG parsers have a complexity of $O(n^3)$ for arbitrary grammars. However, parsing with arbitrary *CFG* is reducible to boolean matrix multiplication \\cite{Valiant1975} (and the reverse \\cite{Lee2002}). This is at present bounded by $O(2^{23728639}$) \\cite{LeGall2014}. Hence, worse case complexity for parsing arbitrary CFG is likely to remain close to cubic.\n\nRegarding PEGs, the actual class of languages that is expressible in *PEG* is currently unknown. In particular, we know that *PEGs* can express certain languages such as $a^n b^n c^n$. However, we do not know if there exist *CFLs* that are not expressible with *PEGs*. In Section 2.3, we provided an instance of a counter-intuitive PEG grammar. While important for our purposes (we use grammars for generation of inputs) this is not a criticism of parsing with PEGs. PEG focuses on writing grammars for recognizing a given language, and not necessarily in interpreting what language an arbitrary PEG might yield. Given a Context-Free Language to parse, it is almost always possible to write a grammar for it in PEG, and given that 1) a PEG can parse any string in $O(n)$ time, and 2) at present we know of no CFL that can't be expressed as a PEG, and 3) compared with *LR* grammars, a PEG is often more intuitive because it allows top-down interpretation, when writing a parser for a language, PEGs should be under serious consideration.", "_____no_output_____" ], [ "## Synopsis\n\nThis chapter introduces `Parser` classes, parsing a string into a _derivation tree_ as introduced in the [chapter on efficient grammar fuzzing](GrammarFuzzer.ipynb). Two important parser classes are provided:\n\n* [Parsing Expression Grammar parsers](#Parsing-Expression-Grammars) (`PEGParser`). These are very efficient, but limited to specific grammar structure. Notably, the alternatives represent *ordered choice*. That is, rather than choosing all rules that can potentially match, we stop at the first match that succeed.\n* [Earley parsers](#Parsing-Context-Free-Grammars) (`EarleyParser`). These accept any kind of context-free grammars, and explore all parsing alternatives (if any).\n\nUsing any of these is fairly easy, though. First, instantiate them with a grammar:", "_____no_output_____" ] ], [ [ "from Grammars import US_PHONE_GRAMMAR", "_____no_output_____" ], [ "us_phone_parser = EarleyParser(US_PHONE_GRAMMAR)", "_____no_output_____" ] ], [ [ "Then, use the `parse()` method to retrieve a list of possible derivation trees:", "_____no_output_____" ] ], [ [ "trees = us_phone_parser.parse(\"(555)987-6543\")\ntree = list(trees)[0]\ndisplay_tree(tree)", "_____no_output_____" ] ], [ [ "These derivation trees can then be used for test generation, notably for mutating and recombining existing inputs.", "_____no_output_____" ] ], [ [ "# ignore\nfrom ClassDiagram import display_class_hierarchy", "_____no_output_____" ], [ "# ignore\ndisplay_class_hierarchy([PEGParser, EarleyParser],\n public_methods=[\n Parser.parse,\n Parser.__init__,\n Parser.grammar,\n Parser.start_symbol\n ],\n types={\n 'DerivationTree': DerivationTree,\n 'Grammar': Grammar\n },\n project='fuzzingbook')", "_____no_output_____" ] ], [ [ "## Lessons Learned\n\n* Grammars can be used to generate derivation trees for a given string.\n* Parsing Expression Grammars are intuitive, and easy to implement, but require care to write.\n* Earley Parsers can parse arbitrary Context Free Grammars.\n", "_____no_output_____" ], [ "## Next Steps\n\n* Use parsed inputs to [recombine existing inputs](LangFuzzer.ipynb)", "_____no_output_____" ], [ "## Exercises", "_____no_output_____" ], [ "### Exercise 1: An Alternative Packrat\n\nIn the _Packrat_ parser, we showed how one could implement a simple _PEG_ parser. That parser kept track of the current location in the text using an index. Can you modify the parser so that it simply uses the current substring rather than tracking the index? That is, it should no longer have the `at` parameter.", "_____no_output_____" ], [ "**Solution.** Here is a possible solution:", "_____no_output_____" ] ], [ [ "class PackratParser(Parser):\n def parse_prefix(self, text):\n txt, res = self.unify_key(self.start_symbol(), text)\n return len(txt), [res]\n\n def parse(self, text):\n remain, res = self.parse_prefix(text)\n if remain:\n raise SyntaxError(\"at \" + res)\n return res\n\n def unify_rule(self, rule, text):\n results = []\n for token in rule:\n text, res = self.unify_key(token, text)\n if res is None:\n return text, None\n results.append(res)\n return text, results\n\n def unify_key(self, key, text):\n if key not in self.cgrammar:\n if text.startswith(key):\n return text[len(key):], (key, [])\n else:\n return text, None\n for rule in self.cgrammar[key]:\n text_, res = self.unify_rule(rule, text)\n if res:\n return (text_, (key, res))\n return text, None", "_____no_output_____" ], [ "mystring = \"1 + (2 * 3)\"\nfor tree in PackratParser(EXPR_GRAMMAR).parse(mystring):\n assert tree_to_string(tree) == mystring\n display_tree(tree)", "_____no_output_____" ] ], [ [ "### Exercise 2: More PEG Syntax\n\nThe _PEG_ syntax provides a few notational conveniences reminiscent of regular expressions. For example, it supports the following operators (letters `T` and `A` represents tokens that can be either terminal or nonterminal. `ε` is an empty string, and `/` is the ordered choice operator similar to the non-ordered choice operator `|`):\n\n* `T?` represents an optional greedy match of T and `A := T?` is equivalent to `A := T/ε`.\n* `T*` represents zero or more greedy matches of `T` and `A := T*` is equivalent to `A := T A/ε`.\n* `T+` represents one or more greedy matches – equivalent to `TT*`\n\nIf you look at the three notations above, each can be represented in the grammar in terms of basic syntax.\nRemember the exercise from [the chapter on grammars](Grammars.ipynb) that developed `define_ex_grammar()` that can represent grammars as Python code? extend `define_ex_grammar()` to `define_peg()` to support the above notational conveniences. The decorator should rewrite a given grammar that contains these notations to an equivalent grammar in basic syntax.", "_____no_output_____" ], [ "### Exercise 3: PEG Predicates\n\nBeyond these notational conveniences, it also supports two predicates that can provide a powerful lookahead facility that does not consume any input.\n\n* `T&A` represents an _And-predicate_ that matches `T` if `T` is matched, and it is immediately followed by `A`\n* `T!A` represents a _Not-predicate_ that matches `T` if `T` is matched, and it is *not* immediately followed by `A`\n\nImplement these predicates in our _PEG_ parser.", "_____no_output_____" ], [ "### Exercise 4: Earley Fill Chart\n\nIn the `Earley Parser`, `Column` class, we keep the states both as a `list` and also as a `dict` even though `dict` is ordered. Can you explain why?\n\n**Hint**: see the `fill_chart` method.", "_____no_output_____" ], [ "**Solution.** Python allows us to append to a list in flight, while a dict, eventhough it is ordered does not allow that facility.\n\nThat is, the following will work\n\n```python\nvalues = [1]\nfor v in values:\n values.append(v*2)\n```\n\nHowever, the following will result in an error\n```python\nvalues = {1:1}\nfor v in values:\n values[v*2] = v*2\n```\n\nIn the `fill_chart`, we make use of this facility to modify the set of states we are iterating on, on the fly.", "_____no_output_____" ], [ "### Exercise 5: Leo Parser\n\nOne of the problems with the original Earley parser is that while it can parse strings using arbitrary _Context Free Gramamrs_, its performance on right-recursive grammars is quadratic. That is, it takes $O(n^2)$ runtime and space for parsing with right-recursive grammars. For example, consider the parsing of the following string by two different grammars `LR_GRAMMAR` and `RR_GRAMMAR`.", "_____no_output_____" ] ], [ [ "mystring = 'aaaaaa'", "_____no_output_____" ] ], [ [ "To see the problem, we need to enable logging. Here is the logged version of parsing with the `LR_GRAMMAR`", "_____no_output_____" ] ], [ [ "result = EarleyParser(LR_GRAMMAR, log=True).parse(mystring)\nfor _ in result: pass # consume the generator so that we can see the logs", "_____no_output_____" ] ], [ [ "Compare that to the parsing of `RR_GRAMMAR` as seen below:", "_____no_output_____" ] ], [ [ "result = EarleyParser(RR_GRAMMAR, log=True).parse(mystring)\nfor _ in result: pass", "_____no_output_____" ] ], [ [ "As can be seen from the parsing log for each letter, the number of states with representation `<A>: a <A> ● (i, j)` increases at each stage, and these are simply a left over from the previous letter. They do not contribute anything more to the parse other than to simply complete these entries. However, they take up space, and require resources for inspection, contributing a factor of `n` in analysis.\n\nJoop Leo \\cite{Leo1991} found that this inefficiency can be avoided by detecting right recursion. The idea is that before starting the `completion` step, check whether the current item has a _deterministic reduction path_. If such a path exists, add a copy of the topmost element of the _deteministic reduction path_ to the current column, and return. If not, perform the original `completion` step.\n\n\n**Definition 2.1**: An item is said to be on the deterministic reduction path above $[A \\rightarrow \\gamma., i]$ if it is $[B \\rightarrow \\alpha A ., k]$ with $[B \\rightarrow \\alpha . A, k]$ being the only item in $ I_i $ with the dot in front of A, or if it is on the deterministic reduction path above $[B \\rightarrow \\alpha A ., k]$. An item on such a path is called *topmost* one if there is no item on the deterministic reduction path above it\\cite{Leo1991}.", "_____no_output_____" ], [ "Finding a _deterministic reduction path_ is as follows:\n\nGiven a complete state, represented by `<A> : seq_1 ● (s, e)` where `s` is the starting column for this rule, and `e` the current column, there is a _deterministic reduction path_ **above** it if two constraints are satisfied.\n\n1. There exist a *single* item in the form `<B> : seq_2 ● <A> (k, s)` in column `s`.\n2. That should be the *single* item in s with dot in front of `<A>`\n\nThe resulting item is of the form `<B> : seq_2 <A> ● (k, e)`, which is simply item from (1) advanced, and is considered above `<A>:.. (s, e)` in the deterministic reduction path.\nThe `seq_1` and `seq_2` are arbitrary symbol sequences.\n\nThis forms the following chain of links, with `<A>:.. (s_1, e)` being the child of `<B>:.. (s_2, e)` etc.", "_____no_output_____" ], [ "Here is one way to visualize the chain:\n```\n<C> : seq_3 <B> ● (s_3, e) \n | constraints satisfied by <C> : seq_3 ● <B> (s_3, s_2)\n <B> : seq_2 <A> ● (s_2, e) \n | constraints satisfied by <B> : seq_2 ● <A> (s_2, s_1)\n <A> : seq_1 ● (s_1, e)\n```", "_____no_output_____" ], [ "Essentially, what we want to do is to identify potential deterministic right recursion candidates, perform completion on them, and *throw away the result*. We do this until we reach the top. See Grune et al.~\\cite{grune2008parsing} for further information.", "_____no_output_____" ], [ "Note that the completions are in the same column (`e`), with each candidates with constraints satisfied \nin further and further earlier columns (as shown below):\n```\n<C> : seq_3 ● <B> (s_3, s_2) --> <C> : seq_3 <B> ● (s_3, e)\n |\n <B> : seq_2 ● <A> (s_2, s_1) --> <B> : seq_2 <A> ● (s_2, e) \n |\n <A> : seq_1 ● (s_1, e)\n```", "_____no_output_____" ], [ "Following this chain, the topmost item is the item `<C>:.. (s_3, e)` that does not have a parent. The topmost item needs to be saved is called a *transitive* item by Leo, and it is associated with the non-terminal symbol that started the lookup. The transitive item needs to be added to each column we inspect.", "_____no_output_____" ], [ "Here is the skeleton for the parser `LeoParser`.", "_____no_output_____" ] ], [ [ "class LeoParser(EarleyParser):\n def complete(self, col, state):\n return self.leo_complete(col, state)\n\n def leo_complete(self, col, state):\n detred = self.deterministic_reduction(state)\n if detred:\n col.add(detred.copy())\n else:\n self.earley_complete(col, state)\n\n def deterministic_reduction(self, state):\n raise NotImplementedError", "_____no_output_____" ] ], [ [ "Can you implement the `deterministic_reduction()` method to obtain the topmost element?", "_____no_output_____" ], [ "**Solution.** Here is a possible solution:", "_____no_output_____" ], [ "First, we update our `Column` class with the ability to add transitive items. Note that, while Leo asks the transitive to be added to the set $ I_k $ there is no actual requirement for the transitive states to be added to the `states` list. The transitive items are only intended for memoization and not for the `fill_chart()` method. Hence, we track them separately.", "_____no_output_____" ] ], [ [ "class Column(Column):\n def __init__(self, index, letter):\n self.index, self.letter = index, letter\n self.states, self._unique, self.transitives = [], {}, {}\n\n def add_transitive(self, key, state):\n assert key not in self.transitives\n self.transitives[key] = state\n return self.transitives[key]", "_____no_output_____" ] ], [ [ "Remember the picture we drew of the deterministic path?\n```\n <C> : seq_3 <B> ● (s_3, e) \n | constraints satisfied by <C> : seq_3 ● <B> (s_3, s_2)\n <B> : seq_2 <A> ● (s_2, e) \n | constraints satisfied by <B> : seq_2 ● <A> (s_2, s_1)\n <A> : seq_1 ● (s_1, e)\n```", "_____no_output_____" ], [ "We define a function `uniq_postdot()` that given the item `<A> := seq_1 ● (s_1, e)`, returns a `<B> : seq_2 ● <A> (s_2, s_1)` that satisfies the constraints mentioned in the above picture.", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def uniq_postdot(self, st_A):\n col_s1 = st_A.s_col\n parent_states = [\n s for s in col_s1.states if s.expr and s.at_dot() == st_A.name\n ]\n if len(parent_states) > 1:\n return None\n matching_st_B = [s for s in parent_states if s.dot == len(s.expr) - 1]\n return matching_st_B[0] if matching_st_B else None", "_____no_output_____" ], [ "lp = LeoParser(RR_GRAMMAR)\n[(str(s), str(lp.uniq_postdot(s))) for s in columns[-1].states]", "_____no_output_____" ] ], [ [ "We next define the function `get_top()` that is the core of deterministic reduction which gets the topmost state above the current state (`A`).", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def get_top(self, state_A):\n st_B_inc = self.uniq_postdot(state_A)\n if not st_B_inc:\n return None\n \n t_name = st_B_inc.name\n if t_name in st_B_inc.e_col.transitives:\n return st_B_inc.e_col.transitives[t_name]\n\n st_B = st_B_inc.advance()\n\n top = self.get_top(st_B) or st_B\n return st_B_inc.e_col.add_transitive(t_name, top)", "_____no_output_____" ] ], [ [ "Once we have the machinery in place, `deterministic_reduction()` itself is simply a wrapper to call `get_top()`", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def deterministic_reduction(self, state):\n return self.get_top(state)", "_____no_output_____" ], [ "lp = LeoParser(RR_GRAMMAR)\ncolumns = lp.chart_parse(mystring, lp.start_symbol())\n[(str(s), str(lp.get_top(s))) for s in columns[-1].states]", "_____no_output_____" ] ], [ [ "Now, both LR and RR grammars should work within $O(n)$ bounds.", "_____no_output_____" ] ], [ [ "result = LeoParser(RR_GRAMMAR, log=True).parse(mystring)\nfor _ in result: pass", "_____no_output_____" ] ], [ [ "We verify the Leo parser with a few more right recursive grammars.", "_____no_output_____" ] ], [ [ "RR_GRAMMAR2 = {\n '<start>': ['<A>'],\n '<A>': ['ab<A>', ''],\n}\nmystring2 = 'ababababab'", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR2, log=True).parse(mystring2)\nfor _ in result: pass", "_____no_output_____" ], [ "RR_GRAMMAR3 = {\n '<start>': ['c<A>'],\n '<A>': ['ab<A>', ''],\n}\nmystring3 = 'cababababab'", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR3, log=True).parse(mystring3)\nfor _ in result: pass", "_____no_output_____" ], [ "RR_GRAMMAR4 = {\n '<start>': ['<A>c'],\n '<A>': ['ab<A>', ''],\n}\nmystring4 = 'ababababc'", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR4, log=True).parse(mystring4)\nfor _ in result: pass", "_____no_output_____" ], [ "RR_GRAMMAR5 = {\n '<start>': ['<A>'],\n '<A>': ['ab<B>', ''],\n '<B>': ['<A>'],\n}\nmystring5 = 'abababab'", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR5, log=True).parse(mystring5)\nfor _ in result: pass", "_____no_output_____" ], [ "RR_GRAMMAR6 = {\n '<start>': ['<A>'],\n '<A>': ['a<B>', ''],\n '<B>': ['b<A>'],\n}\nmystring6 = 'abababab'", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR6, log=True).parse(mystring6)\nfor _ in result: pass", "_____no_output_____" ], [ "RR_GRAMMAR7 = {\n '<start>': ['<A>'],\n '<A>': ['a<A>', 'a'],\n}\nmystring7 = 'aaaaaaaa'", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR7, log=True).parse(mystring7)\nfor _ in result: pass", "_____no_output_____" ] ], [ [ "We verify that our parser works correctly on `LR_GRAMMAR` too.", "_____no_output_____" ] ], [ [ "result = LeoParser(LR_GRAMMAR, log=True).parse(mystring)\nfor _ in result: pass", "_____no_output_____" ] ], [ [ "__Advanced:__ We have fixed the complexity bounds. However, because we are saving only the topmost item of a right recursion, we need to fix our parser to be aware of our fix while extracting parse trees. Can you fix it?\n\n__Hint:__ Leo suggests simply transforming the Leo item sets to normal Earley sets, with the results from deterministic reduction expanded to their originals. For that, keep in mind the picture of constraint chain we drew earlier.", "_____no_output_____" ], [ "**Solution.** Here is a possible solution.", "_____no_output_____" ], [ "We first change the definition of `add_transitive()` so that results of deterministic reduction can be identified later.", "_____no_output_____" ] ], [ [ "class Column(Column):\n def add_transitive(self, key, state):\n assert key not in self.transitives\n self.transitives[key] = TState(state.name, state.expr, state.dot,\n state.s_col, state.e_col)\n return self.transitives[key]", "_____no_output_____" ] ], [ [ "We also need a `back()` method to create the constraints.", "_____no_output_____" ] ], [ [ "class State(State):\n def back(self):\n return TState(self.name, self.expr, self.dot - 1, self.s_col, self.e_col)", "_____no_output_____" ] ], [ [ "We update `copy()` to make `TState` items instead.", "_____no_output_____" ] ], [ [ "class TState(State):\n def copy(self):\n return TState(self.name, self.expr, self.dot, self.s_col, self.e_col)", "_____no_output_____" ] ], [ [ "We now modify the `LeoParser` to keep track of the chain of constrains that we mentioned earlier.", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def __init__(self, grammar, **kwargs):\n super().__init__(grammar, **kwargs)\n self._postdots = {}", "_____no_output_____" ] ], [ [ "Next, we update the `uniq_postdot()` so that it tracks the chain of links.", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def uniq_postdot(self, st_A):\n col_s1 = st_A.s_col\n parent_states = [\n s for s in col_s1.states if s.expr and s.at_dot() == st_A.name\n ]\n if len(parent_states) > 1:\n return None\n matching_st_B = [s for s in parent_states if s.dot == len(s.expr) - 1]\n if matching_st_B:\n self._postdots[matching_st_B[0]._t()] = st_A\n return matching_st_B[0]\n return None\n ", "_____no_output_____" ] ], [ [ "We next define a method `expand_tstate()` that, when given a `TState`, generates all the intermediate links that we threw away earlier for a given end column.", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def expand_tstate(self, state, e):\n if state._t() not in self._postdots:\n return\n c_C = self._postdots[state._t()]\n e.add(c_C.advance())\n self.expand_tstate(c_C.back(), e)", "_____no_output_____" ] ], [ [ "We define a `rearrange()` method to generate a reversed table where each column contains states that start at that column.", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def rearrange(self, table):\n f_table = [Column(c.index, c.letter) for c in table]\n for col in table:\n for s in col.states:\n f_table[s.s_col.index].states.append(s)\n return f_table", "_____no_output_____" ] ], [ [ "Here is the rearranged table. (Can you explain why the Column 0 has a large number of `<start>` items?)", "_____no_output_____" ] ], [ [ "ep = LeoParser(RR_GRAMMAR)\ncolumns = ep.chart_parse(mystring, ep.start_symbol())\nr_table = ep.rearrange(columns)\nfor col in r_table:\n print(col, \"\\n\")", "_____no_output_____" ] ], [ [ "We save the result of rearrange before going into `parse_forest()`.", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def parse(self, text):\n cursor, states = self.parse_prefix(text)\n start = next((s for s in states if s.finished()), None)\n if cursor < len(text) or not start:\n raise SyntaxError(\"at \" + repr(text[cursor:]))\n\n self.r_table = self.rearrange(self.table)\n forest = self.extract_trees(self.parse_forest(self.table, start))\n for tree in forest:\n yield self.prune_tree(tree)", "_____no_output_____" ] ], [ [ "Finally, during `parse_forest()`, we first check to see if it is a transitive state, and if it is, expand it to the original sequence of states using `traverse_constraints()`.", "_____no_output_____" ] ], [ [ "class LeoParser(LeoParser):\n def parse_forest(self, chart, state):\n if isinstance(state, TState):\n self.expand_tstate(state.back(), state.e_col)\n \n return super().parse_forest(chart, state)", "_____no_output_____" ] ], [ [ "This completes our implementation of `LeoParser`.", "_____no_output_____" ], [ "We check whether the previously defined right recursive grammars parse and return the correct parse trees.", "_____no_output_____" ] ], [ [ "result = LeoParser(RR_GRAMMAR).parse(mystring)\nfor tree in result:\n assert mystring == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR2).parse(mystring2)\nfor tree in result:\n assert mystring2 == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR3).parse(mystring3)\nfor tree in result:\n assert mystring3 == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR4).parse(mystring4)\nfor tree in result:\n assert mystring4 == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR5).parse(mystring5)\nfor tree in result:\n assert mystring5 == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR6).parse(mystring6)\nfor tree in result:\n assert mystring6 == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR7).parse(mystring7)\nfor tree in result:\n assert mystring7 == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(LR_GRAMMAR).parse(mystring)\nfor tree in result:\n assert mystring == tree_to_string(tree)", "_____no_output_____" ], [ "RR_GRAMMAR8 = {\n '<start>': ['<A>'],\n '<A>': ['a<A>', 'a']\n}\nmystring8 = 'aa'", "_____no_output_____" ], [ "RR_GRAMMAR9 = {\n '<start>': ['<A>'],\n '<A>': ['<B><A>', '<B>'],\n '<B>': ['b']\n}\nmystring9 = 'bbbbbbb'", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR8).parse(mystring8)\nfor tree in result:\n print(repr(tree_to_string(tree)))\n assert mystring8 == tree_to_string(tree)", "_____no_output_____" ], [ "result = LeoParser(RR_GRAMMAR9).parse(mystring9)\nfor tree in result:\n print(repr(tree_to_string(tree)))\n assert mystring9 == tree_to_string(tree)", "_____no_output_____" ] ], [ [ "### Exercise 6: Filtered Earley Parser", "_____no_output_____" ], [ "One of the problems with our Earley and Leo Parsers is that it can get stuck in infinite loops when parsing with grammars that contain token repetitions in alternatives. For example, consider the grammar below.", "_____no_output_____" ] ], [ [ "RECURSION_GRAMMAR: Grammar = {\n \"<start>\": [\"<A>\"],\n \"<A>\": [\"<A>\", \"<A>aa\", \"AA\", \"<B>\"],\n \"<B>\": [\"<C>\", \"<C>cc\", \"CC\"],\n \"<C>\": [\"<B>\", \"<B>bb\", \"BB\"]\n}", "_____no_output_____" ] ], [ [ "With this grammar, one can produce an infinite chain of derivations of `<A>`, (direct recursion) or an infinite chain of derivations of `<B> -> <C> -> <B> ...` (indirect recursion). The problem is that, our implementation can get stuck trying to derive one of these infinite chains. One possibility is to use the `LazyExtractor`. Another, is to simply avoid generating such chains.", "_____no_output_____" ] ], [ [ "from ExpectError import ExpectTimeout", "_____no_output_____" ], [ "with ExpectTimeout(1, print_traceback=False):\n mystring = 'AA'\n parser = LeoParser(RECURSION_GRAMMAR)\n tree, *_ = parser.parse(mystring)\n assert tree_to_string(tree) == mystring\n display_tree(tree)", "_____no_output_____" ] ], [ [ "Can you implement a solution such that any tree that contains such a chain is discarded?", "_____no_output_____" ], [ "**Solution.** Here is a possible solution.", "_____no_output_____" ] ], [ [ "class FilteredLeoParser(LeoParser):\n def forest(self, s, kind, seen, chart):\n return self.parse_forest(chart, s, seen) if kind == 'n' else (s, [])\n\n def parse_forest(self, chart, state, seen=None):\n if isinstance(state, TState):\n self.expand_tstate(state.back(), state.e_col)\n\n def was_seen(chain, s):\n if isinstance(s, str):\n return False\n if len(s.expr) > 1:\n return False\n return s in chain\n\n if len(state.expr) > 1: # things get reset if we have a non loop\n seen = set()\n elif seen is None: # initialization\n seen = {state}\n\n pathexprs = self.parse_paths(state.expr, chart, state.s_col.index,\n state.e_col.index) if state.expr else []\n return state.name, [[(s, k, seen | {s}, chart)\n for s, k in reversed(pathexpr)\n if not was_seen(seen, s)] for pathexpr in pathexprs]", "_____no_output_____" ] ], [ [ "With the `FilteredLeoParser`, we should be able to recover minimal parse trees in reasonable time.", "_____no_output_____" ] ], [ [ "mystring = 'AA'\nparser = FilteredLeoParser(RECURSION_GRAMMAR)\ntree, *_ = parser.parse(mystring)\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ], [ "mystring = 'AAaa'\nparser = FilteredLeoParser(RECURSION_GRAMMAR)\ntree, *_ = parser.parse(mystring)\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ], [ "mystring = 'AAaaaa'\nparser = FilteredLeoParser(RECURSION_GRAMMAR)\ntree, *_ = parser.parse(mystring)\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ], [ "mystring = 'CC'\nparser = FilteredLeoParser(RECURSION_GRAMMAR)\ntree, *_ = parser.parse(mystring)\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ], [ "mystring = 'BBcc'\nparser = FilteredLeoParser(RECURSION_GRAMMAR)\ntree, *_ = parser.parse(mystring)\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ], [ "mystring = 'BB'\nparser = FilteredLeoParser(RECURSION_GRAMMAR)\ntree, *_ = parser.parse(mystring)\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ], [ "mystring = 'BBccbb'\nparser = FilteredLeoParser(RECURSION_GRAMMAR)\ntree, *_ = parser.parse(mystring)\nassert tree_to_string(tree) == mystring\ndisplay_tree(tree)", "_____no_output_____" ] ], [ [ "As can be seen, we are able to recover minimal parse trees without hitting on infinite chains.", "_____no_output_____" ], [ "### Exercise 7: Iterative Earley Parser\n\nRecursive algorithms are quite handy in some cases but sometimes we might want to have iteration instead of recursion due to memory or speed problems. \n\nCan you implement an iterative version of the `EarleyParser`? \n\n__Hint:__ In general, you can use a stack to replace a recursive algorithm with an iterative one. An easy way to do this is pushing the parameters onto a stack instead of passing them to the recursive function.", "_____no_output_____" ], [ "**Solution.** Here is a possible solution.", "_____no_output_____" ], [ "First, we define `parse_paths()` that extract paths from a parsed expression, which is very similar to the original.", "_____no_output_____" ] ], [ [ "class IterativeEarleyParser(EarleyParser):\n def parse_paths(self, named_expr_, chart, frm, til_):\n return_paths = []\n path_build_stack = [(named_expr_, til_, [])]\n\n def iter_paths(path_prefix, path, start, k, e):\n x = path_prefix + [(path, k)]\n if not e:\n return_paths.extend([x] if start == frm else [])\n else:\n path_build_stack.append((e, start, x))\n\n while path_build_stack:\n named_expr, til, path_prefix = path_build_stack.pop()\n *expr, var = named_expr\n\n starts = None\n if var not in self.cgrammar:\n starts = ([(var, til - len(var), 't')]\n if til > 0 and chart[til].letter == var else [])\n else:\n starts = [(s, s.s_col.index, 'n') for s in chart[til].states\n if s.finished() and s.name == var]\n\n for s, start, k in starts:\n iter_paths(path_prefix, s, start, k, expr)\n\n return return_paths", "_____no_output_____" ] ], [ [ "Next we used these paths to recover the forest data structure using `parse_forest()`. Since `parse_forest()` does not recurse, we reuse the original definition. Next, we define `extract_a_tree()`", "_____no_output_____" ], [ "Now we are ready to extract trees from the forest using `extract_a_tree()`", "_____no_output_____" ] ], [ [ "class IterativeEarleyParser(IterativeEarleyParser):\n def choose_a_node_to_explore(self, node_paths, level_count):\n first, *rest = node_paths\n return first\n\n def extract_a_tree(self, forest_node_):\n start_node = (forest_node_[0], [])\n tree_build_stack = [(forest_node_, start_node[-1], 0)]\n\n while tree_build_stack:\n forest_node, tree, level_count = tree_build_stack.pop()\n name, paths = forest_node\n\n if not paths:\n tree.append((name, []))\n else:\n new_tree = []\n current_node = self.choose_a_node_to_explore(paths, level_count)\n for p in reversed(current_node):\n new_forest_node = self.forest(*p)\n tree_build_stack.append((new_forest_node, new_tree, level_count + 1))\n tree.append((name, new_tree))\n\n return start_node", "_____no_output_____" ] ], [ [ "For now, we simply extract the first tree found.", "_____no_output_____" ] ], [ [ "class IterativeEarleyParser(IterativeEarleyParser):\n def extract_trees(self, forest):\n yield self.extract_a_tree(forest)", "_____no_output_____" ] ], [ [ "Let's see if it works with some of the grammars we have seen so far.", "_____no_output_____" ] ], [ [ "test_cases: List[Tuple[Grammar, str]] = [\n (A1_GRAMMAR, '1-2-3+4-5'),\n (A2_GRAMMAR, '1+2'),\n (A3_GRAMMAR, '1+2+3-6=6-1-2-3'),\n (LR_GRAMMAR, 'aaaaa'),\n (RR_GRAMMAR, 'aa'),\n (DIRECTLY_SELF_REFERRING, 'select a from a'),\n (INDIRECTLY_SELF_REFERRING, 'select a from a'),\n (RECURSION_GRAMMAR, 'AA'),\n (RECURSION_GRAMMAR, 'AAaaaa'),\n (RECURSION_GRAMMAR, 'BBccbb')\n]\n\nfor i, (grammar, text) in enumerate(test_cases):\n print(i, text)\n tree, *_ = IterativeEarleyParser(grammar).parse(text)\n assert text == tree_to_string(tree)", "_____no_output_____" ] ], [ [ "As can be seen, our `IterativeEarleyParser` is able to handle recursive grammars. However, it can only extract the first tree found. What should one do to get all possible parses? What we can do, is to keep track of options to explore at each `choose_a_node_to_explore()`. Next, capture in the nodes explored in a tree data structure, adding new paths each time a new leaf is expanded. See the `TraceTree` datastructure in the [chapter on Concolic fuzzing](ConcolicFuzzer.ipynb) for an example.", "_____no_output_____" ], [ "### Exercise 8: First Set of a Nonterminal\n\nWe previously gave a way to extract a the `nullable` (epsilon) set, which is often used for parsing.\nAlong with `nullable`, parsing algorithms often use two other sets [`first` and `follow`](https://en.wikipedia.org/wiki/Canonical_LR_parser#FIRST_and_FOLLOW_sets).\nThe first set of a terminal symbol is itself, and the first set of a nonterminal is composed of terminal symbols that can come at the beginning of any derivation\nof that nonterminal. The first set of any nonterminal that can derive the empty string should contain `EPSILON`. For example, using our `A1_GRAMMAR`, the first set of both `<expr>` and `<start>` is `{0,1,2,3,4,5,6,7,8,9}`. The extraction first set for any self-recursive nonterminal is simple enough. One simply has to recursively compute the first set of the first element of its choice expressions. The computation of `first` set for a self-recursive nonterminal is tricky. One has to recursively compute the first set until one is sure that no more terminals can be added to the first set.\n\nCan you implement the `first` set using our `fixpoint()` decorator?", "_____no_output_____" ], [ "**Solution.** The first set of all terminals is the set containing just themselves. So we initialize that first. Then we update the first set with rules that derive empty strings.", "_____no_output_____" ] ], [ [ "def firstset(grammar, nullable):\n first = {i: {i} for i in terminals(grammar)}\n for k in grammar:\n first[k] = {EPSILON} if k in nullable else set()\n return firstset_((rules(grammar), first, nullable))[1]", "_____no_output_____" ] ], [ [ "Finally, we rely on the `fixpoint` to update the first set with the contents of the current first set until the first set stops changing.", "_____no_output_____" ] ], [ [ "def first_expr(expr, first, nullable):\n tokens = set()\n for token in expr:\n tokens |= first[token]\n if token not in nullable:\n break\n return tokens", "_____no_output_____" ], [ "@fixpoint\ndef firstset_(arg):\n (rules, first, epsilon) = arg\n for A, expression in rules:\n first[A] |= first_expr(expression, first, epsilon)\n return (rules, first, epsilon)", "_____no_output_____" ], [ "firstset(canonical(A1_GRAMMAR), EPSILON)", "_____no_output_____" ] ], [ [ "### Exercise 9: Follow Set of a Nonterminal\n\nThe follow set definition is similar to the first set. The follow set of a nonterminal is the set of terminals that can occur just after that nonterminal is used in any derivation. The follow set of the start symbol is `EOF`, and the follow set of any nonterminal is the super set of first sets of all symbols that come after it in any choice expression.\n\nFor example, the follow set of `<expr>` in `A1_GRAMMAR` is the set `{EOF, +, -}`.\n\nAs in the previous exercise, implement the `followset()` using the `fixpoint()` decorator.", "_____no_output_____" ], [ "**Solution.** The implementation of `followset()` is similar to `firstset()`. We first initialize the follow set with `EOF`, get the epsilon and first sets, and use the `fixpoint()` decorator to iteratively compute the follow set until nothing changes.", "_____no_output_____" ] ], [ [ "EOF = '\\0'", "_____no_output_____" ], [ "def followset(grammar, start):\n follow = {i: set() for i in grammar}\n follow[start] = {EOF}\n\n epsilon = nullable(grammar)\n first = firstset(grammar, epsilon)\n return followset_((grammar, epsilon, first, follow))[-1]", "_____no_output_____" ] ], [ [ "Given the current follow set, one can update the follow set as follows:", "_____no_output_____" ] ], [ [ "@fixpoint\ndef followset_(arg):\n grammar, epsilon, first, follow = arg\n for A, expression in rules(grammar):\n f_B = follow[A]\n for t in reversed(expression):\n if t in grammar:\n follow[t] |= f_B\n f_B = f_B | first[t] if t in epsilon else (first[t] - {EPSILON})\n\n return (grammar, epsilon, first, follow)", "_____no_output_____" ], [ "followset(canonical(A1_GRAMMAR), START_SYMBOL)", "_____no_output_____" ] ], [ [ "### Exercise 10: A LL(1) Parser\n\nAs we mentioned previously, there exist other kinds of parsers that operate left-to-right with right most derivation (*LR(k)*) or left-to-right with left most derivation (*LL(k)*) with _k_ signifying the amount of lookahead the parser is permitted to use.\n\nWhat should one do with the lookahead? That lookahead can be used to determine which rule to apply. In the case of an *LL(1)* parser, the rule to apply is determined by looking at the _first_ set of the different rules. We previously implemented `first_expr()` that takes a an expression, the set of `nullables`, and computes the first set of that rule.\n\nIf a rule can derive an empty set, then that rule may also be applicable if of sees the `follow()` set of the corresponding nonterminal.", "_____no_output_____" ], [ "#### Part 1: A LL(1) Parsing Table\n\nThe first part of this exercise is to implement the _parse table_ that describes what action to take for an *LL(1)* parser on seeing a terminal symbol on lookahead. The table should be in the form of a _dictionary_ such that the keys represent the nonterminal symbol, and the value should contain another dictionary with keys as terminal symbols and the particular rule to continue parsing as the value.\n\nLet us illustrate this table with an example. The `parse_table()` method populates a `self.table` data structure that should conform to the following requirements:", "_____no_output_____" ] ], [ [ "class LL1Parser(Parser):\n def parse_table(self):\n self.my_rules = rules(self.cgrammar)\n self.table = ... # fill in here to produce\n\n def rules(self):\n for i, rule in enumerate(self.my_rules):\n print(i, rule)\n\n def show_table(self):\n ts = list(sorted(terminals(self.cgrammar)))\n print('Rule Name\\t| %s' % ' | '.join(t for t in ts))\n for k in self.table:\n pr = self.table[k]\n actions = list(str(pr[t]) if t in pr else ' ' for t in ts)\n print('%s \\t| %s' % (k, ' | '.join(actions)))", "_____no_output_____" ] ], [ [ "On invocation of `LL1Parser(A2_GRAMMAR).show_table()`\nIt should result in the following table:", "_____no_output_____" ] ], [ [ "for i, r in enumerate(rules(canonical(A2_GRAMMAR))):\n print(\"%d\\t %s := %s\" % (i, r[0], r[1]))", "_____no_output_____" ] ], [ [ "|Rule Name || + | - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9|\n|-----------||---|---|---|---|---|---|---|---|---|---|---|--|\n|start \t|| | | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0|\n|expr \t|| | | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1|\n|expr_ \t|| 2 | 3 | | | | | | | | | | |\n|integer \t|| | | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5|\n|integer_ \t|| 7 | 7 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6|\n|digit \t|| | | 8 | 9 |10 |11 |12 |13 |14 |15 |16 |17|", "_____no_output_____" ], [ "**Solution.** We define `predict()` as we explained before. Then we use the predicted rules to populate the parse table.", "_____no_output_____" ] ], [ [ "class LL1Parser(LL1Parser):\n def predict(self, rulepair, first, follow, epsilon):\n A, rule = rulepair\n rf = first_expr(rule, first, epsilon)\n if nullable_expr(rule, epsilon):\n rf |= follow[A]\n return rf\n\n def parse_table(self):\n self.my_rules = rules(self.cgrammar)\n epsilon = nullable(self.cgrammar)\n first = firstset(self.cgrammar, epsilon)\n # inefficient, can combine the three.\n follow = followset(self.cgrammar, self.start_symbol())\n\n ptable = [(i, self.predict(rule, first, follow, epsilon))\n for i, rule in enumerate(self.my_rules)]\n\n parse_tbl = {k: {} for k in self.cgrammar}\n\n for i, pvals in ptable:\n (k, expr) = self.my_rules[i]\n parse_tbl[k].update({v: i for v in pvals})\n\n self.table = parse_tbl", "_____no_output_____" ], [ "ll1parser = LL1Parser(A2_GRAMMAR)\nll1parser.parse_table()\nll1parser.show_table()", "_____no_output_____" ] ], [ [ "#### Part 2: The Parser\n\nOnce we have the parse table, implementing the parser is as follows: Consider the first item from the sequence of tokens to parse, and seed the stack with the start symbol.\n\nWhile the stack is not empty, extract the first symbol from the stack, and if the symbol is a terminal, verify that the symbol matches the item from the input stream. If the symbol is a nonterminal, use the symbol and input item to lookup the next rule from the parse table. Insert the rule thus found to the top of the stack. Keep track of the expressions being parsed to build up the parse table.\n\nUse the parse table defined previously to implement the complete LL(1) parser.", "_____no_output_____" ], [ "**Solution.** Here is the complete parser:", "_____no_output_____" ] ], [ [ "class LL1Parser(LL1Parser):\n def parse_helper(self, stack, inplst):\n inp, *inplst = inplst\n exprs = []\n while stack:\n val, *stack = stack\n if isinstance(val, tuple):\n exprs.append(val)\n elif val not in self.cgrammar: # terminal\n assert val == inp\n exprs.append(val)\n inp, *inplst = inplst or [None]\n else:\n if inp is not None:\n i = self.table[val][inp]\n _, rhs = self.my_rules[i]\n stack = rhs + [(val, len(rhs))] + stack\n return self.linear_to_tree(exprs)\n\n def parse(self, inp):\n self.parse_table()\n k, _ = self.my_rules[0]\n stack = [k]\n return self.parse_helper(stack, inp)\n\n def linear_to_tree(self, arr):\n stack = []\n while arr:\n elt = arr.pop(0)\n if not isinstance(elt, tuple):\n stack.append((elt, []))\n else:\n # get the last n\n sym, n = elt\n elts = stack[-n:] if n > 0 else []\n stack = stack[0:len(stack) - n]\n stack.append((sym, elts))\n assert len(stack) == 1\n return stack[0]", "_____no_output_____" ], [ "ll1parser = LL1Parser(A2_GRAMMAR)\ntree = ll1parser.parse('1+2')\ndisplay_tree(tree)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "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", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "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", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
cb2693d25dd00fc60909893bd61b8fdea2931c8d
126,132
ipynb
Jupyter Notebook
Modulo_2/2_3_3_Extraccion_de_caracteristicas.ipynb
txusser/Master_IA_Sanidad
789523ecc626e8fc9dc2a79dd3e2fa10cbde577d
[ "MIT" ]
1
2022-01-26T21:37:06.000Z
2022-01-26T21:37:06.000Z
Modulo_2/2_3_3_Extraccion_de_caracteristicas.ipynb
txusser/Master_IA_Sanidad
789523ecc626e8fc9dc2a79dd3e2fa10cbde577d
[ "MIT" ]
null
null
null
Modulo_2/2_3_3_Extraccion_de_caracteristicas.ipynb
txusser/Master_IA_Sanidad
789523ecc626e8fc9dc2a79dd3e2fa10cbde577d
[ "MIT" ]
null
null
null
257.412245
46,406
0.90058
[ [ [ "<a href=\"https://colab.research.google.com/github/txusser/Master_IA_Sanidad/blob/main/Modulo_2/2_3_3_Extraccion_de_caracteristicas.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Extracción de características", "_____no_output_____" ], [ "## Análisis de la componente principal (PCA)", "_____no_output_____" ] ], [ [ "from sklearn.datasets import load_breast_cancer\nimport pandas as pd", "_____no_output_____" ], [ "# Cargamos los datos\ncancer_data = load_breast_cancer()\ndf = pd.DataFrame(data=cancer_data.data, columns=cancer_data.feature_names)\n# Y mostramos algunas variables por pantalla\nprint(df.head())\nprint(df.describe())", " mean radius mean texture ... worst symmetry worst fractal dimension\n0 17.99 10.38 ... 0.4601 0.11890\n1 20.57 17.77 ... 0.2750 0.08902\n2 19.69 21.25 ... 0.3613 0.08758\n3 11.42 20.38 ... 0.6638 0.17300\n4 20.29 14.34 ... 0.2364 0.07678\n\n[5 rows x 30 columns]\n mean radius mean texture ... worst symmetry worst fractal dimension\ncount 569.000000 569.000000 ... 569.000000 569.000000\nmean 14.127292 19.289649 ... 0.290076 0.083946\nstd 3.524049 4.301036 ... 0.061867 0.018061\nmin 6.981000 9.710000 ... 0.156500 0.055040\n25% 11.700000 16.170000 ... 0.250400 0.071460\n50% 13.370000 18.840000 ... 0.282200 0.080040\n75% 15.780000 21.800000 ... 0.317900 0.092080\nmax 28.110000 39.280000 ... 0.663800 0.207500\n\n[8 rows x 30 columns]\n" ], [ "from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n# Rescalamos los datos teniendo en cuenta la media y desviación estándar de cada variable\nscaler.fit(df.values)\nX_scaled = scaler.transform(df.values)\nprint(\"X_scaled:\\n\", X_scaled)", "X_scaled:\n [[ 1.09706398 -2.07333501 1.26993369 ... 2.29607613 2.75062224\n 1.93701461]\n [ 1.82982061 -0.35363241 1.68595471 ... 1.0870843 -0.24388967\n 0.28118999]\n [ 1.57988811 0.45618695 1.56650313 ... 1.95500035 1.152255\n 0.20139121]\n ...\n [ 0.70228425 2.0455738 0.67267578 ... 0.41406869 -1.10454895\n -0.31840916]\n [ 1.83834103 2.33645719 1.98252415 ... 2.28998549 1.91908301\n 2.21963528]\n [-1.80840125 1.22179204 -1.81438851 ... -1.74506282 -0.04813821\n -0.75120669]]\n" ], [ "# Vamos a utilizar las funciones de Sci-kit learn para análisis PCA\nfrom sklearn.decomposition import PCA\n# Para evaluar los resultados, utilizaremos el conjunto completo de variables \npca = PCA(n_components=30, random_state=2020)\npca.fit(X_scaled)\nX_pca = pca.transform(X_scaled)\n# La variable anterior almacena los valores de los (30) componentes principales\nprint(\"X_pca:\\n\", X_pca)\n\n# Puesto que seleccionamos el conjunto completo de variables las componenete \n# seleccionadas deben dar cuenta del 100% de la varianza en los datos\nprint(\"\\n => Varianza explicada por las componentes:\", sum(pca.explained_variance_ratio_ * 100))", "X_pca:\n [[ 9.19283683e+00 1.94858307e+00 -1.12316616e+00 ... -3.39144536e-02\n 4.56477199e-02 -4.71692081e-02]\n [ 2.38780180e+00 -3.76817174e+00 -5.29292687e-01 ... 3.26241827e-02\n -5.68742432e-03 -1.86787626e-03]\n [ 5.73389628e+00 -1.07517380e+00 -5.51747593e-01 ... 4.70258247e-02\n 3.14589659e-03 7.50534755e-04]\n ...\n [ 1.25617928e+00 -1.90229671e+00 5.62730526e-01 ... -2.57775589e-03\n 6.70621179e-03 3.77041667e-03]\n [ 1.03747941e+01 1.67201011e+00 -1.87702933e+00 ... -6.80863833e-02\n -8.41632764e-02 -2.37828222e-02]\n [-5.47524330e+00 -6.70636791e-01 1.49044308e+00 ... -9.51587894e-03\n -6.09131090e-02 -1.94755854e-02]]\n\n => Varianza explicada por las componentes: 100.00000000000001\n" ], [ "# Si representamos la varianza en función del número de componentes podemos observar\n# cuál es el mínimo número de componenetes que necesitaremos para explicar un cierto\n# porcentaje de la varianza\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.plot(np.cumsum(pca.explained_variance_ratio_ * 100))\nplt.xlabel(\"Número de componenetes\")\nplt.ylabel(\"Porcentaje de varianza explicado\")", "_____no_output_____" ], [ "# Vemos que con solo un tercio de las variables podemos explicar el 95% de la variaza\nn_var = np.cumsum(pca.explained_variance_ratio_ * 100)[9]\nprint(\"Varianza 10 primeras componenetes:\", n_var)", "Varianza 10 primeras componenetes: 95.15688143366667\n" ], [ "# Alternativamente, podemos construir el conjunto que acomode el 95% de la variaza \n# del siguiente modo\npca_95 = PCA(n_components=0.95, random_state=2020)\npca_95.fit(X_scaled)\nX_pca_95 = pca_95.transform(X_scaled)\n\n# Una buena práctica es visualizar la relación de las principales componentes\nimport seaborn as sns\nsns.scatterplot(X_pca_95[:, 0], X_pca_95[:, 1], hue=cancer_data.target)", "/usr/local/lib/python3.7/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n" ], [ "# Finalmente podemos crear un nuevo marco de datos con el resultado del análisis PCA\ncols = ['PCA' + str(i) for i in range(10)]\ndf_pca = pd.DataFrame(X_pca_95, columns=cols)\nprint(\"Datos (PCA - 95%):\\n\", df_pca)\n", "Datos (PCA - 95%):\n PCA0 PCA1 PCA2 ... PCA7 PCA8 PCA9\n0 9.192837 1.948583 -1.123166 ... -0.398407 -0.157118 -0.877402\n1 2.387802 -3.768172 -0.529293 ... 0.240988 -0.711905 1.106995\n2 5.733896 -1.075174 -0.551748 ... 0.097374 0.024066 0.454275\n3 7.122953 10.275589 -3.232790 ... 1.059565 -1.405440 -1.116975\n4 3.935302 -1.948072 1.389767 ... 0.636376 -0.263805 0.377704\n.. ... ... ... ... ... ... ...\n564 6.439315 -3.576817 2.459487 ... -0.035471 0.987929 0.256989\n565 3.793382 -3.584048 2.088476 ... -1.113360 -0.105207 -0.108632\n566 1.256179 -1.902297 0.562731 ... 0.341887 0.393917 0.520877\n567 10.374794 1.672010 -1.877029 ... -0.280239 -0.542035 -0.089296\n568 -5.475243 -0.670637 1.490443 ... 1.046354 0.374101 -0.047726\n\n[569 rows x 10 columns]\n[1.33049908e+01 5.70137460e+00 2.82291016e+00 1.98412752e+00\n 1.65163324e+00 1.20948224e+00 6.76408882e-01 4.77456255e-01\n 4.17628782e-01 3.51310875e-01 2.94433153e-01 2.61621161e-01\n 2.41782421e-01 1.57286149e-01 9.43006956e-02 8.00034045e-02\n 5.95036135e-02 5.27114222e-02 4.95647002e-02 3.12142606e-02\n 3.00256631e-02 2.74877113e-02 2.43836914e-02 1.80867940e-02\n 1.55085271e-02 8.19203712e-03 6.91261258e-03 1.59213600e-03\n 7.50121413e-04 1.33279057e-04]\n" ] ], [ [ "## Análisis de Componentes Independientes (ICA)", "_____no_output_____" ] ], [ [ "# Utilizaremos datos de fMRI para nuestro ejemplo con ICA\n# Para ello, comenzamos instalando la librería nilearn \n!python -m pip install nilearn", "_____no_output_____" ], [ "from nilearn import datasets\n# Descargamos un sujeto del estudio con RM funcional\ndataset = datasets.fetch_development_fmri(n_subjects=1)\nfile_name = dataset.func[0]\n\n# Preprocesado de la imagen\nfrom nilearn.input_data import NiftiMasker\n\n# Aplicamos una máscara para extraer el fondo de la imagen (vóxeles no cerebrales)\nmasker = NiftiMasker(smoothing_fwhm=8, memory='nilearn_cache', memory_level=1,\n mask_strategy='epi', standardize=True)\ndata_masked = masker.fit_transform(file_name)", "_____no_output_____" ], [ "from sklearn.decomposition import FastICA\nimport numpy as np\n# Seleccionamos 10 componentes \nica = FastICA(n_components=10, random_state=42)\ncomponents_masked = ica.fit_transform(data_masked.T).T\n# Aplicamos un corte (80% señal) en los datos después de normalizar según \n# la media y desviación estándar de los datos\ncomponents_masked -= components_masked.mean(axis=0)\ncomponents_masked /= components_masked.std(axis=0)\ncomponents_masked[np.abs(components_masked) < .8] = 0\n# Invertimos la transformación para recuperar la estructura 3D\ncomponent_img = masker.inverse_transform(components_masked)", "_____no_output_____" ], [ "# Finalmete, visualizamos el resultado de las operaciones de reducción\nfrom nilearn import image\nfrom nilearn.plotting import plot_stat_map, show\nmean_img = image.mean_img(func_filename)\nplot_stat_map(image.index_img(component_img, 0), mean_img)\nplot_stat_map(image.index_img(component_img, 1), mean_img)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cb26b1b4a8f9da3fb6688192a0f14bac1707776e
237,005
ipynb
Jupyter Notebook
code/minimum_corr_for_added_value.ipynb
eabarnes1010/course_objective_analysis
45ac32dbdcc52e409a29c5f8dae4bf8bb47aa9ba
[ "MIT" ]
3
2022-02-19T01:40:18.000Z
2022-03-11T16:37:54.000Z
code/minimum_corr_for_added_value.ipynb
eabarnes1010/course_objective_analysis
45ac32dbdcc52e409a29c5f8dae4bf8bb47aa9ba
[ "MIT" ]
null
null
null
code/minimum_corr_for_added_value.ipynb
eabarnes1010/course_objective_analysis
45ac32dbdcc52e409a29c5f8dae4bf8bb47aa9ba
[ "MIT" ]
1
2022-03-06T05:38:06.000Z
2022-03-06T05:38:06.000Z
459.312016
82,216
0.940609
[ [ [ "# Multi-linear regression: how many variables?\n[![Latest release](https://badgen.net/github/release/Naereen/Strapdown.js)](https://github.com/eabarnes1010/course_objective_analysis/tree/main/code)\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eabarnes1010/course_objective_analysis/blob/main/code/minimum_corr_for_added_value.ipynb)\n\n\nIf I have two predictors $x_1$ and $x_2$, under what circumstances is the second one useful for predicting $y$?", "_____no_output_____" ] ], [ [ "#.............................................\n# IMPORT STATEMENTS\n#.............................................\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport importlib\nfrom sklearn import linear_model\nfrom sklearn import metrics\n\nmpl.rcParams['figure.facecolor'] = 'white'\nmpl.rcParams['figure.dpi']= 150\ndpiFig = 300.\n\n\nnp.random.seed(300)", "_____no_output_____" ] ], [ [ "Let's start by creating two predictors, x1 and x2, and predictand y. x1 will be totally random, and the others will build upon that.", "_____no_output_____" ] ], [ [ "x1 = np.random.normal(0.,1.,size=100,)\nprint(np.shape(x1))", "(100,)\n" ] ], [ [ "Now we create x2.", "_____no_output_____" ] ], [ [ "a = 0.8\nb = np.sqrt(1. - a**2)\nx2 = []\n\n# create red-noise time series iteratively\nfor it in np.arange(0,100,1):\n x2.append(a*x1[it] + b*np.random.normal(size=1))\n\nx2 = np.asarray(x2)[:,0] \nprint(np.shape(x2))", "(100,)\n" ] ], [ [ "Now let's make $y$, which is composed of pieces of x1, x2 and noise.", "_____no_output_____" ] ], [ [ "a = 0.3\nb = np.sqrt(1. - a**2)\ny = []\n\n# create red-noise time series iteratively\nfor it in np.arange(0,100,1):\n y.append(a*x1[it] + (.05)*x2[it] + b*np.random.normal(size=1))\n\ny = np.asarray(y)[:,0] \nprint(np.shape(y))", "(100,)\n" ] ], [ [ "We can calculate the correlations of the predictors and predictands just to confirm that they all have some relationship with one another.", "_____no_output_____" ] ], [ [ "c12 = np.corrcoef(x1,x2)[0,1]\nc1y = np.corrcoef(x1,y)[0,1]\nc2y = np.corrcoef(y,x2)[0,1]\n\nprint('corr(x1,x2) = ' + str(np.round(c12,3)))\nprint('corr(x1,y) = ' + str(np.round(c1y,3)))\nprint('corr(x2,y) = ' + str(np.round(c2y,3)))", "corr(x1,x2) = 0.828\ncorr(x1,y) = 0.426\ncorr(x2,y) = 0.35\n" ] ], [ [ "### Theory", "_____no_output_____" ], [ "Based on theory, the minimum useful correlation of c2y is the following (from theory)...", "_____no_output_____" ] ], [ [ "minUseful = np.abs(c1y*c12)\nprint('minimum useful corr(x2,y) = ' + str(np.round(minUseful,3)))", "minimum useful corr(x2,y) = 0.353\n" ] ], [ [ "Furthermore, we can show analytically that the variance explained between using x1 versus x1 and x2 is practically identical since x2 doesn't appear to add additional information (i.e. |c2y| < minUseful).", "_____no_output_____" ] ], [ [ "#just using x1\nR2 = c1y**2\nprint('theory: y variance explained by x1 = ' + str(np.round(R2,3)))\n\n#using x1 and x2\nR2 = (c1y**2 + c2y**2 - 2*c1y*c2y*c12)/(1-c12**2)\nprint('theory: y variance explained by x1 & x2 = ' + str(np.round(R2,3)))", "theory: y variance explained by x1 = 0.181\ntheory: y variance explained by x1 & x2 = 0.181\n" ] ], [ [ "### Actual fits", "_____no_output_____" ], [ "We can confirm the theory now through some fun examples where we actually fit y using x1 and x2. In fact, we see that the fits indeed give us exactly what is expected by theory.", "_____no_output_____" ] ], [ [ "# only x1 predictor\nX = np.swapaxes([x1],1,0)\nY = np.swapaxes([y],1,0)\n\n# with sklearn\nregr = linear_model.LinearRegression()\nregr.fit(X, Y)\nR2_x1 = metrics.r2_score(Y,regr.predict(X))\nprint('y variance explained by x1 fit = ' + str(np.round(R2_x1,5)))\n\n#---------------------------------------------\n# both x1 and x2 predictors\nX = np.swapaxes([x1,x2],1,0)\nY = np.swapaxes([y],1,0)\n\n# with sklearn\nregr = linear_model.LinearRegression()\nregr.fit(X, Y)\nR2_x12 = metrics.r2_score(Y,regr.predict(X))\nprint('y variance explained by x1 & x2 fit = ' + str(np.round(R2_x12,5)))", "y variance explained by x1 fit = 0.18142\ny variance explained by x1 & x2 fit = 0.18144\n" ] ], [ [ "But what is going on here? Why is the $R^2$ slightly higher when we added x2? I thought theory said it shouldn't improve my variance explained _at all_?", "_____no_output_____" ], [ "## What about more predictors? (aka _overfitting_)", "_____no_output_____" ] ], [ [ "X = np.random.normal(0.,1.,size=(100,40))\nY = np.random.normal(0.,1.,size=100,)\n\nrval = []\nfor n in np.arange(0,np.shape(X)[1]):\n # with sklearn\n regr = linear_model.LinearRegression()\n regr.fit(X[:,0:n+1], Y)\n R2 = metrics.r2_score(Y,regr.predict(X[:,0:n+1]))\n rval.append(R2)\n \nplt.figure(figsize=(8,6))\nplt.plot(np.arange(0,np.shape(X)[1]),rval,'o-')\nplt.xlabel('number of random predictors')\nplt.ylabel('fraction variance explained')\nplt.title('Variance Explained')\nplt.show()", "_____no_output_____" ] ], [ [ "### Adjusted R$^2$", "_____no_output_____" ], [ "There is a great solution to this - known as the _adjusted $R^2$_. It is a measure of explained variance, but you are penalized (the number decreases) when too many predictors are used. The adjusted $R^2$ increases only if the new term improves the model more than would be expected by chance.", "_____no_output_____" ] ], [ [ "def adjustRsquared(r2,n,p):\n adjustR2 = 1 - (1-r2)*(n-1)/(n-p-1)\n return adjustR2", "_____no_output_____" ], [ "# only fitting with x1\np=1\nn = len(x1)\nadjustR2 = adjustRsquared(R2_x1,n,p)\nprint('fit with x1 only')\nprint(' R-squared = ' + str(np.round(R2_x1,3)) + ', Adjusted R-squared = ' + str(np.round(adjustR2,3)))\n\n# fitting with x1 and x2\np = 2\nn = len(x1)\nadjustR2 = adjustRsquared(R2_x12,n,p)\nprint('fit with x1 and x2 only')\nprint(' R-squared = ' + str(np.round(R2_x12,3)) + ', Adjusted R-squared = ' + str(np.round(adjustR2,3)))\n", "fit with x1 only\n R-squared = 0.181, Adjusted R-squared = 0.173\nfit with x1 and x2 only\n R-squared = 0.181, Adjusted R-squared = 0.165\n" ] ], [ [ "In our silly example above with 40 predictors, the adjusted R2 is the following...", "_____no_output_____" ] ], [ [ "n = len(Y)\np = np.arange(0,np.shape(X)[1]) + 1\nadjustR2 = adjustRsquared(np.asarray(rval),n,p)\n\nplt.figure(figsize=(8,6))\nplt.axhline(y=0,color='gray')\nplt.plot(np.arange(1,np.shape(X)[1]+1),rval,'o-', label='R2')\nplt.plot(np.arange(1,np.shape(X)[1]+1),adjustR2,'o-',color='red', label='adjusted R2')\nplt.xlabel('number of predictors')\nplt.ylabel('fraction variance explained')\nplt.legend()\nplt.title('Adjusted R-squared')\nplt.show()", "_____no_output_____" ] ], [ [ "### Significance of Adjusted $R^2$\n\nTo end, let's compute the adjusted R-squared many times for a lot of random data to get a feeling of the spread of possible adjusted R-squared values by chance alone.", "_____no_output_____" ] ], [ [ "rVec = np.zeros(shape=(40,500))\nfor nvar in (np.arange(1,np.shape(rVec)[0]+1)):\n r = []\n for n in np.arange(0,500):\n X = np.random.normal(0.,1.,size=(100,nvar))\n Y = np.random.normal(0.,1.,size=100,)\n\n # with sklearn\n regr = linear_model.LinearRegression()\n regr.fit(X[:,0:n+1], Y)\n R2 = metrics.r2_score(Y,regr.predict(X[:,0:n+1]))\n r.append(R2)\n\n rVec[nvar-1,:] = adjustRsquared(np.asarray(r),100,nvar)", "_____no_output_____" ], [ "pTop = np.percentile(rVec,97.5,axis=1)\npBot = np.percentile(rVec,2.5,axis=1)\n\nplt.figure(figsize=(8,6))\nplt.axhline(y=0,color='gray')\nplt.plot(np.arange(1,np.shape(X)[1]+1),adjustR2,'o-',color='red', label='adjusted R2')\nplt.fill_between(np.arange(1,len(p)+1), pBot, pTop,color='lightgray', label='confidence bounds')\n\nplt.xlabel('number of predictors')\nplt.ylabel('fraction variance explained')\nplt.legend()\nplt.title('Adjusted R2')\nplt.ylim(-1,1)\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb26bbb589d7930fcf9e0ca639e328d39a4b1982
38,598
ipynb
Jupyter Notebook
tests/tf/CycleGAN-keras.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
1
2019-05-10T09:16:23.000Z
2019-05-10T09:16:23.000Z
tests/tf/CycleGAN-keras.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
null
null
null
tests/tf/CycleGAN-keras.ipynb
gopala-kr/ds-notebooks
bc35430ecdd851f2ceab8f2437eec4d77cb59423
[ "MIT" ]
1
2019-05-10T09:17:28.000Z
2019-05-10T09:17:28.000Z
46.280576
818
0.571454
[ [ [ "## Keras implementation of https://phillipi.github.io/pix2pix", "_____no_output_____" ] ], [ [ "import os\nos.environ['KERAS_BACKEND']='theano' # can choose theano, tensorflow, cntk\nos.environ['THEANO_FLAGS']='floatX=float32,device=cuda,optimizer=fast_run,dnn.library_path=/usr/lib'\n#os.environ['THEANO_FLAGS']='floatX=float32,device=cuda,optimizer=fast_compile,dnn.library_path=/usr/lib'", "_____no_output_____" ], [ "import keras.backend as K\nif os.environ['KERAS_BACKEND'] =='theano':\n channel_axis=1\n K.set_image_data_format('channels_first')\n channel_first = True\nelse:\n K.set_image_data_format('channels_last')\n channel_axis=-1\n channel_first = False", "Using Theano backend.\nWARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\nERROR (theano.gpuarray): pygpu was configured but could not be imported or is too old (version 0.7 or higher required)\nNoneType: None\n" ], [ "from keras.models import Sequential, Model\nfrom keras.layers import Conv2D, ZeroPadding2D, BatchNormalization, Input, Dropout\nfrom keras.layers import Conv2DTranspose, Reshape, Activation, Cropping2D, Flatten\nfrom keras.layers import Concatenate\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.activations import relu\nfrom keras.initializers import RandomNormal", "_____no_output_____" ], [ "# Weights initializations\n# bias are initailized as 0\ndef __conv_init(a):\n print(\"conv_init\", a)\n k = RandomNormal(0, 0.02)(a) # for convolution kernel\n k.conv_weight = True \n return k\nconv_init = RandomNormal(0, 0.02)\ngamma_init = RandomNormal(1., 0.02) # for batch normalization\n", "_____no_output_____" ], [ "# HACK speed up theano\nif K._BACKEND == 'theano':\n import keras.backend.theano_backend as theano_backend\n def _preprocess_conv2d_kernel(kernel, data_format):\n #return kernel\n if hasattr(kernel, \"original\"):\n print(\"use original\")\n return kernel.original\n elif hasattr(kernel, '_keras_shape'):\n s = kernel._keras_shape\n print(\"use reshape\",s)\n kernel = kernel.reshape((s[3], s[2],s[0], s[1]))\n else:\n kernel = kernel.dimshuffle((3, 2, 0, 1))\n return kernel\n theano_backend._preprocess_conv2d_kernel = _preprocess_conv2d_kernel", "_____no_output_____" ], [ "# Basic discriminator\ndef conv2d(f, *a, **k):\n return Conv2D(f, kernel_initializer = conv_init, *a, **k)\ndef batchnorm():\n return BatchNormalization(momentum=0.9, axis=channel_axis, epsilon=1.01e-5,\n gamma_initializer = gamma_init)\ndef BASIC_D(nc_in, ndf, max_layers=3, use_sigmoid=True):\n \"\"\"DCGAN_D(nc, ndf, max_layers=3)\n nc: channels\n ndf: filters of the first layer\n max_layers: max hidden layers\n \"\"\" \n if channel_first:\n input_a = Input(shape=(nc_in, None, None))\n else:\n input_a = Input(shape=(None, None, nc_in))\n _ = input_a\n _ = conv2d(ndf, kernel_size=4, strides=2, padding=\"same\", name = 'First') (_)\n _ = LeakyReLU(alpha=0.2)(_)\n \n for layer in range(1, max_layers): \n out_feat = ndf * min(2**layer, 8)\n _ = conv2d(out_feat, kernel_size=4, strides=2, padding=\"same\", \n use_bias=False, name = 'pyramid.{0}'.format(layer) \n ) (_)\n _ = batchnorm()(_, training=1) \n _ = LeakyReLU(alpha=0.2)(_)\n \n out_feat = ndf*min(2**max_layers, 8)\n _ = ZeroPadding2D(1)(_)\n _ = conv2d(out_feat, kernel_size=4, use_bias=False, name = 'pyramid_last') (_)\n _ = batchnorm()(_, training=1)\n _ = LeakyReLU(alpha=0.2)(_)\n \n # final layer\n _ = ZeroPadding2D(1)(_)\n _ = conv2d(1, kernel_size=4, name = 'final'.format(out_feat, 1), \n activation = \"sigmoid\" if use_sigmoid else None) (_) \n return Model(inputs=[input_a], outputs=_)", "_____no_output_____" ], [ "def UNET_G(isize, nc_in=3, nc_out=3, ngf=64, fixed_input_size=True): \n max_nf = 8*ngf \n def block(x, s, nf_in, use_batchnorm=True, nf_out=None, nf_next=None):\n # print(\"block\",x,s,nf_in, use_batchnorm, nf_out, nf_next)\n assert s>=2 and s%2==0\n if nf_next is None:\n nf_next = min(nf_in*2, max_nf)\n if nf_out is None:\n nf_out = nf_in\n x = conv2d(nf_next, kernel_size=4, strides=2, use_bias=(not (use_batchnorm and s>2)),\n padding=\"same\", name = 'conv_{0}'.format(s)) (x)\n if s>2:\n if use_batchnorm:\n x = batchnorm()(x, training=1)\n x2 = LeakyReLU(alpha=0.2)(x)\n x2 = block(x2, s//2, nf_next)\n x = Concatenate(axis=channel_axis)([x, x2]) \n x = Activation(\"relu\")(x)\n x = Conv2DTranspose(nf_out, kernel_size=4, strides=2, use_bias=not use_batchnorm,\n kernel_initializer = conv_init, \n name = 'convt.{0}'.format(s))(x) \n x = Cropping2D(1)(x)\n if use_batchnorm:\n x = batchnorm()(x, training=1)\n if s <=8:\n x = Dropout(0.5)(x, training=1)\n return x\n \n s = isize if fixed_input_size else None\n if channel_first:\n _ = inputs = Input(shape=(nc_in, s, s))\n else:\n _ = inputs = Input(shape=(s, s, nc_in)) \n _ = block(_, isize, nc_in, False, nf_out=nc_out, nf_next=ngf)\n _ = Activation('tanh')(_)\n return Model(inputs=inputs, outputs=[_])", "_____no_output_____" ], [ "nc_in = 3\nnc_out = 3\nngf = 64\nndf = 64\nuse_lsgan = True\nλ = 10 if use_lsgan else 100\n\nloadSize = 143\nimageSize = 128\nbatchSize = 1\nlrD = 2e-4\nlrG = 2e-4", "_____no_output_____" ], [ "netDA = BASIC_D(nc_in, ndf, use_sigmoid = not use_lsgan)\nnetDB = BASIC_D(nc_out, ndf, use_sigmoid = not use_lsgan)\nnetDA.summary()\n", "use reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 1)\nuse reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 1)\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) (None, 3, None, None) 0 \n_________________________________________________________________\nFirst (Conv2D) (None, 64, None, None) 3136 \n_________________________________________________________________\nleaky_re_lu_1 (LeakyReLU) (None, 64, None, None) 0 \n_________________________________________________________________\npyramid.1 (Conv2D) (None, 128, None, None) 131072 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 128, None, None) 512 \n_________________________________________________________________\nleaky_re_lu_2 (LeakyReLU) (None, 128, None, None) 0 \n_________________________________________________________________\npyramid.2 (Conv2D) (None, 256, None, None) 524288 \n_________________________________________________________________\nbatch_normalization_2 (Batch (None, 256, None, None) 1024 \n_________________________________________________________________\nleaky_re_lu_3 (LeakyReLU) (None, 256, None, None) 0 \n_________________________________________________________________\nzero_padding2d_1 (ZeroPaddin (None, 256, None, None) 0 \n_________________________________________________________________\npyramid_last (Conv2D) (None, 512, None, None) 2097152 \n_________________________________________________________________\nbatch_normalization_3 (Batch (None, 512, None, None) 2048 \n_________________________________________________________________\nleaky_re_lu_4 (LeakyReLU) (None, 512, None, None) 0 \n_________________________________________________________________\nzero_padding2d_2 (ZeroPaddin (None, 512, None, None) 0 \n_________________________________________________________________\nfinal (Conv2D) (None, 1, None, None) 8193 \n=================================================================\nTotal params: 2,767,425\nTrainable params: 2,765,633\nNon-trainable params: 1,792\n_________________________________________________________________\n" ], [ "from IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\n\n\nnetGB = UNET_G(imageSize, nc_in, nc_out, ngf)\nnetGA = UNET_G(imageSize, nc_out, nc_in, ngf)\n#SVG(model_to_dot(netG, show_shapes=True).create(prog='dot', format='svg'))\nnetGA.summary()\n", "use reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 256, 1024)\nuse reshape (4, 4, 128, 512)\nuse reshape (4, 4, 64, 256)\nuse reshape (4, 4, 3, 128)\nuse reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 256, 1024)\nuse reshape (4, 4, 128, 512)\nuse reshape (4, 4, 64, 256)\nuse reshape (4, 4, 3, 128)\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_4 (InputLayer) (None, 3, 128, 128) 0 \n__________________________________________________________________________________________________\nconv_128 (Conv2D) (None, 64, 64, 64) 3136 input_4[0][0] \n__________________________________________________________________________________________________\nleaky_re_lu_15 (LeakyReLU) (None, 64, 64, 64) 0 conv_128[0][0] \n__________________________________________________________________________________________________\nconv_64 (Conv2D) (None, 128, 32, 32) 131072 leaky_re_lu_15[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_18 (BatchNo (None, 128, 32, 32) 512 conv_64[0][0] \n__________________________________________________________________________________________________\nleaky_re_lu_16 (LeakyReLU) (None, 128, 32, 32) 0 batch_normalization_18[0][0] \n__________________________________________________________________________________________________\nconv_32 (Conv2D) (None, 256, 16, 16) 524288 leaky_re_lu_16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_19 (BatchNo (None, 256, 16, 16) 1024 conv_32[0][0] \n__________________________________________________________________________________________________\nleaky_re_lu_17 (LeakyReLU) (None, 256, 16, 16) 0 batch_normalization_19[0][0] \n__________________________________________________________________________________________________\nconv_16 (Conv2D) (None, 512, 8, 8) 2097152 leaky_re_lu_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_20 (BatchNo (None, 512, 8, 8) 2048 conv_16[0][0] \n__________________________________________________________________________________________________\nleaky_re_lu_18 (LeakyReLU) (None, 512, 8, 8) 0 batch_normalization_20[0][0] \n__________________________________________________________________________________________________\nconv_8 (Conv2D) (None, 512, 4, 4) 4194304 leaky_re_lu_18[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_21 (BatchNo (None, 512, 4, 4) 2048 conv_8[0][0] \n__________________________________________________________________________________________________\nleaky_re_lu_19 (LeakyReLU) (None, 512, 4, 4) 0 batch_normalization_21[0][0] \n__________________________________________________________________________________________________\nconv_4 (Conv2D) (None, 512, 2, 2) 4194304 leaky_re_lu_19[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_22 (BatchNo (None, 512, 2, 2) 2048 conv_4[0][0] \n__________________________________________________________________________________________________\nleaky_re_lu_20 (LeakyReLU) (None, 512, 2, 2) 0 batch_normalization_22[0][0] \n__________________________________________________________________________________________________\nconv_2 (Conv2D) (None, 512, 1, 1) 4194816 leaky_re_lu_20[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 512, 1, 1) 0 conv_2[0][0] \n__________________________________________________________________________________________________\nconvt.2 (Conv2DTranspose) (None, 512, 4, 4) 4194304 activation_9[0][0] \n__________________________________________________________________________________________________\ncropping2d_8 (Cropping2D) (None, 512, 2, 2) 0 convt.2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_23 (BatchNo (None, 512, 2, 2) 2048 cropping2d_8[0][0] \n__________________________________________________________________________________________________\ndropout_4 (Dropout) (None, 512, 2, 2) 0 batch_normalization_23[0][0] \n__________________________________________________________________________________________________\nconcatenate_7 (Concatenate) (None, 1024, 2, 2) 0 batch_normalization_22[0][0] \n dropout_4[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 1024, 2, 2) 0 concatenate_7[0][0] \n__________________________________________________________________________________________________\nconvt.4 (Conv2DTranspose) (None, 512, 6, 6) 8388608 activation_10[0][0] \n__________________________________________________________________________________________________\ncropping2d_9 (Cropping2D) (None, 512, 4, 4) 0 convt.4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_24 (BatchNo (None, 512, 4, 4) 2048 cropping2d_9[0][0] \n__________________________________________________________________________________________________\ndropout_5 (Dropout) (None, 512, 4, 4) 0 batch_normalization_24[0][0] \n__________________________________________________________________________________________________\nconcatenate_8 (Concatenate) (None, 1024, 4, 4) 0 batch_normalization_21[0][0] \n dropout_5[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 1024, 4, 4) 0 concatenate_8[0][0] \n__________________________________________________________________________________________________\nconvt.8 (Conv2DTranspose) (None, 512, 10, 10) 8388608 activation_11[0][0] \n__________________________________________________________________________________________________\ncropping2d_10 (Cropping2D) (None, 512, 8, 8) 0 convt.8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_25 (BatchNo (None, 512, 8, 8) 2048 cropping2d_10[0][0] \n__________________________________________________________________________________________________\ndropout_6 (Dropout) (None, 512, 8, 8) 0 batch_normalization_25[0][0] \n__________________________________________________________________________________________________\nconcatenate_9 (Concatenate) (None, 1024, 8, 8) 0 batch_normalization_20[0][0] \n dropout_6[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 1024, 8, 8) 0 concatenate_9[0][0] \n__________________________________________________________________________________________________\nconvt.16 (Conv2DTranspose) (None, 256, 18, 18) 4194304 activation_12[0][0] \n__________________________________________________________________________________________________\ncropping2d_11 (Cropping2D) (None, 256, 16, 16) 0 convt.16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_26 (BatchNo (None, 256, 16, 16) 1024 cropping2d_11[0][0] \n__________________________________________________________________________________________________\nconcatenate_10 (Concatenate) (None, 512, 16, 16) 0 batch_normalization_19[0][0] \n batch_normalization_26[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 512, 16, 16) 0 concatenate_10[0][0] \n__________________________________________________________________________________________________\nconvt.32 (Conv2DTranspose) (None, 128, 34, 34) 1048576 activation_13[0][0] \n__________________________________________________________________________________________________\ncropping2d_12 (Cropping2D) (None, 128, 32, 32) 0 convt.32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_27 (BatchNo (None, 128, 32, 32) 512 cropping2d_12[0][0] \n__________________________________________________________________________________________________\nconcatenate_11 (Concatenate) (None, 256, 32, 32) 0 batch_normalization_18[0][0] \n batch_normalization_27[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 256, 32, 32) 0 concatenate_11[0][0] \n__________________________________________________________________________________________________\nconvt.64 (Conv2DTranspose) (None, 64, 66, 66) 262144 activation_14[0][0] \n__________________________________________________________________________________________________\ncropping2d_13 (Cropping2D) (None, 64, 64, 64) 0 convt.64[0][0] \n__________________________________________________________________________________________________\n" ], [ "from keras.optimizers import RMSprop, SGD, Adam", "_____no_output_____" ], [ "if use_lsgan:\n loss_fn = lambda output, target : K.mean(K.abs(K.square(output-target)))\nelse:\n loss_fn = lambda output, target : -K.mean(K.log(output+1e-12)*target+K.log(1-output+1e-12)*(1-target))\n\ndef cycle_variables(netG1, netG2):\n real_input = netG1.inputs[0]\n fake_output = netG1.outputs[0]\n rec_input = netG2([fake_output])\n fn_generate = K.function([real_input], [fake_output, rec_input])\n return real_input, fake_output, rec_input, fn_generate\n\nreal_A, fake_B, rec_A, cycleA_generate = cycle_variables(netGB, netGA)\nreal_B, fake_A, rec_B, cycleB_generate = cycle_variables(netGA, netGB)", "use reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 256, 1024)\nuse reshape (4, 4, 128, 512)\nuse reshape (4, 4, 64, 256)\nuse reshape (4, 4, 3, 128)\nuse reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 512)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 512, 1024)\nuse reshape (4, 4, 256, 1024)\nuse reshape (4, 4, 128, 512)\nuse reshape (4, 4, 64, 256)\nuse reshape (4, 4, 3, 128)\n" ], [ "def D_loss(netD, real, fake, rec):\n output_real = netD([real])\n output_fake = netD([fake])\n loss_D_real = loss_fn(output_real, K.ones_like(output_real))\n loss_D_fake = loss_fn(output_fake, K.zeros_like(output_fake))\n loss_G = loss_fn(output_fake, K.ones_like(output_fake))\n loss_D = loss_D_real+loss_D_fake\n loss_cyc = K.mean(K.abs(rec-real))\n return loss_D, loss_G, loss_cyc\n\nloss_DA, loss_GA, loss_cycA = D_loss(netDA, real_A, fake_A, rec_A)\nloss_DB, loss_GB, loss_cycB = D_loss(netDB, real_B, fake_B, rec_B)\nloss_cyc = loss_cycA+loss_cycB", "use reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 1)\nuse reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 1)\nuse reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 1)\nuse reshape (4, 4, 3, 64)\nuse reshape (4, 4, 64, 128)\nuse reshape (4, 4, 128, 256)\nuse reshape (4, 4, 256, 512)\nuse reshape (4, 4, 512, 1)\n" ], [ "loss_G = loss_GA+loss_GB+λ*loss_cyc\nloss_D = loss_DA+loss_DB\n\nweightsD = netDA.trainable_weights + netDB.trainable_weights\nweightsG = netGA.trainable_weights + netGB.trainable_weights\n\ntraining_updates = Adam(lr=lrD, beta_1=0.5).get_updates(weightsD,[],loss_D)\nnetD_train = K.function([real_A, real_B],[loss_DA/2, loss_DB/2], training_updates)\ntraining_updates = Adam(lr=lrG, beta_1=0.5).get_updates(weightsG,[], loss_G)\nnetG_train = K.function([real_A, real_B], [loss_GA, loss_GB, loss_cyc], training_updates)", "_____no_output_____" ], [ "from PIL import Image\nimport numpy as np\nimport glob\nfrom random import randint, shuffle\n\ndef load_data(file_pattern):\n return glob.glob(file_pattern)\n\ndef read_image(fn):\n im = Image.open(fn).convert('RGB')\n im = im.resize( (loadSize, loadSize), Image.BILINEAR )\n arr = np.array(im)/255*2-1\n w1,w2 = (loadSize-imageSize)//2,(loadSize+imageSize)//2\n h1,h2 = w1,w2\n img = arr[h1:h2, w1:w2, :]\n if randint(0,1):\n img=img[:,::-1]\n if channel_first: \n img = np.moveaxis(img, 2, 0)\n return img\n\n#data = \"edges2shoes\"\ndata = \"horse2zebra\"\ntrain_A = load_data('CycleGAN/{}/trainA/*.jpg'.format(data))\ntrain_B = load_data('CycleGAN/{}/trainB/*.jpg'.format(data))\n\nassert len(train_A) and len(train_B)", "_____no_output_____" ], [ "def minibatch(data, batchsize):\n length = len(data)\n epoch = i = 0\n tmpsize = None \n while True:\n size = tmpsize if tmpsize else batchsize\n if i+size > length:\n shuffle(data)\n i = 0\n epoch+=1 \n rtn = [read_image(data[j]) for j in range(i,i+size)]\n i+=size\n tmpsize = yield epoch, np.float32(rtn) \n\ndef minibatchAB(dataA, dataB, batchsize):\n batchA=minibatch(dataA, batchsize)\n batchB=minibatch(dataB, batchsize)\n tmpsize = None \n while True: \n ep1, A = batchA.send(tmpsize)\n ep2, B = batchB.send(tmpsize)\n tmpsize = yield max(ep1, ep2), A, B", "_____no_output_____" ], [ "from IPython.display import display\ndef showX(X, rows=1):\n assert X.shape[0]%rows == 0\n int_X = ( (X+1)/2*255).clip(0,255).astype('uint8')\n if channel_first:\n int_X = np.moveaxis(int_X.reshape(-1,3,imageSize,imageSize), 1, 3)\n else:\n int_X = int_X.reshape(-1,imageSize,imageSize, 3)\n int_X = int_X.reshape(rows, -1, imageSize, imageSize,3).swapaxes(1,2).reshape(rows*imageSize,-1, 3)\n display(Image.fromarray(int_X))", "_____no_output_____" ], [ "train_batch = minibatchAB(train_A, train_B, 6)\n\n_, A, B = next(train_batch)\nshowX(A)\nshowX(B)\ndel train_batch, A, B", "_____no_output_____" ], [ "def showG(A,B):\n assert A.shape==B.shape\n def G(fn_generate, X):\n r = np.array([fn_generate([X[i:i+1]]) for i in range(X.shape[0])])\n return r.swapaxes(0,1)[:,:,0] \n rA = G(cycleA_generate, A)\n rB = G(cycleB_generate, B)\n arr = np.concatenate([A,B,rA[0],rB[0],rA[1],rB[1]])\n showX(arr, 3)", "_____no_output_____" ], [ "import time\nfrom IPython.display import clear_output\nt0 = time.time()\nniter = 150\ngen_iterations = 0\nepoch = 0\nerrCyc_sum = errGA_sum = errGB_sum = errDA_sum = errDB_sum = 0\n\ndisplay_iters = 50\n#val_batch = minibatch(valAB, 6, direction)\ntrain_batch = minibatchAB(train_A, train_B, batchSize)\n\nwhile epoch < niter: \n epoch, A, B = next(train_batch) \n errDA, errDB = netD_train([A, B])\n errDA_sum +=errDA\n errDB_sum +=errDB\n\n # epoch, trainA, trainB = next(train_batch)\n errGA, errGB, errCyc = netG_train([A, B])\n errGA_sum += errGA\n errGB_sum += errGB\n errCyc_sum += errCyc\n gen_iterations+=1\n if gen_iterations%display_iters==0:\n #if gen_iterations%(5*display_iters)==0:\n clear_output()\n print('[%d/%d][%d] Loss_D: %f %f Loss_G: %f %f loss_cyc %f'\n % (epoch, niter, gen_iterations, errDA_sum/display_iters, errDB_sum/display_iters,\n errGA_sum/display_iters, errGB_sum/display_iters, \n errCyc_sum/display_iters), time.time()-t0)\n _, A, B = train_batch.send(4)\n showG(A,B) \n errCyc_sum = errGA_sum = errGB_sum = errDA_sum = errDB_sum = 0", "_____no_output_____" ] ], [ [ "\n\n\n\n\n\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
cb26be5a57fc1bbba4ff90aac6aa295bb4aed41e
20,590
ipynb
Jupyter Notebook
notebooks/lab1.ipynb
EmilieSalem/sdia-python
70ca5af273b087ff65d8b2d2cb142c09547d7f7f
[ "MIT" ]
null
null
null
notebooks/lab1.ipynb
EmilieSalem/sdia-python
70ca5af273b087ff65d8b2d2cb142c09547d7f7f
[ "MIT" ]
1
2021-10-02T17:43:06.000Z
2021-10-02T17:43:06.000Z
notebooks/lab1.ipynb
EmilieSalem/sdia-python
70ca5af273b087ff65d8b2d2cb142c09547d7f7f
[ "MIT" ]
null
null
null
23.108866
165
0.48577
[ [ [ "# Practical session 1 - Some Python basics\r\n\r\nCourse: [SDIA-Python](https://github.com/guilgautier/sdia-python)\r\n\r\nDates: 09/21/2021-09/22/2021\r\n\r\nInstructor: [Guillaume Gautier](https://guilgautier.github.io/)\r\n\r\nStudents (pair):\r\n- [Hadrien SALEM]([link](https://github.com/SnowHawkeye))\r\n- [Emilie SALEM]([link](https://github.com/EmilieSalem))", "_____no_output_____" ] ], [ [ "%load_ext autoreload\r\n%autoreload 2", "_____no_output_____" ] ], [ [ "## Documentation\r\n\r\nTo display the documentation associated to a Python function in your notebook (launched in VSCode), you can either\r\n- run `?functionname` or `help(my_adder)`\r\n- place your mouse pointer on the function name\r\n- write the name of the function and start opening the brackets", "_____no_output_____" ], [ "## Zen of Python\r\n", "_____no_output_____" ] ], [ [ "import this", "_____no_output_____" ] ], [ [ "## Reserved keywords\r\n", "_____no_output_____" ] ], [ [ "import keyword\r\nprint(keyword.kwlist)", "_____no_output_____" ], [ "import keyword\r\nprint(keyword.kwlist)", "_____no_output_____" ] ], [ [ "## Arithmetic", "_____no_output_____" ], [ "Compute 4 raised to the power 8", "_____no_output_____" ] ], [ [ "pow(4,8)", "_____no_output_____" ] ], [ [ "Compute the quotient and the remainder of the euclidean division of 17 by 3. ", "_____no_output_____" ] ], [ [ "17 // 3", "_____no_output_____" ], [ "17 % 3", "_____no_output_____" ] ], [ [ "Create two integer variables `a, b` of your choice and swap their content.", "_____no_output_____" ] ], [ [ "a = 1\r\nb = 2\r\na,b = b,a", "_____no_output_____" ], [ "print (\"a = \" + str(a))\r\nprint(\"b = \" + str(b))", "_____no_output_____" ] ], [ [ "Modify `a` inplace, so that the new value of `a` is twice its previous value.", "_____no_output_____" ] ], [ [ "a = 2*a\r\nprint(a)", "_____no_output_____" ] ], [ [ "Define a complex number `z` and print it as\r\n\r\n`real=real-part, imag=imaginary-part`", "_____no_output_____" ] ], [ [ "z = complex(3,1)\r\nprint(\"real = \" + str(z.real))\r\nprint(\"imag = \" + str(z.imag))\r\n\r\nz2 = 3 + 1j # different notation", "_____no_output_____" ] ], [ [ "## Strings\r\n", "_____no_output_____" ], [ "Propose two ways to define an empty string", "_____no_output_____" ] ], [ [ "string1 = \"\"\r\nstring2 = str()", "_____no_output_____" ], [ "print(\"string1 --->\" + string1 + \"<---\")\r\nprint(\"string2 --->\" + string2 + \"<---\")", "_____no_output_____" ] ], [ [ "Define a string made of the 26 letters of the alphabet (lower case), then\r\n- What is the 12th letter of the alphabet\r\n- What are the 10 last letters of the alphabet\r\n- What are the 5th to the 10th letters of the alphabet\r\n- Create a new string where the 26 letters are converted to upper case.", "_____no_output_____" ] ], [ [ "alphabet = \"abcdefghijklmnopqrstuvwxyz\"\r\nprint(\"12th letter: \" + alphabet[11])\r\nprint(\"Last 10 letters: \" + alphabet[-10:])\r\nprint(\"5th to 10th letter: \" + alphabet[4:10])\r\nalphabetUpperCase = str.upper(alphabet)\r\nprint(\"Upper case: \" + alphabetUpperCase)", "_____no_output_____" ] ], [ [ "Extract the first 4 digits of the number `x = 2341324530045968` (answer is `2341`).", "_____no_output_____" ] ], [ [ "x = 2341324530045968\r\nprint(str(x)[0:4])\r\n\r\n# different method\r\nprint(x // 10**12)", "_____no_output_____" ] ], [ [ "## Lists", "_____no_output_____" ], [ "Propose two ways to define an empty list.", "_____no_output_____" ] ], [ [ "list1 = []\r\nlist2 = list()\r\n\r\nprint(\"list1 --->\" + str(list1) + \"<---\")\r\nprint(\"list2 --->\" + str(list2) + \"<---\")", "_____no_output_____" ] ], [ [ "Create the list of consecutive integers from 5 to 11.", "_____no_output_____" ] ], [ [ "integerList = [i for i in range(5,12)]\r\nprint(integerList)", "_____no_output_____" ] ], [ [ "Add `100` to this list.", "_____no_output_____" ] ], [ [ "integerList.append(100)\r\nprint(integerList)", "_____no_output_____" ] ], [ [ "Given the following list, \r\nChange the `\"sdia\"` to its reverse (`\"aids\"`).", "_____no_output_____" ] ], [ [ "x = [10, [3, 4], [5, [100, 200, [\"sdia\"]], 23, 11], 1, 7]\r\nx[2][1][2][0] = x[2][1][2][0][::-1]\r\nprint(x)", "_____no_output_____" ] ], [ [ "Given the following list, \r\n\r\n 1. extract the first two items\r\n 2. extract the last two items\r\n 3. find the index of the first occurence of `9`\r\n 4. extract the items located at odd indices\r\n 5. create a new list which corresponds to the reversed version of the originial list\r\n 6. create a new list where each item of the original list is raised to the power 3", "_____no_output_____" ] ], [ [ "x = [3, 7, 5, 3, 8, 6, 8, 8, 0, 7, 3, 9, 3, 4, 2, 7, 0, 9, 5, 0, 0, 9, 0, 9, 3, 1, 4, 0, 5, 5, 5, 8, 9, 9, 5, 5, 4, 9, 5, 6, 2, 8, 5, 2, 4, 9, 2, 2, 3, 1]\r\nprint(\"first two items : \" + str(x[0:2]))\r\nprint(\"last two items : \" + str(x[-2::]))\r\nprint(\"index of tthe first occurence of 9 : \" + str(x.index(9)))\r\nprint(\"items located at odd indices : \" + str(x[1::2]))\r\n\r\nreversedList = x.copy()[::-1]\r\nprint(\"reversed version of original list : \" + str(reversedList))\r\n\r\npower3 = [pow(y,3) for y in x]\r\nprint(\"list where each item of the original list is raised to the power 3 : \" + str(power3))", "_____no_output_____" ] ], [ [ "## Tuples", "_____no_output_____" ], [ "\r\nPropose two ways to define an empty tuple.", "_____no_output_____" ] ], [ [ "tuple1 = ()\r\ntuple2 = tuple()\r\n\r\nprint(\"tuple1 --->\" + str(tuple1) + \"<---\")\r\nprint(\"tuple2 --->\" + str(tuple2) + \"<---\")", "_____no_output_____" ] ], [ [ "Given the following tuple\n- try to replace the second item (`4`) to `8`.\n- modify the list so that the second element of the first item is raised to the power 5 ", "_____no_output_____" ], [ "x = ([1, 2, 3], 4)", "_____no_output_____" ] ], [ [ "x = ([1, 2, 3], 4)\r\ntry: \r\n x[1] = 8\r\nexcept TypeError:\r\n print(\"An exception was thrown because tuples are immutable.\")", "_____no_output_____" ], [ "x = ([1, 2, 3], 4)\r\nx[0][1] = pow(x[0][1],2)\r\nprint(x)", "_____no_output_____" ] ], [ [ "What is the main difference between a list and a tuple?\r\n\r\n> Tuples are immutable, whereas list are mutable.", "_____no_output_____" ], [ "## Sets", "_____no_output_____" ], [ "Create an empty set", "_____no_output_____" ] ], [ [ "newSet = {} # ou set(), ou encore set([])\r\n\r\nprint(\"set --->\" + str(newSet) + \"<---\")", "_____no_output_____" ] ], [ [ "Compute the intersection between $A = \\{1, 2, 3\\}$ and $B = \\{2, 4, 5, 6\\}$.", "_____no_output_____" ] ], [ [ "A = {1,2,3}\r\nB = {2,4,5,6}\r\nA.intersection(B)", "_____no_output_____" ] ], [ [ "From the following set\n- add the numbers 4, 5, 6\n- remove the numbers 1, 2, 3\n- check if the resulting set is contained in `{1, 2, 4, 5, 6, 10}` ", "_____no_output_____" ] ], [ [ "x = {0, 1, 2, 3, 6, 7, 8, 9, 10}\r\nx.add(4)\r\nx.add(5)\r\nx.add(6)\r\nx.remove(1)\r\nx.remove(2)\r\nx.remove(3)\r\n\r\ncompared = {1, 2, 4, 5, 6, 10}\r\n\r\nprint(x)\r\nprint(\"x is contained in the set >> \" + str(x.issubset(compared)))", "_____no_output_____" ] ], [ [ "## Dictionnaries", "_____no_output_____" ], [ "Propose two ways to define an empty dictionary", "_____no_output_____" ] ], [ [ "dict1 = {}\r\ndict2 = dict()\r\n\r\nprint(\"dict1 --->\" + str(dict1) + \"<---\")\r\nprint(\"dict2 --->\" + str(dict2) + \"<---\")", "_____no_output_____" ] ], [ [ "Propose at least 3 ways to define a dictionary with \n- keys `(\"a\", \"b\", \"c\", \"d\")`\n- values `(1, 3, 5 , 7)`", "_____no_output_____" ] ], [ [ "dictDirect = {\r\n \"a\" : 1,\r\n \"b\" : 3,\r\n \"c\" : 5,\r\n \"d\" : 7,\r\n}\r\n\r\nkeys = [\"a\", \"b\", \"c\", \"d\"]\r\nvalues = [1, 3, 5 , 7]\r\ndictFromLists = dict(zip(keys, values))\r\n\r\ndictAdd = dict()\r\ndictAdd[\"a\"] = 1\r\ndictAdd[\"b\"] = 3\r\ndictAdd[\"c\"] = 5\r\ndictAdd[\"d\"] = 7\r\n\r\nprint(\"dictDirect --->\" + str(dictDirect))\r\nprint(\"dictFromLists --->\" + str(dictFromLists))\r\nprint(\"dictAdd --->\" + str(dictAdd))", "_____no_output_____" ] ], [ [ "Given the following dictionary, use indexing to get to the word `\"sdia\"`", "_____no_output_____" ] ], [ [ "d = {\r\n \"outer\": [\r\n 1,\r\n 2,\r\n 3,\r\n {\"inner\": [\"this\", \"is\", \"inception\", {\"inner_inner\": [1, 2, 3, \"sdia\"]}]},\r\n ]\r\n}\r\n\r\nprint(d[\"outer\"][3][\"inner\"][3][\"inner_inner\"][3])", "_____no_output_____" ] ], [ [ "From the following dictionary,\r\n- Create the list of keys\r\n- Create the list of values\r\n- Check if the key `\"abc\"` is present, if not, return `123`.\r\n- Merge the initial dictionary with `{\"e\": -1, 4: True}`", "_____no_output_____" ] ], [ [ "d1 = dict(zip([(0, 1), \"e\", 1, None], [\"abc\", 4, None, 1 + 2j]))\r\nkeys = d1.keys()\r\nvalues = d1.values()\r\nprint(keys)\r\nprint(values)", "_____no_output_____" ] ], [ [ "## Conditions", "_____no_output_____" ], [ "Propose two ways to construct the list of odd values ranging from 0 to 30", "_____no_output_____" ], [ "From the following list, create another list which contains\n- `\"fiz\"` if the item is a multiple of 5,\n- `\"buz\"` if the item is a multiple of 7,\n- `\"fizbuz\"` if the item is a both a multiple of 5 and 7,\n- the index of the item otherwise.", "_____no_output_____" ] ], [ [ "x = [2, 1, 3, 31, 35, 20, 70, 132, 144, 49]\r\n\r\nnew_list = []\r\nfor i in range(0,len(x)) :\r\n if (x[i]%5 == 0 and x[i]%7 == 0) : new_list.append(\"fizbuz\")\r\n elif x[i]%5 == 0 : new_list.append(\"fiz\")\r\n elif x[i]%7 == 0 : new_list.append(\"buz\")\r\n else : new_list.append(i)\r\n\r\nprint(new_list)", "_____no_output_____" ] ], [ [ "Given a string variable `course`, construct a `if/elif/else` statement that prints:\n- `\"That is very useful!\"` if `course` is `\"maths\"` (any kind of capitalization)\n- `\"That is very useful!\"` if `course` is `\"python\"` (any kind of capitalization)\n- `\"How nice!\"` if `course` is `\"meditation\"` (any kind of capitalization)\n- `\"You're not at Hogwarts\"` if `course` is `\"magic\"` (any kind of capitalization)\n- otherwise `\"What is this COURSE?\"` if `course` is anything else.", "_____no_output_____" ] ], [ [ "course = \"python\"\r\n\r\nif(course.lower() == \"maths\" or course.lower() == \"python\") : print(\"That is very useful!\")\r\nelif(course.lower() == \"meditation\") : print(\"How nice!\")\r\nelif(course.lower() == \"magic\") : print(\"You're not at Hogwarts\")\r\nelse : print(\"What is this COURSE?\")", "_____no_output_____" ] ], [ [ "Given the following variables, create and print the string\n\n``quantity`` ``fruit``(s) cost(s) $``price``\n\nsuch that\n- there is an `\"s\"` at `\"cost\"` when there is more only one fruit,\n- there is an `\"s\"` at `\"fruit\"` when there is more that one fruit,\n- the price is displayed as ...,xxx,xxx.yy where yy corresponds rounded cents value", "_____no_output_____" ] ], [ [ "quantity = 3\r\nfruit = \"lemon\"\r\nprice = 1.8912392e4\r\n\r\npluralNoun = \"s\" if quantity > 1 else \"\"\r\npluralVerb = \"s\" if quantity == 1 else \"\"\r\nformattedPrice = f\"{price:,}\"\r\n\r\nprint(str(quantity) + \" \" + fruit + pluralNoun + \" cost\" + pluralVerb + \" $\" + formattedPrice)", "_____no_output_____" ] ], [ [ "## Functions\n\n- Create your function in `src/sdia_python/lab1/functions.py` files\n- Import them using `from sdia_python.lab1.functions import MYFUNCTION`", "_____no_output_____" ] ], [ [ "from sdia_python.lab1.functions import *\r\nprintMyString()", "_____no_output_____" ] ], [ [ "Define the function `is_unique(x)` which takes a list of integers `x` as input and returns `True` if the there is no duplicate items otherwise return `False`.", "_____no_output_____" ] ], [ [ "from sdia_python.lab1.functions import *\r\nx1 = [\"3\", \"3\", \"4\"]\r\nx2 = [\"3\", \"4\"]\r\n\r\nprint(is_unique(x1))\r\nprint(is_unique(x2))", "_____no_output_____" ] ], [ [ "Define a function `triangle_shape(height)`, that returns \n- `\"\"` if `height=0`, \n- otherwise it returns a string that forms a triangle with height prescribed by `height`.\n\n**Examples**\n\nheight=1\n```\nx\n```\n\nheight=2\n```\n x \nxxx\n```\n\nheight=3\n```\n x \n xxx \nxxxxx\n```\n\nheight=4\n```\n x \n xxx \n xxxxx \nxxxxxxx\n```\n\nheight=5\n```\n x \n xxx \n xxxxx \n xxxxxxx \nxxxxxxxxx\n```\n\nheight=6\n```\n x \n xxx \n xxxxx \n xxxxxxx \n xxxxxxxxx \nxxxxxxxxxxx\n```", "_____no_output_____" ] ], [ [ "from sdia_python.lab1.functions import *\r\nprint(\"height = 0\\n\" + triangle_shape(0)) \r\nprint(\"height = 1\\n\" + triangle_shape(1)) \r\nprint(\"height = 2\\n\" + triangle_shape(2)) \r\nprint(\"height = 3\\n\" + triangle_shape(3)) ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb26eb3be8cda7e57cc3f9345dec3b24b2ead630
8,227
ipynb
Jupyter Notebook
.ipynb_checkpoints/backprop_point_test-checkpoint.ipynb
alecmeade/ai_for_earth
4d789d123f805158c7146e5c6fd3deb5ee679d83
[ "MIT" ]
1
2021-01-20T02:21:21.000Z
2021-01-20T02:21:21.000Z
.ipynb_checkpoints/backprop_point_test-checkpoint.ipynb
alecmeade/ai_for_earth
4d789d123f805158c7146e5c6fd3deb5ee679d83
[ "MIT" ]
null
null
null
.ipynb_checkpoints/backprop_point_test-checkpoint.ipynb
alecmeade/ai_for_earth
4d789d123f805158c7146e5c6fd3deb5ee679d83
[ "MIT" ]
2
2020-07-22T16:10:11.000Z
2020-12-10T03:07:50.000Z
37.226244
125
0.513431
[ [ [ "import gc\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torchvision\n\n# To view tensorboard metrics\n# tensorboard --logdir=logs --port=6006 --bind_all\nfrom torch.utils.tensorboard import SummaryWriter\nfrom functools import partial\nfrom evolver import CrossoverType, MutationType, VectorEvolver, InitType\nfrom unet import UNet\nfrom dataset_utils import PartitionType\nfrom cuda_utils import maybe_get_cuda_device, clear_cuda\nfrom landcover_dataloader import get_landcover_dataloaders\n\nfrom ignite.contrib.handlers.tensorboard_logger import *\nfrom ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator\nfrom ignite.metrics import Accuracy, Loss, ConfusionMatrix, mIoU\nfrom ignite.handlers import ModelCheckpoint\nfrom ignite.utils import setup_logger\nfrom ignite.engine import Engine\nimport sys\n\n# Define directories for data, logging and model saving.\nbase_dir = os.getcwd()\ndataset_name = \"landcover_large\"\ndataset_dir = os.path.join(base_dir, \"data/\" + dataset_name)\n\nexperiment_name = \"backprop_single_point_finetuning_test_test\"\nmodel_name = \"best_model_30_validation_accuracy=0.9409.pt\"\nmodel_path = os.path.join(base_dir, \"logs/\" + dataset_name + \"/\" + model_name)\nlog_dir = os.path.join(base_dir, \"logs/\" + dataset_name + \"_\" + experiment_name)\n\n# Create DataLoaders for each partition of Landcover data.\ndataloader_params = {\n 'batch_size': 1,\n 'shuffle': True,\n 'num_workers': 6,\n 'pin_memory': True}\n\npartition_types = [PartitionType.TRAIN, PartitionType.VALIDATION, \n PartitionType.FINETUNING, PartitionType.TEST]\ndata_loaders = get_landcover_dataloaders(dataset_dir, \n partition_types,\n dataloader_params,\n force_create_dataset=True)\n\nfinetuning_loader = data_loaders[2]\ntest_loader = data_loaders[3]\n\n# Get GPU device if available.\ndevice = maybe_get_cuda_device()\n\n# Determine model and training params.\nparams = {\n 'max_epochs': 10,\n 'n_classes': 4,\n 'in_channels': 4,\n 'depth': 5,\n 'learning_rate': 0.01,\n 'log_steps': 1,\n 'save_top_n_models': 4\n}\n\nclear_cuda() \nmodel = UNet(in_channels = params['in_channels'],\n n_classes = params['n_classes'],\n depth = params['depth'])\nmodel.load_state_dict(torch.load(model_path))\n\nmodel\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), \n lr=params['learning_rate'])\n\n\n# Determine metrics for evaluation.\ntrain_metrics = {\n \"accuracy\": Accuracy(), \n \"loss\": Loss(criterion),\n \"mean_iou\": mIoU(ConfusionMatrix(num_classes = params['n_classes'])),\n }\n\nvalidation_metrics = {\n \"accuracy\": Accuracy(), \n \"loss\": Loss(criterion),\n \"mean_iou\": mIoU(ConfusionMatrix(num_classes = params['n_classes'])),\n\n}\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n", "_____no_output_____" ], [ "for batch in finetuning_loader:\n batch_x = batch[0]\n _ = model(batch_x)\n break\n \ndrop_out_layers = model.get_dropout_layers()\n\n\n \ndef mask_from_vec(vec, matrix_size):\n mask = np.ones(matrix_size)\n for i in range(len(vec)):\n if vec[i] == 0:\n mask[i, :, :] = 0\n\n elif vec[i] == 1:\n mask[i, :, :] = 1\n\n return mask\n\n\n\nfor layer in drop_out_layers:\n layer_name = layer.name\n size = layer.x_size[1:]\n sizes = [size]\n clear_cuda() \n model = UNet(in_channels = params['in_channels'],\n n_classes = params['n_classes'],\n depth = params['depth'])\n model.load_state_dict(torch.load(model_path))\n model.eval()\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), \n lr=params['learning_rate'])\n\n num_channels = size[0]\n evolver = VectorEvolver(num_channels, \n CrossoverType.UNIFORM,\n MutationType.FLIP_BIT, \n InitType.BINOMIAL, \n flip_bit_prob=None, \n flip_bit_decay=1.0,\n binomial_prob=0.8)\n\n print(\"LAYER\", layer_name, size)\n with torch.no_grad():\n batch_x, batch_y = batch\n loss = sys.float_info.max\n child_mask_prev = None\n for i in range(300):\n child_vec = evolver.spawn_child()\n child_mask = mask_from_vec(child_vec, size)\n model.set_dropout_masks({layer_name: torch.tensor(child_mask, dtype=torch.float32)})\n outputs = model(batch_x)\n current_loss = criterion(outputs[:, :, 127:128,127:128], batch_y[:,127:128,127:128]).item()\n evolver.add_child(child_mask, 1.0 / current_loss)\n print(\"Current\", current_loss)\n loss = min(loss, current_loss)\n \n if current_loss == 0.0:\n current_loss = sys.float_info.max\n else:\n current_loss = 1.0 / current_loss\n\n evolver.add_child(child_vec, current_loss)\n \n priority, best_child = evolver.get_best_child()\n best_mask = mask_from_vec(best_child, size)\n model.set_dropout_masks({layer_name: torch.tensor(best_mask, dtype=torch.float32).to(device)})\n \n \n \n# f, ax = plt.subplots(1, 3, figsize=(20, 8))\n# ax[0].imshow((np.array(batch_y.detach().numpy()[0, :, :])))\n# ax[1].imshow(np.argmax(np.moveaxis(np.array(outputs.detach().numpy()[0, :, :, :]), [0],[ 2]), axis=2))\n# ax[2].imshow(child_mask[0, :, :])\n \n# child_mask_prev = child_mask\n# plt.show()\n print(\"best_loss\", 1.0/evolver.get_best_child()[0])\n\n ", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
cb26f4abe9245e1a66cdc1ce383884d3e406e942
1,140
ipynb
Jupyter Notebook
data_processing/testing.ipynb
CyberFlameGO/gpt-code-clippy
355022b4e9888acc7e193109ef25fc7abcff3d3e
[ "Apache-2.0" ]
435
2021-08-09T17:36:29.000Z
2022-03-31T20:12:32.000Z
data_processing/testing.ipynb
CyberFlameGO/gpt-code-clippy
355022b4e9888acc7e193109ef25fc7abcff3d3e
[ "Apache-2.0" ]
23
2021-08-09T17:24:28.000Z
2022-03-05T06:15:31.000Z
data_processing/testing.ipynb
CyberFlameGO/gpt-code-clippy
355022b4e9888acc7e193109ef25fc7abcff3d3e
[ "Apache-2.0" ]
46
2021-08-11T11:38:35.000Z
2022-03-26T08:18:59.000Z
17.538462
116
0.468421
[ [ [ "import json\n\nwith open(\"/home/nathan/gpt-code-clippy/data_scripts/Programming_Languages_Extensions.json\", \"r\") as f:\n data = json.load(f)", "_____no_output_____" ], [ "exts = []\nfor i in data:\n if \"extensions\" not in i:\n continue\n exts.extend(i[\"extensions\"])\n # print(i)", "_____no_output_____" ], [ "len(exts)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cb27157e6ab059043a94b68fe045e4bc13ed271c
127,421
ipynb
Jupyter Notebook
.ipynb_checkpoints/5 - KMeans-checkpoint.ipynb
guptesanket/Python-for-Neuroscientists
c932dce679319be81e761878e93f178da3026429
[ "MIT" ]
null
null
null
.ipynb_checkpoints/5 - KMeans-checkpoint.ipynb
guptesanket/Python-for-Neuroscientists
c932dce679319be81e761878e93f178da3026429
[ "MIT" ]
null
null
null
.ipynb_checkpoints/5 - KMeans-checkpoint.ipynb
guptesanket/Python-for-Neuroscientists
c932dce679319be81e761878e93f178da3026429
[ "MIT" ]
null
null
null
312.306373
32,138
0.920358
[ [ [ "The $k$-Means Algorithm\n====================\n\nAgain, we start by generating some artificial data:", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n#from IPython.display import HTML\n# This line tells the notebook to show plots inside of the notebook\n%matplotlib inline", "_____no_output_____" ], [ "plt.jet() # set the color map. When your colors are lost, re-run this.\nimport sklearn.datasets as datasets\nX, Y = datasets.make_blobs(centers=4, cluster_std=0.5, random_state=0)", "_____no_output_____" ] ], [ [ "As always, we first *plot* the data to get a feeling of what we're dealing with:", "_____no_output_____" ] ], [ [ "plt.scatter(X[:,0], X[:,1]);", "_____no_output_____" ] ], [ [ "The data looks like it may contain four different \"types\" of data point. \n\nIn fact, this is how it was created above.\n\nWe can plot this information as well, using color:", "_____no_output_____" ] ], [ [ "plt.scatter(X[:,0], X[:,1], c=Y);", "_____no_output_____" ] ], [ [ "Normally, you do not know the information in `Y`, however.\n\nYou could try to recover it from the data alone.\n\nThis is what the kMeans algorithm does. ", "_____no_output_____" ] ], [ [ "from sklearn.cluster import KMeans\nkmeans = KMeans(4, random_state=8)\nY_hat = kmeans.fit(X).labels_", "_____no_output_____" ] ], [ [ "Now the label assignments should be quite similar to `Y`, up to a different ordering of the colors:", "_____no_output_____" ] ], [ [ "plt.scatter(X[:,0], X[:,1], c=Y_hat);", "_____no_output_____" ] ], [ [ "Often, you're not so much interested in the assignments to the means. \n\nYou'll want to have a closer look at the means $\\mu$.\n\nThe means in $\\mu$ can be seen as *representatives* of their respective cluster.", "_____no_output_____" ] ], [ [ "plt.scatter(X[:,0], X[:,1], c=Y_hat, alpha=0.4)\nmu = kmeans.cluster_centers_\nplt.scatter(mu[:,0], mu[:,1], s=100, c=np.unique(Y_hat))\nprint mu", "[[-1.47935679 3.11716896]\n [-1.26811733 7.76378266]\n [ 1.99186903 0.96561071]\n [ 0.92578447 4.32475792]]\n" ] ], [ [ "## $k$-Means on Images", "_____no_output_____" ], [ "In this final example, we use the $k$-Means algorithm on the classical MNIST dataset.\n\nThe MNIST dataset contains images of hand-written digits. \n\nLet's first fetch the dataset from the internet (which may take a while, note the asterisk [*]):", "_____no_output_____" ] ], [ [ "from sklearn.datasets import fetch_mldata\nfrom sklearn.cluster import KMeans\nfrom sklearn.utils import shuffle\nX_digits, _,_, Y_digits = fetch_mldata(\"MNIST Original\").values() # fetch dataset from internet\nX_digits, Y_digits = shuffle(X_digits,Y_digits) # shuffle dataset (which is ordered!)\nX_digits = X_digits[-5000:] # take only the last instances, to shorten runtime of KMeans", "_____no_output_____" ] ], [ [ "Let's have a look at some of the instances in the dataset we just loaded:", "_____no_output_____" ] ], [ [ "plt.rc(\"image\", cmap=\"binary\") # use black/white palette for plotting\nfor i in xrange(10):\n plt.subplot(2,5,i+1)\n plt.imshow(X_digits[i].reshape(28,28))\n plt.xticks(())\n plt.yticks(())\nplt.tight_layout()", "_____no_output_____" ] ], [ [ "**Warning**: This takes quite a few seconds, so be patient until the asterisk [*] disappears!", "_____no_output_____" ] ], [ [ "kmeans = KMeans(20)\nmu_digits = kmeans.fit(X_digits).cluster_centers_", "_____no_output_____" ] ], [ [ "Let's have a closer look at the means. Even though there are 10 digits, some of them are over/under-represented. Do you understand why?", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(16,6))\nfor i in xrange(2*(mu_digits.shape[0]/2)): # loop over all means\n plt.subplot(2,mu_digits.shape[0]/2,i+1)\n plt.imshow(mu_digits[i].reshape(28,28))\n plt.xticks(())\n plt.yticks(())\nplt.tight_layout()", "_____no_output_____" ] ], [ [ "## Playing with $k$-Means", "_____no_output_____" ], [ "You can try other datasets to explore k-means : http://archive.ics.uci.edu/ml/ \n\nTry to get a feeling of how the algorithm proceeds.", "_____no_output_____" ], [ "Homework\n==========================\n\nTry to see what happens when you\n\n- Increase the standard deviation of the clusters in this notebook\n- Choose a \"wrong\" number of clusters by:\n 1. changing the number of clusters generated\n 2. changing the number of clusters used by KMeans\n\n- What happens to result of the $k$-Means algorithm when you have multiplied one axis of the matrix $X$ with a large value?\n\n For example, the 0-th axis with 100:\n\n `X[:,0] *= 100`\n\n Why does the result change?\n\n- Combine the $k$-Means algorithm with the PCA algorithm", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
cb2725834d6f537a906fa072ec231d56b62dbb1a
420,576
ipynb
Jupyter Notebook
01 - Data Exploration.ipynb
nikkhil13/azure-ml-certification
f48ec756c914197fe0f9a9eba32b45b8f3bc0803
[ "MIT" ]
1
2020-12-03T07:23:33.000Z
2020-12-03T07:23:33.000Z
01 - Data Exploration.ipynb
nikkhil13/azure-ml-certification
f48ec756c914197fe0f9a9eba32b45b8f3bc0803
[ "MIT" ]
null
null
null
01 - Data Exploration.ipynb
nikkhil13/azure-ml-certification
f48ec756c914197fe0f9a9eba32b45b8f3bc0803
[ "MIT" ]
2
2020-12-04T20:03:00.000Z
2021-06-08T07:28:51.000Z
92.801412
24,720
0.791096
[ [ [ "# Exploring Data with Python\n\nA significant part of a a data scientist's role is to explore, analyze, and visualize data. There's a wide range of tools and programming languages that they can use to do this; and of of the most popular approaches is to use Jupyter notebooks (like this one) and Python.\n\nPython is a flexible programming language that is used in a wide range of scenarios; from web applications to device programming. It's extremely popular in the data science and machine learning community because of the many packages it supports for data analysis and visualization.\n\nIn this notebook, we'll explore some of these packages, and apply basic techniques to analyze data. This is not intended to be a comprehensive Python programming exercise; or even a deep dive into data analysis. Rather, it's intended as a crash course in some of the common ways in which data scientists can use Python to work with data.\n\n> **Note**: If you've never used the Jupyter Notebooks environment before, there are a few things you should be aware of:\n> \n> - Notebooks are made up of *cells*. Some cells (like this one) contain *markdown* text, while others (like the one beneath this one) contain code.\n> - The notebook is connected to a Python *kernel* (you can see which one at the top right of the page - if you're running this noptebook in an Azure Machine Learning compute instance it should be connected to the **Python 3.6 - AzureML** kernel). If you stop the kernel or disconnect from the server (for example, by closing and reopening the notebook, or ending and resuming your session), the output from cells that have been run will still be displayed; but any variables or functions defined in those cells will have been lost - you must rerun the cells before running any subsequent cells that depend on them.\n> - You can run each code cell by using the **&#9658; Run** button. The **&#9711;** symbol next to the kernel name at the top right will briefly turn to **&#9899;** while the cell runs before turning back to **&#9711;**.\n> - The output from each code cell will be displayed immediately below the cell.\n> - Even though the code cells can be run individually, some variables used in the code are global to the notebook. That means that you should run all of the code cells <u>**in order**</u>. There may be dependencies between code cells, so if you skip a cell, subsequent cells might not run correctly.\n\n\n## Exploring data arrays with NumPy\n\nLets start by looking at some simple data.\n\nSuppose a college takes a sample of student grades for a data science class.\n\nRun the code in the cell below by clicking the **&#9658; Run** button to see the data.", "_____no_output_____" ] ], [ [ "import sys\nprint(sys.version)", "3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31) \n[GCC 7.3.0]\n" ], [ "data = [50,50,47,97,49,3,53,42,26,74,82,62,37,15,70,27,36,35,48,52,63,64]\nprint(data)", "[50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15, 70, 27, 36, 35, 48, 52, 63, 64]\n" ] ], [ [ "The data has been loaded into a Python **list** structure, which is a good data type for general data manipulation, but not optimized for numeric analysis. For that, we're going to use the **NumPy** package, which includes specific data types and functions for working with *Num*bers in *Py*thon.\n\nRun the cell below to load the data into a NumPy **array**.", "_____no_output_____" ] ], [ [ "import numpy as np\n\ngrades = np.array(data)\nprint(grades)", "[50 50 47 97 49 3 53 42 26 74 82 62 37 15 70 27 36 35 48 52 63 64]\n" ] ], [ [ "Just in case you're wondering about the differences between a **list** and a NumPy **array**, let's compare how these data types behave when we use them in an expression that multiplies them by 2.", "_____no_output_____" ] ], [ [ "print (type(data),'x 2:', data * 2)\nprint('---')\nprint (type(grades),'x 2:', grades * 2)", "<class 'list'> x 2: [50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15, 70, 27, 36, 35, 48, 52, 63, 64, 50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15, 70, 27, 36, 35, 48, 52, 63, 64]\n---\n<class 'numpy.ndarray'> x 2: [100 100 94 194 98 6 106 84 52 148 164 124 74 30 140 54 72 70\n 96 104 126 128]\n" ] ], [ [ "Note that multiplying a list by 2 creates a new list of twice the length with the original sequence of list elements repeated. Multiplying a NumPy array on the other hand performs an element-wise calculation in which the array behaves like a *vector*, so we end up with an array of the same size in which each element has been multipled by 2.\n\nThe key takeaway from this is that NumPy arrays are specifically designed to support mathematical operations on numeric data - which makes them more useful for data analysis than a generic list.\n\nYou might have spotted that the class type for the numpy array above is a **numpy.ndarray**. The **nd** indicates that this is a structure that can consists of multiple *dimensions* (it can have *n* dimensions). Our specific instance has a single dimension of student grades.\n\nRun the cell below to view the **shape** of the array.", "_____no_output_____" ] ], [ [ "grades.shape", "_____no_output_____" ] ], [ [ "The shape confirms that this array has only one dimension, which contains 22 elements (there are 22 grades in the original list). You can access the individual elements in the array by their zer0-based ordinal position. Let's get the first element (the one in position 0).", "_____no_output_____" ] ], [ [ "grades[0]", "_____no_output_____" ] ], [ [ "Alright, now you know your way around a NumPy array, it's time to perform some analysis of the grades data.\n\nYou can apply aggregations across the elements in the array, so let's find the simple average grade (in other words, the *mean* grade value).", "_____no_output_____" ] ], [ [ "grades.mean()", "_____no_output_____" ] ], [ [ "So the mean grade is just around 50 - more or less in the middle of the possible range from 0 to 100.\n\nLet's add a second set of data for the same students, this time recording the typical number of hours per week they devoted to studying.", "_____no_output_____" ] ], [ [ "# Define an array of study hours\nstudy_hours = [10.0,11.5,9.0,16.0,9.25,1.0,11.5,9.0,8.5,14.5,15.5,\n 13.75,9.0,8.0,15.5,8.0,9.0,6.0,10.0,12.0,12.5,12.0]\n\n# Create a 2D array (an array of arrays)\nstudent_data = np.array([study_hours, grades])\n\n# display the array\nstudent_data", "_____no_output_____" ] ], [ [ "Now the data consists of a 2-dimensional array - an array of arrays. Let's look at its shape.", "_____no_output_____" ] ], [ [ "# Show shape of 2D array\nstudent_data.shape", "_____no_output_____" ] ], [ [ "The **student_data** array contains two elements, each of which is an array containing 22 elements.\n\nTo navigate this structure, you need to specify the position of each element in the hierarchy. So to find the first value in the first array (which contains the study hours data), you can use the following code.", "_____no_output_____" ] ], [ [ "# Show the first element of the first element\nstudent_data[0][0]", "_____no_output_____" ] ], [ [ "Now you have a multidimensional array containing both the student's study time and grade information, which you can use to compare data. For example, how does the mean study time compare to the mean grade?", "_____no_output_____" ] ], [ [ "# Get the mean value of each sub-array\navg_study = student_data[0].mean()\navg_grade = student_data[1].mean()\n\nprint('Average study hours: {:.2f}\\nAverage grade: {:.2f}'.format(avg_study, avg_grade))", "Average study hours: 10.52\nAverage grade: 49.18\n" ] ], [ [ "## Exploring tabular data with Pandas\n\nWhile NumPy provides a lot of the functionality you need to work with numbers, and specifically arrays of numeric values; when you start to deal with two-dimensional tables of data, the **Pandas** package offers a more convenient structure to work with - the **DataFrame**.\n\nRun the following cell to import the Pandas library and create a DataFrame with three columns. The first column is a list of student names, and the second and third columns are the NumPy arrays containing the study time and grade data.", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ndf_students = pd.DataFrame({'Name': ['Dan', 'Joann', 'Pedro', 'Rosie', 'Ethan', 'Vicky', 'Frederic', 'Jimmie', \n 'Rhonda', 'Giovanni', 'Francesca', 'Rajab', 'Naiyana', 'Kian', 'Jenny',\n 'Jakeem','Helena','Ismat','Anila','Skye','Daniel','Aisha'],\n 'StudyHours':student_data[0],\n 'Grade':student_data[1]})\n\ndf_students ", "_____no_output_____" ] ], [ [ "Note that in addition to the columns you specified, the DataFrame includes an *index* to unique identify each row. We could have specified the index explicitly, and assigned any kind of appropriate value (for example, an email address); but because we didn't specify an index, one has been created with a unique integer value for each row.\n\n### Finding and filtering data in a DataFrame\n\nYou can use the DataFrame's **loc** method to retrieve data for a specific index value, like this.", "_____no_output_____" ] ], [ [ "# Get the data for index value 5\ndf_students.loc[5]", "_____no_output_____" ] ], [ [ "You can also get the data at a range of index values, like this:", "_____no_output_____" ] ], [ [ "# Get the rows with index values from 0 to 5\ndf_students.loc[0:5]", "_____no_output_____" ] ], [ [ "In addition to being able to use the **loc** method to find rows based on the index, you can use the **iloc** method to find rows based on their ordinal position in the DataFrame (regardless of the index):", "_____no_output_____" ] ], [ [ "# Get data in the first five rows\ndf_students.iloc[0:5]", "_____no_output_____" ] ], [ [ "Look carefully at the `iloc[0:5]` results, and compare them to the `loc[0:5]` results you obtained previously. Can you spot the difference?\n\nThe **loc** method returned rows with index *label* in the list of values from *0* to *5* - which includes *0*, *1*, *2*, *3*, *4*, and *5* (six rows). However, the **iloc** method returns the rows in the *positions* included in the range 0 to 5, and since integer ranges don't include the upper-bound value, this includes positions *0*, *1*, *2*, *3*, and *4* (five rows).\n\n**iloc** identifies data values in a DataFrame by *position*, which extends beyond rows to columns. So for example, you can use it to find the values for the columns in positions 1 and 2 in row 0, like this:", "_____no_output_____" ] ], [ [ "df_students.iloc[0,[1,2]]", "_____no_output_____" ] ], [ [ "Let's return to the **loc** method, and see how it works with columns. Remember that **loc** is used to locate data items based on index values rather than positions. In the absence of an explicit index column, the rows in our dataframe are indexed as integer values, but the columns are identified by name:", "_____no_output_____" ] ], [ [ "df_students.loc[0,'Grade']", "_____no_output_____" ] ], [ [ "Here's another useful trick. You can use the **loc** method to find indexed rows based on a filtering expression that references named columns other than the index, like this:", "_____no_output_____" ] ], [ [ "df_students.loc[df_students['Name']=='Aisha']", "_____no_output_____" ] ], [ [ "Actually, you don't need to explicitly use the **loc** method to do this - you can simply apply a DataFrame filtering expression, like this:", "_____no_output_____" ] ], [ [ "df_students[df_students['Name']=='Aisha']", "_____no_output_____" ] ], [ [ "And for good measure, you can achieve the same results by using the DataFrame's **query** method, like this:", "_____no_output_____" ] ], [ [ "df_students.query('Name==\"Aisha\"')", "_____no_output_____" ] ], [ [ "The three previous examples underline an occassionally confusing truth about working with Pandas. Often, there are multiple ways to achieve the same results. Another example of this is the way you refer to a DataFrame column name. You can specify the column name as a named index value (as in the `df_students['Name']` examples we've seen so far), or you can use the column as a property of the DataFrame, like this:", "_____no_output_____" ] ], [ [ "df_students[df_students.Name == 'Aisha']", "_____no_output_____" ] ], [ [ "### Loading a DataFrame from a file\n\nWe constructed the DataFrame from some existing arrays. However, in many real-world scenarios, data is loaded from sources such as files. Let's replace the student grades DataFrame with the contents of a text file.", "_____no_output_____" ] ], [ [ "df_students = pd.read_csv('data/grades.csv',delimiter=',',header='infer')\ndf_students.head()", "_____no_output_____" ] ], [ [ "The DataFrame's **read_csv** method is used to load data from text files. As you can see in the example code, you can specify options such as the column delimiter and which row (if any) contains column headers (in this case, the delimter is a comma and the first row contains the column names - these are the default settings, so the parameters could have been omitted).\n\n\n### Handling missing values\n\nOne of the most common issues data scientists need to deal with is incomplete or missing data. So how would we know that the DataFrame contains missing values? You can use the **isnull** method to identify which individual values are null, like this:", "_____no_output_____" ] ], [ [ "df_students.isnull()", "_____no_output_____" ] ], [ [ "Of course, with a larger DataFrame, it would be inefficient to review all of the rows and columns individually; so we can get the sum of missing values for each column, like this:", "_____no_output_____" ] ], [ [ "df_students.isnull().sum()", "_____no_output_____" ] ], [ [ "So now we know that there's one missing **StudyHours** value, and two missing **Grade** values.\n\nTo see them in context, we can filter the dataframe to include only rows where any of the columns (axis 1 of the DataFrame) are null.", "_____no_output_____" ] ], [ [ "df_students[df_students.isnull().any(axis=1)]", "_____no_output_____" ] ], [ [ "When the DataFrame is retrieved, the missing numeric values show up as **NaN** (*not a number*).\n\nSo now that we've found the null values, what can we do about them?\n\nOne common approach is to *impute* replacement values. For example, if the number of study hours is missing, we could just assume that the student studied for an average amount of time and replace the missing value with the mean study hours. To do this, we can use the **fillna** method, like this:", "_____no_output_____" ] ], [ [ "df_students.StudyHours = df_students.StudyHours.fillna(df_students.StudyHours.mean())\ndf_students", "_____no_output_____" ] ], [ [ "Alternatively, it might be important to ensure that you only use data you know to be absolutely correct; so you can drop rows or columns that contains null values by using the **dropna** method. In this case, we'll remove rows (axis 0 of the DataFrame) where any of the columns contain null values.", "_____no_output_____" ] ], [ [ "df_students = df_students.dropna(axis=0, how='any')\ndf_students", "_____no_output_____" ] ], [ [ "### Explore data in the DataFrame\n\nNow that we've cleaned up the missing values, we're ready to explore the data in the DataFrame. Let's start by comparing the mean study hours and grades.", "_____no_output_____" ] ], [ [ "# Get the mean study hours using to column name as an index\nmean_study = df_students['StudyHours'].mean()\n\n# Get the mean grade using the column name as a property (just to make the point!)\nmean_grade = df_students.Grade.mean()\n\n# Print the mean study hours and mean grade\nprint('Average weekly study hours: {:.2f}\\nAverage grade: {:.2f}'.format(mean_study, mean_grade))", "Average weekly study hours: 10.52\nAverage grade: 49.18\n" ] ], [ [ "OK, let's filter the DataFrame to find only the students who studied for more than the average amount of time.", "_____no_output_____" ] ], [ [ "# Get students who studied for the mean or more hours\ndf_students[df_students.StudyHours > mean_study]", "_____no_output_____" ] ], [ [ "Note that the filtered result is itself a DataFrame, so you can work with its columns just like any other DataFrame.\n\nFor example, let's find the average grade for students who undertook more than the average amount of study time.", "_____no_output_____" ] ], [ [ "# What was their mean grade?\ndf_students[df_students.StudyHours > mean_study].Grade.mean()", "_____no_output_____" ] ], [ [ "Let's assume that the passing grade for the course is 60.\n\nWe can use that information to add a new column to the DataFrame, indicating whether or not each student passed.\n\nFirst, we'll create a Pandas **Series** containing the pass/fail indicator (True or False), and then we'll concatenate that series as a new column (axis 1) in the DataFrame.", "_____no_output_____" ] ], [ [ "passes = pd.Series(df_students['Grade'] >= 60)\ndf_students = pd.concat([df_students, passes.rename(\"Pass\")], axis=1)\n\ndf_students", "_____no_output_____" ] ], [ [ "DataFrames are designed for tabular data, and you can use them to perform many of the kinds of data analytics operation you can do in a relational database; such as grouping and aggregating tables of data.\n\nFor example, you can use the **groupby** method to group the student data into groups based on the **Pass** column you added previously, and count the number of names in each group - in other words, you can determine how many students passed and failed.", "_____no_output_____" ] ], [ [ "print(df_students.groupby(df_students.Pass).Name.count())", "Pass\nFalse 15\nTrue 7\nName: Name, dtype: int64\n" ] ], [ [ "You can aggregate multiple fields in a group using any available aggregation function. For example, you can find the mean study time and grade for the groups of students who passed and failed the course.", "_____no_output_____" ] ], [ [ "print(df_students.groupby(df_students.Pass)['StudyHours', 'Grade'].mean())", " StudyHours Grade\nPass \nFalse 8.783333 38.000000\nTrue 14.250000 73.142857\n" ] ], [ [ "DataFrames are amazingly versatile, and make it easy to manipulate data. Many DataFrame operations return a new copy of the DataFrame; so if you want to modify a DataFrame but keep the existing variable, you need to assign the result of the operation to the existing variable. For example, the following code sorts the student data into descending order of Grade, and assigns the resulting sorted DataFrame to the original **df_students** variable.", "_____no_output_____" ] ], [ [ "# Create a DataFrame with the data sorted by Grade (descending)\ndf_students = df_students.sort_values('Grade', ascending=False)\n\n# Show the DataFrame\ndf_students", "_____no_output_____" ] ], [ [ "## Visualizing data with Matplotlib\n\nDataFrames provide a great way to explore an analyze tabular data, but sometimes a picture is worth a thousand rows and columns. The **Matplotlib** library provides the foundation for plotting data visualizations that can greatly enhance your ability the analyze the data.\n\nLet's start with a simple bar chart that shows the grade of each student.", "_____no_output_____" ] ], [ [ "# Ensure plots are displayed inline in the notebook\n%matplotlib inline\n\nfrom matplotlib import pyplot as plt\n\n# Create a bar plot of name vs grade\nplt.bar(x=df_students.Name, height=df_students.Grade)\n\n# Display the plot\nplt.show()", "_____no_output_____" ] ], [ [ "Well, that worked; but the chart could use some improvements to make it clearer what we're looking at.\n\nNote that you used the **pyplot** class from Matplotlib to plot the chart. This class provides a whole bunch of ways to improve the visual elements of the plot. For example, the following code:\n\n- Specifies the color of the bar chart.\n- Adds a title to the chart (so we know what it represents)\n- Adds labels to the X and Y (so we know which axis shows which data)\n- Adds a grid (to make it easier to determine the values for the bars)\n- Rotates the X markers (so we can read them)", "_____no_output_____" ] ], [ [ "# Create a bar plot of name vs grade\nplt.bar(x=df_students.Name, height=df_students.Grade, color='orange')\n\n# Customize the chart\nplt.title('Student Grades')\nplt.xlabel('Student')\nplt.ylabel('Grade')\nplt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=0.7)\nplt.xticks(rotation=90)\n\n# Display the plot\nplt.show()", "_____no_output_____" ] ], [ [ "A plot is technically contained with a **Figure**. In the previous examples, the figure was created implicitly for you; but you can create it explicitly. For example, the following code creates a figure with a specific size.", "_____no_output_____" ] ], [ [ "# Create a Figure\nfig = plt.figure(figsize=(8,3))\n\n# Create a bar plot of name vs grade\nplt.bar(x=df_students.Name, height=df_students.Grade, color='orange')\n\n# Customize the chart\nplt.title('Student Grades')\nplt.xlabel('Student')\nplt.ylabel('Grade')\nplt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=0.7)\nplt.xticks(rotation=90)\n\n# Show the figure\nplt.show()", "_____no_output_____" ] ], [ [ "A figure can contain multiple subplots, each on its own *axis*.\n\nFor example, the following code creates a figure with two subplots - one is a bar chart showing student grades, and the other is a pie chart comparing the number of passing grades to non-passing grades.", "_____no_output_____" ] ], [ [ "# Create a figure for 2 subplots (1 row, 2 columns)\nfig, ax = plt.subplots(1, 2, figsize = (10,4))\n\n# Create a bar plot of name vs grade on the first axis\nax[0].bar(x=df_students.Name, height=df_students.Grade, color='orange')\nax[0].set_title('Grades')\nax[0].set_xticklabels(df_students.Name, rotation=90)\n\n# Create a pie chart of pass counts on the second axis\npass_counts = df_students['Pass'].value_counts()\nax[1].pie(pass_counts, labels=pass_counts)\nax[1].set_title('Passing Grades')\nax[1].legend(pass_counts.keys().tolist())\n\n# Add a title to the Figure\nfig.suptitle('Student Data')\n\n# Show the figure\nfig.show()", "_____no_output_____" ] ], [ [ "Until now, you've used methods of the Matplotlib.pyplot object to plot charts. However, Matplotlib is so foundational to graphics in Python that many packages, including Pandas, provide methods that abstract the underlying Matplotlib functions and simplify plotting. For example, the DataFrame provides its own methods for plotting data, as shown in the following example to plot a bar chart of study hours.", "_____no_output_____" ] ], [ [ "df_students.plot.bar(x='Name', y='StudyHours', color='teal', figsize=(6,4))", "_____no_output_____" ] ], [ [ "## Getting started with statistical analysis\n\nNow that you know how to use Python to manipulate and visualize data, you can start analyzing it.\n\nA lot of data science is rooted in *statistics*, so we'll explore some basic statistical techniques.\n\n> **Note**: This is <u>not</u> intended to teach you statistics - that's much too big a topic for this notebook. It will however introduce you to some statistical concepts and techniques that data scientists use as they explore data in preparation for machine learning modeling.\n\n### Descriptive statistics and data distribution\n\nWhen examining a *variable* (for example a sample of student grades), data scientists are particularly interested in its *distribution* (in other words, how are all the different grade values spread across the sample). The starting point for this exploration is often to visualize the data as a histogram, and see how frequently each value for the variable occurs.\n\n\n\n\n", "_____no_output_____" ] ], [ [ "# Get the variable to examine\nvar_data = df_students['Grade']\n\n# Create a Figure\nfig = plt.figure(figsize=(10,4))\n\n# Plot a histogram\nplt.hist(var_data)\n\n# Add titles and labels\nplt.title('Data Distribution')\nplt.xlabel('Value')\nplt.ylabel('Frequency')\n\n# Show the figure\nfig.show()", "_____no_output_____" ] ], [ [ "The histogram for grades is a symmetric shape, where the most frequently occuring grades tend to be in the middle of the range (around 50), with fewer grades at the extreme ends of the scale.\n\n#### Measures of central tendency\n\nTo understand the distribution better, we can examine so-called *measures of central tendency*; which is a fancy way of describing statistics that represent the \"middle\" of the data. The goal of this is to try to find a \"typical\" value. Common ways to define the middle of the data include:\n\n- The *mean*: A simple average based on adding together all of the values in the sample set, and then dividing the total by the number of samples.\n- The *median*: The value in the middle of the range of all of the sample values.\n- The *mode*: The most commonly occuring value in the sample set<sup>\\*</sup>.\n\nLet's calculate these values, along with the minimum and maximum values for comparison, and show them on the histogram.\n\n> <sup>\\*</sup>Of course, in some sample sets , there may be a tie for the most common value - in which case the dataset is described as *bimodal* or even *multimodal*.", "_____no_output_____" ] ], [ [ "# Get the variable to examine\nvar = df_students['Grade']\n\n# Get statistics\nmin_val = var.min()\nmax_val = var.max()\nmean_val = var.mean()\nmed_val = var.median()\nmod_val = var.mode()[0]\n\nprint('Minimum:{:.2f}\\nMean:{:.2f}\\nMedian:{:.2f}\\nMode:{:.2f}\\nMaximum:{:.2f}\\n'.format(min_val,\n mean_val,\n med_val,\n mod_val,\n max_val))\n\n# Create a Figure\nfig = plt.figure(figsize=(10,4))\n\n# Plot a histogram\nplt.hist(var)\n\n# Add lines for the statistics\nplt.axvline(x=min_val, color = 'gray', linestyle='dashed', linewidth = 2)\nplt.axvline(x=mean_val, color = 'cyan', linestyle='dashed', linewidth = 2)\nplt.axvline(x=med_val, color = 'red', linestyle='dashed', linewidth = 2)\nplt.axvline(x=mod_val, color = 'yellow', linestyle='dashed', linewidth = 2)\nplt.axvline(x=max_val, color = 'gray', linestyle='dashed', linewidth = 2)\n\n# Add titles and labels\nplt.title('Data Distribution')\nplt.xlabel('Value')\nplt.ylabel('Frequency')\n\n# Show the figure\nfig.show()", "Minimum:3.00\nMean:49.18\nMedian:49.50\nMode:50.00\nMaximum:97.00\n\n" ] ], [ [ "For the grade data, the mean, median, and mode all seem to be more or less in the middle of the minimum and maximum, at around 50.\n\nAnother way to visualize the distribution of a variable is to use a *box* plot (sometimes called a *box-and-whiskers* plot). Let's create one for the grade data.", "_____no_output_____" ] ], [ [ "# Get the variable to examine\nvar = df_students['Grade']\n\n# Create a Figure\nfig = plt.figure(figsize=(10,4))\n\n# Plot a histogram\nplt.boxplot(var)\n\n# Add titles and labels\nplt.title('Data Distribution')\n\n# Show the figure\nfig.show()", "_____no_output_____" ] ], [ [ "The box plot shows the distribution of the grade values in a different format to the histogram. The *box* part of the plot shows where the inner two *quartiles* of the data reside - so in this case, half of the grades are between approximately 36 and 63. The *whiskers* extending from the box show the outer two quartiles; so the other half of the grades in this case are between 0 and 36 or 63 and 100. The line in the box indicates the *median* value.\n\nIt's often useful to combine histograms and box plots, with the box plot's orientation changed to align it with the histogram (in some ways, it can be helpful to think of the histogram as a \"front elevation\" view of the distribution, and the box plot as a \"plan\" view of the distribution from above.)", "_____no_output_____" ] ], [ [ "# Create a function that we can re-use\ndef show_distribution(var_data):\n from matplotlib import pyplot as plt\n\n # Get statistics\n min_val = var_data.min()\n max_val = var_data.max()\n mean_val = var_data.mean()\n med_val = var_data.median()\n mod_val = var_data.mode()[0]\n\n print('Minimum:{:.2f}\\nMean:{:.2f}\\nMedian:{:.2f}\\nMode:{:.2f}\\nMaximum:{:.2f}\\n'.format(min_val,\n mean_val,\n med_val,\n mod_val,\n max_val))\n\n # Create a figure for 2 subplots (2 rows, 1 column)\n fig, ax = plt.subplots(2, 1, figsize = (10,4))\n\n # Plot the histogram \n ax[0].hist(var_data)\n ax[0].set_ylabel('Frequency')\n\n # Add lines for the mean, median, and mode\n ax[0].axvline(x=min_val, color = 'gray', linestyle='dashed', linewidth = 2)\n ax[0].axvline(x=mean_val, color = 'cyan', linestyle='dashed', linewidth = 2)\n ax[0].axvline(x=med_val, color = 'red', linestyle='dashed', linewidth = 2)\n ax[0].axvline(x=mod_val, color = 'yellow', linestyle='dashed', linewidth = 2)\n ax[0].axvline(x=max_val, color = 'gray', linestyle='dashed', linewidth = 2)\n\n # Plot the boxplot \n ax[1].boxplot(var_data, vert=False)\n ax[1].set_xlabel('Value')\n\n # Add a title to the Figure\n fig.suptitle('Data Distribution')\n\n # Show the figure\n fig.show()\n\n# Get the variable to examine\ncol = df_students['Grade']\n# Call the function\nshow_distribution(col)", "Minimum:3.00\nMean:49.18\nMedian:49.50\nMode:50.00\nMaximum:97.00\n\n" ] ], [ [ "All of the measurements of central tendency are right in the middle of the data distribution, which is symmetric with values becoming progressively lower in both directions from the middle.\n\nTo explore this distribution in more detail, you need to understand that statistics is fundamentally about taking *samples* of data and using probability functions to extrapolate information about the full *population* of data. For example, the student data consists of 22 samples, and for each sample there is a grade value. You can think of each sample grade as a variable that's been randomly selected from the set of all grades awarded for this course. With enough of these random variables, you can calculate something called a *probability density function*, which estimates the distribution of grades for the full population.\n\nThe Pandas DataFrame class provides a helpful plot function to show this density.", "_____no_output_____" ] ], [ [ "def show_density(var_data):\n from matplotlib import pyplot as plt\n\n fig = plt.figure(figsize=(10,4))\n\n # Plot density\n var_data.plot.density()\n\n # Add titles and labels\n plt.title('Data Density')\n\n # Show the mean, median, and mode\n plt.axvline(x=var_data.mean(), color = 'cyan', linestyle='dashed', linewidth = 2)\n plt.axvline(x=var_data.median(), color = 'red', linestyle='dashed', linewidth = 2)\n plt.axvline(x=var_data.mode()[0], color = 'yellow', linestyle='dashed', linewidth = 2)\n\n # Show the figure\n plt.show()\n\n# Get the density of Grade\ncol = df_students['Grade']\nshow_density(col)", "_____no_output_____" ] ], [ [ "As expected from the histogram of the sample, the density shows the characteristic 'bell curve\" of what statisticians call a *normal* distribution with the mean and mode at the center and symmetric tails.\n\nNow let's take a look at the distribution of the study hours data.", "_____no_output_____" ] ], [ [ "# Get the variable to examine\ncol = df_students['StudyHours']\n# Call the function\nshow_distribution(col)", "Minimum:1.00\nMean:10.52\nMedian:10.00\nMode:9.00\nMaximum:16.00\n\n" ] ], [ [ "The distribution of the study time data is significantly different from that of the grades.\n\nNote that the whiskers of the box plot only extend to around 6.0, indicating that the vast majority of the first quarter of the data is above this value. The minimum is marked with an **o**, indicating that it is statistically an *outlier* - a value that lies significantly outside the range of the rest of the distribution.\n\nOutliers can occur for many reasons. Maybe a student meant to record \"10\" hours of study time, but entered \"1\" and missed the \"0\". Or maybe the student was abnormally lazy when it comes to studying! Either way, it's a statistical anomaly that doesn't represent a typical student. Let's see what the distribution looks like without it.", "_____no_output_____" ] ], [ [ "# Get the variable to examine\ncol = df_students[df_students.StudyHours>1]['StudyHours']\n# Call the function\nshow_distribution(col)", "Minimum:6.00\nMean:10.98\nMedian:10.00\nMode:9.00\nMaximum:16.00\n\n" ] ], [ [ "In thie example, the datadt is small enough to clearly see that the value **1** is an outlier for the **StudyHours** column, so you can exclude it explicitly. In most real-world cases, it's easier to consider outliers as being values that fall below or above percentiles within which most of the data lie. For example, the following code uses the Pandas **quantile** function to exclude observations below the 0.01th percentile (the value above which 99% of the data reside).", "_____no_output_____" ] ], [ [ "q01 = df_students.StudyHours.quantile(0.01)\n# Get the variable to examine\ncol = df_students[df_students.StudyHours>q01]['StudyHours']\n# Call the function\nshow_distribution(col)", "Minimum:6.00\nMean:10.98\nMedian:10.00\nMode:9.00\nMaximum:16.00\n\n" ] ], [ [ "> **Tip**: You can also eliminate outliers at the upper end of the distribution by defining a threshold at a high percentile value - for example, you could use the **quantile** function to find the 0.99 percentile below which 99% of the data reside.\n\nWith the outliers removed, the box plot shows all data within the four quartiles. Note that the distribution is not symmetric like it is for the grade data though - there are some students with very high study times of around 16 hours, but the bulk of the data is between 7 and 13 hours; The few extremely high values pull the mean towards the higher end of the scale.\n\nLet's look at the density for this distribution.", "_____no_output_____" ] ], [ [ "# Get the density of StudyHours\nshow_density(col)", "_____no_output_____" ] ], [ [ "This kind of distribution is called *right skewed*. The mass of the data is on the left side of the distribution, creating a long tail to the right because of the values at the extreme high end; which pull the mean to the right.\n\n#### Measures of variance\n\nSo now we have a good idea where the middle of the grade and study hours data distributions are. However, there's another aspect of the distributions we should examine: how much variability is there in the data?\n\nTypical statistics that measure variability in the data include:\n\n- **Range**: The difference between the maximum and minimum. There's no built-in function for this, but it's easy to calculate using the **min** and **max** functions.\n- **Variance**: The average of the squared difference from the mean. You can use the built-in **var** function to find this.\n- **Standard Deviation**: The square root of the variance. You can use the built-in **std** function to find this.", "_____no_output_____" ] ], [ [ "for col_name in ['Grade','StudyHours']:\n col = df_students[col_name]\n rng = col.max() - col.min()\n var = col.var()\n std = col.std()\n print('\\n{}:\\n - Range: {:.2f}\\n - Variance: {:.2f}\\n - Std.Dev: {:.2f}'.format(col_name, rng, var, std))", "\nGrade:\n - Range: 94.00\n - Variance: 472.54\n - Std.Dev: 21.74\n\nStudyHours:\n - Range: 15.00\n - Variance: 12.16\n - Std.Dev: 3.49\n" ] ], [ [ "Of these statistics, the standard deviation is generally the most useful. It provides a measure of variance in the data on the same scale as the data itself (so grade points for the Grade distribution and hours for the StudyHours distribution). The higher the standard deviation, the more variance there is when comparing values in the distribution to the distribution mean - in other words, the data is more spread out.\n\nWhen working with a *normal* distribution, the standard deviation works with the particular characteristics of a normal distribution to provide even greater insight. Run the cell below to see the relationship between standard deviations and the data in the normal distribution.", "_____no_output_____" ] ], [ [ "import scipy.stats as stats\n\n# Get the Grade column\ncol = df_students['Grade']\n\n# get the density\ndensity = stats.gaussian_kde(col)\n\n# Plot the density\ncol.plot.density()\n\n# Get the mean and standard deviation\ns = col.std()\nm = col.mean()\n\n# Annotate 1 stdev\nx1 = [m-s, m+s]\ny1 = density(x1)\nplt.plot(x1,y1, color='magenta')\nplt.annotate('1 std (68.26%)', (x1[1],y1[1]))\n\n# Annotate 2 stdevs\nx2 = [m-(s*2), m+(s*2)]\ny2 = density(x2)\nplt.plot(x2,y2, color='green')\nplt.annotate('2 std (95.45%)', (x2[1],y2[1]))\n\n# Annotate 3 stdevs\nx3 = [m-(s*3), m+(s*3)]\ny3 = density(x3)\nplt.plot(x3,y3, color='orange')\nplt.annotate('3 std (99.73%)', (x3[1],y3[1]))\n\n# Show the location of the mean\nplt.axvline(col.mean(), color='cyan', linestyle='dashed', linewidth=1)\n\nplt.axis('off')\n\nplt.show()", "_____no_output_____" ] ], [ [ "The horizontal lines show the percentage of data within 1, 2, and 3 standard deviations of the mean (plus or minus).\n\nIn any normal distribution:\n- Approximately 68.26% of values fall within one standard deviation from the mean.\n- Approximately 95.45% of values fall within two standard deviations from the mean.\n- Approximately 99.73% of values fall within three standard deviations from the mean.\n\nSo, since we know that the mean grade is 49.8, the standard deviation is 21.47, and distribution of grades is approximately normal; we can calculate that 68.26% of students should achieve a grade between 28.33 and 71.27.\n\nThe descriptive statistics we've used to understand the distribution of the student data variables are the basis of statistical analysis; and because they're such an important part of exploring your data, there's a built-in **Describe** method of the DataFrame object that returns the main descriptive statistics for all numeric columns.", "_____no_output_____" ] ], [ [ "df_students.describe()", "_____no_output_____" ] ], [ [ "## Comparing data\n\nNow that you know something about the statistical distribution of the data in your dataset, you're ready to examine your data to identify any apparent relationships between variables.\n\nFirst of all, let's get rid of any rows that contain outliers so that we have a sample that is representative of a typical class of students. We identified that the StudyHours column contains some outliers with extremely low values, so we'll remove those rows.", "_____no_output_____" ] ], [ [ "df_sample = df_students[df_students['StudyHours']>1]\ndf_sample", "_____no_output_____" ] ], [ [ "### Comparing numeric and categorical variables\n\nThe data includes two *numeric* variables (**StudyHours** and **Grade**) and two *categorical* variables (**Name** and **Pass**). Let's start by comparing the numeric **StudyHours** column to the categorical **Pass** column to see if there's an apparent relationship between the number of hours studied and a passing grade.\n\nTo make this comparison, let's create box plots showing the distribution of StudyHours for each possible Pass value (true and false).", "_____no_output_____" ] ], [ [ "df_sample.boxplot(column='StudyHours', by='Pass', figsize=(8,5))", "_____no_output_____" ] ], [ [ "Comparing the StudyHours distributions, it's immediately apparent (if not particularly surprising) that students who passed the course tended to study for more hours than students who didn't. So if you wanted to predict whether or not a student is likely to pass the course, the amount of time they spend studying may be a good predictive feature.\n\n### Comparing numeric variables\n\nNow let's compare two numeric variables. We'll start by creating a bar chart that shows both grade and study hours.", "_____no_output_____" ] ], [ [ "# Create a bar plot of name vs grade and study hours\ndf_sample.plot(x='Name', y=['Grade','StudyHours'], kind='bar', figsize=(8,5))", "_____no_output_____" ] ], [ [ "The chart shows bars for both grade and study hours for each student; but it's not easy to compare because the values are on different scales. Grades are measured in grade points, and range from 3 to 97; while study time is measured in hours and ranges from 1 to 16.\n\nA common technique when dealing with numeric data in different scales is to *normalize* the data so that the values retain their proportional distribution, but are measured on the same scale. To accomplish this, we'll use a technique called *MinMax* scaling that distributes the values proportionally on a scale of 0 to 1. You could write the code to apply this transformation; but the **Scikit-Learn** library provides a scaler to do it for you.", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import MinMaxScaler\n\n# Get a scaler object\nscaler = MinMaxScaler()\n\n# Create a new dataframe for the scaled values\ndf_normalized = df_sample[['Name', 'Grade', 'StudyHours']].copy()\n\n# Normalize the numeric columns\ndf_normalized[['Grade','StudyHours']] = scaler.fit_transform(df_normalized[['Grade','StudyHours']])\n\n# Plot the normalized values\ndf_normalized.plot(x='Name', y=['Grade','StudyHours'], kind='bar', figsize=(8,5))", "_____no_output_____" ] ], [ [ "With the data normalized, it's easier to see an apparent relationship between grade and study time. It's not an exact match, but it definitely seems like students with higher grades tend to have studied more.\n\nSo there seems to be a correlation between study time and grade; and in fact, there's a statistical *correlation* measurement we can use to quantify the relationship between these columns.", "_____no_output_____" ] ], [ [ "df_normalized.Grade.corr(df_normalized.StudyHours)", "_____no_output_____" ] ], [ [ "The correlation statistic is a value between -1 and 1 that indicates the strength of a relationship. Values above 0 indicate a *positive* correlation (high values of one variable tend to coincide with high values of the other), while values below 0 indicate a *negative* correlation (high values of one variable tend to coincide with low values of the other). In this case, the correlation value is close to 1; showing a strongly positive correlation between study time and grade.\n\n> **Note**: Data scientists often quote the maxim \"*correlation* is not *causation*\". In other words, as tempting as it might be, you shouldn't interpret the statistical correlation as explaining *why* one of the values is high. In the case of the student data, the statistics demonstrates that students with high grades tend to also have high amounts of study time; but this is not the same as proving that they achieved high grades *because* they studied a lot. The statistic could equally be used as evidence to support the nonsensical conclusion that the students studied a lot *because* their grades were going to be high.\n\nAnother way to visualise the apparent correlation between two numeric columns is to use a *scatter* plot.", "_____no_output_____" ] ], [ [ "# Create a scatter plot\ndf_sample.plot.scatter(title='Study Time vs Grade', x='StudyHours', y='Grade')", "_____no_output_____" ] ], [ [ "Again, it looks like there's a discernible pattern in which the students who studied the most hours are also the students who got the highest grades.\n\nWe can see this more clearly by adding a *regression* line (or a *line of best fit*) to the plot that shows the general trend in the data. To do this, we'll use a statistical technique called *least squares regression*.\n\n> **Warning - Math Ahead!**\n>\n> Cast your mind back to when you were learning how to solve linear equations in school, and recall that the *slope-intercept* form of a linear equation lookes like this:\n>\n> \\begin{equation}y = mx + b\\end{equation}\n>\n> In this equation, *y* and *x* are the coordinate variables, *m* is the slope of the line, and *b* is the y-intercept (where the line goes through the Y axis).\n>\n> In the case of our scatter plot for our student data, we already have our values for *x* (*StudyHours*) and *y* (*Grade*), so we just need to calculate the intercept and slope of the straight line that lies closest to those points. Then we can form a linear equation that calculates a new *y* value on that line for each of our *x* (*StudyHours*) values - to avoid confusion, we'll call this new *y* value *f(x)* (because it's the output from a linear equation ***f***unction based on *x*). The difference between the original *y* (*Grade*) value and the *f(x)* value is the *error* between our regression line and the actual *Grade* achieved by the student. Our goal is to calculate the slope and intercept for a line with the lowest overall error.\n>\n> Specifically, we define the overall error by taking the error for each point, squaring it, and adding all the squared errors together. The line of best fit is the line that gives us the lowest value for the sum of the squared errors - hence the name *least squares regression*.\n\nFortunately, you don't need to code the regression calculation yourself - the **SciPy** package includes a **stats** class that provides a **linregress** method to do the hard work for you. This returns (among other things) the coefficients you need for the slope equation - slope (*m*) and intercept (*b*) based on a given pair of variable samples you want to compare.", "_____no_output_____" ] ], [ [ "from scipy import stats\n\n#\ndf_regression = df_sample[['Grade', 'StudyHours']].copy()\n\n# Get the regression slope and intercept\nm, b, r, p, se = stats.linregress(df_regression['StudyHours'], df_regression['Grade'])\nprint('slope: {:.4f}\\ny-intercept: {:.4f}'.format(m,b))\nprint('so...\\n f(x) = {:.4f}x + {:.4f}'.format(m,b))\n\n# Use the function (mx + b) to calculate f(x) for each x (StudyHours) value\ndf_regression['fx'] = (m * df_regression['StudyHours']) + b\n\n# Calculate the error between f(x) and the actual y (Grade) value\ndf_regression['error'] = df_regression['fx'] - df_regression['Grade']\n\n# Create a scatter plot of Grade vs Salary\ndf_regression.plot.scatter(x='StudyHours', y='Grade')\n\n# Plot the regression line\nplt.plot(df_regression['StudyHours'],df_regression['fx'], color='cyan')\n\n# Display the plot\nplt.show()", "slope: 6.3134\ny-intercept: -17.9164\nso...\n f(x) = 6.3134x + -17.9164\n" ] ], [ [ "Note that this time, the code plotted two distinct things - the scatter plot of the sample study hours and grades is plotted as before, and then a line of best fit based on the least squares regression coefficients is plotted.\n\nThe slope and intercept coefficients calculated for the regression line are shown above the plot.\n\nThe line is based on the ***f*(x)** values calculated for each **StudyHours** value. Run the following cell to see a table that includes the following values:\n\n- The **StudyHours** for each student.\n- The **Grade** achieved by each student.\n- The ***f(x)*** value calculated using the regression line coefficients.\n- The *error* between the calculated ***f(x)*** value and the actual **Grade** value.\n\nSome of the errors, particularly at the extreme ends, and quite large (up to over 17.5 grade points); but in general, the line is pretty close to the actual grades.", "_____no_output_____" ] ], [ [ "# Show the original x,y values, the f(x) value, and the error\ndf_regression[['StudyHours', 'Grade', 'fx', 'error']]", "_____no_output_____" ] ], [ [ "### Using the regression coefficients for prediction\n\nNow that you have the regression coefficients for the study time and grade relationship, you can use them in a function to estimate the expected grade for a given amount of study.", "_____no_output_____" ] ], [ [ "# Define a function based on our regression coefficients\ndef f(x):\n m = 6.3134\n b = -17.9164\n return m*x + b\n\nstudy_time = 14\n\n# Get f(x) for study time\nprediction = f(study_time)\n\n# Grade can't be less than 0 or more than 100\nexpected_grade = max(0,min(100,prediction))\n\n#Print the estimated grade\nprint ('Studying for {} hours per week may result in a grade of {:.0f}'.format(study_time, expected_grade))", "Studying for 14 hours per week may result in a grade of 70\n" ] ], [ [ "So by applying statistics to sample data, you've determined a relationship between study time and grade; and encapsulated that relationship in a general function that can be used to predict a grade for a given amount of study time.\n\nThis technique is in fact the basic premise of machine learning. You can take a set of sample data that includes one or more *features* (in this case, the number of hours studied) and a known *label* value (in this case, the grade achieved) and use the sample data to derive a function that calculates predicted label values for any given set of features.", "_____no_output_____" ], [ "## Further Reading\n\nTo learn more about the Python packages you explored in this notebook, see the following documentation:\n\n- [NumPy](https://numpy.org/doc/stable/)\n- [Pandas](https://pandas.pydata.org/pandas-docs/stable/)\n- [Matplotlib](https://matplotlib.org/contents.html)\n\n## Challenge: Analyze Flight Data\n\nIf this notebook has inspired you to try exploring data for yourself, why not take on the challenge of a real-world dataset containing flight records from the US Department of Transportation? You'll find the challenge in the [/challenges/01 - Flights Challenge.ipynb](./challenges/01%20-%20Flights%20Challenge.ipynb) notebook!\n\n> **Note**: The time to complete this optional challenge is not included in the estimated time for this exercise - you can spend as little or as much time on it as you like!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "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" ] ]
cb273db2664ca1bd7957fc250da1fc44f579ac96
443,419
ipynb
Jupyter Notebook
21_Analyzing Police Activity with pandas/Police_Activity_data_for_analysis.ipynb
mohd-faizy/DataScience-With-Python
13ebb10cf9083343056d5b782957241de1d595f9
[ "MIT" ]
5
2021-02-03T14:36:58.000Z
2022-01-01T10:29:26.000Z
21_Analyzing Police Activity with pandas/Police_Activity_data_for_analysis.ipynb
mohd-faizy/DataScience-With-Python
13ebb10cf9083343056d5b782957241de1d595f9
[ "MIT" ]
null
null
null
21_Analyzing Police Activity with pandas/Police_Activity_data_for_analysis.ipynb
mohd-faizy/DataScience-With-Python
13ebb10cf9083343056d5b782957241de1d595f9
[ "MIT" ]
3
2021-02-08T00:31:16.000Z
2022-03-17T13:52:32.000Z
66.790029
22,586
0.692577
[ [ [ "<a href=\"https://colab.research.google.com/github/mohd-faizy/CAREER-TRACK-Data-Scientist-with-Python/blob/main/Police_Activity_data_for_analysis.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "--- \r\n<strong> \r\n <h1 align='center'>Preparing the Police Activity data for analysis (Part - 1)\r\n </h1> \r\n</strong>\r\n\r\n---", "_____no_output_____" ] ], [ [ "!git clone https://github.com/mohd-faizy/CAREER-TRACK-Data-Scientist-with-Python.git", "Cloning into 'CAREER-TRACK-Data-Scientist-with-Python'...\nremote: Enumerating objects: 440, done.\u001b[K\nremote: Counting objects: 100% (440/440), done.\u001b[K\nremote: Compressing objects: 100% (375/375), done.\u001b[K\nremote: Total 1811 (delta 131), reused 367 (delta 60), pack-reused 1371\u001b[K\nReceiving objects: 100% (1811/1811), 188.37 MiB | 18.41 MiB/s, done.\nResolving deltas: 100% (623/623), done.\nChecking out files: 100% (802/802), done.\n" ] ], [ [ "__Change the current working directory__", "_____no_output_____" ] ], [ [ "# import os module \r\nimport os \r\n \r\n# to specified path \r\nos.chdir('/content/CAREER-TRACK-Data-Scientist-with-Python/21_Analyzing Police Activity with pandas/_dataset') \r\n \r\n# varify the path using getcwd() \r\ncwd = os.getcwd() \r\n \r\n# print the current directory \r\nprint(\"Current working directory is:\", cwd) ", "Current working directory is: /content/CAREER-TRACK-Data-Scientist-with-Python/21_Analyzing Police Activity with pandas/_dataset\n" ], [ "ls", "police.csv weather.csv\n" ] ], [ [ "## $\\color{green}{\\textbf{Dataset_1_police.csv:}}$ \r\n\r\n[Stanford Open Policing Project dataset](https://openpolicing.stanford.edu/)\r\n\r\n\r\nOn a typical day in the United States, police officers make more than 50,000 traffic stops. __THE STANFORD OPEN POLICING PROJECT__ gathers, analyse, and release the records from millions of traffic stops by law enforcement agencies across the __US__.\r\n\r\n<p align='center'>\r\n <a href=\"#\">\r\n <img src='https://policylab.stanford.edu/images/icons/stanford-open-policing-project.png' width=500px height=300px alt=\"\">\r\n </a>\r\n</p>\r\n\r\n", "_____no_output_____" ], [ "## __01 Examining the dataset__\r\n\r\nBefore beginning your analysis, it's important that you familiarize yourself with the dataset. In this exercise, we'll read the dataset into pandas, examine the first few rows, and then count the number of missing values.", "_____no_output_____" ] ], [ [ "# Import the pandas library as pd\r\nimport pandas as pd\r\n\r\n# Read 'police.csv' into a DataFrame named ri\r\nri = pd.read_csv('police.csv')\r\n\r\n# Examine the head of the DataFrame\r\nri.head()", "_____no_output_____" ], [ "ri.isna().sum()", "_____no_output_____" ], [ "ri.isnull()", "_____no_output_____" ], [ "# Count the number of missing values in each column\r\nri.isnull().sum()", "_____no_output_____" ] ], [ [ "## __02 Dropping columns__\r\n\r\nOften, a DataFrame will contain columns that are not useful to our analysis. Such columns should be dropped from the DataFrame, to make it easier for us to focus on the remaining columns.\r\n\r\nIn this exercise, we'll drop the `'county_name'` column because it only contains missing values, and we'll drop the `'state'` column because all of the traffic stops took place in one state (__Rhode Island__).\r\n\r\nThus, these columns can be dropped because **they contain no useful information**. ", "_____no_output_____" ] ], [ [ "# Examine the shape of the DataFrame\r\nprint(ri.shape)\r\n\r\n# Drop the 'county_name' and 'state' columns\r\nri.drop(['county_name', 'state'], axis='columns', inplace=True)\r\n\r\n# Examine the shape of the DataFrame (again)\r\nprint(ri.shape)", "(91741, 15)\n(91741, 13)\n" ] ], [ [ "## __03 Dropping rows__\r\n\r\nWhen we know that a **specific column** will be **critical to our analysis**, and only a small fraction of rows are missing a value in that column, *it often makes sense to remove those rows from the dataset.*\r\n\r\nthe `'driver_gender'` column will be critical to many of our analyses. Because only a small fraction of rows are missing `'driver_gender'`, we'll drop those rows from the dataset.", "_____no_output_____" ] ], [ [ "# Count the number of missing values in each column\r\nprint(ri.isnull().sum())", "stop_date 0\nstop_time 0\ndriver_gender 5205\ndriver_race 5202\nviolation_raw 5202\nviolation 5202\nsearch_conducted 0\nsearch_type 88434\nstop_outcome 5202\nis_arrested 5202\nstop_duration 5202\ndrugs_related_stop 0\ndistrict 0\ndtype: int64\n" ], [ "# Drop all rows that are missing 'driver_gender'\r\nri.dropna(subset=['driver_gender'], inplace=True)\r\n\r\n# Count the number of missing values in each column (again)\r\nprint(ri.isnull().sum())", "stop_date 0\nstop_time 0\ndriver_gender 0\ndriver_race 0\nviolation_raw 0\nviolation 0\nsearch_conducted 0\nsearch_type 83229\nstop_outcome 0\nis_arrested 0\nstop_duration 0\ndrugs_related_stop 0\ndistrict 0\ndtype: int64\n" ], [ "# Examine the shape of the DataFrame\r\nprint(ri.shape)", "(86536, 13)\n" ] ], [ [ "## __04 Finding an incorrect data type__", "_____no_output_____" ] ], [ [ "ri.dtypes", "_____no_output_____" ] ], [ [ "$\\color{green}{\\textbf{Note:}} $ $\\Rightarrow$ `is_arrested` should have a data type of __bool__", "_____no_output_____" ], [ "## __05 Fixing a data type__\r\n\r\n- `is_arrested column` currently has the __object__ data type. \r\n\r\n- we have to change the data type to __bool__, which is the most suitable type for a column containing **True** and **False** values.\r\n\r\n>Fixing the data type will enable us to use __mathematical operations__ on the `is_arrested` column that would not be possible otherwise.", "_____no_output_____" ] ], [ [ "# Examine the head of the 'is_arrested' column\r\nprint(ri.is_arrested.head())", "0 False\n1 False\n2 False\n3 True\n4 False\nName: is_arrested, dtype: object\n" ], [ "# Change the data type of 'is_arrested' to 'bool'\r\nri['is_arrested'] = ri.is_arrested.astype('bool')\r\n\r\n# Check the data type of 'is_arrested' \r\nprint(ri.is_arrested.dtype)", "bool\n" ] ], [ [ "## __06 Combining object columns (datetime format)__", "_____no_output_____" ], [ "- Currently, the date and time of each traffic stop are stored in separate object columns: **stop_date** and **stop_time**.\r\n\r\n- we have to **combine** these two columns into a **single column**, and then convert it to **datetime format**. \r\n\r\n- This will be beneficial because unlike object columns, datetime columns provide date-based attributes that will make our analysis easier.", "_____no_output_____" ] ], [ [ "# Concatenate 'stop_date' and 'stop_time' (separated by a space)\r\ncombined = ri.stop_date.str.cat(ri.stop_time, sep=' ')\r\n\r\n# Convert 'combined' to datetime format\r\nri['stop_datetime'] = pd.to_datetime(combined)\r\n\r\n# Examine the data types of the DataFrame\r\nprint(ri.dtypes)", "stop_date object\nstop_time object\ndriver_gender object\ndriver_race object\nviolation_raw object\nviolation object\nsearch_conducted bool\nsearch_type object\nstop_outcome object\nis_arrested bool\nstop_duration object\ndrugs_related_stop bool\ndistrict object\nstop_datetime datetime64[ns]\ndtype: object\n" ] ], [ [ "## __07 Setting the index__\r\n\r\nThe last step is to set the `stop_datetime` column as the DataFrame's **index**. By **replacing** the **default index** with a **DatetimeIndex**, this will make it easier to analyze the dataset by date and time, which will come in handy later.\r\n\r\n\r\n", "_____no_output_____" ] ], [ [ "# Set 'stop_datetime' as the index\r\nri.set_index('stop_datetime', inplace=True)\r\n\r\n# Examine the index\r\nri.index", "_____no_output_____" ], [ "# Examine the columns\r\nri.columns", "_____no_output_____" ], [ "ri.head()", "_____no_output_____" ] ], [ [ "--- \r\n<strong> \r\n <h1 align='center'>Exploring the relationship between gender and policing (Part - 2)\r\n </h1> \r\n</strong>\r\n\r\n---", "_____no_output_____" ], [ "## __08 Examining traffic violations__ \r\n\r\nBefore comparing the violations being committed by each gender, we should examine the **violations** committed by all drivers to get a baseline understanding of the data.\r\n\r\nIn this exercise, we'll count the **unique values** in the `violation` column, and then separately express those counts as **proportions**.", "_____no_output_____" ] ], [ [ "ri['violation'].value_counts()", "_____no_output_____" ], [ "# dot method\r\n# Count the unique values in 'violation'\r\nri.violation.value_counts()", "_____no_output_____" ], [ "# Counting unique values (2)\r\nprint(ri.violation.value_counts().sum()) \r\nprint(ri.shape)", "86536\n(86536, 13)\n" ], [ "48423/86536 # Speeding `55.95%`", "_____no_output_____" ], [ "# Express the counts as proportions\r\nri.violation.value_counts(normalize=True)", "_____no_output_____" ] ], [ [ "More than half of all violations are for **speeding**, followed by other moving violations and equipment violations.", "_____no_output_____" ], [ "## __09 Comparing violations by gender__", "_____no_output_____" ], [ "The question we're trying to answer is whether male and female drivers tend to commit different types of traffic violations.\r\n\r\nIn this exercise, we'll first create a DataFrame for each gender, and then analyze the violations in each DataFrame separately.", "_____no_output_____" ] ], [ [ "# Create a DataFrame of male drivers\r\nmale = ri[ri.driver_gender == 'M']\r\n\r\n# Create a DataFrame of female drivers\r\nfemale = ri[ri.driver_gender == 'F']", "_____no_output_____" ], [ "\r\n# Compute the violations by male drivers (as proportions)\r\nprint(male.violation.value_counts(normalize=True))", "Speeding 0.522243\nMoving violation 0.206144\nEquipment 0.134158\nOther 0.058985\nRegistration/plates 0.042175\nSeat belt 0.036296\nName: violation, dtype: float64\n" ], [ "# Compute the violations by female drivers (as proportions)\r\nprint(female.violation.value_counts(normalize=True))", "Speeding 0.658114\nMoving violation 0.138218\nEquipment 0.105199\nRegistration/plates 0.044418\nOther 0.029738\nSeat belt 0.024312\nName: violation, dtype: float64\n" ] ], [ [ "## __10 Filtering by multiple conditions__", "_____no_output_____" ], [ "Which one of these commands would filter the `ri` DataFrame to only include female drivers **who were stopped for a speeding violation**?", "_____no_output_____" ] ], [ [ "female_and_speeding = ri[(ri.driver_gender == 'F') & (ri.violation == 'Speeding')]\r\nfemale_and_speeding", "_____no_output_____" ] ], [ [ "## __11 Comparing speeding outcomes by gender__", "_____no_output_____" ], [ "When a driver is pulled over for `speeding`, **many people believe that gender has an impact on whether the driver will receive a ticket or a warning**. Can you find evidence of this in the dataset?\r\n\r\nFirst, you'll create two DataFrames of drivers who were stopped for speeding: one containing females and the other containing males.\r\n\r\nThen, for each gender, you'll use the `stop_outcome` column to calculate what percentage of stops resulted in a \"Citation\" (meaning a ticket) versus a \"Warning\".", "_____no_output_____" ] ], [ [ "# Create a DataFrame of female drivers stopped for speeding\r\nfemale_and_speeding = ri[(ri.driver_gender == 'F') & (ri.violation == 'Speeding')]\r\n\r\n# Compute the stop outcomes for female drivers (as proportions)\r\nprint(female_and_speeding.stop_outcome.value_counts(normalize=True))", "Citation 0.952192\nWarning 0.040074\nArrest Driver 0.005752\nN/D 0.000959\nArrest Passenger 0.000639\nNo Action 0.000383\nName: stop_outcome, dtype: float64\n" ], [ "# Create a DataFrame of male drivers stopped for speeding\r\nmale_and_speeding = ri[(ri.driver_gender == 'M') & (ri.violation == 'Speeding')]\r\n\r\n# Compute the stop outcomes for male drivers (as proportions)\r\nprint(male_and_speeding.stop_outcome.value_counts(normalize=True))", "Citation 0.944595\nWarning 0.036184\nArrest Driver 0.015895\nArrest Passenger 0.001281\nNo Action 0.001068\nN/D 0.000976\nName: stop_outcome, dtype: float64\n" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>The numbers are similar for **males** and **females**: about **95%** of stops for speeding result in a ticket. Thus, __the data fails to show that gender has an impact on who gets a ticket for speeding__.", "_____no_output_____" ] ], [ [ "# Filtering by multiple conditions (1)\r\nfemale = ri[ri.driver_gender == 'F']\r\nfemale.shape", "_____no_output_____" ], [ "# Filtering by multiple conditions (2)\r\n# Only includes female drivers who were arrested\r\nfemale_and_arrested = ri[(ri.driver_gender == 'F') &(ri.is_arrested == True)]\r\nfemale_and_arrested.shape", "_____no_output_____" ], [ "# Filtering by multiple conditions (3)\r\nfemale_or_arrested = ri[(ri.driver_gender == 'F') | (ri.is_arrested == True)]\r\nfemale_or_arrested.shape", "_____no_output_____" ] ], [ [ "- Includes all females\r\n- Includes all drivers who were arrested", "_____no_output_____" ], [ "## __12 Comparing stop outcomes for two groups__", "_____no_output_____" ] ], [ [ "# driver race --> White\r\nwhite = ri[ri.driver_race == 'White']\r\nwhite.stop_outcome.value_counts(normalize=True)", "_____no_output_____" ], [ "# driver race --> Black\r\nblack = ri[ri.driver_race =='Black']\r\nblack.stop_outcome.value_counts(normalize=True)", "_____no_output_____" ], [ "# driver race --> Asian\r\nasian = ri[ri.driver_race =='Asian']\r\nasian.stop_outcome.value_counts(normalize=True)", "_____no_output_____" ] ], [ [ "## __13 Does gender affect whose vehicle is searched?__", "_____no_output_____" ], [ "**Mean** of **Boolean Series** represents percentage of True values", "_____no_output_____" ] ], [ [ "ri.isnull().sum()", "_____no_output_____" ], [ "# Taking the mean of a Boolean Series\r\nprint(ri.is_arrested.value_counts(normalize=True))\r\nprint(ri.is_arrested.mean())\r\nprint(ri.is_arrested.dtype)", "False 0.964431\nTrue 0.035569\nName: is_arrested, dtype: float64\n0.0355690117407784\nbool\n" ] ], [ [ "__Comparing groups using groupby (1)__", "_____no_output_____" ] ], [ [ "# Study the arrest rate by police district\r\nprint(ri.district.unique())\r\n\r\n# Mean\r\nprint(ri[ri.district == 'Zone K1'].is_arrested.mean())", "['Zone X4' 'Zone K3' 'Zone X1' 'Zone X3' 'Zone K1' 'Zone K2']\n0.024349083895853423\n" ] ], [ [ "__Comparing groups using groupby (2)__", "_____no_output_____" ] ], [ [ "ri[ri.district == 'Zone K2'].is_arrested.mean()", "_____no_output_____" ], [ "ri.groupby('district').is_arrested.mean()", "_____no_output_____" ] ], [ [ "__Grouping by multiple categories__", "_____no_output_____" ] ], [ [ "ri.groupby(['district', 'driver_gender']).is_arrested.mean()", "_____no_output_____" ], [ "ri.groupby(['driver_gender', 'district']).is_arrested.mean()", "_____no_output_____" ] ], [ [ "## __14 Calculating the search rate__\r\n\r\nDuring a traffic stop, the police officer sometimes conducts a search of the vehicle.\r\n\r\nIn this exercise, you'll calculate the percentage of all stops in the ri DataFrame that result in a vehicle search, also known as the search rate.", "_____no_output_____" ] ], [ [ "# Check the data type of 'search_conducted'\r\nprint(ri.search_conducted.dtype)\r\n\r\n# Calculate the search rate by counting the values\r\nprint(ri.search_conducted.value_counts(normalize=True))\r\n\r\n# Calculate the search rate by taking the mean\r\nprint(ri.search_conducted.mean())", "bool\nFalse 0.961785\nTrue 0.038215\nName: search_conducted, dtype: float64\n0.0382153092354627\n" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>It looks like the search rate is about __3.8%__.", "_____no_output_____" ], [ "### __Comparing search rates by gender__", "_____no_output_____" ], [ "Remember that the vehicle **search rate **across all stops is about __3.8%.__\r\n\r\nFirst, we'll filter the DataFrame by gender and calculate the **search rate** for each group separately. Then, you'll perform the same calculation for both genders at once using a `.groupby()`.", "_____no_output_____" ], [ "__Instructions:__\r\n\r\n- Filter the DataFrame to only include female drivers, and then calculate the search rate by taking the mean of search_conducted.\r\n\r\n- Filter the DataFrame to only include male drivers, and then repeat the search rate calculation.\r\n\r\n- Group by driver gender to calculate the search rate for both groups simultaneously. (It should match the previous results.)", "_____no_output_____" ] ], [ [ "# Calculate the search rate for female drivers\r\nprint(ri[ri.driver_gender == 'F'].search_conducted.mean())", "0.019180617481282074\n" ], [ "# Calculate the search rate for male drivers\r\nprint(ri[ri.driver_gender == 'M'].search_conducted.mean())", "0.04542557598546892\n" ], [ "# Calculate the search rate for both groups simultaneously\r\nprint(ri.groupby('driver_gender').search_conducted.mean())", "driver_gender\nF 0.019181\nM 0.045426\nName: search_conducted, dtype: float64\n" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>Male drivers are searched more than twice as often as female drivers. Why might this be?\r\n", "_____no_output_____" ], [ "## __15 Adding a second factor to the analysis__", "_____no_output_____" ], [ "Even though the **search rate** for **males is much higher than for females**, *it's possible that the difference is mostly due to a second factor.*\r\n\r\n>For example, we might **hypothesize** that **the search rate varies by violation type**, and the difference in search rate between males and females is because they tend to commit different violations.\r\n\r\nwe can test this hypothesis by examining the **search rate** for **each combination of gender and violation**. If the hypothesis was true, you would find that males and females are searched at about the same rate for each violation. Find out below if that's the case!", "_____no_output_____" ], [ "__Instructions__\r\n\r\n- Use a `.groupby()` to calculate the search rate for each combination of gender and violation. Are males and females searched at about the same rate for each violation?\r\n\r\n- Reverse the ordering to group by violation before gender. The results may be easier to compare when presented this way.", "_____no_output_____" ] ], [ [ "# Calculate the search rate for each combination of gender and violation\r\nri.groupby(['driver_gender', 'violation']).search_conducted.mean()", "_____no_output_____" ], [ "# Reverse the ordering to group by violation before gender\r\nri.groupby(['violation', 'driver_gender']).search_conducted.mean()", "_____no_output_____" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>For all types of violations, the search rate is higher for males than for females, disproving our hypothesis", "_____no_output_____" ], [ "## __16 Does gender affect who is frisked during a search?__", "_____no_output_____" ] ], [ [ "ri.search_conducted.value_counts()", "_____no_output_____" ] ], [ [ "`.value_counts()`\r\n__excludes missing\r\nvalues by default__\r\n", "_____no_output_____" ] ], [ [ "ri.search_type.value_counts(dropna=False)", "_____no_output_____" ] ], [ [ "\r\n- `dropna=False`\r\n **displays missing\r\nvalues**", "_____no_output_____" ], [ "**Examining the search types**", "_____no_output_____" ] ], [ [ "ri.search_type.value_counts()", "_____no_output_____" ] ], [ [ "- Multiple values are separated by commas.\r\n\r\n- 219 searches in which **\"Inventory\"** was the only search type.\r\n\r\n- Locate **\"Inventory\"** among multiple search types.", "_____no_output_____" ], [ "__Searching for a string (1)__", "_____no_output_____" ] ], [ [ "ri['inventory'] = ri.search_type.str.contains('Inventory', na=False)", "_____no_output_____" ] ], [ [ "- `str.contains()` returns\r\n - True if string is found\r\n - False if not found.\r\n\r\n- `na=False` returns `False` when it ,finds a missing value", "_____no_output_____" ], [ "__Searching for a string (2)__", "_____no_output_____" ] ], [ [ "ri.inventory.dtype", "_____no_output_____" ] ], [ [ "**True** means inventory was done, **False** means it was not", "_____no_output_____" ] ], [ [ "ri.inventory.sum()", "_____no_output_____" ] ], [ [ "__Calculating the inventory rate__", "_____no_output_____" ] ], [ [ "ri.inventory.mean()", "_____no_output_____" ] ], [ [ "**0.5%** of all traffic stops resulted in an inventory.", "_____no_output_____" ] ], [ [ "searched = ri[ri.search_conducted == True]\r\nsearched.inventory.mean()", "_____no_output_____" ] ], [ [ "__13.3% of searches included an inventory__", "_____no_output_____" ], [ "## __17 Counting protective frisks__", "_____no_output_____" ], [ "During a vehicle search, the police officer may pat down the driver to check if they have a weapon. This is known as a \"protective frisk.\"\r\n\r\nIn this exercise, you'll first check to see how many times \"Protective Frisk\" was the only search type. Then, you'll use a string method to locate all instances in which the driver was frisked.", "_____no_output_____" ], [ "__Instructions__\r\n\r\n- Count the `search_type` values in the `ri` DataFrame to see how many times \"Protective Frisk\" was the only search type.\r\n\r\n- Create a new column, `frisk`, that is `True` if search_type contains the string \"Protective Frisk\" and `False` otherwise.\r\n\r\n- Check the data type of `frisk` to confirm that it's a Boolean Series.\r\n\r\n- Take the sum of `frisk` to count the total number of frisks.", "_____no_output_____" ] ], [ [ "# Count the 'search_type' values\r\nprint(ri.search_type.value_counts())\r\n\r\n# Check if 'search_type' contains the string 'Protective Frisk'\r\nri['frisk'] = ri.search_type.str.contains('Protective Frisk', na=False)\r\n\r\n# Check the data type of 'frisk'\r\nprint(ri['frisk'].dtype)\r\n\r\n# Take the sum of 'frisk'\r\nprint(ri['frisk'].sum())", "Incident to Arrest 1290\nProbable Cause 924\nInventory 219\nReasonable Suspicion 214\nProtective Frisk 164\nIncident to Arrest,Inventory 123\nIncident to Arrest,Probable Cause 100\nProbable Cause,Reasonable Suspicion 54\nIncident to Arrest,Inventory,Probable Cause 35\nProbable Cause,Protective Frisk 35\nIncident to Arrest,Protective Frisk 33\nInventory,Probable Cause 25\nProtective Frisk,Reasonable Suspicion 19\nIncident to Arrest,Inventory,Protective Frisk 18\nIncident to Arrest,Probable Cause,Protective Frisk 13\nInventory,Protective Frisk 12\nIncident to Arrest,Reasonable Suspicion 8\nIncident to Arrest,Probable Cause,Reasonable Suspicion 5\nProbable Cause,Protective Frisk,Reasonable Suspicion 5\nIncident to Arrest,Inventory,Reasonable Suspicion 4\nInventory,Reasonable Suspicion 2\nIncident to Arrest,Protective Frisk,Reasonable Suspicion 2\nInventory,Probable Cause,Protective Frisk 1\nInventory,Probable Cause,Reasonable Suspicion 1\nInventory,Protective Frisk,Reasonable Suspicion 1\nName: search_type, dtype: int64\nbool\n303\n" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>It looks like there were **303 drivers** who were **frisked**. Next, you'll examine whether gender affects who is frisked.", "_____no_output_____" ], [ "## __18 Comparing frisk rates by gender__", "_____no_output_____" ], [ "In this exercise, we'll compare the rates at which **female** and **male** drivers are **frisked during a search**.\r\n\r\n>Are males frisked more often than females, perhaps because police officers consider them to be higher risk?\r\n\r\nBefore doing any calculations, it's important to filter the DataFrame to only include the relevant subset of data, namely stops in which a search was conducted.", "_____no_output_____" ], [ "__Instructions__\r\n\r\n- Create a DataFrame, **searched**, that only contains rows in which `search_conducted` is `True`.\r\n\r\n- Take the mean of the `frisk` column to find out what percentage of searches included a frisk.\r\n\r\n- Calculate the frisk rate for each gender using a `.groupby()`.", "_____no_output_____" ] ], [ [ "# Create a DataFrame of stops in which a search was conducted\r\nsearched = ri[ri.search_conducted == True]\r\n\r\n# Calculate the overall frisk rate by taking the mean of 'frisk'\r\nprint(searched.frisk.mean())\r\n\r\n# Calculate the frisk rate for each gender\r\nprint(searched.groupby('driver_gender').frisk.mean())", "0.09162382824312065\ndriver_gender\nF 0.074561\nM 0.094353\nName: frisk, dtype: float64\n" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>The **frisk rate** is **higher for males than for females**, though we **can't** conclude that this difference is caused by the driver's gender.", "_____no_output_____" ], [ "--- \r\n<strong> \r\n <h1 align='center'>Does time of day affect arrest rate?(Part - 3)\r\n </h1> \r\n</strong>\r\n\r\n---", "_____no_output_____" ], [ "## __19 Calculating the hourly arrest rate__", "_____no_output_____" ], [ "When a police officer stops a driver, a small percentage of those stops ends in an arrest. This is known as the arrest rate. In this exercise, you'll find out whether the arrest rate varies by time of day.\r\n\r\nFirst, you'll calculate the arrest rate across all stops in the **ri** DataFrame. Then, you'll calculate the hourly arrest rate by using the **hour** attribute of the index. The **hour** ranges from 0 to 23, in which:\r\n\r\n- *0 = midnight*\r\n- *12 = noon*\r\n- *23 = 11 PM*", "_____no_output_____" ], [ "__Instructions__\r\n\r\n- Take the mean of the `is_arrested` column to calculate the overall arrest rate.\r\n\r\n- Group by the `hour` attribute of the DataFrame index to calculate the hourly arrest rate.\r\n\r\n- Save the hourly arrest rate Series as a new object, `hourly_arrest_rate`.", "_____no_output_____" ] ], [ [ "# Calculate the overall arrest rate\r\nprint(ri.is_arrested.mean())\r\n\r\n# Calculate the hourly arrest rate\r\nprint(ri.groupby(ri.index.hour).is_arrested.mean())\r\n\r\n# Save the hourly arrest rate\r\nhourly_arrest_rate = ri.groupby(ri.index.hour).is_arrested.mean()", "0.0355690117407784\nstop_datetime\n0 0.051431\n1 0.064932\n2 0.060798\n3 0.060549\n4 0.048000\n5 0.042781\n6 0.013813\n7 0.013032\n8 0.021854\n9 0.025206\n10 0.028213\n11 0.028897\n12 0.037399\n13 0.030776\n14 0.030605\n15 0.030679\n16 0.035281\n17 0.040619\n18 0.038204\n19 0.032245\n20 0.038107\n21 0.064541\n22 0.048666\n23 0.047592\nName: is_arrested, dtype: float64\n" ] ], [ [ "## __20 Plotting the hourly arrest rate__", "_____no_output_____" ], [ "In this exercise, we'll create a line plot from the `hourly_arrest_rate` object. A line plot is appropriate in this case because you're showing how a quantity changes over time.\r\n\r\nThis plot should help you to spot some trends that may not have been obvious when examining the raw numbers!", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "# Import matplotlib.pyplot as plt\r\nimport matplotlib.pyplot as plt\r\n\r\n# Create a line plot of 'hourly_arrest_rate'\r\nhourly_arrest_rate.plot()\r\n\r\n# Add the xlabel, ylabel, and title\r\nplt.xlabel('Hour')\r\nplt.ylabel('Arrest Rate')\r\nplt.title('Arrest Rate by Time of Day')\r\n\r\n# Display the plot\r\nplt.show()", "_____no_output_____" ] ], [ [ "## __21 Plotting drug-related stops__\r\n\r\n__Are drug-related\r\nstops on the rise?__", "_____no_output_____" ], [ "In a small portion of traffic stops, drugs are found in the vehicle during a search. In this exercise, you'll assess whether these drug-related stops are becoming more common over time.\r\n\r\nThe Boolean column `drugs_related_stop` indicates whether drugs were found during a given stop. You'll calculate the annual drug rate by resampling this column, and then you'll use a line plot to visualize how the rate has changed over time.", "_____no_output_____" ], [ "__Instructions__\r\n\r\n- Calculate the annual rate of drug-related stops by resampling the `drugs_related_stop` column (on the `'A'` frequency) and taking the mean.\r\n\r\n- Save the annual drug rate Series as a new object, `annual_drug_rate`.\r\n\r\n- Create a line plot of `annual_drug_rate` using the `.plot()` method.\r\n\r\n- Display the plot using the `.show()` function.", "_____no_output_____" ] ], [ [ "# Calculate the annual rate of drug-related stops\r\n# resampling `drugs_related_stop` represented by 'A' for Annual rate\r\n# & chain with mean at end\r\nprint(ri.drugs_related_stop.resample('A').mean())\r\n\r\n# Save the annual rate of drug-related stops\r\nannual_drug_rate = ri.drugs_related_stop.resample('A').mean()\r\n\r\n# Create a line plot of 'annual_drug_rate'\r\nannual_drug_rate.plot()\r\n\r\n# Display the plot\r\nplt.xlabel('year')\r\nplt.ylabel('Annual drug rate')\r\nplt.title('drugs_related_stop')\r\nplt.show()", "stop_datetime\n2005-12-31 0.006501\n2006-12-31 0.007258\n2007-12-31 0.007970\n2008-12-31 0.007505\n2009-12-31 0.009889\n2010-12-31 0.010081\n2011-12-31 0.009731\n2012-12-31 0.009921\n2013-12-31 0.013094\n2014-12-31 0.013826\n2015-12-31 0.012266\nFreq: A-DEC, Name: drugs_related_stop, dtype: float64\n" ] ], [ [ "**Resampling**\r\n \r\nResampling is when we change the frequncy of our __time-series__ obervation.\r\n\r\nMost commonly used time series frequency are –\r\n- **W** : weekly frequency\r\n- **M** : month end frequency\r\n- **SM** : semi-month end frequency -(15th and end of month)\r\n- **Q** : quarter end frequency\r\n- **A** : Annual\r\n\r\nA time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time. \r\n\r\nIt is a Convenience method for **frequency conversion** and resampling of **time serie**s. Object must have a datetime-like index (**DatetimeIndex**, **PeriodIndex**, or **TimedeltaIndex**), or pass datetime-like values to the on or level keyword.", "_____no_output_____" ], [ "## __22 Comparing drug and search rates__", "_____no_output_____" ], [ ">From the above plot its evident that rate of `drug-related` stops increased significantly between **2005** and **2015**. \r\n\r\nwe might **hypothesize** that the **rate of vehicle searches** was also **increasing**, which would have led to an **increase** in **drug-related stops** even if more drivers were not carrying drugs.\r\n\r\nYou can test this **hypothesis** by calculating the **annual search rate**, and then plotting it against the **annual drug rate**.\r\n\r\n*If the hypothesis is true, then you'll see both rates increasing over time.*", "_____no_output_____" ] ], [ [ "# Calculate and save the annual search rate\r\nannual_search_rate = ri.search_conducted.resample('A').mean()\r\n\r\n# Concatenate 'annual_drug_rate' and 'annual_search_rate'\r\nannual = pd.concat([annual_drug_rate, annual_search_rate], axis='columns')\r\n\r\n# Create subplots from 'annual'\r\nannual.plot(subplots=True)\r\n\r\n# Display the subplots\r\nplt.show()", "_____no_output_____" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>The rate of **drug-related** stops **increased** even though the **search rate decreased**, disproving our hypothesis", "_____no_output_____" ], [ "## __23 What violations are caught in each district?__", "_____no_output_____" ] ], [ [ "# Computing a frequency table\r\ntable = pd.crosstab(ri.driver_race, ri.driver_gender)\r\ntable", "_____no_output_____" ], [ "# Driver Asian and Gender is Female \r\nri[(ri.driver_race == 'Asian') & (ri.driver_gender == 'F')].shape", "_____no_output_____" ], [ "# Selecting a DataFrame slice\r\ntable1 = table.loc['Asian':'Hispanic']\r\ntable1", "_____no_output_____" ], [ "# Line Plot\r\ntable1.plot()\r\nplt.show()", "_____no_output_____" ] ], [ [ "**line plot** is not appropriate in this case because it implies a change in time along the **x-axis**, whereas the **x-axis** actually represents **three** distinct categories.", "_____no_output_____" ] ], [ [ "# Creating a bar plot\r\ntable.plot(kind='bar')\r\nplt.show()", "_____no_output_____" ], [ "# Creating a bar plot\r\ntable1.plot(kind='bar')\r\nplt.show()", "_____no_output_____" ], [ "# Stacking the bars for table1\r\ntable1.plot(kind='bar', stacked=True)\r\nplt.show()", "_____no_output_____" ] ], [ [ "__Tallying violations by district__\r\n\r\nThe state of Rhode Island is broken into **six police districts**, also known as zones. How do the zones compare in terms of what violations are caught by police?\r\n\r\nIn this exercise, we'll create a **frequency table** to determine **how many violations of each type took place in each of the six zones**. Then, you'll filter the table to focus on the `\"K\" zones`, which you'll examine further in the next exercise.", "_____no_output_____" ], [ "__Instructions:__\r\n\r\n- Create a frequency table from the `ri` DataFrame's `district` and `violation` columns using the `pd.crosstab()` function.\r\n\r\n- Save the frequency table as a new object, `all_zones`.\r\n\r\n- Select rows `'Zone K1'` through `'Zone K3'` from `all_zones` using the `.loc[]` accessor.\r\nSave the smaller table as a new object, `k_zones`.", "_____no_output_____" ] ], [ [ "# Create a frequency table of districts and violations\r\nprint(pd.crosstab(ri.district, ri.violation))\r\n\r\n# Save the frequency table as 'all_zones'\r\nall_zones = pd.crosstab(ri.district, ri.violation)\r\n\r\n# Select rows 'Zone K1' through 'Zone K3'\r\nprint(all_zones.loc['Zone K1':'Zone K3'])\r\n\r\n# Save the smaller table as 'k_zones'\r\nk_zones = all_zones.loc['Zone K1':'Zone K3']", "violation Equipment Moving violation ... Seat belt Speeding\ndistrict ... \nZone K1 672 1254 ... 0 5960\nZone K2 2061 2962 ... 481 10448\nZone K3 2302 2898 ... 638 12322\nZone X1 296 671 ... 74 1119\nZone X3 2049 3086 ... 820 8779\nZone X4 3541 5353 ... 843 9795\n\n[6 rows x 6 columns]\nviolation Equipment Moving violation ... Seat belt Speeding\ndistrict ... \nZone K1 672 1254 ... 0 5960\nZone K2 2061 2962 ... 481 10448\nZone K3 2302 2898 ... 638 12322\n\n[3 rows x 6 columns]\n" ] ], [ [ "## __24 Plotting violations by district__", "_____no_output_____" ], [ "we've created a frequency table focused on the `\"K\"` zones, **visualize** the data to help you compare what **violations** are being caught in each zone.\r\n\r\n>**First** we'll create a **bar plot**, which is an appropriate plot type since we're **comparing categorical data**. \r\n\r\n>Then we'll create a **stacked bar** plot in order to get a slightly different look at the data to find which plot is more insightful?", "_____no_output_____" ] ], [ [ "# Creating a bar plot\r\nk_zones.plot(kind='bar', figsize=(12, 7))\r\n\r\n# Display the plot\r\nplt.show()", "_____no_output_____" ], [ "# Create a stacked bar plot of 'k_zones'\r\nk_zones.plot(kind='bar', stacked=True, figsize=(12, 7))\r\n\r\n# Display the plot\r\nplt.show()", "_____no_output_____" ] ], [ [ "The vast majority of traffic stops in **Zone K1** are for speeding, and **Zones K2** and **K3** are remarkably similar to one another in terms of violations.", "_____no_output_____" ], [ "## __25 Converting stop durations to numbers__", "_____no_output_____" ], [ "In the traffic stops dataset, the `stop_duration` column tells you approximately how long the driver was detained by the officer. Unfortunately, the durations are stored as strings, such as `'0-15 Min'`. How can you make this data easier to analyze?\r\n\r\nIn this exercise, you'll convert the stop durations to integers. Because the precise durations are not available, you'll have to estimate the numbers using reasonable values:\r\n\r\n- Convert `'0-15 Min'` to `8`\r\n- Convert `'16-30 Min'` to `23`\r\n- Convert `'30+ Min'` to `45`", "_____no_output_____" ], [ "$\\color{red}{\\textbf{Note:}}$\r\n\r\n>`astype()` method to convert strings to numbers or Booleans. \r\n\r\nHowever, `astype()` only works when pandas can infer how the conversion should be done, and that's not the case here.", "_____no_output_____" ] ], [ [ "# Print the unique values in 'stop_duration'\r\nprint(ri.stop_duration.unique())\r\n\r\n# Create a dictionary that maps strings to integers\r\nmapping = {'0-15 Min':8, \r\n '16-30 Min':23,\r\n '30+ Min':45\r\n }\r\n\r\n# Convert the 'stop_duration' strings to integers using the 'mapping'\r\nri['stop_minutes'] = ri.stop_duration.map(mapping)\r\n\r\n# Print the unique values in 'stop_minutes'\r\nprint(ri.stop_minutes.unique())", "['0-15 Min' '16-30 Min' '30+ Min']\n[ 8 23 45]\n" ] ], [ [ "## __26 Plotting stop length__\r\n\r\n>If we were **stopped** for a particular violation, how long might we expect to be detained?\r\n\r\nIn this exercise, we'll visualize the average length of time drivers are stopped for each type of violation. Rather than using the `violation` column in this exercise, you'll use `violation_raw` since it contains more detailed descriptions of the violations.", "_____no_output_____" ], [ "__Instructions__\r\n\r\n- For each value in the ri DataFrame's **violation_raw** column, calculate the mean number of **stop_minutes** that a driver is detained.\r\n\r\n- Save the resulting Series as a new object, **stop_length**.\r\n\r\n- Sort **stop_length** by its values, and then visualize it using a horizontal bar plot.\r\n\r\n- Display the plot.", "_____no_output_____" ] ], [ [ "# Calculate the mean 'stop_minutes' for each value in 'violation_raw'\r\nprint(ri.groupby('violation_raw').stop_minutes.mean())\r\n\r\n# Save the resulting Series as 'stop_length'\r\nstop_length = ri.groupby('violation_raw').stop_minutes.mean()\r\n\r\n# Sort 'stop_length' by its values and create a horizontal bar plot\r\nstop_length.sort_values().plot(kind='barh')\r\n\r\n# Display the plot\r\nplt.show()", "violation_raw\nAPB 17.967033\nCall for Service 22.124371\nEquipment/Inspection Violation 11.445655\nMotorist Assist/Courtesy 17.741463\nOther Traffic Violation 13.844490\nRegistration Violation 13.736970\nSeatbelt Violation 9.662815\nSpecial Detail/Directed Patrol 15.123632\nSpeeding 10.581562\nSuspicious Person 14.910714\nViolation of City/Town Ordinance 13.254144\nWarrant 24.055556\nName: stop_minutes, dtype: float64\n" ] ], [ [ "__Calculating the search rate__\r\n\r\n- **Visualizing** how often searches were done after each **violation** type", "_____no_output_____" ] ], [ [ "search_rate = ri.groupby('violation').search_conducted.mean()\r\nsearch_rate.sort_values().plot(kind='barh')\r\nplt.show()", "_____no_output_____" ] ], [ [ "--- \r\n<strong> \r\n <h1 align='center'>Analyzing the effect of weather on policing(Part - 4)\r\n </h1> \r\n</strong>\r\n\r\n---", "_____no_output_____" ] ], [ [ "ls", "police.csv weather.csv\n" ] ], [ [ "## $\\color{green}{\\textbf{Dataset_2_weather.csv:}}$ \r\n\r\n[National Centers for Environmental Information](https://www.ncei.noaa.gov/)\r\n\r\n<p align=''center>\r\n <a href='#'><img src='https://www.climatecommunication.org/wp-content/uploads/2013/04/Screen-Shot-2016-01-29-at-10.52.21-AM.png'></a>\r\n</p>", "_____no_output_____" ] ], [ [ "# Import the pandas library as pd\r\nimport pandas as pd\r\n\r\n# Read 'weather.csv' into a DataFrame named 'weather'\r\nweather = pd.read_csv('weather.csv')\r\n\r\n# Examine the head of the DataFrame\r\nweather.head()", "_____no_output_____" ] ], [ [ "- __TAVG , TMIN , TMAX__ : Temperature\r\n- __AWND , WSF2 :__ Wind speed\r\n- __WT01 ... WT22 :__ Bad weather conditions", "_____no_output_____" ], [ "__The difference between isnull () and isna ()?__\r\n\r\n`.isnull()` and `isna()` are the same functions (an alias), so we can choose either one. `df.isnull().sum()` or `df.isna().sum()`.\r\n\r\nFinding which index (or row number) contains missing values can be done analogously to the previous example, simply by adding axis=1. ", "_____no_output_____" ] ], [ [ "# Count the number of missing values in each column\r\nprint(weather.isnull().sum())\r\n\r\n# Columns\r\nprint(weather.columns)\r\n\r\n# Shape\r\nprint(weather.shape)", "STATION 0\nDATE 0\nTAVG 2800\nTMIN 0\nTMAX 0\nAWND 0\nWSF2 0\nWT01 2250\nWT02 3796\nWT03 3793\nWT04 3900\nWT05 3657\nWT06 3992\nWT07 3938\nWT08 3613\nWT09 3948\nWT10 4015\nWT11 4016\nWT13 2842\nWT14 3442\nWT15 4011\nWT16 2691\nWT17 4005\nWT18 3672\nWT19 4013\nWT21 3999\nWT22 3985\ndtype: int64\nIndex(['STATION', 'DATE', 'TAVG', 'TMIN', 'TMAX', 'AWND', 'WSF2', 'WT01',\n 'WT02', 'WT03', 'WT04', 'WT05', 'WT06', 'WT07', 'WT08', 'WT09', 'WT10',\n 'WT11', 'WT13', 'WT14', 'WT15', 'WT16', 'WT17', 'WT18', 'WT19', 'WT21',\n 'WT22'],\n dtype='object')\n(4017, 27)\n" ] ], [ [ "## __27 Plotting the temperature__", "_____no_output_____" ] ], [ [ "# Describe the temperature columns\r\nprint(weather[['TMIN', 'TAVG', 'TMAX']].describe())\r\n\r\n# Create a box plot of the temperature columns\r\nweather[['TMIN', 'TAVG', 'TMAX']].plot(kind='box')\r\n\r\n# Display the plot\r\nplt.show()", " TMIN TAVG TMAX\ncount 4017.000000 1217.000000 4017.000000\nmean 43.484441 52.493016 61.268608\nstd 17.020298 17.830714 18.199517\nmin -5.000000 6.000000 15.000000\n25% 30.000000 39.000000 47.000000\n50% 44.000000 54.000000 62.000000\n75% 58.000000 68.000000 77.000000\nmax 77.000000 86.000000 102.000000\n" ] ], [ [ "__Examining the wind speed__\r\n", "_____no_output_____" ] ], [ [ "print(weather[['AWND', 'WSF2']].head())\r\nprint(weather[['AWND', 'WSF2']].describe())\r\n\r\n# Creating a box plot\r\nweather[['AWND', 'WSF2']].plot(kind='box', figsize=(7, 7))\r\nplt.figure()\r\nplt.show()", " AWND WSF2\n0 8.95 25.1\n1 9.40 14.1\n2 6.93 17.0\n3 6.93 16.1\n4 7.83 17.0\n AWND WSF2\ncount 4017.000000 4017.000000\nmean 8.593707 19.274782\nstd 3.364601 5.623866\nmin 0.220000 4.900000\n25% 6.260000 15.000000\n50% 8.050000 17.900000\n75% 10.290000 21.900000\nmax 26.840000 48.100000\n" ], [ "# Creating a histogram (1)\r\nweather['WDIFF'] = weather.WSF2 - weather.AWND\r\nweather.WDIFF.plot(kind='hist')\r\nplt.show()", "_____no_output_____" ], [ "# Creating a histogram (2)\r\nweather.WDIFF.plot(kind='hist', bins=20)\r\nplt.show()", "_____no_output_____" ] ], [ [ "## __28 Plotting the temperature difference__\r\n\r\n\r\n", "_____no_output_____" ] ], [ [ "# Create a 'TDIFF' column that represents temperature difference\r\nweather['TDIFF'] = weather.TMAX - weather.TMIN\r\n\r\n# Describe the 'TDIFF' column\r\nprint(weather.TDIFF.describe())\r\n\r\n# Create a histogram with 20 bins to visualize 'TDIFF'\r\nweather.TDIFF.plot(kind='hist', bins=20)\r\n\r\n# Display the plot\r\nplt.show()", "count 4017.000000\nmean 17.784167\nstd 6.350720\nmin 2.000000\n25% 14.000000\n50% 18.000000\n75% 22.000000\nmax 43.000000\nName: TDIFF, dtype: float64\n" ] ], [ [ "## __29 Categorizing the weather__", "_____no_output_____" ] ], [ [ "# Printing the shape and columns\r\nprint(weather.shape)\r\nprint(weather.columns)", "(4017, 29)\nIndex(['STATION', 'DATE', 'TAVG', 'TMIN', 'TMAX', 'AWND', 'WSF2', 'WT01',\n 'WT02', 'WT03', 'WT04', 'WT05', 'WT06', 'WT07', 'WT08', 'WT09', 'WT10',\n 'WT11', 'WT13', 'WT14', 'WT15', 'WT16', 'WT17', 'WT18', 'WT19', 'WT21',\n 'WT22', 'WDIFF', 'TDIFF'],\n dtype='object')\n" ], [ "# Selecting a DataFrame slice\r\ntemp = weather.loc[:, 'TAVG':'TMAX']\r\nprint(temp.shape)\r\nprint(temp.columns)", "(4017, 3)\nIndex(['TAVG', 'TMIN', 'TMAX'], dtype='object')\n" ] ], [ [ "__Mapping one set of values to another__", "_____no_output_____" ] ], [ [ "print(ri.stop_duration.unique())\r\n\r\nmapping = {'0-15 Min':'short',\r\n '16-30 Min':'medium',\r\n '30+ Min':'long'\r\n }\r\n\r\nri['stop_length'] = ri.stop_duration.map(mapping)\r\nprint(ri.stop_length.dtype)\r\nprint(ri.stop_length.unique())", "['0-15 Min' '16-30 Min' '30+ Min']\nobject\n['short' 'medium' 'long']\n" ] ], [ [ "- Category type stores the data more efficiently.\r\n- Allows you to specify a logical order for the categories.", "_____no_output_____" ] ], [ [ "ri.stop_length.memory_usage(deep=True)", "_____no_output_____" ] ], [ [ "`pandas.DataFrame.memory_usage` __function__\r\n\r\nReturn the **memory usage** of each column in bytes.\r\n\r\n- The **memory usage** can optionally include the contribution of the **index** and **elements** of object dtype.\r\n\r\n- `deep` bool, __default False__\r\nIf **True**, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned values.\r\n", "_____no_output_____" ], [ "__Changing data type from object to category__", "_____no_output_____" ] ], [ [ "from pandas.api.types import CategoricalDtype \r\n\r\n# Changing data type from object to category\r\ncats = ['short', 'medium', 'long']\r\n\r\ncat_type = CategoricalDtype(categories=cats, ordered=True)\r\n\r\nri['stop_length'] = ri['stop_length'].astype(cat_type)\r\n\r\nprint(ri.stop_length.memory_usage(deep=True))", "779090\n" ], [ "# Using ordered categories\r\nprint(ri.stop_length.value_counts())", "short 69577\nmedium 13740\nlong 3219\nName: stop_length, dtype: int64\n" ], [ "ri[ri.stop_length > 'short'].shape", "_____no_output_____" ], [ "ri.groupby('stop_length').is_arrested.mean()", "_____no_output_____" ] ], [ [ "## __30 Counting bad weather conditions__", "_____no_output_____" ], [ "The `weather` DataFrame contains 20 columns that start with `'WT'`, each of which represents a bad weather condition. For example:\r\n\r\n- `WT05` indicates \"Hail\"\r\n- `WT11` indicates \"High or damaging winds\"\r\n- `WT17` indicates \"Freezing rain\"\r\n\r\nFor every row in the dataset, each `WT` column contains either a 1 (meaning the condition was present that day) or `NaN` (meaning the condition was not present).\r\n\r\nIn this exercise, you'll quantify \"how bad\" the weather was each day by counting the number of `1` values in each row.", "_____no_output_____" ] ], [ [ "# Copy 'WT01' through 'WT22' to a new DataFrame\r\nWT = weather.loc[:, 'WT01':'WT22']\r\n\r\n# Calculate the sum of each row in 'WT'\r\nweather['bad_conditions'] = WT.sum(axis='columns')\r\n\r\n# Replace missing values in 'bad_conditions' with '0'\r\nweather['bad_conditions'] = weather.bad_conditions.fillna(0).astype('int')\r\n\r\n# Create a histogram to visualize 'bad_conditions'\r\nweather.bad_conditions.plot(kind='hist')\r\n\r\n# Display the plot\r\nplt.show()", "_____no_output_____" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>It looks like many days didn't have any bad weather conditions, and only a small portion of days had more than four bad weather conditions.", "_____no_output_____" ], [ "## __31 Rating the weather conditions__\r\n\r\nIn the previous exercise, we have counted the number of bad weather conditions each day. In this exercise, we'll use the counts to create a rating system for the weather.\r\n\r\nThe counts range from 0 to 9, and should be converted to ratings as follows:\r\n\r\n- Convert 0 to `'good'`\r\n- Convert 1 through 4 to `'bad'`\r\n- Convert 5 through 9 to `'worse'`\r\n", "_____no_output_____" ] ], [ [ "# Count the unique values in 'bad_conditions' and sort the index\r\nprint(weather.bad_conditions.value_counts().sort_index())\r\n\r\n# Create a dictionary that maps integers to strings\r\nmapping = {0:'good',\r\n 1:'bad', 2:'bad', 3:'bad', 4:'bad', \r\n 5:'worse', 6:'worse', 7:'worse', 8:'worse', 9:'worse'}\r\n\r\n# Convert the 'bad_conditions' integers to strings using the 'mapping'\r\nweather['rating'] = weather.bad_conditions.map(mapping)\r\n\r\n# Count the unique values in 'rating'\r\nprint(weather.rating.value_counts())", "0 1749\n1 613\n2 367\n3 380\n4 476\n5 282\n6 101\n7 41\n8 4\n9 4\nName: bad_conditions, dtype: int64\nbad 1836\ngood 1749\nworse 432\nName: rating, dtype: int64\n" ] ], [ [ "This rating system should make the weather condition data easier to understand.", "_____no_output_____" ], [ "## __32 Changing the data type to category__", "_____no_output_____" ], [ "Since the `rating` column only has a few possible values, we have to change its **data type to category** in order to store the data more efficiently & then specify a logical order for the categories.", "_____no_output_____" ] ], [ [ "from pandas.api.types import CategoricalDtype \r\n\r\n# Create a list of weather ratings in logical order\r\ncats = ['good', 'bad', 'worse']\r\n\r\n# Change the data type of 'rating' to category\r\ncat_types= CategoricalDtype(categories=cats, ordered=True)\r\nweather['rating'] = weather['rating'].astype(cat_types)\r\n\r\n# Examine the head of 'rating'\r\nprint(weather.rating.head())", "0 bad\n1 bad\n2 bad\n3 bad\n4 bad\nName: rating, dtype: category\nCategories (3, object): ['good' < 'bad' < 'worse']\n" ], [ "print(weather.rating.memory_usage(deep=True))", "4408\n" ], [ "# Using ordered categories\r\nprint(weather.rating.value_counts())", "bad 1836\ngood 1749\nworse 432\nName: rating, dtype: int64\n" ], [ "weather.rating.value_counts().plot(kind='bar')\r\nplt.show()", "_____no_output_____" ] ], [ [ "## __33 Merging datasets(Preparing the DataFrames)__", "_____no_output_____" ], [ "In this exercise, we'll prepare the traffic stop and weather rating DataFrames so that they're ready to be merged:\r\n\r\n1. With the `ri` DataFrame, you'll move the `stop_datetime` index to a column since the index will be lost during the merge.\r\n\r\n2. With the `weather` DataFrame, you'll select the `DATE` and `rating` columns and put them in a new DataFrame.", "_____no_output_____" ], [ "__Instructions__\r\n\r\n- Reset the index of the ri DataFrame.\r\n\r\n- Examine the head of ri to verify that `stop_datetime` is now a DataFrame column, and the index is now the default integer index.\r\n\r\n- Create a new DataFrame named `weather_rating` that contains only the `DATE` and rating columns from the weather DataFrame.\r\n\r\n- Examine the head of `weather_rating` to verify that it contains the proper columns.", "_____no_output_____" ] ], [ [ "# Reset the index of 'ri'\r\nri.reset_index(inplace=True)\r\n\r\n# Examine the head of 'ri'\r\nprint(ri.head())\r\n\r\n# Create a DataFrame from the 'DATE' and 'rating' columns\r\nweather_rating = weather[['DATE','rating']]\r\n\r\n# Examine the head of 'weather_rating'\r\nprint(weather_rating.head())", " stop_datetime stop_date stop_time ... frisk stop_minutes stop_length\n0 2005-01-04 12:55:00 2005-01-04 12:55 ... False 8 short\n1 2005-01-23 23:15:00 2005-01-23 23:15 ... False 8 short\n2 2005-02-17 04:15:00 2005-02-17 04:15 ... False 8 short\n3 2005-02-20 17:15:00 2005-02-20 17:15 ... False 23 medium\n4 2005-02-24 01:20:00 2005-02-24 01:20 ... False 8 short\n\n[5 rows x 18 columns]\n DATE rating\n0 2005-01-01 bad\n1 2005-01-02 bad\n2 2005-01-03 bad\n3 2005-01-04 bad\n4 2005-01-05 bad\n" ] ], [ [ "The **ri** and **weather_rating** DataFrames are now ready to be **merged**.", "_____no_output_____" ], [ "__Merging the DataFrames__\r\n\r\nIn this exercise, we'll merge the `ri` and `weather_rating` DataFrames into a new DataFrame, ri_weather.\r\n\r\nThe DataFrames will be joined using the `stop_date` column from `ri` and the `DATE` column from `weather_rating`. Thankfully the date formatting matches exactly, which is not always the case!\r\n\r\nOnce the merge is complete, you'll set `stop_datetime` as the index, which is the column you saved in the previous exercise.\r\n", "_____no_output_____" ] ], [ [ "# Examine the shape of 'ri'\r\nprint(ri.shape)\r\n\r\n# Merge 'ri' and 'weather_rating' using a left join\r\nri_weather = pd.merge(left=ri, right=weather_rating, left_on='stop_date', right_on='DATE', how='left')\r\n\r\n# Examine the shape of 'ri_weather'\r\nprint(ri_weather.shape)\r\n\r\n# Set 'stop_datetime' as the index of 'ri_weather'\r\nri_weather.set_index('stop_datetime', inplace=True)", "(86536, 18)\n(86536, 20)\n" ] ], [ [ "## __34 Does weather affect the arrest rate?__", "_____no_output_____" ] ], [ [ "# Driver gender and vehicle searches\r\nprint(ri.search_conducted.mean())\r\nprint(ri.groupby('driver_gender').search_conducted.mean())", "0.0382153092354627\ndriver_gender\nF 0.019181\nM 0.045426\nName: search_conducted, dtype: float64\n" ], [ "search_rate = ri.groupby(['violation','driver_gender']).search_conducted.mean()\r\nsearch_rate", "_____no_output_____" ], [ "print(type(search_rate))\r\nprint(type(search_rate.index))", "<class 'pandas.core.series.Series'>\n<class 'pandas.core.indexes.multi.MultiIndex'>\n" ], [ "search_rate.loc['Equipment']", "_____no_output_____" ], [ "search_rate.loc['Equipment', 'M']", "_____no_output_____" ], [ "search_rate.unstack()", "_____no_output_____" ], [ "type(search_rate.unstack())", "_____no_output_____" ] ], [ [ "__Converting a multi-indexed Series to a DataFrame__", "_____no_output_____" ] ], [ [ "ri.pivot_table(index='violation',\r\n columns='driver_gender',\r\n values='search_conducted')", "_____no_output_____" ] ], [ [ "### __Comparing arrest rates by weather rating__", "_____no_output_____" ], [ "Do police officers arrest drivers more often when the weather is bad? Find out below!\r\n\r\n- First, you'll calculate the overall arrest rate.\r\n\r\n- Then, you'll calculate the arrest rate for each of the weather ratings you previously assigned.\r\n\r\n- Finally, you'll add violation type as a second factor in the analysis, to see if that accounts for any differences in the arrest rate.\r\n\r\nSince you previously defined a logical order for the weather categories, `good < bad < worse`, they will be sorted that way in the results.", "_____no_output_____" ], [ "__Calculate the overall arrest rate by taking the mean of the `is_arrested` Series__", "_____no_output_____" ] ], [ [ "# Calculate the overall arrest rate\r\nprint(ri_weather.is_arrested.mean())", "0.0355690117407784\n" ] ], [ [ "__Calculate the arrest rate for each weather `rating` using a `.groupby()`.__", "_____no_output_____" ] ], [ [ "# Calculate the arrest rate for each 'rating'\r\nprint(ri_weather.groupby('rating').is_arrested.mean())", "rating\ngood 0.033715\nbad 0.036261\nworse 0.041667\nName: is_arrested, dtype: float64\n" ] ], [ [ "__Calculate the arrest rate for each combination of `violation` and `rating`. How do the arrest rates differ by group?__", "_____no_output_____" ] ], [ [ "# Calculate the arrest rate for each 'violation' and 'rating'\r\nprint(ri_weather.groupby(['violation', 'rating']).is_arrested.mean())", "violation rating\nEquipment good 0.059007\n bad 0.066311\n worse 0.097357\nMoving violation good 0.056227\n bad 0.058050\n worse 0.065860\nOther good 0.076966\n bad 0.087443\n worse 0.062893\nRegistration/plates good 0.081574\n bad 0.098160\n worse 0.115625\nSeat belt good 0.028587\n bad 0.022493\n worse 0.000000\nSpeeding good 0.013405\n bad 0.013314\n worse 0.016886\nName: is_arrested, dtype: float64\n" ] ], [ [ "$\\color{red}{\\textbf{Interpretation:}}$\r\n\r\n>The arrest rate **increases as the weather gets worse**, and that trend persists across many of the violation types. This doesn't prove a causal link, but it's quite an interesting result", "_____no_output_____" ], [ "## __35 Selecting from a multi-indexed Series__\r\n\r\nThe output of a single `.groupby()` operation on multiple columns is a Series with a MultiIndex. Working with this type of object is similar to working with a DataFrame:\r\n\r\n- The outer index level is like the DataFrame rows.\r\n- The inner index level is like the DataFrame columns.\r\n\r\nIn this exercise, you'll practice accessing data from a multi-indexed Series using the `.loc[]` accessor.", "_____no_output_____" ] ], [ [ "# Save the output of the groupby operation from the last exercise\r\narrest_rate = ri_weather.groupby(['violation', 'rating']).is_arrested.mean()\r\n\r\n# Print the 'arrest_rate' Series\r\nprint(arrest_rate)\r\n\r\n# Print the arrest rate for moving violations in bad weather\r\nprint(arrest_rate.loc['Moving violation', 'bad'])\r\n\r\n# Print the arrest rates for speeding violations in all three weather conditions\r\nprint(arrest_rate.loc['Speeding'])", "violation rating\nEquipment good 0.059007\n bad 0.066311\n worse 0.097357\nMoving violation good 0.056227\n bad 0.058050\n worse 0.065860\nOther good 0.076966\n bad 0.087443\n worse 0.062893\nRegistration/plates good 0.081574\n bad 0.098160\n worse 0.115625\nSeat belt good 0.028587\n bad 0.022493\n worse 0.000000\nSpeeding good 0.013405\n bad 0.013314\n worse 0.016886\nName: is_arrested, dtype: float64\n0.05804964058049641\nrating\ngood 0.013405\nbad 0.013314\nworse 0.016886\nName: is_arrested, dtype: float64\n" ] ], [ [ "## __36 Reshaping the arrest rate data__\r\n\r\nIn this exercise, we'll the `arrest_rate` Series into a DataFrame. This is a useful step when working with any **multi-indexed Series**, since it enables us to access the *full range of DataFrame methods*.\r\n\r\nThen, we'll create the exact same DataFrame using a pivot table. This is a great example of how pandas often gives you more than one way to reach the same result!", "_____no_output_____" ] ], [ [ "# Unstack the 'arrest_rate' Series into a DataFrame\r\nprint(arrest_rate.unstack())\r\n\r\n# Create the same DataFrame using a pivot table\r\nprint(ri_weather.pivot_table(index='violation', \r\n columns='rating', \r\n values='is_arrested'))", "rating good bad worse\nviolation \nEquipment 0.059007 0.066311 0.097357\nMoving violation 0.056227 0.058050 0.065860\nOther 0.076966 0.087443 0.062893\nRegistration/plates 0.081574 0.098160 0.115625\nSeat belt 0.028587 0.022493 0.000000\nSpeeding 0.013405 0.013314 0.016886\nrating good bad worse\nviolation \nEquipment 0.059007 0.066311 0.097357\nMoving violation 0.056227 0.058050 0.065860\nOther 0.076966 0.087443 0.062893\nRegistration/plates 0.081574 0.098160 0.115625\nSeat belt 0.028587 0.022493 0.000000\nSpeeding 0.013405 0.013314 0.016886\n" ] ], [ [ "---", "_____no_output_____" ], [ "<p align='center'> \r\n <a href=\"https://twitter.com/F4izy\"> \r\n <img src=\"https://th.bing.com/th/id/OIP.FCKMemzqNplY37Jwi0Yk3AHaGl?w=233&h=207&c=7&o=5&pid=1.7\" width=50px \r\n height=50px> \r\n </a> \r\n <a href=\"https://www.linkedin.com/in/mohd-faizy/\"> \r\n <img src='https://th.bing.com/th/id/OIP.idrBN-LfvMIZl370Vb65SgHaHa?pid=Api&rs=1' width=50px height=50px> \r\n </a> \r\n</p>", "_____no_output_____" ], [ "---", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
cb27425ec31cfc1af590f6a9ceb4e1a17826592a
8,228
ipynb
Jupyter Notebook
weapon_dataset/images/mod_annotations.ipynb
jahab/object-detection-MobileNetV1
6e84a7e9b06fb66556a244f211dd7dea9c564937
[ "Apache-2.0" ]
2
2019-11-13T14:43:58.000Z
2021-05-31T07:05:40.000Z
weapon_dataset/images/mod_annotations.ipynb
jahab/object-detection-MobileNetV1
6e84a7e9b06fb66556a244f211dd7dea9c564937
[ "Apache-2.0" ]
null
null
null
weapon_dataset/images/mod_annotations.ipynb
jahab/object-detection-MobileNetV1
6e84a7e9b06fb66556a244f211dd7dea9c564937
[ "Apache-2.0" ]
1
2021-05-31T07:05:42.000Z
2021-05-31T07:05:42.000Z
29.811594
148
0.491249
[ [ [ "import numpy as np\nimport pandas as pd\nimport cv2\nimport os", "_____no_output_____" ], [ "img_path='/home/lenovo/object-detection/Keras_object-detection/pretrained_MobileNet_keras/weapon_dataset/images'\npath_to_save='/home/lenovo/object-detection/Keras_object-detection/pretrained_MobileNet_keras/weapon_dataset/images_mod'\ncols=['frame','xmin','xmax','ymin','ymax','class_id']\ntrain_annot=pd.read_csv(os.path.join(img_path,'train_labels.csv'))[cols]\ntest_annot=pd.read_csv(os.path.join(img_path,'test_labels.csv'))[cols]\ntrain_annot.head()", "_____no_output_____" ], [ "new_im_wd=224\nnew_im_ht=224", "_____no_output_____" ], [ "def resize_images(img_path,path_to_save):\n for files in sorted(os.listdir(img_path)):\n try:\n img=cv2.imread(files)\n #print(img.shape)\n size=(new_im_wd,new_im_ht)\n cv2.imwrite(os.path.join(path_to_save,files),cv2.resize(img,size))\n except:\n print(files)", "_____no_output_____" ], [ "\ndef mod_annot(data):\n\n size=(new_im_wd,new_im_ht)\n\n for i in range(len(data)):\n file=data['frame'][i]\n img=cv2.imread(file)\n cv2.imwrite(os.path.join(path_to_save,file),cv2.resize(img,size))\n #data.frame[i]='mod_'+data.frame[i]\n data.xmin[i]=round(new_im_wd*data.xmin[i]/img.shape[1])\n data.ymin[i]=round(new_im_ht*data.ymin[i]/img.shape[0])\n data.xmax[i]=round(new_im_wd*data.xmax[i]/img.shape[1])\n data.ymax[i]=round(new_im_ht*data.ymax[i]/img.shape[0])\n return data \n", "_____no_output_____" ], [ "data_train=mod_annot(train_annot)\ndata_train.to_csv(os.path.join(path_to_save,'train_labels.csv'),index=False)\n\ndata_test=mod_annot(test_annot)\ndata_test.to_csv(os.path.join(path_to_save,'test_labels.csv'),index=False)", "/home/lenovo/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:10: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n # Remove the CWD from sys.path while we load stuff.\n/home/lenovo/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:11: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n # This is added back by InteractiveShellApp.init_path()\n/home/lenovo/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:12: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n if sys.path[0] == '':\n/home/lenovo/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:13: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n del sys.path[0]\n" ], [ "data_train", "_____no_output_____" ], [ "new_im_wd*train_annot.xmin[0]/img.shape[1]", "_____no_output_____" ], [ "480*train_annot.xmin[0]/168", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb2742b0d3ec91d14a0ff5472910a00db1843794
29,935
ipynb
Jupyter Notebook
Workshops/08/WS_08_Deep_Learning_Part_III.ipynb
IS3UniCologne/Advanced_Analytics_And_Applications_2021
fd57bdff8d98c972c759e8393cdcd5c469b52e5a
[ "Apache-2.0" ]
3
2021-04-14T13:39:38.000Z
2021-06-10T21:10:56.000Z
Workshops/08/WS_08_Deep_Learning_Part_III.ipynb
IS3UniCologne/Advanced_Analytics_And_Applications_2021
fd57bdff8d98c972c759e8393cdcd5c469b52e5a
[ "Apache-2.0" ]
null
null
null
Workshops/08/WS_08_Deep_Learning_Part_III.ipynb
IS3UniCologne/Advanced_Analytics_And_Applications_2021
fd57bdff8d98c972c759e8393cdcd5c469b52e5a
[ "Apache-2.0" ]
3
2021-04-11T17:30:43.000Z
2021-07-08T18:32:16.000Z
31.510526
274
0.54478
[ [ [ "# Workshop: Deep Learning 3\n\nOutline\n1. Regularization\n2. Hand-Written Digits with Convolutional Neural Networks \n3. Advanced Image Classification with Convolutional Neural Networks \n\n\nSource: Deep Learning With Python, Part 1 - Chapter 4", "_____no_output_____" ], [ "## 1. Regularization", "_____no_output_____" ], [ "To prevent a model from learning misleading or irrelevant patterns found in the\ntraining data, the best solution is to get more training data. However, this is in many times out of our control.\n\nAnother approach is called - by now you should know that - regularization. ", "_____no_output_____" ], [ "### 1.1. Reducing the network’s size", "_____no_output_____" ] ], [ [ "The simplest way to prevent overfitting is to reduce the size of the model: the number\nof learnable parameters in the model (which is determined by the number of layers\nand the number of units per layer).\n\nOr put it this way: A network with more parameters can better memorize stuff...", "_____no_output_____" ], [ "# Unfortunately, there is no closed form solution which gives us the best network size...\n# So, we need to try out different models (or use grid search)", "_____no_output_____" ], [ "# Original Model \nfrom keras import models\nfrom keras import layers\nmodel = models.Sequential()\nmodel.add(layers.Dense(16, activation='relu', input_shape=(28 * 28,)))\nmodel.add(layers.Dense(16, activation='relu'))\nmodel.add(layers.Dense(10, activation='softmax'))", "_____no_output_____" ], [ "# Simpler Model \nfrom keras import models\nfrom keras import layers\nmodel = models.Sequential()\nmodel.add(layers.Dense(16, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(16, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))", "_____no_output_____" ], [ "# Bigger Model \nmodel = models.Sequential()\nmodel.add(layers.Dense(512, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))", "_____no_output_____" ], [ "#### You need to load data, compile the network and then train it (with validation/hold out set)\n#### Then you plot the validation loss for all these combinations", "_____no_output_____" ] ], [ [ "<img src=\"res/img1.png\"></img>", "_____no_output_____" ], [ "<img src=\"res/img2.png\"></img>", "_____no_output_____" ] ], [ [ "# This shows us that the bigger model starts to overfit immediately..", "_____no_output_____" ] ], [ [ "Instead of manually searching for the best model architecture (i.e., hyperparameters) you can use a method called grid-search. However, we will not cover this in this lecture - but you can find a tutorial here:\n\nhttps://machinelearningmastery.com/grid-search-hyperparameters-deep-learning-models-python-keras/\n\n\nBasically, the author conceleates keras with scikit's grid search module. ", "_____no_output_____" ], [ "### 1.2. Adding weight regularization", "_____no_output_____" ] ], [ [ "1. L1 regularization\n2. L2 regularization", "_____no_output_____" ] ], [ [ "#### 1.2.1 Adding L2 Regularization to the model", "_____no_output_____" ] ], [ [ "from keras import regularizers\nmodel = models.Sequential()\n\n# kernel_regularizer = regularizers.l2(0.001), add those weights to the loss with an alpha of 0.001\n# you could use also: regularizers.l1(0.001) for L1 regularization\n# Documentation: https://keras.io/api/layers/regularizers/\nmodel.add(layers.Dense(16, kernel_regularizer=regularizers.l2(0.001),activation='relu', input_shape=(10000,)))\n\nmodel.add(layers.Dense(16, kernel_regularizer=regularizers.l2(0.001), activation='relu'))\n\nmodel.add(layers.Dense(1, activation='sigmoid'))", "_____no_output_____" ] ], [ [ "<img src=\"res/img3.png\"></img>", "_____no_output_____" ], [ "### 1.2.3 Adding Dropout ", "_____no_output_____" ], [ "Idea: Randomly drop out a number of (activation) nodes during training. \n \n**Assume**: [0.2, 0.5, 1.3, 0.8, 1.1] is the output of a layer (after activation function).\n\nDropout sets randomly some of these weights to 0. For example: [0, 0.5, 1.3, 0, 1.1]. \n\nThe *dropout rate* is the fraction of features that are zeroed out (usually between 0.2 and 0.5)", "_____no_output_____" ] ], [ [ "# Example Code \nmodel = models.Sequential()\nmodel.add(layers.Dense(16, activation='relu', input_shape=(10000,)))\n\n# Pass dropout rate!!!\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(16, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\n# Compile..\n# Fit..\n# Evaluate...\n# Doc: https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dropout", "_____no_output_____" ] ], [ [ "<img src=\"res/img4.png\"></img>", "_____no_output_____" ], [ "### To recap, these are the most common ways to prevent overfitting in neural networks:\n1. Get more training data.\n2. Reduce the capacity of the network.\n3. Add weight regularization.\n4. Add dropout.\n5. Data Augmentation (for image classification tasks)", "_____no_output_____" ], [ "## 2 Gradient Descent ", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import california_housing\nfrom sklearn.metrics import mean_squared_error\n\nhousing_data = california_housing.fetch_california_housing()\n\nfeatures = pd.DataFrame(housing_data.data, columns=housing_data.feature_names)\ntarget = pd.DataFrame(housing_data.target, columns=['Target'])\n\ndf = features.join(target)\n\nX = df.MedInc\nY = df.Target", "_____no_output_____" ], [ "def gradient_descent(X, y, lr=0.05, iterations=10):\n \n '''\n Gradient Descent for a single feature\n '''\n \n m, b = 0.2, 0.2 # initial random parameters\n log, mse = [], [] # lists to store learning process\n N = len(X) # number of samples\n \n # MSE = 1/N SUM (y_i - (m*x_i +b))^2 \n # MSE' w.r.t. m => 1/N * SUM(-2*x_i*(m*x_i+b))\n # MSE' w.r.t. b => 1/N * SUM(-2*(m*x_i+b))\n\n for _ in range(iterations):\n \n f = y - (m*X + b)\n \n # Updating m and b \n m -= lr * (-2 * X.dot(f).sum() / N)\n b -= lr * (-2 * f.sum() / N)\n \n log.append((m, b))\n mse.append(mean_squared_error(y, (m*X + b))) \n \n return m, b, log, mse\n", "_____no_output_____" ], [ "m, b, log, mse = gradient_descent(X, Y, lr=0.01, iterations=10)", "_____no_output_____" ], [ "(m, b)", "_____no_output_____" ], [ "# Analytical Solution (compaed to )\nfrom sklearn.linear_model import LinearRegression\nreg = LinearRegression().fit(features[\"MedInc\"].to_numpy().reshape(-1, 1), Y)", "_____no_output_____" ], [ "(reg.coef_, reg.intercept_)", "_____no_output_____" ] ], [ [ "##### Stochastic Gradient Descent", "_____no_output_____" ] ], [ [ "def stochastic_gradient_descent(X, y, lr=0.05, iterations=10, batch_size=10):\n \n '''\n Stochastic Gradient Descent for a single feature\n '''\n \n m, b = 0.5, 0.5 # initial parameters\n log, mse = [], [] # lists to store learning process\n \n for _ in range(iterations):\n \n indexes = np.random.randint(0, len(X), batch_size) # random sample\n \n Xs = np.take(X, indexes)\n ys = np.take(y, indexes)\n N = len(Xs)\n \n f = ys - (m*Xs + b)\n \n # Updating parameters m and b\n m -= lr * (-2 * Xs.dot(f).sum() / N)\n b -= lr * (-2 * f.sum() / N)\n \n log.append((m, b))\n mse.append(mean_squared_error(y, m*X+b)) \n \n return m, b, log, mse", "_____no_output_____" ], [ "m, b, log, mse = stochastic_gradient_descent(X, Y, lr=0.01, iterations=1000)", "_____no_output_____" ], [ "(m,b)", "_____no_output_____" ] ], [ [ "## 2. Using CNNs to Classify Hand-written Digits on MNIST Dataset", "_____no_output_____" ], [ "<img src=\"res/img5.png\"></img>", "_____no_output_____" ] ], [ [ "from keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Conv2D, MaxPool2D\nfrom keras.utils import np_utils", "Using TensorFlow backend.\n/Users/demircanm/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n/Users/demircanm/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n/Users/demircanm/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n/Users/demircanm/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n/Users/demircanm/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n/Users/demircanm/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" ], [ "# Load Data\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n", "_____no_output_____" ], [ "# Shape of data\nprint(\"X_train shape\", X_train.shape)\nprint(\"y_train shape\", y_train.shape)\nprint(\"X_test shape\", X_test.shape)\nprint(\"y_test shape\", y_test.shape)", "X_train shape (60000, 28, 28)\ny_train shape (60000,)\nX_test shape (10000, 28, 28)\ny_test shape (10000,)\n" ], [ "# Flattening the images from the 28x28 pixels to 1D 784 pixels\nX_train = X_train.reshape(60000, 784)\nX_test = X_test.reshape(10000, 784)\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')", "_____no_output_____" ], [ "# normalizing the data to help with the training\nX_train /= 255\nX_test /= 255", "_____no_output_____" ], [ "# To Categorical (One-Hot Encoding)\nn_classes = 10\nprint(\"Shape before one-hot encoding: \", y_train.shape)\nY_train = np_utils.to_categorical(y_train, n_classes)\nY_test = np_utils.to_categorical(y_test, n_classes)\nprint(\"Shape after one-hot encoding: \", Y_train.shape)", "Shape before one-hot encoding: (60000,)\nShape after one-hot encoding: (60000, 10)\n" ], [ "# Let's build again a very boring neural network\nmodel = Sequential()\n# hidden layer\nmodel.add(Dense(100, input_shape=(784,), activation='relu'))\n# output layer\nmodel.add(Dense(10, activation='softmax'))", "_____no_output_____" ], [ "# looking at the model summary\nmodel.summary()\n# Compile\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')\n# Traing (####-> Caution, this is dedicated for validation data - I was just lazy...)\nmodel.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_test, Y_test))", "Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_3 (Dense) (None, 100) 78500 \n_________________________________________________________________\ndense_4 (Dense) (None, 10) 1010 \n=================================================================\nTotal params: 79,510\nTrainable params: 79,510\nNon-trainable params: 0\n_________________________________________________________________\nWARNING:tensorflow:From /Users/demircanm/opt/anaconda3/lib/python3.7/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.\nTrain on 60000 samples, validate on 10000 samples\nEpoch 1/10\n60000/60000 [==============================] - 4s 67us/step - loss: 1.8557 - accuracy: 0.5732 - val_loss: 1.2572 - val_accuracy: 0.7325\nEpoch 2/10\n60000/60000 [==============================] - 5s 88us/step - loss: 0.9612 - accuracy: 0.7905 - val_loss: 0.7372 - val_accuracy: 0.8338\nEpoch 3/10\n60000/60000 [==============================] - 2s 34us/step - loss: 0.6440 - accuracy: 0.8457 - val_loss: 0.5481 - val_accuracy: 0.8679\nEpoch 4/10\n60000/60000 [==============================] - 3s 50us/step - loss: 0.5101 - accuracy: 0.8701 - val_loss: 0.4539 - val_accuracy: 0.8848\nEpoch 5/10\n60000/60000 [==============================] - 2s 35us/step - loss: 0.4394 - accuracy: 0.8842 - val_loss: 0.4014 - val_accuracy: 0.8947\nEpoch 6/10\n60000/60000 [==============================] - 4s 67us/step - loss: 0.3967 - accuracy: 0.8928 - val_loss: 0.3704 - val_accuracy: 0.9003\nEpoch 7/10\n60000/60000 [==============================] - 2s 39us/step - loss: 0.3691 - accuracy: 0.8979 - val_loss: 0.3468 - val_accuracy: 0.9056\nEpoch 8/10\n60000/60000 [==============================] - 4s 64us/step - loss: 0.3497 - accuracy: 0.9024 - val_loss: 0.3297 - val_accuracy: 0.9079\nEpoch 9/10\n60000/60000 [==============================] - 4s 70us/step - loss: 0.3349 - accuracy: 0.9053 - val_loss: 0.3171 - val_accuracy: 0.9094\nEpoch 10/10\n60000/60000 [==============================] - 5s 81us/step - loss: 0.3234 - accuracy: 0.9081 - val_loss: 0.3083 - val_accuracy: 0.9116\n" ], [ "# new imports needed\nfrom keras.layers import Conv2D, MaxPool2D, Flatten\n\n# And now with a convolutional neural network\n# Doc: https://keras.io/api/layers/convolution_layers/\n\n# Load again data\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n# DONT Vectorize - keep grid structure\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\n# normalize\nX_train /= 255\nX_test /= 255\n\n# Sequential Model\nmodel = Sequential()\n# Convolutional layer\n\n# 2D convolutional data \n# filters: number of kernels\n# kernel size: (3, 3) pixel filter\n# stride: (move one to the right, one to the bottom when you reach the end of the row)\n# padding: \"valid\" => no padding => feature map is reduced\nmodel.add(Conv2D(filters=25, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu', input_shape=(28,28,1)))\n\n\nmodel.add(MaxPool2D(pool_size=(1,1)))\n# flatten output such that the \"densly\" connected network can be attached\nmodel.add(Flatten())\n\n# hidden layer\nmodel.add(Dense(100, activation='relu'))\n\n# output layer\nmodel.add(Dense(10, activation='softmax'))\n\n# compiling the sequential model\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')\n\n# training the model for 10 epochs\nmodel.fit(X_train, Y_train, batch_size=128, epochs=10, validation_data=(X_test, Y_test))", "Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n60000/60000 [==============================] - 42s 701us/step - loss: 0.1921 - accuracy: 0.9440 - val_loss: 0.0703 - val_accuracy: 0.9776\nEpoch 2/10\n60000/60000 [==============================] - 45s 746us/step - loss: 0.0577 - accuracy: 0.9830 - val_loss: 0.0554 - val_accuracy: 0.9815\nEpoch 3/10\n60000/60000 [==============================] - 46s 764us/step - loss: 0.0336 - accuracy: 0.9899 - val_loss: 0.0546 - val_accuracy: 0.9817\nEpoch 4/10\n60000/60000 [==============================] - 45s 743us/step - loss: 0.0198 - accuracy: 0.9945 - val_loss: 0.0513 - val_accuracy: 0.9831\nEpoch 5/10\n60000/60000 [==============================] - 65s 1ms/step - loss: 0.0135 - accuracy: 0.9962 - val_loss: 0.0504 - val_accuracy: 0.9840\nEpoch 6/10\n60000/60000 [==============================] - 61s 1ms/step - loss: 0.0097 - accuracy: 0.9972 - val_loss: 0.0542 - val_accuracy: 0.9848\nEpoch 7/10\n60000/60000 [==============================] - 60s 1ms/step - loss: 0.0061 - accuracy: 0.9983 - val_loss: 0.0532 - val_accuracy: 0.9850\nEpoch 8/10\n60000/60000 [==============================] - 75s 1ms/step - loss: 0.0046 - accuracy: 0.9988 - val_loss: 0.0636 - val_accuracy: 0.9819\nEpoch 9/10\n60000/60000 [==============================] - 61s 1ms/step - loss: 0.0058 - accuracy: 0.9984 - val_loss: 0.0568 - val_accuracy: 0.9844\nEpoch 10/10\n60000/60000 [==============================] - 57s 946us/step - loss: 0.0048 - accuracy: 0.9985 - val_loss: 0.0712 - val_accuracy: 0.9814\n" ], [ "# More on Classification with CNNs", "_____no_output_____" ] ], [ [ "## 3. Advanced Image Classification with Deep Convolutional Neural Networks", "_____no_output_____" ], [ "<img src=\"res/img6.png\">", "_____no_output_____" ] ], [ [ "# Imports\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Conv2D, MaxPool2D, Flatten\nfrom keras.utils import np_utils\n\n# Load Data\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\n# # Keep Grid Structure with 32x32 pixels (times 3; due to color channels)\nX_train = X_train.reshape(X_train.shape[0], 32, 32, 3)\nX_test = X_test.reshape(X_test.shape[0], 32, 32, 3)\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\n# Normalize\nX_train /= 255\nX_test /= 255\n\n# One-Hot Encoding\nn_classes = 10\nprint(\"Shape before one-hot encoding: \", y_train.shape)\nY_train = np_utils.to_categorical(y_train, n_classes)\nY_test = np_utils.to_categorical(y_test, n_classes)\nprint(\"Shape after one-hot encoding: \", Y_train.shape)", "Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n170500096/170498071 [==============================] - 57s 0us/step\nShape before one-hot encoding: (50000, 1)\nShape after one-hot encoding: (50000, 10)\n" ], [ "\n# Create Model Object\nmodel = Sequential()\n\n# Add Conv. Layer\nmodel.add(Conv2D(50, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu', input_shape=(32, 32, 3)))\n\n## What happens here?\n\n# Stack 2. Conv. Layer\nmodel.add(Conv2D(75, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Stack 3. Conv. Layer\nmodel.add(Conv2D(125, kernel_size=(3,3), strides=(1,1), padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Flatten Output of Conv. Part such that we can add a densly connected network\nmodel.add(Flatten())\n\n# Add Hidden Layer and Dropout Reg.\nmodel.add(Dense(500, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(250, activation='relu'))\nmodel.add(Dropout(0.3))\n\n# Output Layer\nmodel.add(Dense(10, activation='softmax'))\n\n# Compile\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')\n\n# Train\nmodel.fit(X_train, Y_train, batch_size=128, epochs=2, validation_data=(X_test, Y_test))", "Train on 50000 samples, validate on 10000 samples\nEpoch 1/2\n50000/50000 [==============================] - 609s 12ms/step - loss: 1.5991 - accuracy: 0.4083 - val_loss: 1.1784 - val_accuracy: 0.5895\nEpoch 2/2\n50000/50000 [==============================] - 625s 13ms/step - loss: 1.1153 - accuracy: 0.6038 - val_loss: 1.0032 - val_accuracy: 0.6471\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
cb274b9af278169c3f90bb0f5d256b58d8441c60
587,799
ipynb
Jupyter Notebook
Lab10_DBSCN.ipynb
Chaeguevara/IBM_Machine_Learning
066b2b2f1eb398cbdf91b07e79ba20c9ae216b66
[ "BSD-4-Clause-UC" ]
null
null
null
Lab10_DBSCN.ipynb
Chaeguevara/IBM_Machine_Learning
066b2b2f1eb398cbdf91b07e79ba20c9ae216b66
[ "BSD-4-Clause-UC" ]
null
null
null
Lab10_DBSCN.ipynb
Chaeguevara/IBM_Machine_Learning
066b2b2f1eb398cbdf91b07e79ba20c9ae216b66
[ "BSD-4-Clause-UC" ]
null
null
null
773.419737
240,819
0.682807
[ [ [ "<center>\n <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/Logos/organization_logo/organization_logo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n</center>\n\n# Density-Based Clustering\n\nEstimated time needed: **25** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n- Use DBSCAN to do Density based clustering\n- Use Matplotlib to plot clusters\n", "_____no_output_____" ], [ "Most of the traditional clustering techniques, such as k-means, hierarchical and fuzzy clustering, can be used to group data without supervision. \n\nHowever, when applied to tasks with arbitrary shape clusters, or clusters within cluster, the traditional techniques might be unable to achieve good results. That is, elements in the same cluster might not share enough similarity or the performance may be poor.\nAdditionally, Density-based Clustering locates regions of high density that are separated from one another by regions of low density. Density, in this context, is defined as the number of points within a specified radius.\n\nIn this section, the main focus will be manipulating the data and properties of DBSCAN and observing the resulting clustering.\n", "_____no_output_____" ], [ "Import the following libraries:\n\n<ul>\n <li> <b>numpy as np</b> </li>\n <li> <b>DBSCAN</b> from <b>sklearn.cluster</b> </li>\n <li> <b>make_blobs</b> from <b>sklearn.datasets.samples_generator</b> </li>\n <li> <b>StandardScaler</b> from <b>sklearn.preprocessing</b> </li>\n <li> <b>matplotlib.pyplot as plt</b> </li>\n</ul> <br>\nRemember <b> %matplotlib inline </b> to display plots\n", "_____no_output_____" ] ], [ [ "# Notice: For visualization of map, you need basemap package.\n# if you dont have basemap install on your machine, you can use the following line to install it\n!conda install -c conda-forge basemap matplotlib==3.1 -y\n# Notice: you maight have to refresh your page and re-run the notebook after installation", "Collecting package metadata (current_repodata.json): done\nSolving environment: failed with initial frozen solve. Retrying with flexible solve.\nCollecting package metadata (repodata.json): done\nSolving environment: failed with initial frozen solve. Retrying with flexible solve.\nSolving environment: \nFound conflicts! Looking for incompatible packages.\nThis can take several minutes. Press CTRL-C to abort.| \nfailed\n\nUnsatisfiableError: The following specifications were found to be incompatible with each other:\n\nOutput in format: Requested package -> Available versions\n\nPackage matplotlib conflicts for:\nbasemap -> matplotlib[version='>=1.0.0']\nmatplotlib==3.1\n\nPackage ca-certificates conflicts for:\nbasemap -> python[version='>=2.7,<2.8.0a0'] -> ca-certificates\npython=3.8 -> openssl[version='>=1.1.1i,<1.1.2a'] -> ca-certificates\n\n" ], [ "import numpy as np \nfrom sklearn.cluster import DBSCAN \nfrom sklearn.datasets.samples_generator import make_blobs \nfrom sklearn.preprocessing import StandardScaler \nimport matplotlib.pyplot as plt \n%matplotlib inline", "_____no_output_____" ], [ "### Data generation\n\nThe function below will generate the data points and requires these inputs:\n\n<ul>\n <li> <b>centroidLocation</b>: Coordinates of the centroids that will generate the random data. </li>\n <ul> <li> Example: input: [[4,3], [2,-1], [-1,4]] </li> </ul>\n <li> <b>numSamples</b>: The number of data points we want generated, split over the number of centroids (# of centroids defined in centroidLocation) </li>\n <ul> <li> Example: 1500 </li> </ul>\n <li> <b>clusterDeviation</b>: The standard deviation between the clusters. The larger the number, the further the spacing. </li>\n <ul> <li> Example: 0.5 </li> </ul>\n</ul>\n", "_____no_output_____" ] ], [ [ "def createDataPoints(centroidLocation, numSamples, clusterDeviation):\n # Create random data and store in feature matrix X and response vector y.\n X, y = make_blobs(n_samples=numSamples, centers=centroidLocation, \n cluster_std=clusterDeviation)\n \n # Standardize features by removing the mean and scaling to unit variance\n X = StandardScaler().fit_transform(X)\n return X, y", "_____no_output_____" ] ], [ [ "Use <b>createDataPoints</b> with the <b>3 inputs</b> and store the output into variables <b>X</b> and <b>y</b>.\n", "_____no_output_____" ] ], [ [ "X, y = createDataPoints([[4,3], [2,-1], [-1,4]] , 1500, 0.5)", "_____no_output_____" ] ], [ [ "### Modeling\n\nDBSCAN stands for Density-Based Spatial Clustering of Applications with Noise. This technique is one of the most common clustering algorithms which works based on density of object.\nThe whole idea is that if a particular point belongs to a cluster, it should be near to lots of other points in that cluster.\n\nIt works based on two parameters: Epsilon and Minimum Points \n**Epsilon** determine a specified radius that if includes enough number of points within, we call it dense area \n**minimumSamples** determine the minimum number of data points we want in a neighborhood to define a cluster.\n", "_____no_output_____" ] ], [ [ "epsilon = 0.3\nminimumSamples = 7\ndb = DBSCAN(eps=epsilon, min_samples=minimumSamples).fit(X)\nlabels = db.labels_\nlabels", "_____no_output_____" ] ], [ [ "### Distinguish outliers\n\nLets Replace all elements with 'True' in core_samples_mask that are in the cluster, 'False' if the points are outliers.\n", "_____no_output_____" ], [ "# Firts, create an array of booleans using the labels from db.\ncore_samples_mask = np.zeros_like(db.labels_, dtype=bool)\ncore_samples_mask[db.core_sample_indices_] = True\ncore_samples_mask", "_____no_output_____" ], [ "# Number of clusters in labels, ignoring noise if present.\nn_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\nn_clusters_", "_____no_output_____" ] ], [ [ "# Remove repetition in labels by turning it into a set.\nunique_labels = set(labels)\nunique_labels", "_____no_output_____" ] ], [ [ "### Data visualization\n", "_____no_output_____" ], [ "# Create colors for the clusters.\ncolors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))\n", "_____no_output_____" ], [ "# Plot the points with colors\nfor k, col in zip(unique_labels, colors):\n if k == -1:\n # Black used for noise.\n col = 'k'\n\n class_member_mask = (labels == k)\n\n # Plot the datapoints that are clustered\n xy = X[class_member_mask & core_samples_mask]\n plt.scatter(xy[:, 0], xy[:, 1],s=50, c=[col], marker=u'o', alpha=0.5)\n\n # Plot the outliers\n xy = X[class_member_mask & ~core_samples_mask]\n plt.scatter(xy[:, 0], xy[:, 1],s=50, c=[col], marker=u'o', alpha=0.5)", "*c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*. Please use the *color* keyword-argument or provide a 2-D array with a single row if you intend to specify the same RGB or RGBA value for all points.\n*c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*. Please use the *color* keyword-argument or provide a 2-D array with a single row if you intend to specify the same RGB or RGBA value for all points.\n*c* argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with *x* & *y*. Please use the *color* keyword-argument or provide a 2-D array with a single row if you intend to specify the same RGB or RGBA value for all points.\n" ] ], [ [ "from sklearn.cluster import KMeans \nk = 3\nk_means3 = KMeans(init = \"k-means++\", n_clusters = k, n_init = 12)\nk_means3.fit(X)\nfig = plt.figure(figsize=(6, 4))\nax = fig.add_subplot(1, 1, 1)\nfor k, col in zip(range(k), colors):\n my_members = (k_means3.labels_ == k)\n plt.scatter(X[my_members, 0], X[my_members, 1], c=col, marker=u'o', alpha=0.5)\nplt.show()", "_____no_output_____" ], [ "<h1 align=center> Weather Station Clustering using DBSCAN & scikit-learn </h1>\n<hr>\n\nDBSCAN is specially very good for tasks like class identification on a spatial context. The wonderful attribute of DBSCAN algorithm is that it can find out any arbitrary shape cluster without getting affected by noise. For example, this following example cluster the location of weather stations in Canada.\n<Click 1>\nDBSCAN can be used here, for instance, to find the group of stations which show the same weather condition. As you can see, it not only finds different arbitrary shaped clusters, can find the denser part of data-centered samples by ignoring less-dense areas or noises.\n\nlet's start playing with the data. We will be working according to the following workflow: </font>\n\n1. Loading data\n\n- Overview data\n- Data cleaning\n- Data selection\n- Clusteing\n", "_____no_output_____" ], [ "### About the dataset\n\n<h4 align = \"center\">\nEnvironment Canada \nMonthly Values for July - 2015\t\n</h4>\n<html>\n<head>\n<style>\ntable {\n font-family: arial, sans-serif;\n border-collapse: collapse;\n width: 100%;\n}\n\ntd, th {\n border: 1px solid #dddddd;\n text-align: left;\n padding: 8px;\n}\n\ntr:nth-child(even) {\n background-color: #dddddd;\n}\n</style>\n\n</head>\n<body>\n\n<table>\n <tr>\n <th>Name in the table</th>\n <th>Meaning</th>\n </tr>\n <tr>\n <td><font color = \"green\"><strong>Stn_Name</font></td>\n <td><font color = \"green\"><strong>Station Name</font</td>\n </tr>\n <tr>\n <td><font color = \"green\"><strong>Lat</font></td>\n <td><font color = \"green\"><strong>Latitude (North+, degrees)</font></td>\n </tr>\n <tr>\n <td><font color = \"green\"><strong>Long</font></td>\n <td><font color = \"green\"><strong>Longitude (West - , degrees)</font></td>\n </tr>\n <tr>\n <td>Prov</td>\n <td>Province</td>\n </tr>\n <tr>\n <td>Tm</td>\n <td>Mean Temperature (°C)</td>\n </tr>\n <tr>\n <td>DwTm</td>\n <td>Days without Valid Mean Temperature</td>\n </tr>\n <tr>\n <td>D</td>\n <td>Mean Temperature difference from Normal (1981-2010) (°C)</td>\n </tr>\n <tr>\n <td><font color = \"black\">Tx</font></td>\n <td><font color = \"black\">Highest Monthly Maximum Temperature (°C)</font></td>\n </tr>\n <tr>\n <td>DwTx</td>\n <td>Days without Valid Maximum Temperature</td>\n </tr>\n <tr>\n <td><font color = \"black\">Tn</font></td>\n <td><font color = \"black\">Lowest Monthly Minimum Temperature (°C)</font></td>\n </tr>\n <tr>\n <td>DwTn</td>\n <td>Days without Valid Minimum Temperature</td>\n </tr>\n <tr>\n <td>S</td>\n <td>Snowfall (cm)</td>\n </tr>\n <tr>\n <td>DwS</td>\n <td>Days without Valid Snowfall</td>\n </tr>\n <tr>\n <td>S%N</td>\n <td>Percent of Normal (1981-2010) Snowfall</td>\n </tr>\n <tr>\n <td><font color = \"green\"><strong>P</font></td>\n <td><font color = \"green\"><strong>Total Precipitation (mm)</font></td>\n </tr>\n <tr>\n <td>DwP</td>\n <td>Days without Valid Precipitation</td>\n </tr>\n <tr>\n <td>P%N</td>\n <td>Percent of Normal (1981-2010) Precipitation</td>\n </tr>\n <tr>\n <td>S_G</td>\n <td>Snow on the ground at the end of the month (cm)</td>\n </tr>\n <tr>\n <td>Pd</td>\n <td>Number of days with Precipitation 1.0 mm or more</td>\n </tr>\n <tr>\n <td>BS</td>\n <td>Bright Sunshine (hours)</td>\n </tr>\n <tr>\n <td>DwBS</td>\n <td>Days without Valid Bright Sunshine</td>\n </tr>\n <tr>\n <td>BS%</td>\n <td>Percent of Normal (1981-2010) Bright Sunshine</td>\n </tr>\n <tr>\n <td>HDD</td>\n <td>Degree Days below 18 °C</td>\n </tr>\n <tr>\n <td>CDD</td>\n <td>Degree Days above 18 °C</td>\n </tr>\n <tr>\n <td>Stn_No</td>\n <td>Climate station identifier (first 3 digits indicate drainage basin, last 4 characters are for sorting alphabetically).</td>\n </tr>\n <tr>\n <td>NA</td>\n <td>Not Available</td>\n </tr>\n\n</table>\n\n</body>\n</html>\n", "_____no_output_____" ] ], [ [ "### 1-Download data\n\nTo download the data, we will use **`!wget`**. To download the data, we will use `!wget` to download it from IBM Object Storage. \n**Did you know?** When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC)\n", "--2021-02-07 22:42:57-- https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%204/data/weather-stations20140101-20141231.csv\nResolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 169.45.118.108\nConnecting to cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)|169.45.118.108|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 129821 (127K) [text/csv]\nSaving to: ‘weather-stations20140101-20141231.csv’\n\nweather-stations201 100%[===================>] 126.78K 88.4KB/s in 1.4s \n\n2021-02-07 22:43:02 (88.4 KB/s) - ‘weather-stations20140101-20141231.csv’ saved [129821/129821]\n\n" ] ], [ [ "!wget -O weather-stations20140101-20141231.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%204/data/weather-stations20140101-20141231.csv", "_____no_output_____" ] ], [ [ "### 2- Load the dataset\n\nWe will import the .csv then we creates the columns for year, month and day.\n", "_____no_output_____" ] ], [ [ "import csv\nimport pandas as pd\nimport numpy as np\n\nfilename='weather-stations20140101-20141231.csv'\n\n#Read csv\npdf = pd.read_csv(filename)\npdf.head(5)", "_____no_output_____" ] ], [ [ "### 3-Cleaning\n\nLets remove rows that dont have any value in the **Tm** field.\n", "_____no_output_____" ] ], [ [ "pdf = pdf[pd.notnull(pdf[\"Tm\"])]\npdf = pdf.reset_index(drop=True)\npdf.head(5)", "_____no_output_____" ] ], [ [ "### 4-Visualization\n\nVisualization of stations on map using basemap package. The matplotlib basemap toolkit is a library for plotting 2D data on maps in Python. Basemap does not do any plotting on it’s own, but provides the facilities to transform coordinates to a map projections. \n\nPlease notice that the size of each data points represents the average of maximum temperature for each station in a year. \n", "_____no_output_____" ], [ "from mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\n%matplotlib inline\nrcParams['figure.figsize'] = (14,10)\n\nllon=-140\nulon=-50\nllat=40\nulat=65\n\npdf = pdf[(pdf['Long'] > llon) & (pdf['Long'] < ulon) & (pdf['Lat'] > llat) &(pdf['Lat'] < ulat)]\n\nmy_map = Basemap(projection='merc',\n resolution = 'l', area_thresh = 1000.0,\n llcrnrlon=llon, llcrnrlat=llat, #min longitude (llcrnrlon) and latitude (llcrnrlat)\n urcrnrlon=ulon, urcrnrlat=ulat) #max longitude (urcrnrlon) and latitude (urcrnrlat)\n\nmy_map.drawcoastlines()\nmy_map.drawcountries()\n# my_map.drawmapboundary()\nmy_map.fillcontinents(color = 'white', alpha = 0.3)\nmy_map.shadedrelief()\n\n# To collect data based on stations \n\nxs,ys = my_map(np.asarray(pdf.Long), np.asarray(pdf.Lat))\npdf['xm']= xs.tolist()\npdf['ym'] =ys.tolist()\n\n#Visualization1\nfor index,row in pdf.iterrows():\n# x,y = my_map(row.Long, row.Lat)\n my_map.plot(row.xm, row.ym,markerfacecolor =([1,0,0]), marker='o', markersize= 5, alpha = 0.75)\n#plt.text(x,y,stn)\nplt.show()\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb275a405933c23a4494c90c5deb22800414bebb
6,646
ipynb
Jupyter Notebook
SparkSQL/ETLforSQL_Spark.ipynb
himasai97/MovieLens-Data-Analytics-in-Spark-and-Python
cc7e1c2b8f881c478fede12f83931d6e983b82a2
[ "Apache-2.0" ]
null
null
null
SparkSQL/ETLforSQL_Spark.ipynb
himasai97/MovieLens-Data-Analytics-in-Spark-and-Python
cc7e1c2b8f881c478fede12f83931d6e983b82a2
[ "Apache-2.0" ]
null
null
null
SparkSQL/ETLforSQL_Spark.ipynb
himasai97/MovieLens-Data-Analytics-in-Spark-and-Python
cc7e1c2b8f881c478fede12f83931d6e983b82a2
[ "Apache-2.0" ]
null
null
null
88.613333
1,492
0.633012
[ [ [ "from pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SQLContext, SparkSession\nfrom pyspark.sql.types import StructType, StructField, DoubleType, IntegerType, StringType\n\nfrom ibm_botocore.client import Config\nimport ibm_boto3\nimport os\nfrom pyspark.sql.functions import unix_timestamp, to_date\nimport pyspark.sql.functions as F\n\n\nimport numpy as np\nimport pandas as pd\nimport json\nimport pyspark.sql\nfrom pyspark.sql.functions import col, skewness, kurtosis\nfrom pyspark.sql.functions import isnan, when, count, col\nfrom pyspark.sql.functions import when\nfrom pyspark.sql.functions import UserDefinedFunction\nfrom pyspark.sql.types import StringType\nfrom datetime import date, timedelta, datetime\nimport time\n\nsc = SparkContext.getOrCreate(SparkConf().setMaster(\"local[*]\"))\nfrom pyspark.sql import SparkSession\nspark = SparkSession \\\n .builder \\\n .getOrCreate()", "Waiting for a Spark session to start...\nSpark Initialization Done! ApplicationId = app-20210210211421-0000\nKERNEL_ID = 8f0338a9-dc91-4cab-9963-b666ae82b8f5\n" ], [ "from zipfile import ZipFile\n\ncredentials = {\n 'IAM_SERVICE_ID': 'iam-ServiceId-3c1861d6-5e36-4bd6-9a2c-193573560cbf',\n 'IBM_API_KEY_ID': 'p5ub7Zlafd2TotZeptmWjdN0MbfseCEWl54M7UMVfKtO',\n 'ENDPOINT': 'https://s3-api.us-geo.objectstorage.service.networklayer.com',\n 'IBM_AUTH_ENDPOINT': 'https://iam.cloud.ibm.com/oidc/token',\n 'BUCKET': 'movielensdataanalyticsinsparkandp-donotdelete-pr-7pdjrbcote4rbl',\n 'FILE': ['ratings.dat.zip', 'movies.dat','users.dat']\n}\n\ncos = ibm_boto3.client(service_name='s3',\n ibm_api_key_id=credentials['IBM_API_KEY_ID'],\n ibm_service_instance_id=credentials['IAM_SERVICE_ID'],\n ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'],\n config=Config(signature_version='oauth'),\n endpoint_url=credentials['ENDPOINT'])\ncos.download_file(Bucket=credentials['BUCKET'],Key=credentials['FILE'][0],Filename=credentials['FILE'][0])\ncos.download_file(Bucket=credentials['BUCKET'],Key=credentials['FILE'][1],Filename=credentials['FILE'][1])\ncos.download_file(Bucket=credentials['BUCKET'],Key=credentials['FILE'][2],Filename=credentials['FILE'][2])\n\nwith ZipFile(credentials['FILE'][0],'r') as zipObj:\n zipObj.extractall()", "_____no_output_____" ], [ "import ibmos2spark\n\ncredentials2 = {\n 'endpoint': 'https://s3-api.us-geo.objectstorage.service.networklayer.com',\n 'service_id': 'iam-ServiceId-3c1861d6-5e36-4bd6-9a2c-193573560cbf',\n 'iam_service_endpoint': 'https://iam.cloud.ibm.com/oidc/token',\n 'api_key': 'p5ub7Zlafd2TotZeptmWjdN0MbfseCEWl54M7UMVfKtO'\n}\n\nconfiguration_name = 'os_54ba3cbe01c144af917f4e0e63fb0d9c_configs'\ncos2 = ibmos2spark.CloudObjectStorage(sc, credentials2, configuration_name, 'bluemix_cos')\n", "_____no_output_____" ], [ "\nspark.read.text(\"movies.dat\").createOrReplaceTempView(\"movies_staging\")\nspark.read.text(\"ratings.dat\").createOrReplaceTempView(\"ratings_staging\")\nspark.read.text(\"users.dat\").createOrReplaceTempView(\"users_staging\")\n\n## Create a database to store the tables\nspark.sql(\"drop database if exists sparkdatalake cascade\")\nspark.sql(\"create database sparkdatalake\");\n\n\n## Make appropriate schemas for them\n## movies\nmovies_df = spark.sql(\"\"\" Select \nsplit(value,'::')[0] as movieid,\nsplit(value,'::')[1] as title,\nsubstring(split(value,'::')[1],length(split(value,'::')[1])-4,4) as year,\nsplit(value,'::')[2] as genre \nfrom movies_staging \"\"\").write.parquet(cos2.url('moviesdataframe.parquet', 'movielensdataanalyticsinsparkandp-donotdelete-pr-7pdjrbcote4rbl'))\n\n## users\nspark.sql(\"\"\" Select\nsplit(value,'::')[0] as userid,\nsplit(value,'::')[1] as gender,\nsplit(value,'::')[2] as age,\nsplit(value,'::')[3] as occupation,\nsplit(value,'::')[4] as zipcode\nfrom users_staging \"\"\").write.parquet(cos2.url('usersdataframe.parquet', 'movielensdataanalyticsinsparkandp-donotdelete-pr-7pdjrbcote4rbl'))\n\n## ratings\nspark.sql(\"\"\" Select\nsplit(value,'::')[0] as userid,\nsplit(value,'::')[1] as movieid,\nsplit(value,'::')[2] as rating,\nsplit(value,'::')[3] as timestamp\nfrom ratings_staging \"\"\").write.parquet(cos2.url('ratingsdataframe.parquet', 'movielensdataanalyticsinsparkandp-donotdelete-pr-7pdjrbcote4rbl'))\n", "_____no_output_____" ], [ "dfreadback = spark.read.parquet(cos.url('moviesdataframe.parquet', 'movielensdataanalyticsinsparkandp-donotdelete-pr-7pdjrbcote4rbl'))\ndfreadback.take(4)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
cb275f4c9e5b0ca53ee202ae9f45892d505525f7
93,873
ipynb
Jupyter Notebook
research_phase/gradient_boosting_model.ipynb
cbymar/testing-and-monitoring-ml-deployments
a199e84815c9eba7ab57379e4bebd16e45187926
[ "BSD-3-Clause" ]
null
null
null
research_phase/gradient_boosting_model.ipynb
cbymar/testing-and-monitoring-ml-deployments
a199e84815c9eba7ab57379e4bebd16e45187926
[ "BSD-3-Clause" ]
null
null
null
research_phase/gradient_boosting_model.ipynb
cbymar/testing-and-monitoring-ml-deployments
a199e84815c9eba7ab57379e4bebd16e45187926
[ "BSD-3-Clause" ]
null
null
null
42.190112
18,080
0.471392
[ [ [ "from math import sqrt\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# for the ML pipeline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# from sklearn.pipeline import Pipeline\n# from sklearn.compose import ColumnTransformer\n\nfrom feature_engine.categorical_encoders import RareLabelCategoricalEncoder\n\n# to visualise al the columns in the dataframe\npd.pandas.set_option('display.max_columns', None)", "_____no_output_____" ], [ "# load dataset\n# remember to download the data set from Kaggle and save it into \n# the same folder from where you run this notebook\n\ndata = pd.read_csv('houseprice.csv')\n\nprint(data.shape)\ndata.head()", "(1460, 81)\n" ] ], [ [ "### Separate dataset into train and test\n\nBefore beginning to engineer our features, it is important to separate our data intro training and testing set. This is to avoid over-fitting. This step involves randomness, therefore, we need to set the seed.", "_____no_output_____" ] ], [ [ "# Let's separate into train and test set\n\nX_train, X_test, y_train, y_test = train_test_split(\n data.drop('SalePrice', axis=1), # predictors\n data.SalePrice, # target\n test_size=0.1,\n random_state=0) # for reproducibility\n\nX_train.shape, X_test.shape, y_train.shape, y_test.shape", "_____no_output_____" ] ], [ [ "### Missing values", "_____no_output_____" ] ], [ [ "# make lists capturing the different variables types in our dataset:\n# -----------------------------------------\n# one list to capture date variables\n# one list to capture categorical variables\n# one list to capture numerical variables\n\nvars_dates = ['YearBuilt', 'YearRemodAdd', 'GarageYrBlt']\nvars_cat = [var for var in X_train.columns if X_train[var].dtypes == 'O']\nvars_num = [var for var in X_train.columns if X_train[var].dtypes !=\n 'O' and var not in ['Id']]", "_____no_output_____" ], [ "# check for missing values in our date variables\n\nX_train[vars_dates].isnull().mean().sort_values(ascending=False)", "_____no_output_____" ], [ "# check for missing values in our numerical variables\n\nX_train[vars_num].isnull().mean().sort_values(ascending=False)", "_____no_output_____" ], [ "# check for missing values in our categorical variables\n\nX_train[vars_cat].isnull().mean().sort_values(ascending=False)", "_____no_output_____" ], [ "# removing missing data\n# --------------------\n# imputation numerical variables\nimputer = SimpleImputer(strategy='constant', fill_value=-1)\nX_train['LotFrontage'] = imputer.fit_transform(X_train['LotFrontage'].to_frame())\nX_test['LotFrontage'] = imputer.transform(X_test['LotFrontage'].to_frame())\n\nimputer = SimpleImputer(strategy='most_frequent')\nX_train[vars_num] = imputer.fit_transform(X_train[vars_num])\nX_test[vars_num] = imputer.transform(X_test[vars_num])", "_____no_output_____" ], [ "# imputation categorical variables\nimputer = SimpleImputer(strategy='constant', fill_value='missing')\nX_train[vars_cat] = imputer.fit_transform(X_train[vars_cat])\nX_test[vars_cat] = imputer.transform(X_test[vars_cat])", "_____no_output_____" ] ], [ [ "### Temporal variables", "_____no_output_____" ] ], [ [ "# let's create new temporal features from our date variables\n\n\ndef elapsed_years(df, var):\n # capture difference between year variable and year the house was sold\n df[var] = df['YrSold'] - df[var]\n return df", "_____no_output_____" ], [ "for var in ['YearBuilt', 'YearRemodAdd', 'GarageYrBlt']:\n X_train = elapsed_years(X_train, var)\n X_test = elapsed_years(X_test, var)", "_____no_output_____" ], [ "# check that test set does not contain null values in the engineered variables\n[vr for var in ['YearBuilt', 'YearRemodAdd', 'GarageYrBlt'] if X_test[var].isnull().sum()>0]", "_____no_output_____" ] ], [ [ "### Categorical variable encoding", "_____no_output_____" ] ], [ [ "[var for var in X_train.columns if X_train[var].isnull().sum()>0]", "_____no_output_____" ], [ "[var for var in X_train.columns if X_test[var].isnull().sum()>0]", "_____no_output_____" ], [ "# remove rare caregories\n\nrare_enc = RareLabelCategoricalEncoder(tol=0.01, n_categories=5, variables = vars_cat)\nrare_enc.fit(X_train)\nX_train = rare_enc.transform(X_train)\nX_test = rare_enc.transform(X_test)", "_____no_output_____" ], [ "# encode with labels\n\nordinal_enc = OrdinalEncoder()\nX_train[vars_cat] = ordinal_enc.fit_transform(X_train[vars_cat])\nX_test[vars_cat] = ordinal_enc.transform(X_test[vars_cat])", "_____no_output_____" ], [ "[var for var in X_train.columns if X_test[var].isnull().sum()>0]", "_____no_output_____" ], [ "X_train.head()", "_____no_output_____" ] ], [ [ "## Gradient boosting regressor", "_____no_output_____" ] ], [ [ "tree_reg = GradientBoostingRegressor(random_state=0, n_estimators=50)\ntree_reg.fit(X_train, y_train)", "_____no_output_____" ], [ "# evaluate the model:\n\n# We will evaluate performance using the mean squared error and the\n# root of the mean squared error\n\npred = tree_reg.predict(X_train)\nprint('linear train mse: {}'.format(mean_squared_error(y_train, pred)))\nprint('linear train rmse: {}'.format(sqrt(mean_squared_error(y_train, pred))))\nprint()\npred = tree_reg.predict(X_test)\nprint('linear test mse: {}'.format(mean_squared_error(y_test, pred)))\nprint('linear test rmse: {}'.format(sqrt(mean_squared_error(y_test, pred))))", "linear train mse: 319335295.90204245\nlinear train rmse: 17869.955117516172\n\nlinear test mse: 1100602976.041241\nlinear test rmse: 33175.33686402055\n" ], [ "# These are the values produced by our current live model\n# we new them from the past, so I pase them here for information\n\nprint('''\nPrediction analysis from old Lasso Regression:\n---------------------------------------------\nlinear train mse: 1087435415.4414542\nlinear train rmse: 32976.28565259366\n\nlinear test mse: 1405259552.2596064\nlinear test rmse: 37486.79170400698\n''')", "\nPrediction analysis from old Lasso Regression:\n---------------------------------------------\nlinear train mse: 1087435415.4414542\nlinear train rmse: 32976.28565259366\n\nlinear test mse: 1405259552.2596064\nlinear test rmse: 37486.79170400698\n\n" ], [ "# let's evaluate our predictions respect to the original price\n\nplt.scatter(y_test, tree_reg.predict(X_test))\nplt.xlabel('True House Price')\nplt.ylabel('Predicted House Price')\nplt.title('Evaluation of Lasso Predictions')", "_____no_output_____" ] ], [ [ "## Feature Selection", "_____no_output_____" ] ], [ [ "# here I will do the model fitting and feature selection\n# altogether in one line of code\n\n# To select features we use Scikit-learn's SelectFromModel\n# specifying the the Gradient Boosting Regressor model\n\n# and we train the SelecgFromModel with the train set.\n\n# remember to set the seed, the random state in this function\nsel_ = SelectFromModel(GradientBoostingRegressor(\n random_state=0, n_estimators=50))\nsel_.fit(X_train, y_train)", "_____no_output_____" ], [ "# let's print the number of total and selected features\n\n# this is how we can make a list of the selected features\nselected_feat = X_train.columns[(sel_.get_support())]\n\n# let's print some stats\nprint('total features: {}'.format((X_train.shape[1])))\nprint('selected features: {}'.format(len(selected_feat)))", "total features: 80\nselected features: 10\n" ], [ "selected_feat", "_____no_output_____" ] ], [ [ "## Re-build model with selected features", "_____no_output_____" ] ], [ [ "tree_reg = GradientBoostingRegressor(random_state=0, n_estimators=50)\ntree_reg.fit(X_train[selected_feat], y_train)", "_____no_output_____" ], [ "pred = tree_reg.predict(X_train[selected_feat])\nprint('linear train mse: {}'.format(mean_squared_error(y_train, pred)))\nprint('linear train rmse: {}'.format(sqrt(mean_squared_error(y_train, pred))))\nprint()\npred = tree_reg.predict(X_test[selected_feat])\nprint('linear test mse: {}'.format(mean_squared_error(y_test, pred)))\nprint('linear test rmse: {}'.format(sqrt(mean_squared_error(y_test, pred))))", "linear train mse: 418644251.8706319\nlinear train rmse: 20460.797928493204\n\nlinear test mse: 633153768.8943316\nlinear test rmse: 25162.54694768261\n" ], [ "data[selected_feat].head()", "_____no_output_____" ], [ "# make a list of the categorical variables that contain missing values\n\nvars_dates = ['YearRemodAdd']\nvars_cat = ['BsmtQual']\nvars_num = ['LotArea', 'OverallQual', 'YearRemodAdd', 'BsmtQual', 'BsmtFinSF1',\n 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'GrLivArea', 'GarageCars']", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
cb276625695d9e4a519b15a67e4dfe8ee7eb9b2d
17,991
ipynb
Jupyter Notebook
wienerschnitzelgemeinschaft/src/Russ/ens_sub66d.ipynb
guitarmind/HPA-competition-solutions
547d53aaca148fdb5f4585526ad7364dfa47967d
[ "MIT" ]
null
null
null
wienerschnitzelgemeinschaft/src/Russ/ens_sub66d.ipynb
guitarmind/HPA-competition-solutions
547d53aaca148fdb5f4585526ad7364dfa47967d
[ "MIT" ]
null
null
null
wienerschnitzelgemeinschaft/src/Russ/ens_sub66d.ipynb
guitarmind/HPA-competition-solutions
547d53aaca148fdb5f4585526ad7364dfa47967d
[ "MIT" ]
null
null
null
24.849448
86
0.412984
[ [ [ "prefix = 'ens'\nmidx = '66'", "_____no_output_____" ], [ "import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import f1_score, confusion_matrix", "_____no_output_____" ], [ "new = pd.read_csv('leak2d.csv')\nnew = new[new.Questionable != 1]\nnew.reset_index(inplace=True)\nprint(new.head())\nprint(new.shape)\n\nens = pd.read_csv('sub/'+prefix+midx+'.csv').fillna('')\nens = ens.set_index('Id')\nprint(ens.head())\nprint(ens.shape)", " index Id Target Questionable\n0 0 94205e64-baca-11e8-b2b8-ac1f6b6435d0 16 0\n1 1 53f49b94-bad3-11e8-b2b8-ac1f6b6435d0 9 10 0\n2 3 47c3e666-bac6-11e8-b2b7-ac1f6b6435d0 14 25 0\n3 4 05d45be8-bace-11e8-b2b8-ac1f6b6435d0 2 25 0\n4 6 e5382de2-bad2-11e8-b2b8-ac1f6b6435d0 0 25 0\n(272, 4)\n Predicted\nId \n00008af0-bad0-11e8-b2b8-ac1f6b6435d0 2\n0000a892-bacf-11e8-b2b8-ac1f6b6435d0 5\n0006faa6-bac7-11e8-b2b7-ac1f6b6435d0 0 5 25\n0008baca-bad7-11e8-b2b9-ac1f6b6435d0 0\n000cce7e-bad4-11e8-b2b8-ac1f6b6435d0 \n(11702, 1)\n" ], [ "# # create onehot matrix for a submission file\n# def onehot_sub(csv0, num_classes=28):\n# c0 = pd.read_csv(csv0)\n# s0 = [s if isinstance(s,str) else '' for s in c0.Predicted]\n# p0 = [s.split() for s in s0]\n# y0 = np.zeros((c0.shape[0],num_classes)).astype(int)\n# # print(p0[:5])\n# for i in range(c0.shape[0]):\n# for j in p0[i]: y0[i,int(j)] = 1\n# # print(y0[:5])\n \n# y = pd.DataFrame(y0)\n# y.columns = ['y_'+str(i) for i in range(num_classes)]\n \n# c0 = pd.concat((c0,y),axis=1)\n \n# fname = csv0[:-4] + '_onehot.csv'\n# c0.to_csv(fname) \n# print(fname)\n \n# new['Predicted'] = new['Target'].values\n# fname = 'sub/leak2dd.csv'\n# new.to_csv(fname)\n# onehot_sub(fname)", "_____no_output_____" ], [ "changed = 0\nunchanged = 0\nfor i, item in enumerate(new['Id']):\n# print(test_preds.loc[i]['Target'])\n if ens.loc[item]['Predicted'] != new.loc[i]['Target']:\n print(ens.loc[item]['Predicted'],' => ', new.loc[i]['Target'])\n changed += 1\n ens.loc[item]['Predicted'] = new.loc[i]['Target']\n else:\n unchanged += 1\n\nprint('changed',changed,' unchanged',unchanged)\n\nprint()\nfname = 'sub/'+prefix+midx+'d.csv'\nens.to_csv(fname)\nprint(fname)", "0 7 => 16\n14 => 14 25\n0 3 25 => 2 25\n0 21 25 => 0 25\n0 5 => 0 19 21\n22 => 0 22 23\n25 => 21 25\n0 12 25 => 12\n12 21 26 => 12 21 25\n4 25 => 7 21\n0 21 => 0 21 25\n12 21 25 => 12\n4 => 4 23\n0 12 21 25 => 21\n18 25 => 0 18 25\n0 25 => 0 17 25\n6 23 => 2 23\n0 21 25 => 0 21 23\n0 14 25 => 0 14\n14 16 => 14\n0 16 => 0\n0 12 16 => 21\n16 25 => 14 16 25\n25 => 14 16 25\n2 => 1 2\n13 => 12 13\n0 12 21 25 => 0 12 25\n2 4 26 => 2 4 21 26\n4 12 21 => 13 21\n6 25 => 0 25\n16 25 => 14 16 25\n7 21 25 => 0 21 22\n16 25 => 25\n19 25 => 2 6 14 25\n0 13 19 => 13\n0 5 25 => 13\n7 25 => 21 25\n0 22 25 => 2 22\n4 => 4 21\n4 => 4 21\n7 => 2\n0 16 => 0 16 17 18\n0 16 => 0 16 17 18\n0 11 => 2 11\n18 => 0 19\n0 18 => 0 19\n0 18 => 0 19\n12 => 12 21 25\n14 16 => 0 14\n14 16 => 0 14\n1 => 1 5\n0 4 => 0\n0 12 16 => 21\n0 16 => 0\n5 23 => 23\n12 13 21 => 13 21\n0 14 => 14 25\n0 14 => 14\n0 14 16 => 14\n16 21 22 25 => 25\n14 16 21 25 => 16 19 21 25\n0 1 4 => 1 4\n5 16 => 16\n14 16 => 14 16 17\n5 => 0 5 25\n1 18 => 1\n14 16 25 => 25\n7 23 => 7 25\n => 27\n0 27 => 27\n21 25 => 25\n2 25 => 2\n2 25 => 2\n13 => 7 21\n0 19 => 0 1 7\n16 => 16 25\n7 => 7 17\n4 5 25 => 5 6 25\n25 => 15 25\n21 => 11 16 21\n26 27 => 27\n5 => 0 5 7\n21 22 => 12 21 22\n12 => 2 12\n4 => 4 21\n0 2 => 0\n0 12 => 12\n4 => 17 18\n0 16 25 => 0\n0 13 => 13\n0 13 => 13\n14 => 14 17 25\n5 22 => 25\n21 22 => 0 21 22\n21 22 => 0 21 22\n25 => 17 25\n4 21 => 4 17 21\n13 21 => 13 25\n23 26 27 => 23 27\n4 12 21 22 25 => 0 21 25\n25 => 0 25\n0 16 => 16\n12 13 => 0 22\n12 => 0 22\n => 17 25\n14 => 14 17\n0 16 => 0\n0 16 21 25 => 0 19\n11 14 => 4\n14 => 4\n0 26 => 0 25\n0 7 => 0 25\n0 12 21 => 0 21\n6 25 => 25\n0 => 0 16\n21 25 => 25\n4 => 0\n0 1 2 => 1 2\n14 => 14 16\n0 3 25 => 25\n4 5 => 5\n0 1 25 => 0\n0 16 => 0 16 25\n0 1 => 1\n7 => 7 22\n2 23 => 21 23\n19 => 17 19\n2 12 21 => 12\n5 => 5 24\n0 12 => 22\n1 => 1 2\n0 2 => 2\n7 16 19 => 11 19\n0 14 16 => 0 16 25\n2 3 => 2\n3 => 2\n3 => 2\n0 16 => 16\n2 => 0 25\n0 16 => 16\n14 => 14 16\n5 => 5 23\n0 16 => 0 1 16\n7 14 25 => 11 25\n4 25 => 0 7 22\n4 5 25 => 0 7 22\n0 4 14 16 => 0 16\n0 7 25 => 25\n16 25 => 25\n18 => 18 25\n0 4 5 => 0 21 25\n6 14 => 3 22\n8 25 => 0 25\n0 14 => 14\n4 19 25 => 18 25\n12 => 0 12 25\n4 => 4 7\n14 19 21 25 => 14 18 25\n0 3 25 => 0 21 25\n20 => 20 25\n0 20 => 20 25\n0 2 => 2 21\n6 7 25 => 7 25\n0 5 => 0\n0 14 16 => 0 14 16 17\n1 => 1 25\n0 5 25 => 25\n14 => 14 16\n0 16 => 16\n0 12 => 0 12 25\n0 16 25 => 0\n4 => 4 25\n0 19 => 0 19 25\n0 7 => 7\n14 16 => 14 16 19\n3 5 => 5\n12 => 12 13 25\n4 => 2\n0 16 21 25 => 0 16 25\n0 16 => 0\n5 => 0 5\n3 => 2\n5 22 => 5\n14 16 23 => 14 16 17 23\n16 23 => 14 16 17 23\n2 14 17 25 => 2 17 25\n0 12 21 => 0 21 25\n23 => 22 23\n12 21 25 => 6 21 25\n21 25 => 3 12 25\nchanged 190 unchanged 82\n\nsub/ens66d.csv\n" ], [ "name_label_dict = {\n 0: \"Nucleoplasm\", \n 1: \"Nuclear membrane\", \n 2: \"Nucleoli\", \n 3: \"Nucleoli fibrillar center\", \n 4: \"Nuclear speckles\",\n 5: \"Nuclear bodies\", \n 6: \"Endoplasmic reticulum\", \n 7: \"Golgi apparatus\", \n 8: \"Peroxisomes\", \n 9: \"Endosomes\", \n 10: \"Lysosomes\", \n 11: \"Intermediate filaments\", \n 12: \"Actin filaments\", \n 13: \"Focal adhesion sites\", \n 14: \"Microtubules\", \n 15: \"Microtubule ends\", \n 16: \"Cytokinetic bridge\", \n 17: \"Mitotic spindle\", \n 18: \"Microtubule organizing center\", \n 19: \"Centrosome\", \n 20: \"Lipid droplets\", \n 21: \"Plasma membrane\", \n 22: \"Cell junctions\", \n 23: \"Mitochondria\", \n 24: \"Aggresome\", \n 25: \"Cytosol\", \n 26: \"Cytoplasmic bodies\", \n 27: \"Rods & rings\"\n}\nLABEL_MAP = name_label_dict\nnp.set_printoptions(precision=3, suppress=True, linewidth=100)", "_____no_output_____" ], [ "# compute f1 score between two submission files\ndef f1_sub(csv0, csv1, num_classes=28):\n c0 = pd.read_csv(csv0)\n c1 = pd.read_csv(csv1)\n assert c0.shape == c1.shape\n s0 = [s if isinstance(s,str) else '' for s in c0.Predicted]\n s1 = [s if isinstance(s,str) else '' for s in c1.Predicted]\n p0 = [s.split() for s in s0]\n p1 = [s.split() for s in s1]\n y0 = np.zeros((c0.shape[0],num_classes)).astype(int)\n y1 = np.zeros((c0.shape[0],num_classes)).astype(int)\n # print(p0[:5])\n for i in range(c0.shape[0]):\n for j in p0[i]: y0[i,int(j)] = 1\n for j in p1[i]: y1[i,int(j)] = 1\n # print(y0[:5])\n \n return f1_score(y0, y1, average='macro')\n\n\n# computute confusion matrices between two submission files\ndef f1_confusion(csv0, csv1, num_classes=28):\n c0 = pd.read_csv(csv0)\n c1 = pd.read_csv(csv1)\n assert c0.shape == c1.shape\n s0 = [s if isinstance(s,str) else '' for s in c0.Predicted]\n s1 = [s if isinstance(s,str) else '' for s in c1.Predicted]\n p0 = [s.split() for s in s0]\n p1 = [s.split() for s in s1]\n y0 = np.zeros((c0.shape[0],num_classes)).astype(int)\n y1 = np.zeros((c0.shape[0],num_classes)).astype(int)\n # print(p0[:5])\n for i in range(c0.shape[0]):\n for j in p0[i]: y0[i,int(j)] = 1\n for j in p1[i]: y1[i,int(j)] = 1\n # print(y0[:5])\n \n y0avg = np.average(y0,axis=0)\n y1avg = np.average(y1,axis=0)\n cm = [confusion_matrix(y0[:,i], y1[:,i]) for i in range(y0.shape[1])]\n fm = [f1_score(y0[:,i], y1[:,i]) for i in range(y0.shape[1])]\n for i in range(y0.shape[1]):\n print(LABEL_MAP[i])\n print(cm[i],' %4.2f' % fm[i],' %6.4f' % y0avg[i],' %6.4f' % y1avg[i],\n ' %6.4f' % (y0avg[i] - y1avg[i]))\n print()\n# print('y0avg')\n# print(y0avg)\n# print('y1avg')\n# print(y1avg)\n# print('y0avg - y1avg')\n# print(y0avg-y1avg)\n print('f1 macro')\n print(np.mean(fm)) \n return f1_score(y0, y1, average='macro')\n ", "_____no_output_____" ], [ "f1_sub(fname,'sub/'+prefix+midx+'.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens43c.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens45c.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens53c.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens53d.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens55d.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens56d.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens58d.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens59d.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/ens61d.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/preresnet0d.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/resnet15c.csv')", "_____no_output_____" ], [ "f1_sub(fname,'sub/se_resnext11d.csv')", "_____no_output_____" ], [ "# f1_confusion(fname,'sub/'+prefix+midx+'.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb277b0c46f2f0def4903c6ad691d666cf9b917f
318,676
ipynb
Jupyter Notebook
Notebooks/ORF_MLP_117.ipynb
ShepherdCode/Soars2021
ab4f304eaa09e52d260152397a6c53d7a05457da
[ "MIT" ]
1
2021-08-16T14:49:04.000Z
2021-08-16T14:49:04.000Z
Notebooks/ORF_MLP_117.ipynb
ShepherdCode/Soars2021
ab4f304eaa09e52d260152397a6c53d7a05457da
[ "MIT" ]
null
null
null
Notebooks/ORF_MLP_117.ipynb
ShepherdCode/Soars2021
ab4f304eaa09e52d260152397a6c53d7a05457da
[ "MIT" ]
null
null
null
171.700431
31,258
0.774203
[ [ [ "# ORF MLP \nTrying to fix bugs. \nNEURONS=128 and K={1,2,3}. \n", "_____no_output_____" ] ], [ [ "import time\ndef show_time():\n t = time.time()\n print(time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(t)))\nshow_time()", "2021-07-25 20:40:39 UTC\n" ], [ "PC_TRAINS=8000\nNC_TRAINS=8000\nPC_TESTS=8000\nNC_TESTS=8000 \nRNA_LEN=1000 \nMAX_K = 3 \nINPUT_SHAPE=(None,84) # 4^3 + 4^2 + 4^1\nNEURONS=128\nDROP_RATE=0.01\nEPOCHS=100 # 1000 # 200\nSPLITS=5\nFOLDS=5 # make this 5 for serious testing", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import roc_auc_score\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Embedding,Dropout\nfrom keras.layers import Flatten,TimeDistributed\nfrom keras.losses import BinaryCrossentropy\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import load_model", "_____no_output_____" ], [ "import sys\nIN_COLAB = False\ntry:\n from google.colab import drive\n IN_COLAB = True\nexcept:\n pass\nif IN_COLAB:\n print(\"On Google CoLab, mount cloud-local file, get our code from GitHub.\")\n PATH='/content/drive/'\n #drive.mount(PATH,force_remount=True) # hardly ever need this\n drive.mount(PATH) # Google will require login credentials\n DATAPATH=PATH+'My Drive/data/' # must end in \"/\"\n import requests\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/RNA_describe.py')\n with open('RNA_describe.py', 'w') as f:\n f.write(r.text) \n from RNA_describe import ORF_counter\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/RNA_gen.py')\n with open('RNA_gen.py', 'w') as f:\n f.write(r.text) \n from RNA_gen import Collection_Generator, Transcript_Oracle\n r = requests.get('https://raw.githubusercontent.com/ShepherdCode/Soars2021/master/SimTools/KmerTools.py')\n with open('KmerTools.py', 'w') as f:\n f.write(r.text) \n from KmerTools import KmerTools\nelse:\n print(\"CoLab not working. On my PC, use relative paths.\")\n DATAPATH='data/' # must end in \"/\"\n sys.path.append(\"..\") # append parent dir in order to use sibling dirs\n from SimTools.RNA_describe import ORF_counter\n from SimTools.RNA_gen import Collection_Generator, Transcript_Oracle\n from SimTools.KmerTools import KmerTools\nBESTMODELPATH=DATAPATH+\"BestModel\" # saved on cloud instance and lost after logout\nLASTMODELPATH=DATAPATH+\"LastModel\" # saved on Google Drive but requires login", "On Google CoLab, mount cloud-local file, get our code from GitHub.\nDrive already mounted at /content/drive/; to attempt to forcibly remount, call drive.mount(\"/content/drive/\", force_remount=True).\n" ] ], [ [ "## Data Load\n", "_____no_output_____" ] ], [ [ "show_time()\ndef make_generators(seq_len):\n pcgen = Collection_Generator() \n pcgen.get_len_oracle().set_mean(seq_len)\n pcgen.set_seq_oracle(Transcript_Oracle())\n ncgen = Collection_Generator() \n ncgen.get_len_oracle().set_mean(seq_len)\n return pcgen,ncgen\n\npc_sim,nc_sim = make_generators(RNA_LEN)\npc_all = pc_sim.get_sequences(PC_TRAINS+PC_TESTS)\nnc_all = nc_sim.get_sequences(NC_TRAINS+NC_TESTS)\nprint(\"Generated\",len(pc_all),\"PC seqs\")\nprint(\"Generated\",len(nc_all),\"NC seqs\")", "2021-07-25 20:40:40 UTC\nGenerated 16000 PC seqs\nGenerated 16000 NC seqs\n" ], [ "# Describe the sequences\ndef describe_sequences(list_of_seq):\n oc = ORF_counter()\n num_seq = len(list_of_seq)\n rna_lens = np.zeros(num_seq)\n orf_lens = np.zeros(num_seq)\n for i in range(0,num_seq):\n rna_len = len(list_of_seq[i])\n rna_lens[i] = rna_len\n oc.set_sequence(list_of_seq[i])\n orf_len = oc.get_max_orf_len()\n orf_lens[i] = orf_len\n print (\"Average RNA length:\",rna_lens.mean())\n print (\"Average ORF length:\",orf_lens.mean())\n \nprint(\"Simulated sequences prior to adjustment:\")\nprint(\"PC seqs\")\ndescribe_sequences(pc_all)\nprint(\"NC seqs\")\ndescribe_sequences(nc_all)\nshow_time()", "Simulated sequences prior to adjustment:\nPC seqs\nAverage RNA length: 1000.0\nAverage ORF length: 675.05625\nNC seqs\nAverage RNA length: 1000.0\nAverage ORF length: 180.3455625\n2021-07-25 20:41:00 UTC\n" ] ], [ [ "## Data Prep", "_____no_output_____" ] ], [ [ "# Any portion of a shuffled list is a random selection\npc_train=pc_all[:PC_TRAINS] \nnc_train=nc_all[:NC_TRAINS]\npc_test=pc_all[PC_TRAINS:PC_TRAINS+PC_TESTS] \nnc_test=nc_all[NC_TRAINS:NC_TRAINS+PC_TESTS]\nprint(\"PC train, NC train:\",len(pc_train),len(nc_train))\nprint(\"PC test, NC test:\",len(pc_test),len(nc_test))\n# Garbage collection\npc_all=None\nnc_all=None\nprint(\"First PC train\",pc_train[0])\nprint(\"First PC test\",pc_test[0])", "PC train, NC train: 8000 8000\nPC test, NC test: 8000 8000\nFirst PC train GCCGAAGCGTCTGTTTTCGCACGCTCAGCCATGTCTAACCCTCCCCACTGCGTGGGAATTCCTTCCCCCGTATAGCCTTGCCTGCCAAGGTCTCGACGCTCACGCCGAAGCCGCCGTAGATGCCATTTCATGAAGATCCTGACCTAGACTTGACAATTTTAGATATGTACCGGTATTGCGCGTGTGCATCCCCCCACCGCCTTCTGCGTAGGCATTACGCTATGATTCTTAACAATGGGGTAACAAGAGAAGTTTGCAAAGACACAATGTGCGATCCTCCACCTAAATGTATCCTGGCAGCACCATCACCGCGCATGGTAGTCTTGTCGGGTACGTTTCGGCTTGGCACGATTGTAATCGTGCGCTCCATCCACCTCCCCTCTACAGTTAGATCTGCCGTGAAAGAAGTCAATTTCCAATACCGGTATCGAATAGACATCGGCGATTGCAACAAAAACACTCGAAGCTATGCCAGTGCAAGGACCGTGACTAAGCCAAGCATCGTTCGGTGGTCAGGAAGACATGCCCAAGTCCCCAGCTTTAATGGTACTTCGCCCGGGAATTTCGATACCACCTGGGCTCTCTCGCCTAGATCCAGACCTCCAGCGGCGAATCTTCACAACGACTTGTGTATGCTGGTGTGCGACCGGTTTAATAAAATCTCGAGCCAGTTTGTGATCCCTAGGTCGGTGTCGACGCGGATGAATTATGAGGCAGTGGTTCAACGGGCACTGACACAAGCAGTTAGTAGGTCCACCACGCCGGTTATTACTGGAAGGTGGAGGGTCAAACTGTGTCAAGTTTACATGCCAACCACCCTGAAGTATCTTCATGTTAATTCAACGCGGTATTTCAAAGCTCCCGACTCAGACCCAGGGTGAAAGATTCCAGGTGTAACGAGTCACTGACGAAGAATCTCAGGCCGGGTATTCCGTCCTTAGGGCAGCTACCTGTCCTAACACAAATCCTTTGGAGACTTTAATGCCTGATGGGAAGCGTA\nFirst PC test GGGTCCTGGTTTTTCAGACAAGGTTACAACTACCCTTCGCAATCGAAGCCGTATTAGGCGTAGTTCATTTTGACGCCGAGGCTACTTATGCGCAGCGGCAATCTAGCGAATATGTTTCCGCATCCTACGGTCTGGCTAAACGAAAGATGCGGTCTTTACGCGAATGAGCAGAATTAGACAGTGCGTGTGATTACTGGCGGACTGTAAGTATCTGATTGAATGCCCTAGATGGACTGTTTCGATGGTGTCTTTAGTTTGCTTGATCACCATCCATCGGGTCTAGGCCTCTGGGTGGTAAAGGTGAGGGTCCCCAAAGCTTTGAATACCTGGTACGGTTATAGCGTTTGCCTTGCCTCAACGGATGGTAGGCTCAGCGAAGAGACTATGGCACCGCGAACAAAAACAATGCCTCAAATGCTGGCCCTTGCGCATATACAGGCTGTGGAGGGACAGAGACAAGAAGCACGCCACAGGTGTCCCGGCGCCGAGGGGCCTTTTAGACGAACGATAGGTGTCTCCGATACCCGAAAACTAGGCTGGTTCTTGACGGACTGCGTCTTCGTTAAAGAAACGCTACCGGAGTCGGTCTATAGAGAGTGTAGTACTTCCCCCGAGGAGATTTCGTCTAACATTCATATAGTGAGTCATCCGGGACCCGAAACCACCCCGACACCCGAGACGAGAAGGCACGCGCTGATCTTACTTTGCGATACTCAGCACACCGGCGACGCGGAACCTTGCTTGGGGTGCTATTGTGCGCAATGGCACTAGTCTCTCAGTCGCGTCGCTTAAACCAGAAATGCTCCCCGGCGGGCAGTCGGGTACTCACACACCGTACAGTGATCTAAACTGGCCCGATGCTGTTAAGTCACACTGGCCCTCTACGGATTATGAGCTGACTTCCGTAATTGCCCATTGACTAGGGCACGTCCATTCACCTCTATCACCTCTCCCCTATAAACCACGCCCGAATTCAGCTGCGGTACCTTACTGGCCTCTG\n" ], [ "def prepare_x_and_y(seqs1,seqs0):\n len1=len(seqs1)\n len0=len(seqs0)\n total=len1+len0\n L1=np.ones(len1,dtype=np.int8)\n L0=np.zeros(len0,dtype=np.int8)\n S1 = np.asarray(seqs1)\n S0 = np.asarray(seqs0)\n all_labels = np.concatenate((L1,L0))\n all_seqs = np.concatenate((S1,S0)) \n for i in range(0,len0):\n all_labels[i*2] = L0[i]\n all_seqs[i*2] = S0[i]\n all_labels[i*2+1] = L1[i]\n all_seqs[i*2+1] = S1[i]\n return all_seqs,all_labels # use this to test unshuffled\n # bug in next line?\n X,y = shuffle(all_seqs,all_labels) # sklearn.utils.shuffle \n #Doesn't fix it\n #X = shuffle(all_seqs,random_state=3) # sklearn.utils.shuffle \n #y = shuffle(all_labels,random_state=3) # sklearn.utils.shuffle \n return X,y\nXseq,y=prepare_x_and_y(pc_train,nc_train)\nprint(Xseq[:3])\nprint(y[:3])\n# Tests:\nshow_time()", "['TGTCCAGTATATGCGCCGAGGGGTCGCGTGCCGTCCAAATCACCTGATGCATAAAGAACGCGTTAGGAAAAATTCGGTTGGGCAGTGCGATACACTTTTAAGTCTAGGTGCACGACTCCGATTCGATGGTTGCCAACGAGGGCTACTTATGAACTATTTTGGGCTGCCCGCTAGATCTGCAAGCGTACCTTAGAATATACGCCACCAACGATCAAGCGTGTCTCCCGGGTCTGTCTGTTCATCCCCGAAGTAAGTATGCGACCGGACTTTGTCTTTGCATAAAAGGGGTGCGCAGACCCCCACGCAAAAGGGCCTGGTGGAAAAAAGGCTTCGGATTGTAAACTAAATGACGGCTGCTTTTGATAGCAGATTGAACCTGTTGGGTCCAAAATCTCCAGAGTTGGCGCGGACGGTGCGTTGTAATGTTGTTACAACCTAGTTTCACTTATACATCGGACTTAGAGAGAAATCACGTGAATTTTGCGTGAACCATGGCGTAGCTGTATTCCACGAGTGAGGTTCTGGGACTTCACGTTCGACCATCAATCTGTCGCATTCTACCGATAGGTCTCGGCTATTGTAACGTAGCATTATTATCTTAGTCACGGAACCTTTATGAGGCGCCAAAAGAGCTACATCGCCGTGAGGTCGCGTTTTCCTCCGTCTGTACTATAGTATCCTCACTTGCAGATCCACGGGAAATCTAGTGAAGACGTACGTCCCTTAACCGTGATATCGTTGATGAGAATTCCTGGGTATCACGTCTGCCCAGAGGTCTCATGTGTGCGTGCACAGAGTCGTGACCCGTTAGTATAATTTCTTCATGTATAGAGAGGTTTCTTTTGCTGCACTAGATCAGAGGATCGTAGGATTTTTGCAGCTGCTGCATCAATAAGTGCAATTGGCGGAAGCTTAACCGATCGTTAGGCAAGACTCCACTGGAACTTGCCGGGTCGACAGATACGCTGGAAATGCTCCTGGGTAAGCGTGCACACAAAAC'\n 'GCCGAAGCGTCTGTTTTCGCACGCTCAGCCATGTCTAACCCTCCCCACTGCGTGGGAATTCCTTCCCCCGTATAGCCTTGCCTGCCAAGGTCTCGACGCTCACGCCGAAGCCGCCGTAGATGCCATTTCATGAAGATCCTGACCTAGACTTGACAATTTTAGATATGTACCGGTATTGCGCGTGTGCATCCCCCCACCGCCTTCTGCGTAGGCATTACGCTATGATTCTTAACAATGGGGTAACAAGAGAAGTTTGCAAAGACACAATGTGCGATCCTCCACCTAAATGTATCCTGGCAGCACCATCACCGCGCATGGTAGTCTTGTCGGGTACGTTTCGGCTTGGCACGATTGTAATCGTGCGCTCCATCCACCTCCCCTCTACAGTTAGATCTGCCGTGAAAGAAGTCAATTTCCAATACCGGTATCGAATAGACATCGGCGATTGCAACAAAAACACTCGAAGCTATGCCAGTGCAAGGACCGTGACTAAGCCAAGCATCGTTCGGTGGTCAGGAAGACATGCCCAAGTCCCCAGCTTTAATGGTACTTCGCCCGGGAATTTCGATACCACCTGGGCTCTCTCGCCTAGATCCAGACCTCCAGCGGCGAATCTTCACAACGACTTGTGTATGCTGGTGTGCGACCGGTTTAATAAAATCTCGAGCCAGTTTGTGATCCCTAGGTCGGTGTCGACGCGGATGAATTATGAGGCAGTGGTTCAACGGGCACTGACACAAGCAGTTAGTAGGTCCACCACGCCGGTTATTACTGGAAGGTGGAGGGTCAAACTGTGTCAAGTTTACATGCCAACCACCCTGAAGTATCTTCATGTTAATTCAACGCGGTATTTCAAAGCTCCCGACTCAGACCCAGGGTGAAAGATTCCAGGTGTAACGAGTCACTGACGAAGAATCTCAGGCCGGGTATTCCGTCCTTAGGGCAGCTACCTGTCCTAACACAAATCCTTTGGAGACTTTAATGCCTGATGGGAAGCGTA'\n 'AGTGTATATGTCTCCTTGTGTAACCAACCTCGAAATTTCAGAGTGCGTCGGGTGAATCTTAGGGCTTATTTCTTTTACCATATCCAAGATATTTTGGGCACGTACATGCAACGGCTGCGGTAGATTTCTCTACGACGTACAGGCCACCGCTATAAGTTGTGTCCCGAATGGACAATGCGGGTTTGTAGCCAATTATGTACGGGTAACAAACGGCCGGCGACAGAACAGGTATCTGTCTAATTATAGGTTTCTGACCAGAAGGCACAGTTGTTCGGGCAACGAGCTCGTGCCGTCGTTGGGCATTGCGATTTGACAACGCCAGGTTGGGCATATGAGTATGGCTTGGAGGACAGTTGACGCTTATCTTGGGGTTAAAGTTGAACGACGAGGCCGCACGATTATCTAGTTGAGAAGACGATTGCCTCATGGTGAGTAGCCGCAGTGGAGCGCCGCGCCTCCCTTATACGTGGGAGTCATATCGATAGAAGGGCGGTTAGCTAGATTCGCTGTGAAAGTTAAATGGTTCCTGCCGCCACATCGGTTTAAGCAGTGGTCCCATCGGAAATCAGTTAGCCGGCCCGCGGTACGGACTTTTGCCTTATTTTCTGCTGTTCGTTAAGGCGATGCGGTCGCCCTATTCGAATTCGCGAGTTGACCTGGTACTAAACACGATGACCTCGATTCTATGTTAGAATCGCCCGAAACCCTACCCCCCGTGCGTTTGTGAGCACTCAGAAAAAGGACGTGCTAGCTGCCTGATGAACCTGTACTAGGCGTGTGAAATCAACCTGGATTACAAGCGCGCCTGCAGGACCGTCTCAAATGTGCTATACCCGAGGGCGCAATGCGACCGCCGGGCCTCAAGGTGCTTTGCATCAAATTCATCAAGGTCGCCATCCCTGGTTAGGCGTCGTGATCGAGTAGAATTACACTTCATGCTCAAATCGTTTTCATAGAATCTTACACAGTACTCCGTGATCCGCCAAGACATCGTTGAAAC']\n[0 1 0]\n2021-07-25 20:41:00 UTC\n" ], [ "def seqs_to_kmer_freqs(seqs,max_K):\n tool = KmerTools() # from SimTools\n collection = []\n for seq in seqs:\n counts = tool.make_dict_upto_K(max_K)\n # Last param should be True when using Harvester.\n counts = tool.update_count_one_K(counts,max_K,seq,True)\n # Given counts for K=3, Harvester fills in counts for K=1,2.\n counts = tool.harvest_counts_from_K(counts,max_K)\n fdict = tool.count_to_frequency(counts,max_K)\n freqs = list(fdict.values())\n collection.append(freqs)\n return np.asarray(collection)\nXfrq=seqs_to_kmer_freqs(Xseq,MAX_K)\nprint(Xfrq[:3])\nshow_time()", "[[0.247 0.23 0.256 0.267 0.06806807 0.05605606\n 0.06006006 0.06306306 0.05505506 0.05005005 0.06506507 0.05905906\n 0.06406406 0.06106106 0.05805806 0.07307307 0.06006006 0.06306306\n 0.07307307 0.07107107 0.0240481 0.01402806 0.01503006 0.01503006\n 0.00801603 0.01402806 0.01803607 0.01503006 0.02104208 0.00901804\n 0.01603206 0.01402806 0.01503006 0.02004008 0.01302605 0.01503006\n 0.01402806 0.01803607 0.01102204 0.01202405 0.01503006 0.01002004\n 0.01402806 0.01102204 0.01402806 0.01302605 0.01302605 0.0250501\n 0.01202405 0.00901804 0.02004008 0.01803607 0.01703407 0.01302605\n 0.01603206 0.01803607 0.01803607 0.01002004 0.01803607 0.01503006\n 0.01402806 0.01202405 0.01503006 0.01703407 0.01803607 0.01903808\n 0.01903808 0.01703407 0.01302605 0.01102204 0.01803607 0.01803607\n 0.01402806 0.01603206 0.01503006 0.01803607 0.01503006 0.02705411\n 0.01402806 0.01703407 0.01503006 0.01503006 0.02004008 0.02104208]\n [0.244 0.274 0.239 0.243 0.06606607 0.06006006\n 0.05805806 0.05905906 0.07107107 0.08308308 0.06106106 0.05905906\n 0.05705706 0.06206206 0.05405405 0.06606607 0.05005005 0.06906907\n 0.06506507 0.05905906 0.01202405 0.01202405 0.02304609 0.01903808\n 0.01603206 0.01903808 0.01302605 0.01202405 0.01703407 0.01503006\n 0.01302605 0.01302605 0.00601202 0.01803607 0.01903808 0.01603206\n 0.02204409 0.02004008 0.01603206 0.01302605 0.0240481 0.02004008\n 0.01703407 0.02204409 0.01703407 0.01603206 0.01503006 0.01302605\n 0.01102204 0.01703407 0.01603206 0.01503006 0.01903808 0.01803607\n 0.00601202 0.01402806 0.01503006 0.02104208 0.01503006 0.01102204\n 0.00901804 0.01102204 0.01202405 0.02204409 0.01903808 0.01603206\n 0.01903808 0.01202405 0.01302605 0.01002004 0.01302605 0.01302605\n 0.01603206 0.02304609 0.01603206 0.01402806 0.01402806 0.01903808\n 0.01402806 0.01803607 0.01402806 0.01803607 0.01102204 0.01603206]\n [0.237 0.239 0.264 0.26 0.06106106 0.05405405\n 0.05805806 0.06406406 0.05405405 0.05905906 0.07407407 0.05105105\n 0.06206206 0.06906907 0.06206206 0.07107107 0.05905906 0.05705706\n 0.07007007 0.07407407 0.01603206 0.01402806 0.01402806 0.01703407\n 0.01603206 0.01402806 0.01703407 0.00601202 0.01402806 0.01002004\n 0.01703407 0.01703407 0.01102204 0.01903808 0.01603206 0.01803607\n 0.01703407 0.00901804 0.01402806 0.01402806 0.01102204 0.01302605\n 0.01803607 0.01703407 0.02004008 0.02004008 0.01603206 0.01803607\n 0.01202405 0.01202405 0.01402806 0.01302605 0.01903808 0.01603206\n 0.01302605 0.01402806 0.01302605 0.02304609 0.01903808 0.01402806\n 0.01002004 0.01903808 0.01402806 0.01903808 0.01603206 0.01102204\n 0.02004008 0.0240481 0.00901804 0.01503006 0.01603206 0.01903808\n 0.01402806 0.00901804 0.02004008 0.01402806 0.01803607 0.02004008\n 0.01503006 0.01703407 0.02004008 0.01503006 0.02004008 0.01903808]]\n2021-07-25 20:41:10 UTC\n" ] ], [ [ "## Neural network", "_____no_output_____" ] ], [ [ "def make_DNN():\n dt=np.float32\n print(\"make_DNN\")\n print(\"input shape:\",INPUT_SHAPE)\n dnn = Sequential()\n dnn.add(Dense(NEURONS,activation=\"sigmoid\",dtype=dt)) # relu doesn't work as well\n dnn.add(Dropout(DROP_RATE))\n dnn.add(Dense(NEURONS,activation=\"sigmoid\",dtype=dt)) \n dnn.add(Dropout(DROP_RATE))\n dnn.add(Dense(1,activation=\"sigmoid\",dtype=dt)) \n dnn.compile(optimizer='adam', # adadelta doesn't work as well\n loss=BinaryCrossentropy(from_logits=False),\n metrics=['accuracy']) # add to default metrics=loss\n dnn.build(input_shape=INPUT_SHAPE) \n return dnn\nmodel = make_DNN()\nprint(model.summary())", "make_DNN\ninput shape: (None, 84)\nModel: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_6 (Dense) (None, 128) 10880 \n_________________________________________________________________\ndropout_4 (Dropout) (None, 128) 0 \n_________________________________________________________________\ndense_7 (Dense) (None, 128) 16512 \n_________________________________________________________________\ndropout_5 (Dropout) (None, 128) 0 \n_________________________________________________________________\ndense_8 (Dense) (None, 1) 129 \n=================================================================\nTotal params: 27,521\nTrainable params: 27,521\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ], [ "def do_cross_validation(X,y):\n cv_scores = []\n fold=0\n #mycallbacks = [ModelCheckpoint(\n # filepath=MODELPATH, save_best_only=True, \n # monitor='val_accuracy', mode='max')] \n # When shuffle=True, the valid indices are a random subset.\n splitter = KFold(n_splits=SPLITS,shuffle=True) \n model = None\n for train_index,valid_index in splitter.split(X):\n if fold < FOLDS:\n fold += 1\n X_train=X[train_index] # inputs for training\n y_train=y[train_index] # labels for training\n X_valid=X[valid_index] # inputs for validation\n y_valid=y[valid_index] # labels for validation\n print(\"MODEL\")\n # Call constructor on each CV. Else, continually improves the same model.\n model = model = make_DNN()\n print(\"FIT\") # model.fit() implements learning\n start_time=time.time()\n history=model.fit(X_train, y_train, \n epochs=EPOCHS, \n verbose=1, # ascii art while learning\n # callbacks=mycallbacks, # called at end of each epoch\n validation_data=(X_valid,y_valid))\n end_time=time.time()\n elapsed_time=(end_time-start_time) \n print(\"Fold %d, %d epochs, %d sec\"%(fold,EPOCHS,elapsed_time))\n # print(history.history.keys()) # all these keys will be shown in figure\n pd.DataFrame(history.history).plot(figsize=(8,5))\n plt.grid(True)\n plt.gca().set_ylim(0,1) # any losses > 1 will be off the scale\n plt.show()\n return model # parameters at end of training", "_____no_output_____" ], [ "show_time()\nlast_model = do_cross_validation(Xfrq,y)", "2021-07-25 20:41:10 UTC\nMODEL\nmake_DNN\ninput shape: (None, 84)\nFIT\nEpoch 1/100\n400/400 [==============================] - 2s 4ms/step - loss: 0.7090 - accuracy: 0.5057 - val_loss: 0.6931 - val_accuracy: 0.4953\nEpoch 2/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6962 - accuracy: 0.5065 - val_loss: 0.6985 - val_accuracy: 0.5047\nEpoch 3/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6944 - accuracy: 0.5142 - val_loss: 0.7140 - val_accuracy: 0.4953\nEpoch 4/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6942 - accuracy: 0.5208 - val_loss: 0.6871 - val_accuracy: 0.5738\nEpoch 5/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6905 - accuracy: 0.5278 - val_loss: 0.6842 - val_accuracy: 0.4991\nEpoch 6/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6831 - accuracy: 0.5569 - val_loss: 0.6789 - val_accuracy: 0.5097\nEpoch 7/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6725 - accuracy: 0.5972 - val_loss: 0.6594 - val_accuracy: 0.6191\nEpoch 8/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6548 - accuracy: 0.6315 - val_loss: 0.6332 - val_accuracy: 0.6597\nEpoch 9/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6374 - accuracy: 0.6467 - val_loss: 0.6083 - val_accuracy: 0.6909\nEpoch 10/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6177 - accuracy: 0.6625 - val_loss: 0.5976 - val_accuracy: 0.6847\nEpoch 11/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6092 - accuracy: 0.6627 - val_loss: 0.5830 - val_accuracy: 0.6984\nEpoch 12/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.6056 - accuracy: 0.6692 - val_loss: 0.5859 - val_accuracy: 0.6812\nEpoch 13/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5977 - accuracy: 0.6799 - val_loss: 0.5871 - val_accuracy: 0.6797\nEpoch 14/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5881 - accuracy: 0.6803 - val_loss: 0.5759 - val_accuracy: 0.6947\nEpoch 15/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5788 - accuracy: 0.7004 - val_loss: 0.5642 - val_accuracy: 0.7047\nEpoch 16/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5785 - accuracy: 0.6947 - val_loss: 0.5779 - val_accuracy: 0.6872\nEpoch 17/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5874 - accuracy: 0.6841 - val_loss: 0.5681 - val_accuracy: 0.6994\nEpoch 18/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5837 - accuracy: 0.6896 - val_loss: 0.5578 - val_accuracy: 0.7103\nEpoch 19/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5715 - accuracy: 0.7017 - val_loss: 0.5600 - val_accuracy: 0.7084\nEpoch 20/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5714 - accuracy: 0.6999 - val_loss: 0.5648 - val_accuracy: 0.7022\nEpoch 21/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5741 - accuracy: 0.6985 - val_loss: 0.5534 - val_accuracy: 0.7141\nEpoch 22/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5743 - accuracy: 0.6900 - val_loss: 0.5578 - val_accuracy: 0.7094\nEpoch 23/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5685 - accuracy: 0.6995 - val_loss: 0.5580 - val_accuracy: 0.7072\nEpoch 24/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5663 - accuracy: 0.7050 - val_loss: 0.5563 - val_accuracy: 0.7094\nEpoch 25/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5610 - accuracy: 0.7075 - val_loss: 0.5467 - val_accuracy: 0.7178\nEpoch 26/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5640 - accuracy: 0.7046 - val_loss: 0.5664 - val_accuracy: 0.6997\nEpoch 27/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5699 - accuracy: 0.6962 - val_loss: 0.5446 - val_accuracy: 0.7175\nEpoch 28/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5617 - accuracy: 0.7093 - val_loss: 0.5437 - val_accuracy: 0.7209\nEpoch 29/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5518 - accuracy: 0.7202 - val_loss: 0.5551 - val_accuracy: 0.7088\nEpoch 30/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5628 - accuracy: 0.7013 - val_loss: 0.5427 - val_accuracy: 0.7228\nEpoch 31/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5573 - accuracy: 0.7130 - val_loss: 0.5446 - val_accuracy: 0.7188\nEpoch 32/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5597 - accuracy: 0.7096 - val_loss: 0.5658 - val_accuracy: 0.7034\nEpoch 33/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5573 - accuracy: 0.7122 - val_loss: 0.5482 - val_accuracy: 0.7159\nEpoch 34/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5541 - accuracy: 0.7097 - val_loss: 0.5428 - val_accuracy: 0.7191\nEpoch 35/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5521 - accuracy: 0.7162 - val_loss: 0.5391 - val_accuracy: 0.7262\nEpoch 36/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5544 - accuracy: 0.7132 - val_loss: 0.5498 - val_accuracy: 0.7153\nEpoch 37/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5552 - accuracy: 0.7144 - val_loss: 0.5392 - val_accuracy: 0.7262\nEpoch 38/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5486 - accuracy: 0.7141 - val_loss: 0.5377 - val_accuracy: 0.7294\nEpoch 39/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5510 - accuracy: 0.7138 - val_loss: 0.5713 - val_accuracy: 0.6997\nEpoch 40/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5511 - accuracy: 0.7139 - val_loss: 0.5414 - val_accuracy: 0.7188\nEpoch 41/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5515 - accuracy: 0.7139 - val_loss: 0.5411 - val_accuracy: 0.7194\nEpoch 42/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5518 - accuracy: 0.7085 - val_loss: 0.5687 - val_accuracy: 0.6975\nEpoch 43/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5633 - accuracy: 0.7030 - val_loss: 0.5411 - val_accuracy: 0.7197\nEpoch 44/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5500 - accuracy: 0.7157 - val_loss: 0.5382 - val_accuracy: 0.7244\nEpoch 45/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5461 - accuracy: 0.7214 - val_loss: 0.5366 - val_accuracy: 0.7291\nEpoch 46/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5440 - accuracy: 0.7185 - val_loss: 0.5374 - val_accuracy: 0.7241\nEpoch 47/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5461 - accuracy: 0.7199 - val_loss: 0.5351 - val_accuracy: 0.7341\nEpoch 48/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5470 - accuracy: 0.7168 - val_loss: 0.5461 - val_accuracy: 0.7191\nEpoch 49/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5496 - accuracy: 0.7147 - val_loss: 0.5454 - val_accuracy: 0.7184\nEpoch 50/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5473 - accuracy: 0.7123 - val_loss: 0.5577 - val_accuracy: 0.7059\nEpoch 51/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5483 - accuracy: 0.7170 - val_loss: 0.5350 - val_accuracy: 0.7303\nEpoch 52/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5421 - accuracy: 0.7201 - val_loss: 0.5404 - val_accuracy: 0.7231\nEpoch 53/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5504 - accuracy: 0.7165 - val_loss: 0.5345 - val_accuracy: 0.7316\nEpoch 54/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5448 - accuracy: 0.7240 - val_loss: 0.5406 - val_accuracy: 0.7225\nEpoch 55/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5424 - accuracy: 0.7258 - val_loss: 0.5386 - val_accuracy: 0.7197\nEpoch 56/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5380 - accuracy: 0.7269 - val_loss: 0.5538 - val_accuracy: 0.7084\nEpoch 57/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5461 - accuracy: 0.7165 - val_loss: 0.5351 - val_accuracy: 0.7309\nEpoch 58/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5421 - accuracy: 0.7266 - val_loss: 0.5481 - val_accuracy: 0.7138\nEpoch 59/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5362 - accuracy: 0.7255 - val_loss: 0.5376 - val_accuracy: 0.7228\nEpoch 60/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5436 - accuracy: 0.7217 - val_loss: 0.5464 - val_accuracy: 0.7122\nEpoch 61/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5402 - accuracy: 0.7268 - val_loss: 0.5374 - val_accuracy: 0.7219\nEpoch 62/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5422 - accuracy: 0.7246 - val_loss: 0.5346 - val_accuracy: 0.7319\nEpoch 63/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5422 - accuracy: 0.7183 - val_loss: 0.5350 - val_accuracy: 0.7312\nEpoch 64/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5467 - accuracy: 0.7203 - val_loss: 0.5325 - val_accuracy: 0.7331\nEpoch 65/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5479 - accuracy: 0.7197 - val_loss: 0.5616 - val_accuracy: 0.7053\nEpoch 66/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5481 - accuracy: 0.7246 - val_loss: 0.5456 - val_accuracy: 0.7131\nEpoch 67/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5462 - accuracy: 0.7223 - val_loss: 0.5341 - val_accuracy: 0.7337\nEpoch 68/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5438 - accuracy: 0.7231 - val_loss: 0.5494 - val_accuracy: 0.7122\nEpoch 69/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5353 - accuracy: 0.7283 - val_loss: 0.5336 - val_accuracy: 0.7328\nEpoch 70/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5425 - accuracy: 0.7248 - val_loss: 0.5519 - val_accuracy: 0.7113\nEpoch 71/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5409 - accuracy: 0.7229 - val_loss: 0.5399 - val_accuracy: 0.7175\nEpoch 72/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5540 - accuracy: 0.7089 - val_loss: 0.5327 - val_accuracy: 0.7337\nEpoch 73/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5416 - accuracy: 0.7285 - val_loss: 0.5401 - val_accuracy: 0.7244\nEpoch 74/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5404 - accuracy: 0.7269 - val_loss: 0.5449 - val_accuracy: 0.7172\nEpoch 75/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5424 - accuracy: 0.7290 - val_loss: 0.5322 - val_accuracy: 0.7331\nEpoch 76/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5467 - accuracy: 0.7201 - val_loss: 0.5335 - val_accuracy: 0.7341\nEpoch 77/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5358 - accuracy: 0.7293 - val_loss: 0.5328 - val_accuracy: 0.7344\nEpoch 78/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5425 - accuracy: 0.7231 - val_loss: 0.5327 - val_accuracy: 0.7350\nEpoch 79/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5355 - accuracy: 0.7279 - val_loss: 0.5410 - val_accuracy: 0.7159\nEpoch 80/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5425 - accuracy: 0.7228 - val_loss: 0.5387 - val_accuracy: 0.7188\nEpoch 81/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5400 - accuracy: 0.7266 - val_loss: 0.5334 - val_accuracy: 0.7353\nEpoch 82/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5429 - accuracy: 0.7237 - val_loss: 0.5325 - val_accuracy: 0.7334\nEpoch 83/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5438 - accuracy: 0.7192 - val_loss: 0.5330 - val_accuracy: 0.7350\nEpoch 84/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5422 - accuracy: 0.7267 - val_loss: 0.5423 - val_accuracy: 0.7163\nEpoch 85/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5379 - accuracy: 0.7265 - val_loss: 0.5329 - val_accuracy: 0.7344\nEpoch 86/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5460 - accuracy: 0.7214 - val_loss: 0.5381 - val_accuracy: 0.7269\nEpoch 87/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5382 - accuracy: 0.7266 - val_loss: 0.5379 - val_accuracy: 0.7269\nEpoch 88/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5344 - accuracy: 0.7370 - val_loss: 0.5337 - val_accuracy: 0.7359\nEpoch 89/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5432 - accuracy: 0.7232 - val_loss: 0.5334 - val_accuracy: 0.7356\nEpoch 90/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5351 - accuracy: 0.7290 - val_loss: 0.5335 - val_accuracy: 0.7328\nEpoch 91/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5400 - accuracy: 0.7250 - val_loss: 0.5435 - val_accuracy: 0.7150\nEpoch 92/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5382 - accuracy: 0.7255 - val_loss: 0.5323 - val_accuracy: 0.7328\nEpoch 93/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5344 - accuracy: 0.7237 - val_loss: 0.5339 - val_accuracy: 0.7319\nEpoch 94/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5305 - accuracy: 0.7371 - val_loss: 0.5334 - val_accuracy: 0.7322\nEpoch 95/100\n400/400 [==============================] - 1s 4ms/step - loss: 0.5419 - accuracy: 0.7281 - val_loss: 0.5327 - val_accuracy: 0.7319\nEpoch 96/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5403 - accuracy: 0.7275 - val_loss: 0.5347 - val_accuracy: 0.7294\nEpoch 97/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5359 - accuracy: 0.7288 - val_loss: 0.5342 - val_accuracy: 0.7297\nEpoch 98/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5326 - accuracy: 0.7276 - val_loss: 0.5325 - val_accuracy: 0.7319\nEpoch 99/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5361 - accuracy: 0.7324 - val_loss: 0.5380 - val_accuracy: 0.7275\nEpoch 100/100\n400/400 [==============================] - 1s 3ms/step - loss: 0.5346 - accuracy: 0.7264 - val_loss: 0.5330 - val_accuracy: 0.7337\nFold 1, 100 epochs, 142 sec\n" ], [ "def show_test_AUC(model,X,y):\n ns_probs = [0 for _ in range(len(y))]\n bm_probs = model.predict(X)\n ns_auc = roc_auc_score(y, ns_probs)\n bm_auc = roc_auc_score(y, bm_probs)\n ns_fpr, ns_tpr, _ = roc_curve(y, ns_probs)\n bm_fpr, bm_tpr, _ = roc_curve(y, bm_probs)\n plt.plot(ns_fpr, ns_tpr, linestyle='--', label='Guess, auc=%.4f'%ns_auc)\n plt.plot(bm_fpr, bm_tpr, marker='.', label='Model, auc=%.4f'%bm_auc)\n plt.title('ROC')\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.legend()\n plt.show()\n print(\"%s: %.2f%%\" %('AUC',bm_auc*100.0))\ndef show_test_accuracy(model,X,y):\n scores = model.evaluate(X, y, verbose=0)\n print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n", "_____no_output_____" ], [ "print(\"Accuracy on training data.\")\nprint(\"Prepare...\")\nshow_time()\nXseq,y=prepare_x_and_y(pc_train,nc_train)\nprint(\"Extract K-mer features...\")\nshow_time()\nXfrq=seqs_to_kmer_freqs(Xseq,MAX_K)\nprint(\"Plot...\")\nshow_time()\nshow_test_AUC(last_model,Xfrq,y)\nshow_test_accuracy(last_model,Xfrq,y)\nshow_time()", "Accuracy on training data.\nPrepare...\n2021-07-25 20:52:57 UTC\nExtract K-mer features...\n2021-07-25 20:52:58 UTC\nPlot...\n2021-07-25 20:53:07 UTC\n" ], [ "print(\"Accuracy on test data.\")\nprint(\"Prepare...\")\nshow_time()\nXseq,y=prepare_x_and_y(pc_test,nc_test)\nprint(\"Extract K-mer features...\")\nshow_time()\nXfrq=seqs_to_kmer_freqs(Xseq,MAX_K)\nprint(\"Plot...\")\nshow_time()\nshow_test_AUC(last_model,Xfrq,y)\nshow_test_accuracy(last_model,Xfrq,y)\nshow_time()", "Accuracy on test data.\nPrepare...\n2021-07-25 20:53:09 UTC\nExtract K-mer features...\n2021-07-25 20:53:09 UTC\nPlot...\n2021-07-25 20:53:19 UTC\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
cb277dafc4c37d7f9b83c04a8a47c4d4f46d4966
6,029
ipynb
Jupyter Notebook
notebooks/E_downsampling.ipynb
daxsoule/BOTPT
1ace69005d00f276406dd91be8aae927b047f61a
[ "MIT" ]
null
null
null
notebooks/E_downsampling.ipynb
daxsoule/BOTPT
1ace69005d00f276406dd91be8aae927b047f61a
[ "MIT" ]
null
null
null
notebooks/E_downsampling.ipynb
daxsoule/BOTPT
1ace69005d00f276406dd91be8aae927b047f61a
[ "MIT" ]
null
null
null
33.494444
591
0.568751
[ [ [ "import xarray as xr\nimport pandas as pd\nimport pickle as pk\nimport re\nimport requests\nimport os\nimport gc", "_____no_output_____" ], [ "# Sensor E: url = 'https://opendap.oceanobservatories.org/thredds/catalog/ooi/[email protected]/20181104T104012-RS03ECAL-MJ03E-06-BOTPTA302-streamed-botpt_nano_sample/catalog.html'\n# Sensor B url = 'https://opendap.oceanobservatories.org/thredds/catalog/ooi/[email protected]/20181020T213838-RS03ASHS-MJ03B-09-BOTPTA304-streamed-botpt_nano_sample/catalog.html'\n# Sensor F url = 'https://opendap.oceanobservatories.org/thredds/catalog/ooi/[email protected]/20181104T041943-RS03CCAL-MJ03F-05-BOTPTA301-streamed-botpt_nano_sample/catalog.html'\n# url = 'https://opendap.oceanobservatories.org/thredds/catalog/ooi/[email protected]/20190712T124024454Z-RS03ECAL-MJ03E-06-BOTPTA302-streamed-botpt_nano_sample/catalog.html'\nurl = 'https://ooinet.oceanobservatories.org/api/m2m/12576/sensor/inv/RS03ECAL/MJ03E/06-BOTPTA302/streamed/botpt_nano_sample'\n\ntds_url = 'https://opendap.oceanobservatories.org/thredds/dodsC'\ndatasets = requests.get(url).text\nurls = re.findall(r'href=[\\'\"]?([^\\'\" >]+)', datasets)\nx = re.findall(r'(ooi/.*?.nc)', datasets)\nfor i in x:\n if i.endswith('.nc') == False:\n x.remove(i)\nfor i in x:\n try:\n float(i[-4])\n except:\n x.remove(i)\ndatasets = [os.path.join(tds_url, i) for i in x]", "_____no_output_____" ], [ "# print(datasets[1])\nprint(datasets)", "[]\n" ], [ "# ds = xr.open_dataset(datasets[1])\nds = xr.open_dataset(datasets())", "_____no_output_____" ], [ "# make the output directory\nnew_dir = '/home/jovyan/data/botpt/2019FifteenSecond_mean_dataE/'\nif not os.path.isdir(new_dir):\n try:\n os.makedirs(new_dir)\n except OSError:\n if os.path.exists(new_dir):\n pass\n else:\n raise", "_____no_output_____" ], [ "# read in the data directly off THREDDS and write out as subsampled pickled pandas dataframe\n# NOTE: It takes about one hour to subsample 69499.81 Mbytes of data and write it out to a dataframe. \nnum = 0\nfor i in datasets:\n ds = xr.open_dataset(i)\n ds = ds.swap_dims({'obs': 'time'})\n\n pressure_min = pd.DataFrame()\n pressure_min['bottom_pressure'] = ds['bottom_pressure'].to_pandas().resample('.25T').mean()\n del pressure_min.index.name\n\n pressure_min = pressure_min.dropna()\n\n out = '/home/jovyan/data/botpt/2019FifteenSecond_mean_dataE/' + i.split('/')[-1][:-3] + '_resampled' + '.pd'\n num = num +1\n\n with open(out, 'wb') as fh:\n pk.dump(pressure_min,fh)\n\n gc.collect()", "_____no_output_____" ], [ "# create a single file with all the pickled data.\npressure_min = pd.DataFrame()\nfor path, subdirs, files in os.walk('/home/jovyan/data/botpt/2019FifteenSecond_mean_dataE/'):\n for name in files:\n file_name = os.path.join(path, name) \n with open(file_name, 'rb') as f:\n pd_df = pk.load(f)\n pressure_min = pressure_min.append(pd_df)\n\nwith open('/home/jovyan/data/botpt/2019bottom_pressure15s_E.pkl', 'wb') as f:\n pk.dump(pressure_min,f)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
cb277eeb7a54f125aa5c03fe5b0cda901e16b816
782
ipynb
Jupyter Notebook
Data Mining Term.ipynb
Kanbc/introduction-to-data-mining-techniques
d2e8c4f0e651b1fdf864c3593916effdd95a35e6
[ "Apache-2.0" ]
null
null
null
Data Mining Term.ipynb
Kanbc/introduction-to-data-mining-techniques
d2e8c4f0e651b1fdf864c3593916effdd95a35e6
[ "Apache-2.0" ]
null
null
null
Data Mining Term.ipynb
Kanbc/introduction-to-data-mining-techniques
d2e8c4f0e651b1fdf864c3593916effdd95a35e6
[ "Apache-2.0" ]
null
null
null
20.051282
79
0.533248
[ [ [ "- Database \n- Data warehouse = รวมข้อมูลที่จะใช้ วิเคราะห์ทำ DM จากหลายๆ database \n- Data mining\n\n- BI = รายงานผลข้อมูลที่เกิดขึ้นในอดีต (report)\n- Data mining = ทำนายสิ่งที่จะเกิดขึ้นในอนาคต (predict)\n\n", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
cb2790eb69bc53f3d7704137a0c883b868af739f
105,454
ipynb
Jupyter Notebook
machine-learning/solutions/energy_price_forecasting/.ipynb_checkpoints/Triple+Exponential+Smoothing+Forecasting-checkpoint.ipynb
kjwinters/professional-services
f208f513f4aae919e30bf613a0372a5560ebc665
[ "Apache-2.0" ]
1
2019-10-01T22:17:06.000Z
2019-10-01T22:17:06.000Z
machine-learning/solutions/energy_price_forecasting/.ipynb_checkpoints/Triple+Exponential+Smoothing+Forecasting-checkpoint.ipynb
kjwinters/professional-services
f208f513f4aae919e30bf613a0372a5560ebc665
[ "Apache-2.0" ]
null
null
null
machine-learning/solutions/energy_price_forecasting/.ipynb_checkpoints/Triple+Exponential+Smoothing+Forecasting-checkpoint.ipynb
kjwinters/professional-services
f208f513f4aae919e30bf613a0372a5560ebc665
[ "Apache-2.0" ]
2
2018-10-17T20:56:41.000Z
2018-11-02T19:59:00.000Z
298.736544
66,446
0.905504
[ [ [ "import google.datalab.bigquery as bq\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf", "_____no_output_____" ], [ "#training price data\ntraining = bq.Query('''\nSelect date_utc,price\nfrom Energy.MarketPT\nwhere date_utc between '2015-06-01 00:00:00' and '2015-06-21 23:01:00'\norder by date_utc\n''').execute(bq.QueryOutput.dataframe()).result()\n\n#validation price data\nvalidation = bq.Query('''\nSelect date_utc,price\nfrom Energy.MarketPT\nwhere date_utc between '2015-06-22 00:00:00' and '2015-06-28 23:01:00'\norder by date_utc\n''').execute(bq.QueryOutput.dataframe()).result()", "_____no_output_____" ], [ "#Triple Exponential Smoothing Model\n\n#loockback seasonal pattern (same hour last week)\nc = 24*7\n\n#target shape\nn_y =1 \n\n#number of training examples\nm = len(training)\n\ntf.reset_default_graph() \ntf.set_random_seed(1)\nparam = {\n'A' : tf.get_variable(\"A\", [1,], initializer = tf.constant_initializer(0.5))\n,'B' : tf.get_variable(\"B\", [1,], initializer = tf.constant_initializer(0.5))\n,'G' : tf.get_variable(\"G\", [1,], initializer = tf.constant_initializer(0.5))\n}\n\n#targets\nY = tf.placeholder(tf.float32,[m,n_y], name=\"Y\")\n\n#loockback seasonal pattern (same hour last week)\nC = tf.constant(name=\"C\", dtype=tf.int32, value=c)\n\n#initial values for U anbd V (0.0)\nU = tf.constant(name=\"U\", dtype=tf.float32, value=0.0,shape=[1,])\n\n#initial values for S (average y for first c days)\ny_avg = np.mean(training['price'][:c])\nS = tf.constant(name=\"S\", dtype=tf.float32, value=[y_avg for i in range(c)],shape=[c,])\n\n#auxiliary functions to compute initial U and S\ndef s0f(y,s_c):\n return y/s_c[0]\n\ndef u0f(y,s):\n return y/(s[-1])\n\n#auxiliary functions to compute U,V,S\ndef uf(y,s_c,u_1,v_1):\n return param['A']*y/(s_c[0])+(1-param['A'])*(u_1+v_1)\n\ndef vf(u,u_1,v_1):\n return param['B']*(u-u_1)+(1-param['B'])*v_1\n\ndef sf(y,u,s_c):\n return param['G']*(y/u)+(1-param['G'])*(s_c[0])\n\n#auxiliary function to predict\ndef pf(u_1,v_1,s_c):\n return (u_1+v_1)*(s_c[0])\n\n#auxiliary function for 1st period (1st week) initializaqtion\ndef s1 (ini,ele):\n ini['s'] = tf.concat([ini['s'][1:],s0f(ele,ini['s'])],axis=0)\n ini['u'] = u0f(ele,ini['s'])\n return ini\n\n#auxiliary function for all periods after the first one\ndef s2 (ini,ele):\n ini['p'] = pf(ini['u'],ini['v'],ini['s'])\n aux_u = uf(ele,ini['s'],ini['u'],ini['v'])\n ini['v'] = vf(aux_u,ini['u'],ini['v'])\n ini['s'] = tf.concat((ini['s'][1:],sf(ele,aux_u,ini['s'])),axis=0)\n ini['u'] = aux_u\n return ini\n\n#squared mean error\ndef compute_cost(y_p, y):\n return tf.reduce_mean((y-y_p)**2)\n\n \n#define model\ndef model(Y_train, learning_rate = 0.001,\n num_epochs = 700, print_cost = True): \n tf.set_random_seed(1) \n \n #keep track of costs\n costs = []\n \n #run loop (tf.scan) and send initial state for first period (first week)\n ini_states = tf.scan(s1, elems=Y[0:C], initializer={'u':U\n ,'s':S})\n #make sure parameters A,B,G stay between 0 and 1 })\n for k in param.keys():\n param[k] = tf.minimum(tf.maximum(param[k],0.0),1.0)\n \n #run loop (tf.scan) and send initial state for all periods after the first one \n states = tf.scan(s2, elems=Y[C:], initializer={'u':ini_states['u'][-1]\n ,'v':U\n ,'p':U\n ,'s':ini_states['s'][-1]\n })\n \n #keep track of latest state for future predictions \n last_state = {x:states[x][-1] for x in states.keys()}\n \n #only compute cost on all periods after the first one (initialization for first period is too noisy)\n cost = compute_cost(states['p'], Y[C:])\n #optimizer \n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n init = tf.global_variables_initializer()\n \n #loop for number of epochs for training\n with tf.Session() as sess:\n sess.run(init)\n for epoch in range(num_epochs):\n epoch_cost = 0. \n _ , batch_cost, l_s = sess.run([optimizer, cost,last_state], feed_dict={Y: Y_train})#, C:c})\n epoch_cost = batch_cost\n if print_cost == True and epoch % 100 == 0:\n print (\"Cost after epoch %i: %f\" % (epoch, epoch_cost))\n if print_cost == True and epoch % 5 == 0:\n costs.append(epoch_cost)\n \n #plot learning\n plt.plot(np.squeeze(costs))\n plt.ylabel('cost')\n plt.xlabel('iterations (per tens)')\n plt.title(\"Learning rate =\" + str(learning_rate))\n plt.show()\n \n #return trained parameters (A,B,G) and last state to be used for followup predictions\n return sess.run([param]),l_s", "_____no_output_____" ], [ "#train model\npar, l_s = model(np.array([[x/100.0] for x in training['price']],dtype=np.float32))\npar = par[0]", "Cost after epoch 0: 0.000978\nCost after epoch 100: 0.000872\nCost after epoch 200: 0.000807\nCost after epoch 300: 0.000756\nCost after epoch 400: 0.000686\nCost after epoch 500: 0.000654\nCost after epoch 600: 0.000652\n" ], [ "#prediction function (using trained parameters and last state)\nparam = {\n'A' : tf.convert_to_tensor(par[\"A\"])\n,'B' : tf.convert_to_tensor(par[\"B\"])\n,'G' : tf.convert_to_tensor(par[\"G\"])\n}\ndef predict(ls):\n X = np.reshape(np.array([ls['p']],dtype=np.float32),[1,1])\n x = tf.placeholder(\"float\", [X.shape[0], X.shape[1]],name='px')\n S = np.reshape(np.array([ls['s']],dtype=np.float32),[168,1])\n s = tf.placeholder(\"float\", [S.shape[0],S.shape[1]],name='ps')\n ls['s'] = s\n U = np.reshape(np.array([ls['u']],dtype=np.float32),[1,1])\n u = tf.placeholder(\"float\", [U.shape[0],U.shape[1]],name='pu')\n ls['u'] = u\n V = np.reshape(np.array([ls['v']],dtype=np.float32),[1,1])\n v = tf.placeholder(\"float\", [V.shape[0],V.shape[1]],name='pv')\n ls['v'] = v\n t1 = s2 (ls,x)\n sess = tf.Session()\n return sess.run(t1, feed_dict = {x: X, s: S, u: U, v: V})", "_____no_output_____" ], [ "#learned alfa, beta, and gamma\npar", "_____no_output_____" ], [ "#predict using learned parameters and last state (starting with the one out of training) \npred = []\nay = l_s.copy()\nay['p'] = (ay['u']+ay['v'])*ay['s'][0]\npred.append(ay['p'][0]*100.0)\nfor i in range(24*7-1):\n ay= predict(ay)\n pred.append(ay['p'][0][0]*100.0)", "_____no_output_____" ], [ "#assess metric/plot aux function\ndef assessmodel(m):\n plt.plot(list(validation['price']))\n plt.plot(m)\n print('RSME: '+str(np.math.sqrt(mean_squared_error(validation['price'], m))))\n print('AE: '+str(mean_absolute_error(validation['price'], m)))", "_____no_output_____" ], [ "#assess predictions\nassessmodel(pred)", "RSME: 4.40385603572\nAE: 3.6104393151828216\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb27949bfb0db159ed2daf7eec3a8af72011574e
4,448
ipynb
Jupyter Notebook
Indexing Arrays.ipynb
roden026/github-move
162f1888b29bc2cdc451ac728bff62fceabf7b5a
[ "Apache-2.0" ]
null
null
null
Indexing Arrays.ipynb
roden026/github-move
162f1888b29bc2cdc451ac728bff62fceabf7b5a
[ "Apache-2.0" ]
18
2018-06-07T00:34:35.000Z
2018-06-07T01:30:42.000Z
Indexing Arrays.ipynb
roden026/github-move
162f1888b29bc2cdc451ac728bff62fceabf7b5a
[ "Apache-2.0" ]
null
null
null
16.597015
71
0.448966
[ [ [ "import numpy as np", "_____no_output_____" ], [ "arr = np.arange(0,11)", "_____no_output_____" ], [ "arr[1:5]", "_____no_output_____" ], [ "arr[0:5] = 100", "_____no_output_____" ], [ "arr", "_____no_output_____" ], [ "slice_of_arr = arr[0:6]", "_____no_output_____" ], [ "slice_of_arr", "_____no_output_____" ], [ "slice_of_arr[:] = 99", "_____no_output_____" ], [ "slice_of_arr", "_____no_output_____" ], [ "# Changes also occur in original array!!\narr", "_____no_output_____" ], [ "arr_copy = arr.copy()\n\n# USE THIS TO ACTUALLY CREATE A COPY", "_____no_output_____" ], [ "arr_copy[:] = 88\narr_copy", "_____no_output_____" ], [ "arr", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb2795a5053cd46cc1d1057aa959ae244210f6a1
341,697
ipynb
Jupyter Notebook
notebooks/ws353-agreement.ipynb
mbatchkarov/ExpLosion
705039ec5f77c4203c98487f80d74b9d1f4fd501
[ "BSD-3-Clause" ]
1
2015-10-21T08:53:55.000Z
2015-10-21T08:53:55.000Z
notebooks/ws353-agreement.ipynb
mbatchkarov/ExpLosion
705039ec5f77c4203c98487f80d74b9d1f4fd501
[ "BSD-3-Clause" ]
null
null
null
notebooks/ws353-agreement.ipynb
mbatchkarov/ExpLosion
705039ec5f77c4203c98487f80d74b9d1f4fd501
[ "BSD-3-Clause" ]
null
null
null
306.454709
169,340
0.901963
[ [ [ "# Inter-annotator agreement between the first 10 annotators of WS-353\nMeasured in Kappa and Rho:\n - against the gold standard which is the mean of all annotators, as described in Hill et al 2014 (footnote 6)\n - against each other\n \n Using Kohen's kappa, which is binary, so I average across pairs of annotators.", "_____no_output_____" ] ], [ [ "%cd ~/NetBeansProjects/ExpLosion/\nfrom notebooks.common_imports import *\nfrom skll.metrics import kappa\nfrom scipy.stats import spearmanr\nfrom itertools import combinations\n\nsns.timeseries.algo.bootstrap = my_bootstrap\nsns.categorical.bootstrap = my_bootstrap", "/Volumes/LocalDataHD/m/mm/mmb28/NetBeansProjects/ExpLosion\n" ], [ "columns = 'Word 1,Word 2,Human (mean),1,2,3,4,5,6,7,8,9,10,11,12,13'.split(',')\ndf1 = pd.read_csv('../thesisgenerator/similarity-data/wordsim353/set1.csv')[columns]\ndf2 = pd.read_csv('../thesisgenerator/similarity-data/wordsim353/set2.csv')[columns]\ndf = pd.concat([df1, df2], ignore_index=True)\ndf_gold = pd.read_csv('../thesisgenerator/similarity-data/wordsim353/combined.csv',\n names='w1 w2 sim'.split())", "_____no_output_____" ], [ "# had to remove trailing space from their files to make it parse with pandas\nmarco = pd.read_csv('../thesisgenerator/similarity-data/MEN/agreement/marcos-men-ratings.txt',\n sep='\\t', index_col=[0,1], names=['w1', 'w2', 'sim']).sort_index().convert_objects(convert_numeric=True)\nelia = pd.read_csv('../thesisgenerator/similarity-data/MEN/agreement/elias-men-ratings.txt',\n sep='\\t', index_col=[0,1], names=['w1', 'w2', 'sim']).sort_index().convert_objects(convert_numeric=True)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "# Each index ``i`` returned is such that ``bins[i-1] <= x < bins[i]``\ndef bin(arr, nbins=2, debug=False):\n bins = np.linspace(arr.min(), arr.max(), nbins+1)\n if debug:\n print('bins are', bins)\n return np.digitize(arr, bins[1:-1])", "_____no_output_____" ], [ "bin(df['1'], nbins=5, debug=True)[:10]", "bins are [ 1. 2.8 4.6 6.4 8.2 10. ]\n" ], [ "bin(np.array([0, 2.1, 5.8, 7.9, 10]), debug=True) # 0 and 10 are needed to define the range of values", "bins are [ 0. 5. 10.]\n" ], [ "bin(np.array([0, 2.1, 5.8, 7.9, 10]), nbins=3, debug=True)", "bins are [ 0. 3.33333333 6.66666667 10. ]\n" ], [ "df.describe()", "_____no_output_____" ], [ "elia.describe()", "_____no_output_____" ] ], [ [ "# WS353: Kappa against each other/ against mean ", "_____no_output_____" ] ], [ [ "bin_counts = range(2, 6)\n# pair, bin count, kappa\nkappas_pair = []\nfor name1, name2 in combinations(range(1,14), 2):\n for b in bin_counts:\n kappas_pair.append(['%d-%d'%(name1, name2), \n b, \n kappa(bin(df[str(name1)], b), bin(df[str(name2)], b))])\n\nkappas_mean = []\nfor name in range(1, 14):\n for b in bin_counts:\n kappas_mean.append(['%d-m'%name, \n b, \n kappa(bin(df[str(name)], b), bin(df_gold.sim, b))])\n\nkappas_men = [] # MEN data set- marco vs elia\nfor b in bin_counts:\n kappas_men.append(['marco-elia',\n b,\n kappa(bin(marco.sim.values, b), bin(elia.sim.values, b))])", "_____no_output_____" ], [ "kappas1 = pd.DataFrame(kappas_pair, columns=['pair', 'bins', 'kappa'])\nkappas1['kind'] = 'WS353-pairwise'\nkappas2 = pd.DataFrame(kappas_mean, columns=['pair', 'bins', 'kappa'])\nkappas2['kind'] = 'WS353-to mean'\nkappas3 = pd.DataFrame(kappas_men, columns=['pair', 'bins', 'kappa'])\nkappas3['kind'] = 'MEN'\nkappas = pd.concat([kappas1, kappas2, kappas3], ignore_index=True)\nkappas.head(3)", "_____no_output_____" ], [ "with sns.color_palette(\"cubehelix\", 3):\n ax = sns.tsplot(kappas, time='bins', unit='pair', condition='kind', value='kappa', \n marker='s', linewidth=4);\nax.set_xticklabels(np.arange(kappas.bins.min(), kappas.bins.max() + 0.01, 0.5).astype(np.int))\nsparsify_axis_labels(ax)\nplt.savefig('plot-intrinsic-ws353-kappas.pdf', format='pdf', dpi=300, bbox_inches='tight', pad_inches=0.1)", "_____no_output_____" ], [ "# sns.tsplot(kappas, time='bins', unit='pair', condition='kind', value='kappa', \nsns.factorplot(data=kappas, x='bins', y='kappa', hue='kind', kind='box')", "_____no_output_____" ], [ "kappas.groupby(['bins', 'kind']).mean()", "_____no_output_____" ], [ "rhos_pair = []\nfor name1, name2 in combinations(range(1,14), 2):\n rhos_pair.append(spearmanr(bin(df[str(name1)], b), bin(df[str(name2)], b))[0])\n \nrhos_mean = []\nfor name in range(1,14):\n rhos_mean.append(spearmanr(bin(df[str(name)], b), bin(df_gold.sim, b))[0])", "_____no_output_____" ], [ "sns.distplot(rhos_pair, label='pairwise');\n# plt.axvline(np.mean(rhos_pair));\n\nsns.distplot(rhos_mean, label='to mean');\n# plt.axvline(np.mean(rhos_mean), color='g');\nplt.legend(loc='upper left');\nplt.savefig('plot-intrinsic-ws353-rhos.pdf', format='pdf', dpi=300, bbox_inches='tight', pad_inches=0.1)\nprint(np.mean(rhos_pair), np.mean(rhos_mean))", "0.565874935874 0.73582286453\n" ], [ "# Fisher transform: http://stats.stackexchange.com/a/19825 and wiki article therein\nnp.tanh(np.arctanh(rhos_pair).mean()), np.tanh(np.arctanh(rhos_mean).mean())", "_____no_output_____" ], [ "from nltk.metrics.agreement import AnnotationTask", "_____no_output_____" ], [ "AnnotationTask(data=[\n ('coder1', 'obj1', 'label1'), \n ('coder1', 'obj2', 'label2'), \n ('coder2', 'obj1', 'label1'),\n ('coder2', 'obj2', 'label2'),\n ('coder3', 'obj1', 'label1'),\n ('coder3', 'obj2', 'label1'),\n ]).multi_kappa()", "_____no_output_____" ], [ "multikappas = []\nfor name in range(1, 14):\n for b in bin_counts:\n labels = bin(df[str(name)], b) \n# gold_labels = bin(df_gold.sim, b)\n for i, label in enumerate(labels):\n multikappas.append(('coder%d'%name, 'wordpair%d'%i, label))", "_____no_output_____" ], [ "AnnotationTask(multikappas).multi_kappa()\n# WTF nltk, you are great", "_____no_output_____" ] ], [ [ "# The same thing for the MEN dataset\nAnnotations by Marco and Elia", "_____no_output_____" ] ], [ [ "spearmanr(marco.sim, elia.sim) # they report .6845", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
cb279d3fca06a42b1e29d410c70325fd874f667c
1,018,501
ipynb
Jupyter Notebook
cwru/Gaussian_thermal_learning/Gaussian-thermal-learning-reducedC-fine-tune-temperature.ipynb
akabakcioglu/SGDDynamics
f8b7ed1be545f525b01f0ca9e42591ae38e85976
[ "MIT" ]
null
null
null
cwru/Gaussian_thermal_learning/Gaussian-thermal-learning-reducedC-fine-tune-temperature.ipynb
akabakcioglu/SGDDynamics
f8b7ed1be545f525b01f0ca9e42591ae38e85976
[ "MIT" ]
null
null
null
cwru/Gaussian_thermal_learning/Gaussian-thermal-learning-reducedC-fine-tune-temperature.ipynb
akabakcioglu/SGDDynamics
f8b7ed1be545f525b01f0ca9e42591ae38e85976
[ "MIT" ]
null
null
null
117.786631
2,413
0.63279
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
cb279ee6f1c66b910643b4ae366ea0af21ac0930
259,404
ipynb
Jupyter Notebook
ADL_JupyterNotebooks/ADL_03_Tutorial/TL_Julia_Mueller_Colab.ipynb
jm-201414/DeepLearningLecture_RWU
e15a8a146d24b9934c6c5a5bcfa4dffb048cb1a4
[ "MIT" ]
null
null
null
ADL_JupyterNotebooks/ADL_03_Tutorial/TL_Julia_Mueller_Colab.ipynb
jm-201414/DeepLearningLecture_RWU
e15a8a146d24b9934c6c5a5bcfa4dffb048cb1a4
[ "MIT" ]
null
null
null
ADL_JupyterNotebooks/ADL_03_Tutorial/TL_Julia_Mueller_Colab.ipynb
jm-201414/DeepLearningLecture_RWU
e15a8a146d24b9934c6c5a5bcfa4dffb048cb1a4
[ "MIT" ]
1
2020-09-16T14:33:28.000Z
2020-09-16T14:33:28.000Z
269.650728
73,970
0.81557
[ [ [ "# **Applied Deep Learning Tutorial**\n\n## **Transfer Learning for Object Classification**\n\n\n### **Imports**\n\nImport the necessary libraries and load the Dogs vs Cats dataset from Kaggle.", "_____no_output_____" ] ], [ [ "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\n\ntry:\n # Use the %tensorflow_version magic if in colab.\n %tensorflow_version 1.x\nexcept Exception:\n pass\n \nimport tensorflow as tf\nfrom tensorflow import keras\n#print(\"TensorFlow version is \", tf.__version__)\n\nimport numpy as np\nimport cv2\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n", "TensorFlow 1.x selected.\n" ] ], [ [ "### **Preparing the data**\n\nCreate directories for training and validation for both classes, such as dog and cat.", "_____no_output_____" ] ], [ [ "# Load Cats vs Dogs dataset\nzip_file = tf.keras.utils.get_file(origin=\"https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip\",\n fname=\"cats_and_dogs_filtered.zip\", extract=True)\n\nbase_dir, _ = os.path.splitext(zip_file)\nprint(os.listdir(base_dir))\ntrain_dir = os.path.join(base_dir, 'train')\nprint(os.listdir(train_dir))\nvalidation_dir = os.path.join(base_dir, 'validation')\n\n# Directory with our training cat pictures\ntrain_cats_dir = os.path.join(train_dir, 'cats')\n#'''print how many cat images there are in your training dataset''\n\nprint('Train cats:' + str(len(os.listdir(train_cats_dir))))\nprint(os.listdir(train_cats_dir))\n\n# Directory with our training dog pictures\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\n\nprint('Train dogs:' + str(len(os.listdir(train_dogs_dir))))\nprint(os.listdir(train_dogs_dir))\n\n# Directory with our validation cat pictures\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\n\nprint('Validation cats:' + str(len(os.listdir(validation_cats_dir))))\nprint(os.listdir(validation_cats_dir))\n\n# Directory with our validation dog pictures\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\n\nprint('Validation dogs:' + str(len(os.listdir(validation_dogs_dir))))\nprint(os.listdir(validation_dogs_dir))", "Downloading data from https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip\n68608000/68606236 [==============================] - 1s 0us/step\n['validation', 'vectorize.py', 'train']\n['cats', 'dogs']\nTrain cats:1000\n['cat.76.jpg', 'cat.634.jpg', 'cat.445.jpg', 'cat.67.jpg', 'cat.40.jpg', 'cat.777.jpg', 'cat.355.jpg', 'cat.308.jpg', 'cat.221.jpg', 'cat.703.jpg', 'cat.766.jpg', 'cat.699.jpg', 'cat.55.jpg', 'cat.109.jpg', 'cat.323.jpg', 'cat.778.jpg', 'cat.145.jpg', 'cat.405.jpg', 'cat.309.jpg', 'cat.998.jpg', 'cat.834.jpg', 'cat.648.jpg', 'cat.574.jpg', 'cat.704.jpg', 'cat.795.jpg', 'cat.83.jpg', 'cat.233.jpg', 'cat.564.jpg', 'cat.167.jpg', 'cat.325.jpg', 'cat.836.jpg', 'cat.493.jpg', 'cat.277.jpg', 'cat.315.jpg', 'cat.732.jpg', 'cat.442.jpg', 'cat.34.jpg', 'cat.481.jpg', 'cat.43.jpg', 'cat.410.jpg', 'cat.905.jpg', 'cat.929.jpg', 'cat.260.jpg', 'cat.874.jpg', 'cat.230.jpg', 'cat.32.jpg', 'cat.597.jpg', 'cat.996.jpg', 'cat.21.jpg', 'cat.142.jpg', 'cat.479.jpg', 'cat.290.jpg', 'cat.845.jpg', 'cat.464.jpg', 'cat.948.jpg', 'cat.762.jpg', 'cat.161.jpg', 'cat.19.jpg', 'cat.208.jpg', 'cat.345.jpg', 'cat.848.jpg', 'cat.627.jpg', 'cat.474.jpg', 'cat.702.jpg', 'cat.44.jpg', 'cat.989.jpg', 'cat.96.jpg', 'cat.666.jpg', 'cat.11.jpg', 'cat.377.jpg', 'cat.210.jpg', 'cat.752.jpg', 'cat.630.jpg', 'cat.528.jpg', 'cat.487.jpg', 'cat.909.jpg', 'cat.941.jpg', 'cat.971.jpg', 'cat.311.jpg', 'cat.284.jpg', 'cat.78.jpg', 'cat.257.jpg', 'cat.12.jpg', 'cat.829.jpg', 'cat.495.jpg', 'cat.349.jpg', 'cat.435.jpg', 'cat.910.jpg', 'cat.401.jpg', 'cat.198.jpg', 'cat.659.jpg', 'cat.135.jpg', 'cat.949.jpg', 'cat.826.jpg', 'cat.542.jpg', 'cat.185.jpg', 'cat.127.jpg', 'cat.879.jpg', 'cat.744.jpg', 'cat.421.jpg', 'cat.317.jpg', 'cat.469.jpg', 'cat.786.jpg', 'cat.603.jpg', 'cat.943.jpg', 'cat.336.jpg', 'cat.102.jpg', 'cat.279.jpg', 'cat.524.jpg', 'cat.855.jpg', 'cat.172.jpg', 'cat.965.jpg', 'cat.506.jpg', 'cat.926.jpg', 'cat.645.jpg', 'cat.872.jpg', 'cat.690.jpg', 'cat.385.jpg', 'cat.256.jpg', 'cat.189.jpg', 'cat.751.jpg', 'cat.272.jpg', 'cat.423.jpg', 'cat.244.jpg', 'cat.882.jpg', 'cat.770.jpg', 'cat.549.jpg', 'cat.607.jpg', 'cat.273.jpg', 'cat.749.jpg', 'cat.362.jpg', 'cat.729.jpg', 'cat.802.jpg', 'cat.665.jpg', 'cat.74.jpg', 'cat.667.jpg', 'cat.655.jpg', 'cat.518.jpg', 'cat.635.jpg', 'cat.567.jpg', 'cat.381.jpg', 'cat.98.jpg', 'cat.354.jpg', 'cat.341.jpg', 'cat.286.jpg', 'cat.725.jpg', 'cat.383.jpg', 'cat.376.jpg', 'cat.857.jpg', 'cat.379.jpg', 'cat.499.jpg', 'cat.650.jpg', 'cat.343.jpg', 'cat.587.jpg', 'cat.378.jpg', 'cat.361.jpg', 'cat.884.jpg', 'cat.200.jpg', 'cat.333.jpg', 'cat.63.jpg', 'cat.457.jpg', 'cat.818.jpg', 'cat.327.jpg', 'cat.620.jpg', 'cat.404.jpg', 'cat.934.jpg', 'cat.428.jpg', 'cat.705.jpg', 'cat.414.jpg', 'cat.505.jpg', 'cat.155.jpg', 'cat.366.jpg', 'cat.875.jpg', 'cat.969.jpg', 'cat.318.jpg', 'cat.779.jpg', 'cat.65.jpg', 'cat.548.jpg', 'cat.456.jpg', 'cat.275.jpg', 'cat.963.jpg', 'cat.869.jpg', 'cat.893.jpg', 'cat.622.jpg', 'cat.372.jpg', 'cat.223.jpg', 'cat.8.jpg', 'cat.932.jpg', 'cat.520.jpg', 'cat.224.jpg', 'cat.82.jpg', 'cat.158.jpg', 'cat.938.jpg', 'cat.985.jpg', 'cat.858.jpg', 'cat.609.jpg', 'cat.608.jpg', 'cat.89.jpg', 'cat.241.jpg', 'cat.292.jpg', 'cat.925.jpg', 'cat.979.jpg', 'cat.694.jpg', 'cat.654.jpg', 'cat.625.jpg', 'cat.330.jpg', 'cat.192.jpg', 'cat.148.jpg', 'cat.632.jpg', 'cat.743.jpg', 'cat.906.jpg', 'cat.191.jpg', 'cat.297.jpg', 'cat.471.jpg', 'cat.18.jpg', 'cat.207.jpg', 'cat.239.jpg', 'cat.819.jpg', 'cat.600.jpg', 'cat.754.jpg', 'cat.922.jpg', 'cat.285.jpg', 'cat.827.jpg', 'cat.646.jpg', 'cat.508.jpg', 'cat.921.jpg', 'cat.670.jpg', 'cat.730.jpg', 'cat.211.jpg', 'cat.175.jpg', 'cat.868.jpg', 'cat.20.jpg', 'cat.806.jpg', 'cat.955.jpg', 'cat.179.jpg', 'cat.183.jpg', 'cat.517.jpg', 'cat.832.jpg', 'cat.194.jpg', 'cat.205.jpg', 'cat.980.jpg', 'cat.171.jpg', 'cat.899.jpg', 'cat.255.jpg', 'cat.58.jpg', 'cat.877.jpg', 'cat.248.jpg', 'cat.615.jpg', 'cat.245.jpg', 'cat.638.jpg', 'cat.346.jpg', 'cat.759.jpg', 'cat.677.jpg', 'cat.977.jpg', 'cat.814.jpg', 'cat.937.jpg', 'cat.203.jpg', 'cat.999.jpg', 'cat.885.jpg', 'cat.449.jpg', 'cat.80.jpg', 'cat.468.jpg', 'cat.320.jpg', 'cat.56.jpg', 'cat.301.jpg', 'cat.602.jpg', 'cat.791.jpg', 'cat.991.jpg', 'cat.967.jpg', 'cat.328.jpg', 'cat.168.jpg', 'cat.687.jpg', 'cat.714.jpg', 'cat.422.jpg', 'cat.427.jpg', 'cat.820.jpg', 'cat.390.jpg', 'cat.465.jpg', 'cat.935.jpg', 'cat.525.jpg', 'cat.865.jpg', 'cat.266.jpg', 'cat.484.jpg', 'cat.119.jpg', 'cat.350.jpg', 'cat.562.jpg', 'cat.420.jpg', 'cat.763.jpg', 'cat.895.jpg', 'cat.578.jpg', 'cat.232.jpg', 'cat.903.jpg', 'cat.824.jpg', 'cat.619.jpg', 'cat.353.jpg', 'cat.571.jpg', 'cat.911.jpg', 'cat.218.jpg', 'cat.839.jpg', 'cat.104.jpg', 'cat.329.jpg', 'cat.968.jpg', 'cat.450.jpg', 'cat.642.jpg', 'cat.817.jpg', 'cat.321.jpg', 'cat.852.jpg', 'cat.476.jpg', 'cat.441.jpg', 'cat.7.jpg', 'cat.712.jpg', 'cat.722.jpg', 'cat.392.jpg', 'cat.745.jpg', 'cat.545.jpg', 'cat.863.jpg', 'cat.964.jpg', 'cat.46.jpg', 'cat.804.jpg', 'cat.825.jpg', 'cat.371.jpg', 'cat.228.jpg', 'cat.137.jpg', 'cat.88.jpg', 'cat.569.jpg', 'cat.966.jpg', 'cat.26.jpg', 'cat.541.jpg', 'cat.459.jpg', 'cat.927.jpg', 'cat.363.jpg', 'cat.547.jpg', 'cat.125.jpg', 'cat.503.jpg', 'cat.48.jpg', 'cat.54.jpg', 'cat.748.jpg', 'cat.552.jpg', 'cat.514.jpg', 'cat.85.jpg', 'cat.235.jpg', 'cat.994.jpg', 'cat.197.jpg', 'cat.71.jpg', 'cat.532.jpg', 'cat.788.jpg', 'cat.294.jpg', 'cat.835.jpg', 'cat.166.jpg', 'cat.724.jpg', 'cat.384.jpg', 'cat.126.jpg', 'cat.382.jpg', 'cat.141.jpg', 'cat.195.jpg', 'cat.727.jpg', 'cat.485.jpg', 'cat.246.jpg', 'cat.212.jpg', 'cat.531.jpg', 'cat.664.jpg', 'cat.504.jpg', 'cat.599.jpg', 'cat.616.jpg', 'cat.136.jpg', 'cat.846.jpg', 'cat.867.jpg', 'cat.697.jpg', 'cat.204.jpg', 'cat.568.jpg', 'cat.662.jpg', 'cat.908.jpg', 'cat.842.jpg', 'cat.686.jpg', 'cat.692.jpg', 'cat.719.jpg', 'cat.737.jpg', 'cat.556.jpg', 'cat.912.jpg', 'cat.340.jpg', 'cat.439.jpg', 'cat.853.jpg', 'cat.170.jpg', 'cat.425.jpg', 'cat.790.jpg', 'cat.529.jpg', 'cat.961.jpg', 'cat.680.jpg', 'cat.307.jpg', 'cat.807.jpg', 'cat.793.jpg', 'cat.936.jpg', 'cat.538.jpg', 'cat.31.jpg', 'cat.406.jpg', 'cat.310.jpg', 'cat.332.jpg', 'cat.180.jpg', 'cat.594.jpg', 'cat.544.jpg', 'cat.534.jpg', 'cat.637.jpg', 'cat.954.jpg', 'cat.717.jpg', 'cat.177.jpg', 'cat.669.jpg', 'cat.898.jpg', 'cat.107.jpg', 'cat.130.jpg', 'cat.140.jpg', 'cat.830.jpg', 'cat.443.jpg', 'cat.773.jpg', 'cat.497.jpg', 'cat.182.jpg', 'cat.805.jpg', 'cat.590.jpg', 'cat.344.jpg', 'cat.896.jpg', 'cat.673.jpg', 'cat.77.jpg', 'cat.993.jpg', 'cat.15.jpg', 'cat.75.jpg', 'cat.897.jpg', 'cat.243.jpg', 'cat.873.jpg', 'cat.219.jpg', 'cat.621.jpg', 'cat.116.jpg', 'cat.856.jpg', 'cat.716.jpg', 'cat.792.jpg', 'cat.42.jpg', 'cat.915.jpg', 'cat.735.jpg', 'cat.312.jpg', 'cat.258.jpg', 'cat.959.jpg', 'cat.358.jpg', 'cat.515.jpg', 'cat.165.jpg', 'cat.591.jpg', 'cat.757.jpg', 'cat.411.jpg', 'cat.782.jpg', 'cat.238.jpg', 'cat.289.jpg', 'cat.472.jpg', 'cat.437.jpg', 'cat.753.jpg', 'cat.924.jpg', 'cat.847.jpg', 'cat.365.jpg', 'cat.657.jpg', 'cat.90.jpg', 'cat.446.jpg', 'cat.809.jpg', 'cat.444.jpg', 'cat.70.jpg', 'cat.761.jpg', 'cat.3.jpg', 'cat.220.jpg', 'cat.728.jpg', 'cat.201.jpg', 'cat.101.jpg', 'cat.840.jpg', 'cat.860.jpg', 'cat.742.jpg', 'cat.370.jpg', 'cat.698.jpg', 'cat.453.jpg', 'cat.339.jpg', 'cat.914.jpg', 'cat.583.jpg', 'cat.156.jpg', 'cat.394.jpg', 'cat.99.jpg', 'cat.674.jpg', 'cat.2.jpg', 'cat.9.jpg', 'cat.613.jpg', 'cat.892.jpg', 'cat.696.jpg', 'cat.364.jpg', 'cat.740.jpg', 'cat.274.jpg', 'cat.588.jpg', 'cat.813.jpg', 'cat.124.jpg', 'cat.267.jpg', 'cat.755.jpg', 'cat.772.jpg', 'cat.644.jpg', 'cat.876.jpg', 'cat.252.jpg', 'cat.799.jpg', 'cat.902.jpg', 'cat.368.jpg', 'cat.303.jpg', 'cat.685.jpg', 'cat.356.jpg', 'cat.367.jpg', 'cat.492.jpg', 'cat.322.jpg', 'cat.715.jpg', 'cat.415.jpg', 'cat.434.jpg', 'cat.153.jpg', 'cat.881.jpg', 'cat.851.jpg', 'cat.640.jpg', 'cat.992.jpg', 'cat.373.jpg', 'cat.586.jpg', 'cat.237.jpg', 'cat.501.jpg', 'cat.458.jpg', 'cat.169.jpg', 'cat.302.jpg', 'cat.617.jpg', 'cat.900.jpg', 'cat.628.jpg', 'cat.585.jpg', 'cat.913.jpg', 'cat.337.jpg', 'cat.526.jpg', 'cat.440.jpg', 'cat.1.jpg', 'cat.184.jpg', 'cat.324.jpg', 'cat.629.jpg', 'cat.768.jpg', 'cat.298.jpg', 'cat.122.jpg', 'cat.907.jpg', 'cat.626.jpg', 'cat.917.jpg', 'cat.570.jpg', 'cat.923.jpg', 'cat.95.jpg', 'cat.930.jpg', 'cat.247.jpg', 'cat.403.jpg', 'cat.736.jpg', 'cat.789.jpg', 'cat.565.jpg', 'cat.660.jpg', 'cat.982.jpg', 'cat.904.jpg', 'cat.781.jpg', 'cat.801.jpg', 'cat.25.jpg', 'cat.577.jpg', 'cat.888.jpg', 'cat.106.jpg', 'cat.723.jpg', 'cat.52.jpg', 'cat.477.jpg', 'cat.695.jpg', 'cat.470.jpg', 'cat.178.jpg', 'cat.639.jpg', 'cat.86.jpg', 'cat.160.jpg', 'cat.461.jpg', 'cat.22.jpg', 'cat.269.jpg', 'cat.652.jpg', 'cat.94.jpg', 'cat.643.jpg', 'cat.962.jpg', 'cat.447.jpg', 'cat.187.jpg', 'cat.746.jpg', 'cat.593.jpg', 'cat.35.jpg', 'cat.483.jpg', 'cat.623.jpg', 'cat.512.jpg', 'cat.10.jpg', 'cat.700.jpg', 'cat.387.jpg', 'cat.251.jpg', 'cat.147.jpg', 'cat.416.jpg', 'cat.460.jpg', 'cat.536.jpg', 'cat.950.jpg', 'cat.304.jpg', 'cat.438.jpg', 'cat.29.jpg', 'cat.997.jpg', 'cat.335.jpg', 'cat.951.jpg', 'cat.535.jpg', 'cat.473.jpg', 'cat.395.jpg', 'cat.952.jpg', 'cat.262.jpg', 'cat.380.jpg', 'cat.769.jpg', 'cat.775.jpg', 'cat.229.jpg', 'cat.374.jpg', 'cat.933.jpg', 'cat.213.jpg', 'cat.227.jpg', 'cat.726.jpg', 'cat.250.jpg', 'cat.718.jpg', 'cat.550.jpg', 'cat.785.jpg', 'cat.300.jpg', 'cat.519.jpg', 'cat.513.jpg', 'cat.347.jpg', 'cat.316.jpg', 'cat.543.jpg', 'cat.849.jpg', 'cat.242.jpg', 'cat.112.jpg', 'cat.467.jpg', 'cat.780.jpg', 'cat.259.jpg', 'cat.546.jpg', 'cat.942.jpg', 'cat.579.jpg', 'cat.234.jpg', 'cat.995.jpg', 'cat.489.jpg', 'cat.708.jpg', 'cat.206.jpg', 'cat.159.jpg', 'cat.605.jpg', 'cat.537.jpg', 'cat.150.jpg', 'cat.431.jpg', 'cat.516.jpg', 'cat.226.jpg', 'cat.776.jpg', 'cat.988.jpg', 'cat.523.jpg', 'cat.225.jpg', 'cat.478.jpg', 'cat.974.jpg', 'cat.861.jpg', 'cat.886.jpg', 'cat.709.jpg', 'cat.566.jpg', 'cat.181.jpg', 'cat.413.jpg', 'cat.661.jpg', 'cat.16.jpg', 'cat.57.jpg', 'cat.866.jpg', 'cat.981.jpg', 'cat.889.jpg', 'cat.490.jpg', 'cat.688.jpg', 'cat.448.jpg', 'cat.494.jpg', 'cat.152.jpg', 'cat.280.jpg', 'cat.342.jpg', 'cat.138.jpg', 'cat.800.jpg', 'cat.139.jpg', 'cat.764.jpg', 'cat.217.jpg', 'cat.209.jpg', 'cat.741.jpg', 'cat.558.jpg', 'cat.890.jpg', 'cat.429.jpg', 'cat.978.jpg', 'cat.614.jpg', 'cat.823.jpg', 'cat.236.jpg', 'cat.408.jpg', 'cat.810.jpg', 'cat.14.jpg', 'cat.931.jpg', 'cat.488.jpg', 'cat.393.jpg', 'cat.409.jpg', 'cat.151.jpg', 'cat.684.jpg', 'cat.683.jpg', 'cat.815.jpg', 'cat.701.jpg', 'cat.540.jpg', 'cat.916.jpg', 'cat.612.jpg', 'cat.970.jpg', 'cat.563.jpg', 'cat.33.jpg', 'cat.430.jpg', 'cat.491.jpg', 'cat.720.jpg', 'cat.146.jpg', 'cat.455.jpg', 'cat.360.jpg', 'cat.314.jpg', 'cat.326.jpg', 'cat.649.jpg', 'cat.397.jpg', 'cat.426.jpg', 'cat.711.jpg', 'cat.843.jpg', 'cat.100.jpg', 'cat.871.jpg', 'cat.671.jpg', 'cat.216.jpg', 'cat.398.jpg', 'cat.940.jpg', 'cat.990.jpg', 'cat.522.jpg', 'cat.121.jpg', 'cat.105.jpg', 'cat.396.jpg', 'cat.334.jpg', 'cat.656.jpg', 'cat.50.jpg', 'cat.672.jpg', 'cat.23.jpg', 'cat.812.jpg', 'cat.850.jpg', 'cat.841.jpg', 'cat.894.jpg', 'cat.482.jpg', 'cat.173.jpg', 'cat.154.jpg', 'cat.668.jpg', 'cat.631.jpg', 'cat.555.jpg', 'cat.734.jpg', 'cat.580.jpg', 'cat.0.jpg', 'cat.691.jpg', 'cat.511.jpg', 'cat.681.jpg', 'cat.115.jpg', 'cat.249.jpg', 'cat.679.jpg', 'cat.133.jpg', 'cat.131.jpg', 'cat.498.jpg', 'cat.822.jpg', 'cat.611.jpg', 'cat.176.jpg', 'cat.502.jpg', 'cat.418.jpg', 'cat.838.jpg', 'cat.713.jpg', 'cat.738.jpg', 'cat.97.jpg', 'cat.641.jpg', 'cat.202.jpg', 'cat.945.jpg', 'cat.598.jpg', 'cat.756.jpg', 'cat.143.jpg', 'cat.689.jpg', 'cat.589.jpg', 'cat.265.jpg', 'cat.451.jpg', 'cat.319.jpg', 'cat.878.jpg', 'cat.61.jpg', 'cat.975.jpg', 'cat.901.jpg', 'cat.407.jpg', 'cat.610.jpg', 'cat.606.jpg', 'cat.582.jpg', 'cat.831.jpg', 'cat.452.jpg', 'cat.271.jpg', 'cat.263.jpg', 'cat.4.jpg', 'cat.188.jpg', 'cat.601.jpg', 'cat.803.jpg', 'cat.120.jpg', 'cat.62.jpg', 'cat.123.jpg', 'cat.887.jpg', 'cat.747.jpg', 'cat.424.jpg', 'cat.859.jpg', 'cat.264.jpg', 'cat.797.jpg', 'cat.573.jpg', 'cat.767.jpg', 'cat.454.jpg', 'cat.682.jpg', 'cat.93.jpg', 'cat.261.jpg', 'cat.436.jpg', 'cat.828.jpg', 'cat.821.jpg', 'cat.946.jpg', 'cat.186.jpg', 'cat.190.jpg', 'cat.53.jpg', 'cat.402.jpg', 'cat.575.jpg', 'cat.45.jpg', 'cat.214.jpg', 'cat.765.jpg', 'cat.281.jpg', 'cat.270.jpg', 'cat.66.jpg', 'cat.953.jpg', 'cat.287.jpg', 'cat.707.jpg', 'cat.576.jpg', 'cat.87.jpg', 'cat.282.jpg', 'cat.111.jpg', 'cat.475.jpg', 'cat.196.jpg', 'cat.844.jpg', 'cat.132.jpg', 'cat.24.jpg', 'cat.369.jpg', 'cat.117.jpg', 'cat.462.jpg', 'cat.79.jpg', 'cat.986.jpg', 'cat.939.jpg', 'cat.833.jpg', 'cat.69.jpg', 'cat.113.jpg', 'cat.928.jpg', 'cat.559.jpg', 'cat.883.jpg', 'cat.386.jpg', 'cat.291.jpg', 'cat.240.jpg', 'cat.947.jpg', 'cat.72.jpg', 'cat.110.jpg', 'cat.507.jpg', 'cat.288.jpg', 'cat.283.jpg', 'cat.604.jpg', 'cat.253.jpg', 'cat.530.jpg', 'cat.276.jpg', 'cat.510.jpg', 'cat.6.jpg', 'cat.533.jpg', 'cat.417.jpg', 'cat.27.jpg', 'cat.561.jpg', 'cat.976.jpg', 'cat.733.jpg', 'cat.64.jpg', 'cat.596.jpg', 'cat.760.jpg', 'cat.816.jpg', 'cat.39.jpg', 'cat.399.jpg', 'cat.693.jpg', 'cat.59.jpg', 'cat.231.jpg', 'cat.389.jpg', 'cat.13.jpg', 'cat.653.jpg', 'cat.918.jpg', 'cat.957.jpg', 'cat.984.jpg', 'cat.30.jpg', 'cat.496.jpg', 'cat.419.jpg', 'cat.572.jpg', 'cat.794.jpg', 'cat.278.jpg', 'cat.118.jpg', 'cat.215.jpg', 'cat.463.jpg', 'cat.295.jpg', 'cat.739.jpg', 'cat.500.jpg', 'cat.633.jpg', 'cat.108.jpg', 'cat.553.jpg', 'cat.651.jpg', 'cat.663.jpg', 'cat.509.jpg', 'cat.958.jpg', 'cat.758.jpg', 'cat.466.jpg', 'cat.557.jpg', 'cat.313.jpg', 'cat.944.jpg', 'cat.157.jpg', 'cat.539.jpg', 'cat.581.jpg', 'cat.796.jpg', 'cat.81.jpg', 'cat.338.jpg', 'cat.222.jpg', 'cat.710.jpg', 'cat.774.jpg', 'cat.60.jpg', 'cat.193.jpg', 'cat.721.jpg', 'cat.254.jpg', 'cat.862.jpg', 'cat.299.jpg', 'cat.37.jpg', 'cat.296.jpg', 'cat.91.jpg', 'cat.783.jpg', 'cat.731.jpg', 'cat.199.jpg', 'cat.92.jpg', 'cat.400.jpg', 'cat.880.jpg', 'cat.41.jpg', 'cat.864.jpg', 'cat.854.jpg', 'cat.391.jpg', 'cat.675.jpg', 'cat.359.jpg', 'cat.787.jpg', 'cat.149.jpg', 'cat.348.jpg', 'cat.36.jpg', 'cat.527.jpg', 'cat.771.jpg', 'cat.658.jpg', 'cat.357.jpg', 'cat.162.jpg', 'cat.551.jpg', 'cat.84.jpg', 'cat.432.jpg', 'cat.750.jpg', 'cat.811.jpg', 'cat.837.jpg', 'cat.5.jpg', 'cat.972.jpg', 'cat.554.jpg', 'cat.919.jpg', 'cat.47.jpg', 'cat.521.jpg', 'cat.973.jpg', 'cat.960.jpg', 'cat.480.jpg', 'cat.956.jpg', 'cat.433.jpg', 'cat.618.jpg', 'cat.331.jpg', 'cat.486.jpg', 'cat.584.jpg', 'cat.388.jpg', 'cat.68.jpg', 'cat.306.jpg', 'cat.560.jpg', 'cat.798.jpg', 'cat.174.jpg', 'cat.891.jpg', 'cat.352.jpg', 'cat.144.jpg', 'cat.808.jpg', 'cat.983.jpg', 'cat.920.jpg', 'cat.38.jpg', 'cat.17.jpg', 'cat.103.jpg', 'cat.706.jpg', 'cat.678.jpg', 'cat.305.jpg', 'cat.592.jpg', 'cat.987.jpg', 'cat.128.jpg', 'cat.375.jpg', 'cat.49.jpg', 'cat.647.jpg', 'cat.268.jpg', 'cat.636.jpg', 'cat.28.jpg', 'cat.51.jpg', 'cat.784.jpg', 'cat.293.jpg', 'cat.163.jpg', 'cat.870.jpg', 'cat.129.jpg', 'cat.164.jpg', 'cat.114.jpg', 'cat.73.jpg', 'cat.676.jpg', 'cat.412.jpg', 'cat.351.jpg', 'cat.134.jpg', 'cat.595.jpg', 'cat.624.jpg']\nTrain dogs:1000\n['dog.937.jpg', 'dog.805.jpg', 'dog.351.jpg', 'dog.319.jpg', 'dog.596.jpg', 'dog.102.jpg', 'dog.997.jpg', 'dog.742.jpg', 'dog.378.jpg', 'dog.345.jpg', 'dog.344.jpg', 'dog.309.jpg', 'dog.800.jpg', 'dog.422.jpg', 'dog.247.jpg', 'dog.364.jpg', 'dog.875.jpg', 'dog.558.jpg', 'dog.583.jpg', 'dog.581.jpg', 'dog.948.jpg', 'dog.527.jpg', 'dog.66.jpg', 'dog.314.jpg', 'dog.881.jpg', 'dog.614.jpg', 'dog.630.jpg', 'dog.668.jpg', 'dog.991.jpg', 'dog.789.jpg', 'dog.685.jpg', 'dog.419.jpg', 'dog.168.jpg', 'dog.153.jpg', 'dog.1.jpg', 'dog.86.jpg', 'dog.138.jpg', 'dog.633.jpg', 'dog.769.jpg', 'dog.986.jpg', 'dog.941.jpg', 'dog.453.jpg', 'dog.895.jpg', 'dog.140.jpg', 'dog.713.jpg', 'dog.659.jpg', 'dog.133.jpg', 'dog.611.jpg', 'dog.388.jpg', 'dog.301.jpg', 'dog.862.jpg', 'dog.171.jpg', 'dog.952.jpg', 'dog.349.jpg', 'dog.254.jpg', 'dog.236.jpg', 'dog.720.jpg', 'dog.4.jpg', 'dog.89.jpg', 'dog.938.jpg', 'dog.919.jpg', 'dog.432.jpg', 'dog.758.jpg', 'dog.743.jpg', 'dog.318.jpg', 'dog.439.jpg', 'dog.845.jpg', 'dog.746.jpg', 'dog.702.jpg', 'dog.135.jpg', 'dog.781.jpg', 'dog.615.jpg', 'dog.32.jpg', 'dog.551.jpg', 'dog.416.jpg', 'dog.63.jpg', 'dog.136.jpg', 'dog.471.jpg', 'dog.736.jpg', 'dog.92.jpg', 'dog.763.jpg', 'dog.621.jpg', 'dog.985.jpg', 'dog.644.jpg', 'dog.509.jpg', 'dog.485.jpg', 'dog.803.jpg', 'dog.305.jpg', 'dog.164.jpg', 'dog.212.jpg', 'dog.594.jpg', 'dog.766.jpg', 'dog.402.jpg', 'dog.688.jpg', 'dog.512.jpg', 'dog.150.jpg', 'dog.730.jpg', 'dog.37.jpg', 'dog.69.jpg', 'dog.298.jpg', 'dog.79.jpg', 'dog.78.jpg', 'dog.387.jpg', 'dog.926.jpg', 'dog.172.jpg', 'dog.695.jpg', 'dog.570.jpg', 'dog.250.jpg', 'dog.850.jpg', 'dog.44.jpg', 'dog.662.jpg', 'dog.982.jpg', 'dog.939.jpg', 'dog.465.jpg', 'dog.54.jpg', 'dog.275.jpg', 'dog.777.jpg', 'dog.215.jpg', 'dog.30.jpg', 'dog.660.jpg', 'dog.605.jpg', 'dog.12.jpg', 'dog.867.jpg', 'dog.775.jpg', 'dog.546.jpg', 'dog.359.jpg', 'dog.883.jpg', 'dog.356.jpg', 'dog.288.jpg', 'dog.21.jpg', 'dog.417.jpg', 'dog.687.jpg', 'dog.43.jpg', 'dog.838.jpg', 'dog.994.jpg', 'dog.562.jpg', 'dog.88.jpg', 'dog.968.jpg', 'dog.173.jpg', 'dog.741.jpg', 'dog.692.jpg', 'dog.19.jpg', 'dog.666.jpg', 'dog.368.jpg', 'dog.52.jpg', 'dog.673.jpg', 'dog.283.jpg', 'dog.15.jpg', 'dog.338.jpg', 'dog.128.jpg', 'dog.418.jpg', 'dog.280.jpg', 'dog.224.jpg', 'dog.490.jpg', 'dog.821.jpg', 'dog.333.jpg', 'dog.717.jpg', 'dog.682.jpg', 'dog.436.jpg', 'dog.120.jpg', 'dog.819.jpg', 'dog.167.jpg', 'dog.382.jpg', 'dog.516.jpg', 'dog.93.jpg', 'dog.244.jpg', 'dog.48.jpg', 'dog.885.jpg', 'dog.812.jpg', 'dog.324.jpg', 'dog.661.jpg', 'dog.251.jpg', 'dog.437.jpg', 'dog.26.jpg', 'dog.856.jpg', 'dog.852.jpg', 'dog.395.jpg', 'dog.219.jpg', 'dog.571.jpg', 'dog.284.jpg', 'dog.117.jpg', 'dog.696.jpg', 'dog.469.jpg', 'dog.141.jpg', 'dog.84.jpg', 'dog.246.jpg', 'dog.67.jpg', 'dog.220.jpg', 'dog.686.jpg', 'dog.573.jpg', 'dog.663.jpg', 'dog.255.jpg', 'dog.593.jpg', 'dog.786.jpg', 'dog.815.jpg', 'dog.788.jpg', 'dog.872.jpg', 'dog.143.jpg', 'dog.435.jpg', 'dog.381.jpg', 'dog.735.jpg', 'dog.10.jpg', 'dog.699.jpg', 'dog.779.jpg', 'dog.678.jpg', 'dog.375.jpg', 'dog.992.jpg', 'dog.499.jpg', 'dog.656.jpg', 'dog.714.jpg', 'dog.924.jpg', 'dog.459.jpg', 'dog.804.jpg', 'dog.513.jpg', 'dog.2.jpg', 'dog.797.jpg', 'dog.336.jpg', 'dog.726.jpg', 'dog.576.jpg', 'dog.258.jpg', 'dog.383.jpg', 'dog.569.jpg', 'dog.855.jpg', 'dog.613.jpg', 'dog.361.jpg', 'dog.310.jpg', 'dog.940.jpg', 'dog.97.jpg', 'dog.795.jpg', 'dog.225.jpg', 'dog.830.jpg', 'dog.624.jpg', 'dog.278.jpg', 'dog.473.jpg', 'dog.648.jpg', 'dog.718.jpg', 'dog.380.jpg', 'dog.29.jpg', 'dog.55.jpg', 'dog.185.jpg', 'dog.675.jpg', 'dog.293.jpg', 'dog.440.jpg', 'dog.739.jpg', 'dog.691.jpg', 'dog.549.jpg', 'dog.335.jpg', 'dog.430.jpg', 'dog.334.jpg', 'dog.449.jpg', 'dog.908.jpg', 'dog.360.jpg', 'dog.5.jpg', 'dog.677.jpg', 'dog.119.jpg', 'dog.923.jpg', 'dog.343.jpg', 'dog.722.jpg', 'dog.263.jpg', 'dog.170.jpg', 'dog.911.jpg', 'dog.813.jpg', 'dog.854.jpg', 'dog.176.jpg', 'dog.201.jpg', 'dog.243.jpg', 'dog.665.jpg', 'dog.124.jpg', 'dog.132.jpg', 'dog.23.jpg', 'dog.114.jpg', 'dog.928.jpg', 'dog.287.jpg', 'dog.62.jpg', 'dog.835.jpg', 'dog.979.jpg', 'dog.591.jpg', 'dog.597.jpg', 'dog.761.jpg', 'dog.719.jpg', 'dog.834.jpg', 'dog.814.jpg', 'dog.822.jpg', 'dog.207.jpg', 'dog.337.jpg', 'dog.658.jpg', 'dog.156.jpg', 'dog.347.jpg', 'dog.322.jpg', 'dog.7.jpg', 'dog.315.jpg', 'dog.189.jpg', 'dog.560.jpg', 'dog.245.jpg', 'dog.229.jpg', 'dog.910.jpg', 'dog.579.jpg', 'dog.470.jpg', 'dog.424.jpg', 'dog.969.jpg', 'dog.598.jpg', 'dog.545.jpg', 'dog.59.jpg', 'dog.987.jpg', 'dog.606.jpg', 'dog.587.jpg', 'dog.413.jpg', 'dog.496.jpg', 'dog.373.jpg', 'dog.13.jpg', 'dog.46.jpg', 'dog.960.jpg', 'dog.477.jpg', 'dog.620.jpg', 'dog.759.jpg', 'dog.828.jpg', 'dog.118.jpg', 'dog.524.jpg', 'dog.183.jpg', 'dog.497.jpg', 'dog.480.jpg', 'dog.27.jpg', 'dog.905.jpg', 'dog.744.jpg', 'dog.637.jpg', 'dog.645.jpg', 'dog.184.jpg', 'dog.721.jpg', 'dog.42.jpg', 'dog.628.jpg', 'dog.734.jpg', 'dog.423.jpg', 'dog.846.jpg', 'dog.204.jpg', 'dog.807.jpg', 'dog.125.jpg', 'dog.500.jpg', 'dog.972.jpg', 'dog.397.jpg', 'dog.0.jpg', 'dog.750.jpg', 'dog.326.jpg', 'dog.929.jpg', 'dog.187.jpg', 'dog.679.jpg', 'dog.904.jpg', 'dog.840.jpg', 'dog.346.jpg', 'dog.963.jpg', 'dog.406.jpg', 'dog.999.jpg', 'dog.265.jpg', 'dog.468.jpg', 'dog.428.jpg', 'dog.827.jpg', 'dog.978.jpg', 'dog.899.jpg', 'dog.155.jpg', 'dog.161.jpg', 'dog.72.jpg', 'dog.753.jpg', 'dog.252.jpg', 'dog.341.jpg', 'dog.240.jpg', 'dog.863.jpg', 'dog.81.jpg', 'dog.127.jpg', 'dog.752.jpg', 'dog.951.jpg', 'dog.868.jpg', 'dog.631.jpg', 'dog.131.jpg', 'dog.564.jpg', 'dog.38.jpg', 'dog.165.jpg', 'dog.989.jpg', 'dog.411.jpg', 'dog.609.jpg', 'dog.426.jpg', 'dog.87.jpg', 'dog.764.jpg', 'dog.226.jpg', 'dog.898.jpg', 'dog.844.jpg', 'dog.510.jpg', 'dog.914.jpg', 'dog.886.jpg', 'dog.463.jpg', 'dog.200.jpg', 'dog.504.jpg', 'dog.462.jpg', 'dog.508.jpg', 'dog.918.jpg', 'dog.316.jpg', 'dog.561.jpg', 'dog.186.jpg', 'dog.216.jpg', 'dog.727.jpg', 'dog.235.jpg', 'dog.537.jpg', 'dog.849.jpg', 'dog.792.jpg', 'dog.31.jpg', 'dog.712.jpg', 'dog.267.jpg', 'dog.949.jpg', 'dog.547.jpg', 'dog.142.jpg', 'dog.386.jpg', 'dog.601.jpg', 'dog.199.jpg', 'dog.399.jpg', 'dog.222.jpg', 'dog.478.jpg', 'dog.261.jpg', 'dog.698.jpg', 'dog.967.jpg', 'dog.649.jpg', 'dog.612.jpg', 'dog.159.jpg', 'dog.213.jpg', 'dog.294.jpg', 'dog.61.jpg', 'dog.729.jpg', 'dog.60.jpg', 'dog.954.jpg', 'dog.339.jpg', 'dog.710.jpg', 'dog.415.jpg', 'dog.976.jpg', 'dog.268.jpg', 'dog.592.jpg', 'dog.953.jpg', 'dog.99.jpg', 'dog.325.jpg', 'dog.363.jpg', 'dog.370.jpg', 'dog.158.jpg', 'dog.157.jpg', 'dog.955.jpg', 'dog.450.jpg', 'dog.657.jpg', 'dog.408.jpg', 'dog.947.jpg', 'dog.162.jpg', 'dog.392.jpg', 'dog.884.jpg', 'dog.306.jpg', 'dog.707.jpg', 'dog.865.jpg', 'dog.134.jpg', 'dog.3.jpg', 'dog.557.jpg', 'dog.80.jpg', 'dog.45.jpg', 'dog.782.jpg', 'dog.457.jpg', 'dog.299.jpg', 'dog.790.jpg', 'dog.772.jpg', 'dog.65.jpg', 'dog.429.jpg', 'dog.233.jpg', 'dog.522.jpg', 'dog.313.jpg', 'dog.9.jpg', 'dog.577.jpg', 'dog.567.jpg', 'dog.767.jpg', 'dog.773.jpg', 'dog.716.jpg', 'dog.998.jpg', 'dog.242.jpg', 'dog.531.jpg', 'dog.544.jpg', 'dog.169.jpg', 'dog.823.jpg', 'dog.526.jpg', 'dog.507.jpg', 'dog.444.jpg', 'dog.374.jpg', 'dog.590.jpg', 'dog.272.jpg', 'dog.869.jpg', 'dog.329.jpg', 'dog.109.jpg', 'dog.943.jpg', 'dog.946.jpg', 'dog.530.jpg', 'dog.217.jpg', 'dog.552.jpg', 'dog.123.jpg', 'dog.536.jpg', 'dog.894.jpg', 'dog.541.jpg', 'dog.837.jpg', 'dog.427.jpg', 'dog.410.jpg', 'dog.451.jpg', 'dog.460.jpg', 'dog.289.jpg', 'dog.701.jpg', 'dog.848.jpg', 'dog.618.jpg', 'dog.625.jpg', 'dog.533.jpg', 'dog.35.jpg', 'dog.369.jpg', 'dog.961.jpg', 'dog.431.jpg', 'dog.389.jpg', 'dog.320.jpg', 'dog.348.jpg', 'dog.308.jpg', 'dog.956.jpg', 'dog.126.jpg', 'dog.466.jpg', 'dog.639.jpg', 'dog.783.jpg', 'dog.540.jpg', 'dog.632.jpg', 'dog.302.jpg', 'dog.365.jpg', 'dog.776.jpg', 'dog.181.jpg', 'dog.262.jpg', 'dog.106.jpg', 'dog.8.jpg', 'dog.107.jpg', 'dog.144.jpg', 'dog.122.jpg', 'dog.931.jpg', 'dog.799.jpg', 'dog.390.jpg', 'dog.57.jpg', 'dog.483.jpg', 'dog.50.jpg', 'dog.357.jpg', 'dog.434.jpg', 'dog.210.jpg', 'dog.962.jpg', 'dog.491.jpg', 'dog.279.jpg', 'dog.16.jpg', 'dog.847.jpg', 'dog.640.jpg', 'dog.920.jpg', 'dog.209.jpg', 'dog.237.jpg', 'dog.486.jpg', 'dog.511.jpg', 'dog.342.jpg', 'dog.671.jpg', 'dog.385.jpg', 'dog.934.jpg', 'dog.234.jpg', 'dog.882.jpg', 'dog.809.jpg', 'dog.641.jpg', 'dog.912.jpg', 'dog.922.jpg', 'dog.113.jpg', 'dog.973.jpg', 'dog.407.jpg', 'dog.409.jpg', 'dog.866.jpg', 'dog.548.jpg', 'dog.282.jpg', 'dog.638.jpg', 'dog.398.jpg', 'dog.327.jpg', 'dog.796.jpg', 'dog.461.jpg', 'dog.650.jpg', 'dog.839.jpg', 'dog.879.jpg', 'dog.664.jpg', 'dog.893.jpg', 'dog.626.jpg', 'dog.806.jpg', 'dog.585.jpg', 'dog.667.jpg', 'dog.740.jpg', 'dog.91.jpg', 'dog.230.jpg', 'dog.708.jpg', 'dog.192.jpg', 'dog.575.jpg', 'dog.935.jpg', 'dog.977.jpg', 'dog.519.jpg', 'dog.751.jpg', 'dog.711.jpg', 'dog.166.jpg', 'dog.950.jpg', 'dog.194.jpg', 'dog.412.jpg', 'dog.825.jpg', 'dog.535.jpg', 'dog.506.jpg', 'dog.831.jpg', 'dog.196.jpg', 'dog.116.jpg', 'dog.523.jpg', 'dog.554.jpg', 'dog.177.jpg', 'dog.851.jpg', 'dog.859.jpg', 'dog.238.jpg', 'dog.149.jpg', 'dog.876.jpg', 'dog.623.jpg', 'dog.877.jpg', 'dog.403.jpg', 'dog.798.jpg', 'dog.529.jpg', 'dog.446.jpg', 'dog.53.jpg', 'dog.791.jpg', 'dog.534.jpg', 'dog.900.jpg', 'dog.503.jpg', 'dog.476.jpg', 'dog.715.jpg', 'dog.304.jpg', 'dog.538.jpg', 'dog.891.jpg', 'dog.394.jpg', 'dog.163.jpg', 'dog.36.jpg', 'dog.211.jpg', 'dog.674.jpg', 'dog.188.jpg', 'dog.421.jpg', 'dog.312.jpg', 'dog.111.jpg', 'dog.942.jpg', 'dog.589.jpg', 'dog.933.jpg', 'dog.291.jpg', 'dog.420.jpg', 'dog.553.jpg', 'dog.393.jpg', 'dog.83.jpg', 'dog.77.jpg', 'dog.756.jpg', 'dog.285.jpg', 'dog.514.jpg', 'dog.749.jpg', 'dog.995.jpg', 'dog.425.jpg', 'dog.672.jpg', 'dog.787.jpg', 'dog.603.jpg', 'dog.635.jpg', 'dog.110.jpg', 'dog.40.jpg', 'dog.311.jpg', 'dog.259.jpg', 'dog.228.jpg', 'dog.25.jpg', 'dog.515.jpg', 'dog.518.jpg', 'dog.582.jpg', 'dog.902.jpg', 'dog.218.jpg', 'dog.90.jpg', 'dog.676.jpg', 'dog.642.jpg', 'dog.47.jpg', 'dog.643.jpg', 'dog.737.jpg', 'dog.307.jpg', 'dog.115.jpg', 'dog.858.jpg', 'dog.993.jpg', 'dog.75.jpg', 'dog.706.jpg', 'dog.770.jpg', 'dog.539.jpg', 'dog.896.jpg', 'dog.651.jpg', 'dog.958.jpg', 'dog.379.jpg', 'dog.874.jpg', 'dog.396.jpg', 'dog.957.jpg', 'dog.198.jpg', 'dog.51.jpg', 'dog.574.jpg', 'dog.617.jpg', 'dog.190.jpg', 'dog.286.jpg', 'dog.602.jpg', 'dog.384.jpg', 'dog.475.jpg', 'dog.270.jpg', 'dog.907.jpg', 'dog.214.jpg', 'dog.784.jpg', 'dog.103.jpg', 'dog.479.jpg', 'dog.232.jpg', 'dog.366.jpg', 'dog.297.jpg', 'dog.684.jpg', 'dog.843.jpg', 'dog.925.jpg', 'dog.731.jpg', 'dog.206.jpg', 'dog.95.jpg', 'dog.433.jpg', 'dog.371.jpg', 'dog.704.jpg', 'dog.694.jpg', 'dog.253.jpg', 'dog.595.jpg', 'dog.725.jpg', 'dog.861.jpg', 'dog.906.jpg', 'dog.760.jpg', 'dog.636.jpg', 'dog.768.jpg', 'dog.148.jpg', 'dog.622.jpg', 'dog.778.jpg', 'dog.774.jpg', 'dog.441.jpg', 'dog.525.jpg', 'dog.494.jpg', 'dog.358.jpg', 'dog.988.jpg', 'dog.959.jpg', 'dog.256.jpg', 'dog.202.jpg', 'dog.105.jpg', 'dog.331.jpg', 'dog.880.jpg', 'dog.112.jpg', 'dog.757.jpg', 'dog.810.jpg', 'dog.683.jpg', 'dog.257.jpg', 'dog.352.jpg', 'dog.697.jpg', 'dog.921.jpg', 'dog.39.jpg', 'dog.646.jpg', 'dog.495.jpg', 'dog.377.jpg', 'dog.984.jpg', 'dog.231.jpg', 'dog.317.jpg', 'dog.917.jpg', 'dog.154.jpg', 'dog.654.jpg', 'dog.870.jpg', 'dog.733.jpg', 'dog.555.jpg', 'dog.489.jpg', 'dog.818.jpg', 'dog.975.jpg', 'dog.724.jpg', 'dog.559.jpg', 'dog.68.jpg', 'dog.505.jpg', 'dog.22.jpg', 'dog.147.jpg', 'dog.456.jpg', 'dog.355.jpg', 'dog.897.jpg', 'dog.391.jpg', 'dog.98.jpg', 'dog.853.jpg', 'dog.550.jpg', 'dog.747.jpg', 'dog.101.jpg', 'dog.146.jpg', 'dog.498.jpg', 'dog.600.jpg', 'dog.467.jpg', 'dog.175.jpg', 'dog.323.jpg', 'dog.627.jpg', 'dog.857.jpg', 'dog.599.jpg', 'dog.647.jpg', 'dog.604.jpg', 'dog.909.jpg', 'dog.193.jpg', 'dog.944.jpg', 'dog.71.jpg', 'dog.401.jpg', 'dog.445.jpg', 'dog.14.jpg', 'dog.455.jpg', 'dog.619.jpg', 'dog.438.jpg', 'dog.915.jpg', 'dog.860.jpg', 'dog.794.jpg', 'dog.732.jpg', 'dog.738.jpg', 'dog.873.jpg', 'dog.179.jpg', 'dog.932.jpg', 'dog.563.jpg', 'dog.182.jpg', 'dog.829.jpg', 'dog.653.jpg', 'dog.484.jpg', 'dog.367.jpg', 'dog.28.jpg', 'dog.151.jpg', 'dog.655.jpg', 'dog.271.jpg', 'dog.205.jpg', 'dog.586.jpg', 'dog.454.jpg', 'dog.816.jpg', 'dog.936.jpg', 'dog.332.jpg', 'dog.96.jpg', 'dog.892.jpg', 'dog.464.jpg', 'dog.481.jpg', 'dog.493.jpg', 'dog.966.jpg', 'dog.273.jpg', 'dog.808.jpg', 'dog.6.jpg', 'dog.488.jpg', 'dog.274.jpg', 'dog.945.jpg', 'dog.221.jpg', 'dog.811.jpg', 'dog.448.jpg', 'dog.64.jpg', 'dog.588.jpg', 'dog.321.jpg', 'dog.681.jpg', 'dog.49.jpg', 'dog.670.jpg', 'dog.532.jpg', 'dog.728.jpg', 'dog.474.jpg', 'dog.328.jpg', 'dog.73.jpg', 'dog.248.jpg', 'dog.745.jpg', 'dog.913.jpg', 'dog.405.jpg', 'dog.669.jpg', 'dog.100.jpg', 'dog.785.jpg', 'dog.705.jpg', 'dog.340.jpg', 'dog.290.jpg', 'dog.260.jpg', 'dog.703.jpg', 'dog.841.jpg', 'dog.930.jpg', 'dog.754.jpg', 'dog.58.jpg', 'dog.443.jpg', 'dog.888.jpg', 'dog.580.jpg', 'dog.152.jpg', 'dog.680.jpg', 'dog.24.jpg', 'dog.572.jpg', 'dog.208.jpg', 'dog.608.jpg', 'dog.56.jpg', 'dog.833.jpg', 'dog.354.jpg', 'dog.249.jpg', 'dog.472.jpg', 'dog.965.jpg', 'dog.693.jpg', 'dog.765.jpg', 'dog.802.jpg', 'dog.70.jpg', 'dog.974.jpg', 'dog.492.jpg', 'dog.565.jpg', 'dog.11.jpg', 'dog.801.jpg', 'dog.269.jpg', 'dog.74.jpg', 'dog.292.jpg', 'dog.353.jpg', 'dog.442.jpg', 'dog.616.jpg', 'dog.889.jpg', 'dog.376.jpg', 'dog.487.jpg', 'dog.690.jpg', 'dog.970.jpg', 'dog.842.jpg', 'dog.584.jpg', 'dog.18.jpg', 'dog.793.jpg', 'dog.350.jpg', 'dog.85.jpg', 'dog.971.jpg', 'dog.634.jpg', 'dog.568.jpg', 'dog.227.jpg', 'dog.520.jpg', 'dog.20.jpg', 'dog.197.jpg', 'dog.543.jpg', 'dog.372.jpg', 'dog.824.jpg', 'dog.139.jpg', 'dog.404.jpg', 'dog.517.jpg', 'dog.277.jpg', 'dog.203.jpg', 'dog.223.jpg', 'dog.832.jpg', 'dog.452.jpg', 'dog.264.jpg', 'dog.330.jpg', 'dog.241.jpg', 'dog.578.jpg', 'dog.521.jpg', 'dog.180.jpg', 'dog.447.jpg', 'dog.566.jpg', 'dog.826.jpg', 'dog.610.jpg', 'dog.755.jpg', 'dog.689.jpg', 'dog.276.jpg', 'dog.34.jpg', 'dog.266.jpg', 'dog.104.jpg', 'dog.890.jpg', 'dog.362.jpg', 'dog.528.jpg', 'dog.482.jpg', 'dog.916.jpg', 'dog.980.jpg', 'dog.981.jpg', 'dog.129.jpg', 'dog.108.jpg', 'dog.887.jpg', 'dog.41.jpg', 'dog.780.jpg', 'dog.607.jpg', 'dog.817.jpg', 'dog.82.jpg', 'dog.878.jpg', 'dog.748.jpg', 'dog.121.jpg', 'dog.996.jpg', 'dog.990.jpg', 'dog.864.jpg', 'dog.836.jpg', 'dog.295.jpg', 'dog.414.jpg', 'dog.771.jpg', 'dog.871.jpg', 'dog.195.jpg', 'dog.76.jpg', 'dog.174.jpg', 'dog.820.jpg', 'dog.964.jpg', 'dog.303.jpg', 'dog.281.jpg', 'dog.502.jpg', 'dog.700.jpg', 'dog.542.jpg', 'dog.458.jpg', 'dog.901.jpg', 'dog.652.jpg', 'dog.709.jpg', 'dog.137.jpg', 'dog.400.jpg', 'dog.94.jpg', 'dog.629.jpg', 'dog.927.jpg', 'dog.130.jpg', 'dog.762.jpg', 'dog.239.jpg', 'dog.160.jpg', 'dog.556.jpg', 'dog.903.jpg', 'dog.296.jpg', 'dog.33.jpg', 'dog.723.jpg', 'dog.300.jpg', 'dog.145.jpg', 'dog.191.jpg', 'dog.501.jpg', 'dog.178.jpg', 'dog.17.jpg', 'dog.983.jpg']\nValidation cats:500\n['cat.2058.jpg', 'cat.2447.jpg', 'cat.2170.jpg', 'cat.2432.jpg', 'cat.2458.jpg', 'cat.2155.jpg', 'cat.2498.jpg', 'cat.2118.jpg', 'cat.2006.jpg', 'cat.2251.jpg', 'cat.2490.jpg', 'cat.2074.jpg', 'cat.2125.jpg', 'cat.2335.jpg', 'cat.2222.jpg', 'cat.2318.jpg', 'cat.2324.jpg', 'cat.2379.jpg', 'cat.2141.jpg', 'cat.2175.jpg', 'cat.2366.jpg', 'cat.2329.jpg', 'cat.2471.jpg', 'cat.2382.jpg', 'cat.2315.jpg', 'cat.2398.jpg', 'cat.2467.jpg', 'cat.2062.jpg', 'cat.2427.jpg', 'cat.2229.jpg', 'cat.2394.jpg', 'cat.2396.jpg', 'cat.2005.jpg', 'cat.2327.jpg', 'cat.2193.jpg', 'cat.2340.jpg', 'cat.2410.jpg', 'cat.2057.jpg', 'cat.2428.jpg', 'cat.2368.jpg', 'cat.2291.jpg', 'cat.2102.jpg', 'cat.2421.jpg', 'cat.2046.jpg', 'cat.2402.jpg', 'cat.2359.jpg', 'cat.2348.jpg', 'cat.2392.jpg', 'cat.2209.jpg', 'cat.2114.jpg', 'cat.2088.jpg', 'cat.2159.jpg', 'cat.2423.jpg', 'cat.2429.jpg', 'cat.2032.jpg', 'cat.2417.jpg', 'cat.2491.jpg', 'cat.2110.jpg', 'cat.2152.jpg', 'cat.2475.jpg', 'cat.2130.jpg', 'cat.2169.jpg', 'cat.2137.jpg', 'cat.2372.jpg', 'cat.2337.jpg', 'cat.2041.jpg', 'cat.2477.jpg', 'cat.2285.jpg', 'cat.2325.jpg', 'cat.2469.jpg', 'cat.2038.jpg', 'cat.2123.jpg', 'cat.2404.jpg', 'cat.2064.jpg', 'cat.2200.jpg', 'cat.2191.jpg', 'cat.2286.jpg', 'cat.2037.jpg', 'cat.2080.jpg', 'cat.2187.jpg', 'cat.2190.jpg', 'cat.2103.jpg', 'cat.2015.jpg', 'cat.2144.jpg', 'cat.2371.jpg', 'cat.2462.jpg', 'cat.2214.jpg', 'cat.2349.jpg', 'cat.2033.jpg', 'cat.2171.jpg', 'cat.2369.jpg', 'cat.2487.jpg', 'cat.2256.jpg', 'cat.2266.jpg', 'cat.2497.jpg', 'cat.2460.jpg', 'cat.2073.jpg', 'cat.2030.jpg', 'cat.2356.jpg', 'cat.2485.jpg', 'cat.2186.jpg', 'cat.2223.jpg', 'cat.2072.jpg', 'cat.2056.jpg', 'cat.2197.jpg', 'cat.2344.jpg', 'cat.2226.jpg', 'cat.2360.jpg', 'cat.2219.jpg', 'cat.2220.jpg', 'cat.2361.jpg', 'cat.2451.jpg', 'cat.2126.jpg', 'cat.2365.jpg', 'cat.2068.jpg', 'cat.2480.jpg', 'cat.2488.jpg', 'cat.2478.jpg', 'cat.2465.jpg', 'cat.2430.jpg', 'cat.2253.jpg', 'cat.2040.jpg', 'cat.2353.jpg', 'cat.2199.jpg', 'cat.2452.jpg', 'cat.2267.jpg', 'cat.2484.jpg', 'cat.2069.jpg', 'cat.2132.jpg', 'cat.2408.jpg', 'cat.2363.jpg', 'cat.2139.jpg', 'cat.2150.jpg', 'cat.2221.jpg', 'cat.2016.jpg', 'cat.2183.jpg', 'cat.2097.jpg', 'cat.2131.jpg', 'cat.2346.jpg', 'cat.2087.jpg', 'cat.2025.jpg', 'cat.2276.jpg', 'cat.2195.jpg', 'cat.2375.jpg', 'cat.2010.jpg', 'cat.2431.jpg', 'cat.2238.jpg', 'cat.2364.jpg', 'cat.2031.jpg', 'cat.2258.jpg', 'cat.2022.jpg', 'cat.2289.jpg', 'cat.2290.jpg', 'cat.2437.jpg', 'cat.2241.jpg', 'cat.2154.jpg', 'cat.2156.jpg', 'cat.2095.jpg', 'cat.2281.jpg', 'cat.2381.jpg', 'cat.2067.jpg', 'cat.2120.jpg', 'cat.2278.jpg', 'cat.2393.jpg', 'cat.2303.jpg', 'cat.2385.jpg', 'cat.2004.jpg', 'cat.2225.jpg', 'cat.2018.jpg', 'cat.2316.jpg', 'cat.2167.jpg', 'cat.2179.jpg', 'cat.2280.jpg', 'cat.2296.jpg', 'cat.2017.jpg', 'cat.2090.jpg', 'cat.2401.jpg', 'cat.2208.jpg', 'cat.2380.jpg', 'cat.2065.jpg', 'cat.2036.jpg', 'cat.2282.jpg', 'cat.2314.jpg', 'cat.2434.jpg', 'cat.2374.jpg', 'cat.2420.jpg', 'cat.2250.jpg', 'cat.2412.jpg', 'cat.2461.jpg', 'cat.2312.jpg', 'cat.2330.jpg', 'cat.2384.jpg', 'cat.2147.jpg', 'cat.2306.jpg', 'cat.2157.jpg', 'cat.2206.jpg', 'cat.2178.jpg', 'cat.2284.jpg', 'cat.2244.jpg', 'cat.2181.jpg', 'cat.2466.jpg', 'cat.2204.jpg', 'cat.2309.jpg', 'cat.2184.jpg', 'cat.2035.jpg', 'cat.2328.jpg', 'cat.2399.jpg', 'cat.2390.jpg', 'cat.2231.jpg', 'cat.2043.jpg', 'cat.2158.jpg', 'cat.2416.jpg', 'cat.2013.jpg', 'cat.2194.jpg', 'cat.2116.jpg', 'cat.2370.jpg', 'cat.2277.jpg', 'cat.2260.jpg', 'cat.2232.jpg', 'cat.2234.jpg', 'cat.2246.jpg', 'cat.2091.jpg', 'cat.2409.jpg', 'cat.2163.jpg', 'cat.2176.jpg', 'cat.2093.jpg', 'cat.2249.jpg', 'cat.2436.jpg', 'cat.2079.jpg', 'cat.2129.jpg', 'cat.2218.jpg', 'cat.2457.jpg', 'cat.2224.jpg', 'cat.2397.jpg', 'cat.2143.jpg', 'cat.2383.jpg', 'cat.2026.jpg', 'cat.2044.jpg', 'cat.2076.jpg', 'cat.2293.jpg', 'cat.2189.jpg', 'cat.2419.jpg', 'cat.2297.jpg', 'cat.2063.jpg', 'cat.2003.jpg', 'cat.2287.jpg', 'cat.2400.jpg', 'cat.2450.jpg', 'cat.2294.jpg', 'cat.2092.jpg', 'cat.2283.jpg', 'cat.2343.jpg', 'cat.2321.jpg', 'cat.2011.jpg', 'cat.2367.jpg', 'cat.2243.jpg', 'cat.2235.jpg', 'cat.2334.jpg', 'cat.2373.jpg', 'cat.2288.jpg', 'cat.2496.jpg', 'cat.2124.jpg', 'cat.2456.jpg', 'cat.2007.jpg', 'cat.2242.jpg', 'cat.2012.jpg', 'cat.2099.jpg', 'cat.2135.jpg', 'cat.2376.jpg', 'cat.2108.jpg', 'cat.2418.jpg', 'cat.2357.jpg', 'cat.2228.jpg', 'cat.2019.jpg', 'cat.2347.jpg', 'cat.2192.jpg', 'cat.2391.jpg', 'cat.2395.jpg', 'cat.2113.jpg', 'cat.2445.jpg', 'cat.2320.jpg', 'cat.2308.jpg', 'cat.2027.jpg', 'cat.2304.jpg', 'cat.2105.jpg', 'cat.2049.jpg', 'cat.2083.jpg', 'cat.2495.jpg', 'cat.2236.jpg', 'cat.2121.jpg', 'cat.2345.jpg', 'cat.2198.jpg', 'cat.2464.jpg', 'cat.2322.jpg', 'cat.2499.jpg', 'cat.2066.jpg', 'cat.2405.jpg', 'cat.2299.jpg', 'cat.2389.jpg', 'cat.2070.jpg', 'cat.2127.jpg', 'cat.2149.jpg', 'cat.2203.jpg', 'cat.2453.jpg', 'cat.2021.jpg', 'cat.2177.jpg', 'cat.2104.jpg', 'cat.2262.jpg', 'cat.2305.jpg', 'cat.2352.jpg', 'cat.2310.jpg', 'cat.2425.jpg', 'cat.2082.jpg', 'cat.2326.jpg', 'cat.2313.jpg', 'cat.2275.jpg', 'cat.2094.jpg', 'cat.2362.jpg', 'cat.2081.jpg', 'cat.2173.jpg', 'cat.2014.jpg', 'cat.2424.jpg', 'cat.2230.jpg', 'cat.2378.jpg', 'cat.2433.jpg', 'cat.2023.jpg', 'cat.2188.jpg', 'cat.2403.jpg', 'cat.2438.jpg', 'cat.2172.jpg', 'cat.2271.jpg', 'cat.2492.jpg', 'cat.2307.jpg', 'cat.2059.jpg', 'cat.2298.jpg', 'cat.2136.jpg', 'cat.2213.jpg', 'cat.2463.jpg', 'cat.2413.jpg', 'cat.2338.jpg', 'cat.2020.jpg', 'cat.2411.jpg', 'cat.2248.jpg', 'cat.2001.jpg', 'cat.2459.jpg', 'cat.2239.jpg', 'cat.2128.jpg', 'cat.2443.jpg', 'cat.2051.jpg', 'cat.2207.jpg', 'cat.2008.jpg', 'cat.2237.jpg', 'cat.2216.jpg', 'cat.2257.jpg', 'cat.2212.jpg', 'cat.2407.jpg', 'cat.2274.jpg', 'cat.2153.jpg', 'cat.2386.jpg', 'cat.2160.jpg', 'cat.2479.jpg', 'cat.2272.jpg', 'cat.2028.jpg', 'cat.2474.jpg', 'cat.2302.jpg', 'cat.2406.jpg', 'cat.2109.jpg', 'cat.2440.jpg', 'cat.2205.jpg', 'cat.2387.jpg', 'cat.2336.jpg', 'cat.2029.jpg', 'cat.2134.jpg', 'cat.2101.jpg', 'cat.2148.jpg', 'cat.2439.jpg', 'cat.2084.jpg', 'cat.2115.jpg', 'cat.2085.jpg', 'cat.2050.jpg', 'cat.2024.jpg', 'cat.2140.jpg', 'cat.2268.jpg', 'cat.2468.jpg', 'cat.2089.jpg', 'cat.2295.jpg', 'cat.2448.jpg', 'cat.2449.jpg', 'cat.2052.jpg', 'cat.2486.jpg', 'cat.2483.jpg', 'cat.2151.jpg', 'cat.2261.jpg', 'cat.2142.jpg', 'cat.2317.jpg', 'cat.2146.jpg', 'cat.2112.jpg', 'cat.2162.jpg', 'cat.2117.jpg', 'cat.2300.jpg', 'cat.2002.jpg', 'cat.2342.jpg', 'cat.2210.jpg', 'cat.2174.jpg', 'cat.2165.jpg', 'cat.2333.jpg', 'cat.2078.jpg', 'cat.2269.jpg', 'cat.2045.jpg', 'cat.2048.jpg', 'cat.2071.jpg', 'cat.2472.jpg', 'cat.2042.jpg', 'cat.2201.jpg', 'cat.2415.jpg', 'cat.2054.jpg', 'cat.2323.jpg', 'cat.2473.jpg', 'cat.2270.jpg', 'cat.2202.jpg', 'cat.2331.jpg', 'cat.2455.jpg', 'cat.2145.jpg', 'cat.2182.jpg', 'cat.2180.jpg', 'cat.2161.jpg', 'cat.2164.jpg', 'cat.2106.jpg', 'cat.2481.jpg', 'cat.2196.jpg', 'cat.2166.jpg', 'cat.2414.jpg', 'cat.2119.jpg', 'cat.2053.jpg', 'cat.2185.jpg', 'cat.2098.jpg', 'cat.2493.jpg', 'cat.2273.jpg', 'cat.2435.jpg', 'cat.2000.jpg', 'cat.2476.jpg', 'cat.2061.jpg', 'cat.2442.jpg', 'cat.2240.jpg', 'cat.2247.jpg', 'cat.2441.jpg', 'cat.2489.jpg', 'cat.2255.jpg', 'cat.2227.jpg', 'cat.2034.jpg', 'cat.2264.jpg', 'cat.2358.jpg', 'cat.2107.jpg', 'cat.2388.jpg', 'cat.2075.jpg', 'cat.2319.jpg', 'cat.2454.jpg', 'cat.2350.jpg', 'cat.2111.jpg', 'cat.2039.jpg', 'cat.2252.jpg', 'cat.2122.jpg', 'cat.2377.jpg', 'cat.2168.jpg', 'cat.2009.jpg', 'cat.2263.jpg', 'cat.2233.jpg', 'cat.2211.jpg', 'cat.2245.jpg', 'cat.2047.jpg', 'cat.2254.jpg', 'cat.2100.jpg', 'cat.2446.jpg', 'cat.2351.jpg', 'cat.2341.jpg', 'cat.2077.jpg', 'cat.2422.jpg', 'cat.2339.jpg', 'cat.2259.jpg', 'cat.2494.jpg', 'cat.2217.jpg', 'cat.2332.jpg', 'cat.2138.jpg', 'cat.2301.jpg', 'cat.2444.jpg', 'cat.2292.jpg', 'cat.2215.jpg', 'cat.2265.jpg', 'cat.2055.jpg', 'cat.2482.jpg', 'cat.2311.jpg', 'cat.2133.jpg', 'cat.2096.jpg', 'cat.2355.jpg', 'cat.2279.jpg', 'cat.2354.jpg', 'cat.2426.jpg', 'cat.2470.jpg', 'cat.2060.jpg', 'cat.2086.jpg']\nValidation dogs:500\n['dog.2490.jpg', 'dog.2195.jpg', 'dog.2214.jpg', 'dog.2228.jpg', 'dog.2411.jpg', 'dog.2362.jpg', 'dog.2270.jpg', 'dog.2357.jpg', 'dog.2072.jpg', 'dog.2320.jpg', 'dog.2450.jpg', 'dog.2451.jpg', 'dog.2033.jpg', 'dog.2212.jpg', 'dog.2312.jpg', 'dog.2476.jpg', 'dog.2477.jpg', 'dog.2079.jpg', 'dog.2040.jpg', 'dog.2385.jpg', 'dog.2376.jpg', 'dog.2345.jpg', 'dog.2431.jpg', 'dog.2273.jpg', 'dog.2319.jpg', 'dog.2363.jpg', 'dog.2064.jpg', 'dog.2251.jpg', 'dog.2492.jpg', 'dog.2388.jpg', 'dog.2086.jpg', 'dog.2286.jpg', 'dog.2060.jpg', 'dog.2328.jpg', 'dog.2315.jpg', 'dog.2302.jpg', 'dog.2100.jpg', 'dog.2321.jpg', 'dog.2061.jpg', 'dog.2031.jpg', 'dog.2482.jpg', 'dog.2355.jpg', 'dog.2136.jpg', 'dog.2465.jpg', 'dog.2254.jpg', 'dog.2063.jpg', 'dog.2036.jpg', 'dog.2350.jpg', 'dog.2096.jpg', 'dog.2263.jpg', 'dog.2288.jpg', 'dog.2006.jpg', 'dog.2298.jpg', 'dog.2133.jpg', 'dog.2466.jpg', 'dog.2102.jpg', 'dog.2016.jpg', 'dog.2008.jpg', 'dog.2085.jpg', 'dog.2333.jpg', 'dog.2400.jpg', 'dog.2115.jpg', 'dog.2232.jpg', 'dog.2285.jpg', 'dog.2007.jpg', 'dog.2494.jpg', 'dog.2452.jpg', 'dog.2032.jpg', 'dog.2119.jpg', 'dog.2148.jpg', 'dog.2213.jpg', 'dog.2449.jpg', 'dog.2360.jpg', 'dog.2183.jpg', 'dog.2306.jpg', 'dog.2460.jpg', 'dog.2151.jpg', 'dog.2341.jpg', 'dog.2208.jpg', 'dog.2397.jpg', 'dog.2189.jpg', 'dog.2165.jpg', 'dog.2135.jpg', 'dog.2127.jpg', 'dog.2083.jpg', 'dog.2498.jpg', 'dog.2224.jpg', 'dog.2280.jpg', 'dog.2413.jpg', 'dog.2442.jpg', 'dog.2166.jpg', 'dog.2117.jpg', 'dog.2121.jpg', 'dog.2278.jpg', 'dog.2002.jpg', 'dog.2256.jpg', 'dog.2122.jpg', 'dog.2217.jpg', 'dog.2020.jpg', 'dog.2496.jpg', 'dog.2108.jpg', 'dog.2329.jpg', 'dog.2314.jpg', 'dog.2049.jpg', 'dog.2150.jpg', 'dog.2198.jpg', 'dog.2012.jpg', 'dog.2327.jpg', 'dog.2439.jpg', 'dog.2287.jpg', 'dog.2485.jpg', 'dog.2437.jpg', 'dog.2491.jpg', 'dog.2294.jpg', 'dog.2042.jpg', 'dog.2447.jpg', 'dog.2194.jpg', 'dog.2401.jpg', 'dog.2264.jpg', 'dog.2162.jpg', 'dog.2019.jpg', 'dog.2221.jpg', 'dog.2471.jpg', 'dog.2001.jpg', 'dog.2022.jpg', 'dog.2384.jpg', 'dog.2075.jpg', 'dog.2247.jpg', 'dog.2457.jpg', 'dog.2347.jpg', 'dog.2054.jpg', 'dog.2125.jpg', 'dog.2000.jpg', 'dog.2352.jpg', 'dog.2250.jpg', 'dog.2283.jpg', 'dog.2309.jpg', 'dog.2316.jpg', 'dog.2378.jpg', 'dog.2111.jpg', 'dog.2284.jpg', 'dog.2313.jpg', 'dog.2359.jpg', 'dog.2153.jpg', 'dog.2369.jpg', 'dog.2349.jpg', 'dog.2255.jpg', 'dog.2204.jpg', 'dog.2186.jpg', 'dog.2434.jpg', 'dog.2433.jpg', 'dog.2023.jpg', 'dog.2322.jpg', 'dog.2071.jpg', 'dog.2390.jpg', 'dog.2412.jpg', 'dog.2317.jpg', 'dog.2113.jpg', 'dog.2191.jpg', 'dog.2311.jpg', 'dog.2092.jpg', 'dog.2044.jpg', 'dog.2370.jpg', 'dog.2259.jpg', 'dog.2252.jpg', 'dog.2229.jpg', 'dog.2097.jpg', 'dog.2164.jpg', 'dog.2053.jpg', 'dog.2024.jpg', 'dog.2219.jpg', 'dog.2403.jpg', 'dog.2047.jpg', 'dog.2475.jpg', 'dog.2074.jpg', 'dog.2144.jpg', 'dog.2373.jpg', 'dog.2090.jpg', 'dog.2163.jpg', 'dog.2123.jpg', 'dog.2394.jpg', 'dog.2015.jpg', 'dog.2244.jpg', 'dog.2223.jpg', 'dog.2157.jpg', 'dog.2137.jpg', 'dog.2182.jpg', 'dog.2181.jpg', 'dog.2353.jpg', 'dog.2046.jpg', 'dog.2396.jpg', 'dog.2464.jpg', 'dog.2277.jpg', 'dog.2107.jpg', 'dog.2206.jpg', 'dog.2497.jpg', 'dog.2114.jpg', 'dog.2297.jpg', 'dog.2399.jpg', 'dog.2489.jpg', 'dog.2265.jpg', 'dog.2011.jpg', 'dog.2145.jpg', 'dog.2340.jpg', 'dog.2170.jpg', 'dog.2435.jpg', 'dog.2293.jpg', 'dog.2330.jpg', 'dog.2200.jpg', 'dog.2310.jpg', 'dog.2131.jpg', 'dog.2453.jpg', 'dog.2443.jpg', 'dog.2188.jpg', 'dog.2227.jpg', 'dog.2230.jpg', 'dog.2463.jpg', 'dog.2190.jpg', 'dog.2296.jpg', 'dog.2235.jpg', 'dog.2377.jpg', 'dog.2472.jpg', 'dog.2120.jpg', 'dog.2445.jpg', 'dog.2470.jpg', 'dog.2486.jpg', 'dog.2017.jpg', 'dog.2013.jpg', 'dog.2279.jpg', 'dog.2456.jpg', 'dog.2005.jpg', 'dog.2427.jpg', 'dog.2116.jpg', 'dog.2128.jpg', 'dog.2067.jpg', 'dog.2147.jpg', 'dog.2030.jpg', 'dog.2160.jpg', 'dog.2335.jpg', 'dog.2432.jpg', 'dog.2192.jpg', 'dog.2171.jpg', 'dog.2307.jpg', 'dog.2382.jpg', 'dog.2155.jpg', 'dog.2004.jpg', 'dog.2336.jpg', 'dog.2126.jpg', 'dog.2084.jpg', 'dog.2118.jpg', 'dog.2281.jpg', 'dog.2386.jpg', 'dog.2275.jpg', 'dog.2325.jpg', 'dog.2248.jpg', 'dog.2226.jpg', 'dog.2416.jpg', 'dog.2179.jpg', 'dog.2367.jpg', 'dog.2035.jpg', 'dog.2474.jpg', 'dog.2103.jpg', 'dog.2318.jpg', 'dog.2440.jpg', 'dog.2041.jpg', 'dog.2266.jpg', 'dog.2167.jpg', 'dog.2154.jpg', 'dog.2104.jpg', 'dog.2473.jpg', 'dog.2458.jpg', 'dog.2143.jpg', 'dog.2073.jpg', 'dog.2374.jpg', 'dog.2146.jpg', 'dog.2379.jpg', 'dog.2428.jpg', 'dog.2240.jpg', 'dog.2034.jpg', 'dog.2408.jpg', 'dog.2405.jpg', 'dog.2419.jpg', 'dog.2484.jpg', 'dog.2342.jpg', 'dog.2337.jpg', 'dog.2209.jpg', 'dog.2101.jpg', 'dog.2258.jpg', 'dog.2391.jpg', 'dog.2371.jpg', 'dog.2339.jpg', 'dog.2168.jpg', 'dog.2196.jpg', 'dog.2129.jpg', 'dog.2056.jpg', 'dog.2065.jpg', 'dog.2069.jpg', 'dog.2423.jpg', 'dog.2480.jpg', 'dog.2021.jpg', 'dog.2174.jpg', 'dog.2402.jpg', 'dog.2051.jpg', 'dog.2448.jpg', 'dog.2112.jpg', 'dog.2375.jpg', 'dog.2187.jpg', 'dog.2088.jpg', 'dog.2351.jpg', 'dog.2424.jpg', 'dog.2095.jpg', 'dog.2045.jpg', 'dog.2057.jpg', 'dog.2276.jpg', 'dog.2110.jpg', 'dog.2304.jpg', 'dog.2199.jpg', 'dog.2066.jpg', 'dog.2348.jpg', 'dog.2106.jpg', 'dog.2207.jpg', 'dog.2468.jpg', 'dog.2344.jpg', 'dog.2159.jpg', 'dog.2205.jpg', 'dog.2358.jpg', 'dog.2372.jpg', 'dog.2210.jpg', 'dog.2343.jpg', 'dog.2175.jpg', 'dog.2176.jpg', 'dog.2299.jpg', 'dog.2331.jpg', 'dog.2441.jpg', 'dog.2009.jpg', 'dog.2215.jpg', 'dog.2152.jpg', 'dog.2429.jpg', 'dog.2158.jpg', 'dog.2025.jpg', 'dog.2052.jpg', 'dog.2425.jpg', 'dog.2243.jpg', 'dog.2218.jpg', 'dog.2361.jpg', 'dog.2245.jpg', 'dog.2094.jpg', 'dog.2173.jpg', 'dog.2272.jpg', 'dog.2459.jpg', 'dog.2454.jpg', 'dog.2324.jpg', 'dog.2003.jpg', 'dog.2220.jpg', 'dog.2180.jpg', 'dog.2080.jpg', 'dog.2169.jpg', 'dog.2068.jpg', 'dog.2193.jpg', 'dog.2383.jpg', 'dog.2178.jpg', 'dog.2368.jpg', 'dog.2326.jpg', 'dog.2216.jpg', 'dog.2267.jpg', 'dog.2139.jpg', 'dog.2393.jpg', 'dog.2027.jpg', 'dog.2398.jpg', 'dog.2091.jpg', 'dog.2026.jpg', 'dog.2308.jpg', 'dog.2222.jpg', 'dog.2203.jpg', 'dog.2077.jpg', 'dog.2037.jpg', 'dog.2300.jpg', 'dog.2282.jpg', 'dog.2356.jpg', 'dog.2140.jpg', 'dog.2305.jpg', 'dog.2436.jpg', 'dog.2478.jpg', 'dog.2274.jpg', 'dog.2231.jpg', 'dog.2303.jpg', 'dog.2479.jpg', 'dog.2109.jpg', 'dog.2184.jpg', 'dog.2334.jpg', 'dog.2185.jpg', 'dog.2241.jpg', 'dog.2236.jpg', 'dog.2487.jpg', 'dog.2346.jpg', 'dog.2493.jpg', 'dog.2438.jpg', 'dog.2238.jpg', 'dog.2301.jpg', 'dog.2271.jpg', 'dog.2422.jpg', 'dog.2260.jpg', 'dog.2418.jpg', 'dog.2076.jpg', 'dog.2404.jpg', 'dog.2291.jpg', 'dog.2237.jpg', 'dog.2467.jpg', 'dog.2093.jpg', 'dog.2142.jpg', 'dog.2257.jpg', 'dog.2078.jpg', 'dog.2014.jpg', 'dog.2495.jpg', 'dog.2058.jpg', 'dog.2070.jpg', 'dog.2062.jpg', 'dog.2242.jpg', 'dog.2039.jpg', 'dog.2234.jpg', 'dog.2410.jpg', 'dog.2059.jpg', 'dog.2407.jpg', 'dog.2233.jpg', 'dog.2201.jpg', 'dog.2461.jpg', 'dog.2446.jpg', 'dog.2202.jpg', 'dog.2098.jpg', 'dog.2354.jpg', 'dog.2269.jpg', 'dog.2483.jpg', 'dog.2029.jpg', 'dog.2499.jpg', 'dog.2099.jpg', 'dog.2290.jpg', 'dog.2289.jpg', 'dog.2430.jpg', 'dog.2225.jpg', 'dog.2268.jpg', 'dog.2323.jpg', 'dog.2366.jpg', 'dog.2417.jpg', 'dog.2415.jpg', 'dog.2138.jpg', 'dog.2364.jpg', 'dog.2426.jpg', 'dog.2469.jpg', 'dog.2239.jpg', 'dog.2055.jpg', 'dog.2295.jpg', 'dog.2089.jpg', 'dog.2134.jpg', 'dog.2261.jpg', 'dog.2462.jpg', 'dog.2211.jpg', 'dog.2455.jpg', 'dog.2038.jpg', 'dog.2082.jpg', 'dog.2262.jpg', 'dog.2197.jpg', 'dog.2338.jpg', 'dog.2392.jpg', 'dog.2081.jpg', 'dog.2406.jpg', 'dog.2172.jpg', 'dog.2421.jpg', 'dog.2087.jpg', 'dog.2387.jpg', 'dog.2124.jpg', 'dog.2130.jpg', 'dog.2481.jpg', 'dog.2409.jpg', 'dog.2381.jpg', 'dog.2444.jpg', 'dog.2161.jpg', 'dog.2414.jpg', 'dog.2132.jpg', 'dog.2395.jpg', 'dog.2149.jpg', 'dog.2048.jpg', 'dog.2365.jpg', 'dog.2050.jpg', 'dog.2156.jpg', 'dog.2380.jpg', 'dog.2141.jpg', 'dog.2028.jpg', 'dog.2246.jpg', 'dog.2332.jpg', 'dog.2292.jpg', 'dog.2105.jpg', 'dog.2488.jpg', 'dog.2043.jpg', 'dog.2253.jpg', 'dog.2420.jpg', 'dog.2018.jpg', 'dog.2249.jpg', 'dog.2389.jpg', 'dog.2177.jpg', 'dog.2010.jpg']\n" ], [ "import cv2\nimport pandas as pd,numpy as np,pylab as pl\n#n=np.random.randint(0,210,1)[0]\n#print('Label: ',flower_labels[n],names[flower_labels[n]])\ndef show_img(img_dir: str) -> None:\n n=np.random.randint(0,499,1)[0]\n srcname = os.path.abspath(img_dir) +'/'+ os.listdir(img_dir)[n]\n img=cv2.imread(srcname)\n rgb_img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n pl.figure(figsize=(3,3))\n pl.imshow(rgb_img);\n\nshow_img(train_dogs_dir)\nshow_img(train_cats_dir)\n", "_____no_output_____" ] ], [ [ "Set up a pipeline for data augmentation with Keras", "_____no_output_____" ] ], [ [ "image_size = 200 # All images will be resized to 200x200\nbatch_size = 20\n\n# Rescale all images by 1./255 and apply image augmentation\ntrain_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\nvalidation_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n\n# Flow training images in batches of 20 using train_datagen generator\ntrain_generator = train_datagen.flow_from_directory(\n train_dir, # Source directory for the training images\n target_size=(image_size, image_size),\n batch_size=batch_size,\n # Since we use binary_crossentropy loss, we need binary labels\n class_mode='binary')\n\n# Flow validation images in batches of 20 using test_datagen generator\nvalidation_generator = validation_datagen.flow_from_directory(\n validation_dir, # Source directory for the validation images\n target_size=(image_size, image_size),\n batch_size=batch_size,\n class_mode='binary')", "Found 2000 images belonging to 2 classes.\nFound 1000 images belonging to 2 classes.\n" ] ], [ [ "### **Preparing pretrained model**\n\n The VGG16 model pre-trained on the ImageNet dataset", "_____no_output_____" ] ], [ [ "IMG_SHAPE = (image_size, image_size, 3)\n\n# Create the base model from the pre-trained model MobileNet V2\nfeature_extractor = tf.keras.applications.VGG16(input_shape=IMG_SHAPE,\n include_top=False,\n weights='imagenet')", "WARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\nDownloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5\n58892288/58889256 [==============================] - 2s 0us/step\n" ] ], [ [ "## **Feature Extraction without finetuning**\nWe will freeze the layers of the VGG16 and utilize the feature extractor capabilities of this part of the network.", "_____no_output_____" ] ], [ [ "feature_extractor.trainable = False #'''freeze the pretrained graph of the VGG16'''\n\n# Let's take a look at the base model architecture (notice the amount of non-trainable params, what do you expect? And why?)\nfeature_extractor.summary()\n# There are 14,714,688 non-trainable parameters and 0 trainable. We \"froze\" the model to use the already trained parameters", "Model: \"vgg16\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 200, 200, 3)] 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 200, 200, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 200, 200, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 100, 100, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 100, 100, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 100, 100, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 50, 50, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 50, 50, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 50, 50, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 50, 50, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 25, 25, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 25, 25, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 25, 25, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 25, 25, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 12, 12, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 12, 12, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 12, 12, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 12, 12, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 6, 6, 512) 0 \n=================================================================\nTotal params: 14,714,688\nTrainable params: 0\nNon-trainable params: 14,714,688\n_________________________________________________________________\n" ], [ "# tf.keras.utils.plot_model(feature_extractor)", "_____no_output_____" ], [ "#'''add a global 2D average pooling layer here, why do we need this?'''\n'''Global Average Pooling calculates the average output of each feature map in the previous layer. \nGAP layer reduces each h×w feature map to a single number by simply taking the average of all hw values.\nGAP reduces the data significantly (from 6x6x512 to 1x1x512) and prepares the model for the final classification layer.\n''' \n# activation='softmax': constant : val_loss: 7.6246 - val_acc: 0.5000\nmodel = tf.keras.Sequential([\n feature_extractor,\n keras.layers.GlobalAveragePooling2D(),\n keras.layers.Dense(1, activation='sigmoid')\n])\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.01),\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\nmodel.summary()", "WARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/ops/nn_impl.py:183: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.where in 2.0, which has the same broadcast rule as np.where\nModel: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nvgg16 (Model) (None, 6, 6, 512) 14714688 \n_________________________________________________________________\nglobal_average_pooling2d (Gl (None, 512) 0 \n_________________________________________________________________\ndense (Dense) (None, 1) 513 \n=================================================================\nTotal params: 14,715,201\nTrainable params: 513\nNon-trainable params: 14,714,688\n_________________________________________________________________\n" ], [ "# Saving the model\n# Directory where the checkpoints will be saved\ncheckpoint_dir = './training_checkpoints'\n# Name of the checkpoint files\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt_training_vgg16_I\")\n\ncheckpoint_callback=tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_prefix,\n save_weights_only=True)\n\nepochs = 25 \n# the pretrained model ckpt_training_vgg16 has been trained for: \n# 2 epochs reaching a validation accuracy of:0.9610\n# 5 epochs reaching a validation accuracy of:0.9600\n# 10 epochs reaching a validation accuracy of:0.9570\n# 15 epochs reaching a validation accuracy of:0.9620\nsteps_per_epoch = train_generator.n // batch_size\nvalidation_steps = validation_generator.n // batch_size\n\nhistory = model.fit_generator(train_generator,\n steps_per_epoch = steps_per_epoch,\n epochs=epochs,\n validation_data=validation_generator,\n validation_steps=validation_steps,\n callbacks=[checkpoint_callback])", "Epoch 1/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.4738 - acc: 0.7823Epoch 1/25\n100/100 [==============================] - 19s 186ms/step - loss: 0.4721 - acc: 0.7845 - val_loss: 0.3425 - val_acc: 0.8750\nEpoch 2/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.3289 - acc: 0.8636Epoch 1/25\n100/100 [==============================] - 12s 117ms/step - loss: 0.3284 - acc: 0.8645 - val_loss: 0.2816 - val_acc: 0.9010\nEpoch 3/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.2821 - acc: 0.8838Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.2814 - acc: 0.8845 - val_loss: 0.2741 - val_acc: 0.8870\nEpoch 4/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.2588 - acc: 0.8980Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.2604 - acc: 0.8975 - val_loss: 0.2788 - val_acc: 0.8810\nEpoch 5/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.2372 - acc: 0.9020Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.2376 - acc: 0.9010 - val_loss: 0.2580 - val_acc: 0.8910\nEpoch 6/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.2301 - acc: 0.9091Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.2310 - acc: 0.9085 - val_loss: 0.2502 - val_acc: 0.8970\nEpoch 7/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.2240 - acc: 0.9096Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.2238 - acc: 0.9095 - val_loss: 0.2368 - val_acc: 0.8980\nEpoch 8/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.2097 - acc: 0.9207Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.2090 - acc: 0.9215 - val_loss: 0.2488 - val_acc: 0.8980\nEpoch 9/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.2057 - acc: 0.9222Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.2058 - acc: 0.9225 - val_loss: 0.2282 - val_acc: 0.9120\nEpoch 10/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1968 - acc: 0.9227Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1975 - acc: 0.9220 - val_loss: 0.2369 - val_acc: 0.9040\nEpoch 11/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1910 - acc: 0.9283Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.1914 - acc: 0.9280 - val_loss: 0.2483 - val_acc: 0.8980\nEpoch 12/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1911 - acc: 0.9268Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.1907 - acc: 0.9265 - val_loss: 0.2109 - val_acc: 0.9150\nEpoch 13/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1851 - acc: 0.9313Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.1847 - acc: 0.9315 - val_loss: 0.2168 - val_acc: 0.9120\nEpoch 14/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1826 - acc: 0.9303Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.1832 - acc: 0.9305 - val_loss: 0.2903 - val_acc: 0.8760\nEpoch 15/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1767 - acc: 0.9288Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1777 - acc: 0.9280 - val_loss: 0.2212 - val_acc: 0.9110\nEpoch 16/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1709 - acc: 0.9348Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1703 - acc: 0.9350 - val_loss: 0.2136 - val_acc: 0.9190\nEpoch 17/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1689 - acc: 0.9318Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.1715 - acc: 0.9315 - val_loss: 0.2365 - val_acc: 0.9010\nEpoch 18/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1670 - acc: 0.9348Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1665 - acc: 0.9345 - val_loss: 0.2111 - val_acc: 0.9190\nEpoch 19/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1650 - acc: 0.9404Epoch 1/25\n100/100 [==============================] - 12s 120ms/step - loss: 0.1654 - acc: 0.9395 - val_loss: 0.2138 - val_acc: 0.9150\nEpoch 20/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1642 - acc: 0.9348Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1639 - acc: 0.9350 - val_loss: 0.2250 - val_acc: 0.9050\nEpoch 21/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1574 - acc: 0.9424Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1569 - acc: 0.9430 - val_loss: 0.2089 - val_acc: 0.9120\nEpoch 22/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1567 - acc: 0.9374Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1567 - acc: 0.9375 - val_loss: 0.2107 - val_acc: 0.9160\nEpoch 23/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1553 - acc: 0.9434Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1551 - acc: 0.9435 - val_loss: 0.2074 - val_acc: 0.9160\nEpoch 24/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1583 - acc: 0.9394Epoch 1/25\n100/100 [==============================] - 12s 118ms/step - loss: 0.1585 - acc: 0.9395 - val_loss: 0.2233 - val_acc: 0.9170\nEpoch 25/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.1524 - acc: 0.9419Epoch 1/25\n100/100 [==============================] - 12s 119ms/step - loss: 0.1520 - acc: 0.9420 - val_loss: 0.2085 - val_acc: 0.9150\n" ], [ "def plot_learning_curve(\n title: str, x: int, y: int, y_test: int, ylim: float = 0.6\n) -> None:\n plt.figure()\n plt.title(title)\n axes = plt.gca()\n axes.set_ylim([ylim, 1])\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Accuracy\")\n train_sizes = x\n train_scores = y\n test_scores = y_test\n\n plt.grid()\n\n plt.plot(\n train_sizes,\n train_scores,\n \"o-\",\n color=(177 / 255, 6 / 255, 58 / 255),\n label=\"Training accuracy\",\n )\n plt.plot(\n train_sizes,\n test_scores,\n \"o-\",\n color=(246 / 255, 168 / 255, 0),\n label=\"Validation accuracy\",\n )\n\n plt.legend(loc=\"best\")\n\n\ndef plot_history(title: str, history: \"History\", ylim: float = 0.6) -> None:\n y = history.history[\"acc\"]\n y_test = history.history[\"val_acc\"]\n plot_learning_curve(title, np.arange(1, 1 + len(y)), y, y_test, ylim)\n\nplot_history('Pretrain model performance', history, 0)", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ], [ "## **Feature Extraction with finetuning**\nWe will freeze the layers of the VGG16 and utilize the feature extractor capabilities of this part of the network.", "_____no_output_____" ] ], [ [ "feature_extractor.trainable = True\n\nfeature_extractor.summary()", "Model: \"vgg16\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 200, 200, 3)] 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 200, 200, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 200, 200, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 100, 100, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 100, 100, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 100, 100, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 50, 50, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 50, 50, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 50, 50, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 50, 50, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 25, 25, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 25, 25, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 25, 25, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 25, 25, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 12, 12, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 12, 12, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 12, 12, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 12, 12, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 6, 6, 512) 0 \n=================================================================\nTotal params: 14,714,688\nTrainable params: 14,714,688\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "#add a global 2D average pooling layer\n\nmodel = tf.keras.Sequential([\n feature_extractor,\n keras.layers.GlobalAveragePooling2D(),\n keras.layers.Dense(1, activation='sigmoid')\n])\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.01),\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\nmodel.summary()", "Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nvgg16 (Model) (None, 6, 6, 512) 14714688 \n_________________________________________________________________\nglobal_average_pooling2d_2 ( (None, 512) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 513 \n=================================================================\nTotal params: 14,715,201\nTrainable params: 14,715,201\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "# Saving the model\n# Directory where the checkpoints will be saved\ncheckpoint_dir = './training_checkpoints'\n# Name of the checkpoint files\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt_training_vgg16_II\")\n\ncheckpoint_callback=tf.keras.callbacks.ModelCheckpoint(\n filepath=checkpoint_prefix,\n save_weights_only=True)\n\nepochs = 25 \n# the pretrained model ckpt_training_vgg16 has been trained for: \n# 2 epochs reaching a validation accuracy of:0.9610\n# 5 epochs reaching a validation accuracy of:0.9600\n# 10 epochs reaching a validation accuracy of:0.9570\n# 15 epochs reaching a validation accuracy of:0.9620\nsteps_per_epoch = train_generator.n // batch_size\nvalidation_steps = validation_generator.n // batch_size\n\nhistory_II = model.fit_generator(train_generator,\n steps_per_epoch = steps_per_epoch,\n epochs=epochs,\n validation_data=validation_generator,\n validation_steps=validation_steps,\n callbacks=[checkpoint_callback])\n\n", "Epoch 1/25\n 99/100 [============================>.] - ETA: 0s - loss: 32002068240540.2930 - acc: 0.5000Epoch 1/25\n100/100 [==============================] - 22s 221ms/step - loss: 31682047558134.9141 - acc: 0.5000 - val_loss: 4.9745 - val_acc: 0.5000\nEpoch 2/25\n 99/100 [============================>.] - ETA: 0s - loss: 2.0210 - acc: 0.5020Epoch 1/25\n100/100 [==============================] - 19s 195ms/step - loss: 2.0078 - acc: 0.5030 - val_loss: 0.6932 - val_acc: 0.5000\nEpoch 3/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.9633 - acc: 0.5182Epoch 1/25\n100/100 [==============================] - 20s 195ms/step - loss: 0.9605 - acc: 0.5190 - val_loss: 0.7008 - val_acc: 0.5000\nEpoch 4/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7001 - acc: 0.4965Epoch 1/25\n100/100 [==============================] - 19s 194ms/step - loss: 0.7001 - acc: 0.4960 - val_loss: 0.6938 - val_acc: 0.5000\nEpoch 5/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7024 - acc: 0.4904Epoch 1/25\n100/100 [==============================] - 19s 194ms/step - loss: 0.7023 - acc: 0.4910 - val_loss: 0.6958 - val_acc: 0.5000\nEpoch 6/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7021 - acc: 0.4904Epoch 1/25\n100/100 [==============================] - 19s 193ms/step - loss: 0.7022 - acc: 0.4900 - val_loss: 0.6936 - val_acc: 0.5000\nEpoch 7/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7055 - acc: 0.5005Epoch 1/25\n100/100 [==============================] - 19s 193ms/step - loss: 0.7085 - acc: 0.4980 - val_loss: 0.7052 - val_acc: 0.5000\nEpoch 8/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7060 - acc: 0.4970Epoch 1/25\n100/100 [==============================] - 19s 192ms/step - loss: 0.7060 - acc: 0.4960 - val_loss: 0.6953 - val_acc: 0.5000\nEpoch 9/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7030 - acc: 0.4909Epoch 1/25\n100/100 [==============================] - 19s 194ms/step - loss: 0.7033 - acc: 0.4910 - val_loss: 0.7033 - val_acc: 0.5000\nEpoch 10/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7006 - acc: 0.4960Epoch 1/25\n100/100 [==============================] - 19s 194ms/step - loss: 0.7005 - acc: 0.4970 - val_loss: 0.6993 - val_acc: 0.5000\nEpoch 11/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7020 - acc: 0.4854Epoch 1/25\n100/100 [==============================] - 19s 193ms/step - loss: 0.7018 - acc: 0.4860 - val_loss: 0.6960 - val_acc: 0.5000\nEpoch 12/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6986 - acc: 0.4965Epoch 1/25\n100/100 [==============================] - 19s 193ms/step - loss: 0.6986 - acc: 0.4960 - val_loss: 0.6941 - val_acc: 0.5000\nEpoch 13/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.7000 - acc: 0.4702Epoch 1/25\n100/100 [==============================] - 19s 192ms/step - loss: 0.6998 - acc: 0.4720 - val_loss: 0.7000 - val_acc: 0.5000\nEpoch 14/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6984 - acc: 0.4949Epoch 1/25\n100/100 [==============================] - 19s 193ms/step - loss: 0.6987 - acc: 0.4940 - val_loss: 0.6937 - val_acc: 0.5000\nEpoch 15/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6984 - acc: 0.4949Epoch 1/25\n100/100 [==============================] - 19s 190ms/step - loss: 0.6985 - acc: 0.4950 - val_loss: 0.6990 - val_acc: 0.5000\nEpoch 16/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6957 - acc: 0.5086Epoch 1/25\n100/100 [==============================] - 19s 190ms/step - loss: 0.6957 - acc: 0.5080 - val_loss: 0.6935 - val_acc: 0.5000\nEpoch 17/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6983 - acc: 0.4717Epoch 1/25\n100/100 [==============================] - 19s 191ms/step - loss: 0.6982 - acc: 0.4720 - val_loss: 0.6933 - val_acc: 0.5000\nEpoch 18/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6968 - acc: 0.5035Epoch 1/25\n100/100 [==============================] - 19s 190ms/step - loss: 0.6969 - acc: 0.5020 - val_loss: 0.6934 - val_acc: 0.5000\nEpoch 19/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6976 - acc: 0.4949Epoch 1/25\n100/100 [==============================] - 19s 190ms/step - loss: 0.6974 - acc: 0.4960 - val_loss: 0.7013 - val_acc: 0.5000\nEpoch 20/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6968 - acc: 0.4939Epoch 1/25\n100/100 [==============================] - 19s 190ms/step - loss: 0.6968 - acc: 0.4930 - val_loss: 0.6949 - val_acc: 0.5000\nEpoch 21/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6982 - acc: 0.4768Epoch 1/25\n100/100 [==============================] - 19s 192ms/step - loss: 0.6980 - acc: 0.4780 - val_loss: 0.6992 - val_acc: 0.5000\nEpoch 22/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6981 - acc: 0.4884Epoch 1/25\n100/100 [==============================] - 19s 192ms/step - loss: 0.6981 - acc: 0.4900 - val_loss: 0.6955 - val_acc: 0.5000\nEpoch 23/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6976 - acc: 0.4838Epoch 1/25\n100/100 [==============================] - 19s 191ms/step - loss: 0.6976 - acc: 0.4830 - val_loss: 0.6935 - val_acc: 0.5000\nEpoch 24/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6973 - acc: 0.4854Epoch 1/25\n100/100 [==============================] - 19s 191ms/step - loss: 0.6973 - acc: 0.4850 - val_loss: 0.6933 - val_acc: 0.5000\nEpoch 25/25\n 99/100 [============================>.] - ETA: 0s - loss: 0.6930 - acc: 0.5293Epoch 1/25\n100/100 [==============================] - 19s 192ms/step - loss: 0.6934 - acc: 0.5280 - val_loss: 0.6946 - val_acc: 0.5000\n" ], [ "plot_history('Pretrain model performance', history_II, 0)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ] ]
cb27a43ac0e64236076061c4dd52ce1cc7ffa12b
111,423
ipynb
Jupyter Notebook
mwdsbe/.ipynb_checkpoints/general_funds-checkpoint.ipynb
BinnyDaBin/MWDSBE
aa0de50f2289e47f7c2e9134334b23c3b5594f0c
[ "MIT" ]
null
null
null
mwdsbe/.ipynb_checkpoints/general_funds-checkpoint.ipynb
BinnyDaBin/MWDSBE
aa0de50f2289e47f7c2e9134334b23c3b5594f0c
[ "MIT" ]
10
2021-03-10T01:06:45.000Z
2022-02-26T21:02:40.000Z
mwdsbe/.ipynb_checkpoints/general_funds-checkpoint.ipynb
BinnyDaBin/MWDSBE
aa0de50f2289e47f7c2e9134334b23c3b5594f0c
[ "MIT" ]
null
null
null
54.16772
31,388
0.569891
[ [ [ "# General Funds", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nimport mwdsbe\nimport schuylkill as skool\nimport time", "_____no_output_____" ] ], [ [ "## Data", "_____no_output_____" ] ], [ [ "registry = mwdsbe.load_registry() # geopandas df", "_____no_output_____" ], [ "gf = pd.read_excel(r'C:\\Users\\dabinlee\\Documents\\GitHub\\mwdsbe_binny\\MWDSBE\\mwdsbe\\data\\cwedp_37_report.xlsx', sheet_name='general_funds')", "_____no_output_____" ], [ "city_payments = pd.read_excel(r'C:\\Users\\dabinlee\\Documents\\GitHub\\mwdsbe_binny\\MWDSBE\\analysis\\data\\payments\\city_payments_detailed_2017.xlsx')", "_____no_output_____" ], [ "gf.head()", "_____no_output_____" ], [ "len(gf)", "_____no_output_____" ], [ "gf = gf.loc[gf['MAJ_CLASS'] != 1]", "_____no_output_____" ], [ "len(gf)", "_____no_output_____" ], [ "gf = gf.loc[gf['VEND_NAME'].dropna().index]", "_____no_output_____" ], [ "len(gf)", "_____no_output_____" ], [ "gf.head()", "_____no_output_____" ] ], [ [ "## General Funds by Departments", "_____no_output_____" ] ], [ [ "simple_cp = city_payments[['dept', 'department_title']]", "_____no_output_____" ], [ "# simple_cp['department_title'] = simple_cp['department_title'].str.split(\" \", 1, expand=True)[1]", "_____no_output_____" ], [ "simple_cp = simple_cp.groupby(['dept', 'department_title']).size().to_frame('N').reset_index()", "_____no_output_____" ], [ "simple_cp", "_____no_output_____" ], [ "gf = gf.merge(simple_cp, how='left', left_on='DEPT', right_on='dept').drop('dept', axis=1)", "_____no_output_____" ], [ "gf_dept = gf.groupby(['DEPT','department_title'])['AMT'].sum().to_frame('AMT').reset_index()", "_____no_output_____" ], [ "top_10 = gf_dept.sort_values(by='AMT', ascending=False)[:10]", "_____no_output_____" ], [ "sns.set(style=\"whitegrid\")\nax = sns.barplot(x=\"AMT\", y=\"department_title\", data=top_10)\nax.set(xlabel='Fund Amount', ylabel='Department')\nplt.show()", "_____no_output_____" ] ], [ [ "## Vendors under Director of Finance", "_____no_output_____" ] ], [ [ "finance = gf.loc[gf['department_title'] == '35 DIRECTOR OF FINANCE']", "_____no_output_____" ], [ "len(finance)", "_____no_output_____" ], [ "len(finance['VEND_NAME'].unique())", "_____no_output_____" ], [ "finance['VEND_NAME'].unique()", "_____no_output_____" ] ], [ [ "## Unique Vendors of all general funds", "_____no_output_____" ] ], [ [ "len(gf['VEND_NAME'].unique()) # out of 243375", "_____no_output_____" ], [ "print('Percentage of unique vendors:', 9543 / 243375 * 100, '%')", "Percentage of unique vendors: 3.921109399075501 %\n" ] ], [ [ "## Matching: Fuzz95 + TF-IDF85 ", "_____no_output_____" ] ], [ [ "# clean data\nignore_words = ['inc', 'group', 'llc', 'corp', 'pc', 'incorporated', 'ltd', 'co', 'associates', 'services', 'company', 'enterprises', 'enterprise', 'service', 'corporation']\ncleaned_registry = skool.clean_strings(registry, ['company_name', 'dba_name'], True, ignore_words)\ncleaned_gf = skool.clean_strings(gf, ['VEND_NAME'], True, ignore_words)\n\ncleaned_registry = cleaned_registry.dropna(subset=['company_name'])\ncleaned_gf = cleaned_gf.dropna(subset=['VEND_NAME'])", "_____no_output_____" ], [ "cleaned_gf.to_excel(r'C:\\Users\\dabinlee\\Documents\\GitHub\\mwdsbe_binny\\MWDSBE\\analysis\\data\\general_funds\\cleaned_gf.xlsx', header=True)", "_____no_output_____" ], [ "len(cleaned_gf)", "_____no_output_____" ], [ "# Fuzz 95 + TF-IDF 85 with max_matches = 1\nt1 = time.time()\nmerged = (\n skool.fuzzy_merge(cleaned_registry, cleaned_gf, left_on=\"company_name\", right_on=\"VEND_NAME\", score_cutoff=95)\n .pipe(skool.fuzzy_merge, cleaned_registry, cleaned_gf, left_on=\"dba_name\", right_on=\"VEND_NAME\", score_cutoff=95)\n .pipe(skool.tf_idf_merge, cleaned_registry, cleaned_gf, left_on=\"company_name\", right_on=\"VEND_NAME\", score_cutoff=85)\n .pipe(skool.tf_idf_merge, cleaned_registry, cleaned_gf, left_on=\"dba_name\", right_on=\"VEND_NAME\", score_cutoff=85)\n)\nt = time.time() - t1", "_____no_output_____" ], [ "print('Execution time:', t/60, 'min')", "Execution time: 22.8173419157664 min\n" ], [ "matched = merged.dropna(subset=['VEND_NAME'])", "_____no_output_____" ], [ "print('Matching:', len(matched), 'out of', len(cleaned_registry))", "Matching: 136 out of 3119\n" ], [ "unique_vendors = matched['VEND_NAME'].tolist()", "_____no_output_____" ], [ "full_matched = cleaned_gf.loc[cleaned_gf['VEND_NAME'].apply(lambda x : x in unique_vendors)]", "_____no_output_____" ] ] ]
[ "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb27a7ebc9f9b90ccc6a21e9c36c6061b8f5f910
8,118
ipynb
Jupyter Notebook
data/vienna_catalog/main.ipynb
tech4germany/bam-inclusify
ddc5ca927527ec42d7b2af64750367db3e2d4f09
[ "MIT" ]
11
2021-11-04T14:16:04.000Z
2022-03-30T10:13:32.000Z
data/vienna_catalog/main.ipynb
tech4germany/bam-inclusify
ddc5ca927527ec42d7b2af64750367db3e2d4f09
[ "MIT" ]
null
null
null
data/vienna_catalog/main.ipynb
tech4germany/bam-inclusify
ddc5ca927527ec42d7b2af64750367db3e2d4f09
[ "MIT" ]
2
2021-11-29T21:45:56.000Z
2022-01-04T12:51:24.000Z
33
366
0.493348
[ [ [ "This notebook downloads and processes the gender data from the Vienna catalog. The data comes from a [gendering add-in for Microsoft Word 2010](https://web.archive.org/web/20210629142645/https:/archive.codeplex.com/?p=gendering) that has been developed by Microsoft. The data includes two styles (double notation and inner I).\n\nSome more manual normalization would be necessary to make this data useful for our project. For example, the inner I and double notation forms can both be derived from just the female form (in addition to the male form, which is already given by the replaced word), and entries for the same word but with different cases could be reduced to a single entry. \n\nThe data is highly relevant for this project, because it has been created in a government context as well, and includes many government-specific words.", "_____no_output_____" ] ], [ [ "import io\nimport pandas as pd\nimport re\nimport requests\nfrom typing import *\nimport sys\n\nsys.path.insert(0, \"..\")\nfrom helpers import add_to_dict, log\nfrom helpers_csv import csvs_to_list, dict_to_csvs", "_____no_output_____" ], [ "csv = requests.get(\n \"https://www.data.gv.at/katalog/dataset/15d6ede8-f128-4fcd-aa3a-4479e828f477/resource/804f6db1-add7-4480-b4d0-e52e61c48534/download/worttabelle.csv\"\n).content\ntext = re.sub(\";;\\r\\n\", \"\\n\", csv.decode(\"utf-8\"))\ndf = pd.read_csv(io.StringIO(text))\ndf.head()", "_____no_output_____" ], [ "df.to_csv(\n \"vienna_catalog_raw.csv\",\n index=False,\n)", "_____no_output_____" ] ], [ [ "We change Binnen-I to gender star to have one simple style, and we try to attribute singular and plural as well as possible:", "_____no_output_____" ] ], [ [ "dic: Dict[str, Dict[str, List[str]]] = {\"sg\": {}, \"pl\": {}}\nfor (_, _, ungendered, gendered, binnenI) in df.to_records():\n if binnenI == \"Y\":\n gendered = re.sub(r\"([a-zäöüß])I\", r\"\\1*i\", gendered)\n if type(gendered) == str: # skip ill-formatted rows\n if (\n re.findall(r\"[iI]n( .*)?$\", gendered) != []\n or re.findall(r\" bzw\\.? \", gendered) != []\n ):\n add_to_dict(ungendered, [gendered], dic[\"sg\"])\n elif (\n re.findall(r\"[iI]nnen( .*)?$\", gendered) != []\n or re.findall(r\" und \", gendered) != []\n ):\n add_to_dict(ungendered, [gendered], dic[\"pl\"])\n else:\n add_to_dict(ungendered, [gendered], dic[\"sg\"])\n add_to_dict(ungendered, [gendered], dic[\"pl\"])", "_____no_output_____" ], [ "dict_to_csvs(dic, \"vienna_catalog\")", "_____no_output_____" ] ], [ [ "We can read this CSV back to a Python dictionary with the following method:", "_____no_output_____" ] ], [ [ "list_ = csvs_to_list(\"vienna_catalog\")\nlist_[:5]", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb27b178ce5d7294cda1d6369a9def2ea962dbe4
554
ipynb
Jupyter Notebook
desy/propagate_FAST/Untitled.ipynb
twguest/FELPy
90ed49cc4bddd2188f3284168152d043144ae1fb
[ "Apache-2.0" ]
null
null
null
desy/propagate_FAST/Untitled.ipynb
twguest/FELPy
90ed49cc4bddd2188f3284168152d043144ae1fb
[ "Apache-2.0" ]
null
null
null
desy/propagate_FAST/Untitled.ipynb
twguest/FELPy
90ed49cc4bddd2188f3284168152d043144ae1fb
[ "Apache-2.0" ]
null
null
null
16.787879
34
0.527076
[]
[]
[]
cb27b71eb93bd952e19404557d8d1e2dc1307997
18,994
ipynb
Jupyter Notebook
cpamb_create_map.ipynb
michelmetran/sp_policiaambiental
58554b05fa3e7e16b8ffabaf455fc92a1705962e
[ "MIT" ]
null
null
null
cpamb_create_map.ipynb
michelmetran/sp_policiaambiental
58554b05fa3e7e16b8ffabaf455fc92a1705962e
[ "MIT" ]
null
null
null
cpamb_create_map.ipynb
michelmetran/sp_policiaambiental
58554b05fa3e7e16b8ffabaf455fc92a1705962e
[ "MIT" ]
null
null
null
30.149206
129
0.464568
[ [ [ "# Introdução", "_____no_output_____" ] ], [ [ "import os\nimport re\nimport time\nimport json\nimport folium\nimport random\nimport requests\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport geopandas as gpd\nfrom folium import plugins\nfrom osgeo import gdal, osr\nfrom bs4 import BeautifulSoup\nfrom tqdm.notebook import trange, tqdm", "_____no_output_____" ] ], [ [ "<br>\n\n# Join Data", "_____no_output_____" ] ], [ [ "# Lê o arquivo csv com o nome dos municípios\ndf = pd.read_csv(\n 'https://raw.githubusercontent.com/michelmetran/sp_policiaambiental/main/data/tabs/tab_municipio_cpamb.csv',\n)\n\n# Lê o arquivo csv com o nome dos municípios\ngdf = gpd.read_file(\n 'https://raw.githubusercontent.com/michelmetran/sp/main/data/shps/sp_250k_wgs84.geojson',\n)\ngdf.drop(['municipio_nome'], axis=1, inplace=True)\ngdf['id_municipio'] = gdf['id_municipio'].astype(int)\ngdf['geometry'] = gdf.simplify(0.0015)\n\n# Merge\ngdf = gdf.merge(\n df,\n on='id_municipio',\n how='left'\n)\n\n# Results\ngdf.head()", "_____no_output_____" ], [ "# Batalhão\ngdf['id_batalhao_desc'] = gdf['id_batalhao'].apply(lambda x: '{}º Batalhão'.format(x))\n\n# Companhia\ngdf['id_cia_desc'] = gdf['id_cia'].apply(lambda x: '{}ª Companhia do '.format(x))\ngdf['id_cia_desc'] = gdf[['id_cia_desc', 'id_batalhao_desc']].apply(lambda x: ''.join(x), axis=1)\n\n# Pelotão\ngdf['id_pelotao_desc'] = gdf['id_pelotao'].apply(lambda x: '{}º Pelotão da '.format(x))\ngdf['id_pelotao_desc'] = gdf[['id_pelotao_desc', 'id_cia_desc']].apply(lambda x: ''.join(x), axis=1)\n\n# Results\ngdf.head()", "_____no_output_____" ], [ "set(gdf['id_cia_desc'])", "_____no_output_____" ] ], [ [ "<br>\n\n## Create pop up's column", "_____no_output_____" ] ], [ [ "# Add Field\ndef popup_html_batalhao(row):\n #tel = str(row['telefone']).replace('-', '').replace(')', '').replace('(', '+55').replace(' ', '')\n #fax = str(row['fax']).replace('-', '').replace(')', '').replace('(', '+55').replace(' ', '')\n \n html = \"\"\"\n <div>\n <p><b>{}</b> pertence ao:\n <h5><b>{}</b></h5></p>\n </div>\n \"\"\".format(\n '' if pd.isnull(row['municipio_nome']) else '{}'.format(row['municipio_nome']),\n '' if pd.isnull(row['id_batalhao_desc']) else '{}'.format(row['id_batalhao_desc']),\n )\n \n html = html.replace('\\n','')\n html = re.sub('\\s\\s+' , ' ', html) # Remove Espaços no meio\n html = html.strip()\n return html", "_____no_output_____" ], [ "# Add Field\ndef popup_html_cia(row):\n #tel = str(row['telefone']).replace('-', '').replace(')', '').replace('(', '+55').replace(' ', '')\n #fax = str(row['fax']).replace('-', '').replace(')', '').replace('(', '+55').replace(' ', '')\n \n html = \"\"\"\n <div>\n <p><b>{}</b> pertence ao:\n <h5><b>{}</b></h5></p>\n </div>\n \"\"\".format(\n '' if pd.isnull(row['municipio_nome']) else '{}'.format(row['municipio_nome']),\n '' if pd.isnull(row['id_cia_desc']) else '{}'.format(row['id_cia_desc']),\n )\n \n html = html.replace('\\n','')\n html = re.sub('\\s\\s+' , ' ', html) # Remove Espaços no meio\n html = html.strip()\n return html", "_____no_output_____" ], [ "# Add Field\ndef popup_html_pelotao(row):\n #tel = str(row['telefone']).replace('-', '').replace(')', '').replace('(', '+55').replace(' ', '')\n #fax = str(row['fax']).replace('-', '').replace(')', '').replace('(', '+55').replace(' ', '')\n \n html = \"\"\"\n <div>\n <p><b>{}</b> pertence ao:\n <h5><b>{}</b></h5></p>\n </div>\n \"\"\".format(\n '' if pd.isnull(row['municipio_nome']) else '{}'.format(row['municipio_nome']),\n '' if pd.isnull(row['id_pelotao_desc']) else '{}'.format(row['id_pelotao_desc']),\n )\n \n html = html.replace('\\n','')\n html = re.sub('\\s\\s+' , ' ', html) # Remove Espaços no meio\n html = html.strip()\n return html", "_____no_output_____" ], [ "# <p><b>Sede:</b><br>\n# {}{}{}<br>\n# {}\n# {}\n# {}</p>\n# <p><b>Contatos:</b><br>\n# {}\n# {}\n# {}</p>\n# <p>{}</p>\n\n\n\n\n# '' if pd.isnull(row['agencia']) else '{}'.format(row['agencia']),\n# '' if pd.isnull(row['endereco']) else '{}'.format(row['endereco']),\n# '' if pd.isnull(row['numero']) else ', {}'.format(row['numero']),\n# '' if pd.isnull(row['complemento']) else ' - {}'.format(row['complemento']),\n# '' if pd.isnull(row['bairro']) else 'Bairro: {}<br>'.format(row['bairro']),\n# '' if pd.isnull(row['municipio_sede']) else 'Município: {}<br>'.format(row['municipio_sede']),\n# '' if pd.isnull(row['cep']) else 'CEP: {}<br>'.format(row['cep']),\n# '' if pd.isnull(row['telefone']) else 'Telefone: <a href=\"tel:{}\">{}</a><br>'.format(tel, row['telefone']),\n# '' if pd.isnull(row['fax']) else 'Fax: <a href=\"tel:{}\">{}</a><br>'.format(fax, row['fax']),\n# '' if pd.isnull(row['email']) else 'E-mail: <a href=\"mailto:{}\">{}</a>'.format(row['email'], row['email']),\n# '' if pd.isnull(row['email']) else '<a href=\"{}\" target=\"_blank\">Conferir Dados</a>'.format(row['url']),", "_____no_output_____" ], [ "# Calculate PopUps\ngdf['popup_batalhao'] = gdf.apply(popup_html_batalhao, axis=1)\ngdf['popup_cia'] = gdf.apply(popup_html_cia, axis=1)\ngdf['popup_pelotao'] = gdf.apply(popup_html_pelotao, axis=1)", "_____no_output_____" ] ], [ [ "<br>\n\n## Adjust Table", "_____no_output_____" ] ], [ [ "# Delete Columns\nprint(gdf.columns)\n\n# gdf.drop([\n# 'id_municipio', 'endereco', 'numero', 'bairro',\n# 'municipio_sede', 'cep', 'telefone', 'fax',\n# 'complemento', 'url', 'email',], axis=1, inplace=True)", "_____no_output_____" ], [ "# Save geojson\ngdf.to_file(\n os.path.join('data', 'shps', 'sp_cpamb.geojson'),\n driver='GeoJSON',\n encoding='utf-8'\n)\n\n# Results\ngdf.head()", "_____no_output_____" ] ], [ [ "## Get Centroid", "_____no_output_____" ] ], [ [ "def get_centroid(gdf):\n gdf['apenasparacentroid'] = 35\n gdf_dissolve = gdf.dissolve(by='apenasparacentroid')\n gdf_centroid = gdf_dissolve.representative_point()\n gdf = gdf.drop('apenasparacentroid', axis=1)\n return [float(gdf_centroid.y), float(gdf_centroid.x)]", "_____no_output_____" ], [ "list_centroid = get_centroid(gdf)\nlist_centroid", "_____no_output_____" ] ], [ [ "## Folium", "_____no_output_____" ] ], [ [ "def map_bomb(input_geojson, bbox):\n gdf = gpd.read_file(input_geojson)\n \n # Create Map\n m = folium.Map(\n location=[-22.545968889465207, -49.56185387118866],\n zoom_start=6,\n min_zoom=6,\n max_zoom=11,\n max_bounds=True,\n min_lon = bbox['min_lon']*(101/100),\n max_lon = bbox['max_lon']*(99/100), \n min_lat = bbox['min_lat']*(101/100),\n max_lat = bbox['max_lat']*(99/100),\n #zoom_delta=0.1,\n tiles=None,\n )\n folium.TileLayer(\n 'cartodbpositron',\n name='BaseMap',\n control=False,\n ).add_to(m)\n \n # LAYER 1: Batalhões\n # Column with category\n col_categories1 = 'id_batalhao_desc'\n \n # Set palette\n palette_polygon = 'Paired'\n\n # Get list of unique values\n categories = set(gdf[col_categories1])\n categories = list(categories)\n categories.sort()\n\n # See the palette chosed\n pal = sns.color_palette(palette_polygon, n_colors=len(categories))\n\n # Set dictionary\n color_polygon = dict(zip(categories, pal.as_hex())) \n color_polygon['1º Batalhão'] = '#ff4d4d'\n #color_polygon['2º Batalhão'] = '#4da6ff'\n color_polygon['3º Batalhão'] = '#00b300'\n color_polygon['4º Batalhão'] = '#ffcc99'\n color_polygon1 = color_polygon\n \n # Geo\n folium.GeoJson(\n gdf,\n name='Batalhões',\n smooth_factor=1.0,\n zoom_on_click=False,\n embed=False,\n show=False,\n style_function=lambda x: {\n 'fillColor': color_polygon1[x['properties'][col_categories1]],\n 'color': color_polygon1[x['properties'][col_categories1]],\n 'weight': 1,\n 'fillOpacity': 0.3,\n },\n highlight_function=lambda x: {\n 'weight': 3,\n 'fillOpacity': 0.6,\n },\n tooltip=folium.features.GeoJsonTooltip(\n fields=['municipio_nome', 'id_batalhao_desc'],\n aliases=['Munícipio', 'Batalhão'],\n sticky=True,\n opacity=0.9,\n direction='right',\n ),\n popup=folium.GeoJsonPopup(\n ['popup_batalhao'],\n parse_html=False,\n max_width='400',\n show=False,\n labels=False,\n sticky=True, \n ) \n ).add_to(m)\n \n # LAYER 2: Companhia\n # Column with category\n col_categories2 = 'id_cia_desc'\n \n # Set palette\n palette_polygon = 'Paired'\n\n # Get list of unique values\n categories = set(gdf[col_categories2])\n categories = list(categories)\n categories.sort()\n\n # See the palette chosed\n pal = sns.color_palette(palette_polygon, n_colors=len(categories))\n\n # Set dictionary\n color_polygon = dict(zip(categories, pal.as_hex()))\n color_polygon2 = color_polygon\n \n # Geo\n folium.GeoJson(\n gdf,\n name='Companhias',\n smooth_factor=1.0,\n zoom_on_click=False,\n embed=False,\n show=False,\n style_function=lambda x: {\n 'fillColor': color_polygon2[x['properties'][col_categories2]],\n 'color': color_polygon2[x['properties'][col_categories2]],\n 'weight': 1,\n 'fillOpacity': 0.3,\n },\n highlight_function=lambda x: {\n 'weight': 3,\n 'fillOpacity': 0.6,\n },\n tooltip=folium.features.GeoJsonTooltip(\n fields=['municipio_nome', 'id_cia_desc'],\n aliases=['Munícipio', 'Companhia'],\n sticky=True,\n opacity=0.9,\n direction='right',\n ),\n popup=folium.GeoJsonPopup(\n ['popup_cia'],\n parse_html=False,\n max_width='400',\n show=False,\n labels=False,\n sticky=True, \n )\n ).add_to(m)\n \n # LAYER 3: Pelotão\n # Column with category\n col_categories3 = 'id_pelotao_desc'\n \n # Set palette\n palette_polygon = 'Paired'\n\n # Get list of unique values\n categories = set(gdf[col_categories3])\n categories = list(categories)\n categories.sort()\n\n # See the palette chosed\n pal = sns.color_palette(palette_polygon, n_colors=len(categories))\n\n # Set dictionary\n color_polygon = dict(zip(categories, pal.as_hex()))\n color_polygon3 = color_polygon\n \n # Geo\n folium.GeoJson(\n gdf,\n name='Pelotão',\n smooth_factor=1.0,\n zoom_on_click=False,\n embed=False,\n show=True,\n style_function=lambda x: {\n 'fillColor': color_polygon3[x['properties'][col_categories3]],\n 'color': color_polygon3[x['properties'][col_categories3]],\n 'weight': 1,\n 'fillOpacity': 0.3,\n },\n highlight_function=lambda x: {\n 'weight': 3,\n 'fillOpacity': 0.6,\n },\n tooltip=folium.features.GeoJsonTooltip(\n fields=['municipio_nome', 'id_pelotao_desc'],\n aliases=['Munícipio', 'Pelotão'],\n sticky=True,\n opacity=0.9,\n direction='right',\n ),\n popup=folium.GeoJsonPopup(\n ['popup_pelotao'],\n parse_html=False,\n max_width='400',\n show=False,\n labels=False,\n sticky=True, \n )\n ).add_to(m)\n \n # Plugins\n m.fit_bounds(m.get_bounds())\n plugins.Fullscreen(\n position='topleft',\n title='Clique para Maximizar',\n title_cancel='Mininizar',\n ).add_to(m)\n folium.LayerControl('topright', collapsed=False).add_to(m)\n return m", "_____no_output_____" ], [ "# Map without Bounds\nbbox = {\n 'max_lat': 0,\n 'max_lon': 0,\n 'min_lat': 0,\n 'min_lon': 0,\n}\nm = map_bomb(os.path.join('data', 'shps', 'sp_cpamb.geojson'), bbox)\n\n# Map with Bounds\nbbox = {\n 'max_lat': m.get_bounds()[1][0],\n 'min_lat': m.get_bounds()[0][0],\n 'max_lon': m.get_bounds()[1][1],\n 'min_lon': m.get_bounds()[0][1],\n}\nm = map_bomb(os.path.join('data', 'shps', 'sp_cpamb.geojson'), bbox)\n\n# Results\nprint(bbox)\nm", "_____no_output_____" ] ], [ [ "<br>\n\n# Save Map", "_____no_output_____" ] ], [ [ "os.makedirs('maps', exist_ok=True)\nm.save(os.path.join('maps', 'cpamb_map.html'))\nm.save(os.path.join('..', '..', '..', 'case_django', 'divadmin', 'templates', 'cpamb_map.html'))", "_____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", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
cb27f96be77f74d2c84753b4726c31393bb619a0
26,890
ipynb
Jupyter Notebook
TFD - 3.2 Kontinuumsstroemungen - Navier-Stokes-Gleichungen.ipynb
HsKA-ThermalFluiddynamics/TFD
ae0e9f7fe38f2f33ce1df55c842878fc84318ce3
[ "MIT" ]
null
null
null
TFD - 3.2 Kontinuumsstroemungen - Navier-Stokes-Gleichungen.ipynb
HsKA-ThermalFluiddynamics/TFD
ae0e9f7fe38f2f33ce1df55c842878fc84318ce3
[ "MIT" ]
null
null
null
TFD - 3.2 Kontinuumsstroemungen - Navier-Stokes-Gleichungen.ipynb
HsKA-ThermalFluiddynamics/TFD
ae0e9f7fe38f2f33ce1df55c842878fc84318ce3
[ "MIT" ]
null
null
null
48.979964
686
0.578951
[ [ [ "## Die Navier-Stokes-Gleichungen\n\nDie Navier-Stokes-Gleichungen sind die Grundgleichungen zur Berechnung reibungsbehafteter Strömungen. Obwohl mit dem Begriff im strengen Sinne nur die Impulsgleichung gemeint ist, wird damit in der numerischen Strömungsmechanik gleich der ganze Gleichungssatz aus Kontinuitäts-, Impuls- und Energiegleichung gemeint.\n\nIn diesem Abschnitt soll die aus der Strömungslehre bekannte Herleitung der Gleichungen kurz wiederholt werden. Wir wählen jedoch eine andere Herangehensweise und nutzen die zuvor eingeführte Substantielle Ableitung bzw. die Lagrangesche Betrachtungsweise.\n\nZiel ist es am Ende ein Gleichungssystem für den 2D-Fall zu erhalten.", "_____no_output_____" ], [ "### Kontinuitätsgleichung\n\nAnhand der Kontinuitätsgleichung (Massenerhaltung) soll zunächst eine Herleitung mit Eulerscher Betrachtungsweise und anschließend mit Lagangrescher Betrachtung gezeigt werden.", "_____no_output_____" ], [ "#### Eulersche Betrachtungsweise:\n\nBetrachten wir ein ortsfestes Kontrollvolumen, so entspricht die zeitliche Änderung der Masse im Volumenelement $\\text{d}V$ gerade der Differenz zwischen ein- und ausströmendem Massenstrom.\n\nDer ausströmende Massenstrom unterscheidet sich dabei gerade um die Änderung des Massenstroms über die Abmessung des Kontrollvolumens. Das folgende Bild zeigt das Kontrollvolumen und die ein- und austretenden Massenströme für den 1-D-Fall.\n\n<img src=\"Konti.pdf\" style=\"width: 400px;\"/>\n\nWenn wir die Taylorreihe nach dem ersten Glied abbrechen ergibt sich für die Massenerhaltung (1D):\n\n$$\\frac{\\partial \\dot{m}}{\\partial t} = \\dot{m} - \\left(\\dot{m}+\\frac{\\partial \\dot{m}}{\\partial x}\\text{d}x\\right)$$\n\noder mit $\\text{d}\\dot{m} = \\rho \\text{d}\\dot{V}$ und $\\dot{m} = \\rho v_x \\text{d}y\\text{d}z$:\n\n$$\\frac{\\partial \\rho}{\\partial t} = - \\frac{\\partial \\left(\\rho v_x\\right)}{\\partial x}$$\n\nIm 3D-Fall müssen noch die 4 Massenströme in $y$- und $z$-Richtung berücksichtigt werden, so dass folgende Gleichung für die Kontinuitätsgleichung resultiert:\n\n\n<div class=highlight>\n$$\\frac{\\partial \\rho}{\\partial t} = - \\left[\\frac{\\partial (\\rho v_x)}{\\partial x} + \\frac{\\partial (\\rho v_y)}{\\partial y} + \\frac{\\partial (\\rho v_z)}{\\partial z}\\right]$$\n</div>\n\noder in alternativer Schreibweise:\n\n\n<div class=highlight>\n$$\\frac{\\partial \\rho}{\\partial t} + \\frac{\\partial (\\rho v_i)}{\\partial x_i} = 0 \\quad \\text{bzw.} \\quad \\frac{\\partial \\rho}{\\partial t} + \\text{div}(\\rho \\overrightarrow{v}) = 0 \\quad \\text{bzw.} \\quad \\frac{\\partial \\rho}{\\partial t} + \\nabla\\cdot(\\rho \\overrightarrow{v}) = 0$$\n</div>", "_____no_output_____" ], [ "#### Lagrangesche Betrachtungsweise:\n\nEin mitbewegter Beobachter, der sich mit der Geschwindigkeit $\\overrightarrow{v}$ durch ein Strömungsgebiet unterschiedlicher Dichte bewegt, registriert die folgende Dichteänderung mit der Zeit:\n\n$$\\frac{\\text{D}\\rho}{\\text{D} t} = \\frac{\\partial \\rho}{\\partial t} + \\overrightarrow{v}\\cdot\\nabla \\rho$$\n\nMithilfe der oben hergeleiteten Kontinuitätsgleichung in Eulerscher Betrachtungsweise können wir die partielle Ableitung der Dichte nach der Zeit ersetzen:\n\n$$\\frac{\\text{D}\\rho}{\\text{D} t} = -\\underbrace{\\nabla\\cdot(\\rho \\overrightarrow{v})}_{\\text{Produktregel}\\atop\\text{anwenden}} + \\overrightarrow{v}\\cdot\\nabla \\rho$$\n\nDurch Anwendung der Produktregel auf den ersten Term nach dem Gleichheitszeichen folgt:\n\n$$\\frac{\\text{D}\\rho}{\\text{D} t} = -\\left[\\color{red}{\\overrightarrow{v}\\cdot\\nabla \\rho} + \\rho\\nabla\\cdot\\overrightarrow{v} \\right] + \\color{red}{\\overrightarrow{v}\\cdot\\nabla \\rho} = -\\rho\\nabla\\cdot\\overrightarrow{v} = -\\rho \\text{div}\\overrightarrow{v}$$\n\nFür **inkompressible Strömungen** ($\\rho = const$) vereinfacht sich die Konti-Gleichung zu: \n\n$$\\text{div} \\overrightarrow{v} = 0.$$\n\nD.h. inkompressible Strömungen sind *quellen- und senkenfrei*. Da sich die Dichte im Strömungsgebiet nicht ändern kann, kann sich auch an keiner Stelle Masse ansammeln. Alles was in ein Kontrollvolumen hineinfließt muss auch wieder herausfließen.", "_____no_output_____" ], [ "### Impulsgleichung\n\nDie Herleitung der Impulsgleichung soll ebenfalls in Eulerscher und Lagrangescher Betrachtungsweise erfolgen. Der Impuls ist ein Vektor und entspricht dem Prdukt aus Masse und Geschwindigkeitsvektor:\n\n$$\\overrightarrow{p} = m \\overrightarrow{v} = \\rho V \\overrightarrow{v}$$\n\nDie Änderung des Impulses pro Zeit entspricht einer Kraft:\n\n$$\\frac{\\partial \\overrightarrow{p}}{\\partial t} = \\overrightarrow{F}$$\n\n#### Eulersche Betrachtung\n\nWir betrachten wieder ein im Raum fixiertes Kontrollvolumen. Da der Impuls ein Vektor ist, müssen wir für jede Raumrichtung eine Gleichung aufstellen (später werden wir diese drei Gleichungen zu einer Vektorgleichung zusammenfassen). Die Herleitung soll hier beispielhaft an der Gleichung für die $x$-Richtung erfolgen.\n\nDie Änderung des $x$-Impulses im Kontrollvolumen entspricht der Summe der am Kontrollvolumen angreifenden Volumenkräfte (Gravitation, elektrische Felder, Magnetfelder) und der Oberflächenkräfte (Trägheitskräfte = ein-/austretende Impulsströme, Reibungskräfte, Druckkräfte):\n\n$$\\frac{\\partial (\\rho v_x)}{\\partial t}\\text{d}V = \\scriptsize{ {{\\text{Impulsströme}\\atop\\text{(Trägheitskräfte)}} + \\text{Druckkräfte}} + \\text{Reibungskräfte} + \\text{Volumenkräfte}}$$\n\nDie rechte Seite der Gleichung werden wir nun schrittweise aufstellen. \n\n##### Impulsströme (Trägheitskräfte)\n\nDurch alle sechs Seiten des Kontrollvolumens kann $x$-Impuls mit dem Volumenstrom transportiert werden. $x$-Impuls kann also auch in $y$- und $z$-Richtung mit der Strömung transportiert werden! Im folgenden Bild ist dies für 4 der Seiten dargestellt. \n\n<img src=\"Impuls.pdf\" style=\"width: 500px;\"/>\n\nZusammengefasst ergibt sich für die Impulsströme (Trägheitskräfte):\n\n$$\\text{Impulsströme} = -\\left[\n\\frac{\\partial (\\rho v_x v_x)}{\\partial x} \n+\\frac{\\partial (\\rho v_x v_y)}{\\partial y} \n+\\frac{\\partial (\\rho v_x v_z)}{\\partial z} \n\\right]\\text{d}x\\text{d}y\\text{d}z$$\n\n##### Druckkräfte\n\nDie Druckkräfte in $x$-Richtung wirken auf zwei Seitenflächen des Kontrollvolumens jeweils senkrecht auf die Fläche:\n\n<img src=\"Druck.pdf\" style=\"width: 500px;\"/>\n\nZusammengefasst ergeben die Druckkräfte in $x$-Richtung:\n\n$$\\text{Druckkräfte} =\n-\\frac{\\partial p}{\\partial x} \\text{d}x\\text{d}y\\text{d}z$$\n\n##### Reibungskräfte\n\nDie Reibungskräfte (Normal- und Schubkräfte) in $x$-Richtung greifen an allen 6-Seiten des Kontrollvolumens an:\n\n<img src=\"Schub.pdf\" style=\"width: 500px;\"/>\n\nSie ergeben in Summe:\n\n$$\\text{Reibungskräfte} =\n\\left[\n\\frac{\\partial \\tau_{xx}}{\\partial x} +\n\\frac{\\partial \\tau_{yx}}{\\partial y} +\n\\frac{\\partial \\tau_{zx}}{\\partial z} \n\\right]\\text{d}x\\text{d}y\\text{d}z$$\n\n##### Volumenkräfte\n\nDie Volumenkräfte wirken homogen auf das gesamte Kontrollvolumen. Zu den wichtigsten zählt die Graviationskraft, die wir wie folgt in den Gleichungen berücksichtigen können:\n\n$$\\scriptsize{\\text{Volumenkräfte}} = \\rho\\cdot g_x\\text{d}x\\text{d}y\\text{d}z$$\n\n##### alles zusammengefasst:\n\nAlle Komponenten zusammenaddiert und durch das Kontrollvolumen $\\text{d}V = \\text{d}x\\text{d}y\\text{d}z$ geteilt ergeben die Impulsgleichung für die $x$-Richtung und analog dazu für die $y$- und $z$-Richtung:\n\n$$\\small{\\frac{\\partial (\\rho v_x)}{\\partial t}\n+ \\frac{\\partial (\\rho v_x v_x)}{\\partial x} \n+ \\frac{\\partial (\\rho v_x v_y)}{\\partial y} \n+ \\frac{\\partial (\\rho v_x v_z)}{\\partial z}\n=\n- \\frac{\\partial p}{\\partial x} + \\rho g_x\n+ \\frac{\\partial \\tau_{xx}}{\\partial x}\n+ \\frac{\\partial \\tau_{yx}}{\\partial y}\n+ \\frac{\\partial \\tau_{zx}}{\\partial z}}\n$$\n\n$$\\small{\\frac{\\partial (\\rho v_y)}{\\partial t}\n+ \\frac{\\partial (\\rho v_y v_x)}{\\partial x} \n+ \\frac{\\partial (\\rho v_y v_y)}{\\partial y} \n+ \\frac{\\partial (\\rho v_y v_z)}{\\partial z}\n=\n- \\frac{\\partial p}{\\partial y} + \\rho g_y\n+ \\frac{\\partial \\tau_{xy}}{\\partial x}\n+ \\frac{\\partial \\tau_{yy}}{\\partial y}\n+ \\frac{\\partial \\tau_{zy}}{\\partial z}}\n$$\n\n$$\\small{\\frac{\\partial (\\rho v_z)}{\\partial t}\n+ \\frac{\\partial (\\rho v_z v_x)}{\\partial x} \n+ \\frac{\\partial (\\rho v_z v_y)}{\\partial y} \n+ \\frac{\\partial (\\rho v_z v_z)}{\\partial z}\n=\n- \\frac{\\partial p}{\\partial z} + \\rho g_z\n+ \\frac{\\partial \\tau_{xz}}{\\partial x}\n+ \\frac{\\partial \\tau_{yz}}{\\partial y}\n+ \\frac{\\partial \\tau_{zz}}{\\partial z}}\n$$\n\nDie Navier-Stokes-Gleichungen findet man in verschiedenen Darstellung. Eine weitere soll hier gezeigt werden. Wir betrachten dazu nur die linke Seite der $x$-Impulsgleichung und wenden die Produktregel auf die Ableitungen an:\n\n$$\\small{\\frac{\\partial (\\rho v_x)}{\\partial t}\n+ \\frac{\\partial (\\rho v_x v_x)}{\\partial x} \n+ \\frac{\\partial (\\rho v_x v_y)}{\\partial y} \n+ \\frac{\\partial (\\rho v_x v_z)}{\\partial z} \n= \n\\color{red}{v_x\\frac{\\partial\\rho}{\\partial t}} + \\rho\\frac{\\partial v_x}{\\partial t} + \\color{red}{v_x\\frac{\\partial(\\rho v_x)}{\\partial x}} + v_x\\frac{\\partial(\\rho v_x)}{\\partial x} + \\color{red}{v_x\\frac{\\partial(\\rho v_y)}{\\partial y}} + v_y\\frac{\\partial(\\rho v_x)}{\\partial y} + \\color{red}{v_x\\frac{\\partial(\\rho v_z)}{\\partial z}} + v_z\\frac{\\partial(\\rho v_x)}{\\partial z}}$$\n\nBetrachten wir nur die rot markierten Terme, so wird klar, dass diese in Summe gerade der Kontinuitätsgleichung multipliziert mit $v_x$ und damit Null entsprechen. \n\nWir bekommen also als weitere, gleichwertige Darstellung für die Navier-Stokes-Gleichungen:\n\n<div class=highlight>\n$$\\small{\\rho\\frac{\\partial v_x}{\\partial t} + v_x\\frac{\\partial(\\rho v_x)}{\\partial x} + v_y\\frac{\\partial(\\rho v_x)}{\\partial y} + v_z\\frac{\\partial(\\rho v_x)}{\\partial z}\n=\n- \\frac{\\partial p}{\\partial x} + \\rho g_x\n+ \\frac{\\partial \\tau_{xx}}{\\partial x}\n+ \\frac{\\partial \\tau_{yx}}{\\partial y}\n+ \\frac{\\partial \\tau_{zx}}{\\partial z}\n}$$\n<BR>\n$$\\small{\\rho\\frac{\\partial v_y}{\\partial t} + v_x\\frac{\\partial(\\rho v_y)}{\\partial x} + v_y\\frac{\\partial(\\rho v_y)}{\\partial y} + v_z\\frac{\\partial(\\rho v_y)}{\\partial z}\n=\n- \\frac{\\partial p}{\\partial x} + \\rho g_y\n+ \\frac{\\partial \\tau_{xy}}{\\partial x}\n+ \\frac{\\partial \\tau_{yy}}{\\partial y}\n+ \\frac{\\partial \\tau_{zy}}{\\partial z}\n}$$\n<BR>\n$$\\small{\\underbrace{\\vphantom{v_x\\frac{\\partial(\\rho v_z)}{\\partial x} + v_y\\frac{\\partial(\\rho v_z)}{\\partial y} + v_z\\frac{\\partial(\\rho v_z)}{\\partial z}}\\rho\\frac{\\partial v_z}{\\partial t}}_{\\text{zeitl.}\\atop\\text{Änd.}} + \\underbrace{v_x\\frac{\\partial(\\rho v_z)}{\\partial x} + v_y\\frac{\\partial(\\rho v_z)}{\\partial y} + v_z\\frac{\\partial(\\rho v_z)}{\\partial z}}_{\\text{konvektiver Impulstransport}\\atop\\text{durch Strömung}}\n=\n\\underbrace{\\vphantom{+ \\frac{\\partial \\tau_{xz}}{\\partial x}\n+ \\frac{\\partial \\tau_{yz}}{\\partial y}\n+ \\frac{\\partial \\tau_{zz}}{\\partial z}}- \\frac{\\partial p}{\\partial x} + \\rho g_z}_{\\text{Quell-}\\atop\\text{terme}}\n\\underbrace{+ \\frac{\\partial \\tau_{xz}}{\\partial x}\n+ \\frac{\\partial \\tau_{yz}}{\\partial y}\n+ \\frac{\\partial \\tau_{zz}}{\\partial z}}_{\\text{diffusiver Transport}\\atop\\text{durch räuml. Impulsunterschiede}}}$$\n</div>\n\nDen einzelnen Termen der Impulsgleichung können zwei Transportmechanismen zugeordnet werden: den konvektiven Transport, der durch die Strömungsbewegung selbst zustandekommt und den diffusiven Transport, der aus einem räumlichen Gradienten der Transportgröße (hier der Impuls) resultiert (vgl. Ausbreitung eines Tintentropfens in einem Glas mit ruhender Flüssigkeit).\n\n##### Modellierung der Normal- und Schubspannungen $\\tau_{ij}$\n\nDie Impulsgleichung in der obigen Form ist für beliebige Fluide gültig. Das Gleichungssystem aus den drei Impulsgleichungen und der Kontinuitätsgleichung enthält neben den uns interessierenden Unbekannten $v_x, v_y, v_z$ und $\\rho$ auch noch den Druck $p$ sowie die 9 Normal- und Schubspannungen. Es ist so also noch nicht lösbar (nur 4 Gleichungen für 14 Unbekannte).\n\nBei bekannter Temperatur kann der Druck z.B. über das ideale Gasgesetz $p/\\rho = R T$ berechnet werden. Für die 9 Spannungen benötigen wir noch eine Berechnungsvorschrift, die von der Art des Fluids abhängt. Für [Newtonsche Fluide](https://de.wikipedia.org/wiki/Newtonsches_Fluid) kann hierzu der *Newtonsche Schubspannungsansatz* verwendet werden:\n\n<div class=highlight>\n$$\\tau_{ij} = \\mu \\left(\\frac{\\partial v_i}{\\partial x_j} + \\frac{\\partial v_j}{\\partial x_i} \\right) + \\delta_{ij}\\lambda\\nabla \\overrightarrow{v}$$\n</div>\n\nDieser besagt, dass die Schubspannungen proportional zu den Geschwindigkeitsgradienten (dem Verformungstensor) sind, wobei der Proportionalitätsfaktor gerade die [dynamische Viskosität](https://de.wikipedia.org/wiki/Viskosität) $\\mu$ ist. Der letzte Term in der Gleichung berücksichtigt die sog. [Volumenviskosität](https://de.wikipedia.org/wiki/Volumenviskosität) $\\lambda$. Diese ist im inkompressiblen Fall und bei 1-atomigen Gasen vernachlässigbar. Von Bedeutung ist sie dagegen bei verdünnten, mehratomigen Gasen (z.B. bei der Berechnung von Wiedereintrittsflugkörpern, etc.). Nach der Stokes-Hypothese (die jedoch nicht exakt ist) gilt: $\\lambda+\\frac{2}{3}\\mu = 0$.\n\n> Hinweis: Das Symbol $\\delta_{ij}$ ist das aus der Mathematik bekannte [Kronecker-Delta](https://de.wikipedia.org/wiki/Kronecker-Delta). Es nimmt für $i=j$ den Wert 1 an und für $i\\ne j$ den Wert 0. Es wird immer dann verwendet, wenn in Indexschreibweise nur die Einträge auf der Matrix-Diagonalen angesprochen werden sollen. In der Gleichung oben spielt die Volumenviskosität also nur bei den drei Normalspannungen $\\tau_{11}, \\tau_{22}$ und $\\tau_{33}$ eine Rolle.\n\n**Übung:** Schreiben Sie alle 9 Komponenten des Schubspannungstensors auf.", "_____no_output_____" ], [ "#### Lagrangesche Betrachtung\n\nDie Herleitung der Navier-Stokes-Gleichungen unter Lagrangescher Betrachtungsweise ähnelt der der Molekulardynamiksimulation, nur dass wir jetzt keine einzelnen Teilchen betrachten, sondern ein Volumenelement, das sich mit der Strömung mitbewegt. Nach dem 2. Newtonschen Gesetz gilt:\n\n*Masse mal Beschleunigung ist gleich Kraft*\n\nauf das Kontrollvolumen $V_{KV}$ bezogen gilt also:\n\n$$\\frac{m\\cdot a}{V_{KV}} = \\frac{F}{V_{KV}}$$\n\noder\n\n$$\\rho \\frac{\\text{D}\\overrightarrow{v}}{\\text{D}t} = \\text{Druckkräfte} + \\text{Reibungskräfte} + \\text{Volumenkräfte}$$\n\nIm Gegensatz zur Herleitung in Eulerscher Betrachtungsweise fehlen die Impulsströme, da das Kontrollvolumen ja mit der Strömung mitbewegt wird und nichts hindurchströmt. Die Navier-Stokes-Gleichungen in dieser Form können sehr kompakt geschrieben werden:\n\n$$\\rho \\frac{\\text{D}\\overrightarrow{v}}{\\text{D}t} = \\nabla \\cdot \\tau_{ij}^* + \\rho\\cdot\\overrightarrow{g}$$\n\nmit\n\n$$\\tau_{ij}^* = -p\\cdot\\delta_{ij} + \\tau_{ij}$$\n\nUm auf die Darstellung in Eulerscher Betrachtung zu kommen, muss nur die Substantielle Ableitung ausgeschrieben werden. Dann treten auch die konvektiven Terme wieder in Erscheinung:\n\n$$\\rho\\cdot\\left(\\frac{\\partial \\overrightarrow{v}}{\\partial t}+\\overrightarrow{v}\\cdot\\nabla\\overrightarrow{v} \\right) = \\nabla \\cdot \\tau_{ij}^* + \\rho\\cdot\\overrightarrow{g}$$\n\n**(Längere) Übung:** Schreiben Sie die Vektorgleichung auf und zeigen Sie, dass Sie mit dem Gleichungssystem aus der Eulerschen Betrachtungsweise übereinstimmt. Hinweis: Wenden Sie wieder die Produktregel auf die Ableitungen $\\frac{\\partial (\\rho v_i)}{\\partial x_j}$ an.", "_____no_output_____" ], [ "Damit haben wir das notwendige Gleichungssystem, um isotherme Strömungen zu berechnen. Für nicht isotherme Strömungen benötigen wir noch die Energiegleichung, die an anderer Stelle hergeleitet wird.\n\nIm [nächsten Notebook](TFD - 3.3 Kontinuumsstroemungen - Navier-Stokes-Gleichungen-2D.ipynb) werden wir die Navier-Stokes-Gleichungen für 2-dimensionale, inkompressible Strömungen mit Newtonschen Fluiden vereinfachen und im weiteren Verlauf der Vorlesung mithilfe der Finite-Differenzen-Methode lösen.", "_____no_output_____" ], [ "\n---\n###### Copyright (c) 2017, Matthias Stripf\n\nDer folgende Python-Code darf ignoriert werden. Er dient nur dazu, die richtige Formatvorlage für die Jupyter-Notebooks zu laden.", "_____no_output_____" ] ], [ [ "from IPython.core.display import HTML\ndef css_styling():\n styles = open('TFDStyle.css', 'r').read()\n return HTML(styles)\ncss_styling()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
cb27fd393aaa5187ca606f5ac4bdc03d11f20aee
1,215
ipynb
Jupyter Notebook
.ipynb_checkpoints/EX029 - Radar Electrônico -checkpoint.ipynb
vithep/Python-Hello-World
f28f887de61d9afc12c083d0a26a247a9e67b32c
[ "MIT" ]
null
null
null
.ipynb_checkpoints/EX029 - Radar Electrônico -checkpoint.ipynb
vithep/Python-Hello-World
f28f887de61d9afc12c083d0a26a247a9e67b32c
[ "MIT" ]
null
null
null
.ipynb_checkpoints/EX029 - Radar Electrônico -checkpoint.ipynb
vithep/Python-Hello-World
f28f887de61d9afc12c083d0a26a247a9e67b32c
[ "MIT" ]
null
null
null
20.948276
88
0.520988
[ [ [ "v=float(input('Digite sua atual velocidade: '))\nif v>120:\n print('Você foi multado!!!\\nDiminua sua velocidade.\\nDirija com cuidado')\n print('Multa de R${:.2f}'.format((v-120)*7))\nelif v<=120 and v>80:\n print('Diminua sua velocidade.\\nDirija com cuidado')\nelse:\n print('Muito bem, siga viagem')", "Digite sua atual velocidade: 70\nMuito bem, siga viagem\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
cb28003586efa8757165b5f5dc31fbab3d6a332d
56,341
ipynb
Jupyter Notebook
Starter_Code/credit_risk_ensemble.ipynb
Liincc/credit_risk_sampling
ec2ad00bdda30f6ad4e61777ac6cd4d5c4545b1c
[ "ADSL" ]
null
null
null
Starter_Code/credit_risk_ensemble.ipynb
Liincc/credit_risk_sampling
ec2ad00bdda30f6ad4e61777ac6cd4d5c4545b1c
[ "ADSL" ]
null
null
null
Starter_Code/credit_risk_ensemble.ipynb
Liincc/credit_risk_sampling
ec2ad00bdda30f6ad4e61777ac6cd4d5c4545b1c
[ "ADSL" ]
null
null
null
43.074159
14,100
0.560728
[ [ [ "# Ensemble Learning\n\n## Initial Imports", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom collections import Counter\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler", "_____no_output_____" ], [ "from sklearn.metrics import balanced_accuracy_score\nfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report\nfrom imblearn.metrics import classification_report_imbalanced\nfrom sklearn.ensemble import RandomForestClassifier\nfrom imblearn.ensemble import BalancedRandomForestClassifier\nfrom imblearn.ensemble import EasyEnsembleClassifier", "_____no_output_____" ] ], [ [ "## Read the CSV and Perform Basic Data Cleaning", "_____no_output_____" ] ], [ [ "# Load the data\nfile_path = Path('Resources/LoanStats_2019Q1.csv')\ndf = pd.read_csv(file_path)\n\n# Preview the data\ndf.head()", "_____no_output_____" ] ], [ [ "## Split the Data into Training and Testing", "_____no_output_____" ] ], [ [ "# Create our features\ny = df.loan_status\nX = df.drop(columns='loan_status', axis=1)\n\n# Create our target\ndf.select_dtypes(include='object').info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 68817 entries, 0 to 68816\nData columns (total 10 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 home_ownership 68817 non-null object\n 1 verification_status 68817 non-null object\n 2 issue_d 68817 non-null object\n 3 loan_status 68817 non-null object\n 4 pymnt_plan 68817 non-null object\n 5 initial_list_status 68817 non-null object\n 6 next_pymnt_d 68817 non-null object\n 7 application_type 68817 non-null object\n 8 hardship_flag 68817 non-null object\n 9 debt_settlement_flag 68817 non-null object\ndtypes: object(10)\nmemory usage: 5.3+ MB\n" ], [ "X = pd.get_dummies(X, columns=['home_ownership', 'verification_status', 'issue_d', 'pymnt_plan', 'initial_list_status', 'next_pymnt_d', 'application_type', 'hardship_flag', 'debt_settlement_flag'])", "_____no_output_____" ], [ "# Check the balance of our target values\nX.head()", "_____no_output_____" ], [ "y.value_counts()", "_____no_output_____" ], [ "# Split the X and y into X_train, X_test, y_train, y_test\nX_train, X_test, y_train, y_test = train_test_split(X,\n y,\n random_state=1,\n stratify=y\n)", "_____no_output_____" ] ], [ [ "## Data Pre-Processing\n\nScale the training and testing data using the `StandardScaler` from `sklearn`. Remember that when scaling the data, you only scale the features data (`X_train` and `X_testing`).", "_____no_output_____" ] ], [ [ "# Create the StandardScaler instance\nscaler = StandardScaler()", "_____no_output_____" ], [ "# Fit the Standard Scaler with the training data\n# When fitting scaling functions, only train on the training dataset\nX_scaler = scaler.fit(X_train)", "_____no_output_____" ], [ "# Scale the training and testing data\nX_train_scaled = X_scaler.transform(X_train)\nX_test_scaled = X_scaler.transform(X_test)", "_____no_output_____" ] ], [ [ "## Ensemble Learners\n\nIn this section, you will compare two ensemble algorithms to determine which algorithm results in the best performance. You will train a Balanced Random Forest Classifier and an Easy Ensemble classifier . For each algorithm, be sure to complete the folliowing steps:\n\n1. Train the model using the training data. \n2. Calculate the balanced accuracy score from sklearn.metrics.\n3. Display the confusion matrix from sklearn.metrics.\n4. Generate a classication report using the `imbalanced_classification_report` from imbalanced-learn.\n5. For the Balanced Random Forest Classifier only, print the feature importance sorted in descending order (most important feature to least important) along with the feature score\n\nNote: Use a random state of 1 for each algorithm to ensure consistency between tests", "_____no_output_____" ], [ "### Balanced Random Forest Classifier", "_____no_output_____" ] ], [ [ "# Resample the training data with the BalancedRandomForestClassifier\nrf_model = RandomForestClassifier(n_estimators=100, random_state=1)\nrf_model = rf_model.fit(X_train_scaled, y_train)\nrf_predictions = rf_model.predict(X_test_scaled)", "_____no_output_____" ], [ "# Calculated the balanced accuracy score\nacc_score = accuracy_score(y_test, rf_predictions)\ncm_rf = confusion_matrix(y_test, rf_predictions)\ncm_rf_df = pd.DataFrame(\n cm_rf, index=['Actual 0', 'Actual 1'], columns=['predicted 0', 'predicted 1']\n)", "_____no_output_____" ], [ "# Display the confusion matrix\nprint('Confusion Matrix')\ndisplay(cm_rf_df)\nprint(f'Accuracy Score : {acc_score}')\nprint('Classification Report')\nprint(classification_report(y_test, rf_predictions))", "Confusion Matrix\n" ], [ "# Print the imbalanced classification report\nprint(classification_report_imbalanced(y_test, rf_predictions))", " pre rec spe f1 geo iba sup\n\n high_risk 0.73 0.34 1.00 0.47 0.59 0.32 87\n low_risk 1.00 1.00 0.34 1.00 0.59 0.37 17118\n\navg / total 1.00 1.00 0.35 1.00 0.59 0.37 17205\n\n" ], [ "# List the features sorted in descending order by feature importance\nimportances = rf_model.feature_importances_\nsorted(zip(rf_model.feature_importances_, X.columns), reverse=True)\n\n#personal challenge: trying to put all top 10~ highest importance features in a df to vizualize", "_____no_output_____" ], [ "importances_df = pd.DataFrame(\n (rf_model.feature_importances_, X.columns)\n)\nimportances_df = importances_df.T\nimportances_df.columns = ['Importance', 'Feature']", "_____no_output_____" ], [ "importances_df = importances_df.sort_values([\"Importance\"], ascending=False).reset_index(drop=True)\nimportances_df.head()", "_____no_output_____" ], [ "importances_df.drop(index=importances_df.iloc[10:, :].index.tolist(), inplace=True)\nimportances_df", "_____no_output_____" ], [ "importances_df.set_index(('Feature'), inplace=True)", "_____no_output_____" ], [ "importances_df.plot(kind='barh', color='lightgreen', title= 'Features Importances', legend=False)", "_____no_output_____" ] ], [ [ "### Easy Ensemble Classifier", "_____no_output_____" ] ], [ [ "# Train the Classifier\neec_model = EasyEnsembleClassifier(n_estimators=100, random_state=1)\neec_model = eec_model.fit(X_train_scaled, y_train)\neec_y_predictions = eec_model.predict(X_test_scaled)", "_____no_output_____" ], [ "# Calculated the balanced accuracy score\nbalanced_accuracy_score(y_test, eec_y_predictions)", "_____no_output_____" ], [ "# Display the confusion matrix\nconfusion_matrix(y_test, eec_y_predictions)", "_____no_output_____" ], [ "# Print the imbalanced classification report\nprint(classification_report_imbalanced(y_test, eec_y_predictions, digits=4))", " pre rec spe f1 geo iba sup\n\n high_risk 0.0747 0.9080 0.9429 0.1381 0.9253 0.8532 87\n low_risk 0.9995 0.9429 0.9080 0.9704 0.9253 0.8591 17118\n\navg / total 0.9948 0.9427 0.9082 0.9662 0.9253 0.8591 17205\n\n" ] ], [ [ "### Final Questions\n\n1. Which model had the best balanced accuracy score?\n\n Random Forrest Test\n\n2. Which model had the best recall score?\n\n Random Forrest Test of 1.0\n\n3. Which model had the best geometric mean score?\n\n Easy Ensemble Classifier of 0.9253\n\n4. What are the top three features?\n\n total_recovered_principle, total_payment, total_payment_inv ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
cb280089706dbc3c4eebcf21681f9dc4d9e6fe3f
189,846
ipynb
Jupyter Notebook
notebooks/.ipynb_checkpoints/DataSciencePipelinePlanningTutorial-checkpoint.ipynb
oudrea/grammar2pddl
f5936c5b8f831c99c7378d88e86c7dd6983c7b12
[ "Apache-2.0" ]
11
2021-03-18T23:36:13.000Z
2022-02-27T11:06:15.000Z
notebooks/.ipynb_checkpoints/DataSciencePipelinePlanningTutorial-checkpoint.ipynb
oudrea/grammar2pddl
f5936c5b8f831c99c7378d88e86c7dd6983c7b12
[ "Apache-2.0" ]
3
2021-07-14T22:54:02.000Z
2022-02-22T05:12:28.000Z
notebooks/.ipynb_checkpoints/DataSciencePipelinePlanningTutorial-checkpoint.ipynb
oudrea/grammar2pddl
f5936c5b8f831c99c7378d88e86c7dd6983c7b12
[ "Apache-2.0" ]
1
2022-02-22T02:54:18.000Z
2022-02-22T02:54:18.000Z
155.484029
1,754
0.556298
[ [ [ "# Using AI planning to explore data science pipelines", "_____no_output_____" ] ], [ [ "from __future__ import print_function\nimport sys\nimport os\nimport types\n\nsys.path.append(os.path.abspath(os.path.join(os.getcwd(), \"../grammar2lale\")))\n\n# Clean output directory where we store planning and result files\nos.system('rm -rf ../output')\nos.system('mkdir -p ../output')\n", "_____no_output_____" ] ], [ [ "## 1. Start with a Data Science grammar, in EBNF format", "_____no_output_____" ] ], [ [ "# This is the grammar file we will use\nGRAMMAR_FILE=\"../grammar/dsgrammar-subset-sklearn.bnf\"\n\n# Copy grammar to the output directory\nos.system(\"cp \" + GRAMMAR_FILE + \" ../output/\")", "_____no_output_____" ], [ "!cat ../output/dsgrammar-subset-sklearn.bnf", "# Notation:\r\n# - Anything between angle brackets <..> denotes a symbol in the grammar\r\n# - The pipe symbol | denotes choice in the grammar\r\n# - Terminals are operators and/or hyperparameters denoted by strings braced by double quotes \"..\"\r\n# - { x }+ denotes one or more repetitions of x where x may be a symbol or terminals\r\n# - String hyperparameters have single quotes '..' around them\r\n# - __hpfloat denotes a float hyperparameter\r\n# - __hpint denotes an integer hyperparameter\r\n\r\n\r\n<start> ::= <mm>\r\n<mm> ::= <dag> \" >> \" <est>\r\n<dag> ::= <tfm> | <tfm> \" >> \" <dag> | \"((\" <tfm> \") & (\" <dag> \")) >> Concat()\" | \"((\" <est> \") & (\" <dag> \")) >> Concat()\" | \"( NoOp() & (\" <dag> \")) >> Concat()\"\r\n\r\n# EST \r\n<est> ::= <glm> | <dtc> | <ebm> | <gnb> | <knc> | <qda> \r\n\r\n# GLM\r\n<glm> ::= \"LogisticRegression()\"\r\n\r\n# DTC\r\n<dtc> ::= \"DecisionTreeClassifier()\"\r\n\r\n# EBM\r\n<ebm> ::= <rfc> | <gbc> | <etc>\r\n# RFC\r\n<rfc> ::= \"RandomForestClassifier()\"\r\n# GBC\r\n<gbc> ::= \"GradientBoostingClassifier()\"\r\n# ETC\r\n<etc> ::= \"ExtraTreesClassifier()\"\r\n\r\n# GNB\r\n<gnb> ::= \"GaussianNB()\"\r\n\r\n# KNC\r\n<knc> ::= \"KNeighborsClassifier()\"\r\n\r\n# QDA\r\n<qda> ::= \"QuadraticDiscriminantAnalysis()\"\r\n\r\n# TFM\r\n<tfm> ::= <utfm> | <wtfm>\r\n\r\n# UTFM\r\n<utfm> ::= \"Normalizer()\" | \"MinMaxScaler()\" | \"RobustScaler()\" | \"StandardScaler()\"\r\n\r\n# WTFM\r\n<wtfm> ::= <pca>\r\n# PCA\r\n<pca> ::= \"PCA()\"\r\n" ] ], [ [ "## 2. Convert the grammar into an HTN domain and problem and use [HTN to PDDL](https://github.com/ronwalf/HTN-Translation) to translate to a PDDL task", "_____no_output_____" ] ], [ [ "from grammar2lale import Grammar2Lale\n\n# Generate HTN specifications\nG2L = Grammar2Lale(grammar_file=GRAMMAR_FILE)\nwith open(\"../output/domain.htn\", \"w\") as f:\n f.write(G2L.htn_domain);\nwith open(\"../output/problem.htn\", \"w\") as f:\n f.write(G2L.htn_problem);\n", "Generating HTN specification from grammar\nPrinting HTN domain\n" ], [ "from grammarDiagram import sklearn_diagram\nwith open('../output/grammar.svg', 'w') as f:\n sklearn_diagram.writeSvg(f.write)\nfrom IPython.core.display import SVG\nSVG('../output/grammar.svg')", "_____no_output_____" ], [ "!cat ../output/domain.htn", "_____no_output_____" ], [ "!cat ../output/problem.htn", "_____no_output_____" ] ], [ [ "## 3. Extend the PDDL task by integrating soft constraints", "_____no_output_____" ] ], [ [ "import re\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets\n\n# as a safety step, setting costs to 0 for any parts of the grammar that are non-identifiers (e.g., parens, etc.)\nfor token in G2L.htn.mapping:\n if not re.match('^[_a-zA-Z]', str(token)):\n G2L.costs[token] = 0\n \n# prepare the list of possible constraints\nconstraint_options = G2L.get_selectable_constraints()\nconstraint_options.sort() \n\n# prepare a constraint selection form\ninteract_pipeline_params=interact.options(manual=True, manual_name='Generate PDDL')\n\n\npipelines = []\nNUM_PIPELINES = 10\nCONSTRAINTS = []\n\n\n# This is the function that handles the constraint selection\n@interact_pipeline_params(num_pipelines=widgets.IntSlider(value=10, min=1, max=100), \n constraints=widgets.SelectMultiple(options=constraint_options,\n description='Search constraints',\n rows=min(20, len(constraint_options))))\ndef select_pipeline_gen_params(num_pipelines, constraints):\n global pipelines\n global NUM_PIPELINES\n global CONSTRAINTS\n NUM_PIPELINES = num_pipelines\n CONSTRAINTS = list(constraints)\n G2L.create_pddl_task(NUM_PIPELINES, CONSTRAINTS)\n with open(\"../output/domain.pddl\", \"w\") as f:\n f.write(G2L.last_task['domain'])\n with open(\"../output/problem.pddl\", \"w\") as f:\n f.write(G2L.last_task['problem'])\n", "_____no_output_____" ], [ "!cat ../output/domain.pddl", "_____no_output_____" ], [ "!cat ../output/problem.pddl", "_____no_output_____" ] ], [ [ "## 4. Use a planner to solve the planning task (in this case, [K*](https://github.com/ctpelok77/kstar) )", "_____no_output_____" ] ], [ [ "import json\n\nG2L.run_pddl_planner()\nwith open(\"../output/first_planner_call.json\", \"w\") as f:\n f.write(json.dumps(G2L.last_planner_object, indent=3))", "Running the planner...\nCreated domain file in /tmp/4fbf2409-321a-4aa9-b3be-8fb4a921da0c/domain.pddl\nCreated problem file in /tmp/4fbf2409-321a-4aa9-b3be-8fb4a921da0c/problem.pddl\nRunning kstar /tmp/4fbf2409-321a-4aa9-b3be-8fb4a921da0c/domain.pddl /tmp/4fbf2409-321a-4aa9-b3be-8fb4a921da0c/problem.pddl --search \"kstar(blind(),k=50,json_file_to_dump=result.json)\"\nPlans returned after 0.9218058586120605 seconds.\n" ], [ "!cat ../output/first_planner_call.json", "_____no_output_____" ] ], [ [ "## 5. Translate plans to [LALE](https://github.com/IBM/lale) Data Science pipelines", "_____no_output_____" ] ], [ [ "# Translate to pipelines\npipelines = G2L.translate_to_pipelines(NUM_PIPELINES)\n\nfrom pipeline_optimizer import PipelineOptimizer\nfrom sklearn.datasets import load_iris\n\nfrom lale.helpers import to_graphviz\nfrom lale.lib.sklearn import *\nfrom lale.lib.lale import ConcatFeatures as Concat\nfrom lale.lib.lale import NoOp\nfrom lale.lib.sklearn import KNeighborsClassifier as KNN\nfrom lale.lib.sklearn import OneHotEncoder as OneHotEnc\nfrom lale.lib.sklearn import Nystroem\nfrom lale.lib.sklearn import PCA\n\noptimizer = PipelineOptimizer(load_iris(return_X_y=True))\n# instantiate LALE objects from pipeline definitions\nLALE_pipelines = [optimizer.to_lale_pipeline(p) for p in pipelines]\n\n# Display selected pipeline\ndef show_pipeline(pipeline):\n print(\"Displaying pipeline \" + pipeline['id'] + \", with cost \" + str(pipeline['score']))\n print(pipeline['pipeline'])\n print('==================================================================================')\n print()\n print()\n print()\n display(to_graphviz(pipeline['lale_pipeline']))\n\ndisplay_pipelines = [[p['pipeline'], p] for p in LALE_pipelines] \n \ninteract(show_pipeline, pipeline=display_pipelines)", "Translating plans to LALE pipelines.\n" ], [ "!pip install 'liac-arff>=2.4.0'", "Collecting liac-arff>=2.4.0\n Downloading liac-arff-2.5.0.tar.gz (13 kB)\nBuilding wheels for collected packages: liac-arff\n Building wheel for liac-arff (setup.py) ... \u001b[?25ldone\n\u001b[?25h Created wheel for liac-arff: filename=liac_arff-2.5.0-py3-none-any.whl size=11730 sha256=e047b877b395d00fd1d84e607af797c45aa12616a2235c627f9f45bf3a8f6f64\n Stored in directory: /home/oudrea/.cache/pip/wheels/1f/0f/15/332ca86cbebf25ddf98518caaf887945fbe1712b97a0f2493b\nSuccessfully built liac-arff\nInstalling collected packages: liac-arff\nSuccessfully installed liac-arff-2.5.0\n" ] ], [ [ "## 6. Optimize one of the pipelines on a small dataset", "_____no_output_____" ] ], [ [ "from lale.lib.lale import Hyperopt\nimport lale.datasets.openml\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\nPIPELINE_IDX = 0\n\ndisplay(to_graphviz(LALE_pipelines[PIPELINE_IDX]['lale_pipeline']))\n\nopt = Hyperopt(\n estimator=LALE_pipelines[PIPELINE_IDX]['lale_pipeline'],\n max_evals=20,\n scoring='accuracy'\n)\nX, y = load_iris(return_X_y=True)\ntrain_X, test_X, train_y, test_y = train_test_split(\n X, y, test_size=0.2, stratify=y, random_state=5489\n)\n\nX\n\ntrained_pipeline = opt.fit(train_X, train_y)\n\npredictions = trained_pipeline.predict(test_X)\nbest_accuracy = accuracy_score(test_y, [round(pred) for pred in predictions])\nprint('Best accuracy: ' + str(best_accuracy))\n", "_____no_output_____" ] ], [ [ "## 7. Train hyperparameters and evaluate the resulting LALE pipelines", "_____no_output_____" ] ], [ [ "trained_pipelines, dropped_pipelines = optimizer.evaluate_and_train_pipelines(pipelines)", "Plan 1/10\nStarting to optimize PCA() >> LogisticRegression()\n100%|██████████| 20/20 [00:06<00:00, 2.99trial/s, best loss: -0.95] \nFit completed.\nPredict completed.\nBest accuracy: 0.9733333333333334\nCompleted optimization for PCA() >> LogisticRegression()\nPlan 2/10\nStarting to optimize PCA() >> GaussianNB()\n100%|██████████| 20/20 [00:06<00:00, 2.91trial/s, best loss: -0.9199999999999999]\nFit completed.\nPredict completed.\nBest accuracy: 0.9333333333333333\nCompleted optimization for PCA() >> GaussianNB()\nPlan 3/10\nStarting to optimize PCA() >> DecisionTreeClassifier()\n100%|██████████| 20/20 [00:09<00:00, 2.07trial/s, best loss: -0.8800000000000001]\nFit completed.\nPredict completed.\nBest accuracy: 0.9466666666666667\nCompleted optimization for PCA() >> DecisionTreeClassifier()\nPlan 4/10\nStarting to optimize PCA() >> KNeighborsClassifier()\n100%|██████████| 20/20 [00:10<00:00, 1.86trial/s, best loss: -0.97] \nFit completed.\nPredict completed.\nBest accuracy: 1.0\nCompleted optimization for PCA() >> KNeighborsClassifier()\nPlan 5/10\nStarting to optimize PCA() >> QuadraticDiscriminantAnalysis()\n100%|██████████| 20/20 [00:09<00:00, 2.09trial/s, best loss: -0.97] \nFit completed.\nPredict completed.\nBest accuracy: 0.98\nCompleted optimization for PCA() >> QuadraticDiscriminantAnalysis()\nPlan 6/10\nStarting to optimize PCA() >> ExtraTreesClassifier()\n100%|██████████| 20/20 [00:18<00:00, 1.07trial/s, best loss: -0.89] \nFit completed.\nPredict completed.\nBest accuracy: 0.9533333333333334\nCompleted optimization for PCA() >> ExtraTreesClassifier()\nPlan 7/10\nStarting to optimize PCA() >> GradientBoostingClassifier()\n100%|██████████| 20/20 [00:10<00:00, 1.96trial/s, best loss: -0.95]\n13 out of 20 trials failed, call summary() for details.\nRun with verbose=True to see per-trial exceptions.\nFit completed.\nPredict completed.\nBest accuracy: 1.0\nCompleted optimization for PCA() >> GradientBoostingClassifier()\nPlan 8/10\nStarting to optimize PCA() >> RandomForestClassifier()\n100%|██████████| 20/20 [00:14<00:00, 1.35trial/s, best loss: -0.9400000000000001]\nFit completed.\nPredict completed.\nBest accuracy: 1.0\nCompleted optimization for PCA() >> RandomForestClassifier()\nPlan 9/10\nStarting to optimize Normalizer() >> PCA() >> LogisticRegression()\n100%|██████████| 20/20 [00:05<00:00, 3.37trial/s, best loss: -0.9400000000000001]\n2 out of 20 trials failed, call summary() for details.\nRun with verbose=True to see per-trial exceptions.\nFit completed.\nPredict completed.\nBest accuracy: 0.9533333333333334\nCompleted optimization for Normalizer() >> PCA() >> LogisticRegression()\nPlan 10/10\nStarting to optimize PCA() >> RobustScaler() >> DecisionTreeClassifier()\n100%|██████████| 20/20 [00:09<00:00, 2.16trial/s, best loss: -0.8800000000000001]\nFit completed.\nPredict completed.\nBest accuracy: 0.9466666666666667\nCompleted optimization for PCA() >> RobustScaler() >> DecisionTreeClassifier()\n" ], [ "from IPython.display import HTML\nfrom tabulate import tabulate\nfrom lale.pretty_print import to_string\n\ndef show_pipeline_accuracy(tp):\n pipeline_table = [[to_string(p['trained_pipeline']).replace('\\n', '<br/>'), str(p['best_accuracy'])] for p in tp]\n display(HTML(tabulate(pipeline_table, headers=['Pipeline', 'Accuracy'], tablefmt='html')))\n\n\nshow_pipeline_accuracy(trained_pipelines)", "_____no_output_____" ] ], [ [ "## 8. Use pipeline accuracy to compute new PDDL action costs", "_____no_output_____" ] ], [ [ "feedback = optimizer.get_feedback(trained_pipelines)\nG2L.feedback(feedback)\ncosts_table = [[str(k), G2L.costs[k]] for k in G2L.costs.keys()]\ndisplay(HTML(tabulate(costs_table, headers=['Pipeline element', 'Computed cost'], tablefmt='html')))", "_____no_output_____" ] ], [ [ "## 9. Invoke planner again on updated PDDL task and translate to pipelines", "_____no_output_____" ] ], [ [ "new_pipelines = G2L.get_plans(num_pipelines=NUM_PIPELINES, constraints=CONSTRAINTS)\n\nwith open('../output/domain_after_feedback.pddl', 'w') as f:\n f.write(G2L.last_task['domain'])\nwith open('../output/problem_after_feedback.pddl', 'w') as f:\n f.write(G2L.last_task['problem'])\nwith open('../output/second_planner_call.json', 'w') as f:\n f.write(json.dumps(G2L.last_planner_object, indent=3))\n\ndef build_and_show_new_table():\n new_pipeline_table = [[pipelines[idx]['pipeline'], new_pipelines[idx]['pipeline']] for idx in range(min(len(pipelines), len(new_pipelines)))]\n display(HTML(tabulate(new_pipeline_table, headers=['First iteration', 'After feedback'], tablefmt='html')))\n\nbuild_and_show_new_table()", "Generating PDDL description...\nObtaining 10 plans with constraints ['PCA()']\nRunning the planner...\nCreated domain file in /tmp/51cf31e7-e235-42a4-b517-743603264758/domain.pddl\nCreated problem file in /tmp/51cf31e7-e235-42a4-b517-743603264758/problem.pddl\nRunning kstar /tmp/51cf31e7-e235-42a4-b517-743603264758/domain.pddl /tmp/51cf31e7-e235-42a4-b517-743603264758/problem.pddl --search \"kstar(blind(),k=50,json_file_to_dump=result.json)\"\nPlans returned after 0.7981829643249512 seconds.\nTranslating plans to LALE pipelines.\n" ], [ "!cat ../output/domain_after_feedback.pddl", "_____no_output_____" ], [ "!cat ../output/problem_after_feedback.pddl", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
cb2805f64000f1fc69d9cb3c0857c746d8b48b49
433,028
ipynb
Jupyter Notebook
knowknow/appendices.ipynb
adnanjmi21/knowknow
cd858c1746c815361dc075a3e445c3d0cb8e2d29
[ "MIT" ]
1
2020-07-07T15:15:50.000Z
2020-07-07T15:15:50.000Z
knowknow/appendices.ipynb
adnanjmi21/knowknow
cd858c1746c815361dc075a3e445c3d0cb8e2d29
[ "MIT" ]
null
null
null
knowknow/appendices.ipynb
adnanjmi21/knowknow
cd858c1746c815361dc075a3e445c3d0cb8e2d29
[ "MIT" ]
null
null
null
1,760.276423
64,220
0.956636
[ [ [ "import sys; sys.path.append(_dh[0].split(\"knowknow\")[0])\nimport yaml\nfrom knowknow import *", "_____no_output_____" ], [ "showdocs(\"journal_sum\")", "_____no_output_____" ], [ "showdocs(\"counter\", \"Appendix 1:\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
cb280a9b7c3db2153652c76328da4e0cfdec2571
5,639
ipynb
Jupyter Notebook
bindings/kepler.gl-jupyter/notebooks/DataFrame.ipynb
leeaco/kepler.gl
e35f5ed9b6e99fed0f504706f40053b661f8ffc1
[ "MIT" ]
1
2019-10-09T07:57:02.000Z
2019-10-09T07:57:02.000Z
bindings/kepler.gl-jupyter/notebooks/DataFrame.ipynb
leeaco/kepler.gl
e35f5ed9b6e99fed0f504706f40053b661f8ffc1
[ "MIT" ]
null
null
null
bindings/kepler.gl-jupyter/notebooks/DataFrame.ipynb
leeaco/kepler.gl
e35f5ed9b6e99fed0f504706f40053b661f8ffc1
[ "MIT" ]
null
null
null
33.565476
969
0.469409
[ [ [ "import pandas as pd", "_____no_output_____" ], [ "df = pd.DataFrame(\n {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],\n 'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],\n 'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],\n 'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86],\n 'Time': ['2019-09-01 08:00','2019-09-01 09:00','2019-09-01 10:00','2019-09-01 11:00', '2019-09-01 12:00']\n })", "_____no_output_____" ], [ "config = {\n \"version\": \"v1\",\n \"config\": {\n \"visState\": {\n \"filters\":[\n {\n \"dataId\": \"city\",\n \"enlarged\": True,\n \"name\": \"Time\",\n \"type\": \"timeRange\",\n \"value\": [1567326664000, 1567330842000]\n }\n ],\n \"layers\": [\n {\n \"type\": \"point\",\n \"config\": {\n \"dataId\": \"city\",\n \"isVisible\": True,\n \"columns\": {\n \"altitude\": None,\n \"lat\": \"Latitude\",\n \"lng\": \"Longitude\"\n },\n \"color\": [165, 16, 55],\n \"visConfig\": {\n \"radius\": 64.4\n },\n \"textLabel\": {\n \"field\": {\"name\": \"City\", \"type\": \"string\"}\n }\n }\n }\n ]\n }\n }\n}", "_____no_output_____" ], [ "import keplergl\nw1 = keplergl.KeplerGl(height=400, data={\"city\": df}, config=config)\nw1", "User Guide: https://github.com/keplergl/kepler.gl/blob/master/docs/keplergl-jupyter/user-guide.md\n" ], [ "w1.save_to_html(file_name='keplergl_map_time_test_1.html')", "Map saved to keplergl_map_time_test_1.html!\n" ], [ "from ipyleaflet import *\nm = Map(center=(52, 10), zoom=8, basemap=basemaps.Hydda.Full)\nm", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
cb280ab609109eca0badd5a882c6af0524dd276d
89,096
ipynb
Jupyter Notebook
DL/CNN.ipynb
basiralab/basic-ML-DL-concepts
7eddd98bf591e5ba110e49f398b17d257d170e7a
[ "MIT" ]
1
2021-12-13T11:17:18.000Z
2021-12-13T11:17:18.000Z
DL/CNN.ipynb
basiralab/basic-ML-DL-concepts
7eddd98bf591e5ba110e49f398b17d257d170e7a
[ "MIT" ]
null
null
null
DL/CNN.ipynb
basiralab/basic-ML-DL-concepts
7eddd98bf591e5ba110e49f398b17d257d170e7a
[ "MIT" ]
null
null
null
80.996364
11,912
0.811563
[ [ [ "This Jupyter notebook details theoretically the architecture and the mechanism of the Convolutional Neural Network (ConvNet) step by step. Then, we implement the CNN code for multi-class classification task using pytorch. <br> \nThe notebook was implemented by <i>Nada Chaari</i>, PhD student at Istanbul Technical University (ITU). <br>", "_____no_output_____" ], [ "# Table of Contents:\n\n 1)Convolution layer\n 1-1) Input image \n 1-2) Filter\n 1-3) Output image\n 1-4) Multiple filters\n 1-5) One-layer of a convolutional neural network\n 2)Pooling layer\n 3)Fully connected layer\n 4)Softmax\n 5)Application of CNN using CIFAR dataset\n 5-1) Dataset\n 5-2) Load and normalize the CIFAR10 training and test datasets \n 5-3) Define a Convolutioanl Neural Network\n 5-4) Define a Loss function and optimizer\n 5-5) Train the CNN\n 5-6) Test the network on the test data", "_____no_output_____" ], [ "Sources used to build this Jupiter Notebook:\n* https://towardsdatascience.com/understanding-images-with-skimage-python-b94d210afd23\n* https://gombru.github.io/2018/05/23/cross_entropy_loss/\n* https://medium.com/@toprak.mhmt/activation-functions-for-deep-learning-13d8b9b20e\n* https://github.com/python-engineer/pytorchTutorial/blob/master/14_cnn.py \n* https://medium.com/machine-learning-bites/deeplearning-series-convolutional-neural-networks-a9c2f2ee1524\n* https://towardsdatascience.com/stochastic-gradient-descent-clearly-explained-53d239905d31", "_____no_output_____" ], [ "# CNN (ConvNet) definition", "_____no_output_____" ], [ "Convolutional Neural Network is a sequence of layers made up of neurons that have learnable weights and biases. Each neuron receives some inputs, performs a dot product and optionally follows it with a non-linearity. The whole network still expresses a single differentiable score function: from the raw image pixels on one end to class scores at the other. CNNs have a loss function (e.g. SVM/Softmax) on the last (fully-connected) layer.", "_____no_output_____" ], [ "* There are 3 types of layers to build the ConvNet architectures:\n * Convolution (CONV)\n * Pooling (POOL)\n * Fully connected (FC)", "_____no_output_____" ], [ "# 1) Convolution layer", "_____no_output_____" ], [ "## 1-1) Input image ", "_____no_output_____" ], [ "* Image with color has three channels: red, green and blue, which can be represented as three 2d-matrices stacked over each other (one for each color), each having pixel values in the range 0 to 255.", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/1400/1*icINeO4H7UKe3NlU1fXqlA.jpeg' width='400' align=\"center\">", "_____no_output_____" ], [ "## 1-2) Filter", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*7S266Kq-UCExS25iX_I_AQ.png' width='500' align=\"center\">", "_____no_output_____" ], [ "* In the filter the value '1' allows filtering brightness, \n* While '-1' highlights the darkness,\n* Furthermore, '0' highlights the grey.", "_____no_output_____" ], [ "* The convolution layer in the case of a ConvNet extracts features from the input image:\n * choose a filter (kernel) of a certain dimension\n * slide the filter from the top left to the right until we reach the bottom of the image.\n* The convolution operation is an element-wise multiplication between the two matrices (filter and the part of the image) and an addition of the multiplication outputs.\n\n* The final integer of this computation forms a single element of the output matrix.", "_____no_output_____" ], [ "* Stride: is the step that the filter moves horizontally and vertically by pixel.\nIn the above example, the value of a stride equal to 1.\n\nBecause the pixels on the edges are “touched” less by the filter than the pixels within the image, we apply padding.\n\n* Padding: is to pad the image with zeros all around its border to allow the filter to slide on top and maintain the output size equal to the input", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/684/1*PBnmjdDqn-OF8JEyRgKm9Q.png' width='200' align=\"center\">", "_____no_output_____" ], [ "<font color='red'> Important </font>: The goal of a convolutional neural network is to learn the values of filters. They are treated as parameters, which the network learns using backpropagation.", "_____no_output_____" ], [ "## 1-3) Output image ", "_____no_output_____" ], [ "The size of the output image after applying the filter, knowing the filter size (f), stride (s), pad (p), and input size (n) is given as:", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*rOyHQ2teFXX5rIIFHwYDsg.png' width='400' align=\"center\">", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*IBWQJSnW19WIYsObZcMTNg.png' width='500' align=\"center\">", "_____no_output_____" ], [ "## 1-4) Multiple filters", "_____no_output_____" ], [ "We can generalize the application of one filter at a time to multiple filters to detect several different features. This is the concept for building convolutional neural networks. Each filter brings its own output and we stack them all together and create an output volume, such as:", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*ySaRmKSilLahyK2WxXC1bA.png' width='500' align=\"center\">", "_____no_output_____" ], [ "The general formula of the output image can be written as: ", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*pN09gs3rXeTh_EwED1d76Q.png' width='500' align=\"center\">", "_____no_output_____" ], [ "where nc is the number of filters", "_____no_output_____" ], [ "## 1-5) One-layer of a convolutional neural network", "_____no_output_____" ], [ "The final step that takes us to a convolutional neural layer is to add the bias and a non-linear function.", "_____no_output_____" ], [ "The goal of the activation function is to add a non-linearity to the network so that it can model non-linear relationships. The most used is Rectified Linear (RELU) defined as max(0,z) with thresholding at zero. This function assigns zeros to all negatives inputs and keep the same values to the positives inputs. This leaves the size of the output volume unchanged ([4x4x1]).", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*LiBZo_FcnKWqoU7M3GRKbA.png' width='300' align=\"center\">", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*EpeM8rTf5RFKYphZwYItkg.png' width='500' align=\"center\">", "_____no_output_____" ], [ "The parameters involved in one layer are the elements forming the filters and the bias.\nExample: if we have 10 filters that are of size 3x3x3 in one layer of a neural network. Each filter has 27 (3x3x3) + 1 bias => 28 parameters. Therefore, the total amount of parameters in the layer is 280 (10x28).", "_____no_output_____" ], [ "## Deep Convolutional Network", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*PT1sP_kCvdFEiJEsoKU88Q.png' width='600' align=\"center\">", "_____no_output_____" ], [ "# 2) Pooling layer", "_____no_output_____" ], [ "Pooling layer performs a downsampling operation by progressively reducing the spatial size of the representation (input volume) to reduce the amount of learnable parameters and thus the computational cost; and to avoid overfitting by providing an abstracted form of the input. The Pooling Layer operates independently on every depth slice of the input and resizes it.", "_____no_output_____" ], [ "There are two types of pooling layers: max and average pooling.\n\n* Max pooling: a filter which takes take the largest element within the region it covers.\n* Average pooling: a filter which retains the average of the values encountered within the region it covers.\n\nNote: pooling layer does not have any parameters to learn. ", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*voEBfjohEDVRK7RpNvxd-Q.png' width='300' align=\"center\">", "_____no_output_____" ], [ "# 3) Fully connected layer", "_____no_output_____" ], [ "Fully connected layer (FC) is a layer where all the layer inputs are connectd to all layer outputs. In classification task, FC is used to extract features from the data to make the classification work. Also, FC computes the class scores to classifier the data. In general, FC layer is added to make the model end-to-end trainable by learning a function between the high-level features given as an output from the convolutional layers.", "_____no_output_____" ], [ "<img src='https://miro.medium.com/max/933/1*_l-0PeSh3oL2Wc2ri2sVWA.png' width='600' align=\"center\">", "_____no_output_____" ], [ "It’s common that, as we go deeper into the network, the sizes (nh, nw) decrease, while the number of channels (nc) increases.", "_____no_output_____" ], [ "# 4) Softmax ", "_____no_output_____" ], [ "The softmax function is a type of a sigmoid function, not a loss, used in classification problems. The softmax function is ideally used in the output layer of the classifier where we are actually trying to get the probabilities to define the class of each input. ", "_____no_output_____" ], [ "The Softmax function cannot be applied independently to each $s_i$, since it depends on all elements of $s$. For a given class $s_i$, the Softmax function can be computed as:", "_____no_output_____" ], [ "$$ f(s)_{i} = \\frac{e^{s_{i}}}{\\sum_{j}^{C} e^{s_{j}}} $$", "_____no_output_____" ], [ "Where $s_j$ are the scores inferred by the net for each class in C. Note that the Softmax activation for a class $s_i$ depends on all the scores in $s$.", "_____no_output_____" ], [ "So, if a network with 3 neurons in the output layer outputs [1.6, 0.55, 0.98], then with a softmax activation function, the outputs get converted to [0.51, 0.18, 0.31]. This way, it is easier for us to classify a given data point and determine to which category it belongs.", "_____no_output_____" ], [ "<img src='https://gombru.github.io/assets/cross_entropy_loss/intro.png' width='400' align=\"center\">", "_____no_output_____" ], [ "# 5) Application of CNN using CIFAR dataset", "_____no_output_____" ], [ "## 5-1) dataset", "_____no_output_____" ], [ "For the CNN application, we will use the CIFAR10 dataset. It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.", "_____no_output_____" ], [ "<img src='https://cs231n.github.io/assets/cnn/convnet.jpeg' width='600' align=\"center\">", "_____no_output_____" ], [ "## 5-2) Load and normalize the CIFAR10 training and test datasets using torchvision", "_____no_output_____" ] ], [ [ "import torch\nimport torchvision # torchvision is for loading the dataset (CIFAR10) \nimport torchvision.transforms as transforms # torchvision.transforms is for data transformers for images\nimport numpy as np", "_____no_output_____" ], [ "# Hyper-parameters \nnum_epochs = 5\nbatch_size = 4\nlearning_rate = 0.001", "_____no_output_____" ], [ "# dataset has PILImage images of range [0, 1]. \n# We transform them to Tensors of normalized range [-1, 1]\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])", "_____no_output_____" ], [ "# A CIFAR10 dataset are available in pytorch. We load CIFAR from torchvision.datasets\n# CIFAR10: 60000 32x32 color images in 10 classes, with 6000 images per class\n\ntrain_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform) \n\ntest_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n\n# We define the pytorch data loader so that we can do the batch optimazation and batch training\ntrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, \n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size,\n shuffle=False)\n# Define the classes\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')", "Files already downloaded and verified\nFiles already downloaded and verified\n" ] ], [ [ "## 5-3) Define a Convolutional Neural Network", "_____no_output_____" ] ], [ [ "import torch.nn as nn # for the the neural network \nimport torch.nn.functional as F # import activation function (relu; softmax)", "_____no_output_____" ], [ "# Implement the ConvNet \nclass ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5) # create the first conv layer-- 3: num of channel; 6: output layer; 5: kernel size\n self.pool = nn.MaxPool2d(2, 2) # create the first pool layer -- 2: kernel size; 2: stride size\n self.conv2 = nn.Conv2d(6, 16, 5) # create the second conv layer -- 6: the input channel size must be equal to the last output channel size; 16: the output; 5: kernel size \n self.fc1 = nn.Linear(16 * 5 * 5, 120) # # create the FC layer (classification layer) to flattern 3-d tensor to 1-d tensor\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n # -> size of x: [3, 32, 32]\n x = self.pool(F.relu(self.conv1(x))) # -> size of x: [6, 14, 14] # call an activation function (relu)\n x = self.pool(F.relu(self.conv2(x))) # -> size of x: [16, 5, 5]\n x = x.view(-1, 16 * 5 * 5) # -> size of x: [400]\n x = F.relu(self.fc1(x)) # -> size of x: [120]\n x = F.relu(self.fc2(x)) # -> size of x: [84]\n x = self.fc3(x) # -> size of x: [10]\n return x", "_____no_output_____" ], [ "# Create the model\nmodel = ConvNet()", "_____no_output_____" ] ], [ [ "<img src='https://miro.medium.com/max/933/1*rOyHQ2teFXX5rIIFHwYDsg.png' width='400' align=\"center\">", "_____no_output_____" ], [ "## 5-4) Define a Loss function and optimizer", "_____no_output_____" ] ], [ [ "\n# Create the loss function (multiclass-classification problem)--> CrossEntropy\ncriterion = nn.CrossEntropyLoss() # the softmax is included in the loss\n# Create the optimizer (use the stochastic gradient descent to optimize the model parameters given the lr)\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)", "_____no_output_____" ] ], [ [ "### Stochastic gradient descent (SGD)", "_____no_output_____" ], [ "Unlike the gradiend descent that takes the sum of squared residuals of all data points for each iteration of the algorithm, which is computaionally costed, SGD randomly picks one data point from the whole data set at each iteration to reduce the computations enormously.", "_____no_output_____" ], [ "## 5-5) Train the CNN", "_____no_output_____" ] ], [ [ "# training loop\nn_total_steps = len(train_loader)\nfor epoch in range(num_epochs):# loop over the number of epochs (5)\n for i, (images, labels) in enumerate(train_loader):\n # origin shape: [4, 3, 32, 32] = 4, 3, 1024\n # input_layer: 3 input channels, 6 output channels, 5 kernel size\n images = images # get the inputs images\n labels = labels # get the inputs labels \n\n # Forward pass\n outputs = model(images) # forward: calculate the loss between the predicted scores and the ground truth\n loss = criterion(outputs, labels) # compute the CrossEntropy loss between the predicted and the real labels\n\n # Backward and optimize\n optimizer.zero_grad() # zero the parameter gradients\n loss.backward() # the backward propagates the error (loss) back into the network and update each weight and bias for each layer in the CNN using SGD optimizer\n optimizer.step() # compute the SGD to find the next \n\n if (i+1) % 2000 == 0: # print every 2000 mini-batches\n print (f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{n_total_steps}], Loss: {loss.item():.4f}')\n\nprint('Finished Training')", "Epoch [1/5], Step [2000/12500], Loss: 2.3497\nEpoch [1/5], Step [4000/12500], Loss: 2.2971\nEpoch [1/5], Step [6000/12500], Loss: 2.2820\nEpoch [1/5], Step [8000/12500], Loss: 2.2722\nEpoch [1/5], Step [10000/12500], Loss: 2.2366\nEpoch [1/5], Step [12000/12500], Loss: 2.1255\nEpoch [2/5], Step [2000/12500], Loss: 1.8898\nEpoch [2/5], Step [4000/12500], Loss: 2.8444\nEpoch [2/5], Step [6000/12500], Loss: 1.5852\nEpoch [2/5], Step [8000/12500], Loss: 1.7568\nEpoch [2/5], Step [10000/12500], Loss: 1.7472\nEpoch [2/5], Step [12000/12500], Loss: 1.4950\nEpoch [3/5], Step [2000/12500], Loss: 1.3918\nEpoch [3/5], Step [4000/12500], Loss: 1.1707\nEpoch [3/5], Step [6000/12500], Loss: 1.3633\nEpoch [3/5], Step [8000/12500], Loss: 1.1888\nEpoch [3/5], Step [10000/12500], Loss: 1.2995\nEpoch [3/5], Step [12000/12500], Loss: 1.2683\nEpoch [4/5], Step [2000/12500], Loss: 2.0188\nEpoch [4/5], Step [4000/12500], Loss: 1.1306\nEpoch [4/5], Step [6000/12500], Loss: 1.5046\nEpoch [4/5], Step [8000/12500], Loss: 1.5213\nEpoch [4/5], Step [10000/12500], Loss: 0.8750\nEpoch [4/5], Step [12000/12500], Loss: 0.7599\nEpoch [5/5], Step [2000/12500], Loss: 0.5422\nEpoch [5/5], Step [4000/12500], Loss: 1.4791\nEpoch [5/5], Step [6000/12500], Loss: 1.2368\nEpoch [5/5], Step [8000/12500], Loss: 1.7047\nEpoch [5/5], Step [10000/12500], Loss: 0.9934\nEpoch [5/5], Step [12000/12500], Loss: 1.2859\nFinished Training\n" ] ], [ [ "## 5-6) Test the network on the test data", "_____no_output_____" ] ], [ [ "# Evaluating the model\nwith torch.no_grad(): # since we're not training, we don't need to calculate the gradients for our outputs\n n_correct = 0\n n_samples = 0\n n_class_correct = [0 for i in range(10)]\n n_class_samples = [0 for i in range(10)]\n for images, labels in test_loader:\n outputs = model(images) # run images through the network and output the probability distribution that image belongs to each class over 10 classes \n # max returns (value ,index)\n _, predicted = torch.max(outputs, 1) # returns the index having the highest probability score of each image over one batch\n n_samples += labels.size(0)\n n_correct += (predicted == labels).sum().item() # returns the number of corrected classified samples in each batch and increment them to the total right classified samples \n \n for i in range(batch_size):\n label = labels[i]\n pred = predicted[i]\n if (label == pred): # test if the predicted label of a sample is equal to the real label\n n_class_correct[label] += 1 # calculate the number of corrected classified samples in each class\n n_class_samples[label] += 1 # calculate the number of samples in each class (test data)\n\n acc = 100.0 * n_correct / n_samples # calculate the accuracy classification of the network", "_____no_output_____" ], [ "outputs", "_____no_output_____" ] ], [ [ "* We will visualize the outputs which represent the classes probability scores of 4 samples in one batch.\n* Each sample has 10 classes probability scores. The index of the class having the highest score will be the predicted value and which will be compared with the ground truth later on.", "_____no_output_____" ] ], [ [ "import pandas as pd # Visualizing Statistical Data \nimport seaborn as sns # Visualizing Statistical Data \ndf = pd.DataFrame({'accuracy_sample 1': outputs[0, 0:10].tolist(), 'classes': ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'], })\nsns.set_style('darkgrid')\n# plot the accuracy classification for each class\nsns.barplot(x ='classes', y ='accuracy_sample 1', data = df, palette ='plasma')", "_____no_output_____" ], [ "df = pd.DataFrame({'accuracy_sample 2': outputs[1, 0:10].tolist(), 'classes': ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'], })\nsns.set_style('darkgrid')\n# plot the accuracy classification for each class\nsns.barplot(x ='classes', y ='accuracy_sample 2', data = df, palette ='plasma')", "_____no_output_____" ], [ "df = pd.DataFrame({'accuracy_sample 3': outputs[2, 0:10].tolist(), 'classes': ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'], })\nsns.set_style('darkgrid')\n# plot the accuracy classification for each class\nsns.barplot(x ='classes', y ='accuracy_sample 3', data = df, palette ='plasma')", "_____no_output_____" ], [ "df = pd.DataFrame({'accuracy_sample 4': outputs[3, 0:10].tolist(), 'classes': ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'], })\nsns.set_style('darkgrid')\n# plot the accuracy classification for each class\nsns.barplot(x ='classes', y ='accuracy_sample 4', data = df, palette ='plasma')", "_____no_output_____" ], [ "predicted", "_____no_output_____" ], [ "labels", "_____no_output_____" ], [ "n_samples", "_____no_output_____" ], [ "n_correct", "_____no_output_____" ], [ "acc = 100.0 * n_correct / n_samples # calculate the accuracy classification of the network\nprint('The accuracy classification of the network is:', acc)", "The accuracy classification of the network is: 49.71\n" ], [ "list_class = []\nfor i in range(10): # calculate the accuracy classification for each class\n acc = 100.0 * n_class_correct[i] / n_class_samples[i] \n list_class.append(acc)\n print(f'Accuracy of {classes[i]}: {acc} %')", "Accuracy of plane: 57.0 %\nAccuracy of car: 66.3 %\nAccuracy of bird: 26.9 %\nAccuracy of cat: 30.4 %\nAccuracy of deer: 45.8 %\nAccuracy of dog: 34.7 %\nAccuracy of frog: 64.0 %\nAccuracy of horse: 56.9 %\nAccuracy of ship: 58.9 %\nAccuracy of truck: 56.2 %\n" ], [ "list_class", "_____no_output_____" ], [ "df = pd.DataFrame({'accuracy': [42.6, 49.9, 25.7, 40.9, 34.8, 26.7, 57.6, 62.6, 68.2, 66.4], 'classes': ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'], })\nsns.set_style('darkgrid')\n# plot the accuracy classification for each class\nsns.barplot(x ='classes', y ='accuracy', data = df, palette ='plasma')", "_____no_output_____" ] ], [ [ "The classes that performed well are: car, ship, frog, plane and horse (choose a threshold rate equal to 0.5).\nFor the classes that did not perform well are: bird, cat, deer, dog and truck.", "_____no_output_____" ], [ "Thanks!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
cb2812ee4529be1ad404d7e2bef77169dccc5809
14,806
ipynb
Jupyter Notebook
testing/00_testing.ipynb
rauljrz/curso_python
f241125f0a51c39899f5d59537dca9e7b4c53489
[ "Apache-2.0" ]
null
null
null
testing/00_testing.ipynb
rauljrz/curso_python
f241125f0a51c39899f5d59537dca9e7b4c53489
[ "Apache-2.0" ]
null
null
null
testing/00_testing.ipynb
rauljrz/curso_python
f241125f0a51c39899f5d59537dca9e7b4c53489
[ "Apache-2.0" ]
null
null
null
21.837758
124
0.459341
[ [ [ "![](https://files.realpython.com/media/YXhT6fA.d277d5317026.gif)", "_____no_output_____" ] ], [ [ "# import requests\n\n# with open(\"mynote.ipynb\", \"w\") as f:\n# f.write(requests.get(\"https://raw.githubusercontent.com/polyrand/teach/master/05_testing/testing.ipynb\").text)", "_____no_output_____" ], [ "# !pip install ipytest", "_____no_output_____" ], [ "import warnings\n\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "import pytest\n\nimport ipytest\nipytest.config(rewrite_asserts=True, magics=True)\n\n__file__ = \"testing.ipynb\"", "_____no_output_____" ], [ "assert [1, 2, 3] == [1, 2, 3]", "_____no_output_____" ], [ "num = 1.25\nassert isinstance(num, int), f\"La variable num debe ser un entero pero es: {num}\"", "_____no_output_____" ], [ "def test_example():\n assert [1, 2, 3] == [1, 2, 3]", "_____no_output_____" ], [ "def capital_case(x):\n \n return x.capitalize()", "_____no_output_____" ], [ "capital_case(\"un texto\")", "_____no_output_____" ], [ "%%run_pytest[clean]\n\ndef test_capital_case():\n assert capital_case(\"semaphore\") == \"Semaphore\"\n assert capital_case(\"python\") == \"Python\"\n assert capital_case(\"curso\") == \"Curso\"", "_____no_output_____" ], [ "%%run_pytest[clean] -qq\nimport pytest\n\n\[email protected]\ndef supply_AA_BB_CC():\n aa = 25\n bb = 35\n cc = 45\n return [aa, bb, cc]\n\n\ndef test_comparewithAA(supply_AA_BB_CC):\n zz = 25\n assert supply_AA_BB_CC[0] == zz, \"aa and zz comparison failed\"\n\n\ndef test_comparewithBB(supply_AA_BB_CC):\n zz = 35\n assert supply_AA_BB_CC[1] == zz, \"bb and zz comparison failed\"\n\n\ndef test_comparewithCC(supply_AA_BB_CC):\n zz = 25\n assert supply_AA_BB_CC[2] == zz, \"cc and zz comparison failed\"", "_____no_output_____" ] ], [ [ "## Ejercicio\n\nCrear test para las dos siguientes funciones.", "_____no_output_____" ] ], [ [ "def maximo(valores):\n \"\"\"Calcula el valor maximo de un iterable.\n \n Si se encuentra un `str` hará aosdnad\n \n >>> ...\n ...\n \n \n \"\"\"\n\n max_valor = valores[0]\n\n for val in valores:\n if val > max_valor:\n max_valor = val\n\n return max_valor\n\n\ndef minimo(valores):\n\n min_valor = valores[0]\n\n for val in valores:\n if val < min_valor:\n min_valor = val\n\n return min_valor", "_____no_output_____" ], [ "def maximo(valores):\n \"\"\"Calcular el valor máximo de un iterable.\n \n >>> maximo([1,2,3,4,5,])\n 5\n \n >>> maximo([123123,-2,-234234,0])\n 123123\n \"\"\"\n \n return max(valores)\n\ndef minimo(valores):\n \n return min(valores)", "_____no_output_____" ], [ "import doctest\ndoctest.testmod(verbose=True)", "_____no_output_____" ], [ "%%run_pytest[clean] -qq\n\ndef test_minimo():\n valores = (2, 3, 1, 4, 6)\n\n val = minimo(valores)\n assert val == 1\n \n assert minimo([8,0,4]) == 0\n \n\n\ndef test_maximo():\n valores = (2, 3, 1, 4, 6)\n\n val = maximo(valores)\n assert val == 6", "_____no_output_____" ], [ "%%run_pytest[clean] -m cursopython\n\n\[email protected]\ndef test_b1():\n\n assert \"falcon\" == \"fal\" + \"con\"\n \n \[email protected]\ndef test_b12():\n\n assert \"falcon\" == \"fal\" + \"con\"", "_____no_output_____" ], [ "%%run_pytest[clean]\n\n\[email protected](\n \"valores,resultado\",\n [\n ([30, 20, 10], 10),\n ([200000, -1, 12], -1),\n ([30, 20, 10], \"asd\"),\n ([30, 20, 10], 10),\n ],\n)\ndef test_parser_xml(valores, resultado):\n\n min_valor = valores[0]\n\n for val in valores:\n if val < min_valor:\n min_valor = val\n\n assert min_valor == resultado", "_____no_output_____" ] ], [ [ "## Unit Tests", "_____no_output_____" ] ], [ [ "import unittest\n\n\nclass TestDemo(unittest.TestCase):\n \"\"\"Example of how to use unittest in Jupyter.\"\"\"\n\n def test(self):\n self.assertEqual(\"foo\".upper(), \"FOO\")", "_____no_output_____" ], [ "if __name__ == \"__main__\":\n unittest.main(argv=[\"first-arg-is-ignored\"], exit=False)", "_____no_output_____" ] ], [ [ "## Doctests", "_____no_output_____" ] ], [ [ "def add(a, b):\n \"\"\"\n Suma dos elementos.\n \n \n >>> add(2, 2)\n 4\n \n >>> add(10, 2)\n 12\n \n >>> add(125, 3)\n 128\n \"\"\"\n \n return a + b", "_____no_output_____" ], [ "import doctest\ndoctest.testmod(verbose=True)", "_____no_output_____" ], [ "datos_servers = {\n \"server_1\": [1,2,3],\n \"server_2\": [2,3,4],\n \"server_3\": [4,5,6],\n \"año\": 2020,\n \"admin\": \"ricardo\",\n \n}", "_____no_output_____" ], [ "## ejercicio escribir doctest para esta función\n\ndef filtrar_diccionario(dd):\n \"\"\"\n Devuelve las llaves de un diccionario que empiezan por 'server_'.\n \n Si la palabra 'server_' está en mitad de la key, no la captura,\n solamente si está al principio.\n \n >>> datos_servers = {\n ... \"server_1\": [1,2,3],\n ... \"server_2\": [2,3,4],\n ... \"server_3\": [4,5,6],\n ... \"año\": 2020,\n ... \"admin\": \"ricardo\",\n ... }\n \n >>> datos_servers_2 = {\n ... \"hola_server_1\": [1,2,3],\n ... \"server_2\": [2,3,4],\n ... \"server_3\": [4,5,6],\n ... \"año\": 2020,\n ... \"admin\": \"ricardo\",\n ... }\n \n >>> filtrar_diccionario(datos_servers)\n ['server_1', 'server_2', 'server_3']\n \n >>> filtrar_diccionario(datos_servers_2)\n ['server_2', 'server_3']\n \n >>> filtrar_diccionario({})\n []\n \n \n \"\"\"\n keys = []\n \n for llave in dd.keys():\n if llave.startswith(\"server_\"):\n keys.append(llave)\n \n return keys", "_____no_output_____" ], [ "filtrar_diccionario(datos_servers)", "_____no_output_____" ], [ "import doctest\ndoctest.testmod(verbose=True)", "_____no_output_____" ], [ "help(doctest)", "_____no_output_____" ], [ "import doctest\ndoctest.testmod(verbose=True)", "_____no_output_____" ] ], [ [ "## Ejercicio\n\nEscribir doctests para las funciontes anteriores!!!", "_____no_output_____" ], [ "```\nDirectory structure that makes running tests easy\nFuente: https://medium.com/@bfortuner/python-unit-testing-with-pytest-and-mock-197499c4623c\n\n/rootdir\n /src\n /jobitems \n api.py \n constants.py\n manager.py \n models.py \n tasks.py\n /tests \n /integ_tests \n /jobitems \n test_manager.py\n /unit_tests \n /jobitems \n test_manager.py \nrequirements.py \napplication.py\n\n\nHow do I run these tests?\n\n\npython -m pytest tests/ (all tests)\npython -m pytest -k filenamekeyword (tests matching keyword)\npython -m pytest tests/utils/test_sample.py (single test file)\npython -m pytest tests/utils/test_sample.py::test_answer_correct (single test method)\npython -m pytest --resultlog=testlog.log tests/ (log output to file)\npython -m pytest -s tests/ (print output to console)\n````\n", "_____no_output_____" ], [ "## Pytest Monekypatching", "_____no_output_____" ] ], [ [ "# contents of test_module.py with source code and the test\nfrom pathlib import Path\n\n\ndef getssh():\n \"\"\"Simple function to return expanded homedir ssh path.\"\"\"\n return Path.home() / \".ssh\"\n\n\ndef test_getssh(monkeypatch):\n # mocked return function to replace Path.home\n # always return '/abc'\n def mockreturn():\n return Path(\"/abc\")\n\n # Application of the monkeypatch to replace Path.home\n # with the behavior of mockreturn defined above.\n monkeypatch.setattr(Path, \"home\", mockreturn)\n\n # Calling getssh() will use mockreturn in place of Path.home\n # for this test with the monkeypatch.\n x = getssh()\n assert x == Path(\"/abc/.ssh\")", "_____no_output_____" ], [ "class C:\n def hola(self):\n print(\"Hola\")", "_____no_output_____" ], [ "c = C()", "_____no_output_____" ], [ "c.hola()", "_____no_output_____" ], [ "setattr(C, \"adios\", lambda x: print(\"adios\"))", "_____no_output_____" ], [ "f = C()", "_____no_output_____" ], [ "f.adios()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "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", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
cb2834d8beab927e425794f39227378bf018cdf6
15,056
ipynb
Jupyter Notebook
tutorials/plot-catalog/plot-catalog.ipynb
lethyciacarvalho/astropy-tutorials
e723b8c634efabb773f5ed0047aa50b44b10fb4c
[ "BSD-3-Clause" ]
210
2015-01-04T20:22:20.000Z
2022-03-29T23:39:09.000Z
tutorials/plot-catalog/plot-catalog.ipynb
keflavich/astropy-tutorials
18b480182156886f6057eb2127c07f2a8f8e8c5c
[ "BSD-3-Clause" ]
448
2015-01-04T17:11:43.000Z
2022-03-31T14:58:54.000Z
tutorials/plot-catalog/plot-catalog.ipynb
keflavich/astropy-tutorials
18b480182156886f6057eb2127c07f2a8f8e8c5c
[ "BSD-3-Clause" ]
150
2015-03-16T16:14:36.000Z
2022-02-08T23:47:21.000Z
32.309013
456
0.603812
[ [ [ "# Read in catalog information from a text file and plot some parameters\n\n## Authors\nAdrian Price-Whelan, Kelle Cruz, Stephanie T. Douglas\n\n## Learning Goals\n* Read an ASCII file using `astropy.io`\n* Convert between representations of coordinate components using `astropy.coordinates` (hours to degrees)\n* Make a spherical projection sky plot using `matplotlib`\n\n## Keywords\nfile input/output, coordinates, tables, units, scatter plots, matplotlib\n\n## Summary\n\nThis tutorial demonstrates the use of `astropy.io.ascii` for reading ASCII data, `astropy.coordinates` and `astropy.units` for converting RA (as a sexagesimal angle) to decimal degrees, and `matplotlib` for making a color-magnitude diagram and on-sky locations in a Mollweide projection.", "_____no_output_____" ] ], [ [ "import numpy as np\n\n# Set up matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ] ], [ [ "Astropy provides functionality for reading in and manipulating tabular\ndata through the `astropy.table` subpackage. An additional set of\ntools for reading and writing ASCII data are provided with the\n`astropy.io.ascii` subpackage, but fundamentally use the classes and\nmethods implemented in `astropy.table`.\n\nWe'll start by importing the `ascii` subpackage:", "_____no_output_____" ] ], [ [ "from astropy.io import ascii", "_____no_output_____" ] ], [ [ "For many cases, it is sufficient to use the `ascii.read('filename')` \nfunction as a black box for reading data from table-formatted text \nfiles. By default, this function will try to figure out how your \ndata is formatted/delimited (by default, `guess=True`). For example, \nif your data are:\n\n # name,ra,dec\n BLG100,17:51:00.0,-29:59:48\n BLG101,17:53:40.2,-29:49:52\n BLG102,17:56:20.2,-29:30:51\n BLG103,17:56:20.2,-30:06:22\n ...\n\n(see _simple_table.csv_)\n\n`ascii.read()` will return a `Table` object:", "_____no_output_____" ] ], [ [ "tbl = ascii.read(\"simple_table.csv\")\ntbl", "_____no_output_____" ] ], [ [ "The header names are automatically parsed from the top of the file,\nand the delimiter is inferred from the rest of the file -- awesome! \nWe can access the columns directly from their names as 'keys' of the\ntable object:", "_____no_output_____" ] ], [ [ "tbl[\"ra\"]", "_____no_output_____" ] ], [ [ "If we want to then convert the first RA (as a sexagesimal angle) to\ndecimal degrees, for example, we can pluck out the first (0th) item in\nthe column and use the `coordinates` subpackage to parse the string:", "_____no_output_____" ] ], [ [ "import astropy.coordinates as coord\nimport astropy.units as u\n\nfirst_row = tbl[0] # get the first (0th) row\nra = coord.Angle(first_row[\"ra\"], unit=u.hour) # create an Angle object\nra.degree # convert to degrees", "_____no_output_____" ] ], [ [ "Now let's look at a case where this breaks, and we have to specify some\nmore options to the `read()` function. Our data may look a bit messier::\n\n ,,,,2MASS Photometry,,,,,,WISE Photometry,,,,,,,,Spectra,,,,Astrometry,,,,,,,,,,,\n Name,Designation,RA,Dec,Jmag,J_unc,Hmag,H_unc,Kmag,K_unc,W1,W1_unc,W2,W2_unc,W3,W3_unc,W4,W4_unc,Spectral Type,Spectra (FITS),Opt Spec Refs,NIR Spec Refs,pm_ra (mas),pm_ra_unc,pm_dec (mas),pm_dec_unc,pi (mas),pi_unc,radial velocity (km/s),rv_unc,Astrometry Refs,Discovery Refs,Group/Age,Note\n ,00 04 02.84 -64 10 35.6,1.01201,-64.18,15.79,0.07,14.83,0.07,14.01,0.05,13.37,0.03,12.94,0.03,12.18,0.24,9.16,null,L1γ,,Kirkpatrick et al. 2010,,,,,,,,,,,Kirkpatrick et al. 2010,,\n PC 0025+04,00 27 41.97 +05 03 41.7,6.92489,5.06,16.19,0.09,15.29,0.10,14.96,0.12,14.62,0.04,14.14,0.05,12.24,null,8.89,null,M9.5β,,Mould et al. 1994,,0.0105,0.0004,-0.0008,0.0003,,,,,Faherty et al. 2009,Schneider et al. 1991,,,00 32 55.84 -44 05 05.8,8.23267,-44.08,14.78,0.04,13.86,0.03,13.27,0.04,12.82,0.03,12.49,0.03,11.73,0.19,9.29,null,L0γ,,Cruz et al. 2009,,0.1178,0.0043,-0.0916,0.0043,38.4,4.8,,,Faherty et al. 2012,Reid et al. 2008,,\n ...\n\n(see _Young-Objects-Compilation.csv_)", "_____no_output_____" ], [ "If we try to just use `ascii.read()` on this data, it fails to parse the names out and the column names become `col` followed by the number of the column:", "_____no_output_____" ] ], [ [ "tbl = ascii.read(\"Young-Objects-Compilation.csv\")\ntbl.colnames", "_____no_output_____" ] ], [ [ "What happened? The column names are just `col1`, `col2`, etc., the\ndefault names if `ascii.read()` is unable to parse out column\nnames. We know it failed to read the column names, but also notice\nthat the first row of data are strings -- something else went wrong!", "_____no_output_____" ] ], [ [ "tbl[0]", "_____no_output_____" ] ], [ [ "A few things are causing problems here. First, there are two header \nlines in the file and the header lines are not denoted by comment \ncharacters. The first line is actually some meta data that we don't\ncare about, so we want to skip it. We can get around this problem by \nspecifying the `header_start` keyword to the `ascii.read()` function. \nThis keyword argument specifies the index of the row in the text file \nto read the column names from:", "_____no_output_____" ] ], [ [ "tbl = ascii.read(\"Young-Objects-Compilation.csv\", header_start=1)\ntbl.colnames", "_____no_output_____" ] ], [ [ "Great! Now the columns have the correct names, but there is still a\nproblem: all of the columns have string data types, and the column\nnames are still included as a row in the table. This is because by\ndefault the data are assumed to start on the second row (index=1). \nWe can specify `data_start=2` to tell the reader that the data in\nthis file actually start on the 3rd (index=2) row:", "_____no_output_____" ] ], [ [ "tbl = ascii.read(\"Young-Objects-Compilation.csv\", header_start=1, data_start=2)", "_____no_output_____" ] ], [ [ "Some of the columns have missing data, for example, some of the `RA` values are missing (denoted by -- when printed):", "_____no_output_____" ] ], [ [ "print(tbl['RA'])", "_____no_output_____" ] ], [ [ "This is called a __Masked column__ because some missing values are \nmasked out upon display. If we want to use this numeric data, we have\nto tell `astropy` what to fill the missing values with. We can do this\nwith the `.filled()` method. For example, to fill all of the missing\nvalues with `NaN`'s:", "_____no_output_____" ] ], [ [ "tbl['RA'].filled(np.nan)", "_____no_output_____" ] ], [ [ "Let's recap what we've done so far, then make some plots with the\ndata. Our data file has an extra line above the column names, so we\nuse the `header_start` keyword to tell it to start from line 1 instead\nof line 0 (remember Python is 0-indexed!). We then used had to specify\nthat the data starts on line 2 using the `data_start`\nkeyword. Finally, we note some columns have missing values.", "_____no_output_____" ] ], [ [ "data = ascii.read(\"Young-Objects-Compilation.csv\", header_start=1, data_start=2)", "_____no_output_____" ] ], [ [ "Now that we have our data loaded, let's plot a color-magnitude diagram.", "_____no_output_____" ], [ "Here we simply make a scatter plot of the J-K color on the x-axis\nagainst the J magnitude on the y-axis. We use a trick to flip the\ny-axis `plt.ylim(reversed(plt.ylim()))`. Called with no arguments,\n`plt.ylim()` will return a tuple with the axis bounds, \ne.g. (0,10). Calling the function _with_ arguments will set the limits \nof the axis, so we simply set the limits to be the reverse of whatever they\nwere before. Using this `pylab`-style plotting is convenient for\nmaking quick plots and interactive use, but is not great if you need\nmore control over your figures.", "_____no_output_____" ] ], [ [ "plt.scatter(data[\"Jmag\"] - data[\"Kmag\"], data[\"Jmag\"]) # plot J-K vs. J\nplt.ylim(reversed(plt.ylim())) # flip the y-axis\nplt.xlabel(\"$J-K_s$\", fontsize=20)\nplt.ylabel(\"$J$\", fontsize=20)", "_____no_output_____" ] ], [ [ "As a final example, we will plot the angular positions from the\ncatalog on a 2D projection of the sky. Instead of using `pylab`-style\nplotting, we'll take a more object-oriented approach. We'll start by\ncreating a `Figure` object and adding a single subplot to the\nfigure. We can specify a projection with the `projection` keyword; in\nthis example we will use a Mollweide projection. Unfortunately, it is \nhighly non-trivial to make the matplotlib projection defined this way \nfollow the celestial convention of longitude/RA increasing to the left. \n\nThe axis object, `ax`, knows to expect angular coordinate\nvalues. An important fact is that it expects the values to be in\n_radians_, and it expects the azimuthal angle values to be between\n(-180º,180º). This is (currently) not customizable, so we have to\ncoerce our RA data to conform to these rules! `astropy` provides a\ncoordinate class for handling angular values, `astropy.coordinates.Angle`. \nWe can convert our column of RA values to radians, and wrap the \nangle bounds using this class.", "_____no_output_____" ] ], [ [ "ra = coord.Angle(data['RA'].filled(np.nan)*u.degree)\nra = ra.wrap_at(180*u.degree)\ndec = coord.Angle(data['Dec'].filled(np.nan)*u.degree)", "_____no_output_____" ], [ "fig = plt.figure(figsize=(8,6))\nax = fig.add_subplot(111, projection=\"mollweide\")\nax.scatter(ra.radian, dec.radian)", "_____no_output_____" ] ], [ [ "By default, matplotlib will add degree tick labels, so let's change the\nhorizontal (x) tick labels to be in units of hours, and display a grid:", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(8,6))\nax = fig.add_subplot(111, projection=\"mollweide\")\nax.scatter(ra.radian, dec.radian)\nax.set_xticklabels(['14h','16h','18h','20h','22h','0h','2h','4h','6h','8h','10h'])\nax.grid(True)", "_____no_output_____" ] ], [ [ "We can save this figure as a PDF using the `savefig` function:", "_____no_output_____" ] ], [ [ "fig.savefig(\"map.pdf\")", "_____no_output_____" ] ], [ [ "## Exercises", "_____no_output_____" ], [ "Make the map figures as just above, but color the points by the `'Kmag'` column of the table.", "_____no_output_____" ], [ "Try making the maps again, but with each of the following projections: `aitoff`, `hammer`, `lambert`, and `None` (which is the same as not giving any projection). Do any of them make the data seem easier to understand?", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
cb28350a483a5a01c1cfffa4c9bbb2afce3d6425
3,746
ipynb
Jupyter Notebook
Day 6.ipynb
jaiyesh/15Petro-Numpy-Days
42362b62b220ab04a2c584ae66441c0e22c35af9
[ "MIT" ]
3
2022-01-28T14:33:17.000Z
2022-02-09T15:28:46.000Z
Day 6.ipynb
jaiyesh/15Petro-Numpy-Days
42362b62b220ab04a2c584ae66441c0e22c35af9
[ "MIT" ]
null
null
null
Day 6.ipynb
jaiyesh/15Petro-Numpy-Days
42362b62b220ab04a2c584ae66441c0e22c35af9
[ "MIT" ]
null
null
null
16.21645
114
0.448745
[ [ [ "# Day 6 of #15PetroNumpyDays", "_____no_output_____" ], [ "# Array Indexing (1 D Arrays)\n- Accessing array elements\n- The indexes starts with 0 just like lists, meaning that first element has index 0, and second has index 1.", "_____no_output_____" ] ], [ [ "import numpy as np ", "_____no_output_____" ], [ "array = np.array([1,2,3])", "_____no_output_____" ], [ "type(array[0])", "_____no_output_____" ], [ "arr = np.array([1,23,45,67,'pfs','jaiyesh','last'])", "_____no_output_____" ], [ "type(arr[0])", "_____no_output_____" ], [ "arr[6]", "_____no_output_____" ], [ "arr[-1]", "_____no_output_____" ], [ "arr[2]", "_____no_output_____" ], [ "arr[-5]", "_____no_output_____" ], [ "array[2]+ array[1]", "_____no_output_____" ], [ "arr[-1] + arr[0]", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb2841f59c26822dd89289a1a88f3d6410ccd822
41,018
ipynb
Jupyter Notebook
greyatom-capstone/notebooks/feature_engineering.ipynb
I-Tingya/ML-end-to-end-problems-solutions
bc14bbbee074c2e8e1db064dee4cae2cbd415fd8
[ "MIT" ]
null
null
null
greyatom-capstone/notebooks/feature_engineering.ipynb
I-Tingya/ML-end-to-end-problems-solutions
bc14bbbee074c2e8e1db064dee4cae2cbd415fd8
[ "MIT" ]
null
null
null
greyatom-capstone/notebooks/feature_engineering.ipynb
I-Tingya/ML-end-to-end-problems-solutions
bc14bbbee074c2e8e1db064dee4cae2cbd415fd8
[ "MIT" ]
null
null
null
43.131441
8,342
0.534375
[ [ [ "#Feature Engineering Notebook\nData given was in raw format and it needed to be converted into format which model could make sense. We considered data of 150K users while modelling. <br>\nA data frame **final_df** was created with all the features.<br>\nA dataframe **uninstall_unique** was created which had data of the users and the latest uninstalled date. ", "_____no_output_____" ], [ "##Mount Google drive in Colab where data is stored ", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')\nimport os\n#os.chdir('drive/My Drive/Capstone/CleverTap Capstone/Data\")", "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&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&response_type=code\n\nEnter your authorization code:\n··········\nMounted at /content/drive\n" ] ], [ [ "## Import necessary python libraries<br>\nAs the data was large we tried to use modin for faster computation but we found it was slower than pandas. ", "_____no_output_____" ] ], [ [ "#!pip install modin\n#!pip install --upgrade pandas\n#!pip install ray\n\nimport pandas as pd\nimport numpy as np\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom tqdm import tqdm\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\n", "_____no_output_____" ] ], [ [ "##Function: inttostr()\nAll the six csv data files had date column and the dates were in integer format.This function converted and formatted the dates.", "_____no_output_____" ] ], [ [ "def inttostr(x):\n x = str(x)\n return x[:4]+'-'+x[4:6]+'-'+x[6:]", "_____no_output_____" ] ], [ [ "### Cell description\nBelow cell stores the number of times a user launched the app and the number of days between first launch and latest launch. Number of days were used to create additional feature **launch_rate**", "_____no_output_____" ] ], [ [ "launch = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/AppLaunched.csv')\nlaunch['Date'] = pd.to_datetime(launch['Date'].apply(lambda x:inttostr(x)))\nuserids = launch.UserId.unique()[0:150000]\nlaunch_days_list=[]\ninstall_list=[]\n\nfor uid in tqdm(userids):\n temp = launch.loc[launch.UserId==uid] \n \n launch_days_list.append((temp.Date.max()-temp.Date.min()).days)\n install_list.append(temp.shape[0])\n \n ", "_____no_output_____" ] ], [ [ "### Cell Description\nBelow cell stores the latest status of user in the form completed, not completed or unknown.", "_____no_output_____" ] ], [ [ "registration = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/Registration.csv')\nregistration.Status=registration.Status.replace({'Complete':'Completed'})\nstatus_list=[]\ncountry_list = []\n\n\nfor uid in tqdm(userids):\n \n temp = registration.loc[registration.UserId==uid]\n status = temp.Status.tolist()[-1] if len(temp.Status.tolist())>0 else 'Unknown'\n status_list.append(status)\n if temp.shape[0]>0:\n country_list.append(temp.Country.value_counts().values[0])\n \n else:\n country_list.append(0)\n ", "100%|██████████| 25000/25000 [10:44<00:00, 38.76it/s]\n" ], [ "#final_df = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/final_df.csv',index_col=0)\n", "_____no_output_____" ], [ "def top_country(x):\n if x>2:\n return 5\n else:return x\ntemp = pd.Series(country_list).apply(lambda x:top_country(x))\n\ntemp = temp.replace({0:'A',1:'B',2:'C',5:'MISC'})\ncountry_list = temp.tolist()\n", "_____no_output_____" ], [ "temp.value_counts()", "_____no_output_____" ], [ "final_df = pd.get_dummies(final_df)\nfinal_df.to_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/final_df.csv')", "_____no_output_____" ] ], [ [ "### Cell Description\nBelow cell stores the number of times a user clicked UTM.", "_____no_output_____" ] ], [ [ "utmvisited = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/UTMVisited.csv')\nutm_list = []\nfor uid in tqdm(userids):\n temp = utmvisited.loc[utmvisited.UserId==uid]\n utm_list.append(temp.shape[0])\n#utm_list = pd.Series(utm_list)\n#utm_list.to_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/utm_visted.csv')", "100%|██████████| 25000/25000 [16:39<00:00, 25.01it/s]\n" ] ], [ [ "### Cell Description\nBelow cell stores number of videos a user watched genre wise, category wise and program_type_dict wise. <br>\nIt also stores number of days user was active and number of videos he watched repetitively. <br>\nNumber of days is used later to calculate number of videos a user watched per day.\n", "_____no_output_____" ] ], [ [ "vidstarted = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/VideoStarted.csv')\nvidstarted['Date'] = pd.to_datetime(vidstarted['Date'].apply(lambda x:inttostr(x)))\n\ngenre_dict = {genre:np.zeros(len(userids)) for genre in vidstarted.Genre.unique()}\ncategory_dict = {cat:np.zeros(len(userids)) for cat in vidstarted.Category.unique()}\nprogram_type_dict = {ptype:np.zeros(len(userids)) for ptype in vidstarted.ProgramType.unique()}\n\nvidstart_days_list=[]\nwatches_rep_vid_list = []\n\nfor idx,uid in enumerate(tqdm(userids)):\n temp = vidstarted.loc[vidstarted.UserId==uid]\n \n \n for genre in temp.Genre.tolist():genre_dict[genre][idx]+=1;\n for cat in temp.Category.tolist():category_dict[cat][idx]+=1;\n for ptype in temp.ProgramType.tolist():program_type_dict[ptype][idx]+=1;\n \n vidstart_days_list.append((temp.Date.max()-temp.Date.min()).days)\n \n if len(temp.VideoId.value_counts().values)>2:\n rvf = temp.VideoId.value_counts().values[0] + temp.VideoId.value_counts().values[1] #if temp.VideoId.value_counts().values[0]>1\n elif len(temp.VideoId.value_counts().values)==1:\n rvf = temp.VideoId.value_counts().values[0]\n else: rvf=0\n \n watches_rep_vid_list.append(rvf)\n \n ", "_____no_output_____" ], [ "temp = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/VideoStarted.csv')\ntemp = temp[temp.UserId.isin(userids)]\ntemp.shape", "_____no_output_____" ] ], [ [ "###Cell Description\nBelow cell merges three dictionaries genre, category and program type into single dictionary. Keys of these dictionaries will be used as features in final dataframe.", "_____no_output_____" ] ], [ [ "movie_det_dict = {**genre_dict, **category_dict, **program_type_dict}", "_____no_output_____" ] ], [ [ "### Cell Description\nBelow cell stores the number of times a user has watched video details.", "_____no_output_____" ] ], [ [ "viddetails = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/VideoDetails.csv')\nviddetails['Date'] = pd.to_datetime(viddetails['Date'].apply(lambda x:inttostr(x)))\n\ntemp = viddetails.loc[viddetails.UserId.isin(userids)]\n\ncnt_series = temp.UserId.value_counts()\nviewed_vid_cnt = [cnt_series.loc[uid] if uid in cnt_series.index else 0 for uid in tqdm(userids) ]\n\n#viddet_days_list = [(viddetails.loc[viddetails.UserId.isin(list(uid))]['Date'].max()-viddetails.loc[viddetails.UserId.isin(list(uid))]['Date'].max()).days for uid in tqdm(userids)]", "100%|██████████| 25000/25000 [00:00<00:00, 71258.02it/s]\n" ] ], [ [ "### Cell Description\nBelow cell creates empty data frame **final_df** and stores all the features generated till now in the dataframe.", "_____no_output_____" ] ], [ [ "final_df = pd.DataFrame(data=movie_det_dict)\n\nfinal_df['launched_days'] = pd.Series(launch_days_list)\nfinal_df['installed_times'] = pd.Series(install_list)\nfinal_df['reg_status'] = pd.Series(status_list)\nfinal_df['utm_visited_times'] = pd.Series(utm_list)\nfinal_df['watched_days'] = pd.Series(vidstart_days_list)\nfinal_df['vid_rep_count'] = pd.Series(watches_rep_vid_list)\nfinal_df['viddet_view_cnt'] = pd.Series(viewed_vid_cnt)\nfinal_df['country'] = pd.Series(country_list)\nfinal_df.index = userids\nfinal_df.head()", "_____no_output_____" ] ], [ [ "### Cell Description\nBelow cell creates dummy variables for all the categorical features.", "_____no_output_____" ] ], [ [ "final_df = pd.get_dummies(final_df);\nfinal_df.shape", "_____no_output_____" ] ], [ [ "### Save the dataframe in csv file", "_____no_output_____" ] ], [ [ "final_df.to_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/final_df.csv')", "_____no_output_____" ] ], [ [ "### Cell Description\nBelow cell creates and stores a dataframe which contains latest entry when user uninstalled the app, leaving any previous uninstall records.\n", "_____no_output_____" ] ], [ [ "uninstall_unique = pd.DataFrame()\nuninstall = pd.read_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/AppUninstalled.csv')\nuninstall['Date'] = pd.to_datetime(uninstall['Date'].apply(lambda x:inttostr(x)))\n\nfor uid in tqdm(userids):\n temp = uninstall.loc[uninstall.UserId==uid]\n temp = temp[temp.Date==temp.Date.max()]\n uninstall_unique = pd.concat([uninstall_unique,temp])\n\nuninstall_unique.to_csv('drive/My Drive/Capstone/CleverTap Capstone/Data/uninstall_unique.csv')\n", "100%|██████████| 25000/25000 [12:40<00:00, 32.39it/s]\n" ], [ "import matplotlib.pyplot as plt\n%matplotlib inline\ntemp.VideoId.value_counts().plot(kind='hist',bins=2000)\nplt.xlim(0,1000)", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
cb284dba07320c18d08c83e40a1d3a1aaf961a9c
2,151
ipynb
Jupyter Notebook
_notebooks/2021-08-01-soundcloud-nos-pod.ipynb
jimregan/notes
24e374d326b4e96b7d31d08a808f9f19fe473e76
[ "Apache-2.0" ]
1
2021-08-25T08:08:45.000Z
2021-08-25T08:08:45.000Z
_notebooks/2021-08-01-soundcloud-nos-pod.ipynb
jimregan/notes
24e374d326b4e96b7d31d08a808f9f19fe473e76
[ "Apache-2.0" ]
null
null
null
_notebooks/2021-08-01-soundcloud-nos-pod.ipynb
jimregan/notes
24e374d326b4e96b7d31d08a808f9f19fe473e76
[ "Apache-2.0" ]
null
null
null
23.637363
88
0.564854
[ [ [ "# Soundcloud - NÓS\n\n> \"Dataset\"\n\n- toc: false\n- branch: master\n- badges: false\n- comments: true\n- hidden: true\n- categories: [kaggle, irish, soundcloud, dataset, unlabelled, nos]", "_____no_output_____" ], [ "Original on [Kaggle](https://www.kaggle.com/jimregan/soundcloud-nos-pod) (private)", "_____no_output_____" ] ], [ [ "!pip install youtube-dl\n!youtube-dl https://soundcloud.com/nosmag", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ] ]
cb2854f23ca881d87c6d1d769326777baa341f0c
36,805
ipynb
Jupyter Notebook
tp8/Vino.ipynb
xRUIZxMATIASx/inteligencia-artificial
f4439bb8e299baf18efb7013e0d16b2b13684ab9
[ "Apache-2.0" ]
null
null
null
tp8/Vino.ipynb
xRUIZxMATIASx/inteligencia-artificial
f4439bb8e299baf18efb7013e0d16b2b13684ab9
[ "Apache-2.0" ]
null
null
null
tp8/Vino.ipynb
xRUIZxMATIASx/inteligencia-artificial
f4439bb8e299baf18efb7013e0d16b2b13684ab9
[ "Apache-2.0" ]
null
null
null
34.952517
105
0.47643
[ [ [ "import pandas as pd\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.neural_network import MLPRegressor\nfrom io import StringIO\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()", "_____no_output_____" ], [ "wine = pd.read_csv(\"winequality-red.csv\")\nwine.head()", "_____no_output_____" ], [ "data = wine.values[:,:11]\ndata_columns = list(wine.columns.values[:11])\ntarget=wine.values[:,11]", "_____no_output_____" ] ], [ [ "## Separar datos en entrenamiento y prueba", "_____no_output_____" ] ], [ [ "X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.3, random_state=1)\npd.DataFrame(X_train).head()", "_____no_output_____" ] ], [ [ "## Escalar valores", "_____no_output_____" ] ], [ [ "X_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\npd.DataFrame(X_train).head()", "_____no_output_____" ] ], [ [ "## Definir Regresor", "_____no_output_____" ] ], [ [ "mlp = MLPRegressor(max_iter=700,\n hidden_layer_sizes=(5,5),\n activation='logistic',\n learning_rate_init=0.01, \n verbose = True\n )\nmlp.fit(X_train, y_train)", "Iteration 1, loss = 16.40568125\nIteration 2, loss = 14.98385332\nIteration 3, loss = 13.66503007\nIteration 4, loss = 12.43441358\nIteration 5, loss = 11.27431100\nIteration 6, loss = 10.18349913\nIteration 7, loss = 9.14161233\nIteration 8, loss = 8.14911685\nIteration 9, loss = 7.19811511\nIteration 10, loss = 6.29199267\nIteration 11, loss = 5.42358702\nIteration 12, loss = 4.60193036\nIteration 13, loss = 3.83087128\nIteration 14, loss = 3.12761393\nIteration 15, loss = 2.49067854\nIteration 16, loss = 1.93989357\nIteration 17, loss = 1.47802858\nIteration 18, loss = 1.11011636\nIteration 19, loss = 0.83995336\nIteration 20, loss = 0.64605819\nIteration 21, loss = 0.51336682\nIteration 22, loss = 0.42786952\nIteration 23, loss = 0.37449775\nIteration 24, loss = 0.34125075\nIteration 25, loss = 0.31963982\nIteration 26, loss = 0.30687414\nIteration 27, loss = 0.29637906\nIteration 28, loss = 0.28936412\nIteration 29, loss = 0.28326056\nIteration 30, loss = 0.27862750\nIteration 31, loss = 0.27473363\nIteration 32, loss = 0.27163716\nIteration 33, loss = 0.26902075\nIteration 34, loss = 0.26670033\nIteration 35, loss = 0.26485670\nIteration 36, loss = 0.26307349\nIteration 37, loss = 0.26154555\nIteration 38, loss = 0.26009096\nIteration 39, loss = 0.25887826\nIteration 40, loss = 0.25763053\nIteration 41, loss = 0.25653641\nIteration 42, loss = 0.25556965\nIteration 43, loss = 0.25456074\nIteration 44, loss = 0.25363011\nIteration 45, loss = 0.25282787\nIteration 46, loss = 0.25205035\nIteration 47, loss = 0.25128995\nIteration 48, loss = 0.25063472\nIteration 49, loss = 0.24994974\nIteration 50, loss = 0.24938240\nIteration 51, loss = 0.24875700\nIteration 52, loss = 0.24821111\nIteration 53, loss = 0.24764279\nIteration 54, loss = 0.24718228\nIteration 55, loss = 0.24654545\nIteration 56, loss = 0.24615157\nIteration 57, loss = 0.24560153\nIteration 58, loss = 0.24507695\nIteration 59, loss = 0.24466233\nIteration 60, loss = 0.24417152\nIteration 61, loss = 0.24375388\nIteration 62, loss = 0.24324855\nIteration 63, loss = 0.24274784\nIteration 64, loss = 0.24234442\nIteration 65, loss = 0.24190920\nIteration 66, loss = 0.24149783\nIteration 67, loss = 0.24112779\nIteration 68, loss = 0.24075562\nIteration 69, loss = 0.24034298\nIteration 70, loss = 0.23997525\nIteration 71, loss = 0.23957181\nIteration 72, loss = 0.23925139\nIteration 73, loss = 0.23886153\nIteration 74, loss = 0.23858557\nIteration 75, loss = 0.23814040\nIteration 76, loss = 0.23786581\nIteration 77, loss = 0.23751236\nIteration 78, loss = 0.23716246\nIteration 79, loss = 0.23682640\nIteration 80, loss = 0.23656381\nIteration 81, loss = 0.23621682\nIteration 82, loss = 0.23592352\nIteration 83, loss = 0.23559496\nIteration 84, loss = 0.23529961\nIteration 85, loss = 0.23499465\nIteration 86, loss = 0.23467452\nIteration 87, loss = 0.23436822\nIteration 88, loss = 0.23410441\nIteration 89, loss = 0.23379835\nIteration 90, loss = 0.23350894\nIteration 91, loss = 0.23315130\nIteration 92, loss = 0.23291183\nIteration 93, loss = 0.23259203\nIteration 94, loss = 0.23232052\nIteration 95, loss = 0.23200265\nIteration 96, loss = 0.23171910\nIteration 97, loss = 0.23131153\nIteration 98, loss = 0.23100922\nIteration 99, loss = 0.23061291\nIteration 100, loss = 0.23030028\nIteration 101, loss = 0.22994553\nIteration 102, loss = 0.22963410\nIteration 103, loss = 0.22924145\nIteration 104, loss = 0.22900082\nIteration 105, loss = 0.22850161\nIteration 106, loss = 0.22814813\nIteration 107, loss = 0.22777132\nIteration 108, loss = 0.22742276\nIteration 109, loss = 0.22704782\nIteration 110, loss = 0.22659669\nIteration 111, loss = 0.22631532\nIteration 112, loss = 0.22596436\nIteration 113, loss = 0.22553592\nIteration 114, loss = 0.22523586\nIteration 115, loss = 0.22481184\nIteration 116, loss = 0.22444693\nIteration 117, loss = 0.22406437\nIteration 118, loss = 0.22371183\nIteration 119, loss = 0.22339191\nIteration 120, loss = 0.22303979\nIteration 121, loss = 0.22262726\nIteration 122, loss = 0.22233303\nIteration 123, loss = 0.22206836\nIteration 124, loss = 0.22158204\nIteration 125, loss = 0.22124338\nIteration 126, loss = 0.22086184\nIteration 127, loss = 0.22054356\nIteration 128, loss = 0.22021758\nIteration 129, loss = 0.21985065\nIteration 130, loss = 0.21961553\nIteration 131, loss = 0.21928543\nIteration 132, loss = 0.21884632\nIteration 133, loss = 0.21853412\nIteration 134, loss = 0.21819553\nIteration 135, loss = 0.21788234\nIteration 136, loss = 0.21760530\nIteration 137, loss = 0.21722926\nIteration 138, loss = 0.21689480\nIteration 139, loss = 0.21668025\nIteration 140, loss = 0.21633308\nIteration 141, loss = 0.21606442\nIteration 142, loss = 0.21577433\nIteration 143, loss = 0.21542213\nIteration 144, loss = 0.21513881\nIteration 145, loss = 0.21482599\nIteration 146, loss = 0.21453244\nIteration 147, loss = 0.21430501\nIteration 148, loss = 0.21406390\nIteration 149, loss = 0.21376522\nIteration 150, loss = 0.21355968\nIteration 151, loss = 0.21321204\nIteration 152, loss = 0.21295978\nIteration 153, loss = 0.21270050\nIteration 154, loss = 0.21250392\nIteration 155, loss = 0.21219507\nIteration 156, loss = 0.21200172\nIteration 157, loss = 0.21173093\nIteration 158, loss = 0.21139536\nIteration 159, loss = 0.21128155\nIteration 160, loss = 0.21092491\nIteration 161, loss = 0.21069167\nIteration 162, loss = 0.21050523\nIteration 163, loss = 0.21032665\nIteration 164, loss = 0.20994886\nIteration 165, loss = 0.20970769\nIteration 166, loss = 0.20952014\nIteration 167, loss = 0.20929356\nIteration 168, loss = 0.20912592\nIteration 169, loss = 0.20885496\nIteration 170, loss = 0.20856391\nIteration 171, loss = 0.20834399\nIteration 172, loss = 0.20808789\nIteration 173, loss = 0.20799563\nIteration 174, loss = 0.20763963\nIteration 175, loss = 0.20745244\nIteration 176, loss = 0.20721927\nIteration 177, loss = 0.20701661\nIteration 178, loss = 0.20670426\nIteration 179, loss = 0.20663146\nIteration 180, loss = 0.20626081\nIteration 181, loss = 0.20603263\nIteration 182, loss = 0.20588056\nIteration 183, loss = 0.20555412\nIteration 184, loss = 0.20529909\nIteration 185, loss = 0.20510364\nIteration 186, loss = 0.20490265\nIteration 187, loss = 0.20473985\nIteration 188, loss = 0.20459358\nIteration 189, loss = 0.20432967\nIteration 190, loss = 0.20418750\nIteration 191, loss = 0.20395387\nIteration 192, loss = 0.20394274\nIteration 193, loss = 0.20362771\nIteration 194, loss = 0.20332769\nIteration 195, loss = 0.20319828\nIteration 196, loss = 0.20309754\nIteration 197, loss = 0.20289095\nIteration 198, loss = 0.20280085\nIteration 199, loss = 0.20258500\nIteration 200, loss = 0.20231397\nIteration 201, loss = 0.20214363\nIteration 202, loss = 0.20203756\nIteration 203, loss = 0.20174767\nIteration 204, loss = 0.20165825\nIteration 205, loss = 0.20152086\nIteration 206, loss = 0.20124892\nIteration 207, loss = 0.20112673\nIteration 208, loss = 0.20090056\nIteration 209, loss = 0.20077562\nIteration 210, loss = 0.20060704\nIteration 211, loss = 0.20038542\nIteration 212, loss = 0.20015743\nIteration 213, loss = 0.20004794\nIteration 214, loss = 0.19989797\nIteration 215, loss = 0.19968791\nIteration 216, loss = 0.19945489\nIteration 217, loss = 0.19929574\nIteration 218, loss = 0.19917371\nIteration 219, loss = 0.19899684\nIteration 220, loss = 0.19884249\nIteration 221, loss = 0.19864023\nIteration 222, loss = 0.19849116\nIteration 223, loss = 0.19836640\nIteration 224, loss = 0.19808144\nIteration 225, loss = 0.19795749\nIteration 226, loss = 0.19785889\nIteration 227, loss = 0.19768263\nIteration 228, loss = 0.19748823\nIteration 229, loss = 0.19740244\nIteration 230, loss = 0.19727861\nIteration 231, loss = 0.19720723\nIteration 232, loss = 0.19691215\nIteration 233, loss = 0.19687376\nIteration 234, loss = 0.19667451\nIteration 235, loss = 0.19657895\nIteration 236, loss = 0.19649255\nIteration 237, loss = 0.19625329\nIteration 238, loss = 0.19621584\nIteration 239, loss = 0.19631446\nIteration 240, loss = 0.19591782\nIteration 241, loss = 0.19583288\nIteration 242, loss = 0.19588612\nIteration 243, loss = 0.19560164\nIteration 244, loss = 0.19550430\nIteration 245, loss = 0.19535107\nIteration 246, loss = 0.19519484\nIteration 247, loss = 0.19503136\nIteration 248, loss = 0.19495861\nIteration 249, loss = 0.19490159\nIteration 250, loss = 0.19485835\nIteration 251, loss = 0.19460844\nIteration 252, loss = 0.19458594\nIteration 253, loss = 0.19442115\nIteration 254, loss = 0.19431718\nIteration 255, loss = 0.19428327\nIteration 256, loss = 0.19407776\nIteration 257, loss = 0.19401431\nIteration 258, loss = 0.19390730\nIteration 259, loss = 0.19373131\nIteration 260, loss = 0.19361221\nIteration 261, loss = 0.19352581\nIteration 262, loss = 0.19337754\nIteration 263, loss = 0.19325435\nIteration 264, loss = 0.19328031\nIteration 265, loss = 0.19314459\nIteration 266, loss = 0.19295675\nIteration 267, loss = 0.19287008\nIteration 268, loss = 0.19275024\nIteration 269, loss = 0.19267788\nIteration 270, loss = 0.19254380\nIteration 271, loss = 0.19256999\nIteration 272, loss = 0.19245743\nIteration 273, loss = 0.19224125\nIteration 274, loss = 0.19213106\nIteration 275, loss = 0.19208428\nIteration 276, loss = 0.19204926\nIteration 277, loss = 0.19196816\nIteration 278, loss = 0.19173626\nIteration 279, loss = 0.19161561\nIteration 280, loss = 0.19157464\nIteration 281, loss = 0.19139771\nIteration 282, loss = 0.19133284\nIteration 283, loss = 0.19131226\nIteration 284, loss = 0.19134124\nIteration 285, loss = 0.19098913\nIteration 286, loss = 0.19108342\nIteration 287, loss = 0.19091848\nIteration 288, loss = 0.19075673\n" ] ], [ [ "### Obtener error", "_____no_output_____" ] ], [ [ "y_pred = mlp.predict(X_test)\nerror =metrics.mean_squared_error(y_test,y_pred)\nprint(error)", "0.4211382159668619\n" ] ], [ [ "### Prueba\n\nObtener un valor cualquiera del conjunto de datos de entrenamiento", "_____no_output_____" ] ], [ [ "X_sample = X_test[300]\ny_sample =y_test[300]", "_____no_output_____" ] ], [ [ "### Calcular calidad", "_____no_output_____" ] ], [ [ "y_pred = mlp.predict(X_sample.reshape(1, -1))\nprint(\"El sistema da como resultado una calidad de vino de \"+str(y_pred[0]))\nprint(\"La calidad real del vino es \"+str(y_sample))", "El sistema da como resultado una calidad de vino de 5.414672350844787\nLa calidad real del vino es 6.0\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
cb2855309215c5544ac6a595925883c72d4c34d2
755,127
ipynb
Jupyter Notebook
misc/Hough_Lines_rails_only.ipynb
ccc-frankfurt/dronelab
9b614fc7c3d21718f3de04376a5a5fb3d0248cbf
[ "MIT" ]
1
2021-05-06T13:53:27.000Z
2021-05-06T13:53:27.000Z
misc/Hough_Lines_rails_only.ipynb
ccc-frankfurt/dronelab
9b614fc7c3d21718f3de04376a5a5fb3d0248cbf
[ "MIT" ]
null
null
null
misc/Hough_Lines_rails_only.ipynb
ccc-frankfurt/dronelab
9b614fc7c3d21718f3de04376a5a5fb3d0248cbf
[ "MIT" ]
null
null
null
865.97133
137,072
0.957431
[ [ [ "import os\nimport cv2\nimport numpy as np\n#import layers\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "# credits to https://towardsdatascience.com/lines-detection-with-hough-transform-84020b3b1549\n\nimport matplotlib.lines as mlines\n\n# ist a,b == m, c\n\ndef line_detection_non_vectorized(image, edge_image, num_rhos=100, num_thetas=100, t_count=220):\n edge_height, edge_width = edge_image.shape[:2]\n edge_height_half, edge_width_half = edge_height / 2, edge_width / 2\n #\n d = np.sqrt(np.square(edge_height) + np.square(edge_width))\n dtheta = 180 / num_thetas\n drho = (2 * d) / num_rhos\n #\n thetas = np.arange(0, 180, step=dtheta)\n rhos = np.arange(-d, d, step=drho)\n #\n cos_thetas = np.cos(np.deg2rad(thetas))\n sin_thetas = np.sin(np.deg2rad(thetas))\n #\n accumulator = np.zeros((len(rhos), len(rhos)))\n #\n figure = plt.figure(figsize=(12, 12))\n subplot1 = figure.add_subplot(1, 4, 1)\n subplot1.imshow(image, cmap=\"gray\")\n subplot2 = figure.add_subplot(1, 4, 2)\n subplot2.imshow(edge_image, cmap=\"gray\")\n subplot3 = figure.add_subplot(1, 4, 3)\n subplot3.set_facecolor((0, 0, 0))\n subplot4 = figure.add_subplot(1, 4, 4)\n subplot4.imshow(image, cmap=\"gray\")\n #\n for y in range(edge_height):\n for x in range(edge_width):\n if edge_image[y][x] != 0:\n edge_point = [y - edge_height_half, x - edge_width_half]\n ys, xs = [], []\n for theta_idx in range(len(thetas)):\n rho = (edge_point[1] * cos_thetas[theta_idx]) + (edge_point[0] * sin_thetas[theta_idx])\n theta = thetas[theta_idx]\n rho_idx = np.argmin(np.abs(rhos - rho))\n accumulator[rho_idx][theta_idx] += 1\n ys.append(rho)\n xs.append(theta)\n subplot3.plot(xs, ys, color=\"white\", alpha=0.05)\n line_results = list()\n for y in range(accumulator.shape[0]):\n for x in range(accumulator.shape[1]):\n if accumulator[y][x] > t_count:\n rho = rhos[y]\n theta = thetas[x]\n #print(theta)\n a = np.cos(np.deg2rad(theta))\n b = np.sin(np.deg2rad(theta))\n\n x0 = (a * rho) + edge_width_half\n #print(x0)\n\n y0 = (b * rho) + edge_height_half\n #print(y0)\n x1 = int(x0 + 1000 * (-b))\n y1 = int(y0 + 1000 * (a))\n x2 = int(x0 - 1000 * (-b))\n y2 = int(y0 - 1000 * (a))\n #print([x1, x2])\n #print([y1, y2])\n #print(\"###\")\n subplot3.plot([theta], [rho], marker='o', color=\"yellow\")\n line_results.append([(x1,y1), (x2,y2)])\n subplot4.add_line(mlines.Line2D([x1, x2], [y1, y2]))\n\n subplot3.invert_yaxis()\n subplot3.invert_xaxis()\n\n subplot1.title.set_text(\"Original Image\")\n subplot2.title.set_text(\"Edge Image\")\n subplot3.title.set_text(\"Hough Space\")\n subplot4.title.set_text(\"Detected Lines\")\n plt.show()\n return accumulator, rhos, thetas, line_results", "_____no_output_____" ], [ "img = cv2.imread(f\"C:/Users/fredi/Desktop/Uni/SELS2/github/dronelab/simulation/simulated_data/1.png\", cv2.IMREAD_GRAYSCALE)\n#img = cv2.imread(img_dir, cv2.IMREAD_GRAYSCALE)\nprint(img.shape)\nplt.imshow(img, \"gray\")\nplt.show()", "(400, 600)\n" ], [ "edge_image = cv2.Canny(img, 100, 200)\nacc, rhos, thetas, line_results = line_detection_non_vectorized(img, edge_image, t_count=1000)", "_____no_output_____" ], [ "def merge_lines(edge_image, lines):\n results = list()\n agg = np.zeros(edge_image.shape)*255\n edge_image = np.where(edge_image>0, 1, edge_image)\n kernel = np.ones((3,3),np.float32)*255\n edge_image = cv2.filter2D(edge_image,-1,kernel)\n for line in lines:\n tmp = np.zeros(edge_image.shape)*255\n out = cv2.line(tmp, line[0], line[1], (255,255,255), thickness=1)\n results.append(out * edge_image)\n plt.imshow(results[-1])\n agg = agg + results[-1]\n plt.show()\n agg = np.where(agg>255, 255, agg)\n return results, agg\n", "_____no_output_____" ], [ "results, aggregated = merge_lines(edge_image, line_results)\nplt.imshow(aggregated)\nplt.show()", "_____no_output_____" ], [ "img2 = cv2.imread(f\"C:/Users/fredi/Desktop/Uni/SELS2/hough2/handpicked_rails/2021-07-01-17-07-48/fps_1_frame_018.jpg\")\nplt.imshow(img2)\nplt.show()", "_____no_output_____" ], [ "edge_image2 = cv2.Canny(img2, 100, 200)\nacc, rhos, thetas, line_results2 = line_detection_non_vectorized(img2, edge_image2, t_count=2000)", "_____no_output_____" ], [ "results, aggregated = merge_lines(edge_image2, line_results2)\nplt.imshow(aggregated)\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb285d8637d55522542641ba9e6da339742d7c75
96,409
ipynb
Jupyter Notebook
Activity02/Activity02.ipynb
Develop-Packt/Deep-Neural-Networks-with-Keras
6dd39d4768dc492aafcac4b20a68098b9af08112
[ "MIT" ]
1
2020-03-13T14:04:47.000Z
2020-03-13T14:04:47.000Z
Activity02/Activity02.ipynb
Develop-Packt/Deep-Neural-Networks-with-Keras
6dd39d4768dc492aafcac4b20a68098b9af08112
[ "MIT" ]
null
null
null
Activity02/Activity02.ipynb
Develop-Packt/Deep-Neural-Networks-with-Keras
6dd39d4768dc492aafcac4b20a68098b9af08112
[ "MIT" ]
2
2020-03-05T13:37:49.000Z
2021-02-25T16:48:58.000Z
124.238402
26,852
0.750926
[ [ [ "# Activity 02\n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom tensorflow import random", "Using TensorFlow backend.\n" ], [ "import matplotlib.pyplot as plt \nimport matplotlib\n%matplotlib inline ", "_____no_output_____" ], [ "# Load The dataset\nX = pd.read_csv('../data/HCV_feats.csv')\ny = pd.read_csv('../data/HCV_target.csv')\n\n# Print the sizes of the dataset\nprint(\"Number of Examples in the Dataset = \", X.shape[0])\nprint(\"Number of Features for each example = \", X.shape[1]) \nprint(\"Possible Output Classes = \", y['AdvancedFibrosis'].unique())", "Number of Examples in the Dataset = 1385\nNumber of Features for each example = 28\nPossible Output Classes = [0 1]\n" ] ], [ [ "Set up a seed for random number generator so the result will be reproducible\n\nSplit the dataset into training set and test set with a 80-20 ratio", "_____no_output_____" ] ], [ [ "seed = 1\nnp.random.seed(seed)\nrandom.set_seed(seed)\nsc = StandardScaler()\nX = pd.DataFrame(sc.fit_transform(X), columns=X.columns)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=seed)\n\n# Print the information regarding dataset sizes\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\nprint (\"Number of examples in training set = \", X_train.shape[0])\nprint (\"Number of examples in test set = \", X_test.shape[0])", "(1108, 28)\n(1108, 1)\n(277, 28)\n(277, 1)\nNumber of examples in training set = 1108\nNumber of examples in test set = 277\n" ], [ "np.random.seed(seed)\nrandom.set_seed(seed)\n# define the keras model\nclassifier = Sequential()\nclassifier.add(Dense(units = 3, activation = 'tanh', input_dim=X_train.shape[1]))\nclassifier.add(Dense(units = 1, activation = 'sigmoid'))\nclassifier.compile(optimizer = 'sgd', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\nclassifier.summary()", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_1 (Dense) (None, 3) 87 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 4 \n=================================================================\nTotal params: 91\nTrainable params: 91\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "# train the model while storing all loss values\nhistory=classifier.fit(X_train, y_train, batch_size = 20, epochs = 100, validation_split=0.1, shuffle=False)", "Train on 997 samples, validate on 111 samples\nEpoch 1/100\n997/997 [==============================] - 0s 179us/step - loss: 0.7972 - accuracy: 0.4714 - val_loss: 0.7460 - val_accuracy: 0.5676\nEpoch 2/100\n997/997 [==============================] - 0s 56us/step - loss: 0.7795 - accuracy: 0.4764 - val_loss: 0.7343 - val_accuracy: 0.5676\nEpoch 3/100\n997/997 [==============================] - 0s 56us/step - loss: 0.7653 - accuracy: 0.4794 - val_loss: 0.7248 - val_accuracy: 0.5676\nEpoch 4/100\n997/997 [==============================] - 0s 64us/step - loss: 0.7536 - accuracy: 0.4875 - val_loss: 0.7169 - val_accuracy: 0.5766\nEpoch 5/100\n997/997 [==============================] - 0s 62us/step - loss: 0.7441 - accuracy: 0.4945 - val_loss: 0.7104 - val_accuracy: 0.5766\nEpoch 6/100\n997/997 [==============================] - 0s 54us/step - loss: 0.7363 - accuracy: 0.5035 - val_loss: 0.7050 - val_accuracy: 0.5676\nEpoch 7/100\n997/997 [==============================] - 0s 55us/step - loss: 0.7297 - accuracy: 0.5075 - val_loss: 0.7005 - val_accuracy: 0.5586\nEpoch 8/100\n997/997 [==============================] - 0s 54us/step - loss: 0.7243 - accuracy: 0.5115 - val_loss: 0.6967 - val_accuracy: 0.5586\nEpoch 9/100\n997/997 [==============================] - 0s 51us/step - loss: 0.7197 - accuracy: 0.5206 - val_loss: 0.6935 - val_accuracy: 0.5495\nEpoch 10/100\n997/997 [==============================] - 0s 50us/step - loss: 0.7158 - accuracy: 0.5236 - val_loss: 0.6908 - val_accuracy: 0.5495\nEpoch 11/100\n997/997 [==============================] - 0s 61us/step - loss: 0.7125 - accuracy: 0.5256 - val_loss: 0.6886 - val_accuracy: 0.5766\nEpoch 12/100\n997/997 [==============================] - 0s 52us/step - loss: 0.7097 - accuracy: 0.5266 - val_loss: 0.6866 - val_accuracy: 0.5766\nEpoch 13/100\n997/997 [==============================] - 0s 48us/step - loss: 0.7072 - accuracy: 0.5246 - val_loss: 0.6849 - val_accuracy: 0.5766\nEpoch 14/100\n997/997 [==============================] - 0s 49us/step - loss: 0.7051 - accuracy: 0.5276 - val_loss: 0.6835 - val_accuracy: 0.5766\nEpoch 15/100\n997/997 [==============================] - 0s 50us/step - loss: 0.7032 - accuracy: 0.5216 - val_loss: 0.6823 - val_accuracy: 0.5766\nEpoch 16/100\n997/997 [==============================] - 0s 50us/step - loss: 0.7016 - accuracy: 0.5236 - val_loss: 0.6812 - val_accuracy: 0.5766\nEpoch 17/100\n997/997 [==============================] - 0s 52us/step - loss: 0.7002 - accuracy: 0.5236 - val_loss: 0.6803 - val_accuracy: 0.5766\nEpoch 18/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6990 - accuracy: 0.5236 - val_loss: 0.6795 - val_accuracy: 0.5676\nEpoch 19/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6979 - accuracy: 0.5246 - val_loss: 0.6788 - val_accuracy: 0.5676\nEpoch 20/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6969 - accuracy: 0.5266 - val_loss: 0.6782 - val_accuracy: 0.5766\nEpoch 21/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6960 - accuracy: 0.5266 - val_loss: 0.6777 - val_accuracy: 0.5856\nEpoch 22/100\n997/997 [==============================] - 0s 64us/step - loss: 0.6952 - accuracy: 0.5256 - val_loss: 0.6772 - val_accuracy: 0.5856\nEpoch 23/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6945 - accuracy: 0.5266 - val_loss: 0.6768 - val_accuracy: 0.5766\nEpoch 24/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6938 - accuracy: 0.5266 - val_loss: 0.6765 - val_accuracy: 0.5766\nEpoch 25/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6932 - accuracy: 0.5256 - val_loss: 0.6762 - val_accuracy: 0.5766\nEpoch 26/100\n997/997 [==============================] - 0s 57us/step - loss: 0.6927 - accuracy: 0.5256 - val_loss: 0.6759 - val_accuracy: 0.5856\nEpoch 27/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6922 - accuracy: 0.5276 - val_loss: 0.6756 - val_accuracy: 0.5856\nEpoch 28/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6918 - accuracy: 0.5306 - val_loss: 0.6754 - val_accuracy: 0.5856\nEpoch 29/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6913 - accuracy: 0.5316 - val_loss: 0.6752 - val_accuracy: 0.5856\nEpoch 30/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6910 - accuracy: 0.5306 - val_loss: 0.6750 - val_accuracy: 0.5856\nEpoch 31/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6906 - accuracy: 0.5296 - val_loss: 0.6749 - val_accuracy: 0.5856\nEpoch 32/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6903 - accuracy: 0.5326 - val_loss: 0.6747 - val_accuracy: 0.5856\nEpoch 33/100\n997/997 [==============================] - 0s 60us/step - loss: 0.6899 - accuracy: 0.5336 - val_loss: 0.6746 - val_accuracy: 0.5946\nEpoch 34/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6896 - accuracy: 0.5386 - val_loss: 0.6745 - val_accuracy: 0.5946\nEpoch 35/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6894 - accuracy: 0.5396 - val_loss: 0.6744 - val_accuracy: 0.6036\nEpoch 36/100\n997/997 [==============================] - 0s 64us/step - loss: 0.6891 - accuracy: 0.5406 - val_loss: 0.6743 - val_accuracy: 0.6126\nEpoch 37/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6889 - accuracy: 0.5426 - val_loss: 0.6742 - val_accuracy: 0.6036\nEpoch 38/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6886 - accuracy: 0.5426 - val_loss: 0.6741 - val_accuracy: 0.6036\nEpoch 39/100\n997/997 [==============================] - 0s 61us/step - loss: 0.6884 - accuracy: 0.5436 - val_loss: 0.6740 - val_accuracy: 0.6036\nEpoch 40/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6882 - accuracy: 0.5486 - val_loss: 0.6739 - val_accuracy: 0.6036\nEpoch 41/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6879 - accuracy: 0.5507 - val_loss: 0.6738 - val_accuracy: 0.6036\nEpoch 42/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6877 - accuracy: 0.5527 - val_loss: 0.6738 - val_accuracy: 0.6036\nEpoch 43/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6875 - accuracy: 0.5527 - val_loss: 0.6737 - val_accuracy: 0.5946\nEpoch 44/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6873 - accuracy: 0.5527 - val_loss: 0.6736 - val_accuracy: 0.6036\nEpoch 45/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6871 - accuracy: 0.5537 - val_loss: 0.6736 - val_accuracy: 0.6126\nEpoch 46/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6870 - accuracy: 0.5547 - val_loss: 0.6735 - val_accuracy: 0.6036\nEpoch 47/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6868 - accuracy: 0.5547 - val_loss: 0.6734 - val_accuracy: 0.6036\nEpoch 48/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6866 - accuracy: 0.5537 - val_loss: 0.6734 - val_accuracy: 0.6036\nEpoch 49/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6864 - accuracy: 0.5567 - val_loss: 0.6733 - val_accuracy: 0.6036\nEpoch 50/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6862 - accuracy: 0.5597 - val_loss: 0.6733 - val_accuracy: 0.6036\nEpoch 51/100\n997/997 [==============================] - 0s 47us/step - loss: 0.6861 - accuracy: 0.5627 - val_loss: 0.6732 - val_accuracy: 0.6036\nEpoch 52/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6859 - accuracy: 0.5617 - val_loss: 0.6732 - val_accuracy: 0.6036\nEpoch 53/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6857 - accuracy: 0.5617 - val_loss: 0.6731 - val_accuracy: 0.6036\nEpoch 54/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6855 - accuracy: 0.5617 - val_loss: 0.6731 - val_accuracy: 0.6036\nEpoch 55/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6854 - accuracy: 0.5617 - val_loss: 0.6730 - val_accuracy: 0.6036\nEpoch 56/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6852 - accuracy: 0.5627 - val_loss: 0.6730 - val_accuracy: 0.5946\nEpoch 57/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6850 - accuracy: 0.5637 - val_loss: 0.6729 - val_accuracy: 0.5946\nEpoch 58/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6849 - accuracy: 0.5607 - val_loss: 0.6729 - val_accuracy: 0.5946\nEpoch 59/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6847 - accuracy: 0.5627 - val_loss: 0.6728 - val_accuracy: 0.5946\nEpoch 60/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6845 - accuracy: 0.5607 - val_loss: 0.6728 - val_accuracy: 0.5946\nEpoch 61/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6844 - accuracy: 0.5597 - val_loss: 0.6728 - val_accuracy: 0.5946\nEpoch 62/100\n997/997 [==============================] - 0s 46us/step - loss: 0.6842 - accuracy: 0.5607 - val_loss: 0.6727 - val_accuracy: 0.5946\nEpoch 63/100\n997/997 [==============================] - 0s 46us/step - loss: 0.6840 - accuracy: 0.5617 - val_loss: 0.6727 - val_accuracy: 0.5946\nEpoch 64/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6839 - accuracy: 0.5607 - val_loss: 0.6726 - val_accuracy: 0.5946\nEpoch 65/100\n997/997 [==============================] - 0s 44us/step - loss: 0.6837 - accuracy: 0.5597 - val_loss: 0.6726 - val_accuracy: 0.5946\nEpoch 66/100\n997/997 [==============================] - 0s 47us/step - loss: 0.6835 - accuracy: 0.5607 - val_loss: 0.6726 - val_accuracy: 0.5946\nEpoch 67/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6834 - accuracy: 0.5617 - val_loss: 0.6725 - val_accuracy: 0.5946\nEpoch 68/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6832 - accuracy: 0.5617 - val_loss: 0.6725 - val_accuracy: 0.5946\nEpoch 69/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6830 - accuracy: 0.5607 - val_loss: 0.6725 - val_accuracy: 0.5856\nEpoch 70/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6829 - accuracy: 0.5597 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 71/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6827 - accuracy: 0.5607 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 72/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6825 - accuracy: 0.5607 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 73/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6823 - accuracy: 0.5617 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 74/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6822 - accuracy: 0.5617 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 75/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6820 - accuracy: 0.5627 - val_loss: 0.6723 - val_accuracy: 0.5856\nEpoch 76/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6818 - accuracy: 0.5637 - val_loss: 0.6723 - val_accuracy: 0.5856\nEpoch 77/100\n997/997 [==============================] - 0s 47us/step - loss: 0.6817 - accuracy: 0.5667 - val_loss: 0.6723 - val_accuracy: 0.5856\nEpoch 78/100\n997/997 [==============================] - 0s 47us/step - loss: 0.6815 - accuracy: 0.5697 - val_loss: 0.6723 - val_accuracy: 0.5856\nEpoch 79/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6813 - accuracy: 0.5707 - val_loss: 0.6723 - val_accuracy: 0.5946\nEpoch 80/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6811 - accuracy: 0.5717 - val_loss: 0.6723 - val_accuracy: 0.5946\nEpoch 81/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6810 - accuracy: 0.5717 - val_loss: 0.6723 - val_accuracy: 0.5946\nEpoch 82/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6808 - accuracy: 0.5707 - val_loss: 0.6723 - val_accuracy: 0.5946\nEpoch 83/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6806 - accuracy: 0.5727 - val_loss: 0.6723 - val_accuracy: 0.5856\nEpoch 84/100\n997/997 [==============================] - 0s 47us/step - loss: 0.6805 - accuracy: 0.5737 - val_loss: 0.6723 - val_accuracy: 0.5856\nEpoch 85/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6803 - accuracy: 0.5747 - val_loss: 0.6723 - val_accuracy: 0.5856\nEpoch 86/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6801 - accuracy: 0.5727 - val_loss: 0.6723 - val_accuracy: 0.5766\nEpoch 87/100\n997/997 [==============================] - 0s 60us/step - loss: 0.6799 - accuracy: 0.5707 - val_loss: 0.6723 - val_accuracy: 0.5766\nEpoch 88/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6798 - accuracy: 0.5707 - val_loss: 0.6723 - val_accuracy: 0.5766\nEpoch 89/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6796 - accuracy: 0.5677 - val_loss: 0.6723 - val_accuracy: 0.5766\nEpoch 90/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6794 - accuracy: 0.5687 - val_loss: 0.6724 - val_accuracy: 0.5766\nEpoch 91/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6792 - accuracy: 0.5707 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 92/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6791 - accuracy: 0.5707 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 93/100\n997/997 [==============================] - 0s 60us/step - loss: 0.6789 - accuracy: 0.5707 - val_loss: 0.6724 - val_accuracy: 0.5856\nEpoch 94/100\n997/997 [==============================] - 0s 57us/step - loss: 0.6787 - accuracy: 0.5707 - val_loss: 0.6725 - val_accuracy: 0.5946\nEpoch 95/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6786 - accuracy: 0.5697 - val_loss: 0.6725 - val_accuracy: 0.5946\nEpoch 96/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6784 - accuracy: 0.5697 - val_loss: 0.6725 - val_accuracy: 0.5946\nEpoch 97/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6782 - accuracy: 0.5697 - val_loss: 0.6725 - val_accuracy: 0.5946\nEpoch 98/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6780 - accuracy: 0.5687 - val_loss: 0.6726 - val_accuracy: 0.5856\nEpoch 99/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6779 - accuracy: 0.5657 - val_loss: 0.6726 - val_accuracy: 0.5766\nEpoch 100/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6777 - accuracy: 0.5667 - val_loss: 0.6726 - val_accuracy: 0.5766\n" ], [ "matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) \n\n# plot training error and test error plots \nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train loss', 'validation loss'], loc='upper right')", "_____no_output_____" ], [ "# print the best accuracy reached on training set and the test set\nprint(f\"Best Accuracy on training set = {max(history.history['accuracy'])*100:.3f}%\")\nprint(f\"Best Accuracy on validation set = {max(history.history['val_accuracy'])*100:.3f}%\") \n\ntest_loss, test_acc = classifier.evaluate(X_test, y_test['AdvancedFibrosis'])\nprint(f'The loss on the test set is {test_loss:.4f} and the accuracy is {test_acc*100:.3f}%')", "Best Accuracy on training set = 57.472%\nBest Accuracy on validation set = 61.261%\n277/277 [==============================] - 0s 36us/step\nThe loss on the test set is 0.7101 and the accuracy is 49.458%\n" ], [ "# set up a seed for random number generator so the result will be reproducible\nnp.random.seed(seed)\nrandom.set_seed(seed)\n# define the keras model\nclassifier = Sequential()\nclassifier.add(Dense(units = 4, activation = 'tanh', input_dim = X_train.shape[1]))\nclassifier.add(Dense(units = 2, activation = 'tanh'))\nclassifier.add(Dense(units = 1, activation = 'sigmoid'))\nclassifier.compile(optimizer = 'sgd', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\nclassifier.summary()", "Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_3 (Dense) (None, 4) 116 \n_________________________________________________________________\ndense_4 (Dense) (None, 2) 10 \n_________________________________________________________________\ndense_5 (Dense) (None, 1) 3 \n=================================================================\nTotal params: 129\nTrainable params: 129\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "# train the model while storing all loss values\nhistory=classifier.fit(X_train, y_train, batch_size = 20, epochs = 100, validation_split=0.1, shuffle=False)", "Train on 997 samples, validate on 111 samples\nEpoch 1/100\n997/997 [==============================] - 0s 199us/step - loss: 0.7468 - accuracy: 0.4945 - val_loss: 0.7153 - val_accuracy: 0.5676\nEpoch 2/100\n997/997 [==============================] - 0s 48us/step - loss: 0.7376 - accuracy: 0.4935 - val_loss: 0.7101 - val_accuracy: 0.5586\nEpoch 3/100\n997/997 [==============================] - 0s 48us/step - loss: 0.7302 - accuracy: 0.4945 - val_loss: 0.7060 - val_accuracy: 0.5586\nEpoch 4/100\n997/997 [==============================] - 0s 48us/step - loss: 0.7243 - accuracy: 0.5035 - val_loss: 0.7028 - val_accuracy: 0.5586\nEpoch 5/100\n997/997 [==============================] - 0s 50us/step - loss: 0.7195 - accuracy: 0.5035 - val_loss: 0.7002 - val_accuracy: 0.5586\nEpoch 6/100\n997/997 [==============================] - 0s 50us/step - loss: 0.7155 - accuracy: 0.5015 - val_loss: 0.6981 - val_accuracy: 0.5405\nEpoch 7/100\n997/997 [==============================] - 0s 49us/step - loss: 0.7123 - accuracy: 0.4995 - val_loss: 0.6964 - val_accuracy: 0.5225\nEpoch 8/100\n997/997 [==============================] - 0s 46us/step - loss: 0.7096 - accuracy: 0.5035 - val_loss: 0.6951 - val_accuracy: 0.5315\nEpoch 9/100\n997/997 [==============================] - 0s 45us/step - loss: 0.7073 - accuracy: 0.5075 - val_loss: 0.6940 - val_accuracy: 0.5315\nEpoch 10/100\n997/997 [==============================] - 0s 45us/step - loss: 0.7054 - accuracy: 0.5055 - val_loss: 0.6931 - val_accuracy: 0.5315\nEpoch 11/100\n997/997 [==============================] - 0s 48us/step - loss: 0.7038 - accuracy: 0.5045 - val_loss: 0.6924 - val_accuracy: 0.5315\nEpoch 12/100\n997/997 [==============================] - 0s 47us/step - loss: 0.7025 - accuracy: 0.4985 - val_loss: 0.6918 - val_accuracy: 0.5225\nEpoch 13/100\n997/997 [==============================] - 0s 47us/step - loss: 0.7013 - accuracy: 0.5055 - val_loss: 0.6914 - val_accuracy: 0.5315\nEpoch 14/100\n997/997 [==============================] - 0s 46us/step - loss: 0.7003 - accuracy: 0.5055 - val_loss: 0.6910 - val_accuracy: 0.5315\nEpoch 15/100\n997/997 [==============================] - 0s 47us/step - loss: 0.6994 - accuracy: 0.5035 - val_loss: 0.6907 - val_accuracy: 0.5315\nEpoch 16/100\n997/997 [==============================] - 0s 45us/step - loss: 0.6987 - accuracy: 0.5055 - val_loss: 0.6905 - val_accuracy: 0.5586\nEpoch 17/100\n997/997 [==============================] - 0s 44us/step - loss: 0.6981 - accuracy: 0.5035 - val_loss: 0.6903 - val_accuracy: 0.5586\nEpoch 18/100\n997/997 [==============================] - 0s 46us/step - loss: 0.6975 - accuracy: 0.5025 - val_loss: 0.6901 - val_accuracy: 0.5586\nEpoch 19/100\n997/997 [==============================] - 0s 47us/step - loss: 0.6970 - accuracy: 0.5005 - val_loss: 0.6900 - val_accuracy: 0.5405\nEpoch 20/100\n997/997 [==============================] - 0s 48us/step - loss: 0.6966 - accuracy: 0.5025 - val_loss: 0.6899 - val_accuracy: 0.5405\nEpoch 21/100\n997/997 [==============================] - 0s 46us/step - loss: 0.6962 - accuracy: 0.5035 - val_loss: 0.6898 - val_accuracy: 0.5225\nEpoch 22/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6958 - accuracy: 0.5025 - val_loss: 0.6898 - val_accuracy: 0.5225\nEpoch 23/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6955 - accuracy: 0.5015 - val_loss: 0.6897 - val_accuracy: 0.5225\nEpoch 24/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6953 - accuracy: 0.5015 - val_loss: 0.6897 - val_accuracy: 0.5135\nEpoch 25/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6950 - accuracy: 0.5005 - val_loss: 0.6896 - val_accuracy: 0.5135\nEpoch 26/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6948 - accuracy: 0.4955 - val_loss: 0.6896 - val_accuracy: 0.4955\nEpoch 27/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6946 - accuracy: 0.5005 - val_loss: 0.6896 - val_accuracy: 0.4955\nEpoch 28/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6944 - accuracy: 0.5015 - val_loss: 0.6896 - val_accuracy: 0.5045\nEpoch 29/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6942 - accuracy: 0.5055 - val_loss: 0.6896 - val_accuracy: 0.5045\nEpoch 30/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6941 - accuracy: 0.5075 - val_loss: 0.6896 - val_accuracy: 0.5045\nEpoch 31/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6939 - accuracy: 0.5075 - val_loss: 0.6896 - val_accuracy: 0.4955\nEpoch 32/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6938 - accuracy: 0.5065 - val_loss: 0.6896 - val_accuracy: 0.4955\nEpoch 33/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6936 - accuracy: 0.5085 - val_loss: 0.6896 - val_accuracy: 0.5045\nEpoch 34/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6935 - accuracy: 0.5115 - val_loss: 0.6896 - val_accuracy: 0.5135\nEpoch 35/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6934 - accuracy: 0.5125 - val_loss: 0.6896 - val_accuracy: 0.5135\nEpoch 36/100\n997/997 [==============================] - 0s 56us/step - loss: 0.6933 - accuracy: 0.5115 - val_loss: 0.6896 - val_accuracy: 0.5135\nEpoch 37/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6932 - accuracy: 0.5115 - val_loss: 0.6896 - val_accuracy: 0.5135\nEpoch 38/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6931 - accuracy: 0.5115 - val_loss: 0.6895 - val_accuracy: 0.5225\nEpoch 39/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6930 - accuracy: 0.5125 - val_loss: 0.6895 - val_accuracy: 0.5135\nEpoch 40/100\n997/997 [==============================] - 0s 60us/step - loss: 0.6929 - accuracy: 0.5145 - val_loss: 0.6895 - val_accuracy: 0.5135\nEpoch 41/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6928 - accuracy: 0.5115 - val_loss: 0.6895 - val_accuracy: 0.5135\nEpoch 42/100\n997/997 [==============================] - 0s 61us/step - loss: 0.6927 - accuracy: 0.5135 - val_loss: 0.6895 - val_accuracy: 0.5135\nEpoch 43/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6926 - accuracy: 0.5196 - val_loss: 0.6895 - val_accuracy: 0.5135\nEpoch 44/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6926 - accuracy: 0.5206 - val_loss: 0.6895 - val_accuracy: 0.5135\nEpoch 45/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6925 - accuracy: 0.5216 - val_loss: 0.6895 - val_accuracy: 0.5045\nEpoch 46/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6924 - accuracy: 0.5246 - val_loss: 0.6895 - val_accuracy: 0.5045\nEpoch 47/100\n997/997 [==============================] - 0s 105us/step - loss: 0.6923 - accuracy: 0.5256 - val_loss: 0.6895 - val_accuracy: 0.5045\nEpoch 48/100\n997/997 [==============================] - 0s 59us/step - loss: 0.6923 - accuracy: 0.5266 - val_loss: 0.6895 - val_accuracy: 0.5225\nEpoch 49/100\n997/997 [==============================] - 0s 56us/step - loss: 0.6922 - accuracy: 0.5276 - val_loss: 0.6895 - val_accuracy: 0.5225\nEpoch 50/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6921 - accuracy: 0.5256 - val_loss: 0.6895 - val_accuracy: 0.5225\nEpoch 51/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6921 - accuracy: 0.5286 - val_loss: 0.6895 - val_accuracy: 0.5135\nEpoch 52/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6920 - accuracy: 0.5286 - val_loss: 0.6894 - val_accuracy: 0.5135\nEpoch 53/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6919 - accuracy: 0.5306 - val_loss: 0.6894 - val_accuracy: 0.5225\nEpoch 54/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6919 - accuracy: 0.5316 - val_loss: 0.6894 - val_accuracy: 0.5225\nEpoch 55/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6918 - accuracy: 0.5316 - val_loss: 0.6894 - val_accuracy: 0.5225\nEpoch 56/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6917 - accuracy: 0.5316 - val_loss: 0.6894 - val_accuracy: 0.5315\nEpoch 57/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6917 - accuracy: 0.5306 - val_loss: 0.6894 - val_accuracy: 0.5315\nEpoch 58/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6916 - accuracy: 0.5296 - val_loss: 0.6894 - val_accuracy: 0.5225\nEpoch 59/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6915 - accuracy: 0.5306 - val_loss: 0.6894 - val_accuracy: 0.5135\nEpoch 60/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6915 - accuracy: 0.5316 - val_loss: 0.6894 - val_accuracy: 0.5135\nEpoch 61/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6914 - accuracy: 0.5316 - val_loss: 0.6894 - val_accuracy: 0.5135\nEpoch 62/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6914 - accuracy: 0.5336 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 63/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6913 - accuracy: 0.5326 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 64/100\n997/997 [==============================] - 0s 54us/step - loss: 0.6912 - accuracy: 0.5366 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 65/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6912 - accuracy: 0.5376 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 66/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6911 - accuracy: 0.5366 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 67/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6910 - accuracy: 0.5356 - val_loss: 0.6893 - val_accuracy: 0.5045\nEpoch 68/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6910 - accuracy: 0.5386 - val_loss: 0.6893 - val_accuracy: 0.5045\nEpoch 69/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6909 - accuracy: 0.5396 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 70/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6908 - accuracy: 0.5416 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 71/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6908 - accuracy: 0.5416 - val_loss: 0.6893 - val_accuracy: 0.5135\nEpoch 72/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6907 - accuracy: 0.5426 - val_loss: 0.6892 - val_accuracy: 0.5135\nEpoch 73/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6906 - accuracy: 0.5416 - val_loss: 0.6892 - val_accuracy: 0.5045\nEpoch 74/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6906 - accuracy: 0.5426 - val_loss: 0.6892 - val_accuracy: 0.4955\nEpoch 75/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6905 - accuracy: 0.5436 - val_loss: 0.6892 - val_accuracy: 0.4955\nEpoch 76/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6904 - accuracy: 0.5456 - val_loss: 0.6892 - val_accuracy: 0.5045\nEpoch 77/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6904 - accuracy: 0.5446 - val_loss: 0.6892 - val_accuracy: 0.5135\nEpoch 78/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6903 - accuracy: 0.5456 - val_loss: 0.6892 - val_accuracy: 0.5135\nEpoch 79/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6902 - accuracy: 0.5466 - val_loss: 0.6892 - val_accuracy: 0.5135\nEpoch 80/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6902 - accuracy: 0.5476 - val_loss: 0.6892 - val_accuracy: 0.5135\nEpoch 81/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6901 - accuracy: 0.5476 - val_loss: 0.6892 - val_accuracy: 0.5135\nEpoch 82/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6900 - accuracy: 0.5496 - val_loss: 0.6892 - val_accuracy: 0.5135\nEpoch 83/100\n997/997 [==============================] - 0s 55us/step - loss: 0.6899 - accuracy: 0.5507 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 84/100\n997/997 [==============================] - 0s 56us/step - loss: 0.6899 - accuracy: 0.5496 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 85/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6898 - accuracy: 0.5496 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 86/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6897 - accuracy: 0.5496 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 87/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6896 - accuracy: 0.5496 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 88/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6896 - accuracy: 0.5517 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 89/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6895 - accuracy: 0.5517 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 90/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6894 - accuracy: 0.5517 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 91/100\n997/997 [==============================] - 0s 49us/step - loss: 0.6893 - accuracy: 0.5557 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 92/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6892 - accuracy: 0.5557 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 93/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6891 - accuracy: 0.5557 - val_loss: 0.6891 - val_accuracy: 0.5135\nEpoch 94/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6891 - accuracy: 0.5537 - val_loss: 0.6891 - val_accuracy: 0.5225\nEpoch 95/100\n997/997 [==============================] - 0s 53us/step - loss: 0.6890 - accuracy: 0.5547 - val_loss: 0.6891 - val_accuracy: 0.5225\nEpoch 96/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6889 - accuracy: 0.5547 - val_loss: 0.6890 - val_accuracy: 0.5225\nEpoch 97/100\n997/997 [==============================] - 0s 51us/step - loss: 0.6888 - accuracy: 0.5557 - val_loss: 0.6890 - val_accuracy: 0.5225\nEpoch 98/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6887 - accuracy: 0.5547 - val_loss: 0.6890 - val_accuracy: 0.5225\nEpoch 99/100\n997/997 [==============================] - 0s 50us/step - loss: 0.6886 - accuracy: 0.5557 - val_loss: 0.6890 - val_accuracy: 0.5225\nEpoch 100/100\n997/997 [==============================] - 0s 52us/step - loss: 0.6885 - accuracy: 0.5557 - val_loss: 0.6890 - val_accuracy: 0.5315\n" ], [ "# plot training error and test error plots \nmatplotlib.rcParams['figure.figsize'] = (10.0, 8.0)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train loss', 'validation loss'], loc='upper right')", "_____no_output_____" ], [ "# print the best accuracy reached on training set and the test set\nprint(f\"Best Accuracy on training set = {max(history.history['accuracy'])*100:.3f}%\")\nprint(f\"Best Accuracy on test set = {max(history.history['val_accuracy'])*100:.3f}%\")\n\ntest_loss, test_acc = classifier.evaluate(X_test, y_test['AdvancedFibrosis'])\nprint(f'The loss on the test set is {test_loss:.4f} and the accuracy is {test_acc*100:.3f}%')", "Best Accuracy on training set = 55.567%\nBest Accuracy on test set = 56.757%\n277/277 [==============================] - 0s 22us/step\nThe loss on the test set is 0.6861 and the accuracy is 50.903%\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
cb286c2f1a63794e17601e3059f8d30266c8a2fb
19,521
ipynb
Jupyter Notebook
examples/notebooks/autoregressions.ipynb
chriswmann/statsmodels
79ddd9882a786cce2f34c77a6243d4f191fcb861
[ "BSD-3-Clause" ]
1
2019-01-10T21:19:45.000Z
2019-01-10T21:19:45.000Z
examples/notebooks/autoregressions.ipynb
chriswmann/statsmodels
79ddd9882a786cce2f34c77a6243d4f191fcb861
[ "BSD-3-Clause" ]
1
2015-06-16T04:16:40.000Z
2015-06-16T04:16:40.000Z
examples/notebooks/autoregressions.ipynb
chriswmann/statsmodels
79ddd9882a786cce2f34c77a6243d4f191fcb861
[ "BSD-3-Clause" ]
null
null
null
29.266867
464
0.587828
[ [ [ "# Autoregressions\n\nThis notebook introduces autoregression modeling using the `AutoReg` model. It also covers aspects of `ar_select_order` assists in selecting models that minimize an information criteria such as the AIC. \nAn autoregressive model has dynamics given by \n\n$$ y_t = \\delta + \\phi_1 y_{t-1} + \\ldots + \\phi_p y_{t-p} + \\epsilon_t. $$\n\n`AutoReg` also permits models with:\n\n* Deterministic terms (`trend`)\n * `n`: No deterministic term \n * `c`: Constant (default)\n * `ct`: Constant and time trend\n * `t`: Time trend only\n* Seasonal dummies (`seasonal`)\n * `True` includes $s-1$ dummies where $s$ is the period of the time series (e.g., 12 for monthly)\n* Custom deterministic terms (`deterministic`)\n * Accepts a `DeterministicProcess`\n* Exogenous variables (`exog`)\n * A `DataFrame` or `array` of exogenous variables to include in the model\n* Omission of selected lags (`lags`)\n * If `lags` is an iterable of integers, then only these are included in the model.\n\nThe complete specification is\n\n$$ y_t = \\delta_0 + \\delta_1 t + \\phi_1 y_{t-1} + \\ldots + \\phi_p y_{t-p} + \\sum_{i=1}^{s-1} \\gamma_i d_i + \\sum_{j=1}^{m} \\kappa_j x_{t,j} + \\epsilon_t. $$\n\nwhere:\n\n* $d_i$ is a seasonal dummy that is 1 if $mod(t, period) = i$. Period 0 is excluded if the model contains a constant (`c` is in `trend`).\n* $t$ is a time trend ($1,2,\\ldots$) that starts with 1 in the first observation.\n* $x_{t,j}$ are exogenous regressors. **Note** these are time-aligned to the left-hand-side variable when defining a model.\n* $\\epsilon_t$ is assumed to be a white noise process.", "_____no_output_____" ], [ "This first cell imports standard packages and sets plots to appear inline.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pandas_datareader as pdr\nimport seaborn as sns\nfrom statsmodels.tsa.ar_model import AutoReg, ar_select_order\nfrom statsmodels.tsa.api import acf, pacf, graphics", "_____no_output_____" ] ], [ [ "This cell sets the plotting style, registers pandas date converters for matplotlib, and sets the default figure size.", "_____no_output_____" ] ], [ [ "sns.set_style('darkgrid')\npd.plotting.register_matplotlib_converters()\n# Default figure size\nsns.mpl.rc('figure',figsize=(16, 6))", "_____no_output_____" ] ], [ [ "The first set of examples uses the month-over-month growth rate in U.S. Housing starts that has not been seasonally adjusted. The seasonality is evident by the regular pattern of peaks and troughs. We set the frequency for the time series to \"MS\" (month-start) to avoid warnings when using `AutoReg`.", "_____no_output_____" ] ], [ [ "data = pdr.get_data_fred('HOUSTNSA', '1959-01-01', '2019-06-01')\nhousing = data.HOUSTNSA.pct_change().dropna()\n# Scale by 100 to get percentages\nhousing = 100 * housing.asfreq('MS')\nfig, ax = plt.subplots()\nax = housing.plot(ax=ax)", "_____no_output_____" ] ], [ [ "We can start with an AR(3). While this is not a good model for this data, it demonstrates the basic use of the API.", "_____no_output_____" ] ], [ [ "mod = AutoReg(housing, 3, old_names=False)\nres = mod.fit()\nprint(res.summary())", "_____no_output_____" ] ], [ [ "`AutoReg` supports the same covariance estimators as `OLS`. Below, we use `cov_type=\"HC0\"`, which is White's covariance estimator. While the parameter estimates are the same, all of the quantities that depend on the standard error change.", "_____no_output_____" ] ], [ [ "res = mod.fit(cov_type=\"HC0\")\nprint(res.summary())", "_____no_output_____" ], [ "sel = ar_select_order(housing, 13, old_names=False)\nsel.ar_lags\nres = sel.model.fit()\nprint(res.summary())", "_____no_output_____" ] ], [ [ "`plot_predict` visualizes forecasts. Here we produce a large number of forecasts which show the string seasonality captured by the model.", "_____no_output_____" ] ], [ [ "fig = res.plot_predict(720, 840)", "_____no_output_____" ] ], [ [ "`plot_diagnositcs` indicates that the model captures the key features in the data.", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(16,9))\nfig = res.plot_diagnostics(fig=fig, lags=30)", "_____no_output_____" ] ], [ [ "## Seasonal Dummies", "_____no_output_____" ], [ "`AutoReg` supports seasonal dummies which are an alternative way to model seasonality. Including the dummies shortens the dynamics to only an AR(2).", "_____no_output_____" ] ], [ [ "sel = ar_select_order(housing, 13, seasonal=True, old_names=False)\nsel.ar_lags\nres = sel.model.fit()\nprint(res.summary())", "_____no_output_____" ] ], [ [ "The seasonal dummies are obvious in the forecasts which has a non-trivial seasonal component in all periods 10 years in to the future.", "_____no_output_____" ] ], [ [ "fig = res.plot_predict(720, 840)", "_____no_output_____" ], [ "fig = plt.figure(figsize=(16,9))\nfig = res.plot_diagnostics(lags=30, fig=fig)", "_____no_output_____" ] ], [ [ "## Seasonal Dynamics", "_____no_output_____" ], [ "While `AutoReg` does not directly support Seasonal components since it uses OLS to estimate parameters, it is possible to capture seasonal dynamics using an over-parametrized Seasonal AR that does not impose the restrictions in the Seasonal AR. ", "_____no_output_____" ] ], [ [ "yoy_housing = data.HOUSTNSA.pct_change(12).resample(\"MS\").last().dropna()\n_, ax = plt.subplots()\nax = yoy_housing.plot(ax=ax)", "_____no_output_____" ] ], [ [ "We start by selecting a model using the simple method that only chooses the maximum lag. All lower lags are automatically included. The maximum lag to check is set to 13 since this allows the model to next a Seasonal AR that has both a short-run AR(1) component and a Seasonal AR(1) component, so that\n\n$$ (1-\\phi_s L^{12})(1-\\phi_1 L)y_t = \\epsilon_t $$\nwhich becomes\n$$ y_t = \\phi_1 y_{t-1} +\\phi_s Y_{t-12} - \\phi_1\\phi_s Y_{t-13} + \\epsilon_t $$\n\nwhen expanded. `AutoReg` does not enforce the structure, but can estimate the nesting model \n\n$$ y_t = \\phi_1 y_{t-1} +\\phi_{12} Y_{t-12} - \\phi_{13} Y_{t-13} + \\epsilon_t. $$\n\nWe see that all 13 lags are selected.", "_____no_output_____" ] ], [ [ "sel = ar_select_order(yoy_housing, 13, old_names=False)\nsel.ar_lags", "_____no_output_____" ] ], [ [ "It seems unlikely that all 13 lags are required. We can set `glob=True` to search all $2^{13}$ models that include up to 13 lags.\n\nHere we see that the first three are selected, as is the 7th, and finally the 12th and 13th are selected. This is superficially similar to the structure described above.\n\nAfter fitting the model, we take a look at the diagnostic plots that indicate that this specification appears to be adequate to capture the dynamics in the data.", "_____no_output_____" ] ], [ [ "sel = ar_select_order(yoy_housing, 13, glob=True, old_names=False)\nsel.ar_lags\nres = sel.model.fit()\nprint(res.summary())", "_____no_output_____" ], [ "fig = plt.figure(figsize=(16,9))\nfig = res.plot_diagnostics(fig=fig, lags=30)", "_____no_output_____" ] ], [ [ "We can also include seasonal dummies. These are all insignificant since the model is using year-over-year changes.", "_____no_output_____" ] ], [ [ "sel = ar_select_order(yoy_housing, 13, glob=True, seasonal=True, old_names=False)\nsel.ar_lags\nres = sel.model.fit()\nprint(res.summary())", "_____no_output_____" ] ], [ [ "## Industrial Production\n\nWe will use the industrial production index data to examine forecasting.", "_____no_output_____" ] ], [ [ "data = pdr.get_data_fred('INDPRO', '1959-01-01', '2019-06-01')\nind_prod = data.INDPRO.pct_change(12).dropna().asfreq('MS')\n_, ax = plt.subplots(figsize=(16,9))\nind_prod.plot(ax=ax)", "_____no_output_____" ] ], [ [ "We will start by selecting a model using up to 12 lags. An AR(13) minimizes the BIC criteria even though many coefficients are insignificant.", "_____no_output_____" ] ], [ [ "sel = ar_select_order(ind_prod, 13, 'bic', old_names=False)\nres = sel.model.fit()\nprint(res.summary())", "_____no_output_____" ] ], [ [ "We can also use a global search which allows longer lags to enter if needed without requiring the shorter lags. Here we see many lags dropped. The model indicates there may be some seasonality in the data. ", "_____no_output_____" ] ], [ [ "sel = ar_select_order(ind_prod, 13, 'bic', glob=True, old_names=False)\nsel.ar_lags\nres_glob = sel.model.fit()\nprint(res.summary())", "_____no_output_____" ] ], [ [ "`plot_predict` can be used to produce forecast plots along with confidence intervals. Here we produce forecasts starting at the last observation and continuing for 18 months.", "_____no_output_____" ] ], [ [ "ind_prod.shape", "_____no_output_____" ], [ "fig = res_glob.plot_predict(start=714, end=732)", "_____no_output_____" ] ], [ [ "The forecasts from the full model and the restricted model are very similar. I also include an AR(5) which has very different dynamics", "_____no_output_____" ] ], [ [ "res_ar5 = AutoReg(ind_prod, 5, old_names=False).fit()\npredictions = pd.DataFrame({\"AR(5)\": res_ar5.predict(start=714, end=726),\n \"AR(13)\": res.predict(start=714, end=726),\n \"Restr. AR(13)\": res_glob.predict(start=714, end=726)})\n_, ax = plt.subplots()\nax = predictions.plot(ax=ax)", "_____no_output_____" ] ], [ [ "The diagnostics indicate the model captures most of the the dynamics in the data. The ACF shows a patters at the seasonal frequency and so a more complete seasonal model (`SARIMAX`) may be needed.", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(16,9))\nfig = res_glob.plot_diagnostics(fig=fig, lags=30)", "_____no_output_____" ] ], [ [ "# Forecasting\n\nForecasts are produced using the `predict` method from a results instance. The default produces static forecasts which are one-step forecasts. Producing multi-step forecasts requires using `dynamic=True`. \n\nIn this next cell, we produce 12-step-heard forecasts for the final 24 periods in the sample. This requires a loop.\n\n**Note**: These are technically in-sample since the data we are forecasting was used to estimate parameters. Producing OOS forecasts requires two models. The first must exclude the OOS period. The second uses the `predict` method from the full-sample model with the parameters from the shorter sample model that excluded the OOS period.", "_____no_output_____" ] ], [ [ "import numpy as np\nstart = ind_prod.index[-24]\nforecast_index = pd.date_range(start, freq=ind_prod.index.freq, periods=36)\ncols = ['-'.join(str(val) for val in (idx.year, idx.month)) for idx in forecast_index]\nforecasts = pd.DataFrame(index=forecast_index,columns=cols)\nfor i in range(1, 24):\n fcast = res_glob.predict(start=forecast_index[i], end=forecast_index[i+12], dynamic=True)\n forecasts.loc[fcast.index, cols[i]] = fcast\n_, ax = plt.subplots(figsize=(16, 10))\nind_prod.iloc[-24:].plot(ax=ax, color=\"black\", linestyle=\"--\")\nax = forecasts.plot(ax=ax)", "_____no_output_____" ] ], [ [ "## Comparing to SARIMAX\n\n`SARIMAX` is an implementation of a Seasonal Autoregressive Integrated Moving Average with eXogenous regressors model. It supports:\n\n* Specification of seasonal and nonseasonal AR and MA components\n* Inclusion of Exogenous variables\n* Full maximum-likelihood estimation using the Kalman Filter\n\nThis model is more feature rich than `AutoReg`. Unlike `SARIMAX`, `AutoReg` estimates parameters using OLS. This is faster and the problem is globally convex, and so there are no issues with local minima. The closed-form estimator and its performance are the key advantages of `AutoReg` over `SARIMAX` when comparing AR(P) models. `AutoReg` also support seasonal dummies, which can be used with `SARIMAX` if the user includes them as exogenous regressors. ", "_____no_output_____" ] ], [ [ "from statsmodels.tsa.api import SARIMAX\n\nsarimax_mod = SARIMAX(ind_prod, order=((1,5,12,13),0, 0), trend='c')\nsarimax_res = sarimax_mod.fit()\nprint(sarimax_res.summary())", "_____no_output_____" ], [ "sarimax_params = sarimax_res.params.iloc[:-1].copy()\nsarimax_params.index = res_glob.params.index\nparams = pd.concat([res_glob.params, sarimax_params], axis=1, sort=False)\nparams.columns = [\"AutoReg\", \"SARIMAX\"]\nparams", "_____no_output_____" ] ], [ [ "## Custom Deterministic Processes\n\nThe `deterministic` parameter allows a custom `DeterministicProcess` to be used. This allows for more complex deterministic terms to be constructed, for example one that includes seasonal components with two periods, or, as the next example shows, one that uses a Fourier series rather than seasonal dummies.", "_____no_output_____" ] ], [ [ "from statsmodels.tsa.deterministic import DeterministicProcess\ndp = DeterministicProcess(housing.index, constant=True, period=12, fourier=2)\nmod = AutoReg(housing,2, trend=\"n\",seasonal=False, deterministic=dp)\nres = mod.fit()\nprint(res.summary())", "_____no_output_____" ], [ "fig = res.plot_predict(720, 840)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
cb287a55bd979d51d7ca3665aed438f515251264
96,423
ipynb
Jupyter Notebook
notebooks/.ipynb_checkpoints/6.3-jalvaradoruiz-consolidacion-dataset-materia-rol-checkpoint.ipynb
JALVARADORUIZ/DataAnalytic-PJUD
cd063efd619eca3b7bf583f1fb00383f6f774818
[ "MIT" ]
null
null
null
notebooks/.ipynb_checkpoints/6.3-jalvaradoruiz-consolidacion-dataset-materia-rol-checkpoint.ipynb
JALVARADORUIZ/DataAnalytic-PJUD
cd063efd619eca3b7bf583f1fb00383f6f774818
[ "MIT" ]
null
null
null
notebooks/.ipynb_checkpoints/6.3-jalvaradoruiz-consolidacion-dataset-materia-rol-checkpoint.ipynb
JALVARADORUIZ/DataAnalytic-PJUD
cd063efd619eca3b7bf583f1fb00383f6f774818
[ "MIT" ]
null
null
null
40.719172
218
0.33381
[ [ [ "# Creacion Consolidado por Materia Penal y Rol\n\nComenzaremos el analisis de la data consolidando la info en un unico DataSet", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport os\nimport warnings\n\nfrom tqdm import tqdm\nfrom unicodedata import normalize", "_____no_output_____" ], [ "pd.set_option('display.max_columns', 100)", "_____no_output_____" ], [ "path_processed = \"../data/processed/pjud\"", "_____no_output_____" ], [ "df_materia = pd.read_feather(f\"{path_processed}/Consolidado_Materia_feather\")\nprint(f\"{len(df_materia)} causas en el dataset por materia\")", "4249511 causas en el dataset por materia\n" ], [ "df_rol = pd.read_feather(f\"{path_processed}/Consolidado_Rol_feather\")\nprint(f\"Existen : {len(df_rol)} causas en el dataset por Rol\")", "Existen : 3893767 causas en el dataset por Rol\n" ] ], [ [ "Analizamos la data, uniendo ambos dataset.", "_____no_output_____" ] ], [ [ "df_union = pd.merge(df_materia, df_rol, how='outer', on=['COD. CORTE','COD. TRIBUNAL','RIT'])\nprint(f\"Existen: {len(df_union)} causas en total uniendo ambos dataset\")", "Existen: 5009593 causas en total uniendo ambos dataset\n" ], [ "df_union.sort_values('FECHA INGRESO_x')", "_____no_output_____" ] ], [ [ "Existen Causas sin Materia ... ", "_____no_output_____" ] ], [ [ "df_sin_materia = df_union[df_union['MATERIA'].isnull()]\ndf_sin_materia", "_____no_output_____" ] ], [ [ "Podemos ver que existen causas que estan con ROL pero no han sido incorporadas en causas por Materia.\n\n¿Que hacer con ello?\n\nA mi parecer se deben desestimar para el analisis, los datos son inherentes por su cantidad.", "_____no_output_____" ] ], [ [ "df_sin_materia['MOTIVO TERMINO_y'].value_counts()", "_____no_output_____" ] ], [ [ "Estas no deberian tomarse en cuenta, ya que pueden deberse a causas mal tramitadas.", "_____no_output_____" ], [ "Veamos el caso especial donde no coinciden los MOTIVOS TERMINO", "_____no_output_____" ] ], [ [ "df_diferencia = df_union[df_union['MOTIVO TERMINO_x']!= df_union['MOTIVO TERMINO_y']]", "_____no_output_____" ], [ "df_diferencia['MOTIVO TERMINO_x'].value_counts()", "_____no_output_____" ], [ "df_diferencia[df_diferencia['MOTIVO TERMINO_x'].isnull()]", "_____no_output_____" ], [ "df_diferencia", "_____no_output_____" ] ], [ [ "Aca vemos el problema de :\n\nque todos los delitos (materias) que no tienen término, obedecen a situaciones a las que el siagj no da respuesta, y dependiendo de los criterios de registro de la tramitación, dan origen a esta falta de término.", "_____no_output_____" ], [ "## CARGA DATA A ARCHIVOS FUTHER", "_____no_output_____" ] ], [ [ "# Directorio donde se guardaran archivos feather\ndf_union.reset_index(inplace = True)\nos.makedirs(path_processed, exist_ok = True) \n\n# Guardamos dataset como archivo feather\n\ndf_union.to_feather(f'{path_processed}/Consolidado_Materia_Rol_feather')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
cb289b894b23390af7d266de41c273e6cc195ce4
33,843
ipynb
Jupyter Notebook
AnalysisCode/Checkout Master Data.ipynb
dtroupe18/Thesis-Survey-Of-Political-Bots-On-Twitter
c1840fd6853191797cd6c29e475ed3fb70f9ee55
[ "MIT" ]
1
2018-12-05T01:31:09.000Z
2018-12-05T01:31:09.000Z
AnalysisCode/Checkout Master Data.ipynb
dtroupe18/Thesis-Survey-Of-Political-Bots-On-Twitter
c1840fd6853191797cd6c29e475ed3fb70f9ee55
[ "MIT" ]
null
null
null
AnalysisCode/Checkout Master Data.ipynb
dtroupe18/Thesis-Survey-Of-Political-Bots-On-Twitter
c1840fd6853191797cd6c29e475ed3fb70f9ee55
[ "MIT" ]
null
null
null
138.134694
21,084
0.881896
[ [ [ "import os\nimport pandas as pd\nimport math\nimport nltk\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline \nimport re\nfrom nltk.tokenize import WordPunctTokenizer\nimport pickle", "_____no_output_____" ], [ "def load_csv_as_df(file_name, sub_directories, col_name=None):\n '''\n Load any csv as a pandas dataframe. Provide the filename, the subdirectories, and columns to read(if desired).\n '''\n # sub_directories = '/Data/'\n base_path = os.getcwd()\n full_path = base_path + sub_directories + file_name\n \n if col_name is not None:\n return pd.read_csv(full_path, usecols=[col_name])\n \n # print('Full Path: ', full_path)\n return pd.read_csv(full_path, header=0)\n\n\ndef describe_bots(df, return_dfs=False, for_timeline=False):\n \n if for_timeline:\n df = df.drop_duplicates(subset='user_id', keep='last')\n bot_df = df[df.user_cap >= 0.53]\n human_df = df[df.user_cap < 0.4]\n removed_df = df[(df['user_cap'] >= 0.4) & (df['user_cap'] <= 0.53)]\n else:\n bot_df = df[df.cap >= 0.53]\n human_df = df[df.cap < 0.4]\n removed_df = df[(df['cap'] >= 0.4) & (df['cap'] <= 0.53)]\n \n bot_percent = len(bot_df)/len(df) * 100\n human_percent = len(human_df)/len(df) * 100\n removed_percent = len(removed_df)/len(df) * 100\n\n print('There are ', len(df), 'total records')\n print('There are ', len(bot_df), 'Bots in these records')\n print('Percentage of total accounts that are bots = ' + str(round(bot_percent, 2)) + '%')\n print('Percentage of total accounts that are humans = ' + str(round(human_percent, 2)) + '%')\n print('Percentage of total accounts that were removed = ' + str(round(removed_percent, 2)) + '%')\n \n if return_dfs:\n return bot_df, human_df, removed_df\n \ndef get_top_five_percent(df):\n number_of_accounts = len(df)\n top5 = int(number_of_accounts * 0.05)\n \n print(\"num accounts: \", number_of_accounts)\n print(\"top5: \", top5)\n \n top_df = df.cap.nlargest(top5)\n min_cap = top_df.min()\n return min_cap\n ", "_____no_output_____" ], [ "master_df = load_csv_as_df('MasterIDs-4.csv', '/Data/Master-Data/')\nerror_df = load_csv_as_df('ErrorIDs-4.csv', '/Data/Master-Data/')", "_____no_output_____" ], [ "bot_df, human_df, removed_df = describe_bots(master_df, return_dfs=True)", "There are 546310 total records\nThere are 14403 Bots in these records\nPercentage of total accounts that are bots = 2.64%\nPercentage of total accounts that are humans = 96.2%\nPercentage of total accounts that were removed = 1.17%\n" ], [ "print(len(error_df))", "9641\n" ], [ "min_cap = get_top_five_percent(master_df)\nprint(min_cap)", "num accounts: 546310\ntop5: 27315\n0.2967687660397612\n" ], [ "fig, ax = plt.subplots(figsize=(8, 5))\nax.grid(False)\nax.set_title('Botometer CAP Score Distribution')\nplt.hist(master_df.cap, bins=10, color='b', edgecolor='k')\nplt.xlabel(\"CAP Score\")\nplt.ylabel(\"Number of Accounts\")\nplt.axvline(master_df.cap.mean(), color='y', linewidth=2.5, label='Average CAP Score')\n\nmin_cap = get_top_five_percent(master_df)\nplt.axvline(x=min_cap, color='orange', linewidth=2.5, linestyle='dashed', label='95th Percentile')\nplt.axvline(x=0.4, color='g', linewidth=2.5, label='Human Threshold')\nplt.axvline(x=0.53, color='r', linewidth=2.5, label='Bot Threshold')\n\nplt.legend()\nplt.savefig('Botometer CAP Score Frequency.png', bbox_inches='tight')", "num accounts: 546310\ntop5: 27315\n" ], [ "plt.scatter(master_df.cap, master_df.bot_score)\n\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]