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
4aebf7ede6686f39a0209b742d8a6c20b7c89e30
512,014
ipynb
Jupyter Notebook
debiasing.ipynb
btian/deep-learning
aa169b22a6d049852bf745ef36945a3b6f398459
[ "MIT" ]
null
null
null
debiasing.ipynb
btian/deep-learning
aa169b22a6d049852bf745ef36945a3b6f398459
[ "MIT" ]
null
null
null
debiasing.ipynb
btian/deep-learning
aa169b22a6d049852bf745ef36945a3b6f398459
[ "MIT" ]
null
null
null
489.96555
71,770
0.933855
[ [ [ "<a href=\"https://colab.research.google.com/github/btian/deep-learning/blob/main/debiasing.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import IPython\r\nIPython.display.YouTubeVideo('59bMh59JQDo')", "_____no_output_____" ], [ "%tensorflow_version 2.x\r\nimport tensorflow as tf\r\n\r\nimport functools\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\n\r\n!pip install mitdeeplearning -qq\r\nimport mitdeeplearning as mdl", "\u001b[K |████████████████████████████████| 2.1MB 16.3MB/s \n\u001b[?25h Building wheel for mitdeeplearning (setup.py) ... \u001b[?25l\u001b[?25hdone\n" ], [ "train_path = tf.keras.utils.get_file('train_face.h5', 'https://www.dropbox.com/s/hlz8atheyozp1yx/train_face.h5?dl=1')\r\nloader = mdl.lab2.TrainingDatasetLoader(train_path)", "Downloading data from https://www.dropbox.com/s/hlz8atheyozp1yx/train_face.h5?dl=1\n1263894528/1263889489 [==============================] - 12s 0us/step\nOpening /root/.keras/datasets/train_face.h5\nLoading data into memory...\n" ], [ "n = loader.get_train_size()\r\nprint(n)\r\n(images, labels) = loader.get_batch(100)", "109914\n" ], [ "face_images = images[np.where(labels==1)[0]]\r\nnot_face_images = images[np.where(labels==0)[0]]\r\n\r\nidx_face = 23\r\nidx_not_face = 6\r\n\r\nplt.figure(figsize=(5,5))\r\nplt.subplot(1, 2, 1)\r\nplt.imshow(face_images[idx_face])\r\nplt.title('Face'); plt.grid(False)\r\n\r\nplt.subplot(1, 2, 2)\r\nplt.imshow(not_face_images[idx_not_face])\r\nplt.title('Not Face'); plt.grid(False)", "_____no_output_____" ], [ "n_filters = 12\r\n\r\ndef make_standard_classifier(n_outputs=1):\r\n Conv2D = functools.partial(tf.keras.layers.Conv2D, padding='same', activation='relu')\r\n BatchNorm = tf.keras.layers.BatchNormalization\r\n Flatten = tf.keras.layers.Flatten\r\n Dense = functools.partial(tf.keras.layers.Dense, activation='relu')\r\n\r\n model = tf.keras.Sequential([\r\n Conv2D(filters=1*n_filters, kernel_size=5, strides=2),\r\n BatchNorm(),\r\n Conv2D(filters=2*n_filters, kernel_size=5, strides=2),\r\n BatchNorm(),\r\n Conv2D(filters=4*n_filters, kernel_size=3, strides=2),\r\n BatchNorm(),\r\n Conv2D(filters=6*n_filters, kernel_size=3, strides=2),\r\n BatchNorm(),\r\n Flatten(),\r\n Dense(512),\r\n Dense(n_outputs, activation=None),\r\n ])\r\n return model\r\n\r\n\r\nstandard_classifier = make_standard_classifier()", "_____no_output_____" ], [ "bs = 32\r\nepochs = 2\r\nlr = 1e-3\r\n\r\noptimizer = tf.keras.optimizers.Adam(lr)\r\nloss_history = mdl.util.LossHistory(smoothing_factor=0.99)\r\nplotter = mdl.util.PeriodicPlotter(sec=2, scale='semilogy')\r\nif hasattr(tqdm, '_instances'): tqdm._instances.clear()\r\n\r\n\r\[email protected]\r\ndef standard_train_step(x, y):\r\n with tf.GradientTape() as tape:\r\n logits = standard_classifier(x)\r\n loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits)\r\n grads = tape.gradient(loss, standard_classifier.trainable_variables)\r\n optimizer.apply_gradients(zip(grads, standard_classifier.trainable_variables))\r\n return loss\r\n\r\n\r\nfor epoch in range(epochs):\r\n for idx in tqdm(range(loader.get_train_size() // bs)):\r\n x, y = loader.get_batch(bs)\r\n loss = standard_train_step(x, y)\r\n\r\n loss_history.append(loss.numpy().mean())\r\n plotter.plot(loss_history.get())", "_____no_output_____" ], [ "batch_x, batch_y = loader.get_batch(5000)\r\ny_pred_standard = tf.round(tf.nn.sigmoid(standard_classifier.predict(batch_x)))\r\nacc_standard = tf.reduce_mean(tf.cast(tf.equal(batch_y, y_pred_standard), tf.float32))\r\n\r\nprint(f'Standard CNN accuracy on training set: {acc_standard.numpy():.4f}')", "Standard CNN accuracy on training set: 0.9968\n" ], [ "test_faces = mdl.lab2.get_test_faces()\r\nkeys = ['Light Female', 'Light Male', 'Dark Female', 'Dark Male']\r\nfor group, key in zip(test_faces, keys):\r\n plt.figure(figsize=(5,5))\r\n plt.imshow(np.hstack(group))\r\n plt.title(key, fontsize=15)", "_____no_output_____" ], [ "standard_classifier_logits = [standard_classifier(np.array(x, dtype=np.float32)) for x in test_faces]\r\nstandard_classifier_probs = tf.squeeze(tf.sigmoid(standard_classifier_logits))\r\n\r\nxx = range(len(keys))\r\nyy = standard_classifier_probs.numpy().mean(1)\r\nplt.bar(xx, yy)\r\nplt.xticks(xx, keys)\r\nplt.ylim(max(0, yy.min() - yy.ptp() / 2.), yy.max() + yy.ptp() / 2.)\r\nplt.title('Standard Classifier Predictions')", "_____no_output_____" ], [ "def vae_loss_function(x, x_recon, mu, logsigma, kl_weight=5e-4):\r\n latent_loss = 0.5 * tf.reduce_sum(tf.exp(logsigma) + tf.square(mu) - 1.0 - logsigma, axis=1)\r\n reconstruction_loss = tf.reduce_mean(tf.abs(x - x_recon), axis=(1,2,3))\r\n vae_loss = kl_weight * latent_loss + reconstruction_loss\r\n return vae_loss", "_____no_output_____" ], [ "### VAE Reparameterization ###\r\ndef sampling(z_mean, z_logsigma):\r\n batch, latent_dim = z_mean.shape\r\n epsilon = tf.random.normal(shape=(batch, latent_dim))\r\n z = z_mean + tf.exp(0.5 * z_logsigma) * epsilon\r\n return z", "_____no_output_____" ], [ "### Loss function for DB-VAE ###\r\n\"\"\"Loss function for DB-VAE.\r\n# Arguments\r\n x: true input x\r\n x_pred: reconstructed x\r\n y: true label (face or not face)\r\n y_logit: predicted labels\r\n mu: mean of latent distribution (Q(z|X))\r\n logsigma: log of standard deviation of latent distribution (Q(z|X))\r\n# Returns\r\n total_loss: DB-VAE total loss\r\n classification_loss = DB-VAE classification loss\r\n\"\"\"\r\ndef debiasing_loss_function(x, x_pred, y, y_logit, mu, logsigma):\r\n vae_loss = vae_loss_function(x, x_pred, mu, logsigma)\r\n classification_loss = tf.nn.sigmoid_cross_entropy_with_logits(y, y_logit)\r\n # Use the training data labels to create variable face_indicator:\r\n # indicator that reflects which training data are images of faces\r\n face_indicator = tf.cast(tf.equal(y, 1), tf.float32)\r\n total_loss = tf.reduce_mean(classification_loss + face_indicator * vae_loss)\r\n return total_loss, classification_loss", "_____no_output_____" ], [ "n_filters = 12\r\nlatent_dim = 100\r\n\r\ndef make_face_decoder_network():\r\n Conv2DTranspose = functools.partial(tf.keras.layers.Conv2DTranspose, padding='same', activation='relu')\r\n BatchNorm = tf.keras.layers.BatchNormalization\r\n Flatten = tf.keras.layers.Flatten\r\n Dense = functools.partial(tf.keras.layers.Dense, activation='relu')\r\n Reshape = tf.keras.layers.Reshape\r\n\r\n decoder = tf.keras.Sequential([\r\n Dense(units=4*4*6*n_filters),\r\n Reshape(target_shape=(4, 4, 6*n_filters)),\r\n BatchNorm(),\r\n # Upscaling convolutions\r\n #Conv2DTranspose(filters=6*n_filters, kernel_size=3, strides=2),\r\n #BatchNorm(),\r\n Conv2DTranspose(filters=4*n_filters, kernel_size=3, strides=2),\r\n BatchNorm(),\r\n Conv2DTranspose(filters=2*n_filters, kernel_size=3, strides=2),\r\n BatchNorm(),\r\n Conv2DTranspose(filters=1*n_filters, kernel_size=5, strides=2),\r\n Conv2DTranspose(filters=3, kernel_size=5, strides=2),\r\n ])\r\n return decoder", "_____no_output_____" ], [ "class DB_VAE(tf.keras.Model):\r\n def __init__(self, latent_dim):\r\n super().__init__(self)\r\n self.latent_dim = latent_dim\r\n\r\n num_encoder_dims = 2*self.latent_dim + 1\r\n\r\n self.encoder = make_standard_classifier(num_encoder_dims)\r\n self.decoder = make_face_decoder_network()\r\n\r\n def encode(self, x):\r\n encoder_output = self.encoder(x)\r\n y_logit = tf.expand_dims(encoder_output[:, 0], -1)\r\n z_mean = encoder_output[:, 1:self.latent_dim+1]\r\n z_logsigma = encoder_output[:, self.latent_dim+1:]\r\n return y_logit, z_mean, z_logsigma\r\n\r\n def reparameterize(self, z_mean, z_logsigma):\r\n z = sampling(z_mean, z_logsigma)\r\n return z\r\n\r\n def decode(self, z):\r\n reconstruction = self.decoder(z)\r\n return reconstruction\r\n\r\n def call(self, x):\r\n y_logit, z_mean, z_logsigma = self.encode(x)\r\n z = self.reparameterize(z_mean, z_logsigma)\r\n recon = self.decode(z)\r\n return y_logit, z_mean, z_logsigma, recon\r\n\r\n def predict(self, x):\r\n y_logit, z_mean, z_logsigma = self.encode(x)\r\n return y_logit\r\n\r\ndbvae = DB_VAE(latent_dim)", "_____no_output_____" ], [ "def get_latent_mu(images, dbvae, batch_size=1024):\r\n N = images.shape[0]\r\n mu = np.zeros((N, latent_dim))\r\n for start_ind in range(0, N, batch_size):\r\n end_ind = min(start_ind+batch_size, N+1)\r\n batch = (images[start_ind:end_ind]).astype(np.float32)/255.\r\n _, batch_mu, _ = dbvae.encode(batch)\r\n mu[start_ind:end_ind] = batch_mu\r\n return mu", "_____no_output_____" ], [ "### Resampling algorithm for DB-VAE ###\r\ndef get_training_sample_probabilities(images, dbvae, bins=10, smoothing_fac=1e-3):\r\n print('Recomputing the sampling probabilities')\r\n mu = get_latent_mu(images, dbvae)\r\n training_sample_p = np.zeros(mu.shape[0])\r\n for i in range(latent_dim):\r\n latent_distribution = mu[:,i]\r\n hist_density, bin_edges = np.histogram(latent_distribution, density=True, bins=bins)\r\n\r\n bin_edges[0] = -float('inf')\r\n bin_edges[-1] = float('inf')\r\n\r\n bin_idx = np.digitize(latent_distribution, bin_edges)\r\n\r\n hist_smoothed_density = hist_density + smoothing_fac\r\n hist_smoothed_density = hist_smoothed_density / np.sum(hist_smoothed_density)\r\n\r\n p = 1.0 / hist_smoothed_density[bin_idx-1]\r\n p = p / np.sum(p)\r\n training_sample_p = np.maximum(p, training_sample_p)\r\n training_sample_p /= np.sum(training_sample_p)\r\n return training_sample_p\r\n", "_____no_output_____" ], [ "### Training DB-VAE ###\r\n\r\nbatch_size = 32\r\nlearning_rate = 5e-4\r\nlatent_dim = 100\r\n\r\nnum_epochs = 6\r\n\r\ndbvae = DB_VAE(latent_dim)\r\noptimizer = tf.keras.optimizers.Adam(learning_rate)\r\n\r\[email protected]\r\ndef debiasing_train_step(x, y):\r\n with tf.GradientTape() as tape:\r\n y_logit, z_mean, z_logsigma, x_recon = dbvae(x)\r\n loss, class_loss = debiasing_loss_function(x, x_recon, y, y_logit, z_mean, z_logsigma)\r\n grads = tape.gradient(loss, dbvae.trainable_variables)\r\n optimizer.apply_gradients(zip(grads, dbvae.trainable_variables))\r\n return loss\r\n\r\nall_faces = loader.get_all_train_faces()\r\n\r\nif hasattr(tqdm, '_instances'): tqdm._instances.clear()\r\n\r\nfor i in range(num_epochs):\r\n IPython.display.clear_output(wait=True)\r\n print('Starting epoch {}/{}'.format(i+1, num_epochs))\r\n\r\n p_faces = get_training_sample_probabilities(all_faces, dbvae)\r\n\r\n for j in tqdm(range(loader.get_train_size() // batch_size)):\r\n (x, y) = loader.get_batch(batch_size, p_pos=p_faces)\r\n loss = debiasing_train_step(x, y)\r\n\r\n # Plot progress every 500 steps\r\n if j % 500 == 0:\r\n mdl.util.plot_sample(x, y, dbvae)", "Starting epoch 6/6\nRecomputing the sampling probabilities\n" ], [ "dbvae_logits = [dbvae.predict(np.array(x, dtype=np.float32)) for x in test_faces]\r\ndbvae_probs = tf.squeeze(tf.sigmoid(dbvae_logits))\r\n\r\nxx = np.arange(len(keys))\r\nplt.bar(xx, standard_classifier_probs.numpy().mean(1), width=0.2, label='Standard CNN')\r\nplt.bar(xx+0.2, dbvae_probs.numpy().mean(1), width=0.2, label='DB-VAE')\r\nplt.xticks(xx, keys)\r\nplt.title('Network predictions on test dataset')\r\nplt.ylabel('Probability'); plt.legend(bbox_to_anchor=(1.04,1), loc='upper left');", "_____no_output_____" ], [ "dbvae.summary()", "Model: \"db_vae_10\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nsequential_21 (Sequential) (None, 201) 743801 \n_________________________________________________________________\nsequential_22 (Sequential) (32, 64, 64, 3) 166587 \n=================================================================\nTotal params: 910,388\nTrainable params: 909,788\nNon-trainable params: 600\n_________________________________________________________________\n" ], [ "dbvae.encoder.summary()", "Model: \"sequential_21\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_44 (Conv2D) (None, 32, 32, 12) 912 \n_________________________________________________________________\nbatch_normalization_55 (Batc (None, 32, 32, 12) 48 \n_________________________________________________________________\nconv2d_45 (Conv2D) (None, 16, 16, 24) 7224 \n_________________________________________________________________\nbatch_normalization_56 (Batc (None, 16, 16, 24) 96 \n_________________________________________________________________\nconv2d_46 (Conv2D) (None, 8, 8, 48) 10416 \n_________________________________________________________________\nbatch_normalization_57 (Batc (None, 8, 8, 48) 192 \n_________________________________________________________________\nconv2d_47 (Conv2D) (None, 4, 4, 72) 31176 \n_________________________________________________________________\nbatch_normalization_58 (Batc (None, 4, 4, 72) 288 \n_________________________________________________________________\nflatten_11 (Flatten) (None, 1152) 0 \n_________________________________________________________________\ndense_32 (Dense) (None, 512) 590336 \n_________________________________________________________________\ndense_33 (Dense) (None, 201) 103113 \n=================================================================\nTotal params: 743,801\nTrainable params: 743,489\nNon-trainable params: 312\n_________________________________________________________________\n" ], [ "dbvae.decoder.summary()", "Model: \"sequential_22\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_34 (Dense) (32, 1152) 116352 \n_________________________________________________________________\nreshape_10 (Reshape) (32, 4, 4, 72) 0 \n_________________________________________________________________\nbatch_normalization_59 (Batc (32, 4, 4, 72) 288 \n_________________________________________________________________\nconv2d_transpose_42 (Conv2DT (32, 8, 8, 48) 31152 \n_________________________________________________________________\nbatch_normalization_60 (Batc (32, 8, 8, 48) 192 \n_________________________________________________________________\nconv2d_transpose_43 (Conv2DT (32, 16, 16, 24) 10392 \n_________________________________________________________________\nbatch_normalization_61 (Batc (32, 16, 16, 24) 96 \n_________________________________________________________________\nconv2d_transpose_44 (Conv2DT (32, 32, 32, 12) 7212 \n_________________________________________________________________\nconv2d_transpose_45 (Conv2DT (32, 64, 64, 3) 903 \n=================================================================\nTotal params: 166,587\nTrainable params: 166,299\nNon-trainable params: 288\n_________________________________________________________________\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aebffc4874e9349322860ced5d16340143d4198
6,433
ipynb
Jupyter Notebook
site/ja/io/tutorials/genome.ipynb
phoenix-fork-tensorflow/docs-l10n
2287738c22e3e67177555e8a41a0904edfcf1544
[ "Apache-2.0" ]
491
2020-01-27T19:05:32.000Z
2022-03-31T08:50:44.000Z
site/ja/io/tutorials/genome.ipynb
phoenix-fork-tensorflow/docs-l10n
2287738c22e3e67177555e8a41a0904edfcf1544
[ "Apache-2.0" ]
511
2020-01-27T22:40:05.000Z
2022-03-21T08:40:55.000Z
site/ja/io/tutorials/genome.ipynb
phoenix-fork-tensorflow/docs-l10n
2287738c22e3e67177555e8a41a0904edfcf1544
[ "Apache-2.0" ]
627
2020-01-27T21:49:52.000Z
2022-03-28T18:11:50.000Z
28.847534
250
0.52868
[ [ [ "##### Copyright 2020 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_____" ] ], [ [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://www.tensorflow.org/io/tutorials/genome\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\"> TensorFlow.orgで表示</a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/io/tutorials/genome.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\"> Google Colab で実行</a></td>\n <td><a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/ja/io/tutorials/genome.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\">View source on GitHub</a></td>\n <td><a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/io/tutorials/genome.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\">ノートブックをダウンロード/a0}</a></td>\n</table>", "_____no_output_____" ], [ "## 概要\n\nこのチュートリアルでは、一般的に使用されるゲノミクス IO 機能を提供する<code>tfio.genome</code>パッケージについて解説します。これは、いくつかのゲノミクスファイル形式を読み取り、データを準備するための一般的な演算を提供します (例: One-Hot エンコーディングまたは Phred クオリティスコアを確率に解析します)。\n\nこのパッケージは、[Google Nucleus](https://github.com/google/nucleus) ライブラリを使用して、主な機能の一部を提供します。 ", "_____no_output_____" ], [ "## セットアップ", "_____no_output_____" ] ], [ [ "try:\n %tensorflow_version 2.x\nexcept Exception:\n pass\n!pip install tensorflow-io", "_____no_output_____" ], [ "import tensorflow_io as tfio\nimport tensorflow as tf", "_____no_output_____" ] ], [ [ "## FASTQ データ\n\nFASTQ は、基本的な品質情報に加えて両方の配列情報を保存する一般的なゲノミクスファイル形式です。\n\nまず、サンプルの`fastq`ファイルをダウンロードします。", "_____no_output_____" ] ], [ [ "# Download some sample data:\n!curl -OL https://raw.githubusercontent.com/tensorflow/io/master/tests/test_genome/test.fastq", "_____no_output_____" ] ], [ [ "### FASTQ データの読み込み\n\n`tfio.genome.read_fastq`を使用してこのファイルを読みこみます (`tf.data` API は近日中にリリースされる予定です)。", "_____no_output_____" ] ], [ [ "fastq_data = tfio.genome.read_fastq(filename=\"test.fastq\")\nprint(fastq_data.sequences)\nprint(fastq_data.raw_quality)", "_____no_output_____" ] ], [ [ "ご覧のとおり、返された`fastq_data`には fastq ファイル内のすべてのシーケンスの文字列テンソル (それぞれ異なるサイズにすることが可能) である`fastq_data.sequences`、および、シーケンスで読み取られた各塩基の品質に関する Phred エンコードされた品質情報を含む`fastq_data.raw_quality`が含まれています。\n\n### 品質\n\n関心がある場合は、ヘルパーオペレーションを使用して、この品質情報を確率に変換できます。", "_____no_output_____" ] ], [ [ "quality = tfio.genome.phred_sequences_to_probability(fastq_data.raw_quality)\nprint(quality.shape)\nprint(quality.row_lengths().numpy())\nprint(quality)", "_____no_output_____" ] ], [ [ "### One-Hot エンコーディング\n\nまた、One-Hot エンコーダ―を使用してゲノムシーケンスデータ (`A` `T` `C` `G`の塩基配列で構成される) をエンコードすることもできます。これに役立つ演算が組み込まれています。\n", "_____no_output_____" ] ], [ [ "print(tfio.genome.sequences_to_onehot.__doc__)", "_____no_output_____" ], [ "print(tfio.genome.sequences_to_onehot.__doc__)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4aec0a01ccd1735c0f3b57d7f972e4130a2c91d9
102,831
ipynb
Jupyter Notebook
FastGPEstimation/render_CAM_netCDF.ipynb
ayanbiswas/PRISM
d02612a1bda00835e240e046a4fa23c7089a46cc
[ "BSD-3-Clause" ]
1
2021-10-08T20:55:20.000Z
2021-10-08T20:55:20.000Z
FastGPEstimation/render_CAM_netCDF.ipynb
ayanbiswas/PRISM
d02612a1bda00835e240e046a4fa23c7089a46cc
[ "BSD-3-Clause" ]
12
2021-04-16T15:44:08.000Z
2022-03-28T18:58:29.000Z
FastGPEstimation/render_CAM_netCDF.ipynb
ayanbiswas/PRISM
d02612a1bda00835e240e046a4fa23c7089a46cc
[ "BSD-3-Clause" ]
6
2021-06-25T16:10:42.000Z
2022-01-04T17:11:04.000Z
496.768116
96,932
0.938686
[ [ [ "import netCDF4\nfrom netCDF4 import Dataset\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport math\nimport os\nimport glob\nimport pandas\nimport re\nfrom scipy.interpolate import griddata\n\n%matplotlib inline\nplt.rcParams[\"figure.figsize\"] = (10,6)\nplt.rcParams.update({'font.size': 20})", "_____no_output_____" ], [ "data_path = \"/path/netcdf/\"\nfname = \"20200515.ssp585.TEST_SSP585_DEBUG.ne30_oECv3_ICG.grizzly.cam.h2.2015-01-01-00000.nc\"", "_____no_output_____" ], [ "def print_data_info(data):\n # Print some data info\n ###############################\n print (data.variables.keys())\n print (data)\n for d in data.dimensions.items():\n print (d)\n\n ## http://schubert.atmos.colostate.edu/~cslocum/netcdf_example.html\n print (data.data_model)\n\n nc_attrs = data.ncattrs()\n for nc_attr in nc_attrs:\n print ('\\t%s:' % nc_attr, repr(data.getncattr(nc_attr)))\n\n print (\"NetCDF dimension information:\")\n nc_dims = [dim for dim in data.dimensions] # list of nc dimensions\n for dim in nc_dims:\n print (\"\\tName:\", dim)\n print (\"\\t\\tsize:\", len(data.dimensions[dim]))\n\n nc_vars = [var for var in data.variables] # list of nc variables\n\n print (\"NetCDF variable information:\")\n for var in nc_vars:\n if var not in nc_dims:\n print ('\\tName:', var)\n print (\"\\t\\tdimensions:\", data.variables[var].dimensions)\n print (\"\\t\\tsize:\", data.variables[var].size)\n\n \ndef load_data(filename):\n data = Dataset(filename)\n return data", "_____no_output_____" ], [ "## Load data\ndata = load_data(data_path+fname)\n#print_data_info(data)\ntsteps_per_month = len(data.variables['time'][:])\nvar_name = 'T001'\n\ntstep = 100\nlon_array = np.asarray(data.variables['lon'][:])\nlat_array = np.asarray(data.variables['lat'][:])\nuvel = np.asarray(data.variables[var_name][:])\nuvel = np.asarray(uvel[tstep,:])\n\nprint (np.min(lon_array),np.max(lon_array))\nprint (np.min(lat_array),np.max(lat_array))", "0.0 360.0\n-90.0 90.0\n" ], [ "import matplotlib.colors as matcolors\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\nfrom matplotlib.patches import Rectangle\n\ntop = plt.get_cmap('twilight_shifted', 256)\ntop_cmp = matcolors.ListedColormap(top(np.linspace(0.55, 1, 256)))\nbottom = cm.get_cmap('twilight_shifted', 256)\nbottom_cmp = matcolors.ListedColormap(bottom(np.linspace(0.05,0.45,256)))\n\nwhite = np.array(([256/256, 256/256, 256/256, 1]))\n\nnewcolors = np.vstack((bottom_cmp(np.linspace(0, 1, 256)),\n top_cmp(np.linspace(0, 1, 256))))\nnewcmp = matcolors.ListedColormap(newcolors, name='OrangeBlue')\nnewcmp2 = matcolors.ListedColormap(newcmp(np.linspace(0.0, 0.64, 512)))\n\n\n## Render using python grid data\nlon_dim = 360\nlat_dim = 180\n\npoints = np.column_stack((lon_array, lat_array))\n## create 2D regular grid\ngrid_x, grid_y = np.mgrid[0:360:360j, -89:89:180j] ## grid for whole world\ncur_loc = np.zeros((lat_dim*lon_dim,2),dtype='float')\n\nind = 0\nfor j in range(lat_dim):\n for i in range(lon_dim):\n cur_loc[ind,:] = np.array([grid_x[i][j],grid_y[i][j]])\n ind = ind+1\n\nprint(len(points))\n \ngrid_z0 = griddata(points, uvel, cur_loc, method='linear')\ngrid_z0_2d = grid_z0.reshape((lat_dim,lon_dim))\nplt.imshow(grid_z0_2d, origin='lower',cmap=plt.get_cmap(newcmp2))\nplt.colorbar(orientation=\"vertical\", shrink=0.74, label=\"Kelvin\")\nplt.xlabel(\"Longitude\")\nplt.ylabel(\"Latitude\")\nplt.yticks(np.arange(0, 190, 90))\n\nplt.savefig('out.png')", "48602\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4aec133e6d785656647d5a9632502997adbe8086
10,300
ipynb
Jupyter Notebook
PORTAL DE TRANSPARENCIA/PENHA/.ipynb_checkpoints/INSERT DADOS DB PENHA-checkpoint.ipynb
dionathanCordova/Faculdade-websemantica
87f48ba2c484a68d9ce000402ff2e162bf4e3896
[ "MIT" ]
null
null
null
PORTAL DE TRANSPARENCIA/PENHA/.ipynb_checkpoints/INSERT DADOS DB PENHA-checkpoint.ipynb
dionathanCordova/Faculdade-websemantica
87f48ba2c484a68d9ce000402ff2e162bf4e3896
[ "MIT" ]
null
null
null
PORTAL DE TRANSPARENCIA/PENHA/.ipynb_checkpoints/INSERT DADOS DB PENHA-checkpoint.ipynb
dionathanCordova/Faculdade-websemantica
87f48ba2c484a68d9ce000402ff2e162bf4e3896
[ "MIT" ]
null
null
null
36.013986
1,240
0.58233
[ [ [ "import pandas as pd\nimport csv", "_____no_output_____" ], [ "import MySQLdb", "_____no_output_____" ], [ "con = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"prefeitura_sbac\")", "_____no_output_____" ], [ "cursor = con.cursor()", "_____no_output_____" ], [ "Dados = pd.read_excel(\"Consulta de Quadro Funcional PORTO BELO.xlsx\")\nDados.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 1085 entries, 0 to 1084\nData columns (total 19 columns):\nNome Funcionário 1085 non-null object\nUnnamed: 1 0 non-null float64\nUnnamed: 2 0 non-null float64\nCargo 1085 non-null object\nRegime 1085 non-null object\nMensal - Bruto 1085 non-null float64\nMensal - Líquido 1085 non-null float64\nFérias - Bruto 1085 non-null float64\nFérias - Líquido 1085 non-null float64\n13º Salário - Bruto 1085 non-null float64\n13º Salário - Líquido 1085 non-null float64\nTotal - Bruto 1085 non-null float64\nUnnamed: 12 0 non-null float64\nUnnamed: 13 0 non-null float64\nTotal - Líquido 1085 non-null float64\nUnnamed: 15 0 non-null float64\nUnnamed: 16 0 non-null float64\nUnnamed: 17 0 non-null float64\nUnnamed: 18 0 non-null float64\ndtypes: float64(16), object(3)\nmemory usage: 161.1+ KB\n" ], [ "qtd_registros = len(Dados)\nqtd_registros", "_____no_output_____" ] ], [ [ "### DROP TABELA", "_____no_output_____" ] ], [ [ "drop_table = 'DROP TABLE penha'\ncursor.execute(drop_table)", "_____no_output_____" ] ], [ [ "### Criando Tabela", "_____no_output_____" ] ], [ [ "create_table = \"\"\"CREATE TABLE IF NOT EXISTS penha (\nid int not null auto_increment PRIMARY KEY,\nnome varchar(255),\ncargo varchar(255),\nmatricula varchar(30) DEFAULT 'Não Informado',\nCPF varchar(40) default 'Nao informado',\nhoras_mes varchar(40) DEFAULT 'Nao informado',\nmodifield datetime DEFAULT CURRENT_TIMESTAMP,\ncidade varchar(200) default 'Penha',\ntabela varchar(255) DEFAULT 'penha'\n)DEFAULT CHARSET = utf8;\"\"\"\ncursor.execute(create_table)", "_____no_output_____" ] ], [ [ "### SQL INSERT DADOS", "_____no_output_____" ] ], [ [ "query = \"\"\"INSERT INTO penha (nome, cargo) VALUES (%s, %s)\"\"\"", "_____no_output_____" ], [ "cont = 0;\nfor r in range(0, qtd_registros):\n \n # Assign values from each row\n values = (Dados['Nome Funcionário'][cont], Dados['Cargo'][cont])\n\n # Execute sql Query\n cursor.execute(query, values)\n cont = cont + 1", "_____no_output_____" ], [ "# Close the cursor\ncursor.close()", "_____no_output_____" ], [ "# Commit the transaction\ncon.commit()", "_____no_output_____" ], [ "# Close the database connection\ncon.close()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4aec15605f34cb44132b5eb0f5c0dec1353c814b
27,160
ipynb
Jupyter Notebook
img_seg.ipynb
ugonna05/FACE_RECOG_NEW
ccfb60ebfede4d8a31f436fa1bc7f586f257925e
[ "BSL-1.0" ]
null
null
null
img_seg.ipynb
ugonna05/FACE_RECOG_NEW
ccfb60ebfede4d8a31f436fa1bc7f586f257925e
[ "BSL-1.0" ]
null
null
null
img_seg.ipynb
ugonna05/FACE_RECOG_NEW
ccfb60ebfede4d8a31f436fa1bc7f586f257925e
[ "BSL-1.0" ]
null
null
null
93.013699
2,024
0.664249
[ [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import Sequential", "_____no_output_____" ] ], [ [ "set the model architecture", "_____no_output_____" ] ], [ [ "from tensorflow.keras.layers import Flatten, Dense, Conv2D, Reshape", "_____no_output_____" ], [ "model = tf.keras.models.Sequential([\n Flatten(input_shape=[256, 256, 1]),\n Dense(64, activation='relu'),\n Dense(256*256*2, activation='softmax'),\n Reshape((256, 256, 2))\n])", "_____no_output_____" ] ], [ [ "specify how to train the model with algorithm, the loss function and metric", "_____no_output_____" ] ], [ [ "model.compile(\n optimizer = 'adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accruacy']\n)", "_____no_output_____" ] ], [ [ "print the summary of the model", "_____no_output_____" ] ], [ [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nflatten (Flatten) (None, 65536) 0 \n_________________________________________________________________\ndense (Dense) (None, 64) 4194368 \n_________________________________________________________________\ndense_1 (Dense) (None, 131072) 8519680 \n_________________________________________________________________\nreshape (Reshape) (None, 256, 256, 2) 0 \n=================================================================\nTotal params: 12,714,048\nTrainable params: 12,714,048\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "pip install pydot", "Requirement already satisfied: pydot in c:\\programdata\\anaconda31\\envs\\tf-gpu\\lib\\site-packages (1.4.2)\nRequirement already satisfied: pyparsing>=2.1.4 in c:\\programdata\\anaconda31\\envs\\tf-gpu\\lib\\site-packages (from pydot) (3.0.4)\nNote: you may need to restart the kernel to use updated packages.\n" ], [ "import graphviz\n\ndot = graphviz.Digraph('round-table', comment='The Round Table') \n\ndot ", "_____no_output_____" ], [ "# plot the model including the size of the model\ntf.keras.utils.plot_model(model, show_shapes=True)", "('You must install pydot (`pip install pydot`) and install graphviz (see instructions at https://graphviz.gitlab.io/download/) ', 'for plot_model/model_to_dot to work.')\n" ], [ "# define a callback that shows image predictions on the test set\nclass DisplayCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs=None):\n show_predictions()\n print ('\\nSample Prediction after epoch {}\\n'.format(epoch+1))\n\n# setup a tensorboard callback\nlogdir = os.path.join(\"logs\", datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\ntensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)", "_____no_output_____" ], [ "# setup and run the model\nEPOCHS = 20\nSTEPS_PER_EPOCH = len(list(parsed_training_dataset))\nVALIDATION_STEPS = 26\n\nmodel_history = model.fit(train_dataset, epochs=EPOCHS,\n steps_per_epoch=STEPS_PER_EPOCH,\n validation_steps=VALIDATION_STEPS,\n validation_data=test_dataset,\n callbacks=[DisplayCallback(), tensorboard_callback])", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4aec1820311e78e46b2009817d2233a8901a678e
10,670
ipynb
Jupyter Notebook
examples/notebooks/formulas.ipynb
chengevo/statsmodels
c28e6479ace0f0965001c55fb652b2a431bbd158
[ "BSD-3-Clause" ]
null
null
null
examples/notebooks/formulas.ipynb
chengevo/statsmodels
c28e6479ace0f0965001c55fb652b2a431bbd158
[ "BSD-3-Clause" ]
null
null
null
examples/notebooks/formulas.ipynb
chengevo/statsmodels
c28e6479ace0f0965001c55fb652b2a431bbd158
[ "BSD-3-Clause" ]
null
null
null
24.25
435
0.567104
[ [ [ "# Formulas: Fitting models using R-style formulas", "_____no_output_____" ], [ "Since version 0.5.0, ``statsmodels`` allows users to fit statistical models using R-style formulas. Internally, ``statsmodels`` uses the [patsy](http://patsy.readthedocs.org/) package to convert formulas and data to the matrices that are used in model fitting. The formula framework is quite powerful; this tutorial only scratches the surface. A full description of the formula language can be found in the ``patsy`` docs: \n\n* [Patsy formula language description](http://patsy.readthedocs.org/)\n\n## Loading modules and functions", "_____no_output_____" ] ], [ [ "import numpy as np # noqa:F401 needed in namespace for patsy\nimport statsmodels.api as sm", "_____no_output_____" ] ], [ [ "#### Import convention", "_____no_output_____" ], [ "You can import explicitly from statsmodels.formula.api", "_____no_output_____" ] ], [ [ "from statsmodels.formula.api import ols", "_____no_output_____" ] ], [ [ "Alternatively, you can just use the `formula` namespace of the main `statsmodels.api`.", "_____no_output_____" ] ], [ [ "sm.formula.ols", "_____no_output_____" ] ], [ [ "Or you can use the following convention", "_____no_output_____" ] ], [ [ "import statsmodels.formula.api as smf", "_____no_output_____" ] ], [ [ "These names are just a convenient way to get access to each model's `from_formula` classmethod. See, for instance", "_____no_output_____" ] ], [ [ "sm.OLS.from_formula", "_____no_output_____" ] ], [ [ "All of the lower case models accept ``formula`` and ``data`` arguments, whereas upper case ones take ``endog`` and ``exog`` design matrices. ``formula`` accepts a string which describes the model in terms of a ``patsy`` formula. ``data`` takes a [pandas](https://pandas.pydata.org/) data frame or any other data structure that defines a ``__getitem__`` for variable names like a structured array or a dictionary of variables. \n\n``dir(sm.formula)`` will print a list of available models. \n\nFormula-compatible models have the following generic call signature: ``(formula, data, subset=None, *args, **kwargs)``", "_____no_output_____" ], [ "\n## OLS regression using formulas\n\nTo begin, we fit the linear model described on the [Getting Started](./regression_diagnostics.html) page. Download the data, subset columns, and list-wise delete to remove missing observations:", "_____no_output_____" ] ], [ [ "dta = sm.datasets.get_rdataset(\"Guerry\", \"HistData\", cache=True)", "_____no_output_____" ], [ "df = dta.data[['Lottery', 'Literacy', 'Wealth', 'Region']].dropna()\ndf.head()", "_____no_output_____" ] ], [ [ "Fit the model:", "_____no_output_____" ] ], [ [ "mod = ols(formula='Lottery ~ Literacy + Wealth + Region', data=df)\nres = mod.fit()\nprint(res.summary())", "_____no_output_____" ] ], [ [ "## Categorical variables\n\nLooking at the summary printed above, notice that ``patsy`` determined that elements of *Region* were text strings, so it treated *Region* as a categorical variable. `patsy`'s default is also to include an intercept, so we automatically dropped one of the *Region* categories.\n\nIf *Region* had been an integer variable that we wanted to treat explicitly as categorical, we could have done so by using the ``C()`` operator: ", "_____no_output_____" ] ], [ [ "res = ols(formula='Lottery ~ Literacy + Wealth + C(Region)', data=df).fit()\nprint(res.params)", "_____no_output_____" ] ], [ [ "Patsy's mode advanced features for categorical variables are discussed in: [Patsy: Contrast Coding Systems for categorical variables](./contrasts.html)", "_____no_output_____" ], [ "## Operators\n\nWe have already seen that \"~\" separates the left-hand side of the model from the right-hand side, and that \"+\" adds new columns to the design matrix. \n\n## Removing variables\n\nThe \"-\" sign can be used to remove columns/variables. For instance, we can remove the intercept from a model by: ", "_____no_output_____" ] ], [ [ "res = ols(formula='Lottery ~ Literacy + Wealth + C(Region) -1 ', data=df).fit()\nprint(res.params)", "_____no_output_____" ] ], [ [ "## Multiplicative interactions\n\n\":\" adds a new column to the design matrix with the interaction of the other two columns. \"*\" will also include the individual columns that were multiplied together:", "_____no_output_____" ] ], [ [ "res1 = ols(formula='Lottery ~ Literacy : Wealth - 1', data=df).fit()\nres2 = ols(formula='Lottery ~ Literacy * Wealth - 1', data=df).fit()\nprint(res1.params, '\\n')\nprint(res2.params)", "_____no_output_____" ] ], [ [ "Many other things are possible with operators. Please consult the [patsy docs](https://patsy.readthedocs.org/en/latest/formulas.html) to learn more.", "_____no_output_____" ], [ "## Functions\n\nYou can apply vectorized functions to the variables in your model: ", "_____no_output_____" ] ], [ [ "res = smf.ols(formula='Lottery ~ np.log(Literacy)', data=df).fit()\nprint(res.params)", "_____no_output_____" ] ], [ [ "Define a custom function:", "_____no_output_____" ] ], [ [ "def log_plus_1(x):\n return np.log(x) + 1.\nres = smf.ols(formula='Lottery ~ log_plus_1(Literacy)', data=df).fit()\nprint(res.params)", "_____no_output_____" ] ], [ [ "Any function that is in the calling namespace is available to the formula.", "_____no_output_____" ], [ "## Using formulas with models that do not (yet) support them\n\nEven if a given `statsmodels` function does not support formulas, you can still use `patsy`'s formula language to produce design matrices. Those matrices \ncan then be fed to the fitting function as `endog` and `exog` arguments. \n\nTo generate ``numpy`` arrays: ", "_____no_output_____" ] ], [ [ "import patsy\nf = 'Lottery ~ Literacy * Wealth'\ny,X = patsy.dmatrices(f, df, return_type='matrix')\nprint(y[:5])\nprint(X[:5])", "_____no_output_____" ] ], [ [ "To generate pandas data frames: ", "_____no_output_____" ] ], [ [ "f = 'Lottery ~ Literacy * Wealth'\ny,X = patsy.dmatrices(f, df, return_type='dataframe')\nprint(y[:5])\nprint(X[:5])", "_____no_output_____" ], [ "print(sm.OLS(y, X).fit().summary())", "_____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" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4aec2c386894bc985b19cedfad5762eaef8b4960
28,668
ipynb
Jupyter Notebook
2021/benchmarking_mish/Native_Mish_Benchmark_CPU.ipynb
webbigdata-jp/code_for_blog_posts
71bccafc391d81a31c5aad98854ab7fe8a490074
[ "MIT" ]
3
2021-08-22T20:25:20.000Z
2022-03-02T02:57:27.000Z
2021/benchmarking_mish/Native_Mish_Benchmark_CPU.ipynb
webbigdata-jp/code_for_blog_posts
71bccafc391d81a31c5aad98854ab7fe8a490074
[ "MIT" ]
1
2021-12-22T18:07:08.000Z
2021-12-22T18:07:08.000Z
2021/benchmarking_mish/Native_Mish_Benchmark_CPU.ipynb
webbigdata-jp/code_for_blog_posts
71bccafc391d81a31c5aad98854ab7fe8a490074
[ "MIT" ]
1
2021-12-11T04:02:51.000Z
2021-12-11T04:02:51.000Z
41.668605
595
0.57702
[ [ [ "! pip install fastcore --upgrade -qq\n! pip install fastai --upgrade -qq", "\u001b[K |████████████████████████████████| 61kB 6.9MB/s \n\u001b[K |████████████████████████████████| 194kB 13.9MB/s \n\u001b[?25h" ], [ "from fastai.vision.all import *\nimport fastai\nfrom sys import exit\nfrom operator import itemgetter\nimport re\nimport torch\nfrom torch.nn import functional as F\nimport numpy as np\nfrom time import process_time_ns, process_time\nimport gc", "_____no_output_____" ], [ "def scale(val, spec=\"#0.4G\"):\n PREFIXES = np.array([c for c in u\"yzafpnµm kMGTPEZY\"])\n exp = np.int8(np.log10(np.abs(val)) // 3 * 3 * np.sign(val))\n val /= 10.**exp\n prefix = PREFIXES[exp//3 + len(PREFIXES)//2]\n return f\"{val:{spec}}{prefix}\"\n\ndef display_times(times):\n return f\"{scale(times.mean())}s ± {scale(times.std())}s, {scale(times.min())}s, {scale(times.max())}s\"\n\ndef profile_cpu(func, inp, n_repeat=100, warmup=10):\n fwd_times,bwd_times = [],[]\n for i in range(n_repeat + warmup):\n start = process_time()\n res = func(inp)\n end = process_time()\n if i >= warmup: fwd_times.append(end-start)\n inp = inp.clone().requires_grad_()\n y = func(inp)\n l = y.mean()\n start = process_time()\n _ = torch.autograd.grad(l, inp)\n end = process_time()\n if i >= warmup: bwd_times.append(end-start)\n return (np.array(fwd_times), # Elapsed time is in seconds\n np.array(bwd_times))\n \ndef profile_cuda(func, inp, n_repeat=100, warmup=10):\n fwd_times,bwd_times = [],[]\n for i in range(n_repeat + warmup):\n start,end = (torch.cuda.Event(enable_timing=True) for _ in range(2))\n start.record()\n res = func(inp)\n end.record()\n torch.cuda.synchronize()\n if i >= warmup: fwd_times.append(start.elapsed_time(end))\n start,end = (torch.cuda.Event(enable_timing=True) for _ in range(2))\n inp = inp.clone().requires_grad_()\n y = func(inp)\n l = y.mean()\n start.record()\n _ = torch.autograd.grad(l, inp)\n end.record()\n torch.cuda.synchronize()\n if i >= warmup: bwd_times.append(start.elapsed_time(end))\n return (np.array(fwd_times)/1000, # Elapsed time is in ms\n np.array(bwd_times)/1000)\n\nmish_pt = lambda x: x.mul(torch.tanh(F.softplus(x)))\n\ndef profile(device='cuda', n_repeat=100, warmup=10, size='(16,10,256,256)', baseline=True, types='all'):\n if types == 'all': \n dtypes = [torch.float16, torch.bfloat16, torch.float32, torch.float64]\n else:\n if not hasattr(torch, types): exit(\"Invalid data type, expected torch type or 'all', got {types}\")\n dtypes = [getattr(torch, types)]\n dev = torch.device(type=device)\n sz_str = size.replace(' ','')\n if not re.match(r\"[\\(\\[]\\d+(,\\d+)*[\\)\\]]\", sz_str):\n exit(\"Badly formatted size, should be a list or tuple such as \\\"(1,2,3)\\\".\")\n sz = list(map(int, sz_str[1:-1].split(',')))\n print(f\"Profiling over {n_repeat} runs after {warmup} warmup runs.\")\n for dtype in dtypes:\n if len(dtypes) > 1:\n print(f\"Testing on {dtype}:\")\n ind = ' '\n else: ind = ''\n inp = torch.randn(*sz, dtype=dtype, device=dev)\n timings = []\n funcs = {}\n funcs.update(relu = torch.nn.functional.relu, \n leaky_relu = torch.nn.functional.leaky_relu,\n softplus = torch.nn.functional.softplus,\n silu_jit = fastai.layers.swish,\n silu_native = torch.nn.functional.silu,\n mish_naive = mish_pt,\n mish_jit = fastai.layers.mish,\n mish_native = torch.nn.functional.mish)\n if device=='cuda': funcs['mish_cuda'] = MishCudaFunction.apply\n max_name = max(map(len, funcs.keys())) + 6\n for (name,func) in funcs.items():\n if device=='cuda':\n if (name=='mish_cuda') and (dtype==torch.bfloat16):\n pass\n else: \n fwd_times,bwd_times = profile_cuda(func, inp, n_repeat, warmup)\n torch.cuda.empty_cache()\n if device=='cpu':\n fwd_times,bwd_times = profile_cpu(func, inp, n_repeat, warmup)\n gc.collect()\n print(ind+(name+'_fwd:').ljust(max_name) + display_times(fwd_times))\n print(ind+(name+'_bwd:').ljust(max_name) + display_times(bwd_times))", "_____no_output_____" ] ], [ [ "# Haswell Benchmark", "_____no_output_____" ] ], [ [ "!cat /proc/cpuinfo", "processor\t: 0\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 63\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.30GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2299.998\ncache size\t: 46080 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 0\ncpu cores\t: 2\napicid\t\t: 0\ninitial apicid\t: 0\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs\nbogomips\t: 4599.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\nprocessor\t: 1\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 63\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.30GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2299.998\ncache size\t: 46080 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 1\ncpu cores\t: 2\napicid\t\t: 2\ninitial apicid\t: 2\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs\nbogomips\t: 4599.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\nprocessor\t: 2\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 63\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.30GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2299.998\ncache size\t: 46080 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 0\ncpu cores\t: 2\napicid\t\t: 1\ninitial apicid\t: 1\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs\nbogomips\t: 4599.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\nprocessor\t: 3\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 63\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.30GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2299.998\ncache size\t: 46080 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 1\ncpu cores\t: 2\napicid\t\t: 3\ninitial apicid\t: 3\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs\nbogomips\t: 4599.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\n" ], [ "profile('cpu', types='float32')", "Profiling over 100 runs after 10 warmup runs.\nrelu_fwd: 19.95ms ± 618.7µs, 18.61ms, 23.66ms\nrelu_bwd: 44.59ms ± 1.026ms, 42.70ms, 49.14ms\nleaky_relu_fwd: 20.60ms ± 850.2µs, 17.80ms, 25.07ms\nleaky_relu_bwd: 45.02ms ± 1.071ms, 42.83ms, 48.56ms\nsoftplus_fwd: 61.69ms ± 1.328ms, 59.94ms, 65.84ms\nsoftplus_bwd: 49.82ms ± 1.341ms, 48.06ms, 56.02ms\nsilu_jit_fwd: 47.55ms ± 2.001ms, 44.50ms, 53.54ms\nsilu_jit_bwd: 168.6ms ± 2.993ms, 162.4ms, 181.5ms\nsilu_native_fwd: 24.50ms ± 1.224ms, 22.62ms, 30.06ms\nsilu_native_bwd: 50.89ms ± 1.382ms, 48.49ms, 58.31ms\nmish_naive_fwd: 123.6ms ± 2.575ms, 120.1ms, 132.6ms\nmish_naive_bwd: 143.0ms ± 2.669ms, 138.1ms, 154.2ms\nmish_jit_fwd: 123.0ms ± 2.387ms, 120.1ms, 132.0ms\nmish_jit_bwd: 292.3ms ± 3.622ms, 284.6ms, 301.6ms\nmish_native_fwd: 144.5ms ± 1.294ms, 142.3ms, 149.8ms\nmish_native_bwd: 183.0ms ± 2.418ms, 178.8ms, 192.1ms\n" ], [ "profile('cpu', size='(64,10,256,256)', types='float32')", "Profiling over 100 runs after 10 warmup runs.\nrelu_fwd: 78.93ms ± 1.870ms, 75.26ms, 88.00ms\nrelu_bwd: 175.0ms ± 2.626ms, 170.0ms, 184.1ms\nleaky_relu_fwd: 81.81ms ± 2.367ms, 75.91ms, 90.04ms\nleaky_relu_bwd: 176.3ms ± 3.326ms, 166.3ms, 186.4ms\nsoftplus_fwd: 243.1ms ± 3.984ms, 234.5ms, 253.9ms\nsoftplus_bwd: 196.2ms ± 3.845ms, 184.3ms, 207.4ms\nsilu_jit_fwd: 190.5ms ± 4.441ms, 181.1ms, 201.5ms\nsilu_jit_bwd: 681.8ms ± 15.51ms, 637.7ms, 791.3ms\nsilu_native_fwd: 100.7ms ± 3.996ms, 92.33ms, 109.7ms\nsilu_native_bwd: 200.6ms ± 4.758ms, 187.2ms, 213.4ms\nmish_naive_fwd: 495.6ms ± 7.702ms, 476.5ms, 517.5ms\nmish_naive_bwd: 576.7ms ± 8.659ms, 555.7ms, 600.0ms\nmish_jit_fwd: 495.2ms ± 8.542ms, 477.5ms, 519.2ms\nmish_jit_bwd: 1.175 s ± 12.98ms, 1.145 s, 1.215 s\nmish_native_fwd: 581.8ms ± 8.295ms, 566.9ms, 600.7ms\nmish_native_bwd: 738.3ms ± 10.09ms, 720.1ms, 764.4ms\n" ] ], [ [ "# Broadwell Benchmark", "_____no_output_____" ] ], [ [ "!cat /proc/cpuinfo", "processor\t: 0\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 79\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.20GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2199.998\ncache size\t: 56320 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 0\ncpu cores\t: 2\napicid\t\t: 0\ninitial apicid\t: 0\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\nbogomips\t: 4399.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\nprocessor\t: 1\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 79\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.20GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2199.998\ncache size\t: 56320 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 1\ncpu cores\t: 2\napicid\t\t: 2\ninitial apicid\t: 2\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\nbogomips\t: 4399.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\nprocessor\t: 2\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 79\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.20GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2199.998\ncache size\t: 56320 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 0\ncpu cores\t: 2\napicid\t\t: 1\ninitial apicid\t: 1\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\nbogomips\t: 4399.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\nprocessor\t: 3\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 79\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.20GHz\nstepping\t: 0\nmicrocode\t: 0x1\ncpu MHz\t\t: 2199.998\ncache size\t: 56320 KB\nphysical id\t: 0\nsiblings\t: 4\ncore id\t\t: 1\ncpu cores\t: 2\napicid\t\t: 3\ninitial apicid\t: 3\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\nbogomips\t: 4399.99\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\n" ], [ "profile('cpu', types='float32')", "Profiling over 100 runs after 10 warmup runs.\nrelu_fwd: 15.49ms ± 768.0µs, 14.12ms, 17.71ms\nrelu_bwd: 35.51ms ± 1.919ms, 32.72ms, 43.52ms\nleaky_relu_fwd: 16.01ms ± 868.3µs, 14.39ms, 20.81ms\nleaky_relu_bwd: 35.29ms ± 1.139ms, 33.73ms, 40.99ms\nsoftplus_fwd: 66.98ms ± 1.975ms, 62.24ms, 75.23ms\nsoftplus_bwd: 41.12ms ± 1.893ms, 37.99ms, 49.38ms\nsilu_jit_fwd: 43.30ms ± 1.571ms, 39.81ms, 47.84ms\nsilu_jit_bwd: 142.4ms ± 3.976ms, 135.5ms, 156.1ms\nsilu_native_fwd: 23.05ms ± 1.368ms, 20.84ms, 28.65ms\nsilu_native_bwd: 41.87ms ± 1.587ms, 39.88ms, 52.11ms\nmish_naive_fwd: 124.8ms ± 3.692ms, 118.8ms, 137.8ms\nmish_naive_bwd: 118.7ms ± 3.661ms, 112.9ms, 130.1ms\nmish_jit_fwd: 139.6ms ± 2.405ms, 133.1ms, 150.1ms\nmish_jit_bwd: 270.1ms ± 5.565ms, 258.9ms, 286.4ms\nmish_native_fwd: 139.6ms ± 2.304ms, 135.7ms, 150.3ms\nmish_native_bwd: 173.2ms ± 2.784ms, 166.2ms, 182.4ms\n" ], [ "profile('cpu', size='(64,10,256,256)', types='float32')", "Profiling over 100 runs after 10 warmup runs.\nrelu_fwd: 59.45ms ± 2.378ms, 54.24ms, 66.46ms\nrelu_bwd: 136.5ms ± 3.777ms, 128.7ms, 146.9ms\nleaky_relu_fwd: 63.26ms ± 1.723ms, 59.52ms, 69.18ms\nleaky_relu_bwd: 139.9ms ± 3.657ms, 131.3ms, 151.8ms\nsoftplus_fwd: 267.5ms ± 5.315ms, 256.5ms, 279.5ms\nsoftplus_bwd: 162.7ms ± 4.240ms, 153.0ms, 174.3ms\nsilu_jit_fwd: 168.0ms ± 4.140ms, 158.5ms, 187.2ms\nsilu_jit_bwd: 560.7ms ± 11.17ms, 533.8ms, 585.3ms\nsilu_native_fwd: 91.60ms ± 3.132ms, 83.69ms, 101.3ms\nsilu_native_bwd: 166.7ms ± 4.551ms, 158.1ms, 178.5ms\nmish_naive_fwd: 499.9ms ± 9.079ms, 482.2ms, 523.9ms\nmish_naive_bwd: 471.1ms ± 10.61ms, 443.7ms, 496.3ms\nmish_jit_fwd: 509.2ms ± 10.31ms, 487.0ms, 532.1ms\nmish_jit_bwd: 1.064 s ± 17.73ms, 1.024 s, 1.114 s\nmish_native_fwd: 573.2ms ± 7.804ms, 554.6ms, 589.9ms\nmish_native_bwd: 691.8ms ± 8.222ms, 671.7ms, 707.4ms\n" ] ], [ [ "# Skylake Benchmark", "_____no_output_____" ] ], [ [ "!cat /proc/cpuinfo", "processor\t: 0\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 85\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.00GHz\nstepping\t: 3\nmicrocode\t: 0x1\ncpu MHz\t\t: 2000.186\ncache size\t: 39424 KB\nphysical id\t: 0\nsiblings\t: 2\ncore id\t\t: 0\ncpu cores\t: 1\napicid\t\t: 0\ninitial apicid\t: 0\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\nbogomips\t: 4000.37\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\nprocessor\t: 1\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 85\nmodel name\t: Intel(R) Xeon(R) CPU @ 2.00GHz\nstepping\t: 3\nmicrocode\t: 0x1\ncpu MHz\t\t: 2000.186\ncache size\t: 39424 KB\nphysical id\t: 0\nsiblings\t: 2\ncore id\t\t: 0\ncpu cores\t: 1\napicid\t\t: 1\ninitial apicid\t: 1\nfpu\t\t: yes\nfpu_exception\t: yes\ncpuid level\t: 13\nwp\t\t: yes\nflags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat md_clear arch_capabilities\nbugs\t\t: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\nbogomips\t: 4000.37\nclflush size\t: 64\ncache_alignment\t: 64\naddress sizes\t: 46 bits physical, 48 bits virtual\npower management:\n\n" ], [ "profile('cpu', types='float32')", "Profiling over 100 runs after 10 warmup runs.\nrelu_fwd: 9.791ms ± 541.3µs, 9.225ms, 13.19ms\nrelu_bwd: 26.25ms ± 808.5µs, 25.39ms, 29.88ms\nleaky_relu_fwd: 10.69ms ± 664.5µs, 9.579ms, 13.68ms\nleaky_relu_bwd: 28.27ms ± 1.210ms, 26.49ms, 31.89ms\nsoftplus_fwd: 48.18ms ± 2.954ms, 43.05ms, 53.93ms\nsoftplus_bwd: 32.99ms ± 2.090ms, 30.05ms, 40.69ms\nsilu_jit_fwd: 27.55ms ± 1.636ms, 25.81ms, 34.08ms\nsilu_jit_bwd: 95.21ms ± 2.974ms, 91.30ms, 105.0ms\nsilu_native_fwd: 13.83ms ± 687.5µs, 13.23ms, 17.85ms\nsilu_native_bwd: 30.66ms ± 1.096ms, 29.63ms, 35.38ms\nmish_naive_fwd: 74.72ms ± 5.135ms, 68.01ms, 85.55ms\nmish_naive_bwd: 84.82ms ± 3.569ms, 78.94ms, 94.52ms\nmish_jit_fwd: 73.17ms ± 4.608ms, 67.65ms, 85.18ms\nmish_jit_bwd: 170.3ms ± 7.535ms, 160.6ms, 189.9ms\nmish_native_fwd: 113.9ms ± 7.488ms, 103.4ms, 129.7ms\nmish_native_bwd: 142.7ms ± 9.413ms, 130.2ms, 164.6ms\n" ], [ "profile('cpu', size='(64,10,256,256)', types='float32')", "Profiling over 100 runs after 10 warmup runs.\nrelu_fwd: 41.32ms ± 1.600ms, 38.73ms, 45.67ms\nrelu_bwd: 109.2ms ± 2.995ms, 102.6ms, 117.3ms\nleaky_relu_fwd: 41.42ms ± 1.746ms, 38.96ms, 47.14ms\nleaky_relu_bwd: 106.5ms ± 3.433ms, 102.9ms, 118.4ms\nsoftplus_fwd: 192.2ms ± 13.23ms, 176.6ms, 232.9ms\nsoftplus_bwd: 126.0ms ± 6.323ms, 117.7ms, 145.4ms\nsilu_jit_fwd: 117.0ms ± 5.936ms, 108.8ms, 133.7ms\nsilu_jit_bwd: 388.1ms ± 12.02ms, 370.5ms, 419.9ms\nsilu_native_fwd: 61.13ms ± 4.576ms, 55.08ms, 74.42ms\nsilu_native_bwd: 128.3ms ± 6.544ms, 120.1ms, 150.0ms\nmish_naive_fwd: 289.8ms ± 17.85ms, 272.0ms, 348.9ms\nmish_naive_bwd: 331.7ms ± 11.10ms, 317.6ms, 361.1ms\nmish_jit_fwd: 299.1ms ± 17.01ms, 275.1ms, 343.5ms\nmish_jit_bwd: 691.3ms ± 29.15ms, 647.8ms, 759.4ms\nmish_native_fwd: 445.9ms ± 33.82ms, 414.7ms, 543.5ms\nmish_native_bwd: 553.9ms ± 36.91ms, 514.4ms, 659.7ms\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4aec2defd57c439aadd38b73f013f42e50dd4d76
25,165
ipynb
Jupyter Notebook
completed/Session Last - Textcat-Toxic-Completed.ipynb
mingsqtt/textanalytics_ml
87b0bd3d0e716e44a2cf627a6d7a1345aa886959
[ "MIT" ]
null
null
null
completed/Session Last - Textcat-Toxic-Completed.ipynb
mingsqtt/textanalytics_ml
87b0bd3d0e716e44a2cf627a6d7a1345aa886959
[ "MIT" ]
null
null
null
completed/Session Last - Textcat-Toxic-Completed.ipynb
mingsqtt/textanalytics_ml
87b0bd3d0e716e44a2cf627a6d7a1345aa886959
[ "MIT" ]
null
null
null
34.758287
295
0.509557
[ [ [ "%%html\n<style> table {float:left} </style>", "_____no_output_____" ], [ "!pip install torch tqdm lazyme nltk gensim\n!python -m nltk.downloader punkt", "Requirement already satisfied: torch in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (1.3.1)\nRequirement already satisfied: tqdm in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (4.40.0)\nRequirement already satisfied: lazyme in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (0.0.23)\nRequirement already satisfied: nltk in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (3.4.5)\nRequirement already satisfied: gensim in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (3.8.1)\nRequirement already satisfied: numpy in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from torch) (1.17.4)\nRequirement already satisfied: six in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from nltk) (1.13.0)\nRequirement already satisfied: scipy>=0.18.1 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from gensim) (1.3.3)\nRequirement already satisfied: smart-open>=1.8.1 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from gensim) (1.9.0)\nRequirement already satisfied: requests in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from smart-open>=1.8.1->gensim) (2.22.0)\nRequirement already satisfied: boto3 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from smart-open>=1.8.1->gensim) (1.10.30)\nRequirement already satisfied: boto>=2.32 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from smart-open>=1.8.1->gensim) (2.49.0)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from requests->smart-open>=1.8.1->gensim) (3.0.4)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from requests->smart-open>=1.8.1->gensim) (1.25.7)\nRequirement already satisfied: idna<2.9,>=2.5 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from requests->smart-open>=1.8.1->gensim) (2.8)\nRequirement already satisfied: certifi>=2017.4.17 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from requests->smart-open>=1.8.1->gensim) (2019.9.11)\nRequirement already satisfied: s3transfer<0.3.0,>=0.2.0 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from boto3->smart-open>=1.8.1->gensim) (0.2.1)\nRequirement already satisfied: botocore<1.14.0,>=1.13.30 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from boto3->smart-open>=1.8.1->gensim) (1.13.30)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from boto3->smart-open>=1.8.1->gensim) (0.9.4)\nRequirement already satisfied: docutils<0.16,>=0.10 in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from botocore<1.14.0,>=1.13.30->boto3->smart-open>=1.8.1->gensim) (0.15.2)\nRequirement already satisfied: python-dateutil<2.8.1,>=2.1; python_version >= \"2.7\" in d:\\apps\\anaconda3\\envs\\torch-nlp\\lib\\site-packages (from botocore<1.14.0,>=1.13.30->boto3->smart-open>=1.8.1->gensim) (2.8.0)\n" ], [ "import numpy as np\nfrom tqdm import tqdm\n\nimport pandas as pd\n\nfrom gensim.corpora import Dictionary\n\nimport torch\nfrom torch import nn, optim, tensor, autograd\nfrom torch.nn import functional as F\nfrom torch.utils.data import Dataset, DataLoader", "_____no_output_____" ], [ "try: # Use the default NLTK tokenizer.\n from nltk import word_tokenize, sent_tokenize \n # Testing whether it works. \n # Sometimes it doesn't work on some machines because of setup issues.\n word_tokenize(sent_tokenize(\"This is a foobar sentence. Yes it is.\")[0])\nexcept: # Use a naive sentence tokenizer and toktok.\n import re\n from nltk.tokenize import ToktokTokenizer\n # See https://stackoverflow.com/a/25736515/610569\n sent_tokenize = lambda x: re.split(r'(?<=[^A-Z].[.?]) +(?=[A-Z])', x)\n # Use the toktok tokenizer that requires no dependencies.\n toktok = ToktokTokenizer()\n word_tokenize = word_tokenize = toktok.tokenize", "_____no_output_____" ] ], [ [ "# Classifying Toxic Comments\n\nLets apply what we learnt in a realistic task and **fight cyber-abuse with NLP**!\n\nFrom https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/\n\n> *The threat of abuse and harassment online means that many people stop <br>*\n> *expressing themselves and give up on seeking different opinions. <br>*\n> *Platforms struggle to effectively facilitate conversations, leading many <br>*\n> *communities to limit or completely shut down user comments.*\n\n\nThe goal of the task is to build a model to detect different types of of toxicity:\n\n - toxic\n - severe toxic\n - threats\n - obscenity\n - insults\n - identity-based hate\n \nIn this part, you'll be munging the data as how I would be doing it at work. \n\nYour task is to train a feed-forward network on the toxic comments given the skills we have accomplished thus far.", "_____no_output_____" ], [ "## Digging into the data...\n\nIf you're using linux/Mac you can use these bang commands in the notebook:\n\n```\n!pip3 install kaggle\n!mkdir -p /content/.kaggle/\n!echo '{\"username\":\"natgillin\",\"key\":\"54ae95ab760b52c3307ed4645c6c9b5d\"}' > /content/.kaggle/kaggle.json\n!chmod 600 /content/.kaggle/kaggle.json\n!kaggle competitions download -c jigsaw-toxic-comment-classification-challenge\n!unzip /content/.kaggle/competitions/jigsaw-toxic-comment-classification-challenge/*\n```\n\nOtherwise, download the data from https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/ ", "_____no_output_____" ] ], [ [ "df_train = pd.read_csv('D:/projects/tsundoku-master/data/toxic/train.csv')\ndf_train.head()", "_____no_output_____" ], [ "df_train[df_train['threat'] == 1]['comment_text']", "_____no_output_____" ], [ "df_train.iloc[3712]['comment_text']", "_____no_output_____" ], [ "df_train['comment_text_tokenzied'] = df_train['comment_text'].apply(word_tokenize)", "_____no_output_____" ], [ "# Just in case your Jupyter kernel dies, save the tokenized text =)\n\n# To save your tokenized text you can do this:\nimport pickle\nwith open('train_tokenized_text.pkl', 'wb') as fout:\n pickle.dump(df_train['comment_text_tokenzied'], fout)\n", "_____no_output_____" ], [ "# To load it back:\nimport pickle\nwith open('train_tokenized_text.pkl', 'rb') as fin:\n df_train['comment_text_tokenzied'] = pickle.load(fin)", "_____no_output_____" ] ], [ [ "# How to get a one-hot?\n\nThere are many variants of how to get your one-hot embeddings from the individual columns.\n\nThis is one way:", "_____no_output_____" ] ], [ [ "label_column_names = \"toxic\tsevere_toxic\tobscene\tthreat\tinsult\tidentity_hate\".split()\ndf_train[label_column_names].values", "_____no_output_____" ], [ "torch.tensor(df_train[label_column_names].values).float()", "_____no_output_____" ], [ "# Convert one-hot to indices of the column.\n\nprint(np.argmax(df_train[label_column_names].values, axis=1))", "[0 0 0 ... 0 0 0]\n" ], [ "class ToxicDataset(Dataset):\n def __init__(self, texts, labels):\n self.texts = texts\n self.vocab = Dictionary(texts)\n special_tokens = {'<pad>': 0, '<unk>':1}\n self.vocab = Dictionary(texts)\n self.vocab.patch_with_special_tokens(special_tokens)\n \n self.vocab_size = len(self.vocab)\n \n # Vectorize labels\n self.labels = torch.tensor(labels)\n # Keep track of how many data points.\n self._len = len(texts)\n \n # Find the longest text in the data.\n self.max_len = max(len(txt) for txt in texts)\n \n self.num_labels = len(labels[0])\n \n def __getitem__(self, index):\n vectorized_sent = self.vectorize(self.texts[index])\n # To pad the sentence:\n # Pad left = 0; Pad right = max_len - len of sent.\n pad_dim = (0, self.max_len - len(vectorized_sent))\n vectorized_sent = F.pad(vectorized_sent, pad_dim, 'constant')\n return {'x':vectorized_sent, \n 'y':self.labels[index], \n 'x_len':len(vectorized_sent)}\n \n def __len__(self):\n return self._len\n \n def vectorize(self, tokens):\n \"\"\"\n :param tokens: Tokens that should be vectorized. \n :type tokens: list(str)\n \"\"\"\n # See https://radimrehurek.com/gensim/corpora/dictionary.html#gensim.corpora.dictionary.Dictionary.doc2idx \n # Lets just cast list of indices into torch tensors directly =)\n return torch.tensor(self.vocab.doc2idx(tokens))\n \n def unvectorize(self, indices):\n \"\"\"\n :param indices: Converts the indices back to tokens.\n :type tokens: list(int)\n \"\"\"\n return [self.vocab[i] for i in indices]", "_____no_output_____" ], [ "label_column_names = \"toxic\tsevere_toxic\tobscene\tthreat\tinsult\tidentity_hate\".split()\ntoxic_data = ToxicDataset(df_train['comment_text_tokenzied'],\n df_train[label_column_names].values)", "_____no_output_____" ], [ "toxic_data[123]", "_____no_output_____" ], [ "batch_size = 20\ndataloader = DataLoader(dataset=toxic_data, \n batch_size=batch_size, shuffle=True)", "_____no_output_____" ], [ "class FFNet(nn.Module):\n def __init__(self, max_len, num_labels, vocab_size, embedding_size, hidden_dim):\n super(FFNet, self).__init__()\n self.embeddings = nn.Embedding(num_embeddings=vocab_size,\n embedding_dim=embedding_size, \n padding_idx=0)\n # The no. of inputs to the linear layer is the \n # no. of tokens in each input * embedding_size\n self.linear1 = nn.Linear(embedding_size*max_len, hidden_dim)\n self.linear2 = nn.Linear(hidden_dim, num_labels)\n \n def forward(self, inputs):\n # We want to flatten the inputs so that we get the matrix of shape.\n # batch_size x no. of tokens in each input * embedding_size\n batch_size, max_len = inputs.shape\n embedded = self.embeddings(inputs).view(batch_size, -1)\n hid = F.relu(self.linear1(embedded))\n out = self.linear2(hid)\n return F.sigmoid(out)\n ", "_____no_output_____" ], [ "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nembedding_size = 100\nlearning_rate = 0.003\nhidden_size = 100\n\n\ncriterion = nn.BCELoss()\n# Hint: the CBOW model object you've created.\nmodel = FFNet(toxic_data.max_len, \n len(label_column_names),\n toxic_data.vocab_size, \n embedding_size=embedding_size, \n hidden_dim=hidden_size).to(device)\n\n\noptimizer = optim.Adam(model.parameters(), lr=learning_rate)\n\n#model = nn.DataParallel(model)\n\nlosses = []\nnum_epochs = 50\nfor _e in range(num_epochs):\n epoch_loss = []\n for batch in tqdm(dataloader):\n x = batch['x'].to(device)\n y = batch['y'].to(device)\n # Zero gradient.\n optimizer.zero_grad()\n # Feed forward.\n predictions = model(x)\n loss = criterion(predictions, y.float())\n loss.backward()\n optimizer.step()\n epoch_loss.append(float(loss))\n \n print(sum(epoch_loss)/len(epoch_loss))\n losses.append(sum(epoch_loss)/len(epoch_loss))\n ", " 0%| | 0/7979 [00:00<?, ?it/s]D:\\apps\\Anaconda3\\envs\\torch-nlp\\lib\\site-packages\\torch\\nn\\functional.py:1351: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\n warnings.warn(\"nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\")\n 99%|█████████████████████████████████████████████████████████████████████████████▏| 7893/7979 [03:47<00:02, 35.36it/s]" ], [ "\ndef predict(text):\n # Vectorize and Pad.\n vectorized_sent = toxic_data.vectorize(word_tokenize(text))\n pad_dim = (0, toxic_data.max_len - len(vectorized_sent))\n vectorized_sent = F.pad(vectorized_sent, pad_dim, 'constant')\n # Forward Propagation.\n # Unsqueeze because model is expecting `batch_size` x `sequence_len` shape.\n outputs = model(vectorized_sent.unsqueeze(0).to(device)).squeeze()\n # To get the boolean output, we check if outputs are > 0.5\n return [int(l > 0.5) for l in outputs]\n # What happens if you use torch.max instead? =)\n ##return label_column_names[int(torch.max(outputs, dim=1).indices)]", "_____no_output_____" ], [ "text = \"This is a nice message.\"", "_____no_output_____" ], [ "print(label_column_names)\npredict(text)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aec2f35db1c4969451f44f8a068d66097286073
134,495
ipynb
Jupyter Notebook
L04-Pandas_Part2-Practice.ipynb
shresthasrijana099/Data-Analytics-With-Python
09ca484816b44dfe5857d36a0401746871ae7d9c
[ "Apache-2.0" ]
null
null
null
L04-Pandas_Part2-Practice.ipynb
shresthasrijana099/Data-Analytics-With-Python
09ca484816b44dfe5857d36a0401746871ae7d9c
[ "Apache-2.0" ]
null
null
null
L04-Pandas_Part2-Practice.ipynb
shresthasrijana099/Data-Analytics-With-Python
09ca484816b44dfe5857d36a0401746871ae7d9c
[ "Apache-2.0" ]
null
null
null
29.559341
568
0.329365
[ [ [ "# Lesson 4 Practice: Pandas Part 2\n\nUse this notebook to follow along with the lesson in the corresponding lesson notebook: [L04-Pandas_Part2-Lesson.ipynb](./L04-Pandas_Part2-Lesson.ipynb). \n", "_____no_output_____" ], [ "## Instructions\nFollow along with the teaching material in the lesson. Throughout the tutorial sections labeled as \"Tasks\" are interspersed and indicated with the icon: ![Task](http://icons.iconarchive.com/icons/sbstnblnd/plateau/16/Apps-gnome-info-icon.png). You should follow the instructions provided in these sections by performing them in the practice notebook. When the tutorial is completed you can turn in the final practice notebook. For each task, use the cell below it to write and test your code. You may add additional cells for any task as needed or desired. ", "_____no_output_____" ], [ "## Task 1a: Setup\n\n- import pandas\n- re-create the `df` data frame\n- re-create the `iris_df` data frame", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "df = pd.DataFrame(\n{'alpha': [0, 1, 2, 3, 4],\n 'beta': ['a', 'b', 'c', 'd', 'e']})\ndf", "_____no_output_____" ], [ "iris_df = pd.read_csv('data/iris.csv')\niris_df", "_____no_output_____" ] ], [ [ "## Task 2a: Inserting Columns\n\n+ Create a copy of the `df` dataframe.\n+ Add a new column named \"delta\" to the copy that consists of random numbers.", "_____no_output_____" ] ], [ [ "df['delta'] = np.random.random([5])\ndf", "_____no_output_____" ] ], [ [ "## Task 3a: Missing Data\n\n+ Create two new copies of the `df` dataframe:\n+ Add a new column to both that has missing values.\n+ In one copy, replace missing values with a value of your choice.\n+ In the other copy, drop rows with `NaN` values.\n+ Print both arrays to confirm.", "_____no_output_____" ] ], [ [ "df['gamma'] = pd.Series([2,5,7, np.nan, 8])\ndf", "_____no_output_____" ], [ "a = df.fillna(100)\na", "_____no_output_____" ], [ "df['theta'] = pd.Series([1,6,9, np.nan, 8])\ndf", "_____no_output_____" ], [ "b = df.dropna()\nb", "_____no_output_____" ] ], [ [ "## Task 4a: Operations\n<span style=\"float:right; margin-left:10px; clear:both;\">![Task](./media/task-icon.png)</span>\n\nView the [Computational tools](https://pandas.pydata.org/pandas-docs/stable/user_guide/computation.html) and [statistical methods](https://pandas.pydata.org/pandas-docs/stable/user_guide/computation.html#method-summary) documentation.\nUsing the list of operational functions choose five functions to use with the iris data frame.\n\n", "_____no_output_____" ] ], [ [ "iris_df.mean()", "_____no_output_____" ], [ "iris_df.mean(1)", "_____no_output_____" ], [ "iris_df.min(1)", "_____no_output_____" ], [ "iris_df.std(1)", "_____no_output_____" ], [ "iris_df.var(1)", "_____no_output_____" ], [ "iris_df.count(1)", "_____no_output_____" ] ], [ [ "## Task 4b: Apply\n\nPractice using `apply` on either the `df` or `iris_df` data frames using any two functions of your choice other than `print`, `type`, and `np.sum`.", "_____no_output_____" ] ], [ [ "help(df.apply)", "Help on method apply in module pandas.core.frame:\n\napply(func, axis=0, raw=False, result_type=None, args=(), **kwds) method of pandas.core.frame.DataFrame instance\n Apply a function along an axis of the DataFrame.\n \n Objects passed to the function are Series objects whose index is\n either the DataFrame's index (``axis=0``) or the DataFrame's columns\n (``axis=1``). By default (``result_type=None``), the final return type\n is inferred from the return type of the applied function. Otherwise,\n it depends on the `result_type` argument.\n \n Parameters\n ----------\n func : function\n Function to apply to each column or row.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Axis along which the function is applied:\n \n * 0 or 'index': apply function to each column.\n * 1 or 'columns': apply function to each row.\n \n raw : bool, default False\n Determines if row or column is passed as a Series or ndarray object:\n \n * ``False`` : passes each row or column as a Series to the\n function.\n * ``True`` : the passed function will receive ndarray objects\n instead.\n If you are just applying a NumPy reduction function this will\n achieve much better performance.\n \n result_type : {'expand', 'reduce', 'broadcast', None}, default None\n These only act when ``axis=1`` (columns):\n \n * 'expand' : list-like results will be turned into columns.\n * 'reduce' : returns a Series if possible rather than expanding\n list-like results. This is the opposite of 'expand'.\n * 'broadcast' : results will be broadcast to the original shape\n of the DataFrame, the original index and columns will be\n retained.\n \n The default behaviour (None) depends on the return value of the\n applied function: list-like results will be returned as a Series\n of those. However if the apply function returns a Series these\n are expanded to columns.\n \n .. versionadded:: 0.23.0\n \n args : tuple\n Positional arguments to pass to `func` in addition to the\n array/series.\n **kwds\n Additional keyword arguments to pass as keywords arguments to\n `func`.\n \n Returns\n -------\n Series or DataFrame\n Result of applying ``func`` along the given axis of the\n DataFrame.\n \n See Also\n --------\n DataFrame.applymap: For elementwise operations.\n DataFrame.aggregate: Only perform aggregating type operations.\n DataFrame.transform: Only perform transforming type operations.\n \n Examples\n --------\n >>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])\n >>> df\n A B\n 0 4 9\n 1 4 9\n 2 4 9\n \n Using a numpy universal function (in this case the same as\n ``np.sqrt(df)``):\n \n >>> df.apply(np.sqrt)\n A B\n 0 2.0 3.0\n 1 2.0 3.0\n 2 2.0 3.0\n \n Using a reducing function on either axis\n \n >>> df.apply(np.sum, axis=0)\n A 12\n B 27\n dtype: int64\n \n >>> df.apply(np.sum, axis=1)\n 0 13\n 1 13\n 2 13\n dtype: int64\n \n Returning a list-like will result in a Series\n \n >>> df.apply(lambda x: [1, 2], axis=1)\n 0 [1, 2]\n 1 [1, 2]\n 2 [1, 2]\n dtype: object\n \n Passing ``result_type='expand'`` will expand list-like results\n to columns of a Dataframe\n \n >>> df.apply(lambda x: [1, 2], axis=1, result_type='expand')\n 0 1\n 0 1 2\n 1 1 2\n 2 1 2\n \n Returning a Series inside the function is similar to passing\n ``result_type='expand'``. The resulting column names\n will be the Series index.\n \n >>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)\n foo bar\n 0 1 2\n 1 1 2\n 2 1 2\n \n Passing ``result_type='broadcast'`` will ensure the same shape\n result, whether list-like or scalar is returned by the function,\n and broadcast it along the axis. The resulting column names will\n be the originals.\n \n >>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')\n A B\n 0 1 2\n 1 1 2\n 2 1 2\n\n" ], [ "df.apply(np.sum)", "_____no_output_____" ], [ "iris_df.apply(np.sum)", "_____no_output_____" ] ], [ [ "## Task 4c. Occurances\nIentify the number of occurances for each species (virginica, versicolor, setosa) in the `iris_df` object. *Hint*: the `value_counts` function only works on a `pd.Series` object, not on the full data frame..", "_____no_output_____" ] ], [ [ "pd.value_counts(iris_df['species'])", "_____no_output_____" ] ], [ [ "## Task 5a: String Methods\n\n+ Create a list of five strings that represent dates in the form YYYY-MM-DD (e.g. 2020-02-20 for Feb 20th, 2020).\n+ Add this list of dates as a new column in the `df` dataframe.\n+ Now split the date into 3 new columns with one column representing the year, another the month and another they day.\n+ Combine the values from columns `alpha` and `beta` into a new column where the values are spearated with a colon.\n", "_____no_output_____" ] ], [ [ "list = pd.date_range('20210301', periods=5)\nlist", "_____no_output_____" ], [ "df['date'] = list\ndf", "_____no_output_____" ], [ "df[['year', 'month', 'day']] = df['date'].astype(str).str.split('-',expand=True)\ndf", "_____no_output_____" ], [ "df['combined'] = df['alpha'].astype(str) + ':' + df['beta']\ndf", "_____no_output_____" ] ], [ [ "## Task 6a: Concatenation by Rows\n+ Create the following dataframe\n```Python\ndf1 = pd.DataFrame(\n {'alpha': [0, 1, 2, 3, 4],\n 'beta': ['a', 'b', 'c', 'd', 'e']}, index = ['I1', 'I2' ,'I3', 'I4', 'I5'])\n```\n+ Create a new dataframe named `df2` with column names \"delta\" and \"gamma\" that contins 5 rows with some index names that overlap with the `df1` dataframe and some that do not.\n+ Concatenate the two dataframes by rows and print the result.\n+ You should see the two have combined one after the other, but there should also be missing values added. \n+ Explain why there are missing values.\n", "_____no_output_____" ] ], [ [ "df1 = pd.DataFrame(\n {'alpha': [0, 1, 2, 3, 4],\n 'beta': ['a', 'b', 'c', 'd', 'e']}, index = ['I1', 'I2' ,'I3', 'I4', 'I5'])\ndf1", "_____no_output_____" ], [ "df2 = pd.DataFrame(\n {'delta': [0, 3, 5, 7, 9],\n 'gamma': ['e', 'i', 'a', 's', 'p']}, index = ['I4', 'I5', 'I6', 'I7' ,'I8',])\ndf2", "_____no_output_____" ], [ "df3 = pd.concat([df1, df2], axis = 0)\ndf3 # missing values are there because all the labels are not defined in two data frames", "_____no_output_____" ] ], [ [ "## Task 6b: Concatenation by Columns\n\nUsing the same dataframes, df1 and df2, from Task 6a practice:\n+ Concatenate the two by columns\n+ Add a \"delta\" column to `df1` and concatenate by columns such that there are 5 columns in the merged dataframe.\n+ Respond in writing to this question (add a new 'raw' cell to contain your answer). What will happen if using you had performed an inner join while concatenating? \n+ Try the concatenation with the inner join to see if you are correct.", "_____no_output_____" ] ], [ [ "df4 = pd.concat([df1, df2], axis = 1)\ndf4", "_____no_output_____" ], [ "df1['delta'] = ['0', '3', '5', '7', '9']\ndf1", "_____no_output_____" ], [ "df5 = pd.concat([df1, df2], axis = 1)\ndf5", "_____no_output_____" ], [ "df5 = pd.concat([df1, df2], axis = 1, join = 'inner')\ndf5", "_____no_output_____" ] ], [ [ "#### Task 6c: Concat and append data frames\n<span style=\"float:right; margin-left:10px; clear:both;\">![Task](./media/task-icon.png)</span>\n\n+ Create a new 5x5 dataframe full of random numbers.\n+ Create a new 5x10 dataframe full of 1's.\n+ Append one to the other and print it.\n+ Append a single Series of zeros to the end of the appended dataframe.\n", "_____no_output_____" ] ], [ [ "a = pd.DataFrame(np.random.random([5,5]))\na", "_____no_output_____" ], [ "b = pd.DataFrame(np.ones([5,10]))\nb", "_____no_output_____" ], [ "c = a.append(b, ignore_index = True)\nc", "_____no_output_____" ], [ "d = pd.Series(np.random.random(10))\nd", "_____no_output_____" ], [ "c.append(d, ignore_index = True)", "_____no_output_____" ] ], [ [ "## Task 6d: Grouping\n\nDemonstrate a `groupby`.\n\n+ Create a new column with the label \"region\" in the iris data frame. This column will indicates geographic regions of the US where measurments were taken. Values should include: 'Southeast', 'Northeast', 'Midwest', 'Southwest', 'Northwest'. Use these randomly.\n+ Use `groupby` to get a new data frame of means for each species in each region.\n+ Add a `dev_stage` column by randomly selecting from the values \"early\" and \"late\".\n+ Use `groupby` to get a new data frame of means for each species,in each region and each development stage.\n+ Use the `count` function (just like you used the `mean` function) to identify how many rows in the table belong to each combination of species + region + developmental stage.", "_____no_output_____" ] ], [ [ "iris_df['region'] = np.random.choice(['Southeast', 'Northeast', 'Midwest', 'Southwest', 'Northwest'])\niris_df", "_____no_output_____" ], [ "groups = iris_df.groupby('region')\ngroups.mean()", "_____no_output_____" ], [ "iris_df['region'] = np.random.choice(['Southeast', 'Northeast', 'Midwest', 'Southwest', 'Northwest'])\niris_df", "_____no_output_____" ], [ "groups = iris_df.groupby('region')\ngroups.mean()", "_____no_output_____" ], [ "iris_df['region'] = np.random.choice(['Southeast', 'Northeast', 'Midwest', 'Southwest', 'Northwest'])\niris_df", "_____no_output_____" ], [ "groups = iris_df.groupby('region')\ngroups.mean()", "_____no_output_____" ], [ "iris_df['region'] = np.random.choice(['Southeast', 'Northeast', 'Midwest', 'Southwest', 'Northwest'])\niris_df", "_____no_output_____" ], [ "groups = iris_df.groupby('region')\ngroups.mean()", "_____no_output_____" ], [ "iris_df['region'] = np.random.choice(['Southeast', 'Northeast', 'Midwest', 'Southwest', 'Northwest'])\niris_df", "_____no_output_____" ], [ "groups = iris_df.groupby('region')\ngroups.mean()", "_____no_output_____" ], [ "iris_df['dev_stage'] = np.random.choice(['early', 'late'], iris_df.shape[0])\niris_df.head()", "_____no_output_____" ], [ "groups = iris_df.groupby(['species', 'region', 'dev_stage'])\ngroups.mean()", "_____no_output_____" ], [ "groups.count()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aec30b02c6522b568f32f496f03f00af43927be
45,177
ipynb
Jupyter Notebook
Ch07_AdaBoosting/adaboost.ipynb
jhljx/MachineLearningInAction
782b2ff2213aa79e48c5536738c92cc03c3ab6ca
[ "MIT" ]
null
null
null
Ch07_AdaBoosting/adaboost.ipynb
jhljx/MachineLearningInAction
782b2ff2213aa79e48c5536738c92cc03c3ab6ca
[ "MIT" ]
null
null
null
Ch07_AdaBoosting/adaboost.ipynb
jhljx/MachineLearningInAction
782b2ff2213aa79e48c5536738c92cc03c3ab6ca
[ "MIT" ]
null
null
null
56.330424
19,294
0.781615
[ [ [ "### 基于数据集多重抽样的分类器", "_____no_output_____" ], [ "**元算法(meta-algorithm)** 是对其他算法进行组合的一种方式。Adaboosting算法是最流行的元算法。\n\n将不同的分类器组合起来,这种组合结果被称为**集成方法(ensemble method)** 或者**元算法(meta-algorithm)** 。使用集成方法时会有多种形式:可以是不同算法的集成,也可以是同一算法在不同设置下的集成,还可以是数据集不同部分分配给不同分类器之后的集成。", "_____no_output_____" ], [ "AdaBoost算法的优缺点\n\n- 优点:泛化错误低,易编码,可以应用在大部分分类器上,无参数调整。 \n- 缺点:对离群点敏感。 \n- 适用数据类型:数值型和标称型。", "_____no_output_____" ], [ "#### bagging:基于数据随机重抽样的分类器构建算法", "_____no_output_____" ], [ "**自举汇聚法(bootstrap aggregating)** 也称为bagging方法,是在从原始数据集选择S次后得到S个新数据集的一种技术。新数据集和原数据集的大小相等。每个数据集都是**通过在原始数据集中随机选择一个样本来进行替换**而得到的。这里的替换意味着可以**多次选择同一个样本** 。\n\n这个性质允许新的数据集中**可以有重复的值** 。更先进的bagging方法比如**随机森林(random forest)** 。", "_____no_output_____" ], [ "#### boosting", "_____no_output_____" ], [ "boosting是一种与bagging类似的技术。不管是在boosting还是在bagging中,所使用的多个分类器的类型都是一致的。但boosting不同的分类器是通过**串行训练** 获得的,每个新分类器都根据已训练出的分类器的性能来进行训练。boosting是通过**集中关注被已有分类器错分的那些数据**来获得新的分类器。", "_____no_output_____" ], [ "boosting分类的结果是基于所有分类器的加权求和结果的,因此boosting与bagging不一样。**bagging中分类器的权重是相等的,boosting中分类器的权重并不相等**,每个权重代表的是其对应分类器在上一轮迭代中的成功度。", "_____no_output_____" ], [ "AdaBoosting的一般流程\n\n(1)收集数据:可以使用任意方法。 \n(2)准备数据:依赖于所使用的弱分类器类型,本章使用的是单层决策树,这种分类器可以处理任何数据类型。当然也可以使用任意分类器作为弱分类器,第2章到第6章中的任一分类器都可以充当弱分类器。作为弱分类器,简单分类器的效果更好。 \n(3)分析数据:可以使用任意方法。 \n(4)训练算法:AdaBoost的大部分时间都用在训练上,分类器将多次在同一个数据集上训练弱分类器。 \n(5)测试算法:计算分类器的错误率。 \n(6)使用算法:同SVM一样,AdaBoost预测两个类别中的一个。如果想把它应用到多个类别的场景,那么就要像多类SVM中的做法一样对AdaBoost进行修改。", "_____no_output_____" ], [ "### 训练算法:基于错误提升分类器的性能", "_____no_output_____" ], [ "AdaBoost是adaptive boosting(自适应boosting)的缩写,其运行过程如下:\n\n训练数据中的每个样本,并赋予其一个权重,这些权重构成了向量D。一开始,这些权重都初始化成相等值。首先在训练数据上训练出一个弱分类器并计算该分类的错误率,然后在同一数据集上再次训练弱分类器,在分类器的第二次训练中,将会重新调整每个样本的权重,其中第一次分对的样本的权重将会降低,而第一次分错的样本权重将会提高。\n\n为了从所有弱分类器中得到最终的分类结果,AdaBoost为每个分类器都分配了一个权重值$\\alpha$,这些$\\alpha$值是**基于每个弱分类器的错误率**进行计算的。", "_____no_output_____" ], [ "其中,错误率$\\varepsilon$计算公式为\n$$\\varepsilon = \\frac{未正确分类的样本数目}{所有样本数目}$$\n\n$\\alpha$的计算公式为:\n$$\\alpha = \\frac{1}{2}ln \\left( \\frac{1 - \\varepsilon}{\\varepsilon} \\right)$$\n\n计算出$\\alpha$值之后,可以对权重向量D进行更新,以使得那些**正确分类的样本的权重降低**而**错分样本的权重升高**。\n\n如果某个样本被正确分类,那么该样本的权重更改为:\n$$D_{i}^{(t+1)} = \\frac{D_{i}^{(t)}e^{-\\alpha}}{Sum(D)}$$\n如果某个样本未被正确分类,那么该样本的权重更改为:\n$$D_{i}^{(t+1)} = \\frac{D_{i}^{(t)}e^{\\alpha}}{Sum(D)}$$\n在计算出D之后,AdaBoost又进入下一轮迭代。AdaBoost算法会不断重复训练和调整权重的过程,直到训练错误率为0或者弱分类器的数目达到用户的指定值为止。", "_____no_output_____" ], [ "### 基于单层决策树构建弱分类器", "_____no_output_____" ], [ "本章采用基于单个特征的单层决策树来做决策。由于这棵树只有一次分裂过程,因此只是一个树桩。", "_____no_output_____" ] ], [ [ "%run simpleDataPlot.py", "_____no_output_____" ], [ "import adaboost", "_____no_output_____" ], [ "reload(adaboost)", "_____no_output_____" ], [ "datMat, classLabels = adaboost.loadSimpleData()", "_____no_output_____" ] ], [ [ "构建单层决策树来作为弱分类器的伪代码如下:\n\n将最小错误率minError设置为$+\\infty$ \n对数据集中的每一个特征(第一层循环): \n  对每个步长(第二层循环): \n     对每个不等号(第三层循环): \n       建立一棵单层决策树并利用加权数据集对它进行测试 \n       如果错误率低于minError,则将当前单层决策树设为最佳单层决策树 \n返回最佳单层决策树 ", "_____no_output_____" ] ], [ [ "import numpy as np", "_____no_output_____" ], [ "reload(adaboost)", "_____no_output_____" ], [ "D = np.mat(np.ones((5,1)) / 5)", "_____no_output_____" ], [ "adaboost.buildStump(datMat, classLabels, D)", "_____no_output_____" ], [ "reload(adaboost)", "_____no_output_____" ], [ "classifierArray, aggClassEst = adaboost.adaBoostTrainDS(datMat, classLabels, 9)", "D: [[ 0.2 0.2 0.2 0.2 0.2]]\nclassEst: [[-1. 1. -1. -1. 1.]]\naggClassEst: [[-0.69314718 0.69314718 -0.69314718 -0.69314718 0.69314718]]\ntotal error: 0.2\nD: [[ 0.5 0.125 0.125 0.125 0.125]]\nclassEst: [[ 1. 1. -1. -1. -1.]]\naggClassEst: [[ 0.27980789 1.66610226 -1.66610226 -1.66610226 -0.27980789]]\ntotal error: 0.2\nD: [[ 0.28571429 0.07142857 0.07142857 0.07142857 0.5 ]]\nclassEst: [[ 1. 1. 1. 1. 1.]]\naggClassEst: [[ 1.17568763 2.56198199 -0.77022252 -0.77022252 0.61607184]]\ntotal error: 0.0\n" ] ], [ [ "adaboost算法中的向量D非常重要,一开始这些权重都赋予了相同的值。在后续迭代中,adaboost算法会在增加错分数据的权重的同时,降低正确分类数据的权重。D是一个**概率分布向量** , 因此其所有元素之和为1.0。所以一开始所有元素都被初始化成1/m。", "_____no_output_____" ] ], [ [ "classifierArray", "_____no_output_____" ] ], [ [ "代码中对于D权重向量的更新如下:\n\n expon = multiply(-1*alpha*mat(classLabels).T, classEst)\n D = multiply(D, exp(expon))\n D = D/D.sum()\n\n这段代码表明了数据的classLabel与单层决策树分类的出来的classEst同号时,即为分类正确,得到的指数位置为$-\\alpha$,否则分类错误则为$\\alpha$。\nnumpy.multiply函数是**element-wise product**,表示对应元素相乘。代码中为两个向量的对应元素相乘,这里不是线性代数中的点积。", "_____no_output_____" ], [ "### 测试算法:基于AdaBoost的分类", "_____no_output_____" ] ], [ [ "reload(adaboost)", "_____no_output_____" ], [ "datArr, labelArr = adaboost.loadSimpleData()", "_____no_output_____" ], [ "classifierArr, aggClassEst = adaboost.adaBoostTrainDS(datArr, labelArr, 30)", "D: [[ 0.2 0.2 0.2 0.2 0.2]]\nclassEst: [[-1. 1. -1. -1. 1.]]\naggClassEst: [[-0.69314718 0.69314718 -0.69314718 -0.69314718 0.69314718]]\ntotal error: 0.2\nD: [[ 0.5 0.125 0.125 0.125 0.125]]\nclassEst: [[ 1. 1. -1. -1. -1.]]\naggClassEst: [[ 0.27980789 1.66610226 -1.66610226 -1.66610226 -0.27980789]]\ntotal error: 0.2\nD: [[ 0.28571429 0.07142857 0.07142857 0.07142857 0.5 ]]\nclassEst: [[ 1. 1. 1. 1. 1.]]\naggClassEst: [[ 1.17568763 2.56198199 -0.77022252 -0.77022252 0.61607184]]\ntotal error: 0.0\n" ], [ "classifierArr", "_____no_output_____" ], [ "adaboost.adaClassify([0, 0], classifierArr)", "_____no_output_____" ] ], [ [ "可以发现,随着迭代进行,数据点[0,0]的分类结果越来越强。", "_____no_output_____" ] ], [ [ "adaboost.adaClassify([5, 5], classifierArr)", "_____no_output_____" ], [ "reload(adaboost)", "_____no_output_____" ], [ "datArr, labelArr = adaboost.loadDataSet('horseColicTraining2.txt')", "_____no_output_____" ], [ "classifierArray,aggClassEst = adaboost.adaBoostTrainDS(datArr, labelArr, 10)", "total error: 0.367892976589\ntotal error: 0.367892976589\ntotal error: 0.357859531773\ntotal error: 0.351170568562\ntotal error: 0.351170568562\ntotal error: 0.351170568562\ntotal error: 0.347826086957\ntotal error: 0.351170568562\ntotal error: 0.351170568562\ntotal error: 0.354515050167\n" ], [ "testArr, testLabelArr = adaboost.loadDataSet('horseColicTest2.txt')", "_____no_output_____" ], [ "prediction10 = adaboost.adaClassify(testArr, classifierArray)", "_____no_output_____" ], [ "errArr = np.mat(np.ones((67,1)))", "_____no_output_____" ], [ "errArr[prediction10!=mat(testLabelArr).T].sum()", "_____no_output_____" ], [ "errRate = errArr[prediction10!=mat(testLabelArr).T].sum() / 67", "_____no_output_____" ], [ "errRate", "_____no_output_____" ] ], [ [ "我们可以把弱分类器想成是SVM中的一个核函数,也可以按照最大化某个最小间隔的方式重写AdaBoost算法。", "_____no_output_____" ], [ "### 非均衡分类问题", "_____no_output_____" ], [ "在《机器学习实战》这本书中的算法都是基于**错误率**来衡量分类器任务的成功程度的。错误率是指**在所有测试样例中错分样例的比例** 。\n\n我们经常使用**混淆矩阵(confusion matrix)** 来作为帮助人们更好地了解分类错误的工具。\n\n|||||\n|--|--|--|--|\n|||预测结果||\n|||+1|-1|\n|真实结果|+1|真正例,真阳(TP)|伪反例,假阴(FN)|\n|真实结果|-1|伪正例,假阳(FP)|真反例,真阴(TN)|\n\n$$\\mathbf{正确率(Accuracy)} = \\frac{TP}{TP+FP}$$\n$$\\mathbf{召回率(Recall)} = \\frac{TP}{TP+FN}$$\n\n准确率表示的是预测为正例的样本的真正正例的比例。召回率表示的是预测为正例的样本占所有真实正例的比例。\n\n准确率衡量的可以是预测的癌症病人中有些人不是真的得了癌症,即真的得了癌症的病人比例。召回率是一些真的得了癌症的病人没有预测出来。这个就很可怕了,所以对于癌症预测一般要提高召回率。\n\n另一个用于度量分类中非均衡性的工具是**ROC曲线(ROC curve)** , ROC代表接收者操作特征(receiver operating characteristic)。ROC曲线不仅可以用于比较分类器,也可以基于成本效益(cost-versus-benefit)分析来做出决策。\n\nROC曲线的横坐标为假阳率(即FP/(FP+TN)),纵坐标为真阳率(TP/(TP+FN))。\n\n理想情况下,**最佳的分类器应该尽可能位于左上角**。即在假阳率很低的情况下,真阳率很高。\n\n对于不同的ROC曲线,比较曲线下的面积(Area Unser the Curve, AUC)。AUC给出的是分类器的平均性能值,当然它不能完全代替对整条曲线的观察。完美分类器的AUC为1.0,随机猜测的AUC为0.5。", "_____no_output_____" ] ], [ [ "reload(adaboost)", "_____no_output_____" ], [ "datArr, labelArr = adaboost.loadDataSet('horseColicTraining2.txt')", "_____no_output_____" ], [ "classifierArray, aggClassEst = adaboost.adaBoostTrainDS(datArr, labelArr, 10)", "total error: 0.367892976589\ntotal error: 0.367892976589\ntotal error: 0.357859531773\ntotal error: 0.351170568562\ntotal error: 0.351170568562\ntotal error: 0.351170568562\ntotal error: 0.347826086957\ntotal error: 0.351170568562\ntotal error: 0.351170568562\ntotal error: 0.354515050167\n" ], [ "adaboost.plotROC(aggClassEst.T, labelArr)", "_____no_output_____" ] ], [ [ "还有一些处理非均衡数据的方法,比如**代价敏感学习(cost-sensitive learning)** 。此外,还可以对训练数据进行改造,比如**欠抽样(undersampling)** 或者**过抽样(oversampling)** 来实现。过抽样意味着复制样例,而欠抽样意味着删除样例。", "_____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" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
4aec31b462c8d236b66a847a000bbfd3b140bf8a
83,420
ipynb
Jupyter Notebook
6.2-understanding-recurrent-neural-networks.ipynb
LDJWJ/deep-learning-with-python-notebooks
ebb316012d20858c2e02cf86c45bde3bb28459e5
[ "MIT" ]
null
null
null
6.2-understanding-recurrent-neural-networks.ipynb
LDJWJ/deep-learning-with-python-notebooks
ebb316012d20858c2e02cf86c45bde3bb28459e5
[ "MIT" ]
null
null
null
6.2-understanding-recurrent-neural-networks.ipynb
LDJWJ/deep-learning-with-python-notebooks
ebb316012d20858c2e02cf86c45bde3bb28459e5
[ "MIT" ]
null
null
null
170.593047
18,692
0.878183
[ [ [ "import keras\nkeras.__version__", "Using TensorFlow backend.\n" ] ], [ [ "# Understanding recurrent neural networks\n\n이 노트북은 [케라스 창시자에게 배우는 딥러닝](https://tensorflow.blog/케라스-창시자에게-배우는-딥러닝/) 책의 6장 2절의 코드 예제입니다. 책에는 더 많은 내용과 그림이 있습니다. 이 노트북에는 소스 코드에 관련된 설명만 포함합니다. 이 노트북의 설명은 케라스 버전 2.2.2에 맞추어져 있습니다. 케라스 최신 버전이 릴리스되면 노트북을 다시 테스트하기 때문에 설명과 코드의 결과가 조금 다를 수 있습니다.\n\n---\n\n[...]\n\n## 케라스의 순환 층\n\n\n넘파이로 간단하게 구현한 과정이 실제 케라스의 `SimpleRNN` 층에 해당합니다:", "_____no_output_____" ] ], [ [ "from keras.layers import SimpleRNN", "_____no_output_____" ] ], [ [ "`SimpleRNN`이 한 가지 다른 점은 넘파이 예제처럼 하나의 시퀀스가 아니라 다른 케라스 층과 마찬가지로 시퀀스 배치를 처리한다는 것입니다. 즉, `(timesteps, input_features)` 크기가 아니라 `(batch_size, timesteps, input_features)` 크기의 입력을 받습니다.\n\n케라스에 있는 모든 순환 층과 동일하게 `SimpleRNN`은 두 가지 모드로 실행할 수 있습니다. 각 타임스텝의 출력을 모은 전체 시퀀스를 반환하거나(크기가 `(batch_size, timesteps, output_features)`인 3D 텐서), 입력 시퀀스에 대한 마지막 출력만 반환할 수 있습니다(크기가 `(batch_size, output_features)`인 2D 텐서). 이 모드는 객체를 생성할 때 `return_sequences` 매개변수로 선택할 수 있습니다. 예제를 살펴보죠:", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras.layers import Embedding, SimpleRNN\n\nmodel = Sequential()\nmodel.add(Embedding(10000, 32))\nmodel.add(SimpleRNN(32))\nmodel.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_1 (Embedding) (None, None, 32) 320000 \n_________________________________________________________________\nsimple_rnn_1 (SimpleRNN) (None, 32) 2080 \n=================================================================\nTotal params: 322,080\nTrainable params: 322,080\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model = Sequential()\nmodel.add(Embedding(10000, 32))\nmodel.add(SimpleRNN(32, return_sequences=True))\nmodel.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_2 (Embedding) (None, None, 32) 320000 \n_________________________________________________________________\nsimple_rnn_2 (SimpleRNN) (None, None, 32) 2080 \n=================================================================\nTotal params: 322,080\nTrainable params: 322,080\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "네트워크의 표현력을 증가시키기 위해 여러 개의 순환 층을 차례대로 쌓는 것이 유용할 때가 있습니다. 이런 설정에서는 중간 층들이 전체 출력 시퀀스를 반환하도록 설정해야 합니다:", "_____no_output_____" ] ], [ [ "model = Sequential()\nmodel.add(Embedding(10000, 32))\nmodel.add(SimpleRNN(32, return_sequences=True))\nmodel.add(SimpleRNN(32, return_sequences=True))\nmodel.add(SimpleRNN(32, return_sequences=True))\nmodel.add(SimpleRNN(32)) # 맨 위 층만 마지막 출력을 반환합니다.\nmodel.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_3 (Embedding) (None, None, 32) 320000 \n_________________________________________________________________\nsimple_rnn_3 (SimpleRNN) (None, None, 32) 2080 \n_________________________________________________________________\nsimple_rnn_4 (SimpleRNN) (None, None, 32) 2080 \n_________________________________________________________________\nsimple_rnn_5 (SimpleRNN) (None, None, 32) 2080 \n_________________________________________________________________\nsimple_rnn_6 (SimpleRNN) (None, 32) 2080 \n=================================================================\nTotal params: 328,320\nTrainable params: 328,320\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "이제 IMDB 영화 리뷰 분류 문제에 적용해 보죠. 먼저 데이터를 전처리합니다:", "_____no_output_____" ] ], [ [ "from keras.datasets import imdb\nfrom keras.preprocessing import sequence\n\nmax_features = 10000 # 특성으로 사용할 단어의 수\nmaxlen = 500 # 사용할 텍스트의 길이(가장 빈번한 max_features 개의 단어만 사용합니다)\nbatch_size = 32\n\nprint('데이터 로딩...')\n(input_train, y_train), (input_test, y_test) = imdb.load_data(num_words=max_features)\nprint(len(input_train), '훈련 시퀀스')\nprint(len(input_test), '테스트 시퀀스')\n\nprint('시퀀스 패딩 (samples x time)')\ninput_train = sequence.pad_sequences(input_train, maxlen=maxlen)\ninput_test = sequence.pad_sequences(input_test, maxlen=maxlen)\nprint('input_train 크기:', input_train.shape)\nprint('input_test 크기:', input_test.shape)", "데이터 로딩...\n25000 훈련 시퀀스\n25000 테스트 시퀀스\n시퀀스 패딩 (samples x time)\ninput_train 크기: (25000, 500)\ninput_test 크기: (25000, 500)\n" ] ], [ [ "`Embedding` 층과 `SimpleRNN` 층을 사용해 간단한 순환 네트워크를 훈련시켜 보겠습니다:", "_____no_output_____" ] ], [ [ "from keras.layers import Dense\n\nmodel = Sequential()\nmodel.add(Embedding(max_features, 32))\nmodel.add(SimpleRNN(32))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])\nhistory = model.fit(input_train, y_train,\n epochs=10,\n batch_size=128,\n validation_split=0.2)", "Train on 20000 samples, validate on 5000 samples\nEpoch 1/10\n20000/20000 [==============================] - 16s 782us/step - loss: 0.6448 - acc: 0.6115 - val_loss: 0.6156 - val_acc: 0.6736\nEpoch 2/10\n20000/20000 [==============================] - 15s 747us/step - loss: 0.4175 - acc: 0.8193 - val_loss: 0.3661 - val_acc: 0.8476\nEpoch 3/10\n20000/20000 [==============================] - 15s 745us/step - loss: 0.3060 - acc: 0.8759 - val_loss: 0.4140 - val_acc: 0.8112\nEpoch 4/10\n20000/20000 [==============================] - 15s 746us/step - loss: 0.2431 - acc: 0.9046 - val_loss: 0.3548 - val_acc: 0.8496\nEpoch 5/10\n20000/20000 [==============================] - 15s 746us/step - loss: 0.1911 - acc: 0.9294 - val_loss: 0.3922 - val_acc: 0.8422\nEpoch 6/10\n20000/20000 [==============================] - 15s 748us/step - loss: 0.1410 - acc: 0.9494 - val_loss: 0.3733 - val_acc: 0.8578\nEpoch 7/10\n20000/20000 [==============================] - 15s 746us/step - loss: 0.0995 - acc: 0.9662 - val_loss: 0.4511 - val_acc: 0.8466\nEpoch 8/10\n20000/20000 [==============================] - 15s 746us/step - loss: 0.0647 - acc: 0.9796 - val_loss: 0.4689 - val_acc: 0.8410\nEpoch 9/10\n20000/20000 [==============================] - 15s 746us/step - loss: 0.0402 - acc: 0.9882 - val_loss: 0.5292 - val_acc: 0.8382\nEpoch 10/10\n20000/20000 [==============================] - 15s 747us/step - loss: 0.0247 - acc: 0.9930 - val_loss: 0.5893 - val_acc: 0.8314\n" ] ], [ [ "이제 훈련과 검증의 손실과 정확도를 그래프로 그립니다:", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "acc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()", "_____no_output_____" ] ], [ [ "3장에서 이 데이터셋을 사용한 첫 번째 모델에서 얻은 테스트 정확도는 87%였습니다. 안타깝지만 간단한 순환 네트워크는 이 기준 모델보다 성능이 높지 않습니다(85% 정도의 검증 정확도를 얻었습니다). 이런 원인은 전체 시퀀스가 아니라 처음 500개의 단어만 입력에 사용했기 때문입니다. 이 RNN은 기준 모델보다 얻은 정보가 적습니다. 다른 이유는 `SimpleRNN`이 텍스트와 같이 긴 시퀀스를 처리하는데 적합하지 않기 때문입니다. 더 잘 작동하는 다른 순환 층이 있습니다. 조금 더 고급 순환 층을 살펴보죠.", "_____no_output_____" ], [ "[...]\n\n## 케라스를 사용한 LSTM 예제\n\n이제 실제적인 관심사로 이동해 보죠. LSTM 층으로 모델을 구성하고 IMDB 데이터에서 훈련해 보겠습니다(그림 6-16과 6-17 참조). 이 네트워크는 조금 전 `SimpleRNN`을 사용했던 모델과 비슷합니다. LSTM 층은 출력 차원만 지정하고 다른 (많은) 매개변수는 케라스의 기본값으로 남겨 두었습니다. 케라스는 좋은 기본값을 가지고 있어서 직접 매개변수를 튜닝하는 데 시간을 쓰지 않고도 거의 항상 어느정도 작동하는 모델을 얻을 수 있습니다.", "_____no_output_____" ] ], [ [ "from keras.layers import LSTM\n\nmodel = Sequential()\nmodel.add(Embedding(max_features, 32))\nmodel.add(LSTM(32))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['acc'])\nhistory = model.fit(input_train, y_train,\n epochs=10,\n batch_size=128,\n validation_split=0.2)", "Train on 20000 samples, validate on 5000 samples\nEpoch 1/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.5098 - acc: 0.7607 - val_loss: 0.3865 - val_acc: 0.8426\nEpoch 2/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.2890 - acc: 0.8881 - val_loss: 0.3126 - val_acc: 0.8628\nEpoch 3/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.2334 - acc: 0.9099 - val_loss: 0.3473 - val_acc: 0.8748\nEpoch 4/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.1988 - acc: 0.9259 - val_loss: 0.5105 - val_acc: 0.8396\nEpoch 5/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.1791 - acc: 0.9357 - val_loss: 0.3094 - val_acc: 0.8860\nEpoch 6/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.1538 - acc: 0.9442 - val_loss: 0.3092 - val_acc: 0.8884\nEpoch 7/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.1429 - acc: 0.9492 - val_loss: 0.4297 - val_acc: 0.8772\nEpoch 8/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.1313 - acc: 0.9534 - val_loss: 0.3242 - val_acc: 0.8802\nEpoch 9/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.1174 - acc: 0.9594 - val_loss: 0.3437 - val_acc: 0.8886\nEpoch 10/10\n20000/20000 [==============================] - 72s 4ms/step - loss: 0.1116 - acc: 0.9607 - val_loss: 0.3777 - val_acc: 0.8830\n" ], [ "acc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
4aec3740f37f4a4164a28b2fc3a5920ca42fb85c
206,550
ipynb
Jupyter Notebook
gan_mnist/Intro_to_GANs_Solution.ipynb
Fadi-Almachraki/deep-learning
6bd93a416f65d1524cae23ba941b7a2bc9b0f771
[ "MIT" ]
null
null
null
gan_mnist/Intro_to_GANs_Solution.ipynb
Fadi-Almachraki/deep-learning
6bd93a416f65d1524cae23ba941b7a2bc9b0f771
[ "MIT" ]
null
null
null
gan_mnist/Intro_to_GANs_Solution.ipynb
Fadi-Almachraki/deep-learning
6bd93a416f65d1524cae23ba941b7a2bc9b0f771
[ "MIT" ]
null
null
null
353.076923
89,194
0.915662
[ [ [ "# Generative Adversarial Network\n\nIn this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten digits!\n\nGANs were [first reported on](https://arxiv.org/abs/1406.2661) in 2014 from Ian Goodfellow and others in Yoshua Bengio's lab. Since then, GANs have exploded in popularity. Here are a few examples to check out:\n\n* [Pix2Pix](https://affinelayer.com/pixsrv/) \n* [CycleGAN](https://github.com/junyanz/CycleGAN)\n* [A whole list](https://github.com/wiseodd/generative-models)\n\nThe idea behind GANs is that you have two networks, a generator $G$ and a discriminator $D$, competing against each other. The generator makes fake data to pass to the discriminator. The discriminator also sees real data and predicts if the data it's received is real or fake. The generator is trained to fool the discriminator, it wants to output data that looks _as close as possible_ to real data. And the discriminator is trained to figure out which data is real and which is fake. What ends up happening is that the generator learns to make data that is indistiguishable from real data to the discriminator.\n\n![GAN diagram](assets/gan_diagram.png)\n\nThe general structure of a GAN is shown in the diagram above, using MNIST images as data. The latent sample is a random vector the generator uses to contruct it's fake images. As the generator learns through training, it figures out how to map these random vectors to recognizable images that can foold the discriminator.\n\nThe output of the discriminator is a sigmoid function, where 0 indicates a fake image and 1 indicates an real image. If you're interested only in generating new images, you can throw out the discriminator after training. Now, let's see how we build this thing in TensorFlow.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nimport pickle as pkl\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data')", "Extracting MNIST_data/train-images-idx3-ubyte.gz\nExtracting MNIST_data/train-labels-idx1-ubyte.gz\nExtracting MNIST_data/t10k-images-idx3-ubyte.gz\nExtracting MNIST_data/t10k-labels-idx1-ubyte.gz\n" ] ], [ [ "## Model Inputs\n\nFirst we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input `inputs_real` and the generator input `inputs_z`. We'll assign them the appropriate sizes for each of the networks.", "_____no_output_____" ] ], [ [ "def model_inputs(real_dim, z_dim):\n inputs_real = tf.placeholder(tf.float32, (None, real_dim), name='input_real') \n inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')\n \n return inputs_real, inputs_z", "_____no_output_____" ] ], [ [ "## Generator network\n\n![GAN Network](assets/gan_network.png)\n\nHere we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values.\n\n#### Variable Scope\nHere we need to use `tf.variable_scope` for two reasons. Firstly, we're going to make sure all the variable names start with `generator`. Similarly, we'll prepend `discriminator` to the discriminator variables. This will help out later when we're training the separate networks.\n\nWe could just use `tf.name_scope` to set the names, but we also want to reuse these networks with different inputs. For the generator, we're going to train it, but also _sample from it_ as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the `reuse` keyword for `tf.variable_scope` to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again.\n\nTo use `tf.variable_scope`, you use a `with` statement:\n```python\nwith tf.variable_scope('scope_name', reuse=False):\n # code here\n```\n\nHere's more from [the TensorFlow documentation](https://www.tensorflow.org/programmers_guide/variable_scope#the_problem) to get another look at using `tf.variable_scope`.\n\n#### Leaky ReLU\nTensorFlow doesn't provide an operation for leaky ReLUs, so we'll need to make one . For this you can use take the outputs from a linear fully connected layer and pass them to `tf.maximum`. Typically, a parameter `alpha` sets the magnitude of the output for negative values. So, the output for negative input (`x`) values is `alpha*x`, and the output for positive `x` is `x`:\n$$\nf(x) = max(\\alpha * x, x)\n$$\n\n#### Tanh Output\nThe generator has been found to perform the best with $tanh$ for the generator output. This means that we'll have to rescale the MNIST images to be between -1 and 1, instead of 0 and 1.", "_____no_output_____" ] ], [ [ "def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01):\n with tf.variable_scope('generator', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(z, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum(alpha * h1, h1)\n \n # Logits and tanh output\n logits = tf.layers.dense(h1, out_dim, activation=None)\n out = tf.tanh(logits)\n \n return out", "_____no_output_____" ] ], [ [ "## Discriminator\n\nThe discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer.", "_____no_output_____" ] ], [ [ "def discriminator(x, n_units=128, reuse=False, alpha=0.01):\n with tf.variable_scope('discriminator', reuse=reuse):\n # Hidden layer\n h1 = tf.layers.dense(x, n_units, activation=None)\n # Leaky ReLU\n h1 = tf.maximum(alpha * h1, h1)\n \n logits = tf.layers.dense(h1, 1, activation=None)\n out = tf.sigmoid(logits)\n \n return out, logits", "_____no_output_____" ] ], [ [ "## Hyperparameters", "_____no_output_____" ] ], [ [ "# Size of input image to discriminator\ninput_size = 784\n# Size of latent vector to generator\nz_size = 100\n# Sizes of hidden layers in generator and discriminator\ng_hidden_size = 128\nd_hidden_size = 128\n# Leak factor for leaky ReLU\nalpha = 0.01\n# Smoothing \nsmooth = 0.1", "_____no_output_____" ] ], [ [ "## Build network\n\nNow we're building the network from the functions defined above.\n\nFirst is to get our inputs, `input_real, input_z` from `model_inputs` using the sizes of the input and z.\n\nThen, we'll create the generator, `generator(input_z, input_size)`. This builds the generator with the appropriate input and output sizes.\n\nThen the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as `g_model`. So the real data discriminator is `discriminator(input_real)` while the fake discriminator is `discriminator(g_model, reuse=True)`.", "_____no_output_____" ] ], [ [ "tf.reset_default_graph()\n# Create our input placeholders\ninput_real, input_z = model_inputs(input_size, z_size)\n\n# Build the model\ng_model = generator(input_z, input_size, n_units=g_hidden_size, alpha=alpha)\n# g_model is the generator output\n\nd_model_real, d_logits_real = discriminator(input_real, n_units=d_hidden_size, alpha=alpha)\nd_model_fake, d_logits_fake = discriminator(g_model, reuse=True, n_units=d_hidden_size, alpha=alpha)", "_____no_output_____" ] ], [ [ "## Discriminator and Generator Losses\n\nNow we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, `d_loss = d_loss_real + d_loss_fake`. The losses will by sigmoid cross-entropys, which we can get with `tf.nn.sigmoid_cross_entropy_with_logits`. We'll also wrap that in `tf.reduce_mean` to get the mean for all the images in the batch. So the losses will look something like \n\n```python\ntf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))\n```\n\nFor the real image logits, we'll use `d_logits_real` which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example, using the parameter `smooth`. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like `labels = tf.ones_like(tensor) * (1 - smooth)`\n\nThe discriminator loss for the fake data is similar. The logits are `d_logits_fake`, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.\n\nFinally, the generator losses are using `d_logits_fake`, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images.", "_____no_output_____" ] ], [ [ "# Calculate losses\nd_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, \n labels=tf.ones_like(d_logits_real) * (1 - smooth)))\nd_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, \n labels=tf.zeros_like(d_logits_real)))\nd_loss = d_loss_real + d_loss_fake\n\ng_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake,\n labels=tf.ones_like(d_logits_fake)))", "_____no_output_____" ] ], [ [ "## Optimizers\n\nWe want to update the generator and discriminator variables separately. So we need to get the variables for each part build optimizers for the two parts. To get all the trainable variables, we use `tf.trainable_variables()`. This creates a list of all the variables we've defined in our graph.\n\nFor the generator optimizer, we only want to generator variables. Our past selves were nice and used a variable scope to start all of our generator variable names with `generator`. So, we just need to iterate through the list from `tf.trainable_variables()` and keep variables to start with `generator`. Each variable object has an attribute `name` which holds the name of the variable as a string (`var.name == 'weights_0'` for instance). \n\nWe can do something similar with the discriminator. All the variables in the discriminator start with `discriminator`.\n\nThen, in the optimizer we pass the variable lists to `var_list` in the `minimize` method. This tells the optimizer to only update the listed variables. Something like `tf.train.AdamOptimizer().minimize(loss, var_list=var_list)` will only train the variables in `var_list`.", "_____no_output_____" ] ], [ [ "# Optimizers\nlearning_rate = 0.002\n\n# Get the trainable_variables, split into G and D parts\nt_vars = tf.trainable_variables()\ng_vars = [var for var in t_vars if var.name.startswith('generator')]\nd_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n\nd_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars)\ng_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars)", "_____no_output_____" ] ], [ [ "## Training", "_____no_output_____" ] ], [ [ "batch_size = 100\nepochs = 100\nsamples = []\nlosses = []\n# Only save generator variables\nsaver = tf.train.Saver(var_list=g_vars)\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for e in range(epochs):\n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n \n # Get images, reshape and rescale to pass to D\n batch_images = batch[0].reshape((batch_size, 784))\n batch_images = batch_images*2 - 1\n \n # Sample random noise for G\n batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size))\n \n # Run optimizers\n _ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z})\n _ = sess.run(g_train_opt, feed_dict={input_z: batch_z})\n \n # At the end of each epoch, get the losses and print them out\n train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images})\n train_loss_g = g_loss.eval({input_z: batch_z})\n \n print(\"Epoch {}/{}...\".format(e+1, epochs),\n \"Discriminator Loss: {:.4f}...\".format(train_loss_d),\n \"Generator Loss: {:.4f}\".format(train_loss_g)) \n # Save losses to view after training\n losses.append((train_loss_d, train_loss_g))\n \n # Sample from generator as we're training for viewing afterwards\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, n_units=g_hidden_size, reuse=True, alpha=alpha),\n feed_dict={input_z: sample_z})\n samples.append(gen_samples)\n saver.save(sess, './checkpoints/generator.ckpt')\n\n# Save training generator samples\nwith open('train_samples.pkl', 'wb') as f:\n pkl.dump(samples, f)", "_____no_output_____" ] ], [ [ "## Training loss\n\nHere we'll check out the training losses for the generator and discriminator.", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots()\nlosses = np.array(losses)\nplt.plot(losses.T[0], label='Discriminator')\nplt.plot(losses.T[1], label='Generator')\nplt.title(\"Training Losses\")\nplt.legend()", "_____no_output_____" ] ], [ [ "## Generator samples from training\n\nHere we can view samples of images from the generator. First we'll look at images taken while training.", "_____no_output_____" ] ], [ [ "def view_samples(epoch, samples):\n fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True)\n for ax, img in zip(axes.flatten(), samples[epoch]):\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n im = ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n \n return fig, axes", "_____no_output_____" ], [ "# Load samples from generator taken while training\nwith open('train_samples.pkl', 'rb') as f:\n samples = pkl.load(f)", "_____no_output_____" ] ], [ [ "These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 1, 7, 3, 2. Since this is just a sample, it isn't representative of the full range of images this generator can make.", "_____no_output_____" ] ], [ [ "_ = view_samples(-1, samples)", "_____no_output_____" ] ], [ [ "Below I'm showing the generated images as the network was training, every 10 epochs. With bonus optical illusion!", "_____no_output_____" ] ], [ [ "rows, cols = 10, 6\nfig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True)\n\nfor sample, ax_row in zip(samples[::int(len(samples)/rows)], axes):\n for img, ax in zip(sample[::int(len(sample)/cols)], ax_row):\n ax.imshow(img.reshape((28,28)), cmap='Greys_r')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)", "_____no_output_____" ] ], [ [ "It starts out as all noise. Then it learns to make only the center white and the rest black. You can start to see some number like structures appear out of the noise like 1s and 9s.", "_____no_output_____" ], [ "## Sampling from the generator\n\nWe can also get completely new images from the generator by using the checkpoint we saved after training. We just need to pass in a new latent vector $z$ and we'll get new samples!", "_____no_output_____" ] ], [ [ "saver = tf.train.Saver(var_list=g_vars)\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n sample_z = np.random.uniform(-1, 1, size=(16, z_size))\n gen_samples = sess.run(\n generator(input_z, input_size, n_units=g_hidden_size, reuse=True, alpha=alpha),\n feed_dict={input_z: sample_z})\n_ = view_samples(0, [gen_samples])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4aec3c36a103a7ae6e951b2446452661f13653d0
7,784
ipynb
Jupyter Notebook
Neural Network.ipynb
vn32/Deep-Learning
f110c139192a937a806082f3dde7b94e0dfbdb81
[ "Apache-2.0" ]
1
2019-09-14T16:52:04.000Z
2019-09-14T16:52:04.000Z
Neural Network.ipynb
vn32/Deep-Learning
f110c139192a937a806082f3dde7b94e0dfbdb81
[ "Apache-2.0" ]
null
null
null
Neural Network.ipynb
vn32/Deep-Learning
f110c139192a937a806082f3dde7b94e0dfbdb81
[ "Apache-2.0" ]
null
null
null
31.771429
152
0.487153
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n%matplotlib inline", "_____no_output_____" ], [ "class NNModel:\n \n def __init__(self,learning_rate, n_iter, args):\n self.learning_rate = learning_rate\n self.args = args\n self.n_iter = n_iter\n \n def z_score(self,w,x,b):\n return np.dot(w,x)+b\n \n def init_params(self,n_x):\n parameters={}\n n_a = n_x\n for i in range(1,len(self.args)+1):\n n_h = self.args[i-1][0]\n parameters['w'+str(i)] = np.random.rand(n_h,n_a)*np.sqrt(1/n_x)\n parameters['b'+str(i)] = np.random.randn(n_h,1)\n n_a = n_h\n return parameters\n \n def activation(self,z,fn = 'linear'):\n act_fn ={'linear':z,\n 'relu':np.maximum(z,0),\n 'tanh':np.tanh(z),\n 'sigmoid':1/(1+np.exp(-z)),\n 'softmax':np.exp(z)/np.sum(np.exp(z))}\n return act_fn[fn]\n \n def forward_prop(self,x, parameters):\n L = len(args)\n z_scores = {}\n activations = {'a0':x}\n for i in range(1,L+1):\n z_scores['z'+str(i)] = self.z_score(parameters['w'+str(i)],activations['a'+str(i-1)],parameters['b'+str(i)])\n z = z_scores['z'+str(i)]\n activations['a'+str(i)] = self.activation(z,fn=self.args[i-1][1])\n \n return z_scores, activations\n \n def compute_cost(self,y,y_hat):\n m = y.shape[0]\n cost = (-1/m)*(np.dot(y, np.log(y_hat.T+0.0000001)) + np.dot(1-y, np.log(1-y_hat.T+0.0000001)))\n return np.squeeze(cost)\n \n def backprop(self,y, parameters, z_scores, activations):\n gradients = {}\n L = len(self.args)\n m = y.shape[0]\n for i in range(L,0,-1):\n if i==L:\n gradients['dz'+str(i)]=activations['a'+str(i)]-y\n else:\n gradients['dz'+str(i)] = np.multiply(np.dot(parameters['w'+str(i+1)].T, gradients['dz'+str(i+1)]), 1*(z_scores['z'+str(i)]>=0))\n dz = gradients['dz'+str(i)]\n gradients['dw'+str(i)] = (1/m)*np.matmul(dz,activations['a'+str(i-1)].T)\n gradients['db'+str(i)] = (1/m)*np.sum(dz,axis=1,keepdims=True)\n return gradients\n \n def update_params(self,parameters, gradients):\n eta = self.learning_rate\n for i in range(1,len(parameters)//2+1):\n parameters['w'+str(i)]-=eta*gradients['dw'+str(i)]\n parameters['b'+str(i)]-=eta*gradients['db'+str(i)]\n return parameters\n \n def fit(self,x,y):\n np.random.seed(5)\n params = self.init_params(x.shape[0])\n for i in range(self.n_iter):\n z_scores,activations = self.forward_prop(x,params)\n y_hat = activations['a'+str(len(self.args))]\n #print(y_hat)\n cost = self.compute_cost(y,y_hat)\n gradients = self.backprop(y,params,z_scores,activations)\n params = self.update_params(params,gradients)\n if i%1000==0:\n print('Iteration : {} Cost : {}'.format(i,cost))\n return params\n \n def predict(self,x_test,params):\n z_scores, activations = self.forward_prop(x_test,params)\n y_pred = 1*(activations['a'+str(len(params)//2)]>0.5)\n return np.squeeze(y_pred)", "_____no_output_____" ], [ "path = '/home/mrityunjay/Downloads/sonar.csv'\ndf = pd.read_csv(path)\ndf.columns=['x'+str(i) for i in range(len(df.columns))]\nX=df.drop(['x60'],axis=1)\nY=df['x60']\nX_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.25,random_state=1)\n\nX_train = np.transpose(X_train.values)\nX_test = np.transpose(X_test.values)\n\nY_train = 1*(Y_train.values=='R')\nY_test = 1*(Y_test.values=='R')\nY_train = Y_train.reshape(1,Y_train.shape[0])\nY_test = Y_test.reshape(1,Y_test.shape[0])", "_____no_output_____" ], [ "args=[(100,'relu'),(50,'relu'),(10,'relu'),(5,'relu'),(3,'relu'),(1,'sigmoid')]\nnn = NNModel(learning_rate=0.001, n_iter = 10000, args=args)\nparams = nn.fit(X_train,Y_train)", "Iteration : 0 Cost : 110.57895885689418\nIteration : 1000 Cost : 97.20215085637494\nIteration : 2000 Cost : 24.107818263784335\nIteration : 3000 Cost : 0.059483096239265856\nIteration : 4000 Cost : 0.01442973769956715\nIteration : 5000 Cost : 0.007538193128651977\nIteration : 6000 Cost : 0.004934892738423426\nIteration : 7000 Cost : 0.00361163395157489\nIteration : 8000 Cost : 0.002820134439769308\nIteration : 9000 Cost : 0.0022975636960569958\n" ], [ "Y_pred = nn.predict(X_test,params)\nprint(Y_pred)", "[0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 0 1 0 1 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 1 1 1\n 1 1 0 0 0 1 1 1 0 1 1 0 0 0 0]\n" ], [ "print(Y_test)", "[[0 0 0 0 1 1 0 1 0 1 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0 0 1 1 1 0 0 0 1 1 1 1\n 1 1 1 0 0 0 1 0 0 0 1 1 0 0 0 0]]\n" ], [ "acc = accuracy_score(Y_pred,np.squeeze(Y_test))\nprint(acc)", "0.8461538461538461\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4aec615a5fa60afc877c4d9cb54f0ac23d3789cc
94,317
ipynb
Jupyter Notebook
ETL Pipeline Preparation.ipynb
pulkitjaiswal/Disaster-Response
da638385121fecf73ea7505e4b02d3975414be3b
[ "MIT" ]
null
null
null
ETL Pipeline Preparation.ipynb
pulkitjaiswal/Disaster-Response
da638385121fecf73ea7505e4b02d3975414be3b
[ "MIT" ]
null
null
null
ETL Pipeline Preparation.ipynb
pulkitjaiswal/Disaster-Response
da638385121fecf73ea7505e4b02d3975414be3b
[ "MIT" ]
null
null
null
39.998728
1,504
0.386017
[ [ [ "# ETL Pipeline Preparation\nFollow the instructions below to help you create your ETL pipeline.\n### 1. Import libraries and load datasets.\n- Import Python libraries\n- Load `messages.csv` into a dataframe and inspect the first few lines.\n- Load `categories.csv` into a dataframe and inspect the first few lines.", "_____no_output_____" ] ], [ [ "# import necessary libraries\nimport pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "# load messages into dataframe\nmessages = pd.read_csv(\"messages.csv\")\nmessages.head()", "_____no_output_____" ], [ "categories = pd.read_csv(\"categories.csv\")\ncategories.head()", "_____no_output_____" ] ], [ [ "### 2. Merge datasets.\n- Merge the messages and categories datasets using the common id\n- Assign this combined dataset to `df`, which will be cleaned in the following steps", "_____no_output_____" ] ], [ [ "# merge datasets\ndf = messages.merge(categories, on='id')\ndf.head()", "_____no_output_____" ] ], [ [ "### 3. Split `categories` into separate category columns.\n- Split the values in the `categories` column on the `;` character so that each value becomes a separate column. You'll find [this method](https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Series.str.split.html) very helpful! Make sure to set `expand=True`.\n- Use the first row of categories dataframe to create column names for the categories data.\n- Rename columns of `categories` with new column names.", "_____no_output_____" ] ], [ [ "# create a dataframe of the 36 individual category columns\ncategories = df['categories'].str.split(\";\", expand=True)\ncategories.head()", "_____no_output_____" ], [ "# select the first row of the categories dataframe\nrow = categories.loc[0,:]\n\n# use this row to extract a list of new column names for categories.\n# one way is to apply a lambda function that takes everything \n# up to the second to last character of each string with slicing\ncategory_colnames = row.apply(lambda x:x.split('-')[0]).values.tolist()\nprint(category_colnames)", "['related', 'request', 'offer', 'aid_related', 'medical_help', 'medical_products', 'search_and_rescue', 'security', 'military', 'child_alone', 'water', 'food', 'shelter', 'clothing', 'money', 'missing_people', 'refugees', 'death', 'other_aid', 'infrastructure_related', 'transport', 'buildings', 'electricity', 'tools', 'hospitals', 'shops', 'aid_centers', 'other_infrastructure', 'weather_related', 'floods', 'storm', 'fire', 'earthquake', 'cold', 'other_weather', 'direct_report']\n" ], [ "# rename the columns of `categories`\ncategories.columns = category_colnames\ncategories.head()", "_____no_output_____" ] ], [ [ "### 4. Convert category values to just numbers 0 or 1.\n- Iterate through the category columns in df to keep only the last character of each string (the 1 or 0). For example, `related-0` becomes `0`, `related-1` becomes `1`. Convert the string to a numeric value.\n- You can perform [normal string actions on Pandas Series](https://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str), like indexing, by including `.str` after the Series. You may need to first convert the Series to be of type string, which you can do with `astype(str)`.", "_____no_output_____" ] ], [ [ "for column in categories:\n # set each value to be the last character of the string\n categories[column] = categories[column].apply(lambda x:x.split('-')[1])\n \n # convert column from string to numeric\n categories[column] = categories[column].astype(int)\ncategories.head()", "_____no_output_____" ], [ "# Check non one-hot ecoding columns\ncolumns=(categories.max()>1)[categories.max()>1].index\n# Check number not in (0,1) and update other value to 1\nfor col in columns:\n print(categories[col].value_counts())\n categories.loc[categories[col]>1,col] = 1\n print(categories[col].value_counts())", "1 20042\n0 6140\n2 204\nName: related, dtype: int64\n1 20246\n0 6140\nName: related, dtype: int64\n" ] ], [ [ "### 5. Replace `categories` column in `df` with new category columns.\n- Drop the categories column from the df dataframe since it is no longer needed.\n- Concatenate df and categories data frames.", "_____no_output_____" ] ], [ [ "# drop the original categories column from `df`\ndf.drop('categories',axis=1, inplace=True)\n\ndf.head()", "_____no_output_____" ], [ "# concatenate the original dataframe with the new `categories` dataframe\ndf = pd.concat([df,categories], axis=1)\ndf.head()", "_____no_output_____" ] ], [ [ "### 6. Remove duplicates.\n- Check how many duplicates are in this dataset.\n- Drop the duplicates.\n- Confirm duplicates were removed.", "_____no_output_____" ] ], [ [ "# check number of duplicates\ndf.duplicated().sum()\n", "_____no_output_____" ], [ "# drop duplicates\ndf.drop_duplicates(inplace=True)\n", "_____no_output_____" ], [ "# check number of duplicates\ndf.duplicated().sum()", "_____no_output_____" ] ], [ [ "### 7. Save the clean dataset into an sqlite database.\nYou can do this with pandas [`to_sql` method](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html) combined with the SQLAlchemy library. Remember to import SQLAlchemy's `create_engine` in the first cell of this notebook to use it below.", "_____no_output_____" ] ], [ [ "from sqlalchemy import create_engine\nengine = create_engine('sqlite:///all_messages.db')\ndf.to_sql('all_messages', engine, index=False)", "_____no_output_____" ] ], [ [ "### 8. Use this notebook to complete `etl_pipeline.py`\nUse the template file attached in the Resources folder to write a script that runs the steps above to create a database based on new datasets specified by the user. Alternatively, you can complete `etl_pipeline.py` in the classroom on the `Project Workspace IDE` coming later.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom sqlalchemy import create_engine\ndef etl_pipeline(db_path,csv1=\"messages.csv\", csv2=\"categories.csv\",tablename='disastertab'):\n # load messages dataset\n messages = pd.read_csv(csv1)\n # load categories dataset\n categories = pd.read_csv(csv2)\n \n # merge datasets\n df = messages.merge(categories, on='id')\n \n # create a dataframe of the 36 individual category columns\n categories = df['categories'].str.split(\";\", expand=True)\n \n # select the first row of the categories dataframe\n row = categories.loc[0,:]\n \n # use this row to extract a list of new column names for categories.\n category_colnames = row.apply(lambda x:x.split('-')[0]).values.tolist()\n \n # rename the columns of `categories`\n categories.columns = category_colnames\n \n for column in categories:\n # set each value to be the last character of the string\n categories[column] = categories[column].apply(lambda x:x.split('-')[1])\n # convert column from string to numeric\n categories[column] = categories[column].astype(int)\n # Check number not in (0,1) and update other value to 1\n categories.loc[categories[column]>1,column] = 1\n \n # drop the original categories column from `df`\n df.drop('categories',axis=1, inplace=True)\n \n # concatenate the original dataframe with the new `categories` dataframe\n df = pd.concat([df,categories], axis=1)\n df.head()\n \n # drop duplicates\n df.drop_duplicates(inplace=True)\n \n engine = create_engine('sqlite:///'+db_path)\n df.to_sql(tablename, engine, index=False)", "_____no_output_____" ], [ "etl_pipeline('workspace/data/DisasterResponse.db')", "_____no_output_____" ], [ "engine = create_engine('sqlite:///workspace/data/DisasterResponse.db')\ntt=pd.read_sql('SELECT * from disastertab', engine)\ntt.head(10)", "_____no_output_____" ], [ "\netl_pipeline(db_path='workspace/data/DisasterResponse.db',csv1=\"./workspace/data/disaster_messages.csv\", csv2=\"./workspace/data/disaster_categories.csv\",)", "_____no_output_____" ], [ "engine = create_engine('sqlite:///workspace/data/DisasterResponse.db')\ntt=pd.read_sql('SELECT * from disastertab', engine)\ntt.head(10)", "_____no_output_____" ], [ "tt.genre.value_counts()", "_____no_output_____" ], [ "tt.max()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
4aec86b3813d66e7ac01cb7e7a6ef797ae837e8d
150,060
ipynb
Jupyter Notebook
TensorFlow/TP1 ML/ML_TP1_P1.ipynb
Kuga23/Deep-Learning
86980338208c702b6bfcbcfffdb18498e389a56b
[ "MIT" ]
null
null
null
TensorFlow/TP1 ML/ML_TP1_P1.ipynb
Kuga23/Deep-Learning
86980338208c702b6bfcbcfffdb18498e389a56b
[ "MIT" ]
null
null
null
TensorFlow/TP1 ML/ML_TP1_P1.ipynb
Kuga23/Deep-Learning
86980338208c702b6bfcbcfffdb18498e389a56b
[ "MIT" ]
null
null
null
150,060
150,060
0.85811
[ [ [ "# ML Exercise 1 - Linear Regression", "_____no_output_____" ], [ "To help you start with Python and NumPy, there is a great tutorial online,\ncreated at Stanford. It can be downloaded as a notebook at https://github.com/kuleshov/cs228-material/tree/master/tutorials/python. Note that this tutorial is written in Python 2.7.\n\n\n<font color='red'> PLEASE DO NOT HESITATE to include your remarks/comments (in colors of your choice) in the notebook. That will be considered as a short report.</font>", "_____no_output_____" ] ], [ [ "# Change here using your first and last names\nfn1 = \"bonnie\"\nln1 = \"parker\"\nfn2 = \"clyde\"\nln2 = \"barrow\"\n\nfilename = \"_\".join(map(lambda s: s.strip().lower(), \n [\"tp1\", ln1, fn1, \"and\", ln2, fn2])) + \".ipynb\"\nprint(filename)", "tp1_parker_bonnie_and_barrow_clyde.ipynb\n" ] ], [ [ "## Part 1: Linear regression with one variable", "_____no_output_____" ], [ "You will implement linear regression with one variable to predict profits for a food truck. Suppose you are the CEO of a restaurant franchise and are considering different cities for opening a new outlet. The chain already has trucks in various cities and you have data for profits and populations from the cities.", "_____no_output_____" ], [ "<font color='red'> PLEASE READ CAREFULLY this. When you open a notebook (ipython) with google colab, you create a new working session. If you want that your \"created session\" can see your data in your google drive, you need to \"mount\" the drive and include the correct path to your data. Do not worry, the following code will do that. When call drive.mount, you need to authorize: click the link, copy the authorization code,...\n\n\nYou can run some basic commands like \"pwd, ls\" using \"!pwd, or !ls\"\n</font>", "_____no_output_____" ] ], [ [ "###### METHOD 1: \n\nfrom google.colab import drive\n\n# This will prompt for authorization.\ndrive.mount('/content/drive')\n\nimport os\nos.chdir('/content/drive/My Drive/Option_AI_2nd/ML')\n\n# TODO: change the correct path, you may need to create a \"data\" folder in your drive\n!wget https://www.dropbox.com/s/us61lvxcjnn1n3j/ex1data1.txt?dl=0 \\\n -O /content/drive/My Drive/Option_AI_2nd/ML/data/ex1data1.txt", "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/drive\n" ], [ "###### METHOD 2: EASIER\n!wget https://www.dropbox.com/s/us61lvxcjnn1n3j/ex1data1.txt?dl=0 \\\n -O ex1data1.txt", "--2020-02-04 14:50:25-- https://www.dropbox.com/s/us61lvxcjnn1n3j/ex1data1.txt?dl=0\nResolving www.dropbox.com (www.dropbox.com)... 162.125.1.1, 2620:100:6016:1::a27d:101\nConnecting to www.dropbox.com (www.dropbox.com)|162.125.1.1|:443... connected.\nHTTP request sent, awaiting response... 301 Moved Permanently\nLocation: /s/raw/us61lvxcjnn1n3j/ex1data1.txt [following]\n--2020-02-04 14:50:26-- https://www.dropbox.com/s/raw/us61lvxcjnn1n3j/ex1data1.txt\nReusing existing connection to www.dropbox.com:443.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://uc1d504e4196556a8035332ba599.dl.dropboxusercontent.com/cd/0/inline/AxfAp6b9rxPzgG_PWfL2yw33U5tGdcWTeVthXO-rsxiegLsczCAvwiOzJut7PhEuVChJPha8alp-yR4Ra_47dlFtO2x3RDJXMej71jONbYPZ6A/file# [following]\n--2020-02-04 14:50:26-- https://uc1d504e4196556a8035332ba599.dl.dropboxusercontent.com/cd/0/inline/AxfAp6b9rxPzgG_PWfL2yw33U5tGdcWTeVthXO-rsxiegLsczCAvwiOzJut7PhEuVChJPha8alp-yR4Ra_47dlFtO2x3RDJXMej71jONbYPZ6A/file\nResolving uc1d504e4196556a8035332ba599.dl.dropboxusercontent.com (uc1d504e4196556a8035332ba599.dl.dropboxusercontent.com)... 162.125.8.6, 2620:100:6016:6::a27d:106\nConnecting to uc1d504e4196556a8035332ba599.dl.dropboxusercontent.com (uc1d504e4196556a8035332ba599.dl.dropboxusercontent.com)|162.125.8.6|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 1359 (1.3K) [text/plain]\nSaving to: ‘ex1data1.txt’\n\nex1data1.txt 100%[===================>] 1.33K --.-KB/s in 0s \n\n2020-02-04 14:50:26 (187 MB/s) - ‘ex1data1.txt’ saved [1359/1359]\n\n" ], [ "# Check your current folder if method 1\n!pwd", "/content/drive/My Drive/Option_AI_2nd/ML\n" ] ], [ [ "# Importe some libraries and examine the data.", "_____no_output_____" ] ], [ [ "##### If you use METHOD 1\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport os\npath = os.getcwd() + 'ex1data1.txt' # TO DO: CHANGE THE PATH\ndata = pd.read_csv(path, header=None, names=['Population', 'Profit'])\ndata.head()", "_____no_output_____" ], [ "##### If you use METHOD 2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv('ex1data1.txt', header=None, names=['Population', 'Profit'])\ndata.head()", "_____no_output_____" ], [ "data.describe()", "_____no_output_____" ] ], [ [ "#Plot it to get a better idea of what the data looks like.", "_____no_output_____" ] ], [ [ "data.plot(kind='scatter', x='Population', y='Profit', figsize=(15,10))\n\n#data.T.plot.scatter(x = 'Population', y = 'Profit')", "_____no_output_____" ] ], [ [ "#Goal: fit the linear regression parameters $\\mathbf{w}$ to your dataset using gradient descent. ", "_____no_output_____" ], [ "You suppose that your relation between your data $x$ and target $t$ can be modeled by a linear mode \n\n$y(x,\\mathbf{w})= w_0+w_1x$ \\\\\nThe objective of linear regression is to minimize the cost function:\n\n$E(\\mathbf{w})=\\displaystyle \\frac{1}{2N} \\sum_{n=1}^{N} \\{y(x_n,\\mathbf{w})-t_n\\}^2 $ \\\\\n\n\n\n$N$ is the number of samples in the data set.\n\n\n<font color='red'> Question: in this dataset, $N=?$ </font> \n\n\n\nYour model parameters are the $w_j$ values which you will adjust to minimize cost $E(\\mathbf{w})$. \nOne solution is the batch gradient descent algorithm. In batch gradient descent,each iteration performs the update:\n\n$\\mathbf{w}=\\displaystyle \\mathbf{w} - \\eta \\frac{1}{N} \\sum_{n=1}^{N} \\{y(x_n,\\mathbf{w})-t_n\\}x_n$\n\nWith each step of gradient descent, your parameters $w_j$ come closer to the optimal values that will achieve the lowest cost $E(\\mathbf{w})$.\n\n<font color='red'> Question: how many parameters $w$ do you have to find for this dataset. </font> \n \n\n<font color='red'>TODO: Create a function to compute the cost of a given solution (characterized by the parameters w). </font> \nFunctions like power, sum of numpy may be useful.", "_____no_output_____" ], [ "#Important notes for implementation in Numpy\n\nFor array, * means element-wise multiplication, and the dot() function is used for matrix multiplication.\n\n\nFor matrix, * means matrix multiplication, and the multiply() function is used for element-wise multiplication.\n\n\n<font color='red'> Maybe in this part (Linear Regression), you should learn to use np.array. In part 2 (Logistic Regression), you learn to use np.matrix </font> ", "_____no_output_____" ] ], [ [ "def computeCost(X, t, w):\n #X : input dataset of shape (N x D+1), N: number of examples, D: the number of features. \n \n #t : target of shape (N, ).\n \n #w : parameters of shape (D+1, ).\n \n # Note that if you use np.array, * is elementwise multiplication, unlike Matlab,\n # you may need to use it \n # then using np.sum...\n\n # you can use np.dot\n # WRITE YOU CODE HERE\n\n # In this dataset, X is Population (each data point has only one variable, one feature)\n # t is profit \n # but for coding this function, you should consider that X is a np.array... \n # (array in numpy may have more than one dimension) \n ...\n return ...\n", "_____no_output_____" ] ], [ [ "#Do some data preparation.\n\n<font color='red'>TODO: get X (training data) (first column) and t (target variable) (last column) from \"data\". </font>", "_____no_output_____" ] ], [ [ "# set X (training data) and t (target variable)\ncols = data.shape[1]\nX = data.iloc[:,0:1]\nt = data.iloc.... ##### COMPLETE YOUR CODE HERE#####", "_____no_output_____" ] ], [ [ "Take a look to make sure X (training set) and t (target variable) look correct.", "_____no_output_____" ] ], [ [ "X.head()", "_____no_output_____" ], [ "t.head()", "_____no_output_____" ] ], [ [ "Let's add a column of ones to the X so we can use a vectorized solution to computing the cost and gradients (use X.insert).\n\n<font color='red'>Question: why do you need to do this? (hint: related to $w_0$)</font>", "_____no_output_____" ] ], [ [ "X.insert(0,'Ones',1)\nX.head()", "_____no_output_____" ] ], [ [ "The cost function is expecting numpy array (or matrices) so we need to convert X and t before we can use w (use np.array or np.matrix ...). We also need to initialize w (np.zeros). <font color='red'>Question: explain the shape of w?</font> ", "_____no_output_____" ] ], [ [ "X = np.array(X.values)\nt = np.array.... ##### COMPLETE YOUR CODE HERE#####\nw = np.zeros... ##### COMPLETE YOUR CODE HERE#####", "_____no_output_____" ] ], [ [ "Let's take a quick look at the shape of our X,t,w.", "_____no_output_____" ] ], [ [ "X.shape, w.shape, t.shape", "_____no_output_____" ] ], [ [ "Now let's compute the cost for our initial solution (0 values for w).", "_____no_output_____" ] ], [ [ "computeCost(X, t, w)", "_____no_output_____" ] ], [ [ "Expected result 32.072733877455676. So far so good. \n\n#<font color='red'>Exercise: Define a function to perform gradient descent on the parameters w using the update rules defined in the text.</font>\n\n\n\n\n\nFunctions like multiply, sum of numpy may be useful.", "_____no_output_____" ] ], [ [ "def gradientDescent(X, t, w, eta, iters):\n # Initialize some useful values\n N=... # number of training examples\n cost = np.zeros(iters); \n\n # make a copy of theta, to avoid changing the original array, since numpy arrays\n # are passed by reference to functions\n w = w.copy()\n \n for i in range(iters):\n ##### WRITE YOUR CODE HERE#####\n w = w - ...##### COMPLETE YOUR CODE HERE#####\n\n cost[i] = computeCost(X, t, w) # you should stock the cost function for each epoch\n # this is useful for checking whether the cost reduces...\n return w, cost", "_____no_output_____" ] ], [ [ "Initialize some additional variables - the learning rate eta, and the number of iterations to perform.", "_____no_output_____" ] ], [ [ "eta = 0.01\niters = 1000", "_____no_output_____" ] ], [ [ "Now let's run the gradient descent algorithm to fit our parameters eta to the training set.", "_____no_output_____" ] ], [ [ "w, cost = gradientDescent(X, t, w, eta, iters)\nw", "_____no_output_____" ] ], [ [ "Expected result: matrix([[-3.24140214, 1.1272942 ]]).\n\nFinally you can compute the cost (error) of the trained model using our fitted parameters.", "_____no_output_____" ] ], [ [ "computeCost(X, t, w)", "_____no_output_____" ] ], [ [ "Expected result: 4.515955503078912.\n\nNow let's plot the linear model along with the data to visually see how well it fits.", "_____no_output_____" ] ], [ [ "#TODO: to complete\nx = np.linspace(data.Population.min(), data.Population.max(), 100)\nf = ... ##### COMPLETE YOUR CODE HERE#####\n\nfig, ax = plt.subplots(figsize=(10,7))\nax.plot(x, f, 'r', label='Prediction')\nax.scatter(data.Population, data.Profit, label='Traning Data')\nax.legend(loc=2)\nax.set_xlabel('Population')\nax.set_ylabel('Profit')\nax.set_title('Predicted Profit vs. Population Size')", "_____no_output_____" ] ], [ [ "Looks pretty good! Since the gradient decent function also outputs a vector with the cost at each training iteration, we can plot that as well. Notice that the cost always decreases - this is an example of a convex optimization problem.", "_____no_output_____" ] ], [ [ "#TODO: plot the error vs. training epoch\nfig, ax = plt.subplots(figsize=(10,7))\nax.plot... #use np.arange(iters) to create an array ...\n##### COMPLETE YOUR CODE HERE#####\n", "_____no_output_____" ] ], [ [ "## Part 2: Linear regression with multiple variables", "_____no_output_____" ], [ "This exercise also included a housing price data set with 2 variables (size of the house in square feet and number of bedrooms) and a target (price of the house). Let's use the techniques we already applied to analyze that data set as well.", "_____no_output_____" ] ], [ [ "!wget https://www.dropbox.com/s/5b5hnnnn8d4y2o5/ex1data2.txt?dl=0 \\\n -O ex1data2.txt\n\n", "--2020-02-04 19:28:34-- https://www.dropbox.com/s/5b5hnnnn8d4y2o5/ex1data2.txt?dl=0\nResolving www.dropbox.com (www.dropbox.com)... 162.125.1.1, 2620:100:6016:1::a27d:101\nConnecting to www.dropbox.com (www.dropbox.com)|162.125.1.1|:443... connected.\nHTTP request sent, awaiting response... 301 Moved Permanently\nLocation: /s/raw/5b5hnnnn8d4y2o5/ex1data2.txt [following]\n--2020-02-04 19:28:34-- https://www.dropbox.com/s/raw/5b5hnnnn8d4y2o5/ex1data2.txt\nReusing existing connection to www.dropbox.com:443.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://uc64f44bdc997cb1a7884dcf8896.dl.dropboxusercontent.com/cd/0/inline/AxeHKXXTTfPNSDZ-yJA48-xyuSZ7s7pH-Fwd2PW8KEdVXTq2kbTaBQUUhpJxJU9QIWhldcDXD5AWsiVziNfODVUT5e-BEuqPrrBLKu1Z18K0sA/file# [following]\n--2020-02-04 19:28:34-- https://uc64f44bdc997cb1a7884dcf8896.dl.dropboxusercontent.com/cd/0/inline/AxeHKXXTTfPNSDZ-yJA48-xyuSZ7s7pH-Fwd2PW8KEdVXTq2kbTaBQUUhpJxJU9QIWhldcDXD5AWsiVziNfODVUT5e-BEuqPrrBLKu1Z18K0sA/file\nResolving uc64f44bdc997cb1a7884dcf8896.dl.dropboxusercontent.com (uc64f44bdc997cb1a7884dcf8896.dl.dropboxusercontent.com)... 162.125.1.6, 2620:100:601b:6::a27d:806\nConnecting to uc64f44bdc997cb1a7884dcf8896.dl.dropboxusercontent.com (uc64f44bdc997cb1a7884dcf8896.dl.dropboxusercontent.com)|162.125.1.6|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 657 [text/plain]\nSaving to: ‘ex1data2.txt’\n\n\rex1data2.txt 0%[ ] 0 --.-KB/s \rex1data2.txt 100%[===================>] 657 --.-KB/s in 0s \n\n2020-02-04 19:28:35 (117 MB/s) - ‘ex1data2.txt’ saved [657/657]\n\n" ] ], [ [ "The notebook will start by loading and displaying some values from this dataset. \n\nYou then complete the code to:\n\n\t- Subtract the mean value of each feature from the dataset. \n\t\n\t- After subtracting the mean, additionally scale (divide) the feature values by their respective “standard deviations.” ", "_____no_output_____" ] ], [ [ "file = 'ex1data2.txt'\ndata2 = pd.read_csv(file, header=None, names=['Size', 'Bedrooms', 'Price'])\ndata2.head()", "_____no_output_____" ] ], [ [ "<font color='red'>Exercise: add another pre-processing step - normalizing the features. </font>\n\n<font color='red'>Question: why is it necessary? </font>\n\n\n\t", "_____no_output_____" ] ], [ [ "##TODO, normalize your features\ndata2 = ...##### COMPLETE YOUR CODE HERE#####\n\n\n#Now show the normalized data\ndata2.head()", "_____no_output_____" ] ], [ [ "Now let's repeat our pre-processing steps from part 1 and run the linear regression procedure on the new data set.", "_____no_output_____" ] ], [ [ "eta=0.01\n\n# add ones column\ndata2.insert... ##### COMPLETE YOUR CODE HERE#####\n\n# set X (training data) and t (target variable)\ncols = data2.shape[1]\nX2 = data2.iloc...##### COMPLETE YOUR CODE HERE#####\nt2 = ...##### COMPLETE YOUR CODE HERE#####\n\n# convert to matrices/array\nX2 = ....##### COMPLETE YOUR CODE HERE#####\nt2 = ....##### COMPLETE YOUR CODE HERE#####\n\n# initialize w\n# TODO: what is shape of w? why?\n# ..........................\nw2 = ....##### COMPLETE YOUR CODE HERE#####\n\n# perform linear regression on the data set\nw2, cost2 = gradientDescent(X2, t2, w2, eta, iters)\n\n# get the cost (error) of the model\ncomputeCost(X2, t2, w2)", "_____no_output_____" ] ], [ [ "We can take a quick look at the training progess for this one as well.", "_____no_output_____" ] ], [ [ "#TODO: plot the error vs. training epoch\nfig, ax = plt.subplots(figsize=(10,7))\nax.plot(np.arange(iters), cost, 'r')\nax.set_xlabel('Iterations')\nax.set_ylabel('Cost')\nax.set_title('Error vs. Training Epoch')", "_____no_output_____" ] ], [ [ "<font color='red'>Question: What can you see from this figure ?</font>\n\nAnswer: ....\n\n\n\n<font color='red'>Exercise: Try out different learning rates for the dataset and find a learning rate that converges quickly.</font>", "_____no_output_____" ] ], [ [ "###WRITE YOUR CODE HERE\n....", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "Instead of implementing these algorithms from scratch, we could also use scikit-learn's linear regression function. Let's apply scikit-learn's linear regressio algorithm to the data from part 1 and see what it comes up with.", "_____no_output_____" ] ], [ [ "from sklearn import linear_model\nmodel = linear_model.LinearRegression()\nmodel.fit(X, t)", "_____no_output_____" ] ], [ [ "Here's what the scikit-learn model's predictions look like.", "_____no_output_____" ] ], [ [ "x = np.array(X[:, 1])\nf = model.predict(X).flatten()\n\nfig, ax = plt.subplots(figsize=(10,7))\nax.plot(x, f, 'r', label='Prediction')\nax.scatter(data.Population, data.Profit, label='Traning Data')\nax.legend(loc=2)\nax.set_xlabel('Population')\nax.set_ylabel('Profit')\nax.set_title('Predicted Profit vs. Population Size')", "_____no_output_____" ] ], [ [ "You can submit now your code via Moodle.\nDo not forget to answer the questions!!!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4aec880b8e409f899d5d6096f33a308458b01296
92,873
ipynb
Jupyter Notebook
Movie_Recommender_System.ipynb
omkargawade-10/Movie_Recommender_System
35e1e00ba81eaf140b0c23714563fc4a34648423
[ "Apache-2.0" ]
1
2022-01-04T00:08:50.000Z
2022-01-04T00:08:50.000Z
Movie_Recommender_System.ipynb
omkargawade-10/Movie_Recommender_System
35e1e00ba81eaf140b0c23714563fc4a34648423
[ "Apache-2.0" ]
null
null
null
Movie_Recommender_System.ipynb
omkargawade-10/Movie_Recommender_System
35e1e00ba81eaf140b0c23714563fc4a34648423
[ "Apache-2.0" ]
null
null
null
32.43905
149
0.380627
[ [ [ "# Movie Recommender System", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport ast\n%matplotlib inline", "_____no_output_____" ], [ "movies = pd.read_csv('tmdb_5000_movies.csv')\ncredits = pd.read_csv('tmdb_5000_credits.csv')", "_____no_output_____" ], [ "movies.head()", "_____no_output_____" ], [ "credits.head()", "_____no_output_____" ], [ "movies = movies.merge(credits, on='title')\nmovies.shape", "_____no_output_____" ], [ "movies = movies[['movie_id','title','overview','genres','keywords','cast','crew']]", "_____no_output_____" ], [ "movies.head()", "_____no_output_____" ], [ "movies.isnull().sum()", "_____no_output_____" ], [ "movies.dropna(inplace=True)", "_____no_output_____" ], [ "movies.duplicated().sum()", "_____no_output_____" ], [ "def get_genres(x):\n genre = []\n for i in ast.literal_eval(x):\n genre.append(i['name'])\n return genre", "_____no_output_____" ], [ "movies['genres'] = movies['genres'].apply(lambda x: get_genres(x))", "_____no_output_____" ], [ "movies['keywords'] = movies['keywords'].apply(lambda x: get_genres(x))", "_____no_output_____" ], [ "movies.head(1)", "_____no_output_____" ], [ "def get_actor(x):\n actor_name = []\n counter = 0\n for i in ast.literal_eval(x):\n if counter != 3:\n actor_name.append(i['name'])\n counter += 1\n else:\n break\n return actor_name", "_____no_output_____" ], [ "movies['cast'] = movies['cast'].apply(lambda x: get_actor(x))", "_____no_output_____" ], [ "movies.head(1)", "_____no_output_____" ], [ "def get_director(x):\n director_name = []\n for i in ast.literal_eval(x):\n if i['job'] == 'Director':\n director_name.append(i['name'])\n return director_name", "_____no_output_____" ], [ "movies['crew'] = movies['crew'].apply(lambda x: get_director(x))", "_____no_output_____" ], [ "movies.head()", "_____no_output_____" ], [ "movies['overview'] = movies['overview'].apply(lambda x: x.split())", "_____no_output_____" ], [ "movies", "_____no_output_____" ], [ "movies['genres'] = movies['genres'].apply(lambda x: [i.replace(' ','') for i in x])\nmovies['keywords'] = movies['keywords'].apply(lambda x: [i.replace(' ','') for i in x])\nmovies['cast'] = movies['cast'].apply(lambda x: [i.replace(' ','') for i in x])\nmovies['crew'] = movies['crew'].apply(lambda x: [i.replace(' ','') for i in x])", "_____no_output_____" ], [ "movies.head()", "_____no_output_____" ], [ "movies['tags'] = movies['overview'] + movies['genres'] + movies['keywords'] + movies['cast'] + movies['crew']", "_____no_output_____" ], [ "df = movies[['movie_id','title','tags']]\ndf", "_____no_output_____" ], [ "df['tags'] = df['tags'].apply(lambda x: ' '.join(x))", "<ipython-input-27-b20ed34e6d61>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n df['tags'] = df['tags'].apply(lambda x: ' '.join(x))\n" ], [ "df['tags'] = df['tags'].apply(lambda x: x.lower())", "<ipython-input-28-f3ac90a1e795>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n df['tags'] = df['tags'].apply(lambda x: x.lower())\n" ], [ "import nltk", "_____no_output_____" ], [ "from nltk.stem.porter import PorterStemmer\nps = PorterStemmer()", "_____no_output_____" ], [ "def stem(x):\n stem_words = []\n for i in x.split():\n stem_words.append(ps.stem(i))\n return ' '.join(stem_words)", "_____no_output_____" ], [ "df['tags'] = df['tags'].apply(lambda x: stem(x))", "<ipython-input-32-038453061ae2>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n df['tags'] = df['tags'].apply(lambda x: stem(x))\n" ], [ "from sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer(max_features=5000,stop_words='english')", "_____no_output_____" ], [ "cv.fit_transform(df['tags']).toarray().shape", "_____no_output_____" ], [ "vectors = cv.fit_transform(df['tags']).toarray()", "_____no_output_____" ], [ "cv.get_feature_names()", "_____no_output_____" ], [ "from sklearn.metrics.pairwise import cosine_similarity", "_____no_output_____" ], [ "similarity = cosine_similarity(vectors)", "_____no_output_____" ], [ "similarity", "_____no_output_____" ], [ "distances = sorted(enumerate(similarity[0]),reverse=True,key = lambda x: x[1])[1:6]\ndistances", "_____no_output_____" ], [ "def recommend(movie):\n movie_index = df[df['title'] == movie].index[0]\n distances = similarity[movie_index]\n movie_list = sorted(enumerate(distances),reverse=True,key = lambda x: x[1])[1:6]\n \n for i in movie_list:\n print(df['title'][i[0]])", "_____no_output_____" ], [ "recommend('Avatar')", "Aliens vs Predator: Requiem\nAliens\nAnne of Green Gables\nIndependence Day\nTitan A.E.\n" ], [ "import pickle", "_____no_output_____" ], [ "pickle.dump(df,open('movies.pkl','wb'))", "_____no_output_____" ], [ "pickle.dump(similarity,open('similarity.pkl','wb'))", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aec8a8cdeae6cb9dd8eda608b7c0bb77841d32a
3,724
ipynb
Jupyter Notebook
dataset_processing.ipynb
nkkumawat/Face-Login
eacac2402fa344c40a8cbfdd1c745745212ee577
[ "Apache-2.0" ]
null
null
null
dataset_processing.ipynb
nkkumawat/Face-Login
eacac2402fa344c40a8cbfdd1c745745212ee577
[ "Apache-2.0" ]
null
null
null
dataset_processing.ipynb
nkkumawat/Face-Login
eacac2402fa344c40a8cbfdd1c745745212ee577
[ "Apache-2.0" ]
null
null
null
29.555556
108
0.515306
[ [ [ "import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n#========================================= Training ============================================\ncells =[]\nfor i in range(1 , 50):\n trainImg = cv2.imread('./faces/face_'+str(i)+'.jpg')\n trainGray = cv2.cvtColor(trainImg,cv2.COLOR_BGR2GRAY)\n cells.append([np.hsplit(row,200) for row in np.vsplit(trainGray,200)])\n\nfor i in range(101 , 150):\n trainImg = cv2.imread('./faces/face_'+str(i)+'.jpg')\n trainGray = cv2.cvtColor(trainImg,cv2.COLOR_BGR2GRAY)\n cells.append([np.hsplit(row,200) for row in np.vsplit(trainGray,200)])\n\nfor i in range(51 , 100):\n trainImg = cv2.imread('./faces/face_'+str(i)+'.jpg')\n trainGray = cv2.cvtColor(trainImg,cv2.COLOR_BGR2GRAY)\n cells.append([np.hsplit(row,200) for row in np.vsplit(trainGray,200)])\n\nfor i in range(151 , 200):\n trainImg = cv2.imread('./faces/face_'+str(i)+'.jpg')\n trainGray = cv2.cvtColor(trainImg,cv2.COLOR_BGR2GRAY)\n cells.append([np.hsplit(row,200) for row in np.vsplit(trainGray,200)])\n\n\nx = np.array(cells)\nprint(x.shape)\n\n\n\ntrainData = x[:,1:100].reshape(-1,400).astype(np.float32) \nprint(trainData.shape)\n\n# # Create labels for train and test data\nk = np.arange(2)\ntrainLabels = np.repeat(k,4851)[:,np.newaxis]\n\n# print(trainLabels)\n# Initiate kNN, train the data, then test it with test data for k=1\nknn = cv2.ml.KNearest_create()\nknn.train(trainData, cv2.ml.ROW_SAMPLE, trainLabels)\n# # =================================Testing=======================================================\n\ntestImage = cv2.imread('./faces/face_'+str(125)+'.jpg')\ntestGray = cv2.cvtColor(testImage,cv2.COLOR_BGR2GRAY)\ntestCells = [np.hsplit(row,200) for row in np.vsplit(testGray,200)]\nx = np.array(testCells)\n\nprint(x.shape)\n# testData = x[:,101:200].reshape(-1,400).astype(np.float32) # Size = (2500,400)\ntestData = x[:,:].reshape(-1,400).astype(np.float32)\ntestLabels = [1]\n\n# print(testData)\nret, result, neighbours, dist = knn.findNearest(testData, k=5)\n\n\nmatches = result == testLabels\ncorrect = np.count_nonzero(matches)\nprint(correct)\n\naccuracy = correct*100.0/result.size\nprint (accuracy)", "(196, 200, 200, 1, 1)\n(9702, 400)\n(200, 200, 1, 1)\n14\n14.0\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
4aec8d212b0de343bfdede09d946742cd17677cc
92,050
ipynb
Jupyter Notebook
Dual_Bert.ipynb
Bagja9102Kurniawan/hoax-classification
c1cd968c26db13b6fb21fc4e29b5949f1a4dd6b9
[ "MIT" ]
1
2020-11-01T11:53:37.000Z
2020-11-01T11:53:37.000Z
Dual_Bert.ipynb
Bagja9102Kurniawan/hoax-classification
c1cd968c26db13b6fb21fc4e29b5949f1a4dd6b9
[ "MIT" ]
null
null
null
Dual_Bert.ipynb
Bagja9102Kurniawan/hoax-classification
c1cd968c26db13b6fb21fc4e29b5949f1a4dd6b9
[ "MIT" ]
null
null
null
56.611316
16,882
0.536448
[ [ [ "!pip install transformers", "Requirement already satisfied: transformers in /usr/local/lib/python3.6/dist-packages (3.3.0)\nRequirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers) (3.0.12)\nRequirement already satisfied: tokenizers==0.8.1.rc2 in /usr/local/lib/python3.6/dist-packages (from transformers) (0.8.1rc2)\nRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers) (2.23.0)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers) (2019.12.20)\nRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers) (0.7)\nRequirement already satisfied: sentencepiece!=0.1.92 in /usr/local/lib/python3.6/dist-packages (from transformers) (0.1.91)\nRequirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from transformers) (20.4)\nRequirement already satisfied: sacremoses in /usr/local/lib/python3.6/dist-packages (from transformers) (0.0.43)\nRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from transformers) (1.18.5)\nRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers) (4.41.1)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (1.24.3)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2020.6.20)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2.10)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (3.0.4)\nRequirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->transformers) (2.4.7)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from packaging->transformers) (1.15.0)\nRequirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (7.1.2)\nRequirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (0.16.0)\n" ], [ "# generics \nimport pandas as pd \nimport numpy as np \nfrom tqdm import tqdm\nimport re\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nimport random\n\n\n!pip install pytypo\nimport pytypo\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, Dataset\nfrom sklearn.metrics import confusion_matrix, classification_report, f1_score\n\nimport torch.nn.functional as F\n\nfrom transformers import BertTokenizer, AutoModel, BertConfig, TFBertModel, AdamW, get_linear_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, BertConfig, get_constant_schedule_with_warmup\n\n# import warnings\n# warnings.filterwarnings('FutureWarning')\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else \"cpu\")\ndevice", "Requirement already satisfied: pytypo in /usr/local/lib/python3.6/dist-packages (0.3.0)\n" ], [ "from google.colab import drive \ndrive.mount('/content/drive')", "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" ], [ "def set_seed(seed_value=42):\n \"\"\"Set seed for reproducibility.\n \"\"\"\n random.seed(seed_value)\n np.random.seed(seed_value)\n torch.manual_seed(seed_value)\n torch.cuda.manual_seed_all(seed_value)\n\nset_seed(29092020)", "_____no_output_____" ], [ "tokenizer = BertTokenizer.from_pretrained(\"indobenchmark/indobert-base-p1\")\nmodel = AutoModel.from_pretrained(\"indobenchmark/indobert-base-p1\")", "_____no_output_____" ], [ "# df = pd.read_excel('./drive/My Drive/satdat/dataset.xlsx')\ndf_train = pd.read_csv('./drive/My Drive/satdat/train.csv')\ndf_val = pd.read_csv('./drive/My Drive/satdat/val.csv')\ntest = pd.read_csv('./drive/My Drive/satdat/datatest_labelled.csv')", "_____no_output_____" ], [ "# df_train, df_val = train_test_split(df, test_size=0.1, random_state=42)", "_____no_output_____" ], [ "# df_train.to_csv(\"./drive/My Drive/satdat/b_train.csv\")\n# df_val.to_csv('./drive/My Drive/satdat/b_val.csv')", "_____no_output_____" ], [ "def clean(text) : \n\n text_cleaning_re = \"@\\S+|https?:\\S+|http?:\\S|[#]+|[^A-Za-z0-9]+\"\n text_cleaning_hash = \"#[A-Za-z0-9]+\" \n text_cleaning_num = \"(^|\\W)\\d+\"\n\n text = re.sub(text_cleaning_hash, \" \", text).strip()\n text = re.sub(text_cleaning_num, \" \", text).strip()\n text = re.sub(text_cleaning_re, \" \", text).strip()\n \n text = text.strip()\n\n out = []\n for word in text.split() :\n # try : \n # out.append(word.replace(word, slang[word]))\n # except Exception as e : \n out.append(word)\n \n return pytypo.correct_sentence(\" \".join(out).strip())\n\nslang = pd.read_csv('./drive/My Drive/satdat/slang.csv')\nslang = slang[['slang', 'formal']]\nslang = slang.set_index('slang')['formal'].to_dict()\n\n\ndf_train.narasi = df_train.narasi.apply(lambda x: clean(x)) \ndf_train.judul = df_train.judul.apply(lambda x: clean(x))\n\ndf_val.narasi = df_val.narasi.apply(lambda x: clean(x)) \ndf_val.judul = df_val.judul.apply(lambda x: clean(x))\n\ntest.narasi = test.narasi.apply(lambda x: clean(x))\ntest.judul = test.judul.apply(lambda x: clean(x))", "_____no_output_____" ], [ "class HoaxDataset(Dataset) : \n def __init__(self, feature1, feature2, label, tokenizer, max_len, no_label=False) : \n self.feature1 = feature1\n self.feature2 = feature2\n self.label = label \n self.tokenizer = tokenizer \n self.max_len = max_len \n self.no_label = no_label\n\n def __len__(self) : \n return len(self.feature1)\n \n def __getitem__(self, item) :\n feature1 = str(self.feature1[item])\n feature2 = str(self.feature2[item])\n if not self.no_label: \n label = self.label[item]\n\n encoding1 = tokenizer.encode_plus(\n # ntar diganti <----------------------------------------------------\n feature1, \n max_length=64,\n add_special_tokens=True,\n return_token_type_ids=False,\n return_attention_mask=True,\n truncation=True, \n pad_to_max_length=True,\n return_tensors='pt'\n )\n\n encoding2 = tokenizer.encode_plus(\n feature2, \n max_length=32,\n add_special_tokens=True,\n return_token_type_ids=False,\n return_attention_mask=True,\n truncation=True, \n pad_to_max_length=True,\n return_tensors='pt'\n )\n \n if not self.no_label :\n return {\n 'narasi_text' : feature1,\n 'narasi_input_ids' : encoding1['input_ids'].flatten(), \n 'narasi_attention_mask' : encoding1['attention_mask'].flatten(), \n\n 'judul_narasi_text' : feature2,\n 'judul_input_ids' : encoding2['input_ids'].flatten(), \n 'judul_attention_mask' : encoding2['attention_mask'].flatten(), \n\n 'label' : torch.tensor(label, dtype=torch.long)\n\n }\n else : \n return {\n 'narasi_text' : feature1,\n 'narasi_input_ids' : encoding1['input_ids'].flatten(), \n 'narasi_attention_mask' : encoding1['attention_mask'].flatten(), \n\n 'judul_narasi_text' : feature2,\n 'judul_input_ids' : encoding2['input_ids'].flatten(), \n 'judul_attention_mask' : encoding2['attention_mask'].flatten(), \n\n }\n\n\ndef to_data_loader(df, columns, label, tokenizer, max_len, batch_size) : \n ds = HoaxDataset(\n df[columns[0]], \n df[columns[1]], \n df[label],\n tokenizer=tokenizer, \n max_len=max_len, \n )\n\n return DataLoader(\n ds, \n batch_size=batch_size, \n )\n\ndef test_to_data_loader(df, columns, tokenizer, max_len, batch_size) : \n ds = HoaxDataset(\n df[columns[0]], \n df[columns[1]], \n None,\n tokenizer=tokenizer, \n max_len=max_len, \n no_label=True\n )\n\n return DataLoader(\n ds, \n batch_size=batch_size, \n )", "_____no_output_____" ], [ "train_data_loader = to_data_loader(df_train, ['narasi', 'judul'], 'label', tokenizer, 64, 32)\nval_data_loader = to_data_loader(df_val, ['narasi', 'judul'], 'label', tokenizer, 64, 32)\ntest_data_loader = test_to_data_loader(test, ['narasi', 'judul'], tokenizer, 64, 32)", "_____no_output_____" ], [ "data = next(iter(test_data_loader))\ndata.keys()", "/usr/local/lib/python3.6/dist-packages/transformers/tokenization_utils_base.py:1773: FutureWarning: The `pad_to_max_length` argument is deprecated and will be removed in a future version, use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or use `padding='max_length'` to pad to a max length. In this case, you can give a specific length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the maximal input size of the model (e.g. 512 for Bert).\n FutureWarning,\n" ], [ "class HoaxClassifier(nn.Module) : \n def __init__(self, n_classes) : \n super(HoaxClassifier, self).__init__() \n config = BertConfig.from_pretrained('indobenchmark/indobert-base-p1')\n\n self.bert1 = AutoModel.from_pretrained(\"indobenchmark/indobert-base-p1\", config=config)\n self.bert2 = AutoModel.from_pretrained(\"indobenchmark/indobert-base-p1\", config=config)\n\n self.drop = nn.Dropout(p=0.5)\n\n self.relu = nn.ReLU()\n\n self.tanh = nn.Tanh()\n\n self.dual_bert = nn.Linear(self.bert1.config.hidden_size * 2, 32)\n\n self.out = nn.Linear(32, 2) \n\n\n\n def forward(self, narasi_input_ids, narasi_attention_mask, judul_input_ids, judul_attention_mask) :\n _, pooled_output1 = self.bert1(\n input_ids = narasi_input_ids, \n attention_mask = narasi_attention_mask\n )\n\n _, pooled_output2 = self.bert2(\n input_ids = judul_input_ids, \n attention_mask = judul_attention_mask\n )\n\n x = torch.cat((pooled_output1, pooled_output2), dim=1)\n\n x = self.drop(x)\n x = self.dual_bert(x)\n x = self.tanh(x) \n\n x = self.drop(x)\n x = self.out(x)\n\n return x", "_____no_output_____" ], [ "model = HoaxClassifier(2)\nmodel.to(device)", "_____no_output_____" ], [ "# load freezed only if already exist\n# model.load_state_dict(torch.load('/content/drive/My Drive/satdat/freezed_state.bin'))", "_____no_output_____" ], [ "# toggle to train non embeddings\nmodel.bert1.embeddings.requires_grad_=True\nmodel.bert2.embeddings.requires_grad_=True", "_____no_output_____" ], [ "EPOCHS = 8\nopt = AdamW(model.parameters(), lr=3e-5, correct_bias=False, weight_decay=1e-4)\ntotal_steps = len(train_data_loader) * EPOCHS\n\nscheduler = get_constant_schedule_with_warmup(\n opt, \n num_warmup_steps=0, \n # num_training_steps=total_steps, \n\n)\n\nloss_function = nn.CrossEntropyLoss().to(device)", "_____no_output_____" ], [ "def train_epoch (model, data_loader, loss_fn, optimizer, device, scheduler, n_examples) : \n\n model = model.train() \n\n correct_predictions = 0\n losses = []\n\n for d in data_loader : \n input_ids1 = d['narasi_input_ids'].to(device)\n input_ids2 = d['judul_input_ids'].to(device)\n\n input_mask1 = d['narasi_attention_mask'].to(device)\n input_mask2 = d['judul_attention_mask'].to(device)\n\n label = d['label'].to(device)\n\n outputs = model(\n input_ids1, \n input_mask1, \n input_ids2, \n input_mask2\n )\n\n _, preds = torch.max(outputs, dim=1)\n loss = loss_fn(outputs, label)\n\n correct_predictions += torch.sum(preds == label)\n losses.append(loss.item())\n\n\n loss.backward() \n nn.utils.clip_grad_norm(model.parameters(), max_norm=1.0)\n optimizer.step()\n scheduler.step() \n optimizer.zero_grad()\n return correct_predictions.double() / n_examples, np.mean(losses)\n\ndef eval_model(model, data_loader, loss_fn, device, n_examples) : \n model = model.eval() \n\n losses = []\n correct_predictions=0\n\n with torch.no_grad() : \n for d in data_loader :\n input_ids1 = d['narasi_input_ids'].to(device)\n input_ids2 = d['judul_input_ids'].to(device)\n\n input_mask1 = d['narasi_attention_mask'].to(device)\n input_mask2 = d['judul_attention_mask'].to(device)\n\n label = d['label'].to(device)\n\n outputs = model(\n input_ids1, \n input_mask1, \n input_ids2, \n input_mask2\n )\n\n _, preds = torch.max(outputs, dim=1)\n loss = loss_fn(outputs, label)\n\n correct_predictions += torch.sum(preds == label)\n losses.append(loss.item())\n\n return correct_predictions.double() / n_examples, np.mean(losses)", "_____no_output_____" ], [ "%%time\n\nhistory = defaultdict(list)\nbest_accuracy = 0\n\nfor epoch in range(EPOCHS):\n\n print(f'Epoch {epoch + 1}/{EPOCHS}')\n print('-' * 10)\n\n train_acc, train_loss = train_epoch(\n model,\n train_data_loader, \n loss_function, \n opt, \n device, \n scheduler, \n len(df_train)\n )\n\n print(f'Train loss {train_loss} accuracy {train_acc}')\n\n val_acc, val_loss = eval_model(\n model,\n val_data_loader,\n loss_function, \n device, \n len(df_val)\n )\n\n print(f'Val loss {val_loss} accuracy {val_acc}')\n print()\n\n history['train_acc'].append(train_acc)\n history['train_loss'].append(train_loss)\n history['val_acc'].append(val_acc)\n history['val_loss'].append(val_loss)\n\n\n\n if val_acc > best_accuracy:\n torch.save(model.state_dict(), 'best_model.bin')\n best_accuracy = val_acc\n", "Epoch 1/8\n----------\n" ], [ "def get_predictions(model, data_loader):\n model = model.eval()\n \n predictions = []\n prediction_probs = []\n\n with torch.no_grad():\n for d in data_loader:\n\n input_ids1 = d['narasi_input_ids'].to(device)\n input_ids2 = d['judul_input_ids'].to(device)\n\n input_mask1 = d['narasi_attention_mask'].to(device)\n input_mask2 = d['judul_attention_mask'].to(device)\n\n\n outputs = model(\n input_ids1, \n input_mask1, \n input_ids2, \n input_mask2\n )\n _, preds = torch.max(outputs, dim=1)\n\n probs = F.softmax(outputs, dim=1)\n\n predictions.extend(preds)\n prediction_probs.extend(probs)\n\n predictions = torch.stack(predictions).cpu()\n prediction_probs = torch.stack(prediction_probs).cpu()\n return predictions, prediction_probs", "_____no_output_____" ], [ "# load best model \nmodel.load_state_dict(torch.load('./best_model.bin'))", "_____no_output_____" ], [ "y_pred, y_pred_probs = get_predictions(\n model,\n test_data_loader\n)", "/usr/local/lib/python3.6/dist-packages/transformers/tokenization_utils_base.py:1773: FutureWarning: The `pad_to_max_length` argument is deprecated and will be removed in a future version, use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or use `padding='max_length'` to pad to a max length. In this case, you can give a specific length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the maximal input size of the model (e.g. 512 for Bert).\n FutureWarning,\n" ], [ "y_pred", "_____no_output_____" ], [ "print(classification_report(list(test['label']), y_pred))\n", " precision recall f1-score support\n\n 0 0.72 0.57 0.64 60\n 1 0.94 0.97 0.95 410\n\n accuracy 0.92 470\n macro avg 0.83 0.77 0.79 470\nweighted avg 0.91 0.92 0.91 470\n\n" ], [ "\nprint(f1_score(list(test['label']), y_pred, average='micro'))", "0.9170212765957447\n" ], [ "import itertools\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\ndef plot_confusion_matrix(cm, classes,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n\n # cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n # print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title, fontsize=20)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, fontsize=13)\n plt.yticks(tick_marks, classes, fontsize=13)\n\n fmt = '.2f'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label', fontsize=17)\n plt.xlabel('Predicted label', fontsize=17)", "_____no_output_____" ], [ "cnf_matrix = confusion_matrix(test.label.to_list(), y_pred)\nplt.figure(figsize=(6,6))\nplot_confusion_matrix(cnf_matrix, classes=['0', '1'], title=\"Confusion matrix\")\nplt.show()", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aec8d32a798899c4050670ac986412319c19788
34,178
ipynb
Jupyter Notebook
experiments/notebooks/gym-baselines/pendulum-ppo2.ipynb
WPI-MMR/learning_experiments
bd0cb32dd936bd31f3c671fd0da3455d9e29441a
[ "MIT" ]
null
null
null
experiments/notebooks/gym-baselines/pendulum-ppo2.ipynb
WPI-MMR/learning_experiments
bd0cb32dd936bd31f3c671fd0da3455d9e29441a
[ "MIT" ]
10
2020-11-18T13:56:07.000Z
2021-03-20T21:10:19.000Z
experiments/notebooks/gym-baselines/pendulum-ppo2.ipynb
WPI-MMR/learning_experiments
bd0cb32dd936bd31f3c671fd0da3455d9e29441a
[ "MIT" ]
null
null
null
41.62972
297
0.437591
[ [ [ "# Autotrainer PPO2 on Gym Pendulum\nTest the autotrainer on Open Ai's Pendulum environment, which is continuous and considered to be an easy enviroment to solve.", "_____no_output_____" ], [ "## Ensure that Tensorflow is using the GPU", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nif tf.test.gpu_device_name():\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\nelse:\n print(\"Please install GPU version of TF\")", "Default GPU Device: /device:GPU:0\n" ] ], [ [ "## Define Experiment Tags", "_____no_output_____" ] ], [ [ "TAGS = ['gym-pendulum', 'gpu',]", "_____no_output_____" ] ], [ [ "## Parse CLI arguments and register w/ wandb", "_____no_output_____" ], [ "This experiment will be using the auto trainer to handle all of the hyperparmeter running", "_____no_output_____" ] ], [ [ "from auto_trainer import params\nimport auto_trainer\n\nauto_trainer.trainer.PROJECT_NAME = 'autotrainer-gym-baselines'", "WARNING:tensorflow:\nThe TensorFlow contrib module will not be included in TensorFlow 2.0.\nFor more information, please see:\n * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n * https://github.com/tensorflow/addons\n * https://github.com/tensorflow/io (for I/O related ops)\nIf you depend on functionality not listed there, please file an issue.\n\n" ], [ "config = params.WandbParameters().parse()\n\nconfig.episodes = 10000\nconfig.episode_length = 750\n\nconfig.num_workers = 8\nconfig.eval_frequency = 25\nconfig.eval_episodes = 5\nconfig.fps = 20\n\n# Create a 4 second gif\nconfig.eval_render_freq = int(config.episode_length / (4 * config.fps))\n\nconfig", "_____no_output_____" ], [ "config, run = auto_trainer.get_synced_config(config, TAGS)\nconfig", "\u001b[34m\u001b[1mwandb\u001b[0m: Currently logged in as: \u001b[33magupta231\u001b[0m (use `wandb login --relogin` to force relogin)\n/usr/local/lib/python3.7/dist-packages/IPython/html.py:14: ShimWarning: The `IPython.html` package has been deprecated since IPython 4.0. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`.\n \"`IPython.html.widgets` has moved to `ipywidgets`.\", ShimWarning)\n" ] ], [ [ "## Create a virtual display for environment rendering", "_____no_output_____" ] ], [ [ "import pyvirtualdisplay\ndisplay = pyvirtualdisplay.Display(visible=False, size=(1400, 900))\ndisplay.start()", "_____no_output_____" ] ], [ [ "## Create a normalized wrapper for the Pendulum Environment\nThe vanilla Pendulum enviornment has its action and observation spaces outside of $[-1, 1]$. Create a simple wrapper to apply min/max scaling to the respective values. Note that the default Pendulum environment doesn't have a termination state, so artifically create a termination condition.", "_____no_output_____" ] ], [ [ "from gym.envs.classic_control import pendulum\nfrom gym import spaces\nimport gym\n\nclass NormalizedPendulum(pendulum.PendulumEnv):\n def __init__(self, length: int = 1000):\n super().__init__()\n self.unscaled_obs_space = self.observation_space\n self.action_space = spaces.Box(low=-1., high=1., shape=(1,))\n self.observation_space = spaces.Box(low=-1., high=1., shape=(3,))\n \n self._length = length\n self._cnt = 0\n \n def reset(self):\n self._cnt = 0\n return super().reset()\n \n def step(self, u):\n self._cnt += 1\n \n obs, reward, done, info = super().step(u * self.max_torque)\n if self._cnt % self._length == 0:\n return obs, reward, True, info\n else:\n return obs, reward, done, info\n \n def _get_obs(self):\n return super()._get_obs() / self.unscaled_obs_space.high", "_____no_output_____" ] ], [ [ "Create the environment generator", "_____no_output_____" ] ], [ [ "def make_env(length):\n def _init():\n return NormalizedPendulum(length)\n return _init", "_____no_output_____" ] ], [ [ "### Create the Envs\nImport the desired vectorized env", "_____no_output_____" ] ], [ [ "from stable_baselines.common.vec_env import SubprocVecEnv\nfrom stable_baselines.common.vec_env import VecNormalize", "_____no_output_____" ] ], [ [ "Create training & testing environments", "_____no_output_____" ] ], [ [ "train_env = SubprocVecEnv([make_env(config.episode_length) \n for _ in range(config.num_workers)])\ntest_env = make_env(config.episode_length)()", "_____no_output_____" ] ], [ [ "## Learning\nAnd we're off!", "_____no_output_____" ] ], [ [ "model, config, run = auto_trainer.train(train_env, test_env, config, TAGS, \n log_freq=250, full_logging=False, run=run)", "WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/tf_util.py:191: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/tf_util.py:200: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/policies.py:116: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/input.py:25: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/policies.py:561: flatten (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse keras.layers.flatten instead.\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensorflow_core/python/layers/core.py:332: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `layer.__call__` method instead.\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/tf_layers.py:123: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/distributions.py:418: The name tf.random_normal is deprecated. Please use tf.random.normal instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/ppo2/ppo2.py:190: The name tf.summary.scalar is deprecated. Please use tf.compat.v1.summary.scalar instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/ppo2/ppo2.py:198: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/math_grad.py:1424: 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\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/ppo2/ppo2.py:206: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/ppo2/ppo2.py:240: The name tf.global_variables_initializer is deprecated. Please use tf.compat.v1.global_variables_initializer instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/ppo2/ppo2.py:242: The name tf.summary.merge_all is deprecated. Please use tf.compat.v1.summary.merge_all instead.\n\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/base_class.py:1169: The name tf.summary.FileWriter is deprecated. Please use tf.compat.v1.summary.FileWriter instead.\n\n---------------------------------------\n| approxkl | 1.7475563e-06 |\n| clipfrac | 0.0 |\n| explained_variance | 0.0079 |\n| fps | 1759 |\n| n_updates | 1 |\n| policy_entropy | 1.4193635 |\n| policy_loss | -2.7332295e-05 |\n| serial_timesteps | 128 |\n| time_elapsed | 0.00023 |\n| total_timesteps | 1024 |\n| value_loss | 5202.129 |\n---------------------------------------\nWARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/stable_baselines/common/tf_util.py:502: The name tf.Summary is deprecated. Please use tf.compat.v1.Summary instead.\n\n" ] ] ]
[ "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", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aecbc20e31347445b21c13ef96a6287c07eba6d
19,249
ipynb
Jupyter Notebook
notebooks/113-image-classification-quantization/113-image-classification-quantization.ipynb
zzk0/openvino_notebooks
8303642d77960e247a04ff571e733fae1c8bfba4
[ "Apache-2.0" ]
1
2022-03-25T10:35:54.000Z
2022-03-25T10:35:54.000Z
notebooks/113-image-classification-quantization/113-image-classification-quantization.ipynb
zzk0/openvino_notebooks
8303642d77960e247a04ff571e733fae1c8bfba4
[ "Apache-2.0" ]
null
null
null
notebooks/113-image-classification-quantization/113-image-classification-quantization.ipynb
zzk0/openvino_notebooks
8303642d77960e247a04ff571e733fae1c8bfba4
[ "Apache-2.0" ]
null
null
null
38.116832
444
0.522884
[ [ [ "# Quantization of Image Classification Models\n\nThis tutorial demostrates how to apply INT8 quantization to Image Classification model using [Post-training Optimization Tool API](../../compression/api/README.md). The Mobilenet V2 model trained on Cifar10 dataset is used as an example. The code of this tutorial is designed to be extandable to custom model and dataset. It is assumed that OpenVINO is already installed. This tutorial consists of the following steps:\n- Prepare the model for quantization\n- Define data loading and accuracy validation functionality\n- Run optimization pipeline\n- Compare accuracy of the original and quantized models\n- Compare performance of the original and quantized models\n- Compare results on one picture", "_____no_output_____" ] ], [ [ "import os\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom addict import Dict\nfrom compression.api import DataLoader, Metric\nfrom compression.engines.ie_engine import IEEngine\nfrom compression.graph import load_model, save_model\nfrom compression.graph.model_utils import compress_model_weights\nfrom compression.pipeline.initializer import create_pipeline\nfrom openvino.runtime import Core\nfrom torchvision import transforms\nfrom torchvision.datasets import CIFAR10", "_____no_output_____" ], [ "# Set the data and model directories\nDATA_DIR = 'data'\nMODEL_DIR = 'model'\n\nos.makedirs(DATA_DIR, exist_ok=True)\nos.makedirs(MODEL_DIR, exist_ok=True)", "_____no_output_____" ] ], [ [ "## Prepare the Model\nModel preparation stage has the following steps:\n- Download PyTorch model from Torchvision repository\n- Convert it to ONNX format\n- Run OpenVINO Model Optimizer tool to convert ONNX to OpenVINO Intermediate Representation (IR)\n\n", "_____no_output_____" ] ], [ [ "model = torch.hub.load(\"chenyaofo/pytorch-cifar-models\", \"cifar10_mobilenetv2_x1_0\", pretrained=True)\nmodel.eval()\n\ndummy_input = torch.randn(1, 3, 32, 32)\n\nonnx_model_path = Path(MODEL_DIR) / 'mobilenet_v2.onnx'\nir_model_xml = onnx_model_path.with_suffix('.xml')\nir_model_bin = onnx_model_path.with_suffix('.bin')\n\ntorch.onnx.export(model, dummy_input, onnx_model_path, verbose=True)\n\n# Run OpenVINO Model Optimization tool to convert ONNX to OpenVINO IR\n!mo --framework=onnx --data_type=FP16 --input_shape=[1,3,32,32] -m $onnx_model_path --output_dir $MODEL_DIR", "_____no_output_____" ] ], [ [ "## Define Data Loader\nAt this step the `DataLoader` interface from POT API is implemented.", "_____no_output_____" ] ], [ [ "transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))])\ndataset = CIFAR10(root=DATA_DIR, train=False, transform=transform, download=True)", "_____no_output_____" ], [ "# create DataLoader from CIFAR10 dataset\nclass CifarDataLoader(DataLoader):\n\n def __init__(self, config):\n \"\"\"\n Initialize config and dataset.\n :param config: created config with DATA_DIR path.\n \"\"\"\n if not isinstance(config, Dict):\n config = Dict(config)\n super().__init__(config)\n self.indexes, self.pictures, self.labels = self.load_data(dataset)\n \n def __len__(self):\n return len(self.labels)\n\n def __getitem__(self, index):\n \"\"\"\n Return one sample of index, label and picture.\n :param index: index of the taken sample.\n \"\"\"\n if index >= len(self):\n raise IndexError\n\n return (self.indexes[index], self.labels[index]), self.pictures[index].numpy()\n\n def load_data(self, dataset):\n \"\"\"\n Load dataset in needed format. \n :param dataset: downloaded dataset.\n \"\"\"\n pictures, labels, indexes = [], [], []\n \n for idx, sample in enumerate(dataset):\n pictures.append(sample[0])\n labels.append(sample[1])\n indexes.append(idx)\n\n return indexes, pictures, labels", "_____no_output_____" ] ], [ [ "## Define Accuracy Metric Calculation\nAt this step the `Metric` interface for accuracy Top-1 metric is implemented. It is used for validating accuracy of quantized model.", "_____no_output_____" ] ], [ [ "# Custom implementation of classification accuracy metric.\n\nclass Accuracy(Metric):\n\n # Required methods\n def __init__(self, top_k=1):\n super().__init__()\n self._top_k = top_k\n self._name = 'accuracy@top{}'.format(self._top_k)\n self._matches = []\n\n @property\n def value(self):\n \"\"\" Returns accuracy metric value for the last model output. \"\"\"\n return {self._name: self._matches[-1]}\n\n @property\n def avg_value(self):\n \"\"\" Returns accuracy metric value for all model outputs. \"\"\"\n return {self._name: np.ravel(self._matches).mean()}\n\n def update(self, output, target):\n \"\"\" Updates prediction matches.\n :param output: model output\n :param target: annotations\n \"\"\"\n if len(output) > 1:\n raise Exception('The accuracy metric cannot be calculated '\n 'for a model with multiple outputs')\n if isinstance(target, dict):\n target = list(target.values())\n predictions = np.argsort(output[0], axis=1)[:, -self._top_k:]\n match = [float(t in predictions[i]) for i, t in enumerate(target)]\n\n self._matches.append(match)\n\n def reset(self):\n \"\"\" Resets collected matches \"\"\"\n self._matches = []\n\n def get_attributes(self):\n \"\"\"\n Returns a dictionary of metric attributes {metric_name: {attribute_name: value}}.\n Required attributes: 'direction': 'higher-better' or 'higher-worse'\n 'type': metric type\n \"\"\"\n return {self._name: {'direction': 'higher-better',\n 'type': 'accuracy'}}", "_____no_output_____" ] ], [ [ "## Run Quantization Pipeline and compare the accuracy of the original and quantized models\nHere we define a configuration for our quantization pipeline and run it. \n\nNOTE: we use built-in `IEEngine` implementation of the `Engine` interface from the POT API for model inference. `IEEngine` is built on top of OpenVINO Python* API for inference and provides basic functionality for inference of simple models. If you have a more complicated inference flow for your model/models you should create your own implementation of `Engine` interface, for example by inheriting from `IEEngine` and extending it.", "_____no_output_____" ] ], [ [ "model_config = Dict({\n 'model_name': 'mobilenet_v2',\n 'model': ir_model_xml,\n 'weights': ir_model_bin\n})\nengine_config = Dict({\n 'device': 'CPU',\n 'stat_requests_number': 2,\n 'eval_requests_number': 2\n})\ndataset_config = {\n 'data_source': DATA_DIR\n}\nalgorithms = [\n {\n 'name': 'DefaultQuantization',\n 'params': {\n 'target_device': 'CPU',\n 'preset': 'performance',\n 'stat_subset_size': 300\n }\n }\n]\n\n# Steps 1-7: Model optimization\n# Step 1: Load the model.\nmodel = load_model(model_config)\n\n# Step 2: Initialize the data loader.\ndata_loader = CifarDataLoader(dataset_config)\n\n# Step 3 (Optional. Required for AccuracyAwareQuantization): Initialize the metric.\nmetric = Accuracy(top_k=1)\n\n# Step 4: Initialize the engine for metric calculation and statistics collection.\nengine = IEEngine(engine_config, data_loader, metric)\n\n# Step 5: Create a pipeline of compression algorithms.\npipeline = create_pipeline(algorithms, engine)\n\n# Step 6: Execute the pipeline.\ncompressed_model = pipeline.run(model)\n\n# Step 7 (Optional): Compress model weights quantized precision\n# in order to reduce the size of final .bin file.\ncompress_model_weights(compressed_model)\n\n# Step 8: Save the compressed model to the desired path.\ncompressed_model_paths = save_model(model=compressed_model, save_path=MODEL_DIR, model_name=\"quantized_mobilenet_v2\"\n)\ncompressed_model_xml = compressed_model_paths[0][\"model\"]\ncompressed_model_bin = Path(compressed_model_paths[0][\"model\"]).with_suffix(\".bin\")\n\n# Step 9: Compare accuracy of the original and quantized models.\nmetric_results = pipeline.evaluate(model)\nif metric_results:\n for name, value in metric_results.items():\n print(f\"Accuracy of the original model: {name}: {value}\")\n\nmetric_results = pipeline.evaluate(compressed_model)\nif metric_results:\n for name, value in metric_results.items():\n print(f\"Accuracy of the optimized model: {name}: {value}\")", "_____no_output_____" ] ], [ [ "## Compare Performance of the Original and Quantized Models\n\nFinally, we will measure the inference performance of the FP32 and INT8 models. To do this, we use [Benchmark Tool](https://docs.openvinotoolkit.org/latest/openvino_inference_engine_tools_benchmark_tool_README.html) - OpenVINO's inference performance measurement tool.\n\nNOTE: For more accurate performance, we recommended running benchmark_app in a terminal/command prompt after closing other applications. Run benchmark_app -m model.xml -d CPU to benchmark async inference on CPU for one minute. Change CPU to GPU to benchmark on GPU. Run benchmark_app --help to see an overview of all command line options.\n", "_____no_output_____" ] ], [ [ "# Inference FP16 model (IR)\n!benchmark_app -m $ir_model_xml -d CPU -api async", "_____no_output_____" ], [ "# Inference INT8 model (IR)\n!benchmark_app -m $compressed_model_xml -d CPU -api async", "_____no_output_____" ] ], [ [ "## Compare results on four pictures.", "_____no_output_____" ] ], [ [ "ie = Core()\n\n# read and load float model\nfloat_model = ie.read_model(\n model=ir_model_xml, weights=ir_model_bin\n)\nfloat_compiled_model = ie.compile_model(model=float_model, device_name=\"CPU\")\n\n# read and load quantized model\nquantized_model = ie.read_model(\n model=compressed_model_xml, weights=compressed_model_bin\n)\nquantized_compiled_model = ie.compile_model(model=quantized_model, device_name=\"CPU\")", "_____no_output_____" ], [ "# define all possible labels from CIFAR10\nlabels_names = [\"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\", \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"]\nall_pictures = []\nall_labels = []\n\n# get all pictures and their labels \nfor i, batch in enumerate(data_loader):\n all_pictures.append(batch[1])\n all_labels.append(batch[0][1])", "_____no_output_____" ], [ "def plot_pictures(indexes: list, all_pictures=all_pictures, all_labels=all_labels):\n \"\"\"Plot 4 pictures.\n :param indexes: a list of indexes of pictures to be displayed.\n :param all_batches: batches with pictures.\n \"\"\"\n images, labels = [], []\n num_pics = len(indexes)\n assert num_pics == 4, f'No enough indexes for pictures to be displayed, got {num_pics}'\n for idx in indexes:\n assert idx < 10000, 'Cannot get such index, there are only 10000'\n pic = np.rollaxis(all_pictures[idx].squeeze(), 0, 3)\n images.append(pic)\n\n labels.append(labels_names[all_labels[idx]])\n\n f, axarr = plt.subplots(1, 4)\n axarr[0].imshow(images[0])\n axarr[0].set_title(labels[0])\n\n axarr[1].imshow(images[1])\n axarr[1].set_title(labels[1])\n\n axarr[2].imshow(images[2])\n axarr[2].set_title(labels[2])\n\n axarr[3].imshow(images[3])\n axarr[3].set_title(labels[3])", "_____no_output_____" ], [ "def infer_on_pictures(model, indexes: list, all_pictures=all_pictures):\n \"\"\" Inference model on a few pictures.\n :param net: model on which do inference\n :param indexes: list of indexes \n \"\"\"\n predicted_labels = []\n request = model.create_infer_request()\n for idx in indexes:\n assert idx < 10000, 'Cannot get such index, there are only 10000'\n request.infer(inputs={'input.1': all_pictures[idx][None,]})\n result = request.get_output_tensor(0).data\n result = labels_names[np.argmax(result[0])]\n predicted_labels.append(result)\n return predicted_labels", "_____no_output_____" ], [ "indexes_to_infer = [7, 12, 15, 20] # to plot specify 4 indexes\n\nplot_pictures(indexes_to_infer)\n\nresults_float = infer_on_pictures(float_compiled_model, indexes_to_infer)\nresults_quanized = infer_on_pictures(quantized_compiled_model, indexes_to_infer)\n\nprint(f\"Labels for picture from float model : {results_float}.\")\nprint(f\"Labels for picture from quantized model : {results_quanized}.\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4aecd77b2ec07035152c7399b986b4e57f1908bb
2,598
ipynb
Jupyter Notebook
jupyter-notebooks/environment/setup.ipynb
agnathan/lab-opencv-examples
dc531ad274e99c1319ee6cf5549604b09b5f1d84
[ "MIT" ]
5
2017-07-27T18:24:54.000Z
2021-06-13T17:59:00.000Z
jupyter-notebooks/environment/setup.ipynb
agnathan/lab-opencv-examples
dc531ad274e99c1319ee6cf5549604b09b5f1d84
[ "MIT" ]
null
null
null
jupyter-notebooks/environment/setup.ipynb
agnathan/lab-opencv-examples
dc531ad274e99c1319ee6cf5549604b09b5f1d84
[ "MIT" ]
3
2017-11-29T20:57:03.000Z
2018-05-24T10:08:41.000Z
25.98
152
0.617398
[ [ [ "## Setup the Jupyter Notebook Lab Environment", "_____no_output_____" ] ], [ [ "from colors import *", "_____no_output_____" ], [ "%run 'environment/global.ipynb'", "ERROR:root:File `'environment/global.ipynb.py'` not found.\n" ] ], [ [ "## Setup Lab Specific Environment", "_____no_output_____" ] ], [ [ "caffe_model_path = verify(os.path.join(openvino_install_path, \"deployment_tools/model_downloader/object_detection/common/mobilenet-ssd/caffe/\"))", "_____no_output_____" ], [ "print(color('Initializing lab specific environment variables', fg='blue', style='bold'))\n%env test = $openvino_root_directory\n%env CAFFE_MODELS = /opt/intel/computer_vision_sdk/deployment_tools/model_downloader/object_detection/common/mobilenet-ssd/caffe/\n%env LAB = /home/upsquared/labs/smart-video-workshop/object-detection/\n%env OPENVINO_OBJECT_DETCTION_EXAMPLE = /opt/intel/computer_vision_sdk/deployment_tools/inference_engine/samples/object-detection/", "\u001b[34;1mInitializing lab specific environment variables\u001b[0m\nenv: test=$openvino_root_directory\nenv: CAFFE_MODELS=/opt/intel/computer_vision_sdk/deployment_tools/model_downloader/object_detection/common/mobilenet-ssd/caffe/\nenv: LAB=/home/upsquared/labs/smart-video-workshop/object-detection/\nenv: OPENVINO_OBJECT_DETCTION_EXAMPLE=/opt/intel/computer_vision_sdk/deployment_tools/inference_engine/samples/object-detection/\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4aecdaba5e4abaf30108911c63ac98e773f29b18
58,083
ipynb
Jupyter Notebook
applications/notebooks/stable/kmeans_wssse.ipynb
phenology/infrastructure
ef4398786984cd8bb652df5883348ce54aafb831
[ "Apache-2.0" ]
2
2017-06-21T15:35:37.000Z
2018-03-29T09:04:46.000Z
applications/notebooks/stable/kmeans_wssse.ipynb
phenology/infrastructure
ef4398786984cd8bb652df5883348ce54aafb831
[ "Apache-2.0" ]
50
2017-04-10T09:03:25.000Z
2018-04-06T07:11:51.000Z
applications/notebooks/stable/kmeans_wssse.ipynb
phenology/infrastructure
ef4398786984cd8bb652df5883348ce54aafb831
[ "Apache-2.0" ]
1
2021-06-29T17:24:09.000Z
2021-06-29T17:24:09.000Z
59.147658
18,871
0.637398
[ [ [ "# Connect to Spark\n\nIn this NoteBook we read wssse values and we plot them. \n\n<span style=\"color:red\">It is necessary you first run [create_wssse_csv](create_wssse_csv.ipynb).</span>.\n", "_____no_output_____" ], [ "## Dependencies", "_____no_output_____" ] ], [ [ "#Add all dependencies to PYTHON_PATH\nimport sys\nsys.path.append(\"/usr/lib/spark/python\")\nsys.path.append(\"/usr/lib/spark/python/lib/py4j-0.10.4-src.zip\")\nsys.path.append(\"/usr/lib/python3/dist-packages\")\n\n#Define environment variables\nimport os\nos.environ[\"HADOOP_CONF_DIR\"] = \"/etc/hadoop/conf\"\nos.environ[\"PYSPARK_PYTHON\"] = \"python3\"\nos.environ[\"PYSPARK_DRIVER_PYTHON\"] = \"ipython\"\n\n#Load PySpark to connect to a Spark cluster\nfrom pyspark import SparkConf, SparkContext\n\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql.types import *\nfrom pyspark.sql import DataFrameReader\nfrom pyspark.sql import SparkSession\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## Create Spark Context", "_____no_output_____" ] ], [ [ "appName = \"kmeans_wssse\"\nmasterURL=\"spark://pheno0.phenovari-utwente.surf-hosted.nl:7077\"\n\n#A context needs to be created if it does not already exist\ntry:\n sc.stop()\nexcept NameError:\n print(\"A new Spark Context will be created.\")\n \nsc = SparkContext(conf = SparkConf().setAppName(appName).setMaster(masterURL))\n\nsqlContext = SQLContext(sc)\n\nspark = SparkSession.builder \\\n .master(masterURL) \\\n .appName(appName) \\\n .getOrCreate;\n \n#OR\n#spark = SparkSession.builder.config(conf)", "A new Spark Context will be created.\n" ] ], [ [ "## Read Data", "_____no_output_____" ] ], [ [ "#offline_dir_path = \"hdfs:///user/pheno/avhrr/\"\noffline_dir_path = \"hdfs:///user/pheno/spring-index/\"\n#geoTiff_dir = \"SOST\"\ngeoTiff_dir = \"BloomFinal\"\nwssse_csv_path = offline_dir_path + geoTiff_dir + \"/wssse.csv\"\n \n \ncsvDf = sqlContext.read.format(\"csv\").option(\"header\", \"false\").option(\"inferschema\", \"true\").option(\"mode\", \"DROPMALFORMED\").load(wssse_csv_path) \ndf = csvDf.toPandas()", "_____no_output_____" ] ], [ [ "## Plot WSSSE", "_____no_output_____" ] ], [ [ "res = df[['_c0', '_c2']].as_matrix()", "_____no_output_____" ], [ "%matplotlib notebook\n\nplt.plot(res[:,0],res[:,1])\nplt.show()", "_____no_output_____" ] ], [ [ "## Close Spark Context", "_____no_output_____" ] ], [ [ "sc.stop()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4aece548613b7e120a29973d77ce47993bcfa250
28,074
ipynb
Jupyter Notebook
docs/users/workshops/FY21_workshop/2_plio_analysis.ipynb
gsn9/autocnet
ddcca3ce3a6b59f720804bb3da03857efa4ff534
[ "CC0-1.0" ]
17
2016-11-21T17:07:18.000Z
2022-01-16T06:14:04.000Z
docs/users/workshops/FY21_workshop/2_plio_analysis.ipynb
gsn9/autocnet
ddcca3ce3a6b59f720804bb3da03857efa4ff534
[ "CC0-1.0" ]
504
2015-12-17T18:46:11.000Z
2021-12-17T19:19:49.000Z
docs/users/workshops/FY21_workshop/2_plio_analysis.ipynb
gsn9/autocnet
ddcca3ce3a6b59f720804bb3da03857efa4ff534
[ "CC0-1.0" ]
42
2015-12-09T15:30:15.000Z
2022-02-24T04:47:46.000Z
33.58134
387
0.611562
[ [ [ "# Using PLIO to analyze control networks\nPLIO is a general purpose library for reading data from various sources. In this workshop, we will be using PLIO's ability to read ISIS control networks into a Pandas dataframe.", "_____no_output_____" ] ], [ [ "# PLIO uses pysis for some other things. We don't technically need this but it avoids a warning.\nimport os\nos.environ['ISISROOT'] = '/usgs/cpkgs/anaconda3_linux/envs/isis4.3.0'\nos.environ['ISISDATA'] = '/usgs/cpkgs/isis3/isis_data'\n\n# 3D plotting toolkit for matplotlib\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Numerical Python library\nimport numpy as np", "_____no_output_____" ] ], [ [ "# Our networks\nAll of this data was generously provided by Lynn Weller and Mike Bland from their Europa control project.\n\nThe first network is a very rough starting point. The Galileo images of Europa were put through the [findfeatures](https://isis.astrogeology.usgs.gov/Application/presentation/Tabbed/findfeatures/findfeatures.html) application and then all of the resulting networks were merged together. This network has many known issues including islands, massive residuals, and poor coverage.\n\nThe second network is the final network containing Galileo and Voyager images of Europa. The issues from the initial network have been resolved and the final point cloud covers the majority of the body.", "_____no_output_____" ] ], [ [ "galileo_net = '/scratch/jmapel/europa/networks/GLL_FFCombined_thin_SubReg2_Del_2.net'\nfinal_net = '/scratch/jmapel/europa/networks/GalileoVoyager_Europa_Merged_2020_CilixFree.net'", "_____no_output_____" ] ], [ [ "# The control network dataframe\n\nPLIO directly ingests the data from the control network file. Each row in the dataframe is a single control measure and each column is a field from the protobuf control network. The data for control points is stored implicitly in its measures.", "_____no_output_____" ] ], [ [ "# This function is what reads a control network file\nfrom plio.io.io_controlnetwork import from_isis\n\ngalileo_df = from_isis(galileo_net)\ngalileo_df.describe()", "_____no_output_____" ] ], [ [ "### Exercise: How many measures are there in the network? How many points are there in the network? How many images are there in the network?\n\ntip: use len(dataframe) to find the number of rows in a dataframe\n\ntip: use dataframe[\"columnName\"].nunique() to find the number of unique values in a column", "_____no_output_____" ], [ "## Data types\nThe different columns of our dataframe store different types of data. The cell below shows all of the the data types in the dataframe. You can see all of the different possible datatypes for a dataframe in the [pandas docs](https://pandas.pydata.org/pandas-docs/stable/user_guide/basics.html#basics-dtypes).", "_____no_output_____" ] ], [ [ "galileo_df.dtypes", "_____no_output_____" ] ], [ [ "Most of the data types are straightforward. For example, the line and sample are 64-bit floats. Let's dig into the more unusual types.", "_____no_output_____" ], [ "**pointType, measureType, aprioriSurfPointSource, and aprioriRadiusSource** are 64 bit integers, but those integers correspond to enumerations. For example, a pointType of 2 means Free. See the tables below for all of the enumerations", "_____no_output_____" ] ], [ [ "galileo_df[['pointType', 'measureType', 'aprioriSurfPointSource']].head()", "_____no_output_____" ] ], [ [ "<center>**pointType**</center>\n\n| Value | Name |\n| ----: | :---------------- |\n| 0 | Tie (obsolete) |\n| 1 | Ground (obsolete) |\n| 2 | Free |\n| 3 | Constrained |\n| 4 | Fixed |", "_____no_output_____" ], [ "<center>**measureType**</center>\n\n| Value | Name |\n| ----: | :----------------- |\n| 0 | Candidate |\n| 1 | Manual |\n| 2 | RegisteredPixel |\n| 3 | RegisteredSubPixel |", "_____no_output_____" ], [ "<center>**aprioriSurfPointSource & aprioriRadiusSource **</center>\n\n| Value | Name |\n| ----: | :---------------- |\n| 0 | None |\n| 1 | User |\n| 2 | AverageOfMeasures |\n| 3 | Reference |\n| 4 | Ellipsoid |\n| 5 | DEM |\n| 6 | Basemap |\n| 7 | BundleSolution |", "_____no_output_____" ], [ "### Exercise: Have any measure in this network been sub-pixel registered?\n\ntip: look at the measure types", "_____no_output_____" ], [ "**id, pointChoosername, pointDatetime, aprioriSurfPointSourceFile, aprioriRadiusSourceFile, serialnumber, measureChoosername, and measureDatetime** are all listed as objects but are simply strings.", "_____no_output_____" ] ], [ [ "galileo_df[['id', 'serialnumber', 'pointChoosername', 'pointDatetime', 'measureChoosername', 'measureDatetime']].head()", "_____no_output_____" ] ], [ [ "**adjustedCovar, pointLog, and measureLog** are more complicated. We will go over adjustedCovar later with the final Euroap network. pointLog is leftover from older network formats and can be ignored. measureLog contains information about the registration of the measure.", "_____no_output_____" ] ], [ [ "galileo_df.loc[1,'measureLog']", "_____no_output_____" ] ], [ [ "## Data availability\nDepending on how your network was generated and what processing has been done, many fields will not be set. If a numerical field has a value of 0, then it has not been set. For example, our network has not been bundle adjusted, so there are only a priori ground points.", "_____no_output_____" ] ], [ [ "galileo_df[['aprioriX', 'aprioriY', 'aprioriZ', 'adjustedX', 'adjustedY', 'adjustedZ']].describe()", "_____no_output_____" ] ], [ [ "### Exercise: Can you find all of the fields that are completely unset in our control network?\n\ntip: numerical fields default to 0, strings default to an empty string \"\", and boolean values default to False.", "_____no_output_____" ], [ "You can also check which columns are default programmaticaly. The following cell checks if all of the values in a column are a default value.", "_____no_output_____" ] ], [ [ "(galileo_df==0).all() | (galileo_df==\"\").all() | (galileo_df==False).all()", "_____no_output_____" ] ], [ [ "# Looking at a bundle adjusted control network\n\nOur Galileo network is interesting but networks have significantly more useful information in them after bundle adjustment. So, let's take a look at the final Europa network.", "_____no_output_____" ] ], [ [ "final_net_df = from_isis(final_net)\nfinal_net_df.describe()", "_____no_output_____" ] ], [ [ "### Exercise: What fields are set in the bundle adjusted network that weren't previously?", "_____no_output_____" ], [ "## Analyzing the measures\nThe data in a control network dataframe is not always in the format we want to work with. The measure residuals are broken down into the line and sample residuals. The following cell computes the full magnitude of the residuals and adds it to the dataframe under the \"residualMag\" column.", "_____no_output_____" ] ], [ [ "final_net_df['residualMag'] = np.sqrt(final_net_df['sampleResidual']**2 + final_net_df['lineResidual']**2)", "_____no_output_____" ] ], [ [ "Now let's plot the residuals and see if we can form any theories. The next cell imports matplotlib for plotting tools and then plots the residuals in terms of sample and line residual. Note that the color of points is based on the residual magnitude, whcih should give a nice bullseye effect.", "_____no_output_____" ] ], [ [ "# This allows us to interact with our plots. This must be set before importing pyplot\n%matplotlib notebook\n\n# General plotting library\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nresid_fig = plt.figure(figsize=(6, 6))\nresid_ax = resid_fig.add_subplot(111)\nresid_scatter = resid_ax.scatter(final_net_df['sampleResidual'], final_net_df['lineResidual'], c=final_net_df['residualMag'], marker='+')\nresid_ax.set_aspect('equal')\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\nresid_cbar = plt.colorbar(resid_scatter)\nresid_fig.suptitle('Bundle Adjusted Measure Residuals')\nresid_ax.set_xlabel('Sample Residual')\nresid_ax.set_ylabel('Line Residual')\nresid_cbar.set_label('Residual Magnitude')\nplt.show()", "_____no_output_____" ] ], [ [ "We can also color our points based on other properties. Let's try and separate the measures out by mission. The serial numbers should help us so let's look at the serial numbers for all of our images.", "_____no_output_____" ] ], [ [ "final_net_df['serialnumber'].unique()", "_____no_output_____" ] ], [ [ "Each serial number starts with the mission name, which makes separating them out easy. All we need to do is check if the beginning of the serial number matches our mission.\n\nThe pd.DataFrame.str package allows us to do this type of string comparisons quickly and easily. Here we will use the DataFrame.str.startswith method.", "_____no_output_____" ] ], [ [ "final_galileo_df = final_net_df[final_net_df['serialnumber'].str.startswith('Galileo')]\nfinal_voyager1_df = final_net_df[final_net_df['serialnumber'].str.startswith('Voyager1')]\nfinal_voyager2_df = final_net_df[final_net_df['serialnumber'].str.startswith('Voyager2')]", "_____no_output_____" ] ], [ [ "Now let's plot the measures and color them based on their mission.", "_____no_output_____" ] ], [ [ "inst_resid_fig = plt.figure(figsize=(6, 6))\ninst_resid_ax = inst_resid_fig.add_subplot(111)\ninst_resid_ax.scatter(final_galileo_df['sampleResidual'], final_galileo_df['lineResidual'], color='Green', marker='+', alpha=0.25, label='Galileo')\ninst_resid_ax.scatter(final_voyager1_df['sampleResidual'], final_voyager1_df['lineResidual'], color='Red', marker='+', alpha=0.25, label='Voyager1')\ninst_resid_ax.scatter(final_voyager2_df['sampleResidual'], final_voyager2_df['lineResidual'], color='Blue', marker='+', alpha=0.25, label='Voyager2')\ninst_resid_ax.set_aspect('equal')\nplt.axhline(0, color='black')\nplt.axvline(0, color='black')\nplt.legend()\ninst_resid_fig.suptitle('Bundle Adjusted Measure Residuals by Mission')\ninst_resid_ax.set_xlabel('Sample Residual')\ninst_resid_ax.set_ylabel('Line Residual')\nplt.show()", "_____no_output_____" ] ], [ [ "### What can you say about the residuals for the different missions based on our plot?", "_____no_output_____" ], [ "### Exercise: What the descriptive statistics for the residual magnitude of the Galileo measures? What about for Voyager 1 and Voyager 2?", "_____no_output_____" ] ], [ [ "final_galileo_df['residualMag'].describe()", "_____no_output_____" ], [ "final_voyager1_df['residualMag'].describe()", "_____no_output_____" ], [ "final_voyager2_df['residualMag'].describe()", "_____no_output_____" ] ], [ [ "### Do you notice anything interesting about the residual magnitudes for the different instruments? How does this compare to what you noticed with the scatter plot?", "_____no_output_____" ], [ "We can even test if the measure residuals are normally distributed. The following cell performs a chi-squared test to see if the residual magnitudes could reasonably come from a normal distribution. This is important because it will tell us if we have large blunders in our network or systematic error from something like a bad sensor model.", "_____no_output_____" ] ], [ [ "# Statistics library\nfrom scipy import stats\n\nalpha = 1e-3 # 99.999% confidence\n_, normal_test_result = stats.normaltest(final_voyager1_df['residualMag'])\nprint(f'Chi-squared test statistic: {normal_test_result}')\nif (normal_test_result < alpha):\n print(\"The residuals are normally distributed\")\nelse:\n print(\"The residuals may not be normally distributed\")", "_____no_output_____" ] ], [ [ "## Analyzing the points\nThe information for control points is duplicated for each measure they have. So, the first step in looking at control point data is to extract only the data we want from the dataframe. This will make the dataframe easier to read and it will make things run quicker.\n\nTo do this, we're going to first extract all of the columns with point data. Then, we're going extract the first measure from each point. After all is said and done, we will have a dataframe with columns related to the point info and only one row for each point.", "_____no_output_____" ] ], [ [ "point_columns = ['id',\n 'pointType',\n 'pointChoosername',\n 'pointDatetime',\n 'pointEditLock',\n 'pointIgnore',\n 'pointJigsawRejected',\n 'aprioriSurfPointSource',\n 'aprioriSurfPointSourceFile',\n 'aprioriRadiusSource',\n 'aprioriRadiusSourceFile',\n 'latitudeConstrained',\n 'longitudeConstrained',\n 'radiusConstrained',\n 'aprioriX',\n 'aprioriY',\n 'aprioriZ',\n 'aprioriCovar',\n 'adjustedX',\n 'adjustedY',\n 'adjustedZ',\n 'adjustedCovar',\n 'pointLog']\nfinal_points_df = final_net_df[point_columns].drop_duplicates('id')\nfinal_points_df.describe()", "_____no_output_____" ] ], [ [ "Next, we're going to transform the point data so that it's more useful to us. This cell will take the (X, Y, Z) adjusted ground points and convert them to (lat, lon, radius) using a library called pyproj. pyproj is a very powerful projections library and can do many cartofraphic transformations and projections.\n\n**Note: This cell will generate a warning because we are using old pyproj.Proj calls which will eventually need to change. For now we can ignore the warning.**", "_____no_output_____" ] ], [ [ "# Projection library for switching between rectangular and latitudinal\nos.environ['PROJ_LIB'] = '/usgs/cpkgs/anaconda3_linux/envs/autocnet/share/proj'\nimport pyproj\n\n# Compute the lat/lon/alt\neuropa_radii = [1562600, 1560300, 1559500]\necef = pyproj.Proj(proj='geocent', a=europa_radii[0], b=europa_radii[1], c=europa_radii[2])\nlla = pyproj.Proj(proj='latlong', a=europa_radii[0], b=europa_radii[1], c=europa_radii[2])\nlon, lat, alt = pyproj.transform(ecef, lla, final_points_df['adjustedX'].values, final_points_df['adjustedY'].values, final_points_df['adjustedZ'].values, radians=True)\n\n# Store the data in the dataframe\nfinal_points_df['latitude'] = lat\nfinal_points_df['longitude'] = lon\nfinal_points_df['altitude'] = alt\n\n# We will also want the point radii\nfinal_points_df['radius'] = np.sqrt(final_points_df['adjustedX']**2 + final_points_df['adjustedY']**2 + final_points_df['adjustedZ']**2)", "_____no_output_____" ] ], [ [ "Because of how we defined our projection, the latitude and longitude values will be in radians. Also, the longitude will be in 180 postiive East. You can change this by modifying how you use pyproj but that is outside of this workshop.", "_____no_output_____" ] ], [ [ "final_points_df[[\"latitude\", \"longitude\", \"altitude\", \"radius\"]].describe()", "_____no_output_____" ] ], [ [ "### Exercise: Convert the latitude and longitude from radians to degrees:", "_____no_output_____" ], [ "Similar to how we computed the residual magnitude, we want to compute the average residual magnitude for each point. The following cell goes back to our original dataframe, computes the mean point by point, and then saves all of the results in our new dataframe.\n\n**Note: This cell can take a while to run because it has to re-access the dataframe for every point**", "_____no_output_____" ] ], [ [ "final_points_df[\"averageResidual\"] = 0\nfor point_id, group in final_net_df.groupby('id'):\n final_points_df.loc[final_points_df.id == point_id, \"averageResidual\"] = group['residualMag'].mean()", "_____no_output_____" ] ], [ [ "### Exercise: What is the 95th percentile for the average residuals?", "_____no_output_____" ], [ "## Plotting the points\nNow that we have latitudes and longitudes for each point, we can generate some simple plots to look at them.", "_____no_output_____" ] ], [ [ "point_map = plt.figure(figsize=(10, 10))\npoint_ax = point_map.add_subplot(111)\npoint_ax.scatter(final_points_df[\"longitude\"], final_points_df[\"latitude\"], marker='+')\npoint_map.suptitle('Control Points')\npoint_ax.set_xlabel('Longitude')\npoint_ax.set_ylabel('Latitude')\nplt.show()", "_____no_output_____" ] ], [ [ "It can also be helpful to color the points based on different values. The following cell draws the same plot but colors each point based on its average residual. Because the residuals are not uniformly distributed we also apply a lograithmic scale to the colors that you can see in the colorbar.", "_____no_output_____" ] ], [ [ "point_resid_map = plt.figure(figsize=(10, 10))\npoint_resid_ax = point_resid_map.add_subplot(111)\npoint_resid_norm = matplotlib.colors.LogNorm(vmax=final_points_df[\"averageResidual\"].max())\npoint_resid_scatter = point_resid_ax.scatter(final_points_df[\"longitude\"], final_points_df[\"latitude\"], c=final_points_df[\"averageResidual\"], alpha=0.5, norm=point_resid_norm, marker='+', cmap=plt.get_cmap('plasma'))\npoint_resid_cbar = plt.colorbar(point_resid_scatter)\npoint_resid_map.suptitle('Control Points')\npoint_resid_ax.set_xlabel('Longitude')\npoint_resid_ax.set_ylabel('Latitude')\npoint_resid_cbar.set_label('Average Residual Magnitude')\nplt.show()", "_____no_output_____" ] ], [ [ "Plotting individual points can be helpful getting a general idea for the distribution of the points, but it can be hard to interpret the data in area where there are many points all ontop of each other. So, let's combine near by points and determine the residual based on the region.\n\nTo do this, we're going to bin the points into a regular grid across the latitude and longitude and then compute the mean within each bin.\n\n**Try changing the grid_step value and re-running the two cells**", "_____no_output_____" ] ], [ [ "grid_step = 10\n\nfinal_points_df['lonBin'] = final_points_df['longitude'].apply(lambda x: [e for e in range(-180, 180, grid_step) if e <= x][-1])\nfinal_points_df['latBin'] = final_points_df['latitude'].apply(lambda x: [e for e in range(-90, 90, grid_step) if e <= x][-1])\n\navg_resid_binned = final_points_df.groupby(['lonBin', 'latBin'])['averageResidual'].mean()\n\nfilled_data = []\nfor lon_bin in range(-180, 180, grid_step):\n for lat_bin in range(-90, 90, grid_step):\n try:\n filled_data.append(avg_resid_binned.loc[lon_bin, lat_bin])\n except:\n filled_data.append(0)\nfilled_data = np.array(filled_data).reshape((int(360/grid_step), int(180/grid_step))).T", "_____no_output_____" ], [ "avg_gridded = plt.figure(figsize=(10, 5))\navg_gridded_ax = avg_gridded.add_subplot(111)\navg_gridded_plot = avg_gridded_ax.imshow(filled_data, origin='lower', extent= [-180, 180, -90, 90], cmap=plt.get_cmap('plasma'))\navg_gridded_ax.scatter(final_points_df[\"longitude\"], final_points_df[\"latitude\"], color='black', marker='+', alpha=0.1)\navg_gridded_cbar = plt.colorbar(avg_gridded_plot)\navg_gridded.suptitle('Average Residual by lat/lon grid')\navg_gridded_ax.set_xlabel('Longitude')\navg_gridded_ax.set_ylabel('Latitude')\navg_gridded_cbar.set_label('Average Residual Magnitude')\nplt.show()", "_____no_output_____" ] ], [ [ "## 3D Plotting\n2D plotting either requires these simple equal area projections or converting to another projection via pyproj. Instead, let's look at our data in true 3D.\n\nThe following cell plots the same data as before but plots it in 3d instead of just a 2d projection", "_____no_output_____" ] ], [ [ "resid_fig_3d = plt.figure(figsize=(10, 10))\nresid_ax_3d = resid_fig_3d.add_subplot(111, projection='3d')\nresid_plot_3d = resid_ax_3d.scatter(final_points_df['adjustedX'], final_points_df['adjustedY'], final_points_df['adjustedZ'], c=final_points_df[\"averageResidual\"], alpha=0.5, norm=point_resid_norm, marker='+', cmap=plt.get_cmap('plasma'))\nresid_cbar_3d = plt.colorbar(resid_plot_3d)\nresid_fig_3d.suptitle('3D Control Points')\nresid_cbar_3d.set_label('Average Residual Magnitude (pix)')\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", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4aece9f99fe65fc64802039db704d7678f2929d0
300,224
ipynb
Jupyter Notebook
InTravel_Plot.ipynb
netlabufjf/Evo-Scripts
e0edde1fed3a9330674e92bafba7efcec24be18f
[ "MIT" ]
1
2020-04-22T02:26:45.000Z
2020-04-22T02:26:45.000Z
InTravel_Plot.ipynb
netlabufjf/Evo-Scripts
e0edde1fed3a9330674e92bafba7efcec24be18f
[ "MIT" ]
null
null
null
InTravel_Plot.ipynb
netlabufjf/Evo-Scripts
e0edde1fed3a9330674e92bafba7efcec24be18f
[ "MIT" ]
null
null
null
248.735708
89,826
0.899878
[ [ [ "%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport datetime\nimport pytz", "_____no_output_____" ], [ "columns = ['Capture_time', 'Id']\ndata = pd.read_csv('evo_data_menor.csv', usecols=columns, nrows=500000)", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ], [ "print(datetime.datetime.now())\n\n# Colleting vehicle ids\ncar_ids = list(data.Id.unique())\n\nprint(datetime.datetime.now())\n\n# Removing uncommon ids\n# Ex: 4c5865a3-4b03-40f6-a3a8-d4e94aae3b17\ncar_ids = [id for id in car_ids if id.find('-') == -1]", "2018-08-18 12:37:05.280678\n2018-08-18 12:37:05.326488\n" ], [ "def str_to_datetime(df_time):\n \"\"\" \n Reformatando de string para datetime.\n \n Parameters\n ----------\n df_time : pandas.DataFrame, string\n Dataframe com strings a serem convertidas para datetime.\n \n Returns\n ----------\n date_list : pandas.DataFrame, datetime\n Dataframe com valores em datetime para possíveis fusos de Vancouver.\n \n \"\"\"\n date_list = []\n \n # Formatos de fuso horário comum de Vancouver e \n # fuso horário característico de horário de verão\n format_string = ['%Y-%m-%d %H:%M:%S.%f-08:00', '%Y-%m-%d %H:%M:%S.%f-07:00',\n '%Y-%m-%d %H:%M:%S-08:00', '%Y-%m-%d %H:%M:%S-07:00']\n \n \n for date in df_time:\n for fmt in format_string:\n try:\n date_list.append(datetime.datetime.strptime(str(date), fmt))\n break\n except:\n pass\n \n \n return pd.DataFrame(date_list)", "_____no_output_____" ], [ "data['Capture_time'] = str_to_datetime(data['Capture_time'])", "_____no_output_____" ], [ "data.head()", "_____no_output_____" ], [ "parked = 0\nandando_weekdays = []\nandando_weekends = []\n\ndata = data.sort_index(by='Capture_time')\ndata.index = range(len(data))\nprint(datetime.datetime.now())\n# Percorre todo o dataframe para verificar quantos carros estão andando em dado minuto\nfor i in range(1, len(data)):\n start_time_atual = int(data['Capture_time'].iloc[i].timestamp())\n\n start_time_anterior = int(data['Capture_time'].iloc[i-1].timestamp())\n \n # Enquanto está no mesmo minuto, é analisado se o carro está parado\n if (start_time_atual == start_time_anterior):\n parked += 1\n else:\n # Carros viajando são dados pelo total de carros da frota menos os que estão atualmente estacionados\n in_travel = len(car_ids) - parked\n \n porcentagem = (in_travel/len(car_ids))*100\n \n # Verifica que a data está entre segunda(1) e sexta(5)\n if (int(datetime.datetime.fromtimestamp(start_time_anterior).strftime('%w')) > 0 and \n int(datetime.datetime.fromtimestamp(start_time_anterior).strftime('%w')) < 6):\n andando_weekdays.append([start_time_anterior, in_travel, porcentagem])\n else:\n andando_weekends.append([start_time_anterior, in_travel, porcentagem])\n \n parked = 0\nprint(datetime.datetime.now())\ndfIn_Travel_weekdays = pd.DataFrame(andando_weekdays, columns=['capture_time', 'total_in_travel', 'percentage'])\ndfIn_Travel_weekends = pd.DataFrame(andando_weekends, columns=['capture_time', 'total_in_travel', 'percentage'])", "/home/victor/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:5: FutureWarning: by argument to sort_index is deprecated, pls use .sort_values(by=...)\n \"\"\"\n" ], [ "dfIn_Travel_weekdays.head()", "_____no_output_____" ], [ "def from_timestamp_list(timestamp_list):\n \n datetime_list = []\n \n for date in timestamp_list:\n datetime_list.append(datetime.datetime.fromtimestamp(int(date)))\n \n return pd.DataFrame(datetime_list)", "_____no_output_____" ], [ "# Formatando os dados de unix timestamp para datetime\n\ndfWeekdays = dfIn_Travel_weekdays\n\ndfWeekdays['capture_time'] = from_timestamp_list(dfWeekdays['capture_time']) \n \n \ndfWeekends = dfIn_Travel_weekends\n\ndfWeekends['capture_time'] = from_timestamp_list(dfWeekends['capture_time'])", "_____no_output_____" ], [ "# Plot da porcentagem de carros alocados em dias de semana\nplt.plot(dfWeekdays['capture_time'],dfWeekdays['percentage'])\nplt.gcf().autofmt_xdate()\nplt.show()", "_____no_output_____" ], [ "# Plot da porcentagem de carros alocados em dias de final de semana\nplt.plot(dfWeekends['capture_time'],dfWeekends['percentage'])\nplt.gcf().autofmt_xdate()\nplt.show()", "_____no_output_____" ], [ "dfWeekends.to_csv('weekends.csv', index=False, encoding='utf-8')\ndfWeekdays.to_csv('weekdays.csv', index=False, encoding='utf-8')", "_____no_output_____" ], [ "dfWeekdays = pd.read_csv('plots/weekdays.csv')\ndfWeekends = pd.read_csv('plots/weekends.csv')", "_____no_output_____" ], [ "# Debug\ndfWeekdays.capture_time = pd.to_datetime(dfWeekdays.capture_time)\ndfWeekdays['minute'] = dfWeekdays.capture_time.dt.minute\ndfWeekdays['hour'] = dfWeekdays.capture_time.dt.hour", "_____no_output_____" ], [ "# Outlier importante de ser verificado\ndfWeekdays[(dfWeekdays.hour == 10) & (dfWeekdays.minute == 32)]", "_____no_output_____" ], [ "dfWeekdays['capture_time'] = pd.to_datetime(dfWeekdays['capture_time'])\ndfWeekends['capture_time'] = pd.to_datetime(dfWeekends['capture_time'])", "_____no_output_____" ], [ "def media(df): \n \"\"\"\n Faz a media das porcentagens minuto a minuto de todo o dataset.\n \n Parameters\n ------------\n df : Pandas dataframe\n Dados a serem analisados, com uma coluna dos horários e outra com as porcentagens.\n \n Returns\n ----------\n media : Pandas dataframe\n Dados com a média das porcentagens para 24 horas.\n \n \"\"\"\n minute = []\n\n # Criando um vetor que irá sinalizar a quantidade de minutos corridos até tal registro\n for i in range(len(df)):\n capture_time = df['capture_time'].iloc[i]\n minute.append(capture_time.minute + (capture_time.hour * 60))\n\n # Ordenando o dataset por minutos corridos para facilitar a soma de valores\n df['minute'] = minute\n df = df.sort_values(by=['minute', 'capture_time'])\n \n valores = pd.DataFrame()\n media = []\n for i in range(1,len(df)):\n minute_atual = df['minute'].iloc[i-1]\n minute_proximo = df['minute'].iloc[i]\n\n # Enquanto está no mesmo valor de minutos corridos os valores percentuais \n # são armazenados para ser calculada a média de tal minuto no intervalo de 24h\n if (minute_proximo == minute_atual):\n valores = valores.append([df['percentage'].iloc[i-1]])\n else:\n valores = valores.append([df['percentage'].iloc[i-1]])\n media.append([df['capture_time'].iloc[i-1].strftime('%H:%M'), \n float(valores.mean()), float(valores.std())])\n valores = pd.DataFrame()\n\n media = pd.DataFrame(media, columns=['time', 'mean', 'std'])\n \n return media", "_____no_output_____" ], [ "# Fazendo a média das porcentagens de cada dia\ndfWeekdays = dfWeekdays.sort_values(by='capture_time')\nmediaWeekdays = media(dfWeekdays)\n\ndfWeekends = dfWeekends.sort_values(by='capture_time')\nmediaWeekends = media(dfWeekends)", "_____no_output_____" ], [ "mediaWeekdays.to_csv('mediaWeekdays.csv', index=False, encoding='utf-8')\nmediaWeekends.to_csv('mediaWeekends.csv', index=False, encoding='utf-8')", "_____no_output_____" ], [ "mediaWeekdays = pd.read_csv('plots/mediaWeekdays.csv')\nmediaWeekends = pd.read_csv('plots/mediaWeekends.csv')", "_____no_output_____" ], [ "import numpy as np\n\n# Plot da media das porcentagens dos dias de semana\nfig, ax = plt.subplots()\n# Curva dos carros andando\nax.plot(range(len(mediaWeekdays['time'])),mediaWeekdays['mean'], label='Carros Ocupados')\n\n# Curvas representando o intervalo de desvio padrão\nax.plot(range(len(mediaWeekdays['time'])), mediaWeekdays['mean']+mediaWeekdays['std'], alpha=150, c='gray', label='Desvio Padrão')\nax.plot(range(len(mediaWeekdays['time'])), mediaWeekdays['mean']-mediaWeekdays['std'], alpha=150, c='gray')\n\n# Modificando os labels das horas\nax.xaxis.set_ticks(np.arange(0, 1441, 120))\n\nfig.canvas.draw()\n\nlabels = [item.get_text() for item in ax.get_xticklabels()]\nlabels = range(0,26,2)\n\nax.set_xticklabels(labels)\n\n# Legendas e label dos eixos\nplt.legend(bbox_to_anchor=(0.01, 0.99), loc=2, borderaxespad=0.2)\nplt.ylabel('Percentual')\nplt.xlabel('Horário')\n\n# Salvando o plot\n# plt.savefig('Weekdays_v2.pdf', bbox_inches='tight')\n\nplt.show()", "_____no_output_____" ], [ "import numpy as np\n\n# Plot da media das porcentagens dos dias de semana\nfig, ax = plt.subplots()\n# Curva dos carros andando\nax.plot(range(len(mediaWeekends['time'])),mediaWeekends['mean'], label='Carros Reservados')\n\n# Curvas representando o intervalo de desvio padrão\nax.plot(range(len(mediaWeekends['time'])), mediaWeekends['mean']+mediaWeekends['std'], alpha=150, c='gray', label='Desvio Padrão')\nax.plot(range(len(mediaWeekends['time'])), mediaWeekends['mean']-mediaWeekends['std'], alpha=150, c='gray')\n\n# Modificando os labels das horas\nax.xaxis.set_ticks(np.arange(0, 1441, 120))\n\nfig.canvas.draw()\n\nlabels = [item.get_text() for item in ax.get_xticklabels()]\nlabels = range(0,26,2)\n\nax.set_xticklabels(labels)\n\n# Legendas e label dos eixos\nplt.legend(bbox_to_anchor=(0.01, 0.99), loc=2, borderaxespad=0.2)\nplt.ylabel('Percentual')\nplt.xlabel('Horário')\n\n# Salvando o plot\n# plt.savefig('Weekends_v2.pdf', bbox_inches='tight')\n\nplt.show()", "_____no_output_____" ], [ "# CSV criado a partir dos dados coletados do arquivo ModoApi_Data_Filter\ndfTravels = pd.read_csv('travels.csv')", "_____no_output_____" ], [ "dfTravels['Start_time'] = str_to_datetime(dfTravels['Start_time'])\ndfTravels['End_time'] = str_to_datetime(dfTravels['End_time'])", "_____no_output_____" ], [ "# A função deve receber os valores previamente separados como somente dias de semana ou finais de semana\ndef cont_reservas(dfDays):\n # Coletando todos os minutos de captura\n datas = pd.to_datetime(dfDays['capture_time'])\n datas = pd.DataFrame(datas)\n\n dfReservas = pd.concat([dfTravels['Start_time'], dfTravels['End_time']], axis=1)\n dfReservas = dfReservas.sort_values(by='Start_time')\n \n # Outlier que está gerando comparações erroneas\n dfReservas.drop(65240, axis=0, inplace=True)\n\n cont_reservas = 0\n reservas = []\n \n # Auxiliar para adquirir o indice da viagem mais proxima que engloba a hora atual\n proximo_start = 0\n\n for i in range(len(datas)):\n data = datas['capture_time'].iloc[i]\n \n # Auxiliar para evitar analises desnecessárias\n# start_test = True\n\n # Comparando todas as datas aos intervalos das reservas, e vendo se ele faz parte para somar a porcentagem\n for j in range(proximo_start, len(dfReservas)):\n if (j == 289): continue\n if (dfReservas['Start_time'].iloc[j] <= data <= dfReservas['End_time'].iloc[j]):\n\n cont_reservas += 1\n \n # Evita comparações desnecessárias com viagens que terminaram antes da hora a ser analisada\n # Seguindo a ideia de que se a viagem não englobou antes a hora atual\n # ela não irá englobar as próximas\n# if (start_test) : \n# if (proximo_start > 0): proximo_start = j - 1\n# else: proximo_start = j\n# start_test = False\n \n # Evita analisar viagens que começaram depois da hora atual\n if (dfReservas['Start_time'].iloc[j] > data):\n break\n\n porcentagem = (cont_reservas/len(car_ids))*100\n\n reservas.append([data, cont_reservas, porcentagem])\n\n cont_reservas = 0\n \n if (i % 100 == 0): print(str(i) + \" \"+str(proximo_start))\n\n reservas = pd.DataFrame(reservas, columns=['datetime', 'total_reserves', 'percentage'])\n\n return reservas", "_____no_output_____" ], [ "dfR_Weekdays = cont_reservas(dfWeekdays)\ndfR_Weekends = cont_reservas(dfWeekends)", "_____no_output_____" ], [ "dfR_Weekdays.to_csv('r_weekdays.csv', index=False, encoding='utf-8')\ndfR_Weekends.to_csv('r_weekends.csv', index=False, encoding='utf-8')", "_____no_output_____" ], [ "dfR_Weekends = pd.read_csv('plots/r_weekends.csv')\ndfR_Weekends['datetime']= pd.to_datetime(dfR_Weekends['datetime'])", "_____no_output_____" ], [ "dfR_Weekdays = pd.read_csv('plots/r_weekdays.csv')\ndfR_Weekdays['datetime'] = pd.to_datetime(dfR_Weekdays['datetime'])", "_____no_output_____" ], [ "# Plot da porcentagem de carros alocados em fins de semana\nplt.plot(dfR_Weekends['datetime'],dfR_Weekends['percentage'])\nplt.gcf().autofmt_xdate()\nplt.show()", "_____no_output_____" ], [ "# Plot da porcentagem de carros alocados em dias de semana\nplt.plot(dfR_Weekdays['datetime'],dfR_Weekdays['percentage'])\nplt.gcf().autofmt_xdate()\nplt.show()", "_____no_output_____" ], [ "# Fazendo a média das porcentagens de cada dia\ndfR_Weekdays = dfR_Weekdays.sort_values(by='datetime')\ndfR_Weekdays['capture_time'] = dfR_Weekdays['datetime']\ndfmediaR_Weekdays = media(dfR_Weekdays, 32)\n\ndfR_Weekends = dfR_Weekends.sort_values(by='datetime')\ndfR_Weekends['capture_time'] = dfR_Weekends['datetime']\ndfmediaR_Weekends = media(dfR_Weekends, 20)", "_____no_output_____" ], [ "dfmediaR_Weekdays = pd.read_csv('plots/media_r_weekdays.csv', encoding='utf-8')\ndfmediaR_Weekends = pd.read_csv('plots/media_r_weekends.csv', encoding='utf-8')", "_____no_output_____" ], [ "import matplotlib\nimport numpy as np\n\nmatplotlib.rc('font', size=12)\n\n# Plot das porcentagens dos fins de semana\nfig, (ax1, ax2) = plt.subplots(1, 2)\n\nfig.set_size_inches(14,4.5)\n\n\n\n# Curva dos carros andando\n\nax1.plot(range(len(mediaWeekdays['time'])),mediaWeekdays['mean'], label='Carros Ocupados')\n\n# Curvas representando o intervalo de desvio padrão\nax1.plot(range(len(mediaWeekdays['time'])), mediaWeekdays['mean']+mediaWeekdays['std'], alpha=150, c='gray')\nax1.plot(range(len(mediaWeekdays['time'])), mediaWeekdays['mean']-mediaWeekdays['std'], alpha=150, c='gray')\n\n\n# Curva dos carros reservados\nax1.plot(range(len(dfmediaR_Weekdays['time'])),dfmediaR_Weekdays['mean'], label='Carros Reservados', c='r', ls='--')\n\n# Curvas representando o intervalo de desvio padrão\nax1.plot(range(len(dfmediaR_Weekdays['time'])), dfmediaR_Weekdays['mean']+dfmediaR_Weekdays['std'], alpha=150, c='#FA8072', ls='--')\nax1.plot(range(len(dfmediaR_Weekdays['time'])), dfmediaR_Weekdays['mean']-dfmediaR_Weekdays['std'], alpha=150, c='#FA8072', ls='--')\n\n\n# Modificando os labels das horas e das porcentagens\nax1.xaxis.set_ticks(np.arange(0, 1441, 120))\nax1.yaxis.set_ticks(np.arange(0, 110, 10))\n\nfig.canvas.draw()\n\nlabels = [item.get_text() for item in ax1.get_xticklabels()]\nlabels = range(0,26,2)\n\nax1.set_xticklabels(labels)\n\n# Eixo y de 0 a 100%\nax1.set_ylim([0,100])\n\n# Legendas e label dos eixos\nax1.legend(bbox_to_anchor=(0.01, 0.99), loc=2, borderaxespad=0.2)\nax1.set_ylabel('Percentual')\nax1.set_xlabel('Horário')\n\n\n\n\n# # Curva dos carros andando\nax2.plot(range(len(mediaWeekends['time'])),mediaWeekends['mean'], label='Carros Ocupados')\n\n# # Curvas representando o intervalo de desvio padrão\nax2.plot(range(len(mediaWeekends['time'])), mediaWeekends['mean']+mediaWeekends['std'], alpha=150, c='gray')\nax2.plot(range(len(mediaWeekends['time'])), mediaWeekends['mean']-mediaWeekends['std'], alpha=150, c='gray')\n\n\n# # Curva dos carros reservados\nax2.plot(range(len(dfmediaR_Weekends['time'])),dfmediaR_Weekends['mean'], label='Carros Reservados', c='r', ls='--')\n\n# # Curvas representando o intervalo de desvio padrão\nax2.plot(range(len(dfmediaR_Weekends['time'])), dfmediaR_Weekends['mean']+dfmediaR_Weekends['std'], alpha=150, c='#FA8072', ls='--')\nax2.plot(range(len(dfmediaR_Weekends['time'])), dfmediaR_Weekends['mean']-dfmediaR_Weekends['std'], alpha=150, c='#FA8072', ls='--')\n\n# Modificando os labels das horas e das porcentagens\nax2.xaxis.set_ticks(np.arange(0, 1441, 120))\nax2.yaxis.set_ticks(np.arange(0, 110, 10))\n\nfig.canvas.draw()\n\nlabels = [item.get_text() for item in ax2.get_xticklabels()]\nlabels = range(0,26,2)\n\nax2.set_xticklabels(labels)\n\n# Eixo y de 0 a 100%\nax2.set_ylim([0,100])\n\n# Legendas e label dos eixos\nax2.legend(bbox_to_anchor=(0.55, 0.99), loc=2, borderaxespad=0.1)\nax2.set_ylabel('Percentual')\nax2.set_xlabel('Horário')\n\n\nplt.show()\n#plt.savefig('plots/ViagensPorHoras_Evo.pdf')", "_____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" ] ]
4aecebbe2ad1de12354763786f9003701108d62c
12,772
ipynb
Jupyter Notebook
Lecture_Notebooks/L15_predictedvals.ipynb
ds-modules/ENVECON-118-FA21
9bcafbc0ed505395a488907fc66441ef8defffd9
[ "BSD-3-Clause" ]
null
null
null
Lecture_Notebooks/L15_predictedvals.ipynb
ds-modules/ENVECON-118-FA21
9bcafbc0ed505395a488907fc66441ef8defffd9
[ "BSD-3-Clause" ]
null
null
null
Lecture_Notebooks/L15_predictedvals.ipynb
ds-modules/ENVECON-118-FA21
9bcafbc0ed505395a488907fc66441ef8defffd9
[ "BSD-3-Clause" ]
1
2021-09-09T16:03:42.000Z
2021-09-09T16:03:42.000Z
39.664596
383
0.473771
[ [ [ "library(haven)\n#load gpa dataset \ngpadata<-read_dta(\"gpa2.dta\")\nhead(gpadata)", "_____no_output_____" ], [ "#regress gpa on sat score, class percentile, and high school class size and class size squared\nreg7<-lm(colgpa~sat+ hsperc + hsize + hsizesq, data= gpadata)\nsummary(reg7)", "_____no_output_____" ], [ "#predict values\npredgpa1 = 1.493 + 1200*.001492 -.01386*30 -.06088*5+.00546*25\n#print\nprint(\"predgpa1\")\npredgpa1\n#or, extract. Summary stores beta coefficients in the term \"coef\"\nsummary(reg7)$coef\npredgpa2 = sum(c(1,1200,30,5,25)*summary(reg7)$coef[,1])\n#print\nprint(\"predgpa2\")\npredgpa2", "[1] \"predgpa1\"\n" ], [ "#transform data to get CI\ngpadata$sat0<- gpadata$sat-1200\ngpadata$hsperc0 <-gpadata$hsperc-30\ngpadata$hsize0<-gpadata$hsize-5\ngpadata$hsizesq0<-gpadata$hsizesq-25\n\nreg8<-lm(colgpa~sat0+hsperc0 + hsize0 + hsizesq0, data = gpadata)\nsummary(reg8)", "_____no_output_____" ], [ " ", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4aecee297659ae26e388e98ab1e64f11cb8f8b48
6,868
ipynb
Jupyter Notebook
.ipynb_checkpoints/firstRound-checkpoint.ipynb
lucasosouza/kaggle-challenges
5059b083a6e3ab8d40811c2401f19af349ed65aa
[ "MIT" ]
null
null
null
.ipynb_checkpoints/firstRound-checkpoint.ipynb
lucasosouza/kaggle-challenges
5059b083a6e3ab8d40811c2401f19af349ed65aa
[ "MIT" ]
null
null
null
.ipynb_checkpoints/firstRound-checkpoint.ipynb
lucasosouza/kaggle-challenges
5059b083a6e3ab8d40811c2401f19af349ed65aa
[ "MIT" ]
null
null
null
24.794224
212
0.531887
[ [ [ "# import useful stuff\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier as Tree\nimport re\n\n# avoid undefined metric warning when calculating precision with 0 labels defined as 1\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "### Data transformations (from data analysis)", "_____no_output_____" ] ], [ [ "def transform(df, fillna=False):\n # remove columns\n for col in ['ult_fec_cli_1t', 'conyuemp', 'tipodom', 'cod_prov', \n 'pais_residencia', 'ncodpers', 'indrel', 'indrel_1mes', \n 'ind_empleado', 'fecha_alta', 'fecha_dato']:\n del df[col]\n\n # convert numerical vars to int\n numerical_vars = ['age', 'antiguedad', 'renta']\n df[numerical_vars] = df[numerical_vars].convert_objects(convert_numeric=True)\n\n # convert S/N to boolean\n for var in ['indfall', 'indresi', 'indext']:\n df[var] = df[var] == 'S'\n\n # drop na\n if fillna:\n df = df.fillna(value=0)\n else:\n df = df.dropna() \n \n # one hot encode remaining categorical vars\n categorical_vars = ['segmento', 'sexo', 'tiprel_1mes', 'canal_entrada', 'nomprov']\n df = pd.get_dummies(df, prefix=None, prefix_sep='_', dummy_na=False, \n columns=categorical_vars, sparse=False, drop_first=False)\n \n # remove variables with one value, if any\n for col in df.columns:\n if len(df[col].value_counts()) == 1:\n print(col)\n del df[col]\n \n return df", "_____no_output_____" ], [ "df_train = pd.read_csv('train_ver2.csv', nrows=2000000)", "_____no_output_____" ], [ "df_train = transform(df_train)", "_____no_output_____" ] ], [ [ "### First Shot at Prediction", "_____no_output_____" ], [ "After all required corvertions have been made, I can make a first shot at predicting. First question we need to ask is, what I'm a predicting?\n\nI'm predicting comsuption of a certain product. I have a total of 24 booleans that will tell whether or not this customer consumed this product. These are my labels for a One vs All classification model.\n\n", "_____no_output_____" ] ], [ [ "# separate the labels\nlabels = []\nfor col in df_train.columns:\n if col[:4] == 'ind_' and col[-4:] == 'ult1':\n labels.append(col)\n \n# create X and y delete dataframe\nX = df_train[df_train.columns.difference(labels)]\ny = df_train[labels]\ndel df_train", "_____no_output_____" ], [ "# upload test data\nX_test = pd.read_csv('test_ver2.csv')\n\n# initialize results\nreport = pd.DataFrame(X_test['ncodpers'])\nclassif_results = {}\n\n# prepare test data for classifer\nX_test = transform(X_test, fillna=True)\n", "_____no_output_____" ], [ "# X_test should only have columns that are also in X (needed due to one-hot encoding)\npaired_columns = [col for col in X_test.columns if col in X.columns]\nX_test = X_test[paired_columns]", "_____no_output_____" ], [ "# predict each product with a different clssifer\nfor label in labels:\n if len(y[label].value_counts()) != 1:\n clf = Tree()\n clf.fit(X, y[label])\n classif_results[label] = clf.predict(X_test)", "_____no_output_____" ], [ "# clean memory\ndel X\ndel y\ndel X_test", "_____no_output_____" ], [ "# transform results to expected output\nfn_name_labels = lambda label, pred: list(map(lambda x: label if x else '', pred))\ncf_list = [fn_name_labels(k,v) for k,v in classif_results.items()]\n\n# concatenate results\nfn_join_columns = lambda x:re.sub('\\s+', ' ', ' '.join(x)).strip()\n\n# add new column added products in report\nreport['added_products'] = list(map(fn_join_columns, zip(*cf_list)))", "_____no_output_____" ], [ "report.ix[0, 'added_products']", "_____no_output_____" ], [ "report.to_csv('round1.csv', header=True, index=False)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aecf5e2aea19df62d47768b5fcf2465a61c4c86
50,963
ipynb
Jupyter Notebook
Chap01/06_activation_functions.ipynb
haru-256/tensorflow_cookbook
18923111eaccb57b47d07160ae5c202c945da750
[ "MIT" ]
1
2021-02-27T16:16:02.000Z
2021-02-27T16:16:02.000Z
01_Introduction/06_Implementing_Activation_Functions/06_activation_functions.ipynb
haru-256/tensorflow_cookbook
18923111eaccb57b47d07160ae5c202c945da750
[ "MIT" ]
2
2018-03-07T14:31:22.000Z
2018-03-07T15:04:17.000Z
Chap01/06_activation_functions.ipynb
haru-256/tensorflow_cookbook
18923111eaccb57b47d07160ae5c202c945da750
[ "MIT" ]
null
null
null
121.921053
23,456
0.884151
[ [ [ "# Activation Functions\n\nThis function introduces activation functions in TensorFlow\n\nWe start by loading the necessary libraries for this script.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n# from tensorflow.python.framework import ops\n# ops.reset_default_graph()\ntf.reset_default_graph()", "_____no_output_____" ] ], [ [ "### Start a graph session", "_____no_output_____" ] ], [ [ "sess = tf.Session()", "_____no_output_____" ] ], [ [ "### Initialize the X range values for plotting", "_____no_output_____" ] ], [ [ "x_vals = np.linspace(start=-10., stop=10., num=100)", "_____no_output_____" ] ], [ [ "### Activation Functions:\n\nReLU activation", "_____no_output_____" ] ], [ [ "print(sess.run(tf.nn.relu([-3., 3., 10.])))\ny_relu = sess.run(tf.nn.relu(x_vals))", "[ 0. 3. 10.]\n" ] ], [ [ "ReLU-6 activation", "_____no_output_____" ] ], [ [ "print(sess.run(tf.nn.relu6([-3., 3., 10.])))\ny_relu6 = sess.run(tf.nn.relu6(x_vals))", "[0. 3. 6.]\n" ] ], [ [ "ReLU-6 refers to the following function\n\n\\begin{equation}\n \\min\\left(\\max(0, x), 6\\right)\n\\end{equation}\n", "_____no_output_____" ], [ "Sigmoid activation", "_____no_output_____" ] ], [ [ "print(sess.run(tf.nn.sigmoid([-1., 0., 1.])))\ny_sigmoid = sess.run(tf.nn.sigmoid(x_vals))", "[0.26894143 0.5 0.7310586 ]\n" ] ], [ [ "Hyper Tangent activation", "_____no_output_____" ] ], [ [ "print(sess.run(tf.nn.tanh([-1., 0., 1.])))\ny_tanh = sess.run(tf.nn.tanh(x_vals))", "[-0.7615942 0. 0.7615942]\n" ] ], [ [ "Softsign activation", "_____no_output_____" ] ], [ [ "print(sess.run(tf.nn.softsign([-1., 0., 1.])))\ny_softsign = sess.run(tf.nn.softsign(x_vals))", "[-0.5 0. 0.5]\n" ] ], [ [ "softsign refers to the following function\n\n\\begin{equation}\n \\frac{x}{1 + |x|}\n\\end{equation}\n\n<br>\n<img src=\"http://tecmemo.wpblog.jp/wp-content/uploads/2017/01/activation_04.png\" width=40%>\n", "_____no_output_____" ], [ "Softplus activation", "_____no_output_____" ], [ "![](http://tecmemo.wpblog.jp/wp-content/uploads/2017/01/activation_04.png=200x)", "_____no_output_____" ] ], [ [ "print(sess.run(tf.nn.softplus([-1., 0., 1.])))\ny_softplus = sess.run(tf.nn.softplus(x_vals))", "[0.31326166 0.6931472 1.3132616 ]\n" ] ], [ [ "Softplus refers to the following function\n\n\\begin{equation}\n \\log\\left(\\exp(x) + 1\\right)\n\\end{equation}\n", "_____no_output_____" ], [ "Exponential linear activation", "_____no_output_____" ] ], [ [ "print(sess.run(tf.nn.elu([-1., 0., 1.])))\ny_elu = sess.run(tf.nn.elu(x_vals))", "[-0.63212055 0. 1. ]\n" ] ], [ [ "ELU refers to the following function\n\n\\begin{equation}\\label{eq:}\n f = \\begin{cases}\n \\exp(x) - 1 &(x < 0 )\\\\\n 0 &(x \\geq 0 )\\\\\n \\end{cases}\n\\end{equation}\n", "_____no_output_____" ], [ "### Plot the different functions", "_____no_output_____" ] ], [ [ "plt.style.use('ggplot')\nplt.plot(x_vals, y_softplus, 'r--', label='Softplus', linewidth=2)\nplt.plot(x_vals, y_relu, 'b:', label='ReLU', linewidth=2)\nplt.plot(x_vals, y_relu6, 'g-.', label='ReLU6', linewidth=2)\nplt.plot(x_vals, y_elu, 'k-', label='ExpLU', linewidth=0.5)\nplt.ylim([-1.5,7])\nplt.legend(loc='upper left', shadow=True, edgecolor='k')\nplt.show()\n\nplt.plot(x_vals, y_sigmoid, 'r--', label='Sigmoid', linewidth=2)\nplt.plot(x_vals, y_tanh, 'b:', label='Tanh', linewidth=2)\nplt.plot(x_vals, y_softsign, 'g-.', label='Softsign', linewidth=2)\nplt.ylim([-1.3,1.3])\nplt.legend(loc='upper left', shadow=True, edgecolor='k')\nplt.show()", "_____no_output_____" ] ], [ [ "![Acivation_Functions1](https://github.com/nfmcclure/tensorflow_cookbook/raw/jupyter_notebooks/01_Introduction/images/06_activation_funs1.png)\n\n![Acivation_Functions2](https://github.com/nfmcclure/tensorflow_cookbook/raw/jupyter_notebooks/01_Introduction/images/06_activation_funs2.png)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4aecfa28cb4c307486eaa080b308cfceb104bc00
463,275
ipynb
Jupyter Notebook
Penniless Pilgrim.ipynb
tjol/toy-notebooks
25cb46bb67ff675aad4b6a401d7db180858ff9fd
[ "CC-BY-4.0" ]
null
null
null
Penniless Pilgrim.ipynb
tjol/toy-notebooks
25cb46bb67ff675aad4b6a401d7db180858ff9fd
[ "CC-BY-4.0" ]
null
null
null
Penniless Pilgrim.ipynb
tjol/toy-notebooks
25cb46bb67ff675aad4b6a401d7db180858ff9fd
[ "CC-BY-4.0" ]
1
2020-12-05T13:57:06.000Z
2020-12-05T13:57:06.000Z
919.196429
59,172
0.955309
[ [ [ "# The Penniless Pilgrim\n\nI came across this TED Ed video with a riddle (by [Dan Finkel](https://mathforlove.com/who-am-i/dan-finkel/)) on YouTube:", "_____no_output_____" ] ], [ [ "%%HTML\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/6sBB-gRhfjE\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe>", "_____no_output_____" ] ], [ [ "It's simple enough: you're a traveller, without a penny to your name. You enter a town with a simple grid-based street layout, like this:", "_____no_output_____" ] ], [ [ "import networkx as nx\nfrom matplotlib import pyplot as plt\nimport sys", "_____no_output_____" ], [ "AA = 'ABCDE'\nBB = '12345'\n\ndef make_graph():\n g = nx.Graph()\n g.add_nodes_from(a + b for a in AA for b in BB)\n g.add_edges_from(((a+b1, a+b2) for a in AA for (b1, b2) in zip(BB[:-1], BB[1:])), direction='EW')\n g.add_edges_from(((a1+b, a2+b) for (a1, a2) in zip(AA[:-1], AA[1:]) for b in BB), direction='NS')\n return g\n\ng = make_graph()", "_____no_output_____" ], [ "node_positions = {a+b: (j, len(AA) - i) for (i, a) in enumerate('ABCDE') for (j,b) in enumerate('12345')}\n\ndef draw_graph(g):\n plt.figure(figsize=(4,4))\n nx.draw(g, pos=node_positions,\n edge_color=['r' if g[u][v].get('trodden') else 'grey' for (u,v) in g.edges],\n width=3,\n node_size=100,\n node_color=['b' if n in ('A1', 'A3', 'E5') else 'k' for n in g.nodes])\n\ng['A1']['A2']['trodden'] = True\ng['A2']['A3']['trodden'] = True\n \ndraw_graph(g)", "_____no_output_____" ] ], [ [ "You enter the town at the north-west gate, and walk two blocks to the tourist information office. Your goal is to reach the temple at the far (south-east) corner of town. At the tourist information, you learn that the town has a curious system of tolls levied on all trips along the town's streets:\n\n* Your trip through town is taxed based on the route you take.\n* You are not allowed to use the same street twice in a trip, but you *are* allowed to cross an intersection multiple times.\n* Walking one block from west to east increases your tax bill by 2 silver.\n* Walking one from east to west decreases your bill by 2.\n* Walking one from north to south doubles you tax bill.\n* Walking one from south to north halves your tax bill.\n\nAs you've already walked to tourist information, two blocks east of the gate, you currently owe 4 silver. You want to get to the temple, and **you have no money**. Can you get to the temple without ending up in debtors' prison?\n\nOne of the more direct routes, going due south and turning east at the southern wall, would cost 68 silver. A lot more than you have!\n\nI must admit that I didn't spend a lot of time trying to figure out a solution before giving up and watching the rest of the video, which gives a nice and elegant path that end up costing you nothing.", "_____no_output_____" ], [ "### Python to the rescue\n\nAfter the fact, I couldn't help but wonder if there are other free routes to the temple. If so, how many? Are there any on which you *make* money?\n\nThankfully, this is fairly easy to brute force on a capable computer.\n\nIf we describe the town layout as a graph `g` using (way overpowered) `networkx`, edges being streets and nodes, labelled chessboard-style, being intersections, we mark the paths we've already taken as *“trodden”*", "_____no_output_____" ] ], [ [ "g['A1']['A2']['trodden'] = True\ng['A2']['A3']['trodden'] = True", "_____no_output_____" ] ], [ [ "and without too much effort we can figure out where we *could* go next from our current position, and what that would cost us. Add a bit of housekeeping to produce a new graph for every route with the trodden streets properly marked,", "_____no_output_____" ] ], [ [ "def possible_steps(g, pos, cost):\n for dest, props in g[pos].items():\n if not props.get('trodden'):\n if props['direction'] == 'NS':\n new_cost = cost * 2 if dest[0] > pos[0] else cost / 2\n else:\n new_cost = cost + 2 if dest[1] > pos[1] else cost - 2\n new_g = g.copy()\n new_g[pos][dest]['trodden'] = True\n yield new_g, dest, new_cost", "_____no_output_____" ] ], [ [ "… and all we have to do is walk the graph!\n\nI'll be doing this depth-first, as it were, as there's no easy way to discard partial routes that I can be bothered to think of.", "_____no_output_____" ] ], [ [ "def walk_on(g, steps, cost, dest=AA[-1]+BB[-1]):\n for next_g, next_step, next_cost in possible_steps(g, steps[-1], cost):\n new_steps = [*steps, next_step]\n if next_step == dest:\n yield (next_g, new_steps, next_cost)\n else:\n yield from walk_on(next_g, new_steps, next_cost)", "_____no_output_____" ] ], [ [ "This only takes about ten minutes on a single core of my aging PC. It should be easily parallelizable, but that's not for the here and now.", "_____no_output_____" ] ], [ [ "solutions = []\nfor solu in walk_on(g, ['A1', 'A2', 'A3'], 4):\n solutions.append(solu)\n sys.stdout.write(f'\\r{len(solutions)}')\n sys.stdout.flush()\n \nprint(f'\\n{len(solutions)} solutions found, min cost {min(c for g, s, c in solutions)}')\noptima = [(g, s, c) for (g, s, c) in solutions if c <= 0]\nprint(f'{len(optima)} routes free or better')", "58192\n58192 solutions found, min cost -4.0\n6 routes free or better\n" ] ], [ [ "It turns out that of the 58192 allowed routes, we can afford a grand total of 6, some of which will, actually, give as a healthy tax refund of up to 4 shiny silver coins.\n\nWhat do they look like (and are they correct)?", "_____no_output_____" ] ], [ [ "def explain_cost(steps):\n expl = ''\n g = make_graph()\n cost = 0\n for prev, step in zip(steps[:-1], steps[1:]):\n for new_g, next_step, new_cost in possible_steps(g, prev, cost):\n if next_step == step:\n g = new_g\n cost = new_cost\n break\n else:\n expl += 'ERROR\\n'\n return expl\n expl += f'{prev} to {step} owing {cost}\\n'\n return expl", "_____no_output_____" ], [ "def draw_path(g, s, c):\n draw_graph(g)\n nx.draw_networkx_edge_labels(g, pos=node_positions,\n edge_labels={(u, v): str(i+1) for (i, (u,v)) in enumerate(zip(s[:-1], s[1:]))})\n plt.title(f'Cost: {c} silver')\n plt.figtext(1.1, 0, explain_cost(s))\n\nfor (g, s, c) in optima:\n draw_path(g, s, c)", "_____no_output_____" ] ], [ [ "Reassuringly, this found the canonical route:", "_____no_output_____" ] ], [ [ "draw_path(*optima[5])", "_____no_output_____" ], [ "[len(s) for (g, s, c) in optima]", "_____no_output_____" ] ], [ [ "This is, also, the shortest route we can afford. However, it's not the best. The best route involves a minor detour down the pub at C2:", "_____no_output_____" ] ], [ [ "draw_path(*optima[4])", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4aecfda70044ab28f41060b2ce407c30a6327f7c
687,717
ipynb
Jupyter Notebook
notebooks/bulk-labelling/bulk-labelling.ipynb
vishnupriyavr/rasalit
8305aa1a4cf2f3d7d79e989b4656d1995c420531
[ "Apache-2.0" ]
null
null
null
notebooks/bulk-labelling/bulk-labelling.ipynb
vishnupriyavr/rasalit
8305aa1a4cf2f3d7d79e989b4656d1995c420531
[ "Apache-2.0" ]
null
null
null
notebooks/bulk-labelling/bulk-labelling.ipynb
vishnupriyavr/rasalit
8305aa1a4cf2f3d7d79e989b4656d1995c420531
[ "Apache-2.0" ]
null
null
null
706.800617
646,143
0.627006
[ [ [ "# Bulk Labelling as a Notebook\n\nThis notebook contains a convenient pattern to cluster and label new text data. The end-goal is to discover intents that might be used in a virtual assistant setting. This can be especially useful in an early stage and is part of the \"iterate on your data\"-mindset. \n\n## Dependencies \n\nYou'll need to install a few things to get started. \n\n- [whatlies](https://rasahq.github.io/whatlies/)\n- [human-learn](https://koaning.github.io/human-learn/)\n\nYou can install both tools by running this line in an empty cell; \n\n```python\n%pip install \"whatlies[tfhub]\" \"human-learn\"\n```\n\nWe use `whatlies` to fetch embeddings and to handle the dimensionality reduction. We use `human-learn` for the interactive labelling interface. Feel free to check the documentation of both packages to learn more. \n\n## Let's go\n\nTo get started we'll first import a few tools.", "_____no_output_____" ] ], [ [ "import pathlib \nimport numpy as np\nfrom whatlies.language import CountVectorLanguage, UniversalSentenceLanguage, BytePairLanguage, SentenceTFMLanguage\nfrom whatlies.transformers import Pca, Umap", "_____no_output_____" ] ], [ [ "Next we will load in some embedding frameworks. There can be very heavy, just so you know! ", "_____no_output_____" ] ], [ [ "lang_cv = CountVectorLanguage(10)\nlang_use = UniversalSentenceLanguage(\"large\")\nlang_bp = BytePairLanguage(\"en\", dim=300, vs=200_000)\nlang_brt = SentenceTFMLanguage('distilbert-base-nli-stsb-mean-tokens')", "INFO:absl:Using /var/folders/0v/pj9vtxhd6ml7mb8n94wvcmkr0000gp/T/tfhub_modules to cache modules.\n" ] ], [ [ "Next we'll load in the texts that we'd like to embed/cluster. Feel free to provide another file here.", "_____no_output_____" ] ], [ [ "txt = pathlib.Path(\"nlu.md\").read_text()\ntexts = list(set([t.replace(\" - \", \"\") for t in txt.split(\"\\n\") if len(t) > 0 and t[0] != \"#\"]))\nprint(f\"We're going to plot {len(texts)} texts.\")", "_____no_output_____" ] ], [ [ "Keep in mind that it's better to start out with 1000 sentences or so. Much more might break the browser's memory in the next visual.\n\n## Showing Clusters \n\n![](pipeline.png)\n\nThe cell below will take the texts and have them pass through different language backends. After this they will be mapped to a two dimensional space by using [UMAP](https://umap-learn.readthedocs.io/en/latest/). It takes a while to plot everything (mainly because the universal sentence encoder and the transformer language models are heavy).", "_____no_output_____" ] ], [ [ "%%time\n\ndef make_plot(lang):\n return (lang[texts]\n .transform(Umap(2))\n .plot_interactive(annot=False)\n .properties(width=200, height=200, title=type(lang).__name__))\n\nmake_plot(lang_cv) | make_plot(lang_bp) | make_plot(lang_use) | make_plot(lang_brt)", "CPU times: user 2min 54s, sys: 1min 23s, total: 4min 18s\nWall time: 1min 25s\n" ] ], [ [ "What you see are four charts. You should notice that certain clusters have appeared. For your usecase you might need to check which language backend makes the most sense. \n\n## Note for Non-English \n\nThe only model shown here that is English specific is the universal sentence encoder (`lang_use`). All the other ones also support other languages. For more information check the [bytepair documentation](https://nlp.h-its.org/bpemb/) and the [sentence transformer documentation](https://www.sbert.net/docs/pretrained_models.html#multi-lingual-models).\n\n## Towards Labelling \n\nWe'll now prepare a dataframe that we'll assign labels to. We'll do that by loading in the same text file but now into a pandas dataframe.", "_____no_output_____" ] ], [ [ "df = lang_use[texts].transform(Umap(2)).to_dataframe().reset_index()\ndf.columns = ['text', 'd1', 'd2']\ndf['label'] = ''\ndf.shape[0]", "_____no_output_____" ] ], [ [ "We are now going to be labelling!", "_____no_output_____" ], [ "# Fancy interactive drawing! \n\nWe'll be using Vincent's infamous [human-learn library](https://koaning.github.io/human-learn/guide/drawing-features/custom-features.html) for this. First we'll need to instantiate some charts.\n\nNext we get to draw! Drawing can be a bit tricky though, so pay attention. \n\n1. You'll want to double-click to start drawing. \n2. You can then click points together to form a polygon. \n3. Next you need to double-click to stop drawing. \n\nThis allows you to draw polygons that can be used in the code below to fetch the examples that you're interested in.\n\n## Rerun\n\nThis is where we will start labelling. That also means that we might re-run this cell after we've added labels.", "_____no_output_____" ] ], [ [ "from hulearn.experimental.interactive import InteractiveCharts\n\ncharts = InteractiveCharts(df.loc[lambda d: d['label'] == ''], labels=['group'])\n\ncharts.add_chart(x='d1', y='d2')", "_____no_output_____" ] ], [ [ "We can now use this selection to retreive a subset of rows. This is a quick varification to see if the points you select indeed belong to the same cluster.", "_____no_output_____" ] ], [ [ "from hulearn.preprocessing import InteractivePreprocessor\ntfm = InteractivePreprocessor(json_desc=charts.data())\n\ndf.pipe(tfm.pandas_pipe).loc[lambda d: d['group'] != 0].head(10)", "_____no_output_____" ] ], [ [ "If you're confident that you'd like to assign a label, you can do so below. ", "_____no_output_____" ] ], [ [ "label_name = 'weather'", "_____no_output_____" ], [ "idx", "_____no_output_____" ], [ "idx = df.pipe(tfm.pandas_pipe).loc[lambda d: d['group'] != 0].index\n\ndf.iloc[idx, 3] = label_name\n\nprint(f\"We just assigned {len(idx)} labels!\")", "We just assigned 51 labels!\n" ] ], [ [ "That's it! You've just attached a label to a group of points! \n\n## Rerun \n\nYou can now scroll up and start relabelling clusters that aren't assigned yet. Once you're confident that this works, you can export by running the final code below.", "_____no_output_____" ] ], [ [ "df.head()", "_____no_output_____" ], [ "df.to_csv(\"first_order_labelled.csv\")", "_____no_output_____" ] ], [ [ "## Final Notes\n\nThere's a few things to mention. \n\n1. This method of labelling is great when you're working on version 0 of something. It'll get you a whole lot of data fast but it won't be high quality data. \n2. The use-case for this method might be at the start of design a virtual assistant. You've probably got data from social media that you'd like to use as a source of inspiration for intents. This is certainly a valid starting point but you should be aware that the language that folks use on a feedback form is different than the language used in a chatbox. Again, these labels are a reasonable starting point, but they should not be regarded as ground truth. \n3. Labelling is only part of the goal here. Another big part is understanding the data. This is very much a qualitative/human task. You might be able to quickly label 1000 points in 5 minutes with this technique but you'll lack an understanding if you don't take the time for it. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4aed29225e381ae5e6497daa60aa97ff8c06ea61
5,792
ipynb
Jupyter Notebook
vanderplas/PythonDataScienceHandbook-master/notebooks/04.15-Further-Resources.ipynb
CaiqueCoelho/deep-learning
c39a8f30a5219abed7a07d5db1cb7450a3ecde93
[ "Apache-2.0" ]
18
2017-11-18T05:51:36.000Z
2021-03-05T05:59:24.000Z
Part8Python3DataScienceHandbook/notebooks/04.15-Further-Resources.ipynb
luqian2017/algorithms
e83a17ecf1a7cfea77c5b4ecddc92eb9f1fc329c
[ "MulanPSL-1.0" ]
162
2021-03-09T01:52:11.000Z
2022-03-12T01:09:07.000Z
Part8Python3DataScienceHandbook/notebooks/04.15-Further-Resources.ipynb
luqian2017/algorithms
e83a17ecf1a7cfea77c5b4ecddc92eb9f1fc329c
[ "MulanPSL-1.0" ]
22
2017-11-11T20:54:42.000Z
2022-01-11T00:25:31.000Z
59.102041
605
0.701312
[ [ [ "<!--BOOK_INFORMATION-->\n<img align=\"left\" style=\"padding-right:10px;\" src=\"figures/PDSH-cover-small.png\">\n\n*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).*\n\n*The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!*", "_____no_output_____" ], [ "<!--NAVIGATION-->\n< [Visualization with Seaborn](04.14-Visualization-With-Seaborn.ipynb) | [Contents](Index.ipynb) | [Machine Learning](05.00-Machine-Learning.ipynb) >\n\n<a href=\"https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/04.15-Further-Resources.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open and Execute in Google Colaboratory\"></a>\n", "_____no_output_____" ], [ "# Further Resources", "_____no_output_____" ], [ "## Matplotlib Resources\n\nA single chapter in a book can never hope to cover all the available features and plot types available in Matplotlib.\nAs with other packages we've seen, liberal use of IPython's tab-completion and help functions (see [Help and Documentation in IPython](01.01-Help-And-Documentation.ipynb)) can be very helpful when exploring Matplotlib's API.\nIn addition, Matplotlib’s [online documentation](http://matplotlib.org/) can be a helpful reference.\nSee in particular the [Matplotlib gallery](http://matplotlib.org/gallery.html) linked on that page: it shows thumbnails of hundreds of different plot types, each one linked to a page with the Python code snippet used to generate it.\nIn this way, you can visually inspect and learn about a wide range of different plotting styles and visualization techniques.\n\nFor a book-length treatment of Matplotlib, I would recommend [*Interactive Applications Using Matplotlib*](https://www.packtpub.com/application-development/interactive-applications-using-matplotlib), written by Matplotlib core developer Ben Root.", "_____no_output_____" ], [ "## Other Python Graphics Libraries\n\nAlthough Matplotlib is the most prominent Python visualization library, there are other more modern tools that are worth exploring as well.\nI'll mention a few of them briefly here:\n\n- [Bokeh](http://bokeh.pydata.org) is a JavaScript visualization library with a Python frontend that creates highly interactive visualizations capable of handling very large and/or streaming datasets. The Python front-end outputs a JSON data structure that can be interpreted by the Bokeh JS engine.\n- [Plotly](http://plot.ly) is the eponymous open source product of the Plotly company, and is similar in spirit to Bokeh. Because Plotly is the main product of a startup, it is receiving a high level of development effort. Use of the library is entirely free.\n- [Vispy](http://vispy.org/) is an actively developed project focused on dynamic visualizations of very large datasets. Because it is built to target OpenGL and make use of efficient graphics processors in your computer, it is able to render some quite large and stunning visualizations.\n- [Vega](https://vega.github.io/) and [Vega-Lite](https://vega.github.io/vega-lite) are declarative graphics representations, and are the product of years of research into the fundamental language of data visualization. The reference rendering implementation is JavaScript, but the API is language agnostic. There is a Python API under development in the [Altair](https://altair-viz.github.io/) package. Though as of summer 2016 it's not yet fully mature, I'm quite excited for the possibilities of this project to provide a common reference point for visualization in Python and other languages.\n\nThe visualization space in the Python community is very dynamic, and I fully expect this list to be out of date as soon as it is published.\nKeep an eye out for what's coming in the future!", "_____no_output_____" ], [ "<!--NAVIGATION-->\n< [Visualization with Seaborn](04.14-Visualization-With-Seaborn.ipynb) | [Contents](Index.ipynb) | [Machine Learning](05.00-Machine-Learning.ipynb) >\n\n<a href=\"https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/04.15-Further-Resources.ipynb\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\" title=\"Open and Execute in Google Colaboratory\"></a>\n", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4aed49ed8d7b65e281f406c809a0efd9a500cde4
197,640
ipynb
Jupyter Notebook
examples/Remote.ipynb
BBN-Q/pyWRspice
1c34ad39bd29540596755e7a20be5dda425f4b62
[ "MIT" ]
4
2020-10-15T07:59:29.000Z
2022-01-06T10:51:08.000Z
examples/Remote.ipynb
Ksaihan/pyWRspice
1c34ad39bd29540596755e7a20be5dda425f4b62
[ "MIT" ]
null
null
null
examples/Remote.ipynb
Ksaihan/pyWRspice
1c34ad39bd29540596755e7a20be5dda425f4b62
[ "MIT" ]
4
2020-08-28T16:41:42.000Z
2021-06-03T19:25:04.000Z
262.122016
76,208
0.913762
[ [ [ "# PyWRspice Wrapper Tutorial: Run simulation on remote SSH server\n\n#### Prerequisite:\n* You need to complete the *Tutorial.ipynb* notebook first.\n\nHere we assume you are already famililar with running PyWRspice on a local computer.", "_____no_output_____" ] ], [ [ "# Add pyWRspice location to system path, if you haven't run setup.py\nimport sys\nsys.path.append(\"../\")", "_____no_output_____" ], [ "import numpy as np\nimport logging, importlib\nfrom pyWRspice import script, simulation, remote\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nlogging.basicConfig(level=logging.WARNING)", "_____no_output_____" ] ], [ [ "### 0. Set up a connection to an SSH server\n\nAssume you store login info into a variable ```ssh_login = (server_name, user_name, password)```\nand specify local directory as ```local_dir```, and remote directory as ```remote_dir``` to store simulation related temporary files.", "_____no_output_____" ], [ "Set up a handler", "_____no_output_____" ] ], [ [ "engine_remote = remote.WRWrapperSSH(ssh_login[0],ssh_login[1],ssh_login[2],\n local_dir=local_dir,\n remote_dir=remote_dir,\n command = \"/usr/local/xictools/bin/wrspice\")", "_____no_output_____" ] ], [ [ "## 1. Run a WRspice script one time\n\nLet's try to run the same script from *Tutorial.ipynb*, this time on an SSH server.", "_____no_output_____" ] ], [ [ "script2 = \"\"\"* Transient response of RLC circuit\n.tran 50p 100n\n\n* RLC model of a transmission line\nR1 1 2 0.1\nL1 2 3 1n\nC1 3 0 {cap}p\nR2 3 0 1e3\n\n* Load impedance\nRload 3 0 50\n\n* Pulse voltage source\nV1 1 0 pulse(0 1 1n 1n 1n {dur}n)\n*\n.control\nrun\nset filetype=binary\nwrite {output_file} v(2) v(3)\n.endc\n\"\"\"\n", "_____no_output_____" ] ], [ [ "We then specify the values of ```cap``` and ```dur``` when execute the script with the ```run``` function, the same way we would do when running on local machine.", "_____no_output_____" ] ], [ [ "dat2 = engine_remote.run(script2,cap=30, dur=40)", "_____no_output_____" ], [ "# Extract the data\ndat2 = dat2.to_array()\nts = dat2[0]\nv2 = dat2[1]\nv3 = dat2[2]\n\n# Plot the data\nfig = plt.figure(figsize=(12,6))\nplt.plot(ts*1e9, v2, label=\"v(2)\")\nplt.plot(ts*1e9, v3, label=\"v(3)\")\nplt.xlabel(\"Time [ns]\")\nplt.ylabel(\"Voltage [V]\")\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "## 2. Run WRspice script with multiple parametric values in parallel", "_____no_output_____" ], [ "We can pass a list of values to one or more parameters and run them all in parallel, using multiprocessing, with the ```run_parallel()``` method, almost the same way as running on a local machine, except that we now have a few more options on how to handle the files.\n\nComparing to its local version, the remote function ```run_parallel``` has 2 new options:\n* ```save_file```: The function create a series of files (to be explained later) on the local and remote machines, such as circuit files and output files (after execution). To remove these files, set ```save_file=True``` (default).\n* ```read_raw```: By default (True), the function will read the output raw files into memory. If the output data can be too large, consider set ```read_raw=False```, then the returned value is the list of output filenames (to be manually imported later).\n\nOne can control how the function returns by the parameter ```reshape```: If True, return (params,values) whose shapes are the same (same as the local version). If False, return a pandas DataFrame object containing the params and results in the column ```result```.", "_____no_output_____" ] ], [ [ "# Read the docs\nengine_remote.run_parallel?", "_____no_output_____" ] ], [ [ "#### Simple case: The same way as local version.", "_____no_output_____" ] ], [ [ "params = {}\nparams[\"cap\"] = [20,50,100]\nparams[\"dur\"] = [40,60]\n\nparams3, dat3 = engine_remote.run_parallel(script2,save_file=False,**params)", "_____no_output_____" ] ], [ [ "Because ```reshape=True``` by default, the returned values are the same as in the local case.", "_____no_output_____" ] ], [ [ "# Examine the returned parameter values\nfor k,v in params3.items():\n print(\"%s = %s\" %(k,v))\n print(\"\")", "cap = [[ 20 20]\n [ 50 50]\n [100 100]]\n\ndur = [[40 60]\n [40 60]\n [40 60]]\n\n" ], [ "# Get the shape of the returned data\ndat3.shape", "_____no_output_____" ], [ "# Plot the data\nfig = plt.figure(figsize=(12,6))\nshape = dat3.shape\nfor i in range(shape[0]):\n for j in range(shape[1]):\n dat = dat3[i,j].to_array()\n ts = dat[0]\n v3 = dat[2]\n plt.plot(ts*1e9, v3, label=\"cap=%s[pF], dur=%s[ns]\" %(params3[\"cap\"][i,j],params3[\"dur\"][i,j]))\nplt.xlabel(\"Time [ns]\")\nplt.ylabel(\"Voltage [V]\")\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "#### A more controlled case: turn off ```reshape``` and ```read_raw```", "_____no_output_____" ] ], [ [ "params = {}\nparams[\"cap\"] = [20,50,100]\nparams[\"dur\"] = [40,60]\n\ndat4 = engine_remote.run_parallel(script2,save_file=False,reshape=False,read_raw=False,**params)", "_____no_output_____" ] ], [ [ "Because in this case ```reshape=False```, the returned value is a pandas DataFrame with all the simulation parameters and output.", "_____no_output_____" ] ], [ [ "dat4", "_____no_output_____" ] ], [ [ "Because ```read_raw=False```, the returned output is a list of output raw filenames.", "_____no_output_____" ] ], [ [ "for fname in dat4[\"result\"]:\n print(fname)", "/Users/mnguyen/Documents/GitHub/tmp/tmp_output_0.raw\n/Users/mnguyen/Documents/GitHub/tmp/tmp_output_1.raw\n/Users/mnguyen/Documents/GitHub/tmp/tmp_output_2.raw\n/Users/mnguyen/Documents/GitHub/tmp/tmp_output_3.raw\n/Users/mnguyen/Documents/GitHub/tmp/tmp_output_4.raw\n/Users/mnguyen/Documents/GitHub/tmp/tmp_output_5.raw\n" ] ], [ [ "So we need to do some extra steps to read the output data and reshape them. We can do so manually, or run the function ```reshape_result```.", "_____no_output_____" ] ], [ [ "params4, dat4r = engine_remote.reshape_results(dat4,params)", "_____no_output_____" ], [ "# Examine the returned parameter values\nfor k,v in params4.items():\n print(\"%s = %s\" %(k,v))\n print(\"\")", "cap = [[ 20 20]\n [ 50 50]\n [100 100]]\n\ndur = [[40 60]\n [40 60]\n [40 60]]\n\n" ], [ "# Get the shape of the returned data\n# Note that it is an array of output raw filenames\ndat4r.shape", "_____no_output_____" ], [ "# Plot the data\nfig = plt.figure(figsize=(12,6))\nshape = dat4r.shape\nfor i in range(shape[0]):\n for j in range(shape[1]):\n dat = simulation.RawFile(dat4r[i,j]).to_array() # Need to import the raw file using RawFile class\n ts = dat[0]\n v3 = dat[2]\n plt.plot(ts*1e9, v3, label=\"cap=%s[pF], dur=%s[ns]\" %(params3[\"cap\"][i,j],params3[\"dur\"][i,j]))\nplt.xlabel(\"Time [ns]\")\nplt.ylabel(\"Voltage [V]\")\nplt.legend()\nplt.show()", "_____no_output_____" ] ], [ [ "## 3. Run long simulation on server\n\nThe ways we have run the simulation so far are appropriate for rather light-weight simulation which is expected to be completed in an hour or so on the server. When running heavy simulation on the server, we want to have the simulation running while we can disconnect the SSH connection, then we can be back later to collect the output.\n\nThe way to do so is to break up the function ```run_parallel``` into multiple steps: prepare the files needed for the simulation on the server, then manually execute the simulation, then collect the result.", "_____no_output_____" ], [ "#### Prepare the files\n\nThe function ```prepare_parallel``` creates local and remote copies of the circuit files. It returns a configuration file containing information for execution.\n\nIf there are additional files needed for the simulation (e.g. input files), they have to be copied to the server by the function ```put```.", "_____no_output_____" ] ], [ [ "fconfig = engine_remote.prepare_parallel(script2,**params)\nprint(fconfig)", "simconfig_20200107_173940.csv\n" ], [ "# Let's read the first line of fconfig. We can get the local path by function local_fname\nwith open(engine_remote.local_fname(fconfig),'r') as f:\n print(f.readline())", "# To run manually: python run_parallel.py simconfig_20200107_173940.csv --processes=<num>\n\n" ] ], [ [ "#### Execute\nAs shown above, the command to execute the simulation is ```python run_parallel.py simconfig_20200107_173940.csv --processes=<num>```. How to do it (safely):\n1. Manually SSH log in to the server\n2. Change directory ```cd``` to the working directory ```engine_remote.remote_dir```\n3. Create a separate session by running the command ```screen``` (or ```screen -S <name>``` to specify the screen name)\n4. Run the above command: ```python run_parallel.py simconfig_20200107_173940.csv``` with optional ```--processes=<num>``` (```num``` is the number of processes in parallel, default is 64)\n5. Then hit ```Ctrl + a``` and ```d``` to detach from the screen session\n6. Now you can disconnect from the SSH server. The job will continue in the background.", "_____no_output_____" ], [ "#### Collect results\n\nTwo ways to check if the job is done:\n* Manually log in to the server, change to ```remote_dir``` and check if the file ```finish_<fconfig>.txt``` exists (when the simulation is completed, it will create that file).\n* Run the function ```get_results``` to automatically check and collect the output files.", "_____no_output_____" ] ], [ [ "dat5 = engine_remote.get_results(fconfig,timeout=100,read_raw=False)", "_____no_output_____" ] ], [ [ "Because we set ```read_raw=False```, the returned ```dat5``` is the same as ```dat4``` above. We need to run extra steps to reshape and read the output.", "_____no_output_____" ] ], [ [ "params5, dat5r = engine_remote.reshape_results(dat5,params)\n# The results should be the same as params4 and dat4r above", "_____no_output_____" ], [ "# Finally, after analyzing the results, we need to remove the temp files (circuit and output files, etc)\nengine_remote.remove_fconfig(fconfig, dest=\"both\") # Set dest=\"local\" or dest=\"remote\" if necessary", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4aed4a93d0a0f8eba5101b1ad41452177dd36dd0
263,377
ipynb
Jupyter Notebook
hw_5/hw_5.ipynb
zbalewski/python-ay250-homework
bf41f380a37f8ba61b9bb4aa48ef785637bb7151
[ "MIT" ]
null
null
null
hw_5/hw_5.ipynb
zbalewski/python-ay250-homework
bf41f380a37f8ba61b9bb4aa48ef785637bb7151
[ "MIT" ]
null
null
null
hw_5/hw_5.ipynb
zbalewski/python-ay250-homework
bf41f380a37f8ba61b9bb4aa48ef785637bb7151
[ "MIT" ]
null
null
null
221.511354
54,396
0.870338
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Aiport-data\" data-toc-modified-id=\"Aiport-data-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Aiport data</a></span></li><li><span><a href=\"#Get-all-weather-data-...\" data-toc-modified-id=\"Get-all-weather-data-...-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Get all weather data ...</a></span></li><li><span><a href=\"#...-and-extract-weather-close-to-airports\" data-toc-modified-id=\"...-and-extract-weather-close-to-airports-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>... and extract weather close to airports</a></span></li><li><span><a href=\"#Weather-patterns\" data-toc-modified-id=\"Weather-patterns-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Weather patterns</a></span></li><li><span><a href=\"#Correlations-from-top-10-pairs\" data-toc-modified-id=\"Correlations-from-top-10-pairs-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Correlations from top 10 pairs</a></span></li></ul></div>", "_____no_output_____" ], [ "# Aiport data", "_____no_output_____" ], [ "Combine airport codes and top airports into a table with relevant info (name, wikipedia link, latitude, longitute).", "_____no_output_____" ] ], [ [ "import pandas as pd\n\n# load top 50 airports\ntop50 = pd.read_csv(\"hw_5_data/top_airports.csv\")\ntop50_mini = top50[[\"ICAO\", \"Airport\"]]\n\n# load aiport info\ncodes = pd.read_csv(\"hw_5_data/ICAO_airports.csv\")\ncodes_mini = codes[[\"ident\", \"latitude_deg\", \"longitude_deg\", \"wikipedia_link\"]]\ncodes_mini = codes_mini.rename(columns={'ident': \"ICAO\"})\n\n# combine data into one table\ndata = pd.merge(top50_mini, codes_mini, how=\"left\", on=\"ICAO\")", "_____no_output_____" ] ], [ [ "Load this table into a database.", "_____no_output_____" ] ], [ [ "from sqlalchemy import *\n\n# initiate engine\nengine = create_engine(\"sqlite:///airport_info.db\")\n\n# convert pd to list\ndata.to_sql(name='airports', con=engine)\n", "_____no_output_____" ] ], [ [ "# Get all weather data ... \n# ... and extract weather close to airports", "_____no_output_____" ] ], [ [ "## if need to reload data, just do this instead to save time!\n# import xarray as xr\n# airport_weather = xr.open_dataset('airport_weather.nc')", "_____no_output_____" ] ], [ [ "Get historical weather information (min/max temperature, relative humidity, perciptation) for 1990-2000 from dataset used in class (with xarray/netCDF4).", "_____no_output_____" ] ], [ [ "# load weather data!\n\nimport xarray as xr\n# temp: tasmax/tasmin, RH: rhsmax/rhsmin, precipitation: pr\n\ndatatypes = [\"tasmax\", \"tasmin\", \"rhsmax\", \"rhsmin\", \"pr\"]\ndatatypes_str = [\"air_temperature\", \"air_temperature\", \"relative_humidity\", \"relative_humidity\", \"precipitation\"]\ndatatypes_nice = [\"air_temperature_max\", \"air_temperature_min\", \"relative_humidity_max\", \"relative_humidity_min\", \"precipitation\"]\n\nstorage = []\nfor i in range(len(datatypes)):\n \n data_path = (\"http://thredds.northwestknowledge.net:8080/\"\n f\"thredds/dodsC/agg_macav2metdata_{datatypes[i]}\"\n \"_BNU-ESM_r1i1p1_historical_1950_2005_CONUS_daily.nc\"\n )\n storage.append(xr.open_dataset(data_path).rename({datatypes_str[i] : datatypes_nice[i]}))\n\n\n# combine all data types\nweather_data = xr.merge(storage)\n\n# reduce to time window of interest\ntime_window = pd.date_range(start='1/1/1990', end='12/31/2000', freq='D')\nweather_data = weather_data.sel(time=time_window)", "_____no_output_____" ] ], [ [ "Just keep weather data for coordinates closest to each aiport.", "_____no_output_____" ] ], [ [ "# for each airport, find closest (long, lat) in weather data\n\nimport numpy as np\n\n\ndef find_closest(weather_long, weather_lat, this_long, this_lat):\n \"\"\"\n Find the closest weather station to aiport longitude and \n latitude coordinates.\n \n Parameters\n ----------\n weather_long : np array\n Vector of floats with longitude coordinates for all weather stations\n weather_lat : np array\n Vector of floats with latitude coordinates for all weather stations\n this_long : float\n Longitude coordinate for this airport\n this_lat : float\n Latitude coordinate for this airport\n \n Returns\n -------\n idx : int\n Index for closest weather station\n \n \"\"\"\n # convert weather long coordinates to match expected for aiport\n weather_long_adjusted = weather_long - 360\n \n # find closest long idx:\n long_idx = np.abs(weather_long_adjusted - this_long).argmin()\n \n # find closest lat idx:\n lat_idx = np.abs(weather_lat - this_lat).argmin()\n \n return long_idx, lat_idx\n\n# extract all of the long, lat coordinates from the weather data\nweather_long = weather_data[\"lon\"].values\nweather_lat = weather_data[\"lat\"].values\n\n# extract all of the airport long, lat coordinates \nairport_long = engine.execute(\"SELECT longitude_deg FROM airports\").fetchall()\nairport_lat = engine.execute(\"SELECT latitude_deg FROM airports\").fetchall()\n\n# get airport names\nairport_ICAO = engine.execute(\"SELECT ICAO FROM airports\").fetchall()\n\n# identify the closest weather station for each airport\nweather_idx = [find_closest(weather_long, weather_lat, airport_long[i][0], airport_lat[i][0]) \n for i in range(len(airport_long))] # (long, lat)", "_____no_output_____" ], [ "# pull out weather data closest to each airport and concat into a new xarray\nstorage = []\nfor i in range(len(airport_ICAO)):\n port_data = weather_data.sel(lon=weather_long[weather_idx[i][0]], \n lat=weather_lat[weather_idx[i][1]])\n storage.append(port_data.assign_coords({\"airport_ICAO\": airport_ICAO[i][0]}).drop([\"lon\",\"lat\",\"crs\"]))\n", "_____no_output_____" ], [ "%%time\nairport_weather = xr.concat(storage, \"airport_ICAO\", coords=\"different\") \nairport_weather.to_netcdf('airport_weather.nc')\nairport_weather", "CPU times: user 815 ms, sys: 228 ms, total: 1.04 s\nWall time: 11min 8s\n" ] ], [ [ "This method of concatenating data is pretty slow... need to look for a better way to flatten the weather (long, lat) coordinates to restrict to the top airports.", "_____no_output_____" ], [ "# Weather patterns", "_____no_output_____" ], [ "I'll compare the temperature and precipitation at pairs of aiports by correlating the timeseries. I'm assuming we're interested in comparisons between different airports, so I'll set the diagonal = 0.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_shifty_corr(variable, lag):\n \"\"\"Calculate pairwise correlations between rows in \n variable matrix (with lag).\n \n Parameters\n ----------\n variable : np array or x array\n 2D array (airports x time) for variable (e.g. max temperature, precipitation)\n lag : int\n Number of offset days between correlations\n \n Returns\n -------\n corrcoeffs : np array\n 2D array (airports x airports) with pairwise correlations; columns shifted lag before rows\n \n \"\"\"\n # get number of aiports\n n_ports, n_time = variable.shape\n\n # make array for correlation coefficients\n corrcoeffs = np.empty((n_ports, n_ports))\n \n for port0 in range(n_ports):\n for port1 in range(n_ports):\n corrcoeffs[port0, port1] = np.corrcoef(variable[port0, lag:],\n variable[port1, :n_time-lag])[0, 1]\n\n # set diag to 0\n corrcoeffs[np.eye(50)==1] = 0\n \n return corrcoeffs", "_____no_output_____" ] ], [ [ "**This is the correlation of max temperature and precipitation between all airports (with no lag):**", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(15, 6))\n\nax = fig.add_subplot(1,2,1)\ntemp_corr0 = get_shifty_corr(airport_weather[\"air_temperature_max\"], 0)\ntemp_heat = ax.imshow(temp_corr0, cmap=\"plasma\", vmin=0.35, vmax=0.95)\nax.title.set_text(\"max air temperature\")\nfig.colorbar(temp_heat)\n\nax = fig.add_subplot(1,2,2)\nprec_corr0 = get_shifty_corr(airport_weather[\"precipitation\"], 0)\nprec_heat = ax.imshow(prec_corr0, cmap=\"viridis\", vmin=0, vmax=0.5)\nax.title.set_text(\"precipitation\")\nfig.colorbar(prec_heat)\n", "_____no_output_____" ] ], [ [ "**This is the correlation of max temperature between all airports with lags of 1, 3, or 7 days (columns = shifted before rows):**", "_____no_output_____" ] ], [ [ "daily_lag = [1, 3, 7]\nn_lags = len(daily_lag)\n\ntemp_corr_lag = [get_shifty_corr(airport_weather[\"air_temperature_max\"], d) for d in daily_lag]\n\nfig = plt.figure(figsize=(15, 6))\nfor d in range(n_lags):\n ax = fig.add_subplot(1, n_lags, d+1)\n heat = ax.imshow(temp_corr_lag[d], cmap=\"plasma\", vmin=0.35, vmax=0.95)\n \n ax.set(xlabel=\"leading\", ylabel=\"lagging\", title=f\"shift {daily_lag[d]}\")\n fig.colorbar(heat)", "_____no_output_____" ] ], [ [ "**This is the correlation of precipitation between all airports with lags of 1, 3, or 7 days (columns = shifted before rows):**", "_____no_output_____" ] ], [ [ "prec_corr_lag = [get_shifty_corr(airport_weather[\"precipitation\"], d) for d in daily_lag]\n\nfig = plt.figure(figsize=(15, 6))\nfor d in range(n_lags):\n ax = fig.add_subplot(1, n_lags, d+1)\n heat = ax.imshow(prec_corr_lag[d], cmap=\"viridis\", vmin=0, vmax=0.5)\n \n ax.set(xlabel=\"leading\", ylabel=\"lagging\", title=f\"shift {daily_lag[d]}\")\n fig.colorbar(heat)\n ", "_____no_output_____" ] ], [ [ "# Correlations from top 10 pairs", "_____no_output_____" ] ], [ [ "# For a given correlation matrix, find the long and lat coordinates of the top pairs\n\ndef pull_top_pairs(corrcoeffs, n_pairs, airport_long, airport_lat):\n \"\"\"Find the top n_pairs; return values and \n (long, lat) coordinates of ports in pairs.\n \n Parameters\n ----------\n corrcoeffs : np array\n 2D array (airports x airports) with pairwise correlations; columns shifted lag before rows\n n_pairs : int\n Number of top pairs \n airport_long : np array\n Vector of airport longitude coordinates\n airport_lat : np array\n Vector of aiport latitude coordinates\n \n Returns\n -------\n top_values : np array\n Vector with top correlations\n top_long : np array\n Vector of tuples with long coordinates for airports in pairs\n top_lat : np array\n Vector of tuples with lat coordinates for aiports in pairs\n \n \"\"\"\n # get number of aiports\n n_ports = corrcoeffs.shape[0]\n \n # get top n_pairs \n top_idx = np.argsort(-corrcoeffs, axis=None)[:10] # ravelled index\n top_xy = np.unravel_index(top_idx, (n_ports, n_ports)) # get (row, col) index\n \n # get the corr for these pairs\n top_values = [corrcoeffs[top_xy[0][i], top_xy[1][i]] \n for i in range(n_pairs)]\n \n # get longitude coords for pair\n top_long = [(airport_long[top_xy[0][i]][0], airport_long[top_xy[1][i]][0])\n for i in range(n_pairs)]\n \n # get latitude coords for pair\n top_lat = [(airport_lat[top_xy[0][i]][0], airport_lat[top_xy[1][i]][0])\n for i in range(n_pairs)]\n \n return top_values, top_long, top_lat", "_____no_output_____" ] ], [ [ "**Top temperature correlations as a function of distance:**", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(15, 10))\n\nfor d in range(n_lags):\n \n # get top 10 pairs\n top_values, top_long, top_lat = pull_top_pairs(temp_corr_lag[d], 10, airport_long, airport_lat)\n \n # cartesian distance\n cart_dist = [((long[0] - long[1]) ** 2 + (lat[0] - lat[1]) ** 2) ** 0.5 \n for long, lat in zip(top_long, top_lat)]\n \n # longitude distance\n long_dist = [np.abs(long[0] - long[1]) for long in top_long]\n \n # plot value vs cart dist\n ax = fig.add_subplot(2, n_lags, d+1)\n ax.scatter(cart_dist, top_values, color='r')\n ax.set(xlabel=\"distance between best pairs (~deg)\", \n ylabel=\"temperature correlation\", \n title=f\"shift {daily_lag[d]}\",\n xlim=[0, 10],\n ylim=[0.85, 1])\n \n # plot value vs long dist\n ax = fig.add_subplot(2, n_lags, d+1+n_lags)\n ax.scatter(long_dist, top_values, color='r')\n ax.set(xlabel=\"longitude difference between best pairs (deg)\", \n ylabel=\"temperature correlation\", \n title=f\"shift {daily_lag[d]}\",\n xlim=[0, 10],\n ylim=[0.85, 1])\n", "_____no_output_____" ] ], [ [ "Temperature correlations for the most tightly linked airport pairs decreased with longer lags (1 --> 7 days) but remained quite high overall (> 0.85), as expected given the relatively slow annual cycle in temperature. The best pairs spanned approximately the same range of distances for all lags. Airports with similar temperature trends were at similar latitudes: the distance range for the top pairs was very similar if measured as a function of longitude and latitude or just longitude alone.\n\n(I used cartesian coordinates to approximate the distance between (long, lat) coordinates to simplify calculations. It would be more correct to calculate the distance along the sphere surface.)", "_____no_output_____" ], [ "**Top precipitation correlations as a function of distance:**", "_____no_output_____" ] ], [ [ "fig = plt.figure(figsize=(15, 10))\n\nfor d in range(n_lags):\n \n # get top 10 pairs\n top_values, top_long, top_lat = pull_top_pairs(prec_corr_lag[d], 10, airport_long, airport_lat)\n \n # cartesian distance\n cart_dist = [((long[0] - long[1]) ** 2 + (lat[0] - lat[1]) ** 2) ** 0.5 \n for long, lat in zip(top_long, top_lat)]\n \n # longitude distance\n long_dist = [np.abs(long[0] - long[1]) for long in top_long]\n \n # plot value vs cart dist\n ax = fig.add_subplot(2, n_lags, d+1)\n ax.scatter(cart_dist, top_values, color='b')\n ax.set(xlabel=\"distance between best pairs (~deg)\", \n ylabel=\"precipitation correlation\", \n title=f\"shift {daily_lag[d]}\",\n xlim=[0, 11],\n ylim=[0.1, 0.6])\n \n # plot value vs long dist\n ax = fig.add_subplot(2, n_lags, d+1+n_lags)\n ax.scatter(long_dist, top_values, color='b')\n ax.set(xlabel=\"longitude difference between best pairs (deg)\", \n ylabel=\"precipitation correlation\", \n title=f\"shift {daily_lag[d]}\",\n xlim=[0, 11],\n ylim=[0.1, 0.6])\n", "_____no_output_____" ] ], [ [ "Peak precipitation correlations fell from ~0.5 to ~0.1-0.2 within a couple of days, and the distance between the best pairs decreased from up to 10 deg to up to 2 deg. This is reasonable, since precipitation patterns are more local than temperature and can change daily.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4aed54c905cfc2ab2079c48840864282036236fa
5,720
ipynb
Jupyter Notebook
NAIP/ndwi_single.ipynb
c11/earthengine-py-notebooks
144b57e4d952da095ba73c3cc8ce2f36291162ff
[ "MIT" ]
1
2020-05-31T14:19:59.000Z
2020-05-31T14:19:59.000Z
NAIP/ndwi_single.ipynb
c11/earthengine-py-notebooks
144b57e4d952da095ba73c3cc8ce2f36291162ff
[ "MIT" ]
null
null
null
NAIP/ndwi_single.ipynb
c11/earthengine-py-notebooks
144b57e4d952da095ba73c3cc8ce2f36291162ff
[ "MIT" ]
null
null
null
43.333333
1,031
0.598077
[ [ [ "<table class=\"ee-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/NAIP/ndwi_single.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n <td><a target=\"_blank\" href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/NAIP/ndwi_single.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/NAIP/ndwi_single.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n</table>", "_____no_output_____" ], [ "## Install Earth Engine API and geemap\nInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\nThe following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n\n**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).", "_____no_output_____" ] ], [ [ "# Installs geemap package\nimport subprocess\n\ntry:\n import geemap\nexcept ImportError:\n print('geemap package not installed. Installing ...')\n subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n\n# Checks whether this notebook is running on Google Colab\ntry:\n import google.colab\n import geemap.eefolium as emap\nexcept:\n import geemap as emap\n\n# Authenticates and initializes Earth Engine\nimport ee\n\ntry:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize() ", "_____no_output_____" ] ], [ [ "## Create an interactive map \nThe default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. ", "_____no_output_____" ] ], [ [ "Map = emap.Map(center=[40,-100], zoom=4)\nMap.add_basemap('ROADMAP') # Add Google Map\nMap", "_____no_output_____" ] ], [ [ "## Add Earth Engine Python script ", "_____no_output_____" ] ], [ [ "# Add Earth Engine dataset\n", "_____no_output_____" ] ], [ [ "## Display Earth Engine data layers ", "_____no_output_____" ] ], [ [ "Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\nMap", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aed7f864369d36826c453ee811e1dc8ab26c406
17,659
ipynb
Jupyter Notebook
notebooks/validate-adu-spr.ipynb
CityOfLosAngeles/planning-entitlements
cf83b57063b4e55722cc640172b529611b263b3a
[ "Apache-2.0" ]
null
null
null
notebooks/validate-adu-spr.ipynb
CityOfLosAngeles/planning-entitlements
cf83b57063b4e55722cc640172b529611b263b3a
[ "Apache-2.0" ]
55
2020-01-08T17:50:17.000Z
2021-01-13T21:45:31.000Z
notebooks/validate-adu-spr.ipynb
CityOfLosAngeles/planning-entitlements
cf83b57063b4e55722cc640172b529611b263b3a
[ "Apache-2.0" ]
2
2020-07-16T02:10:30.000Z
2021-01-25T21:14:49.000Z
46.227749
1,513
0.597429
[ [ [ "# Check original file against published reports\n## ADU / SPR", "_____no_output_____" ] ], [ [ "import intake\nimport numpy as np\nimport pandas as pd\nimport laplan\n\ncatalog = intake.open_catalog('../catalogs/*.yml')\nbucket_name = \"city-planning-entitlements\"", "_____no_output_____" ], [ "start_date = \"1/1/10\"\nend_date = \"10/31/19\"\n\n# Let's throw our new master_pcts into the d1_step_by_step\n#master_pcts = catalog.pcts2.read()\nmaster_pcts = pd.read_parquet('s3://city-planning-entitlements/test_new_master_pcts.parquet')", "_____no_output_____" ] ], [ [ "### PCTS Reporting Module Results", "_____no_output_____" ] ], [ [ "def import_and_subset(name):\n df = pd.read_excel(f'../data/pcts_{name}.xlsx', skiprows=4)\n keep = [\"CASE NUMBER\", \"FILE DATE\"]\n df = df[keep].rename(columns = {\"CASE NUMBER\": \"CASE_NBR\"})\n return df", "_____no_output_____" ] ], [ [ "### ITA laplan function", "_____no_output_____" ] ], [ [ "# All prefixes and suffixes\n# This is our old master_pcts\ndef laplan_subset(name):\n name = name.upper()\n pcts = laplan.pcts.subset_pcts(\n master_pcts, \n start_date = start_date , end_date = end_date,\n get_dummies=True, verbose=False)\n pcts = laplan.pcts.drop_child_cases(pcts, keep_child_entitlements=False)\n \n pcts = pcts[pcts[name]==True]\n \n return pcts", "_____no_output_____" ] ], [ [ "### ITA step-by-step in creating master_pcts", "_____no_output_____" ] ], [ [ "def ita_step_by_step(name):\n name = name.upper()\n print(f\"{name}: Creating master PCTS step-by-step\")\n \n case = pd.read_parquet(f's3://{bucket_name}/data/raw/tCASE.parquet')\n app = pd.read_parquet(f's3://{bucket_name}/data/raw/tAPLC.parquet')\n geo_info = pd.read_parquet(f's3://{bucket_name}/data/raw/tPROP_GEO_INFO.parquet')\n la_prop = pd.read_parquet(f's3://{bucket_name}/data/raw/tLA_PROP.parquet')\n\n app1 = app[['APLC_ID', 'PROJ_DESC_TXT']]\n geo_info1 = geo_info[['CASE_ID', 'PROP_ID']]\n la_prop1 = la_prop[la_prop.ASSR_PRCL_NBR.notna()][['PROP_ID', 'ASSR_PRCL_NBR']]\n \n # Subset by start/end date\n case2 = case[(case.CASE_FILE_RCV_DT >= start_date) & \n (case.CASE_FILE_RCV_DT <= end_date)]\n \n # Subset by suffix \n case3 = case2[case2.CASE_NBR.str.contains(f\"-{name}\")]\n \n print(f'1-# unique cases (parents + child): {case3.CASE_NBR.nunique()}')\n \n # Keep parent cases only\n case4 = case3[case3.PARNT_CASE_ID.isna()]\n \n print(f'2-# unique cases (parents): {case4.CASE_NBR.nunique()}')\n \n m1 = pd.merge(case4, geo_info1, on = 'CASE_ID', how = 'inner', validate = '1:m')\n m2 = pd.merge(m1, la_prop1, on = 'PROP_ID', how = 'inner', validate = 'm:1')\n m3 = pd.merge(m2, app1, on = 'APLC_ID', how = 'left', validate = 'm:1')\n \n print(f'3-# unique cases (parents), with geo_info merged: {m1.CASE_NBR.nunique()}')\n print(f'4-# unique cases (parents), with la_prop merged: {m2.CASE_NBR.nunique()}')\n print(f'5-# unique cases (parents), with app merged: {m3.CASE_NBR.nunique()}')\n", "_____no_output_____" ] ], [ [ "### ITA D1 step-by-step for dashboard", "_____no_output_____" ] ], [ [ "prefix_list = laplan.pcts.VALID_PCTS_PREFIX\nsuffix_list = laplan.pcts.VALID_PCTS_SUFFIX\n\nremove_prefix = [\"ENV\"]\nremove_suffix = [\n \"EIR\",\n \"IPRO\",\n \"CA\",\n \"CATEX\",\n \"CPIO\",\n \"CPU\",\n \"FH\",\n \"G\",\n \"HD\",\n \"HPOZ\",\n \"ICO\",\n \"K\",\n \"LCP\",\n \"NSO\",\n \"S\",\n \"SN\",\n \"SP\",\n \"ZAI\",\n \"CRA\", \n \"RFA\",\n]\n\nprefix_list = [x for x in prefix_list if x not in remove_prefix]\nsuffix_list = [x for x in suffix_list if x not in remove_suffix]\n\ndef d1_step_by_step(name):\n name = name.upper()\n print(f\"{name}: D1 step-by-step\")\n \n # Load PCTS and subset to the prefix / suffix list we want\n pcts = laplan.pcts.subset_pcts(\n master_pcts,\n start_date = start_date, end_date = end_date,\n prefix_list=prefix_list, suffix_list=suffix_list,\n get_dummies=True, verbose=False,\n )\n pcts = laplan.pcts.drop_child_cases(pcts, keep_child_entitlements=True)\n pcts = pcts[pcts[name]==True][[\"CASE_NBR\", \"CASE_ID\", \"AIN\"]]\n \n print(f'1-# unique cases (parents) using laplan: {pcts.CASE_NBR.nunique()}')\n \n # Add on tract info\n # See which cases have AINs, but those AINs are not mapped onto tract GEOID\n parcel_to_tract = catalog.crosswalk_parcels_tracts.read()\n parcel_to_tract = parcel_to_tract[[\"AIN\", \"num_AIN\", \"GEOID\"]]\n\n pcts = pd.merge(\n pcts,\n parcel_to_tract, \n on=\"AIN\",\n how=\"inner\",\n validate=\"m:1\",\n )\n \n print(f'2-# unique cases (parents), with tract merged in: {pcts.CASE_NBR.nunique()}')\n \n # Clean AIN data and get rid of outliers\n case_counts = pcts.CASE_ID.value_counts()\n big_cases = pcts[pcts.CASE_ID.isin(case_counts[case_counts > 20].index)]\n\n pcts = pcts[~pcts.CASE_ID.isin(big_cases.CASE_ID)]\n \n print(f'3-# unique cases (parents) removing outliers: {pcts.CASE_NBR.nunique()}')", "_____no_output_____" ] ], [ [ "## Comparisons", "_____no_output_____" ] ], [ [ "# Put functions all together\ndef comparison(suffix):\n dcp = import_and_subset(suffix)\n ita = laplan_subset(suffix)\n\n print(\"Discrepancies in DCP vs ITA\")\n print(f'DCP-{suffix.upper()} unique cases (parents) in PCTS report: {dcp.CASE_NBR.nunique()}')\n print(f'ITA-{suffix.upper()} unique cases (parents) with laplan, all prefixes/suffixes: {ita.CASE_NBR.nunique()}') \n #ita_step_by_step(suffix)\n d1_step_by_step(suffix)", "_____no_output_____" ], [ "comparison(\"1a\")", "Discrepancies in DCP vs ITA\nDCP-1A unique cases (parents) in PCTS report: 1412\nITA-1A unique cases (parents) with laplan, all prefixes/suffixes: 0\n1A: D1 step-by-step\n1-# unique cases (parents) using laplan: 1110\n2-# unique cases (parents), with tract merged in: 1110\n3-# unique cases (parents) removing outliers: 1110\n" ], [ "comparison(\"2a\")", "Discrepancies in DCP vs ITA\nDCP-2A unique cases (parents) in PCTS report: 119\nITA-2A unique cases (parents) with laplan, all prefixes/suffixes: 0\n2A: D1 step-by-step\n1-# unique cases (parents) using laplan: 67\n2-# unique cases (parents), with tract merged in: 67\n3-# unique cases (parents) removing outliers: 67\n" ], [ "comparison(\"5a\")", "Discrepancies in DCP vs ITA\nDCP-5A unique cases (parents) in PCTS report: 3\nITA-5A unique cases (parents) with laplan, all prefixes/suffixes: 0\n5A: D1 step-by-step\n" ], [ "#comparison(\"adu\")", "_____no_output_____" ], [ "#comparison(\"spr\")", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4aed804abbee5ff538fd58d3aa2e420663e964b6
77,930
ipynb
Jupyter Notebook
model_comparison.ipynb
bill9800/Amazon-review-sentiment-analysis
aa7b86bca7d8ab884996d89115aeb7e223115abc
[ "MIT" ]
null
null
null
model_comparison.ipynb
bill9800/Amazon-review-sentiment-analysis
aa7b86bca7d8ab884996d89115aeb7e223115abc
[ "MIT" ]
null
null
null
model_comparison.ipynb
bill9800/Amazon-review-sentiment-analysis
aa7b86bca7d8ab884996d89115aeb7e223115abc
[ "MIT" ]
null
null
null
68.842756
46,216
0.803619
[ [ [ "import pandas as pd\nimport numpy as np\nfrom sklearn.externals import joblib\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score\nimport time\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score,recall_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn import metrics", "_____no_output_____" ], [ "## Preprocess\ndf_raw_data = pd.read_csv('reviews.csv',sep='|',header=0)\ndf_train = df_raw_data.iloc[df_raw_data.index %5 != 0]\ndf_test = df_raw_data.iloc[df_raw_data.index %5 == 0]\n\n# preprocess X\n# word of bag\nword_bag = joblib.load('word_bag.pkl')\n\nX_test = df_test.loc[:,'text'].tolist()\nX_test = word_bag.transform(X_test)\n\nX_train = df_train.loc[:,'text'].tolist()\nX_train = word_bag.transform(X_train)\n\n# preprocess y\ny = df_test['label']\nlec = LabelEncoder()\ny_test = lec.fit_transform(y)\n\ny = df_train['label']\nlec = LabelEncoder()\ny_train = lec.fit_transform(y)", "_____no_output_____" ], [ "# get the feature (v2)\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n## Preprocess\ndf_raw_data = pd.read_csv('reviews.csv',sep='|',header=0)\ndf_train = df_raw_data.iloc[df_raw_data.index %5 != 0]\ndf_test = df_raw_data.iloc[df_raw_data.index %5 == 0]\n\n## Preprocess\nX_train = df_train.loc[:,'text'].tolist()\nX_test = df_test.loc[:,'text'].tolist()\ntransformer = TfidfVectorizer()\n#ngram_range=(1, 3)\nX_train = transformer.fit_transform(X_train)\nfeature_tfidf_name = transformer.get_feature_names()\nX_test = transformer.transform(X_test)\n\n# preprocess y\ny = df_test['label']\nlec = LabelEncoder()\ny_test = lec.fit_transform(y)\n\ny = df_train['label']\nlec = LabelEncoder()\ny_train = lec.fit_transform(y)", "_____no_output_____" ], [ "joblib.dump(feature_tfidf_name,'tfidf_features.pkl')", "_____no_output_____" ], [ "joblib.dump(transformer,'final_model/Tfidf_n_3.pkl')", "_____no_output_____" ] ], [ [ "## Decision Tree", "_____no_output_____" ] ], [ [ "from sklearn.tree import DecisionTreeClassifier", "_____no_output_____" ], [ "tic = time.time()\nclf = DecisionTreeClassifier(criterion='entropy',max_depth=50)\nclf.fit(X_train,y_train)\ntac = time.time()\nprint('training time:',tac-tic,'s')", "training time: 841.031721830368 s\n" ], [ "joblib.dump(clf,'final_model/decision_tree.pkl')", "_____no_output_____" ], [ "# accurarcy\ny_pred = clf.predict(X_train)\nDT_train_ac = accuracy_score(y_train,y_pred)\ny_pred = clf.predict(X_test)\nDT_test_ac = accuracy_score(y_test,y_pred)", "_____no_output_____" ], [ "print('training accuracy:',DT_train_ac*100,'%')\nprint('testing accuracy:',DT_test_ac*100,'%')", "training accuracy: 93.4177420918 %\ntesting accuracy: 76.157673651 %\n" ], [ "# precision and recall\nDT_p_score = precision_score(y_test,y_pred)\nDT_r_score = recall_score(y_test,y_pred)\nDT_f1_score = 2*(DT_p_score*DT_r_score)/(DT_p_score+DT_r_score)\nprint(\"precision: \",DT_p_score,\" recall: \",DT_r_score,\" f1: \",DT_f1_score)", "precision: 0.756514678019 recall: 0.770140280561 f1: 0.763266674115\n" ], [ "# ROC\nDT_fpr,DT_tpr, DT_thresholds = roc_curve(y_test,y_pred)\nprint(DT_fpr,DT_tpr, DT_thresholds)", "[ 0. 0.24695518 1. ] [ 0. 0.77014028 1. ] [2 1 0]\n" ] ], [ [ "## NN model", "_____no_output_____" ] ], [ [ "from sklearn.neural_network import MLPClassifier", "_____no_output_____" ], [ "tic = time.time()\nclf = MLPClassifier(hidden_layer_sizes = (10,10),activation='logistic',max_iter=200,\n learning_rate_init = 0.01,learning_rate='invscaling',\n solver='adam',early_stopping=True,random_state=42)\nclf.fit(X_train,y_train)\ntac = time.time()\nprint('training time:',tac-tic,'s')", "training time: 1177.0293114185333 s\n" ], [ "joblib.dump(clf,'final_model/nn_model.pkl')", "_____no_output_____" ], [ "# accurarcy\ny_pred = clf.predict(X_train)\nNN_train_ac = accuracy_score(y_train,y_pred)\ny_pred = clf.predict(X_test)\nNN_test_ac = accuracy_score(y_test,y_pred)\nprint('training accuracy:',NN_train_ac*100,'%')\nprint('testing accuracy:',NN_test_ac*100,'%')", "training accuracy: 93.1561395339 %\ntesting accuracy: 90.1235185278 %\n" ], [ "# precision and recall\nNN_p_score = precision_score(y_test,y_pred)\nNN_r_score = recall_score(y_test,y_pred)\nNN_f1_score = 2*(NN_p_score*NN_r_score)/(NN_p_score+NN_r_score)\nprint(\"precision: \",NN_p_score,\" recall: \",NN_r_score,\" f1: \",NN_f1_score)", "precision: 0.917797494781 recall: 0.881012024048 f1: 0.899028629857\n" ], [ "# ROC\nNN_fpr,NN_tpr, NN_thresholds = roc_curve(y_test,y_pred)\nprint(NN_fpr,NN_tpr, NN_thresholds)", "[ 0. 0.07861635 1. ] [ 0. 0.88101202 1. ] [2 1 0]\n" ] ], [ [ "## Logistic Regression", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression", "_____no_output_____" ], [ "tic = time.time()\nclf = LogisticRegression()\nclf.fit(X_train,y_train)\ntac = time.time()\nprint('training time:',tac-tic,'s')", "training time: 25.659657955169678 s\n" ], [ "joblib.dump(clf,'final_model/logistic.pkl')", "_____no_output_____" ], [ "# accurarcy\ny_pred = clf.predict(X_train)\nLG_train_ac = accuracy_score(y_train,y_pred)\ny_pred = clf.predict(X_test)\nLG_test_ac = accuracy_score(y_test,y_pred)\nprint('training accuracy:',LG_train_ac*100,'%')\nprint('testing accuracy:',LG_test_ac*100,'%')", "training accuracy: 91.9943991424 %\ntesting accuracy: 90.443566535 %\n" ], [ "# precision and recall\nLG_p_score = precision_score(y_test,y_pred)\nLG_r_score = recall_score(y_test,y_pred)\nLG_f1_score = 2*(LG_p_score*LG_r_score)/(LG_p_score+LG_r_score)\nprint(\"precision: \",LG_p_score,\" recall: \",LG_r_score,\" f1: \",LG_f1_score)", "precision: 0.903470173509 recall: 0.905235470942 f1: 0.90435196076\n" ], [ "# ROC\nLG_fpr,LG_tpr, LG_thresholds = roc_curve(y_test,y_pred)\nprint(LG_fpr,LG_tpr, LG_thresholds)", "[ 0. 0.09636119 1. ] [ 0. 0.90523547 1. ] [2 1 0]\n" ] ], [ [ "## Ensemble model", "_____no_output_____" ], [ "## RandomForest", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier", "_____no_output_____" ], [ "tic = time.time()\nclf = RandomForestClassifier(n_jobs=-1)\nclf.fit(X_train,y_train)\ntac = time.time()\nprint('training time:',tac-tic,'s')", "training time: 271.4661648273468 s\n" ], [ "joblib.dump(clf,'final_model/random_forest.pkl')", "_____no_output_____" ], [ "# accurarcy\ny_pred = clf.predict(X_train)\nRF_train_ac = accuracy_score(y_train,y_pred)\ny_pred = clf.predict(X_test)\nRF_test_ac = accuracy_score(y_test,y_pred)\nprint('training accuracy:',RF_train_ac*100,'%')\nprint('testing accuracy:',RF_test_ac*100,'%')", "training accuracy: 99.4077218074 %\ntesting accuracy: 78.468020203 %\n" ], [ "# precision and recall\nRF_p_score = precision_score(y_test,y_pred)\nRF_r_score = recall_score(y_test,y_pred)\nRF_f1_score = 2*(RF_p_score*RF_r_score)/(RF_p_score+RF_r_score)\nprint(\"precision: \",RF_p_score,\" recall: \",RF_r_score,\" f1: \",RF_f1_score)", "precision: 0.831082066692 recall: 0.713602204409 f1: 0.767874711916\n" ], [ "# ROC\nRF_fpr,RF_tpr, RF_thresholds = roc_curve(y_test,y_pred)\nprint(RF_fpr,RF_tpr, RF_thresholds)", "[ 0. 0.14450434 1. ] [ 0. 0.7136022 1. ] [2 1 0]\n" ] ], [ [ "## logistic+randomforest+NN", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import VotingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nimport time", "_____no_output_____" ], [ "tic = time.time()\nclf1 = RandomForestClassifier(n_jobs=-1)\nclf2 = LogisticRegression(n_jobs=-1,random_state=42)\nclf3 = MLPClassifier(hidden_layer_sizes = (10,10),activation='logistic',max_iter=100,\n learning_rate_init = 0.01,learning_rate='invscaling',\n solver='adam',early_stopping=True,random_state=42)\n\neclf1 = VotingClassifier(estimators=[\n ('rf', clf1), ('lg', clf2),('nn',clf3)],n_jobs=-1,voting='soft')\neclf1.fit(X_train,y_train)\ntac = time.time()\nprint('training time:',tac-tic,'s')", "training time: 1486.9226295948029 s\n" ], [ "joblib.dump(eclf1,'final_model/ensemble.pkl')", "_____no_output_____" ], [ "# accurarcy\ny_pred = eclf1.predict(X_train)\nES_train_ac = accuracy_score(y_train,y_pred)\ny_pred = eclf1.predict(X_test)\nES_test_ac = accuracy_score(y_test,y_pred)\nprint('training accuracy:',RF_train_ac*100,'%')\nprint('testing accuracy:',RF_test_ac*100,'%')", "training accuracy: 95.8246731531 %\ntesting accuracy: 90.4348152223 %\n" ], [ "# precision and recall\nRF_p_score = precision_score(y_test,y_pred)\nRF_r_score = recall_score(y_test,y_pred)\nRF_f1_score = 2*(RF_p_score*RF_r_score)/(RF_p_score+RF_r_score)\nprint(\"precision: \",RF_p_score,\" recall: \",RF_r_score,\" f1: \",RF_f1_score)", "_____no_output_____" ] ], [ [ "## ROC curve", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "DT_clf = joblib.load('final_model/decision_tree.pkl')\nNN_clf = joblib.load('final_model/nn_model.pkl')\nLG_clf = joblib.load('final_model/logistic.pkl')\nRF_clf = joblib.load('final_model/random_forest.pkl')\nES_clf = joblib.load('final_model/ensemble.pkl')", "_____no_output_____" ], [ "print([DT_roc_auc*100,LG_roc_auc*100,NN_roc_auc*100,RF_roc_auc*100,ES_roc_auc*100])", "[78.013854122090649, 96.510333860293201, 96.469514475691938, 86.421485309893029, 96.265507329923921]\n" ], [ "#calculate the fpr and tpr for all thresholds of the classification\n#decision tree\nDT_probs = DT_clf.predict_proba(X_test)\nDT_preds = DT_probs[:,1]\nDT_fpr, DT_tpr, DT_threshold = metrics.roc_curve(y_test,DT_preds)\nDT_roc_auc = metrics.auc(DT_fpr, DT_tpr)\n\nLG_probs = LG_clf.predict_proba(X_test)\nLG_preds = LG_probs[:,1]\nLG_fpr, LG_tpr, LG_threshold = metrics.roc_curve(y_test,LG_preds)\nLG_roc_auc = metrics.auc(LG_fpr, LG_tpr)\n\nNN_probs = NN_clf.predict_proba(X_test)\nNN_preds = NN_probs[:,1]\nNN_fpr, NN_tpr, NN_threshold = metrics.roc_curve(y_test,NN_preds)\nNN_roc_auc = metrics.auc(NN_fpr, NN_tpr)\n\nRF_probs = RF_clf.predict_proba(X_test)\nRF_preds = RF_probs[:,1]\nRF_fpr, RF_tpr, RF_threshold = metrics.roc_curve(y_test,RF_preds)\nRF_roc_auc = metrics.auc(RF_fpr, RF_tpr)\n\nES_probs = ES_clf.predict_proba(X_test)\nES_preds = ES_probs[:,1]\nES_fpr, ES_tpr, ES_threshold = metrics.roc_curve(y_test,ES_preds)\nES_roc_auc = metrics.auc(ES_fpr, ES_tpr)\n\n# plot\nplt.title('Receiver Operating Characteristic')\nplt.plot(DT_fpr, DT_tpr, 'b', label = 'Decision_Tree_AUC = %0.2f' % DT_roc_auc)\nplt.plot(LG_fpr, LG_tpr, 'm', label = 'Logistic_Regression_AUC = %0.2f' % LG_roc_auc)\nplt.plot(NN_fpr, NN_tpr, 'g', label = 'Neural_net(10*10)_AUC = %0.2f' % NN_roc_auc)\nplt.plot(RF_fpr, RF_tpr, 'c', label = 'Random_Forest_AUC = %0.2f' % RF_roc_auc)\nplt.plot(ES_fpr, ES_tpr, 'y', label = 'Ensemble(logitistic+NN+Random_forest)_AUC = %0.2f' % ES_roc_auc)\n\nplt.legend(loc = 'lower right')\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([0, 1])\nplt.ylim([0, 1])\nplt.ylabel('True Positive Rate (tpr)')\nplt.xlabel('False Positive Rate (fpr)')\nplt.show()", "_____no_output_____" ] ], [ [ "## Evaluate model", "_____no_output_____" ] ], [ [ "y_pred = DT_clf.predict(X_train)\nDT_train_ac = accuracy_score(y_train,y_pred)*100\ny_pred = NN_clf.predict(X_train)\nNN_train_ac = accuracy_score(y_train,y_pred)*100\ny_pred = LG_clf.predict(X_train)\nLG_train_ac = accuracy_score(y_train,y_pred)*100\ny_pred = RF_clf.predict(X_train)\nRF_train_ac = accuracy_score(y_train,y_pred)*100\ny_pred = ES_clf.predict(X_train)\nES_train_ac = accuracy_score(y_train,y_pred)*100\nTraining_ac = [DT_train_ac,LG_train_ac,NN_train_ac,RF_train_ac,ES_train_ac]\nprint(Training_ac)", "[93.417742091757802, 91.994399142368678, 93.156139533866124, 99.407721807401757, 95.82467315307656]\n" ], [ "y_pred = DT_clf.predict(X_test)\nDT_test_ac = accuracy_score(y_test,y_pred)*100\nDT_p_score = precision_score(y_test,y_pred)*100\nDT_r_score = recall_score(y_test,y_pred)*100\nDT_f1_score = 2*(DT_p_score*DT_r_score)/(DT_p_score+DT_r_score)\n\ny_pred = LG_clf.predict(X_test)\nLG_test_ac = accuracy_score(y_test,y_pred)*100\nLG_p_score = precision_score(y_test,y_pred)*100\nLG_r_score = recall_score(y_test,y_pred)*100\nLG_f1_score = 2*(LG_p_score*LG_r_score)/(LG_p_score+LG_r_score)\n\ny_pred = NN_clf.predict(X_test)\nNN_test_ac = accuracy_score(y_test,y_pred)*100\nNN_p_score = precision_score(y_test,y_pred)*100\nNN_r_score = recall_score(y_test,y_pred)*100\nNN_f1_score = 2*(NN_p_score*NN_r_score)/(NN_p_score+NN_r_score)\n\ny_pred = RF_clf.predict(X_test)\nRF_test_ac = accuracy_score(y_test,y_pred)*100\nRF_test_ac = accuracy_score(y_test,y_pred)*100\nRF_p_score = precision_score(y_test,y_pred)*100\nRF_r_score = recall_score(y_test,y_pred)*100\nRF_f1_score = 2*(RF_p_score*RF_r_score)/(RF_p_score+RF_r_score)\n\ny_pred = ES_clf.predict(X_test)\nES_test_ac = accuracy_score(y_test,y_pred)*100\nES_test_ac = accuracy_score(y_test,y_pred)*100\nES_p_score = precision_score(y_test,y_pred)*100\nES_r_score = recall_score(y_test,y_pred)*100\nES_f1_score = 2*(ES_p_score*ES_r_score)/(ES_p_score+ES_r_score)\n\nTesting_ac = [DT_test_ac,LG_test_ac,NN_test_ac,RF_test_ac,ES_test_ac]\nprint(Testing_ac)\np_score = [DT_p_score,LG_p_score,NN_p_score,RF_p_score,ES_p_score]\nprint(p_score)\nr_score = [DT_r_score,LG_r_score,NN_r_score,RF_r_score,ES_r_score]\nprint(r_score)\nf1_score = [DT_f1_score,LG_f1_score,NN_f1_score,RF_f1_score,ES_f1_score]\nprint(f1_score)", "[76.157673651047659, 90.443566534980249, 90.123518527779169, 78.468020203030449, 90.434815222283333]\n[75.651467801865209, 90.347017350867546, 91.779749478079324, 83.108206669195084, 91.320716060132654]\n[77.014028056112224, 90.523547094188373, 88.101202404809627, 71.360220440881761, 89.323647294589179]\n[76.32666741146241, 90.435196075977871, 89.902862985685061, 76.787471191557614, 90.311142629199537]\n" ] ], [ [ "## Feature importance", "_____no_output_____" ] ], [ [ "values = sorted(zip(feature_tfidf_name, RF_clf.feature_importances_), key=lambda x: x[1] * -1)\nfeature_imp = {}\nfor i in zip(feature_tfidf_name, RF_clf.feature_importances_*100):\n feature_imp[i[0]] = i[1]", "_____no_output_____" ], [ "print(values[:50])", "[('not', 0.020812454729523897), ('great', 0.011469824135427315), ('waste', 0.0074298190663252368), ('and', 0.0054899028737268717), ('best', 0.0054132389636220033), ('money', 0.0048467353136542393), ('bad', 0.0043647785224612346), ('was', 0.0043067911473494373), ('good', 0.0042278323380913405), ('the', 0.0042183249253557424), ('love', 0.0042044315897036928), ('boring', 0.0041962503533852858), ('but', 0.0039754334912661263), ('easy', 0.0038757622973307356), ('it', 0.0037445684814688693), ('excellent', 0.0037414389727968927), ('for', 0.0036714666000187044), ('this', 0.0036158761734949572), ('is', 0.0036148620332547864), ('don', 0.003538723803220927), ('worst', 0.0035265968563098112), ('of', 0.003506178050248894), ('to', 0.0034763272718490042), ('perfect', 0.003454931381316334), ('poor', 0.0033924146584344158), ('my', 0.0033677523732797672), ('no', 0.003322701223017221), ('disappointed', 0.0031840367702931595), ('you', 0.0031353170782277159), ('disappointing', 0.0030334692688426608), ('highly', 0.0030215287832989048), ('do', 0.0030095305925312574), ('horrible', 0.0029908909655939147), ('in', 0.002990604973833441), ('well', 0.0029452258903113564), ('amazing', 0.0028173453248039326), ('awesome', 0.0027982857417187465), ('that', 0.0027726317085035846), ('on', 0.0026778703790062849), ('if', 0.0026457304878938818), ('didn', 0.0025656945427268182), ('with', 0.002505161413830931), ('be', 0.0024655732861665149), ('have', 0.0024510863521910809), ('awful', 0.002451049031773261), ('only', 0.0022683634569497417), ('or', 0.002212458940087831), ('beautiful', 0.0021824545398920984), ('would', 0.0021417861647770762), ('as', 0.0021207048048827548)]\n" ], [ "top_50_imp_words = []\ntop_50_imp_rate = []\nfor i in values[:50]:\n top_50_imp_words.append(i[0])\n top_50_imp_rate.append(i[1]*100)", "_____no_output_____" ], [ "print(top_50_imp_words)\nprint(top_50_imp_rate)", "['not', 'great', 'waste', 'and', 'best', 'money', 'bad', 'was', 'good', 'the', 'love', 'boring', 'but', 'easy', 'it', 'excellent', 'for', 'this', 'is', 'don', 'worst', 'of', 'to', 'perfect', 'poor', 'my', 'no', 'disappointed', 'you', 'disappointing', 'highly', 'do', 'horrible', 'in', 'well', 'amazing', 'awesome', 'that', 'on', 'if', 'didn', 'with', 'be', 'have', 'awful', 'only', 'or', 'beautiful', 'would', 'as']\n[2.0812454729523897, 1.1469824135427316, 0.74298190663252373, 0.54899028737268718, 0.54132389636220035, 0.4846735313654239, 0.43647785224612345, 0.43067911473494375, 0.42278323380913407, 0.42183249253557425, 0.42044315897036927, 0.41962503533852857, 0.39754334912661266, 0.38757622973307354, 0.37445684814688696, 0.37414389727968927, 0.36714666000187046, 0.36158761734949574, 0.36148620332547865, 0.35387238032209267, 0.3526596856309811, 0.35061780502488937, 0.3476327271849004, 0.3454931381316334, 0.33924146584344156, 0.33677523732797671, 0.33227012230172209, 0.31840367702931593, 0.31353170782277157, 0.30334692688426607, 0.30215287832989046, 0.30095305925312577, 0.29908909655939148, 0.29906049738334411, 0.29452258903113565, 0.28173453248039326, 0.27982857417187468, 0.27726317085035845, 0.26778703790062847, 0.2645730487893882, 0.2565694542726818, 0.25051614138309308, 0.2465573286166515, 0.24510863521910808, 0.24510490317732608, 0.22683634569497418, 0.22124589400878308, 0.21824545398920983, 0.21417861647770761, 0.21207048048827548]\n" ], [ "joblib.dump(top_50_imp_words,'top_50_imp_words.pkl')", "_____no_output_____" ], [ "top_50_words = joblib.load('top_50_words.pkl')", "_____no_output_____" ], [ "feature_imp[''] = 0", "_____no_output_____" ], [ "importances = []\nfor i in top_50_words:\n importances.append(feature_imp[i])", "_____no_output_____" ], [ "print(importances)", "[0.42183249253557425, 0.54899028737268718, 0.3476327271849004, 0.35061780502488937, 0.37445684814688696, 0.36158761734949574, 0.36148620332547865, 0.29906049738334411, 0.36714666000187046, 0.27726317085035845, 0.43067911473494375, 2.0812454729523897, 0.31353170782277157, 0.25051614138309308, 0.39754334912661266, 0.26778703790062847, 0.1976717872098287, 0.24510863521910808, 0.33677523732797671, 0.21207048048827548, 0.20095098497128552, 0.19798552855707593, 0.2465573286166515, 0.18356616475032722, 0.19444382252304371, 1.1469824135427316, 0.20259314360393488, 0.2645730487893882, 0.19962085628122597, 0.42278323380913407, 0.18087395050641653, 0.089112252863010055, 0.17404022444932099, 0.15965502092489214, 0.19234199004250196, 0.22124589400878308, 0.21417861647770761, 0.15807764204268424, 0.15458651448981373, 0.16900819877380632, 0.16677455431975585, 0.14429317084921181, 0.20813822697484033, 0.15471591427347614, 0.17173657558539837, 0.14459037202458996, 0.14473195127703872, 0.1858511370401377, 0.17042478769578531, 0.12313512079524856]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aed809d09dfc74e8c610f9f4146d0d2c6dc816a
60,222
ipynb
Jupyter Notebook
docs/beta/notebooks/00_Table_of_Contents.ipynb
hexagonrecursion/fuzzingbook
772c1eba8135751ec546bbcda03bec8dfda19949
[ "MIT" ]
1
2021-06-20T05:08:14.000Z
2021-06-20T05:08:14.000Z
docs/beta/notebooks/00_Table_of_Contents.ipynb
sthagen/fuzzingbook
38759fe72b7f376bc6dc921dc624912696c417fe
[ "MIT" ]
null
null
null
docs/beta/notebooks/00_Table_of_Contents.ipynb
sthagen/fuzzingbook
38759fe72b7f376bc6dc921dc624912696c417fe
[ "MIT" ]
null
null
null
88.692194
1,546
0.630667
[ [ [ "# The Fuzzing Book", "_____no_output_____" ], [ "## Sitemap\nWhile the chapters of this book can be read one after the other, there are many possible paths through the book. In this graph, an arrow _A_ → _B_ means that chapter _A_ is a prerequisite for chapter _B_. You can pick arbitrary paths in this graph to get to the topics that interest you most:\n", "_____no_output_____" ] ], [ [ "# ignore\nfrom IPython.display import SVG", "_____no_output_____" ], [ "# ignore\nSVG(filename='PICS/Sitemap.svg')", "_____no_output_____" ] ], [ [ "## [Table of Contents](index.ipynb)\n\n\n### <a href=\"01_Intro.ipynb\" title=\"Part I: Whetting Your Appetite (01_Intro)&#10;&#10;In this part, we introduce the topics of the book.\">Part I: Whetting Your Appetite</a>\n\n* <a href=\"Tours.ipynb\" title=\"Tours through the Book (Tours)&#10;&#10;This book is massive. With 17,000 lines of code and 125,000 words of text, a printed version would cover more than 1,000 pages of text. Obviously, we do not assume that everybody wants to read everything.\">Tours through the Book</a>\n* <a href=\"Intro_Testing.ipynb\" title=\"Introduction to Software Testing (Intro_Testing)&#10;&#10;Before we get to the central parts of the book, let us introduce essential concepts of software testing. Why is it necessary to test software at all? How does one test software? How can one tell whether a test has been successful? How does one know if one has tested enough? In this chapter, let us recall the most important concepts, and at the same time get acquainted with Python and interactive notebooks.\">Introduction to Software Testing</a>\n\n### <a href=\"02_Lexical_Fuzzing.ipynb\" title=\"Part II: Lexical Fuzzing (02_Lexical_Fuzzing)&#10;&#10;This part introduces test generation at the lexical level, that is, composing sequences of characters.\">Part II: Lexical Fuzzing</a>\n\n* <a href=\"Fuzzer.ipynb\" title=\"Fuzzing: Breaking Things with Random Inputs (Fuzzer)&#10;&#10;In this chapter, we&#x27;ll start with one of the simplest test generation techniques. The key idea of random text generation, also known as fuzzing, is to feed a string of random characters into a program in the hope to uncover failures.\">Fuzzing: Breaking Things with Random Inputs</a>\n* <a href=\"Coverage.ipynb\" title=\"Code Coverage (Coverage)&#10;&#10;In the previous chapter, we introduced basic fuzzing – that is, generating random inputs to test programs. How do we measure the effectiveness of these tests? One way would be to check the number (and seriousness) of bugs found; but if bugs are scarce, we need a proxy for the likelihood of a test to uncover a bug. In this chapter, we introduce the concept of code coverage, measuring which parts of a program are actually executed during a test run. Measuring such coverage is also crucial for test generators that attempt to cover as much code as possible.\">Code Coverage</a>\n* <a href=\"MutationFuzzer.ipynb\" title=\"Mutation-Based Fuzzing (MutationFuzzer)&#10;&#10;Most randomly generated inputs are syntactically invalid and thus are quickly rejected by the processing program. To exercise functionality beyond input processing, we must increase chances to obtain valid inputs. One such way is so-called mutational fuzzing – that is, introducing small changes to existing inputs that may still keep the input valid, yet exercise new behavior. We show how to create such mutations, and how to guide them towards yet uncovered code, applying central concepts from the popular AFL fuzzer.\">Mutation-Based Fuzzing</a>\n* <a href=\"GreyboxFuzzer.ipynb\" title=\"Greybox Fuzzing (GreyboxFuzzer)&#10;&#10;In the previous chapter, we have introduced mutation-based fuzzing, a technique that generates fuzz inputs by applying small mutations to given inputs. In this chapter, we show how to guide these mutations towards specific goals such as coverage. The algorithms in this book stem from the popular American Fuzzy Lop (AFL) fuzzer, in particular from its AFLFast and AFLGo flavors. We will explore the greybox fuzzing algorithm behind AFL and how we can exploit it to solve various problems for automated vulnerability detection.\">Greybox Fuzzing</a>\n* <a href=\"SearchBasedFuzzer.ipynb\" title=\"Search-Based Fuzzing (SearchBasedFuzzer)&#10;&#10;Sometimes we are not only interested in fuzzing as many as possible diverse program inputs, but in deriving specific test inputs that achieve some objective, such as reaching specific statements in a program. When we have an idea of what we are looking for, then we can search for it. Search algorithms are at the core of computer science, but applying classic search algorithms like breadth or depth first search to search for tests is unrealistic, because these algorithms potentially require us to look at all possible inputs. However, domain-knowledge can be used to overcome this problem. For example, if we can estimate which of several program inputs is closer to the one we are looking for, then this information can guide us to reach the target quicker – this information is known as a heuristic. The way heuristics are applied systematically is captured in meta-heuristic search algorithms. The &quot;meta&quot; denotes that these algorithms are generic and can be instantiated differently to different problems. Meta-heuristics often take inspiration from processes observed in nature. For example, there are algorithms mimicking evolutionary processes, swarm intelligence, or chemical reactions. In general they are much more efficient than exhaustive search approaches such that they can be applied to vast search spaces – search spaces as vast as the domain of program inputs are no problem for them.\">Search-Based Fuzzing</a>\n* <a href=\"MutationAnalysis.ipynb\" title=\"Mutation Analysis (MutationAnalysis)&#10;&#10;In the chapter on coverage, we showed how one can identify which parts of the program are executed by a program, and hence get a sense of the effectiveness of a set of test cases in covering the program structure. However, coverage alone may not be the best measure for the effectiveness of a test, as one can have great coverage without ever checking a result for correctness. In this chapter, we introduce another means for assessing the effectiveness of a test suite: After injecting mutations – artificial faults – into the code, we check whether a test suite can detect these artificial faults. The idea is that if it fails to detect such mutations, it will also miss real bugs.\">Mutation Analysis</a>\n\n### <a href=\"03_Syntactical_Fuzzing.ipynb\" title=\"Part III: Syntactical Fuzzing (03_Syntactical_Fuzzing)&#10;&#10;This part introduces test generation at the syntactical level, that is, composing inputs from language structures.\">Part III: Syntactical Fuzzing</a>\n\n* <a href=\"Grammars.ipynb\" title=\"Fuzzing with Grammars (Grammars)&#10;&#10;In the chapter on &quot;Mutation-Based Fuzzing&quot;, we have seen how to use extra hints – such as sample input files – to speed up test generation. In this chapter, we take this idea one step further, by providing a specification of the legal inputs to a program. Specifying inputs via a grammar allows for very systematic and efficient test generation, in particular for complex input formats. Grammars also serve as the base for configuration fuzzing, API fuzzing, GUI fuzzing, and many more.\">Fuzzing with Grammars</a>\n* <a href=\"GrammarFuzzer.ipynb\" title=\"Efficient Grammar Fuzzing (GrammarFuzzer)&#10;&#10;In the chapter on grammars, we have seen how to use grammars for very effective and efficient testing. In this chapter, we refine the previous string-based algorithm into a tree-based algorithm, which is much faster and allows for much more control over the production of fuzz inputs.\">Efficient Grammar Fuzzing</a>\n* <a href=\"GrammarCoverageFuzzer.ipynb\" title=\"Grammar Coverage (GrammarCoverageFuzzer)&#10;&#10;Producing inputs from grammars gives all possible expansions of a rule the same likelihood. For producing a comprehensive test suite, however, it makes more sense to maximize variety – for instance, by not repeating the same expansions over and over again. In this chapter, we explore how to systematically cover elements of a grammar such that we maximize variety and do not miss out individual elements.\">Grammar Coverage</a>\n* <a href=\"Parser.ipynb\" title=\"Parsing Inputs (Parser)&#10;&#10;In the chapter on Grammars, we discussed how grammars can be&#10;used to represent various languages. We also saw how grammars can be used to&#10;generate strings of the corresponding language. Grammars can also perform the&#10;reverse. That is, given a string, one can decompose the string into its&#10;constituent parts that correspond to the parts of grammar used to generate it&#10;– the derivation tree of that string. These parts (and parts from other similar&#10;strings) can later be recombined using the same grammar to produce new strings.\">Parsing Inputs</a>\n* <a href=\"ProbabilisticGrammarFuzzer.ipynb\" title=\"Probabilistic Grammar Fuzzing (ProbabilisticGrammarFuzzer)&#10;&#10;Let us give grammars even more power by assigning probabilities to individual expansions. This allows us to control how many of each element should be produced, and thus allows us to target our generated tests towards specific functionality. We also show how to learn such probabilities from given sample inputs, and specifically direct our tests towards input features that are uncommon in these samples.\">Probabilistic Grammar Fuzzing</a>\n* <a href=\"GeneratorGrammarFuzzer.ipynb\" title=\"Fuzzing with Generators (GeneratorGrammarFuzzer)&#10;&#10;In this chapter, we show how to extend grammars with functions – pieces of code that get executed during grammar expansion, and that can generate, check, or change elements produced. Adding functions to a grammar allows for very versatile test generation, bringing together the best of grammar generation and programming.\">Fuzzing with Generators</a>\n* <a href=\"GreyboxGrammarFuzzer.ipynb\" title=\"Greybox Fuzzing with Grammars (GreyboxGrammarFuzzer)&#10;&#10;&lt;!--&#10;Previously, we have learned about mutational fuzzing, which generates new inputs by mutating seed inputs. Most mutational fuzzers represent inputs as a sequence of bytes and apply byte-level mutations to this byte sequence. Such byte-level mutations work great for compact file formats with a small number of structural constraints. However, most file formats impose a high-level structure on these byte sequences.\">Greybox Fuzzing with Grammars</a>\n* <a href=\"Reducer.ipynb\" title=\"Reducing Failure-Inducing Inputs (Reducer)&#10;&#10;By construction, fuzzers create inputs that may be hard to read. This causes issues during debugging, when a human has to analyze the exact cause of the failure. In this chapter, we present techniques that automatically reduce and simplify failure-inducing inputs to a minimum in order to ease debugging.\">Reducing Failure-Inducing Inputs</a>\n\n### <a href=\"04_Semantical_Fuzzing.ipynb\" title=\"Part IV: Semantical Fuzzing (04_Semantical_Fuzzing)&#10;&#10;This part introduces test generation techniques that take the semantics of the input into account, notably the behavior of the program that processes the input.\">Part IV: Semantical Fuzzing</a>\n\n* <a href=\"GrammarMiner.ipynb\" title=\"Mining Input Grammars (GrammarMiner)&#10;&#10;So far, the grammars we have seen have been mostly specified manually – that is, you (or the person knowing the input format) had to design and write a grammar in the first place. While the grammars we have seen so far have been rather simple, creating a grammar for complex inputs can involve quite some effort. In this chapter, we therefore introduce techniques that automatically mine grammars from programs – by executing the programs and observing how they process which parts of the input. In conjunction with a grammar fuzzer, this allows us to &#10;1. take a program, &#10;2. extract its input grammar, and &#10;3. fuzz it with high efficiency and effectiveness, using the concepts in this book.\">Mining Input Grammars</a>\n* <a href=\"InformationFlow.ipynb\" title=\"Tracking Information Flow (InformationFlow)&#10;&#10;We have explored how one could generate better inputs that can penetrate deeper into the program in question. While doing so, we have relied on program crashes to tell us that we have succeeded in finding problems in the program. However, that is rather simplistic. What if the behavior of the program is simply incorrect, but does not lead to a crash? Can one do better?\">Tracking Information Flow</a>\n* <a href=\"ConcolicFuzzer.ipynb\" title=\"Concolic Fuzzing (ConcolicFuzzer)&#10;&#10;We have previously seen how one can use dynamic taints to produce more intelligent test cases than simply looking for program crashes. We have also seen how one can use the taints to update the grammar, and hence focus more on the dangerous methods.\">Concolic Fuzzing</a>\n* <a href=\"SymbolicFuzzer.ipynb\" title=\"Symbolic Fuzzing (SymbolicFuzzer)&#10;&#10;One of the problems with traditional methods of fuzzing is that they fail to exercise all the possible behaviors that a system can have, especially when the input space is large. Quite often the execution of a specific branch of execution may happen only with very specific inputs, which could represent an extremely small fraction of the input space. The traditional fuzzing methods relies on chance to produce inputs they need. However, relying on randomness to generate values that we want is a bad idea when the space to be explored is huge. For example, a function that accepts a string, even if one only considers the first $10$ characters, already has $2^{80}$ possible inputs. If one is looking for a specific string, random generation of values will take a few thousand years even in one of the super computers.\">Symbolic Fuzzing</a>\n* <a href=\"DynamicInvariants.ipynb\" title=\"Mining Function Specifications (DynamicInvariants)&#10;&#10;When testing a program, one not only needs to cover its several behaviors; one also needs to check whether the result is as expected. In this chapter, we introduce a technique that allows us to mine function specifications from a set of given executions, resulting in abstract and formal descriptions of what the function expects and what it delivers.\">Mining Function Specifications</a>\n\n### <a href=\"05_Domain-Specific_Fuzzing.ipynb\" title=\"Part V: Domain-Specific Fuzzing (05_Domain-Specific_Fuzzing)&#10;&#10;This part discusses test generation for a number of specific domains. For all these domains, we introduce fuzzers that generate inputs as well as miners that analyze the input structure.\">Part V: Domain-Specific Fuzzing</a>\n\n* <a href=\"ConfigurationFuzzer.ipynb\" title=\"Testing Configurations (ConfigurationFuzzer)&#10;&#10;The behavior of a program is not only governed by its data. The configuration of a program – that is, the settings that govern the execution of a program on its (regular) input data, as set by options or configuration files – just as well influences behavior, and thus can and should be tested. In this chapter, we explore how to systematically test and cover software configurations. By automatically inferring configuration options, we can apply these techniques out of the box, with no need for writing a grammar. Finally, we show how to systematically cover combinations of configuration options, quickly detecting unwanted interferences.\">Testing Configurations</a>\n* <a href=\"APIFuzzer.ipynb\" title=\"Fuzzing APIs (APIFuzzer)&#10;&#10;So far, we have always generated system input, i.e. data that the program as a whole obtains via its input channels. However, we can also generate inputs that go directly into individual functions, gaining flexibility and speed in the process. In this chapter, we explore the use of grammars to synthesize code for function calls, which allows you to generate program code that very efficiently invokes functions directly.\">Fuzzing APIs</a>\n* <a href=\"Carver.ipynb\" title=\"Carving Unit Tests (Carver)&#10;&#10;So far, we have always generated system input, i.e. data that the program as a whole obtains via its input channels. If we are interested in testing only a small set of functions, having to go through the system can be very inefficient. This chapter introduces a technique known as carving, which, given a system test, automatically extracts a set of unit tests that replicate the calls seen during the unit test. The key idea is to record such calls such that we can replay them later – as a whole or selectively. On top, we also explore how to synthesize API grammars from carved unit tests; this means that we can synthesize API tests without having to write a grammar at all.\">Carving Unit Tests</a>\n* <a href=\"WebFuzzer.ipynb\" title=\"Testing Web Applications (WebFuzzer)&#10;&#10;In this chapter, we explore how to generate tests for Graphical User Interfaces (GUIs), notably on Web interfaces. We set up a (vulnerable) Web server and demonstrate how to systematically explore its behavior – first with hand-written grammars, then with grammars automatically inferred from the user interface. We also show how to conduct systematic attacks on these servers, notably with code and SQL injection.\">Testing Web Applications</a>\n* <a href=\"GUIFuzzer.ipynb\" title=\"Testing Graphical User Interfaces (GUIFuzzer)&#10;&#10;In this chapter, we explore how to generate tests for Graphical User Interfaces (GUIs), abstracting from our previous examples on Web testing. Building on general means to extract user interface elements and to activate them, our techniques generalize to arbitrary graphical user interfaces, from rich Web applications to mobile apps, and systematically explore user interfaces through forms and navigation elements.\">Testing Graphical User Interfaces</a>\n\n### <a href=\"06_Managing_Fuzzing.ipynb\" title=\"Part VI: Managing Fuzzing (06_Managing_Fuzzing)&#10;&#10;This part discusses how to manage fuzzing in the large.\">Part VI: Managing Fuzzing</a>\n\n* <a href=\"FuzzingInTheLarge.ipynb\" title=\"Fuzzing in the Large (FuzzingInTheLarge)&#10;&#10;In the past chapters, we have always looked at fuzzing taking place on one machine for a few seconds only. In the real world, however, fuzzers are run on dozens or even thousands of machines; for hours, days and weeks; for one program or dozens of programs. In such contexts, one needs an infrastructure to collect failure data from the individual fuzzer runs, and to aggregate such data in a central repository. In this chapter, we will examine such an infrastructure, the FuzzManager framework from Mozilla.\">Fuzzing in the Large</a>\n* <a href=\"WhenToStopFuzzing.ipynb\" title=\"When To Stop Fuzzing (WhenToStopFuzzing)&#10;&#10;In the past chapters, we have discussed several fuzzing techniques. Knowing what to do is important, but it is also important to know when to stop doing things. In this chapter, we will learn when to stop fuzzing – and use a prominent example for this purpose: The Enigma machine that was used in the second world war by the navy of Nazi Germany to encrypt communications, and how Alan Turing and I.J. Good used fuzzing techniques to crack ciphers for the Naval Enigma machine.\">When To Stop Fuzzing</a>\n\n### <a href=\"99_Appendices.ipynb\" title=\"Appendices (99_Appendices)&#10;&#10;This part holds notebooks and modules that support other notebooks.\">Appendices</a>\n\n* <a href=\"PrototypingWithPython.ipynb\" title=\"Prototyping with Python (PrototypingWithPython)&#10;&#10;This is the manuscript of Andreas Zeller&#x27;s keynote&#10;&quot;Coding Effective Testing Tools Within Minutes&quot; at the TAIC PART 2020 conference.\">Prototyping with Python</a>\n* <a href=\"ExpectError.ipynb\" title=\"Error Handling (ExpectError)&#10;&#10;The code in this notebook helps with handling errors. Normally, an error in notebook code causes the execution of the code to stop; while an infinite loop in notebook code causes the notebook to run without end. This notebook provides two classes to help address these concerns.\">Error Handling</a>\n* <a href=\"Timer.ipynb\" title=\"Timer (Timer)&#10;&#10;The code in this notebook helps with measuring time.\">Timer</a>\n* <a href=\"ControlFlow.ipynb\" title=\"Control Flow Graph (ControlFlow)&#10;&#10;The code in this notebook helps with obtaining the control flow graph of python functions.\">Control Flow Graph</a>\n* <a href=\"RailroadDiagrams.ipynb\" title=\"Railroad Diagrams (RailroadDiagrams)&#10;&#10;The code in this notebook helps with drawing syntax-diagrams. It is a (slightly customized) copy of the excellent library from Tab Atkins jr., which unfortunately is not available as a Python package.\">Railroad Diagrams</a>\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4aedb46ffdee16f6822fd9c6da86ed37fc97212a
219,073
ipynb
Jupyter Notebook
experiments/tl_1/cores-metehan/trials/2/trial.ipynb
stevester94/csc500-notebooks
4c1b04c537fe233a75bed82913d9d84985a89177
[ "MIT" ]
null
null
null
experiments/tl_1/cores-metehan/trials/2/trial.ipynb
stevester94/csc500-notebooks
4c1b04c537fe233a75bed82913d9d84985a89177
[ "MIT" ]
null
null
null
experiments/tl_1/cores-metehan/trials/2/trial.ipynb
stevester94/csc500-notebooks
4c1b04c537fe233a75bed82913d9d84985a89177
[ "MIT" ]
null
null
null
100.862339
76,288
0.781228
[ [ [ "# Transfer Learning Template", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n\n \nimport os, json, sys, time, random\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\nfrom easydict import EasyDict\nimport matplotlib.pyplot as plt\n\nfrom steves_models.steves_ptn import Steves_Prototypical_Network\n\nfrom steves_utils.lazy_iterable_wrapper import Lazy_Iterable_Wrapper\nfrom steves_utils.iterable_aggregator import Iterable_Aggregator\nfrom steves_utils.ptn_train_eval_test_jig import PTN_Train_Eval_Test_Jig\nfrom steves_utils.torch_sequential_builder import build_sequential\nfrom steves_utils.torch_utils import get_dataset_metrics, ptn_confusion_by_domain_over_dataloader\nfrom steves_utils.utils_v2 import (per_domain_accuracy_from_confusion, get_datasets_base_path)\nfrom steves_utils.PTN.utils import independent_accuracy_assesment\n\nfrom torch.utils.data import DataLoader\n\nfrom steves_utils.stratified_dataset.episodic_accessor import Episodic_Accessor_Factory\n\nfrom steves_utils.ptn_do_report import (\n get_loss_curve,\n get_results_table,\n get_parameters_table,\n get_domain_accuracies,\n)\n\nfrom steves_utils.transforms import get_chained_transform", "_____no_output_____" ] ], [ [ "# Allowed Parameters\nThese are allowed parameters, not defaults\nEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)\n\nPapermill uses the cell tag \"parameters\" to inject the real parameters below this cell.\nEnable tags to see what I mean", "_____no_output_____" ] ], [ [ "required_parameters = {\n \"experiment_name\",\n \"lr\",\n \"device\",\n \"seed\",\n \"dataset_seed\",\n \"n_shot\",\n \"n_query\",\n \"n_way\",\n \"train_k_factor\",\n \"val_k_factor\",\n \"test_k_factor\",\n \"n_epoch\",\n \"patience\",\n \"criteria_for_best\",\n \"x_net\",\n \"datasets\",\n \"torch_default_dtype\",\n \"NUM_LOGS_PER_EPOCH\",\n \"BEST_MODEL_PATH\",\n}", "_____no_output_____" ], [ "from steves_utils.CORES.utils import (\n ALL_NODES,\n ALL_NODES_MINIMUM_1000_EXAMPLES,\n ALL_DAYS\n)\n\nfrom steves_utils.ORACLE.utils_v2 import (\n ALL_DISTANCES_FEET_NARROWED,\n ALL_RUNS,\n ALL_SERIAL_NUMBERS,\n)\n\nstandalone_parameters = {}\nstandalone_parameters[\"experiment_name\"] = \"STANDALONE PTN\"\nstandalone_parameters[\"lr\"] = 0.001\nstandalone_parameters[\"device\"] = \"cuda\"\n\nstandalone_parameters[\"seed\"] = 1337\nstandalone_parameters[\"dataset_seed\"] = 1337\n\nstandalone_parameters[\"n_way\"] = 8\nstandalone_parameters[\"n_shot\"] = 3\nstandalone_parameters[\"n_query\"] = 2\nstandalone_parameters[\"train_k_factor\"] = 1\nstandalone_parameters[\"val_k_factor\"] = 2\nstandalone_parameters[\"test_k_factor\"] = 2\n\n\nstandalone_parameters[\"n_epoch\"] = 50\n\nstandalone_parameters[\"patience\"] = 10\nstandalone_parameters[\"criteria_for_best\"] = \"source_loss\"\n\nstandalone_parameters[\"datasets\"] = [\n {\n \"labels\": ALL_SERIAL_NUMBERS,\n \"domains\": ALL_DISTANCES_FEET_NARROWED,\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": os.path.join(get_datasets_base_path(), \"oracle.Run1_framed_2000Examples_stratified_ds.2022A.pkl\"),\n \"source_or_target_dataset\": \"source\",\n \"x_transforms\": [\"unit_mag\", \"minus_two\"],\n \"episode_transforms\": [],\n \"domain_prefix\": \"ORACLE_\"\n },\n {\n \"labels\": ALL_NODES,\n \"domains\": ALL_DAYS,\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": os.path.join(get_datasets_base_path(), \"cores.stratified_ds.2022A.pkl\"),\n \"source_or_target_dataset\": \"target\",\n \"x_transforms\": [\"unit_power\", \"times_zero\"],\n \"episode_transforms\": [],\n \"domain_prefix\": \"CORES_\"\n } \n]\n\nstandalone_parameters[\"torch_default_dtype\"] = \"torch.float32\" \n\n\n\nstandalone_parameters[\"x_net\"] = [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\":[-1, 1, 2, 256]}},\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":1, \"out_channels\":256, \"kernel_size\":(1,7), \"bias\":False, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":256, \"out_channels\":80, \"kernel_size\":(2,7), \"bias\":True, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 80*256, \"out_features\": 256}}, # 80 units per IQ pair\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": 256}},\n]\n\n# Parameters relevant to results\n# These parameters will basically never need to change\nstandalone_parameters[\"NUM_LOGS_PER_EPOCH\"] = 10\nstandalone_parameters[\"BEST_MODEL_PATH\"] = \"./best_model.pth\"\n\n\n\n\n", "_____no_output_____" ], [ "# Parameters\nparameters = {\n \"experiment_name\": \"tl_1_cores-metehan\",\n \"device\": \"cuda\",\n \"lr\": 0.001,\n \"seed\": 1337,\n \"dataset_seed\": 1337,\n \"n_shot\": 3,\n \"n_query\": 2,\n \"train_k_factor\": 3,\n \"val_k_factor\": 2,\n \"test_k_factor\": 2,\n \"torch_default_dtype\": \"torch.float32\",\n \"n_epoch\": 50,\n \"patience\": 3,\n \"criteria_for_best\": \"target_loss\",\n \"x_net\": [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\": [-1, 1, 2, 256]}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 1,\n \"out_channels\": 256,\n \"kernel_size\": [1, 7],\n \"bias\": False,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 256}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 256,\n \"out_channels\": 80,\n \"kernel_size\": [2, 7],\n \"bias\": True,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 20480, \"out_features\": 256}},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\": 256}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": 256}},\n ],\n \"NUM_LOGS_PER_EPOCH\": 10,\n \"BEST_MODEL_PATH\": \"./best_model.pth\",\n \"n_way\": 19,\n \"datasets\": [\n {\n \"labels\": [\n \"1-10.\",\n \"1-11.\",\n \"1-15.\",\n \"1-16.\",\n \"1-17.\",\n \"1-18.\",\n \"1-19.\",\n \"10-4.\",\n \"10-7.\",\n \"11-1.\",\n \"11-14.\",\n \"11-17.\",\n \"11-20.\",\n \"11-7.\",\n \"13-20.\",\n \"13-8.\",\n \"14-10.\",\n \"14-11.\",\n \"14-14.\",\n \"14-7.\",\n \"15-1.\",\n \"15-20.\",\n \"16-1.\",\n \"16-16.\",\n \"17-10.\",\n \"17-11.\",\n \"17-2.\",\n \"19-1.\",\n \"19-16.\",\n \"19-19.\",\n \"19-20.\",\n \"19-3.\",\n \"2-10.\",\n \"2-11.\",\n \"2-17.\",\n \"2-18.\",\n \"2-20.\",\n \"2-3.\",\n \"2-4.\",\n \"2-5.\",\n \"2-6.\",\n \"2-7.\",\n \"2-8.\",\n \"3-13.\",\n \"3-18.\",\n \"3-3.\",\n \"4-1.\",\n \"4-10.\",\n \"4-11.\",\n \"4-19.\",\n \"5-5.\",\n \"6-15.\",\n \"7-10.\",\n \"7-14.\",\n \"8-18.\",\n \"8-20.\",\n \"8-3.\",\n \"8-8.\",\n ],\n \"domains\": [1, 2, 3, 4, 5],\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": \"/mnt/wd500GB/CSC500/csc500-main/datasets/cores.stratified_ds.2022A.pkl\",\n \"source_or_target_dataset\": \"source\",\n \"x_transforms\": [],\n \"episode_transforms\": [],\n \"domain_prefix\": \"CORES_\",\n },\n {\n \"labels\": [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n ],\n \"domains\": [0, 1, 2],\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": \"/mnt/wd500GB/CSC500/csc500-main/datasets/metehan.stratified_ds.2022A.pkl\",\n \"source_or_target_dataset\": \"target\",\n \"x_transforms\": [],\n \"episode_transforms\": [],\n \"domain_prefix\": \"Metehan_\",\n },\n ],\n}\n", "_____no_output_____" ], [ "# Set this to True if you want to run this template directly\nSTANDALONE = False\nif STANDALONE:\n print(\"parameters not injected, running with standalone_parameters\")\n parameters = standalone_parameters\n\nif not 'parameters' in locals() and not 'parameters' in globals():\n raise Exception(\"Parameter injection failed\")\n\n#Use an easy dict for all the parameters\np = EasyDict(parameters)\n\nsupplied_keys = set(p.keys())\n\nif supplied_keys != required_parameters:\n print(\"Parameters are incorrect\")\n if len(supplied_keys - required_parameters)>0: print(\"Shouldn't have:\", str(supplied_keys - required_parameters))\n if len(required_parameters - supplied_keys)>0: print(\"Need to have:\", str(required_parameters - supplied_keys))\n raise RuntimeError(\"Parameters are incorrect\")\n\n", "_____no_output_____" ], [ "###################################\n# Set the RNGs and make it all deterministic\n###################################\nnp.random.seed(p.seed)\nrandom.seed(p.seed)\ntorch.manual_seed(p.seed)\n\ntorch.use_deterministic_algorithms(True) ", "_____no_output_____" ], [ "###########################################\n# The stratified datasets honor this\n###########################################\ntorch.set_default_dtype(eval(p.torch_default_dtype))", "_____no_output_____" ], [ "###################################\n# Build the network(s)\n# Note: It's critical to do this AFTER setting the RNG\n###################################\nx_net = build_sequential(p.x_net)", "_____no_output_____" ], [ "start_time_secs = time.time()", "_____no_output_____" ], [ "p.domains_source = []\np.domains_target = []\n\n\ntrain_original_source = []\nval_original_source = []\ntest_original_source = []\n\ntrain_original_target = []\nval_original_target = []\ntest_original_target = []", "_____no_output_____" ], [ "# global_x_transform_func = lambda x: normalize(x.to(torch.get_default_dtype()), \"unit_power\") # unit_power, unit_mag\n# global_x_transform_func = lambda x: normalize(x, \"unit_power\") # unit_power, unit_mag", "_____no_output_____" ], [ "def add_dataset(\n labels,\n domains,\n pickle_path,\n x_transforms,\n episode_transforms,\n domain_prefix,\n num_examples_per_domain_per_label,\n source_or_target_dataset:str,\n iterator_seed=p.seed,\n dataset_seed=p.dataset_seed,\n n_shot=p.n_shot,\n n_way=p.n_way,\n n_query=p.n_query,\n train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor),\n):\n \n if x_transforms == []: x_transform = None\n else: x_transform = get_chained_transform(x_transforms)\n \n if episode_transforms == []: episode_transform = None\n else: raise Exception(\"episode_transforms not implemented\")\n \n episode_transform = lambda tup, _prefix=domain_prefix: (_prefix + str(tup[0]), tup[1])\n\n\n eaf = Episodic_Accessor_Factory(\n labels=labels,\n domains=domains,\n num_examples_per_domain_per_label=num_examples_per_domain_per_label,\n iterator_seed=iterator_seed,\n dataset_seed=dataset_seed,\n n_shot=n_shot,\n n_way=n_way,\n n_query=n_query,\n train_val_test_k_factors=train_val_test_k_factors,\n pickle_path=pickle_path,\n x_transform_func=x_transform,\n )\n\n train, val, test = eaf.get_train(), eaf.get_val(), eaf.get_test()\n train = Lazy_Iterable_Wrapper(train, episode_transform)\n val = Lazy_Iterable_Wrapper(val, episode_transform)\n test = Lazy_Iterable_Wrapper(test, episode_transform)\n\n if source_or_target_dataset==\"source\":\n train_original_source.append(train)\n val_original_source.append(val)\n test_original_source.append(test)\n\n p.domains_source.extend(\n [domain_prefix + str(u) for u in domains]\n )\n elif source_or_target_dataset==\"target\":\n train_original_target.append(train)\n val_original_target.append(val)\n test_original_target.append(test)\n p.domains_target.extend(\n [domain_prefix + str(u) for u in domains]\n )\n else:\n raise Exception(f\"invalid source_or_target_dataset: {source_or_target_dataset}\")\n ", "_____no_output_____" ], [ "for ds in p.datasets:\n add_dataset(**ds)", "_____no_output_____" ], [ "# from steves_utils.CORES.utils import (\n# ALL_NODES,\n# ALL_NODES_MINIMUM_1000_EXAMPLES,\n# ALL_DAYS\n# )\n\n# add_dataset(\n# labels=ALL_NODES,\n# domains = ALL_DAYS,\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"cores.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"cores_{u}\"\n# )", "_____no_output_____" ], [ "# from steves_utils.ORACLE.utils_v2 import (\n# ALL_DISTANCES_FEET,\n# ALL_RUNS,\n# ALL_SERIAL_NUMBERS,\n# )\n\n\n# add_dataset(\n# labels=ALL_SERIAL_NUMBERS,\n# domains = list(set(ALL_DISTANCES_FEET) - {2,62}),\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"source\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"oracle1_{u}\"\n# )\n", "_____no_output_____" ], [ "# from steves_utils.ORACLE.utils_v2 import (\n# ALL_DISTANCES_FEET,\n# ALL_RUNS,\n# ALL_SERIAL_NUMBERS,\n# )\n\n\n# add_dataset(\n# labels=ALL_SERIAL_NUMBERS,\n# domains = list(set(ALL_DISTANCES_FEET) - {2,62,56}),\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"source\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"oracle2_{u}\"\n# )", "_____no_output_____" ], [ "# add_dataset(\n# labels=list(range(19)),\n# domains = [0,1,2],\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"metehan.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"met_{u}\"\n# )", "_____no_output_____" ], [ "# # from steves_utils.wisig.utils import (\n# # ALL_NODES_MINIMUM_100_EXAMPLES,\n# # ALL_NODES_MINIMUM_500_EXAMPLES,\n# # ALL_NODES_MINIMUM_1000_EXAMPLES,\n# # ALL_DAYS\n# # )\n\n# import steves_utils.wisig.utils as wisig\n\n\n# add_dataset(\n# labels=wisig.ALL_NODES_MINIMUM_100_EXAMPLES,\n# domains = wisig.ALL_DAYS,\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"wisig.node3-19.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"wisig_{u}\"\n# )", "_____no_output_____" ], [ "###################################\n# Build the dataset\n###################################\ntrain_original_source = Iterable_Aggregator(train_original_source, p.seed)\nval_original_source = Iterable_Aggregator(val_original_source, p.seed)\ntest_original_source = Iterable_Aggregator(test_original_source, p.seed)\n\n\ntrain_original_target = Iterable_Aggregator(train_original_target, p.seed)\nval_original_target = Iterable_Aggregator(val_original_target, p.seed)\ntest_original_target = Iterable_Aggregator(test_original_target, p.seed)\n\n# For CNN We only use X and Y. And we only train on the source.\n# Properly form the data using a transform lambda and Lazy_Iterable_Wrapper. Finally wrap them in a dataloader\n\ntransform_lambda = lambda ex: ex[1] # Original is (<domain>, <episode>) so we strip down to episode only\n\ntrain_processed_source = Lazy_Iterable_Wrapper(train_original_source, transform_lambda)\nval_processed_source = Lazy_Iterable_Wrapper(val_original_source, transform_lambda)\ntest_processed_source = Lazy_Iterable_Wrapper(test_original_source, transform_lambda)\n\ntrain_processed_target = Lazy_Iterable_Wrapper(train_original_target, transform_lambda)\nval_processed_target = Lazy_Iterable_Wrapper(val_original_target, transform_lambda)\ntest_processed_target = Lazy_Iterable_Wrapper(test_original_target, transform_lambda)\n\ndatasets = EasyDict({\n \"source\": {\n \"original\": {\"train\":train_original_source, \"val\":val_original_source, \"test\":test_original_source},\n \"processed\": {\"train\":train_processed_source, \"val\":val_processed_source, \"test\":test_processed_source}\n },\n \"target\": {\n \"original\": {\"train\":train_original_target, \"val\":val_original_target, \"test\":test_original_target},\n \"processed\": {\"train\":train_processed_target, \"val\":val_processed_target, \"test\":test_processed_target}\n },\n})", "_____no_output_____" ], [ "from steves_utils.transforms import get_average_magnitude, get_average_power\n\nprint(set([u for u,_ in val_original_source]))\nprint(set([u for u,_ in val_original_target]))\n\ns_x, s_y, q_x, q_y, _ = next(iter(train_processed_source))\nprint(s_x)\n\n# for ds in [\n# train_processed_source,\n# val_processed_source,\n# test_processed_source,\n# train_processed_target,\n# val_processed_target,\n# test_processed_target\n# ]:\n# for s_x, s_y, q_x, q_y, _ in ds:\n# for X in (s_x, q_x):\n# for x in X:\n# assert np.isclose(get_average_magnitude(x.numpy()), 1.0)\n# assert np.isclose(get_average_power(x.numpy()), 1.0)\n ", "{'CORES_2', 'CORES_3', 'CORES_1', 'CORES_4', 'CORES_5'}\n" ], [ "###################################\n# Build the model\n###################################\nmodel = Steves_Prototypical_Network(x_net, device=p.device, x_shape=(2,256))\noptimizer = Adam(params=model.parameters(), lr=p.lr)", "(2, 256)\n" ], [ "###################################\n# train\n###################################\njig = PTN_Train_Eval_Test_Jig(model, p.BEST_MODEL_PATH, p.device)\n\njig.train(\n train_iterable=datasets.source.processed.train,\n source_val_iterable=datasets.source.processed.val,\n target_val_iterable=datasets.target.processed.val,\n num_epochs=p.n_epoch,\n num_logs_per_epoch=p.NUM_LOGS_PER_EPOCH,\n patience=p.patience,\n optimizer=optimizer,\n criteria_for_best=p.criteria_for_best,\n)", "epoch: 1, [batch: 1 / 612], examples_per_second: 377.6380, train_label_loss: 1.8549, \n" ], [ "total_experiment_time_secs = time.time() - start_time_secs", "_____no_output_____" ], [ "###################################\n# Evaluate the model\n###################################\nsource_test_label_accuracy, source_test_label_loss = jig.test(datasets.source.processed.test)\ntarget_test_label_accuracy, target_test_label_loss = jig.test(datasets.target.processed.test)\n\nsource_val_label_accuracy, source_val_label_loss = jig.test(datasets.source.processed.val)\ntarget_val_label_accuracy, target_val_label_loss = jig.test(datasets.target.processed.val)\n\nhistory = jig.get_history()\n\ntotal_epochs_trained = len(history[\"epoch_indices\"])\n\nval_dl = Iterable_Aggregator((datasets.source.original.val,datasets.target.original.val))\n\nconfusion = ptn_confusion_by_domain_over_dataloader(model, p.device, val_dl)\nper_domain_accuracy = per_domain_accuracy_from_confusion(confusion)\n\n# Add a key to per_domain_accuracy for if it was a source domain\nfor domain, accuracy in per_domain_accuracy.items():\n per_domain_accuracy[domain] = {\n \"accuracy\": accuracy,\n \"source?\": domain in p.domains_source\n }\n\n# Do an independent accuracy assesment JUST TO BE SURE!\n# _source_test_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.test, p.device)\n# _target_test_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.test, p.device)\n# _source_val_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.val, p.device)\n# _target_val_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.val, p.device)\n\n# assert(_source_test_label_accuracy == source_test_label_accuracy)\n# assert(_target_test_label_accuracy == target_test_label_accuracy)\n# assert(_source_val_label_accuracy == source_val_label_accuracy)\n# assert(_target_val_label_accuracy == target_val_label_accuracy)\n\nexperiment = {\n \"experiment_name\": p.experiment_name,\n \"parameters\": dict(p),\n \"results\": {\n \"source_test_label_accuracy\": source_test_label_accuracy,\n \"source_test_label_loss\": source_test_label_loss,\n \"target_test_label_accuracy\": target_test_label_accuracy,\n \"target_test_label_loss\": target_test_label_loss,\n \"source_val_label_accuracy\": source_val_label_accuracy,\n \"source_val_label_loss\": source_val_label_loss,\n \"target_val_label_accuracy\": target_val_label_accuracy,\n \"target_val_label_loss\": target_val_label_loss,\n \"total_epochs_trained\": total_epochs_trained,\n \"total_experiment_time_secs\": total_experiment_time_secs,\n \"confusion\": confusion,\n \"per_domain_accuracy\": per_domain_accuracy,\n },\n \"history\": history,\n \"dataset_metrics\": get_dataset_metrics(datasets, \"ptn\"),\n}", "_____no_output_____" ], [ "ax = get_loss_curve(experiment)\nplt.show()", "_____no_output_____" ], [ "get_results_table(experiment)", "_____no_output_____" ], [ "get_domain_accuracies(experiment)", "_____no_output_____" ], [ "print(\"Source Test Label Accuracy:\", experiment[\"results\"][\"source_test_label_accuracy\"], \"Target Test Label Accuracy:\", experiment[\"results\"][\"target_test_label_accuracy\"])\nprint(\"Source Val Label Accuracy:\", experiment[\"results\"][\"source_val_label_accuracy\"], \"Target Val Label Accuracy:\", experiment[\"results\"][\"target_val_label_accuracy\"])", "Source Test Label Accuracy: 0.9862002567394095 Target Test Label Accuracy: 0.22076023391812866\nSource Val Label Accuracy: 0.9897304236200257 Target Val Label Accuracy: 0.15058479532163743\n" ], [ "json.dumps(experiment)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aedcb4cfabb39bcf23cde3981bc1f1e9d0bacf0
34,109
ipynb
Jupyter Notebook
.ipynb_checkpoints/stevens-schutzbach-checkpoint.ipynb
anskipper/jupyter-notebooks
3f87618673fe8caaf313267a19ca869bc9bec98c
[ "MIT" ]
null
null
null
.ipynb_checkpoints/stevens-schutzbach-checkpoint.ipynb
anskipper/jupyter-notebooks
3f87618673fe8caaf313267a19ca869bc9bec98c
[ "MIT" ]
null
null
null
.ipynb_checkpoints/stevens-schutzbach-checkpoint.ipynb
anskipper/jupyter-notebooks
3f87618673fe8caaf313267a19ca869bc9bec98c
[ "MIT" ]
null
null
null
160.13615
15,972
0.796036
[ [ [ "# write stevens-schutzback method\nimport pickle\nimport datetime as dt\nimport numpy as np\n\nfrom calendar import monthrange\n\nfrom flowmeterAnalysis import readFiles\n\nhomeDir = 'P:\\\\PW-WATER SERVICES\\\\TECHNICAL SERVICES\\\\Anna'\npickleLocation = homeDir + '\\\\2018\\\\Python Objects\\\\'\n\ndetailFile = homeDir + '\\\\FMdata.csv'", "_____no_output_____" ], [ "with open(pickleLocation + 'flowDict.pickle', 'rb') as handle:\n dfFlows = pickle.load(handle)", "_____no_output_____" ], [ "fmname = 'BC32'\nmonth = 6\ndfFlow = dfFlows[fmname][\n dt.datetime(2018, month, 1):dt.datetime(2018, month, monthrange(2018,11)[1])]\n\ndf_details = readFiles.readFMdetails(detailFile)\nD = df_details.loc[fmname, 'Diameter']", "_____no_output_____" ], [ "def rsquare(y, f):\n y = np.asanyarray(y)\n f = np.asanyarray(f)\n SStot = sum((y - np.mean(y))**2)\n SSres = sum((y - f)**2)\n return(1 - (SSres/SStot))", "_____no_output_____" ], [ "from scipy.optimize import least_squares\n\ndef gen_data(a, x):\n return(a * x)\n\ndef fun(params, x, y):\n return(params[0] * x - y)\n\na = []\nr2 = []\nd = dfFlow['y (in)'].values\nv = dfFlow['v (ft/s)'].values\nddogList = np.linspace(0, D/5, 100)\nfor i, ddog in enumerate(ddogList):\n de = d - ddog\n th = 2 * np.arccos(1 - (2 * de / D))\n if any(np.isnan(th)):\n vss = v[~np.isnan(th)]\n th = th[~np.isnan(th)]\n P = D * th / 2\n Ae = (D**2 / 8) * (th - np.sin(th))\n Rss = Ae / P\n res_lsq = least_squares(fun, -1, args = (Rss ** (2/3), vss))\n a.append(res_lsq.x[0])\n r2.append(rsquare())", "_____no_output_____" ], [ "from scipy.optimize import least_squares\n\ndef gen_data(a, x):\n return(a * x)\n\ndef fun(params, x, y):\n return(params[0] * x - y)\n\nddog = 4.88\nde = d - ddog\nth = 2 * np.arccos(1 - (2 * de / D))\nif any(np.isnan(th)):\n de = de[~np.isnan(th)]\n v = v[~np.isnan(th)]\n th = th[~np.isnan(th)]\nP = D * th / 2\nAe = (D**2 / 8) * (th - np.sin(th))\nRss = Ae / P\nres_lsq = least_squares(fun, -1, args = (Rss ** (2/3), v))\n\n", "_____no_output_____" ], [ "fig, ax = plt.subplots()\n\nax.scatter(d, v, marker = 'o')\n\nax.plot(d, \n gen_data(a = res_lsq.x[0], x = Rss ** (2/3)),\n color = 'red')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4aedd0bfb6cf5ba68a24e782e0c013374aebedcd
156,198
ipynb
Jupyter Notebook
data/scripts/TransientDMD_surrogates-PyDMD_JOV_Latest.ipynb
corps-g/dmd_lra_surrogate_ans
f9886ec63db5795a7150236f7eb7cdbdb85b93ff
[ "MIT" ]
null
null
null
data/scripts/TransientDMD_surrogates-PyDMD_JOV_Latest.ipynb
corps-g/dmd_lra_surrogate_ans
f9886ec63db5795a7150236f7eb7cdbdb85b93ff
[ "MIT" ]
null
null
null
data/scripts/TransientDMD_surrogates-PyDMD_JOV_Latest.ipynb
corps-g/dmd_lra_surrogate_ans
f9886ec63db5795a7150236f7eb7cdbdb85b93ff
[ "MIT" ]
null
null
null
274.996479
73,496
0.916913
[ [ [ "# Applying DMD for transient modeling, surrogates and Uncertainty Quantificaton.", "_____no_output_____" ], [ "## 2D LRA Benchmark: ", "_____no_output_____" ], [ "In this test case, a control rod ejection in the 2D well known LRA benchmark has been simulated by Detran (developed by J. A. Roberts). The objective here is to build a data-driven, yet physics-revealing time-dependent surrogate model(s). The linearity inherited from the connection to Koopman theory will facilitate a forward/backward uncertainty propagation. ", "_____no_output_____" ], [ "First of all, lets make the necessary imports including the DMD class from PyDMD (developed by math)we import the DMD class from the pydmd package, we set matplotlib for the notebook and we import numpy.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.io import loadmat\nimport scipy as sp\nfrom pydmd import DMD_jov\nimport pickle", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nplt.rcParams['font.family'] = 'serif'\nplt.rcParams['font.serif'] = 'Times'\n\n#plt.rcParams['mathtext.fontset'] = 'custom'\n#plt.rcParams['mathtext.rm'] = 'Times New Roman'\n#plt.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic'\n#plt.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold'\n\nplt.rcParams['font.size'] = 18\nplt.rcParams['axes.labelsize'] = 20\n#plt.rcParams['axes.labelweight'] = 'bold'\nplt.rcParams['axes.titlesize'] = 20\nplt.rcParams['xtick.labelsize'] = 18\nplt.rcParams['ytick.labelsize'] = 18\nplt.rcParams['legend.fontsize'] = 18\nplt.rcParams['legend.fancybox'] = False\nplt.rcParams['legend.frameon'] = False\n\nplt.rcParams['figure.titlesize'] = 20\n\nplt.rcParams['axes.autolimit_mode'] = 'round_numbers'\nplt.rcParams['axes.xmargin'] = 0\nplt.rcParams['axes.ymargin'] = 0\n\nplt.rcParams['text.usetex'] = True\n\nplt.rcParams['savefig.bbox'] = 'tight'", "_____no_output_____" ] ], [ [ "We load the Detran simulation data of the Transient LRA Benchmark", "_____no_output_____" ] ], [ [ "A = pickle.load(open('../inputs/diffusion2x2_ref_with_mesh_temps.p','rb'),encoding='latin')\n\nkappa = 3.204e-11", "_____no_output_____" ], [ "#%% Plots of raw data\nt = np.array(A['times']) # time\nmp = np.array(A['meshpower']).T # mesh-dependent powers\nmp = mp * kappa\np = np.array(A['power'])# total power\nc = p[0]/sp.sum(mp,axis=0)[0]# use to reconstruct power from mesh power\nmaxtemp = A['maxtemp']#\nnp.where(p==max(p))\n#mp = mp * c", "_____no_output_____" ] ], [ [ "Build the surrogates using a batch of DMD's", "_____no_output_____" ] ], [ [ "#%% DMD analysis\nimport time\net_0 = time.time()\n# Time step\ndt = t[1]-t[0]\n# Chop the time domain into discrete patches\ntime_interval = [1.36,1.5,max(t)]\n# Define desire subspace size for each patch\nr = [10,13,40]\n#r = [50,1e5,15]\n#step=[10,1,1]\noptimal=['Jov',False,False]\n# Perform dmd\ntime_index = [0]\nfor i in range(len(time_interval)):\n time_index.append(sp.sum(t<=time_interval[i]))\n\nF_norm = 0.0\nresults={}\nfor i in range(len(time_interval)):\n start, stop = time_index[i], time_index[i+1]\n t_i = t[start:stop]\n dmd = DMD_jov(svd_rank=r[i],opt=optimal[i]) \n fuel_idx = mp[:, 0]>0 # pick out fuel mesh\n tmp_reduced = mp[fuel_idx, start:stop] # extract fuel data\n tmp_full = 0*mp[:, start:stop] # initialize full data\n dmd.fit(tmp_reduced) # do the fit\n tmp_full[fuel_idx] = dmd.reconstructed_data.real\n results[i]={}\n results[i]['dmd'] = dmd\n results[i]['t'] = t_i # All the coming lines can be ommitted except p_dmd\n results[i]['Phi'] = dmd.modes\n results[i]['eigs'] = dmd.eigs\n results[i]['mp_dmd'] = tmp_full.copy()#dmd.reconstructed_data\n results[i]['p_dmd'] = sp.zeros(stop-start)\n results[i]['p_dmd'] = c*sp.sum(tmp_full, axis=0)# c*sp.sum(dmd.reconstructed_data.real,axis=0)\n F_norm_tmp = np.linalg.norm(tmp_reduced-dmd.reconstructed_data.real)\n print(\"patch {} norm = {:.2e}\".format(i, F_norm_tmp))\n F_norm += F_norm_tmp**2\n \net = time.time() - et_0\n\nF_norm = np.sqrt(F_norm)\nprint(\"final norm is {:.2e}\".format(F_norm))\n\nprint('elapsed time = ', et)", "patch 0 norm = 3.11e-03\npatch 1 norm = 6.64e-01\npatch 2 norm = 4.31e+04\nfinal norm is 4.31e+04\nelapsed time = 0.021336793899536133\n" ], [ "#for mode in dmd.modes.T:\n# plt.plot(x, mode.real)\n# plt.title('Modes')\n#plt.show()T.real)\n \n#plt.pcolor(xgrid, tgrid, ((mp[start:stop, :].T-dmd.reconstructed_data).T).real)\n#fig = plt.colorbar()\n\nmarkers = ['o', '^', 's', 'v']\n\nfig5=plt.figure(figsize=(15,5))\n\n# Plot the surrogate and reference on a linear plot\nax1=fig5.add_subplot(1,3,1)\nplt.plot(t, p, 'k-', label='reference')\nfor k in range(len(time_interval)):\n plt.plot(results[k]['t'], results[k]['p_dmd'].real, marker=markers[k], ls='', mfc='w', label='interval '+str(k)) \nplt.axis([0, 3, 0, 5000])\nplt.xlabel('t (s)')\nplt.ylabel('power (W/cm$^3$)')\nplt.legend(loc=\"upper right\")\n\n# Plot the surrogate and reference on a log plot. Put the derivative on the other axis.\nax2=fig5.add_subplot(1,3,2) \nplt.semilogy(t, p, 'k-', label='reference')\nfor k in range(len(time_interval)):\n plt.semilogy(results[k]['t'], results[k]['p_dmd'].real, marker=markers[k], ls='', mfc='w', label='interval '+str(k))\nplt.xlabel('t (s)')\nplt.ylabel('power (W/cm$^3$)')\ndpdt = np.gradient(p, t)\nidx_pos = dpdt>0\nidx_neg = dpdt<0\n#ax2left = ax2.twinx()\n#plt.semilogy(t, abs(dpdt), 'r:', label='derivative')\nplt.legend()\n\n#plt.legend()\n\n# Plot the error\nax2=fig5.add_subplot(1,3,3) \nt_start = 0\nfor k in range(len(time_interval)):\n t_end = t_start + len(results[k]['t'])\n ref = p[t_start:t_end]\n err = abs(results[k]['p_dmd'].real-ref)/ref*100\n plt.semilogy(t[t_start:t_end], err, marker=markers[k], \n ls='', mfc='w', label='interval '+str(k))\n t_start = t_end\nplt.xlabel('t (s)')\nplt.ylabel('absolute error in power (\\%)')\nplt.legend()\n\nplt.tight_layout()\nplt.savefig('../images/corepower.pdf')", "/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n" ], [ "#plt.semilogy(t[idx_pos], dpdt[idx_pos], 'r.', ms=2)\nd2pdt2 = np.gradient(dpdt, t)\nff = abs(p)\nplt.plot(t, ff, 'r-',\n [time_interval[0],time_interval[0]], [min(ff), max(ff)],\n [time_interval[1], time_interval[1]], [min(ff), max(ff)],\n [1, 3], [6e3, 6e3])\n\n#plt.axis([1.3, 1.6, min(ff)/5, max(ff)/5])\nt[p==max(p[t>1.6])]\nt[143]\n\nnp.sqrt(mp.shape[0])*7.5", "_____no_output_____" ], [ "Xdmd_2D=np.reshape(np.concatenate((results[0]['mp_dmd'],results[1]['mp_dmd'],results[2]['mp_dmd']),axis=1),(22,22,-1),order='F')\nmp_2D=np.reshape(mp,(22,22,-1),order='F')", "_____no_output_____" ], [ "X_lim = 21*7.5\nX,Y=np.linspace(0,X_lim,22),np.linspace(0,X_lim,22)", "_____no_output_____" ], [ "xgrid,ygrid=np.meshgrid(X,Y)", "_____no_output_____" ], [ "Xdmd_2D[:,:,0].shape,mp_2D[:,:,0].shape\nE = abs(mp_2D.real-Xdmd_2D.real)/mp_2D.real*100\nE[mp_2D==0]=0", "/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in true_divide\n \n/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in true_divide\n \n" ], [ "## print('t=0')\nfig = plt.figure(figsize=(15,12.75))\n\nsteps = 0, 143, 200\ncolor = 'inferno'\nfor i in range(len(steps)):\n \n ax1=fig.add_subplot(3,3,3*i+1)\n ax1.set_aspect('equal')\n vmax = max(np.max(mp_2D[:,:,steps[i]]), np.max(Xdmd_2D[:,:,steps[i]].real))\n vmin = 0.0#min(np.min(mp_2D[:,:,steps[i]]>0), np.min(Xdmd_2D[:,:,steps[i]].real>0))\n plot = plt.pcolor(xgrid, ygrid, mp_2D[:,:,steps[i]].real.T,cmap=color, \n vmin=vmin, vmax=vmax, rasterized=True, linewidth=0)\n plot.set_edgecolor('face')\n\n cbar = fig.colorbar(plot)\n cbar.formatter.set_powerlimits((0, 0))\n cbar.update_ticks()\n if i == 0:\n plt.title('Reference')\n plt.xlabel('x (cm)')\n plt.ylabel('t = {:.2f} s \\ny (cm)'.format(t[steps[i]]))\n plt.axis([0, 135, 0, 135])\n\n ax2=fig.add_subplot(3,3,3*i+2)\n ax2.set_aspect('equal')\n plt.axis([0, 135, 0, 135])\n plot=plt.pcolor(xgrid, ygrid, Xdmd_2D[:,:,steps[i]].real.T,cmap=color, \n vmin=0, vmax=vmax, rasterized=True, linewidth=0)\n cbar = fig.colorbar(plot)\n cbar.formatter.set_powerlimits((0, 0))\n cbar.update_ticks()\n if i == 0:\n plt.title('DMD')\n\n ax3=fig.add_subplot(3,3,3*i+3)\n ax3.set_aspect('equal')\n plt.axis([0, 135, 0, 135])\n plt.pcolor(xgrid, ygrid, E[:,:,steps[i]].T,cmap=color, \n rasterized=True, linewidth=0)\n plt.colorbar()\n if i == 0:\n plt.title('Relative Error (\\%)')\n\nplt.tight_layout()\nplt.savefig('../images/meshpower.pdf')", "/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n/home/robertsj/opt/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1328: UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n" ], [ "p[0]", "_____no_output_____" ], [ "p[0]/sum(mp[:, 0])*17550.0", "_____no_output_____" ], [ "sum(mp[:,0]), p[0]*17550.0", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aedd71d5dbfc7027138f9600de30b8cdecdf513
9,558
ipynb
Jupyter Notebook
2_6_Attention/.ipynb_checkpoints/1_2. Attention Basics, solution-checkpoint.ipynb
chinitaberrio/CV_nanodegree
bf96199be446a71b6a04fff9598b1ae11d1ae4ab
[ "MIT" ]
null
null
null
2_6_Attention/.ipynb_checkpoints/1_2. Attention Basics, solution-checkpoint.ipynb
chinitaberrio/CV_nanodegree
bf96199be446a71b6a04fff9598b1ae11d1ae4ab
[ "MIT" ]
null
null
null
2_6_Attention/.ipynb_checkpoints/1_2. Attention Basics, solution-checkpoint.ipynb
chinitaberrio/CV_nanodegree
bf96199be446a71b6a04fff9598b1ae11d1ae4ab
[ "MIT" ]
null
null
null
30.932039
335
0.624608
[ [ [ "# [SOLUTION] Attention Basics\nIn this notebook, we look at how attention is implemented. We will focus on implementing attention in isolation from a larger model. That's because when implementing attention in a real-world model, a lot of the focus goes into piping the data and juggling the various vectors rather than the concepts of attention themselves.\n\nWe will implement attention scoring as well as calculating an attention context vector.\n\n## Attention Scoring\n### Inputs to the scoring function\nLet's start by looking at the inputs we'll give to the scoring function. We will assume we're in the first step in the decoging phase. The first input to the scoring function is the hidden state of decoder (assuming a toy RNN with three hidden nodes -- not usable in real life, but easier to illustrate):", "_____no_output_____" ] ], [ [ "dec_hidden_state = [5,1,20]", "_____no_output_____" ] ], [ [ "Let's visualize this vector:", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Let's visualize our decoder hidden state\nplt.figure(figsize=(1.5, 4.5))\nsns.heatmap(np.transpose(np.matrix(dec_hidden_state)), annot=True, cmap=sns.light_palette(\"purple\", as_cmap=True), linewidths=1)", "_____no_output_____" ] ], [ [ "Our first scoring function will score a single annotation (encoder hidden state), which looks like this:", "_____no_output_____" ] ], [ [ "annotation = [3,12,45] #e.g. Encoder hidden state", "_____no_output_____" ], [ "# Let's visualize the single annotation\nplt.figure(figsize=(1.5, 4.5))\nsns.heatmap(np.transpose(np.matrix(annotation)), annot=True, cmap=sns.light_palette(\"orange\", as_cmap=True), linewidths=1)", "_____no_output_____" ] ], [ [ "### IMPLEMENT: Scoring a Single Annotation\nLet's calculate the dot product of a single annotation. Numpy's [dot()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) is a good candidate for this operation", "_____no_output_____" ] ], [ [ "def single_dot_attention_score(dec_hidden_state, enc_hidden_state):\n # TODO: return the dot product of the two vectors\n return np.dot(dec_hidden_state, enc_hidden_state)\n \nsingle_dot_attention_score(dec_hidden_state, annotation)", "_____no_output_____" ] ], [ [ "\n### Annotations Matrix\nLet's now look at scoring all the annotations at once. To do that, here's our annotation matrix:", "_____no_output_____" ] ], [ [ "annotations = np.transpose([[3,12,45], [59,2,5], [1,43,5], [4,3,45.3]])", "_____no_output_____" ] ], [ [ "And it can be visualized like this (each column is a hidden state of an encoder time step):", "_____no_output_____" ] ], [ [ "# Let's visualize our annotation (each column is an annotation)\nax = sns.heatmap(annotations, annot=True, cmap=sns.light_palette(\"orange\", as_cmap=True), linewidths=1)", "_____no_output_____" ] ], [ [ "### IMPLEMENT: Scoring All Annotations at Once\nLet's calculate the scores of all the annotations in one step using matrix multiplication. Let's continue to us the dot scoring method\n\n<img src=\"images/scoring_functions.png\" />\n\nTo do that, we'll have to transpose `dec_hidden_state` and [matrix multiply](https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html) it with `annotations`.", "_____no_output_____" ] ], [ [ "def dot_attention_score(dec_hidden_state, annotations):\n # TODO: return the product of dec_hidden_state transpose and enc_hidden_states\n return np.matmul(np.transpose(dec_hidden_state), annotations)\n \nattention_weights_raw = dot_attention_score(dec_hidden_state, annotations)\nattention_weights_raw", "_____no_output_____" ] ], [ [ "Looking at these scores, can you guess which of the four vectors will get the most attention from the decoder at this time step?\n\n## Softmax\nNow that we have our scores, let's apply softmax:\n<img src=\"images/softmax.png\" />", "_____no_output_____" ] ], [ [ "def softmax(x):\n x = np.array(x, dtype=np.float128)\n e_x = np.exp(x)\n return e_x / e_x.sum(axis=0) \n\nattention_weights = softmax(attention_weights_raw)\nattention_weights", "_____no_output_____" ] ], [ [ "Even when knowing which annotation will get the most focus, it's interesting to see how drastic softmax makes the end score become. The first and last annotation had the respective scores of 927 and 929. But after softmax, the attention they'll get is 0.119 and 0.880 respectively.\n\n# Applying the scores back on the annotations\nNow that we have our scores, let's multiply each annotation by its score to proceed closer to the attention context vector. This is the multiplication part of this formula (we'll tackle the summation part in the latter cells)\n\n<img src=\"images/Context_vector.png\" />", "_____no_output_____" ] ], [ [ "def apply_attention_scores(attention_weights, annotations):\n # TODO: Multiple the annotations by their weights\n return attention_weights * annotations\n\napplied_attention = apply_attention_scores(attention_weights, annotations)\napplied_attention", "_____no_output_____" ] ], [ [ "Let's visualize how the context vector looks now that we've applied the attention scores back on it:", "_____no_output_____" ] ], [ [ "# Let's visualize our annotations after applying attention to them\nax = sns.heatmap(applied_attention, annot=True, cmap=sns.light_palette(\"orange\", as_cmap=True), linewidths=1)", "_____no_output_____" ] ], [ [ "Contrast this with the raw annotations visualized earlier in the notebook, and we can see that the second and third annotations (columns) have been nearly wiped out. The first annotation maintains some of its value, and the fourth annotation is the most pronounced.\n\n# Calculating the Attention Context Vector\nAll that remains to produce our attention context vector now is to sum up the four columns to produce a single attention context vector\n", "_____no_output_____" ] ], [ [ "def calculate_attention_vector(applied_attention):\n return np.sum(applied_attention, axis=1)\n\nattention_vector = calculate_attention_vector(applied_attention)\nattention_vector", "_____no_output_____" ], [ "# Let's visualize the attention context vector\nplt.figure(figsize=(1.5, 4.5))\nsns.heatmap(np.transpose(np.matrix(attention_vector)), annot=True, cmap=sns.light_palette(\"Blue\", as_cmap=True), linewidths=1)", "_____no_output_____" ] ], [ [ "Now that we have the context vector, we can concatinate it with the hidden state and pass it through a hidden layer to produce the the result of this decoding time step.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4aedd7fd170f35f8de438cf6ae332775e4336fdf
5,312
ipynb
Jupyter Notebook
scripts/Analysis Templates/Analysis-inplane-field__Wafer-Piece_Design-Iteration_Junction_Cooldown.ipynb
ShabaniLab/shabanipy
3761eef32e5102782ae11eae5bf08ff596d92205
[ "MIT" ]
6
2019-06-25T20:01:03.000Z
2022-03-25T23:15:57.000Z
scripts/Analysis Templates/Analysis-inplane-field__Wafer-Piece_Design-Iteration_Junction_Cooldown.ipynb
ShabaniLab/shabanipy
3761eef32e5102782ae11eae5bf08ff596d92205
[ "MIT" ]
null
null
null
scripts/Analysis Templates/Analysis-inplane-field__Wafer-Piece_Design-Iteration_Junction_Cooldown.ipynb
ShabaniLab/shabanipy
3761eef32e5102782ae11eae5bf08ff596d92205
[ "MIT" ]
5
2019-06-11T17:21:54.000Z
2021-08-24T14:45:08.000Z
37.408451
162
0.542169
[ [ [ "import h5py\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nplt.style.use('presentation')\n\nfrom shabanipy.jj.plotting_general import plot_inplane_vs_bias, plot_inplane_vs_Ic_Rn, plot_inplane_vs_IcRn\n\n#: Name of the sample that must appear in the measurement name usually of the form \"{Wafer}-{Piece}_{Design}-{Iteration}_{Junction}_{Cooldown}\"\nSAMPLE_NAME = \"{Wafer}-{Piece}_{Design}-{Iteration}\"\nSAMPLE_ID = \"{Wafer}-{Piece}_{Design}-{Iteration}_{Junction}_{Cooldown}\"\n\n#: hdf5 file number\nFILE_NUM = ''\n\n#: Path to store generated files\nPATH = (f\"/Users/bh/Desktop/Code/Topological JJ/Samples/{SAMPLE_NAME}/{SAMPLE_ID}\")\n\n#: Name of generated processed data file\nPROCESSED_DATA_NAME = (f\"{PATH}/Data/{SAMPLE_ID}_processed-data-{FILE_NUM}.hdf5\")\n\nh = h5py.File(PROCESSED_DATA_NAME, 'r')\n\n# field_y = 'In-plane Field - Y\nfield_z = 'In-plane Field - Z'\nvg = 'Vg::'\n\nf = h['Data'][f'{field_z}'][f'{vg}']\n#[f'{field_y}']", "_____no_output_____" ], [ "in_field = np.array(f['Vector Magnet - Field Y'])\nv_drop = np.array(f[\"Voltage Drop\"])\nscaled_v_drop = np.array(f[\"ScaledVoltage\"])\nbias = np.array(f[\"Bias\"])\ndVdI = np.diff(np.array(f[\"ScaledVoltage\"]))/np.diff(np.array(f[\"Bias\"]))\ndR = np.array(f[\"dR\"])", "_____no_output_____" ], [ "plot_inplane_vs_bias(in_field, bias, np.abs(dR)\n# savgol_windowl = 3, savgol_polyorder = 1,\n# cvmax = , cvmin = ,\n# bias_limits = ,\n# in_field_limits = ,\n# fig_size = ,\n )\n\nplt.savefig(f\"Figs/In-plane Field/inplane_vs_bias__{SAMPLE_NAME}_field-z:{field_z[16:]}_Vg:{vg[4:]}_{FILE_NUM}.pdf\", dpi = 400, bbox_inches = 'tight')\n# plt.savefig(f\"Figs/In-plane Field/inplane_vs_bias__{SAMPLE_NAME}_field-y:{field_y[16:]}_Vg:{vg[4:]}_{FILE_NUM}.pdf\", dpi = 400, bbox_inches = 'tight')", "_____no_output_____" ], [ "\"\"\"Voltage threshold in V above which the junction is not considered to carry a\nsupercurrent anymore. Used in the determination of the critical current. Usually of the order of a couple e-5 or e-4. \nDefault is 1e-4.\"\"\"\nic_voltage_threshold = \n\n\"\"\"Positive bias value above which the data can be used to extract the\nnormal resistance. Default is 10e-6.\"\"\"\nhigh_bias_threshold =\n\nplot_inplane_vs_Ic_Rn(in_field, bias, scaled_v_drop,\n ic_voltage_threshold = ic_voltage_threshold,\n high_bias_threshold = high_bias_threshold,\n# savgol_windowl = 3, savgol_polyorder = 1,\n# ic_limits = ,\n# rn_limits = ,\n# in_field_limits = ,\n# fig_size = ,\n )\n\nplt.savefig(f\"Figs/In-plane Field/inplane_vs_Ic_Rn__{SAMPLE_NAME}_field-z:{field_z[16:]}_Vg:{vg[4:]}_{FILE_NUM}.pdf\", dpi = 400, bbox_inches = 'tight')\n# plt.savefig(f\"Figs/In-plane Field/inplane_vs_Ic_Rn__{SAMPLE_NAME}_field-y:{field_y[16:]}_Vg:{vg[4:]}_{FILE_NUM}.pdf\", dpi = 400, bbox_inches = 'tight')", "_____no_output_____" ], [ "plot_inplane_vs_IcRn(in_field, bias, scaled_v_drop,\n ic_voltage_threshold = ic_voltage_threshold,\n high_bias_threshold = high_bias_threshold,\n# savgol_windowl = 3, savgol_polyorder = 1,\n# icrn_limits = ,\n# in_field_limits = ,\n# fig_size = ,)\n\nplt.savefig(f\"Figs/In-plane Field/inplane_vs_IcRn__{SAMPLE_NAME}_field-z:{field_z[16:]}_Vg:{vg[4:]}_{FILE_NUM}.pdf\", dpi = 400, bbox_inches = 'tight')\n# plt.savefig(f\"Figs/In-plane Field/inplane_vs_IcRn__{SAMPLE_NAME}_field-y:{field_y[16:]}_Vg:{vg[4:]}_{FILE_NUM}.pdf\", dpi = 400, bbox_inches = 'tight')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4aedde880ebf4eb8363b96baae9b2baac13b94b9
102,985
ipynb
Jupyter Notebook
Notebooks/Derivatives.ipynb
darkeclipz/jupyter-notebooks
5de784244ad9db12cfacbbec3053b11f10456d7e
[ "Unlicense" ]
1
2018-08-28T12:16:12.000Z
2018-08-28T12:16:12.000Z
Notebooks/Derivatives.ipynb
darkeclipz/jupyter-notebooks
5de784244ad9db12cfacbbec3053b11f10456d7e
[ "Unlicense" ]
null
null
null
Notebooks/Derivatives.ipynb
darkeclipz/jupyter-notebooks
5de784244ad9db12cfacbbec3053b11f10456d7e
[ "Unlicense" ]
null
null
null
251.797066
19,704
0.911162
[ [ [ "%pylab inline", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "import numpy as np", "_____no_output_____" ], [ "def f(x):\n return 2*x**2\n\npoints = np.arange(0,25,0.5)\nplot(points, f(points), color='b', linewidth=2);", "_____no_output_____" ], [ "def fPrime(x):\n return 4*x\n\nplot(points, fPrime(points), color='b', linewidth=2);", "_____no_output_____" ], [ "points", "_____no_output_____" ], [ "points * 2", "_____no_output_____" ], [ "def f(x):\n return 2*x", "_____no_output_____" ], [ "f(points)", "_____no_output_____" ] ], [ [ "## Linear", "_____no_output_____" ] ], [ [ "for i in range(4):\n plot(points, f(points+i*10), linewidth=2);", "_____no_output_____" ] ], [ [ "## Quadratic", "_____no_output_____" ] ], [ [ "def f(x):\n return 4*x**2+3", "_____no_output_____" ], [ "plot(points, f(points), color='b', linewidth=2);", "_____no_output_____" ] ], [ [ "## Cubic", "_____no_output_____" ] ], [ [ "def f(x):\n return 4*(x-12)**3-2**2+10", "_____no_output_____" ], [ "plot(points, f(points), color='b', linewidth=2);", "_____no_output_____" ] ], [ [ "## $f'(x)$", "_____no_output_____" ] ], [ [ "def fPrime(x):\n return 12*(x-12)**2-4*x", "_____no_output_____" ], [ "plot(points, fPrime(points), color='b', linewidth=2);", "_____no_output_____" ] ], [ [ "## $f''(x)$", "_____no_output_____" ] ], [ [ "def fPrime2(x):\n return 24*x-4", "_____no_output_____" ], [ "plot(points, fPrime2(points), color='b', linewidth=2);", "_____no_output_____" ] ], [ [ "## $f'''(x)$", "_____no_output_____" ] ], [ [ "def fPrime3(x):\n return x*0+24", "_____no_output_____" ], [ "plot(points, fPrime3(points), color='b', linewidth=2);", "_____no_output_____" ] ] ]
[ "code", "markdown", "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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4aede7a1d2d421d5c919f25f6b56056f9bf4f85a
34,417
ipynb
Jupyter Notebook
docs/examples/1-basics/1c-Tutorial-Wor_basic.ipynb
scuervo91/dcapy
46c9277e607baff437e5707167476d5f7e2cf80c
[ "MIT" ]
4
2021-05-21T13:26:10.000Z
2021-11-15T17:17:01.000Z
docs/examples/1-basics/1c-Tutorial-Wor_basic.ipynb
scuervo91/dcapy
46c9277e607baff437e5707167476d5f7e2cf80c
[ "MIT" ]
null
null
null
docs/examples/1-basics/1c-Tutorial-Wor_basic.ipynb
scuervo91/dcapy
46c9277e607baff437e5707167476d5f7e2cf80c
[ "MIT" ]
null
null
null
45.345191
190
0.441642
[ [ [ "# WOR Forecasting\n\nIn this section is introduced the basic classes and functions to make Forecast by applying the Wor Methodology ", "_____no_output_____" ] ], [ [ "import os\nfrom dcapy import dca\nfrom datetime import date\nimport numpy as np ", "_____no_output_____" ] ], [ [ "The WOR forecasting is an empirical method to estimate the trend of the water production with respect the cumulative oil production. \n\n\nGenerally you can determine the WOR (Water-Oil Ratio) vs the Np (Cumulative Oil Production) linear relationship on a semi-log plot when preducing at a constant rate of total fluids.\n\n$\nWOR = \\frac{q_{w}}{q_{o}}\n$", "_____no_output_____" ], [ "## Simple Functions to convert Bsw to Wor\n", "_____no_output_____" ] ], [ [ "list_bsw = [0.01,0.01,0.1,0.5,0.8,0.9,0.95,0.99]\n\nlist_wor = dca.bsw_to_wor(list_bsw)", "_____no_output_____" ], [ "dca.wor_to_bsw(list_wor)", "_____no_output_____" ] ], [ [ "## Wor Forecasting function\n\nThe parameters required to define a WOR model are:\n\n+ **Slope**: It is the relationship between the WOR and Np. It is defined as $\\frac{d(log(WOR))}{d Np}$\n+ **Fluid Rate**: Total fluid rate production target\n+ **Ti**: Initial Time\n+ **WOR initial**: The Wor value at the initial time", "_____no_output_____" ] ], [ [ "time1 = np.arange(0,10,1)\nslope = 3e-6\nbswi = 0.5\nwori = dca.bsw_to_wor(bswi)\nfluid_rate = [5000]*10\n\nf1 = dca.wor_forecast(time1,fluid_rate,slope,wori)\nprint(f1)\n", " oil_rate water_rate oil_cum water_cum bsw \\\ndate \n0 2500.000000 2500.000000 2500.000000 2500.000000 0.500000 \n1 2490.625044 2509.374956 4990.625044 5009.374956 0.501875 \n2 2481.285506 2518.714494 7471.910550 7528.089450 0.503743 \n3 2471.981509 2528.018491 9943.892058 10056.107942 0.505604 \n4 2462.713170 2537.286830 12406.605228 12593.394772 0.507457 \n5 2453.480601 2546.519399 14860.085829 15139.914171 0.509304 \n6 2444.283905 2555.716095 17304.369734 17695.630266 0.511143 \n7 2435.123183 2564.876817 19739.492917 20260.507083 0.512975 \n8 2425.998526 2574.001474 22165.491443 22834.508557 0.514800 \n9 2416.910022 2583.089978 24582.401465 25417.598535 0.516618 \n\n wor wor_1 delta_time fluid_rate fluid_cum \ndate \n0 1.000000 2.000000 1.0 5000 5000.0 \n1 1.007528 2.007528 1.0 5000 10000.0 \n2 1.015085 2.015085 1.0 5000 15000.0 \n3 1.022669 2.022669 1.0 5000 20000.0 \n4 1.030281 2.030281 1.0 5000 25000.0 \n5 1.037921 2.037921 1.0 5000 30000.0 \n6 1.045589 2.045589 1.0 5000 35000.0 \n7 1.053284 2.053284 1.0 5000 40000.0 \n8 1.061007 2.061007 1.0 5000 45000.0 \n9 1.068757 2.068757 1.0 5000 50000.0 \n" ] ], [ [ "In this case you have to pass an array with the desired rate whose length be equal to the time array. That means you can pass a fluid rate array with different values.", "_____no_output_____" ] ], [ [ "time1 = np.arange(0,10,1)\nslope = 3e-5\nbswi = 0.5\nwori = dca.bsw_to_wor(bswi)\nfluid_rate = [5000]*5 + [6000]*5\n\nf1 = dca.wor_forecast(time1,fluid_rate,slope,wori)\nprint(f1)", " oil_rate water_rate oil_cum water_cum bsw \\\ndate \n0 2500.000000 2500.000000 2500.000000 2500.000000 0.500000 \n1 2406.293921 2593.706079 4906.293921 5093.706079 0.518741 \n2 2316.345424 2683.654576 7222.639345 7777.360655 0.536731 \n3 2230.205766 2769.794234 9452.845111 10547.154889 0.553959 \n4 2147.874995 2852.125005 11600.720106 13399.279894 0.570425 \n5 2483.173555 3516.826445 14083.893662 16916.106338 0.586138 \n6 2375.487941 3624.512059 16459.381602 20540.618398 0.604085 \n7 2274.018964 3725.981036 18733.400566 24266.599434 0.620997 \n8 2178.506150 3821.493850 20911.906716 28088.093284 0.636916 \n9 2088.660154 3911.339846 23000.566869 31999.433131 0.651890 \n\n wor wor_1 delta_time fluid_rate fluid_cum \ndate \n0 1.000000 2.000000 1.0 5000 5000.0 \n1 1.077884 2.077884 1.0 5000 10000.0 \n2 1.158573 2.158573 1.0 5000 15000.0 \n3 1.241946 2.241946 1.0 5000 20000.0 \n4 1.327882 2.327882 1.0 5000 25000.0 \n5 1.416263 2.416263 1.0 6000 31000.0 \n6 1.525797 2.525797 1.0 6000 37000.0 \n7 1.638500 2.638500 1.0 6000 43000.0 \n8 1.754181 2.754181 1.0 6000 49000.0 \n9 1.872655 2.872655 1.0 6000 55000.0 \n" ] ], [ [ "## Wor Class\n\nLike Arps class, the Wor class have the same advantages described before. In this case you can pass the initial bsw directly so it internally will convert it to WOR value. ", "_____no_output_____" ] ], [ [ "bsw = 0.5\nslope = 3.5e-6\nti = 0\nfluid = 1000\nw1 = dca.Wor(bsw=bsw,slope=slope,ti=ti, fluid_rate = fluid)\n\nprint(type(w1))", "<class 'dcapy.dca.wor.Wor'>\n" ] ], [ [ "The forecast method is also present with the same parameters as seen in Arps class", "_____no_output_____" ] ], [ [ "fr = w1.forecast(\n start = 0,\n end = 5,\n)\nprint(fr)", " oil_rate water_rate oil_cum water_cum bsw wor \\\ndate \n0 500.000000 500.000000 500.000000 500.000000 0.500000 1.000000 \n1 499.562500 500.437500 999.562500 1000.437500 0.500437 1.001752 \n2 499.125384 500.874616 1498.687884 1501.312116 0.500875 1.003505 \n3 498.688651 501.311349 1997.376535 2002.623465 0.501311 1.005259 \n4 498.252303 501.747697 2495.628838 2504.371162 0.501748 1.007015 \n\n wor_1 delta_time fluid_rate fluid_cum iteration oil_volume \\\ndate \n0 2.000000 1.0 1000.0 1000.0 0 499.562500 \n1 2.001752 1.0 1000.0 2000.0 0 499.343942 \n2 2.003505 1.0 1000.0 3000.0 0 498.907017 \n3 2.005259 1.0 1000.0 4000.0 0 498.470477 \n4 2.007015 1.0 1000.0 5000.0 0 498.252303 \n\n water_volume gas_cum gas_volume gas_rate \ndate \n0 500.437500 0 0 0 \n1 500.656058 0 0 0 \n2 501.092983 0 0 0 \n3 501.529523 0 0 0 \n4 501.747697 0 0 0 \n" ] ], [ [ "If you want to change the fluid rate you can pass a different value when calling the `forecast` method", "_____no_output_____" ] ], [ [ "fr = w1.forecast(\n start = 0,\n end = 10,\n fluid_rate = 2000\n)\nprint(fr)", " oil_rate water_rate oil_cum water_cum bsw wor \\\ndate \n0 1000.000000 1000.000000 1000.000000 1000.000000 0.500000 1.000000 \n1 998.250002 1001.749998 1998.250002 2001.749998 0.500875 1.003506 \n2 996.503077 1003.496923 2994.753079 3005.246921 0.501748 1.007018 \n3 994.759230 1005.240770 3989.512309 4010.487691 0.502620 1.010537 \n4 993.018467 1006.981533 4982.530776 5017.469224 0.503491 1.014061 \n5 991.280792 1008.719208 5973.811568 6026.188432 0.504360 1.017592 \n6 989.546211 1010.453789 6963.357778 7036.642222 0.505227 1.021128 \n7 987.814727 1012.185273 7951.172505 8048.827495 0.506093 1.024671 \n8 986.086346 1013.913654 8937.258851 9062.741149 0.506957 1.028220 \n9 984.361072 1015.638928 9921.619923 10078.380077 0.507819 1.031775 \n\n wor_1 delta_time fluid_rate fluid_cum iteration oil_volume \\\ndate \n0 2.000000 1.0 2000.0 2000.0 0 998.250002 \n1 2.003506 1.0 2000.0 4000.0 0 997.376539 \n2 2.007018 1.0 2000.0 6000.0 0 995.631153 \n3 2.010537 1.0 2000.0 8000.0 0 993.888848 \n4 2.014061 1.0 2000.0 10000.0 0 992.149630 \n5 2.017592 1.0 2000.0 12000.0 0 990.413501 \n6 2.021128 1.0 2000.0 14000.0 0 988.680469 \n7 2.024671 1.0 2000.0 16000.0 0 986.950537 \n8 2.028220 1.0 2000.0 18000.0 0 985.223709 \n9 2.031775 1.0 2000.0 20000.0 0 984.361072 \n\n water_volume gas_cum gas_volume gas_rate \ndate \n0 1001.749998 0 0 0 \n1 1002.623461 0 0 0 \n2 1004.368847 0 0 0 \n3 1006.111152 0 0 0 \n4 1007.850370 0 0 0 \n5 1009.586499 0 0 0 \n6 1011.319531 0 0 0 \n7 1013.049463 0 0 0 \n8 1014.776291 0 0 0 \n9 1015.638928 0 0 0 \n" ] ], [ [ "## Multiple Values\n\nYou can create Wor instances with multiple values on each of the parameters. This will create additional iterations accorging with the number of cases and the broadcast shape", "_____no_output_____" ] ], [ [ "bsw = [0.4,0.5,0.6]\nslope = 3.5e-6\nti = 0\nfluid = 1000\nw2 = dca.Wor(bsw=bsw,slope=slope,ti=ti, fluid_rate = fluid)\n\nfr = w2.forecast(\n start = 0,\n end = 4,\n fluid_rate = 2000\n)\nprint(fr)", " oil_rate water_rate oil_cum water_cum bsw wor \\\ndate \n0 1200.000000 800.000000 1200.000000 800.000000 0.400000 0.666667 \n1 1197.983156 802.016844 2397.983156 1602.016844 0.401008 0.669473 \n2 1195.968028 804.031972 3593.951184 2406.048816 0.402016 0.672286 \n3 1193.954637 806.045363 4787.905821 3212.094179 0.403023 0.675106 \n0 1000.000000 1000.000000 1000.000000 1000.000000 0.500000 1.000000 \n1 998.250002 1001.749998 1998.250002 2001.749998 0.500875 1.003506 \n2 996.503077 1003.496923 2994.753079 3005.246921 0.501748 1.007018 \n3 994.759230 1005.240770 3989.512309 4010.487691 0.502620 1.010537 \n0 800.000000 1200.000000 800.000000 1200.000000 0.600000 1.500000 \n1 798.656377 1201.343623 1598.656377 2401.343623 0.600672 1.504206 \n2 797.315766 1202.684234 2395.972143 3604.027857 0.601342 1.508416 \n3 795.978163 1204.021837 3191.950306 4808.049694 0.602011 1.512632 \n\n wor_1 delta_time fluid_rate fluid_cum iteration oil_volume \\\ndate \n0 1.666667 1.0 2000.0 2000.0 0 1197.983156 \n1 1.669473 1.0 2000.0 4000.0 0 1196.975592 \n2 1.672286 1.0 2000.0 6000.0 0 1194.961333 \n3 1.675106 1.0 2000.0 8000.0 0 1193.954637 \n0 2.000000 1.0 2000.0 2000.0 1 998.250002 \n1 2.003506 1.0 2000.0 4000.0 1 997.376539 \n2 2.007018 1.0 2000.0 6000.0 1 995.631153 \n3 2.010537 1.0 2000.0 8000.0 1 994.759230 \n0 2.500000 1.0 2000.0 2000.0 2 798.656377 \n1 2.504206 1.0 2000.0 4000.0 2 797.986072 \n2 2.508416 1.0 2000.0 6000.0 2 796.646965 \n3 2.512632 1.0 2000.0 8000.0 2 795.978163 \n\n water_volume gas_cum gas_volume gas_rate \ndate \n0 802.016844 0 0 0 \n1 803.024408 0 0 0 \n2 805.038667 0 0 0 \n3 806.045363 0 0 0 \n0 1001.749998 0 0 0 \n1 1002.623461 0 0 0 \n2 1004.368847 0 0 0 \n3 1005.240770 0 0 0 \n0 1201.343623 0 0 0 \n1 1202.013928 0 0 0 \n2 1203.353035 0 0 0 \n3 1204.021837 0 0 0 \n" ] ], [ [ "As the each case of fluid rate can be an array with multiple values, you can pass a 2D array to make more than one iteration.", "_____no_output_____" ] ], [ [ "bsw = 0.4\nslope = 3.5e-6\nti = 0\nfluid = [[1000],[2000]]\nw3 = dca.Wor(bsw=bsw,slope=slope,ti=ti, fluid_rate = fluid)\n\nfr = w3.forecast(\n start = 0,\n end = 4,\n)\nprint(fr)", " oil_rate water_rate oil_cum water_cum bsw wor \\\ndate \n0 600.000000 400.000000 600.000000 400.000000 0.400000 0.666667 \n1 599.495894 400.504106 1199.495894 800.504106 0.400504 0.668068 \n2 598.992002 401.007998 1798.487896 1201.512104 0.401008 0.669471 \n3 598.488324 401.511676 2396.976220 1603.023780 0.401512 0.670876 \n0 1200.000000 800.000000 1200.000000 800.000000 0.400000 0.666667 \n1 1197.983156 802.016844 2397.983156 1602.016844 0.401008 0.669473 \n2 1195.968028 804.031972 3593.951184 2406.048816 0.402016 0.672286 \n3 1193.954637 806.045363 4787.905821 3212.094179 0.403023 0.675106 \n\n wor_1 delta_time fluid_rate fluid_cum iteration oil_volume \\\ndate \n0 1.666667 1.0 1000.0 1000.0 0 599.495894 \n1 1.668068 1.0 1000.0 2000.0 0 599.243948 \n2 1.669471 1.0 1000.0 3000.0 0 598.740163 \n3 1.670876 1.0 1000.0 4000.0 0 598.488324 \n0 1.666667 1.0 2000.0 2000.0 1 1197.983156 \n1 1.669473 1.0 2000.0 4000.0 1 1196.975592 \n2 1.672286 1.0 2000.0 6000.0 1 1194.961333 \n3 1.675106 1.0 2000.0 8000.0 1 1193.954637 \n\n water_volume gas_cum gas_volume gas_rate \ndate \n0 400.504106 0 0 0 \n1 400.756052 0 0 0 \n2 401.259837 0 0 0 \n3 401.511676 0 0 0 \n0 802.016844 0 0 0 \n1 803.024408 0 0 0 \n2 805.038667 0 0 0 \n3 806.045363 0 0 0 \n" ], [ "bsw = 0.4\nslope = 3.5e-6\nti = 0\nfluid = [[1000,1200,1300,1250],[2000,2200,2300,2250]]\nw4 = dca.Wor(bsw=bsw,slope=slope,ti=ti, fluid_rate = fluid)\n\nfr = w4.forecast(\n start = 0,\n end = 4,\n)\nprint(fr)", " oil_rate water_rate oil_cum water_cum bsw wor \\\ndate \n0 600.000000 400.000000 600.000000 400.000000 0.400000 0.666667 \n1 719.395073 480.604927 1319.395073 880.604927 0.400504 0.668068 \n2 778.558558 521.441442 2097.953631 1402.046369 0.401109 0.669752 \n3 747.795540 502.204460 2845.749171 1904.250829 0.401764 0.671580 \n0 1200.000000 800.000000 1200.000000 800.000000 0.400000 0.666667 \n1 1317.781471 882.218529 2517.781471 1682.218529 0.401008 0.669473 \n2 1375.131387 924.868613 3892.912859 2607.087141 0.402117 0.672567 \n3 1342.632470 907.367530 5235.545329 3514.454671 0.403274 0.675812 \n\n wor_1 delta_time fluid_rate fluid_cum iteration oil_volume \\\ndate \n0 1.666667 1.0 1000.0 1000.0 0 719.395073 \n1 1.668068 1.0 1200.0 2200.0 0 748.976815 \n2 1.669752 1.0 1300.0 3500.0 0 763.177049 \n3 1.671580 1.0 1250.0 4750.0 0 747.795540 \n0 1.666667 1.0 2000.0 2000.0 1 1317.781471 \n1 1.669473 1.0 2200.0 4200.0 1 1346.456429 \n2 1.672567 1.0 2300.0 6500.0 1 1358.881929 \n3 1.675812 1.0 2250.0 8750.0 1 1342.632470 \n\n water_volume gas_cum gas_volume gas_rate \ndate \n0 480.604927 0 0 0 \n1 501.023185 0 0 0 \n2 511.822951 0 0 0 \n3 502.204460 0 0 0 \n0 882.218529 0 0 0 \n1 903.543571 0 0 0 \n2 916.118071 0 0 0 \n3 907.367530 0 0 0 \n" ] ], [ [ "## Wor with Dates", "_____no_output_____" ] ], [ [ "w1 = dca.Wor(\n bsw = 0.5,\n slope = 3e-5,\n fluid_rate = 4000,\n ti=date(2021,1,1)\n)\n\nprint(w1)", "bsw=0.5 slope=3e-05 fluid_rate=4000.0 ti=datetime.date(2021, 1, 1) seed=None gor=None glr=None\n" ], [ "fr = w1.forecast(start=date(2021,1,1),end=date(2021,1,10),freq_output='D')\nprint(fr)", " oil_rate water_rate oil_cum water_cum bsw \\\ndate \n2021-01-01 2000.000000 2000.000000 2000.000000 2000.000000 0.500000 \n2021-01-02 1940.017994 2059.982006 3940.017994 4059.982006 0.514996 \n2021-01-03 1881.936887 2118.063113 5821.954880 6178.045120 0.529516 \n2021-01-04 1825.784009 2174.215991 7647.738890 8352.261110 0.543554 \n2021-01-05 1771.568989 2228.431011 9419.307879 10580.692121 0.557108 \n2021-01-06 1719.286223 2280.713777 11138.594102 12861.405898 0.570178 \n2021-01-07 1668.917224 2331.082776 12807.511326 15192.488674 0.582771 \n2021-01-08 1620.432808 2379.567192 14427.944134 17572.055866 0.594892 \n2021-01-09 1573.795080 2426.204920 16001.739214 19998.260786 0.606551 \n2021-01-10 1528.959218 2471.040782 17530.698433 22469.301567 0.617760 \n\n wor wor_1 delta_time fluid_rate fluid_cum iteration \\\ndate \n2021-01-01 1.000000 2.000000 1.0 4000.0 4000.0 0 \n2021-01-02 1.061837 2.061837 1.0 4000.0 8000.0 0 \n2021-01-03 1.125470 2.125470 1.0 4000.0 12000.0 0 \n2021-01-04 1.190840 2.190840 1.0 4000.0 16000.0 0 \n2021-01-05 1.257886 2.257886 1.0 4000.0 20000.0 0 \n2021-01-06 1.326547 2.326547 1.0 4000.0 24000.0 0 \n2021-01-07 1.396764 2.396764 1.0 4000.0 28000.0 0 \n2021-01-08 1.468476 2.468476 1.0 4000.0 32000.0 0 \n2021-01-09 1.541627 2.541627 1.0 4000.0 36000.0 0 \n2021-01-10 1.616159 2.616159 1.0 4000.0 40000.0 0 \n\n oil_volume water_volume gas_cum gas_volume gas_rate \ndate \n2021-01-01 1940.017994 2059.982006 0 0 0 \n2021-01-02 1910.977440 2089.022560 0 0 0 \n2021-01-03 1853.860448 2146.139552 0 0 0 \n2021-01-04 1798.676499 2201.323501 0 0 0 \n2021-01-05 1745.427606 2254.572394 0 0 0 \n2021-01-06 1694.101723 2305.898277 0 0 0 \n2021-01-07 1644.675016 2355.324984 0 0 0 \n2021-01-08 1597.113944 2402.886056 0 0 0 \n2021-01-09 1551.377149 2448.622851 0 0 0 \n2021-01-10 1528.959218 2471.040782 0 0 0 \n" ], [ "fr = w1.forecast(start=date(2021,1,1),end=date(2022,1,1),freq_output='M')\nprint(fr)", " iteration oil_rate water_rate oil_cum gas_rate \\\ndate \n2021-01 0 1350.964057 2649.035943 41879.885779 0 \n2021-02 0 698.307430 3301.692570 61432.493832 0 \n2021-03 0 454.264376 3545.735624 75514.689501 0 \n2021-04 0 328.988562 3671.011438 85384.346349 0 \n2021-05 0 256.785782 3743.214218 93344.705592 0 \n2021-06 0 209.970023 3790.029977 99643.806288 0 \n2021-07 0 177.400299 3822.599701 105143.215557 0 \n2021-08 0 153.085705 3846.914295 109888.872406 0 \n2021-09 0 134.807356 3865.192644 113933.093099 0 \n2021-10 0 120.397024 3879.602976 117665.400837 0 \n2021-11 0 108.726462 3891.273538 120927.194690 0 \n2021-12 0 99.106363 3900.893637 123999.491938 0 \n2022-01 0 94.643721 3905.356279 124094.135659 0 \n\n water_cum bsw wor wor_1 delta_time fluid_rate \\\ndate \n2021-01 8.212011e+04 0.662259 2.131557 3.131557 1.0 4000.0 \n2021-02 1.745675e+05 0.825423 4.841201 5.841201 1.0 4000.0 \n2021-03 2.844853e+05 0.886434 7.909190 8.909190 1.0 4000.0 \n2021-04 3.946157e+05 0.917753 11.233783 12.233783 1.0 4000.0 \n2021-05 5.106553e+05 0.935804 14.642358 15.642358 1.0 4000.0 \n2021-06 6.243562e+05 0.947507 18.101453 19.101453 1.0 4000.0 \n2021-07 7.428568e+05 0.955650 21.594753 22.594753 1.0 4000.0 \n2021-08 8.621111e+05 0.961729 25.170100 26.170100 1.0 4000.0 \n2021-09 9.780669e+05 0.966298 28.706044 29.706044 1.0 4000.0 \n2021-10 1.098335e+06 0.969901 32.256139 33.256139 1.0 4000.0 \n2021-11 1.215073e+06 0.972818 35.817407 36.817407 1.0 4000.0 \n2021-12 1.336001e+06 0.975223 39.387899 40.387899 1.0 4000.0 \n2022-01 1.339906e+06 0.976339 41.263765 42.263765 1.0 4000.0 \n\n fluid_cum gas_cum oil_volume water_volume gas_volume \ndate \n2021-01 124000.0 0 41293.084427 82706.915573 0 \n2021-02 236000.0 0 19382.818094 92617.181906 0 \n2021-03 360000.0 0 13996.847735 110003.152265 0 \n2021-04 480000.0 0 9824.916434 110175.083566 0 \n2021-05 604000.0 0 7931.659383 116068.340617 0 \n2021-06 724000.0 0 6280.311138 113719.688862 0 \n2021-07 848000.0 0 5485.431980 118514.568020 0 \n2021-08 972000.0 0 4735.183684 119264.816316 0 \n2021-09 1092000.0 0 4036.324926 115963.675074 0 \n2021-10 1216000.0 0 3725.775309 120274.224691 0 \n2021-11 1336000.0 0 3256.623092 116743.376908 0 \n2021-12 1460000.0 0 3067.846594 120932.153406 0 \n2022-01 1464000.0 0 94.643721 3905.356279 0 \n" ], [ "fr = w1.forecast(start=date(2021,1,1),end=date(2024,1,1),freq_output='A')\nprint(fr)", " iteration oil_rate water_rate oil_cum gas_rate \\\ndate \n2021 0 339.724635 3660.275365 123999.491938 0 \n2022 0 65.339756 3934.660244 147848.502869 0 \n2023 0 37.900718 3962.099282 161682.264808 0 \n2024 0 31.055857 3968.944143 161713.320665 0 \n\n water_cum bsw wor wor_1 delta_time fluid_rate \\\ndate \n2021 1.336001e+06 0.915069 20.238811 21.238811 1.0 4000.0 \n2022 2.772151e+06 0.983665 62.728836 63.728836 1.0 4000.0 \n2023 4.218318e+06 0.990525 106.022536 107.022536 1.0 4000.0 \n2024 4.222287e+06 0.992236 127.800179 128.800179 1.0 4000.0 \n\n fluid_cum gas_cum oil_volume water_volume gas_volume \ndate \n2021 1460000.0 0 123016.822796 1.336983e+06 0 \n2022 2920000.0 0 23825.110874 1.436175e+06 0 \n2023 4380000.0 0 13825.868064 1.446174e+06 0 \n2024 4384000.0 0 31.055857 3.968944e+03 0 \n" ] ] ]
[ "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", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4aedec8739b0674ec5678d09da3b686e03c1d00f
49,530
ipynb
Jupyter Notebook
00_intro/00_content.ipynb
jads-nl/intro-to-python
44a2d7150c5af3965d80d4b82418633207104e4b
[ "MIT" ]
null
null
null
00_intro/00_content.ipynb
jads-nl/intro-to-python
44a2d7150c5af3965d80d4b82418633207104e4b
[ "MIT" ]
null
null
null
00_intro/00_content.ipynb
jads-nl/intro-to-python
44a2d7150c5af3965d80d4b82418633207104e4b
[ "MIT" ]
null
null
null
64.408322
2,548
0.648819
[ [ [ "<a href=\"https://colab.research.google.com/github/jads-nl/intro-to-python/blob/develop/00_intro/00_content.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# An Introduction to Python and Programming", "_____no_output_____" ], [ "This book is a *thorough* introduction to programming in [Python <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.python.org/).\n\nIt teaches the concepts behind and the syntax of the core Python language as defined by the [Python Software Foundation <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.python.org/psf/) in the official [language reference <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://docs.python.org/3/reference/index.html). Furthermore, it introduces commonly used functionalities from the [standard library <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://docs.python.org/3/library/index.html) and popular third-party libraries like [numpy <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.numpy.org/), [pandas <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://pandas.pydata.org/), [matplotlib <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://matplotlib.org/), and others.", "_____no_output_____" ], [ "<img src=\"https://github.com/jads-nl/intro-to-python/blob/develop/00_intro/static/logo.png?raw=1\" width=\"15%\" align=\"left\">", "_____no_output_____" ], [ "## Prerequisites", "_____no_output_____" ], [ "There are *no* prerequisites for reading this book.", "_____no_output_____" ], [ "## Objective", "_____no_output_____" ], [ "The **main goal** of this introduction is to **prepare** the student **for further studies** in the \"field\" of **data science**.", "_____no_output_____" ], [ "### Why data science?", "_____no_output_____" ], [ "The term **[data science <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Data_science)** is rather vague and does *not* refer to an academic discipline. Instead, the term was popularized by the tech industry, who also coined non-meaningful job titles such as \"[rockstar](https://www.quora.com/Why-are-engineers-called-rockstars-and-ninjas)\" or \"[ninja developers](https://www.quora.com/Why-are-engineers-called-rockstars-and-ninjas).\" Most *serious* definitions describe the field as being **multi-disciplinary** *integrating* scientific methods, algorithms, and systems thinking to extract knowledge from structured and unstructured data, *and* also emphasize the importance of **[domain knowledge <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Domain_knowledge)**.\n\nRecently, this integration aspect feeds back into the academic world. The [MIT](https://www.mit.edu/), for example, created the new [Stephen A. Schwarzman College of Computing](http://computing.mit.edu) for [artificial intelligence <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Artificial_intelligence) with a 1 billion dollar initial investment where students undergo a \"bilingual\" curriculum with half the classes in quantitative and method-centric fields and the other half in domains such as biology, business, chemistry, politics, (art) history, or linguistics (cf., the [official Q&As](http://computing.mit.edu/faq/) or this [NYT article](https://www.nytimes.com/2018/10/15/technology/mit-college-artificial-intelligence.html)). Their strategists see a future where programming skills are just as naturally embedded into students' curricula as are nowadays subjects like calculus, statistics, or academic writing. Then, programming literacy is not just another \"nice to have\" skill but a prerequisite, or an enabler, to understanding more advanced topics in the actual domains studied.", "_____no_output_____" ], [ "## Installation", "_____no_output_____" ], [ "To \"read\" this book in the most meaningful way, a working installation of **Python 3.8** with [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) is needed.\n\nFor a tutorial on how to install Python on your computer, follow the instructions in the [README.md](https://github.com/webartifex/intro-to-python/blob/develop/README.md#installation) file in the project's [GitHub repository <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_gh.png?raw=1\">](https://github.com/webartifex/intro-to-python). If you cannot install Python on your own machine, you may open the book interactively in the cloud with [Binder <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_mb.png?raw=1\">](https://mybinder.org/v2/gh/webartifex/intro-to-python/develop?urlpath=lab).", "_____no_output_____" ], [ "## Jupyter Notebooks", "_____no_output_____" ], [ "The document you are viewing is a so-called [Jupyter notebook](https://jupyter-notebook.readthedocs.io/en/stable/notebook.html), a file format introduced by the [Jupyter Project](https://jupyter.org/).\n\n\"Jupyter\" is an [acronym <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Acronym) derived from the names of the three major programming languages **[Julia](https://julialang.org/)**, **[Python <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.python.org)**, and **[R](https://www.r-project.org/)**, all of which play significant roles in the world of data science. The Jupyter Project's idea is to serve as an integrating platform such that different programming languages and software packages can be used together within the same project.\n\nJupyter notebooks have become a de-facto standard for communicating and exchanging results in the data science community - both in academia and business - and provide an alternative to command-line interface (CLI or \"terminal\") based ways of running Python code. As an example for the latter case, we could start the default [Python interpreter <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://docs.python.org/3/tutorial/interpreter.html) that comes with every installation by typing the `python` command into a CLI (or `poetry run python` if the project is managed with the [poetry](https://python-poetry.org/docs/) CLI tool as explained in the [README.md](https://github.com/webartifex/intro-to-python/blob/develop/README.md#alternative-installation-for-instructors) file). Then, as the screenshot below shows, we could execute Python code like `1 + 2` or `print(\"Hello World\")` line by line simply by typing it following the `>>>` **prompt** and pressing the **Enter** key. For an introductory course, however, this would be rather tedious and probably scare off many beginners.", "_____no_output_____" ], [ "<img src=\"https://github.com/jads-nl/intro-to-python/blob/develop/00_intro/static/cli_example.png?raw=1\" width=\"50%\">", "_____no_output_____" ], [ "One reason for the popularity of Jupyter notebooks is that they allow mixing text with code in the same document. Text may be formatted with the [Markdown <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_gh.png?raw=1\">](https://guides.github.com/features/mastering-markdown/) language and mathematical formulas typeset with [LaTeX](https://www.overleaf.com/learn/latex/Free_online_introduction_to_LaTeX_%28part_1%29). Moreover, we may include pictures, plots, and even videos. Because of these features, the notebooks developed for this book come in a self-contained \"tutorial\" style enabling students to simply read them from top to bottom while executing the code snippets.\n\nOther ways of running Python code are to use the [IPython <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://ipython.org/) CLI tool instead of the default interpreter or a full-fledged [Integrated Development Environment <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Integrated_development_environment) (e.g., the commercial [PyCharm](https://www.jetbrains.com/pycharm/) or the free [Spyder <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_gh.png?raw=1\">](https://github.com/spyder-ide/spyder) that comes with the Anaconda Distribution).", "_____no_output_____" ], [ "### Markdown Cells vs. Code Cells", "_____no_output_____" ], [ "A Jupyter notebook consists of cells that have a type associated with them. So far, only cells of type \"Markdown\" have been used, which is the default way to present formatted text.\n\nThe cells below are examples of \"Code\" cells containing actual Python code: They calculate the sum of `1` and `2` and print out `\"Hello World\"` when executed, respectively. To edit an existing code cell, enter into it with a mouse click. You are \"in\" a code cell if its frame is highlighted in blue. We call that the **edit mode**.\n\nThere is also a **command mode** that you reach by hitting the **Escape** key. That un-highlights the frame. You are now \"out\" of but still \"on\" the cell. If you were already in command mode, hitting the Escape key does *nothing*.\n\nUsing the **Enter** and **Escape** keys, you can now switch between the two modes.\n\nTo **execute**, or \"run,\" a code cell, hold down the **Control** key and press **Enter**. Note how you do *not* go to the subsequent cell if you keep re-executing the cell you are on. Alternatively, you can hold the **Shift** key and press **Enter**, which executes a cell *and* places your focus on the subsequent cell or creates a new one if there is none.", "_____no_output_____" ] ], [ [ "1 + 2", "_____no_output_____" ], [ "print(\"Hello World\")", "Hello World\n" ] ], [ [ "Similarly, a Markdown cell is also in either edit or command mode. For example, double-click on the text you are reading: This puts you into edit mode. Now, you could change the formatting (e.g., print a word in *italics* or **bold**) and \"execute\" the cell to render the text as specified.\n\nTo change a cell's type, choose either \"Code\" or \"Markdown\" in the navigation bar at the top. Alternatively, you can press either the **Y** or **M** key in command mode.\n\nSometimes, a code cell starts with an exclamation mark `!`. Then, the Jupyter notebook behaves as if the following command were typed directly into a terminal. The cell below asks the `python` CLI to show its version number and is *not* Python code but a command in the [Shell <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Shell_%28computing%29) language. The `!` is useful to execute short CLI commands without leaving a Jupyter notebook.", "_____no_output_____" ] ], [ [ "!python --version", "Python 3.6.9\n" ] ], [ [ "## Programming vs. Computer Science vs. IT", "_____no_output_____" ], [ "In this book, **programming** is defined as\n- a *structured* way of *problem-solving*\n- by *expressing* the steps of a *computation* or *process*\n- and thereby *documenting* the process in a formal way.\n\nProgramming is always *concrete* and based on a *particular case*. It exhibits elements of an *art* or a *craft* as we hear programmers call code \"beautiful\" or \"ugly\" or talk about the \"expressive\" power of an application.", "_____no_output_____" ], [ "That is different from **computer science**, which is\n- a field of study comparable to applied *mathematics* that\n- asks *abstract* questions (e.g., \"Is something computable at all?\"),\n- develops and analyses *algorithms* and *data structures*,\n- and *proves* the *correctness* of a program.\n\nIn a sense, a computer scientist does not need to know a programming language to work, and many computer scientists only know how to produce \"ugly\" looking code in the eyes of professional programmers.", "_____no_output_____" ], [ "**IT** or **information technology** is a term that has many meanings to different people. Often, it has something to do with hardware or physical devices, both of which are out of scope for programmers and computer scientists. Sometimes, it refers to a [support function](https://en.wikipedia.org/wiki/Value_chain#Support_activities) within a company. Many computer scientists and programmers are more than happy if their printer and internet connection work as they often do not know a lot more about that than \"non-technical\" people.", "_____no_output_____" ], [ "## Why Python?", "_____no_output_____" ], [ "### What is Python?", "_____no_output_____" ], [ "Here is a brief history of and some background on Python (cf., also this [TechRepublic article](https://www.techrepublic.com/article/python-is-eating-the-world-how-one-developers-side-project-became-the-hottest-programming-language-on-the-planet/) for a more elaborate story):\n\n- [Guido van Rossum <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Guido_van_Rossum) (Python’s **[Benevolent Dictator for Life <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Benevolent_dictator_for_life)**) was bored during a week around Christmas 1989 and started Python as a hobby project \"that would keep \\[him\\] occupied\" for some days\n- the idea was to create a **general-purpose** scripting **language** that would allow fast *prototyping* and would *run on every operating system*\n- Python grew through the 90s as van Rossum promoted it via his \"Computer Programming for Everybody\" initiative that had the *goal to encourage a basic level of coding literacy* as an equal knowledge alongside English literacy and math skills\n- to become more independent from its creator, the next major version **Python 2** - released in 2000 and still in heavy use as of today - was **open-source** from the get-go which attracted a *large and global community of programmers* that *contributed* their expertise and best practices in their free time to make Python even better\n- **Python 3** resulted from a significant overhaul of the language in 2008 taking into account the *learnings from almost two decades*, streamlining the language, and getting ready for the age of **big data**\n- the language is named after the sketch comedy group [Monty Python <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Monty_Python)", "_____no_output_____" ], [ "#### Summary", "_____no_output_____" ], [ "Python is a **general-purpose** programming **language** that allows for *fast development*, is *easy to read*, **open-source**, long-established, unifies the knowledge of *hundreds of thousands of experts* around the world, runs on basically every machine, and can handle the complexities of applications involving **big data**.", "_____no_output_____" ], [ "### Why open-source?", "_____no_output_____" ], [ "Couldn't a company like Google, Facebook, or Microsoft come up with a better programming language? The following is an argument on why this can likely not be the case.\n\nWouldn't it be weird if professors and scholars of English literature and language studies dictated how we'd have to speak in day-to-day casual conversations or how authors of poesy and novels should use language constructs to achieve a particular type of mood? If you agree with that premise, it makes sense to assume that even programming languages should evolve in a \"natural\" way as users *use* the language over time and in *new* and *unpredictable* contexts creating new conventions.", "_____no_output_____" ], [ "Loose *communities* are the primary building block around which open-source software projects are built. Someone - like Guido - starts a project and makes it free to use for anybody (e.g., on a code-sharing platform like [GitHub <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_gh.png?raw=1\">](https://github.com/)). People find it useful enough to solve one of their daily problems and start using it. They see how a project could be improved and provide new use cases (e.g., via the popularized concept of a [pull request <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_gh.png?raw=1\">](https://help.github.com/articles/about-pull-requests/)). The project grows both in lines of code and people using it. After a while, people start local user groups to share their same interests and meet regularly (e.g., this is a big market for companies like [Meetup](https://www.meetup.com/) or non-profits like [PyData <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://pydata.org/)). Out of these local and usually monthly meetups grow yearly conferences on the country or even continental level (e.g., the original [PyCon <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://us.pycon.org/) in the US, [EuroPython <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://europython.eu/), or [PyCon.DE <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://de.pycon.org/)). The content presented at these conferences is made publicly available via GitHub and YouTube (e.g., [PyCon 2019 <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.youtube.com/channel/UCxs2IIVXaEHHA4BtTiWZ2mQ) or [EuroPython <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](http://europython.tv/)) and serves as references on what people are working on and introductions to the endless number of specialized fields.", "_____no_output_____" ], [ "While these communities are somewhat loose and continuously changing, smaller in-groups, often democratically organized and elected (e.g., the [Python Software Foundation <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.python.org/psf/)), take care of, for example, the development of the \"core\" Python language itself.\n\nPython itself is just a specification (i.e., a set of rules) as to what is allowed and what not: It must first be implemented (c.f., next section below). The current version of Python can always be looked up in the [Python Language Reference <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://docs.python.org/3/reference/index.html). To make changes to that, anyone can make a so-called **[Python Enhancement Proposal <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.python.org/dev/peps/)**, or **PEP** for short, where it needs to be specified what exact changes are to be made and argued why that is a good thing to do. These PEPs are reviewed by the [core developers <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://devguide.python.org/coredev/) and interested people and are then either accepted, modified, or rejected if, for example, the change introduces internal inconsistencies. This process is similar to the **double-blind peer review** established in academia, just a lot more transparent. Many of the contributors even held or hold positions in academia, one more indicator of the high quality standards in the Python community. To learn more about PEPs, check out [PEP 1 <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://www.python.org/dev/peps/pep-0001/) that describes the entire process.\n\nIn total, no one single entity can control how the language evolves, and the users' needs and ideas always feed back to the language specification via a quality controlled and \"democratic\" process.", "_____no_output_____" ], [ "Besides being **free** as in \"free beer,\" a major benefit of open-source is that one can always *look up how something works in detail*: That is the literal meaning of *open* source and a difference to commercial languages (e.g., [MATLAB](https://www.mathworks.com/products/matlab.html)) as a programmer can always continue to *study best practices* or find out how things are implemented. Along this way, many *errors are uncovered*, as well. Furthermore, if one runs an open-source application, one can be reasonably sure that no bad people built in a \"backdoor.\" [Free software <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Free_software) is consequently free of charge but brings *many other freedoms* with it, most notably the freedom to change the code.", "_____no_output_____" ], [ "### Isn't C a lot faster?", "_____no_output_____" ], [ "The default Python implementation is written in the C language and called CPython. This is also what the Anaconda Distribution uses.\n\n[C <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/C_%28programming_language%29) and [C++ <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/C%2B%2B) (cf., this [introduction](https://www.learncpp.com/)) are wide-spread and long-established (i.e., since the 1970s) programming languages employed in many mission-critical software systems (e.g., operating systems themselves, low latency databases and web servers, nuclear reactor control systems, airplanes, ...). They are fast, mainly because the programmer not only needs to come up with the **business logic** but also manage the computer's memory.\n\nIn contrast, Python automatically manages the memory for the programmer. So, speed here is a trade-off between application run time and engineering/development time. Often, the program's run time is not that important: For example, what if C needs 0.001 seconds in a case where Python needs 0.1 seconds to do the same thing? When the requirements change and computing speed becomes an issue, the Python community offers many third-party libraries - usually also written in C - where specific problems can be solved in near-C time.", "_____no_output_____" ], [ "#### Summary", "_____no_output_____" ], [ "While it is true that a language like C is a lot faster than Python when it comes to *pure* **computation time**, this does not matter in many cases as the *significantly shorter* **development cycles** are the more significant cost factor in a rapidly changing world.", "_____no_output_____" ], [ "### Who uses it?", "_____no_output_____" ], [ "<img src=\"https://github.com/jads-nl/intro-to-python/blob/develop/00_intro/static/example_python_users.png?raw=1\" width=\"70%\">", "_____no_output_____" ], [ "While ad-hominem arguments are usually not the best kind of reasoning, we briefly look at some examples of who uses Python and leave it up to the reader to decide if this is convincing or not:\n\n- **[Massachusetts Institute of Technology](https://www.mit.edu/)**\n - teaches Python in its [introductory course](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/) to computer science independent of the student's major\n - replaced the infamous course on the [Scheme](https://groups.csail.mit.edu/mac/projects/scheme/) language (cf., [source <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_hn.png?raw=1\">](https://news.ycombinator.com/item?id=602307))\n- **[Google](https://www.google.com/)**\n - used the strategy \"Python where we can, C++ where we must\" from its early days on to stay flexible in a rapidly changing environment (cf., [source <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_so.png?raw=1\">](https://stackoverflow.com/questions/2560310/heavy-usage-of-python-at-google))\n - the very first web-crawler was written in Java and so difficult to maintain that it was rewritten in Python right away (cf., [source](https://www.amazon.com/Plex-Google-Thinks-Works-Shapes/dp/1416596585/ref=sr_1_1?ie=UTF8&qid=1539101827&sr=8-1&keywords=in+the+plex))\n - Guido van Rossom was hired by Google from 2005 to 2012 to advance the language there\n- **[NASA](https://www.nasa.gov/)** open-sources many of its projects, often written in Python and regarding analyses with big data (cf., [source](https://code.nasa.gov/language/python/))\n- **[Facebook](https://facebook.com/)** uses Python besides C++ and its legacy PHP (a language for building websites; the \"cool kid\" from the early 2000s)\n- **[Instagram](https://instagram.com/)** operates the largest installation of the popular **web framework [Django](https://www.djangoproject.com/)** (cf., [source](https://instagram-engineering.com/web-service-efficiency-at-instagram-with-python-4976d078e366))\n- **[Spotify](https://spotify.com/)** bases its data science on Python (cf., [source](https://labs.spotify.com/2013/03/20/how-we-use-python-at-spotify/))\n- **[Netflix](https://netflix.com/)** also runs its predictive models on Python (cf., [source](https://medium.com/netflix-techblog/python-at-netflix-86b6028b3b3e))\n- **[Dropbox](https://dropbox.com/)** \"stole\" Guido van Rossom from Google to help scale the platform (cf., [source](https://medium.com/dropbox-makers/guido-van-rossum-on-finding-his-way-e018e8b5f6b1))\n- **[JPMorgan Chase](https://www.jpmorganchase.com/)** requires new employees to learn Python as part of the onboarding process starting with the 2018 intake (cf., [source](https://www.ft.com/content/4c17d6ce-c8b2-11e8-ba8f-ee390057b8c9?segmentId=a7371401-027d-d8bf-8a7f-2a746e767d56))", "_____no_output_____" ], [ "As images tell more than words, here are two plots of popular languages' \"market shares\" based on the number of questions asked on [Stack Overflow <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_so.png?raw=1\">](https://stackoverflow.blog/2017/09/06/incredible-growth-python/), the most relevant platform for answering programming-related questions: As of late 2017, Python surpassed [Java](https://www.java.com/en/), heavily used in big corporates, and [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript), the \"language of the internet\" that does everything in web browsers, in popularity. Two blog posts from \"technical\" people explain this in more depth to the layman: [Stack Overflow <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_so.png?raw=1\">](https://stackoverflow.blog/2017/09/14/python-growing-quickly/) and [DataCamp](https://www.datacamp.com/community/blog/python-scientific-computing-case).", "_____no_output_____" ], [ "<img src=\"https://github.com/jads-nl/intro-to-python/blob/develop/00_intro/static/growth_of_major_programming_languages.png?raw=1\" width=\"50%\">", "_____no_output_____" ], [ "As the graph below shows, neither Google's very own language **[Go](https://golang.org/)** nor **[R](https://www.r-project.org/)**, a domain-specific language in the niche of statistics, can compete with Python's year-to-year growth.", "_____no_output_____" ], [ "<img src=\"https://github.com/jads-nl/intro-to-python/blob/develop/00_intro/static/growth_of_smaller_programming_languages.png?raw=1\" width=\"50%\">", "_____no_output_____" ], [ "[IEEE Sprectrum](https://spectrum.ieee.org/computing/software/the-top-programming-languages-2019) provides a more recent comparison of programming language's popularity. Even news and media outlets notice the recent popularity of Python: [Economist](https://www.economist.com/graphic-detail/2018/07/26/python-is-becoming-the-worlds-most-popular-coding-language), [Huffington Post](https://www.huffingtonpost.com/entry/why-python-is-the-best-programming-language-with-which_us_59ef8f62e4b04809c05011b9), [TechRepublic](https://www.techrepublic.com/article/why-python-is-so-popular-with-developers-3-reasons-the-language-has-exploded/), and [QZ](https://qz.com/1408660/the-rise-of-python-as-seen-through-a-decade-of-stack-overflow/).", "_____no_output_____" ], [ "## How to learn Programming", "_____no_output_____" ], [ "### ABC Rule", "_____no_output_____" ], [ "**A**lways **b**e **c**oding.\n\nProgramming is more than just writing code into a text file. It means reading through parts of the [documentation <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_py.png?raw=1\">](https://docs.python.org/), blogs with best practices, and tutorials, or researching problems on [Stack Overflow <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_so.png?raw=1\">](https://stackoverflow.com/) while trying to implement features in the application at hand. Also, it means using command-line tools to automate some part of the work or manage different versions of a program, for example, with **[git](https://git-scm.com/)**. In short, programming involves a lot of \"muscle memory,\" which can only be built and kept up through near-daily usage.\n\nFurther, many aspects of software architecture and best practices can only be understood after having implemented some requirements for the very first time. Coding also means \"breaking\" things to find out what makes them work in the first place.\n\nTherefore, coding is learned best by just doing it for some time on a daily or at least a regular basis and not right before some task is due, just like learning a \"real\" language.", "_____no_output_____" ], [ "### The Maker's Schedule", "_____no_output_____" ], [ "[Y Combinator <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_hn.png?raw=1\">](https://www.ycombinator.com/) co-founder [Paul Graham <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_wiki.png?raw=1\">](https://en.wikipedia.org/wiki/Paul_Graham_%28programmer%29) wrote a very popular and often cited [article](http://www.paulgraham.com/makersschedule.html) where he divides every person into belonging to one of two groups:\n\n- **Managers**: People that need to organize things and command others (e.g., a \"boss\" or manager). Their schedule is usually organized by the hour or even 30-minute intervals.\n- **Makers**: People that create things (e.g., programmers, artists, or writers). Such people think in half days or full days.\n\nHave you ever wondered why so many tech people work during nights and sleep at \"weird\" times? The reason is that many programming-related tasks require a \"flow\" state in one's mind that is hard to achieve when one can get interrupted, even if it is only for one short question. Graham describes that only knowing that one has an appointment in three hours can cause a programmer to not get into a flow state.\n\nAs a result, do not set aside a certain amount of time for learning something but rather plan in an *entire evening* or a *rainy Sunday* where you can work on a problem in an *open end* setting. And do not be surprised anymore to hear \"I looked at it over the weekend\" from a programmer.", "_____no_output_____" ], [ "### Phase Iteration", "_____no_output_____" ], [ "When being asked the above question, most programmers answer something that can be classified into one of two broader groups.\n\n**1) Toy Problem, Case Study, or Prototype**: Pick some problem, break it down into smaller sub-problems, and solve them with an end in mind.\n\n**2) Books, Video Tutorials, and Courses**: Research the best book, blog, video, or tutorial for something and work it through from start to end.\n\nThe truth is that you need to iterate between these two phases.\n\nBuilding a prototype always reveals issues no book or tutorial can think of before. Data is never as clean as it should be. An algorithm from a textbook must be adapted to a peculiar aspect of a case study. It is essential to learn to \"ship a product\" because only then will one have looked at all the aspects.\n\nThe major downside of this approach is that one likely learns bad \"patterns\" overfitted to the case at hand, and one does not get the big picture or mental concepts behind a solution. This gap can be filled in by well-written books: For example, check the Python/programming books offered by [Packt](https://www.packtpub.com/packt/offers/free-learning/) or [O’Reilly](https://www.oreilly.com/).", "_____no_output_____" ], [ "## Contents", "_____no_output_____" ], [ "**Part A: Expressing Logic**\n\n- What is a programming language? What kind of words exist?\n - *Chapter 1*: [Elements of a Program <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/01_elements/00_content.ipynb)\n - *Chapter 2*: [Functions & Modularization <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/02_functions/00_content.ipynb)\n- What is the flow of execution? How can we form sentences from words?\n - *Chapter 3*: [Conditionals & Exceptions <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/03_conditionals/00_content.ipynb)\n - *Chapter 4*: [Recursion & Looping <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/04_iteration/00_content.ipynb)", "_____no_output_____" ], [ "**Part B: Managing Data and Memory**\n\n- How is data stored in memory?\n - *Chapter 5*: [Numbers & Bits <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/05_numbers/00_content.ipynb)\n - *Chapter 6*: [Text & Bytes <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/06_text/00_content.ipynb)\n - *Chapter 7*: [Sequential Data <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/07_sequences/00_content.ipynb)\n - *Chapter 8*: [Map, Filter, & Reduce <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/08_mfr/00_content.ipynb)\n - *Chapter 9*: [Mappings & Sets <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/09_mappings/00_content.ipynb)\n - *Chapter 10*: Arrays & Dataframes\n- How can we create custom data types?\n - *Chapter 11*: [Classes & Instances <img height=\"12\" style=\"display: inline-block\" src=\"https://github.com/jads-nl/intro-to-python/blob/develop/static/link/to_nb.png?raw=1\">](https://nbviewer.jupyter.org/github/webartifex/intro-to-python/blob/develop/11_classes/00_content.ipynb)", "_____no_output_____" ], [ "## xkcd Comic", "_____no_output_____" ], [ "As with every good book, there has to be a [xkcd](https://xkcd.com/353/) comic somewhere.", "_____no_output_____" ] ], [ [ "import antigravity", "_____no_output_____" ] ], [ [ "<img src=\"https://github.com/jads-nl/intro-to-python/blob/develop/00_intro/static/xkcd.png?raw=1\" width=\"30%\">", "_____no_output_____" ] ] ]
[ "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" ], [ "code", "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" ], [ "code" ], [ "markdown" ] ]
4aedf2c49f5e6eaee36579ea3c6fcdbd88efee2d
25,422
ipynb
Jupyter Notebook
Class1/07_Hough_Transform_Code/Hough_transform_code.ipynb
vvchenvv/Self_Driving_Tutorial
649fddeb1371aa2a02ed49e5dbb8204119b0a3c1
[ "MIT" ]
7
2018-12-27T11:06:21.000Z
2021-09-16T03:07:20.000Z
Class1/07_Hough_Transform_Code/Hough_transform_code.ipynb
vvchenvv/Self_Driving_Tutorial
649fddeb1371aa2a02ed49e5dbb8204119b0a3c1
[ "MIT" ]
null
null
null
Class1/07_Hough_Transform_Code/Hough_transform_code.ipynb
vvchenvv/Self_Driving_Tutorial
649fddeb1371aa2a02ed49e5dbb8204119b0a3c1
[ "MIT" ]
8
2019-02-22T22:20:56.000Z
2021-12-16T06:04:45.000Z
115.554545
10,952
0.848084
[ [ [ "import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nfrom numpy import array\n\n\norigin_image=mpimg.imread(\"canny-edge-detection-test.jpg\")\nplt.figure()\n# plt.subplot(1,3,1)\n# plt.imshow(image)\n\nimage=array(origin_image)\nysize = image.shape[0]\nxsize = image.shape[1]\nleft_bottom = [10,540]\nright_bottom = [900,540]\napex = [480, 280]\n# Fit lines (y=Ax+B) to identify the 3 sided region of interest\n# np.polyfit() returns the coefficients [A, B] of the fit\nfit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)\nfit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)\nfit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)\n\n# Find the region inside the lines\nXX, YY = np.meshgrid(np.arange(0, xsize), np.arange(0, ysize))\nregion_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) & \\\n (YY > (XX*fit_right[0] + fit_right[1])) & \\\n (YY < (XX*fit_bottom[0] + fit_bottom[1]))\n\ngray_image=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\n# plt.subplot(1,3,2)\n# plt.imshow(gray_image)\n\n# Define a kernel size and apply Gaussian smoothing\nkernel_size = 5\nblur_gray = cv2.GaussianBlur(gray_image,(kernel_size, kernel_size),0)\n\n# Define our parameters for Canny and apply\nlow_threshold = 50\nhigh_threshold = 150\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\n\nedges[~region_thresholds] = False\n# plt.subplot(1,3,3)\n# plt.imshow(edges)\n\n\n\n# Define the Hough transform parameters\n# Make a blank the same size as our image to draw on\nrho = 1\ntheta = np.pi/180\nthreshold = 15\nmin_line_length = 40\nmax_line_gap = 20\nline_image = np.copy(image)*0 #creating a blank to draw lines on\n\n# Run Hough on edge detected image\nlines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]),\n min_line_length, max_line_gap)\n\n# Iterate over the output \"lines\" and draw lines on the blank\nfor line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)\n\n# Create a \"color\" binary image to combine with line image\ncolor_edges = np.dstack((edges, edges, edges)) \n\n# Draw the lines on the edge image\ncombo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0) \nplt.imshow(combo)", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\n\n\n# Read in and grayscale the image\n# Note: in the previous example we were reading a .jpg \n# Here we read a .png and convert to 0,255 bytescale\nimage = mpimg.imread(\"canny-edge-detection-test.jpg\")\ngray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\n\n# Define a kernel size and apply Gaussian smoothing\nkernel_size = 5\nblur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)\n\n# Define our parameters for Canny and apply\nlow_threshold = 50\nhigh_threshold = 150\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\n\n# Next we'll create a masked edges image using cv2.fillPoly()\nmask = np.zeros_like(edges) \nignore_mask_color = 255 \n\n# This time we are defining a four sided polygon to mask\nimshape = image.shape\nvertices = np.array([[(0,imshape[0]),(450, 290), (490, 290), (imshape[1],imshape[0])]], dtype=np.int32)\n#在全0的图像上,在指定区域内填入了255\ncv2.fillPoly(mask, vertices, ignore_mask_color)\n#将原始图像与上面填充的图像进行按位与,感兴趣区域外的点会被置为0,感兴趣区域内的点的边沿点原本就是255,按位与之后还是255,其余点均为0\nmasked_edges = cv2.bitwise_and(edges, mask)\n\n\n#可以试试自行调整以下参数,看看都有什么神奇的效果\n# Define the Hough transform parameters\n# Make a blank the same size as our image to draw on\nrho = 1 # distance resolution in pixels of the Hough grid\ntheta = np.pi/180 # angular resolution in radians of the Hough grid\nthreshold = 15 # minimum number of votes (intersections in Hough grid cell)\nmin_line_length = 40 #minimum number of pixels making up a line\nmax_line_gap = 20 # maximum gap in pixels between connectable line segments\nline_image = np.copy(image)*0 # creating a blank to draw lines on\n\n# Run Hough on edge detected image\n# Output \"lines\" is an array containing endpoints of detected line segments\nlines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),\n min_line_length, max_line_gap)\n\n\n#由于输出的只是“线条的端点集合”,所以我们要将这些点连起来,才能最终呈现我们想要的线条\n# Iterate over the output \"lines\" and draw lines on a blank image\nfor line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)\n\n# Create a \"color\" binary image to combine with line image\n#由于edges获得的只是2D的数组,每个点上的元素为一个数字,而真正的图像是每个点为[R,G,B]的数组,要想将edge图像与cv2.line输出的图像结合,需要将其转换为真正的图像,这就用到了dstack,感兴趣的同学可自行百度\ncolor_edges = np.dstack((edges, edges, edges)) \n\n# Draw the lines on the edge image\nlines_edges = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0) \nplt.imshow(lines_edges)\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4aedf2d0d6b0724360ad6d3a1dd196b95828f1c1
756,624
ipynb
Jupyter Notebook
notebooks/source/bayesian_regression.ipynb
amalvaidya/numpyro
eb3907adb47d3df85da15a58bf30393e48922ee3
[ "Apache-2.0" ]
1,394
2019-03-19T16:28:45.000Z
2022-03-31T18:03:26.000Z
notebooks/source/bayesian_regression.ipynb
omarfsosa/numpyro
28fca48864756080016f98b871c8b094908781f0
[ "Apache-2.0" ]
964
2019-03-21T05:02:01.000Z
2022-03-31T18:27:31.000Z
notebooks/source/bayesian_regression.ipynb
omarfsosa/numpyro
28fca48864756080016f98b871c8b094908781f0
[ "Apache-2.0" ]
163
2019-03-20T17:23:15.000Z
2022-03-31T13:39:29.000Z
309.837838
219,984
0.907062
[ [ [ "# Bayesian Regression Using NumPyro\n\nIn this tutorial, we will explore how to do bayesian regression in NumPyro, using a simple example adapted from Statistical Rethinking [[1](#References)]. In particular, we would like to explore the following:\n\n - Write a simple model using the `sample` NumPyro primitive.\n - Run inference using MCMC in NumPyro, in particular, using the No U-Turn Sampler (NUTS) to get a posterior distribution over our regression parameters of interest.\n - Learn about inference utilities such as `Predictive` and `log_likelihood`.\n - Learn how we can use effect-handlers in NumPyro to generate execution traces from the model, condition on sample statements, seed models with RNG seeds, etc., and use this to implement various utilities that will be useful for MCMC. e.g. computing model log likelihood, generating empirical distribution over the posterior predictive, etc.\n\n## Tutorial Outline:\n\n1. [Dataset](#Dataset)\n2. [Regression Model to Predict Divorce Rate](#Regression-Model-to-Predict-Divorce-Rate)\n - [Model-1: Predictor-Marriage Rate](#Model-1:-Predictor---Marriage-Rate)\n - [Posterior Distribution over the Regression Parameters](#Posterior-Distribution-over-the-Regression-Parameters)\n - [Posterior Predictive Distribution](#Posterior-Predictive-Distribution)\n - [Predictive Utility With Effect Handlers](#Predictive-Utility-With-Effect-Handlers)\n - [Model Predictive Density](#Model-Predictive-Density)\n - [Model-2: Predictor-Median Age of Marriage](#Model-2:-Predictor---Median-Age-of-Marriage)\n - [Model-3: Predictor-Marriage Rate and Median Age of Marriage](#Model-3:-Predictor---Marriage-Rate-and-Median-Age-of-Marriage)\n - [Divorce Rate Residuals by State](#Divorce-Rate-Residuals-by-State)\n3. [Regression Model with Measurement Error](#Regression-Model-with-Measurement-Error)\n - [Effect of Incorporating Measurement Noise on Residuals](#Effect-of-Incorporating-Measurement-Noise-on-Residuals)\n4. [References](#References)", "_____no_output_____" ] ], [ [ "!pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro", "_____no_output_____" ], [ "import os\n\nfrom IPython.display import set_matplotlib_formats\nimport jax.numpy as jnp\nfrom jax import random, vmap\nfrom jax.scipy.special import logsumexp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nimport numpyro\nfrom numpyro.diagnostics import hpdi\nimport numpyro.distributions as dist\nfrom numpyro import handlers\nfrom numpyro.infer import MCMC, NUTS\n\nplt.style.use(\"bmh\")\nif \"NUMPYRO_SPHINXBUILD\" in os.environ:\n set_matplotlib_formats(\"svg\")\n\nassert numpyro.__version__.startswith(\"0.8.0\")", "_____no_output_____" ] ], [ [ "## Dataset\n\nFor this example, we will use the `WaffleDivorce` dataset from Chapter 05, Statistical Rethinking [[1](#References)]. The dataset contains divorce rates in each of the 50 states in the USA, along with predictors such as population, median age of marriage, whether it is a Southern state and, curiously, number of Waffle Houses.", "_____no_output_____" ] ], [ [ "DATASET_URL = \"https://raw.githubusercontent.com/rmcelreath/rethinking/master/data/WaffleDivorce.csv\"\ndset = pd.read_csv(DATASET_URL, sep=\";\")\ndset", "_____no_output_____" ] ], [ [ "Let us plot the pair-wise relationship amongst the main variables in the dataset, using `seaborn.pairplot`. ", "_____no_output_____" ] ], [ [ "vars = [\n \"Population\",\n \"MedianAgeMarriage\",\n \"Marriage\",\n \"WaffleHouses\",\n \"South\",\n \"Divorce\",\n]\nsns.pairplot(dset, x_vars=vars, y_vars=vars, palette=\"husl\");", "_____no_output_____" ] ], [ [ "From the plots above, we can clearly observe that there is a relationship between divorce rates and marriage rates in a state (as might be expected), and also between divorce rates and median age of marriage. \n\nThere is also a weak relationship between number of Waffle Houses and divorce rates, which is not obvious from the plot above, but will be clearer if we regress `Divorce` against `WaffleHouse` and plot the results. ", "_____no_output_____" ] ], [ [ "sns.regplot(x=\"WaffleHouses\", y=\"Divorce\", data=dset);", "_____no_output_____" ] ], [ [ "This is an example of a spurious association. We do not expect the number of Waffle Houses in a state to affect the divorce rate, but it is likely correlated with other factors that have an effect on the divorce rate. We will not delve into this spurious association in this tutorial, but the interested reader is encouraged to read Chapters 5 and 6 of [[1](#References)] which explores the problem of causal association in the presence of multiple predictors. \n\nFor simplicity, we will primarily focus on marriage rate and the median age of marriage as our predictors for divorce rate throughout the remaining tutorial.", "_____no_output_____" ], [ "## Regression Model to Predict Divorce Rate\n\nLet us now write a regressionn model in *NumPyro* to predict the divorce rate as a linear function of marriage rate and median age of marriage in each of the states. \n\nFirst, note that our predictor variables have somewhat different scales. It is a good practice to standardize our predictors and response variables to mean `0` and standard deviation `1`, which should result in [faster inference](https://mc-stan.org/docs/2_19/stan-users-guide/standardizing-predictors-and-outputs.html).", "_____no_output_____" ] ], [ [ "standardize = lambda x: (x - x.mean()) / x.std()\n\ndset[\"AgeScaled\"] = dset.MedianAgeMarriage.pipe(standardize)\ndset[\"MarriageScaled\"] = dset.Marriage.pipe(standardize)\ndset[\"DivorceScaled\"] = dset.Divorce.pipe(standardize)", "_____no_output_____" ] ], [ [ "We write the NumPyro model as follows. While the code should largely be self-explanatory, take note of the following:\n\n - In NumPyro, *model* code is any Python callable which can optionally accept additional arguments and keywords. For HMC which we will be using for this tutorial, these arguments and keywords remain static during inference, but we can reuse the same model to generate [predictions](#Posterior-Predictive-Distribution) on new data.\n - In addition to regular Python statements, the model code also contains primitives like `sample`. These primitives can be interpreted with various side-effects using effect handlers. For more on effect handlers, refer to [[3](#References)], [[4](#References)]. For now, just remember that a `sample` statement makes this a stochastic function that samples some latent parameters from a *prior distribution*. Our goal is to infer the *posterior distribution* of these parameters conditioned on observed data.\n - The reason why we have kept our predictors as optional keyword arguments is to be able to reuse the same model as we vary the set of predictors. Likewise, the reason why the response variable is optional is that we would like to reuse this model to sample from the posterior predictive distribution. See the [section](#Posterior-Predictive-Distribution) on plotting the posterior predictive distribution, as an example.", "_____no_output_____" ] ], [ [ "def model(marriage=None, age=None, divorce=None):\n a = numpyro.sample(\"a\", dist.Normal(0.0, 0.2))\n M, A = 0.0, 0.0\n if marriage is not None:\n bM = numpyro.sample(\"bM\", dist.Normal(0.0, 0.5))\n M = bM * marriage\n if age is not None:\n bA = numpyro.sample(\"bA\", dist.Normal(0.0, 0.5))\n A = bA * age\n sigma = numpyro.sample(\"sigma\", dist.Exponential(1.0))\n mu = a + M + A\n numpyro.sample(\"obs\", dist.Normal(mu, sigma), obs=divorce)", "_____no_output_____" ] ], [ [ "### Model 1: Predictor - Marriage Rate\n\nWe first try to model the divorce rate as depending on a single variable, marriage rate. As mentioned above, we can use the same `model` code as earlier, but only pass values for `marriage` and `divorce` keyword arguments. We will use the No U-Turn Sampler (see [[5](#References)] for more details on the NUTS algorithm) to run inference on this simple model.\n\nThe Hamiltonian Monte Carlo (or, the NUTS) implementation in NumPyro takes in a potential energy function. This is the negative log joint density for the model. Therefore, for our model description above, we need to construct a function which given the parameter values returns the potential energy (or negative log joint density). Additionally, the verlet integrator in HMC (or, NUTS) returns sample values simulated using Hamiltonian dynamics in the unconstrained space. As such, continuous variables with bounded support need to be transformed into unconstrained space using bijective transforms. We also need to transform these samples back to their constrained support before returning these values to the user. Thankfully, this is handled on the backend for us, within a convenience class for doing [MCMC inference](https://numpyro.readthedocs.io/en/latest/mcmc.html#numpyro.mcmc.MCMC) that has the following methods:\n\n - `run(...)`: runs warmup, adapts steps size and mass matrix, and does sampling using the sample from the warmup phase.\n - `print_summary()`: print diagnostic information like quantiles, effective sample size, and the Gelman-Rubin diagnostic.\n - `get_samples()`: gets samples from the posterior distribution.\n\nNote the following:\n\n - JAX uses functional PRNGs. Unlike other languages / frameworks which maintain a global random state, in JAX, every call to a sampler requires an [explicit PRNGKey](https://github.com/google/jax#random-numbers-are-different). We will split our initial random seed for subsequent operations, so that we do not accidentally reuse the same seed.\n - We run inference with the `NUTS` sampler. To run vanilla HMC, we can instead use the [HMC](https://numpyro.readthedocs.io/en/latest/mcmc.html#numpyro.mcmc.HMC) class.", "_____no_output_____" ] ], [ [ "# Start from this source of randomness. We will split keys for subsequent operations.\nrng_key = random.PRNGKey(0)\nrng_key, rng_key_ = random.split(rng_key)\n\n# Run NUTS.\nkernel = NUTS(model)\nnum_samples = 2000\nmcmc = MCMC(kernel, num_warmup=1000, num_samples=num_samples)\nmcmc.run(\n rng_key_, marriage=dset.MarriageScaled.values, divorce=dset.DivorceScaled.values\n)\nmcmc.print_summary()\nsamples_1 = mcmc.get_samples()", "sample: 100%|██████████| 3000/3000 [00:04<00:00, 748.14it/s, 7 steps of size 7.41e-01. acc. prob=0.92]\n" ] ], [ [ "#### Posterior Distribution over the Regression Parameters\n\nWe notice that the progress bar gives us online statistics on the acceptance probability, step size and number of steps taken per sample while running NUTS. In particular, during warmup, we adapt the step size and mass matrix to achieve a certain target acceptance probability which is 0.8, by default. We were able to successfully adapt our step size to achieve this target in the warmup phase.\n\nDuring warmup, the aim is to adapt hyper-parameters such as step size and mass matrix (the HMC algorithm is very sensitive to these hyper-parameters), and to reach the typical set (see [[6](#References)] for more details). If there are any issues in the model specification, the first signal to notice would be low acceptance probabilities or very high number of steps. We use the sample from the end of the warmup phase to seed the MCMC chain (denoted by the second `sample` progress bar) from which we generate the desired number of samples from our target distribution.\n\nAt the end of inference, NumPyro prints the mean, std and 90% CI values for each of the latent parameters. Note that since we standardized our predictors and response variable, we would expect the intercept to have mean 0, as can be seen here. It also prints other convergence diagnostics on the latent parameters in the model, including [effective sample size](https://numpyro.readthedocs.io/en/latest/diagnostics.html#numpyro.diagnostics.effective_sample_size) and the [gelman rubin diagnostic](https://numpyro.readthedocs.io/en/latest/diagnostics.html#numpyro.diagnostics.gelman_rubin) ($\\hat{R}$). The value for these diagnostics indicates that the chain has converged to the target distribution. In our case, the \"target distribution\" is the posterior distribution over the latent parameters that we are interested in. Note that this is often worth verifying with multiple chains for more complicated models. In the end, `samples_1` is a collection (in our case, a `dict` since `init_samples` was a `dict`) containing samples from the posterior distribution for each of the latent parameters in the model.\n\nTo look at our regression fit, let us plot the regression line using our posterior estimates for the regression parameters, along with the 90% Credibility Interval (CI). Note that the [hpdi](https://numpyro.readthedocs.io/en/latest/diagnostics.html#numpyro.diagnostics.hpdi) function in NumPyro's diagnostics module can be used to compute CI. In the functions below, note that the collected samples from the posterior are all along the leading axis.", "_____no_output_____" ] ], [ [ "def plot_regression(x, y_mean, y_hpdi):\n # Sort values for plotting by x axis\n idx = jnp.argsort(x)\n marriage = x[idx]\n mean = y_mean[idx]\n hpdi = y_hpdi[:, idx]\n divorce = dset.DivorceScaled.values[idx]\n\n # Plot\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6))\n ax.plot(marriage, mean)\n ax.plot(marriage, divorce, \"o\")\n ax.fill_between(marriage, hpdi[0], hpdi[1], alpha=0.3, interpolate=True)\n return ax\n\n\n# Compute empirical posterior distribution over mu\nposterior_mu = (\n jnp.expand_dims(samples_1[\"a\"], -1)\n + jnp.expand_dims(samples_1[\"bM\"], -1) * dset.MarriageScaled.values\n)\n\nmean_mu = jnp.mean(posterior_mu, axis=0)\nhpdi_mu = hpdi(posterior_mu, 0.9)\nax = plot_regression(dset.MarriageScaled.values, mean_mu, hpdi_mu)\nax.set(\n xlabel=\"Marriage rate\", ylabel=\"Divorce rate\", title=\"Regression line with 90% CI\"\n);", "_____no_output_____" ] ], [ [ "We can see from the plot, that the CI broadens towards the tails where the data is relatively sparse, as can be expected.\n\n#### Prior Predictive Distribution\n\nLet us check that we have set sensible priors by sampling from the prior predictive distribution. NumPyro provides a handy [Predictive](http://num.pyro.ai/en/latest/utilities.html#numpyro.infer.util.Predictive) utility for this purpose.", "_____no_output_____" ] ], [ [ "from numpyro.infer import Predictive\n\nrng_key, rng_key_ = random.split(rng_key)\nprior_predictive = Predictive(model, num_samples=100)\nprior_predictions = prior_predictive(rng_key_, marriage=dset.MarriageScaled.values)[\n \"obs\"\n]\nmean_prior_pred = jnp.mean(prior_predictions, axis=0)\nhpdi_prior_pred = hpdi(prior_predictions, 0.9)\n\nax = plot_regression(dset.MarriageScaled.values, mean_prior_pred, hpdi_prior_pred)\nax.set(xlabel=\"Marriage rate\", ylabel=\"Divorce rate\", title=\"Predictions with 90% CI\");", "_____no_output_____" ] ], [ [ "#### Posterior Predictive Distribution\n\nLet us now look at the posterior predictive distribution to see how our predictive distribution looks with respect to the observed divorce rates. To get samples from the posterior predictive distribution, we need to run the model by substituting the latent parameters with samples from the posterior. Note that by default we generate a single prediction for each sample from the joint posterior distribution, but this can be controlled using the `num_samples` argument.", "_____no_output_____" ] ], [ [ "rng_key, rng_key_ = random.split(rng_key)\npredictive = Predictive(model, samples_1)\npredictions = predictive(rng_key_, marriage=dset.MarriageScaled.values)[\"obs\"]\ndf = dset.filter([\"Location\"])\ndf[\"Mean Predictions\"] = jnp.mean(predictions, axis=0)\ndf.head()", "_____no_output_____" ] ], [ [ "#### Predictive Utility With Effect Handlers\n\nTo remove the magic behind `Predictive`, let us see how we can combine [effect handlers](https://numpyro.readthedocs.io/en/latest/handlers.html) with the [vmap](https://github.com/google/jax#auto-vectorization-with-vmap) JAX primitive to implement our own simplified predictive utility function that can do vectorized predictions.", "_____no_output_____" ] ], [ [ "def predict(rng_key, post_samples, model, *args, **kwargs):\n model = handlers.seed(handlers.condition(model, post_samples), rng_key)\n model_trace = handlers.trace(model).get_trace(*args, **kwargs)\n return model_trace[\"obs\"][\"value\"]\n\n\n# vectorize predictions via vmap\npredict_fn = vmap(\n lambda rng_key, samples: predict(\n rng_key, samples, model, marriage=dset.MarriageScaled.values\n )\n)", "_____no_output_____" ] ], [ [ "Note the use of the `condition`, `seed` and `trace` effect handlers in the `predict` function.\n\n - The `seed` effect-handler is used to wrap a stochastic function with an initial `PRNGKey` seed. When a sample statement inside the model is called, it uses the existing seed to sample from a distribution but this effect-handler also splits the existing key to ensure that future `sample` calls in the model use the newly split key instead. This is to prevent us from having to explicitly pass in a `PRNGKey` to each `sample` statement in the model.\n - The `condition` effect handler conditions the latent sample sites to certain values. In our case, we are conditioning on values from the posterior distribution returned by MCMC.\n - The `trace` effect handler runs the model and records the execution trace within an `OrderedDict`. This trace object contains execution metadata that is useful for computing quantities such as the log joint density.\n \nIt should be clear now that the `predict` function simply runs the model by substituting the latent parameters with samples from the posterior (generated by the `mcmc` function) to generate predictions. Note the use of JAX's auto-vectorization transform called [vmap](https://github.com/google/jax#auto-vectorization-with-vmap) to vectorize predictions. Note that if we didn't use `vmap`, we would have to use a native for loop which for each sample which is much slower. Each draw from the posterior can be used to get predictions over all the 50 states. When we vectorize this over all the samples from the posterior using `vmap`, we will get a `predictions_1` array of shape `(num_samples, 50)`. We can then compute the mean and 90% CI of these samples to plot the posterior predictive distribution. We note that our mean predictions match those obtained from the `Predictive` utility class.", "_____no_output_____" ] ], [ [ "# Using the same key as we used for Predictive - note that the results are identical.\n\npredictions_1 = predict_fn(random.split(rng_key_, num_samples), samples_1)\n\nmean_pred = jnp.mean(predictions_1, axis=0)\ndf = dset.filter([\"Location\"])\ndf[\"Mean Predictions\"] = mean_pred\ndf.head()", "_____no_output_____" ], [ "hpdi_pred = hpdi(predictions_1, 0.9)\n\nax = plot_regression(dset.MarriageScaled.values, mean_pred, hpdi_pred)\nax.set(xlabel=\"Marriage rate\", ylabel=\"Divorce rate\", title=\"Predictions with 90% CI\");", "_____no_output_____" ] ], [ [ "We have used the same `plot_regression` function as earlier. We notice that our CI for the predictive distribution is much broader as compared to the last plot due to the additional noise introduced by the `sigma` parameter. Most data points lie well within the 90% CI, which indicates a good fit.\n\n#### Posterior Predictive Density\n\nLikewise, making use of effect-handlers and `vmap`, we can also compute the log likelihood for this model given the dataset, and the log posterior predictive density [[6](#References)] which is given by \n$$ log \\prod_{i=1}^{n} \\int p(y_i | \\theta) p_{post}(\\theta) d\\theta \n\\approx \\sum_{i=1}^n log \\frac{\\sum_s p(\\theta^{s})}{S} \\\\\n= \\sum_{i=1}^n (log \\sum_s p(\\theta^{s}) - log(S))\n$$.\n\nHere, $i$ indexes the observed data points $y$ and $s$ indexes the posterior samples over the latent parameters $\\theta$. If the posterior predictive density for a model has a comparatively high value, it indicates that the observed data-points have higher probability under the given model.", "_____no_output_____" ] ], [ [ "def log_likelihood(rng_key, params, model, *args, **kwargs):\n model = handlers.condition(model, params)\n model_trace = handlers.trace(model).get_trace(*args, **kwargs)\n obs_node = model_trace[\"obs\"]\n return obs_node[\"fn\"].log_prob(obs_node[\"value\"])\n\n\ndef log_pred_density(rng_key, params, model, *args, **kwargs):\n n = list(params.values())[0].shape[0]\n log_lk_fn = vmap(\n lambda rng_key, params: log_likelihood(rng_key, params, model, *args, **kwargs)\n )\n log_lk_vals = log_lk_fn(random.split(rng_key, n), params)\n return (logsumexp(log_lk_vals, 0) - jnp.log(n)).sum()", "_____no_output_____" ] ], [ [ "Note that NumPyro provides the [log_likelihood](http://num.pyro.ai/en/latest/utilities.html#log-likelihood) utility function that can be used directly for computing `log likelihood` as in the first function for any general model. In this tutorial, we would like to emphasize that there is nothing magical about such utility functions, and you can roll out your own inference utilities using NumPyro's effect handling stack.", "_____no_output_____" ] ], [ [ "rng_key, rng_key_ = random.split(rng_key)\nprint(\n \"Log posterior predictive density: {}\".format(\n log_pred_density(\n rng_key_,\n samples_1,\n model,\n marriage=dset.MarriageScaled.values,\n divorce=dset.DivorceScaled.values,\n )\n )\n)", "Log posterior predictive density: -66.70008087158203\n" ] ], [ [ "### Model 2: Predictor - Median Age of Marriage\n\nWe will now model the divorce rate as a function of the median age of marriage. The computations are mostly a reproduction of what we did for Model 1. Notice the following:\n\n - Divorce rate is inversely related to the age of marriage. Hence states where the median age of marriage is low will likely have a higher divorce rate.\n - We get a higher log likelihood as compared to Model 2, indicating that median age of marriage is likely a much better predictor of divorce rate. ", "_____no_output_____" ] ], [ [ "rng_key, rng_key_ = random.split(rng_key)\n\nmcmc.run(rng_key_, age=dset.AgeScaled.values, divorce=dset.DivorceScaled.values)\nmcmc.print_summary()\nsamples_2 = mcmc.get_samples()", "sample: 100%|██████████| 3000/3000 [00:04<00:00, 722.23it/s, 7 steps of size 7.58e-01. acc. prob=0.92]\n" ], [ "posterior_mu = (\n jnp.expand_dims(samples_2[\"a\"], -1)\n + jnp.expand_dims(samples_2[\"bA\"], -1) * dset.AgeScaled.values\n)\nmean_mu = jnp.mean(posterior_mu, axis=0)\nhpdi_mu = hpdi(posterior_mu, 0.9)\nax = plot_regression(dset.AgeScaled.values, mean_mu, hpdi_mu)\nax.set(\n xlabel=\"Median marriage age\",\n ylabel=\"Divorce rate\",\n title=\"Regression line with 90% CI\",\n);", "_____no_output_____" ], [ "rng_key, rng_key_ = random.split(rng_key)\npredictions_2 = Predictive(model, samples_2)(rng_key_, age=dset.AgeScaled.values)[\"obs\"]\n\nmean_pred = jnp.mean(predictions_2, axis=0)\nhpdi_pred = hpdi(predictions_2, 0.9)\n\nax = plot_regression(dset.AgeScaled.values, mean_pred, hpdi_pred)\nax.set(xlabel=\"Median Age\", ylabel=\"Divorce rate\", title=\"Predictions with 90% CI\");", "_____no_output_____" ], [ "rng_key, rng_key_ = random.split(rng_key)\nprint(\n \"Log posterior predictive density: {}\".format(\n log_pred_density(\n rng_key_,\n samples_2,\n model,\n age=dset.AgeScaled.values,\n divorce=dset.DivorceScaled.values,\n )\n )\n)", "Log posterior predictive density: -59.251956939697266\n" ] ], [ [ "### Model 3: Predictor - Marriage Rate and Median Age of Marriage\n\nFinally, we will also model divorce rate as depending on both marriage rate as well as the median age of marriage. Note that the model's posterior predictive density is similar to Model 2 which likely indicates that the marginal information from marriage rate in predicting divorce rate is low when the median age of marriage is already known.", "_____no_output_____" ] ], [ [ "rng_key, rng_key_ = random.split(rng_key)\n\nmcmc.run(\n rng_key_,\n marriage=dset.MarriageScaled.values,\n age=dset.AgeScaled.values,\n divorce=dset.DivorceScaled.values,\n)\nmcmc.print_summary()\nsamples_3 = mcmc.get_samples()", "sample: 100%|██████████| 3000/3000 [00:04<00:00, 644.48it/s, 7 steps of size 4.65e-01. acc. prob=0.94]\n" ], [ "rng_key, rng_key_ = random.split(rng_key)\nprint(\n \"Log posterior predictive density: {}\".format(\n log_pred_density(\n rng_key_,\n samples_3,\n model,\n marriage=dset.MarriageScaled.values,\n age=dset.AgeScaled.values,\n divorce=dset.DivorceScaled.values,\n )\n )\n)", "Log posterior predictive density: -59.06374740600586\n" ] ], [ [ "### Divorce Rate Residuals by State\n\nThe regression plots above shows that the observed divorce rates for many states differs considerably from the mean regression line. To dig deeper into how the last model (Model 3) under-predicts or over-predicts for each of the states, we will plot the posterior predictive and residuals (`Observed divorce rate - Predicted divorce rate`) for each of the states.", "_____no_output_____" ] ], [ [ "# Predictions for Model 3.\nrng_key, rng_key_ = random.split(rng_key)\npredictions_3 = Predictive(model, samples_3)(\n rng_key_, marriage=dset.MarriageScaled.values, age=dset.AgeScaled.values\n)[\"obs\"]\ny = jnp.arange(50)\n\n\nfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 16))\npred_mean = jnp.mean(predictions_3, axis=0)\npred_hpdi = hpdi(predictions_3, 0.9)\nresiduals_3 = dset.DivorceScaled.values - predictions_3\nresiduals_mean = jnp.mean(residuals_3, axis=0)\nresiduals_hpdi = hpdi(residuals_3, 0.9)\nidx = jnp.argsort(residuals_mean)\n\n# Plot posterior predictive\nax[0].plot(jnp.zeros(50), y, \"--\")\nax[0].errorbar(\n pred_mean[idx],\n y,\n xerr=pred_hpdi[1, idx] - pred_mean[idx],\n marker=\"o\",\n ms=5,\n mew=4,\n ls=\"none\",\n alpha=0.8,\n)\nax[0].plot(dset.DivorceScaled.values[idx], y, marker=\"o\", ls=\"none\", color=\"gray\")\nax[0].set(\n xlabel=\"Posterior Predictive (red) vs. Actuals (gray)\",\n ylabel=\"State\",\n title=\"Posterior Predictive with 90% CI\",\n)\nax[0].set_yticks(y)\nax[0].set_yticklabels(dset.Loc.values[idx], fontsize=10)\n\n# Plot residuals\nresiduals_3 = dset.DivorceScaled.values - predictions_3\nresiduals_mean = jnp.mean(residuals_3, axis=0)\nresiduals_hpdi = hpdi(residuals_3, 0.9)\nerr = residuals_hpdi[1] - residuals_mean\n\nax[1].plot(jnp.zeros(50), y, \"--\")\nax[1].errorbar(\n residuals_mean[idx], y, xerr=err[idx], marker=\"o\", ms=5, mew=4, ls=\"none\", alpha=0.8\n)\nax[1].set(xlabel=\"Residuals\", ylabel=\"State\", title=\"Residuals with 90% CI\")\nax[1].set_yticks(y)\nax[1].set_yticklabels(dset.Loc.values[idx], fontsize=10);", "_____no_output_____" ] ], [ [ "The plot on the left shows the mean predictions with 90% CI for each of the states using Model 3. The gray markers indicate the actual observed divorce rates. The right plot shows the residuals for each of the states, and both these plots are sorted by the residuals, i.e. at the bottom, we are looking at states where the model predictions are higher than the observed rates, whereas at the top, the reverse is true.\n\nOverall, the model fit seems good because most observed data points like within a 90% CI around the mean predictions. However, notice how the model over-predicts by a large margin for states like Idaho (bottom left), and on the other end under-predicts for states like Maine (top right). This is likely indicative of other factors that we are missing out in our model that affect divorce rate across different states. Even ignoring other socio-political variables, one such factor that we have not yet modeled is the measurement noise given by `Divorce SE` in the dataset. We will explore this in the next section.", "_____no_output_____" ], [ "## Regression Model with Measurement Error\n\nNote that in our previous models, each data point influences the regression line equally. Is this well justified? We will build on the previous model to incorporate measurement error given by `Divorce SE` variable in the dataset. Incorporating measurement noise will be useful in ensuring that observations that have higher confidence (i.e. lower measurement noise) have a greater impact on the regression line. On the other hand, this will also help us better model outliers with high measurement errors. For more details on modeling errors due to measurement noise, refer to Chapter 14 of [[1](#References)].\n\nTo do this, we will reuse Model 3, with the only change that the final observed value has a measurement error given by `divorce_sd` (notice that this has to be standardized since the `divorce` variable itself has been standardized to mean 0 and std 1).", "_____no_output_____" ] ], [ [ "def model_se(marriage, age, divorce_sd, divorce=None):\n a = numpyro.sample(\"a\", dist.Normal(0.0, 0.2))\n bM = numpyro.sample(\"bM\", dist.Normal(0.0, 0.5))\n M = bM * marriage\n bA = numpyro.sample(\"bA\", dist.Normal(0.0, 0.5))\n A = bA * age\n sigma = numpyro.sample(\"sigma\", dist.Exponential(1.0))\n mu = a + M + A\n divorce_rate = numpyro.sample(\"divorce_rate\", dist.Normal(mu, sigma))\n numpyro.sample(\"obs\", dist.Normal(divorce_rate, divorce_sd), obs=divorce)", "_____no_output_____" ], [ "# Standardize\ndset[\"DivorceScaledSD\"] = dset[\"Divorce SE\"] / jnp.std(dset.Divorce.values)", "_____no_output_____" ], [ "rng_key, rng_key_ = random.split(rng_key)\n\nkernel = NUTS(model_se, target_accept_prob=0.9)\nmcmc = MCMC(kernel, num_warmup=1000, num_samples=3000)\nmcmc.run(\n rng_key_,\n marriage=dset.MarriageScaled.values,\n age=dset.AgeScaled.values,\n divorce_sd=dset.DivorceScaledSD.values,\n divorce=dset.DivorceScaled.values,\n)\nmcmc.print_summary()\nsamples_4 = mcmc.get_samples()", "sample: 100%|██████████| 4000/4000 [00:06<00:00, 578.19it/s, 15 steps of size 2.58e-01. acc. prob=0.93]\n" ] ], [ [ "### Effect of Incorporating Measurement Noise on Residuals\n\nNotice that our values for the regression coefficients is very similar to Model 3. However, introducing measurement noise allows us to more closely match our predictive distribution to the observed values. We can see this if we plot the residuals as earlier. ", "_____no_output_____" ] ], [ [ "rng_key, rng_key_ = random.split(rng_key)\npredictions_4 = Predictive(model_se, samples_4)(\n rng_key_,\n marriage=dset.MarriageScaled.values,\n age=dset.AgeScaled.values,\n divorce_sd=dset.DivorceScaledSD.values,\n)[\"obs\"]", "_____no_output_____" ], [ "sd = dset.DivorceScaledSD.values\nresiduals_4 = dset.DivorceScaled.values - predictions_4\nresiduals_mean = jnp.mean(residuals_4, axis=0)\nresiduals_hpdi = hpdi(residuals_4, 0.9)\nerr = residuals_hpdi[1] - residuals_mean\nidx = jnp.argsort(residuals_mean)\ny = jnp.arange(50)\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 16))\n\n\n# Plot Residuals\nax.plot(jnp.zeros(50), y, \"--\")\nax.errorbar(\n residuals_mean[idx], y, xerr=err[idx], marker=\"o\", ms=5, mew=4, ls=\"none\", alpha=0.8\n)\n\n# Plot SD\nax.errorbar(residuals_mean[idx], y, xerr=sd[idx], ls=\"none\", color=\"orange\", alpha=0.9)\n\n# Plot earlier mean residual\nax.plot(\n jnp.mean(dset.DivorceScaled.values - predictions_3, 0)[idx],\n y,\n ls=\"none\",\n marker=\"o\",\n ms=6,\n color=\"black\",\n alpha=0.6,\n)\n\nax.set(xlabel=\"Residuals\", ylabel=\"State\", title=\"Residuals with 90% CI\")\nax.set_yticks(y)\nax.set_yticklabels(dset.Loc.values[idx], fontsize=10)\nax.text(\n -2.8,\n -7,\n \"Residuals (with error-bars) from current model (in red). \"\n \"Black marker \\nshows residuals from the previous model (Model 3). \"\n \"Measurement \\nerror is indicated by orange bar.\",\n);", "_____no_output_____" ] ], [ [ "The plot above shows the residuals for each of the states, along with the measurement noise given by inner error bar. The gray dots are the mean residuals from our earlier Model 3. Notice how having an additional degree of freedom to model the measurement noise has shrunk the residuals. In particular, for Idaho and Maine, our predictions are now much closer to the observed values after incorporating measurement noise in the model.\n\nTo better see how measurement noise affects the movement of the regression line, let us plot the residuals with respect to the measurement noise.", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))\nx = dset.DivorceScaledSD.values\ny1 = jnp.mean(residuals_3, 0)\ny2 = jnp.mean(residuals_4, 0)\nax.plot(x, y1, ls=\"none\", marker=\"o\")\nax.plot(x, y2, ls=\"none\", marker=\"o\")\nfor i, (j, k) in enumerate(zip(y1, y2)):\n ax.plot([x[i], x[i]], [j, k], \"--\", color=\"gray\")\n\nax.set(\n xlabel=\"Measurement Noise\",\n ylabel=\"Residual\",\n title=\"Mean residuals (Model 4: red, Model 3: blue)\",\n);", "_____no_output_____" ] ], [ [ "The plot above shows what has happend in more detail - the regression line itself has moved to ensure a better fit for observations with low measurement noise (left of the plot) where the residuals have shrunk very close to 0. That is to say that data points with low measurement error have a concomitantly higher contribution in determining the regression line. On the other hand, for states with high measurement error (right of the plot), incorporating measurement noise allows us to move our posterior distribution mass closer to the observations resulting in a shrinkage of residuals as well.", "_____no_output_____" ], [ "## References\n\n1. McElreath, R. (2016). Statistical Rethinking: A Bayesian Course with Examples in R and Stan CRC Press.\n2. Stan Development Team. [Stan User's Guide](https://mc-stan.org/docs/2_19/stan-users-guide/index.html)\n3. Goodman, N.D., and StuhlMueller, A. (2014). [The Design and Implementation of Probabilistic Programming Languages](http://dippl.org/)\n4. Pyro Development Team. [Poutine: A Guide to Programming with Effect Handlers in Pyro](http://pyro.ai/examples/effect_handlers.html)\n5. Hoffman, M.D., Gelman, A. (2011). The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo.\n6. Betancourt, M. (2017). A Conceptual Introduction to Hamiltonian Monte Carlo.\n7. JAX Development Team (2018). [Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more](https://github.com/google/jax)\n8. Gelman, A., Hwang, J., and Vehtari A. [Understanding predictive information criteria for Bayesian models](https://arxiv.org/pdf/1307.5928.pdf)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4aedf72bc45bfa1cb52dc81beec31455e1bbe10f
9,630
ipynb
Jupyter Notebook
tutorials/4-reasoning.ipynb
ivanDonadello/logictensornetworks_2
e596d8414f0bf5af51c031eb872a57c55af45035
[ "MIT" ]
null
null
null
tutorials/4-reasoning.ipynb
ivanDonadello/logictensornetworks_2
e596d8414f0bf5af51c031eb872a57c55af45035
[ "MIT" ]
null
null
null
tutorials/4-reasoning.ipynb
ivanDonadello/logictensornetworks_2
e596d8414f0bf5af51c031eb872a57c55af45035
[ "MIT" ]
1
2022-02-25T13:43:36.000Z
2022-02-25T13:43:36.000Z
51.497326
372
0.611838
[ [ [ "# Reasoning in LTN\n\nThis tutorial defines and illustrates reasoning in LTN. It expects basic familiarity with other parts of LTN. \n\n### Logical Consequence in LTN\n\nThe essence of reasoning is to determine if a closed formula $\\phi$ is the logical consequence of a knowledgebase $(\\mathcal{K},\\mathcal{G}_\\theta,\\Theta)$, where $\\mathcal{K}$ denotes the set of rules in the knowledgebase and $\\mathcal{G}_\\theta$ denotes a grounding that depends on some parameters $\\theta \\in \\Theta$.\n\nThe notion of logical consequence is adapted to Real Logic as follows:\n- In classical logic (boolean truth values), a formula $\\phi$ is the logical consequence of a knowledgebase $\\mathcal{K}$ is for every interpretation (or model) that verifies every formula in $\\mathcal{K}$, $\\phi$ is verified;\n- In Real Logic (fuzzy truth values), a formula $\\phi$ is the logical consequence of $(\\mathcal{K},\\mathcal{G}_\\theta,\\Theta)$ if for every grounding $\\mathcal{G}_\\theta$ such that $\\mathrm{SatAgg}_{\\phi'\\in\\mathcal{K}}\\mathcal{G}_{\\theta}(\\phi') \\geq q $, we have $\\mathcal{G}_\\theta(\\phi)\\geq q$, where $q$ is a fixed satisfaction threshold. \n\n\nLogical consequence in Real Logic, by direct application of the definition, requires querying the truth value of $\\phi$ for a potentially infinite set of groundings. \nWe therefore, in practice, consider the following directions:\n1. **Reasoning by brave inference**: one seeks to verify if for all the grounded theories that *maximally satisfy* $\\mathcal{K}$, \n the grounding of $\\phi$ gives a truth value greater than a threshold $q$.\n This often requires to check an infinite number of groundings.\n Instead, one can approximate the search for these grounded theories by running the optimization w.r.t. the knowledgebase satisfiability multiple times and checking these groundings only.\n2. **Reasoning by refutation**: one seeks to find out a counterexample of a grounding that does satisfy the knowledgebase $\\mathcal{K}$ but not the formula $\\phi$ (given the threshold $q$). A directed search for such examples is performed using a different learning objective.\n\nIn this tutorial, we illustrate the second option, **reasoning by refutation**. ", "_____no_output_____" ] ], [ [ "import logictensornetworks as ltn\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "### Example\n\nWe illustrate reasoning on the following toy example:\n$$\n(A \\lor B) \\models_q A \\ ?\n$$ \nwhere $A$ and $B$ are two propositional variables, and $\\frac{1}{2} < q < 1$ is the satisfaction threshold.\n\nWe define $\\mathcal{K}=\\{A \\lor B\\}$ and $\\phi=A$. ", "_____no_output_____" ] ], [ [ "A = ltn.proposition(0.,trainable=True)\nB = ltn.proposition(0.,trainable=True)\n\nOr = ltn.Wrapper_Connective(ltn.fuzzy_ops.Or_ProbSum())\n\ndef axioms():\n return Or(A,B)\n\ndef phi():\n return A", "_____no_output_____" ] ], [ [ "### Reasoning by Refutation\n\nThe goal is to find a grounding that satisfies $\\mathcal{K}$ but does not satisfy $\\phi$. One can perform a directed search for such a counterexample by minimizing $\\mathcal{G}_\\theta(\\phi)$ while imposing a constraint that invalidates results where $\\mathcal{G}_\\theta(\\mathcal{K})<q$.\n\nLet us define $\\mathrm{penalty}(\\mathcal{G}_\\theta,q)=\\begin{cases}\n c \\ \\text{if}\\ \\mathcal{G}_\\theta(\\mathcal{K}) < q,\\\\\n 0 \\ \\text{otherwise},\n\\end{cases}$ where $c>1$ and set the objective:\n$$\n \\mathcal{G}^\\ast = \\mathrm{argmin}_{\\mathcal{G}_\\theta} (\\mathcal{G}_\\theta(\\phi) + \\mathrm{penalty}(\\mathcal{G}_\\theta,q))\n$$\n\nThe penalty $c$ ($>1$) is higher than any potential reduction in $\\mathcal{G}(\\phi)$ ($\\leq 1$). $\\mathcal{G}^\\ast$ should satisfy in priority $\\mathcal{G}^*(\\mathcal{K}) \\geq q$ before reducing $\\mathcal{G}^*(\\phi)$.\n- If $\\mathcal{G}^\\ast(\\mathcal{K}) < q$ : Then for all $\\mathcal{G}_\\theta$, $\\mathcal{G}_\\theta(\\mathcal{K}) < q$ and therefore $(\\mathcal{K},\\mathcal{G}(\\ \\cdot\\mid \\theta), \\Theta)\\models_q\\phi$.\n- If $\\mathcal{G}^\\ast(\\mathcal{K}) \\geq q \\ \\text{and}\\ \\mathcal{G}^\\ast(\\phi) \\geq q$ : Then for all $\\mathcal{G}_\\theta$ with $\\mathcal{G}_\\theta(\\mathcal{K}) \\geq q$, we have that $\\mathcal{G}_\\theta(\\phi) \\geq \\mathcal{G}^\\ast(\\phi) \\geq q$ and therefore $(\\mathcal{K},\\mathcal{G}(\\ \\cdot\\mid\\theta),\\Theta)\\models_q\\phi$. \n- If $\\mathcal{G}^\\ast(\\mathcal{K}) \\geq q \\ \\text{and}\\ \\mathcal{G}^\\ast(\\phi) < q$ : Then $(\\mathcal{K},\\mathcal{G}(\\ \\cdot\\mid\\theta),\\Theta) \\nvDash_q\\phi$.\n\n### Soft constraint\n\nHowever, as $\\mathrm{penalty}(\\mathcal{G}_\\theta,q)$ is a constant function on the continuous parts of its domain (zero gradients), it cannot be used directly as an objective to reach via gradient descent optimization.Instead, one should approximate the penalty with a soft constraint.\n\nWe use $\\mathtt{elu}(\\alpha,\\beta (q-\\mathcal{G}_\\theta(\\mathcal{K})))=\\begin{cases}\n \\beta (q-\\mathcal{G}_\\theta(\\mathcal{K}))\\ &\\text{if}\\ \\mathcal{G}_\\theta(\\mathcal{K}) \\leq 0,\\\\\n \\alpha (e^{q-\\mathcal{G}_\\theta(\\mathcal{K})}-1) \\ &\\text{otherwise},\n\\end{cases}$ where $\\alpha \\geq 0$ and $\\beta \\geq 0$ are two hyper-parameters:\n- When $\\mathcal{G}_\\theta(\\mathcal{K}) < q$, the penalty is linear in $(q-\\mathcal{G}_\\theta(\\mathcal{K}))$ with a slope of $\\beta$. \nSetting $\\beta$ high, the gradients for $\\mathcal{G}_\\theta(\\mathcal{K})$ will be high in absolute value if the knowledgebase in not satisfied; the minimizer will prioritize increasing the satisfaction of the knowledgebase.\n- When $\\mathcal{G}_\\theta(\\mathcal{K}) > q$, the penalty is a negative exponential that converges to $-\\alpha$.\nSetting $\\alpha$ low but non zero ensures that, while the penalty plays an insignificant role when the knowledgebase is satisfied, the gradients do not vanish.", "_____no_output_____" ] ], [ [ "trainable_variables = [A,B]\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.001)\n\n# hyperparameters of the soft constraint\nalpha = 0.05\nbeta = 10\n# satisfaction threshold\nq = 0.95\n\nfor epoch in range(4000):\n with tf.GradientTape() as tape:\n sat_KB = axioms()\n sat_phi = phi()\n penalty = tf.keras.activations.elu(beta*(q-sat_KB),alpha=alpha)\n loss = sat_phi + penalty\n grads = tape.gradient(loss, trainable_variables)\n optimizer.apply_gradients(zip(grads, trainable_variables))\n if epoch%400 == 0:\n print(\"Epoch %d: Sat Level Knowledgebase %.3f Sat Level phi %.3f\"%(epoch, axioms(), phi()))\nprint(\"Training finished at Epoch %d with Sat Level Knowledgebase %.3f Sat Level phi %.3f\"%(epoch, axioms(), phi()))", "Epoch 0: Sat Level Knowledgebase 0.002 Sat Level phi 0.001\nEpoch 400: Sat Level Knowledgebase 0.591 Sat Level phi 0.358\nEpoch 800: Sat Level Knowledgebase 0.862 Sat Level phi 0.610\nEpoch 1200: Sat Level Knowledgebase 0.950 Sat Level phi 0.705\nEpoch 1600: Sat Level Knowledgebase 0.950 Sat Level phi 0.615\nEpoch 2000: Sat Level Knowledgebase 0.951 Sat Level phi 0.485\nEpoch 2400: Sat Level Knowledgebase 0.962 Sat Level phi 0.319\nEpoch 2800: Sat Level Knowledgebase 0.998 Sat Level phi 0.116\nEpoch 3200: Sat Level Knowledgebase 1.000 Sat Level phi 0.000\nEpoch 3600: Sat Level Knowledgebase 1.000 Sat Level phi 0.000\nTraining finished at Epoch 3999 with Sat Level Knowledgebase 1.000 Sat Level phi 0.000\n" ] ], [ [ "At the end of training, the optimizer has found a grounding that satisfies $A \\lor B$ but not $A$ (given the satisfaction threshold $q=0.95$). This is a counterexample to the logical consequence, proving that $A \\lor B \\nvDash A$", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4aee02c3a59ce4e60cc3a4e25cb26c39988a21e2
27,179
ipynb
Jupyter Notebook
docs_src/tutorial.itemlist.ipynb
MartinGer/fastai
5a5de8b3a6c2a4ba04f1e5873083808172a6903a
[ "Apache-2.0" ]
2
2019-02-08T04:59:27.000Z
2020-05-15T21:17:23.000Z
docs_src/tutorial.itemlist.ipynb
MartinGer/fastai
5a5de8b3a6c2a4ba04f1e5873083808172a6903a
[ "Apache-2.0" ]
3
2021-05-20T19:59:09.000Z
2022-02-26T09:11:29.000Z
docs_src/tutorial.itemlist.ipynb
MartinGer/fastai
5a5de8b3a6c2a4ba04f1e5873083808172a6903a
[ "Apache-2.0" ]
1
2020-01-09T15:44:46.000Z
2020-01-09T15:44:46.000Z
45.222962
571
0.622687
[ [ [ "# Customizing datasets in fastai", "_____no_output_____" ] ], [ [ "from fastai import *\nfrom fastai.gen_doc.nbdoc import *\nfrom fastai.vision import *", "_____no_output_____" ] ], [ [ "In this tutorial, we'll see how to create custom subclasses of [`ItemBase`](/core.html#ItemBase) or [`ItemList`](/data_block.html#ItemList) while retaining everything the fastai library has to offer. To allow basic functions to work consistently across various applications, the fastai library delegates several tasks to one of those specific objets, and we'll see here which methods you have to implement to be able to have everything work properly. But first let's see take a step back to see where you'll use your end result.", "_____no_output_____" ], [ "## Links with the data block API", "_____no_output_____" ], [ "The data block API works by allowing you to pick a class that is responsible to get your items and another class that is charged with getting your targets. Combined together, they create a pytorch [`Dataset`](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset) that is then wrapped inside a [`DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader). The training set, validation set and maybe test set are then all put in a [`DataBunch`](/basic_data.html#DataBunch).\n\nThe data block API allows you to mix and match what class your inputs have, what clas you target have, how to do the split between train and validation set, then how to create the [`DataBunch`](/basic_data.html#DataBunch), but if you have a very specific kind of input/target, the fastai classes might no be sufficient to you. This tutorial is there to explain what is needed to create a new class of items and what methods are important to implement or override.\n\nIt goes in two phases: first we focus on what you need to create a custom [`ItemBase`](/core.html#ItemBase) class (which the type of your inputs/targets) then on how to create your custom [`ItemList`](/data_block.html#ItemList) (which is basically a set of [`ItemBase`](/core.html#ItemBase)) while highlining which methods are called by the library.", "_____no_output_____" ], [ "## Creating a custom [`ItemBase`](/core.html#ItemBase) subclass", "_____no_output_____" ], [ "The fastai library contains three basic type of [`ItemBase`](/core.html#ItemBase) that you might want to subclass:\n- [`Image`](/vision.image.html#Image) for vision applications\n- [`Text`](/text.data.html#Text) for text applications\n- [`TabularLine`](/tabular.data.html#TabularLine) for tabular applications\n\nWhether you decide to create your own item class or to subclass one of the above, here is what you need to implement:", "_____no_output_____" ], [ "### Basic attributes", "_____no_output_____" ], [ "Those are the more importants attribute your custom [`ItemBase`](/core.html#ItemBase) needs as they're used everywhere in the fastai library:\n- `ItemBase.data` is the thing that is passed to pytorch when you want to create a [`DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader). This is what needs to be fed to your model. Note that it might be different from the representation of your item since you might want something that is more understandable.\n- `ItemBase.obj` is the thing that truly represents the underlying object behind your item. It should be sufficient to create a copy of your item. For instance, when creating the test set, the basic label is the `obj` attribute of the first label (or y) in the training set.\n- `__str__` representation: if applicable, this is what will be displayed when the fastai library has to show your item.\n\nIf we take the example of a [`MultiCategory`](/core.html#MultiCategory) object `o` for instance:\n- `o.obj` is the list of tags that object has\n- `o.data` is a tensor where the tags are one-hot encoded\n- `str(o)` returns the tags separated by ;\n\nIf you want to code the way data augmentation should be applied to your custom `Item`, you should write an `apply_tfms` method. This is what will be called if you apply a [`transform`](/vision.transform.html#vision.transform) block in the data block API.", "_____no_output_____" ], [ "### Advanced show methods", "_____no_output_____" ], [ "If you want to use methods such a `data.show_batch()` or `learn.show_results()` with a brand new kind of [`ItemBase`](/core.html#ItemBase) you will need to implement two other methods. In both cases, the generic function will grab the tensors of inputs, targets and predictions (if applicable), reconstruct the corespoding [`ItemBase`](/core.html#ItemBase) (see below) but it will delegate to the [`ItemBase`](/core.html#ItemBase) the way to display the results.\n\n``` python\ndef show_xys(self, xs, ys, **kwargs)->None:\n\ndef show_xyzs(self, xs, ys, zs, **kwargs)->None:\n```\nIn both cases `xs` and `ys` represent the inputs and the targets, in the second case `zs` represent the predictions. They are lists of the same length that depend on the `rows` argument you passed. The kwargs are passed from `data.show_batch()` / `learn.show_results()`. As an example, here is the source code of those methods in [`Image`](/vision.image.html#Image):\n\n``` python\ndef show_xys(self, xs, ys, figsize:Tuple[int,int]=(9,10), **kwargs):\n \"Show the `xs` and `ys` on a figure of `figsize`. `kwargs` are passed to the show method.\"\n rows = int(math.sqrt(len(xs)))\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten() if rows > 1 else [axs]):\n xs[i].show(ax=ax, y=ys[i], **kwargs)\n plt.tight_layout()\n \ndef show_xyzs(self, xs, ys, zs, figsize:Tuple[int,int]=None, **kwargs):\n \"\"\"Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`. \n `kwargs` are passed to the show method.\"\"\"\n figsize = ifnone(figsize, (6,3*len(xs)))\n fig,axs = plt.subplots(len(xs), 2, figsize=figsize)\n fig.suptitle('Ground truth / Predictions', weight='bold', size=14)\n for i,(x,y,z) in enumerate(zip(xs,ys,zs)):\n x.show(ax=axs[i,0], y=y, **kwargs)\n x.show(ax=axs[i,1], y=z, **kwargs)\n``` ", "_____no_output_____" ], [ "### Example: ImageTuple", "_____no_output_____" ], [ "For cycleGANs, we need to create a custom type of items since we feed the model tuples of images. Let's look at how to code this. The basis is to code the `obj` and [`data`](/vision.data.html#vision.data) attributes. We do that in the init. The object is the tuple of images and the data their underlying tensors normalized between -1 and 1.", "_____no_output_____" ] ], [ [ "class ImageTuple(ItemBase):\n def __init__(self, img1, img2):\n self.img1,self.img2 = img1,img2\n self.obj,self.data = (img1,img2),[-1+2*img1.data,-1+2*img2.data]", "_____no_output_____" ] ], [ [ "Then we want to apply data augmentation to our tuple of images. That's done by writing and `apply_tfms` method as we saw before. Here we just pass that call to the two underlying images then update the data.", "_____no_output_____" ] ], [ [ " def apply_tfms(self, tfms, **kwargs):\n self.img1 = self.img1.apply_tfms(tfms, **kwargs)\n self.img2 = self.img2.apply_tfms(tfms, **kwargs)\n self.data = [-1+2*self.img1.data,-1+2*self.img2.data]\n return self", "_____no_output_____" ] ], [ [ "We define a last method to stack the two images next ot each other, which we will use later for a customized `show_batch`/ `show_results` behavior.", "_____no_output_____" ] ], [ [ " def to_one(self): return Image(0.5+torch.cat(self.data,2)/2)", "_____no_output_____" ] ], [ [ "This is all your need to create your custom [`ItemBase`](/core.html#ItemBase). You won't be able to use it until you have put it inside your custom [`ItemList`](/data_block.html#ItemList) though, so you should continue reading the next section.", "_____no_output_____" ], [ "## Creating a custom [`ItemList`](/data_block.html#ItemList) subclass", "_____no_output_____" ], [ "This is the main class that allows you to group your inputs or your targets in the data block API. You can then use any of the splitting or labelling methods before creating a [`DataBunch`](/basic_data.html#DataBunch). To make sure everything is properly working, her eis what you need to know.", "_____no_output_____" ], [ "### Class variables", "_____no_output_____" ], [ "Whether you're directly subclassing [`ItemList`](/data_block.html#ItemList) or one of the particular fastai ones, make sure to know the content of the following three variables as you may need to adjust them:\n- `_bunch` contains the name of the class that will be used to create a [`DataBunch`](/basic_data.html#DataBunch) \n- `_processor` contains a class (or a list of classes) of [`PreProcessor`](/data_block.html#PreProcessor) that will then be used as the default to create processor for this [`ItemList`](/data_block.html#ItemList)\n- `_label_cls` contains the class that will be used to create the labels by default\n\n`_label_cls` is the first to be used in the data block API, in the labelling function. If this variable is set to `None`, the label class will be guessed between [`CategoryList`](/data_block.html#CategoryList), [`MultiCategoryList`](/data_block.html#MultiCategoryList) and [`FloatList`](/data_block.html#FloatList) depending on the type of the first item. The default can be overriden by passing a `label_cls` in the kwargs of the labelling function.\n\n`_processor` is the second to be used. The processors are called at the end of the labelling to apply some kind of function on your items. The default processor of the inputs can be overriden by passing a `processor` in the kwargs when creating the [`ItemList`](/data_block.html#ItemList), the default processor of the targets can be overriden by passing a `processor` in the kwargs of the labelling function. \n\nProcessors are useful for pre-processing some data, but you also need to put in their state any variable you want to save for the call of `data.export()` before creating a [`Learner`](/basic_train.html#Learner) object for inference: the state of the [`ItemList`](/data_block.html#ItemList) isn't saved there, only their processors. For instance `SegmentationProcessor` only reason to exist is to save the dataset classes, and during the process call, it doesn't do anything apart from setting the `classes` and `c` attributes to its dataset.\n``` python\nclass SegmentationProcessor(PreProcessor):\n def __init__(self, ds:ItemList): self.classes = ds.classes\n def process(self, ds:ItemList): ds.classes,ds.c = self.classes,len(self.classes)\n```\n\n`_bunch` is the last class variable usd in the data block. When you type the final `databunch()`, the data block API calls the `_bunch.create` method with the `_bunch` of the inputs. ", "_____no_output_____" ], [ "### Keeping \\_\\_init\\_\\_ arguments", "_____no_output_____" ], [ "If you pass additional arguments in your `__init__` call that you save in the state of your [`ItemList`](/data_block.html#ItemList), be wary to also pass them along in the `new` method as this one is used to create your training and validation set when splitting. The basic scheme is:\n``` python\nclass MyCustomItemList(ItemList):\n def __init__(self, items, my_arg, **kwargs):\n self.my_arg = my_arg\n super().__init__(items, **kwargs)\n \n def new(self, items, **kwargs):\n return super().new(items, self.my_arg, **kwargs)\n```\nBe sure to keep the kwargs as is, as they contain all the additional stuff you can pass to an [`ItemList`](/data_block.html#ItemList).", "_____no_output_____" ], [ "### Important methods", "_____no_output_____" ], [ "#### - get", "_____no_output_____" ], [ "The most important method you have to implement is `get`: this one will explain your custom [`ItemList`](/data_block.html#ItemList) how to general an [`ItemBase`](/core.html#ItemBase) from the thign stored in its `items` array. For instance an [`ImageItemList`](/vision.data.html#ImageItemList) has the following `get` method:\n``` python\ndef get(self, i):\n fn = super().get(i)\n res = self.open(fn)\n self.sizes[i] = res.size\n return res\n```\nThe first line basically looks at `self.items[i]` (which is a filename). The second line opens it since the `open`method is just\n``` python\ndef open(self, fn): return open_image(fn)\n```\nThe third line is there for [`ImagePoints`](/vision.image.html#ImagePoints) or [`ImageBBox`](/vision.image.html#ImageBBox) targets that require the size of the input [`Image`](/vision.image.html#Image) to be created. Note that if you are building a custom target class and you need the size of an image, you should call `self.x.size[i]`. ", "_____no_output_____" ] ], [ [ "jekyll_note(\"\"\"If you just want to customize the way an `Image` is opened, subclass `Image` and just change the\n`open` method.\"\"\")", "_____no_output_____" ] ], [ [ "#### - reconstruct", "_____no_output_____" ], [ "This is the method that is called in `data.show_batch()`, `learn.predict()` or `learn.show_results()` to transform a pytorch tensor back in an [`ItemBase`](/core.html#ItemBase). In a way, it does the opposite of calling `ItemBase.data`. It should take a tensor `t` and return the same king of thing as the `get` method.\n\nIn some situations ([`ImagePoints`](/vision.image.html#ImagePoints), [`ImageBBox`](/vision.image.html#ImageBBox) for instance) you need to have a look at the corresponding input to rebuild your item. In this case, you should have a second argument called `x` (don't change that name). For instance, here is the `reconstruct` method of [`PointsItemList`](/vision.data.html#PointsItemList):\n```python\ndef reconstruct(self, t, x): return ImagePoints(FlowField(x.size, t), scale=False)\n```", "_____no_output_____" ], [ "#### - analyze_pred", "_____no_output_____" ], [ "This is the method that is called in `learn.predict()` or `learn.show_results()` to transform predictions in an output tensor suitable for `reconstruct`. For instance we may need to take the maximum argument (for [`Category`](/core.html#Category)) or the predictions greater than a certain threshold (for [`MultiCategory`](/core.html#MultiCategory)). It should take a tensor, along with optional kwargs and return a tensor.\n\nFor instance, here is the `anaylze_pred` method of [`MultiCategoryList`](/data_block.html#MultiCategoryList):\n```python\ndef analyze_pred(self, pred, thresh:float=0.5): return (pred >= thresh).float()\n```\n`thresh` can then be passed as kwarg during the calls to `learn.predict()` or `learn.show_results()`.", "_____no_output_____" ], [ "### Advanced show methods", "_____no_output_____" ], [ "If you want to use methods such a `data.show_batch()` or `learn.show_results()` with a brand new kind of [`ItemBase`](/core.html#ItemBase) you will need to implement two other methods. In both cases, the generic function will grab the tensors of inputs, targets and predictions (if applicable), reconstruct the coresponding (as seen before) but it will delegate to the [`ItemList`](/data_block.html#ItemList) the way to display the results.\n\n``` python\ndef show_xys(self, xs, ys, **kwargs)->None:\n\ndef show_xyzs(self, xs, ys, zs, **kwargs)->None:\n```\nIn both cases `xs` and `ys` represent the inputs and the targets, in the second case `zs` represent the predictions. They are lists of the same length that depend on the `rows` argument you passed. The kwargs are passed from `data.show_batch()` / `learn.show_results()`. As an example, here is the source code of those methods in [`ImageItemList`](/vision.data.html#ImageItemList):\n\n``` python\ndef show_xys(self, xs, ys, figsize:Tuple[int,int]=(9,10), **kwargs):\n \"Show the `xs` and `ys` on a figure of `figsize`. `kwargs` are passed to the show method.\"\n rows = int(math.sqrt(len(xs)))\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten() if rows > 1 else [axs]):\n xs[i].show(ax=ax, y=ys[i], **kwargs)\n plt.tight_layout()\n \ndef show_xyzs(self, xs, ys, zs, figsize:Tuple[int,int]=None, **kwargs):\n \"\"\"Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`. \n `kwargs` are passed to the show method.\"\"\"\n figsize = ifnone(figsize, (6,3*len(xs)))\n fig,axs = plt.subplots(len(xs), 2, figsize=figsize)\n fig.suptitle('Ground truth / Predictions', weight='bold', size=14)\n for i,(x,y,z) in enumerate(zip(xs,ys,zs)):\n x.show(ax=axs[i,0], y=y, **kwargs)\n x.show(ax=axs[i,1], y=z, **kwargs)\n``` \n\nLinked to this method is the class variable `_show_square` of an [`ItemList`](/data_block.html#ItemList). It defaults to `False` but if it's `True`, the `show_batch` method will send `rows * rows` `xs` and `ys` to `show_xys` (so that it shows a square of inputs/targets), like here for iamges.", "_____no_output_____" ], [ "### Example: ImageTupleList", "_____no_output_____" ], [ "Continuing our custom item example, we create a custom [`ItemList`](/data_block.html#ItemList) class that will wrap those `ImageTuple` properly. The first thing is to write a custom `__init__` method (since we need to list of filenames here) which means we also have to change the `new` method.", "_____no_output_____" ] ], [ [ "class ImageTupleList(ImageItemList):\n def __init__(self, items, itemsB=None, **kwargs):\n self.itemsB = itemsB\n super().__init__(items, **kwargs)\n \n def new(self, items, **kwargs):\n return super().new(items, itemsB=self.itemsB, **kwargs)", "_____no_output_____" ] ], [ [ "We then specify how to get one item. Here we pass the image in the first list of items, and pick one randomly in the second list.", "_____no_output_____" ] ], [ [ " def get(self, i):\n img1 = super().get(i)\n fn = self.itemsB[random.randint(0, len(self.itemsB)-1)]\n return ImageTuple(img1, open_image(fn))", "_____no_output_____" ] ], [ [ "We also add a custom factory method to directly create an `ImageTupleList` from two folders.", "_____no_output_____" ] ], [ [ " @classmethod\n def from_folders(cls, path, folderA, folderB, **kwargs):\n itemsB = ImageItemList.from_folder(path/folderB).items\n res = super().from_folder(path/folderA, itemsB=itemsB, **kwargs)\n res.path = path\n return res", "_____no_output_____" ] ], [ [ "Finally, we have to specify how to reconstruct the `ImageTuple` from tensors if we want `show_batch` to work. We recreate the images and denormalize.", "_____no_output_____" ] ], [ [ " def reconstruct(self, t:Tensor): \n return ImageTuple(Image(t[0]/2+0.5),Image(t[1]/2+0.5))", "_____no_output_____" ] ], [ [ "There is no need to write a `analyze_preds` method since the default behavior (returning the output tensor) is what we need here. However `show_results` won't work properly unless the target (which we don't really care about here) has the right `reconstruct` method: the fastai library uses the `reconstruct` method of the target on the outputs. That's why we create another custom [`ItemList`](/data_block.html#ItemList) with just that `reconstruct` method. The first line is to reconstruct our dummy targets, and the second one is the same as in `ImageTupleList`.", "_____no_output_____" ] ], [ [ "class TargetTupleList(ItemList):\n def reconstruct(self, t:Tensor): \n if len(t.size()) == 0: return t\n return ImageTuple(Image(t[0]/2+0.5),Image(t[1]/2+0.5))", "_____no_output_____" ] ], [ [ "To make sure our `ImageTupleList` uses that for labelling, we pass it in `_label_cls` and this is what the result looks like.", "_____no_output_____" ] ], [ [ "class ImageTupleList(ImageItemList):\n _label_cls=TargetTupleList\n def __init__(self, items, itemsB=None, **kwargs):\n self.itemsB = itemsB\n super().__init__(items, **kwargs)\n \n def new(self, items, **kwargs):\n return super().new(items, itemsB=self.itemsB, **kwargs)\n \n def get(self, i):\n img1 = super().get(i)\n fn = self.itemsB[random.randint(0, len(self.itemsB)-1)]\n return ImageTuple(img1, open_image(fn))\n \n def reconstruct(self, t:Tensor): \n return ImageTuple(Image(t[0]/2+0.5),Image(t[1]/2+0.5))\n \n @classmethod\n def from_folders(cls, path, folderA, folderB, **kwargs):\n itemsB = ImageItemList.from_folder(path/folderB).items\n res = super().from_folder(path/folderA, itemsB=itemsB, **kwargs)\n res.path = path\n return res", "_____no_output_____" ] ], [ [ "Lastly, we want to customize the behavior of `show_batch` and `show_results`. Remember the `to_one` method just puts the two images next to each other.", "_____no_output_____" ] ], [ [ " def show_xys(self, xs, ys, figsize:Tuple[int,int]=(12,6), **kwargs):\n \"Show the `xs` and `ys` on a figure of `figsize`. `kwargs` are passed to the show method.\"\n rows = int(math.sqrt(len(xs)))\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten() if rows > 1 else [axs]):\n xs[i].to_one().show(ax=ax, **kwargs)\n plt.tight_layout()\n\n def show_xyzs(self, xs, ys, zs, figsize:Tuple[int,int]=None, **kwargs):\n \"\"\"Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`.\n `kwargs` are passed to the show method.\"\"\"\n figsize = ifnone(figsize, (12,3*len(xs)))\n fig,axs = plt.subplots(len(xs), 2, figsize=figsize)\n fig.suptitle('Ground truth / Predictions', weight='bold', size=14)\n for i,(x,z) in enumerate(zip(xs,zs)):\n x.to_one().show(ax=axs[i,0], **kwargs)\n z.to_one().show(ax=axs[i,1], **kwargs)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aee1b7e89429cb12eef8b9c73e6dec449967051
14,463
ipynb
Jupyter Notebook
4 - Creating a Real-time Inferencing Service.ipynb
iuliaferoli/DP100
e534b145f50b80b6816cea9c7913e8d97eb71f1b
[ "MIT" ]
2
2021-01-24T15:18:14.000Z
2021-03-01T19:03:33.000Z
4 - Creating a Real-time Inferencing Service.ipynb
iuliaferoli/DP100
e534b145f50b80b6816cea9c7913e8d97eb71f1b
[ "MIT" ]
null
null
null
4 - Creating a Real-time Inferencing Service.ipynb
iuliaferoli/DP100
e534b145f50b80b6816cea9c7913e8d97eb71f1b
[ "MIT" ]
null
null
null
34.110849
384
0.612183
[ [ [ "# Creating a Real-Time Inferencing Service\n\nYou've spent a lot of time in this course training and registering machine learning models. Now it's time to deploy a model as a real-time service that clients can use to get predictions from new data.\n\n## Connect to Your Workspace\n\nThe first thing you need to do is to connect to your workspace using the Azure ML SDK.\n\n> **Note**: If the authenticated session with your Azure subscription has expired since you completed the previous exercise, you'll be prompted to reauthenticate.", "_____no_output_____" ] ], [ [ "import azureml.core\nfrom azureml.core import Workspace\n\n# Load the workspace from the saved config file\nws = Workspace.from_config()\nprint('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))", "_____no_output_____" ] ], [ [ "## Deploy a Model as a Web Service\n\nYou have trained and registered a machine learning model that classifies patients based on the likelihood of them having diabetes. This model could be used in a production environment such as a doctor's surgery where only patients deemed to be at risk need to be subjected to a clinical test for diabetes. To support this scenario, you will deploy the model as a web service.\n\nFirst, let's determine what models you have registered in the workspace.", "_____no_output_____" ] ], [ [ "from azureml.core import Model\n\nfor model in Model.list(ws):\n print(model.name, 'version:', model.version)\n for tag_name in model.tags:\n tag = model.tags[tag_name]\n print ('\\t',tag_name, ':', tag)\n for prop_name in model.properties:\n prop = model.properties[prop_name]\n print ('\\t',prop_name, ':', prop)\n print('\\n')", "_____no_output_____" ] ], [ [ "Right, now let's get the model that we want to deploy. By default, if we specify a model name, the latest version will be returned.", "_____no_output_____" ] ], [ [ "model = ws.models['diabetes_model']\nprint(model.name, 'version', model.version)", "_____no_output_____" ] ], [ [ "We're going to create a web service to host this model, and this will require some code and configuration files; so let's create a folder for those.", "_____no_output_____" ] ], [ [ "import os\n\nfolder_name = 'diabetes_service'\n\n# Create a folder for the web service files\nexperiment_folder = './' + folder_name\nos.makedirs(folder_name, exist_ok=True)\n\nprint(folder_name, 'folder created.')", "_____no_output_____" ] ], [ [ "The web service where we deploy the model will need some Python code to load the input data, get the model from the workspace, and generate and return predictions. We'll save this code in an *entry script* that will be deployed to the web service:", "_____no_output_____" ] ], [ [ "%%writefile $folder_name/score_diabetes.py\nimport json\nimport joblib\nimport numpy as np\nfrom azureml.core.model import Model\n\n# Called when the service is loaded\ndef init():\n global model\n # Get the path to the deployed model file and load it\n model_path = Model.get_model_path('diabetes_model')\n model = joblib.load(model_path)\n\n# Called when a request is received\ndef run(raw_data):\n # Get the input data as a numpy array\n data = np.array(json.loads(raw_data)['data'])\n # Get a prediction from the model\n predictions = model.predict(data)\n # Get the corresponding classname for each prediction (0 or 1)\n classnames = ['not-diabetic', 'diabetic']\n predicted_classes = []\n for prediction in predictions:\n predicted_classes.append(classnames[prediction])\n # Return the predictions as JSON\n return json.dumps(predicted_classes)", "_____no_output_____" ] ], [ [ "The web service will be hosted in a container, and the container will need to install any required Python dependencies when it gets initialized. In this case, our scoring code requires **scikit-learn**, so we'll create a .yml file that tells the container host to install this into the environment.", "_____no_output_____" ] ], [ [ "from azureml.core.conda_dependencies import CondaDependencies \n\n# Add the dependencies for our model (AzureML defaults is already included)\nmyenv = CondaDependencies()\nmyenv.add_conda_package('scikit-learn')\n\n# Save the environment config as a .yml file\nenv_file = folder_name + \"/diabetes_env.yml\"\nwith open(env_file,\"w\") as f:\n f.write(myenv.serialize_to_string())\nprint(\"Saved dependency info in\", env_file)\n\n# Print the .yml file\nwith open(env_file,\"r\") as f:\n print(f.read())", "_____no_output_____" ] ], [ [ "Now you're ready to deploy. We'll deploy the container a service named **diabetes-service**. The deployment process includes the following steps:\n\n1. Define an inference configuration, which includes the scoring and environment files required to load and use the model.\n2. Define a deployment configuration that defines the execution environment in which the service will be hosted. In this case, an Azure Container Instance.\n3. Deploy the model as a web service.\n4. Verify the status of the deployed service.\n\n> **More Information**: For more details about model deployment, and options for target execution environments, see the [documentation](https://docs.microsoft.com/azure/machine-learning/how-to-deploy-and-where).\n\nDeployment will take some time as it first runs a process to create a container image, and then runs a process to create a web service based on the image. When deployment has completed successfully, you'll see a status of **Healthy**.", "_____no_output_____" ] ], [ [ "from azureml.core.webservice import AciWebservice\nfrom azureml.core.model import InferenceConfig\n\n# Configure the scoring environment\ninference_config = InferenceConfig(runtime= \"python\",\n source_directory = folder_name,\n entry_script=\"score_diabetes.py\",\n conda_file=\"diabetes_env.yml\")\n\ndeployment_config = AciWebservice.deploy_configuration(cpu_cores = 1, memory_gb = 1)\n\nservice_name = \"diabetes-service\"\n\nservice = Model.deploy(ws, service_name, [model], inference_config, deployment_config)\n\nservice.wait_for_deployment(True)\nprint(service.state)", "_____no_output_____" ] ], [ [ "Hopefully, the deployment has been successful and you can see a status of **Healthy**. If not, you can use the following code to check the status and get the service logs to help you troubleshoot.", "_____no_output_____" ] ], [ [ "print(service.state)\nprint(service.get_logs())\n\n# If you need to make a change and redeploy, you may need to delete unhealthy service using the following code:\n#service.delete()", "_____no_output_____" ] ], [ [ "Take a look at your workspace in [Azure ML Studio](https://ml.azure.com) and view the **Endpoints** page, which shows the deployed services in your workspace.\n\nYou can also retrieve the names of web services in your workspace by running the following code:", "_____no_output_____" ] ], [ [ "for webservice_name in ws.webservices:\n print(webservice_name)", "_____no_output_____" ] ], [ [ "## Use the Web Service\n\nWith the service deployed, now you can consume it from a client application.", "_____no_output_____" ] ], [ [ "import json\n\nx_new = [[2,180,74,24,21,23.9091702,1.488172308,22]]\nprint ('Patient: {}'.format(x_new[0]))\n\n# Convert the array to a serializable list in a JSON document\ninput_json = json.dumps({\"data\": x_new})\n\n# Call the web service, passing the input data (the web service will also accept the data in binary format)\npredictions = service.run(input_data = input_json)\n\n# Get the predicted class - it'll be the first (and only) one.\npredicted_classes = json.loads(predictions)\nprint(predicted_classes[0])", "_____no_output_____" ] ], [ [ "You can also send multiple patient observations to the service, and get back a prediction for each one.", "_____no_output_____" ] ], [ [ "import json\n\n# This time our input is an array of two feature arrays\nx_new = [[2,180,74,24,21,23.9091702,1.488172308,22],\n [0,148,58,11,179,39.19207553,0.160829008,45]]\n\n# Convert the array or arrays to a serializable list in a JSON document\ninput_json = json.dumps({\"data\": x_new})\n\n# Call the web service, passing the input data\npredictions = service.run(input_data = input_json)\n\n# Get the predicted classes.\npredicted_classes = json.loads(predictions)\n \nfor i in range(len(x_new)):\n print (\"Patient {}\".format(x_new[i]), predicted_classes[i] )", "_____no_output_____" ] ], [ [ "The code above uses the Azure ML SDK to connect to the containerized web service and use it to generate predictions from your diabetes classification model. In production, a model is likely to be consumed by business applications that do not use the Azure ML SDK, but simply make HTTP requests to the web service.\n\nLet's determine the URL to which these applications must submit their requests:", "_____no_output_____" ] ], [ [ "endpoint = service.scoring_uri\nprint(endpoint)", "_____no_output_____" ] ], [ [ "Now that you know the endpoint URI, an application can simply make an HTTP request, sending the patient data in JSON (or binary) format, and receive back the predicted class(es).", "_____no_output_____" ] ], [ [ "import requests\nimport json\n\nx_new = [[2,180,74,24,21,23.9091702,1.488172308,22],\n [0,148,58,11,179,39.19207553,0.160829008,45]]\n\n# Convert the array to a serializable list in a JSON document\ninput_json = json.dumps({\"data\": x_new})\n\n# Set the content type\nheaders = { 'Content-Type':'application/json' }\n\npredictions = requests.post(endpoint, input_json, headers = headers)\npredicted_classes = json.loads(predictions.json())\n\nfor i in range(len(x_new)):\n print (\"Patient {}\".format(x_new[i]), predicted_classes[i] )", "_____no_output_____" ] ], [ [ "You've deployed your web service as an Azure Container Instance (ACI) service that requires no authentication. This is fine for development and testing, but for production you should consider deploying to an Azure Kubernetes Service (AKS) cluster and enabling authentication. This would require REST requests to include an **Authorization** header.\n\n## Delete the Service\n\nWhen you no longer need your service, you should delete it to avoid incurring unecessary charges.", "_____no_output_____" ] ], [ [ "service.delete()\nprint ('Service deleted.')", "_____no_output_____" ] ], [ [ "For more information about publishing a model as a service, see the [documentation](https://docs.microsoft.com/azure/machine-learning/how-to-deploy-and-where)", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4aee1cce88671e677b185cc7843aa6a15fa8c608
3,075
ipynb
Jupyter Notebook
NLP/Solutions/normalization_solution.ipynb
Vishal7017/Data_Pipelines
300f37c845ca30c589d8328e76b9d90c6952bbbd
[ "BSD-3-Clause" ]
1
2021-06-28T17:43:25.000Z
2021-06-28T17:43:25.000Z
NLP/Solutions/normalization_solution.ipynb
Vishal7017/Data_Pipelines
300f37c845ca30c589d8328e76b9d90c6952bbbd
[ "BSD-3-Clause" ]
null
null
null
NLP/Solutions/normalization_solution.ipynb
Vishal7017/Data_Pipelines
300f37c845ca30c589d8328e76b9d90c6952bbbd
[ "BSD-3-Clause" ]
null
null
null
26.973684
252
0.585691
[ [ [ "# Normalization Quiz\nUse what you've learned in the last video to normalize case in the following text and remove punctuation!", "_____no_output_____" ] ], [ [ "text = \"The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war ? Is AI a bad thing ?\"\nprint(text)", "The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war ? Is AI a bad thing ?\n" ] ], [ [ "### Case Normalization", "_____no_output_____" ] ], [ [ "# Convert to lowercase\ntext = text.lower() \nprint(text)", "the first time you see the second renaissance it may look boring. look at it at least twice and definitely watch part 2. it will change your view of the matrix. are the human people the ones who started the war ? is ai a bad thing ?\n" ] ], [ [ "### Punctuation Removal\nUse the `re` library to remove punctuation with a regular expression (regex). Feel free to refer back to the video or Google to get your regular expression. You can learn more about regex [here](https://docs.python.org/3/howto/regex.html).", "_____no_output_____" ] ], [ [ "import re\n\n# Remove punctuation characters\ntext = re.sub(r\"[^a-zA-Z0-9]\", \" \", text) \nprint(text)", "the first time you see the second renaissance it may look boring look at it at least twice and definitely watch part 2 it will change your view of the matrix are the human people the ones who started the war is ai a bad thing \n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aee241ca12820ff3d6fb2a525b70af631870c58
1,478
ipynb
Jupyter Notebook
All_Source_Code/RoadDetection/RoadDetection.ipynb
APMonitor/pds
fa9a7ec920802de346dcdf7f5dd92d752142c16f
[ "MIT" ]
11
2021-01-21T09:46:29.000Z
2022-03-16T19:33:10.000Z
All_Source_Code/RoadDetection/RoadDetection.ipynb
the-mahapurush/pds
7cb4087dd8e75cb1e9b2a4283966c798175f61f7
[ "MIT" ]
1
2022-03-16T19:47:09.000Z
2022-03-16T20:11:50.000Z
All_Source_Code/RoadDetection/RoadDetection.ipynb
the-mahapurush/pds
7cb4087dd8e75cb1e9b2a4283966c798175f61f7
[ "MIT" ]
12
2021-02-08T21:11:11.000Z
2022-03-20T12:42:49.000Z
1,478
1,478
0.658322
[ [ [ "### Machine Learning for Engineers: [RoadDetection](https://www.apmonitor.com/pds/index.php/Main/RoadDetection)\n- [Road Detection](https://www.apmonitor.com/pds/index.php/Main/RoadDetection)\n - Source Blocks: 1\n - Description: Use OpenCV in Python to split frames from a video into hue, saturation, and intensity to create a filter that accentuates the road path for a self-driving vehicle.\n- [Course Overview](https://apmonitor.com/pds)\n- [Course Schedule](https://apmonitor.com/pds/index.php/Main/CourseSchedule)\n", "_____no_output_____" ] ], [ [ "elif mode.get() == HSV:\n half = cv.resize(frame, (int(width/2), int(height/2)))\n hsv = cv.cvtColor(half, cv.COLOR_BGR2HSV)\n h,s,v = cv.split(hsv)\n if Slider1.get() > 0 and Slider1.get() < 255:\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))\n s = cv.inRange(s, Slider1.get(), Slider2.get())\n s = cv.morphologyEx(s, cv.MORPH_OPEN, kernel)\n v = cv.inRange(v, Slider1.get(), Slider2.get())\n v = cv.morphologyEx(v, cv.MORPH_OPEN, kernel)\n top = cv.hconcat([half, cv.merge((h, h, h))])\n bottom = cv.hconcat([cv.merge((s, s, s)), cv.merge((v, v, v))])\n frame = cv.vconcat([top, bottom])", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
4aee278f905847598eb3ee9aaa84be9ad3c0394e
216,353
ipynb
Jupyter Notebook
docs/all_methods.ipynb
synapticarbors/extensisq
3dec68bfd168cfc1749f7e08a940202c76ba41eb
[ "MIT" ]
null
null
null
docs/all_methods.ipynb
synapticarbors/extensisq
3dec68bfd168cfc1749f7e08a940202c76ba41eb
[ "MIT" ]
null
null
null
docs/all_methods.ipynb
synapticarbors/extensisq
3dec68bfd168cfc1749f7e08a940202c76ba41eb
[ "MIT" ]
null
null
null
104.46789
68,651
0.759329
[ [ [ "# Extensisq methods & Lotka-Volterra problem\n\nThe extensisq methods are compared to the explicit runge kutta methods of scipy on the Lotka-Volterra problem (predator prey model). This problem was copied from the solve_ivp page in scipy's reference manual.\n\n## Problem definition\nThe parameters of this problem are defined as additional arguments `arg` to the derivative function.", "_____no_output_____" ] ], [ [ "def lotkavolterra(t, z, a, b, c, d):\n x, y = z\n return [a*x - b*x*y, -c*y + d*x*y]\n\nproblem = {'fun' : lotkavolterra,\n 'y0' : [10., 5.],\n 't_span' : [0., 15.],\n 'args' : (1.5, 1, 3, 1)}", "_____no_output_____" ] ], [ [ "## Reference solution\n\nFirst a reference solution is created by solving this problem with low tolerance.", "_____no_output_____" ] ], [ [ "from scipy.integrate import solve_ivp\n\nreference = solve_ivp(**problem, atol=1e-12, rtol=1e-12, method='DOP853', dense_output=True)", "_____no_output_____" ] ], [ [ "## Solution plot\n\nThis solution has derivatives that change rapidly.", "_____no_output_____" ] ], [ [ "%matplotlib notebook\nimport matplotlib.pyplot as plt\n\nplt.figure()\nplt.plot(reference.t, reference.y.T)\nplt.title('Lotka-Volterra')\nplt.legend(('prey', 'predator'))\nplt.show()", "_____no_output_____" ] ], [ [ "## Efficiency plot\n\nLet's solve this problem with the explicit runge kutta methods of scipy (`RK45` and `DOP853`) and those of extensisq (`Ts45`, `BS45`, `BS45_i`, `CK45` and `CK45_o`) at a few absolute tolerance values and make a plot to compare their efficiency. The bottom left corner of that plot is the efficiency sweet spot: low error and few fuction evaluations.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom extensisq import *\n\nmethods = ['RK45', 'DOP853', Ts45, BS45, BS45_i, CK45, CK45_o]\ntolerances = np.logspace(-4, -9, 6)\n\nplt.figure()\nfor method in methods:\n name = method if isinstance(method, str) else method.__name__\n e = []\n n = []\n for tol in tolerances:\n sol = solve_ivp(**problem, rtol=1e-13, atol=tol, method=method,\n dense_output=True) # only to separate BS45 and BS45_i\n err = sol.y - reference.sol(sol.t)\n e.append(np.linalg.norm(err))\n n.append(sol.nfev)\n if name == 'RK45':\n style = '--k.'\n elif name == 'DOP853':\n style = '-k.'\n else:\n style = '.:'\n plt.loglog(e, n, style, label=name)\nplt.legend()\nplt.xlabel(r'||error||')\nplt.ylabel('nr of function evaluations')\nplt.title('efficiency')\nplt.show() ", "_____no_output_____" ] ], [ [ "## Discussion\n\nThe efficiency graph shows:\n* `RK45` has the poorest efficiency of all considered methods.\n* `Ts45` is quite similar to `RK45`, but just a bit better.\n* `BS45` and `BS45_i` are the most efficient fifth order methods for lower (tighter) tolerances. These two methods have exactly the same accuracy, but `BS45` needs more evaluations for its accurate interpolant. That interpolant is not used in this case. It was only enabeled, by setting `dense_output=True`, to show the difference with respect to `BS45_i`.\n* `CK45` and `CK45_o` are the most efficient methods at higher (looser) tolerances. The performance at lower tolerance is similar to `Ts45`.\n* `DOP853` is a higher order method (eighth). Typically, it is more efficient at lower tolerance, but for this problem and these tolerances it does not work so well.\n\nThese observation may not be valid for other problems.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4aee32f34546cb75b1df494e5f4d55c81e9310d8
7,722
ipynb
Jupyter Notebook
src/src_old/ingredient_classification.ipynb
dhyeon/ingredient2vec
ef2b36643bb67a5c2e134733f498154946923513
[ "Apache-2.0" ]
1
2018-01-01T23:04:23.000Z
2018-01-01T23:04:23.000Z
src/src_old/ingredient_classification.ipynb
dhyeon/ingredient2vec
ef2b36643bb67a5c2e134733f498154946923513
[ "Apache-2.0" ]
null
null
null
src/src_old/ingredient_classification.ipynb
dhyeon/ingredient2vec
ef2b36643bb67a5c2e134733f498154946923513
[ "Apache-2.0" ]
null
null
null
45.692308
1,398
0.576923
[ [ [ "import os\nimport smart_open\nimport gensim", "_____no_output_____" ], [ "\"\"\"\nLoad train data and build train_corpus for Doc2Vec\n\n\"\"\"\npath = 'data'\ntrain_file = path + os.sep + 'ingredient2vec'\n\ndef read_corpus(fname, tokens_only=False):\n with smart_open.smart_open(fname, encoding=\"iso-8859-1\") as f:\n for i, line in enumerate(f):\n if tokens_only:\n yield gensim.utils.simple_preprocess(line)\n else:\n # For training data, add tags\n line_split = line.split(' ')\n ingredient = line_split[0]\n compounds = ' '.join(line_split[1:])\n yield gensim.models.doc2vec.TaggedDocument(gensim.utils.simple_preprocess(compounds), [ingredient])\n\n# Corpus tag to index\ndef tag_to_index(tags, corpus):\n for doc_id in range(len(corpus)):\n if tags == corpus[doc_id].tags[0]:\n return doc_id\n else:\n continue\n return\n\n# Corpus index to tag \ndef index_to_tag(index, corpus):\n return corpus[index].tags\n \n\n\ncorpus = list(read_corpus(train_file))\ncorpus_th10 = []\n\n# threshold\nfor doc_id in range(len(train_corpus)):\n if len(corpus[doc_id].words) > 10:\n corpus_th10.append(corpus[doc_id])\n\nprint \"Total length of corpus:\", len(corpus)\nprint \"Total length of corpus_th10:\", len(corpus_th10)", "Total length of corpus: 1525\nTotal length of corpus_th10: 514\n" ], [ "from gensim import corpora\n\ndocuments = [\"Human machine interface for lab abc computer applications\",\n \"A survey of user opinion of computer system response time\",\n \"The EPS user interface management system\",\n \"System and human system engineering testing of EPS\", \n \"Relation of user perceived response time to error measurement\",\n \"The generation of random binary unordered trees\",\n \"The intersection graph of paths in trees\",\n \"Graph minors IV Widths of trees and well quasi ordering\",\n \"Graph minors A survey\"]\n\ntexts = [[word for word in document.lower().split()]\n for document in documents]\n\nfor text in texts:\n print text\n\n\ndictionary = gensim.corpora.SvmLightCorpus(texts)\nprint dictionary[0]\n#new_doc = \"Human computer interaction\"\n#new_vec = dictionary.doc2bow(new_doc.lower().split())\n#print new_vec", "['human', 'machine', 'interface', 'for', 'lab', 'abc', 'computer', 'applications']\n['a', 'survey', 'of', 'user', 'opinion', 'of', 'computer', 'system', 'response', 'time']\n['the', 'eps', 'user', 'interface', 'management', 'system']\n['system', 'and', 'human', 'system', 'engineering', 'testing', 'of', 'eps']\n['relation', 'of', 'user', 'perceived', 'response', 'time', 'to', 'error', 'measurement']\n['the', 'generation', 'of', 'random', 'binary', 'unordered', 'trees']\n['the', 'intersection', 'graph', 'of', 'paths', 'in', 'trees']\n['graph', 'minors', 'iv', 'widths', 'of', 'trees', 'and', 'well', 'quasi', 'ordering']\n['graph', 'minors', 'a', 'survey']\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
4aee33011ae65c464feb6c79131109a043135d5a
2,999
ipynb
Jupyter Notebook
notebooks/io-h5-read-earth.ipynb
GeoscienceAustralia/dggs-pilot
4105d7ba47cc1e4323efa4e60e0eb5c0f8ffb213
[ "Apache-2.0" ]
1
2019-07-19T23:05:56.000Z
2019-07-19T23:05:56.000Z
notebooks/io-h5-read-earth.ipynb
GeoscienceAustralia/dggs-pilot
4105d7ba47cc1e4323efa4e60e0eb5c0f8ffb213
[ "Apache-2.0" ]
1
2018-08-08T11:31:17.000Z
2018-08-09T08:13:59.000Z
notebooks/io-h5-read-earth.ipynb
GeoscienceAustralia/dggs-pilot
4105d7ba47cc1e4323efa4e60e0eb5c0f8ffb213
[ "Apache-2.0" ]
2
2018-04-20T03:10:12.000Z
2018-08-09T08:14:47.000Z
22.214815
69
0.507503
[ [ [ "#%matplotlib notebook\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\nimport importlib\nfrom dggs import DGGS, io as dggs_io\nfrom dggs import uitools\nfrom dggs.datasets import get_path", "_____no_output_____" ], [ "dd = dggs_io.h5_load(get_path('earth.h5'))", "_____no_output_____" ], [ "ax = uitools.DgDraw(plt.figure(figsize=(12,6)),\n south_square=0)\nax.hide_axis()\nax.imshow(dd)\nax.figure.savefig('dggs_earth_00.png', dpi=300)\nfig00 = ax.figure", "_____no_output_____" ], [ "for c in 'SNOPQR':\n ax.roi(c, linewidth=2, alpha=0.6, color='y')\n for n in range(8):\n ax.roi(f'{c}{n}', linewidth=1, alpha=0.3, color='y')\n\nfor n in range(8):\n ax.roi(f'R7{n}', linewidth=1, alpha=0.3, color='y')\n \nax.figure", "_____no_output_____" ], [ "ax = uitools.DgDraw(plt.figure(figsize=(12,6)),\n south_square=3, north_square=2)\n\nax.hide_axis()\nax.imshow(dd)\nfig23 = ax.figure", "_____no_output_____" ], [ "fig00.savefig('dggs_earth_00_grids.png', dpi=300)\nfig23.savefig('dggs_earth_23.png', dpi=300)", "_____no_output_____" ], [ "for c in 'SNOPQR':\n ax.roi(c, linewidth=2, alpha=0.6, color='y')\n for n in range(8):\n ax.roi(f'{c}{n}', linewidth=1, alpha=0.3, color='y')\n\nfor n in range(8):\n ax.roi(f'R7{n}', linewidth=1, alpha=0.3, color='y')\n \nax.figure", "_____no_output_____" ], [ "#!open dggs_earth_23.png\n#!open dggs_earth_00_grids.png", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aee3556f478d7f6deb7f2e233533534d945a74c
51,951
ipynb
Jupyter Notebook
wisconsin/VAE_log_regression.ipynb
TomMonks/1909_data_synthesis
1ac1879bacb7d3f0dcb2a87f7610e533bc1353ec
[ "MIT" ]
null
null
null
wisconsin/VAE_log_regression.ipynb
TomMonks/1909_data_synthesis
1ac1879bacb7d3f0dcb2a87f7610e533bc1353ec
[ "MIT" ]
null
null
null
wisconsin/VAE_log_regression.ipynb
TomMonks/1909_data_synthesis
1ac1879bacb7d3f0dcb2a87f7610e533bc1353ec
[ "MIT" ]
null
null
null
36.559465
145
0.448346
[ [ [ "# Creation of synthetic data for Wisoncsin Breat Cancer data set using a Variational AutoEncoder. Tested using a logistic regression model.", "_____no_output_____" ], [ "## Aim\n\nTo test a a Variational AutoEncoder (VAE) for synthesising data that can be used to train a logistic regression machine learning model.", "_____no_output_____" ], [ "## Data\n\nRaw data is avilable at: \n\nhttps://www.kaggle.com/uciml/breast-cancer-wisconsin-data", "_____no_output_____" ], [ "## Basic methods description\n\n* Create synthetic data by use of a Variational AutoEncoder\n\nKingma, D.P. and Welling, M. (2013) Auto-encoding variational bayes. arXiv preprint arXiv:1312.6114,2013.\n\n* Train logistic regression model on synthetic data and test against held-back raw data", "_____no_output_____" ], [ "## Code & results", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt \n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.decomposition import PCA\n\n# Turn warnings off for notebook publication\nimport warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ] ], [ [ "### Import Data", "_____no_output_____" ] ], [ [ "def load_data():\n \"\"\"\"\n Load Wisconsin Breast Cancer Data Set\n \n Inputs\n ------\n None\n \n Returns\n -------\n X: NumPy array of X\n y: Numpy array of y\n col_names: column names for X\n \"\"\"\n \n # Load data and drop 'id' column\n data = pd.read_csv('./wisconsin.csv')\n data.drop('id', axis=1, inplace=True)\n\n # Change 'diagnosis' column to 'malignant', and put in last column place\n malignant = pd.DataFrame()\n data['malignant'] = data['diagnosis'] == 'M'\n data.drop('diagnosis', axis=1, inplace=True)\n\n # Split data in X and y\n X = data.drop(['malignant'], axis=1)\n y = data['malignant']\n \n # Get col names and convert to NumPy arrays\n X_col_names = list(X)\n X = X.values\n y = y.values\n \n return data, X, y, X_col_names ", "_____no_output_____" ] ], [ [ "### Data processing", "_____no_output_____" ], [ "Split X and y into training and test sets", "_____no_output_____" ] ], [ [ "def split_into_train_test(X, y, test_proportion=0.25): \n \"\"\"\"\n Randomly split X and y numpy arrays into training and test data sets\n \n Inputs\n ------\n X and y NumPy arrays\n \n Returns\n -------\n X_test, X_train, y_test, y_train Numpy arrays\n \"\"\"\n \n X_train, X_test, y_train, y_test = \\\n train_test_split(X, y, shuffle=True, test_size=test_proportion)\n \n return X_train, X_test, y_train, y_test ", "_____no_output_____" ] ], [ [ "Standardise data", "_____no_output_____" ] ], [ [ "def standardise_data(X_train, X_test):\n \"\"\"\"\n Standardise training and tets data sets according to mean and standard\n deviation of test set\n \n Inputs\n ------\n X_train, X_test NumPy arrays\n \n Returns\n -------\n X_train_std, X_test_std\n \"\"\"\n \n mu = X_train.mean(axis=0)\n std = X_train.std(axis=0)\n \n X_train_std = (X_train - mu) / std\n X_test_std = (X_test - mu) /std\n \n return X_train_std, X_test_std\n ", "_____no_output_____" ] ], [ [ "### Calculate accuracy measures", "_____no_output_____" ] ], [ [ "def calculate_diagnostic_performance(actual, predicted):\n \"\"\" Calculate sensitivty and specificty.\n \n Inputs\n ------\n actual, predted numpy arrays (1 = +ve, 0 = -ve)\n \n Returns\n -------\n A dictionary of results:\n \n 1) accuracy: proportion of test results that are correct \n 2) sensitivity: proportion of true +ve identified\n 3) specificity: proportion of true -ve identified\n 4) positive likelihood: increased probability of true +ve if test +ve\n 5) negative likelihood: reduced probability of true +ve if test -ve\n 6) false positive rate: proportion of false +ves in true -ve patients\n 7) false negative rate: proportion of false -ves in true +ve patients\n 8) positive predictive value: chance of true +ve if test +ve\n 9) negative predictive value: chance of true -ve if test -ve\n 10) actual positive rate: proportion of actual values that are +ve\n 11) predicted positive rate: proportion of predicted vales that are +ve\n 12) recall: same as sensitivity\n 13) precision: the proportion of predicted +ve that are true +ve\n 14) f1 = 2 * ((precision * recall) / (precision + recall))\n\n *false positive rate is the percentage of healthy individuals who \n incorrectly receive a positive test result\n * alse neagtive rate is the percentage of diseased individuals who \n incorrectly receive a negative test result\n \n \"\"\"\n \n # Calculate results \n actual_positives = actual == 1\n actual_negatives = actual == 0\n test_positives = predicted == 1\n test_negatives = predicted == 0\n test_correct = actual == predicted\n accuracy = test_correct.mean()\n true_positives = actual_positives & test_positives\n false_positives = actual_negatives & test_positives\n true_negatives = actual_negatives & test_negatives\n sensitivity = true_positives.sum() / actual_positives.sum()\n specificity = np.sum(true_negatives) / np.sum(actual_negatives)\n positive_likelihood = sensitivity / (1 - specificity)\n negative_likelihood = (1 - sensitivity) / specificity\n false_postive_rate = 1 - specificity\n false_negative_rate = 1 - sensitivity\n positive_predictive_value = true_positives.sum() / test_positives.sum()\n negative_predicitive_value = true_negatives.sum() / test_negatives.sum()\n actual_positive_rate = actual.mean()\n predicted_positive_rate = predicted.mean()\n recall = sensitivity\n precision = \\\n true_positives.sum() / (true_positives.sum() + false_positives.sum())\n f1 = 2 * ((precision * recall) / (precision + recall))\n \n # Add results to dictionary\n results = dict()\n results['accuracy'] = accuracy\n results['sensitivity'] = sensitivity\n results['specificity'] = specificity\n results['positive_likelihood'] = positive_likelihood\n results['negative_likelihood'] = negative_likelihood\n results['false_postive_rate'] = false_postive_rate\n results['false_postive_rate'] = false_postive_rate\n results['false_negative_rate'] = false_negative_rate\n results['positive_predictive_value'] = positive_predictive_value\n results['negative_predicitive_value'] = negative_predicitive_value\n results['actual_positive_rate'] = actual_positive_rate\n results['predicted_positive_rate'] = predicted_positive_rate\n results['recall'] = recall\n results['precision'] = precision\n results['f1'] = f1\n \n return results", "_____no_output_____" ] ], [ [ "### Logistic Regression Model", "_____no_output_____" ] ], [ [ "def fit_and_test_logistic_regression_model(X_train, X_test, y_train, y_test): \n \"\"\"\"\n Fit and test logistic regression model. \n Return a dictionary of accuracy measures.\n Calls on `calculate_diagnostic_performance` to calculate results\n \n Inputs\n ------\n X_train, X_test NumPy arrays\n \n Returns\n -------\n A dictionary of accuracy results.\n \"\"\"\n \n # Fit logistic regression model \n lr = LogisticRegression(C=0.1)\n lr.fit(X_train,y_train)\n\n # Predict tets set labels\n y_pred = lr.predict(X_test_std)\n \n # Get accuracy results\n accuracy_results = calculate_diagnostic_performance(y_test, y_pred)\n \n return accuracy_results", "_____no_output_____" ] ], [ [ "### Synthetic Data Method - Variational AutoEncoder", "_____no_output_____" ] ], [ [ "def sampling(args):\n \"\"\"\n Reparameterization trick by sampling from an isotropic unit Gaussian.\n Instead of sampling from Q(z|X), sample epsilon = N(0,I)\n z = z_mean + sqrt(var) * epsilon\n\n # Arguments\n args (tensor): mean and log of variance of Q(z|X)\n\n # Returns\n z (tensor): sampled latent vector\n \"\"\"\n\n import tensorflow\n from tensorflow.keras import backend as K\n \n z_mean, z_log_var = args\n batch = K.shape(z_mean)[0]\n dim = K.int_shape(z_mean)[1]\n # by default, random_normal has mean = 0 and std = 1.0\n epsilon = K.random_normal(shape=(batch, dim))\n \n sample = z_mean + K.exp(0.5 * z_log_var) * epsilon\n \n return sample", "_____no_output_____" ], [ "def make_synthetic_data_vae(X_original, y_original, \n batch_size=256,\n latent_dim=8,\n epochs=10000,\n learning_rate=2e-5,\n dropout=0.25,\n number_of_samples=1000):\n \"\"\"\n Synthetic data generation.\n Calls on `get_principal_component_model` for PCA model\n If number of components not defined then the function sets it to the number\n of features in X\n \n Inputs\n ------\n original_data: X, y numpy arrays\n number_of_samples: number of synthetic samples to generate\n n_components: number of principal components to use for data synthesis\n \n Returns\n -------\n X_synthetic: NumPy array\n y_synthetic: NumPy array\n\n \"\"\"\n import tensorflow\n from tensorflow.keras import layers\n from tensorflow.keras.models import Model\n from tensorflow.keras.optimizers import Adam\n from tensorflow.keras import backend as K\n from tensorflow.keras.losses import mean_squared_error\n \n # Standardise X\n mean = X_original.mean(axis=0)\n std = X_original.mean(axis=0) \n X_std = (X_original - mean) / std\n \n # network parameters\n input_shape = X_original.shape[1]\n intermediate_dim = X_original.shape[1]\n \n # Split the training data into positive and negative\n mask = y_original == 1\n X_train_pos = X_std[mask]\n mask = y_original == 0\n X_train_neg = X_std[mask]\n \n # Set up list for positive and negative synthetic data sets\n synthetic_X_sets = []\n \n # Run fir twice: once for positive label examples, the other for negative\n for training_set in [X_train_pos, X_train_neg]:\n \n # Clear Tensorflow\n K.clear_session()\n\n # VAE model = encoder + decoder\n # build encoder model\n inputs = layers.Input(shape=input_shape, name='encoder_input')\n \n encode_dense_1 = layers.Dense(\n intermediate_dim, activation='relu')(inputs)\n \n dropout_encoder_layer_1 = layers.Dropout(dropout)(encode_dense_1)\n \n encode_dense_2 = layers.Dense(\n intermediate_dim, activation='relu')(dropout_encoder_layer_1)\n \n z_mean = layers.Dense(latent_dim, name='z_mean')(encode_dense_2)\n \n z_log_var = layers.Dense(latent_dim, name='z_log_var')(encode_dense_2)\n \n # use reparameterization trick to push the sampling out as input\n # note that \"output_shape\" isn't necessary with the TensorFlow backend\n z = layers.Lambda(\n sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])\n \n # instantiate encoder model\n encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder')\n \n # build decoder model\n latent_inputs = layers.Input(shape=(latent_dim,), name='z_sampling')\n \n decode_dense_1 = layers.Dense(\n intermediate_dim, activation='relu')(latent_inputs)\n \n dropout_decoder_layer_1 = layers.Dropout(dropout)(decode_dense_1)\n \n decode_dense_2 = layers.Dense(\n intermediate_dim, activation='relu')(dropout_decoder_layer_1)\n \n outputs = layers.Dense(input_shape)(decode_dense_2)\n \n # instantiate decoder model\n decoder = Model(latent_inputs, outputs, name='decoder')\n \n # instantiate VAE model\n outputs = decoder(encoder(inputs)[2])\n vae = Model(inputs, outputs, name='vae_mlp')\n \n # Train the autoencoder\n \n optimizer = Adam(lr=learning_rate)\n \n # VAE loss = mse_loss or xent_loss + kl_loss\n vae.compile(optimizer=optimizer, loss = mean_squared_error)\n \n # Train the autoencoder\n vae.fit(training_set, training_set,\n batch_size = batch_size,\n shuffle = True,\n epochs = epochs,\n verbose=0)\n \n # Produce synthetic data\n z_new = np.random.normal(size = (number_of_samples, latent_dim))\n reconst = decoder.predict(np.array(z_new))\n reconst = mean + (reconst * std)\n synthetic_X_sets.append(reconst)\n \n # Clear models\n K.clear_session()\n del encoder\n del decoder\n del vae\n \n # Combine data\n # Combine positive and negative and shuffle rows\n X_synthetic = np.concatenate(\n (synthetic_X_sets[0], synthetic_X_sets[1]), axis=0)\n \n y_synthetic_pos = np.ones((number_of_samples, 1))\n y_synthetic_neg = np.zeros((number_of_samples, 1))\n \n y_synthetic = np.concatenate((y_synthetic_pos, y_synthetic_neg), axis=0)\n \n # Randomise order of X, y\n synthetic = np.concatenate((X_synthetic, y_synthetic), axis=1)\n shuffle_index = np.random.permutation(np.arange(X_synthetic.shape[0]))\n synthetic = synthetic[shuffle_index]\n X_synthetic = synthetic[:,0:-1]\n y_synthetic = synthetic[:,-1]\n \n return X_synthetic, y_synthetic", "_____no_output_____" ] ], [ [ "### Main code", "_____no_output_____" ] ], [ [ "# Load data\noriginal_data, X, y, X_col_names = load_data()\n\n# Set up results DataFrame\nresults = pd.DataFrame()", "_____no_output_____" ] ], [ [ "Fitting classification model to raw data", "_____no_output_____" ] ], [ [ "# Set number of replicate runs\nnumber_of_runs = 30\n\n# Set up lists for results\naccuracy_measure_names = []\naccuracy_measure_data = []\n\nfor run in range(number_of_runs):\n \n # Print progress\n print (run + 1, end=' ')\n \n # Split training and test set\n X_train, X_test, y_train, y_test = split_into_train_test(X, y)\n\n # Standardise data \n X_train_std, X_test_std = standardise_data(X_train, X_test)\n\n # Get accuracy of fitted model\n accuracy = fit_and_test_logistic_regression_model(\n X_train_std, X_test_std, y_train, y_test)\n \n # Get accuracy measure names if not previously done\n if len(accuracy_measure_names) == 0:\n for key, value in accuracy.items():\n accuracy_measure_names.append(key)\n \n # Get accuracy values\n run_accuracy_results = []\n for key, value in accuracy.items():\n run_accuracy_results.append(value)\n \n # Add results to results list\n accuracy_measure_data.append(run_accuracy_results)\n\n# Strore mean and sem in results DataFrame \naccuracy_array = np.array(accuracy_measure_data)\nresults['raw_mean'] = accuracy_array.mean(axis=0)\nresults['raw_sem'] = accuracy_array.std(axis=0)/np.sqrt(number_of_runs)\nresults.index = accuracy_measure_names", "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 " ] ], [ [ "Fitting classification model to synthetic data", "_____no_output_____" ] ], [ [ "# Set number of replicate runs\nnumber_of_runs = 30\n\nfor run in range(number_of_runs):\n \n # Print progress\n print (run + 1, end=' ')\n\n X_synthetic, y_synthetic = \\\n make_synthetic_data_vae(X, y)\n\n # Split training and test set\n X_train, X_test, y_train, y_test = split_into_train_test(X, y)\n\n # Standardise data (using synthetic data)\n X_train_std, X_test_std = standardise_data(X_synthetic, X_test)\n\n # Get accuracy of fitted model\n accuracy = fit_and_test_logistic_regression_model(\n X_train_std, X_test_std, y_synthetic, y_test)\n\n # Get accuracy measure names if not previously done\n if len(accuracy_measure_names) == 0:\n for key, value in accuracy.items():\n accuracy_measure_names.append(key)\n\n # Get accuracy values\n run_accuracy_results = []\n for key, value in accuracy.items():\n run_accuracy_results.append(value)\n \n # Add results to results list\n accuracy_measure_data.append(run_accuracy_results)\n\n# Strore mean and sem in results DataFrame \naccuracy_array = np.array(accuracy_measure_data)\nresults['vae_mean'] = accuracy_array.mean(axis=0)\nresults['vae_sem'] = accuracy_array.std(axis=0)/np.sqrt(number_of_runs)", "_____no_output_____" ] ], [ [ "Save last synthetic data set", "_____no_output_____" ] ], [ [ "# Create a data frame with id\nsynth_df = pd.DataFrame()\nsynth_df['id'] = np.arange(y_synthetic.shape[0])\n\n\n# Transfer X values to DataFrame\nsynth_df=pd.concat([synth_df, \n pd.DataFrame(X_synthetic, columns=X_col_names)],\n axis=1)\n\n# Add a 'M' or 'B' diagnosis\ny_list = list(y_synthetic)\ndiagnosis = ['M' if y==1 else 'B' for y in y_list]\nsynth_df['diagnosis'] = diagnosis\n\n# Shuffle data\nsynth_df = synth_df.sample(frac=1.0)\n\n# Save data\nsynth_df.to_csv('./Output/synthetic_data_vae.csv', index=False)", "_____no_output_____" ] ], [ [ "### Show results", "_____no_output_____" ] ], [ [ "results", "_____no_output_____" ] ], [ [ "## Compare raw and synthetic data means and standard deviations", "_____no_output_____" ] ], [ [ "# Process synthetic data\nsynth_df.drop('id', axis=1, inplace=True)\nmalignant = pd.DataFrame()\nsynth_df['malignant'] = synth_df['diagnosis'] == 'M'\nsynth_df.drop('diagnosis', axis=1, inplace=True)", "_____no_output_____" ], [ "descriptive_stats = pd.DataFrame()\n\ndescriptive_stats['Original M mean'] = \\\n original_data[original_data['malignant']==True].mean()\n\ndescriptive_stats['Synthetic M mean'] = \\\n synth_df[synth_df['malignant']==True].mean()\n\ndescriptive_stats['Original B mean'] = \\\n original_data[original_data['malignant']==False].mean()\n\ndescriptive_stats['Synthetic B mean'] = \\\n synth_df[synth_df['malignant']==False].mean()\n\ndescriptive_stats['Original M std'] = \\\n original_data[original_data['malignant']==True].std()\n\ndescriptive_stats['Synthetic M std'] = \\\n synth_df[synth_df['malignant']==True].std()\n\ndescriptive_stats['Original B std'] = \\\n original_data[original_data['malignant']==False].std()\n\ndescriptive_stats['Synthetic B std'] = \\\n synth_df[synth_df['malignant']==False].std()\n\n\ndescriptive_stats", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4aee4ad5c5a02c4a2928f9d8b3a16fc6318a57d9
9,113
ipynb
Jupyter Notebook
Assignment_2/assignment_2.ipynb
tmarissa/DATA-690-WANG
2f1d0484f840f3d497e1800917e870fdd93631e7
[ "MIT" ]
null
null
null
Assignment_2/assignment_2.ipynb
tmarissa/DATA-690-WANG
2f1d0484f840f3d497e1800917e870fdd93631e7
[ "MIT" ]
null
null
null
Assignment_2/assignment_2.ipynb
tmarissa/DATA-690-WANG
2f1d0484f840f3d497e1800917e870fdd93631e7
[ "MIT" ]
2
2021-05-12T14:11:19.000Z
2021-05-12T14:21:00.000Z
9,113
9,113
0.789093
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4aee6073553fa9617e6875efa8ce15f60dede65d
218,000
ipynb
Jupyter Notebook
DL_assignment_Minst_BALAJI__PRN_20020845006.ipynb
balajisibm/DL_assignment_MNIST_DATASET
696ed108e6dd66fcf7aa2f7c66074857fea3fef7
[ "MIT" ]
null
null
null
DL_assignment_Minst_BALAJI__PRN_20020845006.ipynb
balajisibm/DL_assignment_MNIST_DATASET
696ed108e6dd66fcf7aa2f7c66074857fea3fef7
[ "MIT" ]
null
null
null
DL_assignment_Minst_BALAJI__PRN_20020845006.ipynb
balajisibm/DL_assignment_MNIST_DATASET
696ed108e6dd66fcf7aa2f7c66074857fea3fef7
[ "MIT" ]
null
null
null
138.853503
29,886
0.852133
[ [ [ "**MNIST Handwritten Digit Classification Dataset**", "_____no_output_____" ] ], [ [ "# example of loading the mnist dataset\nfrom tensorflow.keras.datasets import mnist\nfrom matplotlib import pyplot as plt\n# load dataset\n(trainX, trainy), (testX, testy) = mnist.load_data()\n# summarize loaded dataset\nprint('Train: X=%s, y=%s' % (trainX.shape, trainy.shape))\nprint('Test: X=%s, y=%s' % (testX.shape, testy.shape))\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tplt.subplot(330 + 1 + i)\n\t# plot raw pixel data\n\tplt.imshow(trainX[i], cmap=plt.get_cmap('gray'))\n# show the figure\nplt.show()", "Train: X=(60000, 28, 28), y=(60000,)\nTest: X=(10000, 28, 28), y=(10000,)\n" ] ], [ [ "from the above output we can see that MINST has 60000 training dataset (hand written numbers / images) & 10000 testing dataset (hand written numbers / images ) for evaluation . the images are in square size of 28*28 pixels \n\nThe task is to classify a given image of a handwritten digit into one of 10 classes representing integer values from 0 to 9", "_____no_output_____" ] ], [ [ "\n# baseline cnn model for mnist\nfrom numpy import mean\nfrom numpy import std\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import KFold\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.optimizers import SGD", "_____no_output_____" ] ], [ [ "**Model Evaluation Methodology**", "_____no_output_____" ], [ "**How to Develop a Baseline Model**\n\nthere are 5 steps in creating a Baseline model . they are as follows They are the loading of the dataset, the preparation of the dataset, the definition of the model, the evaluation of the model, and the presentation of results.\n\n**Load Dataset**\n\nwe are going to load the images and reshape the data arrays to have a single color channel.", "_____no_output_____" ] ], [ [ "\n# load train and test dataset\ndef load_dataset():\n\t# load dataset\n\t(trainX, trainY), (testX, testY) = mnist.load_data()\n\t# reshape dataset to have a single channel\n\ttrainX = trainX.reshape((trainX.shape[0], 28, 28, 1))\n\ttestX = testX.reshape((testX.shape[0], 28, 28, 1))\n \n \n \t# one hot encode target values\n\ttrainY = to_categorical(trainY)\n\ttestY = to_categorical(testY)\n\treturn trainX, trainY, testX, testY\n", "_____no_output_____" ] ], [ [ " there are 10 classes and that classes are represented as unique integers.\n\nWe can, therefore, use a one hot encoding for the class element of each sample, transforming the integer into a 10 element binary vector with a 1 for the index of the class value, and 0 values for all other classes.so i have done 1 hot encoding in the above code", "_____no_output_____" ], [ "**Prepare Pixel Data**\n\nWe know that the pixel values for each image in the dataset are unsigned integers in the range between black and white, or 0 and 255", "_____no_output_____" ] ], [ [ "\n# scale pixels\ndef prep_pixels(train, test):\n\t# convert from integers to floats\n\ttrain_norm = train.astype('float32')\n\ttest_norm = test.astype('float32')\n\t# normalize to range 0-1\n\ttrain_norm = train_norm / 255.0\n\ttest_norm = test_norm / 255.0\n\t# return normalized images\n\treturn train_norm, test_norm", "_____no_output_____" ] ], [ [ "**Define Model**\n\nThe model has two main aspects: the feature extraction front end comprised of convolutional and pooling layers, and the classifier backend that will make a prediction.\n\nFor the convolutional front-end, we can start with a single convolutional layer with a small filter size (3,3) and a modest number of filters (32) followed by a max pooling layer. The filter maps can then be flattened to provide features to the classifier.", "_____no_output_____" ] ], [ [ "# define cnn model\ndef define_model():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(10, activation='softmax'))\n\t# compile model\n\topt = SGD(learning_rate=0.01, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\treturn model", "_____no_output_____" ] ], [ [ "**Evaluate Model**\nAfter the model is defined, we need to evaluate it", "_____no_output_____" ] ], [ [ "# evaluate a model using k-fold cross-validation\ndef evaluate_model(dataX, dataY, n_folds=5):\n\tscores, histories = list(), list()\n\t# prepare cross validation\n\tkfold = KFold(n_folds, shuffle=True, random_state=1)\n\t# enumerate splits\n\tfor train_ix, test_ix in kfold.split(dataX):\n\t\t# define model\n\t\tmodel = define_model()\n\t\t# select rows for train and test\n\t\ttrainX, trainY, testX, testY = dataX[train_ix], dataY[train_ix], dataX[test_ix], dataY[test_ix]\n\t\t# fit model\n\t\thistory = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX, testY), verbose=0)\n\t\t# evaluate model\n\t\t_, acc = model.evaluate(testX, testY, verbose=0)\n\t\tprint('> %.3f' % (acc * 100.0))\n\t\t# stores scores\n\t\tscores.append(acc)\n\t\thistories.append(history)\n\treturn scores, histories", "_____no_output_____" ] ], [ [ "**Present Results**\n\nThere are two key aspects to present: the diagnostics of the learning behavior of the model during training and the estimation of the model performance. These can be implemented using separate functions.", "_____no_output_____" ] ], [ [ "# plot diagnostic learning curves\ndef summarize_diagnostics(histories):\n\tfor i in range(len(histories)):\n\t\t# plot loss\n\t\tplt.subplot(2, 1, 1)\n\t\tplt.title('Cross Entropy Loss')\n\t\tplt.plot(histories[i].history['loss'], color='blue', label='train')\n\t\tplt.plot(histories[i].history['val_loss'], color='orange', label='test')\n\t\t# plot accuracy\n\t\tplt.subplot(2, 1, 2)\n\t\tplt.title('Classification Accuracy')\n\t\tplt.plot(histories[i].history['accuracy'], color='blue', label='train')\n\t\tplt.plot(histories[i].history['val_accuracy'], color='orange', label='test')\n\tplt.show()\n \n # summarize model performance\ndef summarize_performance(scores):\n\t# print summary\n\tprint('Accuracy: mean=%.3f std=%.3f, n=%d' % (mean(scores)*100, std(scores)*100, len(scores)))\n\t# box and whisker plots of results\n\tplt.boxplot(scores)\n\tplt.show()", "_____no_output_____" ] ], [ [ "**Complete Example**\nWe need a function that will drive the test harness.", "_____no_output_____" ] ], [ [ "# run the test harness for evaluating a model\ndef run_test_harness():\n\t# load dataset\n\ttrainX, trainY, testX, testY = load_dataset()\n\t# prepare pixel data\n\ttrainX, testX = prep_pixels(trainX, testX)\n\t# evaluate model\n\tscores, histories = evaluate_model(trainX, trainY)\n\t# learning curves\n\tsummarize_diagnostics(histories)\n\t# summarize estimated performance\n\tsummarize_performance(scores)\n \n# entry point, run the test harness\nrun_test_harness()", "> 98.517\n> 98.667\n> 98.508\n> 98.808\n> 98.750\n" ] ], [ [ "**How to Develop an Improved Model**\n\nook at areas of model configuration that often result in an improvement\nThe first is a change to the learning algorithm, and the second is an increase in the depth of the model", "_____no_output_____" ], [ "**Improvement to Learning**\n\napproach that can rapidly accelerate the learning of a model and can result in large performance improvements is batch normalization. \n\nWe will evaluate the effect that batch normalization has on our baseline model.\n\n\nSo i am going to use the same set of code that i have used earlier for load & train & test the dataset\nscaling the pixel \ndefining the CNN model\nevaluate using K -FOLD CROSS VALIDATION \nPlotting & summarising \n\nin tehbaove steps the code for the 3rd step (Defining CNN model ) has be changed just to include the code required for Batch normalisation \n\nthe full code to improve the modle has been presneted to you below ", "_____no_output_____" ] ], [ [ "\n# cnn model with batch normalization for mnist\nfrom numpy import mean\nfrom numpy import std\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import KFold\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.layers import BatchNormalization\n \n# load train and test dataset\ndef load_dataset():\n\t# load dataset\n\t(trainX, trainY), (testX, testY) = mnist.load_data()\n\t# reshape dataset to have a single channel\n\ttrainX = trainX.reshape((trainX.shape[0], 28, 28, 1))\n\ttestX = testX.reshape((testX.shape[0], 28, 28, 1))\n\t# one hot encode target values\n\ttrainY = to_categorical(trainY)\n\ttestY = to_categorical(testY)\n\treturn trainX, trainY, testX, testY\n \n# scale pixels\ndef prep_pixels(train, test):\n\t# convert from integers to floats\n\ttrain_norm = train.astype('float32')\n\ttest_norm = test.astype('float32')\n\t# normalize to range 0-1\n\ttrain_norm = train_norm / 255.0\n\ttest_norm = test_norm / 255.0\n\t# return normalized images\n\treturn train_norm, test_norm\n \n# define cnn model\ndef define_model():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))\n\tmodel.add(BatchNormalization())\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(BatchNormalization())\n\tmodel.add(Dense(10, activation='softmax'))\n\t# compile model\n\topt = SGD(learning_rate=0.01, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\treturn model\n \n# evaluate a model using k-fold cross-validation\ndef evaluate_model(dataX, dataY, n_folds=5):\n\tscores, histories = list(), list()\n\t# prepare cross validation\n\tkfold = KFold(n_folds, shuffle=True, random_state=1)\n\t# enumerate splits\n\tfor train_ix, test_ix in kfold.split(dataX):\n\t\t# define model\n\t\tmodel = define_model()\n\t\t# select rows for train and test\n\t\ttrainX, trainY, testX, testY = dataX[train_ix], dataY[train_ix], dataX[test_ix], dataY[test_ix]\n\t\t# fit model\n\t\thistory = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX, testY), verbose=0)\n\t\t# evaluate model\n\t\t_, acc = model.evaluate(testX, testY, verbose=0)\n\t\tprint('> %.3f' % (acc * 100.0))\n\t\t# stores scores\n\t\tscores.append(acc)\n\t\thistories.append(history)\n\treturn scores, histories\n \n# plot diagnostic learning curves\ndef summarize_diagnostics(histories):\n\tfor i in range(len(histories)):\n\t\t# plot loss\n\t\tplt.subplot(2, 1, 1)\n\t\tplt.title('Cross Entropy Loss')\n\t\tplt.plot(histories[i].history['loss'], color='blue', label='train')\n\t\tplt.plot(histories[i].history['val_loss'], color='orange', label='test')\n\t\t# plot accuracy\n\t\tplt.subplot(2, 1, 2)\n\t\tplt.title('Classification Accuracy')\n\t\tplt.plot(histories[i].history['accuracy'], color='blue', label='train')\n\t\tplt.plot(histories[i].history['val_accuracy'], color='orange', label='test')\n\tplt.show()\n \n# summarize model performance\ndef summarize_performance(scores):\n\t# print summary\n\tprint('Accuracy: mean=%.3f std=%.3f, n=%d' % (mean(scores)*100, std(scores)*100, len(scores)))\n\t# box and whisker plots of results\n\tplt.boxplot(scores)\n\tplt.show()\n \n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# load dataset\n\ttrainX, trainY, testX, testY = load_dataset()\n\t# prepare pixel data\n\ttrainX, testX = prep_pixels(trainX, testX)\n\t# evaluate model\n\tscores, histories = evaluate_model(trainX, trainY)\n\t# learning curves\n\tsummarize_diagnostics(histories)\n\t# summarize estimated performance\n\tsummarize_performance(scores)\n \n# entry point, run the test harness\nrun_test_harness()", "> 98.700\n> 98.717\n> 98.842\n> 98.767\n> 98.758\n" ] ], [ [ "From the above we can see that intially we had the accuracy as 98.65 and now after batch normalisation (improving the model) the accuracy obtained is 98.757 \n\n\nfuther i am going to try to improve the model by increasing the model depth ", "_____no_output_____" ], [ "**Increase in Model Depth**\n\nThere are many ways to change the model configuration in order to explore improvements over the baseline model.\n\nWe can increase the depth of the feature extractor part of the model, following a VGG-like pattern of adding more convolutional and pooling layers with the same sized filter, while increasing the number of filters. In this case, we will add a double convolutional layer with 64 filters each, followed by another max pooling laye", "_____no_output_____" ] ], [ [ "\n# deeper cnn model for mnist\nfrom numpy import mean\nfrom numpy import std\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import KFold\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.optimizers import SGD\n \n# load train and test dataset\ndef load_dataset():\n\t# load dataset\n\t(trainX, trainY), (testX, testY) = mnist.load_data()\n\t# reshape dataset to have a single channel\n\ttrainX = trainX.reshape((trainX.shape[0], 28, 28, 1))\n\ttestX = testX.reshape((testX.shape[0], 28, 28, 1))\n\t# one hot encode target values\n\ttrainY = to_categorical(trainY)\n\ttestY = to_categorical(testY)\n\treturn trainX, trainY, testX, testY\n \n# scale pixels\ndef prep_pixels(train, test):\n\t# convert from integers to floats\n\ttrain_norm = train.astype('float32')\n\ttest_norm = test.astype('float32')\n\t# normalize to range 0-1\n\ttrain_norm = train_norm / 255.0\n\ttest_norm = test_norm / 255.0\n\t# return normalized images\n\treturn train_norm, test_norm\n \n# define cnn model\ndef define_model():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(10, activation='softmax'))\n\t# compile model\n\topt = SGD(learning_rate=0.01, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\treturn model\n \n# evaluate a model using k-fold cross-validation\ndef evaluate_model(dataX, dataY, n_folds=5):\n\tscores, histories = list(), list()\n\t# prepare cross validation\n\tkfold = KFold(n_folds, shuffle=True, random_state=1)\n\t# enumerate splits\n\tfor train_ix, test_ix in kfold.split(dataX):\n\t\t# define model\n\t\tmodel = define_model()\n\t\t# select rows for train and test\n\t\ttrainX, trainY, testX, testY = dataX[train_ix], dataY[train_ix], dataX[test_ix], dataY[test_ix]\n\t\t# fit model\n\t\thistory = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX, testY), verbose=0)\n\t\t# evaluate model\n\t\t_, acc = model.evaluate(testX, testY, verbose=0)\n\t\tprint('> %.3f' % (acc * 100.0))\n\t\t# stores scores\n\t\tscores.append(acc)\n\t\thistories.append(history)\n\treturn scores, histories\n \n# plot diagnostic learning curves\ndef summarize_diagnostics(histories):\n\tfor i in range(len(histories)):\n\t\t# plot loss\n\t\tplt.subplot(2, 1, 1)\n\t\tplt.title('Cross Entropy Loss')\n\t\tplt.plot(histories[i].history['loss'], color='blue', label='train')\n\t\tplt.plot(histories[i].history['val_loss'], color='orange', label='test')\n\t\t# plot accuracy\n\t\tplt.subplot(2, 1, 2)\n\t\tplt.title('Classification Accuracy')\n\t\tplt.plot(histories[i].history['accuracy'], color='blue', label='train')\n\t\tplt.plot(histories[i].history['val_accuracy'], color='orange', label='test')\n\tplt.show()\n \n# summarize model performance\ndef summarize_performance(scores):\n\t# print summary\n\tprint('Accuracy: mean=%.3f std=%.3f, n=%d' % (mean(scores)*100, std(scores)*100, len(scores)))\n\t# box and whisker plots of results\n\tplt.boxplot(scores)\n\tplt.show()\n \n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# load dataset\n\ttrainX, trainY, testX, testY = load_dataset()\n\t# prepare pixel data\n\ttrainX, testX = prep_pixels(trainX, testX)\n\t# evaluate model\n\tscores, histories = evaluate_model(trainX, trainY)\n\t# learning curves\n\tsummarize_diagnostics(histories)\n\t# summarize estimated performance\n\tsummarize_performance(scores)\n \n# entry point, run the test harness\nrun_test_harness()", "> 98.933\n> 99.008\n> 98.708\n> 99.192\n> 98.917\n" ] ], [ [ "**How to Finalize the Model and Make Predictions**\n\nThe process of model improvement may continue for as long as we have ideas and the time and resources to test them out.\n\nFirst, we will finalize our model, but fitting a model on the entire training dataset and saving the model to file for later use. We will then load the model and evaluate its performance on the hold out test dataset to get an idea of how well the chosen model actually performs in practice. Finally, we will use the saved model to make a prediction on a single image.", "_____no_output_____" ], [ "**Save Final Model**\n\nA final model is typically fit on all available data, such as the combination of all train and test dataset.", "_____no_output_____" ] ], [ [ "\n# save the final model to file\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.optimizers import SGD\n \n# load train and test dataset\ndef load_dataset():\n\t# load dataset\n\t(trainX, trainY), (testX, testY) = mnist.load_data()\n\t# reshape dataset to have a single channel\n\ttrainX = trainX.reshape((trainX.shape[0], 28, 28, 1))\n\ttestX = testX.reshape((testX.shape[0], 28, 28, 1))\n\t# one hot encode target values\n\ttrainY = to_categorical(trainY)\n\ttestY = to_categorical(testY)\n\treturn trainX, trainY, testX, testY\n \n# scale pixels\ndef prep_pixels(train, test):\n\t# convert from integers to floats\n\ttrain_norm = train.astype('float32')\n\ttest_norm = test.astype('float32')\n\t# normalize to range 0-1\n\ttrain_norm = train_norm / 255.0\n\ttest_norm = test_norm / 255.0\n\t# return normalized images\n\treturn train_norm, test_norm\n \n# define cnn model\ndef define_model():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(10, activation='softmax'))\n\t# compile model\n\topt = SGD(learning_rate=0.01, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\treturn model\n \n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# load dataset\n\ttrainX, trainY, testX, testY = load_dataset()\n\t# prepare pixel data\n\ttrainX, testX = prep_pixels(trainX, testX)\n\t# define model\n\tmodel = define_model()\n\t# fit model\n\tmodel.fit(trainX, trainY, epochs=10, batch_size=32, verbose=0)\n\t# save model\n\tmodel.save('final_model.h5')\n \n# entry point, run the test harness\nrun_test_harness()", "_____no_output_____" ] ], [ [ "**Evaluate Final Model**\n\nWe can now load the final model and evaluate it on the hold out test dataset.\n\nThis is something we might do if we were interested in presenting the performance of the chosen model to project stakeholders.", "_____no_output_____" ] ], [ [ "\n# evaluate the deep model on the test dataset\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.utils import to_categorical\n \n# load train and test dataset\ndef load_dataset():\n\t# load dataset\n\t(trainX, trainY), (testX, testY) = mnist.load_data()\n\t# reshape dataset to have a single channel\n\ttrainX = trainX.reshape((trainX.shape[0], 28, 28, 1))\n\ttestX = testX.reshape((testX.shape[0], 28, 28, 1))\n\t# one hot encode target values\n\ttrainY = to_categorical(trainY)\n\ttestY = to_categorical(testY)\n\treturn trainX, trainY, testX, testY\n \n# scale pixels\ndef prep_pixels(train, test):\n\t# convert from integers to floats\n\ttrain_norm = train.astype('float32')\n\ttest_norm = test.astype('float32')\n\t# normalize to range 0-1\n\ttrain_norm = train_norm / 255.0\n\ttest_norm = test_norm / 255.0\n\t# return normalized images\n\treturn train_norm, test_norm\n \n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# load dataset\n\ttrainX, trainY, testX, testY = load_dataset()\n\t# prepare pixel data\n\ttrainX, testX = prep_pixels(trainX, testX)\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# evaluate model on test dataset\n\t_, acc = model.evaluate(testX, testY, verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n \n# entry point, run the test harness\nrun_test_harness()", "> 99.280\n" ] ], [ [ "Make Prediction\nWe can use our saved model to make a prediction on new images.\n\nThe model assumes that new images are grayscale, that they have been aligned so that one image contains one centered handwritten digit, and that the size of the image is square with the size 28×28 pixels.", "_____no_output_____" ] ], [ [ "from google.colab import files\nuploaded = files.upload()", "_____no_output_____" ] ], [ [ "i have uploaded the sample_image2 we apply the saved model on that image & we will check whether it classifies the image & predicts it correctly", "_____no_output_____" ] ], [ [ "\n# make a prediction for a new image.\nfrom numpy import argmax\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n\n\n \n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, grayscale=True, target_size=(28, 28))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 1 channel\n\timg = img.reshape(1, 28, 28, 1)\n\t# prepare pixel data\n\timg = img.astype('float32')\n\timg = img / 255.0\n\treturn img\n \n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image2.png')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tpredict_value = model.predict(img)\n\tdigit = argmax(predict_value)\n\tprint(digit)\n \n# entry point, run the example\nrun_example()", "/usr/local/lib/python3.7/dist-packages/keras_preprocessing/image/utils.py:107: UserWarning: grayscale is deprecated. Please use color_mode = \"grayscale\"\n warnings.warn('grayscale is deprecated. Please use '\n" ] ], [ [ "so the sample image 2 that i have uploaded has been predicted properly ", "_____no_output_____" ] ], [ [ "from google.colab import files\nuploaded = files.upload()", "_____no_output_____" ] ], [ [ "i have uploaded the sample_image1 which we apply the saved model on that image & we will check whether it classifies the image & predicts it correctly", "_____no_output_____" ] ], [ [ "# make a prediction for a new image.\nfrom numpy import argmax\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n\n\n \n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, grayscale=True, target_size=(28, 28))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 1 channel\n\timg = img.reshape(1, 28, 28, 1)\n\t# prepare pixel data\n\timg = img.astype('float32')\n\timg = img / 255.0\n\treturn img\n \n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image1.png')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tpredict_value = model.predict(img)\n\tdigit = argmax(predict_value)\n\tprint(digit)\n \n# entry point, run the example\nrun_example()", "8\n" ] ], [ [ "so the sample image 1 that i have uploaded has been predicted properly ", "_____no_output_____" ] ], [ [ "from google.colab import files\nuploaded = files.upload()", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "# make a prediction for a new image.\nfrom numpy import argmax\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n\n\n \n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, grayscale=True, target_size=(28, 28))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 1 channel\n\timg = img.reshape(1, 28, 28, 1)\n\t# prepare pixel data\n\timg = img.astype('float32')\n\timg = img / 255.0\n\treturn img\n \n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image3.png')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tpredict_value = model.predict(img)\n\tdigit = argmax(predict_value)\n\tprint(digit)\n \n# entry point, run the example\nrun_example()", "WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fd2cf4a0f80> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n9\n" ], [ "from google.colab import files\nuploaded = files.upload()", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "# make a prediction for a new image.\nfrom numpy import argmax\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n\n\n \n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, grayscale=True, target_size=(28, 28))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 1 channel\n\timg = img.reshape(1, 28, 28, 1)\n\t# prepare pixel data\n\timg = img.astype('float32')\n\timg = img / 255.0\n\treturn img\n \n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image4.png')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tpredict_value = model.predict(img)\n\tdigit = argmax(predict_value)\n\tprint(digit)\n \n# entry point, run the example\nrun_example()", "WARNING:tensorflow:6 out of the last 6 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fd2cff10680> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n0\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4aee7108acfccdb9a40bd518c448f9223b7551dd
182,209
ipynb
Jupyter Notebook
1<4-1.ipynb
bhuiyanmobasshir94/CID
4df62387b3b82bf65158b344436f9a2a726c0304
[ "Apache-2.0" ]
3
2022-02-12T15:42:18.000Z
2022-02-23T06:50:30.000Z
1<4-1.ipynb
bhuiyanmobasshir94/CID
4df62387b3b82bf65158b344436f9a2a726c0304
[ "Apache-2.0" ]
null
null
null
1<4-1.ipynb
bhuiyanmobasshir94/CID
4df62387b3b82bf65158b344436f9a2a726c0304
[ "Apache-2.0" ]
null
null
null
129.963623
119,578
0.805575
[ [ [ "<a href=\"https://colab.research.google.com/github/bhuiyanmobasshir94/Cow-weight-and-Breed-Prediction/blob/main/notebooks/031_dec.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport sys\nimport os\nimport PIL\nimport PIL.Image\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras import layers\nimport tensorflow_datasets as tfds\nimport pathlib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing", "_____no_output_____" ], [ "## Globals \nYT_IMAGE_TO_TAKE = 4", "_____no_output_____" ], [ "images_dataset_url = \"https://cv-datasets-2021.s3.amazonaws.com/images.tar.gz\"\nimages_data_dir = tf.keras.utils.get_file(origin=images_dataset_url,\n fname='images',\n untar=True)\nimages_data_dir = pathlib.Path(images_data_dir)", "Downloading data from https://cv-datasets-2021.s3.amazonaws.com/images.tar.gz\n833052672/833046463 [==============================] - 14s 0us/step\n833060864/833046463 [==============================] - 14s 0us/step\n" ], [ "yt_images_dataset_url = \"https://cv-datasets-2021.s3.amazonaws.com/yt_images.tar.gz\"\nyt_images_data_dir = tf.keras.utils.get_file(origin=yt_images_dataset_url,\n fname='yt_images',\n untar=True)\nyt_images_data_dir = pathlib.Path(yt_images_data_dir)", "Downloading data from https://cv-datasets-2021.s3.amazonaws.com/yt_images.tar.gz\n4026998784/4026992587 [==============================] - 86s 0us/step\n4027006976/4026992587 [==============================] - 86s 0us/step\n" ], [ "if sys.platform == 'darwin':\n os.system(f\"dot_clean {images_data_dir}\")\n os.system(f\"dot_clean {yt_images_data_dir}\")\nelif sys.platform.startswith(\"lin\"):\n os.system(f\"cd {images_data_dir} && find . -type f -name '._*' -delete\")\n os.system(f\"cd {yt_images_data_dir} && find . -type f -name '._*' -delete\")\n", "_____no_output_____" ], [ "image_count = len(list(images_data_dir.glob('*/*.jpg')))\nprint(image_count)", "2056\n" ], [ "yt_image_count = len(list(yt_images_data_dir.glob('*/*.jpg')))\nprint(yt_image_count)", "15843\n" ], [ "df = pd.read_csv(\"https://cv-datasets-2021.s3.amazonaws.com/dataset.csv\")\ndf.shape", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "df.head(2)", "_____no_output_____" ], [ "images = list(images_data_dir.glob('*/*.jpg'))\nyt_images = list(yt_images_data_dir.glob('*/*.jpg'))", "_____no_output_____" ], [ "min_height = 0\nmax_height = 0\nmin_width = 0\nmax_width = 0\nfor i, image in enumerate(images):\n w, h = PIL.Image.open(str(image)).size\n if i == 0:\n min_height = h\n max_height = h\n min_width = w\n max_width = w\n \n if h <= min_height:\n min_height = h\n if h >= max_height:\n max_height = h\n\n if w <= min_width:\n min_width = w\n if w >= max_width:\n max_width = w\n\nprint(f\"min_height: {min_height}\")\nprint(f\"min_width: {min_width}\")\nprint(f\"max_height: {max_height}\")\nprint(f\"max_width: {max_width}\")", "min_height: 450\nmin_width: 800\nmax_height: 675\nmax_width: 1200\n" ], [ "min_height = 0\nmax_height = 0\nmin_width = 0\nmax_width = 0\nfor i, image in enumerate(yt_images):\n w, h = PIL.Image.open(str(image)).size\n if i == 0:\n min_height = h\n max_height = h\n min_width = w\n max_width = w\n\n if h <= min_height:\n min_height = h\n if h >= max_height:\n max_height = h\n\n if w <= min_width:\n min_width = w\n if w >= max_width:\n max_width = w\n\nprint(f\"min_height: {min_height}\")\nprint(f\"min_width: {min_width}\")\nprint(f\"max_height: {max_height}\")\nprint(f\"max_width: {max_width}\")", "min_height: 720\nmin_width: 1280\nmax_height: 720\nmax_width: 1280\n" ], [ "f_df = pd.DataFrame(columns = ['file_path', 'teeth', 'age_in_year', 'breed', 'height_in_inch', 'weight_in_kg'])\nfor index, row in df.iterrows():\n images = list(images_data_dir.glob(f\"{row['sku']}/*.jpg\"))\n yt_images = list(yt_images_data_dir.glob(f\"{row['sku']}/*.jpg\"))\n\n for image in images:\n f_df = f_df.append({'file_path' : image, 'teeth' : row['teeth'], 'age_in_year' : row['age_in_year'], 'breed': row['breed'], 'height_in_inch': row['height_in_inch'], 'weight_in_kg': row['weight_in_kg']}, \n ignore_index = True)\n \n for idx, image in enumerate(yt_images):\n if idx == (YT_IMAGE_TO_TAKE - 1):\n break\n f_df = f_df.append({'file_path' : image, 'teeth' : row['teeth'], 'age_in_year' : row['age_in_year'], 'breed': row['breed'], 'height_in_inch': row['height_in_inch'], 'weight_in_kg': row['weight_in_kg']}, \n ignore_index = True)\n", "_____no_output_____" ], [ "f_df.shape", "_____no_output_____" ], [ "f_df.head(1)", "_____no_output_____" ], [ "def label_encode(df):\n teeth_le = preprocessing.LabelEncoder()\n df['teeth']= teeth_le.fit_transform(df['teeth'])\n breed_le = preprocessing.LabelEncoder()\n df['breed']= breed_le.fit_transform(df['breed'])\n age_in_year_le = preprocessing.LabelEncoder()\n df['age_in_year']= age_in_year_le.fit_transform(df['age_in_year'])\n print(teeth_le.classes_)\n print(breed_le.classes_)\n print(age_in_year_le.classes_)\n return df\n\ndef inverse_transform(le, series=[]):\n return le.inverse_transform(series)\n", "_____no_output_____" ], [ "f_df = label_encode(f_df)", "[2 4 6]\n['BRAHMA' 'HOSTINE_CROSS' 'LOCAL' 'MIR_KADIM' 'PABNA_BREED'\n 'RED_CHITTAGONG' 'SAHIWAL' 'SINDHI']\n[2. 2.5 3. ]\n" ], [ "# train_df, valid_test_df = train_test_split(f_df, test_size=0.3)\n# validation_df, test_df = train_test_split(valid_test_df, test_size=0.3)\n# print(f\"train_df: {train_df.shape}\")\n# print(f\"validation_df: {validation_df.shape}\")\n# print(f\"test_df: {test_df.shape}\")\n\ntrain_df, test_df = train_test_split(f_df, test_size=0.1)\nprint(f\"train_df: {train_df.shape}\")\nprint(f\"test_df: {test_df.shape}\")", "train_df: (3226, 6)\ntest_df: (359, 6)\n" ], [ "# min_height: 450\n# min_width: 800\n\n# input: [image, teeth]\n# outpur: [age_in_year, breed, height_in_inch, weight_in_kg]\n\n# class CustomDataGen(tf.keras.utils.Sequence):\n \n# def __init__(self, df, X_col, y_col,\n# batch_size,\n# input_size=(450, 800, 3), # (input_height, input_width, input_channel)\n# shuffle=True):\n \n# self.df = df.copy()\n# self.X_col = X_col\n# self.y_col = y_col\n# self.batch_size = batch_size\n# self.input_size = input_size\n# self.shuffle = shuffle\n \n# self.n = len(self.df)\n# # self.n_teeth = df[X_col['teeth']].max()\n# # self.n_breed = df[y_col['breed']].nunique()\n \n# def on_epoch_end(self):\n# if self.shuffle:\n# self.df = self.df.sample(frac=1).reset_index(drop=True)\n \n# def __get_input(self, path, target_size):\n# image = tf.keras.preprocessing.image.load_img(path)\n# image_arr = tf.keras.preprocessing.image.img_to_array(image)\n\n# # image_arr = image_arr[ymin:ymin+h, xmin:xmin+w]\n# image_arr = tf.image.resize(image_arr,(target_size[0], target_size[1])).numpy()\n\n# return image_arr/255.\n \n# def __get_output(self, label, num_classes):\n# return tf.keras.utils.to_categorical(label, num_classes=num_classes)\n \n# def __get_data(self, batches):\n# # Generates data containing batch_size samples\n\n# path_batch = batches[self.X_col['file_path']] \n# # teeth_batch = batches[self.X_col['teeth']]\n\n# # breed_batch = batches[self.y_col['breed']]\n# weight_in_kg_batch = batches[self.y_col['weight_in_kg']]\n# height_in_inch_batch = batches[self.y_col['height_in_inch']]\n# age_in_year_batch = batches[self.y_col['age_in_year']]\n\n# X0 = np.asarray([self.__get_input(x, self.input_size) for x in path_batch])\n\n# # y0_batch = np.asarray([self.__get_output(y, self.n_teeth) for y in teeth_batch])\n# # y1_batch = np.asarray([self.__get_output(y, self.n_breed) for y in breed_batch])\n\n# y0 = np.asarray([tf.cast(y, tf.float32) for y in weight_in_kg_batch])\n# y1 = np.asarray([tf.cast(y, tf.float32) for y in height_in_inch_batch])\n# y2 = np.asarray([tf.cast(y, tf.float32) for y in age_in_year_batch])\n\n# return X0, tuple([y0, y1, y2])\n \n# def __getitem__(self, index):\n \n# batches = self.df[index * self.batch_size:(index + 1) * self.batch_size]\n# X, y = self.__get_data(batches) \n# return X, y\n \n# def __len__(self):\n# return self.n // self.batch_size", "_____no_output_____" ], [ "# traingen = CustomDataGen(train_df,\n# X_col={'file_path':'file_path', 'teeth': 'teeth'},\n# y_col={'breed': 'breed', 'weight_in_kg': 'weight_in_kg', 'height_in_inch': 'height_in_inch', 'age_in_year': 'age_in_year'},\n# batch_size=128, input_size=(450, 800, 3))", "_____no_output_____" ], [ "# testgen = CustomDataGen(test_df,\n# X_col={'file_path':'file_path', 'teeth': 'teeth'},\n# y_col={'breed': 'breed', 'weight_in_kg': 'weight_in_kg', 'height_in_inch': 'height_in_inch', 'age_in_year': 'age_in_year'},\n# batch_size=128, input_size=(450, 800, 3))", "_____no_output_____" ], [ "# validgen = CustomDataGen(validation_df,\n# X_col={'file_path':'file_path', 'teeth': 'teeth'},\n# y_col={'breed': 'breed', 'weight_in_kg': 'weight_in_kg', 'height_in_inch': 'height_in_inch', 'age_in_year': 'age_in_year'},\n# batch_size=128, input_size=(450, 800, 3))", "_____no_output_____" ], [ "def __get_input(path, target_size):\n image = tf.keras.preprocessing.image.load_img(path)\n image_arr = tf.keras.preprocessing.image.img_to_array(image)\n image_arr = tf.image.resize(image_arr,(target_size[0], target_size[1])).numpy()\n return image_arr/255.\n\ndef data_loader(df, image_size=(450, 800, 3)):\n y0 = tf.cast(df.weight_in_kg, tf.float32)\n print(y0.shape)\n y1 = tf.cast(df.height_in_inch, tf.float32)\n print(y1.shape)\n # y2 = tf.cast(df.age_in_year, tf.float32)\n y2 = keras.utils.to_categorical(df.age_in_year)\n print(y2.shape)\n y3 = keras.utils.to_categorical(df.breed)\n print(y3.shape)\n\n path_batch = df.file_path\n X0 = tf.cast([__get_input(x, image_size) for x in path_batch], tf.float32)\n print(X0.shape)\n X1 = keras.utils.to_categorical(df.teeth)\n print(X1.shape)\n\n return (X0, X1), (y0, y1, y2, y3)", "_____no_output_____" ], [ "(X0, X1), (y0, y1, y2, y3) = data_loader(train_df, (150, 150, 3))", "(3226,)\n(3226,)\n(3226, 3)\n(3226, 8)\n(3226, 150, 150, 3)\n(3226, 3)\n" ], [ "# input = keras.Input(shape=(128, 128, 3), name=\"original_img\")\n# x = layers.Conv2D(64, 3, activation=\"relu\")(input)\n# x = layers.Conv2D(128, 3, activation=\"relu\")(x)\n# x = layers.MaxPooling2D(3)(x)\n# x = layers.Conv2D(128, 3, activation=\"relu\")(x)\n# x = layers.Conv2D(64, 3, activation=\"relu\")(x)\n# x = layers.GlobalMaxPooling2D()(x)\n\ninput0 = keras.Input(shape=(150, 150, 3), name=\"img\")\nx = layers.Conv2D(32, 3, activation=\"relu\")(input0)\nx = layers.MaxPooling2D(2)(x)\nx = layers.Conv2D(32, 3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(2)(x)\nx = layers.Conv2D(64, 3, activation=\"relu\")(x)\nx = layers.GlobalMaxPooling2D()(x)\n\n# input1 = keras.Input(shape=(3,), name=\"teeth\")\n\n\nout_a = keras.layers.Dense(1, activation='linear', name='wt_rg')(x)\nout_b = keras.layers.Dense(1, activation='linear', name='ht_rg')(x)\n# out_c = keras.layers.Dense(1, activation='linear', name='ag_rg')(x)\nout_c = keras.layers.Dense(3, activation='softmax', name='ag_3cls')(x)\nout_d = keras.layers.Dense(8, activation='softmax', name='brd_8cls')(x)\n\nencoder = keras.Model( inputs = input0 , outputs = [out_a, out_b, out_c, out_d], name=\"encoder\")", "_____no_output_____" ], [ "encoder.compile(\n loss = {\n \"wt_rg\": tf.keras.losses.MeanSquaredError(),\n \"ht_rg\": tf.keras.losses.MeanSquaredError(),\n # \"ag_rg\": tf.keras.losses.MeanSquaredError()\n \"ag_3cls\": tf.keras.losses.CategoricalCrossentropy(),\n \"brd_8cls\": tf.keras.losses.CategoricalCrossentropy()\n },\n\n metrics = {\n \"wt_rg\": 'mse',\n \"ht_rg\": 'mse',\n \"ag_3cls\": 'accuracy',\n \"brd_8cls\": 'accuracy'\n },\n\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001)\n)", "_____no_output_____" ], [ "encoder.fit(X0, [y0, y1, y2, y3], epochs=30, verbose=2, batch_size=32, validation_split=0.2)", "Epoch 1/30\n81/81 - 14s - loss: 71239.4531 - wt_rg_loss: 69169.8281 - ht_rg_loss: 2066.5310 - ag_3cls_loss: 1.1228 - brd_8cls_loss: 1.9676 - wt_rg_mse: 69169.8281 - ht_rg_mse: 2066.5310 - ag_3cls_accuracy: 0.1907 - brd_8cls_accuracy: 0.2225 - val_loss: 62893.9609 - val_wt_rg_loss: 61172.4844 - val_ht_rg_loss: 1718.7097 - val_ag_3cls_loss: 0.7986 - val_brd_8cls_loss: 1.9765 - val_wt_rg_mse: 61172.4844 - val_ht_rg_mse: 1718.7097 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 14s/epoch - 178ms/step\nEpoch 2/30\n81/81 - 3s - loss: 41962.5859 - wt_rg_loss: 41237.3359 - ht_rg_loss: 719.1522 - ag_3cls_loss: 0.8783 - brd_8cls_loss: 5.2167 - wt_rg_mse: 41237.3359 - ht_rg_mse: 719.1522 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 10999.4951 - val_wt_rg_loss: 10736.9385 - val_ht_rg_loss: 252.1356 - val_ag_3cls_loss: 0.7562 - val_brd_8cls_loss: 9.6649 - val_wt_rg_mse: 10736.9385 - val_ht_rg_mse: 252.1356 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 3/30\n81/81 - 3s - loss: 6469.2407 - wt_rg_loss: 6187.5010 - ht_rg_loss: 271.5002 - ag_3cls_loss: 0.8326 - brd_8cls_loss: 9.4047 - wt_rg_mse: 6187.5010 - ht_rg_mse: 271.5002 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5251.0410 - val_wt_rg_loss: 5220.6035 - val_ht_rg_loss: 22.8110 - val_ag_3cls_loss: 0.8248 - val_brd_8cls_loss: 6.8019 - val_wt_rg_mse: 5220.6035 - val_ht_rg_mse: 22.8110 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 39ms/step\nEpoch 4/30\n81/81 - 3s - loss: 5487.1382 - wt_rg_loss: 5461.9053 - ht_rg_loss: 19.5016 - ag_3cls_loss: 0.7965 - brd_8cls_loss: 4.9348 - wt_rg_mse: 5461.9053 - ht_rg_mse: 19.5016 - ag_3cls_accuracy: 0.7438 - brd_8cls_accuracy: 0.6868 - val_loss: 5243.9229 - val_wt_rg_loss: 5218.7241 - val_ht_rg_loss: 20.7916 - val_ag_3cls_loss: 0.7442 - val_brd_8cls_loss: 3.6625 - val_wt_rg_mse: 5218.7241 - val_ht_rg_mse: 20.7916 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 5/30\n81/81 - 3s - loss: 5491.6138 - wt_rg_loss: 5468.1226 - ht_rg_loss: 19.5821 - ag_3cls_loss: 0.7241 - brd_8cls_loss: 3.1849 - wt_rg_mse: 5468.1226 - ht_rg_mse: 19.5821 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5255.9204 - val_wt_rg_loss: 5231.6826 - val_ht_rg_loss: 20.9131 - val_ag_3cls_loss: 0.6941 - val_brd_8cls_loss: 2.6304 - val_wt_rg_mse: 5231.6826 - val_ht_rg_mse: 20.9131 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 42ms/step\nEpoch 6/30\n81/81 - 3s - loss: 5484.4688 - wt_rg_loss: 5462.1382 - ht_rg_loss: 19.5443 - ag_3cls_loss: 0.6576 - brd_8cls_loss: 2.1285 - wt_rg_mse: 5462.1382 - ht_rg_mse: 19.5443 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5233.8491 - val_wt_rg_loss: 5210.8672 - val_ht_rg_loss: 20.7759 - val_ag_3cls_loss: 0.6255 - val_brd_8cls_loss: 1.5809 - val_wt_rg_mse: 5210.8672 - val_ht_rg_mse: 20.7759 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 7/30\n81/81 - 3s - loss: 5491.5205 - wt_rg_loss: 5469.8281 - ht_rg_loss: 19.7537 - ag_3cls_loss: 0.6303 - brd_8cls_loss: 1.3073 - wt_rg_mse: 5469.8281 - ht_rg_mse: 19.7537 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5231.3491 - val_wt_rg_loss: 5208.8887 - val_ht_rg_loss: 20.6115 - val_ag_3cls_loss: 0.6242 - val_brd_8cls_loss: 1.2249 - val_wt_rg_mse: 5208.8887 - val_ht_rg_mse: 20.6115 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 42ms/step\nEpoch 8/30\n81/81 - 3s - loss: 5488.8394 - wt_rg_loss: 5467.2397 - ht_rg_loss: 19.7576 - ag_3cls_loss: 0.6194 - brd_8cls_loss: 1.2246 - wt_rg_mse: 5467.2397 - ht_rg_mse: 19.7576 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5260.1479 - val_wt_rg_loss: 5236.2700 - val_ht_rg_loss: 22.0472 - val_ag_3cls_loss: 0.6144 - val_brd_8cls_loss: 1.2152 - val_wt_rg_mse: 5236.2700 - val_ht_rg_mse: 22.0472 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 9/30\n81/81 - 3s - loss: 5486.9819 - wt_rg_loss: 5465.4614 - ht_rg_loss: 19.6847 - ag_3cls_loss: 0.6162 - brd_8cls_loss: 1.2186 - wt_rg_mse: 5465.4614 - ht_rg_mse: 19.6847 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5273.9834 - val_wt_rg_loss: 5251.3477 - val_ht_rg_loss: 20.8050 - val_ag_3cls_loss: 0.6159 - val_brd_8cls_loss: 1.2143 - val_wt_rg_mse: 5251.3477 - val_ht_rg_mse: 20.8050 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 43ms/step\nEpoch 10/30\n81/81 - 3s - loss: 5484.0747 - wt_rg_loss: 5462.3384 - ht_rg_loss: 19.9137 - ag_3cls_loss: 0.6163 - brd_8cls_loss: 1.2054 - wt_rg_mse: 5462.3384 - ht_rg_mse: 19.9137 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5241.5718 - val_wt_rg_loss: 5218.9463 - val_ht_rg_loss: 20.8057 - val_ag_3cls_loss: 0.6152 - val_brd_8cls_loss: 1.2050 - val_wt_rg_mse: 5218.9463 - val_ht_rg_mse: 20.8057 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 39ms/step\nEpoch 11/30\n81/81 - 3s - loss: 5475.7871 - wt_rg_loss: 5454.7998 - ht_rg_loss: 19.1725 - ag_3cls_loss: 0.6174 - brd_8cls_loss: 1.1974 - wt_rg_mse: 5454.7998 - ht_rg_mse: 19.1725 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5262.5591 - val_wt_rg_loss: 5239.7539 - val_ht_rg_loss: 20.9894 - val_ag_3cls_loss: 0.6266 - val_brd_8cls_loss: 1.1894 - val_wt_rg_mse: 5239.7539 - val_ht_rg_mse: 20.9894 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 43ms/step\nEpoch 12/30\n81/81 - 3s - loss: 5482.3730 - wt_rg_loss: 5461.0669 - ht_rg_loss: 19.5039 - ag_3cls_loss: 0.6170 - brd_8cls_loss: 1.1868 - wt_rg_mse: 5461.0669 - ht_rg_mse: 19.5039 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5222.7026 - val_wt_rg_loss: 5200.5552 - val_ht_rg_loss: 20.3575 - val_ag_3cls_loss: 0.6148 - val_brd_8cls_loss: 1.1748 - val_wt_rg_mse: 5200.5552 - val_ht_rg_mse: 20.3575 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 43ms/step\nEpoch 13/30\n81/81 - 3s - loss: 5480.8208 - wt_rg_loss: 5459.6572 - ht_rg_loss: 19.3662 - ag_3cls_loss: 0.6203 - brd_8cls_loss: 1.1779 - wt_rg_mse: 5459.6572 - ht_rg_mse: 19.3662 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5224.9541 - val_wt_rg_loss: 5202.8447 - val_ht_rg_loss: 20.3281 - val_ag_3cls_loss: 0.6145 - val_brd_8cls_loss: 1.1663 - val_wt_rg_mse: 5202.8447 - val_ht_rg_mse: 20.3281 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 14/30\n81/81 - 3s - loss: 5474.0107 - wt_rg_loss: 5452.7417 - ht_rg_loss: 19.4853 - ag_3cls_loss: 0.6176 - brd_8cls_loss: 1.1674 - wt_rg_mse: 5452.7417 - ht_rg_mse: 19.4853 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5363.3979 - val_wt_rg_loss: 5339.8887 - val_ht_rg_loss: 21.7348 - val_ag_3cls_loss: 0.6149 - val_brd_8cls_loss: 1.1602 - val_wt_rg_mse: 5339.8887 - val_ht_rg_mse: 21.7348 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 39ms/step\nEpoch 15/30\n81/81 - 3s - loss: 5468.7129 - wt_rg_loss: 5447.4453 - ht_rg_loss: 19.4934 - ag_3cls_loss: 0.6158 - brd_8cls_loss: 1.1590 - wt_rg_mse: 5447.4453 - ht_rg_mse: 19.4934 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5201.9116 - val_wt_rg_loss: 5179.1660 - val_ht_rg_loss: 20.9824 - val_ag_3cls_loss: 0.6158 - val_brd_8cls_loss: 1.1473 - val_wt_rg_mse: 5179.1660 - val_ht_rg_mse: 20.9824 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 39ms/step\nEpoch 16/30\n81/81 - 3s - loss: 5482.6104 - wt_rg_loss: 5460.5288 - ht_rg_loss: 20.3163 - ag_3cls_loss: 0.6189 - brd_8cls_loss: 1.1467 - wt_rg_mse: 5460.5288 - ht_rg_mse: 20.3163 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5277.6270 - val_wt_rg_loss: 5252.2739 - val_ht_rg_loss: 23.5817 - val_ag_3cls_loss: 0.6145 - val_brd_8cls_loss: 1.1558 - val_wt_rg_mse: 5252.2739 - val_ht_rg_mse: 23.5817 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 39ms/step\nEpoch 17/30\n81/81 - 3s - loss: 5486.6831 - wt_rg_loss: 5464.7041 - ht_rg_loss: 20.2209 - ag_3cls_loss: 0.6141 - brd_8cls_loss: 1.1439 - wt_rg_mse: 5464.7041 - ht_rg_mse: 20.2209 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5268.2759 - val_wt_rg_loss: 5243.4150 - val_ht_rg_loss: 23.0955 - val_ag_3cls_loss: 0.6319 - val_brd_8cls_loss: 1.1340 - val_wt_rg_mse: 5243.4150 - val_ht_rg_mse: 23.0955 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 18/30\n81/81 - 3s - loss: 5497.1807 - wt_rg_loss: 5475.1924 - ht_rg_loss: 20.2323 - ag_3cls_loss: 0.6210 - brd_8cls_loss: 1.1345 - wt_rg_mse: 5475.1924 - ht_rg_mse: 20.2323 - ag_3cls_accuracy: 0.7438 - brd_8cls_accuracy: 0.6868 - val_loss: 5286.1958 - val_wt_rg_loss: 5261.8188 - val_ht_rg_loss: 22.6348 - val_ag_3cls_loss: 0.6153 - val_brd_8cls_loss: 1.1277 - val_wt_rg_mse: 5261.8188 - val_ht_rg_mse: 22.6348 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 19/30\n81/81 - 3s - loss: 5455.6362 - wt_rg_loss: 5434.4727 - ht_rg_loss: 19.4327 - ag_3cls_loss: 0.6178 - brd_8cls_loss: 1.1154 - wt_rg_mse: 5434.4727 - ht_rg_mse: 19.4327 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5201.7720 - val_wt_rg_loss: 5179.6533 - val_ht_rg_loss: 20.3914 - val_ag_3cls_loss: 0.6143 - val_brd_8cls_loss: 1.1134 - val_wt_rg_mse: 5179.6533 - val_ht_rg_mse: 20.3914 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 20/30\n81/81 - 3s - loss: 5471.3730 - wt_rg_loss: 5449.6138 - ht_rg_loss: 20.0312 - ag_3cls_loss: 0.6164 - brd_8cls_loss: 1.1104 - wt_rg_mse: 5449.6138 - ht_rg_mse: 20.0312 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5370.0586 - val_wt_rg_loss: 5345.6353 - val_ht_rg_loss: 22.6816 - val_ag_3cls_loss: 0.6205 - val_brd_8cls_loss: 1.1206 - val_wt_rg_mse: 5345.6353 - val_ht_rg_mse: 22.6816 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 21/30\n81/81 - 3s - loss: 5484.9990 - wt_rg_loss: 5463.6064 - ht_rg_loss: 19.6585 - ag_3cls_loss: 0.6193 - brd_8cls_loss: 1.1132 - wt_rg_mse: 5463.6064 - ht_rg_mse: 19.6585 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5232.5146 - val_wt_rg_loss: 5210.8599 - val_ht_rg_loss: 19.9270 - val_ag_3cls_loss: 0.6141 - val_brd_8cls_loss: 1.1139 - val_wt_rg_mse: 5210.8599 - val_ht_rg_mse: 19.9270 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 22/30\n81/81 - 3s - loss: 5459.6533 - wt_rg_loss: 5439.0337 - ht_rg_loss: 18.8913 - ag_3cls_loss: 0.6161 - brd_8cls_loss: 1.1117 - wt_rg_mse: 5439.0337 - ht_rg_mse: 18.8913 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5240.8364 - val_wt_rg_loss: 5219.0088 - val_ht_rg_loss: 20.0966 - val_ag_3cls_loss: 0.6166 - val_brd_8cls_loss: 1.1131 - val_wt_rg_mse: 5219.0088 - val_ht_rg_mse: 20.0966 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 23/30\n81/81 - 3s - loss: 5458.9878 - wt_rg_loss: 5438.4639 - ht_rg_loss: 18.7892 - ag_3cls_loss: 0.6205 - brd_8cls_loss: 1.1141 - wt_rg_mse: 5438.4639 - ht_rg_mse: 18.7892 - ag_3cls_accuracy: 0.7438 - brd_8cls_accuracy: 0.6868 - val_loss: 5246.3525 - val_wt_rg_loss: 5224.7363 - val_ht_rg_loss: 19.8797 - val_ag_3cls_loss: 0.6154 - val_brd_8cls_loss: 1.1202 - val_wt_rg_mse: 5224.7363 - val_ht_rg_mse: 19.8797 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 24/30\n81/81 - 3s - loss: 5469.4141 - wt_rg_loss: 5448.3638 - ht_rg_loss: 19.3146 - ag_3cls_loss: 0.6215 - brd_8cls_loss: 1.1138 - wt_rg_mse: 5448.3638 - ht_rg_mse: 19.3146 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5235.3555 - val_wt_rg_loss: 5213.8911 - val_ht_rg_loss: 19.7399 - val_ag_3cls_loss: 0.6143 - val_brd_8cls_loss: 1.1101 - val_wt_rg_mse: 5213.8911 - val_ht_rg_mse: 19.7399 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 25/30\n81/81 - 3s - loss: 5454.3252 - wt_rg_loss: 5433.5537 - ht_rg_loss: 19.0462 - ag_3cls_loss: 0.6174 - brd_8cls_loss: 1.1084 - wt_rg_mse: 5433.5537 - ht_rg_mse: 19.0462 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5206.6562 - val_wt_rg_loss: 5185.3105 - val_ht_rg_loss: 19.6178 - val_ag_3cls_loss: 0.6147 - val_brd_8cls_loss: 1.1120 - val_wt_rg_mse: 5185.3105 - val_ht_rg_mse: 19.6178 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 26/30\n81/81 - 3s - loss: 5463.8589 - wt_rg_loss: 5442.9058 - ht_rg_loss: 19.2270 - ag_3cls_loss: 0.6184 - brd_8cls_loss: 1.1084 - wt_rg_mse: 5442.9058 - ht_rg_mse: 19.2270 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5287.7734 - val_wt_rg_loss: 5265.4077 - val_ht_rg_loss: 20.6312 - val_ag_3cls_loss: 0.6185 - val_brd_8cls_loss: 1.1155 - val_wt_rg_mse: 5265.4077 - val_ht_rg_mse: 20.6312 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 27/30\n81/81 - 3s - loss: 5454.2271 - wt_rg_loss: 5433.4736 - ht_rg_loss: 19.0254 - ag_3cls_loss: 0.6201 - brd_8cls_loss: 1.1094 - wt_rg_mse: 5433.4736 - ht_rg_mse: 19.0254 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5193.3291 - val_wt_rg_loss: 5172.1431 - val_ht_rg_loss: 19.4535 - val_ag_3cls_loss: 0.6186 - val_brd_8cls_loss: 1.1138 - val_wt_rg_mse: 5172.1431 - val_ht_rg_mse: 19.4535 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 28/30\n81/81 - 3s - loss: 5465.3550 - wt_rg_loss: 5443.3804 - ht_rg_loss: 20.2433 - ag_3cls_loss: 0.6165 - brd_8cls_loss: 1.1116 - wt_rg_mse: 5443.3804 - ht_rg_mse: 20.2433 - ag_3cls_accuracy: 0.7434 - brd_8cls_accuracy: 0.6868 - val_loss: 5254.5742 - val_wt_rg_loss: 5231.9805 - val_ht_rg_loss: 20.8594 - val_ag_3cls_loss: 0.6247 - val_brd_8cls_loss: 1.1100 - val_wt_rg_mse: 5231.9805 - val_ht_rg_mse: 20.8594 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 29/30\n81/81 - 3s - loss: 5451.1401 - wt_rg_loss: 5430.5181 - ht_rg_loss: 18.8925 - ag_3cls_loss: 0.6175 - brd_8cls_loss: 1.1117 - wt_rg_mse: 5430.5181 - ht_rg_mse: 18.8925 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5279.5103 - val_wt_rg_loss: 5258.3462 - val_ht_rg_loss: 19.4101 - val_ag_3cls_loss: 0.6189 - val_brd_8cls_loss: 1.1359 - val_wt_rg_mse: 5258.3462 - val_ht_rg_mse: 19.4101 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\nEpoch 30/30\n81/81 - 3s - loss: 5470.8901 - wt_rg_loss: 5449.2773 - ht_rg_loss: 19.8827 - ag_3cls_loss: 0.6174 - brd_8cls_loss: 1.1135 - wt_rg_mse: 5449.2773 - ht_rg_mse: 19.8827 - ag_3cls_accuracy: 0.7442 - brd_8cls_accuracy: 0.6868 - val_loss: 5238.6406 - val_wt_rg_loss: 5214.2842 - val_ht_rg_loss: 22.6288 - val_ag_3cls_loss: 0.6143 - val_brd_8cls_loss: 1.1135 - val_wt_rg_mse: 5214.2842 - val_ht_rg_mse: 22.6288 - val_ag_3cls_accuracy: 0.7399 - val_brd_8cls_accuracy: 0.6920 - 3s/epoch - 38ms/step\n" ], [ "# encoder.output\nkeras.utils.plot_model(encoder, \"encoder.png\", show_shapes=True)", "_____no_output_____" ], [ "(tX0, tX1), (ty0, ty1, ty2, ty3) = data_loader(test_df, (150, 150, 3))", "(359,)\n(359,)\n(359, 3)\n(359, 8)\n(359, 150, 150, 3)\n(359, 3)\n" ], [ "test_scores = encoder.evaluate(tX0, [ty0, ty1, ty2, ty3], verbose=2)", "12/12 - 0s - loss: 8229.9893 - wt_rg_loss: 8206.0010 - ht_rg_loss: 22.1719 - ag_3cls_loss: 0.6977 - brd_8cls_loss: 1.1181 - wt_rg_mse: 8206.0010 - ht_rg_mse: 22.1719 - ag_3cls_accuracy: 0.7326 - brd_8cls_accuracy: 0.6852 - 339ms/epoch - 28ms/step\n" ], [ "print(\"Test loss:\", test_scores[0])\nprint(\"Test accuracy:\", test_scores[1])", "Test loss: 8229.9892578125\nTest accuracy: 8206.0009765625\n" ], [ "p1, p2, p3 = encoder.predict([tf.expand_dims(tX0[0], 0), tf.expand_dims(tX1[0], 0)])", "_____no_output_____" ], [ "# print(p0);ty0[0]", "_____no_output_____" ], [ "print(p1);ty1[0]", "[[45.881622]]\n" ], [ "print(p2.argmax());ty2[0].argmax()", "0\n" ], [ "print(p3.argmax());ty3[0].argmax()", "2\n" ], [ "Cattle are commonly raised as livestock for meat (beef or veal, see beef cattle), for milk (see dairy cattle), and for hides, which are used to make leather. They are used as riding animals and draft animals (oxen or bullocks, which pull carts, plows and other implements). Another product of cattle is their dung, which can be used to create manure or fuel.", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aee84feddcf957733d6972e00700dc37c3b556f
8,212
ipynb
Jupyter Notebook
00 - Why Python.ipynb
Bayzidul/python_for_geosciences
de0d84f806fa9d76bccf2ef3b326c1919f1c2ef3
[ "CC-BY-3.0" ]
null
null
null
00 - Why Python.ipynb
Bayzidul/python_for_geosciences
de0d84f806fa9d76bccf2ef3b326c1919f1c2ef3
[ "CC-BY-3.0" ]
null
null
null
00 - Why Python.ipynb
Bayzidul/python_for_geosciences
de0d84f806fa9d76bccf2ef3b326c1919f1c2ef3
[ "CC-BY-3.0" ]
1
2020-08-30T13:51:05.000Z
2020-08-30T13:51:05.000Z
26.92459
403
0.60302
[ [ [ "# Python for Geosciences", "_____no_output_____" ], [ "Nikolay Koldunov\n\n\[email protected]", "_____no_output_____" ], [ "This is part of [**Python for Geosciences**](https://github.com/koldunovn/python_for_geosciences) notes.", "_____no_output_____" ], [ "# Why python?", "_____no_output_____" ], [ "## - It's easy to learn, easy to read and fast to develop", "_____no_output_____" ], [ "It is considered to be the language of choice for beginners, and proper code formatting is in the design of the language. This is especially useful when you remember, that we are the scientist not programmers. What we need is to have a language that can be learned quickly, but at the same time is powerful enough to satisfy our needs.", "_____no_output_____" ], [ "## - It's free and opensource. ", "_____no_output_____" ], [ "You will be able to use your scripts even if your institute does not have enough money to buy expensive software (MATLAB or IDL). You can make changes in the code, or at least have the possibility to look at the source code if you suspect that there is a bug.", "_____no_output_____" ], [ "## - It's multiplatform", "_____no_output_____" ], [ "You can find it on many systems, so you are not tied to Windows, Mac or Linux. It sounds great, but is not always the case: some modules will work only on limited number of operating systems (e.g. PyNGL, pyFerret).", "_____no_output_____" ], [ "## - It's general purpose language", "_____no_output_____" ], [ "You can use it not only for data processing and visualization, but also for system administration, web development, database programming and so on. It is relatively easy to make your code run in the parallel mode. Last but not the least - if you ever decide to leave academia your chances on the market are much better with some python skills.\n", "_____no_output_____" ], [ "# Downsides:", "_____no_output_____" ], [ "## - There is a smaller legacy code base", "_____no_output_____" ], [ "FORTRAN and Matlab are used for decades, and have a lot of libraries for all kinds of scientific needs. Although now main functionality is covered by python modules, there are still many specific areas where no python solution is available. This problem can be partly solved by python's integration with other languages ([MLabWrap](http://mlabwrap.sourceforge.net/), [F2py](http://www.f2py.com/)).", "_____no_output_____" ], [ "## - It's slow", "_____no_output_____" ], [ "... if you don't use vectorization or [Cython](http://www.cython.org/) or [numba](https://numba.pydata.org/) when loops are inevitable, or [dask](https://dask.pydata.org/en/latest/) when you have to work with parallel code. Critical parts still can be written in FORTRAN or C. ", "_____no_output_____" ], [ "More reading on this topic:\n\n* [10 Reasons Python Rocks for Research (And a Few Reasons it Doesn’t)](http://www.stat.washington.edu/~hoytak/blog/whypython.html)\n* [I used Matlab. Now I use Python](http://stevetjoa.com/305/)\n* [Eight Advantages of Python Over Matlab](http://phillipmfeldman.org/Python/Advantages_of_Python_Over_Matlab.html)", "_____no_output_____" ], [ "# Python in Earth Sciences", "_____no_output_____" ], [ "Lin, J. W.-B. (2012). [**Why Python Is the Next Wave in Earth Sciences Computing**](http://journals.ametsoc.org/doi/full/10.1175/BAMS-D-12-00148.1). *Bulletin of the American Meteorological Society*, 93(12), 1823–1824. doi:10.1175/BAMS-D-12-00148.1", "_____no_output_____" ], [ "- Though it has been around for two decades, it exploded into use in the atmospheric sciences just a few years ago after the development community converged upon the standard scientific packages (e.g., array handling) needed for atmospheric sciences work.\n\n- Much more robust and flexible workflow. Everything from data download to data analysys, visualization and finally writing a paper can be done in one environment.", "_____no_output_____" ], [ "- Ability to access innovations from industries outside of the Earth sciences (cloud computing, big data, mobile computing).\n\n- Institutional support includes groups at Lawrence Livermore National Laboratory’s Program for Climate Model Diagnosis and Intercomparison, NCAR’s Computer Information Systems Laboratory, and the British Atmospheric Data Centre.", "_____no_output_____" ], [ "## Further reading:", "_____no_output_____" ], [ "* [Lectures on Scientific Computing with Python.](https://github.com/jrjohansson/scientific-python-lectures#online-read-only-versions)\n* [Python Scientific Lecture Notes](http://scipy-lectures.github.io/)\n* [NumPy for Matlab Users](http://wiki.scipy.org/NumPy_for_Matlab_Users)\n* [Python data tools just keep getting better](http://strata.oreilly.com/2013/03/python-data-tools-just-keep-getting-better.html)\n* [Third Symposium on Advances in Modeling and Analysis Using Python](http://annual.ametsoc.org/2013/index.cfm/programs-and-events/conferences-and-symposia/third-symposium-on-advances-in-modeling-and-analysis-using-python/)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4aee89a1e402350f3be0e045ac3ced7abfe2947f
1,498
ipynb
Jupyter Notebook
Selenium_Test.ipynb
unKNOWN-G/Whatsapp-Automation
51fc98507e5ec18083126a0df36e34f980cfd657
[ "MIT" ]
null
null
null
Selenium_Test.ipynb
unKNOWN-G/Whatsapp-Automation
51fc98507e5ec18083126a0df36e34f980cfd657
[ "MIT" ]
2
2021-05-11T08:19:08.000Z
2021-05-11T10:17:14.000Z
Selenium_Test.ipynb
unKNOWN-G/Whatsapp-Automation
51fc98507e5ec18083126a0df36e34f980cfd657
[ "MIT" ]
1
2021-05-11T05:39:01.000Z
2021-05-11T05:39:01.000Z
18.268293
70
0.53004
[ [ [ "from selenium import webdriver", "_____no_output_____" ], [ "base_url = 'https://www.yahoo.com.sg'", "_____no_output_____" ], [ "chrome_browser = webdriver.Chrome('chromedriver.exe')", "_____no_output_____" ], [ "chrome_browser.get(base_url)", "_____no_output_____" ], [ "finance = chrome_browser.find_element_by_link_text('Finance')\nfinance.click()", "_____no_output_____" ], [ "search = chrome_browser.find_element_by_id('yfin-usr-qry')\nsearch.send_keys('STI')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
4aee8fef427b2f5c8ac2af1c9cf44721929393b6
482,966
ipynb
Jupyter Notebook
SMARF/[Hierarchical]_modelTrain3_(function_version).ipynb
AIML-Makgeolli/CpE-AIDL
edcf81078000646646f6091445279cb2895e245e
[ "Apache-2.0" ]
null
null
null
SMARF/[Hierarchical]_modelTrain3_(function_version).ipynb
AIML-Makgeolli/CpE-AIDL
edcf81078000646646f6091445279cb2895e245e
[ "Apache-2.0" ]
null
null
null
SMARF/[Hierarchical]_modelTrain3_(function_version).ipynb
AIML-Makgeolli/CpE-AIDL
edcf81078000646646f6091445279cb2895e245e
[ "Apache-2.0" ]
1
2021-09-16T02:09:35.000Z
2021-09-16T02:09:35.000Z
336.327298
86,120
0.912565
[ [ [ "References: \n\n- http://www.diva-portal.org/smash/get/diva2:1382324/FULLTEXT01.pdf\n- https://stackabuse.com/hierarchical-clustering-with-python-and-scikit-learn/\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom numpy import sqrt, array, random, argsort\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nfrom scipy.cluster.hierarchy import dendrogram, linkage, centroid, fcluster\nimport scipy.cluster.hierarchy as shc\nfrom scipy.spatial.distance import cdist, pdist\nfrom sklearn.neighbors import NearestCentroid\n\n\n\n#from google.colab import drive\n#drive.mount('/content/gdrive')", "_____no_output_____" ], [ "df = pd.read_csv(\"https://raw.githubusercontent.com/AIML-Makgeolli/CpE-AIDL/main/thesis_database/Crop_recommendation.csv\")\ndf_train = df.drop(['label','rainfall'], axis = 1)", "_____no_output_____" ] ], [ [ "Declarations", "_____no_output_____" ] ], [ [ "X_N= df_train[['N']]\nX_P= df_train[['P']]\nX_K= df_train[['K']]\nX_temp= df_train[['temperature']]\nX_moist= df_train[['humidity']]\ny = df_train[['ph']]", "_____no_output_____" ] ], [ [ "Nitrogen and ph ", "_____no_output_____" ] ], [ [ "class hierarchical():\n def __init__(self):\n return\n\n def input_train(self, X_in, y_in):\n self.X = X_in\n self.y = y_in\n X_train, X_test, y_train, y_test = train_test_split(self.X, self.y,test_size=0.3, random_state=42)\n self.data = pd.concat([X_train, y_train], axis=1).to_numpy()\n return self.data\n\n def dendograms(self):\n plt.figure(figsize=(7, 5))\n plt.title(\"Dendograms\")\n dend = shc.dendrogram(shc.linkage(self.data, method='ward'))\n\n def cluster_fit(self, clust):\n self.cluster = AgglomerativeClustering(n_clusters = clust, affinity ='euclidean', linkage='ward')\n self.res = self.cluster.fit_predict(self.data)\n \n self.labels = self.cluster.labels_\n \n print(self.labels)\n print(\"Silhouette Coefficient: %0.3f\" % metrics.silhouette_score(self.data, self.labels))\n print(\"Calinski-Harabasz Index: %0.3f\" % metrics.calinski_harabasz_score(self.data, self.labels))\n print(\"Davies-Bouldin Index: %0.3f\" % metrics.davies_bouldin_score(self.data, self.labels))\n \n return self.res\n \n def outlier(self,threshold):\n clf = NearestCentroid()\n clf.fit(self.data, self.res)\n self.centroids = clf.centroids_\n self.points = np.empty((0,len(self.data[0])), float)\n self.distances = np.empty((0,len(self.data[0])), float)\n for i, center_elem in enumerate(self.centroids):\n self.distances = np.append(self.distances, cdist([center_elem],self.data[self.res == i], 'euclidean')) \n self.points = np.append(self.points, self.data[self.res == i], axis=0)\n \n percentile = threshold\n self.outliers = self.points[np.where(self.distances > np.percentile(self.distances, percentile))]\n outliers_df = pd.DataFrame(self.outliers,columns =['X','y'])\n return outliers_df\n\n def cluster_graph(self):\n plt.figure(figsize=(7, 5))\n plt.scatter(self.data[:,0], self.data[:,1], c=self.cluster.labels_, cmap='rainbow')\n plt.scatter(*zip(*self.outliers),marker=\"o\",facecolor=\"None\",edgecolor=\"g\",s=70); \n plt.scatter(*zip(*self.centroids),marker=\"o\",facecolor=\"b\",edgecolor=\"b\",s=20);\n\n\nhierarchical_test = hierarchical()", "_____no_output_____" ] ], [ [ "Nitrogen and pH", "_____no_output_____" ] ], [ [ "hierarchical_test.input_train(X_N,y)", "_____no_output_____" ], [ "hierarchical_test.dendograms()", "_____no_output_____" ], [ "hierarchical_test.cluster_fit(3)", "[0 0 1 ... 0 0 0]\nSilhouette Coefficient: 0.628\nCalinski-Harabasz Index: 6240.256\nDavies-Bouldin Index: 0.526\n" ], [ "hierarchical_test.outlier(80)", "_____no_output_____" ], [ "hierarchical_test.cluster_graph()", "_____no_output_____" ] ], [ [ "Phosphorus and pH", "_____no_output_____" ] ], [ [ "hierarchical_test.input_train(X_P,y)", "_____no_output_____" ], [ "hierarchical_test.dendograms()", "_____no_output_____" ], [ "hierarchical_test.cluster_fit(3)", "[0 0 0 ... 0 1 2]\nSilhouette Coefficient: 0.607\nCalinski-Harabasz Index: 5355.551\nDavies-Bouldin Index: 0.433\n" ], [ "hierarchical_test.outlier(80)", "_____no_output_____" ], [ "hierarchical_test.cluster_graph()", "_____no_output_____" ] ], [ [ "Potassium and pH", "_____no_output_____" ] ], [ [ "hierarchical_test.input_train(X_K,y)", "_____no_output_____" ], [ "hierarchical_test.dendograms()", "_____no_output_____" ], [ "hierarchical_test.cluster_fit(3)", "[2 2 2 ... 2 1 2]\nSilhouette Coefficient: 0.672\nCalinski-Harabasz Index: 24416.300\nDavies-Bouldin Index: 0.353\n" ], [ "hierarchical_test.outlier(80)", "_____no_output_____" ], [ "hierarchical_test.cluster_graph()", "_____no_output_____" ] ], [ [ "Temperature and pH", "_____no_output_____" ] ], [ [ "hierarchical_test.input_train(X_temp,y)", "_____no_output_____" ], [ "hierarchical_test.dendograms()", "_____no_output_____" ], [ "hierarchical_test.cluster_fit(3)", "[0 0 0 ... 0 1 0]\nSilhouette Coefficient: 0.501\nCalinski-Harabasz Index: 1996.702\nDavies-Bouldin Index: 0.582\n" ], [ "hierarchical_test.outlier(80)", "_____no_output_____" ], [ "hierarchical_test.cluster_graph()", "_____no_output_____" ] ], [ [ "Moisture and pH", "_____no_output_____" ] ], [ [ "hierarchical_test.input_train(X_moist,y)", "_____no_output_____" ], [ "hierarchical_test.dendograms()", "_____no_output_____" ], [ "hierarchical_test.cluster_fit(3)", "[1 1 1 ... 1 0 1]\nSilhouette Coefficient: 0.695\nCalinski-Harabasz Index: 6735.176\nDavies-Bouldin Index: 0.386\n" ], [ "hierarchical_test.outlier(80)", "_____no_output_____" ], [ "hierarchical_test.cluster_graph()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4aee94093ac04bde448247175cfcb065c09deb1d
768,766
ipynb
Jupyter Notebook
Cervical_with_ADAYSN_and_Isolation_Forest.ipynb
moinul7002/Analysis-of-ML-Techniques-in-Classifying-Cervical-Cancer-using-Isolation-Forest-with-ADASYN
962f6da9cd8dc8351ca1570abeba16466978dc12
[ "MIT" ]
null
null
null
Cervical_with_ADAYSN_and_Isolation_Forest.ipynb
moinul7002/Analysis-of-ML-Techniques-in-Classifying-Cervical-Cancer-using-Isolation-Forest-with-ADASYN
962f6da9cd8dc8351ca1570abeba16466978dc12
[ "MIT" ]
null
null
null
Cervical_with_ADAYSN_and_Isolation_Forest.ipynb
moinul7002/Analysis-of-ML-Techniques-in-Classifying-Cervical-Cancer-using-Isolation-Forest-with-ADASYN
962f6da9cd8dc8351ca1570abeba16466978dc12
[ "MIT" ]
null
null
null
156.923046
50,716
0.844682
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor \nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, BaggingClassifier,AdaBoostClassifier,GradientBoostingClassifier\nfrom sklearn.linear_model import LinearRegression,LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import metrics\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import RFE\nfrom collections import Counter\nfrom imblearn.over_sampling import SMOTE\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "df=pd.read_csv(\"datasets/cervical_cancer.csv\")\n\npd.set_option('display.max_columns', 40)", "_____no_output_____" ], [ "df.head(20)", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "df.columns=['Age', 'No_of_sex_partner', 'First_sexual_intercourse',\\\n 'No_pregnancies','Smokes', 'Smokes_yrs', 'Smokes_packs_yr', 'Hormonal_Contraceptives',\\\n 'Hormonal_Contraceptives_years','IUD', 'IUD_years', 'STDs', 'STDs_number', 'STDs_condylomatosis',\\\n 'STDs_cervical_condylomatosis', 'STDs_vaginal_condylomatosis', 'STDs_vulvo_perineal_condylomatosis',\\\n 'STDs_syphilis', 'STDs_pelvic_inflammatory_disease', 'STDs_genital_herpes', 'STDs_molluscum_contagiosum',\\\n 'STDs_AIDS', 'STDs_HIV', 'STDs_Hepatitis_B', 'STDs_HPV', 'STDs_No_of_diagnosis', 'STD_Time_since_first_diagnosis',\\\n 'STDs_Time_since_last_diagnosis', 'Dx_Cancer', 'Dx_CIN', 'Dx_HPV', 'Dx', 'Hinselmann','Schiller' ,'Citology', 'Biopsy']", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 858 entries, 0 to 857\nData columns (total 36 columns):\nAge 858 non-null int64\nNo_of_sex_partner 858 non-null object\nFirst_sexual_intercourse 858 non-null object\nNo_pregnancies 858 non-null object\nSmokes 858 non-null object\nSmokes_yrs 858 non-null object\nSmokes_packs_yr 858 non-null object\nHormonal_Contraceptives 858 non-null object\nHormonal_Contraceptives_years 858 non-null object\nIUD 858 non-null object\nIUD_years 858 non-null object\nSTDs 858 non-null object\nSTDs_number 858 non-null object\nSTDs_condylomatosis 858 non-null object\nSTDs_cervical_condylomatosis 858 non-null object\nSTDs_vaginal_condylomatosis 858 non-null object\nSTDs_vulvo_perineal_condylomatosis 858 non-null object\nSTDs_syphilis 858 non-null object\nSTDs_pelvic_inflammatory_disease 858 non-null object\nSTDs_genital_herpes 858 non-null object\nSTDs_molluscum_contagiosum 858 non-null object\nSTDs_AIDS 858 non-null object\nSTDs_HIV 858 non-null object\nSTDs_Hepatitis_B 858 non-null object\nSTDs_HPV 858 non-null object\nSTDs_No_of_diagnosis 858 non-null int64\nSTD_Time_since_first_diagnosis 858 non-null object\nSTDs_Time_since_last_diagnosis 858 non-null object\nDx_Cancer 858 non-null int64\nDx_CIN 858 non-null int64\nDx_HPV 858 non-null int64\nDx 858 non-null int64\nHinselmann 858 non-null int64\nSchiller 858 non-null int64\nCitology 858 non-null int64\nBiopsy 858 non-null int64\ndtypes: int64(10), object(26)\nmemory usage: 241.4+ KB\n" ], [ "df.shape", "_____no_output_____" ], [ "## replace ? with NaN\ndf = df.replace('?', np.NaN)", "_____no_output_____" ], [ "plt.figure(figsize=(10,10))\nnp.round(df.isnull().sum()/df.shape[0]*100).sort_values().plot(kind='bar')", "_____no_output_____" ], [ "df=df.drop(['STD_Time_since_first_diagnosis','STDs_Time_since_last_diagnosis'],axis=1)\ndf=df.drop(df.index[df.Smokes.isnull()] | df.index[df.First_sexual_intercourse.isnull()])", "_____no_output_____" ], [ "x_features=list(df.columns)\nx_features.remove('Biopsy')", "_____no_output_____" ], [ "x_features_categorical=[\n 'Smokes','Hormonal_Contraceptives','IUD','STDs','STDs_condylomatosis','STDs_cervical_condylomatosis','STDs_vaginal_condylomatosis','STDs_vulvo_perineal_condylomatosis','STDs_syphilis','STDs_pelvic_inflammatory_disease','STDs_genital_herpes','STDs_molluscum_contagiosum','STDs_AIDS','STDs_HIV','STDs_Hepatitis_B','STDs_HPV','Dx_Cancer','Dx_CIN','Dx_HPV','Dx']\nx_features_categorical", "_____no_output_____" ], [ "x_features_numerical=[i for i in x_features if i not in x_features_categorical]\nx_features_numerical", "_____no_output_____" ], [ "df_iud=df.copy()\n\nx_features_categorical.remove('IUD')\nfor i in x_features_categorical:\n df_iud[i]=df_iud[i].fillna(df_iud[i].mode()[0])\nfor i in x_features_numerical:\n df_iud[i]=df_iud[i].fillna(df_iud[i].median())\n \ndf_iud=df_iud.astype('float')\ndf_iud[x_features_categorical]=df_iud[x_features_categorical].replace(0,'no')\ndf_iud[x_features_categorical]=df_iud[x_features_categorical].replace(1,'yes')\ndf_iud=pd.get_dummies(df_iud)\n\ntrain_iud=df_iud[df_iud.IUD.isnull()==False]\ntest_iud=df_iud[df_iud.IUD.isnull()]\n\ntrain_iud_x=train_iud.drop('IUD',axis=1)\ntrain_iud_y=train_iud['IUD']\n\ntest_iud_x=test_iud.drop('IUD',axis=1)\ntest_iud_y=test_iud['IUD']\n\ndt=DecisionTreeClassifier()\niud_model=dt.fit(train_iud_x,train_iud_y)\ntest_iud['IUD']=iud_model.predict(test_iud_x)\n\niud_complete=pd.concat([train_iud,test_iud],axis=0)\n\ndf_impute=df.copy()\ndf_impute['IUD']=iud_complete['IUD'].sort_index()", "_____no_output_____" ], [ "df_hor=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('Hormonal_Contraceptives')\nfor i in x_features_categorical:\n df_hor[i]=df_hor[i].fillna(df_hor[i].mode()[0])\nfor i in x_features_numerical:\n df_hor[i]=df_hor[i].fillna(df_hor[i].median())\n \ndf_hor=df_hor.astype('float')\ndf_hor[x_features_categorical]=df_hor[x_features_categorical].replace(0,'no')\ndf_hor[x_features_categorical]=df_hor[x_features_categorical].replace(1,'yes')\ndf_hor=pd.get_dummies(df_hor)\n\ntrain_hor=df_hor[df_hor.Hormonal_Contraceptives.isnull()==False]\ntest_hor=df_hor[df_hor.Hormonal_Contraceptives.isnull()]\n\ntrain_hor_x=train_hor.drop('Hormonal_Contraceptives',axis=1)\ntrain_hor_y=train_hor['Hormonal_Contraceptives']\n\ntest_hor_x=test_hor.drop('Hormonal_Contraceptives',axis=1)\ntest_hor_y=test_hor['Hormonal_Contraceptives']\n\ndt=DecisionTreeClassifier()\nhor_model=dt.fit(train_hor_x,train_hor_y)\ntest_hor['Hormonal_Contraceptives']=hor_model.predict(test_hor_x)\n\nhor_complete=pd.concat([train_hor,test_hor],axis=0)\n\ndf_impute['Hormonal_Contraceptives']=hor_complete['Hormonal_Contraceptives'].sort_index()", "_____no_output_____" ], [ "df_hor_y=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_numerical.remove('Hormonal_Contraceptives_years')\nfor i in x_features_categorical:\n df_hor_y[i]=df_hor_y[i].fillna(df_hor_y[i].mode()[0])\n\nfor i in x_features_numerical:\n df_hor_y[i]=df_hor_y[i].fillna(df_hor_y[i].median())\n\ndf_hor_y=df_hor_y.astype('float')\ndf_hor_y[x_features_categorical]=df_hor_y[x_features_categorical].replace(0,'no')\ndf_hor_y[x_features_categorical]=df_hor_y[x_features_categorical].replace(1,'yes')\ndf_hor_y=pd.get_dummies(df_hor_y)\n\ntrain_hor_yrs=df_hor_y[df_hor_y.Hormonal_Contraceptives_years.isnull()==False]\ntest_hor_yrs=df_hor_y[df_hor_y.Hormonal_Contraceptives_years.isnull()]\n\ntrain_hor_yrs_x=train_hor_yrs.drop('Hormonal_Contraceptives_years',axis=1)\ntrain_hor_yrs_y=train_hor_yrs['Hormonal_Contraceptives_years']\n\ntest_hor_yrs_x=test_hor_yrs.drop('Hormonal_Contraceptives_years',axis=1)\ntest_hor_yrs_y=test_hor_yrs['Hormonal_Contraceptives_years']\n\ndt=DecisionTreeRegressor()\nhor_yrs_model=dt.fit(train_hor_yrs_x,train_hor_yrs_y)\ntest_hor_yrs['Hormonal_Contraceptives_years']=hor_yrs_model.predict(test_hor_yrs_x)\n\nhor_yrs_complete=pd.concat([train_hor_yrs,test_hor_yrs],axis=0)\n\ndf_impute['Hormonal_Contraceptives_years']=hor_yrs_complete['Hormonal_Contraceptives_years'].sort_index()", "_____no_output_____" ], [ "df_std=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs')\nfor i in x_features_categorical:\n df_std[i]=df_std[i].fillna(df_std[i].mode()[0])\nfor i in x_features_numerical:\n df_std[i]=df_std[i].fillna(df_std[i].median())\n \ndf_std=df_std.astype('float')\ndf_std[x_features_categorical]=df_std[x_features_categorical].replace(0,'no')\ndf_std[x_features_categorical]=df_std[x_features_categorical].replace(1,'yes')\ndf_std=pd.get_dummies(df_std)\n\ntrain_std=df_std[df_std.STDs.isnull()==False]\ntest_std=df_std[df_std.STDs.isnull()]\n\ntrain_std_x=train_std.drop('STDs',axis=1)\ntrain_std_y=train_std['STDs']\n\ntest_std_x=test_std.drop('STDs',axis=1)\ntest_std_y=test_std['STDs']\n\ndt=DecisionTreeClassifier()\nstd_model=dt.fit(train_std_x,train_std_y)\ntest_std['STDs']=std_model.predict(test_std_x)\n\nstd_complete=pd.concat([train_std,test_std],axis=0)\n\ndf_impute['STDs']=std_complete['STDs'].sort_index()", "_____no_output_____" ], [ "df_std_num=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_numerical.remove('STDs_number')\nfor i in x_features_categorical:\n df_std_num[i]=df_std_num[i].fillna(df_std_num[i].mode()[0])\nfor i in x_features_numerical:\n df_std_num[i]=df_std_num[i].fillna(df_std_num[i].median())\n\ndf_std_num=df_std_num.astype('float')\ndf_std_num[x_features_categorical]=df_std_num[x_features_categorical].replace(0,'no')\ndf_std_num[x_features_categorical]=df_std_num[x_features_categorical].replace(1,'yes')\ndf_std_num=pd.get_dummies(df_std_num)\n\ntrain_std_num=df_std_num[df_std_num.STDs_number.isnull()==False]\ntest_std_num=df_std_num[df_std_num.STDs_number.isnull()]\n\ntrain_std_num_x=train_std_num.drop('STDs_number',axis=1)\ntrain_std_num_y=train_std_num['STDs_number']\n\ntest_std_num_x=test_std_num.drop('STDs_number',axis=1)\ntest_std_num_y=test_std_num['STDs_number']\n\ndt=DecisionTreeRegressor()\nstd_model_num=dt.fit(train_std_num_x,train_std_num_y)\ntest_std_num['STDs_number']=std_model_num.predict(test_std_num_x)\n\nstd_num_complete=pd.concat([train_std_num,test_std_num],axis=0)\n\ndf_impute['STDs_number']=std_num_complete['STDs_number'].sort_index()", "_____no_output_____" ], [ "df_std_con=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_condylomatosis')\nfor i in x_features_categorical:\n df_std_con[i]=df_std_con[i].fillna(df_std_con[i].mode()[0])\nfor i in x_features_numerical:\n df_std_con[i]=df_std_con[i].fillna(df_std_con[i].median())\n\ndf_std_con=df_std_con.astype('float')\ndf_std_con[x_features_categorical]=df_std_con[x_features_categorical].replace(0,'no')\ndf_std_con[x_features_categorical]=df_std_con[x_features_categorical].replace(1,'yes')\ndf_std_con=pd.get_dummies(df_std_con)\n\ntrain_std_con=df_std_con[df_std_con.STDs_condylomatosis.isnull()==False]\ntest_std_con=df_std_con[df_std_con.STDs_condylomatosis.isnull()]\n\ntrain_std_con_x=train_std_con.drop('STDs_condylomatosis',axis=1)\ntrain_std_con_y=train_std_con['STDs_condylomatosis']\n\ntest_std_con_x=test_std_con.drop('STDs_condylomatosis',axis=1)\ntest_std_con_y=test_std_con['STDs_condylomatosis']\n\ndt=DecisionTreeClassifier()\nstd_model_con=dt.fit(train_std_con_x,train_std_con_y)\ntest_std_con['STDs_condylomatosis']=std_model_con.predict(test_std_con_x)\n\nstd_con_complete=pd.concat([train_std_con,test_std_con],axis=0)\n\ndf_impute['STDs_condylomatosis']=std_con_complete['STDs_condylomatosis'].sort_index()", "_____no_output_____" ], [ "df_std_cerv=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_cervical_condylomatosis')\nfor i in x_features_categorical:\n df_std_cerv[i]=df_std_cerv[i].fillna(df_std_cerv[i].mode()[0])\nfor i in x_features_numerical:\n df_std_cerv[i]=df_std_cerv[i].fillna(df_std_cerv[i].median())\n\ndf_std_cerv=df_std_cerv.astype('float')\ndf_std_cerv[x_features_categorical]=df_std_cerv[x_features_categorical].replace(0,'no')\ndf_std_cerv[x_features_categorical]=df_std_cerv[x_features_categorical].replace(1,'yes')\ndf_std_cerv=pd.get_dummies(df_std_cerv)\n\ntrain_std_cerv=df_std_cerv[df_std_cerv.STDs_cervical_condylomatosis.isnull()==False]\ntest_std_cerv=df_std_cerv[df_std_cerv.STDs_cervical_condylomatosis.isnull()]\n\ntrain_std_cerv_x=train_std_cerv.drop('STDs_cervical_condylomatosis',axis=1)\ntrain_std_cerv_y=train_std_cerv['STDs_cervical_condylomatosis']\n\ntest_std_cerv_x=test_std_cerv.drop('STDs_cervical_condylomatosis',axis=1)\ntest_std_cerv_y=test_std_cerv['STDs_cervical_condylomatosis']\n\ndt=DecisionTreeClassifier()\nstd_model_cerv=dt.fit(train_std_cerv_x,train_std_cerv_y)\ntest_std_cerv['STDs_cervical_condylomatosis']=std_model_cerv.predict(test_std_cerv_x)\n\nstd_cerv_complete=pd.concat([train_std_cerv,test_std_cerv],axis=0)\n\ndf_impute['STDs_cervical_condylomatosis']=std_cerv_complete['STDs_cervical_condylomatosis'].sort_index()", "_____no_output_____" ], [ "df_std_vagi=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_vaginal_condylomatosis')\nfor i in x_features_categorical:\n df_std_vagi[i]=df_std_vagi[i].fillna(df_std_vagi[i].mode()[0])\nfor i in x_features_numerical:\n df_std_vagi[i]=df_std_vagi[i].fillna(df_std_vagi[i].median())\n\ndf_std_vagi=df_std_vagi.astype('float')\ndf_std_vagi[x_features_categorical]=df_std_vagi[x_features_categorical].replace(0,'no')\ndf_std_vagi[x_features_categorical]=df_std_vagi[x_features_categorical].replace(1,'yes')\ndf_std_vagi=pd.get_dummies(df_std_vagi)\n\ntrain_std_vagi=df_std_vagi[df_std_vagi.STDs_vaginal_condylomatosis.isnull()==False]\ntest_std_vagi=df_std_vagi[df_std_vagi.STDs_vaginal_condylomatosis.isnull()]\n\ntrain_std_vagi_x=train_std_vagi.drop('STDs_vaginal_condylomatosis',axis=1)\ntrain_std_vagi_y=train_std_vagi['STDs_vaginal_condylomatosis']\n\ntest_std_vagi_x=test_std_vagi.drop('STDs_vaginal_condylomatosis',axis=1)\ntest_std_vagi_y=test_std_vagi['STDs_vaginal_condylomatosis']\n\ndt=DecisionTreeClassifier()\nstd_model_vagi=dt.fit(train_std_vagi_x,train_std_vagi_y)\ntest_std_vagi['STDs_vaginal_condylomatosis']=std_model_vagi.predict(test_std_vagi_x)\n\nstd_vagi_complete=pd.concat([train_std_vagi,test_std_vagi],axis=0)\n\ndf_impute['STDs_vaginal_condylomatosis']=std_vagi_complete['STDs_vaginal_condylomatosis'].sort_index()", "_____no_output_____" ], [ "df_std_peri=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_vulvo_perineal_condylomatosis')\nfor i in x_features_categorical:\n df_std_peri[i]=df_std_peri[i].fillna(df_std_peri[i].mode()[0])\nfor i in x_features_numerical:\n df_std_peri[i]=df_std_peri[i].fillna(df_std_peri[i].median())\n\ndf_std_peri=df_std_peri.astype('float')\ndf_std_peri[x_features_categorical]=df_std_peri[x_features_categorical].replace(0,'no')\ndf_std_peri[x_features_categorical]=df_std_peri[x_features_categorical].replace(1,'yes')\ndf_std_peri=pd.get_dummies(df_std_peri)\n\ntrain_std_peri=df_std_peri[df_std_peri.STDs_vulvo_perineal_condylomatosis.isnull()==False]\ntest_std_peri=df_std_peri[df_std_peri.STDs_vulvo_perineal_condylomatosis.isnull()]\n\ntrain_std_peri_x=train_std_peri.drop('STDs_vulvo_perineal_condylomatosis',axis=1)\ntrain_std_peri_y=train_std_peri['STDs_vulvo_perineal_condylomatosis']\n\ntest_std_peri_x=test_std_peri.drop('STDs_vulvo_perineal_condylomatosis',axis=1)\ntest_std_peri_y=test_std_peri['STDs_vulvo_perineal_condylomatosis']\n\ndt=DecisionTreeClassifier()\nstd_model_peri=dt.fit(train_std_peri_x,train_std_peri_y)\ntest_std_peri['STDs_vulvo_perineal_condylomatosis']=std_model_peri.predict(test_std_peri_x)\n\nstd_peri_complete=pd.concat([train_std_peri,test_std_peri],axis=0)\n\ndf_impute['STDs_vulvo_perineal_condylomatosis']=std_peri_complete['STDs_vulvo_perineal_condylomatosis'].sort_index()", "_____no_output_____" ], [ "df_std_syp=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_syphilis')\nfor i in x_features_categorical:\n df_std_syp[i]=df_std_syp[i].fillna(df_std_syp[i].mode()[0])\nfor i in x_features_numerical:\n df_std_syp[i]=df_std_syp[i].fillna(df_std_syp[i].median())\n\ndf_std_syp=df_std_syp.astype('float')\ndf_std_syp[x_features_categorical]=df_std_syp[x_features_categorical].replace(0,'no')\ndf_std_syp[x_features_categorical]=df_std_syp[x_features_categorical].replace(1,'yes')\ndf_std_syp=pd.get_dummies(df_std_syp)\n\ntrain_std_syp=df_std_syp[df_std_syp.STDs_syphilis.isnull()==False]\ntest_std_syp=df_std_syp[df_std_syp.STDs_syphilis.isnull()]\n\ntrain_std_syp_x=train_std_syp.drop('STDs_syphilis',axis=1)\ntrain_std_syp_y=train_std_syp['STDs_syphilis']\n\ntest_std_syp_x=test_std_syp.drop('STDs_syphilis',axis=1)\ntest_std_syp_y=test_std_syp['STDs_syphilis']\n\ndt=DecisionTreeClassifier()\nstd_model_syp=dt.fit(train_std_syp_x,train_std_syp_y)\ntest_std_syp['STDs_syphilis']=std_model_syp.predict(test_std_syp_x)\n\nstd_syp_complete=pd.concat([train_std_syp,test_std_syp],axis=0)\n\ndf_impute['STDs_syphilis']=std_syp_complete['STDs_syphilis'].sort_index()", "_____no_output_____" ], [ "df_std_pelv=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_pelvic_inflammatory_disease')\nfor i in x_features_categorical:\n df_std_pelv[i]=df_std_pelv[i].fillna(df_std_pelv[i].mode()[0])\n\nfor i in x_features_numerical:\n df_std_pelv[i]=df_std_pelv[i].fillna(df_std_pelv[i].median()) \n\ndf_std_pelv=df_std_pelv.astype('float')\ndf_std_pelv[x_features_categorical]=df_std_pelv[x_features_categorical].replace(0,'no')\ndf_std_pelv[x_features_categorical]=df_std_pelv[x_features_categorical].replace(1,'yes')\ndf_std_pelv=pd.get_dummies(df_std_pelv)\n\ntrain_std_pelv=df_std_pelv[df_std_pelv.STDs_pelvic_inflammatory_disease.isnull()==False]\ntest_std_pelv=df_std_pelv[df_std_pelv.STDs_pelvic_inflammatory_disease.isnull()]\n\ntrain_std_pelv_x=train_std_pelv.drop('STDs_pelvic_inflammatory_disease',axis=1)\ntrain_std_pelv_y=train_std_pelv['STDs_pelvic_inflammatory_disease']\n\ntest_std_pelv_x=test_std_pelv.drop('STDs_pelvic_inflammatory_disease',axis=1)\ntest_std_pelv_y=test_std_pelv['STDs_pelvic_inflammatory_disease']\n\ndt=DecisionTreeClassifier()\nstd_model_pelv=dt.fit(train_std_pelv_x,train_std_pelv_y)\ntest_std_pelv['STDs_pelvic_inflammatory_disease']=std_model_pelv.predict(test_std_pelv_x)\n\nstd_pelv_complete=pd.concat([train_std_pelv,test_std_pelv],axis=0)\n\ndf_impute['STDs_pelvic_inflammatory_disease']=std_pelv_complete['STDs_pelvic_inflammatory_disease'].sort_index()", "_____no_output_____" ], [ "df_std_geni=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_genital_herpes')\nfor i in x_features_categorical:\n df_std_geni[i]=df_std_geni[i].fillna(df_std_geni[i].mode()[0])\nfor i in x_features_numerical:\n df_std_geni[i]=df_std_geni[i].fillna(df_std_geni[i].median())\n\ndf_std_geni=df_std_geni.astype('float')\ndf_std_geni[x_features_categorical]=df_std_geni[x_features_categorical].replace(0,'no')\ndf_std_geni[x_features_categorical]=df_std_geni[x_features_categorical].replace(1,'yes')\ndf_std_geni=pd.get_dummies(df_std_geni)\n\ntrain_std_geni=df_std_geni[df_std_geni.STDs_genital_herpes.isnull()==False]\ntest_std_geni=df_std_geni[df_std_geni.STDs_genital_herpes.isnull()]\n\ntrain_std_geni_x=train_std_geni.drop('STDs_genital_herpes',axis=1)\ntrain_std_geni_y=train_std_geni['STDs_genital_herpes']\n\ntest_std_geni_x=test_std_geni.drop('STDs_genital_herpes',axis=1)\ntest_std_geni_y=test_std_geni['STDs_genital_herpes']\n\ndt=DecisionTreeClassifier()\nstd_model_geni=dt.fit(train_std_geni_x,train_std_geni_y)\ntest_std_geni['STDs_genital_herpes']=std_model_geni.predict(test_std_geni_x)\n\nstd_geni_complete=pd.concat([train_std_geni,test_std_geni],axis=0)\n\ndf_impute['STDs_genital_herpes']=std_geni_complete['STDs_genital_herpes'].sort_index()", "_____no_output_____" ], [ "df_std_mollu=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_molluscum_contagiosum')\nfor i in x_features_categorical:\n df_std_mollu[i]=df_std_mollu[i].fillna(df_std_mollu[i].mode()[0])\nfor i in x_features_numerical:\n df_std_mollu[i]=df_std_mollu[i].fillna(df_std_mollu[i].median())\n\ndf_std_mollu=df_std_mollu.astype('float')\ndf_std_mollu[x_features_categorical]=df_std_mollu[x_features_categorical].replace(0,'no')\ndf_std_mollu[x_features_categorical]=df_std_mollu[x_features_categorical].replace(1,'yes')\ndf_std_mollu=pd.get_dummies(df_std_mollu)\n\ntrain_std_mollu=df_std_mollu[df_std_mollu.STDs_molluscum_contagiosum.isnull()==False]\ntest_std_mollu=df_std_mollu[df_std_mollu.STDs_molluscum_contagiosum.isnull()]\n\ntrain_std_mollu_x=train_std_mollu.drop('STDs_molluscum_contagiosum',axis=1)\ntrain_std_mollu_y=train_std_mollu['STDs_molluscum_contagiosum']\n\ntest_std_mollu_x=test_std_mollu.drop('STDs_molluscum_contagiosum',axis=1)\ntest_std_mollu_y=test_std_mollu['STDs_molluscum_contagiosum']\n\ndt=DecisionTreeClassifier()\nstd_model_mollu=dt.fit(train_std_mollu_x,train_std_mollu_y)\ntest_std_mollu['STDs_molluscum_contagiosum']=std_model_mollu.predict(test_std_mollu_x)\n\nstd_mollu_complete=pd.concat([train_std_mollu,test_std_mollu],axis=0)\n\ndf_impute['STDs_molluscum_contagiosum']=std_mollu_complete['STDs_molluscum_contagiosum'].sort_index()", "_____no_output_____" ], [ "df_std_aids=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_AIDS')\nfor i in x_features_categorical:\n df_std_aids[i]=df_std_aids[i].fillna(df_std_aids[i].mode()[0])\nfor i in x_features_numerical:\n df_std_aids[i]=df_std_aids[i].fillna(df_std_aids[i].median())\n\ndf_std_aids=df_std_aids.astype('float')\ndf_std_aids[x_features_categorical]=df_std_aids[x_features_categorical].replace(0,'no')\ndf_std_aids[x_features_categorical]=df_std_aids[x_features_categorical].replace(1,'yes')\ndf_std_aids=pd.get_dummies(df_std_aids)\n\ntrain_std_aids=df_std_aids[df_std_aids.STDs_AIDS.isnull()==False]\ntest_std_aids=df_std_aids[df_std_aids.STDs_AIDS.isnull()]\n\ntrain_std_aids_x=train_std_aids.drop('STDs_AIDS',axis=1)\ntrain_std_aids_y=train_std_aids['STDs_AIDS']\n\ntest_std_aids_x=test_std_aids.drop('STDs_AIDS',axis=1)\ntest_std_aids_y=test_std_aids['STDs_AIDS']\n\ndt=DecisionTreeClassifier()\nstd_model_aids=dt.fit(train_std_aids_x,train_std_aids_y)\ntest_std_aids['STDs_AIDS']=std_model_aids.predict(test_std_aids_x)\n\nstd_aids_complete=pd.concat([train_std_aids,test_std_aids],axis=0)\n\ndf_impute['STDs_AIDS']=std_aids_complete['STDs_AIDS'].sort_index()", "_____no_output_____" ], [ "df_std_hiv=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_HIV')\nfor i in x_features_categorical:\n df_std_hiv[i]=df_std_hiv[i].fillna(df_std_hiv[i].mode()[0])\nfor i in x_features_numerical:\n df_std_hiv[i]=df_std_hiv[i].fillna(df_std_hiv[i].median())\n\ndf_std_hiv=df_std_hiv.astype('float')\ndf_std_hiv[x_features_categorical]=df_std_hiv[x_features_categorical].replace(0,'no')\ndf_std_hiv[x_features_categorical]=df_std_hiv[x_features_categorical].replace(1,'yes')\ndf_std_hiv=pd.get_dummies(df_std_hiv)\n\ntrain_std_hiv=df_std_hiv[df_std_hiv.STDs_HIV.isnull()==False]\ntest_std_hiv=df_std_hiv[df_std_hiv.STDs_HIV.isnull()]\n\ntrain_std_hiv_x=train_std_hiv.drop('STDs_HIV',axis=1)\ntrain_std_hiv_y=train_std_hiv['STDs_HIV']\n\ntest_std_hiv_x=test_std_hiv.drop('STDs_HIV',axis=1)\ntest_std_hiv_y=test_std_hiv['STDs_HIV']\n\ndt=DecisionTreeClassifier()\nstd_model_hiv=dt.fit(train_std_hiv_x,train_std_hiv_y)\ntest_std_hiv['STDs_HIV']=std_model_hiv.predict(test_std_hiv_x)\n\nstd_hiv_complete=pd.concat([train_std_hiv,test_std_hiv],axis=0)\n\ndf_impute['STDs_HIV']=std_hiv_complete['STDs_HIV'].sort_index()", "_____no_output_____" ], [ "df_std_hepa=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_Hepatitis_B')\nfor i in x_features_categorical:\n df_std_hepa[i]=df_std_hepa[i].fillna(df_std_hepa[i].mode()[0])\nfor i in x_features_numerical:\n df_std_hepa[i]=df_std_hepa[i].fillna(df_std_hepa[i].median())\n\ndf_std_hepa=df_std_hepa.astype('float')\ndf_std_hepa[x_features_categorical]=df_std_hepa[x_features_categorical].replace(0,'no')\ndf_std_hepa[x_features_categorical]=df_std_hepa[x_features_categorical].replace(1,'yes')\ndf_std_hepa=pd.get_dummies(df_std_hepa)\n\ntrain_std_hepa=df_std_hepa[df_std_hepa.STDs_Hepatitis_B.isnull()==False]\ntest_std_hepa=df_std_hepa[df_std_hepa.STDs_Hepatitis_B.isnull()]\n\ntrain_std_hepa_x=train_std_hepa.drop(['STDs_Hepatitis_B'],axis=1)\ntrain_std_hepa_y=train_std_hepa['STDs_Hepatitis_B']\n\ntest_std_hepa_x=test_std_hepa.drop(['STDs_Hepatitis_B'],axis=1)\ntest_std_hepa_y=test_std_hepa['STDs_Hepatitis_B']\n\ndt=DecisionTreeClassifier()\nstd_model_hepa=dt.fit(train_std_hepa_x,train_std_hepa_y)\ntest_std_hepa['STDs_Hepatitis_B']=std_model_hepa.predict(test_std_hepa_x)\n\nstd_hepa_complete=pd.concat([train_std_hepa,test_std_hepa],axis=0)\n\ndf_impute['STDs_Hepatitis_B']=std_hepa_complete['STDs_Hepatitis_B'].sort_index()", "_____no_output_____" ], [ "df_std_hpv=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_categorical.remove('STDs_HPV')\nfor i in x_features_categorical:\n df_std_hpv[i]=df_std_hpv[i].fillna(df_std_hpv[i].mode()[0])\nfor i in x_features_numerical:\n df_std_hpv[i]=df_std_hpv[i].fillna(df_std_hpv[i].median())\n\ndf_std_hpv=df_std_hpv.astype('float')\ndf_std_hpv[x_features_categorical]=df_std_hpv[x_features_categorical].replace(0,'no')\ndf_std_hpv[x_features_categorical]=df_std_hpv[x_features_categorical].replace(1,'yes')\ndf_std_hpv=pd.get_dummies(df_std_hpv)\n\ntrain_std_hpv=df_std_hpv[df_std_hpv.STDs_HPV.isnull()==False]\ntest_std_hpv=df_std_hpv[df_std_hpv.STDs_HPV.isnull()]\n\ntrain_std_hpv_x=train_std_hpv.drop(['STDs_HPV'],axis=1)\ntrain_std_hpv_y=train_std_hpv['STDs_HPV']\n\ntest_std_hpv_x=test_std_hpv.drop(['STDs_HPV'],axis=1)\ntest_std_hpv_y=test_std_hpv['STDs_HPV']\n\ndt=DecisionTreeClassifier()\nstd_model_hpv=dt.fit(train_std_hpv_x,train_std_hpv_y)\ntest_std_hpv['STDs_HPV']=std_model_hpv.predict(test_std_hpv_x)\n\nstd_hpv_complete=pd.concat([train_std_hpv,test_std_hpv],axis=0)\n\ndf_impute['STDs_HPV']=std_hpv_complete['STDs_HPV'].sort_index()", "_____no_output_____" ], [ "df_no_preg=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_numerical.remove('No_pregnancies')\nfor i in x_features_numerical:\n df_no_preg[i]=df_no_preg[i].fillna(df_no_preg[i].median())\nfor i in x_features_categorical:\n df_no_preg[i]=df_no_preg[i].fillna(df_no_preg[i].mode()[0])\n\ndf_no_preg=df_no_preg.astype('float')\ndf_no_preg[x_features_categorical]=df_no_preg[x_features_categorical].replace(0,'no')\ndf_no_preg[x_features_categorical]=df_no_preg[x_features_categorical].replace(1,'yes')\ndf_no_preg=pd.get_dummies(df_no_preg)\n\ntrain_no_preg=df_no_preg[df_no_preg.No_pregnancies.isnull()==False]\ntest_no_preg=df_no_preg[df_no_preg.No_pregnancies.isnull()]\n\ntrain_no_preg_x=train_no_preg.drop(['No_pregnancies'],axis=1)\ntrain_no_preg_y=train_no_preg['No_pregnancies']\n\ntest_no_preg_x=test_no_preg.drop(['No_pregnancies'],axis=1)\ntest_no_preg_y=test_no_preg['No_pregnancies']\n\ndt=DecisionTreeRegressor()\nmodel_no_preg=dt.fit(train_no_preg_x,train_no_preg_y)\ntest_no_preg['No_pregnancies']=model_no_preg.predict(test_no_preg_x)\n\nno_preg_complete=pd.concat([train_no_preg,test_no_preg],axis=0)\n\ndf_impute['No_pregnancies']=no_preg_complete['No_pregnancies'].sort_index()", "_____no_output_____" ], [ "df_no_sexptnr=df_impute.drop(['Biopsy'],axis=1)\n\nx_features_numerical.remove('No_of_sex_partner')\nfor i in x_features_numerical:\n df_no_sexptnr[i]=df_no_sexptnr[i].fillna(df_no_sexptnr[i].median())\nfor i in x_features_categorical:\n df_no_sexptnr[i]=df_no_sexptnr[i].fillna(df_no_sexptnr[i].mode()[0])\n\ndf_no_sexptnr=df_no_sexptnr.astype('float')\ndf_no_sexptnr[x_features_categorical]=df_no_sexptnr[x_features_categorical].replace(0,'no')\ndf_no_sexptnr[x_features_categorical]=df_no_sexptnr[x_features_categorical].replace(1,'yes')\ndf_no_sexptnr=pd.get_dummies(df_no_sexptnr)\n\ntrain_no_sexptnr=df_no_sexptnr[df_no_sexptnr.No_of_sex_partner.isnull()==False]\ntest_no_sexptnr=df_no_sexptnr[df_no_sexptnr.No_of_sex_partner.isnull()]\n\ntrain_no_sexptnr_x=train_no_sexptnr.drop(['No_of_sex_partner'],axis=1)\ntrain_no_sexptnr_y=train_no_sexptnr['No_of_sex_partner']\n\ntest_no_sexptnr_x=test_no_sexptnr.drop(['No_of_sex_partner'],axis=1)\ntest_no_sexptnr_y=test_no_sexptnr['No_of_sex_partner']\n\ndt=DecisionTreeRegressor()\nmodel_no_sexptnr=dt.fit(train_no_sexptnr_x,train_no_sexptnr_y)\ntest_no_sexptnr['No_of_sex_partner']=model_no_sexptnr.predict(test_no_sexptnr_x)\n\nno_sexptnr_complete=pd.concat([train_no_sexptnr,test_no_sexptnr],axis=0)\n\ndf_impute['No_of_sex_partner']=no_sexptnr_complete['No_of_sex_partner'].sort_index()", "_____no_output_____" ], [ "df_impute.isnull().sum()", "_____no_output_____" ], [ "df_impute[['Age','No_pregnancies', 'No_of_sex_partner',\n 'First_sexual_intercourse',\n 'Smokes_yrs',\n 'Smokes_packs_yr',\n 'STDs_No_of_diagnosis', 'Hormonal_Contraceptives_years', 'IUD_years', 'STDs_number']].describe()", "_____no_output_____" ], [ "df_impute.to_csv('datasets/df_imputation.csv')", "_____no_output_____" ], [ "df = pd.read_csv('df_imputation.csv', index_col=0) #df_imputation is the new CSV file that doesn't have any null values.\n\n#Again manually segregating categorical and numerical colmuns\n\nx_features_categorical = ['Smokes','Hormonal_Contraceptives','IUD','STDs','STDs_condylomatosis','STDs_cervical_condylomatosis',\n 'STDs_vaginal_condylomatosis','STDs_vulvo_perineal_condylomatosis','STDs_syphilis',\n 'STDs_pelvic_inflammatory_disease','STDs_genital_herpes','STDs_molluscum_contagiosum','STDs_AIDS',\n 'STDs_HIV','STDs_Hepatitis_B','STDs_HPV','Dx_Cancer','Dx_CIN','Dx_HPV','Dx', 'Hinselmann', 'Citology', 'Biopsy']\n\nx_features_numerical = [x for x in df.columns if x not in x_features_categorical]", "_____no_output_____" ], [ "impute = df.copy()\nimpute=df.astype('float')\n\nplt.figure(figsize = (12,8))\nplt.pie(impute['Biopsy'].value_counts(), labels = ['NO', 'YES'], autopct = '%1.1f%%', labeldistance=1.1, textprops = {'fontsize': 20})\nplt.title('Biopsy Percentage', fontsize=20)\nplt.show()", "_____no_output_____" ], [ "print(\"Count Plots of Categorical Columns\");print()\nfor i in impute[x_features_categorical]:\n print('*'*100)\n sns.countplot(impute[i])\n plt.title(i)\n plt.show()", "Count Plots of Categorical Columns\n\n****************************************************************************************************\n" ], [ "print(\"Density Plots\");print()\nfor i in impute[x_features_numerical]:\n print('*'*100)\n sns.distplot(impute[i])\n plt.title(i)\n plt.show()", "Density Plots\n\n****************************************************************************************************\n" ], [ "numerical=['Age','No_of_sex_partner','First_sexual_intercourse','No_pregnancies','Smokes_yrs','Smokes_packs_yr',\n 'Hormonal_Contraceptives_years','IUD_years'] # --> Choosing the proper numerical features \n\ndf_copy = df.copy()\ndf_copy[numerical]=df_copy[numerical].astype('float64')", "_____no_output_____" ], [ "df_copy[numerical].plot(kind='bar',subplots=True, layout=(4,4), fontsize=8, figsize=(14,14))", "_____no_output_____" ], [ "IQR=df_copy[numerical].describe().T['75%']-df_copy[numerical].describe().T['25%']\n\nmin,max=[df_copy[numerical].describe().T['25%']-(IQR*1.5),df_copy[numerical].describe().T['75%']+(IQR*1.5)]\n\nfor i in numerical:\n print('range of',i,'b/w',min[i],'and',max[i])\n\nfor i in numerical:\n df_copy[i][df_copy[i]>max[i]]=max[i]\n df_copy[i][df_copy[i]<min[i]]=min[i]", "range of Age b/w 2.0 and 50.0\nrange of No_of_sex_partner b/w 0.5 and 4.5\nrange of First_sexual_intercourse b/w 10.5 and 22.5\nrange of No_pregnancies b/w -2.0 and 6.0\nrange of Smokes_yrs b/w 0.0 and 0.0\nrange of Smokes_packs_yr b/w 0.0 and 0.0\nrange of Hormonal_Contraceptives_years b/w -4.5 and 7.5\nrange of IUD_years b/w 0.0 and 0.0\n" ], [ "df_copy[numerical].plot(kind='bar',subplots=True, layout=(4,4), fontsize=8, figsize=(14,14))\n", "_____no_output_____" ], [ "from sklearn.linear_model import LogisticRegression \nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\n#from catboost import CatBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn import tree\n#import lightgbm as lgb\n#from lightgbm import LGBMClassifier\nimport xgboost as xgb\n\nfrom sklearn.model_selection import train_test_split\nfrom scipy import interp\nfrom sklearn.metrics import classification_report, accuracy_score, auc\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix", "_____no_output_____" ], [ "from sklearn import ensemble\n\nour_anomaly_detector = ensemble.IsolationForest(contamination = 0.1, random_state=42)\nour_anomaly_detector.fit(df[numerical])\n\ntraining_predictions = our_anomaly_detector.predict(df[numerical])\nprint(len(training_predictions))", "838\n" ], [ "outlier_label = []\noutlier_label = list(training_predictions)", "_____no_output_____" ], [ "anomaly_iso = outlier_label.count(-1)\nprint(anomaly_iso)\nnormal_iso = outlier_label.count(1)\nprint(normal_iso)", "84\n754\n" ], [ "df = df.astype('float64')\n\nx = df.drop('Biopsy', axis=1)\ny = df['Biopsy']\n\nSS = StandardScaler()\ndf_scaled = pd.DataFrame(SS.fit_transform(x), columns = x.columns) # as scaling mandotory for KNN model \n\nx_train,x_test,y_train,y_test = train_test_split(x,y, test_size = 0.3, random_state = 1)\nx_train1,x_test1,y_train,y_test = train_test_split(df_scaled,y, test_size = 0.3, random_state = 1)\n\nl= [] #List to store the various model metrics ", "_____no_output_____" ], [ "def models_lr(x,y):\n mod = {}\n model = LogisticRegression().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'LogisticRegression'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_lr(x_train,y_train))\n\ndef models_dt(x,y):\n mod = {}\n model = DecisionTreeClassifier().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'Decision Tree'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_dt(x_train,y_train))\n\ndef models_rf(x,y):\n mod = {}\n model = RandomForestClassifier().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'Random Forest'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_rf(x_train,y_train))\n\ndef models_nb(x,y):\n mod = {}\n model = GaussianNB().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'GaussianNB'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_nb(x_train,y_train))\n\ndef models_knn(x,y):\n mod = {}\n model = KNeighborsClassifier().fit(x,y)\n ypred = model.predict(x_test1)\n mod['Model'] = 'KNN'\n mod['Train_Score'] = model.score(x_train1,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test1)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_knn(x_train1,y_train))\n\ndef models_ada(x,y):\n mod = {}\n model = AdaBoostClassifier(n_estimators=100, random_state=0).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'AdaBoostClassifier'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_ada(x_train,y_train))\n\ndef models_xg(x,y):\n mod = {}\n model = xgb.XGBClassifier(objective=\"binary:logistic\", random_state=42, eval_metric=\"auc\").fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'XGBClasssifier'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_xg(x_train,y_train))\n\ndef models_gbc(x,y):\n mod = {}\n model = GradientBoostingClassifier(loss='exponential', learning_rate=0.03, n_estimators=75 , max_depth=6).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'GradientBoostingClassifier'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_gbc(x_train,y_train))\n\ndef models_svm(x,y):\n mod = {}\n model = SVC(kernel='rbf', probability=True).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'SupportVectorClassifier'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_svm(x_train,y_train))\n\n\ndef models_etc(x,y):\n mod = {}\n model = ExtraTreesClassifier(n_estimators=250, random_state=0).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'ExtraTreesClassifier'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_etc(x_train,y_train))\n\nfrom sklearn.naive_bayes import BernoulliNB\ndef models_bnb(x,y):\n mod = {}\n model = BernoulliNB().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'BernoulliNB'\n mod['Train_Score'] = model.score(x_train,y_train)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl.append(models_bnb(x_train,y_train))\n", "_____no_output_____" ], [ "\nbase_df = pd.DataFrame(l)\nbase_df", "_____no_output_____" ], [ "knneig = KNeighborsClassifier(n_neighbors=10)\nknneig.fit(x_train1, y_train)\npred_knneigh = knneig.predict(x_test1)\nscore_knneigh_before = accuracy_score(y_test, pred_knneigh)\nprint(\"Score KNeighnors :\",score_knneigh_before)\nprint(classification_report(y_test, pred_knneigh))", "Score KNeighnors : 0.9365079365079365\n precision recall f1-score support\n\n 0.0 0.95 0.98 0.97 237\n 1.0 0.43 0.20 0.27 15\n\n accuracy 0.94 252\n macro avg 0.69 0.59 0.62 252\nweighted avg 0.92 0.94 0.93 252\n\n" ], [ "\n# q = 0\n\n# while q < len(outlier_label):\n# if outlier_label[q] == -1:\n# df.drop(q, axis = 0, inplace = True)\n# q+=1", "_____no_output_____" ], [ "from imblearn.over_sampling import (RandomOverSampler,SMOTE,ADASYN)\nx_train_s, y_train_s = ADASYN(random_state=42).fit_resample(x_train, y_train.ravel())\nprint(sorted(Counter(y_train_s).items()))", "[(0.0, 547), (1.0, 541)]\n" ], [ "l_final = [] #--> New list for storing metrics of base models\n\ndef models_dt(x,y):\n mod = {}\n model = DecisionTreeClassifier().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'Decision Tree After Sampling'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_dt(x_train_s,y_train_s))\n\ndef models_rf(x,y):\n mod = {}\n model = RandomForestClassifier().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'Random Forest After Sampling'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_rf(x_train_s,y_train_s))\n\ndef models_lr(x,y):\n mod = {}\n model = LogisticRegression().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'LogisticRegression'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_lr(x_train_s,y_train_s))\n\ndef models_nb(x,y):\n mod = {}\n model = GaussianNB().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'GaussianNB'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_nb(x_train_s,y_train_s))\n\ndef models_knn(x,y):\n mod = {}\n model = KNeighborsClassifier().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'KNN'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_knn(x_train_s,y_train_s))\n\ndef models_ada(x,y):\n mod = {}\n model = AdaBoostClassifier(n_estimators=100, random_state=0).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'AdaBoostClassifier'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_ada(x_train_s,y_train_s))\n\ndef models_xg(x,y):\n mod = {}\n model = xgb.XGBClassifier(objective=\"binary:logistic\", random_state=42, eval_metric=\"auc\").fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'XGBClassifier'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_xg(x_train_s,y_train_s))\n\ndef models_gbc(x,y):\n mod = {}\n model = GradientBoostingClassifier(loss='exponential', learning_rate=0.03, n_estimators=75 , max_depth=6).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'GradientBoostingClassifier'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_gbc(x_train_s,y_train_s))\n\ndef models_svm(x,y):\n mod = {}\n model = SVC(kernel='rbf', probability=True).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'SupportVectorClassifier'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_svm(x_train_s,y_train_s))\n\n\ndef models_etc(x,y):\n mod = {}\n model = ExtraTreesClassifier(n_estimators=250, random_state=0).fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'ExtraTreesClassifier'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_etc(x_train_s,y_train_s))\n\nfrom sklearn.naive_bayes import BernoulliNB\ndef models_bnb(x,y):\n mod = {}\n model = BernoulliNB().fit(x,y)\n ypred = model.predict(x_test)\n mod['Model'] = 'BernoulliNB'\n mod['Train_Score'] = model.score(x_train_s,y_train_s)\n mod['Test_accuracy'] = metrics.accuracy_score(y_test,ypred)\n mod['f1score'] = metrics.f1_score(y_test,ypred)\n mod['recall'] = metrics.recall_score(y_test, ypred)\n mod['precision'] = metrics.precision_score(y_test, ypred)\n model.predict_proba(x_test)\n mod['roc_auc'] = metrics.roc_auc_score(y_test,ypred)\n return mod\nl_final.append(models_bnb(x_train_s,y_train_s))\n", "_____no_output_____" ], [ "final_model = pd.DataFrame(l_final)\nfinal_model", "_____no_output_____" ], [ "knneig = KNeighborsClassifier(n_neighbors=10)\nknneig.fit(x_train_s, y_train_s)\npred_knneigh = knneig.predict(x_test1)\nscore_knneigh_before = accuracy_score(y_test, pred_knneigh)\nprint(\"Score KNeighnors :\",score_knneigh_before)\nprint(classification_report(y_test, pred_knneigh))", "Score KNeighnors : 0.9404761904761905\n precision recall f1-score support\n\n 0.0 0.94 1.00 0.97 237\n 1.0 0.00 0.00 0.00 15\n\n accuracy 0.94 252\n macro avg 0.47 0.50 0.48 252\nweighted avg 0.88 0.94 0.91 252\n\n" ], [ "rfc = RandomForestClassifier(n_estimators=100,random_state = 42)\nrfc.fit(x_train_s, y_train_s)\nrfc_pred = rfc.predict(x_test)\nprint(accuracy_score(y_test,rfc_pred))\nprint(classification_report(y_test,rfc_pred))", "0.9523809523809523\n precision recall f1-score support\n\n 0.0 0.99 0.96 0.97 237\n 1.0 0.57 0.87 0.68 15\n\n accuracy 0.95 252\n macro avg 0.78 0.91 0.83 252\nweighted avg 0.97 0.95 0.96 252\n\n" ], [ "logmodel = LogisticRegression()\nlogmodel.fit(x_train_s,y_train_s)\npredictions = logmodel.predict(x_test)\nprint(accuracy_score(y_test, predictions))\nprint(classification_report(y_test,predictions))", "0.9444444444444444\n precision recall f1-score support\n\n 0.0 0.99 0.95 0.97 237\n 1.0 0.52 0.87 0.65 15\n\n accuracy 0.94 252\n macro avg 0.76 0.91 0.81 252\nweighted avg 0.96 0.94 0.95 252\n\n" ], [ "gbc = GradientBoostingClassifier()\ngbc.fit(x_train_s,y_train_s)\npredictions = gbc.predict(x_test)\nprint(accuracy_score(y_test, predictions))\nprint(classification_report(y_test,predictions))", "0.9523809523809523\n precision recall f1-score support\n\n 0.0 0.99 0.96 0.97 237\n 1.0 0.57 0.87 0.68 15\n\n accuracy 0.95 252\n macro avg 0.78 0.91 0.83 252\nweighted avg 0.97 0.95 0.96 252\n\n" ], [ "ada = AdaBoostClassifier()\nada.fit(x_train_s,y_train_s)\npredictions = ada.predict(x_test)\nprint(accuracy_score(y_test, predictions))\nprint(classification_report(y_test,predictions))", "0.9523809523809523\n precision recall f1-score support\n\n 0.0 0.97 0.97 0.97 237\n 1.0 0.60 0.60 0.60 15\n\n accuracy 0.95 252\n macro avg 0.79 0.79 0.79 252\nweighted avg 0.95 0.95 0.95 252\n\n" ], [ "dt = DecisionTreeClassifier()\ndt.fit(x_train_s,y_train_s)\npredictions = dt.predict(x_test)\nprint(accuracy_score(y_test, predictions))\nprint(classification_report(y_test,predictions))", "0.9444444444444444\n precision recall f1-score support\n\n 0.0 0.99 0.95 0.97 237\n 1.0 0.52 0.87 0.65 15\n\n accuracy 0.94 252\n macro avg 0.76 0.91 0.81 252\nweighted avg 0.96 0.94 0.95 252\n\n" ], [ "r_probs = [0 for _ in range(len(y_test))]\nKNN_probs = knneig.predict_proba(x_test1)\nRF_probs = rfc.predict_proba(x_test)\nGBC_probs = gbc.predict_proba(x_test)\nDT_probs = dt.predict_proba(x_test)\nLR_probs = logmodel.predict_proba(x_test)\nADA_probs = ada.predict_proba(x_test)\n\n\nKNN_probs = KNN_probs[:, 1]\nRF_probs = RF_probs[:, 1]\nGBC_probs = GBC_probs[:, 1]\nLR_probs = LR_probs[:, 1]\nDT_probs = DT_probs[:, 1]\nADA_probs = ADA_probs[:, 1]\n\n\nr_auc = roc_auc_score(y_test, r_probs)\nKNN_auc = roc_auc_score(y_test, KNN_probs)\nRF_auc = roc_auc_score(y_test, RF_probs)\nGBC_auc = roc_auc_score(y_test, GBC_probs)\nLR_auc = roc_auc_score(y_test, LR_probs)\nDT_auc = roc_auc_score(y_test, DT_probs)\nADA_auc = roc_auc_score(y_test, ADA_probs)\n\nr_fpr, r_tpr, _ = roc_curve(y_test, r_probs)\nKNN_fpr, KNN_tpr, _ = roc_curve(y_test, KNN_probs)\nRF_fpr, RF_tpr, _ = roc_curve(y_test, RF_probs)\nGBC_fpr, GBC_tpr, _ = roc_curve(y_test, GBC_probs)\nLR_fpr, LR_tpr, _ = roc_curve(y_test, LR_probs)\nDT_fpr, DT_tpr, _ = roc_curve(y_test, DT_probs)\nADA_fpr, ADA_tpr, _ = roc_curve(y_test, ADA_probs)", "_____no_output_____" ], [ "plt.figure(figsize=(10,6))\nplt.plot(r_fpr, r_tpr, linestyle='--')\n#plt.plot(rf_fpr, rf_tpr, marker='.', label='Random Forest (AUROC = %0.3f)' % rf_auc)\nplt.plot(KNN_fpr, KNN_tpr, label='KNN (AUROC = %0.3f)' % KNN_auc)\nplt.plot(RF_fpr, RF_tpr, label='RF (AUROC = %0.3f)' % RF_auc)\nplt.plot(GBC_fpr, GBC_tpr, label='GBC (AUROC = %0.3f)' % GBC_auc)\nplt.plot(LR_fpr, LR_tpr, label='LR (AUROC = %0.3f)' % LR_auc)\nplt.plot(DT_fpr, DT_tpr, label='DT (AUROC = %0.3f)' % DT_auc)\nplt.plot(ADA_fpr, ADA_tpr, label='ADA (AUROC = %0.3f)' % ADA_auc)\n\n\n\n# Title\nplt.title('ROC Plot (After Oversampling)')\n# Axis labels\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\n# Show legend\nplt.legend() # \n# Show plot\nplt.show()", "_____no_output_____" ] ], [ [ "## ANN", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nmodel= tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Dense(units=200,activation='relu',input_shape= (33,)))\nmodel.add(tf.keras.layers.Dense(units=200,activation='relu'))\nmodel.add(tf.keras.layers.Dense(units=1,activation='sigmoid'))", "WARNING:tensorflow:From C:\\Users\\Moinul\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\ops\\resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\n" ], [ "model.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 200) 6800 \n_________________________________________________________________\ndense_1 (Dense) (None, 200) 40200 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 201 \n=================================================================\nTotal params: 47,201\nTrainable params: 47,201\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "## After Outlier", "_____no_output_____" ] ], [ [ "from sklearn import metrics\nmodel.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\nepochs_hist = model.fit(x_train,y_train,epochs=50,batch_size=20)", "WARNING:tensorflow:From C:\\Users\\Moinul\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\ops\\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nEpoch 1/50\n586/586 [==============================] - 1s 2ms/sample - loss: 0.3980 - acc: 0.9027\nEpoch 2/50\n586/586 [==============================] - 0s 159us/sample - loss: 0.2386 - acc: 0.9317\nEpoch 3/50\n586/586 [==============================] - 0s 155us/sample - loss: 0.2120 - acc: 0.9369\nEpoch 4/50\n586/586 [==============================] - 0s 145us/sample - loss: 0.2060 - acc: 0.9317\nEpoch 5/50\n586/586 [==============================] - 0s 155us/sample - loss: 0.1714 - acc: 0.9386\nEpoch 6/50\n586/586 [==============================] - 0s 160us/sample - loss: 0.1499 - acc: 0.9471\nEpoch 7/50\n586/586 [==============================] - 0s 169us/sample - loss: 0.1236 - acc: 0.9556\nEpoch 8/50\n586/586 [==============================] - 0s 164us/sample - loss: 0.1252 - acc: 0.9522\nEpoch 9/50\n586/586 [==============================] - 0s 177us/sample - loss: 0.1245 - acc: 0.9539\nEpoch 10/50\n586/586 [==============================] - 0s 182us/sample - loss: 0.0917 - acc: 0.9693\nEpoch 11/50\n586/586 [==============================] - 0s 142us/sample - loss: 0.0923 - acc: 0.9659\nEpoch 12/50\n586/586 [==============================] - 0s 164us/sample - loss: 0.0982 - acc: 0.9608\nEpoch 13/50\n586/586 [==============================] - 0s 169us/sample - loss: 0.0854 - acc: 0.9761\nEpoch 14/50\n586/586 [==============================] - 0s 172us/sample - loss: 0.0917 - acc: 0.9710\nEpoch 15/50\n586/586 [==============================] - 0s 152us/sample - loss: 0.0770 - acc: 0.9727\nEpoch 16/50\n586/586 [==============================] - 0s 184us/sample - loss: 0.0776 - acc: 0.9727\nEpoch 17/50\n586/586 [==============================] - 0s 153us/sample - loss: 0.0879 - acc: 0.9676\nEpoch 18/50\n586/586 [==============================] - 0s 150us/sample - loss: 0.0774 - acc: 0.9727\nEpoch 19/50\n586/586 [==============================] - 0s 179us/sample - loss: 0.0758 - acc: 0.9727\nEpoch 20/50\n586/586 [==============================] - 0s 133us/sample - loss: 0.0799 - acc: 0.9727\nEpoch 21/50\n586/586 [==============================] - 0s 162us/sample - loss: 0.0648 - acc: 0.9795\nEpoch 22/50\n586/586 [==============================] - 0s 162us/sample - loss: 0.0621 - acc: 0.9778\nEpoch 23/50\n586/586 [==============================] - 0s 147us/sample - loss: 0.0573 - acc: 0.9812\nEpoch 24/50\n586/586 [==============================] - 0s 188us/sample - loss: 0.0590 - acc: 0.9829\nEpoch 25/50\n586/586 [==============================] - 0s 160us/sample - loss: 0.0536 - acc: 0.9778\nEpoch 26/50\n586/586 [==============================] - 0s 154us/sample - loss: 0.0512 - acc: 0.9829\nEpoch 27/50\n586/586 [==============================] - 0s 182us/sample - loss: 0.0681 - acc: 0.9761\nEpoch 28/50\n586/586 [==============================] - 0s 162us/sample - loss: 0.0623 - acc: 0.9778\nEpoch 29/50\n586/586 [==============================] - 0s 157us/sample - loss: 0.0591 - acc: 0.9744\nEpoch 30/50\n586/586 [==============================] - 0s 164us/sample - loss: 0.0608 - acc: 0.9778\nEpoch 31/50\n586/586 [==============================] - 0s 172us/sample - loss: 0.0543 - acc: 0.9829\nEpoch 32/50\n586/586 [==============================] - 0s 177us/sample - loss: 0.0537 - acc: 0.9795\nEpoch 33/50\n586/586 [==============================] - 0s 167us/sample - loss: 0.0652 - acc: 0.9778\nEpoch 34/50\n586/586 [==============================] - 0s 128us/sample - loss: 0.0632 - acc: 0.9727\nEpoch 35/50\n586/586 [==============================] - 0s 152us/sample - loss: 0.0521 - acc: 0.9881\nEpoch 36/50\n586/586 [==============================] - 0s 162us/sample - loss: 0.0491 - acc: 0.9846\nEpoch 37/50\n586/586 [==============================] - 0s 181us/sample - loss: 0.0404 - acc: 0.9846\nEpoch 38/50\n586/586 [==============================] - 0s 130us/sample - loss: 0.0505 - acc: 0.9812\nEpoch 39/50\n586/586 [==============================] - 0s 130us/sample - loss: 0.0490 - acc: 0.9829\nEpoch 40/50\n586/586 [==============================] - 0s 169us/sample - loss: 0.0418 - acc: 0.9846\nEpoch 41/50\n586/586 [==============================] - 0s 142us/sample - loss: 0.0446 - acc: 0.9846\nEpoch 42/50\n586/586 [==============================] - 0s 130us/sample - loss: 0.0484 - acc: 0.9846\nEpoch 43/50\n586/586 [==============================] - 0s 152us/sample - loss: 0.0553 - acc: 0.9846\nEpoch 44/50\n586/586 [==============================] - 0s 140us/sample - loss: 0.0475 - acc: 0.9829\nEpoch 45/50\n586/586 [==============================] - 0s 142us/sample - loss: 0.0411 - acc: 0.9829\nEpoch 46/50\n586/586 [==============================] - 0s 140us/sample - loss: 0.0356 - acc: 0.9863\nEpoch 47/50\n586/586 [==============================] - 0s 142us/sample - loss: 0.0543 - acc: 0.9829\nEpoch 48/50\n586/586 [==============================] - 0s 142us/sample - loss: 0.0329 - acc: 0.9898\nEpoch 49/50\n586/586 [==============================] - 0s 142us/sample - loss: 0.0374 - acc: 0.9863\nEpoch 50/50\n586/586 [==============================] - 0s 148us/sample - loss: 0.0320 - acc: 0.9898\n" ], [ "model.metrics_names", "_____no_output_____" ], [ "y_pred=model.predict(x_test)\n\ny_pred = (y_pred>0.5)\n\nplt.plot(epochs_hist.history['loss'])\nplt.plot(epochs_hist.history['acc'])\nplt.xlabel('Epochs')\nplt.ylabel('percentage')\nplt.legend(['loss','accuracy'])\nplt.title('Loss and Accuracy plot')", "_____no_output_____" ], [ "from sklearn.metrics import confusion_matrix,classification_report\ncm = confusion_matrix(y_test,y_pred)\nsns.heatmap(cm,annot=True)", "_____no_output_____" ], [ "print(classification_report(y_test,y_pred))", " precision recall f1-score support\n\n 0.0 0.97 0.97 0.97 237\n 1.0 0.57 0.53 0.55 15\n\n accuracy 0.95 252\n macro avg 0.77 0.75 0.76 252\nweighted avg 0.95 0.95 0.95 252\n\n" ] ], [ [ "## After Oversampling ", "_____no_output_____" ] ], [ [ "model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\nepochs_hist = model.fit(x_train_s,y_train_s,epochs=50,batch_size=20)", "Epoch 1/50\n1088/1088 [==============================] - 0s 385us/sample - loss: 0.0720 - acc: 0.9761\nEpoch 2/50\n1088/1088 [==============================] - 0s 131us/sample - loss: 0.0545 - acc: 0.9798\nEpoch 3/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0610 - acc: 0.9807\nEpoch 4/50\n1088/1088 [==============================] - 0s 134us/sample - loss: 0.0396 - acc: 0.9890\nEpoch 5/50\n1088/1088 [==============================] - 0s 135us/sample - loss: 0.0438 - acc: 0.9816\nEpoch 6/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0492 - acc: 0.9853\nEpoch 7/50\n1088/1088 [==============================] - 0s 133us/sample - loss: 0.0366 - acc: 0.9853\nEpoch 8/50\n1088/1088 [==============================] - 0s 130us/sample - loss: 0.0383 - acc: 0.9881\nEpoch 9/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0336 - acc: 0.9899\nEpoch 10/50\n1088/1088 [==============================] - 0s 130us/sample - loss: 0.0293 - acc: 0.9926\nEpoch 11/50\n1088/1088 [==============================] - 0s 148us/sample - loss: 0.0302 - acc: 0.9908\nEpoch 12/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0282 - acc: 0.9908\nEpoch 13/50\n1088/1088 [==============================] - 0s 130us/sample - loss: 0.0295 - acc: 0.9908\nEpoch 14/50\n1088/1088 [==============================] - 0s 135us/sample - loss: 0.0300 - acc: 0.9926\nEpoch 15/50\n1088/1088 [==============================] - 0s 136us/sample - loss: 0.0297 - acc: 0.9936\nEpoch 16/50\n1088/1088 [==============================] - 0s 134us/sample - loss: 0.0302 - acc: 0.9908\nEpoch 17/50\n1088/1088 [==============================] - 0s 149us/sample - loss: 0.0290 - acc: 0.9926\nEpoch 18/50\n1088/1088 [==============================] - 0s 130us/sample - loss: 0.0219 - acc: 0.9926\nEpoch 19/50\n1088/1088 [==============================] - 0s 133us/sample - loss: 0.0414 - acc: 0.9881\nEpoch 20/50\n1088/1088 [==============================] - 0s 139us/sample - loss: 0.0847 - acc: 0.9752\nEpoch 21/50\n1088/1088 [==============================] - 0s 124us/sample - loss: 0.0400 - acc: 0.9862\nEpoch 22/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0212 - acc: 0.9936\nEpoch 23/50\n1088/1088 [==============================] - 0s 139us/sample - loss: 0.0194 - acc: 0.9936\nEpoch 24/50\n1088/1088 [==============================] - 0s 134us/sample - loss: 0.0178 - acc: 0.9936\nEpoch 25/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0156 - acc: 0.9954\nEpoch 26/50\n1088/1088 [==============================] - 0s 129us/sample - loss: 0.0171 - acc: 0.9936\nEpoch 27/50\n1088/1088 [==============================] - 0s 124us/sample - loss: 0.0163 - acc: 0.9954\nEpoch 28/50\n1088/1088 [==============================] - 0s 135us/sample - loss: 0.0131 - acc: 0.9954\nEpoch 29/50\n1088/1088 [==============================] - 0s 127us/sample - loss: 0.0247 - acc: 0.9936\nEpoch 30/50\n1088/1088 [==============================] - 0s 123us/sample - loss: 0.0189 - acc: 0.9917\nEpoch 31/50\n1088/1088 [==============================] - 0s 112us/sample - loss: 0.0137 - acc: 0.9963\nEpoch 32/50\n1088/1088 [==============================] - 0s 110us/sample - loss: 0.0141 - acc: 0.9963\nEpoch 33/50\n1088/1088 [==============================] - 0s 105us/sample - loss: 0.0122 - acc: 0.9972\nEpoch 34/50\n1088/1088 [==============================] - 0s 114us/sample - loss: 0.0099 - acc: 0.9972\nEpoch 35/50\n1088/1088 [==============================] - 0s 155us/sample - loss: 0.0102 - acc: 0.9982\nEpoch 36/50\n1088/1088 [==============================] - 0s 127us/sample - loss: 0.0139 - acc: 0.9945\nEpoch 37/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0123 - acc: 0.9954\nEpoch 38/50\n1088/1088 [==============================] - 0s 122us/sample - loss: 0.0138 - acc: 0.9954\nEpoch 39/50\n1088/1088 [==============================] - 0s 129us/sample - loss: 0.0096 - acc: 0.9982\nEpoch 40/50\n1088/1088 [==============================] - 0s 126us/sample - loss: 0.0119 - acc: 0.9972\nEpoch 41/50\n1088/1088 [==============================] - 0s 131us/sample - loss: 0.0139 - acc: 0.9945\nEpoch 42/50\n1088/1088 [==============================] - 0s 123us/sample - loss: 0.0089 - acc: 0.9972\nEpoch 43/50\n1088/1088 [==============================] - 0s 132us/sample - loss: 0.0075 - acc: 0.9982\nEpoch 44/50\n1088/1088 [==============================] - 0s 124us/sample - loss: 0.0101 - acc: 0.9972\nEpoch 45/50\n1088/1088 [==============================] - 0s 133us/sample - loss: 0.0139 - acc: 0.9954\nEpoch 46/50\n1088/1088 [==============================] - 0s 137us/sample - loss: 0.0154 - acc: 0.9945\nEpoch 47/50\n1088/1088 [==============================] - 0s 124us/sample - loss: 0.0090 - acc: 0.9972\nEpoch 48/50\n1088/1088 [==============================] - 0s 132us/sample - loss: 0.0074 - acc: 0.9972\nEpoch 49/50\n1088/1088 [==============================] - 0s 138us/sample - loss: 0.0084 - acc: 0.9963\nEpoch 50/50\n1088/1088 [==============================] - 0s 123us/sample - loss: 0.0096 - acc: 0.9963\n" ], [ "y_pred=model.predict(x_test)\n\ny_pred = (y_pred>0.5)\n\nplt.plot(epochs_hist.history['loss'])\nplt.plot(epochs_hist.history['acc'])\nplt.xlabel('Epochs')\nplt.ylabel('percentage')\nplt.legend(['loss','accuracy'])\nplt.title('Loss and Accuracy plot')", "_____no_output_____" ], [ "from sklearn.metrics import confusion_matrix,classification_report\ncm = confusion_matrix(y_test,y_pred)\nsns.heatmap(cm,annot=True)\n\nprint(classification_report(y_test,y_pred))", " precision recall f1-score support\n\n 0.0 0.97 0.97 0.97 237\n 1.0 0.53 0.60 0.56 15\n\n accuracy 0.94 252\n macro avg 0.75 0.78 0.77 252\nweighted avg 0.95 0.94 0.95 252\n\n" ] ], [ [ "# Feature Scaling", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
4aeea21cd94afbb4c1117fa0905ec114f4a2be1b
8,793
ipynb
Jupyter Notebook
notebooks/20220519-augmentation-test.ipynb
RLQiao/afq-deep-learning
89da873643b217556da3515805ad4f75db103c6a
[ "BSD-3-Clause" ]
null
null
null
notebooks/20220519-augmentation-test.ipynb
RLQiao/afq-deep-learning
89da873643b217556da3515805ad4f75db103c6a
[ "BSD-3-Clause" ]
null
null
null
notebooks/20220519-augmentation-test.ipynb
RLQiao/afq-deep-learning
89da873643b217556da3515805ad4f75db103c6a
[ "BSD-3-Clause" ]
2
2021-12-01T17:04:39.000Z
2022-01-20T22:53:40.000Z
33.056391
227
0.55021
[ [ [ "import afqinsight.nn.tf_models as nn\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom afqinsight.datasets import AFQDataset\nfrom afqinsight.nn.tf_models import cnn_lenet, mlp4, cnn_vgg, lstm1v0, lstm1, lstm2, blstm1, blstm2, lstm_fcn, cnn_resnet\nfrom sklearn.impute import SimpleImputer\nimport os.path\n# Harmonization\nfrom sklearn.model_selection import train_test_split\nfrom neurocombat_sklearn import CombatModel\nimport pandas as pd\nfrom sklearn.utils import shuffle, resample\nfrom afqinsight.augmentation import jitter, time_warp, scaling\nimport tempfile", "/anaconda/envs/azureml_py38_PT_TF/lib/python3.8/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n from .autonotebook import tqdm as notebook_tqdm\n" ], [ "afq_dataset = AFQDataset.from_files(\n fn_nodes=\"../data/raw/combined_tract_profiles.csv\",\n fn_subjects=\"../data/raw/participants_updated_id.csv\",\n dwi_metrics=[\"dki_fa\", \"dki_md\", \"dki_mk\"],\n index_col=\"subject_id\",\n target_cols=[\"age\", \"dl_qc_score\", \"scan_site_id\"],\n label_encode_cols=[\"scan_site_id\"]\n)", "_____no_output_____" ], [ "afq_dataset.drop_target_na()", "_____no_output_____" ], [ "print(len(afq_dataset.subjects))\nprint(afq_dataset.X.shape)\nprint(afq_dataset.y.shape)", "_____no_output_____" ], [ "full_dataset = list(afq_dataset.as_tensorflow_dataset().as_numpy_iterator())", "_____no_output_____" ], [ "X = np.concatenate([xx[0][None] for xx in full_dataset], 0)\ny = np.array([yy[1][0] for yy in full_dataset])\nqc = np.array([yy[1][1] for yy in full_dataset])\nsite = np.array([yy[1][2] for yy in full_dataset])", "_____no_output_____" ], [ "X = X[qc>0]\ny = y[qc>0]\nsite = site[qc>0]", "_____no_output_____" ], [ "# Split the data into train and test sets:\nX_train, X_test, y_train, y_test, site_train, site_test = train_test_split(X, y, site, test_size=0.2, random_state=42)", "_____no_output_____" ], [ "imputer = SimpleImputer(strategy=\"median\")\n# Impute train and test separately:\nX_train = np.concatenate([imputer.fit_transform(X_train[..., ii])[:, :, None] for ii in range(X_train.shape[-1])], -1)\nX_test = np.concatenate([imputer.fit_transform(X_test[..., ii])[:, :, None] for ii in range(X_test.shape[-1])], -1)\n# Combat\nX_train = np.concatenate([CombatModel().fit_transform(X_train[..., ii], site_train[:, None], None, None)[:, :, None] for ii in range(X_train.shape[-1])], -1)\nX_test = np.concatenate([CombatModel().fit_transform(X_test[..., ii], site_test[:, None], None, None)[:, :, None] for ii in range(X_test.shape[-1])], -1)", "_____no_output_____" ], [ "n_epochs = 1000\n\n# EarlyStopping\nearly_stopping = tf.keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n min_delta=0.001,\n mode=\"min\",\n patience=100\n)\n\n# ReduceLROnPlateau\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(\n monitor=\"val_loss\",\n factor=0.5,\n patience=20,\n verbose=1,\n)", "_____no_output_____" ], [ "def augment_this(X, y, rounds=n_round): \n new_X = X[:]\n new_y = y[:]\n for f in range(rounds): \n aug_X = np.zeros_like(X)\n # Do each channel separately:\n for channel in range(aug_X.shape[-1]):\n this_X = X[..., channel][..., np.newaxis]\n this_X = jitter(this_X, sigma=np.mean(this_X)/25)\n this_X = scaling(this_X, sigma=np.mean(this_X)/25)\n this_X = time_warp(this_X, sigma=np.mean(this_X)/25)\n aug_X[..., channel] = this_X[...,0]\n new_X = np.concatenate([new_X, aug_X])\n new_y = np.concatenate([new_y, y])\n return new_X, new_y ", "_____no_output_____" ], [ "# Generate evaluation results, training history, number of epochs\ndef model_augmentation(model_name, name_str, lr, X_train, y_train, X_test, y_test, n_round):\n model = model_name(input_shape=(100, 72), n_classes=1, output_activation=None, verbose=True)\n model.compile(loss='mean_squared_error',\n optimizer=tf.keras.optimizers.Adam(learning_rate=lr),\n metrics=['mean_squared_error', \n tf.keras.metrics.RootMeanSquaredError(name='rmse'), \n 'mean_absolute_error'])\n \n ckpt_filepath = tempfile.NamedTemporaryFile().name + '.h5'\n ckpt = tf.keras.callbacks.ModelCheckpoint(\n filepath = ckpt_filepath,\n monitor=\"val_loss\",\n verbose=1,\n save_best_only=True,\n save_weights_only=True,\n mode=\"auto\",\n )\n X_train, y_train = augment_this(X_train, y_train)\n log = tf.keras.callbacks.CSVLogger(filename=(name_str + '.csv'), append=True)\n callbacks = [early_stopping, ckpt, reduce_lr, log]\n model.fit(X_train, y_train, epochs=n_epochs, batch_size=128,\n validation_split=0.2, callbacks=callbacks)\n model.load_weights(ckpt_filepath)\n y_predict = model.predict(X_test)\n y_predict = y_predict.reshape(y_test.shape)\n coef = np.corrcoef(y_test, y_predict)[0,1] ** 2\n evaluation = model.evaluate(X_test, y_test)\n\n # Results\n result = {'Model': [name_str]*16,\n 'Train_site': [site_1] * 4 + [site_2] * 4 + [site_3] * 4 + [f'{site_2}, {site_3}'] * 4,\n 'Test_site': [site_1] * 16,\n 'Metric': ['MSE', 'RMSE', 'MAE', 'coef'] * 4,\n 'Value': [eval_1[1], eval_1[2], eval_1[3], coef1,\n eval_2[1], eval_2[2], eval_2[3], coef2,\n eval_3[1], eval_3[2], eval_3[3], coef3,\n eval_4[1], eval_4[2], eval_3[3], coef4]}\n df = pd.DataFrame(result)\n return df", "_____no_output_____" ], [ "def \n for i in range(10):+\n df = model_augmentation(cnn_resnet, 'cnn_resnet', 0.01, 0, 3, 4, X, y)\n df_resnet = (df_resnet1.merge(df_resnet2, how='outer')).merge(df_resnet3, how='outer')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aeecf1a69f54ddadd3d74074e20e0df35b7abc4
12,816
ipynb
Jupyter Notebook
06_Feed-forward_Neural_Networks.ipynb
skaro94/deeplearning_pytorch_tutorial
e3dfd0e56b5f1ecbf34f8f665a1553bd8b27ef9b
[ "MIT" ]
null
null
null
06_Feed-forward_Neural_Networks.ipynb
skaro94/deeplearning_pytorch_tutorial
e3dfd0e56b5f1ecbf34f8f665a1553bd8b27ef9b
[ "MIT" ]
null
null
null
06_Feed-forward_Neural_Networks.ipynb
skaro94/deeplearning_pytorch_tutorial
e3dfd0e56b5f1ecbf34f8f665a1553bd8b27ef9b
[ "MIT" ]
null
null
null
33.116279
174
0.529026
[ [ [ "# 06_Feed-forward_Neural_Networks\nIn this notebook, we will see how to define simple feed-foward neural networks.", "_____no_output_____" ] ], [ [ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\ntorch.manual_seed(777) # reproducibility", "_____no_output_____" ] ], [ [ "## Neural Networks\nA typical training procedure for a neural network is as follows:\n\n- Define the neural network that has some learnable parameters (or weights)\n- Iterate over a dataset of inputs\n- Process input through the network\n- Compute the loss (how far is the output from being correct)\n- Propagate gradients back into the network’s parameters\n- Update the weights of the network, typically using an optimizer.\n\nWe will look at all the above processes with a concrete example, MNIST.\n\n### Define the network\nFirst of all, we need a new feed-foward neural network for performing image classification on MNIST.\nIn PyTorch, you can build your own neural network using the `torch.nn`package:", "_____no_output_____" ] ], [ [ "# Hyper-parameters\ninput_size = 784\nhidden_size = 256\nnum_classes = 10\nnum_epochs = 5\nbatch_size = 100\nlearning_rate = 0.001\n\n# Device configuration\n# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndevice = torch.device('cpu')\n\n# Fully connected neural network with one hidden layer\nclass NeuralNet(nn.Module):\n def __init__(self, input_size, hidden_size, num_classes):\n super(NeuralNet, self).__init__()\n # Define the operations to use for input processing.\n # torch.nn.Linear(in_features, out_features, bias=True)\n # : a linear projection(fc) layer(in_feeatures -> out_features)\n # torch.nn.RELU(inplace=False): a ReLU activation function\n self.fc1 = nn.Linear(input_size, hidden_size) \n self.relu = nn.ReLU()\n self.fc2 = nn.Linear(hidden_size, num_classes) \n \n def forward(self, x):\n # Define the input processing through network\n z1 = self.fc1(x)\n h1 = self.relu(z1)\n out = self.fc2(h1)\n return out\n\nmodel = NeuralNet(input_size, hidden_size, num_classes).to(device)\nprint(model)", "_____no_output_____" ] ], [ [ "You just have to define the `forward` function, and the `backward` function (where gradients are computed) is automatically defined for you using `autograd`.\n\nThe architecture of the above `NeuralNet` is as follows:\n<img src=\"images/nn_architecture.png\" width=\"500\">\n\nHere, x and y are the input, target (true label) values, respectively.\n\nThe learnable parameters of a model are returned by `model.parameters()`.", "_____no_output_____" ] ], [ [ "params = list(model.parameters())\nprint(len(params))\nprint(params[0].size()) # fc1's .weight", "_____no_output_____" ] ], [ [ "### Loss function and Optimizer\nA loss function takes the (output, target) pair of inputs, and computes a value that estimates how far away the output is from the target.\n\nThere are several different loss functions under the nn package.\nWe use `nn.CrossEntropyLoss()`.", "_____no_output_____" ] ], [ [ "input = torch.randn(1, 784) # a random input, for example\noutput = model(input) # output: (batch_size, num_classes)\nprint(output)\n\ntarget = torch.tensor([0]) # a dummy target, for example. target: (batch_size) where 0 <= each element < num_classes\ncriterion = nn.CrossEntropyLoss()\n\nloss = criterion(output, target)\nprint(loss)", "_____no_output_____" ] ], [ [ "Furtheremore, PyTorch supports several optimizers from `torch.optim`.\nWe use an Adam optimizer.", "_____no_output_____" ] ], [ [ "optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)", "_____no_output_____" ] ], [ [ "### DataLoader", "_____no_output_____" ] ], [ [ "# MNIST dataset \ntrain_dataset = torchvision.datasets.MNIST(root='./data', \n train=True, \n transform=transforms.ToTensor(), \n download=True)\n\ntest_dataset = torchvision.datasets.MNIST(root='./data', \n train=False, \n transform=transforms.ToTensor())\n\n# Data loader\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, \n batch_size=batch_size, \n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset, \n batch_size=batch_size, \n shuffle=False)\n\n# plot one example\nprint(train_dataset.train_data.size()) # (60000, 28, 28)\nprint(train_dataset.train_labels.size()) # (60000)\n\nidx = 0\nplt.title('%d' % train_dataset.train_labels[idx].item())\nplt.imshow(train_dataset.train_data[idx,:,:].numpy(), cmap='gray')", "_____no_output_____" ] ], [ [ "### Train the network", "_____no_output_____" ] ], [ [ "# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n running_loss = 0.0\n for i, (images, labels) in enumerate(train_loader): \n # Move tensors to the configured device\n images = images.reshape(-1, input_size).to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # zero the parameter gradients\n optimizer.zero_grad()\n # backward + optimize\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n if (i+1) % 100 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, running_loss / 100))\n running_loss = 0.0", "_____no_output_____" ] ], [ [ "### Test the network", "_____no_output_____" ] ], [ [ "# Test the model\n# In test phase, we don't need to compute gradients (for memory efficiency)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.reshape(-1, input_size).to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))", "_____no_output_____" ] ], [ [ "### Save/Load the network parameters", "_____no_output_____" ] ], [ [ "# Save the model checkpoint\ntorch.save(model.state_dict(), './data/nn_model.ckpt')\n\n# Load the model checkpoint if needed\n# new_model = NeuralNet(input_size, hidden_size, num_classes).to(device)\n# new_model.load_state_dict(torch.load('./data/nn_model.ckpt'))", "_____no_output_____" ] ], [ [ "## Practice: CIFAR10\n\n<img src=\"images/cifar10.png\" width=\"400\">\n\nThe CIFAR-10 dataset has the following specification:\n- The images in CIFAR-10 are of size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.\n- CIFAR-10 has the ten classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’.\n\nYou have to define a feed-foward neural network with two hidden layers for performing image classifcation on the CIFAR-10 dataset as well as train and test the network.", "_____no_output_____" ] ], [ [ "# Hyper-parameters\ninput_size = 3*32*32\nhidden1_size = 512\nhidden2_size = 128\nnum_classes = 10\nnum_epochs = 5\nbatch_size = 100\nlearning_rate = 0.001\n\n# Device configuration\ndevice = torch.device('cpu')\n\n# transform images 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))])\n\n\ntrain_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size,\n shuffle=True, num_workers=2)\n\ntest_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntest_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size,\n shuffle=False, num_workers=2)\n\n# Write the code to define a neural network with two hidden layers.\nclass Net(nn.Module):\n def __init__(self, input_size, hidden1_size, hidden2_size, num_classes):\n super(Net, self).__init__()\n # ============ YOUR CODE HERE ============\n \n # ========================================\n \n def forward(self, x):\n # ============ YOUR CODE HERE ============\n return x # DUMMY\n # ========================================\n\nmodel = Net(input_size, hidden1_size, hidden2_size, num_classes).to(device)\nprint(model)\n\n# Write the code to train and test the network.\n# ============ YOUR CODE HERE ============\n \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" ] ]
4aeee07d8d283915d047dbfec415b774266ddb75
152,943
ipynb
Jupyter Notebook
10_0_develop_new_OD_demand_estimator_Sioux_uni_class/archive/06_demands_adjustment_Sioux_backup_.ipynb
jingzbu/InverseVITraffic
c0d33d91bdd3c014147d58866c1a2b99fb8a9608
[ "MIT" ]
null
null
null
10_0_develop_new_OD_demand_estimator_Sioux_uni_class/archive/06_demands_adjustment_Sioux_backup_.ipynb
jingzbu/InverseVITraffic
c0d33d91bdd3c014147d58866c1a2b99fb8a9608
[ "MIT" ]
null
null
null
10_0_develop_new_OD_demand_estimator_Sioux_uni_class/archive/06_demands_adjustment_Sioux_backup_.ipynb
jingzbu/InverseVITraffic
c0d33d91bdd3c014147d58866c1a2b99fb8a9608
[ "MIT" ]
null
null
null
57.132238
48,506
0.638539
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4aeee5ac319d63b8d3d0cda9cf2b232a2ff12ca0
175,491
ipynb
Jupyter Notebook
doc/hu_fft.ipynb
Ptrskay3/PySprint
f90811970c66e8fadea1220c4c19bf95cdf33c9e
[ "MIT" ]
13
2020-05-29T14:53:13.000Z
2022-02-09T17:29:19.000Z
doc/hu_fft.ipynb
Ptrskay3/Interferometry
f90811970c66e8fadea1220c4c19bf95cdf33c9e
[ "MIT" ]
8
2019-10-14T18:23:26.000Z
2021-09-14T16:42:27.000Z
doc/hu_fft.ipynb
Ptrskay3/Interferometry
f90811970c66e8fadea1220c4c19bf95cdf33c9e
[ "MIT" ]
1
2020-10-07T06:42:17.000Z
2020-10-07T06:42:17.000Z
227.91039
37,872
0.919996
[ [ [ "## 7. Fourier-transzformációs módszer, FFTMethod", "_____no_output_____" ], [ "A kiértékelés a lépései:\n\n**betöltés &rarr; előfeldolgozás &rarr; IFFT &rarr; ablakolás &rarr; FFT &rarr; fázis**\n\nA programban is hasonló nevű a függvényeket kell meghívni. Az ajánlott sorrend a függvények hívásában a fenti folyamatábra, mivel nem garantált, hogy a tengelyek helyesen fognak transzformálódni tetszőleges sorrendű függvényhívások után.\n\n\nA bemutatást szimulált példákkal kezdem, majd rátérek egy mért interferogram kiértékelésére is.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pysprint as ps", "_____no_output_____" ], [ "g = ps.Generator(1, 4, 2.5, 1500, GDD=400, TOD=400, FOD=1000, pulse_width=4, resolution=0.05)\ng.generate_freq()", "_____no_output_____" ] ], [ [ "#### 7.1 Automatikus kiértékelés", "_____no_output_____" ] ], [ [ "f = ps.FFTMethod(*g.data)\nf.autorun(reference_point=2.5, order=4)", "Interferogram received.\nApplying IFFT...Done\nAcquiring gaussian window parameters...Done\nA 12 order gaussian window centered at 2670.46925 fs with FWHM 4055.08976 fs was applied.\n" ] ], [ [ "Egy másik automatikus kiértékelés (ugyan azon az interferogramon), ezúttal csak a fázist kapjuk meg. Ennek a fázisgrafikonnak a széleit kivágjuk a `slice` függvénnyel, majd a `fit` metódust használva számolhatjuk a diszperziós együtthatókat.", "_____no_output_____" ] ], [ [ "f2 = ps.FFTMethod(*g.data)\nphase = f.autorun(show_graph=False, enable_printing=False)\n\nprint(type(phase))\n\nphase.slice(1.1, 3.9)\n\nphase.fit(reference_point=2.5, order=4);", "c:\\pyt\\pysprint\\pysprint\\core\\_fft_tools.py:100: UserWarning: The peak is too close to the origin, manual control is advised.\n UserWarning,\n" ] ], [ [ "Bár látható volt, hogy a program jól határozta meg a Gauss ablakfüggvény paramétereit és ezáltal a diszperziós együtthatókat is, de jelzett, hogy a kivágandó csúcs túl közel van az origóhoz, így jobb ha azt manuálisan állítjuk be. Nézzük meg a fázist az illesztett görbével:", "_____no_output_____" ] ], [ [ "phase.plot()", "_____no_output_____" ] ], [ [ "Majd az illesztési hiba:", "_____no_output_____" ] ], [ [ "phase.errorplot(percent=True)", "_____no_output_____" ] ], [ [ "#### 7.2 Manuális kiértékelés\n\nNézzünk meg egy manuális kiértékelést. Itt a nekem meglévő interferogramot fogom használni, ami enyhén szólva sem ideális a Fourier-transzformációs kiértékeléshez, de megpróbálom a legtöbb használható információt kihozni belőle. Mivel már előre tudom hogy hogyan érdemes az ablakfüggvényt beállítani, így itt az ún. `inplace=False` argumentumot fogom használni. Alapvetően minden függvény amit meghívunk `inplace=True` módon hajtódik végre, azaz megváltoztatja magát az objektumot. Így működik pl. a python listáknál az `append` függvény:\n```python\n>>> a = []\n>>> a.append(1)\n>>> print(a)\n[1]\n```\nA csomag során sok függvénynél lehetőség van megadni az `inplace=False` argumentumot, ami nem változtatja meg magát az objektumot, hanem visszaad egy új másolatot belőle, és kért függvényt azon a másolaton fogja végrehajtani. Ennek két előnye van: Az eredeti objektum (és így vele minden eredetileg betöltött adatsor) megmarad, és anélkül hogy újra és újra betöltenénk más objektumba az adatokat, ezért elég belőle egy. A második előny pedig abból adódik, hogy megengedi a műveletek láncolását, ahogy az alábbi példa mutatja. ([fluent interfacing](https://en.wikipedia.org/wiki/Fluent_interface) and [method cascading](https://en.wikipedia.org/wiki/Method_cascading)) Itt a szokásos kiértékelési lépéseket hajtottam végre. Az utolsó függvény amit meghívtam rajta, az a `build_phase`, ami egy fázist ad vissza, ezért a hosszú láncolat után az lesz a visszatérített érték (ezt elneveztem `phase3`-nak).", "_____no_output_____" ] ], [ [ "f3 = ps.FFTMethod.parse_raw('datasets/ifg.trt', skiprows=8, meta_len=8, decimal=\",\", delimiter=\";\")\n\nphase3 = (\n f3.chdomain(inplace=False)\n .ifft(inplace=False)\n .window(at=145, fwhm=240, window_order=16, inplace=False)\n .apply_window(inplace=False)\n .fft(inplace=False)\n .build_phase()\n)", "_____no_output_____" ] ], [ [ "Itt a jobb olvashatóság miatt minden új függvénynél új sort kezdtem és zárójelbe tettem. Ezek nélkül így festene:", "_____no_output_____" ] ], [ [ "phase4 = f3.chdomain(inplace=False).ifft(inplace=False).window(at=145, fwhm=240, window_order=16, plot=False, inplace=False).apply_window(inplace=False).fft(inplace=False).build_phase()", "_____no_output_____" ] ], [ [ "Mivel nem volt ideális az interferogram vizsgáljuk meg milyen fázist kaptunk vissza.", "_____no_output_____" ] ], [ [ "phase3.plot()", "_____no_output_____" ] ], [ [ "Itt észrevehető, hogy vannak olyan részei a görbének, amely valóban tartalmazza a minta fázistulajdonságait. Vágjuk ki ezt a részt a `slice` függvénnyel.", "_____no_output_____" ] ], [ [ "phase3.slice(1.71, 2.72)\nphase3.plot()", "_____no_output_____" ] ], [ [ "Ezután végezzük el az illesztést a `fit` függvénnyel:", "_____no_output_____" ] ], [ [ "phase3.fit(reference_point=2.355, order=3);", "_____no_output_____" ] ], [ [ "A kapott diszperziós együtthatók valóban jó közelítéssel tükrözik a mintára jellemző (már egyéb módszerekkel meghatározott) koefficienseket. Vizsgáljuk meg az illesztési hibát is:", "_____no_output_____" ] ], [ [ "phase3.errorplot(percent=True)", "_____no_output_____" ] ], [ [ "Ugyan ez a kiértékelés hagyományosan, az `inplace=False` paraméterek nélkül így néz ki:", "_____no_output_____" ] ], [ [ "f4 = ps.FFTMethod.parse_raw('datasets/ifg.trt', skiprows=8, meta_len=8, decimal=\",\", delimiter=\";\")\n\nf4.chdomain()\n\nf4.ifft()\n\nf4.window(at=145, fwhm=240, window_order=16, plot=False)\n\nf4.apply_window()\n\nf4.fft()\n\nphase4 = f4.build_phase()\n\nphase4.slice(1.71, 2.72)\n\nphase4.fit(2.355, 3);", "_____no_output_____" ] ], [ [ "Próbáljuk meg az impulzus időbeli alakját kiszámolni. Ehhez a `get_pulse_shape_from_file` függvényt fogom használni, aminek a tárgykar spektrumát adom meg.", "_____no_output_____" ] ], [ [ "x_t, y_t = f4.get_pulse_shape_from_file(\"datasets/sam.trt\", truncate=True, chdomain=True, skiprows=8, decimal=\",\", sep=\";\")", "_____no_output_____" ], [ "plt.plot(x_t, y_t)\nplt.grid()\nplt.xlabel(\"t [fs]\");", "_____no_output_____" ] ], [ [ "Mivel a használt interferogram nem volt ideális, így itt az impulzus alakját nem lehetett tökéletesen visszakapni.\n\nAlapértelmezetten néhány dolog el van rejtve a felhasználó elől. Az előző `get_pulse_shape_from_file` függvényt újra lefuttatom, ezúttal teljes logging outputtal. Ezt szinte soha nem kell használnunk, itt is csak a magyarázat miatt van létjogosultsága.", "_____no_output_____" ] ], [ [ "import logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\nx_t, y_t = f4.get_pulse_shape_from_file(\"datasets/sam.trt\", truncate=True, chdomain=True, skiprows=8, decimal=\",\", sep=\";\")", "[ fftmethod.py:399 - get_pulse_shape_from_array() ] Shapes were truncated from 2.3226283197396467 to 2.7198388115237 with length 287.\n" ] ], [ [ "Látható, hogy *2.322* és *2.719 PHz* között 287 adatpontnál sikerült kiszámítani a \n $I(t) = |\\mathcal{F}^{-1}\\{\\sqrt{|I_{tárgy}(\\omega)|}\\cdot e^{-i\\Phi{(\\omega)}}\\}|^2$\nkifejezés értékét. Ez annak köszönhető, hogy a kiszámolt fázist elég nagy tartományban nem tudtuk felhasználni (eredetileg a *1.71 - 2.72* *PHz* tartományt vágtuk ki), illetve az transzformációk során behozott numerikus hiba is közrejátszott.\n\n\n#### 7.3 NUFFT\n\nVégül a Non-unifrom FFT használata. Itt teljesen ugyan azt hajtom végre, mint fentebb, csak `usenifft=True` argumentummal.", "_____no_output_____" ] ], [ [ "# csak visszaállítom a log szintet az alapértelmezettre, hogy ne árassza el a képernyőt\nlogger.setLevel(logging.ERROR)\n\nf5 = ps.FFTMethod.parse_raw('datasets/ifg.trt', skiprows=8, meta_len=8, decimal=\",\", delimiter=\";\")\n\nf5.chdomain()\n\nf5.ifft(usenifft=True)\n\nf5.window(at=155, fwhm=260, window_order=16, plot=False)\n\nf5.apply_window()\n\nf5.fft()\n\nphase6 = f5.build_phase()\n\nphase6.slice(None, 2.49)\nphase6.fit(2.355, 3);\nphase6.plot()", "_____no_output_____" ] ], [ [ "A szimulációk alapján a NUFFT valamivel pontatlanabb eredményt ad, mint az interpoláció + FFT.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4aeef0463af869dd7a9ff3c082a19bff8112935b
505,481
ipynb
Jupyter Notebook
week04/.ipynb_checkpoints/Untitled-checkpoint.ipynb
UIUC-iSchool-DataViz/spring2019online
e586cfafd90d6de38c308bf8ad072c9a4ed8485b
[ "BSD-3-Clause" ]
1
2019-08-11T04:03:24.000Z
2019-08-11T04:03:24.000Z
_site/week04/inClassNotes_week04.ipynb
UIUC-iSchool-DataViz/spring2019online
e586cfafd90d6de38c308bf8ad072c9a4ed8485b
[ "BSD-3-Clause" ]
1
2020-03-02T00:11:33.000Z
2020-03-02T00:11:33.000Z
_site/week04/inClassNotes_week04.ipynb
UIUC-iSchool-DataViz/spring2019online
e586cfafd90d6de38c308bf8ad072c9a4ed8485b
[ "BSD-3-Clause" ]
1
2020-03-09T16:13:34.000Z
2020-03-09T16:13:34.000Z
129.577288
90,204
0.789505
[ [ [ "# our usual things!\n%matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np", "_____no_output_____" ], [ "# weather in Champaign!\nw = pd.read_csv(\"/Users/jillnaiman1/Downloads/2018_ChampaignWeather.csv\")", "_____no_output_____" ], [ "w", "_____no_output_____" ], [ "# sort by date\nw.sort_values(by='DATE') # w is our pandas dataframe, sort_values is a pandas call\ntype(w['DATE'])\n\nw['DATE'] = pd.to_datetime(w['DATE']) # changing to datetime format\n\n# lets just look at 1 station\nmask = w['NAME'] == 'CHAMPAIGN 3 S, IL US'\nmask\n\n# minium temperature during a day of 2018\nplt.plot(w['DATE'][mask], w['TMIN'][mask], label='Min Temp')\nplt.plot(w['DATE'][mask], w['TMAX'][mask], label='Max Temp')\n\n# label our axes\nplt.xlabel('Date')\nplt.ylabel('Temp in F')\nplt.legend()\n\n# make our plots a bit bigger\nplt.rcParams['figure.dpi'] = 100", "_____no_output_____" ] ], [ [ "# Histograms & Rolling Averages", "_____no_output_____" ] ], [ [ "mean_temp = 0.5*(w['TMIN']+w['TMAX'])[mask]\n\nimport ipywidgets # interactivity\n\n# make our data look less noisy with rolling averages\[email protected](window=(1,40,1))\ndef make_plot(window):\n mean_temp_avg = mean_temp.rolling(window=window).mean()\n plt.plot(mean_temp, marker='.', linewidth=0.5, alpha=0.5)\n plt.plot(mean_temp_avg, marker='.', linewidth=1.5)\n plt.xlabel('Date')\n plt.ylabel('Mean Daily Temp in F')", "_____no_output_____" ], [ "w.keys()", "_____no_output_____" ], [ "precp = w['PRCP'][mask]\n\n# we want to format our dates correctly\nimport matplotlib.dates as mdates\n\nset_ind = False\nfor k in w.keys():\n if k.find('DATE') != -1: # have we indexed by date yet?\n set_ind = True\n\nif set_ind: w.set_index('DATE', inplace=True)\n#w['PRCP']\n#w\n\n", "_____no_output_____" ], [ "names = ['SteveBob', 'Jerry', 'Frank']\nfor n in names:\n print(n.find('Bob'))", "5\n-1\n-1\n" ], [ "# because we have re-indexed, lets redefine our arrays\nmask = w['NAME'] == 'CHAMPAIGN 3 S, IL US'\nmean_temp = 0.5*(w['TMIN']+w['TMAX'])[mask]\nprecp = w['PRCP'][mask]\n\[email protected](window=(1,60,2))\ndef make_plot(window):\n fig, ax = plt.subplots(1,2, figsize=(10,4))\n # (2) This was right-handed binning\n #mean_temp_avg = mean_temp.rolling(window=window).mean()\n mean_temp_avg = mean_temp.rolling(window=window, center=True).mean()\n mean_temp.plot(ax=ax[0]) # using pandas to plot\n mean_temp_avg.plot(ax=ax[0])\n \n # (1) We tried this, but its not highlighting what\n # we want\n #precp_avg = precp.rolling(window=window).mean()\n # (2) This was right-handed binning\n #precp_avg = precp.rolling(window=window).sum()\n precp_avg = precp.rolling(window=window, center=True).sum()\n precp.plot(ax=ax[1], marker='.', linewidth=0.5, alpha=0.5)\n precp_avg.plot(ax=ax[1], marker='.', linewidth=1.5)\n \n ax[1].set_xlabel('Date')\n ax[1].set_ylabel('Daily rainfall in inches')\n ax[0].set_xlabel('Date')\n ax[0].set_ylabel('Mean Daily Temp in F')", "_____no_output_____" ], [ "precp.rolling?", "_____no_output_____" ], [ "# now lets look at a binning example for our rainfall data\n# this is a strict histogram/rebinning exercise, NOT smoothing\n# Note: rolling averages/sums as we've been using, is somewhere\n# between smoothing & binning\n\[email protected](window=(1,60,1), day_bins=(1,100,5))\ndef make_plot(window,day_bins):\n fig, ax = plt.subplots(1,2,figsize=(10,4))\n \n mean_temp_avg = mean_temp.rolling(window=window,center=True).mean()\n mean_temp.plot(ax=ax[0])\n mean_temp_avg.plot(ax=ax[0])\n \n precp.plot(ax=ax[1], marker='.', linewidth=0.5, alpha=0.5)\n precp_resampled = precp.resample(str(day_bins)+'D').sum()\n # day_bins = 5 => '5D', resampling by months is 'M'\n precp_resampled.plot(ax=ax[1], marker='.')\n \n ax[1].set_xlabel('Date')\n ax[1].set_ylabel('Summed Rainfall over ' + str(day_bins) + 'days, in Inches')\n ax[0].set_xlabel('Date')\n ax[0].set_ylabel('Mean Daily Temp in F')", "_____no_output_____" ] ], [ [ "## Take aways\n* rolling averages => smoothing-lite, or fancy binning => like on our left temp plot\n* on the right rainfall plot => HISTOGRAM\n\n* so, in binning or histograming we are more \"truthful\" to the originial data, where in smoothing we can \"double count\" data points across bins", "_____no_output_____" ], [ "## Quick look at windowing\nToy example first", "_____no_output_____" ] ], [ [ "# window of 10 bins, constant data in the window\nnpoints = 10\nx = np.arange(0,npoints)\ny = np.repeat(1,npoints)\nplt.plot(x,y,'o', label='Original Data')\n\n# so lets say we really want to highlight the center\n# bins\nplt.plot(x,y*np.bartlett(npoints),'o', label='Bartlett')\n# also another type of window\nplt.plot(x,y*np.hamming(npoints),'o',label='Hamming')\nplt.legend()", "_____no_output_____" ], [ "# plot available windows\nwindows_avail = [None,'boxcar','triang','blackman','hamming',\n 'bartlett','parzen', 'bohman', \n 'blackmanharris','nuttall','barthann']\n\[email protected](window=(1,100,1), window_type=windows_avail)\ndef make_plot(window, window_type):\n plt.plot(mean_temp)\n mean_temp_avg = mean_temp.rolling(window=window,center=True,win_type=window_type).mean()\n plt.plot(mean_temp_avg)\n", "_____no_output_____" ] ], [ [ "# Similar binning & Smoothing in 2D", "_____no_output_____" ] ], [ [ "ufos = pd.read_csv(\"/Users/jillnaiman1/Downloads/ufo-scrubbed-geocoded-time-standardized-00.csv\",\n names = [\"date\", \"city\", \"state\", \"country\",\n \"shape\", \"duration_seconds\", \"duration\",\n \"comment\", \"report_date\", \"latitude\", \"longitude\"],\n parse_dates = [\"date\", \"report_date\"])\n# if you get a memory error, don't panic!", "_____no_output_____" ], [ "ufos", "_____no_output_____" ], [ "# quick plot\nplt.plot(ufos['longitude'], ufos['latitude'],'.')", "_____no_output_____" ], [ "# colormaps\nimport matplotlib.cm as cm\nplt.colormaps()", "_____no_output_____" ], [ "plt.scatter(ufos['longitude'],ufos['latitude'],c=np.log10(ufos['duration_seconds']))", "_____no_output_____" ], [ "plt.scatter(ufos['longitude'][0:10], ufos['latitude'][0:10],c=ufos['duration_seconds'][0:10])", "_____no_output_____" ], [ "# our data is hard to see, lets try some rebinning in 2D\nplt.hexbin(ufos[\"longitude\"], ufos[\"latitude\"], ufos[\"duration_seconds\"], gridsize=32,bins='log')\n# almost the exact same thing we did with histograms before in 1D for our rainfall data", "_____no_output_____" ], [ "# can also smooth 2D images\nimport PIL.Image as Image\nim = Image.open('/Users/jillnaiman1/Downloads/stitch_reworked.png')\n\nfig,ax = plt.subplots(figsize=(5,5))\nax.imshow(im)", "_____no_output_____" ], [ "import PIL.ImageFilter as ImageFilter\n\nmyFilter = ImageFilter.GaussianBlur(radius=1)\nsmoothed_image = im.filter(myFilter)\nfig,ax = plt.subplots(figsize=(5,5))\nax.imshow(smoothed_image)", "_____no_output_____" ], [ "data_im = np.array(im)\nnp.unique(data_im)", "_____no_output_____" ], [ "data_sm = np.array(smoothed_image)\nnp.unique(data_sm)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aeef342042558885fd3792f2529cf2c60d64e53
51,556
ipynb
Jupyter Notebook
LogisticRegression multi layers.ipynb
MRYingLEE/Deep-Learning-Project
21c0a92274ed605776f960b385826bb88adc5a23
[ "MIT" ]
null
null
null
LogisticRegression multi layers.ipynb
MRYingLEE/Deep-Learning-Project
21c0a92274ed605776f960b385826bb88adc5a23
[ "MIT" ]
null
null
null
LogisticRegression multi layers.ipynb
MRYingLEE/Deep-Learning-Project
21c0a92274ed605776f960b385826bb88adc5a23
[ "MIT" ]
null
null
null
138.96496
12,962
0.80495
[ [ [ "# Lab 2 - Logistic Regression (LR) with MNIST\n\nThis lab corresponds to Module 2 of the \"Deep Learning Explained\" course. We assume that you have successfully completed Lab 1 (Downloading the MNIST data).\n\nIn this lab we will build and train a Multiclass Logistic Regression model using the MNIST data. \n\n## Introduction\n\n**Problem**:\nOptical Character Recognition (OCR) is a hot research area and there is a great demand for automation. The MNIST data is comprised of hand-written digits with little background noise making it a nice dataset to create, experiment and learn deep learning models with reasonably small comptuing resources.", "_____no_output_____" ], [ "**Goal**:\nOur goal is to train a classifier that will identify the digits in the MNIST dataset. \n\n**Approach**:\nThere are 4 stages in this lab: \n- **Data reading**: We will use the CNTK Text reader. \n- **Data preprocessing**: Covered in part A (suggested extension section). \n- **Model creation**: Multiclass Logistic Regression model.\n- **Train-Test-Predict**: This is the same workflow introduced in the lectures", "_____no_output_____" ], [ "## Logistic Regression\n[Logistic Regression](https://en.wikipedia.org/wiki/Logistic_regression) (LR) is a fundamental machine learning technique that uses a linear weighted combination of features and generates probability-based predictions of different classes. \n\nThere are two basic forms of LR: **Binary LR** (with a single output that can predict two classes) and **multiclass LR** (with multiple outputs, each of which is used to predict a single class). \n\n![LR-forms](http://www.cntk.ai/jup/cntk103b_TwoFormsOfLR-v3.png)", "_____no_output_____" ], [ "In **Binary Logistic Regression** (see top of figure above), the input features are each scaled by an associated weight and summed together. The sum is passed through a squashing (aka activation) function and generates an output in [0,1]. This output value is then compared with a threshold (such as 0.5) to produce a binary label (0 or 1), predicting 1 of 2 classes. This technique supports only classification problems with two output classes, hence the name binary LR. In the binary LR example shown above, the [sigmoid][] function is used as the squashing function.\n\n[sigmoid]: https://en.wikipedia.org/wiki/Sigmoid_function", "_____no_output_____" ], [ "In **Multiclass Linear Regression** (see bottom of figure above), 2 or more output nodes are used, one for each output class to be predicted. Each summation node uses its own set of weights to scale the input features and sum them together. Instead of passing the summed output of the weighted input features through a sigmoid squashing function, the output is often passed through a [softmax][] function (which in addition to squashing, like the sigmoid, the softmax normalizes each nodes' output value using the sum of all unnormalized nodes). (Details in the context of MNIST image to follow)\n\nWe will use multiclass LR for classifying the MNIST digits (0-9) using 10 output nodes (1 for each of our output classes). In our approach, we will move the softmax function out of the model and into our Loss function used in training (details to follow).\n\n[softmax]: https://en.wikipedia.org/wiki/Softmax_function", "_____no_output_____" ] ], [ [ "# Import the relevant components\nfrom IPython.display import Image\nfrom __future__ import print_function # Use a function definition from future version (say 3.x from 2.7 interpreter)\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport os\n\nimport cntk as C\n\n%matplotlib inline", "_____no_output_____" ] ], [ [ "In the block below, we check if we are running this notebook in the CNTK internal test machines by looking for environment variables defined there. We then select the right target device (GPU vs CPU) to test this notebook. In other cases, we use CNTK's default policy to use the best available device (GPU, if available, else CPU).", "_____no_output_____" ] ], [ [ "# Select the right target device when this notebook is being tested:\nif 'TEST_DEVICE' in os.environ:\n if os.environ['TEST_DEVICE'] == 'cpu':\n C.device.try_set_default_device(C.device.cpu())\n else:\n C.device.try_set_default_device(C.device.gpu(0))", "_____no_output_____" ], [ "# Test for CNTK version\n#if not C.__version__ == \"2.0\":\n# raise Exception(\"this lab is designed to work with 2.0. Current Version: \" + C.__version__) ", "_____no_output_____" ] ], [ [ "## Initialization", "_____no_output_____" ] ], [ [ "# Ensure we always get the same amount of randomness\nnp.random.seed(0)\nC.cntk_py.set_fixed_random_seed(1)\nC.cntk_py.force_deterministic_algorithms()\n\n# Define the data dimensions\ninput_dim = 256 #784\nnum_output_classes = 11 #10", "_____no_output_____" ] ], [ [ "## Data reading\n\nThere are different ways one can read data into CNTK. The easiest way is to load the data in memory using NumPy / SciPy / Pandas readers. However, this can be done only for small data sets. Since deep learning requires large amount of data we have chosen in this course to show how to leverage built-in distributed readers that can scale to terrabytes of data with little extra effort. \n\nWe are using the MNIST data you have downloaded using Lab 1 DataLoader notebook. The dataset has 60,000 training images and 10,000 test images with each image being 28 x 28 pixels. Thus the number of features is equal to 784 (= 28 x 28 pixels), 1 per pixel. The variable `num_output_classes` is set to 10 corresponding to the number of digits (0-9) in the dataset.\n\nIn Lab 1, the data was downloaded and written to 2 CTF (CNTK Text Format) files, 1 for training, and 1 for testing. Each line of these text files takes the form:\n\n |labels 0 0 0 1 0 0 0 0 0 0 |features 0 0 0 0 ... \n (784 integers each representing a pixel)\n \nWe are going to use the image pixels corresponding the integer stream named \"features\". We define a `create_reader` function to read the training and test data using the [CTF deserializer](https://cntk.ai/pythondocs/cntk.io.html?highlight=ctfdeserializer#cntk.io.CTFDeserializer). The labels are [1-hot encoded](https://en.wikipedia.org/wiki/One-hot). Refer to Lab 1 for data format visualizations. ", "_____no_output_____" ] ], [ [ "# Read a CTF formatted text (as mentioned above) using the CTF deserializer from a file\ndef create_reader(path, is_training, input_dim, num_label_classes):\n \n labelStream = C.io.StreamDef(field='labels', shape=num_label_classes, is_sparse=False)\n featureStream = C.io.StreamDef(field='features', shape=input_dim, is_sparse=False)\n \n deserailizer = C.io.CTFDeserializer(path, C.io.StreamDefs(labels = labelStream, features = featureStream))\n \n return C.io.MinibatchSource(deserailizer,\n randomize = is_training, max_sweeps = C.io.INFINITELY_REPEAT if is_training else 1)", "_____no_output_____" ], [ "# Ensure the training and test data is generated and available for this lab.\n# We search in two locations in the toolkit for the cached MNIST data set.\ndata_found = False\n\nfor data_dir in [os.path.join(\".\", \"PLAID\")]:\n train_file = os.path.join(data_dir, \"train_log.txt\")\n test_file = os.path.join(data_dir, \"test_log.txt\")\n if os.path.isfile(train_file) and os.path.isfile(test_file):\n data_found = True\n break\n \nif not data_found:\n raise ValueError(\"Please generate the data by completing Lab1_MNIST_DataLoader\")\n \nprint(\"Data directory is {0}\".format(data_dir))", "Data directory is ./PLAID\n" ] ], [ [ "# Model Creation\n\nA multiclass logistic regression (LR) network is a simple building block that has been effectively powering many ML \napplications in the past decade. The figure below summarizes the model in the context of the MNIST data.\n\n![mnist-LR](https://www.cntk.ai/jup/cntk103b_MNIST_LR.png)\n\nLR is a simple linear model that takes as input, a vector of numbers describing the properties of what we are classifying (also known as a feature vector, $\\bf \\vec{x}$, the pixels in the input MNIST digit image) and emits the *evidence* ($z$). For each of the 10 digits, there is a vector of weights corresponding to the input pixels as show in the figure. These 10 weight vectors define the weight matrix ($\\bf {W}$) with dimension of 10 x 784. Each feature in the input layer is connected with a summation node by a corresponding weight $w$ (individual weight values from the $\\bf{W}$ matrix). Note there are 10 such nodes, 1 corresponding to each digit to be classified. ", "_____no_output_____" ], [ "The first step is to compute the evidence for an observation. \n\n$$\\vec{z} = \\textbf{W} \\bf \\vec{x}^T + \\vec{b}$$ \n\nwhere $\\bf{W}$ is the weight matrix of dimension 10 x 784 and $\\vec{b}$ is known as the *bias* vector with lenght 10, one for each digit. \n\nThe evidence ($\\vec{z}$) is not squashed (hence no activation). Instead the output is normalized using a [softmax](https://en.wikipedia.org/wiki/Softmax_function) function such that all the outputs add up to a value of 1, thus lending a probabilistic iterpretation to the prediction. In CNTK, we use the softmax operation combined with the cross entropy error as our Loss Function for training.", "_____no_output_____" ] ], [ [ "#2nd submission, we use 2, 400 respectively\n#3rd submission, we use 4, 100 respectively\n#4rd submission, we use 4, 200 respectively\n\nnum_hidden_layers = 8\nhidden_layers_dim = 400", "_____no_output_____" ] ], [ [ "Network input and output: \n- **input** variable (a key CNTK concept): \n>An **input** variable is a container in which we fill different observations, in this case image pixels, during model learning (a.k.a.training) and model evaluation (a.k.a. testing). Thus, the shape of the `input` must match the shape of the data that will be provided. For example, when data are images each of height 10 pixels and width 5 pixels, the input feature dimension will be 50 (representing the total number of image pixels).\n\n\n**Knowledge Check:** What is the input dimension of your chosen model? This is fundamental to our understanding of variables in a network or model representation in CNTK.", "_____no_output_____" ] ], [ [ "input = C.input_variable(input_dim)\nlabel = C.input_variable(num_output_classes)", "_____no_output_____" ] ], [ [ "## Logistic Regression network setup\n\nThe CNTK Layers module provides a Dense function that creates a fully connected layer which performs the above operations of weighted input summing and bias addition. ", "_____no_output_____" ] ], [ [ "def create_model(features):\n with C.layers.default_options(init = C.layers.glorot_uniform(), activation = C.ops.relu):\n h = features\n for _ in range(num_hidden_layers):\n h = C.layers.Dense(hidden_layers_dim)(h)\n r = C.layers.Dense(num_output_classes, activation = None)(h)\n return r\n ", "_____no_output_____" ] ], [ [ "`z` will be used to represent the output of a network.", "_____no_output_____" ] ], [ [ "# Scale the input to 0-1 range by dividing each pixel by 255.\n#input_s = input/255\nz = create_model(input)", "_____no_output_____" ] ], [ [ "## Training\n\nBelow, we define the **Loss** function, which is used to guide weight changes during training. \n\nAs explained in the lectures, we use the `softmax` function to map the accumulated evidences or activations to a probability distribution over the classes (Details of the [softmax function][] and other [activation][] functions).\n\n[softmax function]: http://cntk.ai/pythondocs/cntk.ops.html#cntk.ops.softmax\n\n[activation]: https://github.com/Microsoft/CNTK/wiki/Activation-Functions\n\nWe minimize the cross-entropy between the label and predicted probability by the network.", "_____no_output_____" ] ], [ [ "loss = C.cross_entropy_with_softmax(z, label)", "_____no_output_____" ] ], [ [ "#### Evaluation\n\nBelow, we define the **Evaluation** (or metric) function that is used to report a measurement of how well our model is performing.\n\nFor this problem, we choose the **classification_error()** function as our metric, which returns the average error over the associated samples (treating a match as \"1\", where the model's prediction matches the \"ground truth\" label, and a non-match as \"0\").", "_____no_output_____" ] ], [ [ "label_error = C.classification_error(z, label)", "_____no_output_____" ] ], [ [ "### Configure training\n\nThe trainer strives to reduce the `loss` function by different optimization approaches, [Stochastic Gradient Descent][] (`sgd`) being one of the most popular. Typically, one would start with random initialization of the model parameters. The `sgd` optimizer would calculate the `loss` or error between the predicted label against the corresponding ground-truth label and using [gradient-decent][] generate a new set model parameters in a single iteration. \n\nThe aforementioned model parameter update using a single observation at a time is attractive since it does not require the entire data set (all observation) to be loaded in memory and also requires gradient computation over fewer datapoints, thus allowing for training on large data sets. However, the updates generated using a single observation sample at a time can vary wildly between iterations. An intermediate ground is to load a small set of observations and use an average of the `loss` or error from that set to update the model parameters. This subset is called a *minibatch*.\n\nWith minibatches, we sample observations from the larger training dataset. We repeat the process of model parameters update using different combination of training samples and over a period of time minimize the `loss` (and the error metric). When the incremental error rates are no longer changing significantly or after a preset number of maximum minibatches to train, we claim that our model is trained.\n\nOne of the key optimization parameters is called the `learning_rate`. For now, we can think of it as a scaling factor that modulates how much we change the parameters in any iteration.\nWith this information, we are ready to create our trainer. \n\n[optimization]: https://en.wikipedia.org/wiki/Category:Convex_optimization\n[Stochastic Gradient Descent]: https://en.wikipedia.org/wiki/Stochastic_gradient_descent\n[gradient-decent]: http://www.statisticsviews.com/details/feature/5722691/Getting-to-the-Bottom-of-Regression-with-Gradient-Descent.html", "_____no_output_____" ] ], [ [ "# Instantiate the trainer object to drive the model training\nlearning_rate = 0.2\nlr_schedule = C.learning_rate_schedule(learning_rate, C.UnitType.minibatch)\nlearner = C.sgd(z.parameters, lr_schedule)\ntrainer = C.Trainer(z, (loss, label_error), [learner])", "_____no_output_____" ] ], [ [ "First let us create some helper functions that will be needed to visualize different functions associated with training.", "_____no_output_____" ] ], [ [ "# Define a utility function to compute the moving average sum.\n# A more efficient implementation is possible with np.cumsum() function\ndef moving_average(a, w=5):\n if len(a) < w:\n return a[:] # Need to send a copy of the array\n return [val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)]\n\n\n# Defines a utility that prints the training progress\ndef print_training_progress(trainer, mb, frequency, verbose=1):\n training_loss = \"NA\"\n eval_error = \"NA\"\n\n if mb%frequency == 0:\n training_loss = trainer.previous_minibatch_loss_average\n eval_error = trainer.previous_minibatch_evaluation_average\n if verbose: \n print (\"Minibatch: {0}, Loss: {1:.4f}, Error: {2:.2f}%\".format(mb, training_loss, eval_error*100))\n \n return mb, training_loss, eval_error", "_____no_output_____" ] ], [ [ "<a id='#Run the trainer'></a>\n### Run the trainer\n\nWe are now ready to train our fully connected neural net. We want to decide what data we need to feed into the training engine.\n\nIn this example, each iteration of the optimizer will work on `minibatch_size` sized samples. We would like to train on all 60000 observations. Additionally we will make multiple passes through the data specified by the variable `num_sweeps_to_train_with`. With these parameters we can proceed with training our simple feed forward network.", "_____no_output_____" ] ], [ [ "# Initialize the parameters for the trainer\nminibatch_size = 64\nnum_samples_per_sweep = 60000\nnum_sweeps_to_train_with = 10\nnum_minibatches_to_train = (num_samples_per_sweep * num_sweeps_to_train_with) / minibatch_size", "_____no_output_____" ], [ "# Create the reader to training data set\nreader_train = create_reader(train_file, True, input_dim, num_output_classes)\n\n# Map the data streams to the input and labels.\ninput_map = {\n label : reader_train.streams.labels,\n input : reader_train.streams.features\n} \n\n# Run the trainer on and perform model training\ntraining_progress_output_freq = 500\n\nplotdata = {\"batchsize\":[], \"loss\":[], \"error\":[]}\n\nfor i in range(0, int(num_minibatches_to_train)):\n \n # Read a mini batch from the training data file\n data = reader_train.next_minibatch(minibatch_size, input_map = input_map)\n \n trainer.train_minibatch(data)\n batchsize, loss, error = print_training_progress(trainer, i, training_progress_output_freq, verbose=1)\n \n if not (loss == \"NA\" or error ==\"NA\"):\n plotdata[\"batchsize\"].append(batchsize)\n plotdata[\"loss\"].append(loss)\n plotdata[\"error\"].append(error)", "Minibatch: 0, Loss: 2.4005, Error: 98.44%\nMinibatch: 500, Loss: 1.8469, Error: 67.19%\nMinibatch: 1000, Loss: 1.1192, Error: 39.06%\nMinibatch: 1500, Loss: 0.8105, Error: 29.69%\nMinibatch: 2000, Loss: 0.8246, Error: 31.25%\nMinibatch: 2500, Loss: 0.5015, Error: 18.75%\nMinibatch: 3000, Loss: 0.5727, Error: 25.00%\nMinibatch: 3500, Loss: 0.4437, Error: 17.19%\nMinibatch: 4000, Loss: 0.0690, Error: 1.56%\nMinibatch: 4500, Loss: 0.3484, Error: 10.94%\nMinibatch: 5000, Loss: 0.1216, Error: 1.56%\nMinibatch: 5500, Loss: 0.0283, Error: 1.56%\nMinibatch: 6000, Loss: 0.1454, Error: 4.69%\nMinibatch: 6500, Loss: 0.0140, Error: 0.00%\nMinibatch: 7000, Loss: 0.0305, Error: 1.56%\nMinibatch: 7500, Loss: 0.0108, Error: 0.00%\nMinibatch: 8000, Loss: 0.0221, Error: 1.56%\nMinibatch: 8500, Loss: 0.0171, Error: 0.00%\nMinibatch: 9000, Loss: 0.0160, Error: 1.56%\n" ] ], [ [ "Let us plot the errors over the different training minibatches. Note that as we progress in our training, the loss decreases though we do see some intermediate bumps. ", "_____no_output_____" ] ], [ [ "# Compute the moving average loss to smooth out the noise in SGD\nplotdata[\"avgloss\"] = moving_average(plotdata[\"loss\"])\nplotdata[\"avgerror\"] = moving_average(plotdata[\"error\"])\n\n# Plot the training loss and the training error\nimport matplotlib.pyplot as plt\n\nplt.figure(1)\nplt.subplot(211)\nplt.plot(plotdata[\"batchsize\"], plotdata[\"avgloss\"], 'b--')\nplt.xlabel('Minibatch number')\nplt.ylabel('Loss')\nplt.title('Minibatch run vs. Training loss')\n\nplt.show()\n\nplt.subplot(212)\nplt.plot(plotdata[\"batchsize\"], plotdata[\"avgerror\"], 'r--')\nplt.xlabel('Minibatch number')\nplt.ylabel('Label Prediction Error')\nplt.title('Minibatch run vs. Label Prediction Error')\nplt.show()", "_____no_output_____" ] ], [ [ "## Evaluation / Testing \n\nNow that we have trained the network, let us evaluate the trained network on the test data. This is done using `trainer.test_minibatch`.", "_____no_output_____" ] ], [ [ "out = C.softmax(z)", "_____no_output_____" ], [ "# Read the data for evaluation\nreader_eval = create_reader(test_file, False, input_dim, num_output_classes)\n\neval_minibatch_size = 1\neval_input_map = {input: reader_eval.streams.features} \n\nnum_samples = 659\nnum_minibatches_to_test = num_samples // eval_minibatch_size\ntest_result = 0.0\n\nresults=[]\n\nfor i in range(num_minibatches_to_test):\n data = reader_eval.next_minibatch(eval_minibatch_size, input_map = eval_input_map)\n\n #img_label = data[label].asarray()\n img_data = data[input].asarray()\n predicted_label_prob = [out.eval(img_data[i]) for i in range(len(img_data))]\n pred = [np.argmax(predicted_label_prob[i]) for i in range(len(predicted_label_prob))]\n #print(predicted_label_prob)\n results.extend(pred )\n\n#print(results)", "_____no_output_____" ], [ "np.savetxt(str(num_hidden_layers)+\"x\"+str(hidden_layers_dim)+\"_log.csv\", np.array(results).astype(int), fmt='%i', delimiter=\",\")", "_____no_output_____" ] ], [ [ "We have so far been dealing with aggregate measures of error. Let us now get the probabilities associated with individual data points. For each observation, the `eval` function returns the probability distribution across all the classes. The classifier is trained to recognize digits, hence has 10 classes. First let us route the network output through a `softmax` function. This maps the aggregated activations across the network to probabilities across the 10 classes.", "_____no_output_____" ], [ "Let us test a small minibatch sample from the test data.", "_____no_output_____" ], [ "As you can see above, our model is not yet perfect. \n\nLet us visualize one of the test images and its associated label. Do they match?", "_____no_output_____" ], [ "**Suggested Explorations**\n\nA. Change the `minibatch_size` parameter (from 64) to 128 and then to 512 during training. What is the observed average test error rate (rounded to 2nd decimal place) with each new model?\n\nB. Increase the number of sweeps. How does the test error change?\n\nC. Can you change the network to reduce the training error rate? When do you see *overfitting* happening? \n\nD. Lets now add more features to our model. We will add square of the input values as additional features. You will take the input pixels, scale them by 255. Use `C.square` and `C.splice` functions to create a new model. Use this model to perform classification. Note: use the original setting for the rest of the notebook\n\nE. Now add sqrt as another set of features to the model. Use this model to perform classification.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
4aeef72932e374fffdbc992de267741168a20337
135,677
ipynb
Jupyter Notebook
examples/GeoNet_FDSN_demo_station.ipynb
sorennh/fdsn
45fb3462a249e6d2749bcb1f765183d87e4d87ff
[ "MIT" ]
14
2017-06-01T23:13:05.000Z
2022-03-25T03:28:30.000Z
examples/GeoNet_FDSN_demo_station.ipynb
sorennh/fdsn
45fb3462a249e6d2749bcb1f765183d87e4d87ff
[ "MIT" ]
101
2017-05-31T06:08:16.000Z
2022-03-21T23:52:53.000Z
examples/GeoNet_FDSN_demo_station.ipynb
sorennh/fdsn
45fb3462a249e6d2749bcb1f765183d87e4d87ff
[ "MIT" ]
21
2017-05-31T20:57:41.000Z
2022-01-04T21:47:39.000Z
440.50974
82,522
0.928241
[ [ [ "# GeoNet FDSN webservice with Obspy demo - Station Service\n\nThis demo introduces some simple code that requests data using [GeoNet's FDSN webservices](http://www.geonet.org.nz/data/tools/FDSN) and the [obspy module](https://github.com/obspy/obspy/wiki) in python. This notebook uses Python 3. \n\n### Getting Started - Import Modules", "_____no_output_____" ] ], [ [ "from obspy import UTCDateTime\nfrom obspy.clients.fdsn import Client as FDSN_Client\nfrom obspy import read_inventory", "_____no_output_____" ] ], [ [ "### Define GeoNet FDSN client", "_____no_output_____" ] ], [ [ "client = FDSN_Client(\"GEONET\")", "_____no_output_____" ] ], [ [ "## Accessing Station Metadata\nUse the **station** service to access station metadata from GeoNet stations. \n\nNote, that metadata provided is prodominately associated with data types available from the FDSN archive, and therefore does not include things such as Geodetic station information. \n\nThis example gets all stations that are operating at the time of the Kaikoura earthquake and that are located within a 0.5 degrees radius of the epicentre. It lists the station codes and plots them on a map. ", "_____no_output_____" ] ], [ [ "inventory = client.get_stations(latitude=-42.693,longitude=173.022,maxradius=0.5, starttime = \"2016-11-13 11:05:00.000\",endtime = \"2016-11-14 11:00:00.000\")\nprint(inventory)\n_=inventory.plot(projection=\"local\")", "Inventory created at 2018-04-09T03:14:59.000000Z\n\tCreated by: Delta\n\t\t \n\tSending institution: GeoNet (WEL(GNS_Test))\n\tContains:\n\t\tNetworks (1):\n\t\t\tNZ\n\t\tStations (20):\n\t\t\tNZ.CECS (Cheviot Emergency Centre)\n\t\t\tNZ.CULC (Culverden Airlie Farm)\n\t\t\tNZ.GLWS (Glyn Wye)\n\t\t\tNZ.GVZ (Greta Valley)\n\t\t\tNZ.HSES (Hanmer Springs Emergency Centre)\n\t\t\tNZ.KHZ (Kahutara)\n\t\t\tNZ.LSRC (Lake Sumner Road)\n\t\t\tNZ.MS10 (Guide River)\n\t\t\tNZ.MS11 (Opera Range)\n\t\t\tNZ.MS12 (Leslie Hills)\n\t\t\tNZ.MS15 (Parnassus)\n\t\t\tNZ.SCAC (Scargill)\n\t\t\tNZ.SR051 (St. James Range)\n\t\t\tNZ.SR052 (West of Seaward Kaikoura range)\n\t\t\tNZ.SR056 (Hanmer Springs)\n\t\t\tNZ.SR057 (Glynn Wye Range)\n\t\t\tNZ.SR058 (Leader Road / Northeast of Waiau)\n\t\t\tNZ.WAKC (Waikari)\n\t\t\tNZ.WIGC (Waiau Gorge)\n\t\t\tNZ.WTMC (Te Mara Farm Waiau)\n\t\tChannels (0):\n\n" ] ], [ [ "The following examples dive into retrieving different information from the inventory object. This object is based on FDSN stationXML and therefore can provide much the same information.\n\nTo get all available information into the inventory you will want to request data down to the response level. The default requests information just to a station level. For more information, see the [obspy inventory class](http://docs.obspy.org/packages/obspy.core.inventory.html#module-obspy.core.inventory). \n\nThis example gets data from a station, KUZ, and prints a summary of the inventory contents", "_____no_output_____" ] ], [ [ "inventory = client.get_stations(station=\"KUZ\",level=\"response\",\n starttime = \"2016-11-13 11:05:00.000\",endtime = \"2016-11-14 11:00:00.000\")\nprint(inventory)", "Inventory created at 2018-04-09T03:14:59.000000Z\n\tCreated by: Delta\n\t\t \n\tSending institution: GeoNet (WEL(GNS_Test))\n\tContains:\n\t\tNetworks (1):\n\t\t\tNZ\n\t\tStations (1):\n\t\t\tNZ.KUZ (Kuaotunu)\n\t\tChannels (21):\n\t\t\tNZ.KUZ.10.EHE, NZ.KUZ.10.EHN, NZ.KUZ.10.EHZ, NZ.KUZ.10.HHE,\n\t\t\tNZ.KUZ.10.HHN, NZ.KUZ.10.HHZ, NZ.KUZ.10.LHE, NZ.KUZ.10.LHN,\n\t\t\tNZ.KUZ.10.LHZ, NZ.KUZ.10.VHE, NZ.KUZ.10.VHN, NZ.KUZ.10.VHZ,\n\t\t\tNZ.KUZ.20.BNE, NZ.KUZ.20.BNN, NZ.KUZ.20.BNZ, NZ.KUZ.20.HNE,\n\t\t\tNZ.KUZ.20.HNN, NZ.KUZ.20.HNZ, NZ.KUZ.20.LNE, NZ.KUZ.20.LNN,\n\t\t\tNZ.KUZ.20.LNZ\n" ] ], [ [ "Now, we can look at more information, such as specifics about the station. Such as the time it opened and location. ", "_____no_output_____" ] ], [ [ "network = inventory[0]\nstation = network[0] # equivalent to inventory[0][0]\nnum_channels = len(station)\nprint(station)", "Station KUZ (Kuaotunu)\n\tStation Code: KUZ\n\tChannel Count: 21/21 (Selected/Total)\n\t1990-10-11T00:00:00.000000Z - \n\tAccess: open \n\tLatitude: -36.75, Longitude: 175.72, Elevation: 76.0 m\n\tAvailable Channels:\n\t\tKUZ.10.EHZ, KUZ.10.EHE, KUZ.10.EHN, KUZ.10.HHZ, KUZ.10.LHN,\n\t\tKUZ.10.LHE, KUZ.10.VHZ, KUZ.10.VHN, KUZ.10.VHE, KUZ.10.LHZ,\n\t\tKUZ.10.HHE, KUZ.10.HHN, KUZ.20.HNZ, KUZ.20.HNN, KUZ.20.HNE,\n\t\tKUZ.20.BNZ, KUZ.20.BNN, KUZ.20.BNE, KUZ.20.LNZ, KUZ.20.LNN,\n\t\tKUZ.20.LNE\n" ] ], [ [ "We can drill down even futher into a particular channel and look at the time it was operating for, whether it was continously recording, the sample rate and some basic sensor information.", "_____no_output_____" ] ], [ [ "channel = station[0] # equivalent to inventory[0][0][0]\nprint(channel)", "Channel 'EHZ', Location '10' \n\tTime range: 1990-10-11T12:51:00.000000Z - 2003-05-05T18:52:00.000000Z\n\tLatitude: -36.75, Longitude: 175.72, Elevation: 76.0 m, Local Depth: 0.0 m\n\tAzimuth: 0.00 degrees from north, clockwise\n\tDip: -90.00 degrees down from horizontal\n\tChannel types: TRIGGERED, GEOPHYSICAL\n\tSampling Rate: 50.00 Hz\n\tSensor (Description): Short Period Seismometer (L4C-3D)\n\tResponse information available\n" ] ], [ [ "This channel states that there is response information available, so we can look at a summary of the response and plot it. ", "_____no_output_____" ] ], [ [ "resp = channel.response\nprint(resp)\nresp.plot(0.001,output=\"VEL\",label='KUZ HHZ')", "Channel Response\n\tFrom m/s () to count ()\n\tOverall Sensitivity: 1.86437e+07 defined at 15.000 Hz\n\t4 stages:\n\t\tStage 1: PolesZerosResponseStage from m/s to V, gain: 177.8\n\t\tStage 2: PolesZerosResponseStage from V to V, gain: 1\n\t\tStage 3: PolesZerosResponseStage from V to V, gain: 1\n\t\tStage 4: CoefficientsTypeResponseStage from V to count, gain: 104858\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" ] ]
4aeef8ba1406d4475fa676dc556e7156e06d0be8
6,291
ipynb
Jupyter Notebook
Chapter05/03_ngrams.ipynb
tunay-initions/Mastering-Azure-Machine-Learning
b87665c3151fb1aae4b8c59a3d25ab259d725293
[ "MIT" ]
38
2020-08-06T12:31:11.000Z
2022-03-29T07:55:49.000Z
Chapter05/03_ngrams.ipynb
tunay-initions/Mastering-Azure-Machine-Learning
b87665c3151fb1aae4b8c59a3d25ab259d725293
[ "MIT" ]
25
2020-08-06T12:39:27.000Z
2022-03-12T00:47:19.000Z
Chapter05/03_ngrams.ipynb
tunay-initions/Mastering-Azure-Machine-Learning
b87665c3151fb1aae4b8c59a3d25ab259d725293
[ "MIT" ]
43
2020-06-08T20:27:59.000Z
2022-03-23T17:12:18.000Z
35.342697
1,162
0.47719
[ [ [ "import nltk\nfrom sklearn.feature_extraction.text import CountVectorizer\n\ndef sklearn_count_vect(data, **kwargs):\n count_vect = CountVectorizer(**kwargs)\n X_train_counts = count_vect.fit_transform(data)\n print(X_train_counts)\n print(count_vect.vocabulary_)\n return X_train_counts\n\ndef skipgram(document, r=2, skip=1):\n return nltk.skipgrams(document.split(' '), r, skip)\n\ndef run_svd(data):\n from sklearn.decomposition import TruncatedSVD\n svd = TruncatedSVD(n_components=1, random_state=42)\n data_tf = svd.fit_transform(data)\n print(data_tf)\n print(svd.explained_variance_ratio_.sum()) \n return data_tf ", "_____no_output_____" ], [ "import numpy as np\n\ndocument = \"Almost before we knew it, we had left the ground. The unknown holds its grounds.\"\nprint('Document:', document)\n\nsklearn_count_vect([document])\n\nd = [\"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\",\n \"Maecenas eleifend ornare justo vestibulum consequat.\",\n \"Mauris finibus hendrerit risus egestas vehicula.\",\n \"Duis lacinia sed neque nec volutpat.\",\n \"Vivamus mollis lacus id nunc semper consectetur.\",\n \"Pellentesque nec dignissim odio.\"]\n\nX = sklearn_count_vect(d, ngram_range=(1,2))\n\nrun_svd(X)\n\nwords = skipgram(document, 2, 1)\nprint(list(words))", "Document: Almost before we knew it, we had left the ground. The unknown holds its grounds.\n (0, 0)\t1\n (0, 1)\t1\n (0, 12)\t2\n (0, 8)\t1\n (0, 6)\t1\n (0, 4)\t1\n (0, 9)\t1\n (0, 10)\t2\n (0, 2)\t1\n (0, 11)\t1\n (0, 5)\t1\n (0, 7)\t1\n (0, 3)\t1\n{'almost': 0, 'before': 1, 'we': 12, 'knew': 8, 'it': 6, 'had': 4, 'left': 9, 'the': 10, 'ground': 2, 'unknown': 11, 'holds': 5, 'its': 7, 'grounds': 3}\n (0, 32)\t1\n (0, 24)\t1\n (0, 9)\t1\n (0, 58)\t1\n (0, 2)\t1\n (0, 4)\t1\n (0, 0)\t1\n (0, 17)\t1\n (0, 33)\t1\n (0, 25)\t1\n (0, 10)\t1\n (0, 59)\t1\n (0, 3)\t1\n (0, 5)\t1\n (0, 1)\t1\n (1, 34)\t1\n (1, 15)\t1\n (1, 48)\t1\n (1, 26)\t1\n (1, 61)\t1\n (1, 6)\t1\n (1, 35)\t1\n (1, 16)\t1\n (1, 49)\t1\n (1, 27)\t1\n :\t:\n (3, 12)\t1\n (3, 29)\t1\n (3, 55)\t1\n (3, 44)\t1\n (3, 42)\t1\n (4, 4)\t1\n (4, 63)\t1\n (4, 38)\t1\n (4, 30)\t1\n (4, 22)\t1\n (4, 45)\t1\n (4, 56)\t1\n (4, 64)\t1\n (4, 39)\t1\n (4, 31)\t1\n (4, 23)\t1\n (4, 46)\t1\n (4, 57)\t1\n (5, 40)\t1\n (5, 50)\t1\n (5, 7)\t1\n (5, 47)\t1\n (5, 51)\t1\n (5, 41)\t1\n (5, 8)\t1\n{'lorem': 32, 'ipsum': 24, 'dolor': 9, 'sit': 58, 'amet': 2, 'consectetur': 4, 'adipiscing': 0, 'elit': 17, 'lorem ipsum': 33, 'ipsum dolor': 25, 'dolor sit': 10, 'sit amet': 59, 'amet consectetur': 3, 'consectetur adipiscing': 5, 'adipiscing elit': 1, 'maecenas': 34, 'eleifend': 15, 'ornare': 48, 'justo': 26, 'vestibulum': 61, 'consequat': 6, 'maecenas eleifend': 35, 'eleifend ornare': 16, 'ornare justo': 49, 'justo vestibulum': 27, 'vestibulum consequat': 62, 'mauris': 36, 'finibus': 18, 'hendrerit': 20, 'risus': 52, 'egestas': 13, 'vehicula': 60, 'mauris finibus': 37, 'finibus hendrerit': 19, 'hendrerit risus': 21, 'risus egestas': 53, 'egestas vehicula': 14, 'duis': 11, 'lacinia': 28, 'sed': 54, 'neque': 43, 'nec': 40, 'volutpat': 65, 'duis lacinia': 12, 'lacinia sed': 29, 'sed neque': 55, 'neque nec': 44, 'nec volutpat': 42, 'vivamus': 63, 'mollis': 38, 'lacus': 30, 'id': 22, 'nunc': 45, 'semper': 56, 'vivamus mollis': 64, 'mollis lacus': 39, 'lacus id': 31, 'id nunc': 23, 'nunc semper': 46, 'semper consectetur': 57, 'pellentesque': 50, 'dignissim': 7, 'odio': 47, 'pellentesque nec': 51, 'nec dignissim': 41, 'dignissim odio': 8}\n[[ 3.62723783e+00]\n [ 1.74353595e-15]\n [-3.39168499e-15]\n [ 6.46035236e-15]\n [ 1.50245110e+00]\n [ 1.45357928e-15]]\n0.19693920498587425\n[('Almost', 'before'), ('Almost', 'we'), ('before', 'we'), ('before', 'knew'), ('we', 'knew'), ('we', 'it,'), ('knew', 'it,'), ('knew', 'we'), ('it,', 'we'), ('it,', 'had'), ('we', 'had'), ('we', 'left'), ('had', 'left'), ('had', 'the'), ('left', 'the'), ('left', 'ground.'), ('the', 'ground.'), ('the', 'The'), ('ground.', 'The'), ('ground.', 'unknown'), ('The', 'unknown'), ('The', 'holds'), ('unknown', 'holds'), ('unknown', 'its'), ('holds', 'its'), ('holds', 'grounds.'), ('its', 'grounds.')]\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4aeefba2ebe1df2612131b23773c3b8df7dcf15b
48,894
ipynb
Jupyter Notebook
examples/envs/building.ipynb
NREL/PowerGridworld
2f72ac5bb663092ca806c6fff9c7cf70f94fd775
[ "BSD-3-Clause" ]
24
2021-11-12T03:42:38.000Z
2022-02-27T17:22:30.000Z
examples/envs/building.ipynb
NREL/PowerGridworld
2f72ac5bb663092ca806c6fff9c7cf70f94fd775
[ "BSD-3-Clause" ]
4
2021-11-11T03:27:58.000Z
2021-11-15T23:12:05.000Z
examples/envs/building.ipynb
NREL/PowerGridworld
2f72ac5bb663092ca806c6fff9c7cf70f94fd775
[ "BSD-3-Clause" ]
2
2022-02-09T09:15:41.000Z
2022-02-24T14:56:40.000Z
301.814815
45,076
0.931648
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom gridworld.agents.buildings import defaults\n\n%matplotlib inline\n%load_ext autoreload", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ] ], [ [ "# Test the base env\nNo reward is implemented but it still runs the physics", "_____no_output_____" ] ], [ [ "%autoreload 2\nfrom gridworld.agents.buildings import FiveZoneROMEnv", "_____no_output_____" ], [ "env = FiveZoneROMEnv(\n start_time=\"08-12-2020 00:00:00\",\n end_time=\"08-13-2020 00:00:00\",\n rescale_spaces=False\n)\n\nenv.obs_labels", "_____no_output_____" ], [ "env.reset()\ndone = False\nmeta = []\ni = 0\nzt = []\nwhile not done:\n action = env.action_space.low\n _, _, done, m = env.step(action)\n zt.append(env.zone_temp.copy())\n \n_ = pd.DataFrame(zt, index=env.df.index[:len(zt)]).plot()", "/Users/dbiagion/gitrepos/PowerGridworld/gridworld/agents/buildings/five_zone_rom_env.py:276: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.\n obs = np.array([v for k, v in self.state.items() if k in self.obs_labels])\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4aeeff93e44d308d07f1d310887c6ff51374bbca
7,238
ipynb
Jupyter Notebook
scripts/download.ipynb
ShervanGharari/shapefile_standardization
e641c35404191d450f69057940f72677eb6e2b71
[ "MIT" ]
null
null
null
scripts/download.ipynb
ShervanGharari/shapefile_standardization
e641c35404191d450f69057940f72677eb6e2b71
[ "MIT" ]
null
null
null
scripts/download.ipynb
ShervanGharari/shapefile_standardization
e641c35404191d450f69057940f72677eb6e2b71
[ "MIT" ]
null
null
null
35.480392
163
0.521553
[ [ [ "import pandas as pd\nfrom shapely.ops import unary_union\nimport shapely\nimport geopandas as gpd\nfrom shapely.geometry import Polygon\nfrom shapely.geometry import Point\nfrom bs4 import BeautifulSoup\nfrom urllib.request import Request, urlopen\nimport requests\nimport re\nimport glob\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\n\n\n\ndef download(des_loc,\n http_page,\n str1,\n str2):\n \"\"\"\n @ author: Shervan Gharari\n @ Github: https://github.com/ShervanGharari/shapefile_standardization\n @ author's email id: [email protected]\n @license: MIT\n\n This function gets name of a http and two str in the name of the link and save them in\n provided destnation\n \n\n Arguments\n ---------\n des_loc: string, the name of the source file including path and extension\n http_page: string, the name of the corresponding catchment (subbasin) for the unresolved hills\n str1: string, a part of the link name to filter\n str2: string, a second part of the link name to filter\n \n\n Returns\n -------\n\n\n Saves Files\n -------\n downlaod the files from the websites and save them in the correct location\n \"\"\"\n\n # first get all the links in the page\n req = Request(http_page)\n html_page = urlopen(req)\n soup = BeautifulSoup(html_page, \"lxml\")\n links = []\n for link in soup.findAll('a'):\n links.append(link.get('href'))\n\n # specify the link to be downloaded\n link_to_download = []\n for link in links:\n # if \"hillslope\" in link and \"clean\" in link: # links that have cat_pfaf and Basins in them\n if str1 in link and str2 in link: # links that have cat_pfaf and Basins in them\n link_to_download.append(link)\n print(link)\n\n # creat urls to download\n urls =[]\n for file_name in link_to_download:\n urls.append(http_page+file_name) # link of the page + file names\n print(http_page+file_name)\n print(urls)\n\n # loop to download the data\n for url in urls:\n name = url.split('/')[-1] # get the name of the file at the end of the url to download\n r = requests.get(url) # download the URL\n # print the specification of the download \n print(r.status_code, r.headers['content-type'], r.encoding)\n # if download successful the statuse code is 200 then save the file, else print not downloaded\n if r.status_code == 200:\n print('download was successful for '+url)\n with open(des_loc+name, 'wb') as f:\n f.write(r.content)\n else:\n print('download was not successful for '+url)\n \n", "_____no_output_____" ] ], [ [ "## Download section and input path\n### A list of IDs based on 2 digit pfaf code are provided for download, the path to save the donwload is provided and also the website to download the model ", "_____no_output_____" ] ], [ [ "# the 2 digit pfaf code for the shapefile to be processed\n# list of IDs for downloading the processing\nIDs = ['11', '12', '13', '14', '15', '16', '17', '18',\n '21', '22', '23', '24', '25', '26', '27', '28', '29',\n '31', '32', '33', '34', '35', '36',\n '41', '42', '43', '44', '45', '46', '47', '48', '49',\n '51', '52', '53', '54', '55', '56', '57',\n '61', '62', '63', '64', '65', '66', '67',\n '71', '72', '73', '74', '75', '76', '77', '78',\n '81', '82', '83', '84', '85', '86',\n '91']\n# location of files online\nhttp_path = 'XXX/for_martyn/' # link to the page that the data exists\n# in this folder create subfolders cat, riv, hill, cat_step_1,cat_step_2\npath = '/Users/shg096/Desktop/MERIT_Hydro/'", "_____no_output_____" ], [ "# STEP- prepare the folder and subfolders for download\n# path is the location were all the shapefiles and anupulaed shapfiles are saved\n# under path create five subfolders: cat, riv, hill, cat_step_0, cat_step_1, cat_fixed, hill_fixed\nif not os.path.exists(path+'cat'):\n os.mkdir(path+'cat')\nif not os.path.exists(path+'riv'):\n os.mkdir(path+'riv')\nif not os.path.exists(path+'hill'):\n os.mkdir(path+'hill')\nif not os.path.exists(path+'cat_step_0'):\n os.mkdir(path+'cat_step_0')\nif not os.path.exists(path+'cat_step_1'):\n os.mkdir(path+'cat_step_1')\nif not os.path.exists(path+'cat_fixed'):\n os.mkdir(path+'cat_fixed')\nif not os.path.exists(path+'ERA5int'):\n os.mkdir(path+'ERA5int')\nif not os.path.exists(path+'hill_fixed'):\n os.mkdir(path+'hill_fixed')\nif not os.path.exists(path+'hill_step_0'):\n os.mkdir(path+'hill_step_0')\n ", "_____no_output_____" ], [ "# downlaod the catchment, river, costal hillslope\nfor ID in IDs:\n download(path+'cat/',\n http_path+'MERIT_Hydro_v07_Basins_v01_bugfix1/pfaf_level_02/',\n 'cat',\n ID)\n download(path+'riv/',\n http_path+'MERIT_Hydro_v07_Basins_v01_bugfix1/pfaf_level_02/',\n 'riv',\n ID)\n if ID != '49' # there is no hillslope for 49\n download(path+'hill/',\n http_path+'coastal_hillslopes/',\n 'hill',\n ID)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4aef0a22c061ac24d1c78d10f85c7e7f4b2783d9
112,033
ipynb
Jupyter Notebook
Code/Plot_GRU.ipynb
Naghipourfar/TraderBot
2604c9df7af7394dfab6a54ea9a65a1b0df6a0ce
[ "MIT" ]
3
2019-02-06T09:45:39.000Z
2022-01-15T04:48:07.000Z
Code/Plot_GRU.ipynb
Naghipourfar/TraderBot
2604c9df7af7394dfab6a54ea9a65a1b0df6a0ce
[ "MIT" ]
null
null
null
Code/Plot_GRU.ipynb
Naghipourfar/TraderBot
2604c9df7af7394dfab6a54ea9a65a1b0df6a0ce
[ "MIT" ]
1
2020-01-07T05:20:24.000Z
2020-01-07T05:20:24.000Z
239.386752
98,968
0.908688
[ [ [ "from keras import applications\nfrom keras.models import Sequential, Model\nfrom keras.models import Model\nfrom keras.layers import Dropout, Flatten, Dense, Activation, Reshape\nfrom keras.callbacks import CSVLogger\nimport tensorflow as tf\nfrom scipy.ndimage import imread\nimport numpy as np\nimport random\nfrom keras.layers import GRU, CuDNNGRU, LSTM, Input\nfrom keras.layers import Conv1D, MaxPooling1D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras import backend as K\nimport keras\nfrom keras.callbacks import CSVLogger, ModelCheckpoint\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras import optimizers\nimport h5py\nfrom sklearn.preprocessing import MinMaxScaler\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport h5py", "_____no_output_____" ], [ "with h5py.File('../Data/' + ''.join(['BTC.h5']), 'r') as hf:\n datas = hf['inputs'].value\n labels = hf['outputs'].value\n input_times = hf['input_times'].value\n output_times = hf['output_times'].value\n original_inputs = hf['original_inputs'].value\n original_outputs = hf['original_outputs'].value\n original_datas = hf['original_datas'].value", "_____no_output_____" ], [ "scaler=MinMaxScaler((-1, 1))\n#split training validation\n# training_size = int(0.8* datas.shape[0])\ntraining_size = datas.shape[0] - 1\ntraining_datas = datas[:training_size,:,:]\ntraining_labels = labels[:training_size,:,:]\nvalidation_datas = datas[training_size:,:,:]\nvalidation_labels = labels[training_size:,:,:]\nvalidation_original_outputs = original_outputs[training_size:,:,:]\nvalidation_original_inputs = original_inputs[training_size:,:,:]\nvalidation_input_times = input_times[training_size:,:,:]\nvalidation_output_times = output_times[training_size:,:,:]\n\nvalidation_size = datas.shape[0] - training_size\n\ntraining_labels = [np.array(training_labels[:, :, 0]).reshape((training_size, -1)),\n np.array(training_labels[:, :, 1]).reshape((training_size, -1)),\n np.array(training_labels[:, :, 2]).reshape((training_size, -1))]\n\nvalidation_labels = [np.array(validation_labels[:, :, 0]).reshape((validation_size, -1)),\n np.array(validation_labels[:, :, 1]).reshape((validation_size, -1)),\n np.array(validation_labels[:, :, 2]).reshape((validation_size, -1))]", "_____no_output_____" ], [ "os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'", "_____no_output_____" ], [ "config = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nset_session(tf.Session(config=config))", "_____no_output_____" ], [ "ground_true = np.append(validation_original_inputs,validation_original_outputs, axis=1)\nground_true_times = np.append(validation_input_times,validation_output_times, axis=1)\nprint(ground_true_times.shape)\nprint(ground_true.shape)", "(1, 372, 1)\n(1, 372, 3)\n" ], [ "step_size = datas.shape[1]\nbatch_size = 8\nn_features = datas.shape[2]\nepochs = 1\noutput_size = 12\nunits = 150", "_____no_output_____" ], [ "# model = Sequential()\n# model.add(GRU(units=units, activation=None, input_shape=(step_size,nb_features),return_sequences=False))\n# model.add(Activation('tanh'))\n# model.add(Dropout(0.2))\n# model.add(Dense(output_size, activation=\"linear\"))\n# model.add(LeakyReLU(alpha=0.001))\n# model.load_weights('../weights/BTC_GRU_1_tanh_relu-49-0.00001.hdf5')\n# model.compile(loss='mape', optimizer='adam')", "_____no_output_____" ], [ "input_layer = Input(shape=(step_size, n_features))\nlayer_1 = GRU(units=units, return_sequences=True)(input_layer)\nlayer_1 = Dropout(0.5)(layer_1)\n\nlayer_2 = GRU(units=units, return_sequences=False)(layer_1)\nlayer_2 = Dropout(0.5)(layer_2)\noutput_1 = Dense(output_size, activation=\"tanh\", name=\"close_dense\")(layer_2)\noutput_2 = Dense(output_size, activation=\"tanh\", name=\"high_dense\")(layer_2)\noutput_3 = Dense(output_size, activation=\"tanh\", name=\"low_dense\")(layer_2)\n\nmodel = Model(inputs=input_layer, outputs=[output_1, output_2, output_3])\nmodel.load_weights('../weights/BTC_GRU_1_tanh_relu-209-0.00000034.hdf5')\nmodel.compile(optimizer=\"adam\", loss=[\"mse\", \"mse\", \"mse\"], loss_weights=[0.001, 0.001, 0.001])\n", "_____no_output_____" ], [ "predicted = np.array(model.predict(validation_datas))\nprint(predicted.shape)\npredicted = predicted.reshape((predicted.shape[1] * predicted.shape[2], predicted.shape[0]))\npredicted_inverted = []\npredicted.shape", "(3, 1, 12)\n" ], [ "scaler.fit(original_datas.reshape(-1, n_features))\n# predicted_inverted.append(scaler.inverse_transform(predicted))\npredicted_inverted = scaler.inverse_transform(predicted[:, :])\nprint(np.array(predicted_inverted).shape)\n\n#get only the close data\nground_true = ground_true[:, :, :].reshape(-1, n_features)\nground_true_times = ground_true_times.reshape(-1)\nground_true_times = pd.to_datetime(ground_true_times, unit='s')\n# since we are appending in the first dimension\n# predicted_inverted = np.array(predicted_inverted)[0,:,:].reshape(-1)\nprint(np.array(predicted_inverted).shape)\nvalidation_output_times = pd.to_datetime(validation_output_times.reshape(-1), unit='s')", "(12, 3)\n(12, 3)\n" ], [ "predicted_inverted[:, 0]", "_____no_output_____" ], [ "validation_output_times.shape", "_____no_output_____" ], [ "ground_true_df = pd.DataFrame()\nground_true_df['times'] = ground_true_times\nground_true_df['close'] = ground_true[:, 0]\nground_true_df['high'] = ground_true[:, 1]\nground_true_df['low'] = ground_true[:, 2]\nground_true_df.set_index('times').reset_index()\nground_true_df.shape", "_____no_output_____" ], [ "prediction_df = pd.DataFrame()\nprediction_df['times'] = validation_output_times\nprediction_df['close'] = predicted_inverted[:, 0]\nprediction_df['high'] = predicted_inverted[:, 1]\nprediction_df['low'] = predicted_inverted[:, 2]\nprediction_df.shape", "_____no_output_____" ], [ "prediction_df = prediction_df.loc[(prediction_df[\"times\"].dt.year == 2018 )&(prediction_df[\"times\"].dt.month >= 7 ),: ]\n# ground_true_df = ground_true_df.loc[(ground_true_df[\"times\"].dt.year >= 2017 )&(ground_true_df[\"times\"].dt.month > 7 ),:]\nground_true_df = ground_true_df.loc[:,:]", "_____no_output_____" ], [ "start_idx = 350\nplt.figure(figsize=(20,10))\nplt.plot(ground_true_df.times[start_idx:],ground_true_df.close[start_idx:], label = 'Actual Close')\n# plt.plot(ground_true_df.times[start_idx:],ground_true_df.high[start_idx:], label = 'Actual High')\n# plt.plot(ground_true_df.times[start_idx:],ground_true_df.low[start_idx:], label = 'Actual Low')\nplt.plot(prediction_df.times,prediction_df.high,'g-', label='Predicted High')\nplt.plot(prediction_df.times,prediction_df.close,'r-', label='Predicted Close')\nplt.plot(prediction_df.times,prediction_df.low,'b-', label='Predicted Low')\nplt.legend(loc='upper left')\nplt.grid()\nplt.title(\"Predicted USD for last 7 days from \" + str(ground_true_df[\"times\"].dt.date.iloc[-12]) + \" to \" + str(ground_true_df[\"times\"].dt.date.iloc[-1]))\nplt.savefig('../Results/BTC/New/BTC_close_GRU_1_tanh_relu_result.png')\nplt.show()", "_____no_output_____" ], [ "from sklearn.metrics import mean_squared_error\nmean_squared_error(validation_original_outputs[:,:,0].reshape(-1),predicted_inverted[:, 0])", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aef13b5edfe79e0ccefc4c46401aca2290f7fd7
85,885
ipynb
Jupyter Notebook
CW06.ipynb
chapman-phys220-2018f/cw06-im-not-good-at-team-naes
4d4cde887993ecc517306ab76f483408d6ad3e58
[ "MIT" ]
null
null
null
CW06.ipynb
chapman-phys220-2018f/cw06-im-not-good-at-team-naes
4d4cde887993ecc517306ab76f483408d6ad3e58
[ "MIT" ]
null
null
null
CW06.ipynb
chapman-phys220-2018f/cw06-im-not-good-at-team-naes
4d4cde887993ecc517306ab76f483408d6ad3e58
[ "MIT" ]
null
null
null
505.205882
81,893
0.942854
[ [ [ "# CW06 - Particles\nRoyal Cuevas and Amelia Roseto\n11 October 2018", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom scipy import constants as const\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom matplotlib import animation, rc\nplt.style.use(\"seaborn-pastel\")\nimport elementary", "_____no_output_____" ], [ "part=elementary.Particle(0,0,1)\ne=elementary.Electron(0,0,2)\npro=elementary.Proton(0,0,3)", "_____no_output_____" ], [ "print(part.mass)\nprint(e.mass)\nprint(pro.mass)", "1.0\n9.10938356e-31\n1.672621898e-27\n" ], [ "part.impulse(0,0,10*part.mass)\ne.impulse(0,0,10*e.mass)\npro.impulse(0,0,10*pro.mass)", "_____no_output_____" ], [ "xpoints = [i for i in np.arange(0, 5, 1e-2)]\nypoints = []\nypoints2 = []\nypoints3 = []\nfor i in range(500):\n part.impulse(0,0,-const.g*part.mass*.01)\n part.move(.01)\n ypoints.append(part.position[2])\nfor i in range(500):\n e.impulse(0,0,-const.g*e.mass*.01)\n e.move(1e-2)\n ypoints2.append(e.position[2])\nfor i in range(500):\n pro.impulse(0,0,-const.g*pro.mass*.01)\n pro.move(1e-2)\n ypoints3.append(pro.position[2])\n# First create a figure, with \"handle\" stored in variable f\n# The figsize is displayed in inches (on a printed page), with (width, height)\nf = plt.figure(figsize=(8,6))\n# Then create axes on the figure, with \"handle\" stored in variable a\na = plt.axes()\n\na.plot(xpoints, ypoints, label=\"Particle\")\na.plot(xpoints, ypoints2, color=\"Red\", label=\"Electron\")\na.plot(xpoints, ypoints3, color=\"Green\", label=\"Proton\")\n\na.set(xlabel=\"Time (s)\", ylabel=\"Position (m)\", title=\"Particle Trajectory\")\n# Add a legend describing which curve is which\na.legend()\n# Show the active plot to the screen\nplt.show()", "_____no_output_____" ] ], [ [ "The particles all acted exactly as they would be expected to. There is minor separation at first because of a difference in starting position, then they all proceed to follow an identical curve as they began with identical momentum.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4aef2c74ffcfec76350789ee4ff88bf6d130cd62
43,882
ipynb
Jupyter Notebook
4 jigsaw/bert-lstm-simple-blender-0-93844-lb.ipynb
MLVPRASAD/KaggleProjects
379e062cf58d83ff57a456552bb956df68381fdd
[ "MIT" ]
2
2020-01-25T08:31:14.000Z
2022-03-23T18:24:03.000Z
4 jigsaw/bert-lstm-simple-blender-0-93844-lb.ipynb
MLVPRASAD/KaggleProjects
379e062cf58d83ff57a456552bb956df68381fdd
[ "MIT" ]
null
null
null
4 jigsaw/bert-lstm-simple-blender-0-93844-lb.ipynb
MLVPRASAD/KaggleProjects
379e062cf58d83ff57a456552bb956df68381fdd
[ "MIT" ]
null
null
null
42.521318
1,731
0.516248
[ [ [ "Thanks for @christofhenkel @abhishek @iezepov for their great work:\n\nhttps://www.kaggle.com/christofhenkel/how-to-preprocessing-for-glove-part2-usage\nhttps://www.kaggle.com/abhishek/pytorch-bert-inference\nhttps://www.kaggle.com/iezepov/starter-gensim-word-embeddings", "_____no_output_____" ] ], [ [ "import sys\npackage_dir = \"../input/ppbert/pytorch-pretrained-bert/pytorch-pretrained-BERT\"\nsys.path.append(package_dir)", "_____no_output_____" ], [ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function", "_____no_output_____" ], [ "%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\n\nimport fastai\nfrom fastai.train import Learner\nfrom fastai.train import DataBunch\nfrom fastai.callbacks import TrainingPhase, GeneralScheduler\nfrom fastai.basic_data import DatasetType\nimport fastprogress\nfrom fastprogress import force_console_behavior\nimport numpy as np\nfrom pprint import pprint\nimport pandas as pd\nimport os\nimport time\nimport gc\nimport random\nfrom tqdm._tqdm_notebook import tqdm_notebook as tqdm\nfrom keras.preprocessing import text, sequence\nimport torch\nfrom torch import nn\nfrom torch.utils import data\nfrom torch.nn import functional as F\n\nimport torch.utils.data\nfrom tqdm import tqdm\nimport warnings\nfrom pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification, BertAdam\nfrom pytorch_pretrained_bert import BertConfig\nfrom nltk.tokenize.treebank import TreebankWordTokenizer\n\nfrom gensim.models import KeyedVectors", "Using TensorFlow backend.\n" ], [ "def convert_lines(example, max_seq_length,tokenizer):\n max_seq_length -=2\n all_tokens = []\n longer = 0\n for text in tqdm(example):\n tokens_a = tokenizer.tokenize(text)\n if len(tokens_a)>max_seq_length:\n tokens_a = tokens_a[:max_seq_length]\n longer += 1\n one_token = tokenizer.convert_tokens_to_ids([\"[CLS]\"]+tokens_a+[\"[SEP]\"])+[0] * (max_seq_length - len(tokens_a))\n all_tokens.append(one_token)\n return np.array(all_tokens)\n\ndef is_interactive():\n return 'SHLVL' not in os.environ\n\ndef seed_everything(seed=123):\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 \ndef get_coefs(word, *arr):\n return word, np.asarray(arr, dtype='float32')\n\n\ndef load_embeddings(path):\n #with open(path,'rb') as f:\n emb_arr = KeyedVectors.load(path)\n return emb_arr\n\ndef build_matrix(word_index, path):\n embedding_index = load_embeddings(path)\n embedding_matrix = np.zeros((max_features + 1, 300))\n unknown_words = []\n \n for word, i in word_index.items():\n if i <= max_features:\n try:\n embedding_matrix[i] = embedding_index[word]\n except KeyError:\n try:\n embedding_matrix[i] = embedding_index[word.lower()]\n except KeyError:\n try:\n embedding_matrix[i] = embedding_index[word.title()]\n except KeyError:\n unknown_words.append(word)\n return embedding_matrix, unknown_words\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\nclass SpatialDropout(nn.Dropout2d):\n def forward(self, x):\n x = x.unsqueeze(2) # (N, T, 1, K)\n x = x.permute(0, 3, 2, 1) # (N, K, 1, T)\n x = super(SpatialDropout, self).forward(x) # (N, K, 1, T), some features are masked\n x = x.permute(0, 3, 2, 1) # (N, T, 1, K)\n x = x.squeeze(2) # (N, T, K)\n return x\n\ndef train_model(learn,test,output_dim,lr=0.001,\n batch_size=512, n_epochs=4,\n enable_checkpoint_ensemble=True):\n \n all_test_preds = []\n checkpoint_weights = [2 ** epoch for epoch in range(n_epochs)]\n test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False)\n n = len(learn.data.train_dl)\n phases = [(TrainingPhase(n).schedule_hp('lr', lr * (0.6**(i)))) for i in range(n_epochs)]\n sched = GeneralScheduler(learn, phases)\n learn.callbacks.append(sched)\n for epoch in range(n_epochs):\n learn.fit(1)\n test_preds = np.zeros((len(test), output_dim)) \n for i, x_batch in enumerate(test_loader):\n X = x_batch[0].cuda()\n y_pred = sigmoid(learn.model(X).detach().cpu().numpy())\n test_preds[i * batch_size:(i+1) * batch_size, :] = y_pred\n\n all_test_preds.append(test_preds)\n\n\n if enable_checkpoint_ensemble:\n test_preds = np.average(all_test_preds, weights=checkpoint_weights, axis=0) \n else:\n test_preds = all_test_preds[-1]\n \n return test_preds\n\ndef handle_punctuation(x):\n x = x.translate(remove_dict)\n x = x.translate(isolate_dict)\n return x\n\ndef handle_contractions(x):\n x = tokenizer.tokenize(x)\n return x\n\ndef fix_quote(x):\n x = [x_[1:] if x_.startswith(\"'\") else x_ for x_ in x]\n x = ' '.join(x)\n return x\n\ndef preprocess(x):\n x = handle_punctuation(x)\n x = handle_contractions(x)\n x = fix_quote(x)\n return x\n\nclass SequenceBucketCollator():\n def __init__(self, choose_length, sequence_index, length_index, label_index=None):\n self.choose_length = choose_length\n self.sequence_index = sequence_index\n self.length_index = length_index\n self.label_index = label_index\n \n def __call__(self, batch):\n batch = [torch.stack(x) for x in list(zip(*batch))]\n \n sequences = batch[self.sequence_index]\n lengths = batch[self.length_index]\n \n length = self.choose_length(lengths)\n mask = torch.arange(start=maxlen, end=0, step=-1) < length\n padded_sequences = sequences[:, mask]\n \n batch[self.sequence_index] = padded_sequences\n \n if self.label_index is not None:\n return [x for i, x in enumerate(batch) if i != self.label_index], batch[self.label_index]\n \n return batch\n \nclass NeuralNet(nn.Module):\n def __init__(self, embedding_matrix, num_aux_targets):\n super(NeuralNet, self).__init__()\n embed_size = embedding_matrix.shape[1]\n \n self.embedding = nn.Embedding(max_features, embed_size)\n self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))\n self.embedding.weight.requires_grad = False\n self.embedding_dropout = SpatialDropout(0.3)\n \n self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)\n self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)\n \n self.linear1 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)\n self.linear2 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)\n \n self.linear_out = nn.Linear(DENSE_HIDDEN_UNITS, 1)\n self.linear_aux_out = nn.Linear(DENSE_HIDDEN_UNITS, num_aux_targets)\n \n def forward(self, x, lengths=None):\n h_embedding = self.embedding(x.long())\n h_embedding = self.embedding_dropout(h_embedding)\n \n h_lstm1, _ = self.lstm1(h_embedding)\n h_lstm2, _ = self.lstm2(h_lstm1)\n \n # global average pooling\n avg_pool = torch.mean(h_lstm2, 1)\n # global max pooling\n max_pool, _ = torch.max(h_lstm2, 1)\n \n h_conc = torch.cat((max_pool, avg_pool), 1)\n h_conc_linear1 = F.relu(self.linear1(h_conc))\n h_conc_linear2 = F.relu(self.linear2(h_conc))\n \n hidden = h_conc + h_conc_linear1 + h_conc_linear2\n \n result = self.linear_out(hidden)\n aux_result = self.linear_aux_out(hidden)\n out = torch.cat([result, aux_result], 1)\n \n return out\n \ndef custom_loss(data, targets):\n bce_loss_1 = nn.BCEWithLogitsLoss(weight=targets[:,1:2])(data[:,:1],targets[:,:1])\n bce_loss_2 = nn.BCEWithLogitsLoss()(data[:,1:],targets[:,2:])\n return (bce_loss_1 * loss_weight) + bce_loss_2\n\ndef reduce_mem_usage(df):\n start_mem = df.memory_usage().sum() / 1024**2\n print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n \n for col in df.columns:\n col_type = df[col].dtype\n \n if col_type != object:\n c_min = df[col].min()\n c_max = df[col].max()\n if str(col_type)[:3] == 'int':\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64) \n else:\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64)\n else:\n df[col] = df[col].astype('category')\n\n end_mem = df.memory_usage().sum() / 1024**2\n print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n \n return df", "_____no_output_____" ], [ "warnings.filterwarnings(action='once')\ndevice = torch.device('cuda')\nMAX_SEQUENCE_LENGTH = 300\nSEED = 1234\nBATCH_SIZE = 512\nBERT_MODEL_PATH = '../input/bert-pretrained-models/uncased_l-12_h-768_a-12/uncased_L-12_H-768_A-12/'\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\nbert_config = BertConfig('../input/arti-bert-inference/bert/bert_config.json')\ntokenizer = BertTokenizer.from_pretrained(BERT_MODEL_PATH, cache_dir=None,do_lower_case=True)\n\ntqdm.pandas()\nCRAWL_EMBEDDING_PATH = '../input/gensim-embeddings-dataset/crawl-300d-2M.gensim'\nGLOVE_EMBEDDING_PATH = '../input/gensim-embeddings-dataset/glove.840B.300d.gensim'\nNUM_MODELS = 2\nLSTM_UNITS = 128\nDENSE_HIDDEN_UNITS = 4 * LSTM_UNITS\nMAX_LEN = 220\nif not is_interactive():\n def nop(it, *a, **k):\n return it\n\n tqdm = nop\n\n fastprogress.fastprogress.NO_BAR = True\n master_bar, progress_bar = force_console_behavior()\n fastai.basic_train.master_bar, fastai.basic_train.progress_bar = master_bar, progress_bar\n\nseed_everything()", "_____no_output_____" ] ], [ [ "**BERT Part**", "_____no_output_____" ] ], [ [ "test_df = pd.read_csv(\"../input/jigsaw-unintended-bias-in-toxicity-classification/test.csv\")\ntest_df['comment_text'] = test_df['comment_text'].astype(str) \nX_test = convert_lines(test_df[\"comment_text\"].fillna(\"DUMMY_VALUE\"), MAX_SEQUENCE_LENGTH, tokenizer)", "_____no_output_____" ], [ "model = BertForSequenceClassification(bert_config, num_labels=1)\nmodel.load_state_dict(torch.load(\"../input/arti-bert-inference/bert/bert_pytorch.bin\"))\nmodel.to(device)\nfor param in model.parameters():\n param.requires_grad = False\nmodel.eval()", "_____no_output_____" ], [ "test_preds = np.zeros((len(X_test)))\ntest = torch.utils.data.TensorDataset(torch.tensor(X_test, dtype=torch.long))\ntest_loader = torch.utils.data.DataLoader(test, batch_size=512, shuffle=False)\ntk0 = tqdm(test_loader)\nfor i, (x_batch,) in enumerate(tk0):\n pred = model(x_batch.to(device), attention_mask=(x_batch > 0).to(device), labels=None)\n test_preds[i * 512:(i + 1) * 512] = pred[:, 0].detach().cpu().squeeze().numpy()\n\ntest_pred = torch.sigmoid(torch.tensor(test_preds)).numpy().ravel()", "_____no_output_____" ], [ "submission_bert = pd.DataFrame.from_dict({\n 'id': test_df['id'],\n 'prediction': test_pred\n})", "_____no_output_____" ] ], [ [ "**LSTM Part**", "_____no_output_____" ] ], [ [ "train_df = reduce_mem_usage(pd.read_csv('../input/jigsaw-unintended-bias-in-toxicity-classification/train.csv'))", "Memory usage of dataframe is 619.65 MB\nMemory usage after optimization is: 350.87 MB\nDecreased by 43.4%\n" ], [ "symbols_to_isolate = '.,?!-;*\"…:—()%#$&_/@\・ω+=”“[]^–>\\\\°<~•≠™ˈʊɒ∞§{}·τα❤☺ɡ|¢→̶`❥━┣┫┗O►★©―ɪ✔®\\x96\\x92●£♥➤´¹☕≈÷♡◐║▬′ɔː€۩۞†μ✒➥═☆ˌ◄½ʻπδηλσερνʃ✬SUPERIT☻±♍µº¾✓◾؟.⬅℅»Вав❣⋅¿¬♫CMβ█▓▒░⇒⭐›¡₂₃❧▰▔◞▀▂▃▄▅▆▇↙γ̄″☹➡«φ⅓„✋:¥̲̅́∙‛◇✏▷❓❗¶˚˙)сиʿ✨。ɑ\\x80◕!%¯−flfi₁²ʌ¼⁴⁄₄⌠♭✘╪▶☭✭♪☔☠♂☃☎✈✌✰❆☙○‣⚓年∎ℒ▪▙☏⅛casǀ℮¸w‚∼‖ℳ❄←☼⋆ʒ⊂、⅔¨͡๏⚾⚽Φ×θ₩?(℃⏩☮⚠月✊❌⭕▸■⇌☐☑⚡☄ǫ╭∩╮,例>ʕɐ̣Δ₀✞┈╱╲▏▕┃╰▊▋╯┳┊≥☒↑☝ɹ✅☛♩☞AJB◔◡↓♀⬆̱ℏ\\x91⠀ˤ╚↺⇤∏✾◦♬³の|/∵∴√Ω¤☜▲↳▫‿⬇✧ovm-208'‰≤∕ˆ⚜☁'\nsymbols_to_delete = '\\n🍕\\r🐵😑\\xa0\\ue014\\t\\uf818\\uf04a\\xad😢🐶️\\uf0e0😜😎👊\\u200b\\u200e😁عدويهصقأناخلىبمغر😍💖💵Е👎😀😂\\u202a\\u202c🔥😄🏻💥ᴍʏʀᴇɴᴅᴏᴀᴋʜᴜʟᴛᴄᴘʙғᴊᴡɢ😋👏שלוםבי😱‼\\x81エンジ故障\\u2009🚌ᴵ͞🌟😊😳😧🙀😐😕\\u200f👍😮😃😘אעכח💩💯⛽🚄🏼ஜ😖ᴠ🚲‐😟😈💪🙏🎯🌹😇💔😡\\x7f👌ἐὶήιὲκἀίῃἴξ🙄H😠\\ufeff\\u2028😉😤⛺🙂\\u3000تحكسة👮💙فزط😏🍾🎉😞\\u2008🏾😅😭👻😥😔😓🏽🎆🍻🍽🎶🌺🤔😪\\x08‑🐰🐇🐱🙆😨🙃💕𝘊𝘦𝘳𝘢𝘵𝘰𝘤𝘺𝘴𝘪𝘧𝘮𝘣💗💚地獄谷улкнПоАН🐾🐕😆ה🔗🚽歌舞伎🙈😴🏿🤗🇺🇸мυтѕ⤵🏆🎃😩\\u200a🌠🐟💫💰💎эпрд\\x95🖐🙅⛲🍰🤐👆🙌\\u2002💛🙁👀🙊🙉\\u2004ˢᵒʳʸᴼᴷᴺʷᵗʰᵉᵘ\\x13🚬🤓\\ue602😵άοόςέὸתמדףנרךצט😒͝🆕👅👥👄🔄🔤👉👤👶👲🔛🎓\\uf0b7\\uf04c\\x9f\\x10成都😣⏺😌🤑🌏😯ех😲Ἰᾶὁ💞🚓🔔📚🏀👐\\u202d💤🍇\\ue613小土豆🏡❔⁉\\u202f👠》कर्मा🇹🇼🌸蔡英文🌞🎲レクサス😛外国人关系Сб💋💀🎄💜🤢َِьыгя不是\\x9c\\x9d🗑\\u2005💃📣👿༼つ༽😰ḷЗз▱ц🤣卖温哥华议会下降你失去所有的钱加拿大坏税骗子🐝ツ🎅\\x85🍺آإشء🎵🌎͟ἔ油别克🤡🤥😬🤧й\\u2003🚀🤴ʲшчИОРФДЯМюж😝🖑ὐύύ特殊作戦群щ💨圆明园קℐ🏈😺🌍⏏ệ🍔🐮🍁🍆🍑🌮🌯🤦\\u200d𝓒𝓲𝓿𝓵안영하세요ЖљКћ🍀😫🤤ῦ我出生在了可以说普通话汉语好极🎼🕺🍸🥂🗽🎇🎊🆘🤠👩🖒🚪天一家⚲\\u2006⚭⚆⬭⬯⏖新✀╌🇫🇷🇩🇪🇮🇬🇧😷🇨🇦ХШ🌐\\x1f杀鸡给猴看ʁ𝗪𝗵𝗲𝗻𝘆𝗼𝘂𝗿𝗮𝗹𝗶𝘇𝗯𝘁𝗰𝘀𝘅𝗽𝘄𝗱📺ϖ\\u2000үսᴦᎥһͺ\\u2007հ\\u2001ɩye൦lƽh𝐓𝐡𝐞𝐫𝐮𝐝𝐚𝐃𝐜𝐩𝐭𝐢𝐨𝐧Ƅᴨןᑯ໐ΤᏧ௦Іᴑ܁𝐬𝐰𝐲𝐛𝐦𝐯𝐑𝐙𝐣𝐇𝐂𝐘𝟎ԜТᗞ౦〔Ꭻ𝐳𝐔𝐱𝟔𝟓𝐅🐋ffi💘💓ё𝘥𝘯𝘶💐🌋🌄🌅𝙬𝙖𝙨𝙤𝙣𝙡𝙮𝙘𝙠𝙚𝙙𝙜𝙧𝙥𝙩𝙪𝙗𝙞𝙝𝙛👺🐷ℋ𝐀𝐥𝐪🚶𝙢Ἱ🤘ͦ💸ج패티W𝙇ᵻ👂👃ɜ🎫\\uf0a7БУі🚢🚂ગુજરાતીῆ🏃𝓬𝓻𝓴𝓮𝓽𝓼☘﴾̯﴿₽\\ue807𝑻𝒆𝒍𝒕𝒉𝒓𝒖𝒂𝒏𝒅𝒔𝒎𝒗𝒊👽😙\\u200cЛ‒🎾👹⎌🏒⛸公寓养宠物吗🏄🐀🚑🤷操美𝒑𝒚𝒐𝑴🤙🐒欢迎来到阿拉斯ספ𝙫🐈𝒌𝙊𝙭𝙆𝙋𝙍𝘼𝙅ﷻ🦄巨收赢得白鬼愤怒要买额ẽ🚗🐳𝟏𝐟𝟖𝟑𝟕𝒄𝟗𝐠𝙄𝙃👇锟斤拷𝗢𝟳𝟱𝟬⦁マルハニチロ株式社⛷한국어ㄸㅓ니͜ʖ𝘿𝙔₵𝒩ℯ𝒾𝓁𝒶𝓉𝓇𝓊𝓃𝓈𝓅ℴ𝒻𝒽𝓀𝓌𝒸𝓎𝙏ζ𝙟𝘃𝗺𝟮𝟭𝟯𝟲👋🦊多伦🐽🎻🎹⛓🏹🍷🦆为和中友谊祝贺与其想象对法如直接问用自己猜本传教士没积唯认识基督徒曾经让相信耶稣复活死怪他但当们聊些政治题时候战胜因圣把全堂结婚孩恐惧且栗谓这样还♾🎸🤕🤒⛑🎁批判检讨🏝🦁🙋😶쥐스탱트뤼도석유가격인상이경제황을렵게만들지않록잘관리해야합다캐나에서대마초와화약금의품런성분갈때는반드시허된사용🔫👁凸ὰ💲🗯𝙈Ἄ𝒇𝒈𝒘𝒃𝑬𝑶𝕾𝖙𝖗𝖆𝖎𝖌𝖍𝖕𝖊𝖔𝖑𝖉𝖓𝖐𝖜𝖞𝖚𝖇𝕿𝖘𝖄𝖛𝖒𝖋𝖂𝕴𝖟𝖈𝕸👑🚿💡知彼百\\uf005𝙀𝒛𝑲𝑳𝑾𝒋𝟒😦𝙒𝘾𝘽🏐𝘩𝘨ὼṑ𝑱𝑹𝑫𝑵𝑪🇰🇵👾ᓇᒧᔭᐃᐧᐦᑳᐨᓃᓂᑲᐸᑭᑎᓀᐣ🐄🎈🔨🐎🤞🐸💟🎰🌝🛳点击查版🍭𝑥𝑦𝑧NG👣\\uf020っ🏉ф💭🎥Ξ🐴👨🤳🦍\\x0b🍩𝑯𝒒😗𝟐🏂👳🍗🕉🐲چی𝑮𝗕𝗴🍒ꜥⲣⲏ🐑⏰鉄リ事件ї💊「」\\uf203\\uf09a\\uf222\\ue608\\uf202\\uf099\\uf469\\ue607\\uf410\\ue600燻製シ虚偽屁理屈Г𝑩𝑰𝒀𝑺🌤𝗳𝗜𝗙𝗦𝗧🍊ὺἈἡχῖΛ⤏🇳𝒙ψՁմեռայինրւդձ冬至ὀ𝒁🔹🤚🍎𝑷🐂💅𝘬𝘱𝘸𝘷𝘐𝘭𝘓𝘖𝘹𝘲𝘫کΒώ💢ΜΟΝΑΕ🇱♲𝝈↴💒⊘Ȼ🚴🖕🖤🥘📍👈➕🚫🎨🌑🐻𝐎𝐍𝐊𝑭🤖🎎😼🕷grntidufbk𝟰🇴🇭🇻🇲𝗞𝗭𝗘𝗤👼📉🍟🍦🌈🔭《🐊🐍\\uf10aლڡ🐦\\U0001f92f\\U0001f92a🐡💳ἱ🙇𝗸𝗟𝗠𝗷🥜さようなら🔼'", "_____no_output_____" ], [ "tokenizer = TreebankWordTokenizer()\n\nisolate_dict = {ord(c):f' {c} ' for c in symbols_to_isolate}\nremove_dict = {ord(c):f'' for c in symbols_to_delete}", "_____no_output_____" ], [ "x_train = train_df['comment_text'].progress_apply(lambda x:preprocess(x))\ny_aux_train = train_df[['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']]\nx_test = test_df['comment_text'].progress_apply(lambda x:preprocess(x))\n\nidentity_columns = [\n 'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish',\n 'muslim', 'black', 'white', 'psychiatric_or_mental_illness']\n# Overall\nweights = np.ones((len(x_train),)) / 4\n# Subgroup\nweights += (train_df[identity_columns].fillna(0).values>=0.5).sum(axis=1).astype(bool).astype(np.int) / 4\n# Background Positive, Subgroup Negative\nweights += (( (train_df['target'].values>=0.5).astype(bool).astype(np.int) +\n (train_df[identity_columns].fillna(0).values<0.5).sum(axis=1).astype(bool).astype(np.int) ) > 1 ).astype(bool).astype(np.int) / 4\n# Background Negative, Subgroup Positive\nweights += (( (train_df['target'].values<0.5).astype(bool).astype(np.int) +\n (train_df[identity_columns].fillna(0).values>=0.5).sum(axis=1).astype(bool).astype(np.int) ) > 1 ).astype(bool).astype(np.int) / 4\nloss_weight = 1.0 / weights.mean()\n\ny_train = np.vstack([(train_df['target'].values>=0.5).astype(np.int),weights]).T\n\nmax_features = 410047", " 99%|█████████▊| 1780823/1804874 [08:50<00:07, 3356.38it/s]\n100%|██████████| 97320/97320 [00:28<00:00, 3402.04it/s]\n" ], [ "tokenizer = text.Tokenizer(num_words = max_features, filters='',lower=False)", "_____no_output_____" ], [ "tokenizer.fit_on_texts(list(x_train) + list(x_test))\n\ncrawl_matrix, unknown_words_crawl = build_matrix(tokenizer.word_index, CRAWL_EMBEDDING_PATH)\nprint('n unknown words (crawl): ', len(unknown_words_crawl))\n\nglove_matrix, unknown_words_glove = build_matrix(tokenizer.word_index, GLOVE_EMBEDDING_PATH)\nprint('n unknown words (glove): ', len(unknown_words_glove))\n\nmax_features = max_features or len(tokenizer.word_index) + 1\nmax_features\n\nembedding_matrix = np.concatenate([crawl_matrix, glove_matrix], axis=-1)\nembedding_matrix.shape\n\ndel crawl_matrix\ndel glove_matrix\ngc.collect()\n\ny_train_torch = torch.tensor(np.hstack([y_train, y_aux_train]), dtype=torch.float32)", "/opt/conda/lib/python3.6/site-packages/smart_open/smart_open_lib.py:398: UserWarning: This function is deprecated, use smart_open.open instead. See the migration notes for details: https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst#migrating-to-the-new-open-function\n 'See the migration notes for details: %s' % _MIGRATION_NOTES_URL\n" ], [ "x_train = tokenizer.texts_to_sequences(x_train)\nx_test = tokenizer.texts_to_sequences(x_test)", "_____no_output_____" ], [ "lengths = torch.from_numpy(np.array([len(x) for x in x_train]))\n \nmaxlen = 300\nx_train_padded = torch.from_numpy(sequence.pad_sequences(x_train, maxlen=maxlen))", "_____no_output_____" ], [ "test_lengths = torch.from_numpy(np.array([len(x) for x in x_test]))\n\nx_test_padded = torch.from_numpy(sequence.pad_sequences(x_test, maxlen=maxlen))", "_____no_output_____" ], [ "batch_size = 512\ntest_dataset = data.TensorDataset(x_test_padded, test_lengths)\ntrain_dataset = data.TensorDataset(x_train_padded, lengths, y_train_torch)\nvalid_dataset = data.Subset(train_dataset, indices=[0, 1])\n\ntrain_collator = SequenceBucketCollator(lambda lenghts: lenghts.max(), \n sequence_index=0, \n length_index=1, \n label_index=2)\ntest_collator = SequenceBucketCollator(lambda lenghts: lenghts.max(), sequence_index=0, length_index=1)\n\ntrain_loader = data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, collate_fn=train_collator)\nvalid_loader = data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=False, collate_fn=train_collator)\ntest_loader = data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, collate_fn=test_collator)\n\ndatabunch = DataBunch(train_dl=train_loader, valid_dl=valid_loader, collate_fn=train_collator)", "_____no_output_____" ], [ "all_test_preds = []\n\nfor model_idx in range(NUM_MODELS):\n print('Model ', model_idx)\n seed_everything(1 + model_idx)\n model = NeuralNet(embedding_matrix, y_aux_train.shape[-1])\n learn = Learner(databunch, model, loss_func=custom_loss)\n test_preds = train_model(learn,test_dataset,output_dim=7) \n all_test_preds.append(test_preds)", "Model 0\nepoch train_loss valid_loss time \n0 0.282716 0.011497 10:30 \nepoch train_loss valid_loss time \n0 0.265401 0.006181 10:29 \nepoch train_loss valid_loss time \n0 0.263534 0.007372 10:32 \nepoch train_loss valid_loss time \n0 0.258076 0.009170 10:32 \nModel 1\nepoch train_loss valid_loss time \n0 0.276667 0.007452 10:32 \nepoch train_loss valid_loss time \n0 0.270660 0.009762 10:31 \nepoch train_loss valid_loss time \n0 0.261831 0.015536 10:31 \nepoch train_loss valid_loss time \n0 0.259937 0.013611 10:30 \n" ], [ "submission_lstm = pd.DataFrame.from_dict({\n 'id': test_df['id'],\n 'prediction': np.mean(all_test_preds, axis=0)[:, 0]\n})", "_____no_output_____" ] ], [ [ "**Blending part**", "_____no_output_____" ] ], [ [ "submission = pd.read_csv('../input/jigsaw-unintended-bias-in-toxicity-classification/sample_submission.csv')\nsubmission['prediction'] = ((submission_bert.prediction + submission_lstm.prediction)/2 + submission_lstm.prediction)/2\nsubmission.to_csv('submission.csv', index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4aef3773439a7361ea5d67a6da92356deee1a11e
203,284
ipynb
Jupyter Notebook
data visualization methods.ipynb
kuluruvineeth/Machine-Learning-with-Python
1c07f6e489c3b8fd9ac0f6bd26dad2db58775423
[ "MIT" ]
null
null
null
data visualization methods.ipynb
kuluruvineeth/Machine-Learning-with-Python
1c07f6e489c3b8fd9ac0f6bd26dad2db58775423
[ "MIT" ]
null
null
null
data visualization methods.ipynb
kuluruvineeth/Machine-Learning-with-Python
1c07f6e489c3b8fd9ac0f6bd26dad2db58775423
[ "MIT" ]
null
null
null
649.469649
99,320
0.953533
[ [ [ "# Univariate Plots\n(understanding each attribute of dataset independently)", "_____no_output_____" ], [ "## Histogram", "_____no_output_____" ], [ "* Histograms group data into bins and provides a count of the number of observations in each bin.\n* From the shape of the bins we can quickly get a feeling for whether an attribute is Gaussian,skewed or even has exponential distribution.\n* It can also help with possible outliers", "_____no_output_____" ] ], [ [ "from matplotlib import pyplot\nfrom pandas import read_csv\nfilename = 'pima-indians-diabetes.data.csv'\nnames = ['preg','plas','pres','skin','test','mass','pedi','age','class']\ndata = read_csv(filename,names=names)\ndata.hist()\npyplot.show()", "_____no_output_____" ] ], [ [ "## Density Plots", "_____no_output_____" ], [ "* It is also another way to get idea of the distribution of each attribute\n* It looks like an abstracted histogram with a smooth curve drawn through the top of each bin.", "_____no_output_____" ] ], [ [ "data.plot(kind='density',subplots=True,layout=(3,3),sharex=False)\npyplot.show()", "_____no_output_____" ] ], [ [ "## Box and Whisker Plots", "_____no_output_____" ], [ "* Boxplots summarize the distribution of each attribute,drawing a line for the median and a box around the 25th and 75th percentiles.\n* The whiskers give an idea of the spread of the data and dots outside of the whiskers show candidate outlier values", "_____no_output_____" ] ], [ [ "data.plot(kind='box',subplots=True,layout=(3,3),sharex=False,sharey=False)\npyplot.show()", "_____no_output_____" ] ], [ [ "# Multivariate Plots\n(It shows the interactions between multiple variables in our dataset)", "_____no_output_____" ], [ "## Correlation Matrix Plot", "_____no_output_____" ], [ "* It gives an indication of how related the changes are between two variables.\n* If two variables change in the same direction they are **positively correlated**.\n* If they change in opposite directions together then they are **negatively related**.\n* Algoruthms like *linear and logistic regression* can have poor performance if there are highly correlated input variables in our data. ", "_____no_output_____" ] ], [ [ "import numpy as np\ncorrelations = data.corr()\n\n# plotting correlation matrix\nfig = pyplot.figure()\nax = fig.add_subplot(111)\ncax = ax.matshow(correlations,vmin=-1,vmax=1)\nfig.colorbar(cax)\nticks = np.arange(0,9,1)\nax.set_xticks(ticks)\nax.set_yticks(ticks)\nax.set_xticklabels(names)\nax.set_yticklabels(names)\npyplot.show()", "_____no_output_____" ], [ "fig = pyplot.figure()\nax = fig.add_subplot(111)\ncax = ax.matshow(correlations,vmin=-1,vmax=1)\nfig.colorbar(cax)\npyplot.show()", "_____no_output_____" ] ], [ [ "## Scatter Plot Matrix", "_____no_output_____" ], [ "* It shows the relationship between two variables as dots in two dimensions,one axis for each attribute ", "_____no_output_____" ] ], [ [ "from pandas.plotting import scatter_matrix\nscatter_matrix(data)\npyplot.show()", "_____no_output_____" ] ], [ [ "## Summary\n* Learnt how to analyse data using various plots like histogram,density plots,correlation matrix and sactter plot matrix", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4aef3cd65edaf47215d933f61d16e98b2daf7f9a
226,001
ipynb
Jupyter Notebook
train.ipynb
PierreEpron/mednist-classification
25a884fc4e8424436463b9fd17ed51dbf885d304
[ "MIT" ]
null
null
null
train.ipynb
PierreEpron/mednist-classification
25a884fc4e8424436463b9fd17ed51dbf885d304
[ "MIT" ]
null
null
null
train.ipynb
PierreEpron/mednist-classification
25a884fc4e8424436463b9fd17ed51dbf885d304
[ "MIT" ]
null
null
null
214.625831
170,200
0.880385
[ [ [ "<a href=\"https://www.nvidia.com/en-us/deep-learning-ai/education/\"> <img src=\"images/DLI Header.png\" alt=\"Header\" style=\"width: 400px;\"/> </a>", "_____no_output_____" ], [ "<a href=\"https://www.mayoclinic.org/\"><img src=\"images/mayologo.png\" alt=\"Mayo Logo\"></a>\n# Medical Image Classification Using the MedNIST Dataset\n### Special thanks to <a href=\"https://www.mayo.edu/research/labs/radiology-informatics/overview\">Dr. Bradley J. Erickson M.D., Ph.D.</a> - Department of Radiology, Mayo Clinic\n#### Acknowledgements: <a href=\"http://www.cancerimagingarchive.net/\">The Cancer Imaging Archive (TCIA)</a>; <a href =\"http://rsnachallenges.cloudapp.net/competitions/4\">Radiological Society of North America</a>; <a href= \"http://openaccess.thecvf.com/content_cvpr_2017/papers/Wang_ChestX-ray8_Hospital-Scale_Chest_CVPR_2017_paper.pdf\">National Institute of Health</a>\n", "_____no_output_____" ], [ "## Introduction\n\nThe use of Artificial Intelligence (AI), and deep Convolutional Neural Networks (CNNs) in particular, has led to improvements in the speed of radiological image processing and diagnosis. This speed-up has not come at the price of accuracy; cutting-edge algorithms are comparable to the current standard of care. The best human experts still outperform AI, so the technologies being developed serve as a complement to doctors and researchers, not as their replacement. Thus, it's important that those using these new tools attain some familiarity with their inner workings.\n\n## Outline\n<ul>\n <li>Discussion of deep learning frameworks</li>\n <li>Creating a dataset for training and testing</li>\n <li>Transforming and partitioning data</li>\n <li>Architecting a CNN</li>\n <li>Training the model</li>\n <li>Testing on new images</li>\n <li>Exercises</li>\n</ul>\n", "_____no_output_____" ], [ "## Deep Learning and Frameworks\nA generic deep neural network consists of a series of <em>layers</em>, running between the input and output layers. Each layer is comprised of <em>nodes</em>, which store intermediate numerical values. The values from each layer are fed to the next after linear transformation by a tensor of <em>weights</em> and a nonlinear <em>activation function</em>. This overall structure is called the <em>architecture</em>.\n\nIn <em>supervised learning</em>, which we will be studying here, each input datum (X value) is provided along with a target output or label (Y value). The inputs can be very general types of data: images, sentences, video clips, etc. The outputs are often things like image classes, text sentiments, or object locations.\n\nThe X values are mapped through the network to outputs (Y predictions). The Y predictions are compared to the actual Y values, and the difference between them is quantified through a <em>loss function</em>. An <em>optimizer</em> varies the weights of the network over several iterations through the dataset, or <em>epochs</em>, in order to minimize the loss. This process is called <em>training</em> the network.\n\nBy providing a large and detailed training dataset, creating an adequately complex network architecture, and training for a sufficient amount of time, the model should be able to predict the correct label for inputs that it has never seen before. Feeding new input into a trained model and making use of its predictions is known as <em>deployment</em>.\n\nThe overhead to create and train networks with standard programming libraries is quite large. Fortunately, deep learning enthusiasts have done the heavy lifting in this process by creating specialized libraries, or <em>frameworks</em>, that allow us to condense what would be thousands of lines of tangled code down into a few dozen straightforward and readable ones. The framework used in this lab is PyTorch, which is on the beginner-friendly side while having its own technical advantages of interest to power users, too. Other popular frameworks include TensorFlow, MS Cognitive Toolkit, and MXNet, each of which has unique tradeoffs between ease of use, flexibility, speed, and accuracy.\n\nThere are also higher-level frameworks called <em>wrappers</em> that can be set up with simpler code or even graphical interfaces, that in turn are able to switch between several different lower-level frameworks with the setting of a single toggle. A popular code-based wrapper is Keras, while DIGITS is a graphical one.\n\nIn the code below, we load the PyTorch framework and other useful libraries. Due to the mathematically intensive nature of training, the code runs much faster on a GPU than on a conventional CPU, so we set parameters allowing for GPU acceleration.\n\n### Using Jupyter\nSimply press `Shift+Enter` or the \"Run\" button in the toolbar above while a cell is highlighted to execute the code contained within. Code can be stopped by pressing the \"Stop\" button next to the \"Run\" button. Sometimes, a markdown cell will get switched to editing mode, though changes cannot actually be made. Pressing `Shift+Enter` will switch it back to a readable form.\n\n### Code Block 1\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport random\nimport os\nimport time\n%matplotlib inline\nimport matplotlib.pyplot as mp\nfrom PIL import Image\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as om\nimport torchvision as tv\nimport torch.utils.data as dat\n\nif torch.cuda.is_available(): # Make sure GPU is available\n dev = torch.device(\"cuda:0\")\n kwar = {'num_workers': 8, 'pin_memory': True}\n cpu = torch.device(\"cpu\")\nelse:\n print(\"Warning: CUDA not found, CPU only.\")\n dev = torch.device(\"cpu\")\n kwar = {}\n cpu = torch.device(\"cpu\")\n\nseed = 551\nnp.random.seed(seed)\ntorch.manual_seed(seed)\nrandom.seed(seed)", "_____no_output_____" ] ], [ [ "## Loading Data and Creating Datasets\nDue to cost, privacy restrictions, and the rarity of certain conditions, gathering medical datasets can be particularly challenging. Once gathered from disparate sources, these data will need to be standardized for training. Preparing data at this level is beyond the scope of this short introductory primer. We have gathered images from several sets at TCIA, the RSNA Bone Age Challenge, and the NIH Chest X-ray dataset and standardized them to the same size.\n\nThe code below examines our image set, organizes the filenames, and displays some statistics about them.\n\n### Code Block 2", "_____no_output_____" ] ], [ [ "dataDir = 'resized' # The main data directory\nclassNames = os.listdir(dataDir) # Each type of image can be found in its own subdirectory\nnumClass = len(classNames) # Number of types = number of subdirectories\nimageFiles = [[os.path.join(dataDir,classNames[i],x) for x in os.listdir(os.path.join(dataDir,classNames[i]))]\n for i in range(numClass)] # A nested list of filenames\nnumEach = [len(imageFiles[i]) for i in range(numClass)] # A count of each type of image\nimageFilesList = [] # Created an un-nested list of filenames\nimageClass = [] # The labels -- the type of each individual image in the list\nfor i in range(numClass):\n imageFilesList.extend(imageFiles[i])\n imageClass.extend([i]*numEach[i])\nnumTotal = len(imageClass) # Total number of images\nimageWidth, imageHeight = Image.open(imageFilesList[0]).size # The dimensions of each image\n\nprint(\"There are\",numTotal,\"images in\",numClass,\"distinct categories\")\nprint(\"Label names:\",classNames)\nprint(\"Label counts:\",numEach)\nprint(\"Image dimensions:\",imageWidth,\"x\",imageHeight)\n", "There are 64322 images in 7 distinct categories\nLabel names: ['AbdomenCT', 'BreastMRI', 'ChestCT', 'CXR', 'Hand', 'HeadCT', 'Pelvis']\nLabel counts: [10000, 8954, 10000, 10000, 10000, 10000, 5368]\nImage dimensions: 64 x 64\n" ] ], [ [ "Because it is comparable to the <a href=\"http://yann.lecun.com/exdb/mnist/\">MNIST dataset</a>, which has 70,000 total 28 x 28 images of handwritten digits from 0 - 9, we call this the MedNIST dataset. Notice, however, that the data aren't perfectly balanced. We'll address that while training the model.\n\nAs the saying goes, a picture is worth 1,000 ± 32 statistics, so let's examine a few random sample images. The following cell can be run repeatedly.\n \n### Code Block 3", "_____no_output_____" ] ], [ [ "mp.subplots(3,3,figsize=(8,8))\nfor i,k in enumerate(np.random.randint(numTotal, size=9)): # Take a random sample of 9 images and\n im = Image.open(imageFilesList[k]) # plot and label them\n arr = np.array(im)\n mp.subplot(3,3,i+1)\n mp.xlabel(classNames[imageClass[k]])\n mp.imshow(arr,cmap='gray',vmin=0,vmax=255)\nmp.tight_layout()\nmp.show()\n", "_____no_output_____" ] ], [ [ "## Transforming Data and Partitioning into Training, Validation, and Testing Sets\n\nDepending on the images shown, you may notice a few things. There are definitely higher and lower quality images. Also, some images also have a different scale - the background isn't black but gray. Because there's a smaller difference between pixels, our model might have a harder time extracting information from them. Thus, to increase the contrast, we first rescale every image so the pixel values run from 0 to 1. \n\nNext, we subtract the mean pixel value of each individual image from the rest. The network could in principle learn to do this through training. However, the activation functions tend to be most sensitive / nonlinear near zero. Therefore, shifting our data to have an average input value of zero will improve the sensitivity and stability of initial training steps and tends to speed things up a little. While it doesn't matter much for the simple model we use here, such tricks can make a noticeable difference in complex models.\n\nAlso, before doing any of these, we'll need to convert the JPEG images into tensors. We define a function below that combines all these steps.\n\n### Code Block 4", "_____no_output_____" ] ], [ [ "toTensor = tv.transforms.ToTensor()\ndef scaleImage(x): # Pass a PIL image, return a tensor\n y = toTensor(x)\n if(y.min() < y.max()): # Assuming the image isn't empty, rescale so its values run from 0 to 1\n y = (y - y.min())/(y.max() - y.min()) \n z = y - y.mean() # Subtract the mean value of the image\n return z\n", "_____no_output_____" ] ], [ [ "With the image-to-tensor transformation function defined, we now create a master tensor out of all these images. We also create a tensor for the labels. Execution of this code takes a moment. We double check the final range of scaled pixel values and verify that the mean is (practically) zero.\n\n### Code Block 5", "_____no_output_____" ] ], [ [ "imageTensor = torch.stack([scaleImage(Image.open(x)) for x in imageFilesList]) # Load, scale, and stack image (X) tensor\nclassTensor = torch.tensor(imageClass) # Create label (Y) tensor\nprint(\"Rescaled min pixel value = {:1.3}; Max = {:1.3}; Mean = {:1.3}\"\n .format(imageTensor.min().item(),imageTensor.max().item(),imageTensor.mean().item()))\n", "Rescaled min pixel value = -0.786; Max = 0.972; Mean = -3.19e-09\n" ] ], [ [ "With everything in order so far, we move on to partitioning these master tensors into three datatsets.\n\nBecause a model may have millions of free parameters, it is quite possible for it to <em>overfit</em> to the data provided. That is, it may adjust its weights to the precise values needed to predict every given image correctly, yet fail to recognize even slight variations on the original images, let alone brand new ones.\n\nA common solution is to separate data into a training set, used to minimize the loss function, and a validation set, evaluated separately during training without directly affecting the model's weights. However, the validation set may be used to modify the <em>hyperparameters</em> (parameters outside the model governing its training), select the best model every epoch, or indirectly impact the training in some other way. For this reason, a third, independent testing set is usually created for final evaluation once the training is complete.\n\nBecause the more data the model sees, the more accurate it tends to become, we usually reserve relatively small fractions for validation and testing.\n\nPyTorch has a built in <a href=\"https://pytorch.org/docs/stable/_modules/torch/utils/data/dataset.html\">Dataset</a> object that can simplify these steps when working with more complex types of data, but in this case, they would require more effort than they save.\n\nThe code below will randomly assign approximately 10% of the indices to lists corresponding to the validation and testing sets. Once this is done, we can create these datasets by slicing the master image and label tensors using these lists.\n\n### Code Block 6", "_____no_output_____" ] ], [ [ "validFrac = 0.1 # Define the fraction of images to move to validation dataset\ntestFrac = 0.1 # Define the fraction of images to move to test dataset\nvalidList = []\ntestList = []\ntrainList = []\n\nfor i in range(numTotal):\n rann = np.random.random() # Randomly reassign images\n if rann < validFrac:\n validList.append(i)\n elif rann < testFrac + validFrac:\n testList.append(i)\n else:\n trainList.append(i)\n \nnTrain = len(trainList) # Count the number in each set\nnValid = len(validList)\nnTest = len(testList)\nprint(\"Training images =\",nTrain,\"Validation =\",nValid,\"Testing =\",nTest)\n\n", "Training images = 51694 Validation = 6376 Testing = 6252\n" ] ], [ [ "If we're satisfied with the breakdown into training, validation, and testing, we can now use these lists to slice the master tensors with the code below. If not, we can rerun the cell above with different fractions set aside.\n\n### Code Block 7", "_____no_output_____" ] ], [ [ "trainIds = torch.tensor(trainList) # Slice the big image and label tensors up into\nvalidIds = torch.tensor(validList) # training, validation, and testing tensors\ntestIds = torch.tensor(testList)\ntrainX = imageTensor[trainIds,:,:,:]\ntrainY = classTensor[trainIds]\nvalidX = imageTensor[validIds,:,:,:]\nvalidY = classTensor[validIds]\ntestX = imageTensor[testIds,:,:,:]\ntestY = classTensor[testIds]", "_____no_output_____" ] ], [ [ "## Model Architecture\n\nThe details of the architecture are explained in the comments within the code, but here we give an overview of the two types of layers encountered.\n\nThe first is the <em>convolutional</em> layer. When interpreting an image, the eye first identifies edges and boundaries. Then, one can make out curves, shapes, and more complex structures at higher levels of abstraction. By only combining information from nearby pixels at first, a series of convolutional layers mimics this organic process. The size of the convolution is how many adjacent pixels are weighted and added up when moving to the next layer, and we can apply multiple convolutions to every pixel in an image (or in a higher layer). Pictured below is a single 3 × 3 convolution. The value of each pixel of the convolutional kernel - these are the weights that are trained - is multiplied with the corresponding pixel value within the neighborhood of the original, central image pixel. These products are summed up, and the total is placed in the central pixel (node, to use the nomenclature) of the new layer. The process is repeated for each pixel and each convolution within the layer. Several convolutional layers can be stacked on top of each other; this has the effect of finding increasingly complex features.\n\n<img src=\"images/Convolution.png\" width=\"600\" alt=\"Convolution\">", "_____no_output_____" ], [ "After several convolutional layers, it is typical to have a few fully connected layers. First, all the information from the last layer is \"flattened\" into a vector. In a fully connected layer, there are weights connecting every single node (place to store a value) of the input layer to every single node of the output layer - no special preference is given to neighboring nodes as in the pixels of a convolutional layer. The weights multiply the values in the nodes of the input layer, are summed together, and then placed in a node of the output layer. This is repeated for each node in the output layer.\n\nNow, there is one additional step in each of these that has been omitted: appication of the activation function. If the linear function `y = 3x + 2` is composed with `z = 4y - 7`, then z is still a linear function of x: `z = 12x + 1`. The same thing is true for linear functions in higher dimensions (multiplication by weights and summing, as we have been doing). Without the activation function, no matter how many layers we stack together, it could ultimately be replaced by a single one. To avoid this, at each output layer, we apply a nonlinear activation function. This need not be the same function at every layer. In this architecture, we choose <a href=\"http://image-net.org/challenges/posters/JKU_EN_RGB_Schwarz_poster.pdf\">ELU</a> functions, but there are many other popular options, such as <a href=\"https://en.wikipedia.org/wiki/Rectifier_(neural_networks)\">ReLU</a>.\n\n### Code Block 8", "_____no_output_____" ] ], [ [ "class MedNet(nn.Module):\n def __init__(self,xDim,yDim,numC): # Pass image dimensions and number of labels when initializing a model \n super(MedNet,self).__init__() # Extends the basic nn.Module to the MedNet class\n # The parameters here define the architecture of the convolutional portion of the CNN. Each image pixel\n # has numConvs convolutions applied to it, and convSize is the number of surrounding pixels included\n # in each convolution. Lastly, the numNodesToFC formula calculates the final, remaining nodes at the last\n # level of convolutions so that this can be \"flattened\" and fed into the fully connected layers subsequently.\n # Each convolution makes the image a little smaller (convolutions do not, by default, \"hang over\" the edges\n # of the image), and this makes the effective image dimension decreases.\n \n numConvs1 = 8\n convSize1 = 3\n numConvs2 = 16\n convSize2 = 3\n numConvs3 = 32\n convSize3 = 3\n numConvs4 = 64\n convSize4 = 3\n \n # nn.Conv2d(channels in, channels out, convolution height/width)\n # 1 channel -- grayscale -- feeds into the first convolution. The same number output from one layer must be\n # fed into the next. These variables actually store the weights between layers for the model.\n \n self.cnv1 = nn.Conv2d(1, numConvs1, convSize1)\n self.cnv2 = nn.Conv2d(numConvs1, numConvs2, convSize2)\n self.mp1 = nn.MaxPool2d((2,2))\n self.bn1 = nn.BatchNorm2d(16)\n self.dp1 = nn.Dropout(.1)\n self.cnv3 = nn.Conv2d(numConvs2, numConvs3, convSize3)\n self.cnv4 = nn.Conv2d(numConvs3, numConvs4, convSize4)\n self.dp2 = nn.Dropout(.1)\n self.mp2 = nn.MaxPool2d((2,2))\n self.bn2 = nn.BatchNorm2d(64)\n numNodesToFC = int(numConvs4 * (xDim / 4 - 3) * (yDim / 4 - 3))\n \n # These parameters define the number of output nodes of each fully connected layer.\n # Each layer must output the same number of nodes as the next layer begins with.\n # The final layer must have output nodes equal to the number of labels used.\n \n fcSize1 = 100\n# fcSize2 = 20\n \n # nn.Linear(nodes in, nodes out)\n # Stores the weights between the fully connected layers\n \n self.ful1 = nn.Linear(numNodesToFC,fcSize1)\n# self.ful2 = nn.Linear(fcSize1, fcSize2)\n self.ful3 = nn.Linear(fcSize1,numC)\n \n def forward(self,x):\n # This defines the steps used in the computation of output from input.\n # It makes uses of the weights defined in the __init__ method.\n # Each assignment of x here is the result of feeding the input up through one layer.\n # Here we use the activation function elu, which is a smoother version of the popular relu function.\n \n x = F.elu(self.cnv1(x)) # Feed through first convolutional layer, then apply activation\n x = F.elu(self.cnv2(x)) # Feed through second convolutional layer, apply activation\n x = F.elu(self.mp1(x))\n x = F.elu(self.bn1(x))\n x = F.elu(self.dp1(x))\n x = F.elu(self.cnv3(x)) # Feed through thirst convolutional layer, then apply activation\n x = F.elu(self.cnv4(x)) # Feed through fourth convolutional layer, apply activation\n x = F.elu(self.mp2(x))\n x = F.elu(self.bn2(x))\n x = F.elu(self.dp2(x))\n x = x.view(-1,self.num_flat_features(x)) # Flatten convolutional layer into fully connected layer\n x = F.relu(self.ful1(x)) # Feed through first fully connected layer, apply activation\n# x = F.elu(self.ful2(x)) # Feed through second FC layer, apply output\n x = self.ful3(x) # Final FC layer to output. No activation, because it's used to calculate loss\n return x\n\n def num_flat_features(self, x): # Count the individual nodes in a layer\n size = x.size()[1:]\n num_features = 1\n for s in size:\n num_features *= s\n return num_features", "_____no_output_____" ] ], [ [ "With the architecture defined, we create an instance of the model. This single line is separated out so that we can continue or repeat the training code below without resetting the model from scratch, if needed.\n\n### Code Block 9", "_____no_output_____" ] ], [ [ "model = MedNet(imageWidth,imageHeight,numClass).to(dev)\nmodel", "_____no_output_____" ] ], [ [ "## Training the Model\n\nNow, it's time to train the model. The next code block does so.\n\nFirst, we define the hyperparameters of the training. The learning rate reflects how much the model is updated per batch. If it is too small, the training proceeds slowly. If it's too large, the weights will be adjusted too much and miss the true minimum loss, or even become unstable. An epoch is a full run through the training data. Some models require thousands of epochs to train; this one will produce high accuracy with just a handful.\n\nWe use validation data to prevent overtraining in our model. The training and validation data are drawn from the same set of data; therefore, the model ought to have similar loss for both. Thus, we set a limit on how much larger the validation loss can be than the training loss. Because random fluctuation might account for some discrepancy, we require a few epochs pass with high validation loss before halting.\n\nThe memory overhead required to feed large datasets through the model can be prohibitive. <em>Batches</em> are an important workaround for this problem. By loading smaller data subsets onto the GPU and training off of them, we can not only save memory, but also speed up the training by making more adjustments to the model per epoch. Smaller batches generally require smaller learning rates to avoid instability, however, so there is some tradeoff.\n\nImagine that a dataset had only a handful of examples of a particular label. The model could still acheive high accuracy overall while totally ignoring these. Using weights in the loss function, with larger weights for less numerous classes, is one strategy to combat this. If a class is particularly tiny, however, it is preferable to use data augmentation to generate new images rather than using weights alone, which are equivalent to feeding the same image over and over again through the network.\n\nNow, we move on to the actual training loop. The first real step is to shuffle the data before slicing it into batches. Once again, PyTorch provides a <a href=\"https://pytorch.org/docs/stable/_modules/torch/utils/data/dataloader.html#DataLoader\">DataLoader</a> class that can automate this, but it's about the same difficulty in this example to implement by hand.\n\nNext, we iterate through the batches. We zero out the accumulated information in the optimizer, feed the batch through the model, and compute the loss for a batch. We use the <a href=\"https://en.wikipedia.org/wiki/Cross_entropy\">cross entropy</a>, a common metric for classifiers. This loss is added to a running total for the epoch, and then we <em>backpropagate</em> it. Backpropagation is a mathematical determination of how much each weight in the model should be changed relative to the others to reduce the loss. The optimizer then takes a step and updates the weights.\n\nAfter all the training batches are complete, the same process happens for the validation data, without the backpropagation and optimization steps. The average loss is calculated, and we compare the validation loss relative to the training loss to test for overfitting.\n\nRun the cell to train the model.\n\n### Code Block 10", "_____no_output_____" ] ], [ [ "learnRate = 0.001 # Define a learning rate.\nmaxEpochs = 20 # Maximum training epochs\nt2vRatio = 1.2 # Maximum allowed ratio of validation to training loss\nt2vEpochs = 3 # Number of consecutive epochs before halting if validation loss exceeds above limit\nbatchSize = 300 # Batch size. Going too large will cause an out-of-memory error.\ntrainBats = nTrain // batchSize # Number of training batches per epoch. Round down to simplify last batch\nvalidBats = nValid // batchSize # Validation batches. Round down\ntestBats = -(-nTest // batchSize) # Testing batches. Round up to include all\nCEweights = torch.zeros(numClass) # This takes into account the imbalanced dataset.\nfor i in trainY.tolist(): # By making rarer images count more to the loss, \n CEweights[i].add_(1) # we prevent the model from ignoring them.\nCEweights = 1. / CEweights.clamp_(min=1.) # Weights should be inversely related to count\nCEweights = (CEweights * numClass / CEweights.sum()).to(dev) # The weights average to 1\nopti = om.Adam(model.parameters(), lr = learnRate) # Initialize an optimizer\n\n\nfor i in range(maxEpochs):\n model.train() # Set model to training mode\n epochLoss = 0.\n permute = torch.randperm(nTrain) # Shuffle data to randomize batches\n trainX = trainX[permute,:,:,:]\n trainY = trainY[permute]\n for j in range(trainBats): # Iterate over batches\n opti.zero_grad() # Zero out gradient accumulated in optimizer\n batX = trainX[j*batchSize:(j+1)*batchSize,:,:,:].to(dev) # Slice shuffled data into batches\n batY = trainY[j*batchSize:(j+1)*batchSize].to(dev) # .to(dev) moves these batches to the GPU\n yOut = model(batX) # Evalute predictions\n loss = F.cross_entropy(yOut, batY,weight=CEweights) # Compute loss\n epochLoss += loss.item() # Add loss\n loss.backward() # Backpropagate loss\n opti.step() # Update model weights using optimizer\n validLoss = 0.\n permute = torch.randperm(nValid) # We go through the exact same steps, without backprop / optimization\n validX = validX[permute,:,:,:] # in order to evaluate the validation loss\n validY = validY[permute]\n model.eval() # Set model to evaluation mode\n with torch.no_grad(): # Temporarily turn off gradient descent\n for j in range(validBats):\n opti.zero_grad()\n batX = validX[j*batchSize:(j+1)*batchSize,:,:,:].to(dev)\n batY = validY[j*batchSize:(j+1)*batchSize].to(dev)\n yOut = model(batX)\n validLoss += F.cross_entropy(yOut, batY,weight=CEweights).item()\n epochLoss /= trainBats # Average loss over batches and print\n validLoss /= validBats\n print(\"Epoch = {:-3}; Training loss = {:.4f}; Validation loss = {:.4f}\".format(i,epochLoss,validLoss))\n if validLoss > t2vRatio * epochLoss:\n t2vEpochs -= 1 # Test if validation loss exceeds halting threshold\n if t2vEpochs < 1:\n print(\"Validation loss too high; halting to prevent overfitting\")\n break\n ", "Epoch = 0; Training loss = 0.0350; Validation loss = 0.0078\nEpoch = 1; Training loss = 0.0021; Validation loss = 0.0036\nEpoch = 2; Training loss = 0.0009; Validation loss = 0.0010\nEpoch = 3; Training loss = 0.0008; Validation loss = 0.0050\nEpoch = 4; Training loss = 0.0019; Validation loss = 0.0013\nEpoch = 5; Training loss = 0.0007; Validation loss = 0.0013\nValidation loss too high; halting to prevent overfitting\n" ], [ "confuseMtx = np.zeros((numClass,numClass),dtype=int) # Create empty confusion matrix\nmodel.eval()\nwith torch.no_grad():\n permute = torch.randperm(nTest) # Shuffle test data\n testX = testX[permute,:,:,:]\n testY = testY[permute]\n for j in range(testBats): # Iterate over test batches\n batX = testX[j*batchSize:(j+1)*batchSize,:,:,:].to(dev)\n batY = testY[j*batchSize:(j+1)*batchSize].to(dev)\n yOut = model(batX) # Pass test batch through model\n pred = yOut.max(1,keepdim=True)[1] # Generate predictions by finding the max Y values\n for j in torch.cat((batY.view_as(pred), pred),dim=1).tolist(): # Glue together Actual and Predicted to\n confuseMtx[j[0],j[1]] += 1 # make (row, col) pairs, and increment confusion matrix\ncorrect = sum([confuseMtx[i,i] for i in range(numClass)]) # Sum over diagonal elements to count correct predictions\nprint(\"Correct predictions: \",correct,\"of\",nTest)\nprint(\"Confusion Matrix:\")\nprint(confuseMtx)\nprint(classNames)\nprint(f'{nTest-correct}')\nprint(f'{correct/nTest}')", "Correct predictions: 6249 of 6252\nConfusion Matrix:\n[[972 0 0 0 0 0 0]\n [ 0 898 0 0 0 0 0]\n [ 0 0 992 0 0 0 0]\n [ 0 0 0 963 0 0 0]\n [ 0 0 0 3 936 0 0]\n [ 0 0 0 0 0 976 0]\n [ 0 0 0 0 0 0 512]]\n['AbdomenCT', 'BreastMRI', 'ChestCT', 'CXR', 'Hand', 'HeadCT', 'Pelvis']\n3\n0.9995201535508638\n" ] ], [ [ "It is most likely that training was halted early to prevent overfitting. Still, the final loss should be roughly 0.01, a huge improvement on the random guessing that the model begins with. (These are slightly dependent on how the random numbers pan out based on how many times earlier cells were executed)\n\nYou may have also noticed that the training loss is quite a bit larger than the validation loss for the first several training steps. <b>Based on what you've learned about the training process, can you explain why this happens?</b>\n\n## Testing the Model on New Data\n\nWith the model fully trained, it's time to apply it to generate predictions from the test dataset. The model outputs a 6 element vector for each image. The individual values of this vector can be thought of, roughly, as relative probabilities that the image belongs in each class. Thus, we consider the class with the maximum value to be the prediction of the model.\n\nWe'll use these predictions to generate a confusion matrix. Despite its name, the confusion matrix is easily understood. The rows in the matrix represent the correct classifications, while the columns represent the predictions of the model. When the row and the column agree (i.e., along the diagonal), the model predicted correctly.\n\nThe short code snippet below iterates through the test batches and fills the confusion matrix.\n\n### Code Block 11", "_____no_output_____" ] ], [ [ "train_run_errors = []\nfor tr in range(100):\n torch.cuda.empty_cache()\n model = MedNet(imageWidth,imageHeight,numClass).to(dev)\n learnRate = 0.001 # Define a learning rate.\n maxEpochs = 20 # Maximum training epochs\n t2vRatio = 1.2 # Maximum allowed ratio of validation to training loss\n t2vEpochs = 3 # Number of consecutive epochs before halting if validation loss exceeds above limit\n batchSize = 300 # Batch size. Going too large will cause an out-of-memory error.\n trainBats = nTrain // batchSize # Number of training batches per epoch. Round down to simplify last batch\n validBats = nValid // batchSize # Validation batches. Round down\n testBats = -(-nTest // batchSize) # Testing batches. Round up to include all\n CEweights = torch.zeros(numClass) # This takes into account the imbalanced dataset.\n for i in trainY.tolist(): # By making rarer images count more to the loss, \n CEweights[i].add_(1) # we prevent the model from ignoring them.\n CEweights = 1. / CEweights.clamp_(min=1.) # Weights should be inversely related to count\n CEweights = (CEweights * numClass / CEweights.sum()).to(dev) # The weights average to 1\n opti = om.Adam(model.parameters(), lr = learnRate) # Initialize an optimizer\n\n for i in range(maxEpochs):\n model.train() # Set model to training mode\n epochLoss = 0.\n permute = torch.randperm(nTrain) # Shuffle data to randomize batches\n trainX = trainX[permute,:,:,:]\n trainY = trainY[permute]\n for j in range(trainBats): # Iterate over batches\n opti.zero_grad() # Zero out gradient accumulated in optimizer\n batX = trainX[j*batchSize:(j+1)*batchSize,:,:,:].to(dev) # Slice shuffled data into batches\n batY = trainY[j*batchSize:(j+1)*batchSize].to(dev) # .to(dev) moves these batches to the GPU\n yOut = model(batX) # Evalute predictions\n loss = F.cross_entropy(yOut, batY,weight=CEweights) # Compute loss\n epochLoss += loss.item() # Add loss\n loss.backward() # Backpropagate loss\n opti.step() # Update model weights using optimizer\n validLoss = 0.\n permute = torch.randperm(nValid) # We go through the exact same steps, without backprop / optimization\n validX = validX[permute,:,:,:] # in order to evaluate the validation loss\n validY = validY[permute]\n model.eval() # Set model to evaluation mode\n with torch.no_grad(): # Temporarily turn off gradient descent\n for j in range(validBats):\n opti.zero_grad()\n batX = validX[j*batchSize:(j+1)*batchSize,:,:,:].to(dev)\n batY = validY[j*batchSize:(j+1)*batchSize].to(dev)\n yOut = model(batX)\n validLoss += F.cross_entropy(yOut, batY,weight=CEweights).item()\n epochLoss /= trainBats # Average loss over batches and print\n validLoss /= validBats\n print(\"Epoch = {:-3}; Training loss = {:.4f}; Validation loss = {:.4f}\".format(i,epochLoss,validLoss))\n if validLoss > t2vRatio * epochLoss:\n t2vEpochs -= 1 # Test if validation loss exceeds halting threshold\n if t2vEpochs < 1:\n print(\"Validation loss too high; halting to prevent overfitting\")\n break\n confuseMtx = np.zeros((numClass,numClass),dtype=int) # Create empty confusion matrix\n model.eval()\n with torch.no_grad():\n permute = torch.randperm(nTest) # Shuffle test data\n testX = testX[permute,:,:,:]\n testY = testY[permute]\n for j in range(testBats): # Iterate over test batches\n batX = testX[j*batchSize:(j+1)*batchSize,:,:,:].to(dev)\n batY = testY[j*batchSize:(j+1)*batchSize].to(dev)\n yOut = model(batX) # Pass test batch through model\n pred = yOut.max(1,keepdim=True)[1] # Generate predictions by finding the max Y values\n for j in torch.cat((batY.view_as(pred), pred),dim=1).tolist(): # Glue together Actual and Predicted to\n confuseMtx[j[0],j[1]] += 1 # make (row, col) pairs, and increment confusion matrix\n correct = sum([confuseMtx[i,i] for i in range(numClass)]) # Sum over diagonal elements to count correct predictions\n train_run_errors.append(nTest-correct)", "_____no_output_____" ], [ "train_run_errors = np.array(train_run_errors)\ntrain_run_errors.mean()", "_____no_output_____" ], [ "train_run_errors.sort()\ntrain_run_errors[:-6].mean()", "_____no_output_____" ], [ "mp.hist(train_run_errors)", "_____no_output_____" ], [ "mp.boxplot(train_run_errors)", "_____no_output_____" ] ], [ [ "You're likely to see 99%+ accuracy. Not bad for a fairly minimal model that trains in just a couple minutes. Now look at the confusion matrix. Notice that some mistakes are more common than others - <b>does this type of confusion make sense to you?</b>\n\nBefore we get to the exercises, let's take a look at some of the images that confused the model. This cell can be rerun to produce more examples.\n\n### Code Block 12\n", "_____no_output_____" ] ], [ [ "def scaleBack(x): # Pass a tensor, return a numpy array from 0 to 1\n if(x.min() < x.max()): # Assuming the image isn't empty, rescale so its values run from 0 to 1\n x = (x - x.min())/(x.max() - x.min())\n return x[0].to(cpu).numpy() # Remove channel (grayscale anyway)\n\nmodel.eval()\nmp.subplots(3,3,figsize=(8,8))\nimagesLeft = 9\npermute = torch.randperm(nTest) # Shuffle test data\ntestX = testX[permute,:,:,:]\ntestY = testY[permute]\nfor j in range(testBats): # Iterate over test batches\n batX = testX[j*batchSize:(j+1)*batchSize,:,:,:].to(dev)\n batY = testY[j*batchSize:(j+1)*batchSize].to(dev)\n yOut = model(batX) # Pass test batch through model\n pred = yOut.max(1)[1].tolist() # Generate predictions by finding the max Y values\n for i, y in enumerate(batY.tolist()):\n if imagesLeft and y != pred[i]: # Compare the actual y value to the prediction\n imagesLeft -= 1\n mp.subplot(3,3,9-imagesLeft)\n mp.xlabel(classNames[pred[i]]) # Label image with what the model thinks it is\n mp.imshow(scaleBack(batX[i]),cmap='gray',vmin=0,vmax=1)\nmp.tight_layout()\nmp.show()\n \n ", "_____no_output_____" ], [ "pwd", "_____no_output_____" ], [ "ls", "_____no_output_____" ], [ "permute = torch.randperm(nTest, device='cuda')\nx = testX[permute,:,:,:]\ntorch.onnx.export(model, \n x, \n \"model_opti.onnx\",\n export_params=True, \n opset_version=10, \n do_constant_folding=True, \n input_names = ['input'], \n output_names = ['output'],\n dynamic_axes={'input' : {0 : 'batch_size'}, \n 'output' : {0 : 'batch_size'}})", "_____no_output_____" ], [ "# Input to the model\n\npermute = torch.randperm(nTest) # Shuffle test data\nx = testX[permute,:,:,:]\nmodel.to('cpu')\n# torch_out = model(x)\n\n# Export the model\ntorch.onnx.export(model, # model being run\n x, # model input (or a tuple for multiple inputs)\n \"MedNet.onnx\", # where to save the model (can be a file or file-like object)\n export_params=True, # store the trained parameter weights inside the model file\n opset_version=10, # the ONNX version to export the model to\n do_constant_folding=True, # whether to execute constant folding for optimization\n input_names = ['input'], # the model's input names\n output_names = ['output'], # the model's output names\n dynamic_axes={'input' : {0 : 'batch_size'}, # variable length axes\n 'output' : {0 : 'batch_size'}})", "_____no_output_____" ] ], [ [ "Some of these images are indeed confusing, even for a human observer. Yet other other ones are harder to fathom - why did a model with 99% accuracy misclassify what is so obviously a hand, for example? The field of <a href=\"https://medium.com/@jrzech/what-are-radiological-deep-learning-models-actually-learning-f97a546c5b98\">interpretability is beginning to explore these questions</a>.\n\n## Exercises\n\nIt may be useful to restart the kernel (under Kernel menu) to clear the memory between exercises, or even to copy the notebook (under File menu) and do each exercise in a clean copy. Because time may be limited, scan through the exercises and start with the ones that most appeal to you. Exercises 1, 2, and 3 are particularly recommended if you are new to deep learning.\n\n<ol>\n <li>Without resetting the kernel, increase <code>t2vRatio</code> in code block 10 and continue the training. Can you improve the final accuracy observed on the test dataset this way? If so, does it improve as much as the change in training loss would seem to indicate? What might this suggest about the relative value of architecting to training?</li><hr>\n <li>Reset the model by running code block 9, then modify the hyperparameters and retraing the model in code block 10. The most interesting ones are the learning rate (larger or smaller) and the batch size (smaller works well; when increasing the batch size, you will run out of memory somewhere in the low thousands). Note the effects on training. Can you make it converge faster than the default values?</li><hr>\n <li>Modify the architecture in code block 8 and note the effects on the training speed and final accuracy\n <ol>\n <li> Easy: Change the number of convolutions, the size of the convolutions, and the number of fully connected layers</li>\n <li> Medium: Add additional convolutional and/or fully connected layers. Use the existing code for reference.</li>\n <li> Hard: Add <a href=\"https://pytorch.org/docs/stable/_modules/torch/nn/modules/batchnorm.html#BatchNorm1d\">batchnorm</a>, <a href=\"https://pytorch.org/docs/stable/_modules/torch/nn/modules/pooling.html#MaxPool2d\">maxpool</a>, and/or <a href=\"https://pytorch.org/docs/stable/_modules/torch/nn/modules/dropout#Dropout\">dropout</a> layers.</li>\n </ol>\n </li><hr>\n <li>Unbalance the classes. This is a common problem in medical imaging, and can be done by adding a single line of code in code block 2: <code>imageFiles[5] = imageFiles[5][:-NNN]</code> where <code>NNN</code> is the number images from the final class to remove. You could also replace the 5 with 0 - 4, instead. Insert this line between <code>imageFiles = ...</code> and <code>numEach = ...</code> How small of a set can you have while still getting good results for this class in the confusion matrix? This exercise combines well with the next one.</li><hr>\n <li>Remove the weights for the loss function by adding <code>CEweights = torch.ones(numClass).to(dev)</code> after the line <code>opti = ...</code> in code block 10. What effect does this have in the confusion matrix when identifying the rarer image class? You could also implement custom weights by using <code>CEweights = torch.tensor([a,b,c,d,e,f]).to(dev)</code> where <code>a ... f</code> are floating point numbers. In this case, note the effects of having one or more relatively large weights.</li><hr>\n <li>Remove one or both of the modifications to the tensor from code block 4. Note the effects on the early training and final accuracy.</li><hr>\n <li><b>Final challenge:</b>By using experience gained from the previous exercises, you can adjust the architecture and training to make a more accurate final model. Can your improved model make fewer than 10 mistakes on the testing set?</li>\n</ol>\n\n", "_____no_output_____" ], [ "<a href=\"hints.txt\">Hints and partial solutions to the exercises</a>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
4aef40c5ec0f5f4f6d67007c73175f6252d7c42c
34,537
ipynb
Jupyter Notebook
python-sonic.ipynb
wallysalami/python-sonic
e76365d43021b0065b77686e0669909825a74df2
[ "MIT" ]
1
2021-07-23T05:58:40.000Z
2021-07-23T05:58:40.000Z
python-sonic.ipynb
wallysalami/python-sonic
e76365d43021b0065b77686e0669909825a74df2
[ "MIT" ]
null
null
null
python-sonic.ipynb
wallysalami/python-sonic
e76365d43021b0065b77686e0669909825a74df2
[ "MIT" ]
null
null
null
22.139103
781
0.499841
[ [ [ "# python-sonic - Programming Music with Python, Sonic Pi or Supercollider", "_____no_output_____" ], [ "Python-Sonic is a simple Python interface for Sonic Pi, which is a real great music software created by Sam Aaron (http://sonic-pi.net). \n\nAt the moment Python-Sonic works with Sonic Pi. It is planned, that it will work with Supercollider, too.\n\nIf you like it, use it. If you have some suggestions, tell me ([email protected]).", "_____no_output_____" ], [ "## Installation", "_____no_output_____" ], [ "* First you need Python 3 (https://www.python.org, ) - Python 3.5 should work, because it's the development environment\n* Then Sonic Pi (https://sonic-pi.net) - That makes the sound\n* Modul python-osc (https://pypi.python.org/pypi/python-osc) - Connection between Python and Sonic Pi Server\n* And this modul python-sonic - simply copy the source\n\nOr try", "_____no_output_____" ] ], [ [ "$ pip install python-sonic", "_____no_output_____" ] ], [ [ "That should work.", "_____no_output_____" ], [ "## Limitations", "_____no_output_____" ], [ "* You have to start _Sonic Pi_ first before you can use it with python-sonic\n* Only the notes from C2 to C6", "_____no_output_____" ], [ "## Changelog", "_____no_output_____" ], [ "|Version | |\n|--------------|------------------------------------------------------------------------------------------|\n| 0.2.0 | Some changes for Sonic Pi 2.11. Simpler multi-threading with decorator *@in_thread*. Messaging with *cue* and *sync*. |\n| 0.3.0 | OSC Communication | ", "_____no_output_____" ], [ "## Examples", "_____no_output_____" ], [ "Many of the examples are inspired from the help menu in *Sonic Pi*.", "_____no_output_____" ] ], [ [ "from psonic import *", "_____no_output_____" ] ], [ [ "The first sound", "_____no_output_____" ] ], [ [ "play(70) #play MIDI note 70", "_____no_output_____" ] ], [ [ "Some more notes", "_____no_output_____" ] ], [ [ "play(72)\nsleep(1)\nplay(75)\nsleep(1)\nplay(79) ", "_____no_output_____" ] ], [ [ "In more tratitional music notation", "_____no_output_____" ] ], [ [ "play(C5)\nsleep(0.5)\nplay(D5)\nsleep(0.5)\nplay(G5) ", "_____no_output_____" ] ], [ [ "Play sharp notes like *F#* or dimished ones like *Eb*", "_____no_output_____" ] ], [ [ "play(Fs5)\nsleep(0.5)\nplay(Eb5)", "_____no_output_____" ] ], [ [ "Play louder (parameter amp) or from a different direction (parameter pan)", "_____no_output_____" ] ], [ [ "play(72,amp=2)\nsleep(0.5)\nplay(74,pan=-1) #left", "_____no_output_____" ] ], [ [ "Different synthesizer sounds", "_____no_output_____" ] ], [ [ "use_synth(SAW)\nplay(38)\nsleep(0.25)\nplay(50)\nsleep(0.5)\nuse_synth(PROPHET)\nplay(57)\nsleep(0.25)", "_____no_output_____" ] ], [ [ "ADSR *(Attack, Decay, Sustain and Release)* Envelope", "_____no_output_____" ] ], [ [ "play (60, attack=0.5, decay=1, sustain_level=0.4, sustain=2, release=0.5) \nsleep(4)", "_____no_output_____" ] ], [ [ "Play some samples", "_____no_output_____" ] ], [ [ "sample(AMBI_LUNAR_LAND, amp=0.5)", "_____no_output_____" ], [ "sample(LOOP_AMEN,pan=-1)\nsleep(0.877)\nsample(LOOP_AMEN,pan=1)", "_____no_output_____" ], [ "sample(LOOP_AMEN,rate=0.5)", "_____no_output_____" ], [ "sample(LOOP_AMEN,rate=1.5)", "_____no_output_____" ], [ "sample(LOOP_AMEN,rate=-1)#back", "_____no_output_____" ], [ "sample(DRUM_CYMBAL_OPEN,attack=0.01,sustain=0.3,release=0.1)", "_____no_output_____" ], [ "sample(LOOP_AMEN,start=0.5,finish=0.8,rate=-0.2,attack=0.3,release=1)", "_____no_output_____" ] ], [ [ "Play some random notes", "_____no_output_____" ] ], [ [ "import random\n\nfor i in range(5):\n play(random.randrange(50, 100))\n sleep(0.5)", "_____no_output_____" ], [ "for i in range(3):\n play(random.choice([C5,E5,G5]))\n sleep(1)", "_____no_output_____" ] ], [ [ "Sample slicing", "_____no_output_____" ] ], [ [ "from psonic import *\n\nnumber_of_pieces = 8\n\nfor i in range(16):\n s = random.randrange(0,number_of_pieces)/number_of_pieces #sample starts at 0.0 and finishes at 1.0\n f = s + (1.0/number_of_pieces)\n sample(LOOP_AMEN,beat_stretch=2,start=s,finish=f)\n sleep(2.0/number_of_pieces)", "_____no_output_____" ] ], [ [ "An infinite loop and if", "_____no_output_____" ] ], [ [ "while True:\n if one_in(2):\n sample(DRUM_HEAVY_KICK)\n sleep(0.5)\n else:\n sample(DRUM_CYMBAL_CLOSED)\n sleep(0.25)", "_____no_output_____" ] ], [ [ "If you want to hear more than one sound at a time, use Threads.", "_____no_output_____" ] ], [ [ "import random\nfrom psonic import *\nfrom threading import Thread\n\ndef bass_sound():\n c = chord(E3, MAJOR7)\n while True:\n use_synth(PROPHET)\n play(random.choice(c), release=0.6)\n sleep(0.5)\n\ndef snare_sound():\n while True:\n sample(ELEC_SNARE)\n sleep(1)\n\nbass_thread = Thread(target=bass_sound)\nsnare_thread = Thread(target=snare_sound)\n\nbass_thread.start()\nsnare_thread.start()\n\nwhile True:\n pass", "_____no_output_____" ] ], [ [ "Every function *bass_sound* and *snare_sound* have its own thread. Your can hear them running.", "_____no_output_____" ] ], [ [ "from psonic import *\nfrom threading import Thread, Condition\nfrom random import choice\n\ndef random_riff(condition):\n use_synth(PROPHET)\n sc = scale(E3, MINOR)\n while True:\n s = random.choice([0.125,0.25,0.5])\n with condition:\n condition.wait() #Wait for message\n for i in range(8):\n r = random.choice([0.125, 0.25, 1, 2])\n n = random.choice(sc)\n co = random.randint(30,100)\n play(n, release = r, cutoff = co)\n sleep(s)\n\ndef drums(condition):\n while True:\n with condition:\n condition.notifyAll() #Message to threads\n for i in range(16):\n r = random.randrange(1,10)\n sample(DRUM_BASS_HARD, rate=r)\n sleep(0.125)\n\ncondition = Condition()\nrandom_riff_thread = Thread(name='consumer1', target=random_riff, args=(condition,))\ndrums_thread = Thread(name='producer', target=drums, args=(condition,))\n\nrandom_riff_thread.start()\ndrums_thread.start()\n\ninput(\"Press Enter to continue...\")", "Press Enter to continue...\n" ] ], [ [ "To synchronize the thread, so that they play a note at the same time, you can use *Condition*. One function sends a message with *condition.notifyAll* the other waits until the message comes *condition.wait*.", "_____no_output_____" ], [ "More simple with decorator __@in_thread__", "_____no_output_____" ] ], [ [ "from psonic import *\nfrom random import choice\n\ntick = Message()\n\n@in_thread\ndef random_riff():\n use_synth(PROPHET)\n sc = scale(E3, MINOR)\n while True:\n s = random.choice([0.125,0.25,0.5])\n tick.sync()\n for i in range(8):\n r = random.choice([0.125, 0.25, 1, 2])\n n = random.choice(sc)\n co = random.randint(30,100)\n play(n, release = r, cutoff = co)\n sleep(s)\n \n@in_thread\ndef drums():\n while True:\n tick.cue()\n for i in range(16):\n r = random.randrange(1,10)\n sample(DRUM_BASS_HARD, rate=r)\n sleep(0.125)\n\nrandom_riff()\ndrums()\n\ninput(\"Press Enter to continue...\")", "Press Enter to continue...\n" ], [ "from psonic import *\n\ntick = Message()\n\n@in_thread\ndef metronom():\n while True:\n tick.cue()\n sleep(1)\n \n@in_thread\ndef instrument():\n while True:\n tick.sync()\n sample(DRUM_HEAVY_KICK)\n\nmetronom()\ninstrument()\n\nwhile True:\n pass", "_____no_output_____" ] ], [ [ "Play a list of notes", "_____no_output_____" ] ], [ [ "from psonic import *\n\nplay ([64, 67, 71], amp = 0.3) \nsleep(1)\nplay ([E4, G4, B4])\nsleep(1)", "_____no_output_____" ] ], [ [ "Play chords", "_____no_output_____" ] ], [ [ "play(chord(E4, MINOR)) \nsleep(1)\nplay(chord(E4, MAJOR))\nsleep(1)\nplay(chord(E4, MINOR7))\nsleep(1)\nplay(chord(E4, DOM7))\nsleep(1)", "_____no_output_____" ] ], [ [ "Play arpeggios", "_____no_output_____" ] ], [ [ "play_pattern( chord(E4, 'm7')) \nplay_pattern_timed( chord(E4, 'm7'), 0.25) \nplay_pattern_timed(chord(E4, 'dim'), [0.25, 0.5]) ", "_____no_output_____" ] ], [ [ "Play scales", "_____no_output_____" ] ], [ [ "play_pattern_timed(scale(C3, MAJOR), 0.125, release = 0.1) \nplay_pattern_timed(scale(C3, MAJOR, num_octaves = 2), 0.125, release = 0.1) \nplay_pattern_timed(scale(C3, MAJOR_PENTATONIC, num_octaves = 2), 0.125, release = 0.1)", "_____no_output_____" ] ], [ [ "The function *scale* returns a list with all notes of a scale. So you can use list methodes or functions. For example to play arpeggios descending or shuffeld.", "_____no_output_____" ] ], [ [ "import random\nfrom psonic import *\n\ns = scale(C3, MAJOR)\ns", "_____no_output_____" ], [ "s.reverse()", "_____no_output_____" ], [ "\nplay_pattern_timed(s, 0.125, release = 0.1)\nrandom.shuffle(s)\nplay_pattern_timed(s, 0.125, release = 0.1)", "_____no_output_____" ] ], [ [ "### Live Loop", "_____no_output_____" ], [ "One of the best in SONIC PI is the _Live Loop_. While a loop is playing music you can change it and hear the change. Let's try it in Python, too.", "_____no_output_____" ] ], [ [ "from psonic import *\nfrom threading import Thread\n\ndef my_loop():\n play(60)\n sleep(1)\n\ndef looper():\n while True:\n my_loop()\n\nlooper_thread = Thread(name='looper', target=looper)\n\nlooper_thread.start()\n\ninput(\"Press Enter to continue...\")", "Press Enter to continue...Y\n" ] ], [ [ "Now change the function *my_loop* und you can hear it.", "_____no_output_____" ] ], [ [ "def my_loop():\n use_synth(TB303)\n play (60, release= 0.3)\n sleep (0.25)", "_____no_output_____" ], [ "def my_loop():\n use_synth(TB303)\n play (chord(E3, MINOR), release= 0.3)\n sleep(0.5)", "_____no_output_____" ], [ "def my_loop():\n use_synth(TB303)\n sample(DRUM_BASS_HARD, rate = random.uniform(0.5, 2))\n play(random.choice(chord(E3, MINOR)), release= 0.2, cutoff=random.randrange(60, 130))\n sleep(0.25)", "_____no_output_____" ] ], [ [ "To stop the sound you have to end the kernel. In IPython with Kernel --> Restart", "_____no_output_____" ], [ "Now with two live loops which are synch.", "_____no_output_____" ] ], [ [ "from psonic import *\nfrom threading import Thread, Condition\nfrom random import choice\n\ndef loop_foo():\n play (E4, release = 0.5)\n sleep (0.5)\n\n\ndef loop_bar():\n sample (DRUM_SNARE_SOFT)\n sleep (1)\n \n\ndef live_loop_1(condition):\n while True:\n with condition:\n condition.notifyAll() #Message to threads\n loop_foo()\n \ndef live_loop_2(condition):\n while True:\n with condition:\n condition.wait() #Wait for message\n loop_bar()\n\ncondition = Condition()\nlive_thread_1 = Thread(name='producer', target=live_loop_1, args=(condition,))\nlive_thread_2 = Thread(name='consumer1', target=live_loop_2, args=(condition,))\n\nlive_thread_1.start()\nlive_thread_2.start()\n\ninput(\"Press Enter to continue...\")", "Press Enter to continue...y\n" ], [ "def loop_foo():\n play (A4, release = 0.5)\n sleep (0.5)", "_____no_output_____" ], [ "def loop_bar():\n sample (DRUM_HEAVY_KICK)\n sleep (0.125)", "_____no_output_____" ] ], [ [ "If would be nice if we can stop the loop with a simple command. With stop event it works.", "_____no_output_____" ] ], [ [ "from psonic import *\nfrom threading import Thread, Condition, Event\n\ndef loop_foo():\n play (E4, release = 0.5)\n sleep (0.5)\n\n\ndef loop_bar():\n sample (DRUM_SNARE_SOFT)\n sleep (1)\n \n\ndef live_loop_1(condition,stop_event):\n while not stop_event.is_set():\n with condition:\n condition.notifyAll() #Message to threads\n loop_foo()\n \ndef live_loop_2(condition,stop_event):\n while not stop_event.is_set():\n with condition:\n condition.wait() #Wait for message\n loop_bar()\n\n\n\ncondition = Condition()\nstop_event = Event()\nlive_thread_1 = Thread(name='producer', target=live_loop_1, args=(condition,stop_event))\nlive_thread_2 = Thread(name='consumer1', target=live_loop_2, args=(condition,stop_event))\n\n\nlive_thread_1.start()\nlive_thread_2.start()\n\ninput(\"Press Enter to continue...\")", "Press Enter to continue...y\n" ], [ "stop_event.set()", "_____no_output_____" ] ], [ [ "More complex live loops", "_____no_output_____" ] ], [ [ "sc = Ring(scale(E3, MINOR_PENTATONIC))\n\ndef loop_foo():\n play (next(sc), release= 0.1)\n sleep (0.125)\n\nsc2 = Ring(scale(E3,MINOR_PENTATONIC,num_octaves=2))\n \ndef loop_bar():\n use_synth(DSAW)\n play (next(sc2), release= 0.25)\n sleep (0.25)", "_____no_output_____" ] ], [ [ "Now a simple structure with four live loops", "_____no_output_____" ] ], [ [ "import random\nfrom psonic import *\nfrom threading import Thread, Condition, Event\n\ndef live_1():\n pass\n\ndef live_2():\n pass\n \ndef live_3():\n pass\n\ndef live_4():\n pass\n\ndef live_loop_1(condition,stop_event):\n while not stop_event.is_set():\n with condition:\n condition.notifyAll() #Message to threads\n live_1()\n \ndef live_loop_2(condition,stop_event):\n while not stop_event.is_set():\n with condition:\n condition.wait() #Wait for message\n live_2()\n\ndef live_loop_3(condition,stop_event):\n while not stop_event.is_set():\n with condition:\n condition.wait() #Wait for message\n live_3()\n\ndef live_loop_4(condition,stop_event):\n while not stop_event.is_set():\n with condition:\n condition.wait() #Wait for message\n live_4()\n \ncondition = Condition()\nstop_event = Event()\nlive_thread_1 = Thread(name='producer', target=live_loop_1, args=(condition,stop_event))\nlive_thread_2 = Thread(name='consumer1', target=live_loop_2, args=(condition,stop_event))\nlive_thread_3 = Thread(name='consumer2', target=live_loop_3, args=(condition,stop_event))\nlive_thread_4 = Thread(name='consumer3', target=live_loop_3, args=(condition,stop_event))\n\nlive_thread_1.start()\nlive_thread_2.start()\nlive_thread_3.start()\nlive_thread_4.start()\n\ninput(\"Press Enter to continue...\")", "Press Enter to continue...y\n" ] ], [ [ "After starting the loops you can change them", "_____no_output_____" ] ], [ [ "def live_1():\n sample(BD_HAUS,amp=2)\n sleep(0.5)\n pass", "_____no_output_____" ], [ "def live_2():\n #sample(AMBI_CHOIR, rate=0.4)\n #sleep(1)\n pass", "_____no_output_____" ], [ "def live_3():\n use_synth(TB303)\n play(E2, release=4,cutoff=120,cutoff_attack=1)\n sleep(4)", "_____no_output_____" ], [ "def live_4():\n notes = scale(E3, MINOR_PENTATONIC, num_octaves=2)\n for i in range(8):\n play(random.choice(notes),release=0.1,amp=1.5)\n sleep(0.125)", "_____no_output_____" ] ], [ [ "And stop.", "_____no_output_____" ] ], [ [ "stop_event.set()", "_____no_output_____" ] ], [ [ "### Creating Sound", "_____no_output_____" ] ], [ [ "from psonic import *\n\nsynth(SINE, note=D4)\nsynth(SQUARE, note=D4)\nsynth(TRI, note=D4, amp=0.4)", "_____no_output_____" ], [ "detune = 0.7\nsynth(SQUARE, note = E4)\nsynth(SQUARE, note = E4+detune)", "_____no_output_____" ], [ "detune=0.1 # Amplitude shaping\nsynth(SQUARE, note = E2, release = 2)\nsynth(SQUARE, note = E2+detune, amp = 2, release = 2)\nsynth(GNOISE, release = 2, amp = 1, cutoff = 60)\nsynth(GNOISE, release = 0.5, amp = 1, cutoff = 100)\nsynth(NOISE, release = 0.2, amp = 1, cutoff = 90)", "_____no_output_____" ] ], [ [ "### Next Step", "_____no_output_____" ], [ "Using FX *Not implemented yet*", "_____no_output_____" ] ], [ [ "from psonic import *\n\nwith Fx(SLICER):\n synth(PROPHET,note=E2,release=8,cutoff=80)\n synth(PROPHET,note=E2+4,release=8,cutoff=80)", "_____no_output_____" ], [ "with Fx(SLICER, phase=0.125, probability=0.6,prob_pos=1):\n synth(TB303, note=E2, cutoff_attack=8, release=8)\n synth(TB303, note=E3, cutoff_attack=4, release=8)\n synth(TB303, note=E4, cutoff_attack=2, release=8)", "_____no_output_____" ] ], [ [ "## OSC Communication (Sonic Pi Ver. 3.x or better)", "_____no_output_____" ], [ "In Sonic Pi version 3 or better you can work with messages.", "_____no_output_____" ] ], [ [ "from psonic import *", "_____no_output_____" ] ], [ [ "First you need a programm in the Sonic Pi server that receives messages. You can write it in th GUI or send one with Python.", "_____no_output_____" ] ], [ [ "run(\"\"\"live_loop :foo do\n use_real_time\n a, b, c = sync \"/osc/trigger/prophet\"\n synth :prophet, note: a, cutoff: b, sustain: c\nend \"\"\")", "_____no_output_____" ] ], [ [ "Now send a message to Sonic Pi.", "_____no_output_____" ] ], [ [ "send_message('/trigger/prophet', 70, 100, 8)", "_____no_output_____" ], [ "stop()", "_____no_output_____" ] ], [ [ "## More Examples", "_____no_output_____" ] ], [ [ "from psonic import *", "_____no_output_____" ], [ "#Inspired by Steve Reich Clapping Music\n\nclapping = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0]\n\nfor i in range(13):\n for j in range(4):\n for k in range(12): \n if clapping[k] ==1 : sample(DRUM_SNARE_SOFT,pan=-0.5)\n if clapping[(i+k)%12] == 1: sample(DRUM_HEAVY_KICK,pan=0.5)\n sleep (0.25)", "_____no_output_____" ] ], [ [ "## Projects that use Python-Sonic", "_____no_output_____" ], [ "Raspberry Pi sonic-track.py a Sonic-pi Motion Track Demo https://github.com/pageauc/sonic-track", "_____no_output_____" ], [ "## Sources", "_____no_output_____" ], [ "Joe Armstrong: Connecting Erlang to the Sonic Pi http://joearms.github.io/2015/01/05/Connecting-Erlang-to-Sonic-Pi.html", "_____no_output_____" ], [ "Joe Armstrong: Controlling Sound with OSC Messages http://joearms.github.io/2016/01/29/Controlling-Sound-with-OSC-Messages.html", "_____no_output_____" ], [ "..", "_____no_output_____" ] ] ]
[ "markdown", "raw", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "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" ], [ "raw" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4aef57e26f74ce12805875bf4b737578981b844b
31,629
ipynb
Jupyter Notebook
Course File/Linear Regression Demo.ipynb
TerenceLiu98/Undergraduate-in-Statistics
e76efc789779ace123abcc2a0e94595168b444ac
[ "MIT" ]
15
2020-01-04T09:17:27.000Z
2022-03-30T16:52:44.000Z
Course File/Linear Regression Demo.ipynb
TerenceLiu98/Undergraduate-in-Statistics
e76efc789779ace123abcc2a0e94595168b444ac
[ "MIT" ]
1
2020-11-25T09:15:17.000Z
2020-11-25T09:15:17.000Z
Course File/Linear Regression Demo.ipynb
TerenceLiu98/Undergraduate-in-Statistics
e76efc789779ace123abcc2a0e94595168b444ac
[ "MIT" ]
7
2020-02-23T16:06:37.000Z
2020-11-22T07:23:12.000Z
128.052632
15,652
0.886813
[ [ [ "# Linear Regression demo\n\nCode including two way to do linear regression:\n\n- Gradient Descent\n- Normal Equation", "_____no_output_____" ], [ "## Gradient Descent", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport random\n%matplotlib inline", "_____no_output_____" ], [ "def cost_function(X, y, theta):\n h = np.dot(X, theta)\n difference = np.square(h - y)\n cost = np.sum(difference) / (2 * len(y))\n return cost\n\ndef gradient_descent(X, y, theta, alpha):\n h = np.dot(X, theta)\n difference = h - y\n theta = theta - (alpha / len(y)) * (np.dot(X.T, difference));\n return theta", "_____no_output_____" ], [ "num_iters = 1000\nalpha = 0.01 # Learning rate", "_____no_output_____" ], [ "data = pd.read_csv('/data_set/ex1data1.txt', header=None)\n\nX = np.array(data[0])\ny = np.transpose([np.array(data[1])])\nsns.scatterplot(X.T, y.T[0]) # Show data distribution\n\nX = np.column_stack((np.ones(len(X)), X))", "_____no_output_____" ], [ "# Randomly select theta for hypothesis\ntheta = np.array([[random.uniform(y.min(), y.max()/2)], [random.uniform(-1, 1)]])\n# theta = np.array([[0],[0]])", "_____no_output_____" ], [ "print(\"Inital θ_0: {:f} θ_1: {:f}\".format(theta[0][0], theta[1][0]))\ncost_array = []\nfor _ in range(num_iters):\n theta = gradient_descent(X, y, theta, alpha)\n cost_array.append(cost_function(X, y, theta))\nprint(\"After {:d} iterations, the cost is {:f} and the hypothesis is h(θ)={:.4f}+{:.4f}X\".format(num_iters, cost_function(X, y, theta), theta[0][0], theta[1][0]))", "Inital θ_0: 9.783382 θ_1: -0.858830\nAfter 1000 iterations, the cost is 4.943083 and the hypothesis is h(θ)=-1.6331+0.9657X\n" ], [ "# Plot cost change\ng = sns.lineplot(np.arange(num_iters), cost_array)\nplt.title('Gradient Descent')\nplt.xlabel('Iteration')\nplt.ylabel('Cost')", "_____no_output_____" ] ], [ [ "## Normal Equation\n\n> Please make sure that your matrix X is a non-singular matrix before you run this code", "_____no_output_____" ] ], [ [ "data = pd.read_csv('ex1data1.txt', header=None)\n\nX = np.array(data[0])\n\nne_X = np.column_stack((np.ones(len(X)), X))\nne_y = np.transpose([np.array(data[1])])", "_____no_output_____" ], [ "theta = np.dot(np.dot(np.linalg.inv(np.dot(ne_X.T, ne_X)), ne_X.T), y)", "_____no_output_____" ], [ "print(\"The cost is {:f} and the hypothesis is h(θ)={:.4f}+{:.4f}X\".format(cost_function(ne_X, ne_y, theta), theta[0][0], theta[1][0]))", "The cost is 4.476971 and the hypothesis is h(θ)=-3.8958+1.1930X\n" ] ], [ [ "## Credit\n\nData `ex1data1.txt` is from Andrew Ng's Machine Learning Course", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
4aef5b1b39b4081caefbf476c26bae4af8236a03
8,205
ipynb
Jupyter Notebook
Image/image_displacement.ipynb
mllzl/earthengine-py-notebooks
cade6a81dd4dbbfb1b9b37aaf6955de42226cfc5
[ "MIT" ]
1
2020-03-26T04:21:15.000Z
2020-03-26T04:21:15.000Z
Image/image_displacement.ipynb
mllzl/earthengine-py-notebooks
cade6a81dd4dbbfb1b9b37aaf6955de42226cfc5
[ "MIT" ]
null
null
null
Image/image_displacement.ipynb
mllzl/earthengine-py-notebooks
cade6a81dd4dbbfb1b9b37aaf6955de42226cfc5
[ "MIT" ]
null
null
null
45.331492
1,031
0.590859
[ [ [ "<table class=\"ee-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/image_displacement.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n <td><a target=\"_blank\" href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Image/image_displacement.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n <td><a target=\"_blank\" href=\"https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Image/image_displacement.ipynb\"><img width=58px src=\"https://mybinder.org/static/images/logo_social.png\" />Run in binder</a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Image/image_displacement.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n</table>", "_____no_output_____" ], [ "## Install Earth Engine API and geemap\nInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\nThe following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n\n**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).", "_____no_output_____" ] ], [ [ "# Installs geemap package\nimport subprocess\n\ntry:\n import geemap\nexcept ImportError:\n print('geemap package not installed. Installing ...')\n subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n\n# Checks whether this notebook is running on Google Colab\ntry:\n import google.colab\n import geemap.eefolium as emap\nexcept:\n import geemap as emap\n\n# Authenticates and initializes Earth Engine\nimport ee\n\ntry:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize() ", "_____no_output_____" ] ], [ [ "## Create an interactive map \nThe default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. ", "_____no_output_____" ] ], [ [ "Map = emap.Map(center=[40,-100], zoom=4)\nMap.add_basemap('ROADMAP') # Add Google Map\nMap", "_____no_output_____" ] ], [ [ "## Add Earth Engine Python script ", "_____no_output_____" ] ], [ [ "# Add Earth Engine dataset\nimport math\n\n# Load the two images to be registered.\nimage1 = ee.Image('SKYSAT/GEN-A/PUBLIC/ORTHO/MULTISPECTRAL/s01_20150502T082736Z')\nimage2 = ee.Image('SKYSAT/GEN-A/PUBLIC/ORTHO/MULTISPECTRAL/s01_20150305T081019Z')\n\n# Use bicubic resampling during registration.\nimage1Orig = image1.resample('bicubic')\nimage2Orig = image2.resample('bicubic')\n\n# Choose to register using only the 'R' bAnd.\nimage1RedBAnd = image1Orig.select('R')\nimage2RedBAnd = image2Orig.select('R')\n\n# Determine the displacement by matching only the 'R' bAnds.\ndisplacement = image2RedBAnd.displacement(**{\n 'referenceImage': image1RedBAnd,\n 'maxOffset': 50.0,\n 'patchWidth': 100.0\n})\n\n# Compute image offset And direction.\noffset = displacement.select('dx').hypot(displacement.select('dy'))\nangle = displacement.select('dx').atan2(displacement.select('dy'))\n\n# Display offset distance And angle.\nMap.addLayer(offset, {'min':0, 'max': 20}, 'offset')\nMap.addLayer(angle, {'min': -math.pi, 'max': math.pi}, 'angle')\nMap.setCenter(37.44,0.58, 15)\n\n\n# Use the computed displacement to register all Original bAnds.\nregistered = image2Orig.displace(displacement)\n\n# Show the results of co-registering the images.\nvisParams = {'bands': ['R', 'G', 'B'], 'max': 4000}\nMap.addLayer(image1Orig, visParams, 'Reference')\nMap.addLayer(image2Orig, visParams, 'BefOre Registration')\nMap.addLayer(registered, visParams, 'After Registration')\n\n\nalsoRegistered = image2Orig.register(**{\n 'referenceImage': image1Orig,\n 'maxOffset': 50.0,\n 'patchWidth': 100.0\n})\nMap.addLayer(alsoRegistered, visParams, 'Also Registered')\n\n", "_____no_output_____" ] ], [ [ "## Display Earth Engine data layers ", "_____no_output_____" ] ], [ [ "Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\nMap", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aef6ac96bd647f753b63750cb5ff545baa45bfb
37,408
ipynb
Jupyter Notebook
Foundations_of_Private_Computation/Split_Learning/Simplet_SL_duet/DO_SNN_VDT_exercises.ipynb
gonzalo-munillag/Private_AI_OpenMined
c23da9cc1c914d10646a0c0bc1a2497fe2cbaaca
[ "MIT" ]
5
2021-01-06T16:49:22.000Z
2021-02-19T05:34:27.000Z
Foundations_of_Private_Computation/Split_Learning/Simplet_SL_duet/DO_SNN_VDT_exercises.ipynb
gonzalo-munillag/Private_AI_OpenMined
c23da9cc1c914d10646a0c0bc1a2497fe2cbaaca
[ "MIT" ]
null
null
null
Foundations_of_Private_Computation/Split_Learning/Simplet_SL_duet/DO_SNN_VDT_exercises.ipynb
gonzalo-munillag/Private_AI_OpenMined
c23da9cc1c914d10646a0c0bc1a2497fe2cbaaca
[ "MIT" ]
null
null
null
147.857708
22,856
0.843643
[ [ [ "import syft as sy\n# We run things locally, good for our own experiments\nduet = sy.duet(loopback=True)", "_____no_output_____" ], [ "import torch\n\ndata = torch.tensor([[1.,0.],[1.,1.],[0.,1.],[0.,0.]])\ndata.send(duet, tags=[\"dataset\"], description=\"simple binary dataset\", searchable=True)", "`searchable` is deprecated please use `pointable` in future" ], [ "duet.requests.add_handler(action=\"accept\")", "_____no_output_____" ], [ "duet.store.pandas", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4aef70af5f284509f2dc7bb8c9a1d595c98eeb10
49,335
ipynb
Jupyter Notebook
nbs/17b-loss-function-cross-entropy.ipynb
gnoparus/bualabs
8a0fe910f2acf349a720137e1858edfcd5e92de7
[ "MIT" ]
7
2019-12-12T22:59:28.000Z
2022-03-25T09:49:36.000Z
nbs/17b-loss-function-cross-entropy.ipynb
gnoparus/bualabs
8a0fe910f2acf349a720137e1858edfcd5e92de7
[ "MIT" ]
1
2020-06-24T04:40:13.000Z
2020-06-24T04:40:13.000Z
nbs/17b-loss-function-cross-entropy.ipynb
gnoparus/bualabs
8a0fe910f2acf349a720137e1858edfcd5e92de7
[ "MIT" ]
29
2020-01-17T19:33:25.000Z
2022-03-22T04:52:32.000Z
43.543689
20,122
0.641208
[ [ [ "[Loss Function](https://www.bualabs.com/archives/2673/what-is-loss-function-cost-function-error-function-loss-function-how-cost-function-work-machine-learning-ep-1/) หรือ Cost Function คือ การคำนวน Error ว่า yhat ที่โมเดลทำนายออกมา ต่างจาก y ของจริง อยู่เท่าไร แล้วหาค่าเฉลี่ย เพื่อที่จะนำมาหา Gradient ของ Loss ขึ้นกับ Weight ต่าง ๆ ด้วย Backpropagation แล้วใช้อัลกอริทึม [Gradient Descent](https://www.bualabs.com/archives/631/what-is-gradient-descent-in-deep-learning-what-is-stochastic-gradient-descent-sgd-optimization-ep-1/) ทำให้ Loss น้อยลง ในการเทรนรอบถัดไป\n\nในเคสนี้เราจะพูดถึง Loss Function สำหรับงาน Classification (Discrete ค่าไม่ต่อเนื่อง) ที่เป็นที่นิยมมากที่สุด ได้แก่ Cross Entropy Loss\n\n* yhat เป็น Probability ที่ออกมาจากโมเดลที่ Layer สุดท้ายเป็น [Softmax Function](https://www.bualabs.com/archives/1819/what-is-softmax-function-how-to-use-softmax-function-benefit-of-softmax/)\n* y เป็นข้อมูลที่อยู่ในรูปแบบ [One Hot Encoding](https://www.bualabs.com/archives/1902/what-is-one-hot-encoding-benefit-one-hot-encoding-why-one-hot-encoding-in-machine-learning/)", "_____no_output_____" ], [ "# 0. Import", "_____no_output_____" ] ], [ [ "import torch\nfrom torch import tensor\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "# 1. Data", "_____no_output_____" ], [ "เราจะสร้างข้อมูลตัวอย่างขึ้นมา Dog = 0, Cat 1, Rat = 2", "_____no_output_____" ], [ "## y", "_____no_output_____" ], [ "สมมติค่า y จากข้อมูลตัวอย่าง ที่เราต้องการจริง ๆ เป็นดังนี้", "_____no_output_____" ] ], [ [ "y = tensor([0, 1, 2, 0, 0, 1, 0, 2, 2, 1])\ny", "_____no_output_____" ], [ "n, c = len(y), y.max()+1", "_____no_output_____" ], [ "y_onehot = torch.zeros(n, c)\ny_onehot[torch.arange(n), y] = 1\ny_onehot", "_____no_output_____" ] ], [ [ "## yhat", "_____no_output_____" ], [ "สมมติว่า โมเดลเราทำนายออกมาได้ nn", "_____no_output_____" ] ], [ [ "yhat = tensor([[3., 2., 1.],\n [5., 6., 2.],\n [0., 0., 5.],\n [2., 3., 1.],\n [5., 4., 3.],\n [1., 0., 3.],\n [5., 3., 2.],\n [2., 2., 4.],\n [8., 5., 3.],\n [3., 4., 0.]])", "_____no_output_____" ] ], [ [ "เราจะใช้ [Softmax Function จาก ep ที่แล้ว](https://www.bualabs.com/archives/1819/what-is-softmax-function-how-to-use-softmax-function-benefit-of-softmax/) แล้วเติม log เอาไว้สำหรับใช้ในขั้นตอนถัดไป", "_____no_output_____" ], [ "$$\\hbox{softmax(x)}_{i} = \\frac{e^{x_{i}}}{\\sum_{0 \\leq j \\leq n-1} e^{x_{j}}}$$ ", "_____no_output_____" ] ], [ [ "def log_softmax(z):\n z = z - z.max(-1, keepdim=True)[0]\n exp_z = torch.exp(z)\n sum_exp_z = torch.sum(exp_z, -1, keepdim=True)\n return (exp_z / sum_exp_z).log()", "_____no_output_____" ] ], [ [ "yhat กลายเป็น Probability ของ 3 Category", "_____no_output_____" ] ], [ [ "log_softmax(yhat)", "_____no_output_____" ] ], [ [ "## argmax เปรียบเทียบ y และ yhat", "_____no_output_____" ], [ "argmax ใช้หาตำแหน่งที่ มีค่ามากที่สุด ในที่นี้ เราสนใจค่ามากที่สุดใน มิติที่ 1", "_____no_output_____" ] ], [ [ "yhat.argmax(1)", "_____no_output_____" ], [ "y", "_____no_output_____" ] ], [ [ "ตรงกัน 7 อัน", "_____no_output_____" ] ], [ [ "(yhat.argmax(1) == y).sum()", "_____no_output_____" ] ], [ [ "# 2. Cross Entropy Loss", "_____no_output_____" ], [ "Cross Entropy Loss (Logistic Regression) หรือ Log Loss คือ การคำนวน Error ว่า yhat ต่างจาก y อยู่เท่าไร ด้วยการนำ Probability มาคำนวน หมายถึง ทายถูก แต่ไม่มั่นใจก็จะ Loss มาก หรือ ยิ่งทายผิด แต่มั่นใจมาก ก็จะ Loss มาก โดยคำนวนทั้ง Batch แล้วหาค่าเฉลี่ย\n\n* p(x) มีค่าระหว่าง 0 ถึง 1 (ทำให้ผ่าน log แล้วติดลบ เมื่อเจอกับเครื่องหมายลบด้านหน้า จะกลายเป็นบวก)\n* Cross Entropy Loss มีค่าระหว่าง 0 ถึง Infinity (ถ้าเป็น 0 คือไม่ Error เลย)", "_____no_output_____" ], [ "# 2.1 สูตร Cross Entropy Loss", "_____no_output_____" ], [ "เรียกว่า Negative Log Likelihood", "_____no_output_____" ], [ "$$ NLL = -\\sum x\\, \\log p(x) $$", "_____no_output_____" ], [ "เนื่องจาก ค่า $x$ อยู่ในรูป One Hot Encoding เราสามารถเขียนใหม่ได้เป็น $-\\log(p_{i})$ โดย i เป็น Index ของ y ที่เราต้องการ", "_____no_output_____" ], [ "## 2.2 โค้ด Negative Log Likelihood", "_____no_output_____" ] ], [ [ "# log_probs = log of probability, target = target\ndef nll(log_probs, target): \n return -(log_probs[torch.arange(log_probs.size()[0]), target]).mean()", "_____no_output_____" ] ], [ [ "## 2.3 การใช้งาน Negative Log Likelihood", "_____no_output_____" ] ], [ [ "loss = nll(log_softmax(yhat), y)\nloss", "_____no_output_____" ] ], [ [ "## 2.4 Optimize", "_____no_output_____" ], [ "เนื่องจาก", "_____no_output_____" ], [ "$$\\log \\left ( \\frac{a}{b} \\right ) = \\log(a) - \\log(b)$$ ", "_____no_output_____" ], [ "ทำให้เราแยก เศษและส่วน ออกเป็น 2 ก่อนลบกัน \n\nและถ้า x ใหญ่เกินไป เมื่อนำมา exp จะทำให้ nan ได้ จากสูตรด้านล่าง ", "_____no_output_____" ], [ "$$\\log \\left ( \\sum_{j=1}^{n} e^{x_{j}} \\right ) = \\log \\left ( e^{a} \\sum_{j=1}^{n} e^{x_{j}-a} \\right ) = a + \\log \\left ( \\sum_{j=1}^{n} e^{x_{j}-a} \\right )$$", "_____no_output_____" ], [ "a คือ max(x) เราสามารถ exp(x-a) ให้ x เป็นค่าติดลบให้หมด เมื่อ exp จะได้ไม่เกิน 1 แล้วค่อยไปบวกก a กลับทีหลังได้", "_____no_output_____" ], [ "จาก 2 สูตรด้านบน เราสามารถ Optimize โค้ด ได้ดังนี้", "_____no_output_____" ] ], [ [ "def log_softmax2(z): \n m = z.max(-1, keepdim=True)[0]\n return z - ((z-m).exp().sum(-1, keepdim=True).log()+m)", "_____no_output_____" ] ], [ [ "หรือ", "_____no_output_____" ] ], [ [ "def log_softmax3(z): \n return z - (z).logsumexp(-1, keepdim=True)", "_____no_output_____" ] ], [ [ "### เปรียบเทียบผลลัพธ์กับ PyTorch", "_____no_output_____" ] ], [ [ "import torch.nn.functional as F", "_____no_output_____" ], [ "F.cross_entropy(yhat, y)", "_____no_output_____" ], [ "nll(log_softmax(yhat), y)", "_____no_output_____" ], [ "nll(log_softmax2(yhat), y)", "_____no_output_____" ], [ "nll(log_softmax3(yhat), y)", "_____no_output_____" ] ], [ [ "ผลลัพธ์ถูกต้อง ตรงกับ PyTorch F.cross_entropy", "_____no_output_____" ], [ "## 2.5 พล็อตกราฟ", "_____no_output_____" ], [ "เราจะสมมติว่า Dog = 0, Cat = 1 และในข้อมูลตัวอย่างมีแต่ Dog (0) อย่างเดียว เราจะลองดูว่าพล็อตกราฟไล่ตั้งแต่ ความน่าจะเป็น 0-100%\n\nเราจะสร้างข้อมูลตัวอย่างขึ้นมา ให้ y เป็น 0 จำนวน 100 ตัว แทนรูปภาพ Dog 100 รูป เราจะได้เอาไว้พล็อตกราฟ", "_____no_output_____" ] ], [ [ "y = torch.zeros(100)\ny[:10]", "_____no_output_____" ] ], [ [ "yhat คือ Output ของโมเดลว่า ความน่าจะเป็นรูป Dog (Column 0) และความน่าจะเป็นรูป Cat (Column 1) เราจะไล่ข้อมูลตั้งแต่ (หมา 0% แมว 100%) ไปยัง (หมา 100% แมว 0%)", "_____no_output_____" ] ], [ [ "yhat = torch.zeros(100, 2)\nyhat[range(0, 100), 0] = torch.arange(0., 1., 0.01)\nyhat[:, 1] = 1-yhat[:, 0]\nyhat[:10]", "_____no_output_____" ] ], [ [ "คำนวนค่าความน่าจะเป็น ของทั้ง 2 Class เอาไว้พล็อตกราฟ", "_____no_output_____" ] ], [ [ "classes = torch.tensor([0., 1.])\nyhat_classes = yhat @ classes.t()\nyhat_classes[:10]", "_____no_output_____" ] ], [ [ "Log ค่า Probability (ของจริงจะมาจาก Softmax ตามตัวอย่างด้านบน) เตรียมไว้เข้าสูตร", "_____no_output_____" ] ], [ [ "log_probs = yhat.log()\nlog_probs[:10]", "_____no_output_____" ] ], [ [ "Negative Log Likelihood", "_____no_output_____" ] ], [ [ "loss = -(log_probs[torch.arange(log_probs.size()[0]), y.long()])\nloss[:10]", "_____no_output_____" ] ], [ [ "### พล็อตกราฟ y, yhat, loss และ log loss", "_____no_output_____" ], [ "* ข้อมูลตัวอย่าง y ที่สมมติว่าเท่ากับ 0 อย่างเดียว (เส้นสีแดง) เทียบกับ yhat ที่ทำนายไล่ตั้งแต่ 1 ไปถึง 0 (ทายผิดไล่ไปถึงทายถูก เส้นสีเขียว)\n* สังเกต Loss สีส้ม เริ่มจากซ้ายสุด Ground Truth เท่ากับ 0 (เส้นสีแดง) แต่โมเดลทายผิด ทายว่าเป็น 1 (เส้นสีเขียว) ด้วยความมั่นใจ 100% ทำให้ Loss พุ่งขึ้นถึง Infinity \n* เลื่อนมาตรงกลาง Loss จะลดลงอย่างรวดเร็ว เมื่อโมเดลทายผิด แต่ไม่ได้มั่นใจเต็มร้อย \n* ด้านขวา Loss ลดลงเรื่อย ๆ จนเป็น 0 เมื่อโมเดลทายถูก ว่าเป็น 0 ด้วยความมั่นใจ 100%\n* Log of Loss คือเปลี่ยน Loss ที่อยู่ช่วง Infinity ถึง 0 เป็น Log Scale จะได้ช่วง Infinity ถึง -Infinity จะได้ Balance ดูง่ายขึ้น\n", "_____no_output_____" ] ], [ [ "fig,ax = plt.subplots(figsize=(9, 9))\nax.scatter(yhat[:,0].numpy(), loss.log(), label=\"Log of Loss\")\nax.scatter(yhat[:,0].numpy(), loss, label=\"Loss\")\nax.plot(yhat[:,0].numpy(), yhat_classes.numpy(), label=\"yhat\", color='green')\nax.plot(yhat[:,0].numpy(), y.numpy(), label=\"y\", color='red')\nax.grid(True)\nax.legend(loc='upper right')", "_____no_output_____" ] ], [ [ "# 3. Loss Function อื่น ๆ", "_____no_output_____" ], [ "เราจะเป็นที่ต้องเข้าใจความเป็นมา และกลไกการทำงานภายใน ของ Loss Function เนื่องจากเมื่อเราต้องการออกแบบโมเดล ในการแก้ปัญหาที่ซับซ้อนมากขึ้น เราต้องออกแบบ Loss Function ให้เข้ากับงานนั้นด้วย เช่น อาจจะเอาหลาย ๆ Loss Function เช่น [Regression Loss](https://www.bualabs.com/archives/1928/what-is-mean-absolute-error-mae-mean-squared-error-mse-root-mean-squared-error-rmse-loss-function-ep-2/) มาผสมกัน แล้ว Weight น้ำหนัก รวมเป็น Loss ที่เราต้องการ เป็นต้น", "_____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", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4aef80cf158d232a0d0ec274f95a71c2766e8f6f
123,374
ipynb
Jupyter Notebook
tutorials/notebook/cx_site_chart_examples/circular_6.ipynb
docinfosci/canvasxpress-python
532a981b04d0f50bbde1852c695117a6220f4589
[ "MIT" ]
4
2021-03-18T17:23:40.000Z
2022-02-01T19:07:01.000Z
tutorials/notebook/cx_site_chart_examples/circular_6.ipynb
docinfosci/canvasxpress-python
532a981b04d0f50bbde1852c695117a6220f4589
[ "MIT" ]
8
2021-04-30T20:46:57.000Z
2022-03-10T07:25:31.000Z
tutorials/notebook/cx_site_chart_examples/circular_6.ipynb
docinfosci/canvasxpress-python
532a981b04d0f50bbde1852c695117a6220f4589
[ "MIT" ]
1
2022-02-03T00:35:14.000Z
2022-02-03T00:35:14.000Z
123,374
123,374
0.162263
[ [ [ "# Example: CanvasXpress circular Chart No. 6\n\nThis example page demonstrates how to, using the Python package, create a chart that matches the CanvasXpress online example located at:\n\nhttps://www.canvasxpress.org/examples/circular-6.html\n\nThis example is generated using the reproducible JSON obtained from the above page and the `canvasxpress.util.generator.generate_canvasxpress_code_from_json_file()` function.\n\nEverything required for the chart to render is included in the code below. Simply run the code block.", "_____no_output_____" ] ], [ [ "from canvasxpress.canvas import CanvasXpress \nfrom canvasxpress.js.collection import CXEvents \nfrom canvasxpress.render.jupyter import CXNoteBook \n\ncx = CanvasXpress(\n render_to=\"circular6\",\n data={\n \"z\": {\n \"chr\": [\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 1,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 2,\n 3,\n 3,\n 3,\n 3,\n 3,\n 3,\n 3,\n 3,\n 3,\n 3,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 4,\n 5,\n 5,\n 5,\n 5,\n 5,\n 5,\n 5,\n 5,\n 5,\n 5,\n 6,\n 6,\n 6,\n 6,\n 6,\n 6,\n 6,\n 6,\n 6,\n 7,\n 7,\n 7,\n 7,\n 7,\n 7,\n 7,\n 7,\n 8,\n 8,\n 8,\n 8,\n 8,\n 8,\n 8,\n 8,\n 9,\n 9,\n 9,\n 9,\n 9,\n 9,\n 9,\n 9,\n 10,\n 10,\n 10,\n 10,\n 10,\n 10,\n 10,\n 11,\n 11,\n 11,\n 11,\n 11,\n 11,\n 11,\n 12,\n 12,\n 12,\n 12,\n 12,\n 12,\n 12,\n 13,\n 13,\n 13,\n 13,\n 13,\n 13,\n 14,\n 14,\n 14,\n 14,\n 14,\n 14,\n 15,\n 15,\n 15,\n 15,\n 15,\n 15,\n 16,\n 16,\n 16,\n 16,\n 16,\n 17,\n 17,\n 17,\n 17,\n 18,\n 18,\n 18,\n 18,\n 19,\n 19,\n 19,\n 19,\n 20,\n 20,\n 20,\n 20,\n 21,\n 21,\n 21,\n 22,\n 22,\n 22,\n \"X\",\n \"X\",\n \"X\",\n \"X\",\n \"X\",\n \"X\",\n \"X\",\n \"X\",\n \"Y\",\n \"Y\",\n \"Y\",\n \"X\",\n 3,\n 19,\n 5,\n 11,\n 10,\n 15,\n 18,\n 11,\n 13,\n 14,\n 21,\n 1,\n 7,\n 14,\n \"Y\",\n 21,\n 2,\n 18,\n 1,\n 7,\n 9,\n 7,\n 19,\n 19,\n 20,\n 20,\n 9,\n \"X\",\n 16,\n 8,\n 20,\n \"X\",\n 18\n ],\n \"pos\": [\n 176158308,\n 195792629,\n 229516707,\n 127588847,\n 79643728,\n 185593801,\n 9679485,\n 244523632,\n 236753568,\n 128133434,\n 228644565,\n 150003054,\n 219011541,\n 168916847,\n 26949439,\n 102746811,\n 2474221,\n 209897353,\n 113021141,\n 77762431,\n 163020942,\n 171034774,\n 213334477,\n 97455775,\n 83291531,\n 143519956,\n 122953780,\n 134434993,\n 6501153,\n 36509633,\n 134712403,\n 16094381,\n 159112661,\n 16092021,\n 29530674,\n 98680615,\n 19640420,\n 108401923,\n 143243174,\n 16342895,\n 42326293,\n 115086153,\n 86673182,\n 138017594,\n 40287060,\n 133573077,\n 138457582,\n 17843222,\n 54643446,\n 31433785,\n 74774102,\n 178335068,\n 56846964,\n 539920,\n 95028169,\n 121007542,\n 131105053,\n 79720263,\n 48227800,\n 142747889,\n 62543189,\n 50598801,\n 33328141,\n 158733438,\n 47107967,\n 5246518,\n 131713113,\n 12326167,\n 58372056,\n 28321194,\n 108652542,\n 103359699,\n 103536939,\n 56208609,\n 87012547,\n 3341929,\n 124836752,\n 59833292,\n 39064309,\n 31063538,\n 67409926,\n 10777547,\n 48520782,\n 18875793,\n 81484304,\n 35095469,\n 120807273,\n 36875340,\n 126128712,\n 100677585,\n 118570992,\n 9612077,\n 77867215,\n 19151335,\n 53602699,\n 49087920,\n 38708284,\n 113120818,\n 101439886,\n 75343477,\n 26249259,\n 54093637,\n 20596380,\n 98938748,\n 40533585,\n 89574094,\n 80301557,\n 56696139,\n 106845694,\n 10555451,\n 101114606,\n 50732192,\n 17458821,\n 9173140,\n 86898750,\n 76472186,\n 16266789,\n 93249681,\n 87911171,\n 9404454,\n 56147990,\n 54904212,\n 87210495,\n 20386568,\n 32880981,\n 14002843,\n 12161519,\n 39664472,\n 73880383,\n 47714897,\n 868308,\n 66004051,\n 24127310,\n 54211025,\n 15902150,\n 8721825,\n 46962668,\n 39093389,\n 55603291,\n 41233282,\n 63103970,\n 10443615,\n 6248945,\n 24491648,\n 19429871,\n 4170936,\n 40286870,\n 54989240,\n 39471767,\n 44811148,\n 28873711,\n 7738820,\n 20461957,\n 23030024,\n 7678949,\n 113205707,\n 9117671,\n 55230156,\n 73702110,\n 105064343,\n 7484814,\n 6345698,\n 45891043,\n 14020510,\n 2971362,\n 29256349,\n 146673737,\n 141355615,\n 31567310,\n 3395353,\n 2464888,\n 68581686,\n 60314299,\n 58307384,\n 26528612,\n 38283186,\n 43483316,\n 41830860,\n 160212793,\n 83692467,\n 39167742,\n 8309133,\n 26927848,\n 197477698,\n 65796042,\n 145369367,\n 91838386,\n 59033170,\n 31843957,\n 33440512,\n 47490053,\n 49915055,\n 1878719,\n 93047574,\n 145870982,\n 75626142,\n 35819134,\n 60862499,\n 18121170,\n 49128537\n ],\n \"Annt1\": [\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\"\n ],\n \"Annt2\": [\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\"\n ],\n \"Annt3\": [\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:1\"\n ],\n \"Annt4\": [\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:5\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:5\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:5\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:4\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:3\",\n \"Desc:1\",\n \"Desc:1\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:2\",\n \"Desc:1\",\n \"Desc:5\",\n \"Desc:3\",\n \"Desc:4\",\n \"Desc:4\",\n \"Desc:5\",\n \"Desc:1\",\n \"Desc:2\",\n \"Desc:2\",\n \"Desc:3\",\n \"Desc:5\",\n \"Desc:3\",\n \"Desc:2\",\n \"Desc:2\"\n ]\n },\n \"x\": {\n \"Factor1\": [\n \"Lev:2\",\n \"Lev:1\",\n \"Lev:1\",\n \"Lev:1\",\n \"Lev:2\",\n \"Lev:1\",\n \"Lev:1\",\n \"Lev:1\",\n \"Lev:2\",\n \"Lev:1\"\n ],\n \"Factor2\": [\n \"Lev:1\",\n \"Lev:2\",\n \"Lev:2\",\n \"Lev:1\",\n \"Lev:1\",\n \"Lev:3\",\n \"Lev:3\",\n \"Lev:1\",\n \"Lev:1\",\n \"Lev:2\"\n ],\n \"Factor3\": [\n \"Lev:4\",\n \"Lev:1\",\n \"Lev:2\",\n \"Lev:1\",\n \"Lev:4\",\n \"Lev:4\",\n \"Lev:1\",\n \"Lev:4\",\n \"Lev:2\",\n \"Lev:2\"\n ],\n \"Factor4\": [\n \"Lev:1\",\n \"Lev:4\",\n \"Lev:2\",\n \"Lev:4\",\n \"Lev:5\",\n \"Lev:2\",\n \"Lev:2\",\n \"Lev:1\",\n \"Lev:4\",\n \"Lev:3\"\n ]\n },\n \"y\": {\n \"vars\": [\n \"V1\",\n \"V2\",\n \"V3\",\n \"V4\",\n \"V5\",\n \"V6\",\n \"V7\",\n \"V8\",\n \"V9\",\n \"V10\",\n \"V11\",\n \"V12\",\n \"V13\",\n \"V14\",\n \"V15\",\n \"V16\",\n \"V17\",\n \"V18\",\n \"V19\",\n \"V20\",\n \"V21\",\n \"V22\",\n \"V23\",\n \"V24\",\n \"V25\",\n \"V26\",\n \"V27\",\n \"V28\",\n \"V29\",\n \"V30\",\n \"V31\",\n \"V32\",\n \"V33\",\n \"V34\",\n \"V35\",\n \"V36\",\n \"V37\",\n \"V38\",\n \"V39\",\n \"V40\",\n \"V41\",\n \"V42\",\n \"V43\",\n \"V44\",\n \"V45\",\n \"V46\",\n \"V47\",\n \"V48\",\n \"V49\",\n \"V50\",\n \"V51\",\n \"V52\",\n \"V53\",\n \"V54\",\n \"V55\",\n \"V56\",\n \"V57\",\n \"V58\",\n \"V59\",\n \"V60\",\n \"V61\",\n \"V62\",\n \"V63\",\n \"V64\",\n \"V65\",\n \"V66\",\n \"V67\",\n \"V68\",\n \"V69\",\n \"V70\",\n \"V71\",\n \"V72\",\n \"V73\",\n \"V74\",\n \"V75\",\n \"V76\",\n \"V77\",\n \"V78\",\n \"V79\",\n \"V80\",\n \"V81\",\n \"V82\",\n \"V83\",\n \"V84\",\n \"V85\",\n \"V86\",\n \"V87\",\n \"V88\",\n \"V89\",\n \"V90\",\n \"V91\",\n \"V92\",\n \"V93\",\n \"V94\",\n \"V95\",\n \"V96\",\n \"V97\",\n \"V98\",\n \"V99\",\n \"V100\",\n \"V101\",\n \"V102\",\n \"V103\",\n \"V104\",\n \"V105\",\n \"V106\",\n \"V107\",\n \"V108\",\n \"V109\",\n \"V110\",\n \"V111\",\n \"V112\",\n \"V113\",\n \"V114\",\n \"V115\",\n \"V116\",\n \"V117\",\n \"V118\",\n \"V119\",\n \"V120\",\n \"V121\",\n \"V122\",\n \"V123\",\n \"V124\",\n \"V125\",\n \"V126\",\n \"V127\",\n \"V128\",\n \"V129\",\n \"V130\",\n \"V131\",\n \"V132\",\n \"V133\",\n \"V134\",\n \"V135\",\n \"V136\",\n \"V137\",\n \"V138\",\n \"V139\",\n \"V140\",\n \"V141\",\n \"V142\",\n \"V143\",\n \"V144\",\n \"V145\",\n \"V146\",\n \"V147\",\n \"V148\",\n \"V149\",\n \"V150\",\n \"V151\",\n \"V152\",\n \"V153\",\n \"V154\",\n \"V155\",\n \"V156\",\n \"V157\",\n \"V158\",\n \"V159\",\n \"V160\",\n \"V161\",\n \"V162\",\n \"V163\",\n \"V164\",\n \"V165\",\n \"V166\",\n \"V167\",\n \"V168\",\n \"V169\",\n \"V170\",\n \"V171\",\n \"V172\",\n \"V173\",\n \"V174\",\n \"V175\",\n \"V176\",\n \"V177\",\n \"V178\",\n \"V179\",\n \"V180\",\n \"V181\",\n \"V182\",\n \"V183\",\n \"V184\",\n \"V185\",\n \"V186\",\n \"V187\",\n \"V188\",\n \"V189\",\n \"V190\",\n \"V191\",\n \"V192\",\n \"V193\",\n \"V194\",\n \"V195\",\n \"V196\",\n \"V197\",\n \"V198\",\n \"V199\",\n \"V200\"\n ],\n \"smps\": [\n \"S1\",\n \"S2\",\n \"S3\",\n \"S4\",\n \"S5\",\n \"S6\",\n \"S7\",\n \"S8\",\n \"S9\",\n \"S10\"\n ],\n \"data\": [\n [\n 52.79,\n 24.71,\n 14.35,\n 22.23,\n 42.42,\n 12.38,\n 19.18,\n 19.6,\n 51.81,\n 20.2\n ],\n [\n 53.39,\n 28.1,\n 8.02,\n 24.12,\n 21.36,\n 28.89,\n 16.29,\n 27.44,\n 38.8,\n 18.3\n ],\n [\n 31.11,\n 13.84,\n 16.32,\n 7.62,\n 29.04,\n 2.66,\n 11.83,\n 8.6,\n 52.39,\n 8.55\n ],\n [\n 42.48,\n 6.54,\n 14.22,\n 6.19,\n 51.77,\n 6.26,\n 6.4,\n 4.32,\n 47.32,\n 3.13\n ],\n [\n 21.44,\n 8.39,\n 17.61,\n 1.59,\n 42.14,\n 6.91,\n 14.92,\n 5.04,\n 30.25,\n 20.55\n ],\n [\n 47.6,\n 25.45,\n 7.53,\n 6.22,\n 40.27,\n 10.96,\n 28.39,\n 19.22,\n 37.05,\n 11.5\n ],\n [\n 22.9,\n 23.06,\n 3.38,\n 25.36,\n 31.83,\n 1.15,\n 25.07,\n 10.77,\n 23.24,\n 24.39\n ],\n [\n 35.39,\n 3.88,\n 19.33,\n 20.16,\n 42.14,\n 21.13,\n 25.74,\n 24.42,\n 25.39,\n 2.43\n ],\n [\n 52.37,\n 6.73,\n 13.85,\n 11.98,\n 21.89,\n 4.12,\n 24.02,\n 19,\n 25.97,\n 23.68\n ],\n [\n 52.58,\n 23.67,\n 7.66,\n 21.44,\n 47.43,\n 4.87,\n 22.18,\n 20.36,\n 52.05,\n 2.86\n ],\n [\n 31.75,\n 16.88,\n 21.22,\n 1.41,\n 45.79,\n 26.28,\n 17.74,\n 9.64,\n 22.42,\n 9.45\n ],\n [\n 24.37,\n 4.16,\n 24.06,\n 23.13,\n 41.6,\n 27.75,\n 13.84,\n 7.34,\n 45.81,\n 16.44\n ],\n [\n 46.31,\n 15.54,\n 6.64,\n 22.44,\n 52.65,\n 14.93,\n 5.5,\n 24.09,\n 22.05,\n 9.59\n ],\n [\n 35.7,\n 19.79,\n 2.5,\n 26.23,\n 34.06,\n 23.88,\n 16.45,\n 7.96,\n 24.18,\n 3.22\n ],\n [\n 35.47,\n 5.46,\n 8.68,\n 2.91,\n 22.42,\n 6.71,\n 1.83,\n 22.89,\n 28.1,\n 14.21\n ],\n [\n 52.58,\n 27.38,\n 27.51,\n 14.4,\n 47.27,\n 15.92,\n 13.59,\n 26.11,\n 33,\n 23.06\n ],\n [\n 38.08,\n 15.55,\n 28.65,\n 28.74,\n 47.06,\n 16.09,\n 20.78,\n 26.79,\n 43.36,\n 22.28\n ],\n [\n 53.38,\n 7.1,\n 26.57,\n 11.79,\n 40.73,\n 26.29,\n 26.21,\n 5.92,\n 53.16,\n 6.62\n ],\n [\n 29.9,\n 13.26,\n 7.23,\n 5.38,\n 53.67,\n 28.59,\n 25.78,\n 21.36,\n 52.78,\n 13.46\n ],\n [\n 52.6,\n 19.51,\n 14.72,\n 15.76,\n 52.13,\n 11.8,\n 1.05,\n 20.58,\n 29.03,\n 17.05\n ],\n [\n 32.48,\n 24.14,\n 21.4,\n 11.61,\n 32.99,\n 7.31,\n 10.01,\n 27.88,\n 43.2,\n 1.14\n ],\n [\n 30.62,\n 26.5,\n 26.38,\n 24.57,\n 21.88,\n 20.69,\n 13.17,\n 13.96,\n 41.89,\n 28.89\n ],\n [\n 43.32,\n 18.91,\n 11.68,\n 22.23,\n 26.85,\n 11.23,\n 25.33,\n 2.87,\n 46.3,\n 9.78\n ],\n [\n 22.35,\n 22.74,\n 27.62,\n 12.85,\n 36.96,\n 1.77,\n 26.33,\n 2.53,\n 27.88,\n 26.44\n ],\n [\n 52.04,\n 3.77,\n 14.24,\n 14.65,\n 28.39,\n 14.11,\n 25.47,\n 21.81,\n 42.57,\n 18.74\n ],\n [\n 47.25,\n 13.18,\n 26.74,\n 17.95,\n 53.01,\n 26.92,\n 1.61,\n 4.51,\n 30.27,\n 7.34\n ],\n [\n 25.46,\n 16.02,\n 25.93,\n 11.33,\n 53.77,\n 17.54,\n 1.39,\n 24.03,\n 23.83,\n 13.23\n ],\n [\n 22.81,\n 10.33,\n 24.77,\n 26.01,\n 28.95,\n 23.99,\n 12.01,\n 17.69,\n 35.64,\n 12.08\n ],\n [\n 49.27,\n 26.71,\n 6.64,\n 14.77,\n 51.25,\n 28.48,\n 1.55,\n 10.43,\n 31.01,\n 17.18\n ],\n [\n 42.41,\n 10.58,\n 15.27,\n 14.52,\n 40.17,\n 22.83,\n 12.05,\n 1.56,\n 22.99,\n 27.03\n ],\n [\n 45.11,\n 18.03,\n 2.03,\n 22.29,\n 47.98,\n 18.79,\n 1.27,\n 3.41,\n 30.1,\n 9.83\n ],\n [\n 52.17,\n 16.1,\n 19.34,\n 5.16,\n 42.09,\n 20.79,\n 20.52,\n 1.7,\n 29.79,\n 28.78\n ],\n [\n 42.62,\n 6.73,\n 9.88,\n 20.52,\n 32.33,\n 23.13,\n 27.96,\n 18.97,\n 47.05,\n 26.31\n ],\n [\n 34.15,\n 27.79,\n 1.84,\n 8.72,\n 23.68,\n 13.74,\n 8.7,\n 13.29,\n 45.97,\n 10.63\n ],\n [\n 53.41,\n 8.13,\n 27.7,\n 1.16,\n 33.81,\n 17.28,\n 17.65,\n 3.52,\n 26.6,\n 1.81\n ],\n [\n 46.08,\n 16.98,\n 2.9,\n 6.39,\n 48.8,\n 14.27,\n 1.16,\n 19.95,\n 26.05,\n 16.55\n ],\n [\n 47.68,\n 20.6,\n 26.02,\n 2.24,\n 30.25,\n 5.2,\n 27.69,\n 27.32,\n 25.77,\n 1.83\n ],\n [\n 43.9,\n 17.09,\n 3.2,\n 27.51,\n 21.37,\n 25.93,\n 26.64,\n 20.24,\n 33.7,\n 17.47\n ],\n [\n 48.23,\n 13.08,\n 5.52,\n 7.6,\n 49.08,\n 28.7,\n 8.77,\n 13.11,\n 32.41,\n 2.72\n ],\n [\n 33.18,\n 9.4,\n 10.42,\n 21.24,\n 44.66,\n 25.64,\n 12.85,\n 7.75,\n 21.55,\n 28.84\n ],\n [\n 42.38,\n 23.57,\n 21.18,\n 25.08,\n 43.04,\n 11.07,\n 14.21,\n 1.42,\n 32.97,\n 21.7\n ],\n [\n 30.55,\n 3.97,\n 4.38,\n 28.78,\n 39.17,\n 12.88,\n 4.53,\n 18.51,\n 48.28,\n 7.76\n ],\n [\n 41.59,\n 14.67,\n 21.58,\n 15.97,\n 32.76,\n 6.12,\n 26.85,\n 15.79,\n 41.7,\n 7.31\n ],\n [\n 46,\n 15.58,\n 27.91,\n 1.88,\n 31.55,\n 28.62,\n 14.72,\n 15.09,\n 52.69,\n 8.05\n ],\n [\n 52.78,\n 22.19,\n 15.16,\n 1.41,\n 45.68,\n 9.69,\n 12.1,\n 7.3,\n 21.85,\n 3.27\n ],\n [\n 47.42,\n 27.04,\n 15.18,\n 26.67,\n 23.72,\n 24.41,\n 28.73,\n 22.77,\n 22.13,\n 8.03\n ],\n [\n 25.76,\n 1.63,\n 11.07,\n 19.24,\n 29.78,\n 9.65,\n 21.95,\n 13.94,\n 48.78,\n 7.68\n ],\n [\n 48.6,\n 27.58,\n 20.39,\n 19.72,\n 35.11,\n 28.69,\n 23.7,\n 1.95,\n 33.49,\n 27.96\n ],\n [\n 41.85,\n 15.79,\n 7.88,\n 16.83,\n 52.66,\n 16.14,\n 5.35,\n 18.82,\n 27.15,\n 5.45\n ],\n [\n 45.62,\n 21.21,\n 11.66,\n 5.16,\n 22.28,\n 11.81,\n 16.28,\n 15.32,\n 33.85,\n 22.43\n ],\n [\n 46.29,\n 25.75,\n 19.88,\n 20.76,\n 22.11,\n 21.46,\n 7.11,\n 26.73,\n 44.82,\n 3.51\n ],\n [\n 24.36,\n 8.99,\n 9.74,\n 27.87,\n 32.85,\n 27.9,\n 18.32,\n 14.07,\n 37.25,\n 17.46\n ],\n [\n 36.43,\n 20.25,\n 1.86,\n 10.53,\n 21.23,\n 4.09,\n 19.13,\n 18.67,\n 36.86,\n 19.04\n ],\n [\n 25.61,\n 11.06,\n 9.71,\n 17.51,\n 32.42,\n 5.87,\n 28.71,\n 7.12,\n 44.66,\n 3.21\n ],\n [\n 28.35,\n 16.72,\n 6.6,\n 21.55,\n 39.72,\n 5.16,\n 9.52,\n 6.6,\n 41.89,\n 4.98\n ],\n [\n 31.16,\n 24.99,\n 5.19,\n 8.29,\n 32.85,\n 5.62,\n 21.49,\n 16.94,\n 48.36,\n 26.06\n ],\n [\n 28.1,\n 14.02,\n 18.97,\n 24.52,\n 48.45,\n 18.57,\n 11.57,\n 26.8,\n 23.16,\n 7.75\n ],\n [\n 34.22,\n 18.8,\n 4.05,\n 5.68,\n 22.38,\n 6.06,\n 19,\n 9.99,\n 38.28,\n 12.62\n ],\n [\n 50,\n 5.17,\n 13.58,\n 27.32,\n 48.93,\n 12.52,\n 12.53,\n 3.9,\n 27.92,\n 13.57\n ],\n [\n 51.8,\n 14.39,\n 27.67,\n 17.76,\n 49.12,\n 18.48,\n 5.37,\n 21.47,\n 26.36,\n 5.42\n ],\n [\n 21.06,\n 27.43,\n 4.66,\n 4.66,\n 43.69,\n 23.29,\n 10.97,\n 24.48,\n 39.68,\n 24.51\n ],\n [\n 38.43,\n 26.14,\n 9.59,\n 21.03,\n 21.09,\n 20.03,\n 19.43,\n 26.53,\n 35.09,\n 19.22\n ],\n [\n 52.81,\n 25.31,\n 18.03,\n 8.39,\n 47.76,\n 23.69,\n 26.31,\n 26.5,\n 37.19,\n 25.91\n ],\n [\n 25.14,\n 7.08,\n 17.93,\n 13.86,\n 21.06,\n 23.32,\n 27.77,\n 1.05,\n 51.25,\n 19.22\n ],\n [\n 48.36,\n 8.08,\n 18.26,\n 16.15,\n 28.64,\n 13.73,\n 13.87,\n 16.39,\n 42.95,\n 1.75\n ],\n [\n 37.43,\n 11.5,\n 23.1,\n 10.51,\n 48.75,\n 5.03,\n 28.38,\n 18.39,\n 27.03,\n 17.35\n ],\n [\n 22.67,\n 19.74,\n 20.84,\n 15.24,\n 40.62,\n 18.13,\n 5.79,\n 8.72,\n 45.6,\n 27.13\n ],\n [\n 39.33,\n 19.08,\n 25.75,\n 14.02,\n 38.13,\n 13.18,\n 25.47,\n 2.38,\n 33.72,\n 3.71\n ],\n [\n 32.02,\n 13.58,\n 25.5,\n 3.88,\n 22.28,\n 5.56,\n 8.13,\n 18.99,\n 32.71,\n 4.26\n ],\n [\n 26.62,\n 3.28,\n 25.59,\n 18.33,\n 27.65,\n 15.9,\n 20.44,\n 28.41,\n 46.91,\n 6.13\n ],\n [\n 51.91,\n 26.1,\n 2.84,\n 28.74,\n 31.25,\n 23.36,\n 12.53,\n 15.14,\n 51.49,\n 10.04\n ],\n [\n 48.71,\n 21.97,\n 15.89,\n 28.65,\n 49.3,\n 21.22,\n 3.76,\n 20.03,\n 42.07,\n 18.88\n ],\n [\n 23.13,\n 2.08,\n 10.52,\n 21.58,\n 48.12,\n 17.61,\n 4.93,\n 15.71,\n 26.94,\n 28.32\n ],\n [\n 25.16,\n 27.29,\n 27.77,\n 21.57,\n 53.14,\n 19.33,\n 6.46,\n 15.55,\n 38.21,\n 22.02\n ],\n [\n 27.01,\n 18.7,\n 18.35,\n 25.85,\n 34.58,\n 16.19,\n 13.52,\n 21.68,\n 33.73,\n 7.28\n ],\n [\n 40.99,\n 15.97,\n 19.43,\n 22.44,\n 46.51,\n 27.81,\n 11.62,\n 2.95,\n 44.24,\n 27.83\n ],\n [\n 27.63,\n 20.4,\n 23.63,\n 18.05,\n 39.83,\n 27.58,\n 26.87,\n 8.77,\n 34.69,\n 3.6\n ],\n [\n 27.43,\n 2.53,\n 1.74,\n 26.48,\n 22.16,\n 14.38,\n 7.54,\n 11.17,\n 43.99,\n 15.86\n ],\n [\n 37.72,\n 24.1,\n 13.48,\n 1.62,\n 31.68,\n 24.96,\n 23.16,\n 12.29,\n 25.18,\n 16.59\n ],\n [\n 46.47,\n 23.57,\n 6.71,\n 11.72,\n 53.77,\n 7.37,\n 1.13,\n 20.3,\n 22.93,\n 6.53\n ],\n [\n 49.41,\n 28.3,\n 16.59,\n 15.22,\n 27.74,\n 6.38,\n 3.01,\n 20.2,\n 38.05,\n 2.12\n ],\n [\n 52.69,\n 14.29,\n 4.48,\n 5.06,\n 38.24,\n 20.31,\n 13.41,\n 10.79,\n 35.45,\n 9.82\n ],\n [\n 48.98,\n 21.97,\n 22.63,\n 3.21,\n 46.84,\n 28.64,\n 5.27,\n 15.32,\n 23.21,\n 17.51\n ],\n [\n 25.76,\n 3.48,\n 16.51,\n 15.99,\n 40.09,\n 17.21,\n 22.1,\n 24.21,\n 22.85,\n 26.39\n ],\n [\n 29.57,\n 22.65,\n 14.76,\n 4.48,\n 47.37,\n 12.4,\n 21.85,\n 12.72,\n 25.18,\n 11.03\n ],\n [\n 22.01,\n 6.11,\n 22.28,\n 15.93,\n 46.41,\n 6.62,\n 21.88,\n 8.61,\n 23.99,\n 15.67\n ],\n [\n 23.29,\n 24.59,\n 2.47,\n 21.52,\n 23.92,\n 11.13,\n 14.74,\n 17.02,\n 33.5,\n 22.62\n ],\n [\n 30.62,\n 18.08,\n 2.31,\n 19.1,\n 45.56,\n 27.75,\n 3.24,\n 9.69,\n 42.93,\n 4.19\n ],\n [\n 24.13,\n 1.35,\n 11.88,\n 25.51,\n 48.22,\n 1.37,\n 28.94,\n 5.28,\n 38.25,\n 15.38\n ],\n [\n 49.63,\n 5.33,\n 18.6,\n 20.61,\n 22.34,\n 11.06,\n 2.22,\n 16.54,\n 53.47,\n 8.68\n ],\n [\n 42.2,\n 19.69,\n 4.01,\n 26.61,\n 34.98,\n 13.31,\n 4.99,\n 26.61,\n 47,\n 22.4\n ],\n [\n 48.24,\n 17.15,\n 28.34,\n 10.62,\n 30.8,\n 15.28,\n 21.08,\n 5.84,\n 49.72,\n 13.17\n ],\n [\n 51.71,\n 3.67,\n 25.57,\n 13.12,\n 38.31,\n 8.22,\n 22.73,\n 13.4,\n 47.61,\n 1.33\n ],\n [\n 41.29,\n 6.55,\n 21.66,\n 3.17,\n 36.62,\n 8.21,\n 19.98,\n 23.25,\n 50.76,\n 6.85\n ],\n [\n 40.45,\n 27.37,\n 2.53,\n 13.66,\n 28.2,\n 14.32,\n 5.53,\n 14.67,\n 45.83,\n 15.08\n ],\n [\n 42.23,\n 15.24,\n 10.62,\n 15.37,\n 33.92,\n 1.51,\n 8.22,\n 23.53,\n 49.44,\n 23.54\n ],\n [\n 30.88,\n 19.84,\n 8.42,\n 12.73,\n 24.76,\n 15.13,\n 23.73,\n 25.79,\n 48.92,\n 25.5\n ],\n [\n 52.89,\n 23.31,\n 3.3,\n 21.71,\n 29.33,\n 10.32,\n 6.42,\n 23.83,\n 25.11,\n 19.65\n ],\n [\n 41.38,\n 7.44,\n 4.04,\n 17.54,\n 22.94,\n 1.33,\n 8.61,\n 15.45,\n 49.55,\n 15.54\n ],\n [\n 36.81,\n 21.34,\n 3.01,\n 7.09,\n 40.02,\n 20.06,\n 21.23,\n 20.02,\n 31.02,\n 17.84\n ],\n [\n 52.29,\n 5.38,\n 9.99,\n 27.28,\n 29.16,\n 1.64,\n 7.27,\n 7.86,\n 23.61,\n 19.17\n ],\n [\n 48.66,\n 10.33,\n 15.84,\n 12.52,\n 31.17,\n 15.37,\n 9.89,\n 16.43,\n 25.28,\n 27.01\n ],\n [\n 22.81,\n 20.15,\n 13.89,\n 6.64,\n 30.87,\n 28.08,\n 11.89,\n 7.24,\n 44.44,\n 4.9\n ],\n [\n 34.43,\n 7.32,\n 7.79,\n 12.2,\n 33.55,\n 16.55,\n 13.96,\n 9.8,\n 51.31,\n 3.19\n ],\n [\n 39.06,\n 17.33,\n 9.56,\n 20.28,\n 40.86,\n 17.91,\n 22.71,\n 13.64,\n 31.37,\n 6.01\n ],\n [\n 45.03,\n 5.67,\n 22.87,\n 12.66,\n 29.29,\n 4.14,\n 7.56,\n 16.01,\n 36.65,\n 12.56\n ],\n [\n 51.77,\n 4.1,\n 26,\n 3.96,\n 32.23,\n 5.26,\n 11.71,\n 17.96,\n 39.59,\n 20.08\n ],\n [\n 49.81,\n 12.7,\n 1.62,\n 11.22,\n 52.71,\n 22.16,\n 13.26,\n 15,\n 42.64,\n 9.27\n ],\n [\n 43.15,\n 20.12,\n 28.12,\n 8.84,\n 26.77,\n 20.31,\n 9.84,\n 15.72,\n 24.4,\n 27.82\n ],\n [\n 41.2,\n 20.39,\n 7.76,\n 8.74,\n 39.75,\n 20.92,\n 15.3,\n 10.16,\n 50.94,\n 15.1\n ],\n [\n 43.31,\n 21.41,\n 24.5,\n 14.25,\n 42.58,\n 10.01,\n 9.79,\n 11.6,\n 24.88,\n 27.58\n ],\n [\n 38.03,\n 9.96,\n 18.37,\n 3.06,\n 28.42,\n 2.99,\n 1.76,\n 4.72,\n 39.11,\n 21.21\n ],\n [\n 38.78,\n 11.89,\n 15.05,\n 21.22,\n 38.79,\n 15.56,\n 7.43,\n 16.35,\n 24.81,\n 13.12\n ],\n [\n 29.68,\n 28.51,\n 27.6,\n 27.92,\n 44.52,\n 18.12,\n 25.71,\n 16.97,\n 36.77,\n 10.44\n ],\n [\n 52.9,\n 19.04,\n 28.71,\n 10.37,\n 27.04,\n 18.85,\n 28.06,\n 18.31,\n 31.31,\n 27.66\n ],\n [\n 50.77,\n 21.27,\n 28.56,\n 5.12,\n 35.39,\n 8.15,\n 11.73,\n 8.75,\n 43.82,\n 26.65\n ],\n [\n 28.09,\n 21.14,\n 17.46,\n 27.36,\n 51.84,\n 26.42,\n 13.57,\n 18.96,\n 33.6,\n 19.64\n ],\n [\n 29.81,\n 7.84,\n 27.68,\n 22.15,\n 34.79,\n 18.01,\n 26.49,\n 15.11,\n 44.04,\n 4\n ],\n [\n 43.29,\n 24.01,\n 13.9,\n 27.21,\n 42.29,\n 17.94,\n 16.38,\n 25.6,\n 49.04,\n 14.41\n ],\n [\n 31.46,\n 9.34,\n 8.84,\n 19.22,\n 52.91,\n 13.62,\n 6.53,\n 26.15,\n 24.57,\n 13.06\n ],\n [\n 42.03,\n 21.07,\n 27.35,\n 24.6,\n 45.33,\n 24.58,\n 5.59,\n 9.23,\n 51.35,\n 1.02\n ],\n [\n 41.69,\n 22.28,\n 12.03,\n 7.11,\n 32.98,\n 5.01,\n 15.36,\n 3.16,\n 22.33,\n 3.7\n ],\n [\n 47.62,\n 11.61,\n 28.85,\n 10.52,\n 36.34,\n 19.35,\n 22.81,\n 15.83,\n 42.17,\n 25.63\n ],\n [\n 30.29,\n 9.92,\n 2.32,\n 4.99,\n 34.83,\n 23.06,\n 17.59,\n 10.86,\n 45.17,\n 16.3\n ],\n [\n 49.02,\n 26.6,\n 15.79,\n 20.37,\n 52.66,\n 28.84,\n 19.57,\n 24.66,\n 42.02,\n 20.58\n ],\n [\n 37.26,\n 10.71,\n 22.96,\n 5.43,\n 29.59,\n 14.85,\n 16.53,\n 24,\n 52.94,\n 26.8\n ],\n [\n 33.25,\n 2.41,\n 17.29,\n 27.27,\n 32.39,\n 28.05,\n 24.16,\n 20.49,\n 28.8,\n 11.27\n ],\n [\n 39.38,\n 6.45,\n 20.91,\n 9.61,\n 45.47,\n 18.77,\n 9.13,\n 13.85,\n 31.49,\n 21.25\n ],\n [\n 51.05,\n 15.04,\n 20.68,\n 8.44,\n 48.1,\n 19.95,\n 19.61,\n 28.13,\n 35.33,\n 17.97\n ],\n [\n 29.34,\n 16.32,\n 6.32,\n 2.27,\n 53.69,\n 14.11,\n 18.18,\n 14.14,\n 35.59,\n 6.2\n ],\n [\n 36.38,\n 12.11,\n 8.04,\n 28.07,\n 24.38,\n 23.47,\n 22.72,\n 27.67,\n 49.74,\n 5.53\n ],\n [\n 29.6,\n 10.14,\n 24.5,\n 8.97,\n 48.86,\n 20.44,\n 1.83,\n 3.96,\n 21.76,\n 9.1\n ],\n [\n 52.36,\n 21.32,\n 23.69,\n 20.39,\n 46.22,\n 24.85,\n 21.1,\n 24.07,\n 30.68,\n 11.32\n ],\n [\n 22.61,\n 13.82,\n 28.27,\n 3.5,\n 32.82,\n 12.1,\n 28.91,\n 10.63,\n 52.58,\n 25.55\n ],\n [\n 25.18,\n 27.88,\n 26.97,\n 24.2,\n 53.01,\n 23.7,\n 22.25,\n 10.12,\n 29.71,\n 5.07\n ],\n [\n 23.97,\n 27.01,\n 9.14,\n 11.7,\n 23.19,\n 12.18,\n 20.88,\n 25.48,\n 38.24,\n 20.58\n ],\n [\n 49.63,\n 13.67,\n 1.34,\n 17.56,\n 50.43,\n 7.5,\n 4.14,\n 12.52,\n 48.7,\n 22.08\n ],\n [\n 51.08,\n 10.04,\n 18.23,\n 14.37,\n 44.22,\n 1.55,\n 7.89,\n 23.5,\n 24.09,\n 8.86\n ],\n [\n 32.88,\n 4.6,\n 4.6,\n 3.62,\n 48.38,\n 2.13,\n 28.81,\n 7.23,\n 25.57,\n 8.73\n ],\n [\n 32.27,\n 17.45,\n 28.26,\n 1.66,\n 39.41,\n 28.36,\n 2.61,\n 23.5,\n 26.42,\n 26.57\n ],\n [\n 45.43,\n 1.89,\n 19.53,\n 14.48,\n 31.9,\n 20.54,\n 1.01,\n 23.49,\n 53.54,\n 11.51\n ],\n [\n 53.68,\n 22.09,\n 15.49,\n 6.19,\n 40.87,\n 25.97,\n 25.33,\n 1.17,\n 31.83,\n 23.54\n ],\n [\n 36.4,\n 3.93,\n 11.53,\n 12.81,\n 28.34,\n 2.62,\n 4.94,\n 21.85,\n 31.44,\n 15.91\n ],\n [\n 38.8,\n 19.03,\n 24.23,\n 9.15,\n 30.01,\n 18.03,\n 19.11,\n 5.56,\n 45.77,\n 28.97\n ],\n [\n 50.44,\n 24.58,\n 14.49,\n 11.83,\n 53.21,\n 13.68,\n 9.97,\n 19.76,\n 35.37,\n 5.13\n ],\n [\n 31.63,\n 16.26,\n 23.55,\n 20.4,\n 27.16,\n 1.02,\n 21.76,\n 12.51,\n 23.73,\n 10.42\n ],\n [\n 38.24,\n 7.25,\n 5.81,\n 19.28,\n 30.62,\n 16.17,\n 19.11,\n 3.93,\n 49.73,\n 19.5\n ],\n [\n 46.77,\n 12.63,\n 25.33,\n 27.77,\n 23.56,\n 28.56,\n 18.59,\n 10.73,\n 25.1,\n 2.19\n ],\n [\n 49.79,\n 2.32,\n 1.86,\n 26.89,\n 41.33,\n 17.48,\n 14.26,\n 15.09,\n 51.34,\n 19.84\n ],\n [\n 26.78,\n 2.77,\n 19.56,\n 18.37,\n 45.22,\n 16.96,\n 3.91,\n 25.44,\n 35.53,\n 8.37\n ],\n [\n 51.84,\n 11.17,\n 21.27,\n 1.05,\n 32.11,\n 2.47,\n 16.07,\n 2.64,\n 41.37,\n 4.85\n ],\n [\n 41.1,\n 27.01,\n 22.43,\n 1.42,\n 22.96,\n 18.39,\n 21.03,\n 3.31,\n 47.51,\n 12.6\n ],\n [\n 46.15,\n 23.08,\n 15.63,\n 10.09,\n 29.78,\n 16.61,\n 11.71,\n 5.25,\n 28.76,\n 15.49\n ],\n [\n 48.44,\n 19.05,\n 12.58,\n 4.44,\n 30.65,\n 17.2,\n 22.99,\n 13.83,\n 24.92,\n 25.95\n ],\n [\n 43.75,\n 27.45,\n 7.52,\n 28.08,\n 48.03,\n 7.82,\n 28.79,\n 13.96,\n 43.92,\n 1.08\n ],\n [\n 23.27,\n 9.73,\n 6.63,\n 7.57,\n 46.95,\n 5.47,\n 8.81,\n 27.18,\n 43.93,\n 20.68\n ],\n [\n 46.11,\n 9.8,\n 19.72,\n 1.68,\n 39.37,\n 8.94,\n 7.18,\n 22.96,\n 43.29,\n 16.61\n ],\n [\n 37.81,\n 28.13,\n 27.44,\n 14.8,\n 38.41,\n 6.19,\n 12.98,\n 15.88,\n 34.2,\n 21.84\n ],\n [\n 25.45,\n 7.63,\n 13.02,\n 13.04,\n 45.67,\n 25.06,\n 18.63,\n 5.5,\n 24.81,\n 10.08\n ],\n [\n 31.85,\n 12.55,\n 10.13,\n 13.15,\n 23.25,\n 16.16,\n 20.33,\n 27.88,\n 36.94,\n 3.71\n ],\n [\n 38.29,\n 16.24,\n 22.73,\n 14.31,\n 43.97,\n 10.44,\n 26.83,\n 20.28,\n 38.77,\n 2.73\n ],\n [\n 27.41,\n 10.64,\n 18.83,\n 16.97,\n 31.26,\n 13.18,\n 2.64,\n 5.84,\n 35.93,\n 24.41\n ],\n [\n 53.9,\n 1.2,\n 28.76,\n 5.34,\n 32.91,\n 18.14,\n 1.6,\n 27.94,\n 41.53,\n 16.48\n ],\n [\n 42.34,\n 8.83,\n 28.06,\n 1.11,\n 21.38,\n 14.28,\n 28.54,\n 14.8,\n 45.92,\n 5.65\n ],\n [\n 22.59,\n 27.42,\n 2.06,\n 3.08,\n 42.51,\n 18.3,\n 21.8,\n 10.97,\n 28.17,\n 9.76\n ],\n [\n 24.03,\n 5.37,\n 3.06,\n 24.75,\n 26.88,\n 17.01,\n 7.32,\n 6.12,\n 53.62,\n 19.39\n ],\n [\n 25.21,\n 12.38,\n 4.06,\n 8.5,\n 23.66,\n 26.27,\n 6.5,\n 13.97,\n 52.23,\n 2.53\n ],\n [\n 21.43,\n 9.02,\n 11.43,\n 24.84,\n 45.26,\n 14.65,\n 1.01,\n 2.52,\n 21.9,\n 16.26\n ],\n [\n 45.57,\n 11.08,\n 20.8,\n 26.15,\n 29.2,\n 26.35,\n 9.27,\n 15.34,\n 34.89,\n 28.51\n ],\n [\n 46.2,\n 11.07,\n 12.05,\n 16.71,\n 45.23,\n 6.56,\n 27.86,\n 17.12,\n 51.75,\n 6.62\n ],\n [\n 21.35,\n 20.14,\n 19.06,\n 22.41,\n 36.04,\n 14.14,\n 1.79,\n 19.66,\n 25.71,\n 23.23\n ],\n [\n 49.33,\n 24.28,\n 22.3,\n 27.59,\n 53.76,\n 26.28,\n 18.32,\n 7.68,\n 47.18,\n 1.02\n ],\n [\n 21.78,\n 17.01,\n 23.26,\n 23.39,\n 25.3,\n 4.18,\n 2.08,\n 10.78,\n 33.78,\n 1.32\n ],\n [\n 30.89,\n 8.35,\n 1.4,\n 25.68,\n 28.98,\n 22.62,\n 18.18,\n 8.84,\n 37.04,\n 2.99\n ],\n [\n 21.55,\n 11.85,\n 24.33,\n 8.5,\n 38.4,\n 9.96,\n 10.91,\n 19.72,\n 41.95,\n 12.44\n ],\n [\n 52.66,\n 1.12,\n 23.65,\n 27.21,\n 37.26,\n 27.38,\n 7.5,\n 17.98,\n 52.83,\n 13.38\n ],\n [\n 34.72,\n 18.76,\n 28.1,\n 18.17,\n 23.51,\n 15.65,\n 7.27,\n 23.02,\n 30.09,\n 18.72\n ],\n [\n 30.5,\n 4.8,\n 3.22,\n 16.88,\n 31,\n 28.99,\n 26.39,\n 24.91,\n 45.3,\n 11.19\n ],\n [\n 43.95,\n 11.96,\n 13.07,\n 25,\n 31.82,\n 21.9,\n 17.47,\n 15.41,\n 39.76,\n 10.66\n ],\n [\n 48.1,\n 1.12,\n 2.47,\n 21.34,\n 43.53,\n 25.06,\n 16.5,\n 6.3,\n 28.09,\n 25.49\n ],\n [\n 29.38,\n 11.34,\n 22.09,\n 6.79,\n 21.35,\n 4.75,\n 1.38,\n 8.5,\n 33.73,\n 15.17\n ],\n [\n 21.45,\n 3.14,\n 13.84,\n 21.62,\n 34.39,\n 1.32,\n 23.04,\n 9.6,\n 33.36,\n 12.83\n ],\n [\n 27.55,\n 13.14,\n 1.92,\n 23.19,\n 34.43,\n 21.65,\n 6.65,\n 8.66,\n 23.27,\n 13.41\n ],\n [\n 42,\n 8.04,\n 10.01,\n 22.62,\n 31.02,\n 26.42,\n 10.56,\n 6.07,\n 52.1,\n 22.73\n ],\n [\n 50.68,\n 11.8,\n 20.5,\n 13.2,\n 49.5,\n 16.36,\n 23.47,\n 1.26,\n 52.11,\n 6.87\n ],\n [\n 46.9,\n 6.11,\n 9.83,\n 5.76,\n 33.14,\n 20.6,\n 22.2,\n 10.86,\n 24.28,\n 7.22\n ],\n [\n 23.49,\n 20.91,\n 13.9,\n 3.77,\n 41.37,\n 16.67,\n 20.85,\n 14.56,\n 41.59,\n 2.48\n ],\n [\n 39.56,\n 7.5,\n 22.68,\n 14.88,\n 26.3,\n 26.24,\n 22.45,\n 27.49,\n 33.75,\n 12.28\n ],\n [\n 41,\n 21.73,\n 26.46,\n 24.01,\n 37.7,\n 19.38,\n 23.42,\n 12.84,\n 32.01,\n 5.28\n ],\n [\n 28.02,\n 16.13,\n 9.13,\n 22.94,\n 29.45,\n 20.2,\n 15.4,\n 13.69,\n 45.03,\n 21.07\n ],\n [\n 26.45,\n 14.49,\n 20.43,\n 7.38,\n 24.85,\n 25.36,\n 2.69,\n 4.91,\n 46.74,\n 18.85\n ],\n [\n 35.11,\n 7.17,\n 22.37,\n 7.18,\n 35.22,\n 17.4,\n 13.75,\n 25.76,\n 37.96,\n 14.03\n ],\n [\n 31.8,\n 28.62,\n 4.03,\n 27.35,\n 34.46,\n 4.35,\n 14.3,\n 8.43,\n 31.49,\n 27.2\n ],\n [\n 52.7,\n 5.97,\n 5.7,\n 10.52,\n 44.97,\n 8.57,\n 15.36,\n 6.99,\n 47.65,\n 17.3\n ],\n [\n 50.45,\n 22.98,\n 24.95,\n 20.9,\n 22.78,\n 22.91,\n 17.43,\n 21.92,\n 25.3,\n 24.46\n ],\n [\n 21.86,\n 20.42,\n 18.33,\n 5.72,\n 29.44,\n 28.62,\n 7.23,\n 5.17,\n 37.31,\n 3.12\n ],\n [\n 48.8,\n 13.89,\n 15.33,\n 11.12,\n 48.7,\n 27.98,\n 19.88,\n 14.3,\n 42.36,\n 19.42\n ],\n [\n 28.11,\n 9.97,\n 25.52,\n 3.68,\n 48.55,\n 2.26,\n 20.76,\n 9.64,\n 42.63,\n 9.84\n ],\n [\n 30.79,\n 2.41,\n 13.33,\n 23.13,\n 52.03,\n 4.8,\n 13.08,\n 26.53,\n 41.04,\n 18.68\n ],\n [\n 45.36,\n 25.66,\n 7.86,\n 3.99,\n 45.06,\n 21.64,\n 4.39,\n 23.03,\n 23,\n 14.41\n ]\n ]\n }\n },\n config={\n \"arcSegmentsSeparation\": 3,\n \"circularAnchors2Align\": \"inside\",\n \"circularAnchorsAlign\": \"outside\",\n \"circularCenterProportion\": 0.5,\n \"circularLabelsAlign\": \"inside\",\n \"colorScheme\": \"Tableau\",\n \"colors\": [\n \"#332288\",\n \"#6699CC\",\n \"#88CCEE\",\n \"#44AA99\",\n \"#117733\",\n \"#999933\",\n \"#DDCC77\",\n \"#661100\",\n \"#CC6677\",\n \"#AA4466\",\n \"#882255\",\n \"#AA4499\"\n ],\n \"connections\": [\n [\n \"rgb(0,0,255)\",\n 1,\n 17615830,\n 13,\n 60500000,\n 100000000,\n 20000000\n ],\n [\n \"rgb(0,255,0)\",\n 1,\n 2300000,\n 8,\n 13650000,\n 40000000,\n 80000000\n ],\n [\n \"rgb(120,0,255)\",\n 3,\n 71800000,\n 17,\n 6800000,\n 50000000,\n 25000000\n ],\n [\n \"rgb(0,40,255)\",\n 7,\n 71800000,\n 12,\n 5520000,\n 200000000,\n 80000000\n ],\n [\n \"rgb(80,0,55)\",\n 4,\n 8430000,\n 22,\n 6600000,\n 100000000,\n 50000000\n ],\n [\n \"rgb(0,55,140)\",\n 4,\n 3100000,\n 14,\n 64100000,\n 58000000,\n 10000000\n ],\n [\n \"rgb(255,0,0)\",\n 2,\n 94840000,\n 20,\n 6243500,\n 70000000,\n 30000000\n ]\n ],\n \"graphType\": \"Circular\",\n \"ringGraphType\": [\n \"heatmap\",\n \"stacked\"\n ],\n \"ringsOrder\": [\n \"chromosomes\",\n \"Annt1\",\n \"Lev:1\",\n \"anchors\",\n \"labels\",\n \"ideogram\",\n \"anchors2\",\n \"Lev:4\"\n ],\n \"segregateSamplesBy\": [\n \"Factor4\"\n ],\n \"showIdeogram\": True,\n \"title\": \"Custom Plotting Order\"\n },\n width=713,\n height=613,\n events=CXEvents(),\n after_render=[],\n other_init_params={\n \"version\": 35,\n \"events\": False,\n \"info\": False,\n \"afterRenderInit\": False,\n \"noValidate\": True\n }\n)\n\ndisplay = CXNoteBook(cx) \ndisplay.render(output_file=\"circular_6.html\") \n", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
4aef86608bb7798eddf00bbf95fac2999797db9f
39,462
ipynb
Jupyter Notebook
examples/legends/default_legend.ipynb
jorisvandenbossche/cartoframes
de0f514a8460d61a86afd58e46f7e738060ba09a
[ "BSD-3-Clause" ]
null
null
null
examples/legends/default_legend.ipynb
jorisvandenbossche/cartoframes
de0f514a8460d61a86afd58e46f7e738060ba09a
[ "BSD-3-Clause" ]
null
null
null
examples/legends/default_legend.ipynb
jorisvandenbossche/cartoframes
de0f514a8460d61a86afd58e46f7e738060ba09a
[ "BSD-3-Clause" ]
null
null
null
38.80236
963
0.465182
[ [ [ "# Default legend\n\nThe color-category type draws a categorical legend on your map that is based your data's geometry using either the color (default) or strokeColor property of your visualization.\n\nTo view available legend parameters, run help(Legend('color-category'))\n\nIn this example, the category legend draws the top 3 tree species types in San Francisco.", "_____no_output_____" ] ], [ [ "from cartoframes.auth import set_default_credentials\nfrom cartoframes.viz import Map, Layer, Legend\n\nset_default_credentials('cartoframes')", "_____no_output_____" ], [ "Map(\n Layer(\n 'trees_sf',\n legend=Legend(\n 'default',\n title='Tree Map',\n description='San Francisco, CA',\n footer='Source: City of SF'\n )\n )\n)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
4aef8d063d8b9c296da85271631a647f7002c4b0
4,007
ipynb
Jupyter Notebook
examples/ITK_Example4_InitialTransformAndMultiThreading.ipynb
N-Dekker/ITKElastix
667d08b0621125bdc6b09913f6544badec3045bf
[ "Apache-2.0" ]
null
null
null
examples/ITK_Example4_InitialTransformAndMultiThreading.ipynb
N-Dekker/ITKElastix
667d08b0621125bdc6b09913f6544badec3045bf
[ "Apache-2.0" ]
null
null
null
examples/ITK_Example4_InitialTransformAndMultiThreading.ipynb
N-Dekker/ITKElastix
667d08b0621125bdc6b09913f6544badec3045bf
[ "Apache-2.0" ]
null
null
null
29.036232
120
0.640379
[ [ [ "## 4. Image Registration with initial transform and/or multiple threads", "_____no_output_____" ], [ "In this notebook 2 other options of the elastix algorithm are shown: initial transformation and multithreading.\nThey're shown together just to reduce the number of example notebooks and \nthus can be used independently as well as in combination with whichever other functionality\nof the elastix algorithm. \n\nInitial transforms are transformations that are done on the moving image before the registration is started.\n\nMultithreading spreaks for itself and can be used in similar fashion in the transformix algorithm.\n\n", "_____no_output_____" ], [ "### Registration", "_____no_output_____" ] ], [ [ "# First import is currently necessary to run ITKElastix on MacOs\nfrom itk import itkElastixRegistrationMethodPython\nimport itk", "_____no_output_____" ], [ "# Import Images\nfixed_image = itk.imread('data/CT_2D_head_fixed.mha', itk.F)\nmoving_image = itk.imread('data/CT_2D_head_moving.mha', itk.F)\n\n# Import Default Parameter Map\nparameter_object = itk.ParameterObject.New()\nparameter_map_rigid = parameter_object.GetDefaultParameterMap('rigid')\nparameter_object.AddParameterMap(parameter_map_rigid)\nparameter_object.AddParameterMap(parameter_map_rigid)", "_____no_output_____" ] ], [ [ "Registration can either be done in one line with the registration function...", "_____no_output_____" ] ], [ [ "# Call registration function with initial transfrom and number of threads\nresult_image, result_transform_parameters = itk.elastix_registration_method(\n fixed_image, moving_image,\n parameter_object=parameter_object,\n initial_transform_parameter_file_name='data/TransformParameters.0.txt',\n number_of_threads=4,\n log_to_console=False)", "_____no_output_____" ] ], [ [ ".. or by initiating an elastix image filter object.", "_____no_output_____" ] ], [ [ "# Load Elastix Image Filter Object with initial transfrom and number of threads\nelastix_object = itk.ElastixRegistrationMethod.New()\nelastix_object.SetFixedImage(fixed_image)\nelastix_object.SetMovingImage(moving_image)\nelastix_object.SetParameterObject(parameter_object)\nelastix_object.SetInitialTransformParameterFileName(\n 'data/TransformParameters.0.txt')\nelastix_object.SetNumberOfThreads(4)\n\n# Set additional options\nelastix_object.SetLogToConsole(False)\n\n# Update filter object (required)\nelastix_object.UpdateLargestPossibleRegion()\n\n# Results of Registration\nresult_image = elastix_object.GetOutput()\nresult_transform_parameters = elastix_object.GetTransformParameterObject()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aef8ebc97a5b9bfd616291477fa0f6d0bd09e29
131,259
ipynb
Jupyter Notebook
Found_in_interpreting_translation.ipynb
yuri-bizzoni/Found-in-Interpreting
1af3e822ed23d420f6203e51df3dc051c513e67b
[ "MIT" ]
null
null
null
Found_in_interpreting_translation.ipynb
yuri-bizzoni/Found-in-Interpreting
1af3e822ed23d420f6203e51df3dc051c513e67b
[ "MIT" ]
null
null
null
Found_in_interpreting_translation.ipynb
yuri-bizzoni/Found-in-Interpreting
1af3e822ed23d420f6203e51df3dc051c513e67b
[ "MIT" ]
null
null
null
49.197526
9,476
0.590268
[ [ [ "# Found in translation/interpreting (MoTra21)", "_____no_output_____" ], [ "In this paper we classify written, spoken, translation and interpreting using\ncompeting sets of features, with a SVM", "_____no_output_____" ] ], [ [ "import time\nimport nltk\nfrom sklearn import svm\nimport sklearn\nfrom sklearn.svm import SVC\nimport glob\nfrom lexical_diversity import lex_div as ld\nimport numpy as np\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.model_selection import cross_val_score", "_____no_output_____" ] ], [ [ "The following part is the most space consuming: we take the KLD values of many terms in a set of contrasted categories (e.g. translation vs written originals) and we make them into dictionary-like objects", "_____no_output_____" ], [ "Name code:\nosvow: Original Spoken Versus Original Written\nosvi: Original Spoken Versus Interpreting\nowto: Original Written Versus Translation \netc.etc.", "_____no_output_____" ] ], [ [ "## KLD preselection\n\n# translation versus original written (written originals)\ntvow = {\n\"title\": \"SITR (written) vs. ORG (written)\",\n\"terms\": [\n[\"this\", 0.01395132, 0.01711909, 0.00000000],\n[\"we\", 0.01053052, 0.01862605, 0.00043504],\n[\"gentlemen\", 0.00675825, 0.00132613, 0.00000000],\n[\"ladies\", 0.00675825, 0.00132613, 0.00000000],\n[\"that\", 0.00565117, 0.02322731, 0.02922500],\n[\"also\", 0.00521316, 0.00528441, 0.00000202],\n[\"you\", 0.00471150, 0.00415922, 0.00877080],\n[\"regard\", 0.00363400, 0.00126585, 0.00001542],\n[\"european\", 0.00307788, 0.00608813, 0.02442100],\n[\"in\", 0.00263547, 0.02670337, 0.13595000],\n[\"however\", 0.00262847, 0.00261207, 0.00055496],\n[\"like\", 0.00240968, 0.00317467, 0.00441320],\n[\"here\", 0.00226540, 0.00168780, 0.00088326],\n[\"must\", 0.00221923, 0.00492274, 0.06620900],\n[\"therefore\", 0.00191655, 0.00174808, 0.00261950],\n[\"which\", 0.00188422, 0.00584701, 0.15325000],\n[\"i\", 0.00184087, 0.01209588, 0.12773000],\n[\"eulex\", 0.00174076, 0.00034158, 0.03430800],\n[\"is\", 0.00169917, 0.02081617, 0.51649000],\n[\"important\", 0.00169504, 0.00170789, 0.00448390],\n[\"social\", 0.00165145, 0.00130603, 0.08807500],\n[\"president-in-office\", 0.00163836, 0.00032149, 0.00015225],\n[\"whether\", 0.00161815, 0.00120557, 0.01290900],\n[\"kosovo\", 0.00159914, 0.00076353, 0.07778200],\n[\"things\", 0.00154647, 0.00066306, 0.01012600],\n[\"opinion\", 0.00146664, 0.00072334, 0.00571210],\n[\"policy\", 0.00146277, 0.00170789, 0.04552100],\n[\"once\", 0.00145597, 0.00102473, 0.00644990],\n[\"micro-entities\", 0.00143357, 0.00028130, 0.05340300],\n[\"would\", 0.00140190, 0.00490265, 0.06362100],\n[\"regulations\", 0.00135180, 0.00056260, 0.01564300],\n[\"thing\", 0.00135180, 0.00056260, 0.01689600],\n[\"wine\", 0.00133117, 0.00026121, 0.07972300],\n[\"again\", 0.00131423, 0.00130603, 0.00955600],\n[\"gambling\", 0.00123471, 0.00048223, 0.12219000],\n[\"guantánamo\", 0.00123471, 0.00048223, 0.02762900],\n[\"fellow\", 0.00123471, 0.00048223, 0.00155680],\n[\"dialogue\", 0.00120883, 0.00052241, 0.03431900],\n[\"company\", 0.00120883, 0.00052241, 0.11371000],\n[\"treaty\", 0.00117067, 0.00134622, 0.13536000],\n[\"because\", 0.00114853, 0.00196910, 0.08543800],\n[\"signal\", 0.00112638, 0.00022102, 0.00277350],\n[\"have\", 0.00112320, 0.01030762, 0.28088000],\n[\"question\", 0.00111624, 0.00092427, 0.01523000],\n[\"germany\", 0.00108657, 0.00044204, 0.01126700],\n[\"want\", 0.00108465, 0.00140650, 0.05764100],\n[\"clear\", 0.00107931, 0.00164761, 0.04204500],\n[\"order\", 0.00107623, 0.00104483, 0.03524100],\n[\"german\", 0.00106910, 0.00048223, 0.03376500],\n[\"know\", 0.00106122, 0.00106492, 0.04006100],\n[\"with\", 0.00102508, 0.00729370, 0.12851000],\n[\"fundamental\", 0.00102430, 0.00074343, 0.04723000],\n[\"decisive\", 0.00102398, 0.00020093, 0.00320750],\n[\"method\", 0.00102398, 0.00020093, 0.04281500],\n[\"redundancies\", 0.00102398, 0.00020093, 0.13355000],\n[\"credibility\", 0.00102398, 0.00020093, 0.00943270],\n[\"chancellor\", 0.00102398, 0.00020093, 0.04239600],\n[\"wines\", 0.00102398, 0.00020093, 0.10225000],\n[\"believe\", 0.00100082, 0.00136631, 0.02579700],\n[\"something\", 0.00099757, 0.00070325, 0.06523800],\n[\"need\", 0.00099105, 0.00287327, 0.19003000],\n[\"been\", 0.00098955, 0.00361671, 0.12982000],\n[\"parliament\", 0.00098435, 0.00223030, 0.19163000],\n[\"austria\", 0.00098022, 0.00030139, 0.02045900],\n[\"who\", 0.00096951, 0.00297374, 0.14869000],\n[\"rights\", 0.00096620, 0.00198919, 0.07099800],\n[\"few\", 0.00096319, 0.00056260, 0.00990810],\n[\"great\", 0.00095528, 0.00080371, 0.11022000],\n[\"together\", 0.00094730, 0.00062288, 0.01834300],\n[\"democrats\", 0.00094211, 0.00040186, 0.01698100],\n[\"not\", 0.00093834, 0.00980530, 0.27992000],\n[\"people\", 0.00092445, 0.00319476, 0.25933000],\n[\"contrary\", 0.00092158, 0.00018084, 0.00705680],\n[\"steps\", 0.00092158, 0.00018084, 0.00574860],\n[\"introduce\", 0.00092158, 0.00018084, 0.00372150],\n[\"about\", 0.00091875, 0.00233077, 0.14106000],\n[\"are\", 0.00091793, 0.00972493, 0.33488000],\n[\"service\", 0.00090540, 0.00078362, 0.20498000],\n[\"say\", 0.00090360, 0.00124576, 0.09488700],\n[\"namely\", 0.00089867, 0.00034158, 0.03508100],\n[\"mission\", 0.00089482, 0.00028130, 0.07246900],\n[\"progress\", 0.00089128, 0.00060278, 0.02106900],\n[\"reason\", 0.00088998, 0.00066306, 0.00700210],\n[\"can\", 0.00087214, 0.00327513, 0.19702000],\n[\"am\", 0.00087046, 0.00172798, 0.17837000],\n[\"talk\", 0.00086631, 0.00042195, 0.01970300],\n[\"course\", 0.00086240, 0.00122566, 0.10684000],\n[\"said\", 0.00086240, 0.00122566, 0.05517000],\n[\"thank\", 0.00084040, 0.00086399, 0.00576800],\n[\"made\", 0.00082622, 0.00144668, 0.10811000],\n[\"unfortunately\", 0.00082559, 0.00048223, 0.02032000],\n[\"quickly\", 0.00082559, 0.00048223, 0.03195600],\n[\"seat\", 0.00081918, 0.00016074, 0.04701400],\n[\"merkel\", 0.00081918, 0.00016074, 0.03316600],\n[\"decrees\", 0.00081918, 0.00016074, 0.08171400],\n[\"austrian\", 0.00081918, 0.00016074, 0.02413900],\n[\"camp\", 0.00081918, 0.00016074, 0.04907100],\n[\"syria\", 0.00081918, 0.00016074, 0.15943000],\n[\"ought\", 0.00081918, 0.00016074, 0.01429600],\n[\"previous\", 0.00081918, 0.00016074, 0.00531000],\n[\"greens\", 0.00081918, 0.00016074, 0.00637020],\n[\"these\", 0.00081785, 0.00261207, 0.10962000],\n[\"already\", 0.00081480, 0.00066306, 0.02822700],\n[\"point\", 0.00081245, 0.00100464, 0.14201000],\n[\"during\", 0.00081084, 0.00054251, 0.02659300],\n[\"alliance\", 0.00081054, 0.00026121, 0.01279600],\n[\"your\", 0.00080832, 0.00082381, 0.09844500],\n[\"at\", 0.00079908, 0.00387792, 0.55385000],\n[\"subject\", 0.00078169, 0.00056260, 0.01782400],\n[\"then\", 0.00076587, 0.00122566, 0.09960600],\n[\"particular\", 0.00075995, 0.00100464, 0.07123800],\n[\"represents\", 0.00073629, 0.00038176, 0.02217700],\n[\"opportunities\", 0.00073342, 0.00034158, 0.02649000],\n[\"chance\", 0.00072751, 0.00024111, 0.01132200],\n[\"malmström\", 0.00072751, 0.00024111, 0.06483500],\n[\"only\", 0.00072644, 0.00196910, 0.12706000],\n[\"example\", 0.00071820, 0.00098455, 0.05974400],\n[\"gsp\", 0.00071678, 0.00014065, 0.08666000],\n[\"america\", 0.00071678, 0.00014065, 0.01920200],\n[\"documents\", 0.00071678, 0.00014065, 0.04198600],\n[\"car\", 0.00071678, 0.00014065, 0.01735900],\n[\"transposition\", 0.00071678, 0.00014065, 0.07560600],\n[\"comment\", 0.00071678, 0.00014065, 0.00943510],\n[\"applies\", 0.00071678, 0.00014065, 0.01849800],\n[\"group\", 0.00071247, 0.00138641, 0.18386000],\n[\"legislative\", 0.00070774, 0.00044204, 0.06497100],\n[\"result\", 0.00070458, 0.00056260, 0.02959800],\n[\"matter\", 0.00070458, 0.00056260, 0.03219500],\n[\"us\", 0.00068375, 0.00235086, 0.14378000],\n[\"case\", 0.00067698, 0.00096446, 0.08257000],\n[\"otherwise\", 0.00067590, 0.00028130, 0.03273900],\n[\"protection\", 0.00066855, 0.00098455, 0.11076000],\n[\"sense\", 0.00066630, 0.00032149, 0.02008600],\n[\"mentioned\", 0.00065040, 0.00042195, 0.06257900],\n[\"uighurs\", 0.00064589, 0.00022102, 0.06915200],\n[\"media\", 0.00064589, 0.00022102, 0.08560800],\n[\"particularly\", 0.00062830, 0.00074343, 0.06479900],\n[\"as\", 0.00062204, 0.00845908, 0.28377000],\n[\"terms\", 0.00062000, 0.00044204, 0.04773700],\n[\"incorporated\", 0.00061439, 0.00012056, 0.03290900],\n[\"debates\", 0.00061439, 0.00012056, 0.01133000],\n[\"consideration\", 0.00061439, 0.00012056, 0.01493400],\n[\"played\", 0.00061439, 0.00012056, 0.00851350],\n[\"separatism\", 0.00061439, 0.00012056, 0.15943000],\n[\"eeas\", 0.00061439, 0.00012056, 0.07967700],\n[\"adopt\", 0.00061439, 0.00012056, 0.02331500],\n[\"langen\", 0.00061439, 0.00012056, 0.03763100],\n[\"internet\", 0.00061103, 0.00034158, 0.16080000],\n[\"represent\", 0.00060442, 0.00026121, 0.04336800],\n[\"implement\", 0.00060056, 0.00030139, 0.05357500],\n[\"extent\", 0.00060056, 0.00030139, 0.10183000],\n[\"pleased\", 0.00060056, 0.00030139, 0.06866300],\n[\"partners\", 0.00060056, 0.00030139, 0.08306600],\n[\"relating\", 0.00060056, 0.00030139, 0.02232200],\n[\"will\", 0.00058648, 0.00651008, 0.38870000],\n[\"quite\", 0.00056993, 0.00056260, 0.08209900],\n[\"democracy\", 0.00056993, 0.00056260, 0.20140000],\n[\"connection\", 0.00056587, 0.00020093, 0.04240600],\n[\"ban\", 0.00056587, 0.00020093, 0.06918600],\n[\"fund\", 0.00056335, 0.00066306, 0.46497000],\n[\"able\", 0.00055655, 0.00090418, 0.09375700],\n[\"what\", 0.00055655, 0.00285318, 0.31158000],\n[\"process\", 0.00054232, 0.00070325, 0.18886000],\n[\"against\", 0.00053544, 0.00126585, 0.22221000],\n[\"give\", 0.00053088, 0.00062288, 0.10980000],\n[\"questions\", 0.00052350, 0.00046214, 0.08952900],\n[\"cannot\", 0.00052067, 0.00132613, 0.25883000],\n[\"situation\", 0.00051548, 0.00076353, 0.19654000],\n[\"peace\", 0.00051378, 0.00034158, 0.15058000],\n[\"aspect\", 0.00051199, 0.00010046, 0.03394500],\n[\"arrive\", 0.00051199, 0.00010046, 0.04695000],\n[\"frequency\", 0.00051199, 0.00010046, 0.04297600],\n[\"italian\", 0.00051199, 0.00010046, 0.06263300],\n[\"react\", 0.00051199, 0.00010046, 0.01526600],\n[\"session\", 0.00051199, 0.00010046, 0.02304400],\n[\"dtp\", 0.00051199, 0.00010046, 0.15943000],\n[\"rail\", 0.00051199, 0.00010046, 0.05243300],\n[\"malaysia\", 0.00051199, 0.00010046, 0.15943000],\n[\"approval\", 0.00051199, 0.00010046, 0.01647700],\n[\"prove\", 0.00051199, 0.00010046, 0.03374800],\n[\"fraud\", 0.00051199, 0.00010046, 0.15943000],\n[\"house\", 0.00050041, 0.00068316, 0.36691000],\n[\"really\", 0.00049990, 0.00080371, 0.06425600],\n[\"actually\", 0.00049990, 0.00080371, 0.21074000],\n[\"make\", 0.00049866, 0.00178826, 0.11869000],\n[\"a\", 0.00049786, 0.02109747, 0.58171000],\n[\"take\", 0.00049334, 0.00144668, 0.08622100],\n[\"internal\", 0.00049282, 0.00042195, 0.11967000],\n[\"currently\", 0.00049140, 0.00050232, 0.08607300],\n[\"starting\", 0.00048766, 0.00018084, 0.06897400],\n[\"yes\", 0.00048766, 0.00018084, 0.05608200],\n[\"factor\", 0.00048766, 0.00018084, 0.02434200],\n[\"adjustment\", 0.00048766, 0.00018084, 0.18879000],\n[\"end\", 0.00048573, 0.00084390, 0.17023000],\n[\"illegal\", 0.00047801, 0.00052241, 0.05672300],\n[\"procedure\", 0.00047491, 0.00044204, 0.11012000],\n[\"thus\", 0.00047366, 0.00026121, 0.02822200],\n[\"discussions\", 0.00047366, 0.00026121, 0.08783800],\n[\"message\", 0.00047366, 0.00026121, 0.03924600],\n[\"beginning\", 0.00046647, 0.00022102, 0.02856800],\n[\"discussed\", 0.00046647, 0.00022102, 0.07867300],\n[\"demands\", 0.00046647, 0.00022102, 0.13342000],\n[\"negotiations\", 0.00046260, 0.00038176, 0.11352000],\n[\"within\", 0.00046080, 0.00078362, 0.26257000],\n[\"consider\", 0.00045840, 0.00032149, 0.06071100],\n[\"return\", 0.00045840, 0.00032149, 0.07435500],\n[\"committee\", 0.00044904, 0.00112520, 0.14525000],\n[\"instead\", 0.00044570, 0.00048223, 0.18665000],\n[\"lot\", 0.00044361, 0.00040186, 0.03833300],\n[\"solidarity\", 0.00044361, 0.00040186, 0.30948000],\n[\"members\", 0.00043523, 0.00086399, 0.27660000],\n[\"local\", 0.00043360, 0.00028130, 0.06865600],\n[\"talking\", 0.00043360, 0.00028130, 0.06528400],\n[\"had\", 0.00043345, 0.00102473, 0.20477000],\n[\"joint\", 0.00043306, 0.00034158, 0.07330300],\n[\"problems\", 0.00042695, 0.00062288, 0.13146000],\n[\"too\", 0.00042381, 0.00090418, 0.21940000],\n[\"itself\", 0.00042247, 0.00052241, 0.17476000],\n[\"very\", 0.00041716, 0.00245133, 0.29312000],\n[\"europe\", 0.00041610, 0.00225040, 0.47060000],\n[\"time\", 0.00041605, 0.00164761, 0.34898000],\n[\"opposition\", 0.00041279, 0.00024111, 0.16789000],\n[\"online\", 0.00041279, 0.00024111, 0.20989000],\n[\"calling\", 0.00041279, 0.00024111, 0.06335300],\n[\"behind\", 0.00041264, 0.00036167, 0.08424200],\n[\"addition\", 0.00041264, 0.00036167, 0.04619300],\n[\"accept\", 0.00041264, 0.00036167, 0.08557000],\n[\"greece\", 0.00041244, 0.00054251, 0.50075000],\n[\"promote\", 0.00041157, 0.00016074, 0.09586400],\n[\"explain\", 0.00041157, 0.00016074, 0.08766300],\n[\"combating\", 0.00041157, 0.00016074, 0.18824000],\n[\"christian\", 0.00041157, 0.00016074, 0.05222200],\n[\"laid\", 0.00040959, 0.00008037, 0.03197300],\n[\"penalties\", 0.00040959, 0.00008037, 0.07634400],\n[\"hearing\", 0.00040959, 0.00008037, 0.05171000],\n[\"traditional\", 0.00040959, 0.00008037, 0.06684900],\n[\"engage\", 0.00040959, 0.00008037, 0.10094000],\n[\"copyright\", 0.00040959, 0.00008037, 0.04721700],\n[\"housing\", 0.00040959, 0.00008037, 0.05919300],\n[\"arguments\", 0.00040959, 0.00008037, 0.06178200],\n[\"orientation\", 0.00040959, 0.00008037, 0.08892900],\n[\"reporting\", 0.00040959, 0.00008037, 0.11438000],\n[\"regulate\", 0.00040959, 0.00008037, 0.09144100],\n[\"human\", 0.00040503, 0.00114529, 0.19312000],\n[\"everyone\", 0.00040454, 0.00030139, 0.06085100],\n[\"insurance\", 0.00040037, 0.00020093, 0.18009000],\n[\"absolutely\", 0.00040037, 0.00020093, 0.04854800],\n[\"structure\", 0.00040037, 0.00020093, 0.09398600],\n[\"carefully\", 0.00040037, 0.00020093, 0.07218200],\n[\"sometimes\", 0.00040037, 0.00020093, 0.08652200]\n]\n}\n\nivos = {\n\"title\": \"SITR (spoken) vs. ORG (spoken)\",\n\"terms\": [\n[\"euh\", 0.03960763, 0.04218045, 0.00000000],\n[\"hum\", 0.00698372, 0.00375940, 0.00001041],\n[\"we\", 0.00596984, 0.02483083, 0.02644400],\n[\"be\", 0.00460203, 0.01135338, 0.00547490],\n[\"kosovo\", 0.00363414, 0.00069549, 0.00526050],\n[\"'t\", 0.00317923, 0.00535714, 0.01024100],\n[\"need\", 0.00315935, 0.00411654, 0.00293900],\n[\"'re\", 0.00312006, 0.00413534, 0.00359710],\n[\"can\", 0.00306121, 0.00518797, 0.00601240],\n[\"going\", 0.00264991, 0.00225564, 0.00377160],\n[\"policy\", 0.00259379, 0.00146617, 0.00915090],\n[\"gentlemen\", 0.00239302, 0.00065789, 0.00002205],\n[\"talking\", 0.00238054, 0.00131579, 0.00445210],\n[\"external\", 0.00235728, 0.00045113, 0.00149750],\n[\"have\", 0.00233189, 0.01122180, 0.10449000],\n[\"ladies\", 0.00228686, 0.00069549, 0.00006145],\n[\"gambling\", 0.00216084, 0.00041353, 0.04878800],\n[\"are\", 0.00215417, 0.00845865, 0.13382000],\n[\"guantánamo\", 0.00206262, 0.00039474, 0.01344400],\n[\"now\", 0.00205627, 0.00419173, 0.08461300],\n[\"has\", 0.00202141, 0.00469925, 0.05163700],\n[\"citizens\", 0.00201887, 0.00122180, 0.04574100],\n[\"'s\", 0.00195831, 0.01033835, 0.10421000],\n[\"something\", 0.00194038, 0.00140977, 0.00111650],\n[\"europe\", 0.00192766, 0.00195489, 0.02778800],\n[\"a\", 0.00190769, 0.02016917, 0.30463000],\n[\"peace\", 0.00176892, 0.00045113, 0.07242000],\n[\"crisis\", 0.00165246, 0.00127820, 0.07221400],\n[\"micro\", 0.00157152, 0.00030075, 0.06122100],\n[\"really\", 0.00154350, 0.00184211, 0.02499000],\n[\"these\", 0.00147660, 0.00306391, 0.06105100],\n[\"arctic\", 0.00147330, 0.00028195, 0.07270700],\n[\"social\", 0.00145241, 0.00109023, 0.15607000],\n[\"wine\", 0.00137508, 0.00026316, 0.08263800],\n[\"eulex\", 0.00137508, 0.00026316, 0.02612200],\n[\"so\", 0.00136696, 0.00486842, 0.11456000],\n[\"freedom\", 0.00134374, 0.00046992, 0.01827800],\n[\"austria\", 0.00127686, 0.00024436, 0.00402600],\n[\"against\", 0.00126790, 0.00114662, 0.02897300],\n[\"mean\", 0.00126591, 0.00088346, 0.06794400],\n[\"there\", 0.00124564, 0.00569549, 0.21563000],\n[\"obviously\", 0.00120633, 0.00054511, 0.00863260],\n[\"germany\", 0.00119494, 0.00043233, 0.01396700],\n[\"european\", 0.00116613, 0.00445489, 0.12981000],\n[\"think\", 0.00110828, 0.00443609, 0.10853000],\n[\"council\", 0.00109536, 0.00193609, 0.09522600],\n[\"transfer\", 0.00108042, 0.00020677, 0.03513100],\n[\"dialogue\", 0.00107833, 0.00050752, 0.09429100],\n[\"got\", 0.00106633, 0.00140977, 0.08530700],\n[\"should\", 0.00104067, 0.00342105, 0.12440000],\n[\"rights\", 0.00100295, 0.00165414, 0.05575900],\n[\"human\", 0.00100177, 0.00103383, 0.06221200],\n[\"hm\", 0.00100021, 0.00082707, 0.16249000],\n[\"greece\", 0.00099450, 0.00045113, 0.18266000],\n[\"president-in-office\", 0.00098340, 0.00028195, 0.00294290],\n[\"shouldn\", 0.00098056, 0.00050752, 0.02400800],\n[\"then\", 0.00095598, 0.00148496, 0.07346400],\n[\"future\", 0.00092064, 0.00095865, 0.02827300],\n[\"financial\", 0.00091838, 0.00097744, 0.04161500],\n[\"if\", 0.00090971, 0.00366541, 0.34595000],\n[\"german\", 0.00090718, 0.00035714, 0.07650100],\n[\"s\", 0.00090551, 0.00065789, 0.05154400],\n[\"border\", 0.00089963, 0.00026316, 0.00719300],\n[\"certain\", 0.00088651, 0.00069549, 0.04223500],\n[\"detainees\", 0.00088398, 0.00016917, 0.02963400],\n[\"eurozone\", 0.00088398, 0.00016917, 0.09689100],\n[\"corruption\", 0.00088398, 0.00016917, 0.03999200],\n[\"pact\", 0.00088398, 0.00016917, 0.07985900],\n[\"service\", 0.00087832, 0.00060150, 0.02732100],\n[\"illegal\", 0.00084598, 0.00030075, 0.03595500],\n[\"clear\", 0.00082946, 0.00110902, 0.09575200],\n[\"means\", 0.00082513, 0.00071429, 0.08311900],\n[\"talk\", 0.00082513, 0.00071429, 0.05385800],\n[\"media\", 0.00081686, 0.00024436, 0.06365100],\n[\"market\", 0.00079575, 0.00122180, 0.06558300],\n[\"like\", 0.00079183, 0.00229323, 0.07310500],\n[\"things\", 0.00079015, 0.00107143, 0.03889200],\n[\"minority\", 0.00078576, 0.00015038, 0.00386270],\n[\"merkel\", 0.00078576, 0.00015038, 0.03238400],\n[\"austrian\", 0.00078576, 0.00015038, 0.01600500],\n[\"redundancies\", 0.00078576, 0.00015038, 0.11032000],\n[\"resolution\", 0.00077615, 0.00056391, 0.03879100],\n[\"data\", 0.00077615, 0.00056391, 0.08171900],\n[\"turkey\", 0.00077215, 0.00028195, 0.07406600],\n[\"justice\", 0.00077215, 0.00028195, 0.02172700],\n[\"same\", 0.00076085, 0.00078947, 0.05429300],\n[\"taken\", 0.00075664, 0.00082707, 0.21130000],\n[\"lot\", 0.00075261, 0.00088346, 0.08247200],\n[\"motion\", 0.00073520, 0.00022556, 0.03229600],\n[\"'d\", 0.00073079, 0.00129699, 0.02472500],\n[\"people\", 0.00072993, 0.00422932, 0.38731000],\n[\"comes\", 0.00072943, 0.00069549, 0.02460500],\n[\"solidarity\", 0.00071889, 0.00033835, 0.24116000],\n[\"fund\", 0.00071726, 0.00056391, 0.18754000],\n[\"government\", 0.00071354, 0.00082707, 0.30528000],\n[\"community\", 0.00069140, 0.00041353, 0.10879000],\n[\"regardless\", 0.00068754, 0.00013158, 0.05607200],\n[\"serbia\", 0.00068754, 0.00013158, 0.04735900],\n[\"considerations\", 0.00068754, 0.00013158, 0.02276700],\n[\"international\", 0.00068225, 0.00069549, 0.11971000],\n[\"situation\", 0.00067159, 0.00084586, 0.15583000],\n[\"kind\", 0.00066915, 0.00054511, 0.10928000],\n[\"violence\", 0.00065624, 0.00031955, 0.13030000],\n[\"china\", 0.00065624, 0.00031955, 0.06901900],\n[\"policies\", 0.00065624, 0.00031955, 0.16789000],\n[\"croatia\", 0.00065479, 0.00020677, 0.16094000],\n[\"colleagues\", 0.00065422, 0.00120301, 0.06007500],\n[\"with\", 0.00064291, 0.00644737, 0.13583000],\n[\"guarantee\", 0.00062823, 0.00024436, 0.02654400],\n[\"for\", 0.00062165, 0.01077068, 0.24142000],\n[\"fundamental\", 0.00060057, 0.00035714, 0.02081300],\n[\"step\", 0.00059692, 0.00045113, 0.01373200],\n[\"summit\", 0.00059482, 0.00030075, 0.11075000],\n[\"arab\", 0.00058932, 0.00011278, 0.03103500],\n[\"gsp\", 0.00058932, 0.00011278, 0.09039200],\n[\"incorporated\", 0.00058932, 0.00011278, 0.04483800],\n[\"pornography\", 0.00058932, 0.00011278, 0.07908000],\n[\"path\", 0.00058932, 0.00011278, 0.03185300],\n[\"react\", 0.00058932, 0.00011278, 0.03180000],\n[\"regards\", 0.00058932, 0.00011278, 0.01314600],\n[\"applies\", 0.00058932, 0.00011278, 0.00969780],\n[\"origin\", 0.00058932, 0.00011278, 0.01651700],\n[\"waiting\", 0.00058932, 0.00011278, 0.01457900],\n[\"said\", 0.00058169, 0.00140977, 0.16987000],\n[\"question\", 0.00057997, 0.00112782, 0.04002900],\n[\"resolved\", 0.00057580, 0.00018797, 0.03481300],\n[\"iran\", 0.00057580, 0.00018797, 0.02953600],\n[\"epp\", 0.00057580, 0.00018797, 0.03160100],\n[\"adjustment\", 0.00057580, 0.00018797, 0.09919800],\n[\"chinese\", 0.00057580, 0.00018797, 0.07496200],\n[\"afghanistan\", 0.00057580, 0.00018797, 0.12620000],\n[\"ready\", 0.00057580, 0.00018797, 0.01595500],\n[\"minorities\", 0.00057098, 0.00026316, 0.05626900],\n[\"online\", 0.00057098, 0.00026316, 0.14655000],\n[\"country\", 0.00056127, 0.00092105, 0.38118000],\n[\"whether\", 0.00055995, 0.00090226, 0.11708000],\n[\"possible\", 0.00055407, 0.00078947, 0.12690000],\n[\"up\", 0.00053996, 0.00212406, 0.10071000],\n[\"strategy\", 0.00052969, 0.00035714, 0.17243000],\n[\"euro\", 0.00052969, 0.00035714, 0.07489400],\n[\"states\", 0.00051703, 0.00233083, 0.25204000],\n[\"problems\", 0.00051519, 0.00075188, 0.16840000],\n[\"system\", 0.00051344, 0.00065789, 0.12513000],\n[\"civil\", 0.00050977, 0.00030075, 0.01437100],\n[\"won\", 0.00050778, 0.00039474, 0.15635000],\n[\"fighting\", 0.00050774, 0.00024436, 0.02073800],\n[\"signal\", 0.00050774, 0.00024436, 0.20075000],\n[\"swedish\", 0.00050774, 0.00024436, 0.22400000],\n[\"smes\", 0.00050010, 0.00041353, 0.34871000],\n[\"unity\", 0.00049845, 0.00016917, 0.05247000],\n[\"former\", 0.00049845, 0.00016917, 0.09462300],\n[\"dairy\", 0.00049845, 0.00016917, 0.08302300],\n[\"other\", 0.00049482, 0.00182331, 0.18230000],\n[\"region\", 0.00049166, 0.00031955, 0.12420000],\n[\"decisions\", 0.00049166, 0.00031955, 0.05622300],\n[\"speculation\", 0.00049110, 0.00009398, 0.11465000],\n[\"quartet\", 0.00049110, 0.00009398, 0.04340400],\n[\"membership\", 0.00049110, 0.00009398, 0.02128000],\n[\"reinfeldt\", 0.00049110, 0.00009398, 0.09043600],\n[\"dtp\", 0.00049110, 0.00009398, 0.15940000],\n[\"employees\", 0.00049110, 0.00009398, 0.07172000],\n[\"deserves\", 0.00049110, 0.00009398, 0.03248500],\n[\"malaysia\", 0.00049110, 0.00009398, 0.15940000],\n[\"peaceful\", 0.00049110, 0.00009398, 0.02728900],\n[\"separatism\", 0.00049110, 0.00009398, 0.15940000],\n[\"palestinians\", 0.00049110, 0.00009398, 0.04977000],\n[\"existence\", 0.00049110, 0.00009398, 0.01551900],\n[\"torture\", 0.00049110, 0.00009398, 0.05693100],\n[\"south\", 0.00049020, 0.00020677, 0.06394100],\n[\"fight\", 0.00049020, 0.00020677, 0.02791300],\n[\"structural\", 0.00049020, 0.00020677, 0.04122900],\n[\"influence\", 0.00049020, 0.00020677, 0.05267800],\n[\"favour\", 0.00048902, 0.00045113, 0.06286900],\n[\"responsibility\", 0.00048191, 0.00048872, 0.10281000],\n[\"calling\", 0.00047809, 0.00033835, 0.06777800],\n[\"interest\", 0.00047752, 0.00052632, 0.04114400],\n[\"wants\", 0.00047611, 0.00026316, 0.06613800],\n[\"banks\", 0.00047611, 0.00026316, 0.18713000],\n[\"hamas\", 0.00047611, 0.00026316, 0.55874000],\n[\"cases\", 0.00047611, 0.00026316, 0.03022100],\n[\"deal\", 0.00047608, 0.00054511, 0.03943400],\n[\"after\", 0.00047505, 0.00056391, 0.15886000],\n[\"thing\", 0.00047439, 0.00065789, 0.05530600],\n[\"sure\", 0.00046573, 0.00097744, 0.20605000],\n[\"sort\", 0.00044827, 0.00041353, 0.06543600],\n[\"military\", 0.00044612, 0.00022556, 0.28371000],\n[\"therefore\", 0.00044469, 0.00077068, 0.08073500],\n[\"individual\", 0.00043916, 0.00030075, 0.13141000],\n[\"towards\", 0.00043896, 0.00046992, 0.03245900],\n[\"always\", 0.00043509, 0.00052632, 0.06240000],\n[\"set\", 0.00043482, 0.00060150, 0.13341000],\n[\"great\", 0.00043450, 0.00058271, 0.11045000],\n[\"effects\", 0.00042380, 0.00018797, 0.09255300],\n[\"task\", 0.00042380, 0.00018797, 0.04240600],\n[\"roma\", 0.00042299, 0.00015038, 0.26522000],\n[\"prisoners\", 0.00042299, 0.00015038, 0.09167000],\n[\"take\", 0.00042278, 0.00133459, 0.17778000],\n[\"dear\", 0.00041903, 0.00024436, 0.05192400],\n[\"here\", 0.00041843, 0.00186090, 0.13236000],\n[\"being\", 0.00041419, 0.00165414, 0.43106000],\n[\"involved\", 0.00040751, 0.00037594, 0.09075900],\n[\"position\", 0.00040751, 0.00037594, 0.13326000],\n[\"still\", 0.00040713, 0.00073308, 0.28810000],\n[\"politics\", 0.00040088, 0.00026316, 0.32770000],\n[\"budget\", 0.00039852, 0.00043233, 0.19639000],\n[\"act\", 0.00039587, 0.00046992, 0.15614000],\n[\"don\", 0.00039436, 0.00152256, 0.31144000],\n[\"remind\", 0.00039288, 0.00007519, 0.03341400],\n[\"decrees\", 0.00039288, 0.00007519, 0.08392600],\n[\"mexico\", 0.00039288, 0.00007519, 0.15940000],\n[\"greek\", 0.00039288, 0.00007519, 0.03689900],\n[\"florenz\", 0.00039288, 0.00007519, 0.02522900],\n[\"belarus\", 0.00039288, 0.00007519, 0.15940000],\n[\"journalists\", 0.00039288, 0.00007519, 0.09591000],\n[\"bosnia\", 0.00039288, 0.00007519, 0.08988100],\n[\"ultimately\", 0.00039288, 0.00007519, 0.02715500],\n[\"langen\", 0.00039288, 0.00007519, 0.05544100],\n[\"violations\", 0.00039288, 0.00007519, 0.06813000],\n[\"quickly\", 0.00038808, 0.00028195, 0.15480000],\n[\"globalisation\", 0.00038628, 0.00020677, 0.28176000],\n[\"entities\", 0.00038628, 0.00020677, 0.25151000],\n[\"direction\", 0.00038628, 0.00020677, 0.02494300],\n[\"economic\", 0.00038540, 0.00107143, 0.53376000],\n[\"help\", 0.00038204, 0.00080827, 0.24730000],\n[\"live\", 0.00037877, 0.00030075, 0.13346000],\n[\"haven\", 0.00037877, 0.00030075, 0.18950000],\n[\"israel\", 0.00037877, 0.00030075, 0.66719000],\n[\"good\", 0.00037744, 0.00140977, 0.22628000],\n[\"would\", 0.00037249, 0.00323308, 0.29239000],\n[\"area\", 0.00036457, 0.00063910, 0.13225000],\n[\"partners\", 0.00036366, 0.00022556, 0.25846000],\n[\"internet\", 0.00036295, 0.00035714, 0.24287000],\n[\"presidency\", 0.00036151, 0.00060150, 0.24366000],\n[\"difficult\", 0.00036015, 0.00058271, 0.25790000],\n[\"everything\", 0.00036015, 0.00037594, 0.22185000],\n[\"immediately\", 0.00035944, 0.00016917, 0.06266200],\n[\"application\", 0.00035944, 0.00016917, 0.16907000],\n[\"implement\", 0.00035944, 0.00016917, 0.07810300],\n[\"developments\", 0.00035944, 0.00016917, 0.04401100],\n[\"suffering\", 0.00035944, 0.00016917, 0.10158000],\n[\"quite\", 0.00035892, 0.00056391, 0.11396000],\n[\"not\", 0.00035808, 0.00601504, 0.48961000],\n[\"they\", 0.00035570, 0.00488722, 0.65931000],\n[\"achieve\", 0.00035544, 0.00046992, 0.32708000],\n[\"none\", 0.00034976, 0.00013158, 0.05371500],\n[\"assume\", 0.00034976, 0.00013158, 0.04553600],\n[\"decisive\", 0.00034976, 0.00013158, 0.08279500],\n[\"accounts\", 0.00034976, 0.00013158, 0.08787400],\n[\"hasn\", 0.00034879, 0.00024436, 0.10585000],\n[\"burden\", 0.00034879, 0.00024436, 0.17489000]\n]\n}\n\nowvt = {\n\"title\": \"ORG (written) vs. SITR (written)\",\n\"terms\": [\n[\"and\", 0.00960090, 0.03562200, 0.00224550],\n[\"eu\", 0.00692414, 0.00488063, 0.00043077],\n[\"to\", 0.00623391, 0.04048055, 0.02807700],\n[\"uk\", 0.00368134, 0.00086129, 0.00006078],\n[\"sri\", 0.00356908, 0.00068461, 0.01355400],\n[\"but\", 0.00310011, 0.00483647, 0.00122370],\n[\"on\", 0.00257630, 0.01020295, 0.13891000],\n[\"lanka\", 0.00241777, 0.00046377, 0.01519500],\n[\"ltte\", 0.00218750, 0.00041960, 0.05155200],\n[\"britain\", 0.00196322, 0.00050794, 0.00232440],\n[\"by\", 0.00191546, 0.00583026, 0.01039500],\n[\"'s\", 0.00184886, 0.00373225, 0.04232300],\n[\"capital\", 0.00181136, 0.00055211, 0.02766000],\n[\"member\", 0.00177253, 0.00320223, 0.11940000],\n[\"across\", 0.00174368, 0.00059628, 0.00285810],\n[\"debt\", 0.00174368, 0.00059628, 0.05600200],\n[\"mrls\", 0.00172698, 0.00033126, 0.15962000],\n[\"those\", 0.00169945, 0.00178883, 0.02922700],\n[\"its\", 0.00166869, 0.00278262, 0.02764400],\n[\"british\", 0.00165240, 0.00044169, 0.00280400],\n[\"schengen\", 0.00162173, 0.00050794, 0.07640100],\n[\"children\", 0.00156147, 0.00092754, 0.07471200],\n[\"sovereign\", 0.00155004, 0.00041960, 0.00406740],\n[\"welcome\", 0.00149580, 0.00099379, 0.00991630],\n[\"visa\", 0.00146314, 0.00057419, 0.11699000],\n[\"trading\", 0.00144839, 0.00039752, 0.00459020],\n[\"some\", 0.00143826, 0.00189925, 0.01402800],\n[\"health\", 0.00141765, 0.00081712, 0.22798000],\n[\"may\", 0.00139295, 0.00117047, 0.00598600],\n[\"bank\", 0.00139253, 0.00050794, 0.00616290],\n[\"review\", 0.00138158, 0.00026501, 0.00145920],\n[\"e-money\", 0.00138158, 0.00026501, 0.08895800],\n[\"tamil\", 0.00138158, 0.00026501, 0.10616000],\n[\"timber\", 0.00138158, 0.00026501, 0.13994000],\n[\"travel\", 0.00138111, 0.00055211, 0.10882000],\n[\"membership\", 0.00134752, 0.00037543, 0.01217800],\n[\"cut\", 0.00134752, 0.00037543, 0.02324800],\n[\"economies\", 0.00134752, 0.00037543, 0.00539170],\n[\"when\", 0.00130412, 0.00207593, 0.03304900],\n[\"systems\", 0.00127979, 0.00064045, 0.03040200],\n[\"electricity\", 0.00126645, 0.00024293, 0.00976480],\n[\"profiling\", 0.00126645, 0.00024293, 0.15962000],\n[\"eurozone\", 0.00126645, 0.00024293, 0.02058800],\n[\"death\", 0.00126645, 0.00024293, 0.00168400],\n[\"ireland\", 0.00121982, 0.00050794, 0.12647000],\n[\"where\", 0.00120641, 0.00119255, 0.05085300],\n[\"own\", 0.00117263, 0.00145756, 0.09212000],\n[\"such\", 0.00117124, 0.00192134, 0.03242800],\n[\"legislation\", 0.00115758, 0.00072878, 0.05764000],\n[\"lankan\", 0.00115132, 0.00022084, 0.01815600],\n[\"imf\", 0.00115132, 0.00022084, 0.01110900],\n[\"kingdom\", 0.00115132, 0.00022084, 0.00803850],\n[\"islamic\", 0.00115132, 0.00022084, 0.01893200],\n[\"firm\", 0.00115132, 0.00022084, 0.00130560],\n[\"england\", 0.00115132, 0.00022084, 0.00285080],\n[\"beef\", 0.00115132, 0.00022084, 0.11243000],\n[\"wales\", 0.00115132, 0.00022084, 0.05193700],\n[\"while\", 0.00114933, 0.00083920, 0.01268200],\n[\"their\", 0.00111230, 0.00335682, 0.14261000],\n[\"needs\", 0.00109674, 0.00094963, 0.00150940],\n[\"so\", 0.00109316, 0.00249553, 0.20793000],\n[\"system\", 0.00107999, 0.00139131, 0.08261500],\n[\"support\", 0.00107772, 0.00165632, 0.04740600],\n[\"arrest\", 0.00105045, 0.00030918, 0.01384800],\n[\"could\", 0.00104805, 0.00117047, 0.11704000],\n[\"regime\", 0.00103619, 0.00019876, 0.01048500],\n[\"commit\", 0.00103619, 0.00019876, 0.02662400],\n[\"banking\", 0.00103619, 0.00019876, 0.02058300],\n[\"warrant\", 0.00103619, 0.00019876, 0.00978190],\n[\"crimes\", 0.00103619, 0.00019876, 0.01799500],\n[\"minor\", 0.00103619, 0.00019876, 0.07386800],\n[\"israel\", 0.00102180, 0.00081712, 0.06791000],\n[\"between\", 0.00101499, 0.00103796, 0.03237100],\n[\"public\", 0.00099579, 0.00088337, 0.08658200],\n[\"consumers\", 0.00098930, 0.00064045, 0.15580000],\n[\"asylum\", 0.00098560, 0.00044169, 0.16540000],\n[\"young\", 0.00098560, 0.00044169, 0.08878400],\n[\"states\", 0.00098071, 0.00311389, 0.20279000],\n[\"farmers\", 0.00097099, 0.00057419, 0.09895200],\n[\"aid\", 0.00093470, 0.00046377, 0.05410000],\n[\"humanitarian\", 0.00093470, 0.00046377, 0.05648100],\n[\"full\", 0.00092716, 0.00061836, 0.02685700],\n[\"indeed\", 0.00092716, 0.00061836, 0.07214400],\n[\"extra\", 0.00092105, 0.00017667, 0.00394070],\n[\"refused\", 0.00092105, 0.00017667, 0.02245600],\n[\"poorest\", 0.00092105, 0.00017667, 0.00748940],\n[\"laboratory\", 0.00092105, 0.00017667, 0.15962000],\n[\"general\", 0.00090591, 0.00055211, 0.05304200],\n[\"eastern\", 0.00089974, 0.00033126, 0.12326000],\n[\"price\", 0.00089499, 0.00037543, 0.00597400],\n[\"mechanism\", 0.00089499, 0.00037543, 0.04070400],\n[\"countries\", 0.00087946, 0.00178883, 0.20607000],\n[\"workers\", 0.00087294, 0.00070670, 0.08853200],\n[\"real\", 0.00086604, 0.00050794, 0.01130000],\n[\"they\", 0.00086499, 0.00379850, 0.19935000],\n[\"care\", 0.00086318, 0.00044169, 0.09461300],\n[\"his\", 0.00086275, 0.00099379, 0.05980600],\n[\"liberal\", 0.00085809, 0.00026501, 0.03825300],\n[\"both\", 0.00082468, 0.00088337, 0.08190000],\n[\"years\", 0.00081570, 0.00143548, 0.15359000],\n[\"looks\", 0.00080592, 0.00015459, 0.00738310],\n[\"vis\", 0.00080592, 0.00015459, 0.15962000],\n[\"commend\", 0.00080592, 0.00015459, 0.02372400],\n[\"underlying\", 0.00080592, 0.00015459, 0.00472790],\n[\"gay\", 0.00080592, 0.00015459, 0.15962000],\n[\"race\", 0.00080592, 0.00015459, 0.03034500],\n[\"operating\", 0.00080592, 0.00015459, 0.00474870],\n[\"terrible\", 0.00080592, 0.00015459, 0.01336400],\n[\"common\", 0.00077034, 0.00090546, 0.20545000],\n[\"reduce\", 0.00076404, 0.00024293, 0.01515700],\n[\"fiscal\", 0.00076404, 0.00024293, 0.01613300],\n[\"most\", 0.00076289, 0.00106005, 0.19334000],\n[\"agency\", 0.00076221, 0.00037543, 0.18557000],\n[\"forward\", 0.00075506, 0.00068461, 0.07918900],\n[\"justice\", 0.00074661, 0.00055211, 0.09529300],\n[\"vital\", 0.00073920, 0.00033126, 0.01723900],\n[\"long-term\", 0.00073157, 0.00028710, 0.01080000],\n[\"recognise\", 0.00072400, 0.00039752, 0.04702100],\n[\"or\", 0.00069890, 0.00324639, 0.47882000],\n[\"used\", 0.00069223, 0.00070670, 0.04066400],\n[\"markets\", 0.00069223, 0.00070670, 0.08073800],\n[\"any\", 0.00069101, 0.00136923, 0.05404300],\n[\"shadows\", 0.00069079, 0.00013251, 0.00958950],\n[\"deliver\", 0.00069079, 0.00013251, 0.01512500],\n[\"suspect\", 0.00069079, 0.00013251, 0.07565400],\n[\"conduct\", 0.00069079, 0.00013251, 0.00917600],\n[\"recession\", 0.00069079, 0.00013251, 0.02585600],\n[\"families\", 0.00069079, 0.00013251, 0.01829000],\n[\"excuse\", 0.00069079, 0.00013251, 0.01014300],\n[\"poor\", 0.00069079, 0.00013251, 0.01835500],\n[\"glad\", 0.00069079, 0.00013251, 0.04595600],\n[\"london\", 0.00069079, 0.00013251, 0.00815520],\n[\"fee\", 0.00069079, 0.00013251, 0.06084100],\n[\"sadly\", 0.00069079, 0.00013251, 0.03773700],\n[\"irish\", 0.00069054, 0.00035335, 0.13403000],\n[\"the\", 0.00069008, 0.07775888, 0.37829000],\n[\"world\", 0.00067480, 0.00108213, 0.09473000],\n[\"secure\", 0.00067167, 0.00022084, 0.03283900],\n[\"seeking\", 0.00067167, 0.00022084, 0.04644800],\n[\"macedonia\", 0.00067167, 0.00022084, 0.17389000],\n[\"banks\", 0.00066897, 0.00057419, 0.11501000],\n[\"operators\", 0.00066364, 0.00030918, 0.10097000],\n[\"access\", 0.00065659, 0.00046377, 0.03402100],\n[\"agenda\", 0.00065659, 0.00046377, 0.15424000],\n[\"framework\", 0.00064998, 0.00064045, 0.12441000],\n[\"was\", 0.00064596, 0.00282679, 0.17714000],\n[\"jobs\", 0.00064553, 0.00066253, 0.15948000],\n[\"interest\", 0.00064279, 0.00048585, 0.09284600],\n[\"money\", 0.00062804, 0.00090546, 0.10613000],\n[\"services\", 0.00062237, 0.00053002, 0.07822900],\n[\"fair\", 0.00061476, 0.00055211, 0.07082300],\n[\"standards\", 0.00059885, 0.00061836, 0.15451000],\n[\"global\", 0.00059885, 0.00061836, 0.09567500],\n[\"more\", 0.00059593, 0.00293721, 0.20248000],\n[\"benefits\", 0.00059052, 0.00035335, 0.10176000],\n[\"economy\", 0.00058983, 0.00068461, 0.09245500],\n[\"told\", 0.00058982, 0.00028710, 0.00733570],\n[\"cooperation\", 0.00058632, 0.00072878, 0.33848000],\n[\"work\", 0.00058551, 0.00145756, 0.19123000],\n[\"get\", 0.00058425, 0.00077295, 0.09034500],\n[\"use\", 0.00058365, 0.00079504, 0.12336000],\n[\"commitments\", 0.00058123, 0.00019876, 0.03432900],\n[\"month\", 0.00058123, 0.00019876, 0.02528100],\n[\"equivalent\", 0.00058123, 0.00019876, 0.07688000],\n[\"northern\", 0.00058123, 0.00019876, 0.15202000],\n[\"whilst\", 0.00058123, 0.00019876, 0.06963000],\n[\"lukashenko\", 0.00058123, 0.00019876, 0.14499000],\n[\"many\", 0.00058107, 0.00174466, 0.24745000],\n[\"third\", 0.00057580, 0.00048585, 0.12276000],\n[\"everybody\", 0.00057566, 0.00011042, 0.01887000],\n[\"clarity\", 0.00057566, 0.00011042, 0.05418700],\n[\"chain\", 0.00057566, 0.00011042, 0.01899500],\n[\"lastly\", 0.00057566, 0.00011042, 0.01284000],\n[\"maybe\", 0.00057566, 0.00011042, 0.01663300],\n[\"investments\", 0.00057566, 0.00011042, 0.01823900],\n[\"frankly\", 0.00057566, 0.00011042, 0.01601000],\n[\"post\", 0.00057566, 0.00011042, 0.01450900],\n[\"rate\", 0.00057566, 0.00011042, 0.01515300],\n[\"failing\", 0.00057033, 0.00024293, 0.04582000],\n[\"seek\", 0.00057033, 0.00024293, 0.00887600],\n[\"medicines\", 0.00057033, 0.00024293, 0.20931000],\n[\"short-term\", 0.00057033, 0.00024293, 0.03125600],\n[\"over\", 0.00056441, 0.00123672, 0.19464000],\n[\"credit\", 0.00055205, 0.00030918, 0.10260000],\n[\"resources\", 0.00055205, 0.00030918, 0.15391000],\n[\"under\", 0.00054872, 0.00103796, 0.19014000],\n[\"change\", 0.00054461, 0.00097171, 0.24638000],\n[\"less\", 0.00053934, 0.00041960, 0.09825200],\n[\"come\", 0.00053866, 0.00081712, 0.09809300],\n[\"state\", 0.00053784, 0.00134714, 0.08044600],\n[\"an\", 0.00052796, 0.00408560, 0.34540000],\n[\"animal\", 0.00052617, 0.00033126, 0.43848000],\n[\"them\", 0.00052369, 0.00154590, 0.40272000],\n[\"proposed\", 0.00052126, 0.00046377, 0.07103600],\n[\"attacks\", 0.00051791, 0.00026501, 0.07841600],\n[\"belarus\", 0.00051791, 0.00026501, 0.27334000],\n[\"colleagues\", 0.00051791, 0.00026501, 0.05888900],\n[\"gaza\", 0.00050968, 0.00050794, 0.23557000],\n[\"products\", 0.00050748, 0.00035335, 0.31976000],\n[\"since\", 0.00050554, 0.00053002, 0.08439400],\n[\"out\", 0.00050464, 0.00167841, 0.26686000],\n[\"there\", 0.00049653, 0.00430644, 0.25915000],\n[\"rules\", 0.00049601, 0.00061836, 0.30057000],\n[\"labour\", 0.00049351, 0.00037543, 0.07335200],\n[\"stability\", 0.00049351, 0.00037543, 0.12922000],\n[\"cuba\", 0.00049302, 0.00017667, 0.22124000],\n[\"discipline\", 0.00049302, 0.00017667, 0.05298300],\n[\"relations\", 0.00049302, 0.00017667, 0.10779000],\n[\"sources\", 0.00049302, 0.00017667, 0.05298700],\n[\"record\", 0.00049302, 0.00017667, 0.09184600],\n[\"turkish\", 0.00049302, 0.00017667, 0.07753500],\n[\"compromises\", 0.00049302, 0.00017667, 0.13970000],\n[\"regret\", 0.00049302, 0.00017667, 0.07353600],\n[\"alde\", 0.00049302, 0.00017667, 0.09756400],\n[\"welfare\", 0.00049280, 0.00022084, 0.38266000],\n[\"patients\", 0.00049280, 0.00022084, 0.23850000],\n[\"projects\", 0.00049280, 0.00022084, 0.10579000],\n[\"urge\", 0.00048549, 0.00028710, 0.08580200],\n[\"regarding\", 0.00048549, 0.00028710, 0.09579900],\n[\"europol\", 0.00048549, 0.00028710, 0.30561000],\n[\"businesses\", 0.00048283, 0.00039752, 0.17997000],\n[\"government\", 0.00047919, 0.00112630, 0.10428000],\n[\"financial\", 0.00046883, 0.00136923, 0.20056000],\n[\"food\", 0.00046804, 0.00044169, 0.16545000],\n[\"he\", 0.00046716, 0.00099379, 0.29353000],\n[\"lives\", 0.00046358, 0.00030918, 0.13064000],\n[\"join\", 0.00046358, 0.00030918, 0.08651700],\n[\"address\", 0.00046358, 0.00030918, 0.05182900],\n[\"pay\", 0.00046358, 0.00030918, 0.14578000],\n[\"civilians\", 0.00046358, 0.00030918, 0.09292500],\n[\"dimension\", 0.00046053, 0.00008834, 0.02648400],\n[\"deaths\", 0.00046053, 0.00008834, 0.06614400],\n[\"helping\", 0.00046053, 0.00008834, 0.04280800],\n[\"s\", 0.00046053, 0.00008834, 0.10251000],\n[\"solvency\", 0.00046053, 0.00008834, 0.09885700],\n[\"professionals\", 0.00046053, 0.00008834, 0.15962000],\n[\"business\", 0.00045339, 0.00053002, 0.16599000],\n[\"look\", 0.00044866, 0.00066253, 0.11425000],\n[\"powers\", 0.00044809, 0.00024293, 0.15572000],\n[\"expected\", 0.00044809, 0.00024293, 0.09303600],\n[\"practices\", 0.00044809, 0.00024293, 0.08129600],\n[\"coming\", 0.00044809, 0.00024293, 0.01714900],\n[\"investment\", 0.00044809, 0.00024293, 0.03333700],\n[\"confidence\", 0.00044809, 0.00024293, 0.03762300],\n[\"past\", 0.00044797, 0.00033126, 0.06629100],\n[\"un\", 0.00044797, 0.00033126, 0.08095200],\n[\"value\", 0.00043647, 0.00035335, 0.10649000],\n[\"might\", 0.00043647, 0.00035335, 0.03910600],\n[\"partnership\", 0.00043647, 0.00035335, 0.19236000],\n[\"week\", 0.00042782, 0.00037543, 0.07779300]\n]\n}\n\nosvow = {\n\"title\": \"ORG (spoken) vs. ORG (written)\",\n\"terms\": [\n[\"euh\", 0.09633409, 0.02102153, 0.00000000],\n[\"you\", 0.02140486, 0.00972162, 0.00000000],\n[\"'ve\", 0.01855840, 0.00362672, 0.00000000],\n[\"'t\", 0.01569518, 0.00345881, 0.00000000],\n[\"we\", 0.01484792, 0.02082004, 0.00000864],\n[\"i\", 0.01264441, 0.01811679, 0.00000189],\n[\"that\", 0.01224740, 0.02709963, 0.00000829],\n[\"thank\", 0.01148094, 0.00401289, 0.00000000],\n[\"'re\", 0.01109373, 0.00236744, 0.00000000],\n[\"'s\", 0.01061868, 0.00899963, 0.00000152],\n[\"'m\", 0.00746077, 0.00147755, 0.00000000],\n[\"think\", 0.00717772, 0.00369388, 0.00000050],\n[\"don\", 0.00621711, 0.00125928, 0.00000000],\n[\"this\", 0.00587547, 0.01304611, 0.00059879],\n[\"very\", 0.00563114, 0.00500353, 0.00008040],\n[\"about\", 0.00476960, 0.00413043, 0.00003830],\n[\"'d\", 0.00409951, 0.00085631, 0.00000002],\n[\"hum\", 0.00369391, 0.00092347, 0.00001696],\n[\"because\", 0.00310904, 0.00287115, 0.00011263],\n[\"want\", 0.00307503, 0.00223312, 0.00057311],\n[\"'ll\", 0.00306671, 0.00062124, 0.00000064],\n[\"she\", 0.00301866, 0.00082273, 0.03661300],\n[\"and\", 0.00301455, 0.03776151, 0.12378000],\n[\"iraq\", 0.00285131, 0.00048692, 0.15954000],\n[\"got\", 0.00275224, 0.00080594, 0.00000716],\n[\"it\", 0.00263665, 0.01314685, 0.08638600],\n[\"at\", 0.00262916, 0.00493636, 0.02568800],\n[\"so\", 0.00248249, 0.00396252, 0.00379450],\n[\"but\", 0.00235001, 0.00634675, 0.03569600],\n[\"know\", 0.00223549, 0.00152792, 0.00055865],\n[\"what\", 0.00220259, 0.00379462, 0.02912100],\n[\"our\", 0.00208613, 0.00505390, 0.07023200],\n[\"say\", 0.00200169, 0.00172941, 0.00086378],\n[\"had\", 0.00198240, 0.00174620, 0.00303480],\n[\"here\", 0.00196746, 0.00157829, 0.00201660],\n[\"important\", 0.00193871, 0.00181336, 0.00719570],\n[\"people\", 0.00185406, 0.00372746, 0.08619100],\n[\"terms\", 0.00173362, 0.00080594, 0.00284980],\n[\"yes\", 0.00172380, 0.00047013, 0.00331470],\n[\"ow\", 0.00167146, 0.00028544, 0.15954000],\n[\"your\", 0.00165132, 0.00115853, 0.01135400],\n[\"just\", 0.00159858, 0.00189731, 0.02235900],\n[\"all\", 0.00158511, 0.00465093, 0.09555000],\n[\"isn\", 0.00156228, 0.00030223, 0.00096069],\n[\"evening\", 0.00154635, 0.00028544, 0.00069755],\n[\"actually\", 0.00153624, 0.00125928, 0.02904800],\n[\"hm\", 0.00148506, 0.00033581, 0.00565710],\n[\"together\", 0.00142870, 0.00078915, 0.01041100],\n[\"house\", 0.00138741, 0.00105779, 0.01101400],\n[\"course\", 0.00136894, 0.00146076, 0.06251700],\n[\"things\", 0.00135968, 0.00062124, 0.00628620],\n[\"feed\", 0.00135183, 0.00050371, 0.02554300],\n[\"parliament\", 0.00132912, 0.00241781, 0.14269000],\n[\"look\", 0.00131865, 0.00136002, 0.04925800],\n[\"much\", 0.00129427, 0.00194768, 0.02192300],\n[\"gonna\", 0.00128514, 0.00023506, 0.00371930],\n[\"cod\", 0.00127817, 0.00021827, 0.15954000],\n[\"they\", 0.00125688, 0.00463414, 0.08616100],\n[\"doesn\", 0.00123565, 0.00025186, 0.00079774],\n[\"colleagues\", 0.00119095, 0.00080594, 0.00503380],\n[\"well\", 0.00117644, 0.00169583, 0.04906800],\n[\"back\", 0.00116608, 0.00110816, 0.00657190],\n[\"v\", 0.00115920, 0.00020148, 0.05599000],\n[\"pacific\", 0.00115920, 0.00020148, 0.11441000],\n[\"reporting\", 0.00114569, 0.00021827, 0.02038900],\n[\"issue\", 0.00114178, 0.00112495, 0.02611600],\n[\"me\", 0.00114166, 0.00112495, 0.02004500],\n[\"particularly\", 0.00112747, 0.00095705, 0.02402900],\n[\"w\", 0.00112104, 0.00021827, 0.03731300],\n[\"car\", 0.00112104, 0.00021827, 0.01927500],\n[\"f\", 0.00110605, 0.00020148, 0.04316300],\n[\"big\", 0.00109218, 0.00048692, 0.02509900],\n[\"emas\", 0.00108153, 0.00018469, 0.08251700],\n[\"fourty\", 0.00108153, 0.00018469, 0.01143400],\n[\"didn\", 0.00107803, 0.00021827, 0.00119650],\n[\"report\", 0.00105981, 0.00213238, 0.14089000],\n[\"misses\", 0.00104605, 0.00031902, 0.00596590],\n[\"whole\", 0.00102287, 0.00077236, 0.02984400],\n[\"going\", 0.00101139, 0.00094026, 0.01373700],\n[\"can\", 0.00100714, 0.00335807, 0.13918000],\n[\"wasn\", 0.00100440, 0.00020148, 0.00319530],\n[\"looking\", 0.00100335, 0.00067161, 0.04127700],\n[\"commissioner\", 0.00099902, 0.00179657, 0.06215700],\n[\"pcbs\", 0.00098321, 0.00016790, 0.10350000],\n[\"was\", 0.00097989, 0.00347560, 0.10372000],\n[\"somebody\", 0.00097963, 0.00018469, 0.00296020],\n[\"perhaps\", 0.00095137, 0.00077236, 0.02477400],\n[\"t\", 0.00094234, 0.00018469, 0.02061700],\n[\"debates\", 0.00094234, 0.00018469, 0.00620460],\n[\"now\", 0.00091925, 0.00292152, 0.18000000],\n[\"m\", 0.00089684, 0.00016790, 0.03233700],\n[\"debate\", 0.00089486, 0.00119212, 0.03304300],\n[\"committee\", 0.00088985, 0.00136002, 0.13202000],\n[\"work\", 0.00088841, 0.00201484, 0.13383000],\n[\"really\", 0.00088715, 0.00099063, 0.03063000],\n[\"cause\", 0.00088166, 0.00033581, 0.03076600],\n[\"if\", 0.00088070, 0.00305584, 0.10138000],\n[\"working\", 0.00086555, 0.00073878, 0.05344600],\n[\"were\", 0.00085258, 0.00157829, 0.15017000],\n[\"point\", 0.00081658, 0.00100742, 0.06185900],\n[\"sure\", 0.00080547, 0.00068840, 0.05025400],\n[\"go\", 0.00080083, 0.00097384, 0.11144000],\n[\"get\", 0.00079965, 0.00124249, 0.02846200],\n[\"there\", 0.00079143, 0.00485241, 0.35193000],\n[\"those\", 0.00078886, 0.00230028, 0.09897500],\n[\"coming\", 0.00078602, 0.00062124, 0.03293400],\n[\"copyright\", 0.00077520, 0.00015111, 0.10797000],\n[\"into\", 0.00075835, 0.00196447, 0.20363000],\n[\"give\", 0.00075454, 0.00072199, 0.06712900],\n[\"p\", 0.00074833, 0.00013432, 0.00264070],\n[\"referendums\", 0.00074833, 0.00013432, 0.04047600],\n[\"question\", 0.00074557, 0.00077236, 0.10911000],\n[\"who\", 0.00074465, 0.00283757, 0.08520800],\n[\"thing\", 0.00073032, 0.00038618, 0.06339800],\n[\"good\", 0.00072687, 0.00115853, 0.07400800],\n[\"some\", 0.00071198, 0.00236744, 0.43026000],\n[\"referendum\", 0.00071107, 0.00050371, 0.24000000],\n[\"pleased\", 0.00070999, 0.00033581, 0.04711600],\n[\"doha\", 0.00070405, 0.00013432, 0.05987200],\n[\"tonight\", 0.00070109, 0.00040297, 0.11332000],\n[\"documents\", 0.00070077, 0.00015111, 0.13042000],\n[\"morning\", 0.00069123, 0.00028544, 0.02571700],\n[\"indeed\", 0.00066840, 0.00100742, 0.02679100],\n[\"won\", 0.00065535, 0.00015111, 0.00471150],\n[\"last\", 0.00065065, 0.00125928, 0.03806300],\n[\"o\", 0.00064154, 0.00021827, 0.18245000],\n[\"trying\", 0.00064011, 0.00038618, 0.02052600],\n[\"anti-discrimination\", 0.00063498, 0.00011753, 0.03531100],\n[\"tell\", 0.00063399, 0.00026865, 0.02286900],\n[\"regard\", 0.00063027, 0.00041976, 0.16020000],\n[\"moment\", 0.00062934, 0.00050371, 0.06180300],\n[\"syria\", 0.00061799, 0.00013432, 0.13214000],\n[\"previous\", 0.00061092, 0.00013432, 0.01125800],\n[\"lot\", 0.00060867, 0.00047013, 0.01996700],\n[\"hearing\", 0.00060823, 0.00011753, 0.01049700],\n[\"my\", 0.00060135, 0.00256892, 0.16913000],\n[\"fraud\", 0.00059660, 0.00011753, 0.15954000],\n[\"approval\", 0.00059660, 0.00011753, 0.01470700],\n[\"consideration\", 0.00058590, 0.00011753, 0.01518500],\n[\"irish\", 0.00058563, 0.00067161, 0.36750000],\n[\"treaty\", 0.00057796, 0.00105779, 0.38244000],\n[\"parliaments\", 0.00057151, 0.00025186, 0.04652100],\n[\"talking\", 0.00056937, 0.00033581, 0.01162100],\n[\"find\", 0.00056786, 0.00058766, 0.11860000],\n[\"happy\", 0.00056522, 0.00020148, 0.03693300],\n[\"proposal\", 0.00056239, 0.00114174, 0.16646000],\n[\"putting\", 0.00055298, 0.00028544, 0.03176300],\n[\"british\", 0.00055204, 0.00075557, 0.15419000],\n[\"process\", 0.00054587, 0.00070519, 0.20001000],\n[\"where\", 0.00054505, 0.00154471, 0.24447000],\n[\"different\", 0.00054476, 0.00065482, 0.28669000],\n[\"please\", 0.00054440, 0.00031902, 0.07251300],\n[\"introduce\", 0.00054256, 0.00011753, 0.01354600],\n[\"saying\", 0.00052678, 0.00043655, 0.03568700],\n[\"n\", 0.00052486, 0.00010074, 0.01934700],\n[\"syrian\", 0.00051748, 0.00018469, 0.23235000],\n[\"haven\", 0.00051615, 0.00011753, 0.01961100],\n[\"r\", 0.00051595, 0.00018469, 0.10157000],\n[\"negotiate\", 0.00051297, 0.00010074, 0.01176600],\n[\"aren\", 0.00051297, 0.00010074, 0.01742100],\n[\"damage\", 0.00051293, 0.00018469, 0.02896300],\n[\"ratification\", 0.00050998, 0.00018469, 0.04152000],\n[\"already\", 0.00050993, 0.00053729, 0.08866500],\n[\"property\", 0.00050569, 0.00018469, 0.07145700],\n[\"said\", 0.00050335, 0.00104100, 0.09534600],\n[\"couldn\", 0.00050220, 0.00010074, 0.02641700],\n[\"again\", 0.00050164, 0.00092347, 0.06917800],\n[\"bit\", 0.00049841, 0.00033581, 0.05331200],\n[\"feel\", 0.00049211, 0.00030223, 0.05013400],\n[\"companies\", 0.00049098, 0.00055408, 0.14581000],\n[\"something\", 0.00048743, 0.00050371, 0.09667500],\n[\"talk\", 0.00048076, 0.00030223, 0.09304000],\n[\"minister\", 0.00047877, 0.00047013, 0.12789000],\n[\"pointed\", 0.00047495, 0.00010074, 0.00995720],\n[\"chair\", 0.00046571, 0.00021827, 0.02603900],\n[\"shouldn\", 0.00046409, 0.00011753, 0.01487700],\n[\"re\", 0.00045993, 0.00010074, 0.02425800],\n[\"let\", 0.00045911, 0.00080594, 0.13327000],\n[\"ha\", 0.00045313, 0.00010074, 0.03224400],\n[\"see\", 0.00045310, 0.00130965, 0.17785000],\n[\"getting\", 0.00045261, 0.00031902, 0.04547400],\n[\"issues\", 0.00045253, 0.00087310, 0.21956000],\n[\"corporate\", 0.00044925, 0.00016790, 0.08274700],\n[\"hear\", 0.00044804, 0.00040297, 0.03771700],\n[\"place\", 0.00044592, 0.00082273, 0.10003000],\n[\"legislation\", 0.00044464, 0.00100742, 0.09331700],\n[\"interesting\", 0.00044399, 0.00016790, 0.04159900],\n[\"mechanisms\", 0.00044146, 0.00016790, 0.06627600],\n[\"doing\", 0.00043747, 0.00055408, 0.15853000],\n[\"relation\", 0.00043464, 0.00036939, 0.07493300],\n[\"times\", 0.00043270, 0.00036939, 0.08097800],\n[\"ought\", 0.00042453, 0.00010074, 0.04648300],\n[\"him\", 0.00042157, 0.00033581, 0.12452000],\n[\"worked\", 0.00042062, 0.00033581, 0.18668000],\n[\"laid\", 0.00041850, 0.00008395, 0.02876500],\n[\"th\", 0.00041850, 0.00008395, 0.01634300],\n[\"programs\", 0.00041850, 0.00008395, 0.02360000],\n[\"weren\", 0.00041850, 0.00008395, 0.03443300],\n[\"seen\", 0.00041778, 0.00047013, 0.18235000],\n[\"maybe\", 0.00041076, 0.00030223, 0.05281100],\n[\"ireland\", 0.00040883, 0.00075557, 0.21383000],\n[\"engage\", 0.00040874, 0.00008395, 0.05462800],\n[\"wouldn\", 0.00040874, 0.00008395, 0.01550600],\n[\"complex\", 0.00040874, 0.00008395, 0.02358000],\n[\"delighted\", 0.00040655, 0.00020148, 0.04400500],\n[\"man\", 0.00040472, 0.00020148, 0.13691000],\n[\"also\", 0.00040453, 0.00282078, 0.48669000],\n[\"her\", 0.00040236, 0.00043655, 0.35098000],\n[\"steps\", 0.00040224, 0.00010074, 0.00911790],\n[\"traditional\", 0.00039991, 0.00008395, 0.03912400],\n[\"attitude\", 0.00039991, 0.00008395, 0.05296500],\n[\"traffic\", 0.00039991, 0.00008395, 0.04128600],\n[\"regulate\", 0.00039991, 0.00008395, 0.02987900],\n[\"organisations\", 0.00039836, 0.00023506, 0.30728000],\n[\"side\", 0.00039708, 0.00026865, 0.12711000],\n[\"done\", 0.00039524, 0.00095705, 0.17565000],\n[\"session\", 0.00039185, 0.00008395, 0.01329000],\n[\"prove\", 0.00039185, 0.00008395, 0.01411600],\n[\"bring\", 0.00039032, 0.00060445, 0.15287000],\n[\"us\", 0.00038876, 0.00216596, 0.28295000],\n[\"program\", 0.00038445, 0.00008395, 0.05644400],\n[\"aspect\", 0.00038445, 0.00008395, 0.04174500],\n[\"vat\", 0.00038328, 0.00015111, 0.09417700],\n[\"heard\", 0.00038327, 0.00040297, 0.08657100],\n[\"food\", 0.00038325, 0.00067161, 0.29133000],\n[\"implications\", 0.00038214, 0.00015111, 0.08327400],\n[\"covered\", 0.00037879, 0.00015111, 0.09390100],\n[\"minutes\", 0.00037879, 0.00015111, 0.07411900],\n[\"room\", 0.00037770, 0.00015111, 0.03297600],\n[\"forward\", 0.00037671, 0.00092347, 0.30466000],\n[\"comes\", 0.00037206, 0.00031902, 0.09716900],\n[\"came\", 0.00036525, 0.00028544, 0.10075000],\n[\"making\", 0.00036518, 0.00047013, 0.11632000],\n[\"women\", 0.00036368, 0.00028544, 0.11160000],\n[\"hasn\", 0.00035981, 0.00008395, 0.04191500],\n[\"tha\", 0.00035981, 0.00008395, 0.01643900],\n[\"chamber\", 0.00035630, 0.00025186, 0.10152000],\n[\"local\", 0.00035208, 0.00025186, 0.10303000],\n[\"up\", 0.00035096, 0.00176299, 0.28776000],\n[\"went\", 0.00034832, 0.00018469, 0.07536300],\n[\"absolutely\", 0.00034782, 0.00018469, 0.03060000],\n[\"few\", 0.00034775, 0.00033581, 0.11599000],\n[\"challenges\", 0.00034732, 0.00018469, 0.11891000],\n[\"sometimes\", 0.00034633, 0.00018469, 0.06390600],\n[\"talked\", 0.00034633, 0.00018469, 0.06261300],\n[\"points\", 0.00034566, 0.00038618, 0.09212700],\n[\"beginning\", 0.00034298, 0.00018469, 0.08968000],\n[\"particular\", 0.00034123, 0.00078915, 0.20631000],\n[\"able\", 0.00034086, 0.00078915, 0.24134000],\n[\"context\", 0.00033501, 0.00030223, 0.16236000]\n]\n}\n\nosvi = {\n\"title\": \"ORG (spoken) vs. SITR (spoken)\",\n\"terms\": [\n[\"i\", 0.00691985, 0.01811679, 0.00690470],\n[\"the\", 0.00627184, 0.06612042, 0.07359200],\n[\"of\", 0.00607479, 0.03238860, 0.06737900],\n[\"on\", 0.00470029, 0.00987273, 0.00390810],\n[\"and\", 0.00370189, 0.03776151, 0.05203800],\n[\"our\", 0.00330152, 0.00505390, 0.00909200],\n[\"my\", 0.00325766, 0.00256892, 0.00017945],\n[\"british\", 0.00315225, 0.00075557, 0.00924450],\n[\"feed\", 0.00256161, 0.00050371, 0.00322400],\n[\"iraq\", 0.00247622, 0.00048692, 0.15954000],\n[\"by\", 0.00238901, 0.00359314, 0.00645790],\n[\"that\", 0.00224544, 0.02709963, 0.08061100],\n[\"some\", 0.00221019, 0.00236744, 0.07720800],\n[\"report\", 0.00213053, 0.00213238, 0.03347100],\n[\"work\", 0.00196264, 0.00201484, 0.01405200],\n[\"believe\", 0.00194179, 0.00085631, 0.00235510],\n[\"was\", 0.00192274, 0.00347560, 0.00603850],\n[\"it\", 0.00187846, 0.01314685, 0.13321000],\n[\"irish\", 0.00187670, 0.00067161, 0.02146800],\n[\"food\", 0.00187670, 0.00067161, 0.00891010],\n[\"all\", 0.00187448, 0.00465093, 0.11016000],\n[\"health\", 0.00186025, 0.00075557, 0.04231900],\n[\"their\", 0.00181168, 0.00315659, 0.01448400],\n[\"ireland\", 0.00172099, 0.00075557, 0.00540750],\n[\"she\", 0.00170703, 0.00082273, 0.07769700],\n[\"as\", 0.00168282, 0.00634675, 0.18602000],\n[\"in\", 0.00160689, 0.02313711, 0.15992000],\n[\"his\", 0.00155837, 0.00104100, 0.01494700],\n[\"recognise\", 0.00153697, 0.00030223, 0.00016274],\n[\"actually\", 0.00153360, 0.00125928, 0.03373800],\n[\"had\", 0.00150735, 0.00174620, 0.02900300],\n[\"tonight\", 0.00148367, 0.00040297, 0.00567320],\n[\"at\", 0.00147261, 0.00493636, 0.03092100],\n[\"ow\", 0.00145158, 0.00028544, 0.15954000],\n[\"enforcement\", 0.00145158, 0.00028544, 0.01617200],\n[\"even\", 0.00144587, 0.00097384, 0.00036536],\n[\"last\", 0.00141570, 0.00125928, 0.00112020],\n[\"referendum\", 0.00140753, 0.00050371, 0.09726700],\n[\"legislation\", 0.00139506, 0.00100742, 0.02270500],\n[\"indeed\", 0.00139506, 0.00100742, 0.00525960],\n[\"may\", 0.00137548, 0.00083952, 0.01725400],\n[\"britain\", 0.00136619, 0.00026865, 0.00193260],\n[\"relation\", 0.00133111, 0.00036939, 0.00186350],\n[\"proposal\", 0.00130039, 0.00114174, 0.07566400],\n[\"chamber\", 0.00128081, 0.00025186, 0.00672820],\n[\"kingdom\", 0.00128081, 0.00025186, 0.00080461],\n[\"accountability\", 0.00128081, 0.00025186, 0.02431600],\n[\"but\", 0.00125895, 0.00634675, 0.18852000],\n[\"record\", 0.00125550, 0.00035260, 0.01633600],\n[\"those\", 0.00125006, 0.00230028, 0.03952600],\n[\"me\", 0.00120356, 0.00112495, 0.03329900],\n[\"commitments\", 0.00119542, 0.00023506, 0.00406020],\n[\"members\", 0.00117203, 0.00065482, 0.03983200],\n[\"business\", 0.00114883, 0.00070519, 0.06787900],\n[\"regulation\", 0.00112102, 0.00063803, 0.03306800],\n[\"cod\", 0.00111003, 0.00021827, 0.15954000],\n[\"chair\", 0.00111003, 0.00021827, 0.00199080],\n[\"face\", 0.00111003, 0.00021827, 0.00058163],\n[\"requirements\", 0.00110579, 0.00031902, 0.00549030],\n[\"from\", 0.00105322, 0.00402969, 0.05717500],\n[\"issue\", 0.00104706, 0.00112495, 0.02917200],\n[\"house\", 0.00104583, 0.00105779, 0.00529700],\n[\"earlier\", 0.00103179, 0.00030223, 0.00857950],\n[\"into\", 0.00103120, 0.00196447, 0.18329000],\n[\"an\", 0.00103109, 0.00357635, 0.04809700],\n[\"v\", 0.00102464, 0.00020148, 0.05599000],\n[\"chain\", 0.00102464, 0.00020148, 0.02803100],\n[\"pacific\", 0.00102464, 0.00020148, 0.11441000],\n[\"where\", 0.00099843, 0.00154471, 0.06653000],\n[\"consumer\", 0.00096082, 0.00038618, 0.05640600],\n[\"emas\", 0.00093926, 0.00018469, 0.08251700],\n[\"fourty\", 0.00093926, 0.00018469, 0.01143400],\n[\"industries\", 0.00093926, 0.00018469, 0.01155500],\n[\"syrian\", 0.00093926, 0.00018469, 0.15954000],\n[\"him\", 0.00093835, 0.00033581, 0.01081300],\n[\"services\", 0.00093116, 0.00065482, 0.01258400],\n[\"perhaps\", 0.00091411, 0.00077236, 0.06221600],\n[\"course\", 0.00091310, 0.00146076, 0.05615300],\n[\"farmers\", 0.00090716, 0.00053729, 0.03105200],\n[\"place\", 0.00086638, 0.00082273, 0.01612800],\n[\"vote\", 0.00085776, 0.00052050, 0.04428800],\n[\"commend\", 0.00085387, 0.00016790, 0.00639830],\n[\"corporate\", 0.00085387, 0.00016790, 0.04773800],\n[\"pcbs\", 0.00085387, 0.00016790, 0.10350000],\n[\"professionals\", 0.00085387, 0.00016790, 0.13578000],\n[\"looking\", 0.00084263, 0.00067161, 0.05727600],\n[\"forward\", 0.00084113, 0.00092347, 0.13585000],\n[\"debate\", 0.00082656, 0.00119212, 0.04922500],\n[\"very\", 0.00082300, 0.00500353, 0.37943000],\n[\"this\", 0.00081751, 0.01304611, 0.22339000],\n[\"he\", 0.00079263, 0.00117532, 0.23405000],\n[\"back\", 0.00078200, 0.00110816, 0.09418600],\n[\"to\", 0.00077970, 0.03742570, 0.61131000],\n[\"systems\", 0.00077961, 0.00033581, 0.03656100],\n[\"consumers\", 0.00077919, 0.00052050, 0.07285000],\n[\"over\", 0.00077786, 0.00120891, 0.04992000],\n[\"many\", 0.00077694, 0.00141039, 0.12153000],\n[\"years\", 0.00077076, 0.00122570, 0.01619900],\n[\"tribute\", 0.00076848, 0.00015111, 0.01105700],\n[\"dossier\", 0.00076848, 0.00015111, 0.01322200],\n[\"refused\", 0.00076848, 0.00015111, 0.00790590],\n[\"committee\", 0.00075734, 0.00136002, 0.24660000],\n[\"yet\", 0.00075310, 0.00058766, 0.03011700],\n[\"second\", 0.00073047, 0.00041976, 0.04168000],\n[\"let\", 0.00072521, 0.00080594, 0.05975300],\n[\"staff\", 0.00072088, 0.00031902, 0.09156600],\n[\"public\", 0.00071608, 0.00062124, 0.08559200],\n[\"best\", 0.00071346, 0.00047013, 0.09452000],\n[\"did\", 0.00071000, 0.00057087, 0.04028500],\n[\"member\", 0.00070502, 0.00253534, 0.29929000],\n[\"use\", 0.00069722, 0.00070519, 0.06085800],\n[\"welcome\", 0.00069722, 0.00070519, 0.06775300],\n[\"suggested\", 0.00068310, 0.00013432, 0.01732100],\n[\"increasing\", 0.00068310, 0.00013432, 0.00861660],\n[\"religion\", 0.00068310, 0.00013432, 0.02844600],\n[\"referendums\", 0.00068310, 0.00013432, 0.04047600],\n[\"ensuring\", 0.00068310, 0.00013432, 0.00352260],\n[\"stakeholders\", 0.00068310, 0.00013432, 0.05108400],\n[\"working\", 0.00067290, 0.00073878, 0.14935000],\n[\"support\", 0.00067082, 0.00151113, 0.30934000],\n[\"existing\", 0.00066826, 0.00036939, 0.04453000],\n[\"maybe\", 0.00066309, 0.00030223, 0.00799430],\n[\"ways\", 0.00066309, 0.00030223, 0.09035300],\n[\"coming\", 0.00065975, 0.00062124, 0.06074600],\n[\"legal\", 0.00064371, 0.00052050, 0.22590000],\n[\"particular\", 0.00064143, 0.00078915, 0.09200700],\n[\"you\", 0.00063748, 0.00972162, 0.38216000],\n[\"proud\", 0.00062008, 0.00025186, 0.06442000],\n[\"while\", 0.00060629, 0.00028544, 0.08553300],\n[\"crucial\", 0.00060629, 0.00028544, 0.03828500],\n[\"global\", 0.00060135, 0.00050371, 0.14136000],\n[\"authorities\", 0.00060084, 0.00040297, 0.10854000],\n[\"package\", 0.00060084, 0.00040297, 0.14665000],\n[\"inclusion\", 0.00059771, 0.00011753, 0.02882300],\n[\"assets\", 0.00059771, 0.00011753, 0.08907500],\n[\"argument\", 0.00059771, 0.00011753, 0.01014900],\n[\"core\", 0.00059771, 0.00011753, 0.00545350],\n[\"ii\", 0.00059771, 0.00011753, 0.02624600],\n[\"industry\", 0.00058318, 0.00065482, 0.05199900],\n[\"who\", 0.00057917, 0.00283757, 0.09889100],\n[\"am\", 0.00057744, 0.00047013, 0.03550000],\n[\"'ve\", 0.00056947, 0.00362672, 0.22194000],\n[\"initiative\", 0.00056697, 0.00033581, 0.03942700],\n[\"access\", 0.00055968, 0.00048692, 0.08611000],\n[\"document\", 0.00055947, 0.00023506, 0.03803400],\n[\"organisations\", 0.00055947, 0.00023506, 0.15736000],\n[\"issues\", 0.00055730, 0.00087310, 0.15715000],\n[\"lives\", 0.00055056, 0.00026865, 0.09254000],\n[\"trade\", 0.00054254, 0.00057087, 0.16363000],\n[\"must\", 0.00053601, 0.00114174, 0.11569000],\n[\"levels\", 0.00053572, 0.00018469, 0.03271700],\n[\"damage\", 0.00053572, 0.00018469, 0.04718400],\n[\"families\", 0.00053572, 0.00018469, 0.03214400],\n[\"due\", 0.00053572, 0.00018469, 0.01464800],\n[\"amongst\", 0.00053572, 0.00018469, 0.02568400],\n[\"r\", 0.00053572, 0.00018469, 0.07969000],\n[\"does\", 0.00052956, 0.00052050, 0.12909000],\n[\"particularly\", 0.00052451, 0.00095705, 0.17990000],\n[\"do\", 0.00051916, 0.00313980, 0.18838000],\n[\"making\", 0.00051872, 0.00047013, 0.10956000],\n[\"recognised\", 0.00051232, 0.00010074, 0.01591000],\n[\"caught\", 0.00051232, 0.00010074, 0.00992190],\n[\"hopefully\", 0.00051232, 0.00010074, 0.04082000],\n[\"collective\", 0.00051232, 0.00010074, 0.03245600],\n[\"voted\", 0.00051232, 0.00010074, 0.00986450],\n[\"spend\", 0.00051232, 0.00010074, 0.00847940],\n[\"setting\", 0.00051232, 0.00010074, 0.06293900],\n[\"invest\", 0.00051232, 0.00010074, 0.00767940],\n[\"such\", 0.00051227, 0.00078915, 0.18284000],\n[\"times\", 0.00050924, 0.00036939, 0.05259900],\n[\"across\", 0.00050397, 0.00048692, 0.06500500],\n[\"costs\", 0.00050388, 0.00028544, 0.06730600],\n[\"projects\", 0.00050009, 0.00021827, 0.07731300],\n[\"range\", 0.00050009, 0.00021827, 0.01576900],\n[\"emissions\", 0.00050009, 0.00021827, 0.02820900],\n[\"regulators\", 0.00050009, 0.00021827, 0.18011000],\n[\"elected\", 0.00050009, 0.00021827, 0.03443300],\n[\"balance\", 0.00049598, 0.00025186, 0.04070400],\n[\"her\", 0.00049383, 0.00043655, 0.17878000],\n[\"off\", 0.00048765, 0.00038618, 0.03352600],\n[\"find\", 0.00048351, 0.00058766, 0.20710000],\n[\"agreement\", 0.00048161, 0.00097384, 0.22919000],\n[\"rapporteur\", 0.00047850, 0.00045334, 0.11404000],\n[\"come\", 0.00047084, 0.00100742, 0.10596000],\n[\"pay\", 0.00046959, 0.00030223, 0.15129000],\n[\"relationship\", 0.00046918, 0.00016790, 0.17219000],\n[\"cars\", 0.00046918, 0.00016790, 0.06629800],\n[\"recession\", 0.00046918, 0.00016790, 0.04648900],\n[\"constituency\", 0.00046918, 0.00016790, 0.04377600],\n[\"voters\", 0.00046918, 0.00016790, 0.07774000],\n[\"year\", 0.00046584, 0.00080594, 0.08560700],\n[\"sector\", 0.00046482, 0.00047013, 0.07982500],\n[\"your\", 0.00046127, 0.00115853, 0.24488000],\n[\"union\", 0.00045947, 0.00183015, 0.31279000],\n[\"serious\", 0.00045320, 0.00041976, 0.12912000],\n[\"around\", 0.00044500, 0.00036939, 0.04765400],\n[\"uk\", 0.00044206, 0.00020148, 0.08279400],\n[\"delighted\", 0.00044206, 0.00020148, 0.04902100],\n[\"probably\", 0.00044206, 0.00020148, 0.02373400],\n[\"stage\", 0.00044206, 0.00020148, 0.01519300],\n[\"cross-border\", 0.00044206, 0.00020148, 0.05814500],\n[\"bring\", 0.00043040, 0.00060445, 0.12795000],\n[\"areas\", 0.00042810, 0.00038618, 0.14303000],\n[\"shadows\", 0.00042694, 0.00008395, 0.01513400],\n[\"consistent\", 0.00042694, 0.00008395, 0.02793000],\n[\"regime\", 0.00042694, 0.00008395, 0.05994200],\n[\"list\", 0.00042694, 0.00008395, 0.05056000],\n[\"gay\", 0.00042694, 0.00008395, 0.08148000],\n[\"submitted\", 0.00042694, 0.00008395, 0.04358900],\n[\"extra\", 0.00042694, 0.00008395, 0.02063700],\n[\"sovereign\", 0.00042694, 0.00008395, 0.03451100],\n[\"plant\", 0.00042694, 0.00008395, 0.04500100],\n[\"book\", 0.00042694, 0.00008395, 0.06163400],\n[\"faith\", 0.00042694, 0.00008395, 0.01527400],\n[\"nothing\", 0.00042252, 0.00028544, 0.03061500],\n[\"aid\", 0.00042252, 0.00028544, 0.14530000],\n[\"came\", 0.00042252, 0.00028544, 0.05934600],\n[\"which\", 0.00042247, 0.00396252, 0.19304000],\n[\"worked\", 0.00042132, 0.00033581, 0.10076000],\n[\"between\", 0.00042053, 0.00094026, 0.07552500],\n[\"hear\", 0.00041340, 0.00040297, 0.04456000],\n[\"will\", 0.00040978, 0.00465093, 0.30212000],\n[\"effect\", 0.00040450, 0.00025186, 0.03132000],\n[\"local\", 0.00040450, 0.00025186, 0.09355100],\n[\"strongly\", 0.00040416, 0.00015111, 0.02095300],\n[\"speech\", 0.00040416, 0.00015111, 0.06264300],\n[\"caused\", 0.00040416, 0.00015111, 0.06784000],\n[\"mutual\", 0.00040416, 0.00015111, 0.15871000],\n[\"interim\", 0.00040416, 0.00015111, 0.16240000],\n[\"early\", 0.00040416, 0.00015111, 0.02721300],\n[\"frankly\", 0.00040416, 0.00015111, 0.02198900],\n[\"takes\", 0.00040416, 0.00015111, 0.05460400],\n[\"detail\", 0.00040416, 0.00015111, 0.12731000],\n[\"wider\", 0.00040416, 0.00015111, 0.09766800],\n[\"important\", 0.00040231, 0.00181336, 0.44057000],\n[\"whole\", 0.00040225, 0.00077236, 0.18329000],\n[\"concerns\", 0.00039839, 0.00030223, 0.21993000],\n[\"what\", 0.00039728, 0.00379462, 0.46166000],\n[\"car\", 0.00039068, 0.00021827, 0.05315300],\n[\"despite\", 0.00039068, 0.00021827, 0.03474000],\n[\"comments\", 0.00039068, 0.00021827, 0.07040000],\n[\"history\", 0.00039068, 0.00021827, 0.14876000],\n[\"took\", 0.00039068, 0.00021827, 0.17571000],\n[\"safety\", 0.00038788, 0.00036939, 0.18726000],\n[\"jobs\", 0.00038613, 0.00052050, 0.22132000],\n[\"care\", 0.00038552, 0.00018469, 0.15517000],\n[\"met\", 0.00038552, 0.00018469, 0.03357100],\n[\"congratulate\", 0.00038552, 0.00018469, 0.02386500],\n[\"needed\", 0.00038552, 0.00018469, 0.07083600],\n[\"done\", 0.00038105, 0.00095705, 0.18788000]\n]\n}\n\nowvos = {\n\"title\": \"ORG (written) vs. ORG (spoken)\",\n\"terms\": [\n[\"the\", 0.01721251, 0.07775888, 0.00002504],\n[\"is\", 0.00776894, 0.01961087, 0.00056669],\n[\"of\", 0.00746952, 0.03747709, 0.00775670],\n[\"eu\", 0.00687078, 0.00488063, 0.00067786],\n[\"not\", 0.00572750, 0.00914291, 0.00052560],\n[\"for\", 0.00537463, 0.01375853, 0.00207860],\n[\"must\", 0.00531162, 0.00353349, 0.00010846],\n[\"to\", 0.00434510, 0.04048055, 0.01574500],\n[\"sri\", 0.00425140, 0.00068461, 0.01355400],\n[\"by\", 0.00383010, 0.00583026, 0.00317260],\n[\"has\", 0.00356932, 0.00552108, 0.00136990],\n[\"be\", 0.00353305, 0.01073298, 0.01227800],\n[\"its\", 0.00328165, 0.00278262, 0.00249940],\n[\"are\", 0.00317841, 0.00907665, 0.05370300],\n[\"lanka\", 0.00287998, 0.00046377, 0.01519500],\n[\"a\", 0.00274743, 0.02073717, 0.06314100],\n[\"ltte\", 0.00260570, 0.00041960, 0.05155200],\n[\"asylum\", 0.00257168, 0.00044169, 0.03474900],\n[\"as\", 0.00255230, 0.00801661, 0.01788900],\n[\"system\", 0.00245497, 0.00139131, 0.00244890],\n[\"in\", 0.00242062, 0.02484486, 0.17096000],\n[\"capital\", 0.00239068, 0.00055211, 0.00638730],\n[\"such\", 0.00230355, 0.00192134, 0.00091774],\n[\"will\", 0.00224467, 0.00609527, 0.03850000],\n[\"species\", 0.00224257, 0.00039752, 0.15962000],\n[\"membership\", 0.00218488, 0.00037543, 0.00309050],\n[\"international\", 0.00213672, 0.00123672, 0.00145580],\n[\"however\", 0.00211161, 0.00123672, 0.00105140],\n[\"israel\", 0.00207558, 0.00081712, 0.17266000],\n[\"mrls\", 0.00205713, 0.00033126, 0.15962000],\n[\"economic\", 0.00202849, 0.00185508, 0.00829330],\n[\"europe\", 0.00194527, 0.00196550, 0.02234500],\n[\"justice\", 0.00193105, 0.00055211, 0.00317890],\n[\"states\", 0.00190975, 0.00311389, 0.04346700],\n[\"arrest\", 0.00189230, 0.00030918, 0.00327730],\n[\"financial\", 0.00189104, 0.00136923, 0.01261300],\n[\"crisis\", 0.00170937, 0.00130297, 0.03362200],\n[\"uk\", 0.00168222, 0.00086129, 0.01004100],\n[\"tamil\", 0.00164570, 0.00026501, 0.10616000],\n[\"e-money\", 0.00164570, 0.00026501, 0.08895800],\n[\"timber\", 0.00164570, 0.00026501, 0.13994000],\n[\"banks\", 0.00159561, 0.00057419, 0.04189300],\n[\"would\", 0.00157290, 0.00397518, 0.26236000],\n[\"countries\", 0.00155503, 0.00178883, 0.02580000],\n[\"debt\", 0.00155244, 0.00059628, 0.06251700],\n[\"profiling\", 0.00150856, 0.00024293, 0.15962000],\n[\"china\", 0.00149503, 0.00055211, 0.05556400],\n[\"belarus\", 0.00148909, 0.00026501, 0.13829000],\n[\"am\", 0.00148656, 0.00119255, 0.02352400],\n[\"citizens\", 0.00148493, 0.00103796, 0.04590700],\n[\"children\", 0.00146991, 0.00092754, 0.18075000],\n[\"failing\", 0.00143280, 0.00024293, 0.01421700],\n[\"government\", 0.00142990, 0.00112630, 0.03235300],\n[\"turkey\", 0.00140302, 0.00044169, 0.05713200],\n[\"general\", 0.00137431, 0.00055211, 0.05360800],\n[\"lankan\", 0.00137142, 0.00022084, 0.01815600],\n[\"macedonia\", 0.00134411, 0.00022084, 0.13382000],\n[\"eurozone\", 0.00132250, 0.00024293, 0.02058800],\n[\"state\", 0.00131037, 0.00134714, 0.03095100],\n[\"requirement\", 0.00123797, 0.00022084, 0.00676830],\n[\"while\", 0.00121956, 0.00083920, 0.00534840],\n[\"lukashenko\", 0.00120711, 0.00019876, 0.07970600],\n[\"warrant\", 0.00120711, 0.00019876, 0.00978190],\n[\"gaza\", 0.00120552, 0.00050794, 0.06862800],\n[\"should\", 0.00115451, 0.00348932, 0.20642000],\n[\"market\", 0.00114556, 0.00139131, 0.05334500],\n[\"civilians\", 0.00114441, 0.00030918, 0.01434000],\n[\"visa\", 0.00111976, 0.00057419, 0.08763200],\n[\"schengen\", 0.00109918, 0.00050794, 0.08870000],\n[\"trading\", 0.00108955, 0.00039752, 0.01356700],\n[\"euro\", 0.00105113, 0.00053002, 0.03811100],\n[\"travel\", 0.00104720, 0.00055211, 0.13726000],\n[\"cuba\", 0.00104613, 0.00017667, 0.15962000],\n[\"detention\", 0.00104613, 0.00017667, 0.01611200],\n[\"including\", 0.00104362, 0.00070670, 0.00648640],\n[\"resolution\", 0.00104340, 0.00066253, 0.02213600],\n[\"discipline\", 0.00102452, 0.00017667, 0.02680500],\n[\"policy\", 0.00102272, 0.00090546, 0.05213200],\n[\"member\", 0.00101986, 0.00320223, 0.22584000],\n[\"turkish\", 0.00100488, 0.00017667, 0.04286300],\n[\"dairy\", 0.00100055, 0.00028710, 0.10247000],\n[\"economies\", 0.00099913, 0.00037543, 0.01245400],\n[\"agency\", 0.00099384, 0.00037543, 0.13221000],\n[\"country\", 0.00098867, 0.00112630, 0.11568000],\n[\"council\", 0.00098302, 0.00187717, 0.09643300],\n[\"repression\", 0.00097033, 0.00017667, 0.03031500],\n[\"ensure\", 0.00096744, 0.00103796, 0.03865900],\n[\"which\", 0.00096138, 0.00461562, 0.15226000],\n[\"party\", 0.00093665, 0.00046377, 0.03985200],\n[\"markets\", 0.00091857, 0.00070670, 0.05737900],\n[\"programme\", 0.00091297, 0.00026501, 0.01075900],\n[\"external\", 0.00090887, 0.00022084, 0.03164000],\n[\"bank\", 0.00090775, 0.00050794, 0.05041800],\n[\"sovereign\", 0.00090562, 0.00041960, 0.02564500],\n[\"responsible\", 0.00087789, 0.00030918, 0.04584800],\n[\"energy\", 0.00087202, 0.00081712, 0.32737000],\n[\"security\", 0.00086818, 0.00079504, 0.03364400],\n[\"mechanism\", 0.00085945, 0.00037543, 0.03969500],\n[\"illegally\", 0.00085307, 0.00015459, 0.07992900],\n[\"transaction\", 0.00085307, 0.00015459, 0.04369600],\n[\"future\", 0.00084792, 0.00092754, 0.01639800],\n[\"common\", 0.00084730, 0.00090546, 0.19811000],\n[\"with\", 0.00084063, 0.00658113, 0.20422000],\n[\"strategy\", 0.00083835, 0.00046377, 0.12758000],\n[\"immediate\", 0.00082219, 0.00033126, 0.01517800],\n[\"action\", 0.00081512, 0.00077295, 0.15647000],\n[\"former\", 0.00079984, 0.00024293, 0.02553500],\n[\"path\", 0.00077494, 0.00015459, 0.00447200],\n[\"humanitarian\", 0.00077051, 0.00046377, 0.06907800],\n[\"proposed\", 0.00077014, 0.00046377, 0.02059000],\n[\"hamas\", 0.00076249, 0.00035335, 0.29829000],\n[\"against\", 0.00076163, 0.00092754, 0.14536000],\n[\"under\", 0.00076079, 0.00103796, 0.13320000],\n[\"money\", 0.00075976, 0.00090546, 0.08351700],\n[\"workers\", 0.00075926, 0.00070670, 0.27007000],\n[\"or\", 0.00075674, 0.00324639, 0.22885000],\n[\"european\", 0.00075638, 0.00419602, 0.26119000],\n[\"both\", 0.00075500, 0.00088337, 0.15196000],\n[\"price\", 0.00075380, 0.00037543, 0.07707800],\n[\"standards\", 0.00074840, 0.00061836, 0.18395000],\n[\"means\", 0.00074824, 0.00068461, 0.04488100],\n[\"islamic\", 0.00074653, 0.00022084, 0.10443000],\n[\"war\", 0.00074597, 0.00037543, 0.06668500],\n[\"cannot\", 0.00074388, 0.00099379, 0.14373000],\n[\"an\", 0.00074319, 0.00408560, 0.40488000],\n[\"competitiveness\", 0.00073576, 0.00022084, 0.02954400],\n[\"area\", 0.00073272, 0.00081712, 0.08831600],\n[\"does\", 0.00072603, 0.00092754, 0.07423800],\n[\"fear\", 0.00072317, 0.00022084, 0.04826200],\n[\"liberal\", 0.00072251, 0.00026501, 0.17966000],\n[\"corruption\", 0.00072108, 0.00015459, 0.01552800],\n[\"basel\", 0.00071998, 0.00013251, 0.14024000],\n[\"minority\", 0.00071357, 0.00015459, 0.00755560],\n[\"attacks\", 0.00071281, 0.00026501, 0.09840300],\n[\"especially\", 0.00071132, 0.00041960, 0.03609900],\n[\"freedom\", 0.00070520, 0.00030918, 0.09112800],\n[\"president\", 0.00070183, 0.00375433, 0.33492000],\n[\"framework\", 0.00069941, 0.00064045, 0.04171600],\n[\"full\", 0.00069588, 0.00061836, 0.03011500],\n[\"become\", 0.00069524, 0.00046377, 0.06111300],\n[\"policies\", 0.00069305, 0.00033126, 0.06783500],\n[\"risk\", 0.00068852, 0.00053002, 0.05575200],\n[\"mexico\", 0.00068010, 0.00013251, 0.08549400],\n[\"illegal\", 0.00067563, 0.00026501, 0.18367000],\n[\"more\", 0.00067044, 0.00293721, 0.35061000],\n[\"human\", 0.00066885, 0.00088337, 0.13371000],\n[\"nation\", 0.00066373, 0.00028710, 0.01022100],\n[\"crimes\", 0.00064652, 0.00019876, 0.06350300],\n[\"commit\", 0.00064408, 0.00019876, 0.08276500],\n[\"death\", 0.00064075, 0.00024293, 0.01895900],\n[\"fiscal\", 0.00063944, 0.00024293, 0.05132000],\n[\"electricity\", 0.00063944, 0.00024293, 0.08610300],\n[\"credible\", 0.00063932, 0.00019876, 0.05123100],\n[\"migrants\", 0.00063932, 0.00019876, 0.08871200],\n[\"clear\", 0.00063838, 0.00101588, 0.14792000],\n[\"guidelines\", 0.00063699, 0.00019876, 0.09038900],\n[\"fair\", 0.00063570, 0.00055211, 0.14698000],\n[\"any\", 0.00063487, 0.00136923, 0.08848700],\n[\"programmes\", 0.00062803, 0.00019876, 0.03123300],\n[\"data\", 0.00062744, 0.00050794, 0.22088000],\n[\"terrorist\", 0.00062344, 0.00024293, 0.15777000],\n[\"information\", 0.00061846, 0.00083920, 0.14213000],\n[\"own\", 0.00060528, 0.00145756, 0.31862000],\n[\"serbia\", 0.00060052, 0.00013251, 0.03818000],\n[\"political\", 0.00059770, 0.00099379, 0.06485000],\n[\"value\", 0.00059379, 0.00035335, 0.10955000],\n[\"agencies\", 0.00059226, 0.00035335, 0.11919000],\n[\"developing\", 0.00059112, 0.00035335, 0.08158400],\n[\"single\", 0.00058417, 0.00055211, 0.02668100],\n[\"efforts\", 0.00058065, 0.00037543, 0.05021700],\n[\"same\", 0.00057533, 0.00070670, 0.07765700],\n[\"exploitation\", 0.00057480, 0.00011042, 0.07917700],\n[\"achievement\", 0.00057480, 0.00011042, 0.03034900],\n[\"administration\", 0.00057480, 0.00011042, 0.03237200],\n[\"still\", 0.00057203, 0.00081712, 0.03295200],\n[\"players\", 0.00056290, 0.00011042, 0.02475800],\n[\"systems\", 0.00056154, 0.00064045, 0.12691000],\n[\"only\", 0.00056005, 0.00150173, 0.32289000],\n[\"england\", 0.00055555, 0.00022084, 0.04345500],\n[\"wales\", 0.00055555, 0.00022084, 0.09104600],\n[\"secure\", 0.00055441, 0.00022084, 0.02693100],\n[\"firm\", 0.00055328, 0.00022084, 0.03441900],\n[\"bosnia\", 0.00055203, 0.00011042, 0.11022000],\n[\"via\", 0.00055203, 0.00011042, 0.01585200],\n[\"beef\", 0.00055104, 0.00022084, 0.18105000],\n[\"added\", 0.00054994, 0.00022084, 0.09732700],\n[\"welfare\", 0.00054994, 0.00022084, 0.17347000],\n[\"imf\", 0.00054777, 0.00022084, 0.07990100],\n[\"other\", 0.00054685, 0.00185508, 0.12918000],\n[\"regret\", 0.00054496, 0.00017667, 0.03983400],\n[\"western\", 0.00054249, 0.00022084, 0.04804400],\n[\"operators\", 0.00054151, 0.00030918, 0.30374000],\n[\"provision\", 0.00054089, 0.00017667, 0.04790900],\n[\"outstanding\", 0.00054089, 0.00017667, 0.04677800],\n[\"join\", 0.00054021, 0.00030918, 0.03334600],\n[\"resources\", 0.00053767, 0.00030918, 0.09647000],\n[\"palestinians\", 0.00053279, 0.00011042, 0.02274900],\n[\"south\", 0.00053162, 0.00022084, 0.12820000],\n[\"budgets\", 0.00053125, 0.00017667, 0.02295300],\n[\"eastern\", 0.00053098, 0.00033126, 0.16491000],\n[\"may\", 0.00053023, 0.00117047, 0.15116000],\n[\"world\", 0.00052874, 0.00108213, 0.11270000],\n[\"than\", 0.00052475, 0.00132506, 0.24280000],\n[\"concern\", 0.00052455, 0.00048585, 0.22289000],\n[\"greece\", 0.00052325, 0.00030918, 0.18090000],\n[\"monetary\", 0.00052229, 0.00017667, 0.04406300],\n[\"budget\", 0.00052206, 0.00048585, 0.15231000],\n[\"care\", 0.00052123, 0.00044169, 0.26232000],\n[\"crime\", 0.00051960, 0.00035335, 0.09367900],\n[\"rights\", 0.00051841, 0.00139131, 0.33272000],\n[\"available\", 0.00051717, 0.00041960, 0.03879200],\n[\"essential\", 0.00051667, 0.00037543, 0.15083000],\n[\"step\", 0.00051277, 0.00041960, 0.01563700],\n[\"kosovo\", 0.00051274, 0.00015459, 0.10056000],\n[\"group\", 0.00051214, 0.00094963, 0.26642000],\n[\"short-term\", 0.00051129, 0.00024293, 0.06370800],\n[\"forces\", 0.00050853, 0.00024293, 0.04544900],\n[\"many\", 0.00050632, 0.00174466, 0.22310000],\n[\"border\", 0.00050461, 0.00017667, 0.00659670],\n[\"high\", 0.00050344, 0.00059628, 0.09846200],\n[\"minorities\", 0.00049814, 0.00024293, 0.09655400],\n[\"employees\", 0.00049490, 0.00011042, 0.05040800],\n[\"laws\", 0.00048722, 0.00026501, 0.04477300],\n[\"urge\", 0.00047476, 0.00028710, 0.05435000],\n[\"minor\", 0.00047300, 0.00019876, 0.14942000],\n[\"based\", 0.00047206, 0.00046377, 0.13903000],\n[\"national\", 0.00047189, 0.00101588, 0.16652000],\n[\"month\", 0.00047010, 0.00019876, 0.19871000],\n[\"young\", 0.00046892, 0.00044169, 0.41259000],\n[\"permanent\", 0.00046820, 0.00019876, 0.17748000],\n[\"fail\", 0.00046820, 0.00019876, 0.04596000],\n[\"reform\", 0.00046751, 0.00044169, 0.09587700],\n[\"civil\", 0.00046653, 0.00028710, 0.02263400],\n[\"purpose\", 0.00046542, 0.00019876, 0.04073900],\n[\"provided\", 0.00046494, 0.00030918, 0.12874000],\n[\"welcome\", 0.00046459, 0.00099379, 0.26340000],\n[\"immigration\", 0.00046361, 0.00019876, 0.06774700],\n[\"cut\", 0.00046233, 0.00037543, 0.13901000],\n[\"positive\", 0.00046179, 0.00030918, 0.15983000],\n[\"seems\", 0.00046158, 0.00039752, 0.13867000],\n[\"stability\", 0.00046069, 0.00037543, 0.25470000],\n[\"on\", 0.00045975, 0.01020295, 0.53251000],\n[\"suffering\", 0.00045835, 0.00019876, 0.05535400],\n[\"most\", 0.00045708, 0.00106005, 0.26715000],\n[\"race\", 0.00045131, 0.00015459, 0.07985100],\n[\"protectionism\", 0.00044787, 0.00015459, 0.09102900],\n[\"needs\", 0.00044786, 0.00094963, 0.24175000],\n[\"therefore\", 0.00044708, 0.00077295, 0.07928100],\n[\"grant\", 0.00044588, 0.00008834, 0.07036100],\n[\"prosperity\", 0.00044454, 0.00015459, 0.02653000]\n]\n}", "_____no_output_____" ], [ "# We gathered this way five dictionaries of words\ndics = [owvt,tvow,ivos,osvi,osvow]", "_____no_output_____" ], [ "# We now select for each dictionary only words having a KLD value higher than a \n# given threhsold (thres)\n\nkld_words = []\nkld_words_scores = []\nthres = .05\n\nfreqs = [] # array for frequencies\n\nfor dic in dics:\n terms = dic['terms']\n kld_words += [t[0] for t in terms if t[-1]<=thres] # kld words\n freqs += [(t[1],t[-2],t[0]) for t in terms if t[-1]<=thres] # frequencies\n kld_words_scores += [(t[2],t[0]) for t in terms if t[-1]<thres] # kld words with scores\n \n\nlen(kld_words)", "_____no_output_____" ], [ "# Sort and reverse frequences\nfreqs.sort()\nfreqs.reverse()", "_____no_output_____" ], [ "# here you can see some of the selected kld words\nprint(kld_words[:30])", "['and', 'eu', 'to', 'uk', 'sri', 'but', 'lanka', 'britain', 'by', \"'s\", 'capital', 'across', 'those', 'its', 'british', 'sovereign', 'welcome', 'trading', 'some', 'may', 'bank', 'review', 'membership', 'cut', 'economies', 'when', 'systems', 'electricity', 'eurozone', 'death']\n" ], [ "#Now we take the corpora's directories\n\ndirectory = '/Users/yuribizzoni/Downloads/Translation/B7/'\n\n#Originals\n# ewo = English Written Originals\newo = glob.glob(directory+\"epuds-parallel/words/*.en\") + glob.glob(directory+\"txt_translationese/en/originals/*\") #english wo\n\n# eso = English Spoken Originals\neso = glob.glob(directory+\"1 interpreting data/ORG_SP_EN_korrigiert/*\")#english spoken originals\nprint(len(ewo),len(eso))\n\n\n#Translations\n# ewt = English Written Translations\newt = glob.glob(directory+\"txt_translationese/en/translations_all/*\") \nprint(len(ewt))\n\n#Interpreting transcripts\n# ei = English Interpreting\nei = glob.glob(directory+\"1 interpreting data/SI_DE_EN_korrigiert/*\")#english in\nprint(len(ei))\n", "1079 114\n1077\n149\n" ], [ "# some very useful functions\n\n# cleaning a little bit the transcripts (can be made richer)\ndef clean(hm):\n hm = hm.replace(\"/\",\"\").replace(\"[\",\"\").replace(\"]\",\"\").replace(\"#\",\"\")#.replace('euh','')\n return hm\n\n\n#from text to features: for the more traditional features\ndef featureit(text):\n ttext = [e[0] for e in text]\n ptext = [e[1] for e in text]\n ttr = ld.ttr(ttext) ## type token ratio\n \n semgro = \"VERB ADV ADJ NOUN\".split()\n lexema = [e for e in ptext if e in semgro] # lexical (non function) words\n \n density = (len(lexema)+1)/(len(ptext)+1) # textual density\n \n #verbs, nouns = ptext.count(\"VERB\"), ptext.count(\"NOUN\") # other features you can add\n \n #return [ttr,density,verbs,nouns]\n return {'ttr':ttr, 'density':density} # in this form returns ttr and density\n\n\n# keeping only instances of chosen words\ndef featureit_words(text, wordlist):\n seltext = [w for w in text if w in wordlist]\n return seltext\n\n", "_____no_output_____" ], [ "%%time\n\n## Now we create the Y labels and the texts from which we will make our X \n \nminamo = 110 # amount of documents\nmaxlen = 40000 # maximal amount of characters per document\n\n\nclasses = [ei, eso, ewt, ewo] \n\ntexts_,Y_ = [],[]\n\nlatins = []\nlens = []\n\nclass_number=0\n \nfor each_class in classes:\n \n print(class_number)\n \n # feature every point\n for point in each_class[:minamo]: \n #print(point)\n # take the text\n try:\n text = open(point, encoding='utf-16').read()#.split()\n except: \n text = open(point, encoding='latin1').read()\n latins.append(text)\n print(\"reading latin\")\n lens.append(len(text))\n text = text[:maxlen]\n text = nltk.wordpunct_tokenize(clean(text).lower())# clean and tokenize\n \n # turn them into X and Y\n if len(text)>10:\n text = nltk.pos_tag(text, tagset='universal') # PoS tagging\n texts_.append(text)#+[1/class_number])\n Y_.append(class_number)\n else: print(\"Not enough chars\")\n \n class_number+=1\n # ", "0\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\n1\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nNot enough chars\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nNot enough chars\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nNot enough chars\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nNot enough chars\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\nreading latin\n2\nreading latin\n3\nreading latin\nreading latin\nreading latin\nCPU times: user 45.8 s, sys: 422 ms, total: 46.2 s\nWall time: 46.4 s\n" ], [ "#checking the Y_ class is okay\nlen(Y_),Y_.count(0), Y_.count(1), Y_.count(2), Y_.count(3)", "_____no_output_____" ] ], [ [ "Labels:\n0: interpreting\n1: spoken originals\n2: written translation\n3: written originals", "_____no_output_____" ] ], [ [ "# Explicit way of taking only classes 2 and 3\n# If we want all 4 classes, go start = 0 etc.\n\nstart = Y_.count(0)+Y_.count(1) \nclassize = start+Y_.count(2)+Y_.count(3)\ntexts = texts_[start:classize]\nY = Y_[start:classize]\nlen(texts), len(Y)", "_____no_output_____" ], [ "#", "_____no_output_____" ], [ "## Feature Selection\n\n#title = \"min freq 20\" #\"Kld_unigrams\" #\"Pos_ngrams+Kld_unigrams\"#\n\nX,c=[],0\nfor text in texts:\n \n text = [e for e in text if e[0]!='breath' and e[0]!='noise']\n #print(text[:3], Y[c])\n c+=1\n \n \n # EXTRACT THE FEATURES: GATEWAY\n \n # If the featureset is the whole text, uncomment:\n features = \" \".join([e[0] for e in text])\n \n \n # If the features are both kld and tranditionals, uncomment:\n #features = \" \".join(featureit_words([e[0] for e in text], kld_words)) \n \n \n # If the features are only traditionals uncomment:\n #features = featureit(text)\n \n \n # If we want to have both words and Parts of Speech to our feature set, uncomment:\n #features = [e[0] for e in text]\n #features += \" \".join([w[1] for w in text])##\n \n \n # In any case, we end up adding the featureset to the X array:\n X.append(features)\n \n\n\n# THEN WE MAKE THE VECTORIZER\n# in this instance: we take the top 9000 unigrams. Check the CountVectorizer for more functions\nvectorizer = CountVectorizer(max_features=9000, ngram_range=(1,1))#, min_df=.5)\n\n# ATTENTION: If using \"featureit\", use the following:\n#vectorizer = DictVectorizer()\n\n# Another possible dictionary\n#vectorizer = TfidfVectorizer(max_features=4000, ngram_range=(1,1))#, min_df=10)\n\n\n# Finally, we fit transform X with the vectorizer. \n# Which means we apply the feature selection we defined in the vectorizer to X\nX = vectorizer.fit_transform(X)", "_____no_output_____" ], [ "# This is how ti shows, f.e.\nprint(vectorizer.get_feature_names()[:100])\nX.toarray()", "['10', '12', '1and', '1angling', '1are', '1ashton', '1baringdorf', '1because', '1but', '1can', '1cannot', '1coelho', '1commission', '1commissioner', '1committee', '1could', '1council', '1detrimental', '1did', '1do', '1does', '1economy', '1euh', '1everybody', '1everything', '1from', '1going', '1gone', '1government', '1group', '1had', '1has', '1have', '1he', '1i', '1important', '1in', '1information', '1integration', '1is', '1it', '1let', '1must', '1nobody', '1not', '1ombudsman', '1onesta', '1parliament', '1paying', '1penny', '1people', '1plenary', '1protection', '1raise', '1reason', '1report', '1representative', '1rhen', '1s', '1she', '1ship', '1should', '1simplification', '1stays', '1that', '1the', '1there', '1they', '1thing', '1think', '1to', '1union', '1unprecedented', '1want', '1was', '1we', '1were', '1what', '1who', '1will', '1with', '1wortmann', '1would', '1you', '21', '2able', '2admiration', '2agreed', '2and', '2another', '2appointed', '2are', '2become', '2cannot', '2citizens', '2closely', '2compatible', '2coordination', '2discussion', '2do']\n" ], [ "# This is the number of distinct features in the vectorizer r.n.\nprint(len(vectorizer.get_feature_names()))", "6677\n" ], [ "# Verify length and shape (Y and X should have the same length)\nlen(Y), X.shape # so, these are our X and Y rn", "_____no_output_____" ] ], [ [ "IFF you want to use the Information Gain midway passage, the following cell does it.", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom sklearn.feature_selection import mutual_info_classif\n\nres = zip(mutual_info_classif(X, Y, discrete_features='auto'),vectorizer.get_feature_names())\nsorted_features = sorted(res, key=lambda x: x[0])\n\nthreshold=-400\nselected = [e[1] for e in sorted_features[threshold:]]\ntoprint = [e for e in sorted_features[threshold:]]\nlen(selected)", "_____no_output_____" ] ], [ [ "You can go deeper with the IG, in the next cell. Since it is convoluted and we didn't take much out of it in the end, I marked it down and it is unpolished yet", "_____no_output_____" ], [ "\n\nbohed = [e for e in boh]\nig = [round(b[0],3) for b in bohed_]\nfea = [b[1] for b in bohed_]\n\n\ndf = pd.DataFrame(dict(feature=fea,ig=ig))\nprint(df.to_latex(index=False))\n\nX=[]\nfor text in texts:\n \n # extract the features again\n text = [e[1] for e in text]+[e[0] for e in text] #pos and word mixed\n #features = \" \".join(featureit_words(text, selected)) \n X.append(\" \".join(text))\nvectorizer = CountVectorizer(max_features=None, ngram_range=(1,3), vocabulary=fea)\nX = vectorizer.fit_transform(X)\n\niss=[]\nfor i in range(1,len(Y)):\n y = Y[i]\n if y>Y[i-1]: print(i)\n \n \nx2arr = X.toarray()\ni2f, s2f, t2f, w2f = [],[],[],[]\nfor i in range(len(fea)):\n feat = fea[i]\n print(feat)\n c = X.getcol(i).toarray()\n \n a,b,c,d = c[:50], c[50:100], c[100:149], c[149:]\n #i2f.append(a[0]), s2f.append(b[0]), t2f.append(c[0]), w2f.append(d[0])\n \n #i2f.append(np.mean(a)), s2f.append(np.mean(b)), t2f.append(np.mean(c)), w2f.append(np.mean(d))\n i2f.append(np.sum(a)), s2f.append(np.sum(b)), t2f.append(np.sum(c)), w2f.append(np.sum(d))\n \n\nig = [round(b[0],3) for b in bohed_]\nfea = [b[1] for b in bohed_]\n\n\ndf = pd.DataFrame(dict(feature=fea, inte=i2f, spo=s2f, tra=t2f, wro=w2f, ig=ig))\nprint(df.to_latex(index=False))", "_____no_output_____" ], [ "# Here begins the Classification", "_____no_output_____" ] ], [ [ "# CLF (classifier) will be our linear-kerneled Support Vector Machine\nclf = SVC(kernel='linear', random_state=0)", "_____no_output_____" ], [ "# we simply cross-validate X on Y with our machine, on 10 splits, using a weighter f1 score\nscores = cross_val_score(clf, X, Y, cv=10, scoring='f1_weighted')\nprint(scores)\nnp.mean(scores), np.std(scores)", "[0.81818182 0.90909091 0.81666667 0.95445135 0.86335404 0.60714286\n 0.72727273 0.90833333 0.90909091 0.81666667]\n" ], [ "%%time\n\n# The following cell brings it \"all together\" (without cross-validation)\n# We split the data in train and test, fit the model and generate a number of useful\n# performance metrics from it.\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=.1, random_state=42)\nprint(x_train.shape)\nclf = SVC(kernel='linear', random_state=0)\nclf.fit(x_train, y_train)\npredicted = clf.predict(x_test)\ngold = y_test\nfrom sklearn.metrics import precision_recall_fscore_support as pr\nbPrecis, bRecall, bFscore, bSupport = pr(gold, predicted, average='weighted')\nprint(bPrecis, bRecall, bFscore, bSupport)", "(198, 6677)\n0.9586776859504131 0.9545454545454546 0.9546395633352156 None\nCPU times: user 82.4 ms, sys: 2.4 ms, total: 84.8 ms\nWall time: 84.8 ms\n" ], [ "# Visualization\n\nfrom sklearn import metrics \nfrom sklearn.metrics import plot_confusion_matrix\nfrom matplotlib import pyplot as plt\n\ntitle = '' \n\nclassifier = clf\nX_test = x_test\n\nclass_names = \"WrO Tra SpO Si\".split()\n\n\ndisp = plot_confusion_matrix(classifier, X_test, y_test,\n display_labels=class_names,\n cmap=plt.cm.Blues,\n normalize='pred')\ndisp.ax_.set_title(title)\n\nprint(title)\n#plt.savefig(\"Kld_500_top\"+'.png')\nplt.show()", "\n" ] ], [ [ "c=0\ncoff = clf.coef_ #clf.steps[1][1].coef_\ncoff = coff.data\ntosort = []\nfor el in coff:\n tup=(abs(el),names[c])\n c+=1\n tosort.append(tup)\n #for feature in el: print(round(feature),3)\n #print(round(el[0],3), round(el[1],3), round(el[2],3))#, round(el[3],3))\n \ntosort.sort()\ntosort.reverse()\nfor el in tosort: print(el)", "_____no_output_____" ] ], [ [ "# Feature Exploration", "_____no_output_____" ], [ "# We try to gather the most representative features used by the SVM to tell\n# one class from another\n\nvalues_array = clf.coef_.toarray()\n\nused=[]\n\nc=0\nclasses = set(Y)\nnames = vectorizer.get_feature_names()\n\nclassmap = {2:'Tra', 3:'Wr orig'} ## uncomment if focusing on written\n#classmap = {0:'Int',1:'Sp orig'} ## uncomment if focusing on spoken\n#classmap = {0:'Int', 1:'Sp orig', 2:'Tra', 3:'Wr orig'} ## uncomment if using all 4 classes\n\nfor y in classes:\n for y_ in classes:\n if y!=y_ and (y_,y) not in used: \n print(\"\\n\",classmap[y], \"vs.\", classmap[y_],\"&\",end=\" \")\n used.append((y,y_))\n values = values_array[c]\n values_and_names = [(round(values[i],4), names[i]) for i in range(len(names))]\n values_and_names.sort()\n top=values_and_names[:10]\n for el in top: print(el[1],\"(\"+str(round(el[0],3))[1:]+\")\",end=\", \")\n print(\"\\\\\\\\\")\n c+=1", "\n Tra vs. Wr orig & my (0.071), our (0.064), farmers (0.061), welcome (0.057), at (0.056), debate (0.056), was (0.055), hm (0.053), as (0.052), their (0.052), \\\\\n" ], [ "# writing it out\n\n#out = open('/Users/yuribizzoni/Documents/.txt','w')\nfor el in values_and_names[:1000]: \n out.write(el[1]+\"(\"+str(el[0])[:]+\")\"+\"\\n\")\n\nout.close()", "_____no_output_____" ], [ "print(disp.confusion_matrix)\nnp.mean(scores), np.std(scores)", "[[0.90909091 0. ]\n [0.09090909 1. ]]\n" ] ] ]
[ "markdown", "code", "raw", "code", "raw", "code", "raw", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "raw", "raw" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "raw" ], [ "code", "code", "code", "code", "code", "code" ], [ "raw" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4aefa18ca169b37a85d55b79142af87d4831da94
22,827
ipynb
Jupyter Notebook
nbs/42_tabular.learner.ipynb
hussam789/fastai2
7eaa4a6a10a8836fbbb90360a7df92d170d1bba3
[ "Apache-2.0" ]
null
null
null
nbs/42_tabular.learner.ipynb
hussam789/fastai2
7eaa4a6a10a8836fbbb90360a7df92d170d1bba3
[ "Apache-2.0" ]
null
null
null
nbs/42_tabular.learner.ipynb
hussam789/fastai2
7eaa4a6a10a8836fbbb90360a7df92d170d1bba3
[ "Apache-2.0" ]
null
null
null
29.530401
125
0.41578
[ [ [ "#export\nfrom fastai2.basics import *\nfrom fastai2.tabular.core import *\nfrom fastai2.tabular.model import *", "_____no_output_____" ], [ "from nbdev.showdoc import *", "_____no_output_____" ], [ "#default_exp tabular.learner", "_____no_output_____" ] ], [ [ "# Tabular learner\n\n> The function to immediately get a `Learner` ready to train for tabular data", "_____no_output_____" ], [ "## Main functions", "_____no_output_____" ] ], [ [ "#export\nclass TabularLearner(Learner):\n \"`Learner` for tabular data\"\n def predict(self, row):\n tst_to = self.dls.valid_ds.new(pd.DataFrame(row).T)\n tst_to.process()\n dl = self.dls.valid.new(tst_to)\n inp,preds,_,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True)\n i = getattr(self.dls, 'n_inp', -1)\n b = (*tuplify(inp),*tuplify(dec_preds))\n full_dec = self.dls.decode((*tuplify(inp),*tuplify(dec_preds)))\n return full_dec,dec_preds[0],preds[0]", "_____no_output_____" ], [ "#export\n@delegates(Learner.__init__)\ndef tabular_learner(dls, layers=None, emb_szs=None, config=None, **kwargs):\n \"Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params.\"\n if config is None: config = tabular_config()\n if layers is None: layers = [200,100]\n to = dls.train_ds\n emb_szs = get_emb_sz(dls.train_ds, {} if emb_szs is None else emb_szs)\n model = TabularModel(emb_szs, len(dls.cont_names), get_c(dls), layers, **config)\n return TabularLearner(dls, model, **kwargs)", "_____no_output_____" ], [ "#export\n@typedispatch\ndef show_results(x:Tabular, y:Tabular, samples, outs, ctxs=None, max_n=10, **kwargs):\n df = x.all_cols[:max_n]\n for n in x.y_names: df[n+'_pred'] = y[n][:max_n].values\n display_df(df)", "_____no_output_____" ] ], [ [ "## Integration example with training", "_____no_output_____" ] ], [ [ "from fastai2.callback.all import *", "_____no_output_____" ], [ "path = untar_data(URLs.ADULT_SAMPLE)\ndf = pd.read_csv(path/'adult.csv')", "_____no_output_____" ], [ "cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']\ncont_names = ['age', 'fnlwgt', 'education-num']\nprocs = [Categorify, FillMissing, Normalize]\nsplits = RandomSplitter()(range_of(df))", "_____no_output_____" ], [ "to = TabularPandas(df, procs, cat_names, cont_names, y_names=\"salary\", splits=splits)", "_____no_output_____" ], [ "dls = to.dataloaders(bs=64)\ndls.show_batch()", "_____no_output_____" ], [ "learn = tabular_learner(dls, [200,100], metrics=accuracy)", "_____no_output_____" ], [ "learn.fit_one_cycle(1)", "_____no_output_____" ], [ "learn.show_results()", "_____no_output_____" ], [ "learn.predict(df.iloc[0])", "_____no_output_____" ], [ "#TODO: Fix prod for tabular\n#learn.export()\n#learn1 = torch.load('export.pkl')\n#learn1.predict(df.iloc[0])", "_____no_output_____" ] ], [ [ "## Export -", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.export import notebook2script\nnotebook2script()", "Converted 00_torch_core.ipynb.\nConverted 01_layers.ipynb.\nConverted 02_data.load.ipynb.\nConverted 03_data.core.ipynb.\nConverted 04_data.external.ipynb.\nConverted 05_data.transforms.ipynb.\nConverted 06_data.block.ipynb.\nConverted 07_vision.core.ipynb.\nConverted 08_vision.data.ipynb.\nConverted 09_vision.augment.ipynb.\nConverted 09b_vision.utils.ipynb.\nConverted 09c_vision.widgets.ipynb.\nConverted 10_tutorial.pets.ipynb.\nConverted 11_vision.models.xresnet.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_learner.ipynb.\nConverted 13a_metrics.ipynb.\nConverted 14_callback.schedule.ipynb.\nConverted 14a_callback.data.ipynb.\nConverted 15_callback.hook.ipynb.\nConverted 15a_vision.models.unet.ipynb.\nConverted 16_callback.progress.ipynb.\nConverted 17_callback.tracker.ipynb.\nConverted 18_callback.fp16.ipynb.\nConverted 19_callback.mixup.ipynb.\nConverted 20_interpret.ipynb.\nConverted 20a_distributed.ipynb.\nConverted 21_vision.learner.ipynb.\nConverted 22_tutorial.imagenette.ipynb.\nConverted 23_tutorial.transfer_learning.ipynb.\nConverted 24_vision.gan.ipynb.\nConverted 30_text.core.ipynb.\nConverted 31_text.data.ipynb.\nConverted 32_text.models.awdlstm.ipynb.\nConverted 33_text.models.core.ipynb.\nConverted 34_callback.rnn.ipynb.\nConverted 35_tutorial.wikitext.ipynb.\nConverted 36_text.models.qrnn.ipynb.\nConverted 37_text.learner.ipynb.\nConverted 38_tutorial.ulmfit.ipynb.\nConverted 40_tabular.core.ipynb.\nConverted 41_tabular.data.ipynb.\nConverted 42_tabular.learner.ipynb.\nConverted 43_tabular.model.ipynb.\nConverted 45_collab.ipynb.\nConverted 50_datablock_examples.ipynb.\nConverted 60_medical.imaging.ipynb.\nConverted 65_medical.text.ipynb.\nConverted 70_callback.wandb.ipynb.\nConverted 71_callback.tensorboard.ipynb.\nConverted 97_test_utils.ipynb.\nConverted index.ipynb.\nConverted migrating.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4aefafa6d1ae81492c64bd4979aacec2aa65ae1a
162,305
ipynb
Jupyter Notebook
secondaryPtychography.ipynb
tangchini/OPTI556
adcaf1fb8168c21d012b59abc8477c8a4a0f9a37
[ "MIT" ]
null
null
null
secondaryPtychography.ipynb
tangchini/OPTI556
adcaf1fb8168c21d012b59abc8477c8a4a0f9a37
[ "MIT" ]
null
null
null
secondaryPtychography.ipynb
tangchini/OPTI556
adcaf1fb8168c21d012b59abc8477c8a4a0f9a37
[ "MIT" ]
null
null
null
1,159.321429
157,297
0.949761
[ [ [ "<a href=\"https://colab.research.google.com/github/tangchini/OPTI556/blob/main/secondaryPtychography.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "# Time of flight ptychography\n###David Brady\n### University of Arizona\n\nNovember 2021", "_____no_output_____" ], [ "### Python modules", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom google.colab import files\nfrom scipy import signal, io\nfrom scipy import integrate\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [30, 10]\nplt.rcParams.update({'font.size': 22})\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.models import Model\nimport cv2\nfrom keras.datasets import mnist\n", "_____no_output_____" ] ], [ [ "## Forward Model", "_____no_output_____" ], [ "We consider imaging on the system illustrated below. We consider an illumination source that projects a focused spot on to the reflecting wall. The focused spot produces an illumination wave $A\\frac{e^{i 2 \\pi \\frac{(x-x_s)^2}{\\lambda z}}}{z}$ in the object space, where $z$ is the range from the reflecting wall to the target. The return signal on the wall is\n$$\\psi(x')= A\\int \\int f(x,z)\\frac{e^{i 2 \\pi \\frac{(x-x_s)^2}{\\lambda z}}}{z}\\frac{e^{-i 2 \\pi \\frac{(x'-x)^2}{\\lambda z}}}{z} dx dz\n$$\nwhere, implicitly, $x$ corresponds to the 2D $xy$ plane. A remote camera array forms an image of $|\\psi(x')|^2$. The measured signal is \n$$g(x')= \\frac{|A|^2}{z^2}\\left |\\int f(x)e^{i 4 \\pi \\frac{(x'-x_s)x}{\\lambda z}} dx \\right |^2\n$$\nwhere we assume for simplicity that $f(x,z)=f(x)\\delta(z-z_o)$, e.g. that the object is a surface at a fixed distance. Thus, the observed signal is \n$$g(x')= \\frac{|A|^2}{z^2}\\left |{\\hat f}\\left ( u= \\frac{2(x'-x_s)}{\\lambda z}\\right )\\right |^2\n$$\nWhere ${\\hat f}(u)$ is the Fourier transform of $f(x)$. Thus, by scanning $x_s$ over a range of positions we can sample ${\\hat f}(u)$ over the full plane. We use ptychographic phase retrieval to recover ${\\hat f}(u)$ from the range of samples. \n\nThe angular resolution with which we can reconstruct $f(x)$ is equal to the inverse of the maximum spatial frequency measured, $u_{\\rm max}=\\frac{2\\Delta x}{\\lambda z}=\\frac{4A}{\\lambda z}$, where $A$ is the aperture allowed $x$ and $x_s$. so the resolution is $\\delta x=\\frac{\\lambda z}{4A}$. The field of view depends on the sampling rate in the fourier space. If the range from the camera array to the reflecting wall is $R$, this rate is $2 R/(z\\alpha) $, where $\\alpha $ is the aperture of the camera array. The FoV is $(z\\alpha)/(2R) $. The number of points resolved is $(2A\\alpha)/(\\lambda R) $. The angular field of view is $\\frac{\\alpha}{R}$.", "_____no_output_____" ], [ "![nlosPtychography.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABdwAAAOECAYAAAC7OPPEAAABb2lDQ1BpY2MAACi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AADQAoE7AAAAAAC0QOAOAAAAAAAtELgDAAAAAEALBO4AAAAAANACgTsAAAAAALRA4A4AAAAAAC0QuAMAAAAAQAsE7gAAAAAA0AKBOwAAAAAAtEDgDgAAAAAALRC4AwAAAABACwTuAAAAAADQAoE7AAAAAAC0QOAOAAAAAAAtELgDAAAAAEALBO4AAAAAANACgTsAAAAAALRA4A4AAAAAAC0QuAMAAAAAQAsE7gAAAAAA0AKBOwAAAAAAtEDgDgAAAAAALRC4AwAAAABACwTuAAAAAADQAoE7AAAAAAC0QOAOAAAAAAAtELgDAAAAAEALBO4AAAzK85///PKsZz2rnhYvXjzQ1bd4Z511Vu/z9fGPf3ygqwMAACPAmIGuAAAAcdlll5WHH364nn/iiScGuDYLFy4sl1xyST1/6KGHDnBtAABgJFDhDgAAAAAALRC4AwAAAABACwTuAACMWE899VR56KGHyqOPPjrQVQeU20pLndxezgMAAKxJD3cAANZp5cqV5U/+5E/q+ccff7z38r/6q78qO+6442rX3W+//cq73/3uev7iiy8u5557bpk9e3a58cYby1133VWD6tGjR5edd965zJgxo5x88snl7W9/e5k+fXrpy/e+971y3nnn1fOnnHJKPcWDDz5YfvCDH5RrrrmmbLXVVuXDH/5w2X777Vf73UsvvbR87nOfKz/72c/K0qVL62UTJkwoL3rRi8q73vWuelnuX7z2ta8tz372s0tf8vi/9a1vla9//evlwgsvrH87xo0bVxdDPf3008vrX//6ej8aP/7xj8vPf/7z+tgbF110UfmjP/qjtW7/Pe95T9l3333XuhwAABieRj2lPAcAgHV48skny9Zbbz3Q1arnPe955Ve/+lU9f8wxx6wWOK/LtttuWz7/+c+XP/iDP1jrZwmo//7v/76eT8D/kY98pJxzzjk15F68eHHv9e69996y++671/MJyN///veXz372s2vdXqcddtihdwHYL33pS+UP//AP17rOHXfcUX73d3+3XH755Wv9rNOLX/zi8t3vfrfstNNO9fu//Mu/LP/zf/7Pfn+ncf7555fnPOc5A10NAAAYJlS4AwDQr1SlR8LsRiq6R40a1ef11jR27Nhy0EEH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M19XXZhthuu+16zz/00EP9XLN/W2+9de/5k046qfz0pz/t59oAAACrs2gqAACtWbZsWfne977X+/1ZZ51V3vrWt7YWrK9LquUb8+fP7+ea/UslfqOzvQwAAMBgCNwBAFhvq1at6vPy6667rvdn48ePL6eeemqf12vbwQcf3Hv+wgsv7Oea/TvssMN6z990001l6dKl/Vx78Nb1fAEAACOLwB0AgEEZPXp07/nOXuedHn744d7z6We+1VZDs7v5whe+sPf8L37xi3L77bev87pPPfVUrcTvS/rL77fffvX8ypUry5lnntnn9Qaj8/l6/PHH+7kmAAAwUgzNERAAAMPehAkTes/feuutfV6nc5HRhQsX1gVU1+W73/1uvz9fHwncp0yZUs8nKH/DG95Q7r333rWud/3115dXv/rV5cc//vFaP4tRo0aVt7/97b3fn3HGGeWaa67p87qdHnjggdq7vlPn83XzzTev+SsAAMAIJHAHAGBQjjnmmN7zn/zkJ1dbnDQtUxIqH3LIIWWvvfbqvfwtb3lLWbJkyWq3M2/evPKmN72pvPa1ry1PPPFEaUMWO819alx22WW1Uv2//tf/Wj70oQ+Vd77zneWoo44qhx56aPnBD37Qzy2Vet0ZM2bU86nYf97znle++tWvlhUrVqx13Xvuuad8/OMfr3/rn//5n1f72dFHH917fvbs2eX73//+aj9ftGhRuf/++wsAADBybNrVqwAAGDFOP/308u1vf7uev+CCC8ree+9dQ+y0Trn66qvLQQcdVH71q1+V97///eW9731vvV7au+R6xx57bNlpp51qRXsqxtPWZZtttqktZx577LH+/uygJVy/8sory2c+85n6/fLly8s3vvGNta63//77l912261cdNFFa/0s0grn7LPPLieffHIdLEj7mTz2P/3TPy3HHXdc2X333et9zgDDtddeWx9L7LDDDqvdzoEHHlivf+mll9bvU1mfHvGpxF+8eHG9r+edd155znOes9Z9AAAAhicV7gAADMpLXvKSWv3dSBD9n//5n+XnP/95DZAb7373u8vrXve63u/T7/3Xv/51+dGPflSD+QTU6ZV+/vnnr1YN34ZPf/rT5etf/3qZNm3aWj/LIq6pdr/iiivK9OnTey8fM2btGp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WM4999yydOnSGri/7GUvK6eeemqZMmVKGT169EA3A8BmInAHAAAA6AIrV66sAfvs2bPLL37xi3LDDTfUAH7JkiVlwoQJ5bjjjiuTJ08WuAN0MYE7AAAAwGaWXu33339/ufrqq8tvfvOb2lImfdxXrVpVHn300bJs2bLy2GOPWUAVoMsJ3AEAAAA2kwToCdLvvvvuct1119Ww/frrr6993POzLJI6ZsyYsu2221o0FWAYELgDAAAADKEE6Wkfk+r1hx9+uMydO7dcfPHF5bLLLiu33XZbbSGz1VZb1aA9ttlmm3o+7WXyOwB0L4E7AAAAwBBJaJ7q9eXLl9d+7alsT8/2hO133nln/VnC9l122aW2lMkpgXsC+gcffLB+n2p3ALqTwB0AAABgCCQsX7x4cbnpppvKzTffXBYuXFgWLVpU5s+fX+65557aWiZtY/bYY4+y11571er3hPBNSH/vvffWfu477rij1jIAXUrgDgAAALAJpYVMwvNUs6eS/cILLyx33HFHrVhPyJ4FU1PBvsMOO9SgfdasWWX//fevoXyq4NNiJoum5vfzO7vttltvuxkAuoutMwAAAEDL0ms9lempak9IPm/evNo65pJLLilz5sypl0Uq2seOHVvD9ilTppRjjjmmHH/88fX7BO2pZH/yySdrZfv9999fvybAB6A7CdwBAAAAWpIwPBXrDzzwQLnrrrtqVXq+draRSWievuzp0z5x4sR6Stg+c+bMcsghh5RJkybVFjI77bRT2W677XpD91TJ53KBO0D3ErgDAAAAtCBV7QnTE7JfffXV9ZTK9vvuu6+2hklVe4LzhOgJ2NM65rDDDiv77LNP2X333WsAn5A9i6ImVN91113r96mCz20/9NBDNcjPbSSwB6D7CNwBAAAANkL6rydoX758ea1gv/LKK8tFF11Ubr/99t6APIF5KtUToO+99961bcxzn/vcWtW+/fbb1wB99OjRZauttqq3mZB9woQJNXTPz9Kepgnc06YmvwNA9xG4AwAAAGyAJmhPCJ5FUG+77bbanz1f58+f39unPRXtCch33nnnGrYfeeSRtVf7vvvuW8aNG1eD+DVlUdRcP6F7erwntE+rmoT6+ZoK+L5+D4DNS+AO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aNaBrPd7/7XXf//fefJvTSpv75z39uTv1oEMKvueYa++5oV//qV78y8T56/7/zne+Ya53jp03rXfoI85677747IrbTFifa5qtf/eop+8G2zz77rLvllluqNYO0LuG88neMs53CqMxQ4Hukf4O7H+c6taOot0RkELc8V52ZvUII0dCQ4C6EELUAnRUamzSqaZTSWK0OCPc4Q2jw464pS3DHuUPj17t1srKyXK9evcp4t6rBPiOIQ3Uc7uCnj7L/nAemnkZPFd66dat9jnfICCEaIb7oKQ72Q4dMZKeoKUJ7QXCNQGC3bHYKoQbXVMtjR6TAyR5cZ5OD60xKcM0tCRakEQT11G7dXFqPHqH89a5dTXg3wT3seDdBPiyyCyFEPKEthmmBdhtiNItvy9UGxLFU1kH8uc99zjLWAUHax8hMmDDB/f73vz+tqCX7TJQMbct7773XnkNURmD3EYa45H1OOftBdvo555zjStMjuCYjuF933XVu3bp1p71eE4g3YQHqAd13331lnhOc+w888ID78pe/bO1nD8eGscXf55jLYurUqe6uu+6yBRig+O1vf2v3OUcI7B4E+RtvvPG096BtfP3119t74BRPVOgD+BgZYnQYSGBggkEJDDXUjBo/frw52ocMGWJOfvo/KowqhBAhKvfLLIQQosowddTnddJgrQ50GmjUIqaXl4HOOnTm+BycVIjv8RDcffY6S7TbqSowQOCnVCO4R58H9hnB3XdA41nsVQiRoHBNwZWOkz2crW6xMcF94mFOfvqpieyFuNr37w8524PrBq9btAsCT/h655o0sRiY1MxMl9atm0sibz24HqZ07GgOdouKIZ+dgT+EdkQAxP1wwVQhhIg3vnYPzuXoGjuI0/GqsVMWlZ2J6I0UtCt9Fjr84Ac/qFAoxT3+4IMPmpGE+BhyvCkgCojOHrLgyxLboxk9erQt8SQ6cx3DS6yZniNGjIjc57siJgeYjYo7viIYMPCCOxErHgYs/HdOhMwNN9xQ1ub1AtrtDECsWbPGvfPOO1YAl8EB/s6YwUA/g+958uTJbtCgQdbeZ4CjtgaVhBCiPiLBXQghagmmVOIEqahgaGVAuKdjVF4+OwWfPvzww0hOKA4fc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kK/MEIIIYQQQgghRJxAUG/WrJmJvNwSJxPtchfxB7F9//79ltc+d+5c99FHH7k9e/ZYgVS+h27durlRo0a5kSNHuq5du7omTZrEekshhBCi2khwF0IIIYQQQggh4oyPlGHB5e7jZUR8YRCDzHZiZBDbFy9ebGI7tGvXzvXt29eNHTvWnO29evVyTZs2jfGOQgghRM2Q4C6EEEIIIYQQQsQRiqb6gqlytdcu5LNnZWVZhIx3tnP+yWg/66yz3IwZM0xwx9lO1I8K1wohhKhtJLgLIYQQQgghhBBxAhc7+eAsRJ2wHDx40B09etREeAm+8YPImJycHIuSWbFihd3nfLdt29bE9vPOO89NmDDBMtsVIyOEEKKukOAuhBBCCCGEEELECQR3xF1iZHBasxB5QvFOud3jB852BPZly5a5+fPnu02bNrljx45Zbj4xMtOnTzexHWc7OfpCCCFEXSHBXQghhBBCCCGEiCM42RGEWRDcEYK5FfGB87p7926LkXn77bfN4Z6Xl2eDHeS2Dx061I0ePdp16tRJYrsQQog6R3PZhBBCCCGEEEKIOIP4i6MdoR13O4vPdRfVx8fILF261Iqkrl692h04cMDON1EyAwcONLG9W7duKpAqhBDijCCHuxBCCCGEEEIIESfIaCfWpFWrVib44sY+ceKEO3TokInFEoGrD+dy7969bvny5e6dd95xa9eutXx8XOzt27e33PZp06a54cOHu/T0dBPhhRBCiLpGgrsQQgghhBBCCBEnEHlbtGjhOnToYKI7znbw8TKienD+srKyImL7xx9/bDEyiO242ceOHesmTZpkojvnXlEyQgghzhQS3IUQQgghhBBCiDiC2NumTRsT3HG2p6amWhFVOa6rB4MW2dnZbtGiRW7evHlu3bp1FiPDeaYo6sSJE61I6qBBg1zr1q3tXAshhBBnCgnuQgghhBBCCCFEHEHwJTqGaBnuewGYTHdReThfxPFQINVntq9atcpiZDinFEgdMWKEmzJlihs8eLANcmhQQwghxJlGgrsQQgghhBBCCBFHEH0RhIuKiiwKBZc78SfcR0SWKFw5cLZv377dxPb33nvPbdiwwcR2ziFiO1ntkydPjjjbdV6FEEIkAh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8u+7fZd8v+e8L2tFvMfEfZJ0yv9hyTrLbaamUun4033rjszyaAH5vFNAAwrhK4081dd91VJpLMpb2i+rnnnmvdPyI9rEdUqn9TFRHpeZ0+gAno7r///jI5zyGHHFIqJ9LqY2KUHuO1o446qoSgqTrJhEWpMk6lctq09BfMZijrqquu2rq94447VldccUXpw56RBanIvvjii/t4hX/KQUN6nteV32lNss4665RJlOoqnYTFxx13XLXeeuu12tekMj6h9dh26qmnln7sCZ9z0qFud5O/GS6bSu66eju/u/weI9vb/hu84IILSuiccL4OrVONfvjhh1ff+MY3WsvttNNOnU4qxaabbtoavZCKofS9/PWvf11+8zfddFP1X//1X+W9209WNCHrkRMktfx28u/vxhtvLFXoH374YaliGjp0aJkr4Nhjj21tW773008/vZwEivxullxyyep73/teWe+0xsnzc/9FF11UPsf8Lq+++uoe1wUAYGKQUYY51qn7mydkz1w/2Zfva3TqmJD9vKxD9mHTBjLFTykayX59TgpkPz6ToGafLiNVU0jxla98pZp77rlLC5lsGwDQnRlN6GaLLbYok0d2lbCxDhwPPvjgxqrNM+HOD37wgxIyRlps/Md//Ee35VKhnSrbX/7yl90em5AlYD/vvPPKd5Kd4oSguXSVEHn66acv4WdvEo7ecsst5frzzz9fAuN2Bx10ULXVVlv19NROUuF+2mmnlQrsyImRVD+np2MuXVuIJJg999xzx5mhpjmRVP+ec6AwaNCgcrKnfVhvDowSqrfPMZATCMccc0zrt3rllVeWS0LoVPd0rZxPFVBPJ0LS93K//fZrVY/nBMqWW27ZbbkczCy++OKdquVHV06WvPbaa63JeDMJVi4jYrHFFivbmzA9VVD5zI4++uhyAQCgu+xrJrTO/l/m00mBQkL37I+mtUz278fGPnLC9BRMpOXik08+WQpOHn744XLMkar2yEmC9Gdfa621yv5/5iTKvr6gHQD65v+UjBMSKn/nO9/p9fGEwNkJTOA+scmOeaqeU3Hcm5ygSGjb1zKRSupUstdVyqNj5513LqHt7LPP3rovO+ftYXsOHrJchqa2T9g5tuSEQqrP24e+JmTv2tM+B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pD9zTuiWBdnq2Zy6oTF6auYESwg+khPuZxyjzBj322GNlLp68f9Zn/vnnL/NfZWLUrCcAMHpUuAMAAMAASnuWelLS999/v1SbJ/Seeuqpy+Np65Kwe6AmT03rmHfffbd69tlnW2F72sakl/xKK61ULbTQQtWgQYO0kAGABgzM/80BAACAIi1kpplmmnJJqP2nP/2pTKT68ssvl0lME4APpPSKf/3118v7ffjhhyXYn2666cokqalun3766cdIWxsAmBgI3AEAAGAAfeELXygtZRK4p71LJi994403SgietjIDVdle++STT8r7vf322+V6TgB8+ctfrhZeeOFq5pln1koGABo0sP9XBwAAgIlcAvX0bk/P9ITvqWhPT/VUtycAH0h5rwT8CdtT3Z4K+7STSeCevu25DgA0Rw93AAAAGGCpKk/P9vRKr0P3BOC5xED0T0+v+IT6mSz11VdfLeF+3jvrkbB9qqmmKrcBgOaocAcAAIABlh7pM8wwQzXjjDOWqvK///3vpco9/dwTjDctgf4777xT3XfffdXNN99cQvf0cs97p43MHHPMYaJUABgAAncAAAAYYAncE3TPN9981ZRTTlnazHz00UfVe++916pyb8rf/va36v33368efPDB6vrrr6/uvffe6q233ir949NHPusw22yzlTY3AECzBO4AAAAwwBKwp4XLggsuWMLuySefvITwqXRPhXv+NiWtY1566aXqrrvuqh577LES6ieET9i+6KKLVksvvXQ100wzlfcHAJqlhzsAAACMAZNOOmmZrHTxxRcvoXjavswyyyzVFFNM0Vhrl88++6wE7I8++mj15JNPVn/84x/La0833XQlaF9zzTVL6J7wPycBAIBmCdwBAABgDEjwnQlLl1pqqdJWJpXtc845ZzXttNM2En7XfeGff/75Utn+5ptvlvvyXosttlgJ2/PeWYcvfnHMxQEvvvhidfbZZ1f33HNP6SufEw/TTz99tdxyy1X77rtvteuuu7aWveCCC/p4Jehf5iv47//+73I9kwMfc8wxnR4/88wzq9tuu61c33rrrasNNtig60sAjJbPdaSJGwAAADDgcgieyvb0b0+bl0ximl7qTVS4//nPf66eeuqpMknqHXfcUb3xxhvVF77whWqeeeapNt544+qrX/1qaSXTRLg/on72s59Ve++9d48Twy6wwALV3XffXVrd1Mb3iGLo0KHVLbfcUq4n7E24y5iV3/6qq65ari+yyCLV448/3unxXXbZpTrrrLPK9WHDhlX7779/t9cAGB1j7pQ2AAAATOQSrE8yySSt/ulNBO0J7hO2p7L3pptuKr3bU0mesH2GGWaollxyyVLh3lQl/Yi69tprq29/+9ud7svEsdn2nAwYX/zmN7+pTjvttHJ97bXXrvbbb79el00rnxtuuKFczwkFACY+AncAAAAYw5oI2iMV4QnbU8WbyvaE7QmzE8InbE/QvuKKK1azzz57CfrHlKzXgQce2Lqd1h0//vGPS+AeqXjPCYLxwSuvvNIK0TNCAAD6InAHAACA8dRf//rX6oUXXihtTH73u9+VsD1hdiZinW222arll1++Wmihhap//dd/bSzkHxHpI//EE0+U6wmpzznnnE6Bf67nZEAmdZ2Q5MRCRhTE4MGD+1kagAmRwB0AAADGM6kg/+STT6q33nqrevDBB6uHHnqo+v3vf1999tln1aBBg8pkrKlsX2KJJUqP9LSXGZMeeeSR1vWvfOUrY7S6fmzKBJwm4QSYuAncAQAAYDySsD2V7Wl18sADD1T3339/9fbbb1d///vfSyX7fPPNV6222mpl4sgvf/nL1aSTTtrfSzbuvffea13XhgWAiYnAHQAAAMYjn376afW///u/1a233lp6tr/88svVxx9/XML2ueaaq1pzzTVLVXlaymTy1LPOOqs8Lz3dd9ttt3I9oX2q4m+//fbqL3/5S7XpppuWFi/t0gf+0ksvrS688MLq3nvvLRX0qZRPiL/yyitX3/zmN6uvfvWrnZ5zxx13lIlbcxKgdt9991WHHXZYp+WWWmqpaqONNqpGRnrVZ1syieljjz1W2tHkZMK8885btnnPPfcs1/vz9NNPV+eee241fPjw8tllpMB0001XLb744tW6665bbb755tVUU01V3XbbbeVy9913t5778MMPd9uW2H777au55567fE6ZLDbSWmaTTTbptNwJJ5zQaqPzrW99q5yMSEugo446qvrtb39bvfbaa6Ud0L/927+Vx7fZZpt+WwHl5MZPf/rT8rmkjU9GOcw444zVSiutVO24446lpdD5559fll144YWrLbfcss/X6+oPf/hDddJJJ7Vuf+973+t1xEK2PZ9B7LvvvtWUU07Z43LXXXdddc8995Trq6++erlEfmM33nhj+f1kAtr8zt9///3ye81r5beXNklDhgxpte4BGOd0AAAAAOONDz74oOPmm2/u2G233TpWXXXVjiWXXLJj2WWX7dhss806TjzxxI4nn3yy4+OPPy7L3nXXXR059M9lkUUWKfe9+eabHeuvv37r/lxOPfXUTu/xwgsvdCy99NKdlunpsssuu3R8+umnrecdffTR/T4nl5133rks//7773e6vzfXXXddx4wzztjna04yySQdZ5xxRq+v8Ze//KW87+c+97k+X+dLX/pSxymnnNJx6KGH9rsd9eXGG28s7/GTn/ykdd+QIUO6rcMcc8zRevzBBx/sOO200zqmmGKKXl93u+226/jb3/7W7XVqV199dcfgwYP7XLf2xzfffPNeX6s3+X6nmmqq1mvcc889vS6b32K93EUXXdTrcmuuuWZrucsvv7x1/0EHHdTntrRf9tprr47PPvus22sPHz68tUz9m2+X30D9+LBhw7o9DjC6VLgDAADAeCQVz6k0T3X35JNPXn3xi1+spp122mqZZZYpVc2zzz57r21kUoGcque0oOnNc889V9rRpD98ZPLP9dZbr5p11lmrjz76qFSsp7I+zjzzzPL+p556aq+vN7pSZZ+q7LTMiVSxr7HGGmW9Un198803lyrxTBabqvtUp2+xxRadXuPDDz+s1lprrVZVdXzpS18qVe35rDLJayacjWxjWvVkewdSvof2Xvep4O7o6CgjDmqpTF9hhRVaIxPaXXPNNdXGG29cRiLU5plnnmqWWWYpowGeeeaZMvIhn9HoyPebERNXXXVVuZ3JeZdbbrluy6XFUUYA1FJxv9VWW3VbLt9jfkOR33JeuzfZllS15/ee0Rovvvhi+YwiVfdTTz119cMf/rDX5wOMDZ/vbwEAAABg3PEv//Iv1RxzzFFCzwTsCZ8TvK699tqlf3uC5J48++yzZULPhO1pCbLKKqtUW2+9dbXZZpu1+qwntE5LlTps33nnnUuQesEFF1THHHNMdeKJJ5bANcF9/T4/+9nPyn2RNiIJjI8//vjW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AAAo3SURBVBkhkHWtA/ecfBhds802WzXvvPNWzz//fLm94YYbtnrK9yRtZUYkcM8cAkOHDq0OOOCAcjvtg3KCpV3W/5hjjim/xVNOOaWnlwEY60b/v7QAAADAOCntYep+3/VklyNixRVXLFXsF110Uak6vvvuuzu1TUmonSrzVKBvs802nQLqyO36fXuaTLOWoLa9H3lvvvnNb5ZK6QTfV155Zenx3d4qJZX36Que8HeLLbbocdLNhPCPPvpomTg11eDZpjrAT6iex1PNv8MOO5Tq6q7PzXumlcs111xTvf322+X+jAhIy5n6s82kovX2tLeiqeX16+f2NzFoAuh6/bp+vrWE14888kj5rnJJW5zBgweX5+YkReTkSa29H/3o2G233Vq98Hfcccc+l82ktflOUoWfzzm/rd6kyj2f/fe///1Ofdzze9t8882r7373u+Xx9OivP+eE/+2y/X395tOSprfnAjThcx09NWIDAAAA+P8lOki7lQTAk046aQk1e5okc0xJG5W0GUnoPmjQoNLSJmHuyKi3Ka+R8DvbNaLynEz02UTF+EBLSJ2q8Dj++OOrffbZp59njBvSm/7NN98sYXuC85H5fgDGJoE7AAAAwAQokU8qulPZH+lD39eIAwBG39g7HQ0AAADAKElLl48//rjPZU444YRW2D7ffPOVVjMADCwV7gAAAADjmUwE++qrr5a+8KusskqpZE+rn/RKf/rpp6tf/OIX1fXXX99aPr34M2ksAANL4A4AAAAwnkng/sQTT/S3WJHJSIcNG9bfYgA0QEsZAAAAgPHM9NNP398i1dxzz10q3YcOHdrfogA0RIU7AAAAwHgmcU5ayjz88MPVc889V73zzjvVJ598Uk022WTVbLPNVi277LJlgtTPf16tJcCYJHAHAAAAAIAGOM0JAAAAAAANELgDAAAAAEADBO4AAAAAANAAgTsAAAAAADRA4A4AAAAAAA0QuAMAAAAAQAME7gAAAAAA0ACBOwAAAAAANEDgDgAAAAAADRC4AwAAAABAAwTuAAAAAADQAIE7AAAAAAA0QOAOAAAAAAANELgDAAAAAEADBO4AAAAAANAAgTsAAAAAADRA4A4AAAAAAA0QuAMAAAAAQAME7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AAAAAADRA4A4AAAAAAA0QuAMAAAAAQAME7gAAAAAA0ACBOwAAAAAANEDgDgAAAAAADRC4AwAAAABAAwTuAAAAAADQAIE7AAAAAAA0QOAOAAAAAAANELgDAAAAAEADBO4AAAAAANAAgTsAAAAAADTg/wOpI9Dmyxty6wAAAABJRU5ErkJggg==)", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ] ]
4aefb39c443208f94f2a5f08eaeafce26722acd1
645,470
ipynb
Jupyter Notebook
visualisation/tutorials/Coastlines.ipynb
mrocklin/notebook-examples
7a91addde701f4fe50ebf152d5b1e5593bf36aa2
[ "Apache-2.0" ]
2
2019-06-19T06:11:36.000Z
2020-06-13T18:27:33.000Z
visualisation/tutorials/Coastlines.ipynb
mrocklin/notebook-examples
7a91addde701f4fe50ebf152d5b1e5593bf36aa2
[ "Apache-2.0" ]
null
null
null
visualisation/tutorials/Coastlines.ipynb
mrocklin/notebook-examples
7a91addde701f4fe50ebf152d5b1e5593bf36aa2
[ "Apache-2.0" ]
null
null
null
2,272.78169
197,460
0.961428
[ [ [ "# Exploring different Coastline options in Magics\n\nThis notebook will help you discover lots of posibilities for designing background of your maps in Magics.\n\nFrom your workstation: \nload magics \n\nmodule swap(or load) Magics/new \njupyter notebook \n\nload this notebook\n\n", "_____no_output_____" ], [ "**mcoast** controls background of our maps. Here you can set things like colours of land and sea, coastline resolution and colour, and also grid, rivers, boarders, cities etc. \nList of all **mcoast** parameters you can find [here](https://confluence.ecmwf.int/display/MAGP/Coastlines \"Coastlines parameters\")\n", "_____no_output_____" ], [ "### Import Magics and define non coastline paramters\n\nFor start we will define some none coastline parameters, which we will not change later.", "_____no_output_____" ] ], [ [ "import Magics.macro as magics\n\nprojection = magics.mmap(\n subpage_map_library_area = \"on\",\n subpage_map_area_name = 'central_europe'\n)\n", "_____no_output_____" ] ], [ [ "As with all Magics functions, default is something you can start with. But if you don't like it, *everything* can be changed", "_____no_output_____" ] ], [ [ "coast = magics.mcoast()\n\nmagics.plot(projection, coast)", "_____no_output_____" ] ], [ [ "### High resolution coastline and dash gridlines\nIn Magics we can fully control how land and sea look like. \nCoastline resolution can be 'low', 'medium' or 'high', or if you want to leave Magics to decide, you can set it as 'automatic'. \nLand and sea can be shaded or not, and you can set the colour. \nYou can choose to have gridlines or not, their frequency, style, colour, thickness, labels...", "_____no_output_____" ] ], [ [ "coast = magics.mcoast( \n map_coastline_style = \"solid\",\n map_coastline_colour = \"tan\",\n map_coastline_resolution = \"high\",\n map_coastline_land_shade = \"on\",\n map_coastline_land_shade_colour = \"cream\",\n map_grid = \"on\",\n map_grid_colour = \"tan\",\n map_grid_latitude_increment = 5.00,\n map_grid_longitude_increment = 10.00,\n map_grid_line_style = \"dash\",\n map_label = \"on\",\n map_label_colour = \"charcoal\",\n map_label_height = 0.35,\n map_label_latitude_frequency = 2,\n map_label_longitude_frequency = 2,\n map_label_blanking = \"off\"\n )\n\nmagics.plot(projection, coast)", "_____no_output_____" ] ], [ [ "### Administrative boundaries, cities and rivers", "_____no_output_____" ] ], [ [ "coast = magics.mcoast(\n map_boundaries = \"on\",\n map_boundaries_colour = \"red\",\n map_coastline_resolution = \"high\",\n map_coastline_land_shade_colour = \"cream\",\n map_cities = \"on\",\n map_grid = \"off\",\n map_coastline_land_shade = \"on\",\n map_coastline_colour = \"tan\",\n map_administrative_boundaries = \"on\",\n map_administrative_boundaries_countries_list = [\"FRA\", \"ESP\", \"GBR\"],\n map_administrative_boundaries_colour = \"orange\",\n map_rivers = \"on\"\n)\n\nmagics.plot(projection, coast)", "_____no_output_____" ] ], [ [ "### Grid lines, boundaries and rivers", "_____no_output_____" ] ], [ [ "coast = magics.mcoast(\n map_boundaries = \"on\",\n map_boundaries_colour = \"red\",\n map_coastline_resolution = \"high\",\n map_coastline_colour = \"tan\",\n map_coastline_land_shade = \"on\", \n map_coastline_land_shade_colour = \"cream\",\n map_grid = \"on\",\n map_grid_line_style = \"dot\",\n map_grid_colour = \"tan\",\n map_grid_latitude_increment = 2.00,\n map_grid_longitude_increment = 2.00, \n map_grid_latitude_reference = 0.00,\n map_rivers = \"on\"\n)\n\nmagics.plot(projection, coast)", "_____no_output_____" ] ], [ [ "### Sea, lakes and rivers", "_____no_output_____" ] ], [ [ "coast = magics.mcoast(\n map_coastline_sea_shade_colour = \"sky\",\n map_coastline_resolution = \"high\",\n map_rivers_colour = \"sky\",\n map_grid = \"off\",\n map_coastline_land_shade = \"off\",\n map_coastline_colour = \"sky\",\n map_coastline_sea_shade = \"on\",\n map_rivers = \"on\")\n\n\nmagics.plot(projection, coast)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aefb5305d7a605503568d20b15e70075e84d322
45,570
ipynb
Jupyter Notebook
testing/benchmarking/automated-benchmark/README.ipynb
eastmon94/seldon-core
514eb289fe44dbd46e4d0eb9b3417bdcec49d080
[ "Apache-2.0" ]
null
null
null
testing/benchmarking/automated-benchmark/README.ipynb
eastmon94/seldon-core
514eb289fe44dbd46e4d0eb9b3417bdcec49d080
[ "Apache-2.0" ]
55
2021-09-02T22:35:35.000Z
2022-03-28T11:11:44.000Z
testing/benchmarking/automated-benchmark/README.ipynb
eastmon94/seldon-core
514eb289fe44dbd46e4d0eb9b3417bdcec49d080
[ "Apache-2.0" ]
null
null
null
91.875
4,064
0.317907
[ [ [ "# Benchmarking with Argo Worfklows & Vegeta\n\nIn this notebook we will dive into how you can run bench marking with batch processing with Argo Workflows, Seldon Core and Vegeta.\n\nDependencies:\n\n* Seldon core installed as per the docs with Istio as an ingress \n* Argo Workfklows installed in cluster (and argo CLI for commands)\n", "_____no_output_____" ], [ "## Setup\n\n### Install Seldon Core\nUse the notebook to [set-up Seldon Core with Ambassador or Istio Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html).\n\nNote: If running with KIND you need to make sure do follow [these steps](https://github.com/argoproj/argo-workflows/issues/2376#issuecomment-595593237) as workaround to the `/.../docker.sock` known issue.\n", "_____no_output_____" ], [ "### Install Argo Workflows\nYou can follow the instructions from the official [Argo Workflows Documentation](https://github.com/argoproj/argo#quickstart).\n\nDownload the right CLi for your environment following the documentation (https://github.com/argoproj/argo-workflows/releases/tag/v3.0.8)\n\nYou also need to make sure that argo has permissions to create seldon deployments - for this you can just create a default-admin rolebinding as follows:", "_____no_output_____" ], [ "Set up the RBAC so the argo workflow is able to create seldon deployments.", "_____no_output_____" ], [ "Set up the configmap in order for it to work in KIND and other environments where Docker may not be thr main runtime (see https://github.com/argoproj/argo-workflows/issues/5243#issuecomment-792993742)", "_____no_output_____" ], [ "### Create Benchmark Argo Workflow\n\nIn order to create a benchmark, we created a simple argo workflow template so you can leverage the power of the helm charts.\n\nBefore we dive into the contents of the full helm chart, let's first give it a try with some of the settings.\n\nWe will run a batch job that will set up a Seldon Deployment with 1 replicas and 4 cpus (with 100 max workers) to send requests.", "_____no_output_____" ] ], [ [ "!helm template seldon-benchmark-workflow ../../../helm-charts/seldon-benchmark-workflow/ \\\n --set workflow.namespace=argo \\\n --set workflow.name=seldon-benchmark-process \\\n --set workflow.parallelism=2 \\\n --set seldonDeployment.name=sklearn \\\n --set seldonDeployment.replicas=\"1\" \\\n --set seldonDeployment.serverWorkers=\"5\" \\\n --set seldonDeployment.serverThreads=1 \\\n --set seldonDeployment.modelUri=\"gs://seldon-models/v1.11.0-dev/sklearn/iris\" \\\n --set seldonDeployment.server=\"SKLEARN_SERVER\" \\\n --set seldonDeployment.apiType=\"rest|grpc\" \\\n --set seldonDeployment.requests.cpu=\"2000Mi\" \\\n --set seldonDeployment.limits.cpu=\"2000Mi\" \\\n --set seldonDeployment.disableOrchestrator=\"true|false\" \\\n --set benchmark.cpu=\"2\" \\\n --set benchmark.concurrency=\"1\" \\\n --set benchmark.duration=\"30s\" \\\n --set benchmark.rate=0 \\\n --set benchmark.data='\\{\"data\": {\"ndarray\": [[0\\,1\\,2\\,3]]\\}\\}' \\\n | argo submit -", "Name: seldon-benchmark-process\r\nNamespace: argo\r\nServiceAccount: default\r\nStatus: Pending\r\nCreated: Mon Jun 28 18:38:12 +0100 (now)\r\nProgress: \r\n" ], [ "!argo list -n argo", "NAME STATUS AGE DURATION PRIORITY\r\nseldon-benchmark-process Running 20s 20s 0\r\n" ], [ "!argo logs -f seldon-benchmark-process -n argo", "\u001b[33mseldon-benchmark-process-635956972: [{\"name\": \"sklearn-0\", \"replicas\": \"1\", \"serverWorkers\": \"5\", \"serverThreads\": \"1\", \"modelUri\": \"gs://seldon-models/sklearn/iris\", \"image\": \"\", \"server\": \"SKLEARN_SERVER\", \"apiType\": \"rest\", \"requestsCpu\": \"2000Mi\", \"requestsMemory\": \"100Mi\", \"limitsCpu\": \"2000Mi\", \"limitsMemory\": \"1000Mi\", \"benchmarkCpu\": \"2\", \"concurrency\": \"1\", \"duration\": \"30s\", \"rate\": \"0\", \"disableOrchestrator\": \"true\", \"params\": \"{\\\"name\\\": \\\"sklearn-0\\\", \\\"replicas\\\": \\\"1\\\", \\\"serverWorkers\\\": \\\"5\\\", \\\"serverThreads\\\": \\\"1\\\", \\\"modelUri\\\": \\\"gs://seldon-models/sklearn/iris\\\", \\\"image\\\": \\\"\\\", \\\"server\\\": \\\"SKLEARN_SERVER\\\", \\\"apiType\\\": \\\"rest\\\", \\\"requestsCpu\\\": \\\"2000Mi\\\", \\\"requestsMemory\\\": \\\"100Mi\\\", \\\"limitsCpu\\\": \\\"2000Mi\\\", \\\"limitsMemory\\\": \\\"1000Mi\\\", \\\"benchmarkCpu\\\": \\\"2\\\", \\\"concurrency\\\": \\\"1\\\", \\\"duration\\\": \\\"30s\\\", \\\"rate\\\": \\\"0\\\", \\\"disableOrchestrator\\\": \\\"true\\\"}\"}]\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.287Z\" level=info msg=\"Starting Workflow Executor\" version=\"{v3.0.3 2021-05-11T21:14:20Z 02071057c082cf295ab8da68f1b2027ff8762b5a v3.0.3 clean go1.15.7 gc linux/amd64}\"\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.289Z\" level=info msg=\"Creating a docker executor\"\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.289Z\" level=info msg=\"Executor (version: v3.0.3, build_date: 2021-05-11T21:14:20Z) initialized (pod: argo/seldon-benchmark-process-2323867814) with template:\\n{\\\"name\\\":\\\"create-seldon-resource-template\\\",\\\"inputs\\\":{\\\"parameters\\\":[{\\\"name\\\":\\\"inparam\\\",\\\"value\\\":\\\"sklearn-0\\\"},{\\\"name\\\":\\\"replicas\\\",\\\"value\\\":\\\"1\\\"},{\\\"name\\\":\\\"serverWorkers\\\",\\\"value\\\":\\\"5\\\"},{\\\"name\\\":\\\"serverThreads\\\",\\\"value\\\":\\\"1\\\"},{\\\"name\\\":\\\"modelUri\\\",\\\"value\\\":\\\"gs://seldon-models/sklearn/iris\\\"},{\\\"name\\\":\\\"image\\\",\\\"value\\\":\\\"\\\"},{\\\"name\\\":\\\"server\\\",\\\"value\\\":\\\"SKLEARN_SERVER\\\"},{\\\"name\\\":\\\"apiType\\\",\\\"value\\\":\\\"rest\\\"},{\\\"name\\\":\\\"requestsCpu\\\",\\\"value\\\":\\\"2000Mi\\\"},{\\\"name\\\":\\\"requestsMemory\\\",\\\"value\\\":\\\"100Mi\\\"},{\\\"name\\\":\\\"limitsCpu\\\",\\\"value\\\":\\\"2000Mi\\\"},{\\\"name\\\":\\\"limitsMemory\\\",\\\"value\\\":\\\"1000Mi\\\"},{\\\"name\\\":\\\"benchmarkCpu\\\",\\\"value\\\":\\\"2\\\"},{\\\"name\\\":\\\"concurrency\\\",\\\"value\\\":\\\"1\\\"},{\\\"name\\\":\\\"duration\\\",\\\"value\\\":\\\"30s\\\"},{\\\"name\\\":\\\"rate\\\",\\\"value\\\":\\\"0\\\"},{\\\"name\\\":\\\"params\\\",\\\"value\\\":\\\"{\\\\\\\\\\\\\\\"name\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"sklearn-0\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"replicas\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"1\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"serverWorkers\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"5\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"serverThreads\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"1\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"modelUri\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"gs://seldon-models/sklearn/iris\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"image\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"server\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"SKLEARN_SERVER\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"apiType\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"rest\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"requestsCpu\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"2000Mi\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"requestsMemory\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"100Mi\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"limitsCpu\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"2000Mi\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"limitsMemory\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"1000Mi\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"benchmarkCpu\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"2\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"concurrency\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"1\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"duration\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"30s\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"rate\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"0\\\\\\\\\\\\\\\", \\\\\\\\\\\\\\\"disableOrchestrator\\\\\\\\\\\\\\\": \\\\\\\\\\\\\\\"true\\\\\\\\\\\\\\\"}\\\"},{\\\"name\\\":\\\"disableOrchestrator\\\",\\\"value\\\":\\\"true\\\"}]},\\\"outputs\\\":{},\\\"metadata\\\":{},\\\"resource\\\":{\\\"action\\\":\\\"create\\\",\\\"manifest\\\":\\\"apiVersion: machinelearning.seldon.io/v1\\\\nkind: SeldonDeployment\\\\nmetadata:\\\\n name: \\\\\\\"sklearn-0\\\\\\\"\\\\n namespace: argo\\\\n ownerReferences:\\\\n - apiVersion: argoproj.io/v1alpha1\\\\n blockOwnerDeletion: true\\\\n kind: Workflow\\\\n name: \\\\\\\"seldon-benchmark-process\\\\\\\"\\\\n uid: \\\\\\\"8be89da7-cb46-40c5-98ac-c17dd9d99d12\\\\\\\"\\\\nspec:\\\\n name: \\\\\\\"sklearn-0\\\\\\\"\\\\n transport: \\\\\\\"rest\\\\\\\"\\\\n predictors:\\\\n - annotations:\\\\n seldonio/no-engine: \\\\\\\"true\\\\\\\"\\\\n componentSpecs:\\\\n - spec:\\\\n containers:\\\\n - name: classifier\\\\n env:\\\\n - name: GUNICORN_THREADS\\\\n value: \\\\\\\"1\\\\\\\"\\\\n - name: GUNICORN_WORKERS\\\\n value: \\\\\\\"5\\\\\\\"\\\\n graph:\\\\n children: []\\\\n implementation: SKLEARN_SERVER\\\\n modelUri: gs://seldon-models/sklearn/iris\\\\n name: classifier\\\\n name: default\\\\n replicas: 1\\\\n\\\"}}\"\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.289Z\" level=info msg=\"Loading manifest to /tmp/manifest.yaml\"\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.289Z\" level=info msg=\"kubectl create -f /tmp/manifest.yaml -o json\"\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.808Z\" level=info msg=argo/SeldonDeployment.machinelearning.seldon.io/sklearn-0\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.808Z\" level=info msg=\"Starting SIGUSR2 signal monitor\"\u001b[0m\n\u001b[31mseldon-benchmark-process-2323867814: time=\"2021-06-28T17:27:52.808Z\" level=info msg=\"No output parameters\"\u001b[0m\n\u001b[32mseldon-benchmark-process-2388065488: Waiting for deployment \"sklearn-0-default-0-classifier\" rollout to finish: 0 of 1 updated replicas are available...\u001b[0m\n\u001b[32mseldon-benchmark-process-2388065488: deployment \"sklearn-0-default-0-classifier\" successfully rolled out\u001b[0m\n\u001b[31mseldon-benchmark-process-3406592537: {\"latencies\":{\"total\":29976397800,\"mean\":4636720,\"50th\":4085862,\"90th\":6830905,\"95th\":7974040,\"99th\":12617402,\"max\":37090400,\"min\":2523500},\"bytes_in\":{\"total\":1183095,\"mean\":183},\"bytes_out\":{\"total\":219810,\"mean\":34},\"earliest\":\"2021-06-28T17:28:30.4200499Z\",\"latest\":\"2021-06-28T17:29:00.4217614Z\",\"end\":\"2021-06-28T17:29:00.4249416Z\",\"duration\":30001711500,\"wait\":3180200,\"requests\":6465,\"rate\":215.48770642634838,\"throughput\":215.46486701700042,\"success\":1,\"status_codes\":{\"200\":6465},\"errors\":[],\"params\":{\"name\":\"sklearn-0\",\"replicas\":\"1\",\"serverWorkers\":\"5\",\"serverThreads\":\"1\",\"modelUri\":\"gs://seldon-models/sklearn/iris\",\"image\":\"\",\"server\":\"SKLEARN_SERVER\",\"apiType\":\"rest\",\"requestsCpu\":\"2000Mi\",\"requestsMemory\":\"100Mi\",\"limitsCpu\":\"2000Mi\",\"limitsMemory\":\"1000Mi\",\"benchmarkCpu\":\"2\",\"concurrency\":\"1\",\"duration\":\"30s\",\"rate\":\"0\",\"disableOrchestrator\":\"true\"}}\u001b[0m\n\u001b[37mseldon-benchmark-process-1122797932: seldondeployment.machinelearning.seldon.io \"sklearn-0\" deleted\u001b[0m\n" ], [ "!argo get seldon-benchmark-process -n argo", "Name: seldon-benchmark-process\r\nNamespace: argo\r\nServiceAccount: default\r\nStatus: Running\r\nConditions: \r\n PodRunning False\r\nCreated: Mon Jun 28 18:38:12 +0100 (4 minutes ago)\r\nStarted: Mon Jun 28 18:38:12 +0100 (4 minutes ago)\r\nDuration: 4 minutes 53 seconds\r\nProgress: 14/15\r\nResourcesDuration: 4m41s*(1 cpu),4m41s*(100Mi memory)\r\n\r\n\u001b[39mSTEP\u001b[0m TEMPLATE PODNAME DURATION MESSAGE\r\n \u001b[36m●\u001b[0m seldon-benchmark-process seldon-benchmark-process \r\n ├───\u001b[32m✔\u001b[0m generate-parameters generate-parameters-template seldon-benchmark-process-635956972 3s \r\n └─┬─\u001b[32m✔\u001b[0m run-benchmark-iteration(0:apiType:rest,benchmarkCpu:2,concurrency:1,disableOrchestrator:true,duration:30s,image:,limitsCpu:2000Mi,limitsMemory:1000Mi,modelUri:gs://seldon-models/sklearn/iris,name:sklearn-0,params:{\\\"name\\\": \\\"sklearn-0\\\", \\\"replicas\\\": \\\"1\\\", \\\"serverWorkers\\\": \\\"5\\\", \\\"serverThreads\\\": \\\"1\\\", \\\"modelUri\\\": \\\"gs://seldon-models/sklearn/iris\\\", \\\"image\\\": \\\"\\\", \\\"server\\\": \\\"SKLEARN_SERVER\\\", \\\"apiType\\\": \\\"rest\\\", \\\"requestsCpu\\\": \\\"2000Mi\\\", \\\"requestsMemory\\\": \\\"100Mi\\\", \\\"limitsCpu\\\": \\\"2000Mi\\\", \\\"limitsMemory\\\": \\\"1000Mi\\\", \\\"benchmarkCpu\\\": \\\"2\\\", \\\"concurrency\\\": \\\"1\\\", \\\"duration\\\": \\\"30s\\\", \\\"rate\\\": \\\"0\\\", \\\"disableOrchestrator\\\": \\\"true\\\"},rate:0,replicas:1,requestsCpu:2000Mi,requestsMemory:100Mi,server:SKLEARN_SERVER,serverThreads:1,serverWorkers:5) run-benchmark-iteration-step-template \r\n │ ├───\u001b[32m✔\u001b[0m create-seldon-resource create-seldon-resource-template seldon-benchmark-process-2323867814 1s \r\n │ ├───\u001b[32m✔\u001b[0m wait-seldon-resource wait-seldon-resource-template seldon-benchmark-process-2388065488 15s \r\n │ ├─┬─\u001b[39m○\u001b[0m run-benchmark-grpc run-benchmark-template-grpc when 'rest == grpc' evaluated false \r\n │ │ └─\u001b[32m✔\u001b[0m run-benchmark-rest run-benchmark-template-rest seldon-benchmark-process-3406592537 31s \r\n │ └───\u001b[32m✔\u001b[0m delete-seldon-resource delete-seldon-resource-template seldon-benchmark-process-1122797932 3s \r\n ├─\u001b[32m✔\u001b[0m run-benchmark-iteration(1:apiType:rest,benchmarkCpu:2,concurrency:1,disableOrchestrator:false,duration:30s,image:,limitsCpu:2000Mi,limitsMemory:1000Mi,modelUri:gs://seldon-models/sklearn/iris,name:sklearn-1,params:{\\\"name\\\": \\\"sklearn-1\\\", \\\"replicas\\\": \\\"1\\\", \\\"serverWorkers\\\": \\\"5\\\", \\\"serverThreads\\\": \\\"1\\\", \\\"modelUri\\\": \\\"gs://seldon-models/sklearn/iris\\\", \\\"image\\\": \\\"\\\", \\\"server\\\": \\\"SKLEARN_SERVER\\\", \\\"apiType\\\": \\\"rest\\\", \\\"requestsCpu\\\": \\\"2000Mi\\\", \\\"requestsMemory\\\": \\\"100Mi\\\", \\\"limitsCpu\\\": \\\"2000Mi\\\", \\\"limitsMemory\\\": \\\"1000Mi\\\", \\\"benchmarkCpu\\\": \\\"2\\\", \\\"concurrency\\\": \\\"1\\\", \\\"duration\\\": \\\"30s\\\", \\\"rate\\\": \\\"0\\\", \\\"disableOrchestrator\\\": \\\"false\\\"},rate:0,replicas:1,requestsCpu:2000Mi,requestsMemory:100Mi,server:SKLEARN_SERVER,serverThreads:1,serverWorkers:5) run-benchmark-iteration-step-template \r\n │ ├───\u001b[32m✔\u001b[0m create-seldon-resource create-seldon-resource-template seldon-benchmark-process-1282498819 2s \r\n │ ├───\u001b[32m✔\u001b[0m wait-seldon-resource wait-seldon-resource-template seldon-benchmark-process-634593 17s \r\n │ ├─┬─\u001b[39m○\u001b[0m run-benchmark-grpc run-benchmark-template-grpc when 'rest == grpc' evaluated false \r\n │ │ └─\u001b[32m✔\u001b[0m run-benchmark-rest run-benchmark-template-rest seldon-benchmark-process-692934928 32s \r\n │ └───\u001b[32m✔\u001b[0m delete-seldon-resource delete-seldon-resource-template seldon-benchmark-process-3935684561 2s \r\n ├─\u001b[32m✔\u001b[0m run-benchmark-iteration(2:apiType:grpc,benchmarkCpu:2,concurrency:1,disableOrchestrator:true,duration:30s,image:,limitsCpu:2000Mi,limitsMemory:1000Mi,modelUri:gs://seldon-models/sklearn/iris,name:sklearn-2,params:{\\\"name\\\": \\\"sklearn-2\\\", \\\"replicas\\\": \\\"1\\\", \\\"serverWorkers\\\": \\\"5\\\", \\\"serverThreads\\\": \\\"1\\\", \\\"modelUri\\\": \\\"gs://seldon-models/sklearn/iris\\\", \\\"image\\\": \\\"\\\", \\\"server\\\": \\\"SKLEARN_SERVER\\\", \\\"apiType\\\": \\\"grpc\\\", \\\"requestsCpu\\\": \\\"2000Mi\\\", \\\"requestsMemory\\\": \\\"100Mi\\\", \\\"limitsCpu\\\": \\\"2000Mi\\\", \\\"limitsMemory\\\": \\\"1000Mi\\\", \\\"benchmarkCpu\\\": \\\"2\\\", \\\"concurrency\\\": \\\"1\\\", \\\"duration\\\": \\\"30s\\\", \\\"rate\\\": \\\"0\\\", \\\"disableOrchestrator\\\": \\\"true\\\"},rate:0,replicas:1,requestsCpu:2000Mi,requestsMemory:100Mi,server:SKLEARN_SERVER,serverThreads:1,serverWorkers:5) run-benchmark-iteration-step-template \r\n │ ├───\u001b[32m✔\u001b[0m create-seldon-resource create-seldon-resource-template seldon-benchmark-process-637309828 1s \r\n │ ├───\u001b[32m✔\u001b[0m wait-seldon-resource wait-seldon-resource-template seldon-benchmark-process-2284480586 19s \r\n │ ├─┬─\u001b[32m✔\u001b[0m run-benchmark-grpc run-benchmark-template-grpc seldon-benchmark-process-2580139445 32s \r\n │ │ └─\u001b[39m○\u001b[0m run-benchmark-rest run-benchmark-template-rest when 'grpc == rest' evaluated false \r\n │ └───\u001b[32m✔\u001b[0m delete-seldon-resource delete-seldon-resource-template seldon-benchmark-process-757645342 3s \r\n └─\u001b[36m●\u001b[0m run-benchmark-iteration(3:apiType:grpc,benchmarkCpu:2,concurrency:1,disableOrchestrator:false,duration:30s,image:,limitsCpu:2000Mi,limitsMemory:1000Mi,modelUri:gs://seldon-models/sklearn/iris,name:sklearn-3,params:{\\\"name\\\": \\\"sklearn-3\\\", \\\"replicas\\\": \\\"1\\\", \\\"serverWorkers\\\": \\\"5\\\", \\\"serverThreads\\\": \\\"1\\\", \\\"modelUri\\\": \\\"gs://seldon-models/sklearn/iris\\\", \\\"image\\\": \\\"\\\", \\\"server\\\": \\\"SKLEARN_SERVER\\\", \\\"apiType\\\": \\\"grpc\\\", \\\"requestsCpu\\\": \\\"2000Mi\\\", \\\"requestsMemory\\\": \\\"100Mi\\\", \\\"limitsCpu\\\": \\\"2000Mi\\\", \\\"limitsMemory\\\": \\\"1000Mi\\\", \\\"benchmarkCpu\\\": \\\"2\\\", \\\"concurrency\\\": \\\"1\\\", \\\"duration\\\": \\\"30s\\\", \\\"rate\\\": \\\"0\\\", \\\"disableOrchestrator\\\": \\\"false\\\"},rate:0,replicas:1,requestsCpu:2000Mi,requestsMemory:100Mi,server:SKLEARN_SERVER,serverThreads:1,serverWorkers:5) run-benchmark-iteration-step-template \r\n ├───\u001b[32m✔\u001b[0m create-seldon-resource create-seldon-resource-template seldon-benchmark-process-1376808213 1s \r\n └───\u001b[33m◷\u001b[0m wait-seldon-resource wait-seldon-resource-template seldon-benchmark-process-3668579423 7s \r\n" ] ], [ [ "## Process the results\n\nWe can now print the results in a consumable format.", "_____no_output_____" ], [ "## Deeper Analysis\nNow that we have all the parameters, we can do a deeper analysis", "_____no_output_____" ] ], [ [ "import sys\n\nsys.path.append(\"../../../testing/scripts\")\nimport pandas as pd\nfrom seldon_e2e_utils import bench_results_from_output_logs\n\nresults = bench_results_from_output_logs(\"seldon-benchmark-process\", namespace=\"argo\")\ndf = pd.DataFrame.from_dict(results)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "!argo delete seldon-benchmark-process -n argo || echo \"Argo workflow already deleted or not exists\"", "Workflow 'seldon-benchmark-process' deleted\r\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
4aefbca9744fd6494ca752bb3b831f9d76baa094
13,516
ipynb
Jupyter Notebook
examples/01_Introducing_txtai.ipynb
asysc2020/txtai
84f62e4a38411e5ccce7399f696bc5746ab0e240
[ "Apache-2.0" ]
null
null
null
examples/01_Introducing_txtai.ipynb
asysc2020/txtai
84f62e4a38411e5ccce7399f696bc5746ab0e240
[ "Apache-2.0" ]
null
null
null
examples/01_Introducing_txtai.ipynb
asysc2020/txtai
84f62e4a38411e5ccce7399f696bc5746ab0e240
[ "Apache-2.0" ]
null
null
null
39.988166
265
0.55364
[ [ [ "# Part 1: Introducing txtai\n\n[txtai](https://github.com/neuml/txtai) builds an AI-powered index over sections of text. txtai supports building text indices to perform similarity searches and create extractive question-answering based systems. \n\nNeuML uses txtai and/or the concepts behind it to power all of our Natural Language Processing (NLP) applications. Example applications:\n\n- [paperai](https://github.com/neuml/paperai) - AI-powered literature discovery and review engine for medical/scientific papers\n- [tldrstory](https://github.com/neuml/tldrstory) - AI-powered understanding of headlines and story text\n- [neuspo](https://neuspo.com) - a fact-driven, real-time sports event and news site\n- [codequestion](https://github.com/neuml/codequestion) - Ask coding questions directly from the terminal\n\ntxtai is built on the following stack:\n\n- [sentence-transformers](https://github.com/UKPLab/sentence-transformers)\n- [transformers](https://github.com/huggingface/transformers)\n- [faiss](https://github.com/facebookresearch/faiss)\n- Python 3.6+\n\nThis notebook gives an overview of txtai and how to run similarity searches.", "_____no_output_____" ], [ "# Install dependencies\n\nInstall txtai and all dependencies", "_____no_output_____" ] ], [ [ "%%capture\n!pip install git+https://github.com/neuml/txtai", "_____no_output_____" ] ], [ [ "# Create an Embeddings instance\n\nThe Embeddings instance is the main entrypoint for txtai. An Embeddings instance defines the method used to tokenize and convert a text section into an embeddings vector. ", "_____no_output_____" ] ], [ [ "%%capture\n\nfrom txtai.embeddings import Embeddings\n\n# Create embeddings model, backed by sentence-transformers & transformers\nembeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/bert-base-nli-mean-tokens\"})", "_____no_output_____" ] ], [ [ "# Running similarity queries\n\nAn embedding instance relies on the underlying transformer model to build text embeddings. The following example shows how to use an transformers Embedding instance to run similarity searches for a list of different concepts.", "_____no_output_____" ] ], [ [ "import numpy as np\n\nsections = [\"US tops 5 million confirmed virus cases\",\n \"Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg\",\n \"Beijing mobilises invasion craft along coast as Taiwan tensions escalate\",\n \"The National Park Service warns against sacrificing slower friends in a bear attack\",\n \"Maine man wins $1M from $25 lottery ticket\",\n \"Make huge profits without work, earn up to $100,000 a day\"]\n\nprint(\"%-20s %s\" % (\"Query\", \"Best Match\"))\nprint(\"-\" * 50)\n\nfor query in (\"feel good story\", \"climate change\", \"health\", \"war\", \"wildlife\", \"asia\", \"north america\", \"dishonest junk\"):\n # Get index of best section that best matches query\n uid = np.argmax(embeddings.similarity(query, sections))\n\n print(\"%-20s %s\" % (query, sections[uid]))", "Query Best Match\n--------------------------------------------------\nfeel good story Maine man wins $1M from $25 lottery ticket\nclimate change Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg\nhealth US tops 5 million confirmed virus cases\nwar Beijing mobilises invasion craft along coast as Taiwan tensions escalate\nwildlife The National Park Service warns against sacrificing slower friends in a bear attack\nasia Beijing mobilises invasion craft along coast as Taiwan tensions escalate\nnorth america US tops 5 million confirmed virus cases\ndishonest junk Make huge profits without work, earn up to $100,000 a day\n" ] ], [ [ "The example above shows for almost all of the queries, the actual text isn't stored in the list of text sections. This is the true power of transformer models over token based search. What you get out of the box is 🔥🔥🔥!", "_____no_output_____" ], [ "# Building an Embeddings index\n\nFor small lists of texts, the method above works. But for larger repositories of documents, it doesn't make sense to tokenize and convert to embeddings on each query. txtai supports building pre-computed indices which signficantly improve performance. \n\nBuilding on the previous example, the following example runs an index method to build and store the text embeddings. In this case, only the query is converted to an embeddings vector each search. ", "_____no_output_____" ] ], [ [ "# Create an index for the list of sections\nembeddings.index([(uid, text, None) for uid, text in enumerate(sections)])\n\nprint(\"%-20s %s\" % (\"Query\", \"Best Match\"))\nprint(\"-\" * 50)\n\n# Run an embeddings search for each query\nfor query in (\"feel good story\", \"climate change\", \"health\", \"war\", \"wildlife\", \"asia\", \"north america\", \"dishonest junk\"):\n # Extract uid of first result\n # search result format: (uid, score)\n uid = embeddings.search(query, 1)[0][0]\n\n # Print section\n print(\"%-20s %s\" % (query, sections[uid]))", "Query Best Match\n--------------------------------------------------\nfeel good story Maine man wins $1M from $25 lottery ticket\nclimate change Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg\nhealth US tops 5 million confirmed virus cases\nwar Beijing mobilises invasion craft along coast as Taiwan tensions escalate\nwildlife The National Park Service warns against sacrificing slower friends in a bear attack\nasia Beijing mobilises invasion craft along coast as Taiwan tensions escalate\nnorth america US tops 5 million confirmed virus cases\ndishonest junk Make huge profits without work, earn up to $100,000 a day\n" ] ], [ [ "# Embeddings load/save\n\nEmbeddings indices can be saved to disk and reloaded. At this time, indices are not incrementally created, the index needs a full rebuild to incorporate new data. But that enhancement is in the backlog.", "_____no_output_____" ] ], [ [ "embeddings.save(\"index\")\n\nembeddings = Embeddings()\nembeddings.load(\"index\")\n\nuid = embeddings.search(\"climate change\", 1)[0][0]\nprint(sections[uid])", "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg\n" ], [ "!ls index", "config\tembeddings\n" ] ], [ [ "# Embedding methods\n\nEmbeddings supports two methods for creating text vectors, the sentence-transformers library and word embeddings vectors. Both methods have their merits as shown below:\n\n- [sentence-transformers](https://github.com/UKPLab/sentence-transformers)\n - Creates a single embeddings vector via mean pooling of vectors generated by the transformers library. \n - Supports models stored on Hugging Face's model hub or stored locally. \n - See sentence-transformers for details on how to create custom models, which can be kept local or uploaded to Hugging Face's model hub.\n - Base models require significant compute capability (GPU preferred). Possible to build smaller/lighter weight models that tradeoff accuracy for speed.\n- word embeddings\n - Creates a single embeddings vector via BM25 scoring of each word component. See this [Medium article](https://towardsdatascience.com/building-a-sentence-embedding-index-with-fasttext-and-bm25-f07e7148d240) for the logic behind this method.\n - Backed by the [pymagnitude](https://github.com/plasticityai/magnitude) library. Pre-trained word vectors can be installed from the referenced link.\n - See [vectors.py](https://github.com/neuml/txtai/blob/master/src/python/txtai/vectors.py) for code that can build word vectors for custom datasets.\n - Significantly better performance with default models. For larger datasets, it offers a good tradeoff of speed and accuracy.", "_____no_output_____" ], [ "# Next\nIn part 2 of this series, we'll look at how to use txtai to run extractive searches", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
4aefbdd90616790a062944d3c539497981bea45d
14,523
ipynb
Jupyter Notebook
notebooks/build_rcdb_from_xyz.ipynb
vwcruzeiro/ANI-Tools
bc44c65589148b6e6dd8065d63e73ead00d8ac9d
[ "MIT" ]
8
2018-10-30T16:48:44.000Z
2021-03-08T01:44:41.000Z
notebooks/build_rcdb_from_xyz.ipynb
vwcruzeiro/ANI-Tools
bc44c65589148b6e6dd8065d63e73ead00d8ac9d
[ "MIT" ]
null
null
null
notebooks/build_rcdb_from_xyz.ipynb
vwcruzeiro/ANI-Tools
bc44c65589148b6e6dd8065d63e73ead00d8ac9d
[ "MIT" ]
5
2018-04-05T15:51:12.000Z
2019-05-23T21:38:31.000Z
23.199681
1,066
0.47745
[ [ [ "import hdnntools as hdt\n\nimport os", "_____no_output_____" ], [ "fdir = '/home/jsmith48/scratch/extensibility_test_sets/COMP6v1/s66x8/xyzfiles/'\nodir = '/home/jsmith48/scratch/extensibility_test_sets/COMP6v1/s66x8/rcdb_inputs/'", "_____no_output_____" ], [ "files = [f for f in os.listdir(fdir) if '.xyz' in f]\nprint(files)", "['s66ds_59.xyz', 's66ds_17.xyz', 's66ds_27.xyz', 's66ds_31.xyz', 's66ds_07.xyz', 's66ds_56.xyz', 's66ds_62.xyz', 's66ds_44.xyz', 's66ds_34.xyz', 's66ds_53.xyz', 's66ds_14.xyz', 's66ds_09.xyz', 's66ds_30.xyz', 's66ds_15.xyz', 's66ds_22.xyz', 's66ds_61.xyz', 's66ds_28.xyz', 's66ds_19.xyz', 's66ds_16.xyz', 's66ds_26.xyz', 's66ds_48.xyz', 's66ds_36.xyz', 's66ds_38.xyz', 's66ds_00.xyz', 's66ds_13.xyz', 's66ds_37.xyz', 's66ds_58.xyz', 's66ds_33.xyz', 's66ds_03.xyz', 's66ds_11.xyz', 's66ds_10.xyz', 's66ds_08.xyz', 's66ds_54.xyz', 's66ds_05.xyz', 's66ds_46.xyz', 's66ds_51.xyz', 's66ds_45.xyz', 's66ds_41.xyz', 's66ds_21.xyz', 's66ds_42.xyz', 's66ds_55.xyz', 's66ds_24.xyz', 's66ds_29.xyz', 's66ds_18.xyz', 's66ds_02.xyz', 's66ds_52.xyz', 's66ds_49.xyz', 's66ds_35.xyz', 's66ds_60.xyz', 's66ds_63.xyz', 's66ds_40.xyz', 's66ds_32.xyz', 's66ds_06.xyz', 's66ds_25.xyz', 's66ds_20.xyz', 's66ds_50.xyz', 's66ds_12.xyz', 's66ds_04.xyz', 's66ds_64.xyz', 's66ds_43.xyz', 's66ds_47.xyz', 's66ds_57.xyz', 's66ds_65.xyz', 's66ds_23.xyz', 's66ds_01.xyz', 's66ds_39.xyz']\n" ], [ "for f in files:\n X,S,Na,c = hdt.readxyz2(fdir+f)\n for i,x in enumerate(X):\n print(i,f.rsplit('.xyz')[0])\n hdt.write_rcdb_input(x,S,i,odir,f.rsplit('.xyz')[0],'wb97x/6-31g*',opt='0')", "0 s66ds_59\n1 s66ds_59\n2 s66ds_59\n3 s66ds_59\n4 s66ds_59\n5 s66ds_59\n6 s66ds_59\n7 s66ds_59\n0 s66ds_17\n1 s66ds_17\n2 s66ds_17\n3 s66ds_17\n4 s66ds_17\n5 s66ds_17\n6 s66ds_17\n7 s66ds_17\n0 s66ds_27\n1 s66ds_27\n2 s66ds_27\n3 s66ds_27\n4 s66ds_27\n5 s66ds_27\n6 s66ds_27\n7 s66ds_27\n0 s66ds_31\n1 s66ds_31\n2 s66ds_31\n3 s66ds_31\n4 s66ds_31\n5 s66ds_31\n6 s66ds_31\n7 s66ds_31\n0 s66ds_07\n1 s66ds_07\n2 s66ds_07\n3 s66ds_07\n4 s66ds_07\n5 s66ds_07\n6 s66ds_07\n7 s66ds_07\n0 s66ds_56\n1 s66ds_56\n2 s66ds_56\n3 s66ds_56\n4 s66ds_56\n5 s66ds_56\n6 s66ds_56\n7 s66ds_56\n0 s66ds_62\n1 s66ds_62\n2 s66ds_62\n3 s66ds_62\n4 s66ds_62\n5 s66ds_62\n6 s66ds_62\n7 s66ds_62\n0 s66ds_44\n1 s66ds_44\n2 s66ds_44\n3 s66ds_44\n4 s66ds_44\n5 s66ds_44\n6 s66ds_44\n7 s66ds_44\n0 s66ds_34\n1 s66ds_34\n2 s66ds_34\n3 s66ds_34\n4 s66ds_34\n5 s66ds_34\n6 s66ds_34\n7 s66ds_34\n0 s66ds_53\n1 s66ds_53\n2 s66ds_53\n3 s66ds_53\n4 s66ds_53\n5 s66ds_53\n6 s66ds_53\n7 s66ds_53\n0 s66ds_14\n1 s66ds_14\n2 s66ds_14\n3 s66ds_14\n4 s66ds_14\n5 s66ds_14\n6 s66ds_14\n7 s66ds_14\n0 s66ds_09\n1 s66ds_09\n2 s66ds_09\n3 s66ds_09\n4 s66ds_09\n5 s66ds_09\n6 s66ds_09\n7 s66ds_09\n0 s66ds_30\n1 s66ds_30\n2 s66ds_30\n3 s66ds_30\n4 s66ds_30\n5 s66ds_30\n6 s66ds_30\n7 s66ds_30\n0 s66ds_15\n1 s66ds_15\n2 s66ds_15\n3 s66ds_15\n4 s66ds_15\n5 s66ds_15\n6 s66ds_15\n7 s66ds_15\n0 s66ds_22\n1 s66ds_22\n2 s66ds_22\n3 s66ds_22\n4 s66ds_22\n5 s66ds_22\n6 s66ds_22\n7 s66ds_22\n0 s66ds_61\n1 s66ds_61\n2 s66ds_61\n3 s66ds_61\n4 s66ds_61\n5 s66ds_61\n6 s66ds_61\n7 s66ds_61\n0 s66ds_28\n1 s66ds_28\n2 s66ds_28\n3 s66ds_28\n4 s66ds_28\n5 s66ds_28\n6 s66ds_28\n7 s66ds_28\n0 s66ds_19\n1 s66ds_19\n2 s66ds_19\n3 s66ds_19\n4 s66ds_19\n5 s66ds_19\n6 s66ds_19\n7 s66ds_19\n0 s66ds_16\n1 s66ds_16\n2 s66ds_16\n3 s66ds_16\n4 s66ds_16\n5 s66ds_16\n6 s66ds_16\n7 s66ds_16\n0 s66ds_26\n1 s66ds_26\n2 s66ds_26\n3 s66ds_26\n4 s66ds_26\n5 s66ds_26\n6 s66ds_26\n7 s66ds_26\n0 s66ds_48\n1 s66ds_48\n2 s66ds_48\n3 s66ds_48\n4 s66ds_48\n5 s66ds_48\n6 s66ds_48\n7 s66ds_48\n0 s66ds_36\n1 s66ds_36\n2 s66ds_36\n3 s66ds_36\n4 s66ds_36\n5 s66ds_36\n6 s66ds_36\n7 s66ds_36\n0 s66ds_38\n1 s66ds_38\n2 s66ds_38\n3 s66ds_38\n4 s66ds_38\n5 s66ds_38\n6 s66ds_38\n7 s66ds_38\n0 s66ds_00\n1 s66ds_00\n2 s66ds_00\n3 s66ds_00\n4 s66ds_00\n5 s66ds_00\n6 s66ds_00\n7 s66ds_00\n0 s66ds_13\n1 s66ds_13\n2 s66ds_13\n3 s66ds_13\n4 s66ds_13\n5 s66ds_13\n6 s66ds_13\n7 s66ds_13\n0 s66ds_37\n1 s66ds_37\n2 s66ds_37\n3 s66ds_37\n4 s66ds_37\n5 s66ds_37\n6 s66ds_37\n7 s66ds_37\n0 s66ds_58\n1 s66ds_58\n2 s66ds_58\n3 s66ds_58\n4 s66ds_58\n5 s66ds_58\n6 s66ds_58\n7 s66ds_58\n0 s66ds_33\n1 s66ds_33\n2 s66ds_33\n3 s66ds_33\n4 s66ds_33\n5 s66ds_33\n6 s66ds_33\n7 s66ds_33\n0 s66ds_03\n1 s66ds_03\n2 s66ds_03\n3 s66ds_03\n4 s66ds_03\n5 s66ds_03\n6 s66ds_03\n7 s66ds_03\n0 s66ds_11\n1 s66ds_11\n2 s66ds_11\n3 s66ds_11\n4 s66ds_11\n5 s66ds_11\n6 s66ds_11\n7 s66ds_11\n0 s66ds_10\n1 s66ds_10\n2 s66ds_10\n3 s66ds_10\n4 s66ds_10\n5 s66ds_10\n6 s66ds_10\n7 s66ds_10\n0 s66ds_08\n1 s66ds_08\n2 s66ds_08\n3 s66ds_08\n4 s66ds_08\n5 s66ds_08\n6 s66ds_08\n7 s66ds_08\n0 s66ds_54\n1 s66ds_54\n2 s66ds_54\n3 s66ds_54\n4 s66ds_54\n5 s66ds_54\n6 s66ds_54\n7 s66ds_54\n0 s66ds_05\n1 s66ds_05\n2 s66ds_05\n3 s66ds_05\n4 s66ds_05\n5 s66ds_05\n6 s66ds_05\n7 s66ds_05\n0 s66ds_46\n1 s66ds_46\n2 s66ds_46\n3 s66ds_46\n4 s66ds_46\n5 s66ds_46\n6 s66ds_46\n7 s66ds_46\n0 s66ds_51\n1 s66ds_51\n2 s66ds_51\n3 s66ds_51\n4 s66ds_51\n5 s66ds_51\n6 s66ds_51\n7 s66ds_51\n0 s66ds_45\n1 s66ds_45\n2 s66ds_45\n3 s66ds_45\n4 s66ds_45\n5 s66ds_45\n6 s66ds_45\n7 s66ds_45\n0 s66ds_41\n1 s66ds_41\n2 s66ds_41\n3 s66ds_41\n4 s66ds_41\n5 s66ds_41\n6 s66ds_41\n7 s66ds_41\n0 s66ds_21\n1 s66ds_21\n2 s66ds_21\n3 s66ds_21\n4 s66ds_21\n5 s66ds_21\n6 s66ds_21\n7 s66ds_21\n0 s66ds_42\n1 s66ds_42\n2 s66ds_42\n3 s66ds_42\n4 s66ds_42\n5 s66ds_42\n6 s66ds_42\n7 s66ds_42\n0 s66ds_55\n1 s66ds_55\n2 s66ds_55\n3 s66ds_55\n4 s66ds_55\n5 s66ds_55\n6 s66ds_55\n7 s66ds_55\n0 s66ds_24\n1 s66ds_24\n2 s66ds_24\n3 s66ds_24\n4 s66ds_24\n5 s66ds_24\n6 s66ds_24\n7 s66ds_24\n0 s66ds_29\n1 s66ds_29\n2 s66ds_29\n3 s66ds_29\n4 s66ds_29\n5 s66ds_29\n6 s66ds_29\n7 s66ds_29\n0 s66ds_18\n1 s66ds_18\n2 s66ds_18\n3 s66ds_18\n4 s66ds_18\n5 s66ds_18\n6 s66ds_18\n7 s66ds_18\n0 s66ds_02\n1 s66ds_02\n2 s66ds_02\n3 s66ds_02\n4 s66ds_02\n5 s66ds_02\n6 s66ds_02\n7 s66ds_02\n0 s66ds_52\n1 s66ds_52\n2 s66ds_52\n3 s66ds_52\n4 s66ds_52\n5 s66ds_52\n6 s66ds_52\n7 s66ds_52\n0 s66ds_49\n1 s66ds_49\n2 s66ds_49\n3 s66ds_49\n4 s66ds_49\n5 s66ds_49\n6 s66ds_49\n7 s66ds_49\n0 s66ds_35\n1 s66ds_35\n2 s66ds_35\n3 s66ds_35\n4 s66ds_35\n5 s66ds_35\n6 s66ds_35\n7 s66ds_35\n0 s66ds_60\n1 s66ds_60\n2 s66ds_60\n3 s66ds_60\n4 s66ds_60\n5 s66ds_60\n6 s66ds_60\n7 s66ds_60\n0 s66ds_63\n1 s66ds_63\n2 s66ds_63\n3 s66ds_63\n4 s66ds_63\n5 s66ds_63\n6 s66ds_63\n7 s66ds_63\n0 s66ds_40\n1 s66ds_40\n2 s66ds_40\n3 s66ds_40\n4 s66ds_40\n5 s66ds_40\n6 s66ds_40\n7 s66ds_40\n0 s66ds_32\n1 s66ds_32\n2 s66ds_32\n3 s66ds_32\n4 s66ds_32\n5 s66ds_32\n6 s66ds_32\n7 s66ds_32\n0 s66ds_06\n1 s66ds_06\n2 s66ds_06\n3 s66ds_06\n4 s66ds_06\n5 s66ds_06\n6 s66ds_06\n7 s66ds_06\n0 s66ds_25\n1 s66ds_25\n2 s66ds_25\n3 s66ds_25\n4 s66ds_25\n5 s66ds_25\n6 s66ds_25\n7 s66ds_25\n0 s66ds_20\n1 s66ds_20\n2 s66ds_20\n3 s66ds_20\n4 s66ds_20\n5 s66ds_20\n6 s66ds_20\n7 s66ds_20\n0 s66ds_50\n1 s66ds_50\n2 s66ds_50\n3 s66ds_50\n4 s66ds_50\n5 s66ds_50\n6 s66ds_50\n7 s66ds_50\n0 s66ds_12\n1 s66ds_12\n2 s66ds_12\n3 s66ds_12\n4 s66ds_12\n5 s66ds_12\n6 s66ds_12\n7 s66ds_12\n0 s66ds_04\n1 s66ds_04\n2 s66ds_04\n3 s66ds_04\n4 s66ds_04\n5 s66ds_04\n6 s66ds_04\n7 s66ds_04\n0 s66ds_64\n1 s66ds_64\n2 s66ds_64\n3 s66ds_64\n4 s66ds_64\n5 s66ds_64\n6 s66ds_64\n7 s66ds_64\n0 s66ds_43\n1 s66ds_43\n2 s66ds_43\n3 s66ds_43\n4 s66ds_43\n5 s66ds_43\n6 s66ds_43\n7 s66ds_43\n0 s66ds_47\n1 s66ds_47\n2 s66ds_47\n3 s66ds_47\n4 s66ds_47\n5 s66ds_47\n6 s66ds_47\n7 s66ds_47\n0 s66ds_57\n1 s66ds_57\n2 s66ds_57\n3 s66ds_57\n4 s66ds_57\n5 s66ds_57\n6 s66ds_57\n7 s66ds_57\n0 s66ds_65\n1 s66ds_65\n2 s66ds_65\n3 s66ds_65\n4 s66ds_65\n5 s66ds_65\n6 s66ds_65\n7 s66ds_65\n0 s66ds_23\n1 s66ds_23\n2 s66ds_23\n3 s66ds_23\n4 s66ds_23\n5 s66ds_23\n6 s66ds_23\n7 s66ds_23\n0 s66ds_01\n1 s66ds_01\n2 s66ds_01\n3 s66ds_01\n4 s66ds_01\n5 s66ds_01\n6 s66ds_01\n7 s66ds_01\n0 s66ds_39\n1 s66ds_39\n2 s66ds_39\n3 s66ds_39\n4 s66ds_39\n5 s66ds_39\n6 s66ds_39\n7 s66ds_39\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4aefc428186321e4a799a9165e7b99a004a2f8f6
92,303
ipynb
Jupyter Notebook
.ipynb_checkpoints/S_Version-checkpoint.ipynb
APK500/PythonAPI-Homework-WeatherPy
f0719d4fa5e227e084bfe8cbda1fb824a8056d73
[ "MIT" ]
null
null
null
.ipynb_checkpoints/S_Version-checkpoint.ipynb
APK500/PythonAPI-Homework-WeatherPy
f0719d4fa5e227e084bfe8cbda1fb824a8056d73
[ "MIT" ]
null
null
null
.ipynb_checkpoints/S_Version-checkpoint.ipynb
APK500/PythonAPI-Homework-WeatherPy
f0719d4fa5e227e084bfe8cbda1fb824a8056d73
[ "MIT" ]
null
null
null
68.321984
252
0.701234
[ [ [ "# IMPORT OUR DEPENDENCIES: \n\n#To create our randomly-selected coordinates:\nimport random\nimport requests\nimport numpy as np\n\n\n#To hold our data and create dataframes:\nimport pandas as pd\n\n\n#Our API keys, and citipy (newly installed for project), to import the city weather-data.\nfrom config import api_key\nfrom citipy import citipy \n\n\n#And to plot our data:\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n\n#Last, for any formating of plots (they may be needed):\nimport seaborn\n\n", "_____no_output_____" ], [ "# GETTING A RANDOM SET OF COORDINATES TO USE FOR CALLING ON CITY WEATHER: \n\n# First we define the Latitude & Longitude Zones use numpy to select coordinates at random, given the ranges:\nlat_zone = np.arange(-90,90,15)\nlon_zone = np.arange(-200,200,15)\n", "_____no_output_____" ], [ "# DATAFRAME TO HOLD OUR COORDINATES:\n\n# Create our list/Pandas DataFrame & calling it \"cities\" which will hold the coordinates to their city.\n\n\ncities_df = pd.DataFrame()\n\ncities_df[\"Latitude\"] = \"\"\ncities_df[\"Longitude\"] = \"\"\n\n", "_____no_output_____" ], [ "# COORDINATE SELECTION!\n\n# First, using a coordinate systen we will assign \"X\" for latitude, and \"Y\" for long.\n# For both latitude \"X\" & longitude \"Y\", we randomly select **(50 ?) unique coordinates:\n# **For the random sample we collect, we will assign \"lats\" for X and \"lons\" for y.\n# We then will create/append the lists, \"lat_samples\" and \"lon_samples\", to use in dataframes.\n\nfor x in lat_zone:\n for y in lon_zone:\n x_values = list(np.arange(x,x+15,0.01))\n y_values = list(np.arange(y,y+15,0.01))\n lats = random.sample(x_values,50)\n lons = random.sample(y_values,50)\n lat_samples = [(x+dec_lat) for dec_lat in lats]\n lon_samples = [y+dec_lon for dec_lon in lons]\n cities_df = cities_df.append(pd.DataFrame.from_dict({\"Latitude\":lat_samples,\n \"Longitude\":lon_samples}))\n\n# We then place the coordinates into our \"cities\" dataframe that was created above. \ncities_df = cities_df.reset_index(drop=True)\n\n# IS THIS LINE NECC ??\ncities_df.shape", "_____no_output_____" ], [ "# USING CITIPY MODULE TO TIE COORDINATES TO A CORRESPONDING/NEARBY CITY:\n\ncities_df[\"Closest City name\"] = \"\"\ncities_df[\"Closest Country code\"] = \"\"\nfor index,row in cities_df.iterrows():\n city = citipy.nearest_city(row[\"Latitude\"],row[\"Longitude\"])\n cities_df.set_value(index,\"Closest City name\",city.city_name)\n cities_df.set_value(index,\"Closest Country code\",city.country_code)", "C:\\Users\\Adam Knapp\\AppData\\Local\\conda\\conda\\envs\\PythonData\\lib\\site-packages\\ipykernel_launcher.py:7: FutureWarning: set_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead\n import sys\nC:\\Users\\Adam Knapp\\AppData\\Local\\conda\\conda\\envs\\PythonData\\lib\\site-packages\\ipykernel_launcher.py:8: FutureWarning: set_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead\n \n" ], [ "# CLEANING THE DATAFRAME: ELIMINATE COORDINATE-SETS THAT DON'T YIELD NEARBY CITIES:\n\n\n# First we create a new data frame that eliminates coordinates that aren't near any city:\n# ..Calling it \"clean_cities\":\nclean_cities_df = cities_df.drop(['Latitude', 'Longitude'],axis=1)\nclean_cities_df\n\n# Next we filter for any possible duplicates (cities that come twice)\nclean_cities_df = clean_cities_df.drop_duplicates()\n\n# **Neccesary?\nclean_cities_df.shape", "_____no_output_____" ], [ "# CREATING OUR SET OF CITIES WE WILL MAKE AN API CALL WITH\n\n# Creation of our random sample set of cities from our \"clean\" data frame (above).\n# Now we use a sample size of 500 in order to return their weather data.\n# ** We will call this group of 500, \"selected_cities\".\n\nselected_cities = clean_cities_df.sample(500)\n\nselected_cities = selected_cities.reset_index(drop=True)\n\n", "_____no_output_____" ], [ "# USING API CALLS TO GATHER WEATHER INFO ON OUR SELECTED CITIES:\n\n# We use Openweathermap to make our API CALLS:\n# Set up format for the calls:\nbase_url = \"http://api.openweathermap.org/data/2.5/weather\"\n\napp_id = api_key\n\nparams = { \"appid\" :app_id,\"units\":\"metric\" }\n\n\n", "_____no_output_____" ], [ "# NOW enter the call data, url formatting, variables we want to collect &\n# interate through for our \"selected_cities\" group:\n\ndef encrypt_key(input_url):\n return input_url[0:53]+\"<YourKey>\"+input_url[85:]\n\nfor index,row in selected_cities.iterrows():\n params[\"q\"] =f'{row[\"Closest City name\"]},{row[\"Closest Country code\"]}'\n print(f\"Retrieving weather information for {params['q']}\")\n city_weather_resp = requests.get(base_url,params)\n print(encrypt_key(city_weather_resp.url))\n city_weather_resp = city_weather_resp.json()\n selected_cities.set_value(index,\"Latitude\",city_weather_resp.get(\"coord\",{}).get(\"lat\"))\n selected_cities.set_value(index,\"Longitude\",city_weather_resp.get(\"coord\",{}).get(\"lon\"))\n selected_cities.set_value(index,\"Temperature\",city_weather_resp.get(\"main\",{}).get(\"temp_max\"))\n selected_cities.set_value(index,\"Wind speed\",city_weather_resp.get(\"wind\",{}).get(\"speed\"))\n selected_cities.set_value(index,\"Humidity\",city_weather_resp.get(\"main\",{}).get(\"humidity\"))\n selected_cities.set_value(index,\"Cloudiness\",city_weather_resp.get(\"clouds\",{}).get(\"all\"))", "Retrieving weather information for grand baie,mu\nhttp://api.openweathermap.org/data/2.5/weather?appid=<YourKey>&units=metric&q=grand+baie%2Cmu\nRetrieving weather information for tarakan,id\nhttp://api.openweathermap.org/data/2.5/weather?appid=<YourKey>&units=metric&q=tarakan%2Cid\nRetrieving weather information for rincon,an\n" ], [ "# POST CALL-RETREIVING: CLEAN UP DATA (When needed) AND EXPORT OUR DATA TO CSV:\nselected_cities = selected_cities.dropna()\n\nselected_cities.shape\nselected_cities.to_csv(\"City_Weather_data.csv\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aefcffaf348af1b2f46caba2e99fb6ff8ca5d18
5,848
ipynb
Jupyter Notebook
HubSpot/HubSpot_Update_deal.ipynb
srini047/awesome-notebooks
2a5b771b37b62090de5311d61dce8495fae7b59f
[ "BSD-3-Clause" ]
null
null
null
HubSpot/HubSpot_Update_deal.ipynb
srini047/awesome-notebooks
2a5b771b37b62090de5311d61dce8495fae7b59f
[ "BSD-3-Clause" ]
null
null
null
HubSpot/HubSpot_Update_deal.ipynb
srini047/awesome-notebooks
2a5b771b37b62090de5311d61dce8495fae7b59f
[ "BSD-3-Clause" ]
null
null
null
20.165517
281
0.484439
[ [ [ "<img width=\"10%\" alt=\"Naas\" src=\"https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160\"/>", "_____no_output_____" ], [ "# HubSpot - Update deal\n<a href=\"https://app.naas.ai/user-redirect/naas/downloader?url=https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/HubSpot/HubSpot_Update_deal.ipynb\" target=\"_parent\"><img src=\"https://naasai-public.s3.eu-west-3.amazonaws.com/open_in_naas.svg\"/></a>", "_____no_output_____" ], [ "**Tags:** #hubspot #crm #sales #deal #naas_drivers", "_____no_output_____" ], [ "**Author:** [Florent Ravenel](https://www.linkedin.com/in/florent-ravenel/)", "_____no_output_____" ], [ "## Input", "_____no_output_____" ], [ "### Import library", "_____no_output_____" ] ], [ [ "from naas_drivers import hubspot", "_____no_output_____" ] ], [ [ "### Setup your HubSpot\n👉 Access your [HubSpot API key](https://knowledge.hubspot.com/integrations/how-do-i-get-my-hubspot-api-key)", "_____no_output_____" ] ], [ [ "HS_API_KEY = 'YOUR_HUBSPOT_API_KEY'", "_____no_output_____" ] ], [ [ "### Enter deal parameters to update", "_____no_output_____" ] ], [ [ "deal_id = \"3501002068\"\ndealname = \"TEST\"\ndealstage = '5102584'\nclosedate = '2021-12-31' #date format must be %Y-%m-%d\namount = '100.50'\nhubspot_owner_id = None", "_____no_output_____" ] ], [ [ "## Model", "_____no_output_____" ], [ "### With patch method", "_____no_output_____" ] ], [ [ "update_deal = {\"properties\": \n {\n \"dealstage\": dealstage,\n \"dealname\": dealname,\n \"amount\": amount,\n \"closedate\": closedate,\n \"hubspot_owner_id\": hubspot_owner_id,\n }\n }\n\ndeal1 = hubspot.connect(HS_API_KEY).deals.patch(deal_id,\n update_deal)", "_____no_output_____" ] ], [ [ "### With update method", "_____no_output_____" ] ], [ [ "deal2 = hubspot.connect(HS_API_KEY).deals.update(\n deal_id,\n dealname,\n dealstage,\n closedate,\n amount,\n hubspot_owner_id\n)", "_____no_output_____" ] ], [ [ "## Output", "_____no_output_____" ], [ "### Display results", "_____no_output_____" ] ], [ [ "deal1", "_____no_output_____" ], [ "deal2", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ] ]
4aefd08f73a64646223a9a276e867ba92652353a
6,249
ipynb
Jupyter Notebook
notebooks/tweet-streaming-cosmosdb-python.ipynb
sumanthkannedari/datalakerepo
b1b87781a3408db5bb4a0bec94252be34bb2693c
[ "MIT" ]
42
2018-08-17T11:10:02.000Z
2022-03-04T20:49:21.000Z
notebooks/tweet-streaming-cosmosdb-python.ipynb
sumanthkannedari/datalakerepo
b1b87781a3408db5bb4a0bec94252be34bb2693c
[ "MIT" ]
null
null
null
notebooks/tweet-streaming-cosmosdb-python.ipynb
sumanthkannedari/datalakerepo
b1b87781a3408db5bb4a0bec94252be34bb2693c
[ "MIT" ]
40
2018-11-05T20:01:10.000Z
2022-03-25T12:46:00.000Z
3,124.5
6,248
0.75004
[ [ [ "# Streaming Sample: Cosmos DB ChangeFeed - Databricks\nIn this notebook, you read a live stream of tweets that stored in Cosmos DB by leveraging Apache Spart to read the Cosmos DB's Change Feed, and run transformations on the data in Databricks cluster.\n\n## prerequisites:\n- Databricks Cluster (Spark)\n- Cosmos DB Spark Connector (azure-cosmosdb-spark)\n - Create a library using maven coordinates. Simply typed in `azure-cosmosdb-spark_2.2.0` in the search box and search it, or create library by simply uploading jar file that can be donwload from marven central repository\n- Azure Cosmos DB Collection\n\n## Test Feed Generator\n- https://github.com/tknandu/TwitterCosmosDBFeed\n\n## LINKS\n- [Working with the change feed support in Azure Cosmos DB](https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed)\n- [Twitter with Spark and Azure Cosmos DB Change Feed Sample](https://github.com/Azure/azure-cosmosdb-spark/blob/master/samples/notebooks/Twitter%20with%20Spark%20and%20Azure%20Cosmos%20DB%20Change%20Feed.ipynb)\n- [Stream Processing Changes using Azure Cosmos DB Change Feed and Apache Spark](https://github.com/Azure/azure-cosmosdb-spark/wiki/Stream-Processing-Changes-using-Azure-Cosmos-DB-Change-Feed-and-Apache-Spark)\n- https://github.com/tknandu/TwitterCosmosDBFeed", "_____no_output_____" ], [ "## Configure Connection to Cosmos DB Change Feed using azure-cosmosdb-spark\nThe parameters below connect to the Cosmos DB Change Feed; for more information, please refer to Change Feed Test Runs.", "_____no_output_____" ] ], [ [ "# Adding variables \nrollingChangeFeed = False\nstartFromTheBeginning = False\nuseNextToken = True \n\ndatabase = \"changefeedsource\"\ncollection = \"tweet_new\"\n\ntweetsConfig = {\n\"Endpoint\" : \"https://dbstreamdemo.documents.azure.com:443/\",\n\"Masterkey\" : \"ekRLXkETPJ93s6XZz4YubZOw1mjSnoO5Bhz1Gk29bVxCbtgtKmiyRz4SogOSxLOGTouXbwlaAHcHOzct4JVwtQ==\",\n#\"Database\" : database,\n#\"Collection\" : collection, \n\"Database\" : \"changefeedsource\",\n\"Collection\" : \"tweet_new\", \n\"ReadChangeFeed\" : \"true\",\n\"ChangeFeedQueryName\" : database + collection + \" \",\n\"ChangeFeedStartFromTheBeginning\" : str(startFromTheBeginning),\n\"ChangeFeedUseNextToken\" : str(useNextToken),\n\"RollingChangeFeed\" : str(rollingChangeFeed),\n#\"ChangeFeedCheckpointLocation\" : \"./changefeedcheckpointlocation\",\n\"SamplingRatio\" : \"1.0\"\n}# Adding", "_____no_output_____" ] ], [ [ "## Read a DataFrame", "_____no_output_____" ] ], [ [ "# Read a DataFrame\n# SparkSession available as 'spark'.\ntweets = spark.read.format(\"com.microsoft.azure.cosmosdb.spark\").options(**tweetsConfig).load()\n", "_____no_output_____" ] ], [ [ "##Get the number of tweets\nThis provides the count of tweets; it will start off 0 and then continue growing as you re-run the cell below.", "_____no_output_____" ] ], [ [ "# Get the number of tweets\ntweets.count()\n# display(tweets)\n# tweets.printSchema()", "_____no_output_____" ] ], [ [ "## Create tweets TempView\nThis way we can run SQL statements within the notebook", "_____no_output_____" ] ], [ [ "# Create tweets TempView\n# This way we can run SQL statements within the notebook\ntweets.createOrReplaceTempView(\"tweets\")", "_____no_output_____" ], [ "%sql\nselect count(1) from tweets", "_____no_output_____" ] ], [ [ "## Show various attributes of the first 20 tweets", "_____no_output_____" ] ], [ [ "%sql\nselect \n id,\n created_at,\n user.screen_name,\n user.location,\n text,\n retweet_count,\n entities.hashtags,\n entities.user_mentions,\n favorited,\n source\nfrom tweets\nlimit 20", "_____no_output_____" ] ], [ [ "## Determine Top 10 hashtags for the tweets", "_____no_output_____" ] ], [ [ "%sql\nselect concat(concat((dense_rank() OVER (PARTITION BY 1 ORDER BY tweets DESC)-1), '. '), text) as hashtags, tweets\nfrom (\nselect hashtags.text, count(distinct id) as tweets\nfrom (\nselect \n explode(entities.hashtags) as hashtags,\n id\nfrom tweets\n) a\ngroup by hashtags.text\norder by tweets desc\nlimit 10\n) b", "_____no_output_____" ] ], [ [ "# [APPENDIX] Connnecting to Cosmos DB using pydocumentdb", "_____no_output_____" ] ], [ [ "# Import Necessary Libraries\nimport pydocumentdb\nfrom pydocumentdb import document_client\nfrom pydocumentdb import documents\nimport datetime\n\n# Configuring the connection policy (allowing for endpoint discovery)\nconnectionPolicy = documents.ConnectionPolicy()\nconnectionPolicy.EnableEndpointDiscovery \nconnectionPolicy.PreferredLocations = [\"Japan East\", \"Japan West\"]\n\n\n# Set keys to connect to Cosmos DB \nmasterKey = 'b3KPBHQvWTD8prYsQDiHlaM8kDzBholipD1sgshjT60ayDK9WkvRAT0Qywsi5FkcyKsYcvF4iIrUEBBzaZwJKw==' \nhost = 'https://videoanalytics.documents.azure.com:443/'\nclient = document_client.DocumentClient(host, {'masterKey': masterKey}, connectionPolicy)\n\n\n# Configure Database and Collections\ndatabaseId = 'asset'\ncollectionId = 'meta'\n\n# Configurations the Cosmos DB client will use to connect to the database and collection\ndbLink = 'dbs/' + databaseId\ncollLink = dbLink + '/colls/' + collectionId\n\n\n# Set query parameter\n#querystr = \"SELECT c.City FROM c WHERE c.State='WA'\"\nquerystr= \"SELECT * FROM c\"\n# Query documents\nquery = client.QueryDocuments(collLink, querystr, options=None, partition_key=None)\n\n# Query for partitioned collections\n# query = client.QueryDocuments(collLink, query, options= { 'enableCrossPartitionQuery': True }, partition_key=None)\n\n# Push into list `elements`\nelements = list(query)\nprint(elements)", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4aefe01f3ad64c1b79d6b85b266cd539d72df3e6
282,254
ipynb
Jupyter Notebook
src/scripts/experiment-2-VSD/test-results-fig.ipynb
NickleDave/Nicholson-Prinz-2020
35d49c5330f9e5e9945eb2ea93302b60ee1f0c1f
[ "BSD-3-Clause" ]
1
2020-12-24T09:56:35.000Z
2020-12-24T09:56:35.000Z
src/scripts/experiment-2-VSD/test-results-fig.ipynb
NickleDave/Nicholson-Prinz-2020
35d49c5330f9e5e9945eb2ea93302b60ee1f0c1f
[ "BSD-3-Clause" ]
12
2021-07-03T19:41:59.000Z
2021-07-29T02:01:33.000Z
src/scripts/experiment-2-VSD/test-results-fig.ipynb
NickleDave/Nicholson-Prinz-2020
35d49c5330f9e5e9945eb2ea93302b60ee1f0c1f
[ "BSD-3-Clause" ]
null
null
null
1,844.797386
277,960
0.957319
[ [ [ "from itertools import product\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pyprojroot\nimport seaborn as sns", "_____no_output_____" ], [ "SOURCE_DATA_ROOT = pyprojroot.here().joinpath('results/VSD/source_data')\n\nFIGURES_ROOT = pyprojroot.here('docs/paper/figures/experiment-2')", "_____no_output_____" ], [ "all_test_results_df = pd.read_csv(SOURCE_DATA_ROOT.joinpath('all_test_results.csv'))", "_____no_output_____" ], [ "all_test_results_df = pd.read_csv(SOURCE_DATA_ROOT.joinpath(", "_____no_output_____" ], [ "METHODS = ['transfer']\nLOSS_FUNCS = ['CE-largest', 'CE-random', 'BCE']\nLOSS_FUNC_ML_TASK_MAP = {\n 'CE-largest': 'single-label classification, largest object',\n 'CE-random': 'single label classification, random object',\n 'BCE': 'multi-label classification',\n}\n\nrows = list(product(METHODS, LOSS_FUNCS))\n\nn_rows = len(rows)\n\ncolumns = ['acc_largest', 'acc_random', 'f1']\nMETRIC_TITLE_MAP = {\n 'acc_largest': 'acc. (largest object)',\n 'acc_random': 'acc. (random object)',\n 'f1': 'f1 (macro)'\n}\n\nn_cols = len(METRICS)\n\nFIGSIZE = (15, 7.5)\nDPI = 300\n\nLABELSIZE = 6\nXTICKPAD = 2\nYTICKPAD = 1\n\nfig, ax = plt.subplots(n_rows, n_cols, figsize=FIGSIZE, dpi=DPI)\nfig.subplots_adjust(hspace=0.5)\n\nfor row_ind, row in enumerate(rows):\n method, loss_func = row[0], row[1]\n row_df = all_test_results_df[(all_test_results_df['method'] == method) & (all_test_results_df['loss_func'] == loss_func)]\n for col_ind, metric in enumerate(columns):\n row_df_sorted = row_df.sort_values(by=metric)\n sns.stripplot(x='net_name', y=metric, data=row_df_sorted, ax = ax[row_ind, col_ind])\n ax[row_ind, col_ind].set_ylim([0, 1])\n\n # add titles on top row\n if row_ind == 0:\n ax[row_ind, col_ind].set_title(METRIC_TITLE_MAP[metric])\n\n # add \"ML task\" as y-label for first column\n if col_ind == 0:\n ax[row_ind, col_ind].text(-0.45, -0.3, LOSS_FUNC_ML_TASK_MAP[loss_func], fontweight='bold', fontsize=12)\n\n ax[row_ind, col_ind].set_ylabel('')\n ax[row_ind, col_ind].set_xlabel('')\n \n# add a big axis, hide frame\nbig_ax = fig.add_subplot(111, frameon=False)\n# hide tick and tick label of the big axis\nbig_ax.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\nbig_ax.grid(False)\nbig_ax.set_xlabel(\"net name\", labelpad=0.1);\n\nfor ext in ('svg', 'png'):\n fig_path = FIGURES_ROOT.joinpath(\n f'test-results/test-results.{ext}'\n )\n plt.savefig(fig_path)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4aefe0a2621d5d228a4e775bf23cabf3450c6013
794,878
ipynb
Jupyter Notebook
notebook/FinalX.ipynb
harshnagoriya/FaceMask-Detection-System
4e45a258c8cf4cb8f8f4393780e6dcf4e8a82c7f
[ "BSD-2-Clause" ]
null
null
null
notebook/FinalX.ipynb
harshnagoriya/FaceMask-Detection-System
4e45a258c8cf4cb8f8f4393780e6dcf4e8a82c7f
[ "BSD-2-Clause" ]
null
null
null
notebook/FinalX.ipynb
harshnagoriya/FaceMask-Detection-System
4e45a258c8cf4cb8f8f4393780e6dcf4e8a82c7f
[ "BSD-2-Clause" ]
1
2020-09-10T15:52:39.000Z
2020-09-10T15:52:39.000Z
754.869896
755,310
0.943026
[ [ [ "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport shutil\nimport time\nimport copy\n", "_____no_output_____" ], [ "\n#to transform images and to convert it in order to form to tensors\ndata_transforms = {\n 'train': transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.ToTensor(), \n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]), \n 'test' : transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n}\n\n", "_____no_output_____" ], [ "import io\nimport zipfile\n!unzip /content/jpgtraintest.zip\n", "Archive: /content/jpgtraintest.zip\nreplace jpgtraintest/train/y/y91.jpg? [y]es, [n]o, [A]ll, [N]one, [r]ename: A\n inflating: jpgtraintest/train/y/y91.jpg \n inflating: jpgtraintest/train/y/y53.jpg \n inflating: jpgtraintest/train/y/y51.jpg \n inflating: jpgtraintest/train/y/y107.jpg \n inflating: jpgtraintest/train/y/y2.jpg \n inflating: jpgtraintest/train/y/y6.jpg \n inflating: jpgtraintest/train/y/y29.jpg \n inflating: jpgtraintest/train/y/y5.jpg \n inflating: jpgtraintest/train/y/y20.jpg \n inflating: jpgtraintest/train/y/y104.jpg \n inflating: jpgtraintest/train/y/y90.jpg \n inflating: jpgtraintest/train/y/y93.jpg \n inflating: jpgtraintest/train/y/y98.jpg \n inflating: jpgtraintest/train/y/y43.jpg \n inflating: jpgtraintest/train/y/y99.jpg \n inflating: jpgtraintest/train/y/y1.jpg \n inflating: jpgtraintest/train/y/y101.jpg \n inflating: jpgtraintest/train/y/y39.jpg \n inflating: jpgtraintest/train/y/y56.jpg \n inflating: jpgtraintest/train/y/y62.jpg \n inflating: jpgtraintest/train/y/y65.jpg \n inflating: jpgtraintest/train/y/y27.jpg \n inflating: jpgtraintest/train/y/y30.jpg \n inflating: jpgtraintest/train/y/y59.jpg \n inflating: jpgtraintest/train/y/y21.jpg \n inflating: jpgtraintest/train/y/y15.jpg \n inflating: jpgtraintest/train/y/y7.jpg \n inflating: jpgtraintest/train/y/y14.jpg \n inflating: jpgtraintest/train/y/y63.jpg \n inflating: jpgtraintest/train/y/y85.jpg \n inflating: jpgtraintest/train/y/y50.jpg \n inflating: jpgtraintest/train/y/y26.jpg \n inflating: jpgtraintest/train/y/y68.jpg \n inflating: jpgtraintest/train/y/y100.jpg \n inflating: jpgtraintest/train/y/y34.jpg \n inflating: jpgtraintest/train/y/y82.jpg \n inflating: jpgtraintest/train/y/y33.jpg \n inflating: jpgtraintest/train/y/y64.jpg \n inflating: jpgtraintest/train/y/y108.jpg \n inflating: jpgtraintest/train/y/y97.jpg \n inflating: jpgtraintest/train/y/y17.jpg \n inflating: jpgtraintest/train/y/y37.jpg \n inflating: jpgtraintest/train/y/y83.jpg \n inflating: jpgtraintest/train/y/y57.jpg \n inflating: jpgtraintest/train/y/y31.jpg \n inflating: jpgtraintest/train/y/y12.jpg \n inflating: jpgtraintest/train/y/y48.jpg \n inflating: jpgtraintest/train/y/y24.jpg \n inflating: jpgtraintest/train/y/y94.jpg \n inflating: jpgtraintest/train/y/y8.jpg \n inflating: jpgtraintest/train/y/y86.jpg \n inflating: jpgtraintest/train/y/y0.jpg \n inflating: jpgtraintest/train/y/y18.jpg \n inflating: jpgtraintest/train/y/y32.jpg \n inflating: jpgtraintest/train/y/y74.jpg \n inflating: jpgtraintest/train/y/y42.jpg \n inflating: jpgtraintest/train/y/y25.jpg \n inflating: jpgtraintest/train/y/y54.jpg \n inflating: jpgtraintest/train/y/y16.jpg \n inflating: jpgtraintest/train/y/y77.jpg \n inflating: jpgtraintest/train/y/y55.jpg \n inflating: jpgtraintest/train/y/y109.jpg \n inflating: jpgtraintest/train/y/y95.jpg \n inflating: jpgtraintest/train/y/y72.jpg \n inflating: jpgtraintest/train/y/y103.jpg \n inflating: jpgtraintest/train/y/y47.jpg \n inflating: jpgtraintest/train/y/y106.jpg \n inflating: jpgtraintest/train/y/y102.jpg \n inflating: jpgtraintest/train/y/y60.jpg \n inflating: jpgtraintest/train/y/y78.jpg \n inflating: jpgtraintest/train/y/y22.jpg \n inflating: jpgtraintest/train/y/y3.jpg \n inflating: jpgtraintest/train/y/y70.jpg \n inflating: jpgtraintest/train/y/y36.jpg \n inflating: jpgtraintest/train/y/y92.jpg \n inflating: jpgtraintest/train/y/y28.jpg \n inflating: jpgtraintest/train/y/y52.jpg \n inflating: jpgtraintest/train/y/y13.jpg \n inflating: jpgtraintest/train/y/y69.jpg \n inflating: jpgtraintest/train/y/y40.jpg \n inflating: jpgtraintest/train/y/y10.jpg \n inflating: jpgtraintest/train/y/y87.jpg \n inflating: jpgtraintest/train/y/y75.jpg \n inflating: jpgtraintest/train/y/y79.jpg \n inflating: jpgtraintest/train/y/y4.jpg \n inflating: jpgtraintest/train/y/y58.jpg \n inflating: jpgtraintest/train/y/y105.jpg \n inflating: jpgtraintest/train/y/y46.jpg \n inflating: jpgtraintest/train/x/x91.jpg \n inflating: jpgtraintest/train/x/x53.jpg \n inflating: jpgtraintest/train/x/x51.jpg \n inflating: jpgtraintest/train/x/x107.jpg \n inflating: jpgtraintest/train/x/x2.jpg \n inflating: jpgtraintest/train/x/x6.jpg \n inflating: jpgtraintest/train/x/x29.jpg \n inflating: jpgtraintest/train/x/x5.jpg \n inflating: jpgtraintest/train/x/x20.jpg \n inflating: jpgtraintest/train/x/x104.jpg \n inflating: jpgtraintest/train/x/x90.jpg \n inflating: jpgtraintest/train/x/x93.jpg \n inflating: jpgtraintest/train/x/x98.jpg \n inflating: jpgtraintest/train/x/x43.jpg \n inflating: jpgtraintest/train/x/x99.jpg \n inflating: jpgtraintest/train/x/x1.jpg \n inflating: jpgtraintest/train/x/x101.jpg \n inflating: jpgtraintest/train/x/x39.jpg \n inflating: jpgtraintest/train/x/x56.jpg \n inflating: jpgtraintest/train/x/x62.jpg \n inflating: jpgtraintest/train/x/x65.jpg \n inflating: jpgtraintest/train/x/x27.jpg \n inflating: jpgtraintest/train/x/x30.jpg \n inflating: jpgtraintest/train/x/x59.jpg \n inflating: jpgtraintest/train/x/x21.jpg \n inflating: jpgtraintest/train/x/x15.jpg \n inflating: jpgtraintest/train/x/x7.jpg \n inflating: jpgtraintest/train/x/x14.jpg \n inflating: jpgtraintest/train/x/x63.jpg \n inflating: jpgtraintest/train/x/x85.jpg \n inflating: jpgtraintest/train/x/x50.jpg \n inflating: jpgtraintest/train/x/x26.jpg \n inflating: jpgtraintest/train/x/x68.jpg \n inflating: jpgtraintest/train/x/x100.jpg \n inflating: jpgtraintest/train/x/x34.jpg \n inflating: jpgtraintest/train/x/x82.jpg \n inflating: jpgtraintest/train/x/x33.jpg \n inflating: jpgtraintest/train/x/x64.jpg \n inflating: jpgtraintest/train/x/x108.jpg \n inflating: jpgtraintest/train/x/x97.jpg \n inflating: jpgtraintest/train/x/x17.jpg \n inflating: jpgtraintest/train/x/x37.jpg \n inflating: jpgtraintest/train/x/x83.jpg \n inflating: jpgtraintest/train/x/x57.jpg \n inflating: jpgtraintest/train/x/x31.jpg \n inflating: jpgtraintest/train/x/x12.jpg \n inflating: jpgtraintest/train/x/x48.jpg \n inflating: jpgtraintest/train/x/x24.jpg \n inflating: jpgtraintest/train/x/x94.jpg \n inflating: jpgtraintest/train/x/x8.jpg \n inflating: jpgtraintest/train/x/x86.jpg \n inflating: jpgtraintest/train/x/x0.jpg \n inflating: jpgtraintest/train/x/x18.jpg \n inflating: jpgtraintest/train/x/x32.jpg \n inflating: jpgtraintest/train/x/x74.jpg \n inflating: jpgtraintest/train/x/x42.jpg \n inflating: jpgtraintest/train/x/x25.jpg \n inflating: jpgtraintest/train/x/x54.jpg \n inflating: jpgtraintest/train/x/x16.jpg \n inflating: jpgtraintest/train/x/x77.jpg \n inflating: jpgtraintest/train/x/x55.jpg \n inflating: jpgtraintest/train/x/x109.jpg \n inflating: jpgtraintest/train/x/x95.jpg \n inflating: jpgtraintest/train/x/x72.jpg \n inflating: jpgtraintest/train/x/x103.jpg \n inflating: jpgtraintest/train/x/x47.jpg \n inflating: jpgtraintest/train/x/x106.jpg \n inflating: jpgtraintest/train/x/x102.jpg \n inflating: jpgtraintest/train/x/x60.jpg \n inflating: jpgtraintest/train/x/x78.jpg \n inflating: jpgtraintest/train/x/x22.jpg \n inflating: jpgtraintest/train/x/x3.jpg \n inflating: jpgtraintest/train/x/x70.jpg \n inflating: jpgtraintest/train/x/x36.jpg \n inflating: jpgtraintest/train/x/x92.jpg \n inflating: jpgtraintest/train/x/x28.jpg \n inflating: jpgtraintest/train/x/x52.jpg \n inflating: jpgtraintest/train/x/x13.jpg \n inflating: jpgtraintest/train/x/x69.jpg \n inflating: jpgtraintest/train/x/x40.jpg \n inflating: jpgtraintest/train/x/x10.jpg \n inflating: jpgtraintest/train/x/x87.jpg \n inflating: jpgtraintest/train/x/x75.jpg \n inflating: jpgtraintest/train/x/x79.jpg \n inflating: jpgtraintest/train/x/x4.jpg \n inflating: jpgtraintest/train/x/x58.jpg \n inflating: jpgtraintest/train/x/x105.jpg \n inflating: jpgtraintest/train/x/x46.jpg \n inflating: jpgtraintest/test/y/y89.jpg \n inflating: jpgtraintest/test/y/y49.jpg \n inflating: jpgtraintest/test/y/y11.jpg \n inflating: jpgtraintest/test/y/y88.jpg \n inflating: jpgtraintest/test/y/y76.jpg \n inflating: jpgtraintest/test/y/y23.jpg \n inflating: jpgtraintest/test/y/y80.jpg \n inflating: jpgtraintest/test/y/y45.jpg \n inflating: jpgtraintest/test/y/y35.jpg \n inflating: jpgtraintest/test/y/y96.jpg \n inflating: jpgtraintest/test/y/y73.jpg \n inflating: jpgtraintest/test/y/y44.jpg \n inflating: jpgtraintest/test/y/y38.jpg \n inflating: jpgtraintest/test/y/y9.jpg \n inflating: jpgtraintest/test/y/y19.jpg \n inflating: jpgtraintest/test/y/y84.jpg \n inflating: jpgtraintest/test/y/y67.jpg \n inflating: jpgtraintest/test/y/y66.jpg \n inflating: jpgtraintest/test/y/y41.jpg \n inflating: jpgtraintest/test/y/y81.jpg \n inflating: jpgtraintest/test/y/y61.jpg \n inflating: jpgtraintest/test/y/y71.jpg \n inflating: jpgtraintest/test/x/x89.jpg \n inflating: jpgtraintest/test/x/x49.jpg \n inflating: jpgtraintest/test/x/x11.jpg \n inflating: jpgtraintest/test/x/x88.jpg \n inflating: jpgtraintest/test/x/x76.jpg \n inflating: jpgtraintest/test/x/x23.jpg \n inflating: jpgtraintest/test/x/x80.jpg \n inflating: jpgtraintest/test/x/x45.jpg \n inflating: jpgtraintest/test/x/x35.jpg \n inflating: jpgtraintest/test/x/x96.jpg \n inflating: jpgtraintest/test/x/x73.jpg \n inflating: jpgtraintest/test/x/x44.jpg \n inflating: jpgtraintest/test/x/x38.jpg \n inflating: jpgtraintest/test/x/x9.jpg \n inflating: jpgtraintest/test/x/x19.jpg \n inflating: jpgtraintest/test/x/x84.jpg \n inflating: jpgtraintest/test/x/x67.jpg \n inflating: jpgtraintest/test/x/x66.jpg \n inflating: jpgtraintest/test/x/x41.jpg \n inflating: jpgtraintest/test/x/x81.jpg \n inflating: jpgtraintest/test/x/x61.jpg \n inflating: jpgtraintest/test/x/x71.jpg \n" ], [ "", "_____no_output_____" ], [ "image_datasets = {x: datasets.ImageFolder(os.path.join('/content/jpgtraintest', x), data_transforms[x]) for x in ['train', 'test']}", "_____no_output_____" ], [ "image_datasets['train']", "_____no_output_____" ], [ "image_datasets['test']", "_____no_output_____" ], [ "dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], \n batch_size=16, \n shuffle=True, \n num_workers=4) \n for x in ['train', 'test']}\n#HSN: data loader: python iterable dataset", "_____no_output_____" ], [ "dataloaders", "_____no_output_____" ], [ "class_names = image_datasets['train'].classes", "_____no_output_____" ], [ "class_names", "_____no_output_____" ], [ "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n#to use GPU version", "_____no_output_____" ], [ "device", "_____no_output_____" ], [ "dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'test']}", "_____no_output_____" ], [ "def imshow(inp, title=None):\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 plt.figure(figsize=(20,20))\n plt.imshow(inp)\n\n if title is not None:\n plt.title(title)\n plt.pause(0.001)\n", "_____no_output_____" ], [ "inputs, classes = next(iter(dataloaders['train']))\nout = torchvision.utils.make_grid(inputs)\n#iter(dataloader) creates an object of class _DataLoaderIter and, in the loop, creates same object n times and retrieve the first batch only.", "_____no_output_____" ], [ "imshow(out, title=[class_names[x] for x in classes])", "_____no_output_____" ], [ "def train_model(model, criterion, optimizer, scheduler, num_epochs=20):\n since = time.time()\n best_acc = 0.0\n best_model = copy.deepcopy(model.state_dict())\n #HSN: making deep copy of model.\n new_freeze_state = None\n prev_freeze_state = False\n for epoch in range(num_epochs):\n print(\"Epoch {}/{}\".format(epoch, num_epochs - 1))\n print('-' * 10)\n \n for phase in ['train', 'test']:\n if phase == 'train':\n scheduler.step()\n #HSN: Following the scheme to Decay LR by a factor of 0.1 every 7 epochs\n model.train()\n #HSNL model.train() tells your model that you are training the model. So effectively layers like dropout, batchnorm etc. \n else:\n model.eval()\n #HSN: model.eval() will notify all layers that you are in eval mode, that way, batchnorm or dropout layers will work in eval mode instead of training mode\n running_loss = 0.0\n running_corrects = 0\n \n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n #HSN: Saving it to CUDA:0 GPU\n optimizer.zero_grad()\n #HSN: to clear the existing gradient\n #HSN: we need to set the gradients to zero before starting to do backpropragation\n \n with torch.set_grad_enabled(phase == 'train'):\n #HSNL enable grad, based on train phase\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n #HSN: maximum value of all elements in the input tensor.\n loss = criterion(outputs, labels)\n \n if phase == 'train':\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n \n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n \n print('{} Loss: {:.4f} Acc:{:.4f}'.format(\n phase, epoch_loss, epoch_acc))\n \n \n if phase == 'test' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model = copy.deepcopy(model.state_dict())\n \n print()\n \n time_elapsed = time.time() - since\n print('Training complete in {:0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Best val acc: {:4f}'.format(best_acc))\n \n model.load_state_dict(best_model)\n return model", "_____no_output_____" ], [ "import ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\n", "_____no_output_____" ], [ "model_ft = models.resnet101(pretrained=True)\n#HSN: ResNet-101 model from Deep Residual Learning for Image Recognition\nnum_frts = model_ft.fc.in_features\nmodel_ft.fc = nn.Linear(num_frts, len(class_names))\n#HSN: in-feature for fc layer of resnet101\n\nmodel_ft = model_ft.to(device)\n#HSN: Model saved to CUDA:0 GPU\ncriterion = nn.CrossEntropyLoss()\n#HSN: setting criterion as \"training a classification problem with n number of classes\".\n\n#optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.01, momentum=0.9)\noptimizer_ft = optim.Adagrad(model_ft.parameters(), lr=0.001)\n#HSN: Implements Adagrad algorithm with Learning rate 0.001\nexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)\n#HSN: Decays the learning rate of each parameter group by gamma every step_size epochs. This decay can happen simultaneously with other changes to the learning rate from outside this scheduler.", "_____no_output_____" ], [ "model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=20)", "Epoch 0/19\n----------\n" ], [ "", "_____no_output_____" ], [ "torch.save(model_ft, 'x.pth')", "_____no_output_____" ], [ "model = None\n\ndef load_model():\n global model\n filepath = 'x.pth'\n model = torch.load(filepath)\n class_names = ['without_mask','with_mask']", "_____no_output_____" ], [ "\nimport pickle\nimport numpy as np\nfrom flask import Flask, request\n\nmodel = None\napp = Flask(__name__)\n\nmodel = None\ndef load_model():\n global model\n filepath = 'x.pth'\n model = torch.load(filepath)\n class_names = ['without_mask','with_mask']\n\[email protected]('/')\ndef home_endpoint():\n return 'Hello World!'\n\n\[email protected]('/predict', methods=['POST'])\ndef get_prediction():\n # Works only for a single sample\n if request.method == 'POST':\n data = request.get_json() # Get data posted as a json\n data = np.array(data)[np.newaxis, :] # converts shape from (4,) to (1, 4)\n prediction = model.predict(data) # runs globally loaded model on the data\n return str(prediction[0])\n\n\nif __name__ == '__main__':\n load_model() # load model at the beginning once only\n app.run(host='0.0.0.0', port=80)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4aeff981e3aef4b16d4d421e7ac7be5e754ae8ee
66,762
ipynb
Jupyter Notebook
nbs/03_data.core.ipynb
flpeters/fastai2
370ac0169a190abe45bae061daa5fb00ab2d1e01
[ "Apache-2.0" ]
null
null
null
nbs/03_data.core.ipynb
flpeters/fastai2
370ac0169a190abe45bae061daa5fb00ab2d1e01
[ "Apache-2.0" ]
null
null
null
nbs/03_data.core.ipynb
flpeters/fastai2
370ac0169a190abe45bae061daa5fb00ab2d1e01
[ "Apache-2.0" ]
null
null
null
32.456004
828
0.534705
[ [ [ "#default_exp data.core", "_____no_output_____" ], [ "#export\nfrom fastai2.torch_basics import *\nfrom fastai2.data.load import *", "_____no_output_____" ], [ "from nbdev.showdoc import *", "_____no_output_____" ] ], [ [ "# Data core\n\n> Core functionality for gathering data", "_____no_output_____" ], [ "The classes here provide functionality for applying a list of transforms to a set of items (`TfmdLists`, `Datasets`) or a `DataLoader` (`TfmdDl`) as well as the base class used to gather the data for model training: `DataLoaders`.", "_____no_output_____" ], [ "## TfmdDL -", "_____no_output_____" ] ], [ [ "#export\n@typedispatch\ndef show_batch(x, y, samples, ctxs=None, max_n=9, **kwargs):\n if ctxs is None: ctxs = Inf.nones\n if hasattr(samples[0], 'show'):\n ctxs = [s.show(ctx=c, **kwargs) for s,c,_ in zip(samples,ctxs,range(max_n))]\n else:\n for i in range_of(samples[0]):\n ctxs = [b.show(ctx=c, **kwargs) for b,c,_ in zip(samples.itemgot(i),ctxs,range(max_n))]\n return ctxs", "_____no_output_____" ] ], [ [ "`show_batch` is a type-dispatched function that is responsible for showing decoded `samples`. `x` and `y` are the input and the target in the batch to be shown, and are passed along to dispatch on their types. There is a different implementation of `show_batch` if `x` is a `TensorImage` or a `TensorText` for instance (see vision.core or text.data for more details). `ctxs` can be passed but the function is responsible to create them if necessary. `kwargs` depend on the specific implementation.", "_____no_output_____" ] ], [ [ "#export\n@typedispatch\ndef show_results(x, y, samples, outs, ctxs=None, max_n=9, **kwargs):\n if ctxs is None: ctxs = Inf.nones\n for i in range(len(samples[0])):\n ctxs = [b.show(ctx=c, **kwargs) for b,c,_ in zip(samples.itemgot(i),ctxs,range(max_n))]\n for i in range(len(outs[0])):\n ctxs = [b.show(ctx=c, **kwargs) for b,c,_ in zip(outs.itemgot(i),ctxs,range(max_n))]\n return ctxs", "_____no_output_____" ] ], [ [ "`show_results` is a type-dispatched function that is responsible for showing decoded `samples` and their corresponding `outs`. Like in `show_batch`, `x` and `y` are the input and the target in the batch to be shown, and are passed along to dispatch on their types. `ctxs` can be passed but the function is responsible to create them if necessary. `kwargs` depend on the specific implementation.", "_____no_output_____" ] ], [ [ "#export\n_all_ = [\"show_batch\", \"show_results\"]", "_____no_output_____" ], [ "#export\n_batch_tfms = ('after_item','before_batch','after_batch')", "_____no_output_____" ], [ "#export\n@log_args(but_as=DataLoader.__init__)\n@delegates()\nclass TfmdDL(DataLoader):\n \"Transformed `DataLoader`\"\n def __init__(self, dataset, bs=64, shuffle=False, num_workers=None, verbose=False, do_setup=True, **kwargs):\n if num_workers is None: num_workers = min(16, defaults.cpus)\n for nm in _batch_tfms: kwargs[nm] = Pipeline(kwargs.get(nm,None))\n super().__init__(dataset, bs=bs, shuffle=shuffle, num_workers=num_workers, **kwargs)\n if do_setup:\n for nm in _batch_tfms: \n pv(f\"Setting up {nm}: {kwargs[nm]}\", verbose)\n kwargs[nm].setup(self)\n\n def _one_pass(self):\n b = self.do_batch([self.do_item(0)])\n if self.device is not None: b = to_device(b, self.device)\n its = self.after_batch(b)\n self._n_inp = 1 if not isinstance(its, (list,tuple)) or len(its)==1 else len(its)-1\n self._types = explode_types(its)\n\n def _retain_dl(self,b):\n if not getattr(self, '_types', None): self._one_pass()\n return retain_types(b, typs=self._types)\n\n @delegates(DataLoader.new)\n def new(self, dataset=None, cls=None, **kwargs):\n res = super().new(dataset, cls, do_setup=False, **kwargs)\n if not hasattr(self, '_n_inp') or not hasattr(self, '_types'):\n self._one_pass()\n res._n_inp,res._types = self._n_inp,self._types\n else: res._n_inp,res._types = self._n_inp,self._types\n return res\n\n def before_iter(self):\n super().before_iter()\n split_idx = getattr(self.dataset, 'split_idx', None)\n for nm in _batch_tfms:\n f = getattr(self,nm)\n if isinstance(f,Pipeline): f.split_idx=split_idx\n\n def decode(self, b): return self.before_batch.decode(to_cpu(self.after_batch.decode(self._retain_dl(b))))\n def decode_batch(self, b, max_n=9, full=True): return self._decode_batch(self.decode(b), max_n, full)\n\n def _decode_batch(self, b, max_n=9, full=True):\n f = self.after_item.decode\n f = compose(f, partial(getattr(self.dataset,'decode',noop), full = full))\n return L(batch_to_samples(b, max_n=max_n)).map(f)\n\n def _pre_show_batch(self, b, max_n=9):\n \"Decode `b` to be ready for `show_batch`\"\n b = self.decode(b)\n if hasattr(b, 'show'): return b,None,None\n its = self._decode_batch(b, max_n, full=False)\n if not is_listy(b): b,its = [b],L((o,) for o in its)\n return detuplify(b[:self.n_inp]),detuplify(b[self.n_inp:]),its\n\n def show_batch(self, b=None, max_n=9, ctxs=None, show=True, unique=False, **kwargs):\n if unique:\n old_get_idxs = self.get_idxs\n self.get_idxs = lambda: Inf.zeros\n if b is None: b = self.one_batch()\n if not show: return self._pre_show_batch(b, max_n=max_n)\n show_batch(*self._pre_show_batch(b, max_n=max_n), ctxs=ctxs, max_n=max_n, **kwargs)\n if unique: self.get_idxs = old_get_idxs\n\n def show_results(self, b, out, max_n=9, ctxs=None, show=True, **kwargs):\n x,y,its = self.show_batch(b, max_n=max_n, show=False)\n b_out = type(b)(b[:self.n_inp] + (tuple(out) if is_listy(out) else (out,))) \n x1,y1,outs = self.show_batch(b_out, max_n=max_n, show=False)\n res = (x,x1,None,None) if its is None else (x, y, its, outs.itemgot(slice(self.n_inp,None)))\n if not show: return res\n show_results(*res, ctxs=ctxs, max_n=max_n, **kwargs)\n\n @property\n def n_inp(self):\n if hasattr(self.dataset, 'n_inp'): return self.dataset.n_inp\n if not hasattr(self, '_n_inp'): self._one_pass()\n return self._n_inp\n \n def to(self, device):\n self.device = device\n for tfm in self.after_batch.fs:\n for a in L(getattr(tfm, 'parameters', None)): setattr(tfm, a, getattr(tfm, a).to(device))\n return self", "_____no_output_____" ] ], [ [ "A `TfmdDL` is a `DataLoader` that creates `Pipeline` from a list of `Transform`s for the callbacks `after_item`, `before_batch` and `after_batch`. As a result, it can decode or show a processed `batch`.", "_____no_output_____" ] ], [ [ "add_docs(TfmdDL,\n decode=\"Decode `b` using `tfms`\",\n decode_batch=\"Decode `b` entirely\",\n new=\"Create a new version of self with a few changed attributes\",\n show_batch=\"Show `b` (defaults to `one_batch`), a list of lists of pipeline outputs (i.e. output of a `DataLoader`)\",\n show_results=\"Show each item of `b` and `out`\",\n before_iter=\"override\",\n to=\"Put self and its transforms state on `device`\")", "_____no_output_____" ], [ "class _Category(int, ShowTitle): pass", "_____no_output_____" ], [ "#Test retain type\nclass NegTfm(Transform):\n def encodes(self, x): return torch.neg(x)\n def decodes(self, x): return torch.neg(x)\n \ntdl = TfmdDL([(TensorImage([1]),)] * 4, after_batch=NegTfm(), bs=4, num_workers=4)\nb = tdl.one_batch()\ntest_eq(type(b[0]), TensorImage)\nb = (tensor([1.,1.,1.,1.]),)\ntest_eq(type(tdl.decode_batch(b)[0][0]), TensorImage)", "_____no_output_____" ], [ "class A(Transform): \n def encodes(self, x): return x \n def decodes(self, x): return TitledInt(x) \n\n@Transform\ndef f(x)->None: return Tuple((x,x))\n\nstart = torch.arange(50)\ntest_eq_type(f(2), Tuple((2,2)))", "_____no_output_____" ], [ "a = A()\ntdl = TfmdDL(start, after_item=lambda x: (a(x), f(x)), bs=4)\nx,y = tdl.one_batch()\ntest_eq(type(y), Tuple)\n\ns = tdl.decode_batch((x,y))\ntest_eq(type(s[0][1]), Tuple)", "_____no_output_____" ], [ "tdl = TfmdDL(torch.arange(0,50), after_item=A(), after_batch=NegTfm(), bs=4)\ntest_eq(tdl.dataset[0], start[0])\ntest_eq(len(tdl), (50-1)//4+1)\ntest_eq(tdl.bs, 4)\ntest_stdout(tdl.show_batch, '0\\n1\\n2\\n3')\ntest_stdout(partial(tdl.show_batch, unique=True), '0\\n0\\n0\\n0')", "_____no_output_____" ], [ "class B(Transform):\n parameters = 'a'\n def __init__(self): self.a = torch.tensor(0.)\n def encodes(self, x): x\n \ntdl = TfmdDL([(TensorImage([1]),)] * 4, after_batch=B(), bs=4)\ntest_eq(tdl.after_batch.fs[0].a.device, torch.device('cpu'))\ntdl.to(default_device())\ntest_eq(tdl.after_batch.fs[0].a.device, default_device())", "_____no_output_____" ] ], [ [ "### Methods", "_____no_output_____" ] ], [ [ "show_doc(TfmdDL.one_batch)", "_____no_output_____" ], [ "tfm = NegTfm()\ntdl = TfmdDL(start, after_batch=tfm, bs=4)", "_____no_output_____" ], [ "b = tdl.one_batch()\ntest_eq(tensor([0,-1,-2,-3]), b)", "_____no_output_____" ], [ "show_doc(TfmdDL.decode)", "_____no_output_____" ], [ "test_eq(tdl.decode(b), tensor(0,1,2,3))", "_____no_output_____" ], [ "show_doc(TfmdDL.decode_batch)", "_____no_output_____" ], [ "test_eq(tdl.decode_batch(b), [0,1,2,3])", "_____no_output_____" ], [ "show_doc(TfmdDL.show_batch)", "_____no_output_____" ], [ "show_doc(TfmdDL.to)", "_____no_output_____" ] ], [ [ "## DataLoaders -", "_____no_output_____" ] ], [ [ "# export\n@docs\nclass DataLoaders(GetAttr):\n \"Basic wrapper around several `DataLoader`s.\"\n _default='train'\n def __init__(self, *loaders, path='.', device=None):\n self.loaders,self.path = list(loaders),Path(path)\n self.device = device\n\n def __getitem__(self, i): return self.loaders[i]\n def new_empty(self):\n loaders = [dl.new(dl.dataset.new_empty()) for dl in self.loaders]\n return type(self)(*loaders, path=self.path, device=self.device)\n \n def _set(i, self, v): self.loaders[i] = v\n train ,valid = add_props(lambda i,x: x[i], _set)\n train_ds,valid_ds = add_props(lambda i,x: x[i].dataset)\n\n @property\n def device(self): return self._device\n\n @device.setter\n def device(self, d):\n for dl in self.loaders: dl.to(d)\n self._device = d\n\n def to(self, device): \n self.device = device\n return self\n \n def cuda(self): return self.to(device=default_device())\n def cpu(self): return self.to(device=torch.device('cpu'))\n \n @classmethod\n def from_dsets(cls, *ds, path='.', bs=64, device=None, dl_type=TfmdDL, **kwargs):\n default = (True,) + (False,) * (len(ds)-1)\n defaults = {'shuffle': default, 'drop_last': default}\n for nm in _batch_tfms: \n if nm in kwargs: kwargs[nm] = Pipeline(kwargs[nm])\n kwargs = merge(defaults, {k: tuplify(v, match=ds) for k,v in kwargs.items()})\n kwargs = [{k: v[i] for k,v in kwargs.items()} for i in range_of(ds)]\n return cls(*[dl_type(d, bs=bs, **k) for d,k in zip(ds, kwargs)], path=path, device=device)\n\n @classmethod\n def from_dblock(cls, dblock, source, path='.', bs=64, val_bs=None, shuffle_train=True, device=None, **kwargs):\n return dblock.dataloaders(source, path=path, bs=bs, val_bs=val_bs, shuffle_train=shuffle_train, device=device, **kwargs)\n\n _docs=dict(__getitem__=\"Retrieve `DataLoader` at `i` (`0` is training, `1` is validation)\",\n train=\"Training `DataLoader`\",\n valid=\"Validation `DataLoader`\",\n train_ds=\"Training `Dataset`\",\n valid_ds=\"Validation `Dataset`\",\n to=\"Use `device`\",\n cuda=\"Use the gpu if available\",\n cpu=\"Use the cpu\",\n new_empty=\"Create a new empty version of `self` with the same transforms\",\n from_dblock=\"Create a dataloaders from a given `dblock`\")", "_____no_output_____" ], [ "dls = DataLoaders(tdl,tdl)\nx = dls.train.one_batch()\nx2 = first(tdl)\ntest_eq(x,x2)\nx2 = dls.one_batch()\ntest_eq(x,x2)", "_____no_output_____" ], [ "#hide\n#test assignment works\ndls.train = dls.train.new(bs=4)", "_____no_output_____" ] ], [ [ "### Methods", "_____no_output_____" ] ], [ [ "show_doc(DataLoaders.__getitem__)", "_____no_output_____" ], [ "x2 = dls[0].one_batch()\ntest_eq(x,x2)", "_____no_output_____" ], [ "show_doc(DataLoaders.train, name=\"DataLoaders.train\")", "_____no_output_____" ], [ "show_doc(DataLoaders.valid, name=\"DataLoaders.valid\")", "_____no_output_____" ], [ "show_doc(DataLoaders.train_ds, name=\"DataLoaders.train_ds\")", "_____no_output_____" ], [ "show_doc(DataLoaders.valid_ds, name=\"DataLoaders.valid_ds\")", "_____no_output_____" ] ], [ [ "## TfmdLists -", "_____no_output_____" ] ], [ [ "#export\nclass FilteredBase:\n \"Base class for lists with subsets\"\n _dl_type,_dbunch_type = TfmdDL,DataLoaders\n def __init__(self, *args, dl_type=None, **kwargs):\n if dl_type is not None: self._dl_type = dl_type\n self.dataloaders = delegates(self._dl_type.__init__)(self.dataloaders)\n super().__init__(*args, **kwargs)\n\n @property\n def n_subsets(self): return len(self.splits)\n def _new(self, items, **kwargs): return super()._new(items, splits=self.splits, **kwargs)\n def subset(self): raise NotImplemented\n\n def dataloaders(self, bs=64, val_bs=None, shuffle_train=True, n=None, path='.', dl_type=None, dl_kwargs=None, \n device=None, **kwargs):\n if device is None: device=default_device()\n if dl_kwargs is None: dl_kwargs = [{}] * self.n_subsets\n if dl_type is None: dl_type = self._dl_type\n drop_last = kwargs.pop('drop_last', shuffle_train)\n dl = dl_type(self.subset(0), bs=bs, shuffle=shuffle_train, drop_last=drop_last, n=n, device=device,\n **merge(kwargs, dl_kwargs[0]))\n dls = [dl] + [dl.new(self.subset(i), bs=(bs if val_bs is None else val_bs), shuffle=False, drop_last=False, \n n=None, **dl_kwargs[i]) for i in range(1, self.n_subsets)]\n return self._dbunch_type(*dls, path=path, device=device)\n\nFilteredBase.train,FilteredBase.valid = add_props(lambda i,x: x.subset(i))", "_____no_output_____" ], [ "#export\nclass TfmdLists(FilteredBase, L, GetAttr):\n \"A `Pipeline` of `tfms` applied to a collection of `items`\"\n _default='tfms'\n def __init__(self, items, tfms, use_list=None, do_setup=True, split_idx=None, train_setup=True,\n splits=None, types=None, verbose=False, dl_type=None):\n super().__init__(items, use_list=use_list)\n if dl_type is not None: self._dl_type = dl_type\n self.splits = L([slice(None),[]] if splits is None else splits).map(mask2idxs)\n if isinstance(tfms,TfmdLists): tfms = tfms.tfms\n if isinstance(tfms,Pipeline): do_setup=False\n self.tfms = Pipeline(tfms, split_idx=split_idx)\n store_attr(self, 'types,split_idx')\n if do_setup: \n pv(f\"Setting up {self.tfms}\", verbose)\n self.setup(train_setup=train_setup)\n\n def _new(self, items, split_idx=None, **kwargs): \n split_idx = ifnone(split_idx,self.split_idx)\n return super()._new(items, tfms=self.tfms, do_setup=False, types=self.types, split_idx=split_idx, **kwargs)\n def subset(self, i): return self._new(self._get(self.splits[i]), split_idx=i)\n def _after_item(self, o): return self.tfms(o)\n def __repr__(self): return f\"{self.__class__.__name__}: {self.items}\\ntfms - {self.tfms.fs}\"\n def __iter__(self): return (self[i] for i in range(len(self)))\n def show(self, o, **kwargs): return self.tfms.show(o, **kwargs)\n def decode(self, o, **kwargs): return self.tfms.decode(o, **kwargs)\n def __call__(self, o, **kwargs): return self.tfms.__call__(o, **kwargs)\n def overlapping_splits(self): return L(Counter(self.splits.concat()).values()).filter(gt(1))\n def new_empty(self): return self._new([])\n\n def setup(self, train_setup=True):\n self.tfms.setup(self, train_setup)\n if len(self) != 0:\n x = super().__getitem__(0) if self.splits is None else super().__getitem__(self.splits[0])[0]\n self.types = []\n for f in self.tfms.fs:\n self.types.append(getattr(f, 'input_types', type(x)))\n x = f(x)\n self.types.append(type(x))\n types = L(t if is_listy(t) else [t] for t in self.types).concat().unique()\n self.pretty_types = '\\n'.join([f' - {t}' for t in types])\n\n def infer_idx(self, x):\n idx = 0\n for t in self.types:\n if isinstance(x, t): break\n idx += 1\n types = L(t if is_listy(t) else [t] for t in self.types).concat().unique()\n pretty_types = '\\n'.join([f' - {t}' for t in types])\n assert idx < len(self.types), f\"Expected an input of type in \\n{pretty_types}\\n but got {type(x)}\"\n return idx\n\n def infer(self, x):\n return compose_tfms(x, tfms=self.tfms.fs[self.infer_idx(x):], split_idx=self.split_idx)\n\n def __getitem__(self, idx):\n res = super().__getitem__(idx)\n if self._after_item is None: return res\n return self._after_item(res) if is_indexer(idx) else res.map(self._after_item)", "_____no_output_____" ], [ "add_docs(TfmdLists,\n setup=\"Transform setup with self\",\n decode=\"From `Pipeline\",\n show=\"From `Pipeline\",\n overlapping_splits=\"All splits that are in more than one split\",\n subset=\"New `TfmdLists` with same tfms that only includes items in `i`th split\",\n infer_idx=\"Finds the index where `self.tfms` can be applied to `x`, depending on the type of `x`\",\n infer=\"Apply `self.tfms` to `x` starting at the right tfm depending on the type of `x`\",\n new_empty=\"A new version of `self` but with no items\")", "_____no_output_____" ], [ "#exports\ndef decode_at(o, idx):\n \"Decoded item at `idx`\"\n return o.decode(o[idx])", "_____no_output_____" ], [ "#exports\ndef show_at(o, idx, **kwargs):\n \"Show item at `idx`\",\n return o.show(o[idx], **kwargs)", "_____no_output_____" ] ], [ [ "A `TfmdLists` combines a collection of object with a `Pipeline`. `tfms` can either be a `Pipeline` or a list of transforms, in which case, it will wrap them in a `Pipeline`. `use_list` is passed along to `L` with the `items` and `split_idx` are passed to each transform of the `Pipeline`. `do_setup` indicates if the `Pipeline.setup` method should be called during initialization.", "_____no_output_____" ] ], [ [ "class _IntFloatTfm(Transform):\n def encodes(self, o): return TitledInt(o)\n def decodes(self, o): return TitledFloat(o)\nint2f_tfm=_IntFloatTfm()\n\ndef _neg(o): return -o\nneg_tfm = Transform(_neg, _neg)", "_____no_output_____" ], [ "items = L([1.,2.,3.]); tfms = [neg_tfm, int2f_tfm]\ntl = TfmdLists(items, tfms=tfms)\ntest_eq_type(tl[0], TitledInt(-1))\ntest_eq_type(tl[1], TitledInt(-2))\ntest_eq_type(tl.decode(tl[2]), TitledFloat(3.))\ntest_stdout(lambda: show_at(tl, 2), '-3')\ntest_eq(tl.types, [float, float, TitledInt])\ntl", "_____no_output_____" ], [ "# add splits to TfmdLists\nsplits = [[0,2],[1]]\ntl = TfmdLists(items, tfms=tfms, splits=splits)\ntest_eq(tl.n_subsets, 2)\ntest_eq(tl.train, tl.subset(0))\ntest_eq(tl.valid, tl.subset(1))\ntest_eq(tl.train.items, items[splits[0]])\ntest_eq(tl.valid.items, items[splits[1]])\ntest_eq(tl.train.tfms.split_idx, 0)\ntest_eq(tl.valid.tfms.split_idx, 1)\ntest_eq(tl.train.new_empty().split_idx, 0)\ntest_eq(tl.valid.new_empty().split_idx, 1)\ntest_eq_type(tl.splits, L(splits))\nassert not tl.overlapping_splits()", "_____no_output_____" ], [ "df = pd.DataFrame(dict(a=[1,2,3],b=[2,3,4]))\ntl = TfmdLists(df, lambda o: o.a+1, splits=[[0],[1,2]])\ntest_eq(tl[1,2], [3,4])\ntr = tl.subset(0)\ntest_eq(tr[:], [2])\nval = tl.subset(1)\ntest_eq(val[:], [3,4])", "_____no_output_____" ], [ "class _B(Transform):\n def __init__(self): self.m = 0\n def encodes(self, o): return o+self.m\n def decodes(self, o): return o-self.m\n def setups(self, items): \n print(items)\n self.m = tensor(items).float().mean().item()\n\n# test for setup, which updates `self.m`\ntl = TfmdLists(items, _B())\ntest_eq(tl.m, 2)", "TfmdLists: [1.0, 2.0, 3.0]\ntfms - (#0) []\n" ] ], [ [ "Here's how we can use `TfmdLists.setup` to implement a simple category list, getting labels from a mock file list:", "_____no_output_____" ] ], [ [ "class _Cat(Transform):\n order = 1\n def encodes(self, o): return int(self.o2i[o])\n def decodes(self, o): return TitledStr(self.vocab[o])\n def setups(self, items): self.vocab,self.o2i = uniqueify(L(items), sort=True, bidir=True)\ntcat = _Cat()\n\ndef _lbl(o): return TitledStr(o.split('_')[0])\n\n# Check that tfms are sorted by `order` & `_lbl` is called first\nfns = ['dog_0.jpg','cat_0.jpg','cat_2.jpg','cat_1.jpg','dog_1.jpg']\ntl = TfmdLists(fns, [tcat,_lbl])\nexp_voc = ['cat','dog']\ntest_eq(tcat.vocab, exp_voc)\ntest_eq(tl.tfms.vocab, exp_voc)\ntest_eq(tl.vocab, exp_voc)\ntest_eq(tl, (1,0,0,0,1))\ntest_eq([tl.decode(o) for o in tl], ('dog','cat','cat','cat','dog'))", "_____no_output_____" ], [ "#Check only the training set is taken into account for setup\ntl = TfmdLists(fns, [tcat,_lbl], splits=[[0,4], [1,2,3]])\ntest_eq(tcat.vocab, ['dog'])", "_____no_output_____" ], [ "tfm = NegTfm(split_idx=1)\ntds = TfmdLists(start, A())\ntdl = TfmdDL(tds, after_batch=tfm, bs=4)\nx = tdl.one_batch()\ntest_eq(x, torch.arange(4))\ntds.split_idx = 1\nx = tdl.one_batch()\ntest_eq(x, -torch.arange(4))\ntds.split_idx = 0\nx = tdl.one_batch()\ntest_eq(x, torch.arange(4))", "_____no_output_____" ], [ "tds = TfmdLists(start, A())\ntdl = TfmdDL(tds, after_batch=NegTfm(), bs=4)\ntest_eq(tdl.dataset[0], start[0])\ntest_eq(len(tdl), (len(tds)-1)//4+1)\ntest_eq(tdl.bs, 4)\ntest_stdout(tdl.show_batch, '0\\n1\\n2\\n3')", "_____no_output_____" ], [ "show_doc(TfmdLists.subset)", "_____no_output_____" ], [ "show_doc(TfmdLists.infer_idx)", "_____no_output_____" ], [ "show_doc(TfmdLists.infer)", "_____no_output_____" ], [ "def mult(x): return x*2\nmult.order = 2\n\nfns = ['dog_0.jpg','cat_0.jpg','cat_2.jpg','cat_1.jpg','dog_1.jpg']\ntl = TfmdLists(fns, [_lbl,_Cat(),mult])", "_____no_output_____" ], [ "test_eq(tl.infer_idx('dog_45.jpg'), 0)\ntest_eq(tl.infer('dog_45.jpg'), 2)\n\ntest_eq(tl.infer_idx(4), 2)\ntest_eq(tl.infer(4), 8)\n\ntest_fail(lambda: tl.infer_idx(2.0))\ntest_fail(lambda: tl.infer(2.0))", "_____no_output_____" ], [ "#hide\n#Test input_types works on a Transform\ncat = _Cat()\ncat.input_types = (str, float)\ntl = TfmdLists(fns, [_lbl,cat,mult])\ntest_eq(tl.infer_idx(2.0), 1)", "_____no_output_____" ], [ "#hide\n#Test type annotations work on a function\ndef mult(x:(int,float)): return x*2\nmult.order = 2\ntl = TfmdLists(fns, [_lbl,_Cat(),mult])\ntest_eq(tl.infer_idx(2.0), 2)", "_____no_output_____" ] ], [ [ "## Datasets -", "_____no_output_____" ] ], [ [ "#export\n@docs\n@delegates(TfmdLists)\nclass Datasets(FilteredBase):\n \"A dataset that creates a tuple from each `tfms`, passed thru `item_tfms`\"\n def __init__(self, items=None, tfms=None, tls=None, n_inp=None, dl_type=None, **kwargs):\n super().__init__(dl_type=dl_type)\n self.tls = L(tls if tls else [TfmdLists(items, t, **kwargs) for t in L(ifnone(tfms,[None]))])\n self.n_inp = ifnone(n_inp, max(1, len(self.tls)-1))\n\n def __getitem__(self, it):\n res = tuple([tl[it] for tl in self.tls])\n return res if is_indexer(it) else list(zip(*res))\n\n def __getattr__(self,k): return gather_attrs(self, k, 'tls')\n def __dir__(self): return super().__dir__() + gather_attr_names(self, 'tls')\n def __len__(self): return len(self.tls[0])\n def __iter__(self): return (self[i] for i in range(len(self)))\n def __repr__(self): return coll_repr(self)\n def decode(self, o, full=True): return tuple(tl.decode(o_, full=full) for o_,tl in zip(o,tuplify(self.tls, match=o)))\n def subset(self, i): return type(self)(tls=L(tl.subset(i) for tl in self.tls), n_inp=self.n_inp)\n def _new(self, items, *args, **kwargs): return super()._new(items, tfms=self.tfms, do_setup=False, **kwargs)\n def overlapping_splits(self): return self.tls[0].overlapping_splits()\n def new_empty(self): return type(self)(tls=[tl.new_empty() for tl in self.tls], n_inp=self.n_inp)\n @property\n def splits(self): return self.tls[0].splits\n @property\n def split_idx(self): return self.tls[0].tfms.split_idx\n @property\n def items(self): return self.tls[0].items\n @items.setter\n def items(self, v):\n for tl in self.tls: tl.items = v\n\n def show(self, o, ctx=None, **kwargs):\n for o_,tl in zip(o,self.tls): ctx = tl.show(o_, ctx=ctx, **kwargs)\n return ctx\n\n @contextmanager\n def set_split_idx(self, i):\n old_split_idx = self.split_idx\n for tl in self.tls: tl.tfms.split_idx = i\n try: yield self\n finally:\n for tl in self.tls: tl.tfms.split_idx = old_split_idx\n\n _docs=dict(\n decode=\"Compose `decode` of all `tuple_tfms` then all `tfms` on `i`\",\n show=\"Show item `o` in `ctx`\",\n dataloaders=\"Get a `DataLoaders`\",\n overlapping_splits=\"All splits that are in more than one split\",\n subset=\"New `Datasets` that only includes subset `i`\",\n new_empty=\"Create a new empty version of the `self`, keeping only the transforms\",\n set_split_idx=\"Contextmanager to use the same `Datasets` with another `split_idx`\"\n )", "_____no_output_____" ] ], [ [ "A `Datasets` creates a tuple from `items` (typically input,target) by applying to them each list of `Transform` (or `Pipeline`) in `tfms`. Note that if `tfms` contains only one list of `tfms`, the items given by `Datasets` will be tuples of one element. \n\n`n_inp` is the number of elements in the tuples that should be considered part of the input and will default to 1 if `tfms` consists of one set of transforms, `len(tfms)-1` otherwise. In most cases, the number of elements in the tuples spit out by `Datasets` will be 2 (for input,target) but it can happen that there is 3 (Siamese networks or tabular data) in which case we need to be able to determine when the inputs end and the targets begin.", "_____no_output_____" ] ], [ [ "items = [1,2,3,4]\ndsets = Datasets(items, [[neg_tfm,int2f_tfm], [add(1)]])\nt = dsets[0]\ntest_eq(t, (-1,2))\ntest_eq(dsets[0,1,2], [(-1,2),(-2,3),(-3,4)])\ntest_eq(dsets.n_inp, 1)\ndsets.decode(t)", "_____no_output_____" ], [ "class Norm(Transform):\n def encodes(self, o): return (o-self.m)/self.s\n def decodes(self, o): return (o*self.s)+self.m\n def setups(self, items):\n its = tensor(items).float()\n self.m,self.s = its.mean(),its.std()", "_____no_output_____" ], [ "items = [1,2,3,4]\nnrm = Norm()\ndsets = Datasets(items, [[neg_tfm,int2f_tfm], [neg_tfm,nrm]])\n\nx,y = zip(*dsets)\ntest_close(tensor(y).mean(), 0)\ntest_close(tensor(y).std(), 1)\ntest_eq(x, (-1,-2,-3,-4,))\ntest_eq(nrm.m, -2.5)\ntest_stdout(lambda:show_at(dsets, 1), '-2')\n\ntest_eq(dsets.m, nrm.m)\ntest_eq(dsets.norm.m, nrm.m)\ntest_eq(dsets.train.norm.m, nrm.m)", "_____no_output_____" ], [ "#hide\n#Check filtering is properly applied\nclass B(Transform):\n def encodes(self, x)->None: return int(x+1)\n def decodes(self, x): return TitledInt(x-1)\nadd1 = B(split_idx=1)\n\ndsets = Datasets(items, [neg_tfm, [neg_tfm,int2f_tfm,add1]], splits=[[3],[0,1,2]])\ntest_eq(dsets[1], [-2,-2])\ntest_eq(dsets.valid[1], [-2,-1])\ntest_eq(dsets.valid[[1,1]], [[-2,-1], [-2,-1]])\ntest_eq(dsets.train[0], [-4,-4])", "_____no_output_____" ], [ "test_fns = ['dog_0.jpg','cat_0.jpg','cat_2.jpg','cat_1.jpg','kid_1.jpg']\ntcat = _Cat()\ndsets = Datasets(test_fns, [[tcat,_lbl]], splits=[[0,1,2], [3,4]])\ntest_eq(tcat.vocab, ['cat','dog'])\ntest_eq(dsets.train, [(1,),(0,),(0,)])\ntest_eq(dsets.valid[0], (0,))\ntest_stdout(lambda: show_at(dsets.train, 0), \"dog\")", "_____no_output_____" ], [ "inp = [0,1,2,3,4]\ndsets = Datasets(inp, tfms=[None])\n\ntest_eq(*dsets[2], 2) # Retrieve one item (subset 0 is the default)\ntest_eq(dsets[1,2], [(1,),(2,)]) # Retrieve two items by index\nmask = [True,False,False,True,False]\ntest_eq(dsets[mask], [(0,),(3,)]) # Retrieve two items by mask", "_____no_output_____" ], [ "inp = pd.DataFrame(dict(a=[5,1,2,3,4]))\ndsets = Datasets(inp, tfms=attrgetter('a')).subset(0)\ntest_eq(*dsets[2], 2) # Retrieve one item (subset 0 is the default)\ntest_eq(dsets[1,2], [(1,),(2,)]) # Retrieve two items by index\nmask = [True,False,False,True,False]\ntest_eq(dsets[mask], [(5,),(3,)]) # Retrieve two items by mask", "_____no_output_____" ], [ "#test n_inp\ninp = [0,1,2,3,4]\ndsets = Datasets(inp, tfms=[None])\ntest_eq(dsets.n_inp, 1)\ndsets = Datasets(inp, tfms=[[None],[None],[None]])\ntest_eq(dsets.n_inp, 2)\ndsets = Datasets(inp, tfms=[[None],[None],[None]], n_inp=1)\ntest_eq(dsets.n_inp, 1)", "_____no_output_____" ], [ "# splits can be indices\ndsets = Datasets(range(5), tfms=[None], splits=[tensor([0,2]), [1,3,4]])\n\ntest_eq(dsets.subset(0), [(0,),(2,)])\ntest_eq(dsets.train, [(0,),(2,)]) # Subset 0 is aliased to `train`\ntest_eq(dsets.subset(1), [(1,),(3,),(4,)])\ntest_eq(dsets.valid, [(1,),(3,),(4,)]) # Subset 1 is aliased to `valid`\ntest_eq(*dsets.valid[2], 4)\n#assert '[(1,),(3,),(4,)]' in str(dsets) and '[(0,),(2,)]' in str(dsets)\ndsets", "_____no_output_____" ], [ "# splits can be boolean masks (they don't have to cover all items, but must be disjoint)\nsplits = [[False,True,True,False,True], [True,False,False,False,False]]\ndsets = Datasets(range(5), tfms=[None], splits=splits)\n\ntest_eq(dsets.train, [(1,),(2,),(4,)])\ntest_eq(dsets.valid, [(0,)])", "_____no_output_____" ], [ "# apply transforms to all items\ntfm = [[lambda x: x*2,lambda x: x+1]]\nsplits = [[1,2],[0,3,4]]\ndsets = Datasets(range(5), tfm, splits=splits)\ntest_eq(dsets.train,[(3,),(5,)])\ntest_eq(dsets.valid,[(1,),(7,),(9,)])\ntest_eq(dsets.train[False,True], [(5,)])", "_____no_output_____" ], [ "# only transform subset 1\nclass _Tfm(Transform):\n split_idx=1\n def encodes(self, x): return x*2\n def decodes(self, x): return TitledStr(x//2)", "_____no_output_____" ], [ "dsets = Datasets(range(5), [_Tfm()], splits=[[1,2],[0,3,4]])\ntest_eq(dsets.train,[(1,),(2,)])\ntest_eq(dsets.valid,[(0,),(6,),(8,)])\ntest_eq(dsets.train[False,True], [(2,)])\ndsets", "_____no_output_____" ], [ "#A context manager to change the split_idx and apply the validation transform on the training set\nds = dsets.train\nwith ds.set_split_idx(1):\n test_eq(ds,[(2,),(4,)])\ntest_eq(dsets.train,[(1,),(2,)])", "_____no_output_____" ], [ "#hide\n#Test Datasets pickles\ndsrc1 = pickle.loads(pickle.dumps(dsets))\ntest_eq(dsets.train, dsrc1.train)\ntest_eq(dsets.valid, dsrc1.valid)", "_____no_output_____" ], [ "dsets = Datasets(range(5), [_Tfm(),noop], splits=[[1,2],[0,3,4]])\ntest_eq(dsets.train,[(1,1),(2,2)])\ntest_eq(dsets.valid,[(0,0),(6,3),(8,4)])", "_____no_output_____" ], [ "start = torch.arange(0,50)\ntds = Datasets(start, [A()])\ntdl = TfmdDL(tds, after_item=NegTfm(), bs=4)\nb = tdl.one_batch()\ntest_eq(tdl.decode_batch(b), ((0,),(1,),(2,),(3,)))\ntest_stdout(tdl.show_batch, \"0\\n1\\n2\\n3\")", "_____no_output_____" ], [ "# only transform subset 1\nclass _Tfm(Transform):\n split_idx=1\n def encodes(self, x): return x*2\n\ndsets = Datasets(range(8), [None], splits=[[1,2,5,7],[0,3,4,6]])", "_____no_output_____" ], [ "# only transform subset 1\nclass _Tfm(Transform):\n split_idx=1\n def encodes(self, x): return x*2\n\ndsets = Datasets(range(8), [None], splits=[[1,2,5,7],[0,3,4,6]])\ndls = dsets.dataloaders(bs=4, after_batch=_Tfm(), shuffle_train=False, device=torch.device('cpu'))\ntest_eq(dls.train, [(tensor([1,2,5, 7]),)])\ntest_eq(dls.valid, [(tensor([0,6,8,12]),)])\ntest_eq(dls.n_inp, 1)", "_____no_output_____" ] ], [ [ "### Methods", "_____no_output_____" ] ], [ [ "items = [1,2,3,4]\ndsets = Datasets(items, [[neg_tfm,int2f_tfm]])", "_____no_output_____" ], [ "#hide_input\n_dsrc = Datasets([1,2])\nshow_doc(_dsrc.dataloaders, name=\"Datasets.dataloaders\")", "_____no_output_____" ], [ "show_doc(Datasets.decode)", "_____no_output_____" ], [ "test_eq(*dsets[0], -1)\ntest_eq(*dsets.decode((-1,)), 1)", "_____no_output_____" ], [ "show_doc(Datasets.show)", "_____no_output_____" ], [ "test_stdout(lambda:dsets.show(dsets[1]), '-2')", "_____no_output_____" ], [ "show_doc(Datasets.new_empty)", "_____no_output_____" ], [ "items = [1,2,3,4]\nnrm = Norm()\ndsets = Datasets(items, [[neg_tfm,int2f_tfm], [neg_tfm]])\nempty = dsets.new_empty()\ntest_eq(empty.items, [])", "_____no_output_____" ], [ "#hide\n#test it works for dataframes too\ndf = pd.DataFrame({'a':[1,2,3,4,5], 'b':[6,7,8,9,10]})\ndsets = Datasets(df, [[attrgetter('a')], [attrgetter('b')]])\nempty = dsets.new_empty()", "_____no_output_____" ] ], [ [ "## Add test set for inference", "_____no_output_____" ] ], [ [ "# only transform subset 1\nclass _Tfm1(Transform):\n split_idx=0\n def encodes(self, x): return x*3\n\ndsets = Datasets(range(8), [[_Tfm(),_Tfm1()]], splits=[[1,2,5,7],[0,3,4,6]])\ntest_eq(dsets.train, [(3,),(6,),(15,),(21,)])\ntest_eq(dsets.valid, [(0,),(6,),(8,),(12,)])", "_____no_output_____" ], [ "#export\ndef test_set(dsets, test_items, rm_tfms=None, with_labels=False):\n \"Create a test set from `test_items` using validation transforms of `dsets`\"\n if isinstance(dsets, Datasets):\n tls = dsets.tls if with_labels else dsets.tls[:dsets.n_inp]\n test_tls = [tl._new(test_items, split_idx=1) for tl in tls]\n if rm_tfms is None: rm_tfms = [tl.infer_idx(get_first(test_items)) for tl in test_tls]\n else: rm_tfms = tuplify(rm_tfms, match=test_tls)\n for i,j in enumerate(rm_tfms): test_tls[i].tfms.fs = test_tls[i].tfms.fs[j:]\n return Datasets(tls=test_tls)\n elif isinstance(dsets, TfmdLists):\n test_tl = dsets._new(test_items, split_idx=1)\n if rm_tfms is None: rm_tfms = dsets.infer_idx(get_first(test_items))\n test_tl.tfms.fs = test_tl.tfms.fs[rm_tfms:]\n return test_tl\n else: raise Exception(f\"This method requires using the fastai library to assemble your data. Expected a `Datasets` or a `TfmdLists` but got {dsets.__class__.__name__}\")", "_____no_output_____" ], [ "class _Tfm1(Transform):\n split_idx=0\n def encodes(self, x): return x*3\n\ndsets = Datasets(range(8), [[_Tfm(),_Tfm1()]], splits=[[1,2,5,7],[0,3,4,6]])\ntest_eq(dsets.train, [(3,),(6,),(15,),(21,)])\ntest_eq(dsets.valid, [(0,),(6,),(8,),(12,)])\n\n#Tranform of the validation set are applied\ntst = test_set(dsets, [1,2,3])\ntest_eq(tst, [(2,),(4,),(6,)])", "_____no_output_____" ], [ "#hide\n#Test with different types\ntfm = _Tfm1()\ntfm.split_idx,tfm.order = None,2\ndsets = Datasets(['dog', 'cat', 'cat', 'dog'], [[_Cat(),tfm]])\n\n#With strings\ntest_eq(test_set(dsets, ['dog', 'cat', 'cat']), [(3,), (0,), (0,)])\n#With ints\ntest_eq(test_set(dsets, [1,2]), [(3,), (6,)])", "_____no_output_____" ], [ "#hide\n#Test with various input lengths\ndsets = Datasets(range(8), [[_Tfm(),_Tfm1()],[_Tfm(),_Tfm1()],[_Tfm(),_Tfm1()]], splits=[[1,2,5,7],[0,3,4,6]])\ntst = test_set(dsets, [1,2,3])\ntest_eq(tst, [(2,2),(4,4),(6,6)])\n\ndsets = Datasets(range(8), [[_Tfm(),_Tfm1()],[_Tfm(),_Tfm1()],[_Tfm(),_Tfm1()]], splits=[[1,2,5,7],[0,3,4,6]], n_inp=1)\ntst = test_set(dsets, [1,2,3])\ntest_eq(tst, [(2,),(4,),(6,)])", "_____no_output_____" ], [ "#hide\n#Test with rm_tfms\ndsets = Datasets(range(8), [[_Tfm(),_Tfm()]], splits=[[1,2,5,7],[0,3,4,6]])\ntst = test_set(dsets, [1,2,3])\ntest_eq(tst, [(4,),(8,),(12,)])\n\ndsets = Datasets(range(8), [[_Tfm(),_Tfm()]], splits=[[1,2,5,7],[0,3,4,6]])\ntst = test_set(dsets, [1,2,3], rm_tfms=1)\ntest_eq(tst, [(2,),(4,),(6,)])\n\ndsets = Datasets(range(8), [[_Tfm(),_Tfm()], [_Tfm(),_Tfm()]], splits=[[1,2,5,7],[0,3,4,6]], n_inp=2)\ntst = test_set(dsets, [1,2,3], rm_tfms=(1,0))\ntest_eq(tst, [(2,4),(4,8),(6,12)])", "_____no_output_____" ], [ "#export\n@delegates(TfmdDL.__init__)\n@patch\ndef test_dl(self:DataLoaders, test_items, rm_type_tfms=None, with_labels=False, **kwargs):\n \"Create a test dataloader from `test_items` using validation transforms of `dls`\"\n test_ds = test_set(self.valid_ds, test_items, rm_tfms=rm_type_tfms, with_labels=with_labels\n ) if isinstance(self.valid_ds, (Datasets, TfmdLists)) else test_items\n return self.valid.new(test_ds, **kwargs)", "_____no_output_____" ], [ "dsets = Datasets(range(8), [[_Tfm(),_Tfm1()]], splits=[[1,2,5,7],[0,3,4,6]])\ndls = dsets.dataloaders(bs=4, device=torch.device('cpu'))", "_____no_output_____" ], [ "dsets = Datasets(range(8), [[_Tfm(),_Tfm1()]], splits=[[1,2,5,7],[0,3,4,6]])\ndls = dsets.dataloaders(bs=4, device=torch.device('cpu'))\ntst_dl = dls.test_dl([2,3,4,5])\ntest_eq(tst_dl._n_inp, 1)\ntest_eq(list(tst_dl), [(tensor([ 4, 6, 8, 10]),)])\n#Test you can change transforms\ntst_dl = dls.test_dl([2,3,4,5], after_item=add1)\ntest_eq(list(tst_dl), [(tensor([ 5, 7, 9, 11]),)])", "_____no_output_____" ] ], [ [ "## Export -", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.export import notebook2script\nnotebook2script()", "Converted 00_torch_core.ipynb.\nConverted 01_layers.ipynb.\nConverted 02_data.load.ipynb.\nConverted 03_data.core.ipynb.\nConverted 04_data.external.ipynb.\nConverted 05_data.transforms.ipynb.\nConverted 06_data.block.ipynb.\nConverted 07_vision.core.ipynb.\nConverted 08_vision.data.ipynb.\nConverted 09_vision.augment.ipynb.\nConverted 09b_vision.utils.ipynb.\nConverted 09c_vision.widgets.ipynb.\nConverted 10_tutorial.pets.ipynb.\nConverted 11_vision.models.xresnet.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_callback.core.ipynb.\nConverted 13a_learner.ipynb.\nConverted 13b_metrics.ipynb.\nConverted 14_callback.schedule.ipynb.\nConverted 14a_callback.data.ipynb.\nConverted 15_callback.hook.ipynb.\nConverted 15a_vision.models.unet.ipynb.\nConverted 16_callback.progress.ipynb.\nConverted 17_callback.tracker.ipynb.\nConverted 18_callback.fp16.ipynb.\nConverted 18a_callback.training.ipynb.\nConverted 19_callback.mixup.ipynb.\nConverted 20_interpret.ipynb.\nConverted 20a_distributed.ipynb.\nConverted 21_vision.learner.ipynb.\nConverted 22_tutorial.imagenette.ipynb.\nConverted 23_tutorial.vision.ipynb.\nConverted 24_tutorial.siamese.ipynb.\nConverted 24_vision.gan.ipynb.\nConverted 30_text.core.ipynb.\nConverted 31_text.data.ipynb.\nConverted 32_text.models.awdlstm.ipynb.\nConverted 33_text.models.core.ipynb.\nConverted 34_callback.rnn.ipynb.\nConverted 35_tutorial.wikitext.ipynb.\nConverted 36_text.models.qrnn.ipynb.\nConverted 37_text.learner.ipynb.\nConverted 38_tutorial.text.ipynb.\nConverted 40_tabular.core.ipynb.\nConverted 41_tabular.data.ipynb.\nConverted 42_tabular.model.ipynb.\nConverted 43_tabular.learner.ipynb.\nConverted 44_tutorial.tabular.ipynb.\nConverted 45_collab.ipynb.\nConverted 46_tutorial.collab.ipynb.\nConverted 50_tutorial.datablock.ipynb.\nConverted 60_medical.imaging.ipynb.\nConverted 61_tutorial.medical_imaging.ipynb.\nConverted 65_medical.text.ipynb.\nConverted 70_callback.wandb.ipynb.\nConverted 71_callback.tensorboard.ipynb.\nConverted 72_callback.neptune.ipynb.\nConverted 73_callback.captum.ipynb.\nConverted 74_callback.cutmix.ipynb.\nConverted 97_test_utils.ipynb.\nConverted 99_pytorch_doc.ipynb.\nConverted index.ipynb.\nConverted tutorial.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4af004a20baf750a5191fcf543951c6de70b6613
210,633
ipynb
Jupyter Notebook
Mini-Projects/IMDB Sentiment Analysis - XGBoost (Updating a Model).ipynb
giaminhhoang/MLND-sagemaker-deployment
997172b41e082e76240c316cde4e463b4cdce4b3
[ "MIT" ]
null
null
null
Mini-Projects/IMDB Sentiment Analysis - XGBoost (Updating a Model).ipynb
giaminhhoang/MLND-sagemaker-deployment
997172b41e082e76240c316cde4e463b4cdce4b3
[ "MIT" ]
null
null
null
Mini-Projects/IMDB Sentiment Analysis - XGBoost (Updating a Model).ipynb
giaminhhoang/MLND-sagemaker-deployment
997172b41e082e76240c316cde4e463b4cdce4b3
[ "MIT" ]
null
null
null
60.457233
2,276
0.644324
[ [ [ "# Sentiment Analysis\n\n## Updating a Model in SageMaker\n\n_Deep Learning Nanodegree Program | Deployment_\n\n---\n\nIn this notebook we will consider a situation in which a model that we constructed is no longer working as we intended. In particular, we will look at the XGBoost sentiment analysis model that we constructed earlier. In this case, however, we have some new data that our model doesn't seem to perform very well on. As a result, we will re-train our model and update an existing endpoint so that it uses our new model.\n\nThis notebook starts by re-creating the XGBoost sentiment analysis model that was created in earlier notebooks. This means that you will have already seen the cells up to the end of Step 4. The new content in this notebook begins at Step 5.\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.", "_____no_output_____" ], [ "## Step 1: Downloading the data\n\nThe dataset we are going to use is very popular among researchers in Natural Language Processing, usually referred to as the [IMDb dataset](http://ai.stanford.edu/~amaas/data/sentiment/). It consists of movie reviews from the website [imdb.com](http://www.imdb.com/), each labeled as either '**pos**itive', if the reviewer enjoyed the film, or '**neg**ative' otherwise.\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.\n\nWe begin by using some Jupyter Notebook magic to download and extract the dataset.", "_____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", "_____no_output_____" ] ], [ [ "## Step 2: Preparing the data\n\nThe data we have downloaded is split into various files, each of which contains a single review. It will be much easier going forward if we combine these individual files into two large files, one for training and one for testing.", "_____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" ], [ "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" ], [ "train_X[100]", "_____no_output_____" ] ], [ [ "## Step 3: Processing the data\n\nNow that we have our training and testing datasets merged and ready to use, we need to start processing the raw data into something that will be useable by our machine learning algorithm. To begin with, we remove any html formatting that may appear in the reviews and perform some standard natural language processing in order to homogenize the data.", "_____no_output_____" ] ], [ [ "import nltk\nnltk.download(\"stopwords\")\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\nstemmer = PorterStemmer()", "[nltk_data] Downloading package stopwords to\n[nltk_data] /home/ec2-user/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "import re\nfrom bs4 import BeautifulSoup\n\ndef review_to_words(review):\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_____" ], [ "review_to_words(train_X[100])", "_____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" ] ], [ [ "### Extract Bag-of-Words features\n\nFor the model we will be implementing, rather than using the reviews directly, we are going to transform each review into a Bag-of-Words feature representation. Keep in mind that 'in the wild' we will only have access to the training set so our transformer can only use the training set to construct a representation.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\n# from sklearn.externals import joblib\nimport joblib\n# joblib is an enhanced version of pickle that is more efficient for storing NumPy arrays\n\ndef extract_BoW_features(words_train, words_test, vocabulary_size=5000,\n cache_dir=cache_dir, cache_file=\"bow_features.pkl\"):\n \"\"\"Extract Bag-of-Words for a given set of documents, already preprocessed into words.\"\"\"\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 = joblib.load(f)\n print(\"Read features 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 # Fit a vectorizer to training documents and use it to transform them\n # NOTE: Training documents have already been preprocessed and tokenized into words;\n # pass in dummy functions to skip those steps, e.g. preprocessor=lambda x: x\n vectorizer = CountVectorizer(max_features=vocabulary_size,\n preprocessor=lambda x: x, tokenizer=lambda x: x) # already preprocessed\n features_train = vectorizer.fit_transform(words_train).toarray()\n\n # Apply the same vectorizer to transform the test documents (ignore unknown words)\n features_test = vectorizer.transform(words_test).toarray()\n \n # NOTE: Remember to convert the features using .toarray() for a compact representation\n \n # Write to cache file for future runs (store vocabulary as well)\n if cache_file is not None:\n vocabulary = vectorizer.vocabulary_\n cache_data = dict(features_train=features_train, features_test=features_test,\n vocabulary=vocabulary)\n with open(os.path.join(cache_dir, cache_file), \"wb\") as f:\n joblib.dump(cache_data, f)\n print(\"Wrote features to cache file:\", cache_file)\n else:\n # Unpack data loaded from cache file\n features_train, features_test, vocabulary = (cache_data['features_train'],\n cache_data['features_test'], cache_data['vocabulary'])\n \n # Return both the extracted features as well as the vocabulary\n return features_train, features_test, vocabulary", "_____no_output_____" ], [ "# Extract Bag of Words features for both training and test datasets\ntrain_X, test_X, vocabulary = extract_BoW_features(train_X, test_X)", "Wrote features to cache file: bow_features.pkl\n" ], [ "len(train_X[100])", "_____no_output_____" ] ], [ [ "## Step 4: Classification using XGBoost\n\nNow that we have created the feature representation of our training (and testing) data, it is time to start setting up and using the XGBoost classifier provided by SageMaker.\n\n### Writing the dataset\n\nThe XGBoost classifier that we will be using requires the dataset to be written to a file and stored using Amazon S3. To do this, we will start by splitting the training dataset into two parts, the data we will train the model with and a validation set. Then, we will write those datasets to a file and upload the files to S3. In addition, we will write the test set input to a file and upload the file to S3. This is so that we can use SageMakers Batch Transform functionality to test our model once we've fit it.", "_____no_output_____" ] ], [ [ "import pandas as pd\n\n# Earlier we shuffled the training dataset so to make things simple we can just assign\n# the first 10 000 reviews to the validation set and use the remaining reviews for training.\nval_X = pd.DataFrame(train_X[:10000])\ntrain_X = pd.DataFrame(train_X[10000:])\n\nval_y = pd.DataFrame(train_y[:10000])\ntrain_y = pd.DataFrame(train_y[10000:])", "_____no_output_____" ] ], [ [ "The documentation for the XGBoost algorithm in SageMaker requires that the saved datasets should contain no headers or index and that for the training and validation data, the label should occur first for each sample.\n\nFor more information about this and other algorithms, the SageMaker developer documentation can be found on __[Amazon's website.](https://docs.aws.amazon.com/sagemaker/latest/dg/)__", "_____no_output_____" ] ], [ [ "# First we make sure that the local directory in which we'd like to store the training and validation csv files exists.\ndata_dir = '../data/sentiment_update'\nif not os.path.exists(data_dir):\n os.makedirs(data_dir)", "_____no_output_____" ], [ "pd.DataFrame(test_X).to_csv(os.path.join(data_dir, 'test.csv'), header=False, index=False)\n\npd.concat([val_y, val_X], axis=1).to_csv(os.path.join(data_dir, 'validation.csv'), header=False, index=False)\npd.concat([train_y, train_X], axis=1).to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False)", "_____no_output_____" ], [ "# To save a bit of memory we can set text_X, train_X, val_X, train_y and val_y to None.\n\ntest_X = train_X = val_X = train_y = val_y = None", "_____no_output_____" ] ], [ [ "### Uploading Training / Validation files to S3\n\nAmazon's S3 service allows us to store files that can be access by both the built-in training models such as the XGBoost model we will be using as well as custom models such as the one we will see a little later.\n\nFor this, and most other tasks we will be doing using SageMaker, there are two methods we could use. The first is to use the low level functionality of SageMaker which requires knowing each of the objects involved in the SageMaker environment. The second is to use the high level functionality in which certain choices have been made on the user's behalf. The low level approach benefits from allowing the user a great deal of flexibility while the high level approach makes development much quicker. For our purposes we will opt to use the high level approach although using the low-level approach is certainly an option.\n\nRecall the method `upload_data()` which is a member of object representing our current SageMaker session. What this method does is upload the data to the default bucket (which is created if it does not exist) into the path described by the key_prefix variable. To see this for yourself, once you have uploaded the data files, go to the S3 console and look to see where the files have been uploaded.\n\nFor additional resources, see the __[SageMaker API documentation](http://sagemaker.readthedocs.io/en/latest/)__ and in addition the __[SageMaker Developer Guide.](https://docs.aws.amazon.com/sagemaker/latest/dg/)__", "_____no_output_____" ] ], [ [ "import sagemaker\n\nsession = sagemaker.Session() # Store the current SageMaker session\n\n# S3 prefix (which folder will we use)\nprefix = 'sentiment-update'\n\ntest_location = session.upload_data(os.path.join(data_dir, 'test.csv'), key_prefix=prefix)\nval_location = session.upload_data(os.path.join(data_dir, 'validation.csv'), key_prefix=prefix)\ntrain_location = session.upload_data(os.path.join(data_dir, 'train.csv'), key_prefix=prefix)", "_____no_output_____" ] ], [ [ "### Creating the XGBoost model\n\nNow that the data has been uploaded it is time to create the XGBoost model. To begin with, we need to do some setup. At this point it is worth discussing what a model is in SageMaker. It is easiest to think of a model of comprising three different objects in the SageMaker ecosystem, which interact with one another.\n\n- Model Artifacts\n- Training Code (Container)\n- Inference Code (Container)\n\nThe Model Artifacts are what you might think of as the actual model itself. For example, if you were building a neural network, the model artifacts would be the weights of the various layers. In our case, for an XGBoost model, the artifacts are the actual trees that are created during training.\n\nThe other two objects, the training code and the inference code are then used the manipulate the training artifacts. More precisely, the training code uses the training data that is provided and creates the model artifacts, while the inference code uses the model artifacts to make predictions on new data.\n\nThe way that SageMaker runs the training and inference code is by making use of Docker containers. For now, think of a container as being a way of packaging code up so that dependencies aren't an issue.", "_____no_output_____" ] ], [ [ "from sagemaker import get_execution_role\n\n# Our current execution role is require when creating the model as the training\n# and inference code will need to access the model artifacts.\nrole = get_execution_role()", "_____no_output_____" ], [ "# We need to retrieve the location of the container which is provided by Amazon for using XGBoost.\n# As a matter of convenience, the training and inference code both use the same container.\nfrom sagemaker.amazon.amazon_estimator import get_image_uri\n\ncontainer = get_image_uri(session.boto_region_name, 'xgboost')", "'get_image_uri' method will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.\nThere is a more up to date SageMaker XGBoost image. To use the newer image, please set 'repo_version'='1.0-1'. For example:\n\tget_image_uri(region, 'xgboost', '1.0-1').\n" ], [ "# First we create a SageMaker estimator object for our model.\nxgb = sagemaker.estimator.Estimator(container, # The location of the container we wish to use\n role, # What is our current IAM Role\n train_instance_count=1, # How many compute instances\n train_instance_type='ml.m4.xlarge', # What kind of compute instances\n output_path='s3://{}/{}/output'.format(session.default_bucket(), prefix),\n sagemaker_session=session)\n\n# And then set the algorithm specific parameters.\nxgb.set_hyperparameters(max_depth=5,\n eta=0.2,\n gamma=4,\n min_child_weight=6,\n subsample=0.8,\n silent=0,\n objective='binary:logistic',\n early_stopping_rounds=10,\n num_round=500)", "Parameter image_name will be renamed to image_uri in SageMaker Python SDK v2.\n" ] ], [ [ "### Fit the XGBoost model\n\nNow that our model has been set up we simply need to attach the training and validation datasets and then ask SageMaker to set up the computation.", "_____no_output_____" ] ], [ [ "s3_input_train = sagemaker.s3_input(s3_data=train_location, content_type='csv')\ns3_input_validation = sagemaker.s3_input(s3_data=val_location, content_type='csv')", "'s3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.\n's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.\n" ], [ "xgb.fit({'train': s3_input_train, 'validation': s3_input_validation})", "2020-09-15 22:24:57 Starting - Starting the training job...\n2020-09-15 22:24:58 Starting - Launching requested ML instances......\n2020-09-15 22:26:06 Starting - Preparing the instances for training......\n2020-09-15 22:26:59 Downloading - Downloading input data...\n2020-09-15 22:27:52 Training - Training image download completed. Training in progress..\u001b[34mArguments: train\u001b[0m\n\u001b[34m[2020-09-15:22:27:52:INFO] Running standalone xgboost training.\u001b[0m\n\u001b[34m[2020-09-15:22:27:52:INFO] File size need to be processed in the node: 238.47mb. Available memory size in the node: 8484.52mb\u001b[0m\n\u001b[34m[2020-09-15:22:27:52:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[22:27:52] S3DistributionType set as FullyReplicated\u001b[0m\n\u001b[34m[22:27:54] 15000x5000 matrix with 75000000 entries loaded from /opt/ml/input/data/train?format=csv&label_column=0&delimiter=,\u001b[0m\n\u001b[34m[2020-09-15:22:27:54:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[22:27:54] S3DistributionType set as FullyReplicated\u001b[0m\n\u001b[34m[22:27:55] 10000x5000 matrix with 50000000 entries loaded from /opt/ml/input/data/validation?format=csv&label_column=0&delimiter=,\u001b[0m\n\u001b[34m[22:27:59] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 40 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[0]#011train-error:0.300133#011validation-error:0.2935\u001b[0m\n\u001b[34mMultiple eval metrics have been passed: 'validation-error' will be used for early stopping.\n\u001b[0m\n\u001b[34mWill train until validation-error hasn't improved in 10 rounds.\u001b[0m\n\u001b[34m[22:28:00] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 40 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[1]#011train-error:0.284067#011validation-error:0.2798\u001b[0m\n\u001b[34m[22:28:02] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 44 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[2]#011train-error:0.282267#011validation-error:0.2794\u001b[0m\n\u001b[34m[22:28:03] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[3]#011train-error:0.279267#011validation-error:0.2794\u001b[0m\n\u001b[34m[22:28:04] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 38 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[4]#011train-error:0.2662#011validation-error:0.2658\u001b[0m\n\u001b[34m[22:28:06] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[5]#011train-error:0.259#011validation-error:0.2588\u001b[0m\n\u001b[34m[22:28:07] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 40 extra nodes, 2 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[6]#011train-error:0.2522#011validation-error:0.2501\u001b[0m\n\u001b[34m[22:28:08] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 34 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[7]#011train-error:0.236467#011validation-error:0.2381\u001b[0m\n\u001b[34m[22:28:10] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 30 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[8]#011train-error:0.229933#011validation-error:0.2317\u001b[0m\n\u001b[34m[22:28:11] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 2 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[9]#011train-error:0.2238#011validation-error:0.2265\u001b[0m\n\u001b[34m[22:28:12] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 30 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[10]#011train-error:0.220333#011validation-error:0.2244\u001b[0m\n\u001b[34m[22:28:13] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 34 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[11]#011train-error:0.213667#011validation-error:0.2216\u001b[0m\n\u001b[34m[22:28:15] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 30 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[12]#011train-error:0.210467#011validation-error:0.2202\u001b[0m\n\u001b[34m[22:28:16] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 30 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[13]#011train-error:0.204933#011validation-error:0.2162\u001b[0m\n\u001b[34m[22:28:17] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[14]#011train-error:0.200933#011validation-error:0.212\u001b[0m\n\u001b[34m[22:28:18] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[15]#011train-error:0.1972#011validation-error:0.2099\u001b[0m\n\u001b[34m[22:28:20] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[16]#011train-error:0.194933#011validation-error:0.207\u001b[0m\n\u001b[34m[22:28:21] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 26 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[17]#011train-error:0.192733#011validation-error:0.2048\u001b[0m\n\u001b[34m[22:28:22] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 18 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[18]#011train-error:0.191933#011validation-error:0.2035\u001b[0m\n\u001b[34m[22:28:24] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 34 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[19]#011train-error:0.188#011validation-error:0.1996\u001b[0m\n\u001b[34m[22:28:25] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 40 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[20]#011train-error:0.1844#011validation-error:0.1999\u001b[0m\n\u001b[34m[22:28:26] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[21]#011train-error:0.182533#011validation-error:0.1974\u001b[0m\n\u001b[34m[22:28:27] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[22]#011train-error:0.180667#011validation-error:0.1969\u001b[0m\n\u001b[34m[22:28:29] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 24 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[23]#011train-error:0.179867#011validation-error:0.1926\u001b[0m\n\u001b[34m[22:28:30] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[24]#011train-error:0.178933#011validation-error:0.1918\u001b[0m\n\u001b[34m[22:28:31] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[25]#011train-error:0.177133#011validation-error:0.1894\u001b[0m\n\u001b[34m[22:28:32] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 2 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[26]#011train-error:0.173733#011validation-error:0.1884\u001b[0m\n\u001b[34m[22:28:34] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 38 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[27]#011train-error:0.1718#011validation-error:0.186\u001b[0m\n\u001b[34m[22:28:35] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 18 extra nodes, 14 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[28]#011train-error:0.168933#011validation-error:0.1871\u001b[0m\n\u001b[34m[22:28:36] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 20 extra nodes, 14 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[29]#011train-error:0.1686#011validation-error:0.1872\u001b[0m\n\u001b[34m[22:28:37] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 20 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[30]#011train-error:0.1654#011validation-error:0.1838\u001b[0m\n\u001b[34m[22:28:39] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 0 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[31]#011train-error:0.163867#011validation-error:0.1822\u001b[0m\n\u001b[34m[22:28:40] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[32]#011train-error:0.162533#011validation-error:0.1825\u001b[0m\n\u001b[34m[22:28:41] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 38 extra nodes, 2 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[33]#011train-error:0.161533#011validation-error:0.1816\u001b[0m\n\u001b[34m[22:28:43] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 30 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[34]#011train-error:0.159533#011validation-error:0.1806\u001b[0m\n\u001b[34m[22:28:44] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 16 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[35]#011train-error:0.1586#011validation-error:0.1795\u001b[0m\n\u001b[34m[22:28:45] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[36]#011train-error:0.156933#011validation-error:0.1765\u001b[0m\n\u001b[34m[22:28:46] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 26 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[37]#011train-error:0.157733#011validation-error:0.1748\u001b[0m\n\u001b[34m[22:28:48] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 34 extra nodes, 14 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[38]#011train-error:0.155533#011validation-error:0.1755\u001b[0m\n\u001b[34m[22:28:49] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[39]#011train-error:0.1538#011validation-error:0.1754\u001b[0m\n\u001b[34m[22:28:50] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[40]#011train-error:0.152667#011validation-error:0.1734\u001b[0m\n\u001b[34m[22:28:51] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 20 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[41]#011train-error:0.150467#011validation-error:0.1727\u001b[0m\n\u001b[34m[22:28:53] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 20 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[42]#011train-error:0.1504#011validation-error:0.1713\u001b[0m\n" ] ], [ [ "### Testing the model\n\nNow that we've fit our XGBoost model, it's time to see how well it performs. To do this we will use SageMakers Batch Transform functionality. Batch Transform is a convenient way to perform inference on a large dataset in a way that is not realtime. That is, we don't necessarily need to use our model's results immediately and instead we can peform inference on a large number of samples. An example of this in industry might be peforming an end of month report. This method of inference can also be useful to us as it means to can perform inference on our entire test set. \n\nTo perform a Batch Transformation we need to first create a transformer objects from our trained estimator object.", "_____no_output_____" ] ], [ [ "xgb_transformer = xgb.transformer(instance_count = 1, instance_type = 'ml.m4.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n" ] ], [ [ "Next we actually perform the transform job. When doing so we need to make sure to specify the type of data we are sending so that it is serialized correctly in the background. In our case we are providing our model with csv data so we specify `text/csv`. Also, if the test data that we have provided is too large to process all at once then we need to specify how the data file should be split up. Since each line is a single entry in our data set we tell SageMaker that it can split the input on each line.", "_____no_output_____" ] ], [ [ "xgb_transformer.transform(test_location, content_type='text/csv', split_type='Line')", "_____no_output_____" ] ], [ [ "Currently the transform job is running but it is doing so in the background. Since we wish to wait until the transform job is done and we would like a bit of feedback we can run the `wait()` method.", "_____no_output_____" ] ], [ [ "xgb_transformer.wait()", "............................\u001b[32m2020-09-15T22:43:12.508:[sagemaker logs]: MaxConcurrentTransforms=4, MaxPayloadInMB=6, BatchStrategy=MULTI_RECORD\u001b[0m\n\u001b[34mArguments: serve\u001b[0m\n\u001b[34m[2020-09-15 22:43:12 +0000] [1] [INFO] Starting gunicorn 19.7.1\u001b[0m\n\u001b[34m[2020-09-15 22:43:12 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)\u001b[0m\n\u001b[34m[2020-09-15 22:43:12 +0000] [1] [INFO] Using worker: gevent\u001b[0m\n\u001b[34m[2020-09-15 22:43:12 +0000] [37] [INFO] Booting worker with pid: 37\u001b[0m\n\u001b[34m[2020-09-15 22:43:12 +0000] [38] [INFO] Booting worker with pid: 38\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 37\u001b[0m\n\u001b[34m[2020-09-15 22:43:12 +0000] [39] [INFO] Booting worker with pid: 39\u001b[0m\n\u001b[34m[2020-09-15 22:43:12 +0000] [40] [INFO] Booting worker with pid: 40\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 38\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 39\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 40\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:12:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35mArguments: serve\u001b[0m\n\u001b[35m[2020-09-15 22:43:12 +0000] [1] [INFO] Starting gunicorn 19.7.1\u001b[0m\n\u001b[35m[2020-09-15 22:43:12 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)\u001b[0m\n\u001b[35m[2020-09-15 22:43:12 +0000] [1] [INFO] Using worker: gevent\u001b[0m\n\u001b[35m[2020-09-15 22:43:12 +0000] [37] [INFO] Booting worker with pid: 37\u001b[0m\n\u001b[35m[2020-09-15 22:43:12 +0000] [38] [INFO] Booting worker with pid: 38\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 37\u001b[0m\n\u001b[35m[2020-09-15 22:43:12 +0000] [39] [INFO] Booting worker with pid: 39\u001b[0m\n\u001b[35m[2020-09-15 22:43:12 +0000] [40] [INFO] Booting worker with pid: 40\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 38\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 39\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Model loaded successfully for worker : 40\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:12:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:14:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:14:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:14:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:14:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:21:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:21:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:21:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:21:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:23:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:28:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:30:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:30:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:30:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:30:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:30:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:30:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:30:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:30:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:33:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:35:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:43:35:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:35:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:43:35:INFO] Determined delimiter of CSV input is ','\u001b[0m\n" ] ], [ [ "Now the transform job has executed and the result, the estimated sentiment of each review, has been saved on S3. Since we would rather work on this file locally we can perform a bit of notebook magic to copy the file to the `data_dir`.", "_____no_output_____" ] ], [ [ "!aws s3 cp --recursive $xgb_transformer.output_path $data_dir", "Completed 256.0 KiB/368.9 KiB (3.2 MiB/s) with 1 file(s) remaining\rCompleted 368.9 KiB/368.9 KiB (4.6 MiB/s) with 1 file(s) remaining\rdownload: s3://sagemaker-us-east-2-444100773610/xgboost-2020-09-15-22-38-47-933/test.csv.out to ../data/sentiment_update/test.csv.out\r\n" ] ], [ [ "The last step is now to read in the output from our model, convert the output to something a little more usable, in this case we want the sentiment to be either `1` (positive) or `0` (negative), and then compare to the ground truth labels.", "_____no_output_____" ] ], [ [ "predictions = pd.read_csv(os.path.join(data_dir, 'test.csv.out'), header=None)\npredictions = [round(num) for num in predictions.squeeze().values]", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\naccuracy_score(test_y, predictions)", "_____no_output_____" ] ], [ [ "## Step 5: Looking at New Data\n\nSo now we have an XGBoost sentiment analysis model that we believe is working pretty well. As a result, we deployed it and we are using it in some sort of app.\n\nHowever, as we allow users to use our app we periodically record submitted movie reviews so that we can perform some quality control on our deployed model. Once we've accumulated enough reviews we go through them by hand and evaluate whether they are positive or negative (there are many ways you might do this in practice aside from by hand). The reason for doing this is so that we can check to see how well our model is doing.", "_____no_output_____" ] ], [ [ "import new_data\n\nnew_X, new_Y = new_data.get_new_data()", "_____no_output_____" ] ], [ [ "**NOTE:** Part of the fun in this notebook is trying to figure out what exactly is happening with the new data, so try not to cheat by looking in the `new_data` module. Also, the `new_data` module assumes that the cache created earlier in Step 3 is still stored in `../cache/sentiment_analysis`.", "_____no_output_____" ], [ "### (TODO) Testing the current model\n\nNow that we've loaded the new data, let's check to see how our current XGBoost model performs on it.\n\nFirst, note that the data that has been loaded has already been pre-processed so that each entry in `new_X` is a list of words that have been processed using `nltk`. However, we have not yet constructed the bag of words encoding, which we will do now.\n\nFirst, we use the vocabulary that we constructed earlier using the original training data to construct a `CountVectorizer` which we will use to transform our new data into its bag of words encoding.\n\n**TODO:** Create the CountVectorizer object using the vocabulary created earlier and use it to transform the new data.", "_____no_output_____" ] ], [ [ "# TODO: Create the CountVectorizer using the previously constructed vocabulary\nvectorizer = CountVectorizer(vocabulary = vocabulary, preprocessor=lambda x: x, tokenizer=lambda x: x)\n\n# TODO: Transform our new data set and store the transformed data in the variable new_XV\nnew_XV = vectorizer.transform(new_X).toarray()", "_____no_output_____" ] ], [ [ "As a quick sanity check, we make sure that the length of each of our bag of words encoded reviews is correct. In particular, it must be the same size as the vocabulary which in our case is `5000`.", "_____no_output_____" ] ], [ [ "len(new_XV[100])", "_____no_output_____" ] ], [ [ "Now that we've performed the data processing that is required by our model we can save it locally and then upload it to S3 so that we can construct a batch transform job in order to see how well our model is working.\n\nFirst, we save the data locally.\n\n**TODO:** Save the new data (after it has been transformed using the original vocabulary) to the local notebook instance.", "_____no_output_____" ] ], [ [ "# TODO: Save the data contained in new_XV locally in the data_dir with the file name new_data.csv\npd.DataFrame(new_XV).to_csv(os.path.join(data_dir, 'new_data.csv'), header=False, index=False)", "_____no_output_____" ] ], [ [ "Next, we upload the data to S3.\n\n**TODO:** Upload the csv file created above to S3.", "_____no_output_____" ] ], [ [ "# TODO: Upload the new_data.csv file contained in the data_dir folder to S3 and save the resulting\n# URI as new_data_location\n\nnew_data_location = session.upload_data(os.path.join(data_dir, 'new_data.csv'), key_prefix=prefix)", "_____no_output_____" ] ], [ [ "Then, once the new data has been uploaded to S3, we create and run the batch transform job to get our model's predictions about the sentiment of the new movie reviews.\n\n**TODO:** Using the `xgb_transformer` object that was created earlier (at the end of Step 4 to test the XGBoost model), transform the data located at `new_data_location`.", "_____no_output_____" ] ], [ [ "# TODO: Using xgb_transformer, transform the new_data_location data. You may wish to **wait** until\n# the batch transform job has finished.\nxgb_transformer.transform(new_data_location, content_type='text/csv', split_type='Line')\nxgb_transformer.wait()", ".............................\u001b[34mArguments: serve\u001b[0m\n\u001b[35mArguments: serve\u001b[0m\n\u001b[34m[2020-09-15 22:51:12 +0000] [1] [INFO] Starting gunicorn 19.7.1\u001b[0m\n\u001b[34m[2020-09-15 22:51:12 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)\u001b[0m\n\u001b[34m[2020-09-15 22:51:12 +0000] [1] [INFO] Using worker: gevent\u001b[0m\n\u001b[34m[2020-09-15 22:51:12 +0000] [37] [INFO] Booting worker with pid: 37\u001b[0m\n\u001b[34m[2020-09-15 22:51:12 +0000] [38] [INFO] Booting worker with pid: 38\u001b[0m\n\u001b[34m[2020-09-15 22:51:12 +0000] [39] [INFO] Booting worker with pid: 39\u001b[0m\n\u001b[34m[2020-09-15:22:51:12:INFO] Model loaded successfully for worker : 37\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Model loaded successfully for worker : 38\u001b[0m\n\u001b[34m[2020-09-15 22:51:13 +0000] [40] [INFO] Booting worker with pid: 40\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Model loaded successfully for worker : 39\u001b[0m\n\u001b[35m[2020-09-15 22:51:12 +0000] [1] [INFO] Starting gunicorn 19.7.1\u001b[0m\n\u001b[35m[2020-09-15 22:51:12 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)\u001b[0m\n\u001b[35m[2020-09-15 22:51:12 +0000] [1] [INFO] Using worker: gevent\u001b[0m\n\u001b[35m[2020-09-15 22:51:12 +0000] [37] [INFO] Booting worker with pid: 37\u001b[0m\n\u001b[35m[2020-09-15 22:51:12 +0000] [38] [INFO] Booting worker with pid: 38\u001b[0m\n\u001b[35m[2020-09-15 22:51:12 +0000] [39] [INFO] Booting worker with pid: 39\u001b[0m\n\u001b[35m[2020-09-15:22:51:12:INFO] Model loaded successfully for worker : 37\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Model loaded successfully for worker : 38\u001b[0m\n\u001b[35m[2020-09-15 22:51:13 +0000] [40] [INFO] Booting worker with pid: 40\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Model loaded successfully for worker : 39\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Model loaded successfully for worker : 40\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Model loaded successfully for worker : 40\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:15:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:15:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:17:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[32m2020-09-15T22:51:13.003:[sagemaker logs]: MaxConcurrentTransforms=4, MaxPayloadInMB=6, BatchStrategy=MULTI_RECORD\u001b[0m\n\u001b[34m[2020-09-15:22:51:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:19:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:19:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:20:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:20:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:21:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:21:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:21:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:21:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:22:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:22:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:24:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:26:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:26:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:27:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:27:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:27:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:27:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:27:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:27:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:27:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:27:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:29:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:31:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:31:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:32:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:32:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:32:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:32:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:32:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:32:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:32:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:32:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:34:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:36:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:36:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:36:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:22:51:36:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:36:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:36:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:36:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:22:51:36:INFO] Determined delimiter of CSV input is ','\u001b[0m\n" ] ], [ [ "As usual, we copy the results of the batch transform job to our local instance.", "_____no_output_____" ] ], [ [ "!aws s3 cp --recursive $xgb_transformer.output_path $data_dir", "Completed 256.0 KiB/369.1 KiB (2.0 MiB/s) with 1 file(s) remaining\rCompleted 369.1 KiB/369.1 KiB (2.9 MiB/s) with 1 file(s) remaining\rdownload: s3://sagemaker-us-east-2-444100773610/xgboost-2020-09-15-22-46-28-174/new_data.csv.out to ../data/sentiment_update/new_data.csv.out\r\n" ] ], [ [ "Read in the results of the batch transform job.", "_____no_output_____" ] ], [ [ "predictions = pd.read_csv(os.path.join(data_dir, 'new_data.csv.out'), header=None)\npredictions = [round(num) for num in predictions.squeeze().values]", "_____no_output_____" ] ], [ [ "And check the accuracy of our current model.", "_____no_output_____" ] ], [ [ "accuracy_score(new_Y, predictions)", "_____no_output_____" ] ], [ [ "So it would appear that *something* has changed since our model is no longer (as) effective at determining the sentiment of a user provided review.\n\nIn a real life scenario you would check a number of different things to see what exactly is going on. In our case, we are only going to check one and that is whether some aspect of the underlying distribution has changed. In other words, we want to see if the words that appear in our new collection of reviews matches the words that appear in the original training set. Of course, we want to narrow our scope a little bit so we will only look at the `5000` most frequently appearing words in each data set, or in other words, the vocabulary generated by each data set.\n\nBefore doing that, however, let's take a look at some of the incorrectly classified reviews in the new data set.\n\nTo start, we will deploy the original XGBoost model. We will then use the deployed model to infer the sentiment of some of the new reviews. This will also serve as a nice excuse to deploy our model so that we can mimic a real life scenario where we have a model that has been deployed and is being used in production.\n\n**TODO:** Deploy the XGBoost model.", "_____no_output_____" ] ], [ [ "# TODO: Deploy the model that was created earlier. Recall that the object name is 'xgb'.\nxgb_predictor = xgb.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\nUsing already existing model: xgboost-2020-09-15-22-24-56-899\n" ] ], [ [ "### Diagnose the problem\n\nNow that we have our deployed \"production\" model, we can send some of our new data to it and filter out some of the incorrectly classified reviews.", "_____no_output_____" ] ], [ [ "from sagemaker.predictor import csv_serializer\n\n# We need to tell the endpoint what format the data we are sending is in so that SageMaker can perform the serialization.\nxgb_predictor.content_type = 'text/csv'\nxgb_predictor.serializer = csv_serializer", "_____no_output_____" ] ], [ [ "It will be useful to look at a few different examples of incorrectly classified reviews so we will start by creating a *generator* which we will use to iterate through some of the new reviews and find ones that are incorrect.\n\n**NOTE:** Understanding what Python generators are isn't really required for this module. The reason we use them here is so that we don't have to iterate through all of the new reviews, searching for incorrectly classified samples.", "_____no_output_____" ] ], [ [ "def get_sample(in_X, in_XV, in_Y):\n for idx, smp in enumerate(in_X):\n res = round(float(xgb_predictor.predict(in_XV[idx])))\n if res != in_Y[idx]:\n yield smp, in_Y[idx]", "_____no_output_____" ], [ "gn = get_sample(new_X, new_XV, new_Y)", "_____no_output_____" ] ], [ [ "At this point, `gn` is the *generator* which generates samples from the new data set which are not classified correctly. To get the *next* sample we simply call the `next` method on our generator.", "_____no_output_____" ] ], [ [ "print(next(gn))", "(['yowsa', 'realli', 'want', 'action', 'check', 'babe', 'bomb', 'non', 'stop', 'thriller', 'veteran', 'star', 'martin', 'sheen', 'lead', 'trio', 'supermodel', 'mission', 'stop', 'nuclear', 'terror', 'director', 'dean', 'hamilton', 'let', 'heavi', 'plotlin', 'get', 'way', 'massiv', 'dose', 'teensi', 'swimsuit', 'scene', 'jiggli', 'beach', 'jog', 'hubba', 'hubba', 'hot', 'tub', 'like', 'want', 'action', 'get', 'pearl', 'harbor', 'want', 'babe', 'get', 'eye', 'everi', 'two', 'minut', 'want', 'go', 'buy', 'video', 'yowsa', 'yowsa', 'yowsa', 'mighti', 'spici', 'meatbal'], 1)\n" ] ], [ [ "After looking at a few examples, maybe we decide to look at the most frequently appearing `5000` words in each data set, the original training data set and the new data set. The reason for looking at this might be that we expect the frequency of use of different words to have changed, maybe there is some new slang that has been introduced or some other artifact of popular culture that has changed the way that people write movie reviews.\n\nTo do this, we start by fitting a `CountVectorizer` to the new data.", "_____no_output_____" ] ], [ [ "new_vectorizer = CountVectorizer(max_features=5000,\n preprocessor=lambda x: x, tokenizer=lambda x: x)\nnew_vectorizer.fit(new_X)", "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:484: UserWarning: The parameter 'token_pattern' will not be used since 'tokenizer' is not None'\n warnings.warn(\"The parameter 'token_pattern' will not be used\"\n" ] ], [ [ "Now that we have this new `CountVectorizor` object, we can check to see if the corresponding vocabulary has changed between the two data sets.", "_____no_output_____" ] ], [ [ "original_vocabulary = set(vocabulary.keys())\nnew_vocabulary = set(new_vectorizer.vocabulary_.keys())", "_____no_output_____" ] ], [ [ "We can look at the words that were in the original vocabulary but not in the new vocabulary.", "_____no_output_____" ] ], [ [ "print(original_vocabulary - new_vocabulary)", "{'profil', 'rapidli', 'ghetto', 'spill', 'playboy', 'growth', 'turtl', 'bach', 'assort'}\n" ] ], [ [ "And similarly, we can look at the words that are in the new vocabulary but which were not in the original vocabulary.", "_____no_output_____" ] ], [ [ "print(new_vocabulary - original_vocabulary)", "{'dubiou', 'evan', 'substanti', 'bravo', 'ingrid', 'drone', 'banana', 'scariest', 'incorrect'}\n" ] ], [ [ "These words themselves don't tell us much, however if one of these words occured with a large frequency, that might tell us something. In particular, we wouldn't really expect any of the words above to appear with too much frequency.\n\n**Question** What exactly is going on here. Not only what (if any) words appear with a larger than expected frequency but also, what does this mean? What has changed about the world that our original model no longer takes into account?\n\n**NOTE:** This is meant to be a very open ended question. To investigate you may need more cells than the one provided below. Also, there isn't really a *correct* answer, this is meant to be an opportunity to explore the data.", "_____no_output_____" ], [ "### (TODO) Build a new model\n\nSupposing that we believe something has changed about the underlying distribution of the words that our reviews are made up of, we need to create a new model. This way our new model will take into account whatever it is that has changed.\n\nTo begin with, we will use the new vocabulary to create a bag of words encoding of the new data. We will then use this data to train a new XGBoost model.\n\n**NOTE:** Because we believe that the underlying distribution of words has changed it should follow that the original vocabulary that we used to construct a bag of words encoding of the reviews is no longer valid. This means that we need to be careful with our data. If we send an bag of words encoded review using the *original* vocabulary we should not expect any sort of meaningful results.\n\nIn particular, this means that if we had deployed our XGBoost model like we did in the Web App notebook then we would need to implement this vocabulary change in the Lambda function as well.", "_____no_output_____" ] ], [ [ "new_XV = new_vectorizer.transform(new_X).toarray()", "_____no_output_____" ] ], [ [ "And a quick check to make sure that the newly encoded reviews have the correct length, which should be the size of the new vocabulary which we created.", "_____no_output_____" ] ], [ [ "len(new_XV[0])", "_____no_output_____" ] ], [ [ "Now that we have our newly encoded, newly collected data, we can split it up into a training and validation set so that we can train a new XGBoost model. As usual, we first split up the data, then save it locally and then upload it to S3.", "_____no_output_____" ] ], [ [ "import pandas as pd\n\n# Earlier we shuffled the training dataset so to make things simple we can just assign\n# the first 10 000 reviews to the validation set and use the remaining reviews for training.\nnew_val_X = pd.DataFrame(new_XV[:10000])\nnew_train_X = pd.DataFrame(new_XV[10000:])\n\nnew_val_y = pd.DataFrame(new_Y[:10000])\nnew_train_y = pd.DataFrame(new_Y[10000:])", "_____no_output_____" ] ], [ [ "In order to save some memory we will effectively delete the `new_X` variable. Remember that this contained a list of reviews and each review was a list of words. Note that once this cell has been executed you will need to read the new data in again if you want to work with it.", "_____no_output_____" ] ], [ [ "new_X = None", "_____no_output_____" ] ], [ [ "Next we save the new training and validation sets locally. Note that we overwrite the training and validation sets used earlier. This is mostly because the amount of space that we have available on our notebook instance is limited. Of course, you can increase this if you'd like but to do so may increase the cost of running the notebook instance.", "_____no_output_____" ] ], [ [ "pd.DataFrame(new_XV).to_csv(os.path.join(data_dir, 'new_data.csv'), header=False, index=False)\n\npd.concat([new_val_y, new_val_X], axis=1).to_csv(os.path.join(data_dir, 'new_validation.csv'), header=False, index=False)\npd.concat([new_train_y, new_train_X], axis=1).to_csv(os.path.join(data_dir, 'new_train.csv'), header=False, index=False)", "_____no_output_____" ] ], [ [ "Now that we've saved our data to the local instance, we can safely delete the variables to save on memory.", "_____no_output_____" ] ], [ [ "new_val_y = new_val_X = new_train_y = new_train_X = new_XV = None", "_____no_output_____" ] ], [ [ "Lastly, we make sure to upload the new training and validation sets to S3.\n\n**TODO:** Upload the new data as well as the new training and validation data sets to S3.", "_____no_output_____" ] ], [ [ "# TODO: Upload the new data and the new validation.csv and train.csv files in the data_dir directory to S3.\nnew_data_location = session.upload_data(os.path.join(data_dir, 'new_data.csv'), key_prefix=prefix)\nnew_val_location = session.upload_data(os.path.join(data_dir, 'new_validation.csv'), key_prefix=prefix)\nnew_train_location = session.upload_data(os.path.join(data_dir, 'new_train.csv'), key_prefix=prefix)", "_____no_output_____" ] ], [ [ "Once our new training data has been uploaded to S3, we can create a new XGBoost model that will take into account the changes that have occured in our data set.\n\n**TODO:** Create a new XGBoost estimator object.", "_____no_output_____" ] ], [ [ "# TODO: First, create a SageMaker estimator object for our model.\nnew_xgb = sagemaker.estimator.Estimator(container, # The image name of the training container\n role, # The IAM role to use (our current role in this case)\n train_instance_count=1, # The number of instances to use for training\n train_instance_type='ml.m4.xlarge', # The type of instance to use for training\n output_path='s3://{}/{}/output'.format(session.default_bucket(), prefix),\n # Where to save the output (the model artifacts)\n sagemaker_session=session) # The current SageMaker session\n\n# TODO: Then set the algorithm specific parameters. You may wish to use the same parameters that were\n# used when training the original model.\nnew_xgb.set_hyperparameters(max_depth=5,\n eta=0.2,\n gamma=4,\n min_child_weight=6,\n subsample=0.8,\n objective='binary:logistic',\n early_stopping_rounds=10,\n num_round=200)", "Parameter image_name will be renamed to image_uri in SageMaker Python SDK v2.\n" ] ], [ [ "Once the model has been created, we can train it with our new data.\n\n**TODO:** Train the new XGBoost model.", "_____no_output_____" ] ], [ [ "# TODO: First, make sure that you create s3 input objects so that SageMaker knows where to\n# find the training and validation data.\ns3_new_input_train = sagemaker.s3_input(s3_data=new_train_location, content_type='csv')\ns3_new_input_validation = sagemaker.s3_input(s3_data=new_val_location, content_type='csv')", "'s3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.\n's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.\n" ], [ "# TODO: Using the new validation and training data, 'fit' your new model.\nnew_xgb.fit({'train': s3_new_input_train, 'validation': s3_new_input_validation})", "2020-09-15 23:07:49 Starting - Starting the training job...\n2020-09-15 23:07:50 Starting - Launching requested ML instances......\n2020-09-15 23:09:14 Starting - Preparing the instances for training.........\n2020-09-15 23:10:31 Downloading - Downloading input data...\n2020-09-15 23:11:05 Training - Downloading the training image..\u001b[34mArguments: train\u001b[0m\n\u001b[34m[2020-09-15:23:11:25:INFO] Running standalone xgboost training.\u001b[0m\n\u001b[34m[2020-09-15:23:11:25:INFO] File size need to be processed in the node: 238.47mb. Available memory size in the node: 8485.76mb\u001b[0m\n\u001b[34m[2020-09-15:23:11:25:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[23:11:25] S3DistributionType set as FullyReplicated\u001b[0m\n\u001b[34m[23:11:27] 15000x5000 matrix with 75000000 entries loaded from /opt/ml/input/data/train?format=csv&label_column=0&delimiter=,\u001b[0m\n\u001b[34m[2020-09-15:23:11:27:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[23:11:27] S3DistributionType set as FullyReplicated\u001b[0m\n\u001b[34m[23:11:29] 10000x5000 matrix with 50000000 entries loaded from /opt/ml/input/data/validation?format=csv&label_column=0&delimiter=,\u001b[0m\n\u001b[34m[23:11:32] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 44 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[0]#011train-error:0.314#011validation-error:0.3096\u001b[0m\n\u001b[34mMultiple eval metrics have been passed: 'validation-error' will be used for early stopping.\n\u001b[0m\n\u001b[34mWill train until validation-error hasn't improved in 10 rounds.\u001b[0m\n\u001b[34m[23:11:34] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 48 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[1]#011train-error:0.3008#011validation-error:0.2957\u001b[0m\n\u001b[34m[23:11:35] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 36 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[2]#011train-error:0.287667#011validation-error:0.2815\u001b[0m\n\u001b[34m[23:11:37] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 40 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[3]#011train-error:0.285067#011validation-error:0.2818\u001b[0m\n\n2020-09-15 23:11:25 Training - Training image download completed. Training in progress.\u001b[34m[23:11:38] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 38 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[4]#011train-error:0.276667#011validation-error:0.2732\u001b[0m\n\u001b[34m[23:11:39] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 38 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[5]#011train-error:0.258533#011validation-error:0.26\u001b[0m\n\u001b[34m[23:11:40] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 48 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[6]#011train-error:0.253867#011validation-error:0.2558\u001b[0m\n\u001b[34m[23:11:42] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 36 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[7]#011train-error:0.248867#011validation-error:0.2522\u001b[0m\n\u001b[34m[23:11:43] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 42 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[8]#011train-error:0.243867#011validation-error:0.248\u001b[0m\n\u001b[34m[23:11:44] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 44 extra nodes, 2 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[9]#011train-error:0.238333#011validation-error:0.2407\u001b[0m\n\u001b[34m[23:11:45] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 34 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[10]#011train-error:0.229933#011validation-error:0.2373\u001b[0m\n\u001b[34m[23:11:47] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 38 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[11]#011train-error:0.226867#011validation-error:0.2317\u001b[0m\n\u001b[34m[23:11:48] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 40 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[12]#011train-error:0.224533#011validation-error:0.2295\u001b[0m\n\u001b[34m[23:11:49] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 38 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[13]#011train-error:0.219667#011validation-error:0.2271\u001b[0m\n\u001b[34m[23:11:50] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 26 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[14]#011train-error:0.2152#011validation-error:0.2206\u001b[0m\n\u001b[34m[23:11:52] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 26 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[15]#011train-error:0.213667#011validation-error:0.2207\u001b[0m\n\u001b[34m[23:11:53] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 36 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[16]#011train-error:0.2106#011validation-error:0.22\u001b[0m\n\u001b[34m[23:11:54] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[17]#011train-error:0.205867#011validation-error:0.2175\u001b[0m\n\u001b[34m[23:11:55] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 42 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[18]#011train-error:0.204133#011validation-error:0.2145\u001b[0m\n\u001b[34m[23:11:57] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 4 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[19]#011train-error:0.201667#011validation-error:0.2114\u001b[0m\n\u001b[34m[23:11:58] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 42 extra nodes, 2 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[20]#011train-error:0.200467#011validation-error:0.2089\u001b[0m\n\u001b[34m[23:11:59] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 36 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[21]#011train-error:0.197#011validation-error:0.209\u001b[0m\n\u001b[34m[23:12:01] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[22]#011train-error:0.195467#011validation-error:0.2075\u001b[0m\n\u001b[34m[23:12:02] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 34 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[23]#011train-error:0.1922#011validation-error:0.2066\u001b[0m\n\u001b[34m[23:12:03] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[24]#011train-error:0.1904#011validation-error:0.2045\u001b[0m\n\u001b[34m[23:12:04] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 32 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[25]#011train-error:0.188333#011validation-error:0.2016\u001b[0m\n\u001b[34m[23:12:06] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[26]#011train-error:0.186467#011validation-error:0.2008\u001b[0m\n\u001b[34m[23:12:07] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 24 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[27]#011train-error:0.184667#011validation-error:0.1997\u001b[0m\n\u001b[34m[23:12:08] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 24 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[28]#011train-error:0.1812#011validation-error:0.1968\u001b[0m\n\u001b[34m[23:12:09] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[29]#011train-error:0.181267#011validation-error:0.1964\u001b[0m\n\u001b[34m[23:12:11] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 30 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[30]#011train-error:0.180333#011validation-error:0.1975\u001b[0m\n\u001b[34m[23:12:12] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[31]#011train-error:0.178333#011validation-error:0.1977\u001b[0m\n\u001b[34m[23:12:13] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 36 extra nodes, 10 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[32]#011train-error:0.177667#011validation-error:0.1954\u001b[0m\n\u001b[34m[23:12:15] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 34 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[33]#011train-error:0.175667#011validation-error:0.1948\u001b[0m\n\u001b[34m[23:12:16] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 28 extra nodes, 14 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[34]#011train-error:0.174333#011validation-error:0.1935\u001b[0m\n\u001b[34m[23:12:17] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 20 extra nodes, 8 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[35]#011train-error:0.174467#011validation-error:0.192\u001b[0m\n\u001b[34m[23:12:18] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 24 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[36]#011train-error:0.172933#011validation-error:0.1921\u001b[0m\n\u001b[34m[23:12:20] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 6 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[37]#011train-error:0.1716#011validation-error:0.1901\u001b[0m\n\u001b[34m[23:12:21] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 20 extra nodes, 12 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[38]#011train-error:0.169667#011validation-error:0.1902\u001b[0m\n\u001b[34m[23:12:22] src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 20 extra nodes, 16 pruned nodes, max_depth=5\u001b[0m\n\u001b[34m[39]#011train-error:0.1692#011validation-error:0.1888\u001b[0m\n" ] ], [ [ "### (TODO) Check the new model\n\nSo now we have a new XGBoost model that we believe more accurately represents the state of the world at this time, at least in how it relates to the sentiment analysis problem that we are working on. The next step is to double check that our model is performing reasonably.\n\nTo do this, we will first test our model on the new data.\n\n**Note:** In practice this is a pretty bad idea. We already trained our model on the new data, so testing it shouldn't really tell us much. In fact, this is sort of a textbook example of leakage. We are only doing it here so that we have a numerical baseline.\n\n**Question:** How might you address the leakage problem?", "_____no_output_____" ], [ "First, we create a new transformer based on our new XGBoost model.\n\n**TODO:** Create a transformer object from the newly created XGBoost model.", "_____no_output_____" ] ], [ [ "# TODO: Create a transformer object from the new_xgb model\nnew_xgb_transformer = new_xgb.transformer(instance_count = 1, instance_type = 'ml.m4.xlarge')", "Parameter image will be renamed to image_uri in SageMaker Python SDK v2.\n" ] ], [ [ "Next we test our model on the new data.\n\n**TODO:** Use the transformer object to transform the new data (stored in the `new_data_location` variable)", "_____no_output_____" ] ], [ [ "# TODO: Using new_xgb_transformer, transform the new_data_location data. You may wish to\n# 'wait' for the transform job to finish.\nnew_xgb_transformer.transform(new_data_location, content_type='text/csv', split_type='Line')\nnew_xgb_transformer.wait()", ".............................\u001b[34mArguments: serve\u001b[0m\n\u001b[34m[2020-09-15 23:20:53 +0000] [1] [INFO] Starting gunicorn 19.7.1\u001b[0m\n\u001b[34m[2020-09-15 23:20:53 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)\u001b[0m\n\u001b[34m[2020-09-15 23:20:53 +0000] [1] [INFO] Using worker: gevent\u001b[0m\n\u001b[34m[2020-09-15 23:20:53 +0000] [36] [INFO] Booting worker with pid: 36\u001b[0m\n\u001b[34m[2020-09-15 23:20:53 +0000] [37] [INFO] Booting worker with pid: 37\u001b[0m\n\u001b[34m[2020-09-15:23:20:53:INFO] Model loaded successfully for worker : 36\u001b[0m\n\u001b[34m[2020-09-15 23:20:53 +0000] [38] [INFO] Booting worker with pid: 38\u001b[0m\n\u001b[34m[2020-09-15:23:20:53:INFO] Model loaded successfully for worker : 37\u001b[0m\n\u001b[34m[2020-09-15 23:20:53 +0000] [39] [INFO] Booting worker with pid: 39\u001b[0m\n\u001b[34m[2020-09-15:23:20:53:INFO] Model loaded successfully for worker : 38\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Model loaded successfully for worker : 39\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:54:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:56:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:56:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:56:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:56:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:56:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:56:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:57:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:57:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[32m2020-09-15T23:20:53.806:[sagemaker logs]: MaxConcurrentTransforms=4, MaxPayloadInMB=6, BatchStrategy=MULTI_RECORD\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:20:59:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:01:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:01:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:01:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:01:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:01:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:01:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:01:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:01:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:02:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:02:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:01:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:01:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:01:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:01:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:02:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:02:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:04:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:06:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:11:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:14:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:14:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:14:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:14:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:13:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:13:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:14:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:14:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:14:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:14:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:21:16:INFO] Determined delimiter of CSV input is ','\u001b[0m\n" ] ], [ [ "Copy the results to our local instance.", "_____no_output_____" ] ], [ [ "!aws s3 cp --recursive $new_xgb_transformer.output_path $data_dir", "Completed 256.0 KiB/366.5 KiB (3.7 MiB/s) with 1 file(s) remaining\rCompleted 366.5 KiB/366.5 KiB (5.1 MiB/s) with 1 file(s) remaining\rdownload: s3://sagemaker-us-east-2-444100773610/xgboost-2020-09-15-23-16-11-742/new_data.csv.out to ../data/sentiment_update/new_data.csv.out\r\n" ] ], [ [ "And see how well the model did.", "_____no_output_____" ] ], [ [ "predictions = pd.read_csv(os.path.join(data_dir, 'new_data.csv.out'), header=None)\npredictions = [round(num) for num in predictions.squeeze().values]", "_____no_output_____" ], [ "accuracy_score(new_Y, predictions)", "_____no_output_____" ] ], [ [ "As expected, since we trained the model on this data, our model performs pretty well. So, we have reason to believe that our new XGBoost model is a \"better\" model.\n\nHowever, before we start changing our deployed model, we should first make sure that our new model isn't too different. In other words, if our new model performed really poorly on the original test data then this might be an indication that something else has gone wrong.\n\nTo start with, since we got rid of the variable that stored the original test reviews, we will read them in again from the cache that we created in Step 3. Note that we need to make sure that we read in the original test data after it has been pre-processed with `nltk` but before it has been bag of words encoded. This is because we need to use the new vocabulary instead of the original one.", "_____no_output_____" ] ], [ [ "cache_data = None\nwith open(os.path.join(cache_dir, \"preprocessed_data.pkl\"), \"rb\") as f:\n cache_data = pickle.load(f)\n print(\"Read preprocessed data from cache file:\", \"preprocessed_data.pkl\")\n \ntest_X = cache_data['words_test']\ntest_Y = cache_data['labels_test']\n\n# Here we set cache_data to None so that it doesn't occupy memory\ncache_data = None", "Read preprocessed data from cache file: preprocessed_data.pkl\n" ] ], [ [ "Once we've loaded the original test reviews, we need to create a bag of words encoding of them using the new vocabulary that we created, based on the new data.\n\n**TODO:** Transform the original test data using the new vocabulary.", "_____no_output_____" ] ], [ [ "# TODO: Use the new_vectorizer object that you created earlier to transform the test_X data.\ntest_X = new_vectorizer.transform(test_X).toarray()", "_____no_output_____" ] ], [ [ "Now that we have correctly encoded the original test data, we can write it to the local instance, upload it to S3 and test it.", "_____no_output_____" ] ], [ [ "pd.DataFrame(test_X).to_csv(os.path.join(data_dir, 'test.csv'), header=False, index=False)", "_____no_output_____" ], [ "test_location = session.upload_data(os.path.join(data_dir, 'test.csv'), key_prefix=prefix)", "_____no_output_____" ], [ "new_xgb_transformer.transform(test_location, content_type='text/csv', split_type='Line')\nnew_xgb_transformer.wait()", ".............................\u001b[32m2020-09-15T23:28:42.812:[sagemaker logs]: MaxConcurrentTransforms=4, MaxPayloadInMB=6, BatchStrategy=MULTI_RECORD\u001b[0m\n\u001b[34mArguments: serve\u001b[0m\n\u001b[34m[2020-09-15 23:28:42 +0000] [1] [INFO] Starting gunicorn 19.7.1\u001b[0m\n\u001b[34m[2020-09-15 23:28:42 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)\u001b[0m\n\u001b[34m[2020-09-15 23:28:42 +0000] [1] [INFO] Using worker: gevent\u001b[0m\n\u001b[34m[2020-09-15 23:28:42 +0000] [36] [INFO] Booting worker with pid: 36\u001b[0m\n\u001b[34m[2020-09-15:23:28:42:INFO] Model loaded successfully for worker : 36\u001b[0m\n\u001b[34m[2020-09-15 23:28:42 +0000] [37] [INFO] Booting worker with pid: 37\u001b[0m\n\u001b[34m[2020-09-15 23:28:42 +0000] [38] [INFO] Booting worker with pid: 38\u001b[0m\n\u001b[34m[2020-09-15 23:28:42 +0000] [39] [INFO] Booting worker with pid: 39\u001b[0m\n\u001b[34m[2020-09-15:23:28:42:INFO] Model loaded successfully for worker : 37\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Model loaded successfully for worker : 38\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Model loaded successfully for worker : 39\u001b[0m\n\u001b[35mArguments: serve\u001b[0m\n\u001b[35m[2020-09-15 23:28:42 +0000] [1] [INFO] Starting gunicorn 19.7.1\u001b[0m\n\u001b[35m[2020-09-15 23:28:42 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)\u001b[0m\n\u001b[35m[2020-09-15 23:28:42 +0000] [1] [INFO] Using worker: gevent\u001b[0m\n\u001b[35m[2020-09-15 23:28:42 +0000] [36] [INFO] Booting worker with pid: 36\u001b[0m\n\u001b[35m[2020-09-15:23:28:42:INFO] Model loaded successfully for worker : 36\u001b[0m\n\u001b[35m[2020-09-15 23:28:42 +0000] [37] [INFO] Booting worker with pid: 37\u001b[0m\n\u001b[35m[2020-09-15 23:28:42 +0000] [38] [INFO] Booting worker with pid: 38\u001b[0m\n\u001b[35m[2020-09-15 23:28:42 +0000] [39] [INFO] Booting worker with pid: 39\u001b[0m\n\u001b[35m[2020-09-15:23:28:42:INFO] Model loaded successfully for worker : 37\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Model loaded successfully for worker : 38\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Model loaded successfully for worker : 39\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:45:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:45:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:45:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:45:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:45:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:45:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:43:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:45:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:45:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:45:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:45:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:45:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:45:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:46:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:46:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:46:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:46:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:48:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:51:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:51:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:51:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:51:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:53:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:55:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:57:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:57:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:58:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:58:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:58:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:58:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:57:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:57:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:58:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:58:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:58:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:58:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:58:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[34m[2020-09-15:23:28:58:INFO] Determined delimiter of CSV input is ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:58:INFO] Sniff delimiter as ','\u001b[0m\n\u001b[35m[2020-09-15:23:28:58:INFO] Determined delimiter of CSV input is ','\u001b[0m\n" ], [ "!aws s3 cp --recursive $new_xgb_transformer.output_path $data_dir", "Completed 256.0 KiB/367.0 KiB (2.6 MiB/s) with 1 file(s) remaining\rCompleted 367.0 KiB/367.0 KiB (3.6 MiB/s) with 1 file(s) remaining\rdownload: s3://sagemaker-us-east-2-444100773610/xgboost-2020-09-15-23-24-04-077/test.csv.out to ../data/sentiment_update/test.csv.out\r\n" ], [ "predictions = pd.read_csv(os.path.join(data_dir, 'test.csv.out'), header=None)\npredictions = [round(num) for num in predictions.squeeze().values]", "_____no_output_____" ], [ "accuracy_score(test_Y, predictions)", "_____no_output_____" ] ], [ [ "It would appear that our new XGBoost model is performing quite well on the old test data. This gives us some indication that our new model should be put into production and replace our original model.", "_____no_output_____" ], [ "## Step 6: (TODO) Updating the Model\n\nSo we have a new model that we'd like to use instead of one that is already deployed. Furthermore, we are assuming that the model that is already deployed is being used in some sort of application. As a result, what we want to do is update the existing endpoint so that it uses our new model.\n\nOf course, to do this we need to create an endpoint configuration for our newly created model.\n\nFirst, note that we can access the name of the model that we created above using the `model_name` property of the transformer. The reason for this is that in order for the transformer to create a batch transform job it needs to first create the model object inside of SageMaker. Since we've sort of already done this we should take advantage of it.", "_____no_output_____" ] ], [ [ "new_xgb_transformer.model_name", "_____no_output_____" ] ], [ [ "Next, we create an endpoint configuration using the low level approach of creating the dictionary object which describes the endpoint configuration we want.\n\n**TODO:** Using the low level approach, create a new endpoint configuration. Don't forget that it needs a name and that the name needs to be unique. If you get stuck, try looking at the Boston Housing Low Level Deployment tutorial notebook.", "_____no_output_____" ] ], [ [ "from time import gmtime, strftime\n\n\n# TODO: Give our endpoint configuration a name. Remember, it needs to be unique.\nnew_xgb_endpoint_config_name = \"sentiment-update-xgboost-endpoint-config-\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\n# TODO: Using the SageMaker Client, construct the endpoint configuration.\nnew_xgb_endpoint_config_info = session.sagemaker_client.create_endpoint_config(\n EndpointConfigName = new_xgb_endpoint_config_name,\n ProductionVariants = [{\n \"InstanceType\": \"ml.m4.xlarge\",\n \"InitialVariantWeight\": 1,\n \"InitialInstanceCount\": 1,\n \"ModelName\": new_xgb_transformer.model_name,\n \"VariantName\": \"XGB-Model\"\n }])", "_____no_output_____" ] ], [ [ "Once the endpoint configuration has been constructed, it is a straightforward matter to ask SageMaker to update the existing endpoint so that it uses the new endpoint configuration.\n\nOf note here is that SageMaker does this in such a way that there is no downtime. Essentially, SageMaker deploys the new model and then updates the original endpoint so that it points to the newly deployed model. After that, the original model is shut down. This way, whatever app is using our endpoint won't notice that we've changed the model that is being used.\n\n**TODO:** Use the SageMaker Client to update the endpoint that you deployed earlier.", "_____no_output_____" ] ], [ [ "# TODO: Update the xgb_predictor.endpoint so that it uses new_xgb_endpoint_config_name.\nsession.sagemaker_client.update_endpoint(EndpointName=xgb_predictor.endpoint, EndpointConfigName=new_xgb_endpoint_config_name)", "_____no_output_____" ] ], [ [ "And, as is generally the case with SageMaker requests, this is being done in the background so if we want to wait for it to complete we need to call the appropriate method.", "_____no_output_____" ] ], [ [ "session.wait_for_endpoint(xgb_predictor.endpoint)", "------------!" ] ], [ [ "## Step 7: Delete the Endpoint\n\nOf course, since we are done with the deployed endpoint we need to make sure to shut it down, otherwise we will continue to be charged for it.", "_____no_output_____" ] ], [ [ "xgb_predictor.delete_endpoint()", "_____no_output_____" ] ], [ [ "## Some Additional Questions\n\nThis notebook is a little different from the other notebooks in this module. In part, this is because it is meant to be a little bit closer to the type of problem you may face in a real world scenario. Of course, this problem is a very easy one with a prescribed solution, but there are many other interesting questions that we did not consider here and that you may wish to consider yourself.\n\nFor example,\n- What other ways could the underlying distribution change?\n- Is it a good idea to re-train the model using only the new data?\n- What would change if the quantity of new data wasn't large. Say you only received 500 samples?\n", "_____no_output_____" ], [ "## Optional: Clean up\n\nThe default notebook instance on SageMaker doesn't have a lot of excess disk space available. As you continue to complete and execute notebooks you will eventually fill up this disk space, leading to errors which can be difficult to diagnose. Once you are completely finished using a notebook it is a good idea to remove the files that you created along the way. Of course, you can do this from the terminal or from the notebook hub if you would like. The cell below contains some commands to clean up the created files from within the notebook.", "_____no_output_____" ] ], [ [ "# First we will remove all of the files contained in the data_dir directory\n!rm $data_dir/*\n\n# And then we delete the directory itself\n!rmdir $data_dir\n\n# Similarly we will remove the files in the cache_dir directory and the directory itself\n!rm $cache_dir/*\n!rmdir $cache_dir", "_____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", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "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", "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", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4af012bc81011029554863c20e7d86f1fbe3f134
33,196
ipynb
Jupyter Notebook
advanced_functionality/scikit_bring_your_own_junchi_v2/scikit_bring_your_own.ipynb
junchitan/amazon-sagemaker-examples
3387b805c530c596a652f477cbe99b5aef30ce46
[ "Apache-2.0" ]
null
null
null
advanced_functionality/scikit_bring_your_own_junchi_v2/scikit_bring_your_own.ipynb
junchitan/amazon-sagemaker-examples
3387b805c530c596a652f477cbe99b5aef30ce46
[ "Apache-2.0" ]
null
null
null
advanced_functionality/scikit_bring_your_own_junchi_v2/scikit_bring_your_own.ipynb
junchitan/amazon-sagemaker-examples
3387b805c530c596a652f477cbe99b5aef30ce46
[ "Apache-2.0" ]
null
null
null
51.070769
519
0.669328
[ [ [ "# Building your own algorithm container\n\nWith Amazon SageMaker, you can package your own algorithms that can than be trained and deployed in the SageMaker environment. This notebook will guide you through an example that shows you how to build a Docker container for SageMaker and use it for training and inference.\n\nBy packaging an algorithm in a container, you can bring almost any code to the Amazon SageMaker environment, regardless of programming language, environment, framework, or dependencies. \n\n_**Note:**_ SageMaker now includes a [pre-built scikit container](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/scikit_learn_iris/Scikit-learn%20Estimator%20Example%20With%20Batch%20Transform.ipynb). We recommend the pre-built container be used for almost all cases requiring a scikit algorithm. However, this example remains relevant as an outline for bringing in other libraries to SageMaker as your own container.\n\n1. [Building your own algorithm container](#Building-your-own-algorithm-container)\n 1. [When should I build my own algorithm container?](#When-should-I-build-my-own-algorithm-container%3F)\n 1. [Permissions](#Permissions)\n 1. [The example](#The-example)\n 1. [The presentation](#The-presentation)\n1. [Part 1: Packaging and Uploading your Algorithm for use with Amazon SageMaker](#Part-1%3A-Packaging-and-Uploading-your-Algorithm-for-use-with-Amazon-SageMaker)\n 1. [An overview of Docker](#An-overview-of-Docker)\n 1. [How Amazon SageMaker runs your Docker container](#How-Amazon-SageMaker-runs-your-Docker-container)\n 1. [Running your container during training](#Running-your-container-during-training)\n 1. [The input](#The-input)\n 1. [The output](#The-output)\n 1. [Running your container during hosting](#Running-your-container-during-hosting)\n 1. [The parts of the sample container](#The-parts-of-the-sample-container)\n 1. [The Dockerfile](#The-Dockerfile)\n 1. [Building and registering the container](#Building-and-registering-the-container)\n 1. [Testing your algorithm on your local machine or on an Amazon SageMaker notebook instance](#Testing-your-algorithm-on-your-local-machine-or-on-an-Amazon-SageMaker-notebook-instance)\n1. [Part 2: Using your Algorithm in Amazon SageMaker](#Part-2%3A-Using-your-Algorithm-in-Amazon-SageMaker)\n 1. [Set up the environment](#Set-up-the-environment)\n 1. [Create the session](#Create-the-session)\n 1. [Upload the data for training](#Upload-the-data-for-training)\n 1. [Create an estimator and fit the model](#Create-an-estimator-and-fit-the-model)\n 1. [Hosting your model](#Hosting-your-model)\n 1. [Deploy the model](#Deploy-the-model)\n 2. [Choose some data and use it for a prediction](#Choose-some-data-and-use-it-for-a-prediction)\n 3. [Optional cleanup](#Optional-cleanup)\n 1. [Run Batch Transform Job](#Run-Batch-Transform-Job)\n 1. [Create a Transform Job](#Create-a-Transform-Job)\n 2. [View Output](#View-Output)\n\n_or_ I'm impatient, just [let me see the code](#The-Dockerfile)!\n\n## When should I build my own algorithm container?\n\nYou may not need to create a container to bring your own code to Amazon SageMaker. When you are using a framework (such as Apache MXNet or TensorFlow) that has direct support in SageMaker, you can simply supply the Python code that implements your algorithm using the SDK entry points for that framework. This set of frameworks is continually expanding, so we recommend that you check the current list if your algorithm is written in a common machine learning environment.\n\nEven if there is direct SDK support for your environment or framework, you may find it more effective to build your own container. If the code that implements your algorithm is quite complex on its own or you need special additions to the framework, building your own container may be the right choice.\n\nIf there isn't direct SDK support for your environment, don't worry. You'll see in this walk-through that building your own container is quite straightforward.\n\n## Permissions\n\nRunning this notebook requires permissions in addition to the normal `SageMakerFullAccess` permissions. This is because we'll creating new repositories in Amazon ECR. The easiest way to add these permissions is simply to add the managed policy `AmazonEC2ContainerRegistryFullAccess` to the role that you used to start your notebook instance. There's no need to restart your notebook instance when you do this, the new permissions will be available immediately.\n\n## The example\n\nHere, we'll show how to package a simple Python example which showcases the [decision tree][] algorithm from the widely used [scikit-learn][] machine learning package. The example is purposefully fairly trivial since the point is to show the surrounding structure that you'll want to add to your own code so you can train and host it in Amazon SageMaker.\n\nThe ideas shown here will work in any language or environment. You'll need to choose the right tools for your environment to serve HTTP requests for inference, but good HTTP environments are available in every language these days.\n\nIn this example, we use a single image to support training and hosting. This is easy because it means that we only need to manage one image and we can set it up to do everything. Sometimes you'll want separate images for training and hosting because they have different requirements. Just separate the parts discussed below into separate Dockerfiles and build two images. Choosing whether to have a single image or two images is really a matter of which is more convenient for you to develop and manage.\n\nIf you're only using Amazon SageMaker for training or hosting, but not both, there is no need to build the unused functionality into your container.\n\n[scikit-learn]: http://scikit-learn.org/stable/\n[decision tree]: http://scikit-learn.org/stable/modules/tree.html\n\n## The presentation\n\nThis presentation is divided into two parts: _building_ the container and _using_ the container.", "_____no_output_____" ], [ "# Part 1: Packaging and Uploading your Algorithm for use with Amazon SageMaker\n\n### An overview of Docker\n\nIf you're familiar with Docker already, you can skip ahead to the next section.\n\nFor many data scientists, Docker containers are a new concept, but they are not difficult, as you'll see here. \n\nDocker provides a simple way to package arbitrary code into an _image_ that is totally self-contained. Once you have an image, you can use Docker to run a _container_ based on that image. Running a container is just like running a program on the machine except that the container creates a fully self-contained environment for the program to run. Containers are isolated from each other and from the host environment, so the way you set up your program is the way it runs, no matter where you run it.\n\nDocker is more powerful than environment managers like conda or virtualenv because (a) it is completely language independent and (b) it comprises your whole operating environment, including startup commands, environment variable, etc.\n\nIn some ways, a Docker container is like a virtual machine, but it is much lighter weight. For example, a program running in a container can start in less than a second and many containers can run on the same physical machine or virtual machine instance.\n\nDocker uses a simple file called a `Dockerfile` to specify how the image is assembled. We'll see an example of that below. You can build your Docker images based on Docker images built by yourself or others, which can simplify things quite a bit.\n\nDocker has become very popular in the programming and devops communities for its flexibility and well-defined specification of the code to be run. It is the underpinning of many services built in the past few years, such as [Amazon ECS].\n\nAmazon SageMaker uses Docker to allow users to train and deploy arbitrary algorithms.\n\nIn Amazon SageMaker, Docker containers are invoked in a certain way for training and a slightly different way for hosting. The following sections outline how to build containers for the SageMaker environment.\n\nSome helpful links:\n\n* [Docker home page](http://www.docker.com)\n* [Getting started with Docker](https://docs.docker.com/get-started/)\n* [Dockerfile reference](https://docs.docker.com/engine/reference/builder/)\n* [`docker run` reference](https://docs.docker.com/engine/reference/run/)\n\n[Amazon ECS]: https://aws.amazon.com/ecs/\n\n### How Amazon SageMaker runs your Docker container\n\nBecause you can run the same image in training or hosting, Amazon SageMaker runs your container with the argument `train` or `serve`. How your container processes this argument depends on the container:\n\n* In the example here, we don't define an `ENTRYPOINT` in the Dockerfile so Docker will run the command `train` at training time and `serve` at serving time. In this example, we define these as executable Python scripts, but they could be any program that we want to start in that environment.\n* If you specify a program as an `ENTRYPOINT` in the Dockerfile, that program will be run at startup and its first argument will be `train` or `serve`. The program can then look at that argument and decide what to do.\n* If you are building separate containers for training and hosting (or building only for one or the other), you can define a program as an `ENTRYPOINT` in the Dockerfile and ignore (or verify) the first argument passed in. \n\n#### Running your container during training\n\nWhen Amazon SageMaker runs training, your `train` script is run just like a regular Python program. A number of files are laid out for your use, under the `/opt/ml` directory:\n\n /opt/ml\n |-- input\n | |-- config\n | | |-- hyperparameters.json\n | | `-- resourceConfig.json\n | `-- data\n | `-- <channel_name>\n | `-- <input data>\n |-- model\n | `-- <model files>\n `-- output\n `-- failure\n\n##### The input\n\n* `/opt/ml/input/config` contains information to control how your program runs. `hyperparameters.json` is a JSON-formatted dictionary of hyperparameter names to values. These values will always be strings, so you may need to convert them. `resourceConfig.json` is a JSON-formatted file that describes the network layout used for distributed training. Since scikit-learn doesn't support distributed training, we'll ignore it here.\n* `/opt/ml/input/data/<channel_name>/` (for File mode) contains the input data for that channel. The channels are created based on the call to CreateTrainingJob but it's generally important that channels match what the algorithm expects. The files for each channel will be copied from S3 to this directory, preserving the tree structure indicated by the S3 key structure. \n* `/opt/ml/input/data/<channel_name>_<epoch_number>` (for Pipe mode) is the pipe for a given epoch. Epochs start at zero and go up by one each time you read them. There is no limit to the number of epochs that you can run, but you must close each pipe before reading the next epoch.\n\n##### The output\n\n* `/opt/ml/model/` is the directory where you write the model that your algorithm generates. Your model can be in any format that you want. It can be a single file or a whole directory tree. SageMaker will package any files in this directory into a compressed tar archive file. This file will be available at the S3 location returned in the `DescribeTrainingJob` result.\n* `/opt/ml/output` is a directory where the algorithm can write a file `failure` that describes why the job failed. The contents of this file will be returned in the `FailureReason` field of the `DescribeTrainingJob` result. For jobs that succeed, there is no reason to write this file as it will be ignored.\n\n#### Running your container during hosting\n\nHosting has a very different model than training because hosting is responding to inference requests that come in via HTTP. In this example, we use our recommended Python serving stack to provide robust and scalable serving of inference requests:\n\n![Request serving stack](stack.png)\n\nThis stack is implemented in the sample code here and you can mostly just leave it alone. \n\nAmazon SageMaker uses two URLs in the container:\n\n* `/ping` will receive `GET` requests from the infrastructure. Your program returns 200 if the container is up and accepting requests.\n* `/invocations` is the endpoint that receives client inference `POST` requests. The format of the request and the response is up to the algorithm. If the client supplied `ContentType` and `Accept` headers, these will be passed in as well. \n\nThe container will have the model files in the same place they were written during training:\n\n /opt/ml\n `-- model\n `-- <model files>\n\n", "_____no_output_____" ], [ "### The parts of the sample container\n\nIn the `container` directory are all the components you need to package the sample algorithm for Amazon SageMager:\n\n .\n |-- Dockerfile\n |-- build_and_push.sh\n `-- decision_trees\n |-- nginx.conf\n |-- predictor.py\n |-- serve\n |-- train\n `-- wsgi.py\n\nLet's discuss each of these in turn:\n\n* __`Dockerfile`__ describes how to build your Docker container image. More details below.\n* __`build_and_push.sh`__ is a script that uses the Dockerfile to build your container images and then pushes it to ECR. We'll invoke the commands directly later in this notebook, but you can just copy and run the script for your own algorithms.\n* __`decision_trees`__ is the directory which contains the files that will be installed in the container.\n* __`local_test`__ is a directory that shows how to test your new container on any computer that can run Docker, including an Amazon SageMaker notebook instance. Using this method, you can quickly iterate using small datasets to eliminate any structural bugs before you use the container with Amazon SageMaker. We'll walk through local testing later in this notebook.\n\nIn this simple application, we only install five files in the container. You may only need that many or, if you have many supporting routines, you may wish to install more. These five show the standard structure of our Python containers, although you are free to choose a different toolset and therefore could have a different layout. If you're writing in a different programming language, you'll certainly have a different layout depending on the frameworks and tools you choose.\n\nThe files that we'll put in the container are:\n\n* __`nginx.conf`__ is the configuration file for the nginx front-end. Generally, you should be able to take this file as-is.\n* __`predictor.py`__ is the program that actually implements the Flask web server and the decision tree predictions for this app. You'll want to customize the actual prediction parts to your application. Since this algorithm is simple, we do all the processing here in this file, but you may choose to have separate files for implementing your custom logic.\n* __`serve`__ is the program started when the container is started for hosting. It simply launches the gunicorn server which runs multiple instances of the Flask app defined in `predictor.py`. You should be able to take this file as-is.\n* __`train`__ is the program that is invoked when the container is run for training. You will modify this program to implement your training algorithm.\n* __`wsgi.py`__ is a small wrapper used to invoke the Flask app. You should be able to take this file as-is.\n\nIn summary, the two files you will probably want to change for your application are `train` and `predictor.py`.", "_____no_output_____" ], [ "### The Dockerfile\n\nThe Dockerfile describes the image that we want to build. You can think of it as describing the complete operating system installation of the system that you want to run. A Docker container running is quite a bit lighter than a full operating system, however, because it takes advantage of Linux on the host machine for the basic operations. \n\nFor the Python science stack, we will start from a standard Ubuntu installation and run the normal tools to install the things needed by scikit-learn. Finally, we add the code that implements our specific algorithm to the container and set up the right environment to run under.\n\nAlong the way, we clean up extra space. This makes the container smaller and faster to start.\n\nLet's look at the Dockerfile for the example:", "_____no_output_____" ] ], [ [ "!cat container/Dockerfile", "_____no_output_____" ] ], [ [ "### Building and registering the container\n\nThe following shell code shows how to build the container image using `docker build` and push the container image to ECR using `docker push`. This code is also available as the shell script `container/build-and-push.sh`, which you can run as `build-and-push.sh decision_trees_sample` to build the image `decision_trees_sample`. \n\nThis code looks for an ECR repository in the account you're using and the current default region (if you're using a SageMaker notebook instance, this will be the region where the notebook instance was created). If the repository doesn't exist, the script will create it.", "_____no_output_____" ] ], [ [ "%%sh\n\n# The name of our algorithm\nalgorithm_name=sagemaker-decision-trees\n\ncd container\n\nchmod +x decision_trees/train\nchmod +x decision_trees/serve\n\naccount=$(aws sts get-caller-identity --query Account --output text)\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --repository-names \"${algorithm_name}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n aws ecr create-repository --repository-name \"${algorithm_name}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\naws ecr get-login-password --region ${region}|docker login --username AWS --password-stdin ${fullname}\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build -t ${algorithm_name} .\ndocker tag ${algorithm_name} ${fullname}\n\ndocker push ${fullname}", "_____no_output_____" ] ], [ [ "## Testing your algorithm on your local machine or on an Amazon SageMaker notebook instance\n\nWhile you're first packaging an algorithm use with Amazon SageMaker, you probably want to test it yourself to make sure it's working right. In the directory `container/local_test`, there is a framework for doing this. It includes three shell scripts for running and using the container and a directory structure that mimics the one outlined above.\n\nThe scripts are:\n\n* `train_local.sh`: Run this with the name of the image and it will run training on the local tree. For example, you can run `$ ./train_local.sh sagemaker-decision-trees`. It will generate a model under the `/test_dir/model` directory. You'll want to modify the directory `test_dir/input/data/...` to be set up with the correct channels and data for your algorithm. Also, you'll want to modify the file `input/config/hyperparameters.json` to have the hyperparameter settings that you want to test (as strings).\n* `serve_local.sh`: Run this with the name of the image once you've trained the model and it should serve the model. For example, you can run `$ ./serve_local.sh sagemaker-decision-trees`. It will run and wait for requests. Simply use the keyboard interrupt to stop it.\n* `predict.sh`: Run this with the name of a payload file and (optionally) the HTTP content type you want. The content type will default to `text/csv`. For example, you can run `$ ./predict.sh payload.csv text/csv`.\n\nThe directories as shipped are set up to test the decision trees sample algorithm presented here.", "_____no_output_____" ], [ "# Part 2: Using your Algorithm in Amazon SageMaker\n\nOnce you have your container packaged, you can use it to train models and use the model for hosting or batch transforms. Let's do that with the algorithm we made above.\n\n## Set up the environment\n\nHere we specify a bucket to use and the role that will be used for working with SageMaker.", "_____no_output_____" ] ], [ [ "# S3 prefix\nprefix = \"DEMO-scikit-byo-iris\"\n\n# Define IAM role\nimport boto3\nimport re\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sagemaker import get_execution_role\n\nrole = get_execution_role()", "_____no_output_____" ] ], [ [ "## Create the session\n\nThe session remembers our connection parameters to SageMaker. We'll use it to perform all of our SageMaker operations.", "_____no_output_____" ] ], [ [ "import sagemaker as sage\nfrom time import gmtime, strftime\n\nsess = sage.Session()", "_____no_output_____" ] ], [ [ "## Upload the data for training\n\nWhen training large models with huge amounts of data, you'll typically use big data tools, like Amazon Athena, AWS Glue, or Amazon EMR, to create your data in S3. For the purposes of this example, we're using some the classic [Iris dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set), which we have included. \n\nWe can use use the tools provided by the SageMaker Python SDK to upload the data to a default bucket. ", "_____no_output_____" ] ], [ [ "WORK_DIRECTORY = \"data\"\n\ndata_location = sess.upload_data(WORK_DIRECTORY, key_prefix=prefix)", "_____no_output_____" ] ], [ [ "## Create an estimator and fit the model\n\nIn order to use SageMaker to fit our algorithm, we'll create an `Estimator` that defines how to use the container to train. This includes the configuration we need to invoke SageMaker training:\n\n* The __container name__. This is constructed as in the shell commands above.\n* The __role__. As defined above.\n* The __instance count__ which is the number of machines to use for training.\n* The __instance type__ which is the type of machine to use for training.\n* The __output path__ determines where the model artifact will be written.\n* The __session__ is the SageMaker session object that we defined above.\n\nThen we use fit() on the estimator to train against the data that we uploaded above.", "_____no_output_____" ] ], [ [ "account = sess.boto_session.client(\"sts\").get_caller_identity()[\"Account\"]\nregion = sess.boto_session.region_name\nimage = \"{}.dkr.ecr.{}.amazonaws.com/sagemaker-decision-trees:latest\".format(account, region)\n\ntree = sage.estimator.Estimator(\n image,\n role,\n 1,\n \"ml.c4.2xlarge\",\n output_path=\"s3://{}/output\".format(sess.default_bucket()),\n sagemaker_session=sess,\n)\n\ntree.fit(data_location)", "_____no_output_____" ] ], [ [ "## Hosting your model\nYou can use a trained model to get real time predictions using HTTP endpoint. Follow these steps to walk you through the process.", "_____no_output_____" ], [ "### Deploy the model\n\nDeploying the model to SageMaker hosting just requires a `deploy` call on the fitted model. This call takes an instance count, instance type, and optionally serializer and deserializer functions. These are used when the resulting predictor is created on the endpoint.", "_____no_output_____" ] ], [ [ "from sagemaker.predictor import csv_serializer\n\npredictor = tree.deploy(1, \"ml.m4.xlarge\", serializer=csv_serializer)", "_____no_output_____" ] ], [ [ "### Choose some data and use it for a prediction\n\nIn order to do some predictions, we'll extract some of the data we used for training and do predictions against it. This is, of course, bad statistical practice, but a good way to see how the mechanism works.", "_____no_output_____" ] ], [ [ "shape = pd.read_csv(\"data/iris.csv\", header=None)\nshape.sample(3)", "_____no_output_____" ], [ "# drop the label column in the training set\nshape.drop(shape.columns[[0]], axis=1, inplace=True)\nshape.sample(3)", "_____no_output_____" ], [ "import itertools\n\na = [50 * i for i in range(3)]\nb = [40 + i for i in range(10)]\nindices = [i + j for i, j in itertools.product(a, b)]\n\ntest_data = shape.iloc[indices[:-1]]", "_____no_output_____" ] ], [ [ "Prediction is as easy as calling predict with the predictor we got back from deploy and the data we want to do predictions with. The serializers take care of doing the data conversions for us.", "_____no_output_____" ] ], [ [ "print(predictor.predict(test_data.values).decode(\"utf-8\"))", "_____no_output_____" ] ], [ [ "### Optional cleanup\nWhen you're done with the endpoint, you'll want to clean it up.", "_____no_output_____" ] ], [ [ "sess.delete_endpoint(predictor.endpoint)", "_____no_output_____" ] ], [ [ "## Run Batch Transform Job\nYou can use a trained model to get inference on large data sets by using [Amazon SageMaker Batch Transform](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-batch.html). A batch transform job takes your input data S3 location and outputs the predictions to the specified S3 output folder. Similar to hosting, you can extract inferences for training data to test batch transform.", "_____no_output_____" ], [ "### Create a Transform Job\nWe'll create an `Transformer` that defines how to use the container to get inference results on a data set. This includes the configuration we need to invoke SageMaker batch transform:\n\n* The __instance count__ which is the number of machines to use to extract inferences\n* The __instance type__ which is the type of machine to use to extract inferences\n* The __output path__ determines where the inference results will be written", "_____no_output_____" ] ], [ [ "transform_output_folder = \"batch-transform-output\"\noutput_path = \"s3://{}/{}\".format(sess.default_bucket(), transform_output_folder)\n\ntransformer = tree.transformer(\n instance_count=1,\n instance_type=\"ml.m4.xlarge\",\n output_path=output_path,\n assemble_with=\"Line\",\n accept=\"text/csv\",\n)", "_____no_output_____" ] ], [ [ "We use tranform() on the transfomer to get inference results against the data that we uploaded. You can use these options when invoking the transformer. \n\n* The __data_location__ which is the location of input data\n* The __content_type__ which is the content type set when making HTTP request to container to get prediction\n* The __split_type__ which is the delimiter used for splitting input data \n* The __input_filter__ which indicates the first column (ID) of the input will be dropped before making HTTP request to container", "_____no_output_____" ] ], [ [ "transformer.transform(\n data_location, content_type=\"text/csv\", split_type=\"Line\", input_filter=\"$[1:]\"\n)\ntransformer.wait()", "_____no_output_____" ] ], [ [ "For more information on the configuration options, see [CreateTransformJob API](https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateTransformJob.html)", "_____no_output_____" ], [ "### View Output\nLets read results of above transform job from s3 files and print output", "_____no_output_____" ] ], [ [ "s3_client = sess.boto_session.client(\"s3\")\ns3_client.download_file(\n sess.default_bucket(), \"{}/iris.csv.out\".format(transform_output_folder), \"/tmp/iris.csv.out\"\n)\nwith open(\"/tmp/iris.csv.out\") as f:\n results = f.readlines()\nprint(\"Transform results: \\n{}\".format(\"\".join(results)))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]