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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cbd39c014b33340fdc53b1e44611fdd93865ea40
| 14,767 |
ipynb
|
Jupyter Notebook
|
Actor_CriticPointer_Network-TSP/Critic Network Bello.ipynb
|
GeoffNN/DLforCombin
|
02553a50491420ab0d51860faff4f9d5aee59616
|
[
"MIT"
] | 5 |
2017-12-29T12:16:37.000Z
|
2020-05-24T22:53:56.000Z
|
Actor_CriticPointer_Network-TSP/Critic Network Bello.ipynb
|
GeoffNN/DLforCombin
|
02553a50491420ab0d51860faff4f9d5aee59616
|
[
"MIT"
] | 1 |
2018-01-28T20:09:44.000Z
|
2018-01-28T20:09:44.000Z
|
Actor_CriticPointer_Network-TSP/Critic Network Bello.ipynb
|
GeoffNN/DLforCombin
|
02553a50491420ab0d51860faff4f9d5aee59616
|
[
"MIT"
] | 1 |
2020-05-24T22:53:50.000Z
|
2020-05-24T22:53:50.000Z
| 68.050691 | 1,416 | 0.599783 |
[
[
[
"import tensorflow as tf\nimport numpy as np\nimport tsp_env",
"_____no_output_____"
],
[
"def attention(W_ref, W_q, v, enc_outputs, query):\n with tf.variable_scope(\"attention_mask\"):\n u_i0s = tf.einsum('kl,itl->itk', W_ref, enc_outputs)\n u_i1s = tf.expand_dims(tf.einsum('kl,il->ik', W_q, query), 1)\n u_is = tf.einsum('k,itk->it', v, tf.tanh(u_i0s + u_i1s))\n return tf.einsum('itk,it->ik', enc_outputs, tf.nn.softmax(u_is))",
"_____no_output_____"
],
[
"def critic_network(enc_inputs, \n hidden_size = 128, embedding_size = 128,\n max_time_steps = 5, input_size = 2,\n batch_size = 128,\n initialization_stddev = 0.1,\n n_processing_steps = 5, d = 128):\n # Embed inputs in larger dimensional tensors\n W_embed = tf.Variable(tf.random_normal([embedding_size, input_size],\n stddev=initialization_stddev))\n embedded_inputs = tf.einsum('kl,itl->itk', W_embed, enc_inputs)\n\n # Define encoder\n with tf.variable_scope(\"encoder\"):\n enc_rnn_cell = tf.nn.rnn_cell.LSTMCell(hidden_size)\n enc_outputs, enc_final_state = tf.nn.dynamic_rnn(cell=enc_rnn_cell,\n inputs=embedded_inputs,\n dtype=tf.float32)\n # Define process block\n with tf.variable_scope(\"process_block\"):\n process_cell = tf.nn.rnn_cell.LSTMCell(hidden_size)\n first_process_block_input = tf.tile(tf.Variable(tf.random_normal([1, embedding_size]),\n name='first_process_block_input'), \n [batch_size, 1])\n # Define attention weights\n with tf.variable_scope(\"attention_weights\", reuse=True):\n W_ref = tf.Variable(tf.random_normal([embedding_size, embedding_size],\n stddev=initialization_stddev),\n name='W_ref')\n W_q = tf.Variable(tf.random_normal([embedding_size, embedding_size],\n stddev=initialization_stddev),\n name='W_q')\n v = tf.Variable(tf.random_normal([embedding_size], stddev=initialization_stddev),\n name='v')\n\n # Processing chain\n processing_state = enc_final_state\n processing_input = first_process_block_input\n for t in range(n_processing_steps):\n processing_cell_output, processing_state = process_cell(inputs=processing_input,\n state=processing_state)\n processing_input = attention(W_ref, W_q, v, \n enc_outputs=enc_outputs, query=processing_cell_output)\n\n\n # Apply 2 layers of ReLu for decoding the processed state\n return tf.squeeze(tf.layers.dense(inputs=tf.layers.dense(inputs=processing_cell_output,\n units=d, activation=tf.nn.relu),\n units=1, activation=None))",
"_____no_output_____"
],
[
"batch_size = 128; max_time_steps = 5; input_size = 2\nenc_inputs = tf.placeholder(tf.float32, [batch_size, max_time_steps, input_size])\nbsln_value = critic_network(enc_inputs,\n hidden_size = 128, embedding_size = 128,\n max_time_steps = 5, input_size = 2,\n batch_size = 128,\n initialization_stddev = 0.1,\n n_processing_steps = 5, d = 128)\ntours_rewards_ph = tf.placeholder(tf.float32, [batch_size])\nloss = tf.losses.mean_squared_error(labels=tours_rewards_ph,\n predictions=bsln_value)\ntrain_op = tf.train.AdamOptimizer(1e-2).minimize(loss)",
"_____no_output_____"
],
[
"##############################################################################\n# Trying it out: can we learn the reward of the optimal policy for the TSP5? #\n##############################################################################\ndef generate_batch(n_cities, batch_size):\n inputs_list = []; labels_list = []\n env = tsp_env.TSP_env(n_cities, use_alternative_state=True)\n for i in range(batch_size):\n env.reset()\n s = env.reset()\n coords = s.reshape([4, n_cities])[:2, ].T\n inputs_list.append(coords)\n labels_list.append(env.optimal_solution()[0])\n return np.array(inputs_list), np.array(labels_list)\n# Create tf session and initialize variables\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n# Training loop\nloss_vals = []\nfor i in range(10000):\n inputs_batch, labels_batch = generate_batch(max_time_steps, batch_size)\n loss_val, _ = sess.run([loss, train_op],\n feed_dict={enc_inputs: inputs_batch,\n tours_rewards_ph: labels_batch})\n loss_vals.append(loss_val)\n if i % 50 == 0:\n print(loss_val)",
"4.34178\n0.154837\n0.139899\n0.0980297\n"
],
[
"import matplotlib.pyplot as plt\n%matplotlib inline\nplt.plot(np.log(loss_vals_slow_lr))\nplt.xlabel('Number of iterations')\nplt.ylabel('Log of mean squared error')",
"_____no_output_____"
],
[
"len(loss_vals)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd39d0809f70ea4b789e8ca012b5c1c8d873cef
| 24,013 |
ipynb
|
Jupyter Notebook
|
bin/data_processing/data_scratch.ipynb
|
michaelneuder/image_quality_analysis_v2
|
ff404344d53022f01222f6d3f4e61b5c18fe4366
|
[
"MIT"
] | null | null | null |
bin/data_processing/data_scratch.ipynb
|
michaelneuder/image_quality_analysis_v2
|
ff404344d53022f01222f6d3f4e61b5c18fe4366
|
[
"MIT"
] | null | null | null |
bin/data_processing/data_scratch.ipynb
|
michaelneuder/image_quality_analysis_v2
|
ff404344d53022f01222f6d3f4e61b5c18fe4366
|
[
"MIT"
] | null | null | null | 125.722513 | 20,404 | 0.888061 |
[
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd",
"_____no_output_____"
],
[
"data_path = '/home/michaelneuder/fc_recon_6400/'\norig = np.loadtxt(os.path.join(data_path, 'orig3.txt'))\nrecon = np.loadtxt(os.path.join(data_path, 'recon3.txt'))",
"_____no_output_____"
]
],
[
[
"making sure data isn't corrupted",
"_____no_output_____"
]
],
[
[
"orig.shape, recon.shape",
"_____no_output_____"
],
[
"orig = orig.reshape((3,96,96))\nrecon = recon.reshape((3,96,96))",
"_____no_output_____"
],
[
"plt.imshow(orig[0], cmap='gray')\nplt.show()",
"_____no_output_____"
],
[
"# trimming extra data on recon file\nrecon = np.loadtxt(os.path.join(data_path, 'recon3.txt'))\nrecon.shape",
"_____no_output_____"
],
[
"recon = np.around(recon, decimals=3)",
"_____no_output_____"
],
[
"recon",
"_____no_output_____"
],
[
"recon.shape",
"_____no_output_____"
],
[
"np.savetxt(os.path.join(data_path, 'recon3_shortened.txt'), recon, fmt='%.3f',)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd3a5506a6d12883028e264055e31ee42d82cbb
| 14,068 |
ipynb
|
Jupyter Notebook
|
ChannelVocoder/ChannelVocoder.ipynb
|
prandoni/COM418
|
202264bf05bd1957440182286c94dc952b3dc1bc
|
[
"CC0-1.0"
] | 3 |
2022-02-19T23:36:18.000Z
|
2022-03-08T12:08:46.000Z
|
ChannelVocoder/ChannelVocoder.ipynb
|
prandoni/COM418
|
202264bf05bd1957440182286c94dc952b3dc1bc
|
[
"CC0-1.0"
] | null | null | null |
ChannelVocoder/ChannelVocoder.ipynb
|
prandoni/COM418
|
202264bf05bd1957440182286c94dc952b3dc1bc
|
[
"CC0-1.0"
] | 2 |
2022-03-14T13:38:25.000Z
|
2022-03-18T11:29:05.000Z
| 34.908189 | 631 | 0.616079 |
[
[
[
"<div align=\"right\"><i>COM418 - Computers and Music</i></div>\n<div align=\"right\"><a href=\"https://people.epfl.ch/paolo.prandoni\">Lucie Perrotta</a>, <a href=\"https://www.epfl.ch/labs/lcav/\">LCAV, EPFL</a></div>\n\n<p style=\"font-size: 30pt; font-weight: bold; color: #B51F1F;\">Channel Vocoder</p>",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython.display import Audio\nfrom IPython.display import IFrame\nfrom scipy import signal\n\nimport import_ipynb\nfrom Helpers import * \n\nfigsize=(10,5)\nimport matplotlib\nmatplotlib.rcParams.update({'font.size': 16});",
"_____no_output_____"
],
[
"fs=44100",
"_____no_output_____"
]
],
[
[
"In this notebook, we will implement and test an easy **channel vocoder**. A channel vocoder is a musical device that allows to sing while playing notes on a keyboard at the same time. The vocoder blends the voice (called the modulator) with the played notes on the keyboard (called the carrier) so that the resulting voice sings the note played on the keyboard. The resulting voice has a robotic, artificial sound that is rather popular in electronic music, with notable uses by bands such as Daft Punk, or Kraftwerk.\n\n<img src=\"https://www.bhphotovideo.com/images/images2000x2000/waldorf_stvc_string_synthesizer_1382081.jpg\" alt=\"Drawing\" style=\"width: 35%;\"/>\n\nThe implementation of a Channel vocoder is in fact quite simple. It takes 2 inputs, the carrier and the modulator signals, that must be of the same length. It divides each signal into frequency bands called **channels** (hence the name) using many parallel bandpass filters. The width of each channel can be equal, or logarithmically sized to match the human ear perception of frequency. For each channel, the envelope of the modulator signal is then computed, for instance using a rectifier and a moving average. It is simply multiplied to the carrier signal for each channel, before all channels are added back together.\n\n<img src=\"https://i.imgur.com/aIePutp.png\" alt=\"Drawing\" style=\"width: 65%;\"/>\n\nTo improve the intelligibility of the speech, it is also possible to add AWGN to each to the carrier of each band, helping to produce non-voiced sounds, such as the sound s, or f. ",
"_____no_output_____"
],
[
"As an example signal to test our vocoder with, we are going to use dry voice samples from the song \"Nightcall\" by french artist Kavinsky.\n\n\n\nFirst, let's listen to the original song: ",
"_____no_output_____"
]
],
[
[
"IFrame(src=\"https://www.youtube.com/embed/46qo_V1zcOM?start=30\", width=\"560\", height=\"315\", frameborder=\"0\", allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\")",
"_____no_output_____"
]
],
[
[
"## 1. The modulator and the carrier signals",
"_____no_output_____"
],
[
"\nWe are now going to recreate the lead vocoder using 2 signals: we need a modulator signal, a voice pronouning the lyrics, and a carrier signal, a synthesizer, containing the notes for the pitch.",
"_____no_output_____"
],
[
"### 1.1. The modulator",
"_____no_output_____"
],
[
"Let's first import the modulator signal. It is simply the lyrics spoken at the right rhythm. No need to sing or pay attention to the pitch, only the prononciation and the rhythm of the text are going to matter. Note that the voice sample is available for free on **Splice**, an online resource for audio production.",
"_____no_output_____"
]
],
[
[
"nightcall_modulator = open_audio('snd/nightcall_modulator.wav')\nAudio('snd/nightcall_modulator.wav', autoplay=False)",
"_____no_output_____"
]
],
[
[
"### 1.2. The carrier",
"_____no_output_____"
],
[
"Second, we import a carrier signal, which is simply a synthesizer playing the chords that are gonna be used for the vocoder. Note that the carrier signal does not need to feature silent parts, since the modulator's silences will automatically mute the final vocoded track. The carrier and the modulator simply need to be in synch with each other.",
"_____no_output_____"
]
],
[
[
"nightcall_carrier = open_audio('snd/nightcall_carrier.wav')\nAudio(\"snd/nightcall_carrier.wav\", autoplay=False)",
"_____no_output_____"
]
],
[
[
"## 2. The channel vocoder",
"_____no_output_____"
],
[
"### 2.1. The channeler",
"_____no_output_____"
],
[
"Let's now start implementing the phase vocoder. The first tool we need is an efficient filter to allow decomposing both the carrier and the modulator signals into channels (or bands). Let's call this function the **channeler** since it decomposes the input signals into frequency channels. It takes as input a signal to be filtered, a integer representing the number of bands, and a boolean for setting if we want white noise to be added to each band (used for the carrier).",
"_____no_output_____"
]
],
[
[
"def channeler(x, n_bands, add_noise=False):\n \"\"\"\n Separate a signal into log-sized frequency channels.\n x: the input signal\n n_bands: the number of frequency channels\n add_noise: add white noise or note to each channel\n \"\"\"\n band_freqs = np.logspace(2, 14, n_bands+1, base=2) # get all the limits between the bands, in log space\n \n x_bands = np.zeros((n_bands, x.size)) # Placeholder for all bands\n \n for i in range(n_bands):\n noise = 0.7*np.random.random(x.size) if add_noise else 0 # Create AWGN or not\n x_bands[i] = butter_pass_filter(x + noise, np.array((band_freqs[i], band_freqs[i+1])), fs, btype=\"band\", order=5).astype(np.float32) # Carrier + uniform noise \n\n return x_bands",
"_____no_output_____"
],
[
"# Example plot\nplt.figure(figsize=figsize)\nplt.magnitude_spectrum(nightcall_carrier)\nplt.title(\"Carrier signal before channeling\")\nplt.xscale(\"log\")\nplt.xlim(1e-4)\nplt.show()\n\ncarrier_bands = channeler(nightcall_carrier, 8, add_noise=True)\nplt.figure(figsize=figsize)\nfor i in range(8):\n plt.magnitude_spectrum(carrier_bands[i], alpha=.7)\nplt.title(\"Carrier channels after channeling and noise addition\")\nplt.xscale(\"log\")\nplt.xlim(1e-4)\nplt.show() ",
"_____no_output_____"
]
],
[
[
"### 2.2. The envelope computer",
"_____no_output_____"
],
[
"Next, we can implement a simple envelope computer. Given a signal, this function computes its temporal envelope.",
"_____no_output_____"
]
],
[
[
"def envelope_computer(x):\n \"\"\"\n Envelope computation of one channels of the modulator\n x: the input signal\n \"\"\"\n x = np.abs(x) # Rectify the signal to positive\n x = moving_average(x, 1000) # Smooth the signal\n return 3*x # Normalize # Normalize",
"_____no_output_____"
],
[
"plt.figure(figsize=figsize)\nplt.plot(np.abs(nightcall_modulator)[:150000] , label=\"Modulator\")\nplt.plot(envelope_computer(nightcall_modulator)[:150000], label=\"Modulator envelope\")\nplt.legend(loc=\"best\")\nplt.title(\"Modulator signal and its envelope\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"### 2.3. The channel vocoder (itself)",
"_____no_output_____"
],
[
"We can now implement the channel vocoder itself! It takes as input both signals presented above, as well as an integer controlling the number of channels (bands) of the vocoder. A larger number of channels results in the finer grained vocoded sound, but also takes more time to compute. Some artists may voluntarily use a lower numer of bands to increase the artificial effect of the vocoder. Try playing with it!",
"_____no_output_____"
]
],
[
[
"def channel_vocoder(modulator, carrier, n_bands=32):\n \"\"\"\n Channel vocoder\n modulator: the modulator signal\n carrier: the carrier signal\n n_bands: the number of bands of the vocoder (better to be a power of 2)\n \"\"\"\n # Decompose both modulation and carrier signals into frequency channels\n modul_bands = channeler(modulator, n_bands, add_noise=False)\n carrier_bands = channeler(carrier, n_bands, add_noise=True)\n \n # Compute envelope of the modulator\n modul_bands = np.array([envelope_computer(modul_bands[i]) for i in range(n_bands)])\n\n # Multiply carrier and modulator\n result_bands = np.prod([modul_bands, carrier_bands], axis=0)\n\n # Merge back all channels together and normalize\n result = np.sum(result_bands, axis=0)\n return normalize(result) # Normalize",
"_____no_output_____"
],
[
"nightcall_vocoder = channel_vocoder(nightcall_modulator, nightcall_carrier, n_bands=32)\nAudio(nightcall_vocoder, rate=fs)",
"_____no_output_____"
]
],
[
[
"The vocoded voice is still perfectly intelligible, and it's easy to understand the lyrics. However, the pitch of the voice is now the synthesizer playing chords! One can try to deactivate the AWGN and compare the results. We finally plot the STFT of all 3 signals. One can notice that the vocoded signal has kept the general shape of the voice (modulator) signal, but is using the frequency information from the carrier!",
"_____no_output_____"
]
],
[
[
"# Plot\nf, t, Zxx = signal.stft(nightcall_modulator[:7*fs], fs, nperseg=1000)\nplt.figure(figsize=figsize)\nplt.pcolormesh(t, f[:100], np.abs(Zxx[:100,:]), cmap='nipy_spectral', shading='gouraud')\nplt.title(\"Original voice (modulator)\")\nplt.ylabel('Frequency [Hz]')\nplt.xlabel('Time [sec]')\nplt.show()\n\nf, t, Zxx = signal.stft(nightcall_vocoder[:7*fs], fs, nperseg=1000)\nplt.figure(figsize=figsize)\nplt.pcolormesh(t, f[:100], np.abs(Zxx[:100,:]), cmap='nipy_spectral', shading='gouraud')\nplt.title(\"Vocoded voice\")\nplt.ylabel('Frequency [Hz]')\nplt.xlabel('Time [sec]')\nplt.show()\n\nf, t, Zxx = signal.stft(nightcall_carrier[:7*fs], fs, nperseg=1000)\nplt.figure(figsize=figsize)\nplt.pcolormesh(t, f[:100], np.abs(Zxx[:100,:]), cmap='nipy_spectral', shading='gouraud')\nplt.title(\"Carrier\")\nplt.ylabel('Frequency [Hz]')\nplt.xlabel('Time [sec]')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## 3. Playing it together with the music",
"_____no_output_____"
],
[
"Finally, let's try to play it with the background music to see if it sounds like the original!",
"_____no_output_____"
]
],
[
[
"nightcall_instru = open_audio('snd/nightcall_instrumental.wav')\n\nnightcall_final = nightcall_vocoder + 0.6*nightcall_instru\nnightcall_final = normalize(nightcall_final) # Normalize\n\nAudio(nightcall_final, rate=fs)",
"_____no_output_____"
]
]
] |
[
"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",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
cbd3ae25c6e5d94e2a93e4edf400861bb6a46d72
| 301,509 |
ipynb
|
Jupyter Notebook
|
HW5/2019121004_pca.ipynb
|
avani17101/SMAI-Assignments
|
8d408911f964768bf50d965f881d10d37ac8f7f7
|
[
"MIT"
] | 3 |
2021-03-05T12:28:39.000Z
|
2021-03-05T12:28:44.000Z
|
HW5/2019121004_pca.ipynb
|
avani17101/Statistical-Methods-in-AI
|
8d408911f964768bf50d965f881d10d37ac8f7f7
|
[
"MIT"
] | null | null | null |
HW5/2019121004_pca.ipynb
|
avani17101/Statistical-Methods-in-AI
|
8d408911f964768bf50d965f881d10d37ac8f7f7
|
[
"MIT"
] | 1 |
2021-03-05T12:21:26.000Z
|
2021-03-05T12:21:26.000Z
| 388.542526 | 124,638 | 0.927568 |
[
[
[
"Authored by: Avani Gupta <br>\n Roll: 2019121004",
"_____no_output_____"
],
[
"**Note: dataset shape is version dependent hence final answer too will be dependent of sklearn version installed on machine**",
"_____no_output_____"
],
[
"# Excercise: Eigen Face\n\nHere, we will look into ability of PCA to perform dimensionality reduction on a set of Labeled Faces in the Wild dataset made available from scikit-learn. Our images will be of shape (62, 47). This problem is also famously known as the eigenface problem. Mathematically, we would like to find the principal components (or eigenvectors) of the covariance matrix of the set of face images. These eigenvectors are essentially a set of orthonormal features depicts the amount of variation between face images. When plotted, these eigenvectors are called eigenfaces.",
"_____no_output_____"
],
[
"#### Imports",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import pi\nfrom sklearn.datasets import fetch_lfw_people\nimport seaborn as sns; sns.set()",
"/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n"
],
[
"import sklearn\nprint(sklearn.__version__)",
"0.22.2.post1\n"
]
],
[
[
"#### Setup data",
"_____no_output_____"
]
],
[
[
"faces = fetch_lfw_people(min_faces_per_person=8)\nX = faces.data\ny = faces.target\nprint(faces.target_names)\nprint(faces.images.shape)",
"Downloading LFW metadata: https://ndownloader.figshare.com/files/5976012\nDownloading LFW metadata: https://ndownloader.figshare.com/files/5976009\nDownloading LFW metadata: https://ndownloader.figshare.com/files/5976006\nDownloading LFW data (~200MB): https://ndownloader.figshare.com/files/5976015\n"
]
],
[
[
"Note: **images num is version dependent** <br>\nI get (4822, 62, 47) in my version of sklearn which is 0.22.2. <br>\n\nSince our images is of the shape (62, 47), we unroll each image into a single row vector of shape (1, 4822). This means that we have 4822 features defining each image. These 4822 features will result into 4822 principal components in the PCA projection space. Therefore, each image location contributes more or less to each principal component.",
"_____no_output_____"
],
[
"#### Implement Eigen Faces",
"_____no_output_____"
]
],
[
[
"print(faces.images.shape)",
"(4822, 62, 47)\n"
],
[
"img_shape = faces.images.shape[1:]",
"_____no_output_____"
],
[
"print(img_shape)",
"(62, 47)\n"
],
[
"def FindEigen(X_mat):\n X_mat -= np.mean(X_mat, axis=0, keepdims=True)\n temp = np.matmul(X_mat.T, X_mat)\n cov_mat = 1/X_mat.shape[0]* temp\n eigvals, eigvecs = np.linalg.eig(cov_mat)\n ind = eigvals.argsort()[::-1]\n return np.real(eigvals[ind]), np.real(eigvecs[:, ind])",
"_____no_output_____"
],
[
"def plotFace(faces, h=10, v=1):\n fig, axes = plt.subplots(v, h, figsize=(10, 2.5),\n subplot_kw={'xticks':[], 'yticks':[]},\n gridspec_kw=dict(hspace=0.1, wspace=0.1))\n for i, ax in enumerate(axes.flat):\n ax.imshow(faces[i].reshape(*img_shape), cmap='gray')",
"_____no_output_____"
],
[
"def plotgraph(eigenvals):\n plt.plot(range(1, eigenvals.shape[0]+1), np.cumsum(eigenvals / np.sum(eigenvals)))\n plt.show()",
"_____no_output_____"
],
[
"def PrincipalComponentsNum(X, eigenvals, threshold=0.95):\n num = np.argmax(np.cumsum(eigenvals / np.sum(eigenvals)) >= threshold) + 1\n print(f\"No. of principal components required to preserve {threshold*100} % variance is: {num}.\") ",
"_____no_output_____"
]
],
[
[
"### Q1\n\nHow many principal components are required such that 95% of the vari-\nance in the data is preserved?",
"_____no_output_____"
]
],
[
[
"eigenvals, eigenvecs = FindEigen(X)",
"_____no_output_____"
],
[
"plotgraph(eigenvals)",
"_____no_output_____"
],
[
"PrincipalComponentsNum(X, eigenvals)",
"No. of principal components required to preserve 95.0 % variance is: 178.\n"
]
],
[
[
"### Q2\n\nShow the reconstruction of the first 10 face images using only 100 principal\ncomponents.",
"_____no_output_____"
]
],
[
[
"def reconstructMat(X, eigvecs, num_c):\n return (np.matmul(X,np.matmul(eigvecs[:, :num_c], eigvecs[:, :num_c].T)))",
"_____no_output_____"
],
[
"faceNum = 10\nprint('original faces')\nplotFace(X[:faceNum, :], faceNum)",
"original faces\n"
],
[
"recFace = reconstructMat(X[:faceNum, :], eigenvecs, 100)\nprint('reconstructed faces using only 100 principal components')\nplotFace(recFace, faceNum)",
"reconstructed faces using only 100 principal components\n"
]
],
[
[
"# Adding noise to images\n\nWe now add gaussian noise to the images. Will PCA be able to effectively perform dimensionality reduction? ",
"_____no_output_____"
]
],
[
[
"def plot_noisy_faces(noisy_faces):\n fig, axes = plt.subplots(2, 10, figsize=(10, 2.5),\n subplot_kw={'xticks':[], 'yticks':[]},\n gridspec_kw=dict(hspace=0.1, wspace=0.1))\n for i, ax in enumerate(axes.flat):\n ax.imshow(noisy_faces[i].reshape(62, 47), cmap='binary_r')",
"_____no_output_____"
]
],
[
[
"Below we plot first twenty noisy input face images.",
"_____no_output_____"
]
],
[
[
"np.random.seed(42)\nnoisy_faces = np.random.normal(X, 15)\nplot_noisy_faces(noisy_faces)",
"_____no_output_____"
],
[
"noisy_faces.shape",
"_____no_output_____"
],
[
"noisy_eigenvals, noisy_eigenvecs = FindEigen(noisy_faces)",
"_____no_output_____"
]
],
[
[
"### Q3.1\nShow the above two results for a noisy face dataset.\nHow many principal components are required such that 95% of the vari-\nance in the data is preserved?",
"_____no_output_____"
]
],
[
[
"plotgraph(noisy_eigenvals)",
"_____no_output_____"
],
[
"PrincipalComponentsNum(noisy_faces, noisy_eigenvals, 0.95)",
"No. of principal components required to preserve 95.0 % variance is: 1014.\n"
]
],
[
[
"### Q3.2\n\nShow the reconstruction of the first 10 face images using only 100 principal\ncomponents.",
"_____no_output_____"
]
],
[
[
"faces = 10\nnoisy_recons = reconstructMat(noisy_faces[:faces, :], noisy_eigenvecs, 100)",
"_____no_output_____"
],
[
"print('reconstructed faces for nosiy images only 100 principal components')\nplotFace(noisy_recons, faces)",
"reconstructed faces for nosiy images only 100 principal components\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbd3aff7eb46500bef0d862b46138477e4dc16dd
| 488,514 |
ipynb
|
Jupyter Notebook
|
notebooks/optimize.ipynb
|
sarodz/MLOps
|
59ad8c0cb417a338630e3c037362a00d2940ae80
|
[
"MIT"
] | 189 |
2020-12-27T04:02:59.000Z
|
2021-04-01T18:36:58.000Z
|
notebooks/optimize.ipynb
|
sarodz/MLOps
|
59ad8c0cb417a338630e3c037362a00d2940ae80
|
[
"MIT"
] | 1 |
2021-02-27T15:22:07.000Z
|
2021-03-10T21:53:51.000Z
|
notebooks/optimize.ipynb
|
sarodz/MLOps
|
59ad8c0cb417a338630e3c037362a00d2940ae80
|
[
"MIT"
] | 23 |
2021-01-18T13:54:07.000Z
|
2021-03-30T21:51:26.000Z
| 86.218496 | 1,387 | 0.275392 |
[
[
[
"<div align=\"center\">\n<h1><img width=\"30\" src=\"https://madewithml.com/static/images/rounded_logo.png\"> <a href=\"https://madewithml.com/\">Made With ML</a></h1>\nApplied ML · MLOps · Production\n<br>\nJoin 30K+ developers in learning how to responsibly <a href=\"https://madewithml.com/about/\">deliver value</a> with ML.\n <br>\n</div>\n\n<br>\n\n<div align=\"center\">\n <a target=\"_blank\" href=\"https://newsletter.madewithml.com\"><img src=\"https://img.shields.io/badge/Subscribe-30K-brightgreen\"></a> \n <a target=\"_blank\" href=\"https://github.com/GokuMohandas/MadeWithML\"><img src=\"https://img.shields.io/github/stars/GokuMohandas/MadeWithML.svg?style=social&label=Star\"></a> \n <a target=\"_blank\" href=\"https://www.linkedin.com/in/goku\"><img src=\"https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social\"></a> \n <a target=\"_blank\" href=\"https://twitter.com/GokuMohandas\"><img src=\"https://img.shields.io/twitter/follow/GokuMohandas.svg?label=Follow&style=social\"></a>\n <br>\n 🔥 Among the <a href=\"https://github.com/topics/mlops\" target=\"_blank\">top MLOps</a> repositories on GitHub\n</div>\n\n<br>\n<hr>",
"_____no_output_____"
],
[
"# Optimize (GPU)",
"_____no_output_____"
],
[
"Use this notebooks to run hyperparameter optimization on Google Colab and utilize it's free GPUs.",
"_____no_output_____"
],
[
"## Clone repository",
"_____no_output_____"
]
],
[
[
"# Load repository\n!git clone https://github.com/GokuMohandas/MLOps.git mlops",
"Cloning into 'mlops'...\nremote: Enumerating objects: 597, done.\u001b[K\nremote: Counting objects: 100% (597/597), done.\u001b[K\nremote: Compressing objects: 100% (363/363), done.\u001b[K\nremote: Total 597 (delta 284), reused 491 (delta 185), pack-reused 0\u001b[K\nReceiving objects: 100% (597/597), 3.01 MiB | 17.05 MiB/s, done.\nResolving deltas: 100% (284/284), done.\n"
],
[
"# Files\n% cd mlops\n!ls",
"/content/mlops\napp\t docs\t\tmkdocs.yml\tREADME.md\t streamlit\nconfig\t great_expectations\tmodel\t\trequirements.txt tagifai\ndata\t LICENSE\t\tnotebooks\tsetup.py\t tests\nDockerfile Makefile\t\tpyproject.toml\tstores\n"
]
],
[
[
"## Setup",
"_____no_output_____"
]
],
[
[
"%%bash\n!pip install --upgrade pip\n!python -m pip install -e \".[dev]\" --no-cache-dir",
"_____no_output_____"
]
],
[
[
"# Download data",
"_____no_output_____"
],
[
"We're going to download data directly from GitHub since our blob stores are local. But you can easily load the correct data versions from your cloud blob store using the *.json.dvc pointer files in the [data directory](https://github.com/GokuMohandas/MLOps/tree/main/data).",
"_____no_output_____"
]
],
[
[
"from app import cli",
"_____no_output_____"
],
[
"# Download data\ncli.download_data()",
"[04/09/21 20:19:43] INFO ✅ Data downloaded! cli.py:49\n"
],
[
"# Check if data downloaded\n!ls data",
"projects.json projects.json.dvc tags.json tags.json.dvc\n"
]
],
[
[
"# Compute features",
"_____no_output_____"
]
],
[
[
"# Download data\ncli.compute_features()",
"_____no_output_____"
],
[
"# Computed features\n!ls data",
"_____no_output_____"
]
],
[
[
"## Optimize",
"_____no_output_____"
],
[
"Now we're going to perform hyperparameter optimization using the objective and parameter distributions defined in the [main script](https://github.com/GokuMohandas/MLOps/blob/main/tagifai/main.py). The best parameters will be written to [config/params.json](https://raw.githubusercontent.com/GokuMohandas/MLOps/main/config/params.json) which will be used to train the best model below.",
"_____no_output_____"
]
],
[
[
"# Optimize\ncli.optimize(num_trials=100)",
"\u001b[1;30;43mStreaming output truncated to the last 5000 lines.\u001b[0m\n[01/26/21 18:00:18] INFO Epoch: 8 | train_loss: 0.00160, train.py:146\n val_loss: 0.00169, lr: 4.35E-04, \n _patience: 10 \n[01/26/21 18:00:22] INFO Epoch: 9 | train_loss: 0.00142, train.py:146\n val_loss: 0.00164, lr: 4.35E-04, \n _patience: 10 \n[01/26/21 18:00:26] INFO Epoch: 10 | train_loss: 0.00125, train.py:146\n val_loss: 0.00161, lr: 4.35E-04, \n _patience: 10 \n[01/26/21 18:00:30] INFO Epoch: 11 | train_loss: 0.00104, train.py:146\n val_loss: 0.00159, lr: 4.35E-04, \n _patience: 10 \n[01/26/21 18:00:34] INFO Epoch: 12 | train_loss: 0.00092, train.py:146\n val_loss: 0.00160, lr: 4.35E-04, \n _patience: 9 \n[01/26/21 18:00:37] INFO Epoch: 13 | train_loss: 0.00079, train.py:146\n val_loss: 0.00161, lr: 4.35E-04, \n _patience: 8 \n[01/26/21 18:00:41] INFO Epoch: 14 | train_loss: 0.00071, train.py:146\n val_loss: 0.00162, lr: 4.35E-04, \n _patience: 7 \n[01/26/21 18:00:45] INFO Epoch: 15 | train_loss: 0.00060, train.py:146\n val_loss: 0.00168, lr: 4.35E-04, \n _patience: 6 \n[01/26/21 18:00:49] INFO Epoch: 16 | train_loss: 0.00053, train.py:146\n val_loss: 0.00176, lr: 4.35E-04, \n _patience: 5 \n[01/26/21 18:00:52] INFO Epoch: 17 | train_loss: 0.00047, train.py:146\n val_loss: 0.00173, lr: 2.17E-05, \n _patience: 4 \n[01/26/21 18:00:56] INFO Epoch: 18 | train_loss: 0.00041, train.py:146\n val_loss: 0.00171, lr: 2.17E-05, \n _patience: 3 \n[01/26/21 18:01:00] INFO Epoch: 19 | train_loss: 0.00039, train.py:146\n val_loss: 0.00166, lr: 2.17E-05, \n _patience: 2 \n[01/26/21 18:01:03] INFO Epoch: 20 | train_loss: 0.00038, train.py:146\n val_loss: 0.00165, lr: 2.17E-05, \n _patience: 1 \n[01/26/21 18:01:07] INFO Stopping early! train.py:141\n[01/26/21 18:01:20] INFO { train.py:460\n \"precision\": 0.7962635896268228, \n \"recall\": 0.5412817879074037, \n \"f1\": 0.6134366496710195, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 58: \n INFO { train.py:454\n \"embedding_dim\": 337, \n \"num_filters\": 384, \n \"hidden_dim\": 379, \n \"dropout_p\": 0.5854175653531235, \n \"lr\": 0.00027937932163914 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 337, \n \"num_filters\": 384, \n \"hidden_dim\": 379, \n \"dropout_p\": 0.5854175653531235, \n \"lr\": 0.00027937932163914, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.27794718742370605 \n } \n[01/26/21 18:01:23] INFO Epoch: 1 | train_loss: 0.00637, train.py:146\n val_loss: 0.00498, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:25] INFO Epoch: 2 | train_loss: 0.00502, train.py:146\n val_loss: 0.00311, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:28] INFO Epoch: 3 | train_loss: 0.00366, train.py:146\n val_loss: 0.00254, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:30] INFO Epoch: 4 | train_loss: 0.00316, train.py:146\n val_loss: 0.00240, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:33] INFO Epoch: 5 | train_loss: 0.00277, train.py:146\n val_loss: 0.00232, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:35] INFO Epoch: 6 | train_loss: 0.00250, train.py:146\n val_loss: 0.00211, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:38] INFO Epoch: 7 | train_loss: 0.00229, train.py:146\n val_loss: 0.00197, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:41] INFO Epoch: 8 | train_loss: 0.00205, train.py:146\n val_loss: 0.00185, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:43] INFO Epoch: 9 | train_loss: 0.00180, train.py:146\n val_loss: 0.00175, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:46] INFO Epoch: 10 | train_loss: 0.00166, train.py:146\n val_loss: 0.00168, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:48] INFO Epoch: 11 | train_loss: 0.00156, train.py:146\n val_loss: 0.00163, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:51] INFO Epoch: 12 | train_loss: 0.00142, train.py:146\n val_loss: 0.00159, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:54] INFO Epoch: 13 | train_loss: 0.00125, train.py:146\n val_loss: 0.00157, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:56] INFO Epoch: 14 | train_loss: 0.00116, train.py:146\n val_loss: 0.00157, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:01:59] INFO Epoch: 15 | train_loss: 0.00109, train.py:146\n val_loss: 0.00152, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:02:02] INFO Epoch: 16 | train_loss: 0.00099, train.py:146\n val_loss: 0.00153, lr: 2.79E-04, \n _patience: 9 \n[01/26/21 18:02:05] INFO Epoch: 17 | train_loss: 0.00090, train.py:146\n val_loss: 0.00150, lr: 2.79E-04, \n _patience: 10 \n[01/26/21 18:02:07] INFO Epoch: 18 | train_loss: 0.00083, train.py:146\n val_loss: 0.00155, lr: 2.79E-04, \n _patience: 9 \n[01/26/21 18:02:10] INFO Epoch: 19 | train_loss: 0.00074, train.py:146\n val_loss: 0.00155, lr: 2.79E-04, \n _patience: 8 \n[01/26/21 18:02:12] INFO Epoch: 20 | train_loss: 0.00070, train.py:146\n val_loss: 0.00154, lr: 2.79E-04, \n _patience: 7 \n[01/26/21 18:02:15] INFO Epoch: 21 | train_loss: 0.00063, train.py:146\n val_loss: 0.00153, lr: 2.79E-04, \n _patience: 6 \n[01/26/21 18:02:18] INFO Epoch: 22 | train_loss: 0.00060, train.py:146\n val_loss: 0.00155, lr: 2.79E-04, \n _patience: 5 \n[01/26/21 18:02:20] INFO Epoch: 23 | train_loss: 0.00056, train.py:146\n val_loss: 0.00158, lr: 1.40E-05, \n _patience: 4 \n[01/26/21 18:02:23] INFO Epoch: 24 | train_loss: 0.00050, train.py:146\n val_loss: 0.00157, lr: 1.40E-05, \n _patience: 3 \n[01/26/21 18:02:25] INFO Epoch: 25 | train_loss: 0.00050, train.py:146\n val_loss: 0.00156, lr: 1.40E-05, \n _patience: 2 \n[01/26/21 18:02:28] INFO Epoch: 26 | train_loss: 0.00048, train.py:146\n val_loss: 0.00155, lr: 1.40E-05, \n _patience: 1 \n[01/26/21 18:02:31] INFO Stopping early! train.py:141\n[01/26/21 18:02:39] INFO { train.py:460\n \"precision\": 0.7960190791577995, \n \"recall\": 0.5551390959888497, \n \"f1\": 0.6233643660144468, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 59: \n INFO { train.py:454\n \"embedding_dim\": 367, \n \"num_filters\": 460, \n \"hidden_dim\": 423, \n \"dropout_p\": 0.5740508185886749, \n \"lr\": 0.00020335484420869025 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 367, \n \"num_filters\": 460, \n \"hidden_dim\": 423, \n \"dropout_p\": 0.5740508185886749, \n \"lr\": 0.00020335484420869025, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.23221373558044434 \n } \n[01/26/21 18:02:43] INFO Epoch: 1 | train_loss: 0.00609, train.py:146\n val_loss: 0.00469, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:02:46] INFO Epoch: 2 | train_loss: 0.00496, train.py:146\n val_loss: 0.00330, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:02:49] INFO Epoch: 3 | train_loss: 0.00371, train.py:146\n val_loss: 0.00252, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:02:52] INFO Epoch: 4 | train_loss: 0.00318, train.py:146\n val_loss: 0.00239, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:02:55] INFO Epoch: 5 | train_loss: 0.00282, train.py:146\n val_loss: 0.00230, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:02:59] INFO Epoch: 6 | train_loss: 0.00255, train.py:146\n val_loss: 0.00214, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:02] INFO Epoch: 7 | train_loss: 0.00232, train.py:146\n val_loss: 0.00200, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:05] INFO Epoch: 8 | train_loss: 0.00209, train.py:146\n val_loss: 0.00190, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:09] INFO Epoch: 9 | train_loss: 0.00192, train.py:146\n val_loss: 0.00181, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:12] INFO Epoch: 10 | train_loss: 0.00169, train.py:146\n val_loss: 0.00174, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:15] INFO Epoch: 11 | train_loss: 0.00160, train.py:146\n val_loss: 0.00167, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:19] INFO Epoch: 12 | train_loss: 0.00150, train.py:146\n val_loss: 0.00164, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:22] INFO Epoch: 13 | train_loss: 0.00134, train.py:146\n val_loss: 0.00160, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:25] INFO Epoch: 14 | train_loss: 0.00126, train.py:146\n val_loss: 0.00158, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:29] INFO Epoch: 15 | train_loss: 0.00115, train.py:146\n val_loss: 0.00158, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:32] INFO Epoch: 16 | train_loss: 0.00105, train.py:146\n val_loss: 0.00157, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:35] INFO Epoch: 17 | train_loss: 0.00097, train.py:146\n val_loss: 0.00153, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:39] INFO Epoch: 18 | train_loss: 0.00095, train.py:146\n val_loss: 0.00155, lr: 2.03E-04, \n _patience: 9 \n[01/26/21 18:03:42] INFO Epoch: 19 | train_loss: 0.00086, train.py:146\n val_loss: 0.00157, lr: 2.03E-04, \n _patience: 8 \n[01/26/21 18:03:45] INFO Epoch: 20 | train_loss: 0.00082, train.py:146\n val_loss: 0.00150, lr: 2.03E-04, \n _patience: 10 \n[01/26/21 18:03:49] INFO Epoch: 21 | train_loss: 0.00071, train.py:146\n val_loss: 0.00154, lr: 2.03E-04, \n _patience: 9 \n[01/26/21 18:03:52] INFO Epoch: 22 | train_loss: 0.00067, train.py:146\n val_loss: 0.00153, lr: 2.03E-04, \n _patience: 8 \n[01/26/21 18:03:55] INFO Epoch: 23 | train_loss: 0.00062, train.py:146\n val_loss: 0.00157, lr: 2.03E-04, \n _patience: 7 \n[01/26/21 18:03:58] INFO Epoch: 24 | train_loss: 0.00059, train.py:146\n val_loss: 0.00154, lr: 2.03E-04, \n _patience: 6 \n[01/26/21 18:04:01] INFO Epoch: 25 | train_loss: 0.00053, train.py:146\n val_loss: 0.00160, lr: 2.03E-04, \n _patience: 5 \n[01/26/21 18:04:05] INFO Epoch: 26 | train_loss: 0.00049, train.py:146\n val_loss: 0.00161, lr: 1.02E-05, \n _patience: 4 \n[01/26/21 18:04:08] INFO Epoch: 27 | train_loss: 0.00048, train.py:146\n val_loss: 0.00159, lr: 1.02E-05, \n _patience: 3 \n[01/26/21 18:04:11] INFO Epoch: 28 | train_loss: 0.00046, train.py:146\n val_loss: 0.00158, lr: 1.02E-05, \n _patience: 2 \n[01/26/21 18:04:14] INFO Epoch: 29 | train_loss: 0.00044, train.py:146\n val_loss: 0.00158, lr: 1.02E-05, \n _patience: 1 \n[01/26/21 18:04:18] INFO Stopping early! train.py:141\n[01/26/21 18:04:29] INFO { train.py:460\n \"precision\": 0.8088107519954528, \n \"recall\": 0.5392876362827101, \n \"f1\": 0.6099244324051005, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 60: \n INFO { train.py:454\n \"embedding_dim\": 355, \n \"num_filters\": 400, \n \"hidden_dim\": 346, \n \"dropout_p\": 0.40749798209671806, \n \"lr\": 0.0003745253450864249 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 355, \n \"num_filters\": 400, \n \"hidden_dim\": 346, \n \"dropout_p\": 0.40749798209671806, \n \"lr\": 0.0003745253450864249, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.25125086307525635 \n } \n[01/26/21 18:04:32] INFO Epoch: 1 | train_loss: 0.00655, train.py:146\n val_loss: 0.00493, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:35] INFO Epoch: 2 | train_loss: 0.00475, train.py:146\n val_loss: 0.00278, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:38] INFO Epoch: 3 | train_loss: 0.00332, train.py:146\n val_loss: 0.00248, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:40] INFO Epoch: 4 | train_loss: 0.00275, train.py:146\n val_loss: 0.00230, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:43] INFO Epoch: 5 | train_loss: 0.00236, train.py:146\n val_loss: 0.00206, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:46] INFO Epoch: 6 | train_loss: 0.00203, train.py:146\n val_loss: 0.00187, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:49] INFO Epoch: 7 | train_loss: 0.00176, train.py:146\n val_loss: 0.00175, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:52] INFO Epoch: 8 | train_loss: 0.00152, train.py:146\n val_loss: 0.00166, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:55] INFO Epoch: 9 | train_loss: 0.00136, train.py:146\n val_loss: 0.00163, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:04:58] INFO Epoch: 10 | train_loss: 0.00117, train.py:146\n val_loss: 0.00158, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:05:01] INFO Epoch: 11 | train_loss: 0.00103, train.py:146\n val_loss: 0.00158, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:05:04] INFO Epoch: 12 | train_loss: 0.00090, train.py:146\n val_loss: 0.00154, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:05:07] INFO Epoch: 13 | train_loss: 0.00079, train.py:146\n val_loss: 0.00153, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:05:10] INFO Epoch: 14 | train_loss: 0.00070, train.py:146\n val_loss: 0.00158, lr: 3.75E-04, \n _patience: 9 \n[01/26/21 18:05:13] INFO Epoch: 15 | train_loss: 0.00060, train.py:146\n val_loss: 0.00159, lr: 3.75E-04, \n _patience: 8 \n[01/26/21 18:05:16] INFO Epoch: 16 | train_loss: 0.00055, train.py:146\n val_loss: 0.00162, lr: 3.75E-04, \n _patience: 7 \n[01/26/21 18:05:19] INFO Epoch: 17 | train_loss: 0.00050, train.py:146\n val_loss: 0.00164, lr: 3.75E-04, \n _patience: 6 \n[01/26/21 18:05:22] INFO Epoch: 18 | train_loss: 0.00045, train.py:146\n val_loss: 0.00168, lr: 3.75E-04, \n _patience: 5 \n[01/26/21 18:05:25] INFO Epoch: 19 | train_loss: 0.00040, train.py:146\n val_loss: 0.00176, lr: 1.87E-05, \n _patience: 4 \n[01/26/21 18:05:27] INFO Epoch: 20 | train_loss: 0.00038, train.py:146\n val_loss: 0.00171, lr: 1.87E-05, \n _patience: 3 \n[01/26/21 18:05:30] INFO Epoch: 21 | train_loss: 0.00033, train.py:146\n val_loss: 0.00165, lr: 1.87E-05, \n _patience: 2 \n[01/26/21 18:05:33] INFO Epoch: 22 | train_loss: 0.00032, train.py:146\n val_loss: 0.00164, lr: 1.87E-05, \n _patience: 1 \n[01/26/21 18:05:36] INFO Stopping early! train.py:141\n[01/26/21 18:05:46] INFO { train.py:460\n \"precision\": 0.8183343922874255, \n \"recall\": 0.54927984964315, \n \"f1\": 0.6261781891301342, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 61: \n INFO { train.py:454\n \"embedding_dim\": 329, \n \"num_filters\": 363, \n \"hidden_dim\": 283, \n \"dropout_p\": 0.5027218466559851, \n \"lr\": 0.0004622303779946712 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 329, \n \"num_filters\": 363, \n \"hidden_dim\": 283, \n \"dropout_p\": 0.5027218466559851, \n \"lr\": 0.0004622303779946712, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2879375219345093 \n } \n[01/26/21 18:05:48] INFO Epoch: 1 | train_loss: 0.00707, train.py:146\n val_loss: 0.00510, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:05:51] INFO Epoch: 2 | train_loss: 0.00517, train.py:146\n val_loss: 0.00279, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:05:53] INFO Epoch: 3 | train_loss: 0.00357, train.py:146\n val_loss: 0.00253, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:05:56] INFO Epoch: 4 | train_loss: 0.00298, train.py:146\n val_loss: 0.00242, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:05:58] INFO Epoch: 5 | train_loss: 0.00269, train.py:146\n val_loss: 0.00217, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:01] INFO Epoch: 6 | train_loss: 0.00226, train.py:146\n val_loss: 0.00200, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:03] INFO Epoch: 7 | train_loss: 0.00197, train.py:146\n val_loss: 0.00183, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:06] INFO Epoch: 8 | train_loss: 0.00172, train.py:146\n val_loss: 0.00174, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:08] INFO Epoch: 9 | train_loss: 0.00153, train.py:146\n val_loss: 0.00166, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:11] INFO Epoch: 10 | train_loss: 0.00136, train.py:146\n val_loss: 0.00160, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:13] INFO Epoch: 11 | train_loss: 0.00122, train.py:146\n val_loss: 0.00160, lr: 4.62E-04, \n _patience: 9 \n[01/26/21 18:06:16] INFO Epoch: 12 | train_loss: 0.00104, train.py:146\n val_loss: 0.00159, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:18] INFO Epoch: 13 | train_loss: 0.00095, train.py:146\n val_loss: 0.00156, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:21] INFO Epoch: 14 | train_loss: 0.00083, train.py:146\n val_loss: 0.00155, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:23] INFO Epoch: 15 | train_loss: 0.00075, train.py:146\n val_loss: 0.00155, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:06:26] INFO Epoch: 16 | train_loss: 0.00068, train.py:146\n val_loss: 0.00164, lr: 4.62E-04, \n _patience: 9 \n[01/26/21 18:06:29] INFO Epoch: 17 | train_loss: 0.00061, train.py:146\n val_loss: 0.00173, lr: 4.62E-04, \n _patience: 8 \n[01/26/21 18:06:31] INFO Epoch: 18 | train_loss: 0.00055, train.py:146\n val_loss: 0.00182, lr: 4.62E-04, \n _patience: 7 \n[01/26/21 18:06:34] INFO Epoch: 19 | train_loss: 0.00051, train.py:146\n val_loss: 0.00178, lr: 4.62E-04, \n _patience: 6 \n[01/26/21 18:06:36] INFO Epoch: 20 | train_loss: 0.00046, train.py:146\n val_loss: 0.00172, lr: 4.62E-04, \n _patience: 5 \n[01/26/21 18:06:39] INFO Epoch: 21 | train_loss: 0.00042, train.py:146\n val_loss: 0.00158, lr: 2.31E-05, \n _patience: 4 \n[01/26/21 18:06:42] INFO Epoch: 22 | train_loss: 0.00036, train.py:146\n val_loss: 0.00164, lr: 2.31E-05, \n _patience: 3 \n[01/26/21 18:06:44] INFO Epoch: 23 | train_loss: 0.00033, train.py:146\n val_loss: 0.00173, lr: 2.31E-05, \n _patience: 2 \n[01/26/21 18:06:47] INFO Epoch: 24 | train_loss: 0.00033, train.py:146\n val_loss: 0.00173, lr: 2.31E-05, \n _patience: 1 \n[01/26/21 18:06:49] INFO Stopping early! train.py:141\n[01/26/21 18:06:58] INFO { train.py:460\n \"precision\": 0.848965296263433, \n \"recall\": 0.5301663987809307, \n \"f1\": 0.619282253119128, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 62: \n INFO { train.py:454\n \"embedding_dim\": 314, \n \"num_filters\": 349, \n \"hidden_dim\": 325, \n \"dropout_p\": 0.4588544202821141, \n \"lr\": 0.0004481875471676014 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 314, \n \"num_filters\": 349, \n \"hidden_dim\": 325, \n \"dropout_p\": 0.4588544202821141, \n \"lr\": 0.0004481875471676014, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.3188823163509369 \n } \n[01/26/21 18:07:00] INFO Epoch: 1 | train_loss: 0.00691, train.py:146\n val_loss: 0.00513, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:02] INFO Epoch: 2 | train_loss: 0.00476, train.py:146\n val_loss: 0.00275, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:05] INFO Epoch: 3 | train_loss: 0.00351, train.py:146\n val_loss: 0.00252, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:07] INFO Epoch: 4 | train_loss: 0.00294, train.py:146\n val_loss: 0.00241, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:09] INFO Epoch: 5 | train_loss: 0.00254, train.py:146\n val_loss: 0.00218, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:11] INFO Epoch: 6 | train_loss: 0.00226, train.py:146\n val_loss: 0.00201, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:14] INFO Epoch: 7 | train_loss: 0.00195, train.py:146\n val_loss: 0.00185, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:16] INFO Epoch: 8 | train_loss: 0.00172, train.py:146\n val_loss: 0.00175, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:18] INFO Epoch: 9 | train_loss: 0.00153, train.py:146\n val_loss: 0.00169, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:21] INFO Epoch: 10 | train_loss: 0.00134, train.py:146\n val_loss: 0.00164, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:23] INFO Epoch: 11 | train_loss: 0.00116, train.py:146\n val_loss: 0.00163, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:25] INFO Epoch: 12 | train_loss: 0.00104, train.py:146\n val_loss: 0.00158, lr: 4.48E-04, \n _patience: 10 \n[01/26/21 18:07:28] INFO Epoch: 13 | train_loss: 0.00092, train.py:146\n val_loss: 0.00158, lr: 4.48E-04, \n _patience: 9 \n[01/26/21 18:07:30] INFO Epoch: 14 | train_loss: 0.00080, train.py:146\n val_loss: 0.00159, lr: 4.48E-04, \n _patience: 8 \n[01/26/21 18:07:32] INFO Epoch: 15 | train_loss: 0.00070, train.py:146\n val_loss: 0.00162, lr: 4.48E-04, \n _patience: 7 \n[01/26/21 18:07:35] INFO Epoch: 16 | train_loss: 0.00063, train.py:146\n val_loss: 0.00165, lr: 4.48E-04, \n _patience: 6 \n[01/26/21 18:07:37] INFO Epoch: 17 | train_loss: 0.00055, train.py:146\n val_loss: 0.00169, lr: 4.48E-04, \n _patience: 5 \n[01/26/21 18:07:40] INFO Epoch: 18 | train_loss: 0.00050, train.py:146\n val_loss: 0.00170, lr: 2.24E-05, \n _patience: 4 \n[01/26/21 18:07:42] INFO Epoch: 19 | train_loss: 0.00044, train.py:146\n val_loss: 0.00167, lr: 2.24E-05, \n _patience: 3 \n[01/26/21 18:07:44] INFO Epoch: 20 | train_loss: 0.00044, train.py:146\n val_loss: 0.00163, lr: 2.24E-05, \n _patience: 2 \n[01/26/21 18:07:47] INFO Epoch: 21 | train_loss: 0.00042, train.py:146\n val_loss: 0.00162, lr: 2.24E-05, \n _patience: 1 \n[01/26/21 18:07:49] INFO Stopping early! train.py:141\n[01/26/21 18:07:57] INFO { train.py:460\n \"precision\": 0.8230975184792056, \n \"recall\": 0.5263677817803434, \n \"f1\": 0.6104545997071277, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 63: \n INFO { train.py:454\n \"embedding_dim\": 298, \n \"num_filters\": 431, \n \"hidden_dim\": 389, \n \"dropout_p\": 0.5316238010726352, \n \"lr\": 0.00039868966650492854 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 298, \n \"num_filters\": 431, \n \"hidden_dim\": 389, \n \"dropout_p\": 0.5316238010726352, \n \"lr\": 0.00039868966650492854, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.3115173876285553 \n } \n[01/26/21 18:08:00] INFO Epoch: 1 | train_loss: 0.00722, train.py:146\n val_loss: 0.00544, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:02] INFO Epoch: 2 | train_loss: 0.00549, train.py:146\n val_loss: 0.00303, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:05] INFO Epoch: 3 | train_loss: 0.00371, train.py:146\n val_loss: 0.00254, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:08] INFO Epoch: 4 | train_loss: 0.00303, train.py:146\n val_loss: 0.00246, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:10] INFO Epoch: 5 | train_loss: 0.00268, train.py:146\n val_loss: 0.00222, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:13] INFO Epoch: 6 | train_loss: 0.00232, train.py:146\n val_loss: 0.00205, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:15] INFO Epoch: 7 | train_loss: 0.00209, train.py:146\n val_loss: 0.00188, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:18] INFO Epoch: 8 | train_loss: 0.00182, train.py:146\n val_loss: 0.00177, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:21] INFO Epoch: 9 | train_loss: 0.00159, train.py:146\n val_loss: 0.00170, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:23] INFO Epoch: 10 | train_loss: 0.00142, train.py:146\n val_loss: 0.00164, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:26] INFO Epoch: 11 | train_loss: 0.00126, train.py:146\n val_loss: 0.00159, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:29] INFO Epoch: 12 | train_loss: 0.00111, train.py:146\n val_loss: 0.00157, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:31] INFO Epoch: 13 | train_loss: 0.00101, train.py:146\n val_loss: 0.00155, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:34] INFO Epoch: 14 | train_loss: 0.00088, train.py:146\n val_loss: 0.00154, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:37] INFO Epoch: 15 | train_loss: 0.00080, train.py:146\n val_loss: 0.00153, lr: 3.99E-04, \n _patience: 10 \n[01/26/21 18:08:39] INFO Epoch: 16 | train_loss: 0.00070, train.py:146\n val_loss: 0.00156, lr: 3.99E-04, \n _patience: 9 \n[01/26/21 18:08:42] INFO Epoch: 17 | train_loss: 0.00062, train.py:146\n val_loss: 0.00154, lr: 3.99E-04, \n _patience: 8 \n[01/26/21 18:08:45] INFO Epoch: 18 | train_loss: 0.00056, train.py:146\n val_loss: 0.00159, lr: 3.99E-04, \n _patience: 7 \n[01/26/21 18:08:47] INFO Epoch: 19 | train_loss: 0.00051, train.py:146\n val_loss: 0.00169, lr: 3.99E-04, \n _patience: 6 \n[01/26/21 18:08:50] INFO Epoch: 20 | train_loss: 0.00046, train.py:146\n val_loss: 0.00172, lr: 3.99E-04, \n _patience: 5 \n[01/26/21 18:08:53] INFO Epoch: 21 | train_loss: 0.00041, train.py:146\n val_loss: 0.00170, lr: 1.99E-05, \n _patience: 4 \n[01/26/21 18:08:55] INFO Epoch: 22 | train_loss: 0.00038, train.py:146\n val_loss: 0.00167, lr: 1.99E-05, \n _patience: 3 \n[01/26/21 18:08:58] INFO Epoch: 23 | train_loss: 0.00037, train.py:146\n val_loss: 0.00164, lr: 1.99E-05, \n _patience: 2 \n[01/26/21 18:09:01] INFO Epoch: 24 | train_loss: 0.00035, train.py:146\n val_loss: 0.00164, lr: 1.99E-05, \n _patience: 1 \n[01/26/21 18:09:03] INFO Stopping early! train.py:141\n[01/26/21 18:09:12] INFO { train.py:460\n \"precision\": 0.8095380199382549, \n \"recall\": 0.5481715003205151, \n \"f1\": 0.6211487165042849, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 64: \n INFO { train.py:454\n \"embedding_dim\": 382, \n \"num_filters\": 410, \n \"hidden_dim\": 353, \n \"dropout_p\": 0.480587452098813, \n \"lr\": 0.00032999967552735956 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 382, \n \"num_filters\": 410, \n \"hidden_dim\": 353, \n \"dropout_p\": 0.480587452098813, \n \"lr\": 0.00032999967552735956, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2765241861343384 \n } \n[01/26/21 18:09:16] INFO Epoch: 1 | train_loss: 0.00647, train.py:146\n val_loss: 0.00498, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:19] INFO Epoch: 2 | train_loss: 0.00475, train.py:146\n val_loss: 0.00277, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:22] INFO Epoch: 3 | train_loss: 0.00344, train.py:146\n val_loss: 0.00250, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:25] INFO Epoch: 4 | train_loss: 0.00288, train.py:146\n val_loss: 0.00234, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:28] INFO Epoch: 5 | train_loss: 0.00254, train.py:146\n val_loss: 0.00212, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:31] INFO Epoch: 6 | train_loss: 0.00223, train.py:146\n val_loss: 0.00193, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:34] INFO Epoch: 7 | train_loss: 0.00193, train.py:146\n val_loss: 0.00182, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:37] INFO Epoch: 8 | train_loss: 0.00170, train.py:146\n val_loss: 0.00170, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:40] INFO Epoch: 9 | train_loss: 0.00149, train.py:146\n val_loss: 0.00167, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:43] INFO Epoch: 10 | train_loss: 0.00134, train.py:146\n val_loss: 0.00161, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:46] INFO Epoch: 11 | train_loss: 0.00118, train.py:146\n val_loss: 0.00155, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:50] INFO Epoch: 12 | train_loss: 0.00107, train.py:146\n val_loss: 0.00154, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:53] INFO Epoch: 13 | train_loss: 0.00094, train.py:146\n val_loss: 0.00152, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:09:56] INFO Epoch: 14 | train_loss: 0.00081, train.py:146\n val_loss: 0.00155, lr: 3.30E-04, \n _patience: 9 \n[01/26/21 18:09:59] INFO Epoch: 15 | train_loss: 0.00072, train.py:146\n val_loss: 0.00155, lr: 3.30E-04, \n _patience: 8 \n[01/26/21 18:10:02] INFO Epoch: 16 | train_loss: 0.00065, train.py:146\n val_loss: 0.00153, lr: 3.30E-04, \n _patience: 7 \n[01/26/21 18:10:05] INFO Epoch: 17 | train_loss: 0.00058, train.py:146\n val_loss: 0.00152, lr: 3.30E-04, \n _patience: 10 \n[01/26/21 18:10:08] INFO Epoch: 18 | train_loss: 0.00051, train.py:146\n val_loss: 0.00157, lr: 3.30E-04, \n _patience: 9 \n[01/26/21 18:10:12] INFO Epoch: 19 | train_loss: 0.00047, train.py:146\n val_loss: 0.00157, lr: 3.30E-04, \n _patience: 8 \n[01/26/21 18:10:15] INFO Epoch: 20 | train_loss: 0.00043, train.py:146\n val_loss: 0.00159, lr: 3.30E-04, \n _patience: 7 \n[01/26/21 18:10:18] INFO Epoch: 21 | train_loss: 0.00038, train.py:146\n val_loss: 0.00166, lr: 3.30E-04, \n _patience: 6 \n[01/26/21 18:10:21] INFO Epoch: 22 | train_loss: 0.00035, train.py:146\n val_loss: 0.00165, lr: 3.30E-04, \n _patience: 5 \n[01/26/21 18:10:24] INFO Epoch: 23 | train_loss: 0.00031, train.py:146\n val_loss: 0.00167, lr: 1.65E-05, \n _patience: 4 \n[01/26/21 18:10:27] INFO Epoch: 24 | train_loss: 0.00031, train.py:146\n val_loss: 0.00166, lr: 1.65E-05, \n _patience: 3 \n[01/26/21 18:10:30] INFO Epoch: 25 | train_loss: 0.00028, train.py:146\n val_loss: 0.00166, lr: 1.65E-05, \n _patience: 2 \n[01/26/21 18:10:33] INFO Epoch: 26 | train_loss: 0.00027, train.py:146\n val_loss: 0.00167, lr: 1.65E-05, \n _patience: 1 \n[01/26/21 18:10:36] INFO Stopping early! train.py:141\n[01/26/21 18:10:46] INFO { train.py:460\n \"precision\": 0.8067314551895833, \n \"recall\": 0.5631521627888623, \n \"f1\": 0.6332669360680295, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 65: \n INFO { train.py:454\n \"embedding_dim\": 352, \n \"num_filters\": 376, \n \"hidden_dim\": 404, \n \"dropout_p\": 0.5570650164613432, \n \"lr\": 0.0001556836540436888 \n } \n[01/26/21 18:10:47] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 352, \n \"num_filters\": 376, \n \"hidden_dim\": 404, \n \"dropout_p\": 0.5570650164613432, \n \"lr\": 0.0001556836540436888, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.23578034341335297 \n } \n[01/26/21 18:10:49] INFO Epoch: 1 | train_loss: 0.00549, train.py:146\n val_loss: 0.00398, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:10:52] INFO Epoch: 2 | train_loss: 0.00446, train.py:146\n val_loss: 0.00336, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:10:54] INFO Epoch: 3 | train_loss: 0.00357, train.py:146\n val_loss: 0.00259, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:10:57] INFO Epoch: 4 | train_loss: 0.00317, train.py:146\n val_loss: 0.00248, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:10:59] INFO Epoch: 5 | train_loss: 0.00294, train.py:146\n val_loss: 0.00238, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:02] INFO Epoch: 6 | train_loss: 0.00268, train.py:146\n val_loss: 0.00230, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:05] INFO Epoch: 7 | train_loss: 0.00254, train.py:146\n val_loss: 0.00219, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:07] INFO Epoch: 8 | train_loss: 0.00232, train.py:146\n val_loss: 0.00209, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:10] INFO Epoch: 9 | train_loss: 0.00217, train.py:146\n val_loss: 0.00200, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:13] INFO Epoch: 10 | train_loss: 0.00202, train.py:146\n val_loss: 0.00192, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:15] INFO Epoch: 11 | train_loss: 0.00189, train.py:146\n val_loss: 0.00183, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:18] INFO Epoch: 12 | train_loss: 0.00178, train.py:146\n val_loss: 0.00177, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:21] INFO Epoch: 13 | train_loss: 0.00165, train.py:146\n val_loss: 0.00173, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:23] INFO Epoch: 14 | train_loss: 0.00155, train.py:146\n val_loss: 0.00169, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:26] INFO Epoch: 15 | train_loss: 0.00144, train.py:146\n val_loss: 0.00166, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:29] INFO Epoch: 16 | train_loss: 0.00138, train.py:146\n val_loss: 0.00161, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:31] INFO Epoch: 17 | train_loss: 0.00130, train.py:146\n val_loss: 0.00162, lr: 1.56E-04, \n _patience: 9 \n[01/26/21 18:11:34] INFO Epoch: 18 | train_loss: 0.00123, train.py:146\n val_loss: 0.00159, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:37] INFO Epoch: 19 | train_loss: 0.00113, train.py:146\n val_loss: 0.00156, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:39] INFO Epoch: 20 | train_loss: 0.00109, train.py:146\n val_loss: 0.00155, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:42] INFO Epoch: 21 | train_loss: 0.00102, train.py:146\n val_loss: 0.00154, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:44] INFO Epoch: 22 | train_loss: 0.00097, train.py:146\n val_loss: 0.00156, lr: 1.56E-04, \n _patience: 9 \n[01/26/21 18:11:47] INFO Epoch: 23 | train_loss: 0.00090, train.py:146\n val_loss: 0.00152, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:11:50] INFO Epoch: 24 | train_loss: 0.00086, train.py:146\n val_loss: 0.00153, lr: 1.56E-04, \n _patience: 9 \n[01/26/21 18:11:52] INFO Epoch: 25 | train_loss: 0.00080, train.py:146\n val_loss: 0.00153, lr: 1.56E-04, \n _patience: 8 \n[01/26/21 18:11:55] INFO Epoch: 26 | train_loss: 0.00076, train.py:146\n val_loss: 0.00153, lr: 1.56E-04, \n _patience: 7 \n[01/26/21 18:11:57] INFO Epoch: 27 | train_loss: 0.00072, train.py:146\n val_loss: 0.00154, lr: 1.56E-04, \n _patience: 6 \n[01/26/21 18:12:00] INFO Epoch: 28 | train_loss: 0.00068, train.py:146\n val_loss: 0.00153, lr: 1.56E-04, \n _patience: 5 \n[01/26/21 18:12:03] INFO Epoch: 29 | train_loss: 0.00066, train.py:146\n val_loss: 0.00150, lr: 1.56E-04, \n _patience: 10 \n[01/26/21 18:12:05] INFO Epoch: 30 | train_loss: 0.00061, train.py:146\n val_loss: 0.00152, lr: 1.56E-04, \n _patience: 9 \n[01/26/21 18:12:08] INFO Epoch: 31 | train_loss: 0.00057, train.py:146\n val_loss: 0.00155, lr: 1.56E-04, \n _patience: 8 \n[01/26/21 18:12:10] INFO Epoch: 32 | train_loss: 0.00054, train.py:146\n val_loss: 0.00156, lr: 1.56E-04, \n _patience: 7 \n[01/26/21 18:12:13] INFO Epoch: 33 | train_loss: 0.00053, train.py:146\n val_loss: 0.00156, lr: 1.56E-04, \n _patience: 6 \n[01/26/21 18:12:15] INFO Epoch: 34 | train_loss: 0.00048, train.py:146\n val_loss: 0.00156, lr: 1.56E-04, \n _patience: 5 \n[01/26/21 18:12:18] INFO Epoch: 35 | train_loss: 0.00046, train.py:146\n val_loss: 0.00158, lr: 7.78E-06, \n _patience: 4 \n[01/26/21 18:12:21] INFO Epoch: 36 | train_loss: 0.00044, train.py:146\n val_loss: 0.00157, lr: 7.78E-06, \n _patience: 3 \n[01/26/21 18:12:23] INFO Epoch: 37 | train_loss: 0.00043, train.py:146\n val_loss: 0.00156, lr: 7.78E-06, \n _patience: 2 \n[01/26/21 18:12:26] INFO Epoch: 38 | train_loss: 0.00043, train.py:146\n val_loss: 0.00156, lr: 7.78E-06, \n _patience: 1 \n[01/26/21 18:12:28] INFO Stopping early! train.py:141\n[01/26/21 18:12:37] INFO { train.py:460\n \"precision\": 0.7863621453393749, \n \"recall\": 0.533427746993018, \n \"f1\": 0.6060356599374448, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 66: \n INFO { train.py:454\n \"embedding_dim\": 336, \n \"num_filters\": 423, \n \"hidden_dim\": 295, \n \"dropout_p\": 0.4364070163222632, \n \"lr\": 0.00046214748249670664 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 336, \n \"num_filters\": 423, \n \"hidden_dim\": 295, \n \"dropout_p\": 0.4364070163222632, \n \"lr\": 0.00046214748249670664, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.27214863896369934 \n } \n[01/26/21 18:12:40] INFO Epoch: 1 | train_loss: 0.00713, train.py:146\n val_loss: 0.00510, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:12:43] INFO Epoch: 2 | train_loss: 0.00492, train.py:146\n val_loss: 0.00278, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:12:45] INFO Epoch: 3 | train_loss: 0.00341, train.py:146\n val_loss: 0.00248, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:12:48] INFO Epoch: 4 | train_loss: 0.00282, train.py:146\n val_loss: 0.00234, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:12:51] INFO Epoch: 5 | train_loss: 0.00242, train.py:146\n val_loss: 0.00209, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:12:54] INFO Epoch: 6 | train_loss: 0.00208, train.py:146\n val_loss: 0.00191, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:12:57] INFO Epoch: 7 | train_loss: 0.00182, train.py:146\n val_loss: 0.00177, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:13:00] INFO Epoch: 8 | train_loss: 0.00160, train.py:146\n val_loss: 0.00169, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:13:02] INFO Epoch: 9 | train_loss: 0.00138, train.py:146\n val_loss: 0.00165, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:13:05] INFO Epoch: 10 | train_loss: 0.00120, train.py:146\n val_loss: 0.00161, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:13:08] INFO Epoch: 11 | train_loss: 0.00105, train.py:146\n val_loss: 0.00157, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:13:11] INFO Epoch: 12 | train_loss: 0.00091, train.py:146\n val_loss: 0.00158, lr: 4.62E-04, \n _patience: 9 \n[01/26/21 18:13:14] INFO Epoch: 13 | train_loss: 0.00080, train.py:146\n val_loss: 0.00154, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:13:17] INFO Epoch: 14 | train_loss: 0.00070, train.py:146\n val_loss: 0.00156, lr: 4.62E-04, \n _patience: 9 \n[01/26/21 18:13:20] INFO Epoch: 15 | train_loss: 0.00060, train.py:146\n val_loss: 0.00161, lr: 4.62E-04, \n _patience: 8 \n[01/26/21 18:13:23] INFO Epoch: 16 | train_loss: 0.00054, train.py:146\n val_loss: 0.00169, lr: 4.62E-04, \n _patience: 7 \n[01/26/21 18:13:25] INFO Epoch: 17 | train_loss: 0.00047, train.py:146\n val_loss: 0.00177, lr: 4.62E-04, \n _patience: 6 \n[01/26/21 18:13:28] INFO Epoch: 18 | train_loss: 0.00043, train.py:146\n val_loss: 0.00185, lr: 4.62E-04, \n _patience: 5 \n[01/26/21 18:13:31] INFO Epoch: 19 | train_loss: 0.00041, train.py:146\n val_loss: 0.00182, lr: 2.31E-05, \n _patience: 4 \n[01/26/21 18:13:34] INFO Epoch: 20 | train_loss: 0.00037, train.py:146\n val_loss: 0.00177, lr: 2.31E-05, \n _patience: 3 \n[01/26/21 18:13:37] INFO Epoch: 21 | train_loss: 0.00033, train.py:146\n val_loss: 0.00168, lr: 2.31E-05, \n _patience: 2 \n[01/26/21 18:13:39] INFO Epoch: 22 | train_loss: 0.00031, train.py:146\n val_loss: 0.00166, lr: 2.31E-05, \n _patience: 1 \n[01/26/21 18:13:42] INFO Stopping early! train.py:141\n[01/26/21 18:13:52] INFO { train.py:460\n \"precision\": 0.8210546549226938, \n \"recall\": 0.5417123512320556, \n \"f1\": 0.6248262875973905, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 67: \n INFO { train.py:454\n \"embedding_dim\": 260, \n \"num_filters\": 398, \n \"hidden_dim\": 256, \n \"dropout_p\": 0.5023434290824353, \n \"lr\": 0.0003738485017309363 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 260, \n \"num_filters\": 398, \n \"hidden_dim\": 256, \n \"dropout_p\": 0.5023434290824353, \n \"lr\": 0.0003738485017309363, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.3357660472393036 \n } \n[01/26/21 18:13:54] INFO Epoch: 1 | train_loss: 0.00640, train.py:146\n val_loss: 0.00502, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:13:56] INFO Epoch: 2 | train_loss: 0.00503, train.py:146\n val_loss: 0.00287, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:13:58] INFO Epoch: 3 | train_loss: 0.00365, train.py:146\n val_loss: 0.00256, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:01] INFO Epoch: 4 | train_loss: 0.00306, train.py:146\n val_loss: 0.00239, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:03] INFO Epoch: 5 | train_loss: 0.00275, train.py:146\n val_loss: 0.00225, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:05] INFO Epoch: 6 | train_loss: 0.00241, train.py:146\n val_loss: 0.00205, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:07] INFO Epoch: 7 | train_loss: 0.00213, train.py:146\n val_loss: 0.00190, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:10] INFO Epoch: 8 | train_loss: 0.00190, train.py:146\n val_loss: 0.00178, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:12] INFO Epoch: 9 | train_loss: 0.00170, train.py:146\n val_loss: 0.00170, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:14] INFO Epoch: 10 | train_loss: 0.00150, train.py:146\n val_loss: 0.00165, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:16] INFO Epoch: 11 | train_loss: 0.00139, train.py:146\n val_loss: 0.00160, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:19] INFO Epoch: 12 | train_loss: 0.00126, train.py:146\n val_loss: 0.00158, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:21] INFO Epoch: 13 | train_loss: 0.00114, train.py:146\n val_loss: 0.00155, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:23] INFO Epoch: 14 | train_loss: 0.00099, train.py:146\n val_loss: 0.00153, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:26] INFO Epoch: 15 | train_loss: 0.00091, train.py:146\n val_loss: 0.00151, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:28] INFO Epoch: 16 | train_loss: 0.00084, train.py:146\n val_loss: 0.00151, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:30] INFO Epoch: 17 | train_loss: 0.00076, train.py:146\n val_loss: 0.00151, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:32] INFO Epoch: 18 | train_loss: 0.00066, train.py:146\n val_loss: 0.00148, lr: 3.74E-04, \n _patience: 10 \n[01/26/21 18:14:35] INFO Epoch: 19 | train_loss: 0.00064, train.py:146\n val_loss: 0.00154, lr: 3.74E-04, \n _patience: 9 \n[01/26/21 18:14:37] INFO Epoch: 20 | train_loss: 0.00060, train.py:146\n val_loss: 0.00156, lr: 3.74E-04, \n _patience: 8 \n[01/26/21 18:14:39] INFO Epoch: 21 | train_loss: 0.00054, train.py:146\n val_loss: 0.00166, lr: 3.74E-04, \n _patience: 7 \n[01/26/21 18:14:42] INFO Epoch: 22 | train_loss: 0.00051, train.py:146\n val_loss: 0.00168, lr: 3.74E-04, \n _patience: 6 \n[01/26/21 18:14:44] INFO Epoch: 23 | train_loss: 0.00047, train.py:146\n val_loss: 0.00172, lr: 3.74E-04, \n _patience: 5 \n[01/26/21 18:14:46] INFO Epoch: 24 | train_loss: 0.00042, train.py:146\n val_loss: 0.00177, lr: 1.87E-05, \n _patience: 4 \n[01/26/21 18:14:48] INFO Epoch: 25 | train_loss: 0.00044, train.py:146\n val_loss: 0.00166, lr: 1.87E-05, \n _patience: 3 \n[01/26/21 18:14:51] INFO Epoch: 26 | train_loss: 0.00038, train.py:146\n val_loss: 0.00157, lr: 1.87E-05, \n _patience: 2 \n[01/26/21 18:14:53] INFO Epoch: 27 | train_loss: 0.00037, train.py:146\n val_loss: 0.00157, lr: 1.87E-05, \n _patience: 1 \n[01/26/21 18:14:55] INFO Stopping early! train.py:141\n[01/26/21 18:15:03] INFO { train.py:460\n \"precision\": 0.8209069181882735, \n \"recall\": 0.5733823987087534, \n \"f1\": 0.6472830002050478, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 68: \n INFO { train.py:454\n \"embedding_dim\": 246, \n \"num_filters\": 394, \n \"hidden_dim\": 219, \n \"dropout_p\": 0.5707943968301363, \n \"lr\": 0.0003085571731854818 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 246, \n \"num_filters\": 394, \n \"hidden_dim\": 219, \n \"dropout_p\": 0.5707943968301363, \n \"lr\": 0.0003085571731854818, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2556852698326111 \n } \n[01/26/21 18:15:05] INFO Epoch: 1 | train_loss: 0.00628, train.py:146\n val_loss: 0.00480, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:07] INFO Epoch: 2 | train_loss: 0.00542, train.py:146\n val_loss: 0.00315, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:09] INFO Epoch: 3 | train_loss: 0.00380, train.py:146\n val_loss: 0.00259, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:11] INFO Epoch: 4 | train_loss: 0.00334, train.py:146\n val_loss: 0.00244, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:13] INFO Epoch: 5 | train_loss: 0.00300, train.py:146\n val_loss: 0.00237, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:15] INFO Epoch: 6 | train_loss: 0.00267, train.py:146\n val_loss: 0.00218, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:17] INFO Epoch: 7 | train_loss: 0.00245, train.py:146\n val_loss: 0.00207, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:20] INFO Epoch: 8 | train_loss: 0.00221, train.py:146\n val_loss: 0.00196, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:22] INFO Epoch: 9 | train_loss: 0.00202, train.py:146\n val_loss: 0.00187, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:24] INFO Epoch: 10 | train_loss: 0.00191, train.py:146\n val_loss: 0.00179, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:26] INFO Epoch: 11 | train_loss: 0.00178, train.py:146\n val_loss: 0.00177, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:28] INFO Epoch: 12 | train_loss: 0.00164, train.py:146\n val_loss: 0.00172, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:30] INFO Epoch: 13 | train_loss: 0.00150, train.py:146\n val_loss: 0.00167, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:32] INFO Epoch: 14 | train_loss: 0.00142, train.py:146\n val_loss: 0.00163, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:34] INFO Epoch: 15 | train_loss: 0.00130, train.py:146\n val_loss: 0.00160, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:36] INFO Epoch: 16 | train_loss: 0.00120, train.py:146\n val_loss: 0.00161, lr: 3.09E-04, \n _patience: 9 \n[01/26/21 18:15:39] INFO Epoch: 17 | train_loss: 0.00113, train.py:146\n val_loss: 0.00163, lr: 3.09E-04, \n _patience: 8 \n[01/26/21 18:15:41] INFO Epoch: 18 | train_loss: 0.00104, train.py:146\n val_loss: 0.00157, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:43] INFO Epoch: 19 | train_loss: 0.00096, train.py:146\n val_loss: 0.00158, lr: 3.09E-04, \n _patience: 9 \n[01/26/21 18:15:45] INFO Epoch: 20 | train_loss: 0.00092, train.py:146\n val_loss: 0.00155, lr: 3.09E-04, \n _patience: 10 \n[01/26/21 18:15:47] INFO Epoch: 21 | train_loss: 0.00086, train.py:146\n val_loss: 0.00156, lr: 3.09E-04, \n _patience: 9 \n[01/26/21 18:15:49] INFO Epoch: 22 | train_loss: 0.00081, train.py:146\n val_loss: 0.00155, lr: 3.09E-04, \n _patience: 8 \n[01/26/21 18:15:51] INFO Epoch: 23 | train_loss: 0.00074, train.py:146\n val_loss: 0.00161, lr: 3.09E-04, \n _patience: 7 \n[01/26/21 18:15:54] INFO Epoch: 24 | train_loss: 0.00071, train.py:146\n val_loss: 0.00158, lr: 3.09E-04, \n _patience: 6 \n[01/26/21 18:15:56] INFO Epoch: 25 | train_loss: 0.00066, train.py:146\n val_loss: 0.00160, lr: 3.09E-04, \n _patience: 5 \n[01/26/21 18:15:58] INFO Epoch: 26 | train_loss: 0.00059, train.py:146\n val_loss: 0.00157, lr: 1.54E-05, \n _patience: 4 \n[01/26/21 18:16:00] INFO Epoch: 27 | train_loss: 0.00058, train.py:146\n val_loss: 0.00161, lr: 1.54E-05, \n _patience: 3 \n[01/26/21 18:16:02] INFO Epoch: 28 | train_loss: 0.00057, train.py:146\n val_loss: 0.00163, lr: 1.54E-05, \n _patience: 2 \n[01/26/21 18:16:04] INFO Epoch: 29 | train_loss: 0.00054, train.py:146\n val_loss: 0.00162, lr: 1.54E-05, \n _patience: 1 \n[01/26/21 18:16:06] INFO Stopping early! train.py:141\n[01/26/21 18:16:13] INFO { train.py:460\n \"precision\": 0.8376705040990756, \n \"recall\": 0.5296339267829415, \n \"f1\": 0.616295626867525, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 69: \n INFO { train.py:454\n \"embedding_dim\": 261, \n \"num_filters\": 445, \n \"hidden_dim\": 251, \n \"dropout_p\": 0.5020042067860869, \n \"lr\": 0.00035320409450082554 \n } \n[01/26/21 18:16:14] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 261, \n \"num_filters\": 445, \n \"hidden_dim\": 251, \n \"dropout_p\": 0.5020042067860869, \n \"lr\": 0.00035320409450082554, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2663338780403137 \n } \n[01/26/21 18:16:16] INFO Epoch: 1 | train_loss: 0.00675, train.py:146\n val_loss: 0.00526, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:18] INFO Epoch: 2 | train_loss: 0.00559, train.py:146\n val_loss: 0.00318, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:21] INFO Epoch: 3 | train_loss: 0.00385, train.py:146\n val_loss: 0.00255, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:23] INFO Epoch: 4 | train_loss: 0.00330, train.py:146\n val_loss: 0.00241, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:26] INFO Epoch: 5 | train_loss: 0.00282, train.py:146\n val_loss: 0.00232, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:28] INFO Epoch: 6 | train_loss: 0.00253, train.py:146\n val_loss: 0.00209, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:30] INFO Epoch: 7 | train_loss: 0.00221, train.py:146\n val_loss: 0.00195, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:33] INFO Epoch: 8 | train_loss: 0.00201, train.py:146\n val_loss: 0.00182, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:35] INFO Epoch: 9 | train_loss: 0.00178, train.py:146\n val_loss: 0.00172, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:38] INFO Epoch: 10 | train_loss: 0.00161, train.py:146\n val_loss: 0.00166, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:40] INFO Epoch: 11 | train_loss: 0.00148, train.py:146\n val_loss: 0.00164, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:43] INFO Epoch: 12 | train_loss: 0.00135, train.py:146\n val_loss: 0.00162, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:45] INFO Epoch: 13 | train_loss: 0.00122, train.py:146\n val_loss: 0.00159, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:48] INFO Epoch: 14 | train_loss: 0.00112, train.py:146\n val_loss: 0.00156, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:50] INFO Epoch: 15 | train_loss: 0.00101, train.py:146\n val_loss: 0.00154, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:53] INFO Epoch: 16 | train_loss: 0.00091, train.py:146\n val_loss: 0.00153, lr: 3.53E-04, \n _patience: 10 \n[01/26/21 18:16:55] INFO Epoch: 17 | train_loss: 0.00083, train.py:146\n val_loss: 0.00154, lr: 3.53E-04, \n _patience: 9 \n[01/26/21 18:16:58] INFO Epoch: 18 | train_loss: 0.00075, train.py:146\n val_loss: 0.00158, lr: 3.53E-04, \n _patience: 8 \n[01/26/21 18:17:00] INFO Epoch: 19 | train_loss: 0.00071, train.py:146\n val_loss: 0.00157, lr: 3.53E-04, \n _patience: 7 \n[01/26/21 18:17:02] INFO Epoch: 20 | train_loss: 0.00064, train.py:146\n val_loss: 0.00160, lr: 3.53E-04, \n _patience: 6 \n[01/26/21 18:17:05] INFO Epoch: 21 | train_loss: 0.00058, train.py:146\n val_loss: 0.00157, lr: 3.53E-04, \n _patience: 5 \n[01/26/21 18:17:07] INFO Epoch: 22 | train_loss: 0.00054, train.py:146\n val_loss: 0.00159, lr: 1.77E-05, \n _patience: 4 \n[01/26/21 18:17:10] INFO Epoch: 23 | train_loss: 0.00052, train.py:146\n val_loss: 0.00157, lr: 1.77E-05, \n _patience: 3 \n[01/26/21 18:17:12] INFO Epoch: 24 | train_loss: 0.00048, train.py:146\n val_loss: 0.00157, lr: 1.77E-05, \n _patience: 2 \n[01/26/21 18:17:15] INFO Epoch: 25 | train_loss: 0.00047, train.py:146\n val_loss: 0.00158, lr: 1.77E-05, \n _patience: 1 \n[01/26/21 18:17:17] INFO Stopping early! train.py:141\n[01/26/21 18:17:25] INFO { train.py:460\n \"precision\": 0.7996783743661807, \n \"recall\": 0.5475352614453599, \n \"f1\": 0.6173887428264277, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 70: \n INFO { train.py:454\n \"embedding_dim\": 285, \n \"num_filters\": 381, \n \"hidden_dim\": 469, \n \"dropout_p\": 0.5341536599295494, \n \"lr\": 0.0003890226047179095 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 285, \n \"num_filters\": 381, \n \"hidden_dim\": 469, \n \"dropout_p\": 0.5341536599295494, \n \"lr\": 0.0003890226047179095, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.24505078792572021 \n } \n[01/26/21 18:17:28] INFO Epoch: 1 | train_loss: 0.00708, train.py:146\n val_loss: 0.00527, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:30] INFO Epoch: 2 | train_loss: 0.00511, train.py:146\n val_loss: 0.00287, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:32] INFO Epoch: 3 | train_loss: 0.00358, train.py:146\n val_loss: 0.00256, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:34] INFO Epoch: 4 | train_loss: 0.00296, train.py:146\n val_loss: 0.00241, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:37] INFO Epoch: 5 | train_loss: 0.00256, train.py:146\n val_loss: 0.00222, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:39] INFO Epoch: 6 | train_loss: 0.00228, train.py:146\n val_loss: 0.00203, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:41] INFO Epoch: 7 | train_loss: 0.00202, train.py:146\n val_loss: 0.00189, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:44] INFO Epoch: 8 | train_loss: 0.00178, train.py:146\n val_loss: 0.00176, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:46] INFO Epoch: 9 | train_loss: 0.00161, train.py:146\n val_loss: 0.00170, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:48] INFO Epoch: 10 | train_loss: 0.00142, train.py:146\n val_loss: 0.00165, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:50] INFO Epoch: 11 | train_loss: 0.00127, train.py:146\n val_loss: 0.00160, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:53] INFO Epoch: 12 | train_loss: 0.00111, train.py:146\n val_loss: 0.00158, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:55] INFO Epoch: 13 | train_loss: 0.00101, train.py:146\n val_loss: 0.00156, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:17:57] INFO Epoch: 14 | train_loss: 0.00087, train.py:146\n val_loss: 0.00156, lr: 3.89E-04, \n _patience: 10 \n[01/26/21 18:18:00] INFO Epoch: 15 | train_loss: 0.00080, train.py:146\n val_loss: 0.00158, lr: 3.89E-04, \n _patience: 9 \n[01/26/21 18:18:02] INFO Epoch: 16 | train_loss: 0.00068, train.py:146\n val_loss: 0.00159, lr: 3.89E-04, \n _patience: 8 \n[01/26/21 18:18:04] INFO Epoch: 17 | train_loss: 0.00058, train.py:146\n val_loss: 0.00160, lr: 3.89E-04, \n _patience: 7 \n[01/26/21 18:18:07] INFO Epoch: 18 | train_loss: 0.00054, train.py:146\n val_loss: 0.00165, lr: 3.89E-04, \n _patience: 6 \n[01/26/21 18:18:09] INFO Epoch: 19 | train_loss: 0.00049, train.py:146\n val_loss: 0.00163, lr: 3.89E-04, \n _patience: 5 \n[01/26/21 18:18:11] INFO Epoch: 20 | train_loss: 0.00044, train.py:146\n val_loss: 0.00163, lr: 1.95E-05, \n _patience: 4 \n[01/26/21 18:18:14] INFO Epoch: 21 | train_loss: 0.00042, train.py:146\n val_loss: 0.00163, lr: 1.95E-05, \n _patience: 3 \n[01/26/21 18:18:16] INFO Epoch: 22 | train_loss: 0.00039, train.py:146\n val_loss: 0.00165, lr: 1.95E-05, \n _patience: 2 \n[01/26/21 18:18:18] INFO Epoch: 23 | train_loss: 0.00039, train.py:146\n val_loss: 0.00165, lr: 1.95E-05, \n _patience: 1 \n[01/26/21 18:18:21] INFO Stopping early! train.py:141\n[01/26/21 18:18:28] INFO { train.py:460\n \"precision\": 0.7887315608010825, \n \"recall\": 0.5339074442707448, \n \"f1\": 0.6059476076308993, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 71: \n INFO { train.py:454\n \"embedding_dim\": 318, \n \"num_filters\": 356, \n \"hidden_dim\": 269, \n \"dropout_p\": 0.482205485147863, \n \"lr\": 0.0004189056685539703 \n } \n[01/26/21 18:18:29] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 318, \n \"num_filters\": 356, \n \"hidden_dim\": 269, \n \"dropout_p\": 0.482205485147863, \n \"lr\": 0.0004189056685539703, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.31098732352256775 \n } \n[01/26/21 18:18:31] INFO Epoch: 1 | train_loss: 0.00643, train.py:146\n val_loss: 0.00476, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:33] INFO Epoch: 2 | train_loss: 0.00492, train.py:146\n val_loss: 0.00277, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:36] INFO Epoch: 3 | train_loss: 0.00349, train.py:146\n val_loss: 0.00252, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:38] INFO Epoch: 4 | train_loss: 0.00300, train.py:146\n val_loss: 0.00239, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:40] INFO Epoch: 5 | train_loss: 0.00257, train.py:146\n val_loss: 0.00216, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:43] INFO Epoch: 6 | train_loss: 0.00224, train.py:146\n val_loss: 0.00197, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:45] INFO Epoch: 7 | train_loss: 0.00194, train.py:146\n val_loss: 0.00182, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:47] INFO Epoch: 8 | train_loss: 0.00176, train.py:146\n val_loss: 0.00173, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:50] INFO Epoch: 9 | train_loss: 0.00154, train.py:146\n val_loss: 0.00167, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:52] INFO Epoch: 10 | train_loss: 0.00140, train.py:146\n val_loss: 0.00160, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:54] INFO Epoch: 11 | train_loss: 0.00119, train.py:146\n val_loss: 0.00159, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:18:57] INFO Epoch: 12 | train_loss: 0.00107, train.py:146\n val_loss: 0.00159, lr: 4.19E-04, \n _patience: 9 \n[01/26/21 18:18:59] INFO Epoch: 13 | train_loss: 0.00097, train.py:146\n val_loss: 0.00156, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:19:02] INFO Epoch: 14 | train_loss: 0.00085, train.py:146\n val_loss: 0.00150, lr: 4.19E-04, \n _patience: 10 \n[01/26/21 18:19:04] INFO Epoch: 15 | train_loss: 0.00078, train.py:146\n val_loss: 0.00154, lr: 4.19E-04, \n _patience: 9 \n[01/26/21 18:19:06] INFO Epoch: 16 | train_loss: 0.00070, train.py:146\n val_loss: 0.00156, lr: 4.19E-04, \n _patience: 8 \n[01/26/21 18:19:09] INFO Epoch: 17 | train_loss: 0.00061, train.py:146\n val_loss: 0.00159, lr: 4.19E-04, \n _patience: 7 \n[01/26/21 18:19:11] INFO Epoch: 18 | train_loss: 0.00054, train.py:146\n val_loss: 0.00162, lr: 4.19E-04, \n _patience: 6 \n[01/26/21 18:19:14] INFO Epoch: 19 | train_loss: 0.00048, train.py:146\n val_loss: 0.00162, lr: 4.19E-04, \n _patience: 5 \n[01/26/21 18:19:16] INFO Epoch: 20 | train_loss: 0.00045, train.py:146\n val_loss: 0.00169, lr: 2.09E-05, \n _patience: 4 \n[01/26/21 18:19:18] INFO Epoch: 21 | train_loss: 0.00041, train.py:146\n val_loss: 0.00165, lr: 2.09E-05, \n _patience: 3 \n[01/26/21 18:19:21] INFO Epoch: 22 | train_loss: 0.00040, train.py:146\n val_loss: 0.00163, lr: 2.09E-05, \n _patience: 2 \n[01/26/21 18:19:23] INFO Epoch: 23 | train_loss: 0.00039, train.py:146\n val_loss: 0.00162, lr: 2.09E-05, \n _patience: 1 \n[01/26/21 18:19:26] INFO Stopping early! train.py:141\n[01/26/21 18:19:33] INFO { train.py:460\n \"precision\": 0.8177055145037513, \n \"recall\": 0.5086051061235791, \n \"f1\": 0.5891958306691578, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 72: \n INFO { train.py:454\n \"embedding_dim\": 231, \n \"num_filters\": 410, \n \"hidden_dim\": 284, \n \"dropout_p\": 0.4547082990516873, \n \"lr\": 0.0003754923078214773 \n } \n[01/26/21 18:19:34] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 231, \n \"num_filters\": 410, \n \"hidden_dim\": 284, \n \"dropout_p\": 0.4547082990516873, \n \"lr\": 0.0003754923078214773, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.3210599720478058 \n } \n[01/26/21 18:19:36] INFO Epoch: 1 | train_loss: 0.00657, train.py:146\n val_loss: 0.00507, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:38] INFO Epoch: 2 | train_loss: 0.00525, train.py:146\n val_loss: 0.00312, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:40] INFO Epoch: 3 | train_loss: 0.00376, train.py:146\n val_loss: 0.00257, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:42] INFO Epoch: 4 | train_loss: 0.00317, train.py:146\n val_loss: 0.00241, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:44] INFO Epoch: 5 | train_loss: 0.00279, train.py:146\n val_loss: 0.00232, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:46] INFO Epoch: 6 | train_loss: 0.00245, train.py:146\n val_loss: 0.00211, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:48] INFO Epoch: 7 | train_loss: 0.00219, train.py:146\n val_loss: 0.00198, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:50] INFO Epoch: 8 | train_loss: 0.00193, train.py:146\n val_loss: 0.00187, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:52] INFO Epoch: 9 | train_loss: 0.00174, train.py:146\n val_loss: 0.00177, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:54] INFO Epoch: 10 | train_loss: 0.00156, train.py:146\n val_loss: 0.00170, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:57] INFO Epoch: 11 | train_loss: 0.00145, train.py:146\n val_loss: 0.00166, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:19:59] INFO Epoch: 12 | train_loss: 0.00128, train.py:146\n val_loss: 0.00162, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:20:01] INFO Epoch: 13 | train_loss: 0.00116, train.py:146\n val_loss: 0.00158, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:20:03] INFO Epoch: 14 | train_loss: 0.00105, train.py:146\n val_loss: 0.00157, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:20:05] INFO Epoch: 15 | train_loss: 0.00092, train.py:146\n val_loss: 0.00154, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:20:07] INFO Epoch: 16 | train_loss: 0.00084, train.py:146\n val_loss: 0.00153, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:20:09] INFO Epoch: 17 | train_loss: 0.00075, train.py:146\n val_loss: 0.00153, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:20:11] INFO Epoch: 18 | train_loss: 0.00070, train.py:146\n val_loss: 0.00152, lr: 3.75E-04, \n _patience: 10 \n[01/26/21 18:20:13] INFO Epoch: 19 | train_loss: 0.00061, train.py:146\n val_loss: 0.00154, lr: 3.75E-04, \n _patience: 9 \n[01/26/21 18:20:16] INFO Epoch: 20 | train_loss: 0.00056, train.py:146\n val_loss: 0.00153, lr: 3.75E-04, \n _patience: 8 \n[01/26/21 18:20:18] INFO Epoch: 21 | train_loss: 0.00051, train.py:146\n val_loss: 0.00161, lr: 3.75E-04, \n _patience: 7 \n[01/26/21 18:20:20] INFO Epoch: 22 | train_loss: 0.00048, train.py:146\n val_loss: 0.00164, lr: 3.75E-04, \n _patience: 6 \n[01/26/21 18:20:22] INFO Epoch: 23 | train_loss: 0.00044, train.py:146\n val_loss: 0.00170, lr: 3.75E-04, \n _patience: 5 \n[01/26/21 18:20:24] INFO Epoch: 24 | train_loss: 0.00039, train.py:146\n val_loss: 0.00165, lr: 1.88E-05, \n _patience: 4 \n[01/26/21 18:20:26] INFO Epoch: 25 | train_loss: 0.00038, train.py:146\n val_loss: 0.00162, lr: 1.88E-05, \n _patience: 3 \n[01/26/21 18:20:28] INFO Epoch: 26 | train_loss: 0.00035, train.py:146\n val_loss: 0.00161, lr: 1.88E-05, \n _patience: 2 \n[01/26/21 18:20:30] INFO Epoch: 27 | train_loss: 0.00035, train.py:146\n val_loss: 0.00161, lr: 1.88E-05, \n _patience: 1 \n[01/26/21 18:20:32] INFO Stopping early! train.py:141\n[01/26/21 18:20:39] INFO { train.py:460\n \"precision\": 0.8370460665041946, \n \"recall\": 0.5333817696625578, \n \"f1\": 0.618843383229588, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 73: \n INFO { train.py:454\n \"embedding_dim\": 301, \n \"num_filters\": 424, \n \"hidden_dim\": 442, \n \"dropout_p\": 0.49422621202650435, \n \"lr\": 0.0004965372083403619 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 301, \n \"num_filters\": 424, \n \"hidden_dim\": 442, \n \"dropout_p\": 0.49422621202650435, \n \"lr\": 0.0004965372083403619, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.3303174674510956 \n } \n[01/26/21 18:20:42] INFO Epoch: 1 | train_loss: 0.00780, train.py:146\n val_loss: 0.00505, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:20:45] INFO Epoch: 2 | train_loss: 0.00518, train.py:146\n val_loss: 0.00293, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:20:47] INFO Epoch: 3 | train_loss: 0.00343, train.py:146\n val_loss: 0.00259, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:20:50] INFO Epoch: 4 | train_loss: 0.00288, train.py:146\n val_loss: 0.00245, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:20:52] INFO Epoch: 5 | train_loss: 0.00252, train.py:146\n val_loss: 0.00219, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:20:55] INFO Epoch: 6 | train_loss: 0.00216, train.py:146\n val_loss: 0.00197, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:20:57] INFO Epoch: 7 | train_loss: 0.00189, train.py:146\n val_loss: 0.00182, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:00] INFO Epoch: 8 | train_loss: 0.00166, train.py:146\n val_loss: 0.00173, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:03] INFO Epoch: 9 | train_loss: 0.00141, train.py:146\n val_loss: 0.00166, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:05] INFO Epoch: 10 | train_loss: 0.00125, train.py:146\n val_loss: 0.00161, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:08] INFO Epoch: 11 | train_loss: 0.00111, train.py:146\n val_loss: 0.00160, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:11] INFO Epoch: 12 | train_loss: 0.00095, train.py:146\n val_loss: 0.00159, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:13] INFO Epoch: 13 | train_loss: 0.00080, train.py:146\n val_loss: 0.00159, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:16] INFO Epoch: 14 | train_loss: 0.00070, train.py:146\n val_loss: 0.00155, lr: 4.97E-04, \n _patience: 10 \n[01/26/21 18:21:19] INFO Epoch: 15 | train_loss: 0.00062, train.py:146\n val_loss: 0.00160, lr: 4.97E-04, \n _patience: 9 \n[01/26/21 18:21:21] INFO Epoch: 16 | train_loss: 0.00052, train.py:146\n val_loss: 0.00159, lr: 4.97E-04, \n _patience: 8 \n[01/26/21 18:21:24] INFO Epoch: 17 | train_loss: 0.00046, train.py:146\n val_loss: 0.00162, lr: 4.97E-04, \n _patience: 7 \n[01/26/21 18:21:27] INFO Epoch: 18 | train_loss: 0.00039, train.py:146\n val_loss: 0.00164, lr: 4.97E-04, \n _patience: 6 \n[01/26/21 18:21:29] INFO Epoch: 19 | train_loss: 0.00034, train.py:146\n val_loss: 0.00168, lr: 4.97E-04, \n _patience: 5 \n[01/26/21 18:21:32] INFO Epoch: 20 | train_loss: 0.00031, train.py:146\n val_loss: 0.00174, lr: 2.48E-05, \n _patience: 4 \n[01/26/21 18:21:34] INFO Epoch: 21 | train_loss: 0.00028, train.py:146\n val_loss: 0.00172, lr: 2.48E-05, \n _patience: 3 \n[01/26/21 18:21:37] INFO Epoch: 22 | train_loss: 0.00027, train.py:146\n val_loss: 0.00170, lr: 2.48E-05, \n _patience: 2 \n[01/26/21 18:21:40] INFO Epoch: 23 | train_loss: 0.00026, train.py:146\n val_loss: 0.00169, lr: 2.48E-05, \n _patience: 1 \n[01/26/21 18:21:42] INFO Stopping early! train.py:141\n[01/26/21 18:21:51] INFO { train.py:460\n \"precision\": 0.8085364780269261, \n \"recall\": 0.5664487257405977, \n \"f1\": 0.634257260442032, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 74: \n INFO { train.py:454\n \"embedding_dim\": 369, \n \"num_filters\": 370, \n \"hidden_dim\": 254, \n \"dropout_p\": 0.5147797764915422, \n \"lr\": 0.00034663591528551224 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 369, \n \"num_filters\": 370, \n \"hidden_dim\": 254, \n \"dropout_p\": 0.5147797764915422, \n \"lr\": 0.00034663591528551224, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2896561324596405 \n } \n[01/26/21 18:21:54] INFO Epoch: 1 | train_loss: 0.00639, train.py:146\n val_loss: 0.00480, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:21:57] INFO Epoch: 2 | train_loss: 0.00499, train.py:146\n val_loss: 0.00291, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:21:59] INFO Epoch: 3 | train_loss: 0.00363, train.py:146\n val_loss: 0.00255, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:02] INFO Epoch: 4 | train_loss: 0.00309, train.py:146\n val_loss: 0.00233, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:05] INFO Epoch: 5 | train_loss: 0.00274, train.py:146\n val_loss: 0.00219, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:08] INFO Epoch: 6 | train_loss: 0.00233, train.py:146\n val_loss: 0.00200, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:10] INFO Epoch: 7 | train_loss: 0.00210, train.py:146\n val_loss: 0.00187, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:13] INFO Epoch: 8 | train_loss: 0.00188, train.py:146\n val_loss: 0.00177, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:16] INFO Epoch: 9 | train_loss: 0.00168, train.py:146\n val_loss: 0.00168, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:19] INFO Epoch: 10 | train_loss: 0.00149, train.py:146\n val_loss: 0.00164, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:22] INFO Epoch: 11 | train_loss: 0.00131, train.py:146\n val_loss: 0.00161, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:25] INFO Epoch: 12 | train_loss: 0.00123, train.py:146\n val_loss: 0.00156, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:28] INFO Epoch: 13 | train_loss: 0.00109, train.py:146\n val_loss: 0.00155, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:30] INFO Epoch: 14 | train_loss: 0.00100, train.py:146\n val_loss: 0.00154, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:33] INFO Epoch: 15 | train_loss: 0.00088, train.py:146\n val_loss: 0.00158, lr: 3.47E-04, \n _patience: 9 \n[01/26/21 18:22:36] INFO Epoch: 16 | train_loss: 0.00082, train.py:146\n val_loss: 0.00157, lr: 3.47E-04, \n _patience: 8 \n[01/26/21 18:22:39] INFO Epoch: 17 | train_loss: 0.00076, train.py:146\n val_loss: 0.00153, lr: 3.47E-04, \n _patience: 10 \n[01/26/21 18:22:42] INFO Epoch: 18 | train_loss: 0.00066, train.py:146\n val_loss: 0.00159, lr: 3.47E-04, \n _patience: 9 \n[01/26/21 18:22:45] INFO Epoch: 19 | train_loss: 0.00060, train.py:146\n val_loss: 0.00154, lr: 3.47E-04, \n _patience: 8 \n[01/26/21 18:22:47] INFO Epoch: 20 | train_loss: 0.00054, train.py:146\n val_loss: 0.00160, lr: 3.47E-04, \n _patience: 7 \n[01/26/21 18:22:50] INFO Epoch: 21 | train_loss: 0.00053, train.py:146\n val_loss: 0.00171, lr: 3.47E-04, \n _patience: 6 \n[01/26/21 18:22:53] INFO Epoch: 22 | train_loss: 0.00047, train.py:146\n val_loss: 0.00176, lr: 3.47E-04, \n _patience: 5 \n[01/26/21 18:22:56] INFO Epoch: 23 | train_loss: 0.00045, train.py:146\n val_loss: 0.00176, lr: 1.73E-05, \n _patience: 4 \n[01/26/21 18:22:58] INFO Epoch: 24 | train_loss: 0.00043, train.py:146\n val_loss: 0.00169, lr: 1.73E-05, \n _patience: 3 \n[01/26/21 18:23:01] INFO Epoch: 25 | train_loss: 0.00039, train.py:146\n val_loss: 0.00161, lr: 1.73E-05, \n _patience: 2 \n[01/26/21 18:23:04] INFO Epoch: 26 | train_loss: 0.00038, train.py:146\n val_loss: 0.00159, lr: 1.73E-05, \n _patience: 1 \n[01/26/21 18:23:07] INFO Stopping early! train.py:141\n[01/26/21 18:23:16] INFO { train.py:460\n \"precision\": 0.8331905069720196, \n \"recall\": 0.5538995817628822, \n \"f1\": 0.6350550074805342, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 75: \n INFO { train.py:454\n \"embedding_dim\": 413, \n \"num_filters\": 339, \n \"hidden_dim\": 242, \n \"dropout_p\": 0.47494522221325464, \n \"lr\": 0.000405094092573397 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 413, \n \"num_filters\": 339, \n \"hidden_dim\": 242, \n \"dropout_p\": 0.47494522221325464, \n \"lr\": 0.000405094092573397, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.25233879685401917 \n } \n[01/26/21 18:23:19] INFO Epoch: 1 | train_loss: 0.00631, train.py:146\n val_loss: 0.00487, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:22] INFO Epoch: 2 | train_loss: 0.00473, train.py:146\n val_loss: 0.00265, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:25] INFO Epoch: 3 | train_loss: 0.00344, train.py:146\n val_loss: 0.00246, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:28] INFO Epoch: 4 | train_loss: 0.00291, train.py:146\n val_loss: 0.00229, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:31] INFO Epoch: 5 | train_loss: 0.00248, train.py:146\n val_loss: 0.00205, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:34] INFO Epoch: 6 | train_loss: 0.00218, train.py:146\n val_loss: 0.00189, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:37] INFO Epoch: 7 | train_loss: 0.00188, train.py:146\n val_loss: 0.00178, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:39] INFO Epoch: 8 | train_loss: 0.00161, train.py:146\n val_loss: 0.00169, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:42] INFO Epoch: 9 | train_loss: 0.00145, train.py:146\n val_loss: 0.00164, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:45] INFO Epoch: 10 | train_loss: 0.00134, train.py:146\n val_loss: 0.00162, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:48] INFO Epoch: 11 | train_loss: 0.00116, train.py:146\n val_loss: 0.00160, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:51] INFO Epoch: 12 | train_loss: 0.00105, train.py:146\n val_loss: 0.00160, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:54] INFO Epoch: 13 | train_loss: 0.00092, train.py:146\n val_loss: 0.00159, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:23:57] INFO Epoch: 14 | train_loss: 0.00083, train.py:146\n val_loss: 0.00157, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:24:00] INFO Epoch: 15 | train_loss: 0.00072, train.py:146\n val_loss: 0.00152, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:24:03] INFO Epoch: 16 | train_loss: 0.00065, train.py:146\n val_loss: 0.00151, lr: 4.05E-04, \n _patience: 10 \n[01/26/21 18:24:06] INFO Epoch: 17 | train_loss: 0.00058, train.py:146\n val_loss: 0.00154, lr: 4.05E-04, \n _patience: 9 \n[01/26/21 18:24:09] INFO Epoch: 18 | train_loss: 0.00055, train.py:146\n val_loss: 0.00154, lr: 4.05E-04, \n _patience: 8 \n[01/26/21 18:24:12] INFO Epoch: 19 | train_loss: 0.00050, train.py:146\n val_loss: 0.00167, lr: 4.05E-04, \n _patience: 7 \n[01/26/21 18:24:14] INFO Epoch: 20 | train_loss: 0.00047, train.py:146\n val_loss: 0.00172, lr: 4.05E-04, \n _patience: 6 \n[01/26/21 18:24:17] INFO Epoch: 21 | train_loss: 0.00042, train.py:146\n val_loss: 0.00181, lr: 4.05E-04, \n _patience: 5 \n[01/26/21 18:24:20] INFO Epoch: 22 | train_loss: 0.00038, train.py:146\n val_loss: 0.00188, lr: 2.03E-05, \n _patience: 4 \n[01/26/21 18:24:23] INFO Epoch: 23 | train_loss: 0.00036, train.py:146\n val_loss: 0.00176, lr: 2.03E-05, \n _patience: 3 \n[01/26/21 18:24:26] INFO Epoch: 24 | train_loss: 0.00033, train.py:146\n val_loss: 0.00166, lr: 2.03E-05, \n _patience: 2 \n[01/26/21 18:24:29] INFO Epoch: 25 | train_loss: 0.00031, train.py:146\n val_loss: 0.00165, lr: 2.03E-05, \n _patience: 1 \n[01/26/21 18:24:32] INFO Stopping early! train.py:141\n[01/26/21 18:24:41] INFO { train.py:460\n \"precision\": 0.8308973509338873, \n \"recall\": 0.552328951836341, \n \"f1\": 0.634285511500247, \n \"num_samples\": 476.0 \n } \n[01/26/21 18:24:42] INFO train.py:453\n Trial 76: \n INFO { train.py:454\n \"embedding_dim\": 328, \n \"num_filters\": 392, \n \"hidden_dim\": 309, \n \"dropout_p\": 0.5420223497867113, \n \"lr\": 0.0002933257181196498 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 328, \n \"num_filters\": 392, \n \"hidden_dim\": 309, \n \"dropout_p\": 0.5420223497867113, \n \"lr\": 0.0002933257181196498, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2609623968601227 \n } \n[01/26/21 18:24:44] INFO Epoch: 1 | train_loss: 0.00638, train.py:146\n val_loss: 0.00488, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:24:47] INFO Epoch: 2 | train_loss: 0.00516, train.py:146\n val_loss: 0.00318, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:24:50] INFO Epoch: 3 | train_loss: 0.00371, train.py:146\n val_loss: 0.00255, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:24:52] INFO Epoch: 4 | train_loss: 0.00322, train.py:146\n val_loss: 0.00241, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:24:55] INFO Epoch: 5 | train_loss: 0.00281, train.py:146\n val_loss: 0.00231, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:24:57] INFO Epoch: 6 | train_loss: 0.00253, train.py:146\n val_loss: 0.00213, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:00] INFO Epoch: 7 | train_loss: 0.00232, train.py:146\n val_loss: 0.00200, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:03] INFO Epoch: 8 | train_loss: 0.00203, train.py:146\n val_loss: 0.00189, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:05] INFO Epoch: 9 | train_loss: 0.00183, train.py:146\n val_loss: 0.00178, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:08] INFO Epoch: 10 | train_loss: 0.00167, train.py:146\n val_loss: 0.00171, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:10] INFO Epoch: 11 | train_loss: 0.00153, train.py:146\n val_loss: 0.00167, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:13] INFO Epoch: 12 | train_loss: 0.00137, train.py:146\n val_loss: 0.00162, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:16] INFO Epoch: 13 | train_loss: 0.00127, train.py:146\n val_loss: 0.00159, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:18] INFO Epoch: 14 | train_loss: 0.00115, train.py:146\n val_loss: 0.00159, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:21] INFO Epoch: 15 | train_loss: 0.00106, train.py:146\n val_loss: 0.00157, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:23] INFO Epoch: 16 | train_loss: 0.00094, train.py:146\n val_loss: 0.00155, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:26] INFO Epoch: 17 | train_loss: 0.00090, train.py:146\n val_loss: 0.00154, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:29] INFO Epoch: 18 | train_loss: 0.00081, train.py:146\n val_loss: 0.00154, lr: 2.93E-04, \n _patience: 9 \n[01/26/21 18:25:31] INFO Epoch: 19 | train_loss: 0.00075, train.py:146\n val_loss: 0.00151, lr: 2.93E-04, \n _patience: 10 \n[01/26/21 18:25:34] INFO Epoch: 20 | train_loss: 0.00069, train.py:146\n val_loss: 0.00155, lr: 2.93E-04, \n _patience: 9 \n[01/26/21 18:25:36] INFO Epoch: 21 | train_loss: 0.00063, train.py:146\n val_loss: 0.00161, lr: 2.93E-04, \n _patience: 8 \n[01/26/21 18:25:39] INFO Epoch: 22 | train_loss: 0.00057, train.py:146\n val_loss: 0.00159, lr: 2.93E-04, \n _patience: 7 \n[01/26/21 18:25:42] INFO Epoch: 23 | train_loss: 0.00053, train.py:146\n val_loss: 0.00164, lr: 2.93E-04, \n _patience: 6 \n[01/26/21 18:25:44] INFO Epoch: 24 | train_loss: 0.00049, train.py:146\n val_loss: 0.00166, lr: 2.93E-04, \n _patience: 5 \n[01/26/21 18:25:47] INFO Epoch: 25 | train_loss: 0.00044, train.py:146\n val_loss: 0.00165, lr: 1.47E-05, \n _patience: 4 \n[01/26/21 18:25:49] INFO Epoch: 26 | train_loss: 0.00042, train.py:146\n val_loss: 0.00164, lr: 1.47E-05, \n _patience: 3 \n[01/26/21 18:25:52] INFO Epoch: 27 | train_loss: 0.00041, train.py:146\n val_loss: 0.00161, lr: 1.47E-05, \n _patience: 2 \n[01/26/21 18:25:55] INFO Epoch: 28 | train_loss: 0.00041, train.py:146\n val_loss: 0.00159, lr: 1.47E-05, \n _patience: 1 \n[01/26/21 18:25:57] INFO Stopping early! train.py:141\n[01/26/21 18:26:06] INFO { train.py:460\n \"precision\": 0.7863341579035238, \n \"recall\": 0.5650414391301091, \n \"f1\": 0.6266050419727477, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 77: \n INFO { train.py:454\n \"embedding_dim\": 388, \n \"num_filters\": 460, \n \"hidden_dim\": 332, \n \"dropout_p\": 0.5234034272902796, \n \"lr\": 0.0004623246414899254 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 388, \n \"num_filters\": 460, \n \"hidden_dim\": 332, \n \"dropout_p\": 0.5234034272902796, \n \"lr\": 0.0004623246414899254, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.23703604936599731 \n } \n[01/26/21 18:26:09] INFO Epoch: 1 | train_loss: 0.00821, train.py:146\n val_loss: 0.00590, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:13] INFO Epoch: 2 | train_loss: 0.00575, train.py:146\n val_loss: 0.00290, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:16] INFO Epoch: 3 | train_loss: 0.00361, train.py:146\n val_loss: 0.00260, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:19] INFO Epoch: 4 | train_loss: 0.00305, train.py:146\n val_loss: 0.00248, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:22] INFO Epoch: 5 | train_loss: 0.00270, train.py:146\n val_loss: 0.00219, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:26] INFO Epoch: 6 | train_loss: 0.00230, train.py:146\n val_loss: 0.00201, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:29] INFO Epoch: 7 | train_loss: 0.00200, train.py:146\n val_loss: 0.00181, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:32] INFO Epoch: 8 | train_loss: 0.00177, train.py:146\n val_loss: 0.00172, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:36] INFO Epoch: 9 | train_loss: 0.00152, train.py:146\n val_loss: 0.00165, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:39] INFO Epoch: 10 | train_loss: 0.00132, train.py:146\n val_loss: 0.00161, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:42] INFO Epoch: 11 | train_loss: 0.00119, train.py:146\n val_loss: 0.00161, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:46] INFO Epoch: 12 | train_loss: 0.00103, train.py:146\n val_loss: 0.00159, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:49] INFO Epoch: 13 | train_loss: 0.00092, train.py:146\n val_loss: 0.00158, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:52] INFO Epoch: 14 | train_loss: 0.00079, train.py:146\n val_loss: 0.00155, lr: 4.62E-04, \n _patience: 10 \n[01/26/21 18:26:55] INFO Epoch: 15 | train_loss: 0.00068, train.py:146\n val_loss: 0.00156, lr: 4.62E-04, \n _patience: 9 \n[01/26/21 18:26:59] INFO Epoch: 16 | train_loss: 0.00062, train.py:146\n val_loss: 0.00157, lr: 4.62E-04, \n _patience: 8 \n[01/26/21 18:27:02] INFO Epoch: 17 | train_loss: 0.00058, train.py:146\n val_loss: 0.00158, lr: 4.62E-04, \n _patience: 7 \n[01/26/21 18:27:05] INFO Epoch: 18 | train_loss: 0.00053, train.py:146\n val_loss: 0.00163, lr: 4.62E-04, \n _patience: 6 \n[01/26/21 18:27:09] INFO Epoch: 19 | train_loss: 0.00051, train.py:146\n val_loss: 0.00179, lr: 4.62E-04, \n _patience: 5 \n[01/26/21 18:27:12] INFO Epoch: 20 | train_loss: 0.00045, train.py:146\n val_loss: 0.00204, lr: 2.31E-05, \n _patience: 4 \n[01/26/21 18:27:15] INFO Epoch: 21 | train_loss: 0.00047, train.py:146\n val_loss: 0.00183, lr: 2.31E-05, \n _patience: 3 \n[01/26/21 18:27:19] INFO Epoch: 22 | train_loss: 0.00037, train.py:146\n val_loss: 0.00166, lr: 2.31E-05, \n _patience: 2 \n[01/26/21 18:27:22] INFO Epoch: 23 | train_loss: 0.00035, train.py:146\n val_loss: 0.00164, lr: 2.31E-05, \n _patience: 1 \n[01/26/21 18:27:25] INFO Stopping early! train.py:141\n[01/26/21 18:27:37] INFO { train.py:460\n \"precision\": 0.8331272565536718, \n \"recall\": 0.5526770825416145, \n \"f1\": 0.6375770806736228, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 78: \n INFO { train.py:454\n \"embedding_dim\": 288, \n \"num_filters\": 442, \n \"hidden_dim\": 497, \n \"dropout_p\": 0.5012564793338639, \n \"lr\": 9.476938634107242e-05 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 288, \n \"num_filters\": 442, \n \"hidden_dim\": 497, \n \"dropout_p\": 0.5012564793338639, \n \"lr\": 9.476938634107242e-05, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.31773996353149414 \n } \n[01/26/21 18:27:40] INFO Epoch: 1 | train_loss: 0.00553, train.py:146\n val_loss: 0.00341, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:27:42] INFO Epoch: 2 | train_loss: 0.00412, train.py:146\n val_loss: 0.00358, lr: 9.48E-05, \n _patience: 9 \n[01/26/21 18:27:45] INFO Epoch: 3 | train_loss: 0.00371, train.py:146\n val_loss: 0.00286, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:27:47] INFO Epoch: 4 | train_loss: 0.00319, train.py:146\n val_loss: 0.00256, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:27:50] INFO Epoch: 5 | train_loss: 0.00301, train.py:146\n val_loss: 0.00252, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:27:52] INFO Epoch: 6 | train_loss: 0.00283, train.py:146\n val_loss: 0.00244, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:27:55] INFO Epoch: 7 | train_loss: 0.00272, train.py:146\n val_loss: 0.00240, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:27:57] INFO Epoch: 8 | train_loss: 0.00257, train.py:146\n val_loss: 0.00232, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:00] INFO Epoch: 9 | train_loss: 0.00249, train.py:146\n val_loss: 0.00226, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:02] INFO Epoch: 10 | train_loss: 0.00235, train.py:146\n val_loss: 0.00219, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:05] INFO Epoch: 11 | train_loss: 0.00227, train.py:146\n val_loss: 0.00213, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:07] INFO Epoch: 12 | train_loss: 0.00213, train.py:146\n val_loss: 0.00206, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:09] INFO Epoch: 13 | train_loss: 0.00204, train.py:146\n val_loss: 0.00200, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:12] INFO Epoch: 14 | train_loss: 0.00195, train.py:146\n val_loss: 0.00194, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:14] INFO Epoch: 15 | train_loss: 0.00182, train.py:146\n val_loss: 0.00188, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:17] INFO Epoch: 16 | train_loss: 0.00173, train.py:146\n val_loss: 0.00183, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:19] INFO Epoch: 17 | train_loss: 0.00167, train.py:146\n val_loss: 0.00178, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:22] INFO Epoch: 18 | train_loss: 0.00163, train.py:146\n val_loss: 0.00175, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:24] INFO Epoch: 19 | train_loss: 0.00153, train.py:146\n val_loss: 0.00173, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:27] INFO Epoch: 20 | train_loss: 0.00147, train.py:146\n val_loss: 0.00169, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:29] INFO Epoch: 21 | train_loss: 0.00139, train.py:146\n val_loss: 0.00167, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:32] INFO Epoch: 22 | train_loss: 0.00131, train.py:146\n val_loss: 0.00165, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:34] INFO Epoch: 23 | train_loss: 0.00129, train.py:146\n val_loss: 0.00162, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:37] INFO Epoch: 24 | train_loss: 0.00124, train.py:146\n val_loss: 0.00161, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:39] INFO Epoch: 25 | train_loss: 0.00119, train.py:146\n val_loss: 0.00159, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:42] INFO Epoch: 26 | train_loss: 0.00111, train.py:146\n val_loss: 0.00158, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:44] INFO Epoch: 27 | train_loss: 0.00107, train.py:146\n val_loss: 0.00158, lr: 9.48E-05, \n _patience: 9 \n[01/26/21 18:28:47] INFO Epoch: 28 | train_loss: 0.00103, train.py:146\n val_loss: 0.00155, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:49] INFO Epoch: 29 | train_loss: 0.00102, train.py:146\n val_loss: 0.00155, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:52] INFO Epoch: 30 | train_loss: 0.00094, train.py:146\n val_loss: 0.00154, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:54] INFO Epoch: 31 | train_loss: 0.00089, train.py:146\n val_loss: 0.00155, lr: 9.48E-05, \n _patience: 9 \n[01/26/21 18:28:57] INFO Epoch: 32 | train_loss: 0.00087, train.py:146\n val_loss: 0.00152, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:28:59] INFO Epoch: 33 | train_loss: 0.00083, train.py:146\n val_loss: 0.00152, lr: 9.48E-05, \n _patience: 9 \n[01/26/21 18:29:02] INFO Epoch: 34 | train_loss: 0.00078, train.py:146\n val_loss: 0.00153, lr: 9.48E-05, \n _patience: 8 \n[01/26/21 18:29:04] INFO Epoch: 35 | train_loss: 0.00078, train.py:146\n val_loss: 0.00152, lr: 9.48E-05, \n _patience: 7 \n[01/26/21 18:29:07] INFO Epoch: 36 | train_loss: 0.00074, train.py:146\n val_loss: 0.00154, lr: 9.48E-05, \n _patience: 6 \n[01/26/21 18:29:09] INFO Epoch: 37 | train_loss: 0.00071, train.py:146\n val_loss: 0.00151, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:29:12] INFO Epoch: 38 | train_loss: 0.00067, train.py:146\n val_loss: 0.00152, lr: 9.48E-05, \n _patience: 9 \n[01/26/21 18:29:14] INFO Epoch: 39 | train_loss: 0.00065, train.py:146\n val_loss: 0.00153, lr: 9.48E-05, \n _patience: 8 \n[01/26/21 18:29:17] INFO Epoch: 40 | train_loss: 0.00062, train.py:146\n val_loss: 0.00153, lr: 9.48E-05, \n _patience: 7 \n[01/26/21 18:29:19] INFO Epoch: 41 | train_loss: 0.00059, train.py:146\n val_loss: 0.00150, lr: 9.48E-05, \n _patience: 10 \n[01/26/21 18:29:22] INFO Epoch: 42 | train_loss: 0.00057, train.py:146\n val_loss: 0.00154, lr: 9.48E-05, \n _patience: 9 \n[01/26/21 18:29:24] INFO Epoch: 43 | train_loss: 0.00055, train.py:146\n val_loss: 0.00155, lr: 9.48E-05, \n _patience: 8 \n[01/26/21 18:29:26] INFO Epoch: 44 | train_loss: 0.00052, train.py:146\n val_loss: 0.00153, lr: 9.48E-05, \n _patience: 7 \n[01/26/21 18:29:29] INFO Epoch: 45 | train_loss: 0.00052, train.py:146\n val_loss: 0.00150, lr: 9.48E-05, \n _patience: 6 \n[01/26/21 18:29:31] INFO Epoch: 46 | train_loss: 0.00048, train.py:146\n val_loss: 0.00158, lr: 9.48E-05, \n _patience: 5 \n[01/26/21 18:29:34] INFO Epoch: 47 | train_loss: 0.00047, train.py:146\n val_loss: 0.00154, lr: 4.74E-06, \n _patience: 4 \n[01/26/21 18:29:36] INFO Epoch: 48 | train_loss: 0.00045, train.py:146\n val_loss: 0.00154, lr: 4.74E-06, \n _patience: 3 \n[01/26/21 18:29:39] INFO Epoch: 49 | train_loss: 0.00045, train.py:146\n val_loss: 0.00154, lr: 4.74E-06, \n _patience: 2 \n[01/26/21 18:29:41] INFO Epoch: 50 | train_loss: 0.00045, train.py:146\n val_loss: 0.00154, lr: 4.74E-06, \n _patience: 1 \n[01/26/21 18:29:44] INFO Stopping early! train.py:141\n[01/26/21 18:29:52] INFO { train.py:460\n \"precision\": 0.7975119423833125, \n \"recall\": 0.5377621609826044, \n \"f1\": 0.6090434649197274, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 79: \n INFO { train.py:454\n \"embedding_dim\": 277, \n \"num_filters\": 404, \n \"hidden_dim\": 374, \n \"dropout_p\": 0.5639550539961422, \n \"lr\": 0.000430492916383215 \n } \n[01/26/21 18:29:53] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 277, \n \"num_filters\": 404, \n \"hidden_dim\": 374, \n \"dropout_p\": 0.5639550539961422, \n \"lr\": 0.000430492916383215, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2920498251914978 \n } \n[01/26/21 18:29:55] INFO Epoch: 1 | train_loss: 0.00747, train.py:146\n val_loss: 0.00557, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:29:57] INFO Epoch: 2 | train_loss: 0.00549, train.py:146\n val_loss: 0.00291, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:00] INFO Epoch: 3 | train_loss: 0.00378, train.py:146\n val_loss: 0.00258, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:02] INFO Epoch: 4 | train_loss: 0.00319, train.py:146\n val_loss: 0.00248, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:04] INFO Epoch: 5 | train_loss: 0.00278, train.py:146\n val_loss: 0.00230, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:07] INFO Epoch: 6 | train_loss: 0.00242, train.py:146\n val_loss: 0.00210, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:09] INFO Epoch: 7 | train_loss: 0.00216, train.py:146\n val_loss: 0.00194, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:11] INFO Epoch: 8 | train_loss: 0.00193, train.py:146\n val_loss: 0.00181, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:14] INFO Epoch: 9 | train_loss: 0.00169, train.py:146\n val_loss: 0.00173, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:16] INFO Epoch: 10 | train_loss: 0.00150, train.py:146\n val_loss: 0.00167, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:18] INFO Epoch: 11 | train_loss: 0.00138, train.py:146\n val_loss: 0.00161, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:21] INFO Epoch: 12 | train_loss: 0.00120, train.py:146\n val_loss: 0.00161, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:23] INFO Epoch: 13 | train_loss: 0.00108, train.py:146\n val_loss: 0.00158, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:25] INFO Epoch: 14 | train_loss: 0.00095, train.py:146\n val_loss: 0.00154, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:28] INFO Epoch: 15 | train_loss: 0.00087, train.py:146\n val_loss: 0.00153, lr: 4.30E-04, \n _patience: 10 \n[01/26/21 18:30:30] INFO Epoch: 16 | train_loss: 0.00077, train.py:146\n val_loss: 0.00157, lr: 4.30E-04, \n _patience: 9 \n[01/26/21 18:30:32] INFO Epoch: 17 | train_loss: 0.00069, train.py:146\n val_loss: 0.00159, lr: 4.30E-04, \n _patience: 8 \n[01/26/21 18:30:35] INFO Epoch: 18 | train_loss: 0.00061, train.py:146\n val_loss: 0.00166, lr: 4.30E-04, \n _patience: 7 \n[01/26/21 18:30:37] INFO Epoch: 19 | train_loss: 0.00055, train.py:146\n val_loss: 0.00162, lr: 4.30E-04, \n _patience: 6 \n[01/26/21 18:30:39] INFO Epoch: 20 | train_loss: 0.00051, train.py:146\n val_loss: 0.00160, lr: 4.30E-04, \n _patience: 5 \n[01/26/21 18:30:42] INFO Epoch: 21 | train_loss: 0.00045, train.py:146\n val_loss: 0.00161, lr: 2.15E-05, \n _patience: 4 \n[01/26/21 18:30:44] INFO Epoch: 22 | train_loss: 0.00041, train.py:146\n val_loss: 0.00164, lr: 2.15E-05, \n _patience: 3 \n[01/26/21 18:30:46] INFO Epoch: 23 | train_loss: 0.00039, train.py:146\n val_loss: 0.00168, lr: 2.15E-05, \n _patience: 2 \n[01/26/21 18:30:49] INFO Epoch: 24 | train_loss: 0.00040, train.py:146\n val_loss: 0.00167, lr: 2.15E-05, \n _patience: 1 \n[01/26/21 18:30:51] INFO Stopping early! train.py:141\n[01/26/21 18:30:59] INFO { train.py:460\n \"precision\": 0.8070025212882357, \n \"recall\": 0.5202753935081521, \n \"f1\": 0.6001594675634555, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 80: \n INFO { train.py:454\n \"embedding_dim\": 349, \n \"num_filters\": 417, \n \"hidden_dim\": 264, \n \"dropout_p\": 0.43841328407881885, \n \"lr\": 5.340906211871656e-05 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 349, \n \"num_filters\": 417, \n \"hidden_dim\": 264, \n \"dropout_p\": 0.43841328407881885, \n \"lr\": 5.340906211871656e-05, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.30309101939201355 \n } \n[01/26/21 18:31:02] INFO Epoch: 1 | train_loss: 0.00636, train.py:146\n val_loss: 0.00275, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:05] INFO Epoch: 2 | train_loss: 0.00345, train.py:146\n val_loss: 0.00300, lr: 5.34E-05, \n _patience: 9 \n[01/26/21 18:31:08] INFO Epoch: 3 | train_loss: 0.00350, train.py:146\n val_loss: 0.00300, lr: 5.34E-05, \n _patience: 8 \n[01/26/21 18:31:11] INFO Epoch: 4 | train_loss: 0.00344, train.py:146\n val_loss: 0.00275, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:13] INFO Epoch: 5 | train_loss: 0.00308, train.py:146\n val_loss: 0.00257, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:16] INFO Epoch: 6 | train_loss: 0.00298, train.py:146\n val_loss: 0.00252, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:19] INFO Epoch: 7 | train_loss: 0.00286, train.py:146\n val_loss: 0.00248, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:22] INFO Epoch: 8 | train_loss: 0.00282, train.py:146\n val_loss: 0.00244, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:25] INFO Epoch: 9 | train_loss: 0.00271, train.py:146\n val_loss: 0.00240, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:28] INFO Epoch: 10 | train_loss: 0.00265, train.py:146\n val_loss: 0.00237, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:31] INFO Epoch: 11 | train_loss: 0.00260, train.py:146\n val_loss: 0.00233, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:34] INFO Epoch: 12 | train_loss: 0.00253, train.py:146\n val_loss: 0.00228, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:37] INFO Epoch: 13 | train_loss: 0.00244, train.py:146\n val_loss: 0.00224, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:39] INFO Epoch: 14 | train_loss: 0.00240, train.py:146\n val_loss: 0.00220, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:42] INFO Epoch: 15 | train_loss: 0.00230, train.py:146\n val_loss: 0.00216, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:45] INFO Epoch: 16 | train_loss: 0.00225, train.py:146\n val_loss: 0.00212, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:48] INFO Epoch: 17 | train_loss: 0.00219, train.py:146\n val_loss: 0.00208, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:51] INFO Epoch: 18 | train_loss: 0.00213, train.py:146\n val_loss: 0.00204, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:54] INFO Epoch: 19 | train_loss: 0.00205, train.py:146\n val_loss: 0.00200, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:31:57] INFO Epoch: 20 | train_loss: 0.00198, train.py:146\n val_loss: 0.00197, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:00] INFO Epoch: 21 | train_loss: 0.00193, train.py:146\n val_loss: 0.00193, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:03] INFO Epoch: 22 | train_loss: 0.00189, train.py:146\n val_loss: 0.00190, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:06] INFO Epoch: 23 | train_loss: 0.00182, train.py:146\n val_loss: 0.00187, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:09] INFO Epoch: 24 | train_loss: 0.00175, train.py:146\n val_loss: 0.00185, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:12] INFO Epoch: 25 | train_loss: 0.00171, train.py:146\n val_loss: 0.00182, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:14] INFO Epoch: 26 | train_loss: 0.00167, train.py:146\n val_loss: 0.00179, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:17] INFO Epoch: 27 | train_loss: 0.00162, train.py:146\n val_loss: 0.00177, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:20] INFO Epoch: 28 | train_loss: 0.00159, train.py:146\n val_loss: 0.00175, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:23] INFO Epoch: 29 | train_loss: 0.00154, train.py:146\n val_loss: 0.00173, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:26] INFO Epoch: 30 | train_loss: 0.00150, train.py:146\n val_loss: 0.00172, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:29] INFO Epoch: 31 | train_loss: 0.00145, train.py:146\n val_loss: 0.00170, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:32] INFO Epoch: 32 | train_loss: 0.00144, train.py:146\n val_loss: 0.00168, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:35] INFO Epoch: 33 | train_loss: 0.00140, train.py:146\n val_loss: 0.00167, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:38] INFO Epoch: 34 | train_loss: 0.00135, train.py:146\n val_loss: 0.00166, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:41] INFO Epoch: 35 | train_loss: 0.00132, train.py:146\n val_loss: 0.00164, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:44] INFO Epoch: 36 | train_loss: 0.00128, train.py:146\n val_loss: 0.00164, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:47] INFO Epoch: 37 | train_loss: 0.00126, train.py:146\n val_loss: 0.00163, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:50] INFO Epoch: 38 | train_loss: 0.00121, train.py:146\n val_loss: 0.00161, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:52] INFO Epoch: 39 | train_loss: 0.00120, train.py:146\n val_loss: 0.00161, lr: 5.34E-05, \n _patience: 9 \n[01/26/21 18:32:55] INFO Epoch: 40 | train_loss: 0.00114, train.py:146\n val_loss: 0.00160, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:32:58] INFO Epoch: 41 | train_loss: 0.00112, train.py:146\n val_loss: 0.00159, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:01] INFO Epoch: 42 | train_loss: 0.00113, train.py:146\n val_loss: 0.00157, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:04] INFO Epoch: 43 | train_loss: 0.00107, train.py:146\n val_loss: 0.00158, lr: 5.34E-05, \n _patience: 9 \n[01/26/21 18:33:07] INFO Epoch: 44 | train_loss: 0.00106, train.py:146\n val_loss: 0.00156, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:10] INFO Epoch: 45 | train_loss: 0.00103, train.py:146\n val_loss: 0.00156, lr: 5.34E-05, \n _patience: 9 \n[01/26/21 18:33:13] INFO Epoch: 46 | train_loss: 0.00100, train.py:146\n val_loss: 0.00156, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:16] INFO Epoch: 47 | train_loss: 0.00096, train.py:146\n val_loss: 0.00156, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:19] INFO Epoch: 48 | train_loss: 0.00096, train.py:146\n val_loss: 0.00155, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:22] INFO Epoch: 49 | train_loss: 0.00094, train.py:146\n val_loss: 0.00154, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:25] INFO Epoch: 50 | train_loss: 0.00091, train.py:146\n val_loss: 0.00154, lr: 5.34E-05, \n _patience: 9 \n[01/26/21 18:33:28] INFO Epoch: 51 | train_loss: 0.00090, train.py:146\n val_loss: 0.00152, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:31] INFO Epoch: 52 | train_loss: 0.00088, train.py:146\n val_loss: 0.00154, lr: 5.34E-05, \n _patience: 9 \n[01/26/21 18:33:34] INFO Epoch: 53 | train_loss: 0.00084, train.py:146\n val_loss: 0.00153, lr: 5.34E-05, \n _patience: 8 \n[01/26/21 18:33:37] INFO Epoch: 54 | train_loss: 0.00082, train.py:146\n val_loss: 0.00154, lr: 5.34E-05, \n _patience: 7 \n[01/26/21 18:33:39] INFO Epoch: 55 | train_loss: 0.00081, train.py:146\n val_loss: 0.00151, lr: 5.34E-05, \n _patience: 10 \n[01/26/21 18:33:42] INFO Epoch: 56 | train_loss: 0.00079, train.py:146\n val_loss: 0.00154, lr: 5.34E-05, \n _patience: 9 \n[01/26/21 18:33:45] INFO Epoch: 57 | train_loss: 0.00076, train.py:146\n val_loss: 0.00152, lr: 5.34E-05, \n _patience: 8 \n[01/26/21 18:33:48] INFO Epoch: 58 | train_loss: 0.00074, train.py:146\n val_loss: 0.00152, lr: 5.34E-05, \n _patience: 7 \n[01/26/21 18:33:51] INFO Epoch: 59 | train_loss: 0.00073, train.py:146\n val_loss: 0.00154, lr: 5.34E-05, \n _patience: 6 \n[01/26/21 18:33:54] INFO Epoch: 60 | train_loss: 0.00069, train.py:146\n val_loss: 0.00152, lr: 5.34E-05, \n _patience: 5 \n[01/26/21 18:33:57] INFO Epoch: 61 | train_loss: 0.00068, train.py:146\n val_loss: 0.00153, lr: 2.67E-06, \n _patience: 4 \n[01/26/21 18:34:00] INFO Epoch: 62 | train_loss: 0.00069, train.py:146\n val_loss: 0.00152, lr: 2.67E-06, \n _patience: 3 \n[01/26/21 18:34:03] INFO Epoch: 63 | train_loss: 0.00069, train.py:146\n val_loss: 0.00152, lr: 2.67E-06, \n _patience: 2 \n[01/26/21 18:34:06] INFO Epoch: 64 | train_loss: 0.00066, train.py:146\n val_loss: 0.00152, lr: 2.67E-06, \n _patience: 1 \n[01/26/21 18:34:09] INFO Stopping early! train.py:141\n[01/26/21 18:34:19] INFO { train.py:460\n \"precision\": 0.7790324811313116, \n \"recall\": 0.5005698197077507, \n \"f1\": 0.5796788219864949, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 81: \n INFO { train.py:454\n \"embedding_dim\": 341, \n \"num_filters\": 434, \n \"hidden_dim\": 483, \n \"dropout_p\": 0.5432894746320721, \n \"lr\": 0.00033614579991995876 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 341, \n \"num_filters\": 434, \n \"hidden_dim\": 483, \n \"dropout_p\": 0.5432894746320721, \n \"lr\": 0.00033614579991995876, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2996252477169037 \n } \n[01/26/21 18:34:22] INFO Epoch: 1 | train_loss: 0.00714, train.py:146\n val_loss: 0.00535, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:25] INFO Epoch: 2 | train_loss: 0.00543, train.py:146\n val_loss: 0.00303, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:28] INFO Epoch: 3 | train_loss: 0.00367, train.py:146\n val_loss: 0.00253, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:31] INFO Epoch: 4 | train_loss: 0.00302, train.py:146\n val_loss: 0.00242, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:34] INFO Epoch: 5 | train_loss: 0.00263, train.py:146\n val_loss: 0.00225, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:37] INFO Epoch: 6 | train_loss: 0.00232, train.py:146\n val_loss: 0.00206, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:40] INFO Epoch: 7 | train_loss: 0.00204, train.py:146\n val_loss: 0.00189, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:43] INFO Epoch: 8 | train_loss: 0.00182, train.py:146\n val_loss: 0.00177, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:46] INFO Epoch: 9 | train_loss: 0.00162, train.py:146\n val_loss: 0.00168, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:49] INFO Epoch: 10 | train_loss: 0.00143, train.py:146\n val_loss: 0.00162, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:52] INFO Epoch: 11 | train_loss: 0.00126, train.py:146\n val_loss: 0.00159, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:34:55] INFO Epoch: 12 | train_loss: 0.00112, train.py:146\n val_loss: 0.00159, lr: 3.36E-04, \n _patience: 9 \n[01/26/21 18:34:58] INFO Epoch: 13 | train_loss: 0.00101, train.py:146\n val_loss: 0.00153, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:35:01] INFO Epoch: 14 | train_loss: 0.00092, train.py:146\n val_loss: 0.00154, lr: 3.36E-04, \n _patience: 9 \n[01/26/21 18:35:04] INFO Epoch: 15 | train_loss: 0.00082, train.py:146\n val_loss: 0.00153, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:35:07] INFO Epoch: 16 | train_loss: 0.00071, train.py:146\n val_loss: 0.00151, lr: 3.36E-04, \n _patience: 10 \n[01/26/21 18:35:10] INFO Epoch: 17 | train_loss: 0.00062, train.py:146\n val_loss: 0.00157, lr: 3.36E-04, \n _patience: 9 \n[01/26/21 18:35:13] INFO Epoch: 18 | train_loss: 0.00056, train.py:146\n val_loss: 0.00156, lr: 3.36E-04, \n _patience: 8 \n[01/26/21 18:35:16] INFO Epoch: 19 | train_loss: 0.00052, train.py:146\n val_loss: 0.00156, lr: 3.36E-04, \n _patience: 7 \n[01/26/21 18:35:19] INFO Epoch: 20 | train_loss: 0.00046, train.py:146\n val_loss: 0.00154, lr: 3.36E-04, \n _patience: 6 \n[01/26/21 18:35:22] INFO Epoch: 21 | train_loss: 0.00041, train.py:146\n val_loss: 0.00164, lr: 3.36E-04, \n _patience: 5 \n[01/26/21 18:35:25] INFO Epoch: 22 | train_loss: 0.00037, train.py:146\n val_loss: 0.00166, lr: 1.68E-05, \n _patience: 4 \n[01/26/21 18:35:28] INFO Epoch: 23 | train_loss: 0.00034, train.py:146\n val_loss: 0.00164, lr: 1.68E-05, \n _patience: 3 \n[01/26/21 18:35:31] INFO Epoch: 24 | train_loss: 0.00033, train.py:146\n val_loss: 0.00162, lr: 1.68E-05, \n _patience: 2 \n[01/26/21 18:35:34] INFO Epoch: 25 | train_loss: 0.00031, train.py:146\n val_loss: 0.00161, lr: 1.68E-05, \n _patience: 1 \n[01/26/21 18:35:37] INFO Stopping early! train.py:141\n[01/26/21 18:35:47] INFO { train.py:460\n \"precision\": 0.8100887638420241, \n \"recall\": 0.5522686235494118, \n \"f1\": 0.6295506839421037, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 82: \n INFO { train.py:454\n \"embedding_dim\": 363, \n \"num_filters\": 438, \n \"hidden_dim\": 476, \n \"dropout_p\": 0.5285180801454178, \n \"lr\": 0.00036515582090591495 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 363, \n \"num_filters\": 438, \n \"hidden_dim\": 476, \n \"dropout_p\": 0.5285180801454178, \n \"lr\": 0.00036515582090591495, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2847495377063751 \n } \n[01/26/21 18:35:50] INFO Epoch: 1 | train_loss: 0.00712, train.py:146\n val_loss: 0.00527, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:35:53] INFO Epoch: 2 | train_loss: 0.00512, train.py:146\n val_loss: 0.00282, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:35:56] INFO Epoch: 3 | train_loss: 0.00355, train.py:146\n val_loss: 0.00251, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:35:59] INFO Epoch: 4 | train_loss: 0.00295, train.py:146\n val_loss: 0.00240, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:02] INFO Epoch: 5 | train_loss: 0.00260, train.py:146\n val_loss: 0.00216, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:05] INFO Epoch: 6 | train_loss: 0.00221, train.py:146\n val_loss: 0.00197, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:08] INFO Epoch: 7 | train_loss: 0.00194, train.py:146\n val_loss: 0.00183, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:12] INFO Epoch: 8 | train_loss: 0.00170, train.py:146\n val_loss: 0.00170, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:15] INFO Epoch: 9 | train_loss: 0.00147, train.py:146\n val_loss: 0.00164, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:18] INFO Epoch: 10 | train_loss: 0.00133, train.py:146\n val_loss: 0.00161, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:21] INFO Epoch: 11 | train_loss: 0.00115, train.py:146\n val_loss: 0.00157, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:25] INFO Epoch: 12 | train_loss: 0.00103, train.py:146\n val_loss: 0.00155, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:28] INFO Epoch: 13 | train_loss: 0.00090, train.py:146\n val_loss: 0.00155, lr: 3.65E-04, \n _patience: 9 \n[01/26/21 18:36:31] INFO Epoch: 14 | train_loss: 0.00079, train.py:146\n val_loss: 0.00153, lr: 3.65E-04, \n _patience: 10 \n[01/26/21 18:36:34] INFO Epoch: 15 | train_loss: 0.00068, train.py:146\n val_loss: 0.00155, lr: 3.65E-04, \n _patience: 9 \n[01/26/21 18:36:38] INFO Epoch: 16 | train_loss: 0.00060, train.py:146\n val_loss: 0.00159, lr: 3.65E-04, \n _patience: 8 \n[01/26/21 18:36:41] INFO Epoch: 17 | train_loss: 0.00053, train.py:146\n val_loss: 0.00163, lr: 3.65E-04, \n _patience: 7 \n[01/26/21 18:36:44] INFO Epoch: 18 | train_loss: 0.00047, train.py:146\n val_loss: 0.00161, lr: 3.65E-04, \n _patience: 6 \n[01/26/21 18:36:47] INFO Epoch: 19 | train_loss: 0.00041, train.py:146\n val_loss: 0.00162, lr: 3.65E-04, \n _patience: 5 \n[01/26/21 18:36:50] INFO Epoch: 20 | train_loss: 0.00038, train.py:146\n val_loss: 0.00165, lr: 1.83E-05, \n _patience: 4 \n[01/26/21 18:36:53] INFO Epoch: 21 | train_loss: 0.00033, train.py:146\n val_loss: 0.00164, lr: 1.83E-05, \n _patience: 3 \n[01/26/21 18:36:56] INFO Epoch: 22 | train_loss: 0.00032, train.py:146\n val_loss: 0.00163, lr: 1.83E-05, \n _patience: 2 \n[01/26/21 18:37:00] INFO Epoch: 23 | train_loss: 0.00032, train.py:146\n val_loss: 0.00163, lr: 1.83E-05, \n _patience: 1 \n[01/26/21 18:37:03] INFO Stopping early! train.py:141\n[01/26/21 18:37:13] INFO { train.py:460\n \"precision\": 0.8081712162178847, \n \"recall\": 0.5568306570277014, \n \"f1\": 0.6275363325234221, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 83: \n INFO { train.py:454\n \"embedding_dim\": 311, \n \"num_filters\": 454, \n \"hidden_dim\": 458, \n \"dropout_p\": 0.5518118210042028, \n \"lr\": 0.00031680832439600617 \n } \n[01/26/21 18:37:14] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 311, \n \"num_filters\": 454, \n \"hidden_dim\": 458, \n \"dropout_p\": 0.5518118210042028, \n \"lr\": 0.00031680832439600617, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2726909816265106 \n } \n[01/26/21 18:37:16] INFO Epoch: 1 | train_loss: 0.00727, train.py:146\n val_loss: 0.00585, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:19] INFO Epoch: 2 | train_loss: 0.00552, train.py:146\n val_loss: 0.00308, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:22] INFO Epoch: 3 | train_loss: 0.00383, train.py:146\n val_loss: 0.00256, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:25] INFO Epoch: 4 | train_loss: 0.00311, train.py:146\n val_loss: 0.00245, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:27] INFO Epoch: 5 | train_loss: 0.00278, train.py:146\n val_loss: 0.00231, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:30] INFO Epoch: 6 | train_loss: 0.00248, train.py:146\n val_loss: 0.00213, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:33] INFO Epoch: 7 | train_loss: 0.00214, train.py:146\n val_loss: 0.00197, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:36] INFO Epoch: 8 | train_loss: 0.00192, train.py:146\n val_loss: 0.00185, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:39] INFO Epoch: 9 | train_loss: 0.00174, train.py:146\n val_loss: 0.00175, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:42] INFO Epoch: 10 | train_loss: 0.00155, train.py:146\n val_loss: 0.00169, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:45] INFO Epoch: 11 | train_loss: 0.00139, train.py:146\n val_loss: 0.00163, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:47] INFO Epoch: 12 | train_loss: 0.00127, train.py:146\n val_loss: 0.00161, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:50] INFO Epoch: 13 | train_loss: 0.00114, train.py:146\n val_loss: 0.00156, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:53] INFO Epoch: 14 | train_loss: 0.00102, train.py:146\n val_loss: 0.00154, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:37:56] INFO Epoch: 15 | train_loss: 0.00089, train.py:146\n val_loss: 0.00155, lr: 3.17E-04, \n _patience: 9 \n[01/26/21 18:37:59] INFO Epoch: 16 | train_loss: 0.00080, train.py:146\n val_loss: 0.00156, lr: 3.17E-04, \n _patience: 8 \n[01/26/21 18:38:02] INFO Epoch: 17 | train_loss: 0.00073, train.py:146\n val_loss: 0.00156, lr: 3.17E-04, \n _patience: 7 \n[01/26/21 18:38:05] INFO Epoch: 18 | train_loss: 0.00068, train.py:146\n val_loss: 0.00153, lr: 3.17E-04, \n _patience: 10 \n[01/26/21 18:38:08] INFO Epoch: 19 | train_loss: 0.00059, train.py:146\n val_loss: 0.00159, lr: 3.17E-04, \n _patience: 9 \n[01/26/21 18:38:11] INFO Epoch: 20 | train_loss: 0.00054, train.py:146\n val_loss: 0.00158, lr: 3.17E-04, \n _patience: 8 \n[01/26/21 18:38:14] INFO Epoch: 21 | train_loss: 0.00049, train.py:146\n val_loss: 0.00161, lr: 3.17E-04, \n _patience: 7 \n[01/26/21 18:38:16] INFO Epoch: 22 | train_loss: 0.00045, train.py:146\n val_loss: 0.00162, lr: 3.17E-04, \n _patience: 6 \n[01/26/21 18:38:19] INFO Epoch: 23 | train_loss: 0.00042, train.py:146\n val_loss: 0.00161, lr: 3.17E-04, \n _patience: 5 \n[01/26/21 18:38:22] INFO Epoch: 24 | train_loss: 0.00037, train.py:146\n val_loss: 0.00164, lr: 1.58E-05, \n _patience: 4 \n[01/26/21 18:38:25] INFO Epoch: 25 | train_loss: 0.00034, train.py:146\n val_loss: 0.00164, lr: 1.58E-05, \n _patience: 3 \n[01/26/21 18:38:28] INFO Epoch: 26 | train_loss: 0.00034, train.py:146\n val_loss: 0.00163, lr: 1.58E-05, \n _patience: 2 \n[01/26/21 18:38:31] INFO Epoch: 27 | train_loss: 0.00032, train.py:146\n val_loss: 0.00163, lr: 1.58E-05, \n _patience: 1 \n[01/26/21 18:38:33] INFO Stopping early! train.py:141\n[01/26/21 18:38:43] INFO { train.py:460\n \"precision\": 0.8342805907566895, \n \"recall\": 0.5295818938860811, \n \"f1\": 0.6191130421967106, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 84: \n INFO { train.py:454\n \"embedding_dim\": 331, \n \"num_filters\": 487, \n \"hidden_dim\": 493, \n \"dropout_p\": 0.4968056461773721, \n \"lr\": 0.0003429701889083903 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 331, \n \"num_filters\": 487, \n \"hidden_dim\": 493, \n \"dropout_p\": 0.4968056461773721, \n \"lr\": 0.0003429701889083903, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.31639382243156433 \n } \n[01/26/21 18:38:46] INFO Epoch: 1 | train_loss: 0.00726, train.py:146\n val_loss: 0.00537, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:38:49] INFO Epoch: 2 | train_loss: 0.00519, train.py:146\n val_loss: 0.00292, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:38:52] INFO Epoch: 3 | train_loss: 0.00358, train.py:146\n val_loss: 0.00251, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:38:55] INFO Epoch: 4 | train_loss: 0.00285, train.py:146\n val_loss: 0.00239, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:38:59] INFO Epoch: 5 | train_loss: 0.00253, train.py:146\n val_loss: 0.00215, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:02] INFO Epoch: 6 | train_loss: 0.00217, train.py:146\n val_loss: 0.00194, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:05] INFO Epoch: 7 | train_loss: 0.00189, train.py:146\n val_loss: 0.00181, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:08] INFO Epoch: 8 | train_loss: 0.00167, train.py:146\n val_loss: 0.00171, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:11] INFO Epoch: 9 | train_loss: 0.00146, train.py:146\n val_loss: 0.00165, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:14] INFO Epoch: 10 | train_loss: 0.00130, train.py:146\n val_loss: 0.00160, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:17] INFO Epoch: 11 | train_loss: 0.00114, train.py:146\n val_loss: 0.00157, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:21] INFO Epoch: 12 | train_loss: 0.00100, train.py:146\n val_loss: 0.00155, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:24] INFO Epoch: 13 | train_loss: 0.00088, train.py:146\n val_loss: 0.00153, lr: 3.43E-04, \n _patience: 10 \n[01/26/21 18:39:27] INFO Epoch: 14 | train_loss: 0.00082, train.py:146\n val_loss: 0.00154, lr: 3.43E-04, \n _patience: 9 \n[01/26/21 18:39:30] INFO Epoch: 15 | train_loss: 0.00069, train.py:146\n val_loss: 0.00155, lr: 3.43E-04, \n _patience: 8 \n[01/26/21 18:39:33] INFO Epoch: 16 | train_loss: 0.00061, train.py:146\n val_loss: 0.00160, lr: 3.43E-04, \n _patience: 7 \n[01/26/21 18:39:36] INFO Epoch: 17 | train_loss: 0.00052, train.py:146\n val_loss: 0.00158, lr: 3.43E-04, \n _patience: 6 \n[01/26/21 18:39:40] INFO Epoch: 18 | train_loss: 0.00047, train.py:146\n val_loss: 0.00162, lr: 3.43E-04, \n _patience: 5 \n[01/26/21 18:39:43] INFO Epoch: 19 | train_loss: 0.00042, train.py:146\n val_loss: 0.00158, lr: 1.71E-05, \n _patience: 4 \n[01/26/21 18:39:46] INFO Epoch: 20 | train_loss: 0.00037, train.py:146\n val_loss: 0.00159, lr: 1.71E-05, \n _patience: 3 \n[01/26/21 18:39:49] INFO Epoch: 21 | train_loss: 0.00037, train.py:146\n val_loss: 0.00161, lr: 1.71E-05, \n _patience: 2 \n[01/26/21 18:39:52] INFO Epoch: 22 | train_loss: 0.00036, train.py:146\n val_loss: 0.00162, lr: 1.71E-05, \n _patience: 1 \n[01/26/21 18:39:55] INFO Stopping early! train.py:141\n[01/26/21 18:40:06] INFO { train.py:460\n \"precision\": 0.7975094280136298, \n \"recall\": 0.5614830250482962, \n \"f1\": 0.6317559594357111, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 85: \n INFO { train.py:454\n \"embedding_dim\": 345, \n \"num_filters\": 423, \n \"hidden_dim\": 294, \n \"dropout_p\": 0.6030643499536257, \n \"lr\": 0.0002574778622365341 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 345, \n \"num_filters\": 423, \n \"hidden_dim\": 294, \n \"dropout_p\": 0.6030643499536257, \n \"lr\": 0.0002574778622365341, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.27456000447273254 \n } \n[01/26/21 18:40:09] INFO Epoch: 1 | train_loss: 0.00625, train.py:146\n val_loss: 0.00473, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:12] INFO Epoch: 2 | train_loss: 0.00516, train.py:146\n val_loss: 0.00321, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:15] INFO Epoch: 3 | train_loss: 0.00383, train.py:146\n val_loss: 0.00252, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:18] INFO Epoch: 4 | train_loss: 0.00333, train.py:146\n val_loss: 0.00238, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:21] INFO Epoch: 5 | train_loss: 0.00292, train.py:146\n val_loss: 0.00228, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:24] INFO Epoch: 6 | train_loss: 0.00262, train.py:146\n val_loss: 0.00210, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:27] INFO Epoch: 7 | train_loss: 0.00238, train.py:146\n val_loss: 0.00197, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:29] INFO Epoch: 8 | train_loss: 0.00210, train.py:146\n val_loss: 0.00186, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:32] INFO Epoch: 9 | train_loss: 0.00195, train.py:146\n val_loss: 0.00177, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:35] INFO Epoch: 10 | train_loss: 0.00178, train.py:146\n val_loss: 0.00173, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:38] INFO Epoch: 11 | train_loss: 0.00165, train.py:146\n val_loss: 0.00166, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:41] INFO Epoch: 12 | train_loss: 0.00152, train.py:146\n val_loss: 0.00164, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:44] INFO Epoch: 13 | train_loss: 0.00139, train.py:146\n val_loss: 0.00161, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:47] INFO Epoch: 14 | train_loss: 0.00128, train.py:146\n val_loss: 0.00157, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:50] INFO Epoch: 15 | train_loss: 0.00119, train.py:146\n val_loss: 0.00155, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:53] INFO Epoch: 16 | train_loss: 0.00110, train.py:146\n val_loss: 0.00153, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:56] INFO Epoch: 17 | train_loss: 0.00103, train.py:146\n val_loss: 0.00151, lr: 2.57E-04, \n _patience: 10 \n[01/26/21 18:40:59] INFO Epoch: 18 | train_loss: 0.00097, train.py:146\n val_loss: 0.00152, lr: 2.57E-04, \n _patience: 9 \n[01/26/21 18:41:01] INFO Epoch: 19 | train_loss: 0.00086, train.py:146\n val_loss: 0.00155, lr: 2.57E-04, \n _patience: 8 \n[01/26/21 18:41:04] INFO Epoch: 20 | train_loss: 0.00080, train.py:146\n val_loss: 0.00152, lr: 2.57E-04, \n _patience: 7 \n[01/26/21 18:41:07] INFO Epoch: 21 | train_loss: 0.00077, train.py:146\n val_loss: 0.00152, lr: 2.57E-04, \n _patience: 6 \n[01/26/21 18:41:10] INFO Epoch: 22 | train_loss: 0.00070, train.py:146\n val_loss: 0.00156, lr: 2.57E-04, \n _patience: 5 \n[01/26/21 18:41:13] INFO Epoch: 23 | train_loss: 0.00066, train.py:146\n val_loss: 0.00157, lr: 1.29E-05, \n _patience: 4 \n[01/26/21 18:41:16] INFO Epoch: 24 | train_loss: 0.00061, train.py:146\n val_loss: 0.00156, lr: 1.29E-05, \n _patience: 3 \n[01/26/21 18:41:19] INFO Epoch: 25 | train_loss: 0.00059, train.py:146\n val_loss: 0.00155, lr: 1.29E-05, \n _patience: 2 \n[01/26/21 18:41:22] INFO Epoch: 26 | train_loss: 0.00059, train.py:146\n val_loss: 0.00155, lr: 1.29E-05, \n _patience: 1 \n[01/26/21 18:41:25] INFO Stopping early! train.py:141\n[01/26/21 18:41:35] INFO { train.py:460\n \"precision\": 0.8078827660171933, \n \"recall\": 0.5349694991197453, \n \"f1\": 0.6109311822387716, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 86: \n INFO { train.py:454\n \"embedding_dim\": 265, \n \"num_filters\": 364, \n \"hidden_dim\": 423, \n \"dropout_p\": 0.6224357504996898, \n \"lr\": 0.0002921528275756848 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 265, \n \"num_filters\": 364, \n \"hidden_dim\": 423, \n \"dropout_p\": 0.6224357504996898, \n \"lr\": 0.0002921528275756848, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2556745707988739 \n } \n[01/26/21 18:41:37] INFO Epoch: 1 | train_loss: 0.00618, train.py:146\n val_loss: 0.00498, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:39] INFO Epoch: 2 | train_loss: 0.00508, train.py:146\n val_loss: 0.00306, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:41] INFO Epoch: 3 | train_loss: 0.00385, train.py:146\n val_loss: 0.00257, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:43] INFO Epoch: 4 | train_loss: 0.00326, train.py:146\n val_loss: 0.00247, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:45] INFO Epoch: 5 | train_loss: 0.00293, train.py:146\n val_loss: 0.00238, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:47] INFO Epoch: 6 | train_loss: 0.00267, train.py:146\n val_loss: 0.00223, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:49] INFO Epoch: 7 | train_loss: 0.00244, train.py:146\n val_loss: 0.00209, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:51] INFO Epoch: 8 | train_loss: 0.00220, train.py:146\n val_loss: 0.00195, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:53] INFO Epoch: 9 | train_loss: 0.00200, train.py:146\n val_loss: 0.00184, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:55] INFO Epoch: 10 | train_loss: 0.00183, train.py:146\n val_loss: 0.00176, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:41:58] INFO Epoch: 11 | train_loss: 0.00165, train.py:146\n val_loss: 0.00171, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:42:00] INFO Epoch: 12 | train_loss: 0.00154, train.py:146\n val_loss: 0.00164, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:42:02] INFO Epoch: 13 | train_loss: 0.00143, train.py:146\n val_loss: 0.00162, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:42:04] INFO Epoch: 14 | train_loss: 0.00132, train.py:146\n val_loss: 0.00161, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:42:06] INFO Epoch: 15 | train_loss: 0.00118, train.py:146\n val_loss: 0.00156, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:42:08] INFO Epoch: 16 | train_loss: 0.00109, train.py:146\n val_loss: 0.00151, lr: 2.92E-04, \n _patience: 10 \n[01/26/21 18:42:10] INFO Epoch: 17 | train_loss: 0.00102, train.py:146\n val_loss: 0.00152, lr: 2.92E-04, \n _patience: 9 \n[01/26/21 18:42:12] INFO Epoch: 18 | train_loss: 0.00094, train.py:146\n val_loss: 0.00153, lr: 2.92E-04, \n _patience: 8 \n[01/26/21 18:42:14] INFO Epoch: 19 | train_loss: 0.00087, train.py:146\n val_loss: 0.00155, lr: 2.92E-04, \n _patience: 7 \n[01/26/21 18:42:16] INFO Epoch: 20 | train_loss: 0.00080, train.py:146\n val_loss: 0.00159, lr: 2.92E-04, \n _patience: 6 \n[01/26/21 18:42:18] INFO Epoch: 21 | train_loss: 0.00075, train.py:146\n val_loss: 0.00154, lr: 2.92E-04, \n _patience: 5 \n[01/26/21 18:42:20] INFO Epoch: 22 | train_loss: 0.00066, train.py:146\n val_loss: 0.00155, lr: 1.46E-05, \n _patience: 4 \n[01/26/21 18:42:22] INFO Epoch: 23 | train_loss: 0.00061, train.py:146\n val_loss: 0.00154, lr: 1.46E-05, \n _patience: 3 \n[01/26/21 18:42:24] INFO Epoch: 24 | train_loss: 0.00061, train.py:146\n val_loss: 0.00153, lr: 1.46E-05, \n _patience: 2 \n[01/26/21 18:42:26] INFO Epoch: 25 | train_loss: 0.00058, train.py:146\n val_loss: 0.00154, lr: 1.46E-05, \n _patience: 1 \n[01/26/21 18:42:28] INFO Stopping early! train.py:141\n[01/26/21 18:42:35] INFO { train.py:460\n \"precision\": 0.7893852422087716, \n \"recall\": 0.5279210364986227, \n \"f1\": 0.6018187342341855, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 87: \n INFO { train.py:454\n \"embedding_dim\": 319, \n \"num_filters\": 398, \n \"hidden_dim\": 398, \n \"dropout_p\": 0.5110900946253784, \n \"lr\": 0.0003903345571537999 \n } \n[01/26/21 18:42:36] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 319, \n \"num_filters\": 398, \n \"hidden_dim\": 398, \n \"dropout_p\": 0.5110900946253784, \n \"lr\": 0.0003903345571537999, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.24199669063091278 \n } \n[01/26/21 18:42:38] INFO Epoch: 1 | train_loss: 0.00706, train.py:146\n val_loss: 0.00552, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:41] INFO Epoch: 2 | train_loss: 0.00500, train.py:146\n val_loss: 0.00276, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:43] INFO Epoch: 3 | train_loss: 0.00354, train.py:146\n val_loss: 0.00253, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:46] INFO Epoch: 4 | train_loss: 0.00294, train.py:146\n val_loss: 0.00244, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:49] INFO Epoch: 5 | train_loss: 0.00258, train.py:146\n val_loss: 0.00221, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:51] INFO Epoch: 6 | train_loss: 0.00227, train.py:146\n val_loss: 0.00202, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:54] INFO Epoch: 7 | train_loss: 0.00201, train.py:146\n val_loss: 0.00187, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:56] INFO Epoch: 8 | train_loss: 0.00178, train.py:146\n val_loss: 0.00174, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:42:59] INFO Epoch: 9 | train_loss: 0.00157, train.py:146\n val_loss: 0.00170, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:43:02] INFO Epoch: 10 | train_loss: 0.00139, train.py:146\n val_loss: 0.00164, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:43:04] INFO Epoch: 11 | train_loss: 0.00119, train.py:146\n val_loss: 0.00162, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:43:07] INFO Epoch: 12 | train_loss: 0.00105, train.py:146\n val_loss: 0.00160, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:43:09] INFO Epoch: 13 | train_loss: 0.00094, train.py:146\n val_loss: 0.00157, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:43:12] INFO Epoch: 14 | train_loss: 0.00088, train.py:146\n val_loss: 0.00159, lr: 3.90E-04, \n _patience: 9 \n[01/26/21 18:43:14] INFO Epoch: 15 | train_loss: 0.00075, train.py:146\n val_loss: 0.00159, lr: 3.90E-04, \n _patience: 8 \n[01/26/21 18:43:17] INFO Epoch: 16 | train_loss: 0.00068, train.py:146\n val_loss: 0.00157, lr: 3.90E-04, \n _patience: 10 \n[01/26/21 18:43:20] INFO Epoch: 17 | train_loss: 0.00058, train.py:146\n val_loss: 0.00166, lr: 3.90E-04, \n _patience: 9 \n[01/26/21 18:43:22] INFO Epoch: 18 | train_loss: 0.00051, train.py:146\n val_loss: 0.00162, lr: 3.90E-04, \n _patience: 8 \n[01/26/21 18:43:25] INFO Epoch: 19 | train_loss: 0.00045, train.py:146\n val_loss: 0.00162, lr: 3.90E-04, \n _patience: 7 \n[01/26/21 18:43:27] INFO Epoch: 20 | train_loss: 0.00043, train.py:146\n val_loss: 0.00164, lr: 3.90E-04, \n _patience: 6 \n[01/26/21 18:43:30] INFO Epoch: 21 | train_loss: 0.00037, train.py:146\n val_loss: 0.00166, lr: 3.90E-04, \n _patience: 5 \n[01/26/21 18:43:33] INFO Epoch: 22 | train_loss: 0.00034, train.py:146\n val_loss: 0.00179, lr: 1.95E-05, \n _patience: 4 \n[01/26/21 18:43:35] INFO Epoch: 23 | train_loss: 0.00032, train.py:146\n val_loss: 0.00174, lr: 1.95E-05, \n _patience: 3 \n[01/26/21 18:43:38] INFO Epoch: 24 | train_loss: 0.00029, train.py:146\n val_loss: 0.00170, lr: 1.95E-05, \n _patience: 2 \n[01/26/21 18:43:40] INFO Epoch: 25 | train_loss: 0.00029, train.py:146\n val_loss: 0.00169, lr: 1.95E-05, \n _patience: 1 \n[01/26/21 18:43:43] INFO Stopping early! train.py:141\n[01/26/21 18:43:52] INFO { train.py:460\n \"precision\": 0.8336235669092811, \n \"recall\": 0.5263132527479819, \n \"f1\": 0.6139130017039391, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 88: \n INFO { train.py:454\n \"embedding_dim\": 373, \n \"num_filters\": 383, \n \"hidden_dim\": 278, \n \"dropout_p\": 0.5774155147120894, \n \"lr\": 0.0003609571245956659 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 373, \n \"num_filters\": 383, \n \"hidden_dim\": 278, \n \"dropout_p\": 0.5774155147120894, \n \"lr\": 0.0003609571245956659, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.32279571890830994 \n } \n[01/26/21 18:43:55] INFO Epoch: 1 | train_loss: 0.00677, train.py:146\n val_loss: 0.00522, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:43:58] INFO Epoch: 2 | train_loss: 0.00514, train.py:146\n val_loss: 0.00288, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:00] INFO Epoch: 3 | train_loss: 0.00366, train.py:146\n val_loss: 0.00253, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:03] INFO Epoch: 4 | train_loss: 0.00312, train.py:146\n val_loss: 0.00237, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:06] INFO Epoch: 5 | train_loss: 0.00272, train.py:146\n val_loss: 0.00215, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:09] INFO Epoch: 6 | train_loss: 0.00236, train.py:146\n val_loss: 0.00197, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:11] INFO Epoch: 7 | train_loss: 0.00213, train.py:146\n val_loss: 0.00184, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:14] INFO Epoch: 8 | train_loss: 0.00186, train.py:146\n val_loss: 0.00173, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:17] INFO Epoch: 9 | train_loss: 0.00168, train.py:146\n val_loss: 0.00166, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:20] INFO Epoch: 10 | train_loss: 0.00151, train.py:146\n val_loss: 0.00162, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:22] INFO Epoch: 11 | train_loss: 0.00138, train.py:146\n val_loss: 0.00159, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:25] INFO Epoch: 12 | train_loss: 0.00122, train.py:146\n val_loss: 0.00155, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:28] INFO Epoch: 13 | train_loss: 0.00109, train.py:146\n val_loss: 0.00154, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:31] INFO Epoch: 14 | train_loss: 0.00101, train.py:146\n val_loss: 0.00150, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:34] INFO Epoch: 15 | train_loss: 0.00089, train.py:146\n val_loss: 0.00149, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:36] INFO Epoch: 16 | train_loss: 0.00082, train.py:146\n val_loss: 0.00149, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:39] INFO Epoch: 17 | train_loss: 0.00074, train.py:146\n val_loss: 0.00150, lr: 3.61E-04, \n _patience: 9 \n[01/26/21 18:44:42] INFO Epoch: 18 | train_loss: 0.00069, train.py:146\n val_loss: 0.00148, lr: 3.61E-04, \n _patience: 10 \n[01/26/21 18:44:45] INFO Epoch: 19 | train_loss: 0.00062, train.py:146\n val_loss: 0.00152, lr: 3.61E-04, \n _patience: 9 \n[01/26/21 18:44:48] INFO Epoch: 20 | train_loss: 0.00059, train.py:146\n val_loss: 0.00150, lr: 3.61E-04, \n _patience: 8 \n[01/26/21 18:44:50] INFO Epoch: 21 | train_loss: 0.00055, train.py:146\n val_loss: 0.00162, lr: 3.61E-04, \n _patience: 7 \n[01/26/21 18:44:53] INFO Epoch: 22 | train_loss: 0.00054, train.py:146\n val_loss: 0.00168, lr: 3.61E-04, \n _patience: 6 \n[01/26/21 18:44:56] INFO Epoch: 23 | train_loss: 0.00049, train.py:146\n val_loss: 0.00178, lr: 3.61E-04, \n _patience: 5 \n[01/26/21 18:44:59] INFO Epoch: 24 | train_loss: 0.00049, train.py:146\n val_loss: 0.00195, lr: 1.80E-05, \n _patience: 4 \n[01/26/21 18:45:02] INFO Epoch: 25 | train_loss: 0.00045, train.py:146\n val_loss: 0.00172, lr: 1.80E-05, \n _patience: 3 \n[01/26/21 18:45:04] INFO Epoch: 26 | train_loss: 0.00040, train.py:146\n val_loss: 0.00157, lr: 1.80E-05, \n _patience: 2 \n[01/26/21 18:45:07] INFO Epoch: 27 | train_loss: 0.00038, train.py:146\n val_loss: 0.00159, lr: 1.80E-05, \n _patience: 1 \n[01/26/21 18:45:10] INFO Stopping early! train.py:141\n[01/26/21 18:45:19] INFO { train.py:460\n \"precision\": 0.8189582885120643, \n \"recall\": 0.5470936860530456, \n \"f1\": 0.6264581681190291, \n \"num_samples\": 476.0 \n } \n[01/26/21 18:45:20] INFO train.py:453\n Trial 89: \n INFO { train.py:454\n \"embedding_dim\": 353, \n \"num_filters\": 412, \n \"hidden_dim\": 304, \n \"dropout_p\": 0.4880140706552939, \n \"lr\": 0.0004787595812666331 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 353, \n \"num_filters\": 412, \n \"hidden_dim\": 304, \n \"dropout_p\": 0.4880140706552939, \n \"lr\": 0.0004787595812666331, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.29166287183761597 \n } \n[01/26/21 18:45:23] INFO Epoch: 1 | train_loss: 0.00761, train.py:146\n val_loss: 0.00543, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:25] INFO Epoch: 2 | train_loss: 0.00524, train.py:146\n val_loss: 0.00276, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:28] INFO Epoch: 3 | train_loss: 0.00348, train.py:146\n val_loss: 0.00252, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:31] INFO Epoch: 4 | train_loss: 0.00292, train.py:146\n val_loss: 0.00240, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:34] INFO Epoch: 5 | train_loss: 0.00252, train.py:146\n val_loss: 0.00212, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:37] INFO Epoch: 6 | train_loss: 0.00221, train.py:146\n val_loss: 0.00193, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:40] INFO Epoch: 7 | train_loss: 0.00190, train.py:146\n val_loss: 0.00179, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:42] INFO Epoch: 8 | train_loss: 0.00170, train.py:146\n val_loss: 0.00168, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:45] INFO Epoch: 9 | train_loss: 0.00150, train.py:146\n val_loss: 0.00164, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:48] INFO Epoch: 10 | train_loss: 0.00130, train.py:146\n val_loss: 0.00159, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:51] INFO Epoch: 11 | train_loss: 0.00115, train.py:146\n val_loss: 0.00160, lr: 4.79E-04, \n _patience: 9 \n[01/26/21 18:45:54] INFO Epoch: 12 | train_loss: 0.00100, train.py:146\n val_loss: 0.00155, lr: 4.79E-04, \n _patience: 10 \n[01/26/21 18:45:57] INFO Epoch: 13 | train_loss: 0.00088, train.py:146\n val_loss: 0.00156, lr: 4.79E-04, \n _patience: 9 \n[01/26/21 18:46:00] INFO Epoch: 14 | train_loss: 0.00076, train.py:146\n val_loss: 0.00157, lr: 4.79E-04, \n _patience: 8 \n[01/26/21 18:46:02] INFO Epoch: 15 | train_loss: 0.00066, train.py:146\n val_loss: 0.00155, lr: 4.79E-04, \n _patience: 7 \n[01/26/21 18:46:05] INFO Epoch: 16 | train_loss: 0.00057, train.py:146\n val_loss: 0.00156, lr: 4.79E-04, \n _patience: 6 \n[01/26/21 18:46:08] INFO Epoch: 17 | train_loss: 0.00052, train.py:146\n val_loss: 0.00163, lr: 4.79E-04, \n _patience: 5 \n[01/26/21 18:46:11] INFO Epoch: 18 | train_loss: 0.00046, train.py:146\n val_loss: 0.00166, lr: 2.39E-05, \n _patience: 4 \n[01/26/21 18:46:14] INFO Epoch: 19 | train_loss: 0.00040, train.py:146\n val_loss: 0.00165, lr: 2.39E-05, \n _patience: 3 \n[01/26/21 18:46:17] INFO Epoch: 20 | train_loss: 0.00039, train.py:146\n val_loss: 0.00166, lr: 2.39E-05, \n _patience: 2 \n[01/26/21 18:46:20] INFO Epoch: 21 | train_loss: 0.00037, train.py:146\n val_loss: 0.00166, lr: 2.39E-05, \n _patience: 1 \n[01/26/21 18:46:23] INFO Stopping early! train.py:141\n[01/26/21 18:46:32] INFO { train.py:460\n \"precision\": 0.7989005975142037, \n \"recall\": 0.5703397223101657, \n \"f1\": 0.6344938861166481, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 90: \n INFO { train.py:454\n \"embedding_dim\": 245, \n \"num_filters\": 299, \n \"hidden_dim\": 129, \n \"dropout_p\": 0.4733410178024575, \n \"lr\": 0.0004173092687623612 \n } \n[01/26/21 18:46:33] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 245, \n \"num_filters\": 299, \n \"hidden_dim\": 129, \n \"dropout_p\": 0.4733410178024575, \n \"lr\": 0.0004173092687623612, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.24495862424373627 \n } \n[01/26/21 18:46:34] INFO Epoch: 1 | train_loss: 0.00654, train.py:146\n val_loss: 0.00393, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:36] INFO Epoch: 2 | train_loss: 0.00508, train.py:146\n val_loss: 0.00310, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:38] INFO Epoch: 3 | train_loss: 0.00378, train.py:146\n val_loss: 0.00253, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:39] INFO Epoch: 4 | train_loss: 0.00326, train.py:146\n val_loss: 0.00242, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:41] INFO Epoch: 5 | train_loss: 0.00293, train.py:146\n val_loss: 0.00231, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:43] INFO Epoch: 6 | train_loss: 0.00262, train.py:146\n val_loss: 0.00215, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:44] INFO Epoch: 7 | train_loss: 0.00240, train.py:146\n val_loss: 0.00202, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:46] INFO Epoch: 8 | train_loss: 0.00218, train.py:146\n val_loss: 0.00190, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:48] INFO Epoch: 9 | train_loss: 0.00198, train.py:146\n val_loss: 0.00182, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:49] INFO Epoch: 10 | train_loss: 0.00177, train.py:146\n val_loss: 0.00174, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:51] INFO Epoch: 11 | train_loss: 0.00166, train.py:146\n val_loss: 0.00168, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:53] INFO Epoch: 12 | train_loss: 0.00151, train.py:146\n val_loss: 0.00165, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:54] INFO Epoch: 13 | train_loss: 0.00143, train.py:146\n val_loss: 0.00162, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:56] INFO Epoch: 14 | train_loss: 0.00133, train.py:146\n val_loss: 0.00161, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:57] INFO Epoch: 15 | train_loss: 0.00121, train.py:146\n val_loss: 0.00155, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:46:59] INFO Epoch: 16 | train_loss: 0.00111, train.py:146\n val_loss: 0.00152, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:47:01] INFO Epoch: 17 | train_loss: 0.00104, train.py:146\n val_loss: 0.00150, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:47:02] INFO Epoch: 18 | train_loss: 0.00098, train.py:146\n val_loss: 0.00152, lr: 4.17E-04, \n _patience: 9 \n[01/26/21 18:47:04] INFO Epoch: 19 | train_loss: 0.00093, train.py:146\n val_loss: 0.00150, lr: 4.17E-04, \n _patience: 8 \n[01/26/21 18:47:06] INFO Epoch: 20 | train_loss: 0.00088, train.py:146\n val_loss: 0.00151, lr: 4.17E-04, \n _patience: 7 \n[01/26/21 18:47:07] INFO Epoch: 21 | train_loss: 0.00086, train.py:146\n val_loss: 0.00152, lr: 4.17E-04, \n _patience: 6 \n[01/26/21 18:47:09] INFO Epoch: 22 | train_loss: 0.00083, train.py:146\n val_loss: 0.00147, lr: 4.17E-04, \n _patience: 10 \n[01/26/21 18:47:11] INFO Epoch: 23 | train_loss: 0.00075, train.py:146\n val_loss: 0.00157, lr: 4.17E-04, \n _patience: 9 \n[01/26/21 18:47:12] INFO Epoch: 24 | train_loss: 0.00078, train.py:146\n val_loss: 0.00160, lr: 4.17E-04, \n _patience: 8 \n[01/26/21 18:47:14] INFO Epoch: 25 | train_loss: 0.00077, train.py:146\n val_loss: 0.00172, lr: 4.17E-04, \n _patience: 7 \n[01/26/21 18:47:16] INFO Epoch: 26 | train_loss: 0.00079, train.py:146\n val_loss: 0.00179, lr: 4.17E-04, \n _patience: 6 \n[01/26/21 18:47:17] INFO Epoch: 27 | train_loss: 0.00077, train.py:146\n val_loss: 0.00223, lr: 4.17E-04, \n _patience: 5 \n[01/26/21 18:47:19] INFO Epoch: 28 | train_loss: 0.00084, train.py:146\n val_loss: 0.00286, lr: 2.09E-05, \n _patience: 4 \n[01/26/21 18:47:21] INFO Epoch: 29 | train_loss: 0.00105, train.py:146\n val_loss: 0.00223, lr: 2.09E-05, \n _patience: 3 \n[01/26/21 18:47:22] INFO Epoch: 30 | train_loss: 0.00070, train.py:146\n val_loss: 0.00163, lr: 2.09E-05, \n _patience: 2 \n[01/26/21 18:47:24] INFO Epoch: 31 | train_loss: 0.00060, train.py:146\n val_loss: 0.00149, lr: 2.09E-05, \n _patience: 1 \n[01/26/21 18:47:26] INFO Stopping early! train.py:141\n[01/26/21 18:47:31] INFO { train.py:460\n \"precision\": 0.8234504559892607, \n \"recall\": 0.5171160678857724, \n \"f1\": 0.6029065424805947, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 91: \n INFO { train.py:454\n \"embedding_dim\": 359, \n \"num_filters\": 448, \n \"hidden_dim\": 386, \n \"dropout_p\": 0.5229960569796543, \n \"lr\": 0.0004373395819952221 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 359, \n \"num_filters\": 448, \n \"hidden_dim\": 386, \n \"dropout_p\": 0.5229960569796543, \n \"lr\": 0.0004373395819952221, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.35561510920524597 \n } \n[01/26/21 18:47:34] INFO Epoch: 1 | train_loss: 0.00787, train.py:146\n val_loss: 0.00581, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:37] INFO Epoch: 2 | train_loss: 0.00558, train.py:146\n val_loss: 0.00281, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:40] INFO Epoch: 3 | train_loss: 0.00365, train.py:146\n val_loss: 0.00255, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:43] INFO Epoch: 4 | train_loss: 0.00298, train.py:146\n val_loss: 0.00243, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:46] INFO Epoch: 5 | train_loss: 0.00262, train.py:146\n val_loss: 0.00217, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:49] INFO Epoch: 6 | train_loss: 0.00223, train.py:146\n val_loss: 0.00195, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:52] INFO Epoch: 7 | train_loss: 0.00195, train.py:146\n val_loss: 0.00179, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:55] INFO Epoch: 8 | train_loss: 0.00170, train.py:146\n val_loss: 0.00170, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:47:58] INFO Epoch: 9 | train_loss: 0.00149, train.py:146\n val_loss: 0.00162, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:48:01] INFO Epoch: 10 | train_loss: 0.00133, train.py:146\n val_loss: 0.00163, lr: 4.37E-04, \n _patience: 9 \n[01/26/21 18:48:04] INFO Epoch: 11 | train_loss: 0.00114, train.py:146\n val_loss: 0.00158, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:48:07] INFO Epoch: 12 | train_loss: 0.00102, train.py:146\n val_loss: 0.00154, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:48:11] INFO Epoch: 13 | train_loss: 0.00088, train.py:146\n val_loss: 0.00152, lr: 4.37E-04, \n _patience: 10 \n[01/26/21 18:48:14] INFO Epoch: 14 | train_loss: 0.00075, train.py:146\n val_loss: 0.00155, lr: 4.37E-04, \n _patience: 9 \n[01/26/21 18:48:17] INFO Epoch: 15 | train_loss: 0.00067, train.py:146\n val_loss: 0.00152, lr: 4.37E-04, \n _patience: 8 \n[01/26/21 18:48:20] INFO Epoch: 16 | train_loss: 0.00058, train.py:146\n val_loss: 0.00162, lr: 4.37E-04, \n _patience: 7 \n[01/26/21 18:48:23] INFO Epoch: 17 | train_loss: 0.00052, train.py:146\n val_loss: 0.00164, lr: 4.37E-04, \n _patience: 6 \n[01/26/21 18:48:26] INFO Epoch: 18 | train_loss: 0.00049, train.py:146\n val_loss: 0.00167, lr: 4.37E-04, \n _patience: 5 \n[01/26/21 18:48:29] INFO Epoch: 19 | train_loss: 0.00043, train.py:146\n val_loss: 0.00170, lr: 2.19E-05, \n _patience: 4 \n[01/26/21 18:48:32] INFO Epoch: 20 | train_loss: 0.00037, train.py:146\n val_loss: 0.00167, lr: 2.19E-05, \n _patience: 3 \n[01/26/21 18:48:35] INFO Epoch: 21 | train_loss: 0.00037, train.py:146\n val_loss: 0.00162, lr: 2.19E-05, \n _patience: 2 \n[01/26/21 18:48:38] INFO Epoch: 22 | train_loss: 0.00036, train.py:146\n val_loss: 0.00161, lr: 2.19E-05, \n _patience: 1 \n[01/26/21 18:48:41] INFO Stopping early! train.py:141\n[01/26/21 18:48:51] INFO { train.py:460\n \"precision\": 0.8007439317599163, \n \"recall\": 0.574527388092659, \n \"f1\": 0.6387845738898614, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 92: \n INFO { train.py:454\n \"embedding_dim\": 361, \n \"num_filters\": 468, \n \"hidden_dim\": 412, \n \"dropout_p\": 0.5403049297395742, \n \"lr\": 0.0004987761541215856 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 361, \n \"num_filters\": 468, \n \"hidden_dim\": 412, \n \"dropout_p\": 0.5403049297395742, \n \"lr\": 0.0004987761541215856, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2822585105895996 \n } \n[01/26/21 18:48:55] INFO Epoch: 1 | train_loss: 0.00868, train.py:146\n val_loss: 0.00617, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:48:58] INFO Epoch: 2 | train_loss: 0.00575, train.py:146\n val_loss: 0.00284, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:01] INFO Epoch: 3 | train_loss: 0.00358, train.py:146\n val_loss: 0.00259, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:04] INFO Epoch: 4 | train_loss: 0.00302, train.py:146\n val_loss: 0.00249, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:07] INFO Epoch: 5 | train_loss: 0.00259, train.py:146\n val_loss: 0.00223, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:10] INFO Epoch: 6 | train_loss: 0.00232, train.py:146\n val_loss: 0.00202, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:13] INFO Epoch: 7 | train_loss: 0.00199, train.py:146\n val_loss: 0.00185, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:16] INFO Epoch: 8 | train_loss: 0.00176, train.py:146\n val_loss: 0.00175, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:20] INFO Epoch: 9 | train_loss: 0.00158, train.py:146\n val_loss: 0.00169, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:23] INFO Epoch: 10 | train_loss: 0.00135, train.py:146\n val_loss: 0.00166, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:26] INFO Epoch: 11 | train_loss: 0.00117, train.py:146\n val_loss: 0.00162, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:29] INFO Epoch: 12 | train_loss: 0.00102, train.py:146\n val_loss: 0.00159, lr: 4.99E-04, \n _patience: 10 \n[01/26/21 18:49:32] INFO Epoch: 13 | train_loss: 0.00086, train.py:146\n val_loss: 0.00160, lr: 4.99E-04, \n _patience: 9 \n[01/26/21 18:49:35] INFO Epoch: 14 | train_loss: 0.00077, train.py:146\n val_loss: 0.00159, lr: 4.99E-04, \n _patience: 8 \n[01/26/21 18:49:38] INFO Epoch: 15 | train_loss: 0.00068, train.py:146\n val_loss: 0.00162, lr: 4.99E-04, \n _patience: 7 \n[01/26/21 18:49:42] INFO Epoch: 16 | train_loss: 0.00059, train.py:146\n val_loss: 0.00167, lr: 4.99E-04, \n _patience: 6 \n[01/26/21 18:49:45] INFO Epoch: 17 | train_loss: 0.00048, train.py:146\n val_loss: 0.00165, lr: 4.99E-04, \n _patience: 5 \n[01/26/21 18:49:48] INFO Epoch: 18 | train_loss: 0.00044, train.py:146\n val_loss: 0.00170, lr: 2.49E-05, \n _patience: 4 \n[01/26/21 18:49:51] INFO Epoch: 19 | train_loss: 0.00041, train.py:146\n val_loss: 0.00168, lr: 2.49E-05, \n _patience: 3 \n[01/26/21 18:49:54] INFO Epoch: 20 | train_loss: 0.00038, train.py:146\n val_loss: 0.00167, lr: 2.49E-05, \n _patience: 2 \n[01/26/21 18:49:57] INFO Epoch: 21 | train_loss: 0.00037, train.py:146\n val_loss: 0.00166, lr: 2.49E-05, \n _patience: 1 \n[01/26/21 18:50:00] INFO Stopping early! train.py:141\n[01/26/21 18:50:12] INFO { train.py:460\n \"precision\": 0.7914283443131369, \n \"recall\": 0.5417624117808847, \n \"f1\": 0.6138675280555068, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 93: \n INFO { train.py:454\n \"embedding_dim\": 395, \n \"num_filters\": 446, \n \"hidden_dim\": 452, \n \"dropout_p\": 0.5205674287907339, \n \"lr\": 0.0004359838631573852 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 395, \n \"num_filters\": 446, \n \"hidden_dim\": 452, \n \"dropout_p\": 0.5205674287907339, \n \"lr\": 0.0004359838631573852, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2733114957809448 \n } \n[01/26/21 18:50:15] INFO Epoch: 1 | train_loss: 0.00800, train.py:146\n val_loss: 0.00551, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:18] INFO Epoch: 2 | train_loss: 0.00523, train.py:146\n val_loss: 0.00278, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:22] INFO Epoch: 3 | train_loss: 0.00353, train.py:146\n val_loss: 0.00252, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:25] INFO Epoch: 4 | train_loss: 0.00286, train.py:146\n val_loss: 0.00236, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:28] INFO Epoch: 5 | train_loss: 0.00249, train.py:146\n val_loss: 0.00211, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:32] INFO Epoch: 6 | train_loss: 0.00217, train.py:146\n val_loss: 0.00192, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:35] INFO Epoch: 7 | train_loss: 0.00184, train.py:146\n val_loss: 0.00177, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:38] INFO Epoch: 8 | train_loss: 0.00160, train.py:146\n val_loss: 0.00171, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:41] INFO Epoch: 9 | train_loss: 0.00141, train.py:146\n val_loss: 0.00164, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:45] INFO Epoch: 10 | train_loss: 0.00124, train.py:146\n val_loss: 0.00160, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:48] INFO Epoch: 11 | train_loss: 0.00108, train.py:146\n val_loss: 0.00160, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:51] INFO Epoch: 12 | train_loss: 0.00092, train.py:146\n val_loss: 0.00155, lr: 4.36E-04, \n _patience: 10 \n[01/26/21 18:50:55] INFO Epoch: 13 | train_loss: 0.00080, train.py:146\n val_loss: 0.00158, lr: 4.36E-04, \n _patience: 9 \n[01/26/21 18:50:58] INFO Epoch: 14 | train_loss: 0.00068, train.py:146\n val_loss: 0.00159, lr: 4.36E-04, \n _patience: 8 \n[01/26/21 18:51:01] INFO Epoch: 15 | train_loss: 0.00061, train.py:146\n val_loss: 0.00159, lr: 4.36E-04, \n _patience: 7 \n[01/26/21 18:51:05] INFO Epoch: 16 | train_loss: 0.00051, train.py:146\n val_loss: 0.00162, lr: 4.36E-04, \n _patience: 6 \n[01/26/21 18:51:08] INFO Epoch: 17 | train_loss: 0.00045, train.py:146\n val_loss: 0.00164, lr: 4.36E-04, \n _patience: 5 \n[01/26/21 18:51:11] INFO Epoch: 18 | train_loss: 0.00038, train.py:146\n val_loss: 0.00173, lr: 2.18E-05, \n _patience: 4 \n[01/26/21 18:51:15] INFO Epoch: 19 | train_loss: 0.00037, train.py:146\n val_loss: 0.00170, lr: 2.18E-05, \n _patience: 3 \n[01/26/21 18:51:18] INFO Epoch: 20 | train_loss: 0.00034, train.py:146\n val_loss: 0.00167, lr: 2.18E-05, \n _patience: 2 \n[01/26/21 18:51:21] INFO Epoch: 21 | train_loss: 0.00034, train.py:146\n val_loss: 0.00166, lr: 2.18E-05, \n _patience: 1 \n[01/26/21 18:51:25] INFO Stopping early! train.py:141\n[01/26/21 18:51:36] INFO { train.py:460\n \"precision\": 0.8020210497629853, \n \"recall\": 0.5810783403332664, \n \"f1\": 0.6468973352784165, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 94: \n INFO { train.py:454\n \"embedding_dim\": 388, \n \"num_filters\": 449, \n \"hidden_dim\": 450, \n \"dropout_p\": 0.5181690515782456, \n \"lr\": 0.00044198429028284293 \n } \n[01/26/21 18:51:37] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 388, \n \"num_filters\": 449, \n \"hidden_dim\": 450, \n \"dropout_p\": 0.5181690515782456, \n \"lr\": 0.00044198429028284293, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.25229451060295105 \n } \n[01/26/21 18:51:40] INFO Epoch: 1 | train_loss: 0.00809, train.py:146\n val_loss: 0.00579, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:51:43] INFO Epoch: 2 | train_loss: 0.00564, train.py:146\n val_loss: 0.00293, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:51:46] INFO Epoch: 3 | train_loss: 0.00355, train.py:146\n val_loss: 0.00260, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:51:50] INFO Epoch: 4 | train_loss: 0.00298, train.py:146\n val_loss: 0.00248, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:51:53] INFO Epoch: 5 | train_loss: 0.00260, train.py:146\n val_loss: 0.00222, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:51:56] INFO Epoch: 6 | train_loss: 0.00225, train.py:146\n val_loss: 0.00202, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:51:59] INFO Epoch: 7 | train_loss: 0.00195, train.py:146\n val_loss: 0.00186, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:52:02] INFO Epoch: 8 | train_loss: 0.00169, train.py:146\n val_loss: 0.00175, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:52:06] INFO Epoch: 9 | train_loss: 0.00149, train.py:146\n val_loss: 0.00170, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:52:09] INFO Epoch: 10 | train_loss: 0.00135, train.py:146\n val_loss: 0.00163, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:52:12] INFO Epoch: 11 | train_loss: 0.00116, train.py:146\n val_loss: 0.00159, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:52:16] INFO Epoch: 12 | train_loss: 0.00102, train.py:146\n val_loss: 0.00160, lr: 4.42E-04, \n _patience: 9 \n[01/26/21 18:52:19] INFO Epoch: 13 | train_loss: 0.00087, train.py:146\n val_loss: 0.00159, lr: 4.42E-04, \n _patience: 8 \n[01/26/21 18:52:22] INFO Epoch: 14 | train_loss: 0.00077, train.py:146\n val_loss: 0.00162, lr: 4.42E-04, \n _patience: 7 \n[01/26/21 18:52:25] INFO Epoch: 15 | train_loss: 0.00065, train.py:146\n val_loss: 0.00158, lr: 4.42E-04, \n _patience: 10 \n[01/26/21 18:52:29] INFO Epoch: 16 | train_loss: 0.00058, train.py:146\n val_loss: 0.00161, lr: 4.42E-04, \n _patience: 9 \n[01/26/21 18:52:32] INFO Epoch: 17 | train_loss: 0.00049, train.py:146\n val_loss: 0.00161, lr: 4.42E-04, \n _patience: 8 \n[01/26/21 18:52:35] INFO Epoch: 18 | train_loss: 0.00044, train.py:146\n val_loss: 0.00167, lr: 4.42E-04, \n _patience: 7 \n[01/26/21 18:52:38] INFO Epoch: 19 | train_loss: 0.00039, train.py:146\n val_loss: 0.00170, lr: 4.42E-04, \n _patience: 6 \n[01/26/21 18:52:42] INFO Epoch: 20 | train_loss: 0.00038, train.py:146\n val_loss: 0.00174, lr: 4.42E-04, \n _patience: 5 \n[01/26/21 18:52:45] INFO Epoch: 21 | train_loss: 0.00034, train.py:146\n val_loss: 0.00180, lr: 2.21E-05, \n _patience: 4 \n[01/26/21 18:52:48] INFO Epoch: 22 | train_loss: 0.00029, train.py:146\n val_loss: 0.00178, lr: 2.21E-05, \n _patience: 3 \n[01/26/21 18:52:52] INFO Epoch: 23 | train_loss: 0.00027, train.py:146\n val_loss: 0.00175, lr: 2.21E-05, \n _patience: 2 \n[01/26/21 18:52:55] INFO Epoch: 24 | train_loss: 0.00026, train.py:146\n val_loss: 0.00174, lr: 2.21E-05, \n _patience: 1 \n[01/26/21 18:52:58] INFO Stopping early! train.py:141\n[01/26/21 18:53:10] INFO { train.py:460\n \"precision\": 0.7963226611243647, \n \"recall\": 0.5421359023206314, \n \"f1\": 0.6208434390587372, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 95: \n INFO { train.py:454\n \"embedding_dim\": 419, \n \"num_filters\": 428, \n \"hidden_dim\": 431, \n \"dropout_p\": 0.5050637981286842, \n \"lr\": 6.160277423302567e-05 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 419, \n \"num_filters\": 428, \n \"hidden_dim\": 431, \n \"dropout_p\": 0.5050637981286842, \n \"lr\": 6.160277423302567e-05, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.27507394552230835 \n } \n[01/26/21 18:53:13] INFO Epoch: 1 | train_loss: 0.00563, train.py:146\n val_loss: 0.00285, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:17] INFO Epoch: 2 | train_loss: 0.00361, train.py:146\n val_loss: 0.00326, lr: 6.16E-05, \n _patience: 9 \n[01/26/21 18:53:20] INFO Epoch: 3 | train_loss: 0.00362, train.py:146\n val_loss: 0.00295, lr: 6.16E-05, \n _patience: 8 \n[01/26/21 18:53:23] INFO Epoch: 4 | train_loss: 0.00322, train.py:146\n val_loss: 0.00261, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:27] INFO Epoch: 5 | train_loss: 0.00296, train.py:146\n val_loss: 0.00251, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:30] INFO Epoch: 6 | train_loss: 0.00287, train.py:146\n val_loss: 0.00246, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:34] INFO Epoch: 7 | train_loss: 0.00274, train.py:146\n val_loss: 0.00240, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:37] INFO Epoch: 8 | train_loss: 0.00267, train.py:146\n val_loss: 0.00235, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:40] INFO Epoch: 9 | train_loss: 0.00253, train.py:146\n val_loss: 0.00230, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:44] INFO Epoch: 10 | train_loss: 0.00247, train.py:146\n val_loss: 0.00224, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:47] INFO Epoch: 11 | train_loss: 0.00237, train.py:146\n val_loss: 0.00219, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:51] INFO Epoch: 12 | train_loss: 0.00225, train.py:146\n val_loss: 0.00213, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:54] INFO Epoch: 13 | train_loss: 0.00214, train.py:146\n val_loss: 0.00207, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:53:57] INFO Epoch: 14 | train_loss: 0.00213, train.py:146\n val_loss: 0.00201, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:01] INFO Epoch: 15 | train_loss: 0.00202, train.py:146\n val_loss: 0.00196, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:04] INFO Epoch: 16 | train_loss: 0.00193, train.py:146\n val_loss: 0.00192, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:08] INFO Epoch: 17 | train_loss: 0.00183, train.py:146\n val_loss: 0.00187, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:11] INFO Epoch: 18 | train_loss: 0.00176, train.py:146\n val_loss: 0.00184, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:15] INFO Epoch: 19 | train_loss: 0.00170, train.py:146\n val_loss: 0.00180, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:18] INFO Epoch: 20 | train_loss: 0.00162, train.py:146\n val_loss: 0.00177, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:21] INFO Epoch: 21 | train_loss: 0.00156, train.py:146\n val_loss: 0.00174, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:25] INFO Epoch: 22 | train_loss: 0.00153, train.py:146\n val_loss: 0.00171, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:28] INFO Epoch: 23 | train_loss: 0.00146, train.py:146\n val_loss: 0.00169, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:32] INFO Epoch: 24 | train_loss: 0.00143, train.py:146\n val_loss: 0.00166, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:35] INFO Epoch: 25 | train_loss: 0.00136, train.py:146\n val_loss: 0.00164, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:39] INFO Epoch: 26 | train_loss: 0.00130, train.py:146\n val_loss: 0.00164, lr: 6.16E-05, \n _patience: 9 \n[01/26/21 18:54:42] INFO Epoch: 27 | train_loss: 0.00126, train.py:146\n val_loss: 0.00160, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:45] INFO Epoch: 28 | train_loss: 0.00122, train.py:146\n val_loss: 0.00161, lr: 6.16E-05, \n _patience: 9 \n[01/26/21 18:54:49] INFO Epoch: 29 | train_loss: 0.00118, train.py:146\n val_loss: 0.00159, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:52] INFO Epoch: 30 | train_loss: 0.00115, train.py:146\n val_loss: 0.00157, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:54:56] INFO Epoch: 31 | train_loss: 0.00109, train.py:146\n val_loss: 0.00157, lr: 6.16E-05, \n _patience: 9 \n[01/26/21 18:54:59] INFO Epoch: 32 | train_loss: 0.00106, train.py:146\n val_loss: 0.00156, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:03] INFO Epoch: 33 | train_loss: 0.00104, train.py:146\n val_loss: 0.00155, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:06] INFO Epoch: 34 | train_loss: 0.00099, train.py:146\n val_loss: 0.00154, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:10] INFO Epoch: 35 | train_loss: 0.00097, train.py:146\n val_loss: 0.00153, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:13] INFO Epoch: 36 | train_loss: 0.00094, train.py:146\n val_loss: 0.00152, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:16] INFO Epoch: 37 | train_loss: 0.00088, train.py:146\n val_loss: 0.00152, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:20] INFO Epoch: 38 | train_loss: 0.00086, train.py:146\n val_loss: 0.00153, lr: 6.16E-05, \n _patience: 9 \n[01/26/21 18:55:23] INFO Epoch: 39 | train_loss: 0.00085, train.py:146\n val_loss: 0.00150, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:27] INFO Epoch: 40 | train_loss: 0.00082, train.py:146\n val_loss: 0.00151, lr: 6.16E-05, \n _patience: 9 \n[01/26/21 18:55:30] INFO Epoch: 41 | train_loss: 0.00079, train.py:146\n val_loss: 0.00151, lr: 6.16E-05, \n _patience: 8 \n[01/26/21 18:55:34] INFO Epoch: 42 | train_loss: 0.00075, train.py:146\n val_loss: 0.00151, lr: 6.16E-05, \n _patience: 7 \n[01/26/21 18:55:37] INFO Epoch: 43 | train_loss: 0.00073, train.py:146\n val_loss: 0.00151, lr: 6.16E-05, \n _patience: 6 \n[01/26/21 18:55:41] INFO Epoch: 44 | train_loss: 0.00071, train.py:146\n val_loss: 0.00151, lr: 6.16E-05, \n _patience: 5 \n[01/26/21 18:55:44] INFO Epoch: 45 | train_loss: 0.00069, train.py:146\n val_loss: 0.00149, lr: 6.16E-05, \n _patience: 10 \n[01/26/21 18:55:48] INFO Epoch: 46 | train_loss: 0.00066, train.py:146\n val_loss: 0.00153, lr: 6.16E-05, \n _patience: 9 \n[01/26/21 18:55:51] INFO Epoch: 47 | train_loss: 0.00064, train.py:146\n val_loss: 0.00151, lr: 6.16E-05, \n _patience: 8 \n[01/26/21 18:55:54] INFO Epoch: 48 | train_loss: 0.00063, train.py:146\n val_loss: 0.00150, lr: 6.16E-05, \n _patience: 7 \n[01/26/21 18:55:58] INFO Epoch: 49 | train_loss: 0.00061, train.py:146\n val_loss: 0.00150, lr: 6.16E-05, \n _patience: 6 \n[01/26/21 18:56:01] INFO Epoch: 50 | train_loss: 0.00059, train.py:146\n val_loss: 0.00151, lr: 6.16E-05, \n _patience: 5 \n[01/26/21 18:56:05] INFO Epoch: 51 | train_loss: 0.00057, train.py:146\n val_loss: 0.00149, lr: 3.08E-06, \n _patience: 4 \n[01/26/21 18:56:08] INFO Epoch: 52 | train_loss: 0.00055, train.py:146\n val_loss: 0.00150, lr: 3.08E-06, \n _patience: 3 \n[01/26/21 18:56:12] INFO Epoch: 53 | train_loss: 0.00055, train.py:146\n val_loss: 0.00151, lr: 3.08E-06, \n _patience: 2 \n[01/26/21 18:56:15] INFO Epoch: 54 | train_loss: 0.00055, train.py:146\n val_loss: 0.00151, lr: 3.08E-06, \n _patience: 1 \n[01/26/21 18:56:19] INFO Stopping early! train.py:141\n[01/26/21 18:56:30] INFO { train.py:460\n \"precision\": 0.8213188715094906, \n \"recall\": 0.5135333691121868, \n \"f1\": 0.5950658003529242, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 96: \n INFO { train.py:454\n \"embedding_dim\": 378, \n \"num_filters\": 470, \n \"hidden_dim\": 381, \n \"dropout_p\": 0.4575595125215008, \n \"lr\": 0.0004509250264596135 \n } \n[01/26/21 18:56:31] INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 378, \n \"num_filters\": 470, \n \"hidden_dim\": 381, \n \"dropout_p\": 0.4575595125215008, \n \"lr\": 0.0004509250264596135, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2808901071548462 \n } \n[01/26/21 18:56:34] INFO Epoch: 1 | train_loss: 0.00762, train.py:146\n val_loss: 0.00511, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:56:37] INFO Epoch: 2 | train_loss: 0.00510, train.py:146\n val_loss: 0.00277, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:56:41] INFO Epoch: 3 | train_loss: 0.00340, train.py:146\n val_loss: 0.00252, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:56:44] INFO Epoch: 4 | train_loss: 0.00278, train.py:146\n val_loss: 0.00234, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:56:47] INFO Epoch: 5 | train_loss: 0.00239, train.py:146\n val_loss: 0.00211, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:56:50] INFO Epoch: 6 | train_loss: 0.00207, train.py:146\n val_loss: 0.00189, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:56:53] INFO Epoch: 7 | train_loss: 0.00174, train.py:146\n val_loss: 0.00177, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:56:57] INFO Epoch: 8 | train_loss: 0.00155, train.py:146\n val_loss: 0.00167, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:57:00] INFO Epoch: 9 | train_loss: 0.00132, train.py:146\n val_loss: 0.00164, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:57:03] INFO Epoch: 10 | train_loss: 0.00114, train.py:146\n val_loss: 0.00157, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:57:06] INFO Epoch: 11 | train_loss: 0.00097, train.py:146\n val_loss: 0.00158, lr: 4.51E-04, \n _patience: 9 \n[01/26/21 18:57:10] INFO Epoch: 12 | train_loss: 0.00082, train.py:146\n val_loss: 0.00157, lr: 4.51E-04, \n _patience: 10 \n[01/26/21 18:57:13] INFO Epoch: 13 | train_loss: 0.00072, train.py:146\n val_loss: 0.00158, lr: 4.51E-04, \n _patience: 9 \n[01/26/21 18:57:16] INFO Epoch: 14 | train_loss: 0.00060, train.py:146\n val_loss: 0.00162, lr: 4.51E-04, \n _patience: 8 \n[01/26/21 18:57:19] INFO Epoch: 15 | train_loss: 0.00054, train.py:146\n val_loss: 0.00165, lr: 4.51E-04, \n _patience: 7 \n[01/26/21 18:57:23] INFO Epoch: 16 | train_loss: 0.00047, train.py:146\n val_loss: 0.00166, lr: 4.51E-04, \n _patience: 6 \n[01/26/21 18:57:26] INFO Epoch: 17 | train_loss: 0.00041, train.py:146\n val_loss: 0.00162, lr: 4.51E-04, \n _patience: 5 \n[01/26/21 18:57:29] INFO Epoch: 18 | train_loss: 0.00036, train.py:146\n val_loss: 0.00171, lr: 2.25E-05, \n _patience: 4 \n[01/26/21 18:57:33] INFO Epoch: 19 | train_loss: 0.00031, train.py:146\n val_loss: 0.00170, lr: 2.25E-05, \n _patience: 3 \n[01/26/21 18:57:36] INFO Epoch: 20 | train_loss: 0.00030, train.py:146\n val_loss: 0.00170, lr: 2.25E-05, \n _patience: 2 \n[01/26/21 18:57:39] INFO Epoch: 21 | train_loss: 0.00030, train.py:146\n val_loss: 0.00169, lr: 2.25E-05, \n _patience: 1 \n[01/26/21 18:57:43] INFO Stopping early! train.py:141\n[01/26/21 18:57:54] INFO { train.py:460\n \"precision\": 0.8341567891218513, \n \"recall\": 0.5604473694067291, \n \"f1\": 0.6458502034580447, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 97: \n INFO { train.py:454\n \"embedding_dim\": 431, \n \"num_filters\": 492, \n \"hidden_dim\": 367, \n \"dropout_p\": 0.4526555488148677, \n \"lr\": 0.00040802218810157736 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 431, \n \"num_filters\": 492, \n \"hidden_dim\": 367, \n \"dropout_p\": 0.4526555488148677, \n \"lr\": 0.00040802218810157736, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.3095209300518036 \n } \n[01/26/21 18:57:58] INFO Epoch: 1 | train_loss: 0.00749, train.py:146\n val_loss: 0.00526, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:02] INFO Epoch: 2 | train_loss: 0.00512, train.py:146\n val_loss: 0.00273, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:06] INFO Epoch: 3 | train_loss: 0.00333, train.py:146\n val_loss: 0.00243, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:09] INFO Epoch: 4 | train_loss: 0.00274, train.py:146\n val_loss: 0.00223, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:13] INFO Epoch: 5 | train_loss: 0.00231, train.py:146\n val_loss: 0.00196, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:17] INFO Epoch: 6 | train_loss: 0.00194, train.py:146\n val_loss: 0.00180, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:20] INFO Epoch: 7 | train_loss: 0.00168, train.py:146\n val_loss: 0.00170, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:24] INFO Epoch: 8 | train_loss: 0.00146, train.py:146\n val_loss: 0.00165, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:28] INFO Epoch: 9 | train_loss: 0.00124, train.py:146\n val_loss: 0.00161, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:32] INFO Epoch: 10 | train_loss: 0.00107, train.py:146\n val_loss: 0.00158, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:35] INFO Epoch: 11 | train_loss: 0.00092, train.py:146\n val_loss: 0.00157, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:39] INFO Epoch: 12 | train_loss: 0.00078, train.py:146\n val_loss: 0.00160, lr: 4.08E-04, \n _patience: 9 \n[01/26/21 18:58:43] INFO Epoch: 13 | train_loss: 0.00067, train.py:146\n val_loss: 0.00157, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:47] INFO Epoch: 14 | train_loss: 0.00062, train.py:146\n val_loss: 0.00155, lr: 4.08E-04, \n _patience: 10 \n[01/26/21 18:58:51] INFO Epoch: 15 | train_loss: 0.00051, train.py:146\n val_loss: 0.00167, lr: 4.08E-04, \n _patience: 9 \n[01/26/21 18:58:54] INFO Epoch: 16 | train_loss: 0.00045, train.py:146\n val_loss: 0.00173, lr: 4.08E-04, \n _patience: 8 \n[01/26/21 18:58:58] INFO Epoch: 17 | train_loss: 0.00041, train.py:146\n val_loss: 0.00179, lr: 4.08E-04, \n _patience: 7 \n[01/26/21 18:59:02] INFO Epoch: 18 | train_loss: 0.00036, train.py:146\n val_loss: 0.00192, lr: 4.08E-04, \n _patience: 6 \n[01/26/21 18:59:06] INFO Epoch: 19 | train_loss: 0.00032, train.py:146\n val_loss: 0.00183, lr: 4.08E-04, \n _patience: 5 \n[01/26/21 18:59:09] INFO Epoch: 20 | train_loss: 0.00029, train.py:146\n val_loss: 0.00174, lr: 2.04E-05, \n _patience: 4 \n[01/26/21 18:59:13] INFO Epoch: 21 | train_loss: 0.00025, train.py:146\n val_loss: 0.00177, lr: 2.04E-05, \n _patience: 3 \n[01/26/21 18:59:17] INFO Epoch: 22 | train_loss: 0.00025, train.py:146\n val_loss: 0.00179, lr: 2.04E-05, \n _patience: 2 \n[01/26/21 18:59:21] INFO Epoch: 23 | train_loss: 0.00023, train.py:146\n val_loss: 0.00177, lr: 2.04E-05, \n _patience: 1 \n[01/26/21 18:59:25] INFO Stopping early! train.py:141\n[01/26/21 18:59:38] INFO { train.py:460\n \"precision\": 0.8107455400233579, \n \"recall\": 0.5537466791099795, \n \"f1\": 0.631559175490811, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 98: \n INFO { train.py:454\n \"embedding_dim\": 402, \n \"num_filters\": 349, \n \"hidden_dim\": 397, \n \"dropout_p\": 0.41276496189011963, \n \"lr\": 0.0003866519224545234 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 402, \n \"num_filters\": 349, \n \"hidden_dim\": 397, \n \"dropout_p\": 0.41276496189011963, \n \"lr\": 0.0003866519224545234, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.32694026827812195 \n } \n[01/26/21 18:59:41] INFO Epoch: 1 | train_loss: 0.00612, train.py:146\n val_loss: 0.00434, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 18:59:44] INFO Epoch: 2 | train_loss: 0.00421, train.py:146\n val_loss: 0.00256, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 18:59:47] INFO Epoch: 3 | train_loss: 0.00317, train.py:146\n val_loss: 0.00244, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 18:59:50] INFO Epoch: 4 | train_loss: 0.00262, train.py:146\n val_loss: 0.00221, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 18:59:52] INFO Epoch: 5 | train_loss: 0.00223, train.py:146\n val_loss: 0.00197, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 18:59:55] INFO Epoch: 6 | train_loss: 0.00189, train.py:146\n val_loss: 0.00182, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 18:59:58] INFO Epoch: 7 | train_loss: 0.00163, train.py:146\n val_loss: 0.00170, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 19:00:01] INFO Epoch: 8 | train_loss: 0.00142, train.py:146\n val_loss: 0.00164, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 19:00:04] INFO Epoch: 9 | train_loss: 0.00124, train.py:146\n val_loss: 0.00158, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 19:00:06] INFO Epoch: 10 | train_loss: 0.00103, train.py:146\n val_loss: 0.00158, lr: 3.87E-04, \n _patience: 9 \n[01/26/21 19:00:09] INFO Epoch: 11 | train_loss: 0.00090, train.py:146\n val_loss: 0.00156, lr: 3.87E-04, \n _patience: 10 \n[01/26/21 19:00:12] INFO Epoch: 12 | train_loss: 0.00080, train.py:146\n val_loss: 0.00158, lr: 3.87E-04, \n _patience: 9 \n[01/26/21 19:00:15] INFO Epoch: 13 | train_loss: 0.00068, train.py:146\n val_loss: 0.00160, lr: 3.87E-04, \n _patience: 8 \n[01/26/21 19:00:18] INFO Epoch: 14 | train_loss: 0.00059, train.py:146\n val_loss: 0.00157, lr: 3.87E-04, \n _patience: 7 \n[01/26/21 19:00:20] INFO Epoch: 15 | train_loss: 0.00051, train.py:146\n val_loss: 0.00160, lr: 3.87E-04, \n _patience: 6 \n[01/26/21 19:00:23] INFO Epoch: 16 | train_loss: 0.00043, train.py:146\n val_loss: 0.00169, lr: 3.87E-04, \n _patience: 5 \n[01/26/21 19:00:26] INFO Epoch: 17 | train_loss: 0.00040, train.py:146\n val_loss: 0.00172, lr: 1.93E-05, \n _patience: 4 \n[01/26/21 19:00:29] INFO Epoch: 18 | train_loss: 0.00035, train.py:146\n val_loss: 0.00167, lr: 1.93E-05, \n _patience: 3 \n[01/26/21 19:00:32] INFO Epoch: 19 | train_loss: 0.00034, train.py:146\n val_loss: 0.00163, lr: 1.93E-05, \n _patience: 2 \n[01/26/21 19:00:35] INFO Epoch: 20 | train_loss: 0.00032, train.py:146\n val_loss: 0.00163, lr: 1.93E-05, \n _patience: 1 \n[01/26/21 19:00:37] INFO Stopping early! train.py:141\n[01/26/21 19:00:47] INFO { train.py:460\n \"precision\": 0.7814493031076472, \n \"recall\": 0.5483748601790474, \n \"f1\": 0.6186803995225048, \n \"num_samples\": 476.0 \n } \n INFO train.py:453\n Trial 99: \n INFO { train.py:454\n \"embedding_dim\": 377, \n \"num_filters\": 468, \n \"hidden_dim\": 322, \n \"dropout_p\": 0.4614999705582103, \n \"lr\": 0.0004828033421729261 \n } \n INFO Parameters: { train.py:411\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 377, \n \"num_filters\": 468, \n \"hidden_dim\": 322, \n \"dropout_p\": 0.4614999705582103, \n \"lr\": 0.0004828033421729261, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.2981618046760559 \n } \n[01/26/21 19:00:50] INFO Epoch: 1 | train_loss: 0.00796, train.py:146\n val_loss: 0.00558, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:00:54] INFO Epoch: 2 | train_loss: 0.00519, train.py:146\n val_loss: 0.00272, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:00:57] INFO Epoch: 3 | train_loss: 0.00352, train.py:146\n val_loss: 0.00248, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:00] INFO Epoch: 4 | train_loss: 0.00289, train.py:146\n val_loss: 0.00230, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:03] INFO Epoch: 5 | train_loss: 0.00248, train.py:146\n val_loss: 0.00202, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:06] INFO Epoch: 6 | train_loss: 0.00207, train.py:146\n val_loss: 0.00185, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:10] INFO Epoch: 7 | train_loss: 0.00181, train.py:146\n val_loss: 0.00175, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:13] INFO Epoch: 8 | train_loss: 0.00158, train.py:146\n val_loss: 0.00166, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:16] INFO Epoch: 9 | train_loss: 0.00136, train.py:146\n val_loss: 0.00160, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:19] INFO Epoch: 10 | train_loss: 0.00116, train.py:146\n val_loss: 0.00156, lr: 4.83E-04, \n _patience: 10 \n[01/26/21 19:01:23] INFO Epoch: 11 | train_loss: 0.00098, train.py:146\n val_loss: 0.00158, lr: 4.83E-04, \n _patience: 9 \n[01/26/21 19:01:26] INFO Epoch: 12 | train_loss: 0.00087, train.py:146\n val_loss: 0.00157, lr: 4.83E-04, \n _patience: 8 \n[01/26/21 19:01:29] INFO Epoch: 13 | train_loss: 0.00073, train.py:146\n val_loss: 0.00157, lr: 4.83E-04, \n _patience: 7 \n[01/26/21 19:01:32] INFO Epoch: 14 | train_loss: 0.00062, train.py:146\n val_loss: 0.00159, lr: 4.83E-04, \n _patience: 6 \n[01/26/21 19:01:35] INFO Epoch: 15 | train_loss: 0.00055, train.py:146\n val_loss: 0.00163, lr: 4.83E-04, \n _patience: 5 \n[01/26/21 19:01:39] INFO Epoch: 16 | train_loss: 0.00048, train.py:146\n val_loss: 0.00164, lr: 2.41E-05, \n _patience: 4 \n[01/26/21 19:01:42] INFO Epoch: 17 | train_loss: 0.00044, train.py:146\n val_loss: 0.00163, lr: 2.41E-05, \n _patience: 3 \n[01/26/21 19:01:45] INFO Epoch: 18 | train_loss: 0.00041, train.py:146\n val_loss: 0.00162, lr: 2.41E-05, \n _patience: 2 \n[01/26/21 19:01:49] INFO Epoch: 19 | train_loss: 0.00041, train.py:146\n val_loss: 0.00161, lr: 2.41E-05, \n _patience: 1 \n[01/26/21 19:01:52] INFO Stopping early! train.py:141\n[01/26/21 19:02:04] INFO { train.py:460\n \"precision\": 0.8188516519058392, \n \"recall\": 0.5639196592952751, \n \"f1\": 0.6425545580571962, \n \"num_samples\": 476.0 \n } \n INFO Best f1: 0.6524069869530076 main.py:155\n INFO { main.py:160\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": 0, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 322, \n \"num_filters\": 421, \n \"hidden_dim\": 365, \n \"dropout_p\": 0.5000749141287706, \n \"lr\": 0.0003717563576081464, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.27709120512008667 \n } \n"
]
],
[
[
"# Train",
"_____no_output_____"
],
[
"Once we're identified the best hyperparameters, we're ready to train our best model and save the corresponding artifacts (label encoder, tokenizer, etc.)",
"_____no_output_____"
]
],
[
[
"# Train best model\ncli.train_model()",
"INFO: 'best' does not exist. Creating a new experiment\n[04/09/21 20:26:42] INFO Parameters: { main.py:101\n \"seed\": 1234, \n \"cuda\": true, \n \"shuffle\": true, \n \"num_samples\": null, \n \"min_tag_freq\": 30, \n \"lower\": true, \n \"stem\": false, \n \"train_size\": 0.7, \n \"char_level\": true, \n \"max_filter_size\": 10, \n \"batch_size\": 128, \n \"embedding_dim\": 503, \n \"num_filters\": 269, \n \"hidden_dim\": 443, \n \"dropout_p\": 0.374218478616704, \n \"lr\": 0.0004479615733949203, \n \"num_epochs\": 200, \n \"patience\": 10, \n \"threshold\": 0.32731616497039795 \n } \n[04/09/21 20:26:45] INFO Epoch: 1 | train_loss: 0.00627, train.py:178\n val_loss: 0.00422, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:26:48] INFO Epoch: 2 | train_loss: 0.00418, train.py:178\n val_loss: 0.00278, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:26:51] INFO Epoch: 3 | train_loss: 0.00297, train.py:178\n val_loss: 0.00241, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:26:53] INFO Epoch: 4 | train_loss: 0.00249, train.py:178\n val_loss: 0.00219, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:26:56] INFO Epoch: 5 | train_loss: 0.00209, train.py:178\n val_loss: 0.00191, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:26:59] INFO Epoch: 6 | train_loss: 0.00175, train.py:178\n val_loss: 0.00173, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:27:01] INFO Epoch: 7 | train_loss: 0.00150, train.py:178\n val_loss: 0.00160, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:27:04] INFO Epoch: 8 | train_loss: 0.00125, train.py:178\n val_loss: 0.00153, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:27:07] INFO Epoch: 9 | train_loss: 0.00107, train.py:178\n val_loss: 0.00148, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:27:10] INFO Epoch: 10 | train_loss: 0.00093, train.py:178\n val_loss: 0.00146, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:27:12] INFO Epoch: 11 | train_loss: 0.00078, train.py:178\n val_loss: 0.00146, lr: 4.48E-04, \n _patience: 9 \n[04/09/21 20:27:15] INFO Epoch: 12 | train_loss: 0.00067, train.py:178\n val_loss: 0.00143, lr: 4.48E-04, \n _patience: 10 \n[04/09/21 20:27:18] INFO Epoch: 13 | train_loss: 0.00057, train.py:178\n val_loss: 0.00146, lr: 4.48E-04, \n _patience: 9 \n[04/09/21 20:27:21] INFO Epoch: 14 | train_loss: 0.00048, train.py:178\n val_loss: 0.00146, lr: 4.48E-04, \n _patience: 8 \n[04/09/21 20:27:24] INFO Epoch: 15 | train_loss: 0.00040, train.py:178\n val_loss: 0.00147, lr: 4.48E-04, \n _patience: 7 \n[04/09/21 20:27:26] INFO Epoch: 16 | train_loss: 0.00035, train.py:178\n val_loss: 0.00146, lr: 4.48E-04, \n _patience: 6 \n[04/09/21 20:27:29] INFO Epoch: 17 | train_loss: 0.00031, train.py:178\n val_loss: 0.00153, lr: 4.48E-04, \n _patience: 5 \n[04/09/21 20:27:32] INFO Epoch: 18 | train_loss: 0.00027, train.py:178\n val_loss: 0.00148, lr: 2.24E-05, \n _patience: 4 \n[04/09/21 20:27:35] INFO Epoch: 19 | train_loss: 0.00025, train.py:178\n val_loss: 0.00148, lr: 2.24E-05, \n _patience: 3 \n[04/09/21 20:27:38] INFO Epoch: 20 | train_loss: 0.00023, train.py:178\n val_loss: 0.00150, lr: 2.24E-05, \n _patience: 2 \n[04/09/21 20:27:41] INFO Epoch: 21 | train_loss: 0.00023, train.py:178\n val_loss: 0.00151, lr: 2.24E-05, \n _patience: 1 \n[04/09/21 20:27:44] INFO Stopping early! train.py:173\n"
]
],
[
[
"# Change metadata",
"_____no_output_____"
],
[
"In order to transfer our trained model and it's artifacts to our local model registry, we should change the metadata to match.",
"_____no_output_____"
]
],
[
[
"from pathlib import Path\nfrom config import config\nimport yaml",
"_____no_output_____"
],
[
"def change_artifact_metadata(fp):\n with open(fp) as f:\n metadata = yaml.load(f)\n for key in [\"artifact_location\", \"artifact_uri\"]:\n if key in metadata:\n metadata[key] = metadata[key].replace(\n str(config.MODEL_REGISTRY), model_registry)\n with open(fp, \"w\") as f:\n yaml.dump(metadata, f)",
"_____no_output_____"
],
[
"# Change this as necessary\nmodel_registry = \"/Users/goku/Documents/madewithml/applied-ml/stores/model\"",
"_____no_output_____"
],
[
"# Change metadata in all meta.yaml files\nexperiment_dir = Path(config.MODEL_REGISTRY, \"1\")\nfor fp in list(Path(experiment_dir).glob(\"**/meta.yaml\")):\n change_artifact_metadata(fp=fp)",
"_____no_output_____"
]
],
[
[
"## Download",
"_____no_output_____"
],
[
"Download and transfer the trained model's files to your local model registry. If you existing runs, just transfer that run's directory.",
"_____no_output_____"
]
],
[
[
"from google.colab import files",
"_____no_output_____"
],
[
"# Download\n!zip -r model.zip model\n!zip -r run.zip stores/model/1\nfiles.download(\"run.zip\")",
" adding: stores/model/1/ (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/ (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/metrics/ (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/metrics/recall (deflated 3%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/metrics/precision (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/metrics/best_val_loss (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/metrics/slices_f1 (deflated 23%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/metrics/f1 (deflated 3%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/metrics/behavioral_score (deflated 37%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/ (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/batch_size (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/seed (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/char_level (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/lr (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/threshold (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/max_filter_size (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/dropout_p (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/train_size (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/min_tag_freq (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/hidden_dim (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/stem (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/cuda (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/lower (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/num_filters (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/num_samples (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/num_epochs (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/patience (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/embedding_dim (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/params/shuffle (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/tags/ (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/tags/mlflow.runName (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/tags/mlflow.source.type (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/tags/mlflow.user (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/tags/mlflow.source.name (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/meta.yaml (deflated 43%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/artifacts/ (stored 0%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/artifacts/model.pt (deflated 8%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/artifacts/tokenizer.json (deflated 69%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/artifacts/performance.json (deflated 86%)\n adding: stores/model/1/dce5cc211fbb474e9b86af40939be0ca/artifacts/label_encoder.json (deflated 62%)\n adding: stores/model/1/meta.yaml (deflated 16%)\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cbd3b6091f666e5ac4e42f3b119e6bd8524e85e8
| 13,773 |
ipynb
|
Jupyter Notebook
|
Exercise05/Exercise05.ipynb
|
Develop-Packt/Importance-of-Data-Visualization-and-Data-Exploration
|
74ed7ce4262b2f764d4395bc8b9e5fe5cedcc471
|
[
"MIT"
] | 1 |
2021-11-09T14:34:12.000Z
|
2021-11-09T14:34:12.000Z
|
Exercise05/Exercise05.ipynb
|
Develop-Packt/Importance-of-Data-Visualization-and-Data-Exploration
|
74ed7ce4262b2f764d4395bc8b9e5fe5cedcc471
|
[
"MIT"
] | null | null | null |
Exercise05/Exercise05.ipynb
|
Develop-Packt/Importance-of-Data-Visualization-and-Data-Exploration
|
74ed7ce4262b2f764d4395bc8b9e5fe5cedcc471
|
[
"MIT"
] | 3 |
2020-03-16T08:18:20.000Z
|
2022-02-05T05:48:40.000Z
| 26.69186 | 251 | 0.433094 |
[
[
[
"## Exercise 05: Using pandas to Compute the Mean, Median, and Variance of a Dataset",
"_____no_output_____"
],
[
"In this exercise, you will consolidate the skills you've acquired in the last exercise and use Pandas to do some very basic mathematical calculations on our `world_population.csv` dataset. \nPandas have consistent API, so it should be rather easy to transfer your knowledge of the mean method to median and variance. \nYour already existing knowledge of NumPy will also help.",
"_____no_output_____"
],
[
"#### Loading the dataset",
"_____no_output_____"
]
],
[
[
"# importing the necessary dependencies\nimport pandas as pd",
"_____no_output_____"
],
[
"# loading the Dataset\ndataset = pd.read_csv('../../Datasets/world_population.csv', index_col=0)",
"_____no_output_____"
],
[
"# looking at the first two rows of the dataset\ndataset[0:2]",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"#### Mean",
"_____no_output_____"
]
],
[
[
"# calculate the mean of the third row\ndataset.iloc[[2]].mean(axis=1)",
"_____no_output_____"
],
[
"# calculate the mean of the last row\ndataset.iloc[[-1]].mean(axis=1)",
"_____no_output_____"
],
[
"# calculate the mean of the country Germany\ndataset.loc[[\"Germany\"]].mean(axis=1)",
"_____no_output_____"
]
],
[
[
"**Note:** \n`.iloc()` and `.loc()` are two important methods when indexing with Pandas. They allow to make precise selections of data based on either the integer value index (`iloc`) or the index column (`loc`), which in our case is the country name column.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"#### Median",
"_____no_output_____"
]
],
[
[
"# calculate the median of the last row\ndataset.iloc[[-1]].median(axis=1)",
"_____no_output_____"
],
[
"# calculate the median of the last 3 rows\ndataset[-3:].median(axis=1)",
"_____no_output_____"
]
],
[
[
"**Note:** \nSlicing can be done in the same way as with NumPy. \n`dataset[1:3]` will return the second and third row of our dataset.",
"_____no_output_____"
]
],
[
[
"# calculate the median of the first 10 countries\ndataset.head(10).median(axis=1)",
"_____no_output_____"
]
],
[
[
"**Note:** \nWhen handling larger datasets, the order in which methods get executed definitely matters. \nThink about what `.head(10)` does for a moment, it simply takes your dataset and returns the first 10 rows of it, cutting down your input to the `.mean()` method drastically. \nThis will definitely have an impact when using more memory intensive calculations, so keep an eye on the order.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"#### Variance",
"_____no_output_____"
]
],
[
[
"# calculate the variance of the last 5 columns\ndataset.var().tail()",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
],
[
"As mentioned in the introduction of Pandas, it's interoperable with several of NumPy's features. \nHere's an example of how to use NumPy's `mean` method with a Pandas dataFrame.",
"_____no_output_____"
]
],
[
[
"# NumPy Pandas interoperability\nimport numpy as np\n\nprint(\"Pandas\", dataset[\"2015\"].mean())\nprint(\"NumPy\", np.mean(dataset[\"2015\"]))",
"Pandas 368.70660104001837\nNumPy 368.70660104001837\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
cbd3b7d52b7f87a27cb0adba57e11298a765cfe3
| 16,549 |
ipynb
|
Jupyter Notebook
|
_build/jupyter_execute/Lecture2/Expressions and Arithmetic.ipynb
|
ccha23/CS1302ICP
|
80907dae8d4d90b911e52dbea159629a221b9a3c
|
[
"CC0-1.0"
] | 2 |
2021-04-04T05:08:05.000Z
|
2022-01-24T08:10:36.000Z
|
_build/jupyter_execute/Lecture2/Expressions and Arithmetic.ipynb
|
ccha23/CS1302ICP
|
80907dae8d4d90b911e52dbea159629a221b9a3c
|
[
"CC0-1.0"
] | null | null | null |
_build/jupyter_execute/Lecture2/Expressions and Arithmetic.ipynb
|
ccha23/CS1302ICP
|
80907dae8d4d90b911e52dbea159629a221b9a3c
|
[
"CC0-1.0"
] | 1 |
2022-03-06T11:10:34.000Z
|
2022-03-06T11:10:34.000Z
| 24.265396 | 255 | 0.519669 |
[
[
[
"# Expressions and Arithmetic",
"_____no_output_____"
],
[
"**CS1302 Introduction to Computer Programming**\n___",
"_____no_output_____"
],
[
"## Operators",
"_____no_output_____"
],
[
"The followings are common operators you can use to form an expression in Python:",
"_____no_output_____"
],
[
"| Operator | Operation | Example |\n| --------: | :------------- | :-----: |\n| unary `-` | Negation | `-y` |\n| `+` | Addition | `x + y` |\n| `-` | Subtraction | `x - y` |\n| `*` | Multiplication | `x*y` |\n| `/` | Division | `x/y` |",
"_____no_output_____"
],
[
"- `x` and `y` in the examples are called the *left and right operands* respectively.\n- The first operator is a *unary operator*, which operates on just one operand. \n (`+` can also be used as a unary operator, but that is not useful.)\n- All other operators are *binary operators*, which operate on two operands.",
"_____no_output_____"
],
[
"Python also supports some more operators such as the followings:",
"_____no_output_____"
],
[
"| Operator | Operation | Example |\n| -------: | :--------------- | :-----: |\n| `//` | Integer division | `x//y` |\n| `%` | Modulo | `x%y` |\n| `**` | Exponentiation | `x**y` |",
"_____no_output_____"
]
],
[
[
"# ipywidgets to demonstrate the operations of binary operators\nfrom ipywidgets import interact\nbinary_operators = {'+':' + ','-':' - ','*':'*','/':'/','//':'//','%':'%','**':'**'}\n@interact(operand1=r'10',\n operator=binary_operators,\n operand2=r'3')\ndef binary_operation(operand1,operator,operand2):\n expression = f\"{operand1}{operator}{operand2}\"\n value = eval(expression)\n print(f\"\"\"{'Expression:':>11} {expression}\\n{'Value:':>11} {value}\\n{'Type:':>11} {type(value)}\"\"\")",
"_____no_output_____"
]
],
[
[
"**Exercise** What is the difference between `/` and `//`?",
"_____no_output_____"
],
[
"- `/` is the usual division, and so `10/3` returns the floating-point number $3.\\dot{3}$.\n- `//` is integer division, and so `10//3` gives the integer quotient 3.",
"_____no_output_____"
],
[
"**What does the modulo operator `%` do?**",
"_____no_output_____"
],
[
"You can think of it as computing the remainder, but the [truth](https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations) is more complicated than required for the course.",
"_____no_output_____"
],
[
"**Exercise** What does `'abc' * 3` mean? What about `10 * 'a'`?",
"_____no_output_____"
],
[
"- The first expression means concatenating `'abc'` three times.\n- The second means concatenating `'a'` ten times.",
"_____no_output_____"
],
[
"**Exercise** How can you change the default operands (`10` and `3`) for different operators so that the overall expression has type `float`. \nDo you need to change all the operands to `float`?",
"_____no_output_____"
],
[
"- `/` already returns a `float`.\n- For all other operators, changing at least one of the operands to `float` will return a `float`.",
"_____no_output_____"
],
[
"## Operator Precedence and Associativity",
"_____no_output_____"
],
[
"An expression can consist of a sequence of operations performed in a row such as `x + y*z`.",
"_____no_output_____"
],
[
"**How to determine which operation should be performed first?**",
"_____no_output_____"
],
[
"Like arithmetics, the order of operations is decided based on the following rules applied sequentially: \n1. *grouping* by parentheses: inner grouping first\n1. operator *precedence/priority*: higher precedence first\n1. operator *associativity*:\n - left associativity: left operand first\n - right associativity: right operand first",
"_____no_output_____"
],
[
"**What are the operator precedence and associativity?**",
"_____no_output_____"
],
[
"The following table gives a concise summary:",
"_____no_output_____"
],
[
"| Operators | Associativity |\n| :--------------- | :-----------: |\n| `**` | right |\n| `-` (unary) | right |\n| `*`,`/`,`//`,`%` | left |\n| `+`,`-` | left |",
"_____no_output_____"
],
[
"**Exercise** Play with the following widget to understand the precedence and associativity of different operators. \nIn particular, explain whether the expression `-10 ** 2*3` gives $(-10)^{2\\times 3}= 10^6 = 1000000$.",
"_____no_output_____"
]
],
[
[
"from ipywidgets import fixed\n@interact(operator1={'None':'','unary -':'-'},\n operand1=fixed(r'10'),\n operator2=binary_operators,\n operand2=fixed(r'2'),\n operator3=binary_operators,\n operand3=fixed(r'3')\n )\ndef three_operators(operator1,operand1,operator2,operand2,operator3,operand3):\n expression = f\"{operator1}{operand1}{operator2}{operand2}{operator3}{operand3}\"\n value = eval(expression)\n print(f\"\"\"{'Expression:':>11} {expression}\\n{'Value:':>11} {value}\\n{'Type:':>11} {type(value)}\"\"\")",
"_____no_output_____"
]
],
[
[
"The expression evaluates to $(-(10^2))\\times 3=-300$ instead because the exponentiation operator `**` has higher precedence than both the multiplication `*` and the negation operators `-`.",
"_____no_output_____"
],
[
"**Exercise** To avoid confusion in the order of operations, we should follow the [style guide](https://www.python.org/dev/peps/pep-0008/#other-recommendations) when writing expression. \nWhat is the proper way to write `-10 ** 2*3`? ",
"_____no_output_____"
]
],
[
[
"print(-10**2 * 3) # can use use code-prettify extension to fix incorrect styles\nprint((-10)**2 * 3)",
"_____no_output_____"
]
],
[
[
"## Augmented Assignment Operators",
"_____no_output_____"
],
[
"- For convenience, Python defines the [augmented assignment operators](https://docs.python.org/3/reference/simple_stmts.html#grammar-token-augmented-assignment-stmt) such as `+=`, where \n- `x += 1` means `x = x + 1`.",
"_____no_output_____"
],
[
"The following widgets demonstrate other augmented assignment operators.",
"_____no_output_____"
]
],
[
[
"from ipywidgets import interact, fixed\n@interact(initial_value=fixed(r'10'),\n operator=['+=','-=','*=','/=','//=','%=','**='],\n operand=fixed(r'2'))\ndef binary_operation(initial_value,operator,operand):\n assignment = f\"x = {initial_value}\\nx {operator} {operand}\"\n _locals = {}\n exec(assignment,None,_locals)\n print(f\"\"\"Assignments:\\n{assignment:>10}\\nx: {_locals['x']} ({type(_locals['x'])})\"\"\")",
"_____no_output_____"
]
],
[
[
"**Exercise** Can we create an expression using (augmented) assignment operators? Try running the code to see the effect.",
"_____no_output_____"
]
],
[
[
"3*(x = 15)",
"_____no_output_____"
]
],
[
[
"Assignment operators are used in assignment statements, which are not expressions because they cannot be evaluated.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbd3b88385492dc334679c2e1185552a222882e9
| 279,306 |
ipynb
|
Jupyter Notebook
|
Simulation/Stochastic_differential_equations.ipynb
|
ketsonroberto/StochasticProcesses
|
45d1029db0aa9ffef80bd4f0353a6b6331f40d2c
|
[
"MIT"
] | null | null | null |
Simulation/Stochastic_differential_equations.ipynb
|
ketsonroberto/StochasticProcesses
|
45d1029db0aa9ffef80bd4f0353a6b6331f40d2c
|
[
"MIT"
] | null | null | null |
Simulation/Stochastic_differential_equations.ipynb
|
ketsonroberto/StochasticProcesses
|
45d1029db0aa9ffef80bd4f0353a6b6331f40d2c
|
[
"MIT"
] | null | null | null | 793.482955 | 102,284 | 0.953152 |
[
[
[
"## Sample paths of stochastic processes.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"sigma = 1. # Standard deviation.\nmu = 10. # Mean.\ntau = .05 # Time constant.",
"_____no_output_____"
],
[
"dt = .001 # Time step.\nT = 1. # Total time.\nn = int(T / dt) # Number of time steps.\nt = np.linspace(0., T, n) # Vector of times.",
"_____no_output_____"
],
[
"sigma_bis = sigma * np.sqrt(2. / tau)\nsqrtdt = np.sqrt(dt)",
"_____no_output_____"
],
[
"x = np.zeros(n)",
"_____no_output_____"
],
[
"for i in range(n - 1):\n x[i + 1] = x[i] + dt * (-(x[i] - mu) / tau) + sigma_bis * sqrtdt * np.random.randn()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.plot(t, x, lw=2)",
"_____no_output_____"
],
[
"ntrials = 10000\nX = np.zeros(ntrials)",
"_____no_output_____"
],
[
"# We create bins for the histograms.\nbins = np.linspace(-2., 14., 100)\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nfor i in range(n):\n # We update the process independently for\n # all trials\n X += dt * (-(X - mu) / tau) + \\\n sigma_bis * sqrtdt * np.random.randn(ntrials)\n # We display the histogram for a few points in\n # time\n if i in (5, 50, 900):\n hist, _ = np.histogram(X, bins=bins)\n ax.plot((bins[1:] + bins[:-1]) / 2, hist,\n {5: '-', 50: '.', 900: '-.', }[i],\n label=f\"t={i * dt:.2f}\")\n ax.legend()",
"No handles with labels found to put in legend.\nNo handles with labels found to put in legend.\nNo handles with labels found to put in legend.\nNo handles with labels found to put in legend.\nNo handles with labels found to put in legend.\n"
]
],
[
[
"### Black-Scholes Equation.",
"_____no_output_____"
]
],
[
[
"sigma = 0.5 # Standard deviation.\nmu = 0.05 # Mean.\n\nx = np.zeros(n)\nx[0] = 1",
"_____no_output_____"
],
[
"for i in range(n - 1):\n x[i + 1] = x[i] + dt * (mu*x[i]) + (sigma*x[i]) * sqrtdt * np.random.randn()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 1, figsize=(8, 4))\nax.plot(t, x, lw=2)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(1, 1, figsize=(8, 4))\nfor samples in range(10): \n for i in range(n - 1):\n x[i + 1] = x[i] + dt * (mu*x[i]) + (sigma*x[i]) * sqrtdt * np.random.randn()\n \n ax.plot(t, x, lw=2)",
"_____no_output_____"
],
[
"def wiener_process(x0, n):\n\n w = np.ones(n)*x0\n\n for i in range(1,n):\n # Sampling from the Normal distribution\n yi = np.random.normal()\n # Weiner process\n w[i] = w[i-1]+(yi/np.sqrt(n))\n\n return w",
"_____no_output_____"
],
[
"x0 = 1\n\nfig, ax = plt.subplots(1, 1, figsize=(8, 4))\nfor samples in range(100): \n #xa = np.zeros(n)\n W = wiener_process(x0, n)\n #for i in range(n):\n xa = x0*np.exp((mu - sigma**2/2)*t+sigma*W)\n \n ax.plot(t, xa, lw=2)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd3be0d8332a8145d2e8e17aae46b0222d3a9d6
| 14,773 |
ipynb
|
Jupyter Notebook
|
resources/.ipynb_checkpoints/WITS Data ETL Process-checkpoint.ipynb
|
PaulBernert/World-Bank-Visualizations
|
8affb2a8a1180e02022c5c15dbfb014bd8d14f3c
|
[
"MIT"
] | null | null | null |
resources/.ipynb_checkpoints/WITS Data ETL Process-checkpoint.ipynb
|
PaulBernert/World-Bank-Visualizations
|
8affb2a8a1180e02022c5c15dbfb014bd8d14f3c
|
[
"MIT"
] | null | null | null |
resources/.ipynb_checkpoints/WITS Data ETL Process-checkpoint.ipynb
|
PaulBernert/World-Bank-Visualizations
|
8affb2a8a1180e02022c5c15dbfb014bd8d14f3c
|
[
"MIT"
] | null | null | null | 30.14898 | 243 | 0.399039 |
[
[
[
"### Load in CSVs, Libraries, etc.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom sqlalchemy import create_engine\nimport pymongo",
"_____no_output_____"
],
[
"summaryDATAFRAME = pd.read_csv('../herokuApp/static/data/witsSummaryData.csv')\nglanceDATAFRAME = pd.read_csv('../herokuApp/static/data/witsGlanceData.csv')",
"_____no_output_____"
]
],
[
[
"### 'Summary' DataFrame Transformations",
"_____no_output_____"
]
],
[
[
"summaryDF = summaryDATAFRAME.copy()\nsummaryDF = summaryDF.rename(columns={\"Reporter\":\"country\",\"Partner\":\"trade_partner\",\"Product categories\":\"category\",\"Indicator Type\":\"indicator_type\",\"Indicator\":\"indicator\"})\nsummaryDF.tail(5)",
"_____no_output_____"
]
],
[
[
"### 'At-a-Glance' DataFrame Transformations",
"_____no_output_____"
]
],
[
[
"glanceDF = glanceDATAFRAME.copy()\nglanceDF = glanceDF.rename(columns={\"Reporter\":\"country\",\"Partner\":\"trade_partner\",\"Product categories\":\"category\",\"Indicator Type\":\"indicator_type\",\"Indicator\":\"indicator\",\"Indicator Value\":\"indicator_value\"})\nglanceDF.head(5)",
"_____no_output_____"
]
],
[
[
"### Create Database Connection",
"_____no_output_____"
]
],
[
[
"engine = create_engine('postgresql://postgres:0607@localhost:5432/WITS')",
"_____no_output_____"
],
[
"summaryDF.to_sql('witssummary',engine,index=True)",
"_____no_output_____"
],
[
"glanceDF.to_sql('witsglance',engine,index=True)",
"_____no_output_____"
],
[
"conn = 'mongodb://localhost:27017'\nclient = pymongo.MongoClient(conn)\n\ndb = client.yourDBName",
"_____no_output_____"
],
[
"db.yourDBName.drop()",
"_____no_output_____"
],
[
"db.yourDBName.insert_many(yourDF.to_dict('records'))\n#OUTPUT\n# <pymongo.results.InsertManyResult at 0x21f574fb548>",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd3d031433ac6aa1c1b575e5f68f232b9ed21c2
| 100,666 |
ipynb
|
Jupyter Notebook
|
ReadBook/zh_gluon_ai/fashion-mnist/VGG.ipynb
|
nickliqian/ralph_doc_to_chinese
|
be120ce2bb94a8e8395630218985f5e51ae087d9
|
[
"MIT"
] | 8 |
2018-05-22T01:11:33.000Z
|
2020-03-19T01:44:55.000Z
|
ReadBook/zh_gluon_ai/fashion-mnist/VGG.ipynb
|
nickliqian/ralph_doc_to_chinese
|
be120ce2bb94a8e8395630218985f5e51ae087d9
|
[
"MIT"
] | null | null | null |
ReadBook/zh_gluon_ai/fashion-mnist/VGG.ipynb
|
nickliqian/ralph_doc_to_chinese
|
be120ce2bb94a8e8395630218985f5e51ae087d9
|
[
"MIT"
] | 3 |
2018-07-25T09:31:53.000Z
|
2019-09-14T14:05:31.000Z
| 42.031733 | 1,643 | 0.420758 |
[
[
[
"%matplotlib inline\nfrom IPython import display\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport time\n\nimport sys\nsys.path.append(\"../\")\nimport d2lzh1981 as d2l\n\nfrom tqdm import tqdm\n\nprint(torch.__version__)\nprint(torchvision.__version__)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"1.3.1\n0.4.2\n"
],
[
"mnist_train = torchvision.datasets.FashionMNIST(root='/Users/nick/Documents/dataset/FashionMNIST2065', \n train=True, download=False)\nmnist_test = torchvision.datasets.FashionMNIST(root='/Users/nick/Documents/dataset/FashionMNIST2065', \n train=False, download=False)",
"_____no_output_____"
],
[
"num_id = 0\nfor x, y in mnist_train:\n if num_id % 1000 == 0:\n print(num_id)\n x.save(\"/Users/nick/Documents/dataset/FashionMNIST_img/train/{}_{}.png\".format(y, num_id))\n num_id += 1\n",
"0\n1000\n2000\n3000\n4000\n5000\n6000\n7000\n8000\n9000\n10000\n11000\n12000\n13000\n14000\n15000\n16000\n17000\n18000\n19000\n20000\n21000\n22000\n23000\n24000\n25000\n26000\n27000\n28000\n29000\n30000\n31000\n32000\n33000\n34000\n35000\n36000\n37000\n38000\n39000\n40000\n41000\n42000\n43000\n44000\n45000\n46000\n47000\n48000\n49000\n50000\n51000\n52000\n53000\n54000\n55000\n56000\n57000\n58000\n59000\n"
],
[
"num_id = 0\nfor x, y in mnist_test:\n if num_id % 1000 == 0:\n print(num_id)\n x.save(\"/Users/nick/Documents/dataset/FashionMNIST_img/test/{}_{}.png\".format(y, num_id))\n num_id += 1\n",
"0\n1000\n2000\n3000\n4000\n5000\n6000\n7000\n8000\n9000\n"
],
[
"mnist_train = torchvision.datasets.FashionMNIST(root='/Users/nick/Documents/dataset/FashionMNIST2065', \n train=True, download=False, transform=transforms.ToTensor())\nmnist_test = torchvision.datasets.FashionMNIST(root='/Users/nick/Documents/dataset/FashionMNIST2065', \n train=False, download=False, transform=transforms.ToTensor())",
"_____no_output_____"
],
[
"def vgg_block(num_convs, in_channels, out_channels): #卷积层个数,输入通道数,输出通道数\n blk = []\n for i in range(num_convs):\n if i == 0:\n blk.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1))\n else:\n blk.append(nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1))\n blk.append(nn.ReLU())\n blk.append(nn.MaxPool2d(kernel_size=2, stride=2)) # 这里会使宽高减半\n return nn.Sequential(*blk)\n\ndef vgg(conv_arch, fc_features, fc_hidden_units=4096):\n net = nn.Sequential()\n # 卷积层部分\n for i, (num_convs, in_channels, out_channels) in enumerate(conv_arch):\n # 每经过一个vgg_block都会使宽高减半\n net.add_module(\"vgg_block_\" + str(i+1), vgg_block(num_convs, in_channels, out_channels))\n # 全连接层部分\n net.add_module(\"fc\", nn.Sequential(d2l.FlattenLayer(),\n nn.Linear(fc_features, fc_hidden_units),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(fc_hidden_units, fc_hidden_units),\n nn.ReLU(),\n nn.Dropout(0.5),\n nn.Linear(fc_hidden_units, 10)\n ))\n return net\n\ndef evaluate_accuracy(data_iter, net, device=None):\n if device is None and isinstance(net, torch.nn.Module):\n # 如果没指定device就使用net的device\n device = list(net.parameters())[0].device \n acc_sum, n = 0.0, 0\n with torch.no_grad():\n for X, y in data_iter:\n if isinstance(net, torch.nn.Module):\n net.eval() # 评估模式, 这会关闭dropout\n acc_sum += (net(X.to(device)).argmax(dim=1) == y.to(device)).float().sum().cpu().item()\n net.train() # 改回训练模式\n else: # 自定义的模型, 3.13节之后不会用到, 不考虑GPU\n if('is_training' in net.__code__.co_varnames): # 如果有is_training这个参数\n # 将is_training设置成False\n acc_sum += (net(X, is_training=False).argmax(dim=1) == y).float().sum().item() \n else:\n acc_sum += (net(X).argmax(dim=1) == y).float().sum().item() \n n += y.shape[0]\n return acc_sum / n",
"_____no_output_____"
],
[
"batch_size = 100\n\nif sys.platform.startswith('win'):\n num_workers = 0\nelse:\n num_workers = 4\n \ntrain_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, \n shuffle=True, num_workers=num_workers)\ntest_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, \n shuffle=False, num_workers=num_workers)",
"_____no_output_____"
],
[
"conv_arch = ((1, 1, 64), (1, 64, 128))\n# 经过5个vgg_block, 宽高会减半5次, 变成 224/32 = 7\nfc_features = 128 * 7 * 7 # c * w * h\nfc_hidden_units = 4096 # 任意\n\n# ratio = 8\n# small_conv_arch = [(1, 1, 64//ratio), (1, 64//ratio, 128//ratio), (2, 128//ratio, 256//ratio), \n# (2, 256//ratio, 512//ratio), (2, 512//ratio, 512//ratio)]\n# net = vgg(small_conv_arch, fc_features // ratio, fc_hidden_units // ratio)",
"_____no_output_____"
],
[
"net = vgg(conv_arch, fc_features, fc_hidden_units)\n\nlr, num_epochs = 0.001, 5\noptimizer = torch.optim.Adam(net.parameters(), lr=lr)\n\nnet = net.to(device)\nprint(\"training on \", device)\nloss = torch.nn.CrossEntropyLoss()",
"training on cpu\n"
],
[
"for epoch in range(num_epochs):\n train_l_sum, train_acc_sum, n, batch_count, start = 0.0, 0.0, 0, 0, time.time()\n for X, y in tqdm(train_iter):\n X = X.to(device)\n y = y.to(device)\n y_hat = net(X)\n l = loss(y_hat, y)\n optimizer.zero_grad()\n l.backward()\n optimizer.step()\n train_l_sum += l.cpu().item()\n train_acc_sum += (y_hat.argmax(dim=1) == y).sum().cpu().item()\n n += y.shape[0]\n batch_count += 1\n test_acc = evaluate_accuracy(test_iter, net)\n print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, time %.1f sec'\n % (epoch + 1, train_l_sum / batch_count, train_acc_sum / n, test_acc, time.time() - start))",
"\n\n 0%| | 0/600 [00:00<?, ?it/s]\u001b[A\u001b[A\n\n 0%| | 1/600 [00:01<15:08, 1.52s/it]\u001b[A\u001b[A\n\n 0%| | 2/600 [00:02<12:29, 1.25s/it]\u001b[A\u001b[A\n\n 0%| | 3/600 [00:02<10:43, 1.08s/it]\u001b[A\u001b[A\n\n 1%| | 4/600 [00:03<09:23, 1.06it/s]\u001b[A\u001b[A\n\n 1%| | 5/600 [00:04<08:26, 1.17it/s]\u001b[A\u001b[A\n\n 1%| | 6/600 [00:04<07:46, 1.27it/s]\u001b[A\u001b[A\n\n 1%| | 7/600 [00:05<07:18, 1.35it/s]\u001b[A\u001b[A\n\n 1%|▏ | 8/600 [00:06<07:01, 1.41it/s]\u001b[A\u001b[A\n\n 2%|▏ | 9/600 [00:06<06:48, 1.45it/s]\u001b[A\u001b[A\n\n 2%|▏ | 10/600 [00:07<06:36, 1.49it/s]\u001b[A\u001b[A\n\n 2%|▏ | 11/600 [00:07<06:31, 1.50it/s]\u001b[A\u001b[A\n\n 2%|▏ | 12/600 [00:08<06:25, 1.53it/s]\u001b[A\u001b[A\n\n 2%|▏ | 13/600 [00:09<06:19, 1.55it/s]\u001b[A\u001b[A\n\n 2%|▏ | 14/600 [00:09<06:17, 1.55it/s]\u001b[A\u001b[A\n\n 2%|▎ | 15/600 [00:10<06:13, 1.57it/s]\u001b[A\u001b[A\n\n 3%|▎ | 16/600 [00:11<06:12, 1.57it/s]\u001b[A\u001b[A\n\n 3%|▎ | 17/600 [00:11<06:12, 1.56it/s]\u001b[A\u001b[A\n\n 3%|▎ | 18/600 [00:12<06:15, 1.55it/s]\u001b[A\u001b[A\n\n 3%|▎ | 19/600 [00:13<06:22, 1.52it/s]\u001b[A\u001b[A\n\n 3%|▎ | 20/600 [00:13<06:45, 1.43it/s]\u001b[A\u001b[A\n\n 4%|▎ | 21/600 [00:14<06:45, 1.43it/s]\u001b[A\u001b[A\n\n 4%|▎ | 22/600 [00:15<06:46, 1.42it/s]\u001b[A\u001b[A\n\n 4%|▍ | 23/600 [00:15<06:34, 1.46it/s]\u001b[A\u001b[A\n\n 4%|▍ | 24/600 [00:16<06:25, 1.49it/s]\u001b[A\u001b[A\n\n 4%|▍ | 25/600 [00:17<06:18, 1.52it/s]\u001b[A\u001b[A\n\n 4%|▍ | 26/600 [00:17<06:13, 1.54it/s]\u001b[A\u001b[A\n\n 4%|▍ | 27/600 [00:18<06:08, 1.55it/s]\u001b[A\u001b[A\n\n 5%|▍ | 28/600 [00:19<06:05, 1.57it/s]\u001b[A\u001b[A\n\n 5%|▍ | 29/600 [00:19<06:06, 1.56it/s]\u001b[A\u001b[A\n\n 5%|▌ | 30/600 [00:20<06:06, 1.56it/s]\u001b[A\u001b[A\n\n 5%|▌ | 31/600 [00:21<06:06, 1.55it/s]\u001b[A\u001b[A\n\n 5%|▌ | 32/600 [00:21<06:19, 1.50it/s]\u001b[A\u001b[A\n\n 6%|▌ | 33/600 [00:22<06:15, 1.51it/s]\u001b[A\u001b[A\n\n 6%|▌ | 34/600 [00:23<06:09, 1.53it/s]\u001b[A\u001b[A\n\n 6%|▌ | 35/600 [00:23<06:08, 1.53it/s]\u001b[A\u001b[A\n\n 6%|▌ | 36/600 [00:24<06:10, 1.52it/s]\u001b[A\u001b[A\n\n 6%|▌ | 37/600 [00:25<06:16, 1.50it/s]\u001b[A\u001b[A\n\n 6%|▋ | 38/600 [00:25<06:42, 1.40it/s]\u001b[A\u001b[A\n\n 6%|▋ | 39/600 [00:26<06:36, 1.42it/s]\u001b[A\u001b[A\n\n 7%|▋ | 40/600 [00:27<06:32, 1.43it/s]\u001b[A\u001b[A\n\n 7%|▋ | 41/600 [00:27<06:23, 1.46it/s]\u001b[A\u001b[A\n\n 7%|▋ | 42/600 [00:28<06:18, 1.47it/s]\u001b[A\u001b[A\n\n 7%|▋ | 43/600 [00:29<06:15, 1.48it/s]\u001b[A\u001b[A\n\n 7%|▋ | 44/600 [00:29<06:14, 1.48it/s]\u001b[A\u001b[A\n\n 8%|▊ | 45/600 [00:30<06:23, 1.45it/s]\u001b[A\u001b[A\n\n 8%|▊ | 46/600 [00:31<06:20, 1.46it/s]\u001b[A\u001b[A\n\n 8%|▊ | 47/600 [00:31<06:16, 1.47it/s]\u001b[A\u001b[A\n\n 8%|▊ | 48/600 [00:32<06:17, 1.46it/s]\u001b[A\u001b[A\n\n 8%|▊ | 49/600 [00:33<06:18, 1.46it/s]\u001b[A\u001b[A\n\n 8%|▊ | 50/600 [00:34<06:14, 1.47it/s]\u001b[A\u001b[A\n\n 8%|▊ | 51/600 [00:34<06:16, 1.46it/s]\u001b[A\u001b[A\n\n 9%|▊ | 52/600 [00:35<06:20, 1.44it/s]\u001b[A\u001b[A\n\n 9%|▉ | 53/600 [00:36<06:19, 1.44it/s]\u001b[A\u001b[A\n\n 9%|▉ | 54/600 [00:36<06:20, 1.43it/s]\u001b[A\u001b[A\n\n 9%|▉ | 55/600 [00:37<06:33, 1.39it/s]\u001b[A\u001b[A\n\n 9%|▉ | 56/600 [00:38<06:24, 1.41it/s]\u001b[A\u001b[A\n\n 10%|▉ | 57/600 [00:38<06:18, 1.43it/s]\u001b[A\u001b[A\n\n 10%|▉ | 58/600 [00:39<06:24, 1.41it/s]\u001b[A\u001b[A\n\n 10%|▉ | 59/600 [00:40<06:21, 1.42it/s]\u001b[A\u001b[A\n\n 10%|█ | 60/600 [00:41<06:19, 1.42it/s]\u001b[A\u001b[A\n\n 10%|█ | 61/600 [00:41<06:14, 1.44it/s]\u001b[A\u001b[A\n\n 10%|█ | 62/600 [00:42<06:11, 1.45it/s]\u001b[A\u001b[A\n\n 10%|█ | 63/600 [00:43<06:17, 1.42it/s]\u001b[A\u001b[A\n\n 11%|█ | 64/600 [00:43<06:11, 1.44it/s]\u001b[A\u001b[A\n\n 11%|█ | 65/600 [00:44<06:15, 1.43it/s]\u001b[A\u001b[A\n\n 11%|█ | 66/600 [00:45<06:10, 1.44it/s]\u001b[A\u001b[A\n\n 11%|█ | 67/600 [00:45<06:03, 1.47it/s]\u001b[A\u001b[A\n\n 11%|█▏ | 68/600 [00:46<05:59, 1.48it/s]\u001b[A\u001b[A\n\n 12%|█▏ | 69/600 [00:47<05:58, 1.48it/s]\u001b[A\u001b[A\n\n 12%|█▏ | 70/600 [00:47<05:57, 1.48it/s]\u001b[A\u001b[A\n\n 12%|█▏ | 71/600 [00:48<05:54, 1.49it/s]\u001b[A\u001b[A\n\n 12%|█▏ | 72/600 [00:49<05:57, 1.48it/s]\u001b[A\u001b[A\n\n 12%|█▏ | 73/600 [00:49<05:59, 1.47it/s]\u001b[A\u001b[A\n\n 12%|█▏ | 74/600 [00:50<06:02, 1.45it/s]\u001b[A\u001b[A\n\n 12%|█▎ | 75/600 [00:51<06:01, 1.45it/s]\u001b[A\u001b[A\n\n 13%|█▎ | 76/600 [00:51<05:58, 1.46it/s]\u001b[A\u001b[A\n\n 13%|█▎ | 77/600 [00:52<05:57, 1.46it/s]\u001b[A\u001b[A\n\n 13%|█▎ | 78/600 [00:53<05:55, 1.47it/s]\u001b[A\u001b[A\n\n 13%|█▎ | 79/600 [00:54<05:54, 1.47it/s]\u001b[A\u001b[A\n\n 13%|█▎ | 80/600 [00:54<05:57, 1.46it/s]\u001b[A\u001b[A\n\n 14%|█▎ | 81/600 [00:55<05:51, 1.48it/s]\u001b[A\u001b[A\n\n 14%|█▎ | 82/600 [00:56<05:45, 1.50it/s]\u001b[A\u001b[A\n\n 14%|█▍ | 83/600 [00:56<05:38, 1.53it/s]\u001b[A\u001b[A\n\n 14%|█▍ | 84/600 [00:57<05:35, 1.54it/s]\u001b[A\u001b[A\n\n 14%|█▍ | 85/600 [00:57<05:36, 1.53it/s]\u001b[A\u001b[A\n\n 14%|█▍ | 86/600 [00:58<05:34, 1.54it/s]\u001b[A\u001b[A\n\n 14%|█▍ | 87/600 [00:59<05:33, 1.54it/s]\u001b[A\u001b[A\n\n 15%|█▍ | 88/600 [00:59<05:29, 1.55it/s]\u001b[A\u001b[A\n\n 15%|█▍ | 89/600 [01:00<05:27, 1.56it/s]\u001b[A\u001b[A\n\n 15%|█▌ | 90/600 [01:01<05:28, 1.55it/s]\u001b[A\u001b[A\n\n 15%|█▌ | 91/600 [01:01<05:25, 1.57it/s]\u001b[A\u001b[A\n\n 15%|█▌ | 92/600 [01:02<05:26, 1.56it/s]\u001b[A\u001b[A\n\n 16%|█▌ | 93/600 [01:03<05:23, 1.57it/s]\u001b[A\u001b[A\n\n 16%|█▌ | 94/600 [01:03<05:25, 1.56it/s]\u001b[A\u001b[A\n\n 16%|█▌ | 95/600 [01:04<05:38, 1.49it/s]\u001b[A\u001b[A\n\n 16%|█▌ | 96/600 [01:05<05:47, 1.45it/s]\u001b[A\u001b[A\n\n 16%|█▌ | 97/600 [01:05<05:56, 1.41it/s]\u001b[A\u001b[A\n\n 16%|█▋ | 98/600 [01:06<06:01, 1.39it/s]\u001b[A\u001b[A\n\n 16%|█▋ | 99/600 [01:07<06:01, 1.39it/s]\u001b[A\u001b[A\n\n 17%|█▋ | 100/600 [01:08<06:03, 1.38it/s]\u001b[A\u001b[A\n\n 17%|█▋ | 101/600 [01:08<05:56, 1.40it/s]\u001b[A\u001b[A\n\n 17%|█▋ | 102/600 [01:09<05:52, 1.41it/s]\u001b[A\u001b[A\n\n 17%|█▋ | 103/600 [01:10<05:48, 1.43it/s]\u001b[A\u001b[A\n\n 17%|█▋ | 104/600 [01:10<05:42, 1.45it/s]\u001b[A\u001b[A\n\n 18%|█▊ | 105/600 [01:11<05:42, 1.44it/s]\u001b[A\u001b[A\n\n 18%|█▊ | 106/600 [01:12<06:00, 1.37it/s]\u001b[A\u001b[A\n\n 18%|█▊ | 107/600 [01:13<06:03, 1.36it/s]\u001b[A\u001b[A\n\n 18%|█▊ | 108/600 [01:13<05:57, 1.38it/s]\u001b[A\u001b[A\n\n 18%|█▊ | 109/600 [01:14<05:44, 1.43it/s]\u001b[A\u001b[A\n\n 18%|█▊ | 110/600 [01:15<05:42, 1.43it/s]\u001b[A\u001b[A\n\n 18%|█▊ | 111/600 [01:15<05:33, 1.47it/s]\u001b[A\u001b[A\n\n 19%|█▊ | 112/600 [01:16<05:30, 1.48it/s]\u001b[A\u001b[A\n\n 19%|█▉ | 113/600 [01:17<05:26, 1.49it/s]\u001b[A\u001b[A\n\n 19%|█▉ | 114/600 [01:17<05:21, 1.51it/s]\u001b[A\u001b[A\n\n 19%|█▉ | 115/600 [01:18<05:24, 1.49it/s]\u001b[A\u001b[A\n\n 19%|█▉ | 116/600 [01:19<05:23, 1.50it/s]\u001b[A\u001b[A\n\n 20%|█▉ | 117/600 [01:19<05:27, 1.48it/s]\u001b[A\u001b[A\n\n 20%|█▉ | 118/600 [01:20<05:27, 1.47it/s]\u001b[A\u001b[A\n\n 20%|█▉ | 119/600 [01:21<05:26, 1.48it/s]\u001b[A\u001b[A\n\n 20%|██ | 120/600 [01:21<05:31, 1.45it/s]\u001b[A\u001b[A\n\n 20%|██ | 121/600 [01:22<05:31, 1.45it/s]\u001b[A\u001b[A\n\n 20%|██ | 122/600 [01:23<05:28, 1.46it/s]\u001b[A\u001b[A\n\n 20%|██ | 123/600 [01:23<05:21, 1.48it/s]\u001b[A\u001b[A\n\n 21%|██ | 124/600 [01:24<05:19, 1.49it/s]\u001b[A\u001b[A\n\n 21%|██ | 125/600 [01:25<05:22, 1.47it/s]\u001b[A\u001b[A\n\n 21%|██ | 126/600 [01:26<05:27, 1.45it/s]\u001b[A\u001b[A\n\n 21%|██ | 127/600 [01:26<05:35, 1.41it/s]\u001b[A\u001b[A\n\n 21%|██▏ | 128/600 [01:27<05:43, 1.37it/s]\u001b[A\u001b[A\n\n 22%|██▏ | 129/600 [01:28<05:41, 1.38it/s]\u001b[A\u001b[A\n\n 22%|██▏ | 130/600 [01:28<05:28, 1.43it/s]\u001b[A\u001b[A\n\n 22%|██▏ | 131/600 [01:29<05:24, 1.45it/s]\u001b[A\u001b[A\n\n 22%|██▏ | 132/600 [01:30<05:24, 1.44it/s]\u001b[A\u001b[A\n\n 22%|██▏ | 133/600 [01:30<05:22, 1.45it/s]\u001b[A\u001b[A\n\n 22%|██▏ | 134/600 [01:31<05:15, 1.48it/s]\u001b[A\u001b[A\n\n 22%|██▎ | 135/600 [01:32<05:22, 1.44it/s]\u001b[A\u001b[A\n\n 23%|██▎ | 136/600 [01:33<05:24, 1.43it/s]\u001b[A\u001b[A\n\n 23%|██▎ | 137/600 [01:33<05:19, 1.45it/s]\u001b[A\u001b[A\n\n 23%|██▎ | 138/600 [01:34<05:12, 1.48it/s]\u001b[A\u001b[A\n\n 23%|██▎ | 139/600 [01:35<05:09, 1.49it/s]\u001b[A\u001b[A\n\n 23%|██▎ | 140/600 [01:35<05:12, 1.47it/s]\u001b[A\u001b[A\n\n 24%|██▎ | 141/600 [01:36<05:11, 1.47it/s]\u001b[A\u001b[A\n\n 24%|██▎ | 142/600 [01:37<05:05, 1.50it/s]\u001b[A\u001b[A\n\n 24%|██▍ | 143/600 [01:37<05:01, 1.52it/s]\u001b[A\u001b[A\n\n 24%|██▍ | 144/600 [01:38<05:01, 1.51it/s]\u001b[A\u001b[A\n\n 24%|██▍ | 145/600 [01:38<04:58, 1.52it/s]\u001b[A\u001b[A\n\n 24%|██▍ | 146/600 [01:39<04:57, 1.53it/s]\u001b[A\u001b[A\n\n 24%|██▍ | 147/600 [01:40<04:58, 1.52it/s]\u001b[A\u001b[A\n\n 25%|██▍ | 148/600 [01:40<04:54, 1.53it/s]\u001b[A\u001b[A\n\n 25%|██▍ | 149/600 [01:41<04:53, 1.54it/s]\u001b[A\u001b[A\n\n 25%|██▌ | 150/600 [01:42<05:00, 1.50it/s]\u001b[A\u001b[A\n\n 25%|██▌ | 151/600 [01:42<04:56, 1.51it/s]\u001b[A\u001b[A\n\n 25%|██▌ | 152/600 [01:43<04:52, 1.53it/s]\u001b[A\u001b[A\n\n 26%|██▌ | 153/600 [01:44<04:52, 1.53it/s]\u001b[A\u001b[A\n\n 26%|██▌ | 154/600 [01:44<04:52, 1.53it/s]\u001b[A\u001b[A\n\n 26%|██▌ | 155/600 [01:45<04:49, 1.53it/s]\u001b[A\u001b[A\n\n 26%|██▌ | 156/600 [01:46<04:50, 1.53it/s]\u001b[A\u001b[A\n\n 26%|██▌ | 157/600 [01:46<04:49, 1.53it/s]\u001b[A\u001b[A\n\n 26%|██▋ | 158/600 [01:47<04:51, 1.52it/s]\u001b[A\u001b[A\n\n 26%|██▋ | 159/600 [01:48<05:00, 1.47it/s]\u001b[A\u001b[A\n\n 27%|██▋ | 160/600 [01:48<04:57, 1.48it/s]\u001b[A\u001b[A\n\n 27%|██▋ | 161/600 [01:49<05:03, 1.45it/s]\u001b[A\u001b[A\n\n 27%|██▋ | 162/600 [01:50<05:08, 1.42it/s]\u001b[A\u001b[A\n\n 27%|██▋ | 163/600 [01:51<05:05, 1.43it/s]\u001b[A\u001b[A\n\n 27%|██▋ | 164/600 [01:51<04:57, 1.46it/s]\u001b[A\u001b[A\n\n 28%|██▊ | 165/600 [01:52<04:52, 1.49it/s]\u001b[A\u001b[A\n\n 28%|██▊ | 166/600 [01:53<04:52, 1.49it/s]\u001b[A\u001b[A\n\n 28%|██▊ | 167/600 [01:53<04:51, 1.49it/s]\u001b[A\u001b[A\n\n 28%|██▊ | 168/600 [01:54<04:49, 1.49it/s]\u001b[A\u001b[A\n\n 28%|██▊ | 169/600 [01:55<04:49, 1.49it/s]\u001b[A\u001b[A\n\n 28%|██▊ | 170/600 [01:55<04:45, 1.51it/s]\u001b[A\u001b[A\n\n 28%|██▊ | 171/600 [01:56<04:44, 1.51it/s]\u001b[A\u001b[A\n\n 29%|██▊ | 172/600 [01:56<04:42, 1.52it/s]\u001b[A\u001b[A\n\n 29%|██▉ | 173/600 [01:57<04:38, 1.53it/s]\u001b[A\u001b[A\n\n 29%|██▉ | 174/600 [01:58<04:41, 1.51it/s]\u001b[A\u001b[A\n\n 29%|██▉ | 175/600 [01:59<04:46, 1.49it/s]\u001b[A\u001b[A\n\n 29%|██▉ | 176/600 [01:59<04:43, 1.49it/s]\u001b[A\u001b[A\n\n 30%|██▉ | 177/600 [02:00<04:41, 1.50it/s]\u001b[A\u001b[A\n\n 30%|██▉ | 178/600 [02:00<04:40, 1.50it/s]\u001b[A\u001b[A\n\n 30%|██▉ | 179/600 [02:01<04:43, 1.48it/s]\u001b[A\u001b[A\n\n 30%|███ | 180/600 [02:02<04:40, 1.50it/s]\u001b[A\u001b[A\n\n 30%|███ | 181/600 [02:02<04:33, 1.53it/s]\u001b[A\u001b[A\n\n 30%|███ | 182/600 [02:03<04:32, 1.54it/s]\u001b[A\u001b[A\n\n 30%|███ | 183/600 [02:04<04:31, 1.54it/s]\u001b[A\u001b[A\n\n 31%|███ | 184/600 [02:04<04:28, 1.55it/s]\u001b[A\u001b[A\n\n 31%|███ | 185/600 [02:05<04:34, 1.51it/s]\u001b[A\u001b[A\n\n 31%|███ | 186/600 [02:06<04:43, 1.46it/s]\u001b[A\u001b[A\n\n 31%|███ | 187/600 [02:07<04:52, 1.41it/s]\u001b[A\u001b[A\n\n 31%|███▏ | 188/600 [02:07<04:49, 1.42it/s]\u001b[A\u001b[A\n\n 32%|███▏ | 189/600 [02:08<04:44, 1.44it/s]\u001b[A\u001b[A\n\n 32%|███▏ | 190/600 [02:09<04:42, 1.45it/s]\u001b[A\u001b[A\n\n 32%|███▏ | 191/600 [02:09<04:46, 1.43it/s]\u001b[A\u001b[A\n\n 32%|███▏ | 192/600 [02:10<04:44, 1.44it/s]\u001b[A\u001b[A\n\n 32%|███▏ | 193/600 [02:11<04:50, 1.40it/s]\u001b[A\u001b[A\n\n 32%|███▏ | 194/600 [02:11<04:47, 1.41it/s]\u001b[A\u001b[A\n\n 32%|███▎ | 195/600 [02:12<04:46, 1.41it/s]\u001b[A\u001b[A\n\n 33%|███▎ | 196/600 [02:13<04:45, 1.42it/s]\u001b[A\u001b[A\n\n 33%|███▎ | 197/600 [02:14<04:39, 1.44it/s]\u001b[A\u001b[A\n\n 33%|███▎ | 198/600 [02:14<04:43, 1.42it/s]\u001b[A\u001b[A\n\n 33%|███▎ | 199/600 [02:15<04:39, 1.44it/s]\u001b[A\u001b[A\n\n 33%|███▎ | 200/600 [02:16<04:33, 1.46it/s]\u001b[A\u001b[A\n\n 34%|███▎ | 201/600 [02:16<04:33, 1.46it/s]\u001b[A\u001b[A\n\n 34%|███▎ | 202/600 [02:17<04:34, 1.45it/s]\u001b[A\u001b[A\n\n 34%|███▍ | 203/600 [02:18<04:29, 1.47it/s]\u001b[A\u001b[A\n\n 34%|███▍ | 204/600 [02:18<04:29, 1.47it/s]\u001b[A\u001b[A\n\n 34%|███▍ | 205/600 [02:19<04:29, 1.46it/s]\u001b[A\u001b[A\n\n 34%|███▍ | 206/600 [02:20<04:34, 1.44it/s]\u001b[A\u001b[A\n\n 34%|███▍ | 207/600 [02:21<04:37, 1.41it/s]\u001b[A\u001b[A\n\n 35%|███▍ | 208/600 [02:21<04:31, 1.44it/s]\u001b[A\u001b[A\n\n 35%|███▍ | 209/600 [02:22<04:23, 1.48it/s]\u001b[A\u001b[A\n\n 35%|███▌ | 210/600 [02:22<04:21, 1.49it/s]\u001b[A\u001b[A\n\n 35%|███▌ | 211/600 [02:23<04:29, 1.44it/s]\u001b[A\u001b[A\n\n 35%|███▌ | 212/600 [02:24<04:33, 1.42it/s]\u001b[A\u001b[A\n\n 36%|███▌ | 213/600 [02:25<04:36, 1.40it/s]\u001b[A\u001b[A\n\n 36%|███▌ | 214/600 [02:25<04:33, 1.41it/s]\u001b[A\u001b[A\n\n 36%|███▌ | 215/600 [02:26<04:30, 1.43it/s]\u001b[A\u001b[A\n\n 36%|███▌ | 216/600 [02:27<04:25, 1.44it/s]\u001b[A\u001b[A\n\n 36%|███▌ | 217/600 [02:27<04:21, 1.46it/s]\u001b[A\u001b[A\n\n 36%|███▋ | 218/600 [02:28<04:30, 1.41it/s]\u001b[A\u001b[A\n\n 36%|███▋ | 219/600 [02:29<04:29, 1.41it/s]\u001b[A\u001b[A\n\n 37%|███▋ | 220/600 [02:30<04:26, 1.43it/s]\u001b[A\u001b[A\n\n 37%|███▋ | 221/600 [02:30<04:22, 1.44it/s]\u001b[A\u001b[A\n\n 37%|███▋ | 222/600 [02:31<04:18, 1.46it/s]\u001b[A\u001b[A\n\n 37%|███▋ | 223/600 [02:32<04:17, 1.47it/s]\u001b[A\u001b[A\n\n 37%|███▋ | 224/600 [02:32<04:21, 1.44it/s]\u001b[A\u001b[A\n\n 38%|███▊ | 225/600 [02:33<04:18, 1.45it/s]\u001b[A\u001b[A\n\n 38%|███▊ | 226/600 [02:34<04:19, 1.44it/s]\u001b[A\u001b[A\n\n 38%|███▊ | 227/600 [02:34<04:18, 1.45it/s]\u001b[A\u001b[A\n\n 38%|███▊ | 228/600 [02:35<04:22, 1.42it/s]\u001b[A\u001b[A\n\n 38%|███▊ | 229/600 [02:36<04:27, 1.39it/s]\u001b[A\u001b[A\n\n 38%|███▊ | 230/600 [02:37<04:37, 1.33it/s]\u001b[A\u001b[A\n\n 38%|███▊ | 231/600 [02:38<04:45, 1.29it/s]\u001b[A\u001b[A\n\n 39%|███▊ | 232/600 [02:38<04:45, 1.29it/s]\u001b[A\u001b[A\n\n 39%|███▉ | 233/600 [02:39<04:41, 1.31it/s]\u001b[A\u001b[A\n\n 39%|███▉ | 234/600 [02:40<04:32, 1.34it/s]\u001b[A\u001b[A\n\n 39%|███▉ | 235/600 [02:40<04:27, 1.36it/s]\u001b[A\u001b[A\n\n 39%|███▉ | 236/600 [02:41<04:29, 1.35it/s]\u001b[A\u001b[A\n\n 40%|███▉ | 237/600 [02:42<04:35, 1.32it/s]\u001b[A\u001b[A\n\n 40%|███▉ | 238/600 [02:43<04:31, 1.34it/s]\u001b[A\u001b[A\n\n 40%|███▉ | 239/600 [02:43<04:27, 1.35it/s]\u001b[A\u001b[A\n\n 40%|████ | 240/600 [02:44<04:26, 1.35it/s]\u001b[A\u001b[A\n\n 40%|████ | 241/600 [02:45<04:34, 1.31it/s]\u001b[A\u001b[A\n\n 40%|████ | 242/600 [02:46<04:36, 1.30it/s]\u001b[A\u001b[A\n\n 40%|████ | 243/600 [02:46<04:27, 1.33it/s]\u001b[A\u001b[A\n\n 41%|████ | 244/600 [02:47<04:29, 1.32it/s]\u001b[A\u001b[A\n\n 41%|████ | 245/600 [02:48<04:22, 1.35it/s]\u001b[A\u001b[A\n\n 41%|████ | 246/600 [02:49<04:19, 1.36it/s]\u001b[A\u001b[A\n\n 41%|████ | 247/600 [02:49<04:15, 1.38it/s]\u001b[A\u001b[A\n\n 41%|████▏ | 248/600 [02:50<04:12, 1.39it/s]\u001b[A\u001b[A\n\n 42%|████▏ | 249/600 [02:51<04:11, 1.39it/s]\u001b[A\u001b[A\n\n 42%|████▏ | 250/600 [02:51<04:07, 1.41it/s]\u001b[A\u001b[A\n\n 42%|████▏ | 251/600 [02:52<04:07, 1.41it/s]\u001b[A\u001b[A\n\n 42%|████▏ | 252/600 [02:53<04:02, 1.44it/s]\u001b[A\u001b[A\n\n 42%|████▏ | 253/600 [02:54<04:00, 1.44it/s]\u001b[A\u001b[A\n\n 42%|████▏ | 254/600 [02:54<03:57, 1.46it/s]\u001b[A\u001b[A\n\n 42%|████▎ | 255/600 [02:55<04:02, 1.42it/s]\u001b[A\u001b[A\n\n 43%|████▎ | 256/600 [02:56<04:00, 1.43it/s]\u001b[A\u001b[A\n\n 43%|████▎ | 257/600 [02:56<03:55, 1.46it/s]\u001b[A\u001b[A\n\n 43%|████▎ | 258/600 [02:57<03:53, 1.47it/s]\u001b[A\u001b[A\n\n 43%|████▎ | 259/600 [02:58<03:49, 1.49it/s]\u001b[A\u001b[A\n\n 43%|████▎ | 260/600 [02:58<03:46, 1.50it/s]\u001b[A\u001b[A\n\n 44%|████▎ | 261/600 [02:59<03:47, 1.49it/s]\u001b[A\u001b[A\n\n 44%|████▎ | 262/600 [03:00<03:45, 1.50it/s]\u001b[A\u001b[A\n\n 44%|████▍ | 263/600 [03:00<03:44, 1.50it/s]\u001b[A\u001b[A\n\n 44%|████▍ | 264/600 [03:01<03:46, 1.48it/s]\u001b[A\u001b[A\n\n 44%|████▍ | 265/600 [03:02<03:48, 1.47it/s]\u001b[A\u001b[A\n\n 44%|████▍ | 266/600 [03:02<03:48, 1.46it/s]\u001b[A\u001b[A\n\n 44%|████▍ | 267/600 [03:03<03:48, 1.46it/s]\u001b[A\u001b[A\n\n 45%|████▍ | 268/600 [03:04<03:48, 1.45it/s]\u001b[A\u001b[A\n\n 45%|████▍ | 269/600 [03:04<03:46, 1.46it/s]\u001b[A\u001b[A\n\n 45%|████▌ | 270/600 [03:05<03:43, 1.48it/s]\u001b[A\u001b[A\n\n 45%|████▌ | 271/600 [03:06<03:43, 1.47it/s]\u001b[A\u001b[A\n\n 45%|████▌ | 272/600 [03:06<03:39, 1.50it/s]\u001b[A\u001b[A\n\n 46%|████▌ | 273/600 [03:07<03:39, 1.49it/s]\u001b[A\u001b[A\n\n 46%|████▌ | 274/600 [03:08<03:45, 1.45it/s]\u001b[A\u001b[A\n\n 46%|████▌ | 275/600 [03:09<03:50, 1.41it/s]\u001b[A\u001b[A\n\n 46%|████▌ | 276/600 [03:09<03:45, 1.43it/s]\u001b[A\u001b[A\n\n 46%|████▌ | 277/600 [03:10<03:44, 1.44it/s]\u001b[A\u001b[A\n\n 46%|████▋ | 278/600 [03:11<03:41, 1.45it/s]\u001b[A\u001b[A\n\n 46%|████▋ | 279/600 [03:11<03:42, 1.44it/s]\u001b[A\u001b[A\n\n 47%|████▋ | 280/600 [03:12<03:37, 1.47it/s]\u001b[A\u001b[A\n\n 47%|████▋ | 281/600 [03:13<03:37, 1.47it/s]\u001b[A\u001b[A\n\n 47%|████▋ | 282/600 [03:13<03:36, 1.47it/s]\u001b[A\u001b[A\n\n 47%|████▋ | 283/600 [03:14<03:32, 1.49it/s]\u001b[A\u001b[A\n\n 47%|████▋ | 284/600 [03:15<03:40, 1.43it/s]\u001b[A\u001b[A\n\n 48%|████▊ | 285/600 [03:15<03:43, 1.41it/s]\u001b[A\u001b[A\n\n 48%|████▊ | 286/600 [03:16<03:48, 1.37it/s]\u001b[A\u001b[A\n\n 48%|████▊ | 287/600 [03:17<03:52, 1.35it/s]\u001b[A\u001b[A\n\n"
],
[
"test_acc = evaluate_accuracy(test_iter, net)\ntest_acc",
"_____no_output_____"
],
[
"for X, y in train_iter:\n X = X.to(device)\n predict_y = net(X)\n print(y)\n print(predict_y.argmax(dim=1))\n break\n\n# predict_y.argmax(dim=1)",
"tensor([0, 3, 3, 5, 7, 2, 6, 9, 6, 7, 9, 4, 6, 8, 8, 5, 9, 3, 5, 6, 4, 2, 3, 5,\n 0, 6, 7, 6, 4, 6, 3, 9, 3, 4, 3, 0, 7, 5, 0, 0, 1, 4, 9, 7, 4, 6, 6, 9,\n 6, 7, 3, 5, 3, 1, 2, 8, 0, 3, 6, 8, 7, 4, 6, 9, 4, 1, 0, 8, 6, 0, 2, 3,\n 9, 2, 9, 5, 1, 2, 1, 6, 3, 8, 3, 3, 2, 3, 4, 8, 6, 7, 4, 7, 8, 6, 8, 4,\n 7, 7, 1, 2])\ntensor([6, 4, 3, 5, 7, 2, 4, 9, 6, 7, 9, 4, 4, 8, 8, 5, 9, 3, 5, 6, 4, 4, 3, 5,\n 0, 6, 7, 4, 4, 3, 3, 9, 3, 4, 3, 2, 7, 5, 0, 0, 1, 4, 9, 7, 4, 6, 6, 9,\n 0, 7, 3, 5, 3, 1, 2, 8, 6, 3, 6, 8, 9, 4, 6, 9, 4, 1, 0, 8, 6, 6, 6, 3,\n 9, 2, 9, 5, 1, 2, 1, 4, 3, 8, 3, 3, 2, 3, 4, 8, 6, 7, 4, 7, 8, 6, 8, 4,\n 7, 7, 1, 2])\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd3de6bec61d311fc94760df4b18dd3e66a4e9a
| 318,892 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/Project1_Draft1-checkpoint.ipynb
|
mraitor/AA222Project1_2020
|
5a3234e443cadf1d222b5eb83bfdaa2364d7418a
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Project1_Draft1-checkpoint.ipynb
|
mraitor/AA222Project1_2020
|
5a3234e443cadf1d222b5eb83bfdaa2364d7418a
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Project1_Draft1-checkpoint.ipynb
|
mraitor/AA222Project1_2020
|
5a3234e443cadf1d222b5eb83bfdaa2364d7418a
|
[
"MIT"
] | null | null | null | 206.938352 | 33,852 | 0.687734 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbd3ded51ee82a9c4612ef3906ef611138e39f6d
| 3,399 |
ipynb
|
Jupyter Notebook
|
problems/0021/solution.ipynb
|
Dynortice/didactic-rotary-phone
|
99a0201b5d5f147eab77fc52d9db8995045cded0
|
[
"MIT"
] | null | null | null |
problems/0021/solution.ipynb
|
Dynortice/didactic-rotary-phone
|
99a0201b5d5f147eab77fc52d9db8995045cded0
|
[
"MIT"
] | null | null | null |
problems/0021/solution.ipynb
|
Dynortice/didactic-rotary-phone
|
99a0201b5d5f147eab77fc52d9db8995045cded0
|
[
"MIT"
] | null | null | null | 21.512658 | 205 | 0.482201 |
[
[
[
"# Problem 21\n## Amicable numbers\n\nLet $d(n)$ be defined as the sum of proper divisors of $n$ (numbers less than $n$ which divide evenly into $n$).\n\nIf $d(a) = b$ and $d(b) = a$, where $a \\ne b$, then $a$ and $b$ are an amicable pair and each of $a$ and $b$ are called amicable numbers.\n\nFor example, the proper divisors of $220$ are $1, 2, 4, 5, 10, 11, 20, 22, 44, 55$ and $110$; therefore $d(220) = 284$. The proper divisors of $284$ are $1, 2, 4, 71$ and $142$; so $d(284) = 220$.\n\nEvaluate the sum of all the amicable numbers under $10000$.\n\nOEIS Sequence: [A063990](https://oeis.org/A063990)\n\n## Solution",
"_____no_output_____"
]
],
[
[
"from math import isqrt\nfrom euler.primes import prime_numbers\nfrom euler.numbers import sum_proper_divisors",
"_____no_output_____"
],
[
"def compute(n: int) -> int:\n primes = list(prime_numbers(isqrt(n)))\n sum_factors = [0] * (n + 1)\n result = 0\n for i in range(1, n + 1):\n sum_factors[i] = sum_proper_divisors(i)\n for i in range(2, n + 1):\n j = sum_factors[i]\n if j != i and j <= n and sum_factors[j] == i:\n result += i\n return result",
"_____no_output_____"
],
[
"compute(1_000)",
"_____no_output_____"
],
[
"compute(10_000)",
"_____no_output_____"
],
[
"%timeit -n 100 -r 1 -p 6 compute(10_000)",
"132.57 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 100 loops each)\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbd3ea04f734ae170c23e4b3fb286652028f5e73
| 83,647 |
ipynb
|
Jupyter Notebook
|
Chapter13_CaseStudies/CaseStudyIncome/USIncome_model4.ipynb
|
franneck94/UdemyML
|
f495d557ad34560a84827a52eb6174d7c4c3f3ff
|
[
"MIT"
] | 8 |
2020-11-01T13:22:02.000Z
|
2022-03-18T09:28:12.000Z
|
Chapter13_CaseStudies/CaseStudyIncome/USIncome_model4.ipynb
|
franneck94/UdemyML
|
f495d557ad34560a84827a52eb6174d7c4c3f3ff
|
[
"MIT"
] | null | null | null |
Chapter13_CaseStudies/CaseStudyIncome/USIncome_model4.ipynb
|
franneck94/UdemyML
|
f495d557ad34560a84827a52eb6174d7c4c3f3ff
|
[
"MIT"
] | 9 |
2020-09-09T08:20:30.000Z
|
2022-01-08T09:59:59.000Z
| 92.735033 | 18,226 | 0.724079 |
[
[
[
"import os\nimport numpy as np\nnp.random.seed(0)\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import set_config\nset_config(display=\"diagram\")",
"_____no_output_____"
],
[
"DATA_PATH = os.path.abspath(\n r\"C:\\Users\\jan\\Dropbox\\_Coding\\UdemyML\\Chapter13_CaseStudies\\CaseStudyIncome\\adult.xlsx\"\n)",
"_____no_output_____"
]
],
[
[
"### Dataset",
"_____no_output_____"
]
],
[
[
"df = pd.read_excel(DATA_PATH)",
"_____no_output_____"
],
[
"idx = np.where(df[\"native-country\"] == \"Holand-Netherlands\")[0]",
"_____no_output_____"
],
[
"data = df.to_numpy()\n\nx = data[:, :-1]\nx = np.delete(x, idx, axis=0)\ny = data[:, -1]\ny = np.delete(y, idx, axis=0)\n\ncategorical_features = [1, 2, 3, 4, 5, 6, 7, 9]\nnumerical_features = [0, 8]\n\nprint(f\"x shape: {x.shape}\")\nprint(f\"y shape: {y.shape}\")",
"x shape: (48841, 10)\ny shape: (48841,)\n"
]
],
[
[
"### y-Data",
"_____no_output_____"
]
],
[
[
"def one_hot(y):\n return np.array([0 if val == \"<=50K\" else 1 for val in y], dtype=np.int32)",
"_____no_output_____"
],
[
"y = one_hot(y)",
"_____no_output_____"
]
],
[
[
"### Helper",
"_____no_output_____"
]
],
[
[
"def print_grid_cv_results(grid_result):\n print(\n f\"Best model score: {grid_result.best_score_} \"\n f\"Best model params: {grid_result.best_params_} \"\n )\n means = grid_result.cv_results_[\"mean_test_score\"]\n stds = grid_result.cv_results_[\"std_test_score\"]\n params = grid_result.cv_results_[\"params\"]\n\n for mean, std, param in zip(means, stds, params):\n mean = round(mean, 4)\n std = round(std, 4)\n print(f\"{mean} (+/- {2 * std}) with: {param}\")",
"_____no_output_____"
]
],
[
[
"### Sklearn Imports",
"_____no_output_____"
]
],
[
[
"from sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV",
"_____no_output_____"
],
[
"x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3)",
"_____no_output_____"
]
],
[
[
"### Classifier and Params",
"_____no_output_____"
]
],
[
[
"params = {\n \"classifier__n_estimators\": [50, 100, 200],\n \"classifier__max_depth\": [None, 100, 200]\n}\n\nclf = RandomForestClassifier()",
"_____no_output_____"
]
],
[
[
"### Ordinal Features",
"_____no_output_____"
]
],
[
[
"numeric_transformer = Pipeline(\n steps=[\n ('scaler', StandardScaler())\n ]\n)\n\ncategorical_transformer = Pipeline(\n steps=[\n ('ordinal', OrdinalEncoder())\n ]\n)\n\npreprocessor_odinal = ColumnTransformer(\n transformers=[\n ('numeric', numeric_transformer, numerical_features),\n ('categorical', categorical_transformer, categorical_features)\n ]\n)",
"_____no_output_____"
],
[
"preprocessor_odinal",
"_____no_output_____"
],
[
"preprocessor_odinal.fit(x_train)\n\nx_train_ordinal = preprocessor_odinal.transform(x_train)\nx_test_ordinal = preprocessor_odinal.transform(x_test)\n\nprint(f\"Shape of odinal data: {x_train_ordinal.shape}\")\nprint(f\"Shape of odinal data: {x_test_ordinal.shape}\")",
"Shape of odinal data: (34188, 10)\nShape of odinal data: (14653, 10)\n"
],
[
"pipe_ordinal = Pipeline(\n steps=[\n ('preprocessor_odinal', preprocessor_odinal),\n ('classifier', clf)\n ]\n)",
"_____no_output_____"
],
[
"pipe_ordinal",
"_____no_output_____"
],
[
"grid_ordinal = GridSearchCV(pipe_ordinal, params, cv=3)\ngrid_results_ordinal = grid_ordinal.fit(x_train, y_train)\nprint_grid_cv_results(grid_results_ordinal)",
"Best model score: 0.817947817947818 Best model params: {'classifier__max_depth': 200, 'classifier__n_estimators': 200} \n0.8169 (+/- 0.0022) with: {'classifier__max_depth': None, 'classifier__n_estimators': 50}\n0.8173 (+/- 0.002) with: {'classifier__max_depth': None, 'classifier__n_estimators': 100}\n0.8178 (+/- 0.0016) with: {'classifier__max_depth': None, 'classifier__n_estimators': 200}\n0.8174 (+/- 0.0024) with: {'classifier__max_depth': 100, 'classifier__n_estimators': 50}\n0.8179 (+/- 0.002) with: {'classifier__max_depth': 100, 'classifier__n_estimators': 100}\n0.8179 (+/- 0.0036) with: {'classifier__max_depth': 100, 'classifier__n_estimators': 200}\n0.8169 (+/- 0.001) with: {'classifier__max_depth': 200, 'classifier__n_estimators': 50}\n0.8174 (+/- 0.0034) with: {'classifier__max_depth': 200, 'classifier__n_estimators': 100}\n0.8179 (+/- 0.0012) with: {'classifier__max_depth': 200, 'classifier__n_estimators': 200}\n"
]
],
[
[
"### OneHot Features",
"_____no_output_____"
]
],
[
[
"numeric_transformer = Pipeline(\n steps=[\n ('scaler', StandardScaler())\n ]\n)\n\ncategorical_transformer = Pipeline(\n steps=[\n ('onehot', OneHotEncoder(handle_unknown=\"ignore\", sparse=False))\n ]\n)\n\npreprocessor_onehot = ColumnTransformer(\n transformers=[\n ('numeric', numeric_transformer, numerical_features),\n ('categorical', categorical_transformer, categorical_features)\n ]\n)",
"_____no_output_____"
],
[
"preprocessor_onehot",
"_____no_output_____"
],
[
"preprocessor_onehot.fit(x_train)\n\nx_train_onehot = preprocessor_onehot.transform(x_train)\nx_test_onehot = preprocessor_onehot.transform(x_test)\n\nprint(f\"Shape of onehot data: {x_train_onehot.shape}\")\nprint(f\"Shape of onehot data: {x_test_onehot.shape}\")",
"Shape of onehot data: (34188, 103)\nShape of onehot data: (14653, 103)\n"
],
[
"pipe_onehot = Pipeline(\n steps=[\n ('preprocessor_onehot', preprocessor_odinal),\n ('classifier', clf)\n ]\n)",
"_____no_output_____"
],
[
"pipe_onehot",
"_____no_output_____"
],
[
"grid_onehot = GridSearchCV(pipe_onehot, params, cv=3)\ngrid_results_onehot = grid_onehot.fit(x_train, y_train)\nprint_grid_cv_results(grid_results_onehot)",
"Best model score: 0.818094068094068 Best model params: {'classifier__max_depth': 100, 'classifier__n_estimators': 200} \n0.8173 (+/- 0.0016) with: {'classifier__max_depth': None, 'classifier__n_estimators': 50}\n0.8167 (+/- 0.0016) with: {'classifier__max_depth': None, 'classifier__n_estimators': 100}\n0.8173 (+/- 0.0038) with: {'classifier__max_depth': None, 'classifier__n_estimators': 200}\n0.818 (+/- 0.0024) with: {'classifier__max_depth': 100, 'classifier__n_estimators': 50}\n0.8177 (+/- 0.005) with: {'classifier__max_depth': 100, 'classifier__n_estimators': 100}\n0.8181 (+/- 0.0016) with: {'classifier__max_depth': 100, 'classifier__n_estimators': 200}\n0.8163 (+/- 0.002) with: {'classifier__max_depth': 200, 'classifier__n_estimators': 50}\n0.8179 (+/- 0.003) with: {'classifier__max_depth': 200, 'classifier__n_estimators': 100}\n0.8175 (+/- 0.002) with: {'classifier__max_depth': 200, 'classifier__n_estimators': 200}\n"
]
],
[
[
"### TensorFlow Model",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import SGD",
"_____no_output_____"
],
[
"y_train = y_train.reshape(-1, 1)\ny_test = y_test.reshape(-1, 1)",
"_____no_output_____"
],
[
"def build_model(input_dim, output_dim):\n model = Sequential()\n model.add(Dense(units=128, input_dim=input_dim))\n model.add(Activation(\"relu\"))\n model.add(Dense(units=64))\n model.add(Activation(\"relu\"))\n model.add(Dense(units=output_dim))\n model.add(Activation(\"sigmoid\"))\n return model",
"_____no_output_____"
]
],
[
[
"### Neural Network with Ordinal Features",
"_____no_output_____"
]
],
[
[
"model = build_model(\n input_dim=x_test_ordinal.shape[1],\n output_dim=y_train.shape[1]\n)\n\nmodel.compile(\n loss=\"binary_crossentropy\",\n optimizer=SGD(learning_rate=0.001),\n metrics=[\"binary_accuracy\"]\n)\n\nhistory_ordinal = model.fit(\n x=x_train_ordinal,\n y=y_train,\n epochs=20,\n validation_data=(x_test_ordinal, y_test)\n)",
"Epoch 1/20\n1069/1069 [==============================] - 6s 4ms/step - loss: 0.5620 - binary_accuracy: 0.7354 - val_loss: 0.4939 - val_binary_accuracy: 0.7594\nEpoch 2/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4853 - binary_accuracy: 0.7590 - val_loss: 0.5097 - val_binary_accuracy: 0.7466\nEpoch 3/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4741 - binary_accuracy: 0.7617 - val_loss: 0.4750 - val_binary_accuracy: 0.7592\nEpoch 4/20\n1069/1069 [==============================] - 4s 3ms/step - loss: 0.4719 - binary_accuracy: 0.7642 - val_loss: 0.4730 - val_binary_accuracy: 0.7704\nEpoch 5/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4686 - binary_accuracy: 0.7686 - val_loss: 0.4585 - val_binary_accuracy: 0.7657\nEpoch 6/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4615 - binary_accuracy: 0.7674 - val_loss: 0.4632 - val_binary_accuracy: 0.7617\nEpoch 7/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4575 - binary_accuracy: 0.7678 - val_loss: 0.4530 - val_binary_accuracy: 0.7684\nEpoch 8/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4555 - binary_accuracy: 0.7720 - val_loss: 0.4507 - val_binary_accuracy: 0.7691\nEpoch 9/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4552 - binary_accuracy: 0.7683 - val_loss: 0.4493 - val_binary_accuracy: 0.7764\nEpoch 10/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4520 - binary_accuracy: 0.7719 - val_loss: 0.4457 - val_binary_accuracy: 0.7725\nEpoch 11/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4490 - binary_accuracy: 0.7719 - val_loss: 0.4518 - val_binary_accuracy: 0.7798\nEpoch 12/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4463 - binary_accuracy: 0.7746 - val_loss: 0.4645 - val_binary_accuracy: 0.7612\nEpoch 13/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4425 - binary_accuracy: 0.7738 - val_loss: 0.4425 - val_binary_accuracy: 0.7843\nEpoch 14/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4442 - binary_accuracy: 0.7758 - val_loss: 0.4359 - val_binary_accuracy: 0.7802\nEpoch 15/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4389 - binary_accuracy: 0.7776 - val_loss: 0.4348 - val_binary_accuracy: 0.7750\nEpoch 16/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4373 - binary_accuracy: 0.7791 - val_loss: 0.4350 - val_binary_accuracy: 0.7706\nEpoch 17/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4343 - binary_accuracy: 0.7816 - val_loss: 0.4574 - val_binary_accuracy: 0.7632\nEpoch 18/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4299 - binary_accuracy: 0.7851 - val_loss: 0.4412 - val_binary_accuracy: 0.7691\nEpoch 19/20\n1069/1069 [==============================] - 4s 3ms/step - loss: 0.4344 - binary_accuracy: 0.7804 - val_loss: 0.4274 - val_binary_accuracy: 0.7915\nEpoch 20/20\n1069/1069 [==============================] - 4s 3ms/step - loss: 0.4273 - binary_accuracy: 0.7843 - val_loss: 0.4261 - val_binary_accuracy: 0.7754\n"
],
[
"val_binary_accuracy = history_ordinal.history[\"val_binary_accuracy\"]\n\nplt.plot(range(len(val_binary_accuracy)), val_binary_accuracy)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Neural Network with OneHot Features",
"_____no_output_____"
]
],
[
[
"model = build_model(\n input_dim=x_train_onehot.shape[1],\n output_dim=y_train.shape[1]\n)\n\nmodel.compile(\n loss=\"binary_crossentropy\",\n optimizer=SGD(learning_rate=0.001),\n metrics=[\"binary_accuracy\"]\n)\n\nhistory_onehot = model.fit(\n x=x_train_onehot,\n y=y_train,\n epochs=20,\n validation_data=(x_test_onehot, y_test)\n)",
"Epoch 1/20\n1069/1069 [==============================] - 5s 4ms/step - loss: 0.6268 - binary_accuracy: 0.6721 - val_loss: 0.5141 - val_binary_accuracy: 0.7603\nEpoch 2/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.5006 - binary_accuracy: 0.7592 - val_loss: 0.4658 - val_binary_accuracy: 0.7605\nEpoch 3/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4540 - binary_accuracy: 0.7658 - val_loss: 0.4362 - val_binary_accuracy: 0.7755\nEpoch 4/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4312 - binary_accuracy: 0.7814 - val_loss: 0.4185 - val_binary_accuracy: 0.7929\nEpoch 5/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4118 - binary_accuracy: 0.7991 - val_loss: 0.4072 - val_binary_accuracy: 0.8015\nEpoch 6/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.4042 - binary_accuracy: 0.8080 - val_loss: 0.3992 - val_binary_accuracy: 0.8074\nEpoch 7/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3951 - binary_accuracy: 0.8122 - val_loss: 0.3930 - val_binary_accuracy: 0.8128\nEpoch 8/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3910 - binary_accuracy: 0.8127 - val_loss: 0.3879 - val_binary_accuracy: 0.8159\nEpoch 9/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3843 - binary_accuracy: 0.8181 - val_loss: 0.3834 - val_binary_accuracy: 0.8187\nEpoch 10/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3827 - binary_accuracy: 0.8170 - val_loss: 0.3796 - val_binary_accuracy: 0.8209\nEpoch 11/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3815 - binary_accuracy: 0.8212 - val_loss: 0.3763 - val_binary_accuracy: 0.8237\nEpoch 12/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3753 - binary_accuracy: 0.8241 - val_loss: 0.3733 - val_binary_accuracy: 0.8260\nEpoch 13/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3695 - binary_accuracy: 0.8297 - val_loss: 0.3706 - val_binary_accuracy: 0.8287\nEpoch 14/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3714 - binary_accuracy: 0.8259 - val_loss: 0.3683 - val_binary_accuracy: 0.8305\nEpoch 15/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3671 - binary_accuracy: 0.8274 - val_loss: 0.3661 - val_binary_accuracy: 0.8316\nEpoch 16/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3691 - binary_accuracy: 0.8272 - val_loss: 0.3642 - val_binary_accuracy: 0.8327\nEpoch 17/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3651 - binary_accuracy: 0.8283 - val_loss: 0.3625 - val_binary_accuracy: 0.8334\nEpoch 18/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3619 - binary_accuracy: 0.8323 - val_loss: 0.3608 - val_binary_accuracy: 0.8345\nEpoch 19/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3621 - binary_accuracy: 0.8301 - val_loss: 0.3594 - val_binary_accuracy: 0.8350\nEpoch 20/20\n1069/1069 [==============================] - 4s 4ms/step - loss: 0.3615 - binary_accuracy: 0.8310 - val_loss: 0.3581 - val_binary_accuracy: 0.8358\n"
],
[
"val_binary_accuracy = history_onehot.history[\"val_binary_accuracy\"]\n\nplt.plot(range(len(val_binary_accuracy)), val_binary_accuracy)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Pass in user-data",
"_____no_output_____"
]
],
[
[
"pipe_ordinal.fit(x_train, y_train)\nscore = pipe_ordinal.score(x_test, y_test)\n\nprint(f\"Score: {score}\")",
"C:\\Users\\Jan\\Anaconda3\\lib\\site-packages\\sklearn\\pipeline.py:335: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n self._final_estimator.fit(Xt, y, **fit_params_last_step)\n"
],
[
"x_sample = [\n 25,\n \"Private\",\n \"11th\",\n \"Never-married\",\n \"Machine-op-inspct\",\n \"Own-child\",\n \"Black\",\n \"Male\",\n 40,\n \"United-States\"\n]\ny_sample = 0\n\ny_pred_sample = pipe_ordinal.predict([x_sample])\n\nprint(f\"Pred: {y_pred_sample}\")",
"Pred: [0]\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbd3edb60132d7ba37ef104a627677e629734a23
| 6,885 |
ipynb
|
Jupyter Notebook
|
examples/topics/uk_researchers.ipynb
|
philippjfr/datashader
|
eb9218cb810297aea2ae1030349cef6a6f3ab3cb
|
[
"BSD-3-Clause"
] | 1 |
2018-07-17T19:33:43.000Z
|
2018-07-17T19:33:43.000Z
|
examples/topics/uk_researchers.ipynb
|
philippjfr/datashader
|
eb9218cb810297aea2ae1030349cef6a6f3ab3cb
|
[
"BSD-3-Clause"
] | null | null | null |
examples/topics/uk_researchers.ipynb
|
philippjfr/datashader
|
eb9218cb810297aea2ae1030349cef6a6f3ab3cb
|
[
"BSD-3-Clause"
] | null | null | null | 39.797688 | 597 | 0.658969 |
[
[
[
"# UK research networks with HoloViews+Bokeh+Datashader\n\n[Datashader](http://datashader.readthedocs.org) makes it possible to plot very large datasets in a web browser, while [Bokeh](http://bokeh.pydata.org) makes those plots interactive, and [HoloViews](http://holoviews.org) provides a convenient interface for building these plots.\nHere, let's use these three programs to visualize an example dataset of 600,000 collaborations between 15000 UK research institutions, previously laid out using a force-directed algorithm by [Ian Calvert](https://www.digital-science.com/people/ian-calvert).\n\nFirst, we'll import the packages we are using and set up some defaults.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport holoviews as hv\nimport fastparquet as fp\n\nfrom colorcet import fire\nfrom datashader.bundling import directly_connect_edges, hammer_bundle\n\nfrom holoviews.operation.datashader import datashade, dynspread\nfrom holoviews.operation import decimate\n\nfrom dask.distributed import Client\nclient = Client()\n\nhv.notebook_extension('bokeh','matplotlib')\n\ndecimate.max_samples=20000\ndynspread.threshold=0.01\ndatashade.cmap=fire[40:]\nsz = dict(width=150,height=150)\n\n%opts RGB [xaxis=None yaxis=None show_grid=False bgcolor=\"black\"]",
"_____no_output_____"
]
],
[
[
"The files are stored in the efficient Parquet format:",
"_____no_output_____"
]
],
[
[
"r_nodes_file = '../data/calvert_uk_research2017_nodes.snappy.parq'\nr_edges_file = '../data/calvert_uk_research2017_edges.snappy.parq'\n\nr_nodes = hv.Points(fp.ParquetFile(r_nodes_file).to_pandas(index='id'), label=\"Nodes\")\nr_edges = hv.Curve( fp.ParquetFile(r_edges_file).to_pandas(index='id'), label=\"Edges\")\nlen(r_nodes),len(r_edges)",
"_____no_output_____"
]
],
[
[
"We can render each collaboration as a single-line direct connection, but the result is a dense tangle:",
"_____no_output_____"
]
],
[
[
"%%opts RGB [tools=[\"hover\"] width=400 height=400] \n\n%time r_direct = hv.Curve(directly_connect_edges(r_nodes.data, r_edges.data),label=\"Direct\")\n\ndynspread(datashade(r_nodes,cmap=[\"cyan\"])) + \\\ndatashade(r_direct)",
"_____no_output_____"
]
],
[
[
"Detailed substructure of this graph becomes visible after bundling edges using a variant of [Hurter, Ersoy, & Telea (ECV-2012)](http://www.cs.rug.nl/~alext/PAPERS/EuroVis12/kdeeb.pdf), which takes several minutes even using multiple cores with [Dask](https://dask.pydata.org):",
"_____no_output_____"
]
],
[
[
"%time r_bundled = hv.Curve(hammer_bundle(r_nodes.data, r_edges.data),label=\"Bundled\")",
"_____no_output_____"
],
[
"%%opts RGB [tools=[\"hover\"] width=400 height=400] \n\ndynspread(datashade(r_nodes,cmap=[\"cyan\"])) + datashade(r_bundled)",
"_____no_output_____"
]
],
[
[
"Zooming into these plots reveals interesting patterns (if you are running a live Python server), but immediately one then wants to ask what the various groupings of nodes might represent. With a small number of nodes or a small number of categories one could color-code the dots (using datashader's categorical color coding support), but here we just have thousands of indistinguishable dots. Instead, let's use hover information so the viewer can at least see the identity of each node on inspection. \n\nTo do that, we'll first need to pull in something useful to hover, so let's load the names of each institution in the researcher list and merge that with our existing layout data:",
"_____no_output_____"
]
],
[
[
"node_names = pd.read_csv(\"../data/calvert_uk_research2017_nodes.csv\", index_col=\"node_id\", usecols=[\"node_id\",\"name\"])\nnode_names = node_names.rename(columns={\"name\": \"Institution\"})\nnode_names\n\nr_nodes_named = pd.merge(r_nodes.data, node_names, left_index=True, right_index=True)\nr_nodes_named.tail()",
"_____no_output_____"
]
],
[
[
"We can now overlay a set of points on top of the datashaded edges, which will provide hover information for each node. Here, the entire set of 15000 nodes would be reasonably feasible to plot, but to show how to work with larger datasets we wrap the `hv.Points()` call with `decimate` so that only a finite subset of the points will be shown at any one time. If a node of interest is not visible in a particular zoom, then you can simply zoom in on that region; at some point the number of visible points will be below the specified decimate limit and the required point should be revealed.",
"_____no_output_____"
]
],
[
[
"%%opts Points (color=\"cyan\") [tools=[\"hover\"] width=900 height=650] \ndatashade(r_bundled, width=900, height=650) * \\\ndecimate( hv.Points(r_nodes_named),max_samples=10000)",
"_____no_output_____"
]
],
[
[
"If you click around and hover, you should see interesting groups of nodes, and can then set up further interactive tools using [HoloViews' stream support](http://holoviews.org/user_guide/Responding_to_Events.html) to reveal aspects relevant to your research interests or questions.\n\nAs you can see, datashader lets you work with very large graph datasets, though there are a number of decisions to make by trial and error, you do have to be careful when doing computationally expensive operations like edge bundling, and interactive information will only be available for a limited subset of the data at any one time due to data-size limitations of current web browsers.",
"_____no_output_____"
]
]
] |
[
"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"
]
] |
cbd3fcfb97e8a1cca74f77b6257e7d04a111230a
| 1,763 |
ipynb
|
Jupyter Notebook
|
13. conditional_statements.ipynb
|
chinmoyee-A/Python
|
1eeb6a8e3370e7ad63561a7e6ee2a5854023f266
|
[
"MIT"
] | null | null | null |
13. conditional_statements.ipynb
|
chinmoyee-A/Python
|
1eeb6a8e3370e7ad63561a7e6ee2a5854023f266
|
[
"MIT"
] | null | null | null |
13. conditional_statements.ipynb
|
chinmoyee-A/Python
|
1eeb6a8e3370e7ad63561a7e6ee2a5854023f266
|
[
"MIT"
] | null | null | null | 18.557895 | 176 | 0.47249 |
[
[
[
"# Problem 1 : Take a variable x and print \"Even\" if the number is divisible by 2, otherwise print \"Odd\".",
"_____no_output_____"
]
],
[
[
"x=4\n\nif(x%2==0):\n print(\"Even\")\nelse:\n print(\"Odd\")",
"Even\n"
]
],
[
[
"# Problem 2 : Take a variable y and print \"Grade A\" if y is greater than 90, \"Grade B\" if y is greater than 60 but less than or equal to 90 and \"Grade F\" Otherwise.",
"_____no_output_____"
]
],
[
[
"y=90\n\nif(y>90):\n print(\"Grade A\")\nelif(y>60):\n print(\"Grade B\")\nelse:\n print(\"Grade F\")",
"Grade B\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd41943716bf2073e4748925b323f9b15cbe104
| 35,096 |
ipynb
|
Jupyter Notebook
|
MathAndPython/week1/Types_in_Python.ipynb
|
ishatserka/MachineLearningAndDataAnalysisCoursera
|
e82e772df2f4aec162cb34ac6127df10d14a625a
|
[
"MIT"
] | null | null | null |
MathAndPython/week1/Types_in_Python.ipynb
|
ishatserka/MachineLearningAndDataAnalysisCoursera
|
e82e772df2f4aec162cb34ac6127df10d14a625a
|
[
"MIT"
] | null | null | null |
MathAndPython/week1/Types_in_Python.ipynb
|
ishatserka/MachineLearningAndDataAnalysisCoursera
|
e82e772df2f4aec162cb34ac6127df10d14a625a
|
[
"MIT"
] | null | null | null | 19.986333 | 1,243 | 0.478886 |
[
[
[
"# Типы данных в Python",
"_____no_output_____"
],
[
"## 1. Числовые",
"_____no_output_____"
],
[
"### int",
"_____no_output_____"
]
],
[
[
"x = 5",
"_____no_output_____"
],
[
"print (x)",
"5\n"
],
[
"print(type(x))",
"<class 'int'>\n"
],
[
"a = 4 + 5\nb = 4 * 5\nc = 5 // 4\n\nprint(a, b, c)",
"9 20 1\n"
],
[
"print -5 / 4",
"-2\n"
],
[
"print -(5 / 4)",
"-1\n"
]
],
[
[
"### long",
"_____no_output_____"
]
],
[
[
"x = 5 * 1000000 * 1000000 * 1000000 * 1000000 + 1\nprint x\nprint type(x)",
"5000000000000000000000001\n<type 'long'>\n"
],
[
"y = 5\nprint type(y)\ny = x\nprint type(y)",
"<type 'int'>\n<type 'long'>\n"
]
],
[
[
"### float",
"_____no_output_____"
]
],
[
[
"y = 5.7",
"_____no_output_____"
],
[
"print y\nprint type(y)",
"5.7\n<type 'float'>\n"
],
[
"a = 4.2 + 5.1\nb = 4.2 * 5.1\nc = 5.0 / 4.0\n\nprint a, b, c",
"9.3 21.42 1.25\n"
],
[
"a = 5\nb = 4\nprint float(a) / float(b)",
"1.25\n"
],
[
"print 5.0 / 4\nprint 5 / 4.0",
"1.25\n1.25\n"
],
[
"print float(a) / b",
"1.25\n"
]
],
[
[
"### bool",
"_____no_output_____"
]
],
[
[
"a = True\nb = False\n\nprint a\nprint type(a)\n\nprint b\nprint type(b)",
"True\n<type 'bool'>\nFalse\n<type 'bool'>\n"
],
[
"print a + b\nprint a + a\nprint b + b",
"1\n2\n0\n"
],
[
"print int(a), int(b)",
"1 0\n"
],
[
"print True and False\nprint True and True\nprint False and False",
"False\nTrue\nFalse\n"
],
[
"print True or False\nprint True or True\nprint False or False",
"True\nTrue\nFalse\n"
]
],
[
[
"## 2. None",
"_____no_output_____"
]
],
[
[
"z = None\nprint z\nprint type(z)",
"None\n<type 'NoneType'>\n"
],
[
"print int(z)",
"_____no_output_____"
]
],
[
[
"## 3. Строковые",
"_____no_output_____"
],
[
"### str",
"_____no_output_____"
]
],
[
[
"x = \"abc\"\nprint x\nprint type(x)",
"abc\n<type 'str'>\n"
],
[
"a = 'Ivan'\nb = \"Ivanov\"\ns = a + \" \" + b\nprint s",
"Ivan Ivanov\n"
],
[
"print a.upper()\nprint a.lower()",
"IVAN\nivan\n"
],
[
"print len(a)",
"4\n"
],
[
"print bool(a)\nprint bool(\"\")",
"True\nFalse\n"
],
[
"print int(a)",
"_____no_output_____"
],
[
"print a\nprint a[0]\nprint a[1]\nprint a[0:3]",
"Ivan\nI\nv\nIva\n"
],
[
"print a[0:4:2]",
"Ia\n"
]
],
[
[
"### unicode",
"_____no_output_____"
]
],
[
[
"x = u\"abc\"\nprint x\nprint type(x)",
"abc\n<type 'unicode'>\n"
],
[
"x = u'Элеонора Михайловна'\nprint x, type(x)\ny = x.encode('utf-8')\nprint y, type(y)\nz = y.decode('utf-8')\nprint z, type(z)\nq = y.decode('cp1251')\nprint q, type(q)",
"Элеонора Михайловна <type 'unicode'>\nЭлеонора Михайловна <type 'str'>\nЭлеонора Михайловна <type 'unicode'>\nРлеонора Михайловна <type 'unicode'>\n"
],
[
"1",
"_____no_output_____"
],
[
"x = u'Элеонора Михайловна'\nprint x, type(x)\ny = x.encode('utf-8')\nprint y, type(y)\nz = y.decode('utf-8')\nprint z, type(z)\nq = y.decode('cp1251')\nprint q, type(q)",
"Элеонора Михайловна <type 'unicode'>\nЭлеонора Михайловна <type 'str'>\nЭлеонора Михайловна <type 'unicode'>\nРлеонора Михайловна <type 'unicode'>\n"
],
[
"print str(x)",
"_____no_output_____"
],
[
"print y[1:]\nprint len(y), type(y)\nprint len(x), type(x)",
"�леонора Михайловна\n37 <type 'str'>\n19 <type 'unicode'>\n"
],
[
"y = u'Иван Иванович'.encode('utf-8')\nprint y.decode('utf-8')",
"Иван Иванович\n"
],
[
"print y.decode('cp1251')",
"_____no_output_____"
],
[
"splitted_line = \"Ivanov Ivan Ivanovich\".split(' ')\nprint splitted_line",
"['Ivanov', 'Ivan', 'Ivanovich']\n"
],
[
"print type(splitted_line)",
"<type 'list'>\n"
],
[
"print \"Иванов Иван Иванович\".split(\" \")",
"['\\xd0\\x98\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xbe\\xd0\\xb2', '\\xd0\\x98\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd', '\\xd0\\x98\\xd0\\xb2\\xd0\\xb0\\xd0\\xbd\\xd0\\xbe\\xd0\\xb2\\xd0\\xb8\\xd1\\x87']\n"
],
[
"print \"\\x98\"",
"�\n"
],
[
"print u\"Иванов Иван Иванович\".split(\" \")",
"[u'\\u0418\\u0432\\u0430\\u043d\\u043e\\u0432', u'\\u0418\\u0432\\u0430\\u043d', u'\\u0418\\u0432\\u0430\\u043d\\u043e\\u0432\\u0438\\u0447']\n"
]
],
[
[
"## 3. Массивы",
"_____no_output_____"
],
[
"### list",
"_____no_output_____"
]
],
[
[
"saled_goods_count = [33450, 34010, 33990, 33200]\nprint saled_goods_count\nprint type(saled_goods_count)",
"[33450, 34010, 33990, 33200]\n<type 'list'>\n"
],
[
"income = [u'Высокий', u'Средний', u'Высокий']\nnames = [u'Элеонора Михайловна', u'Иван Иванович', u'Михаил Абрамович']\n\nprint income\nprint names",
"[u'\\u0412\\u044b\\u0441\\u043e\\u043a\\u0438\\u0439', u'\\u0421\\u0440\\u0435\\u0434\\u043d\\u0438\\u0439', u'\\u0412\\u044b\\u0441\\u043e\\u043a\\u0438\\u0439']\n[u'\\u042d\\u043b\\u0435\\u043e\\u043d\\u043e\\u0440\\u0430 \\u041c\\u0438\\u0445\\u0430\\u0439\\u043b\\u043e\\u0432\\u043d\\u0430', u'\\u0418\\u0432\\u0430\\u043d \\u0418\\u0432\\u0430\\u043d\\u043e\\u0432\\u0438\\u0447', u'\\u041c\\u0438\\u0445\\u0430\\u0438\\u043b \\u0410\\u0431\\u0440\\u0430\\u043c\\u043e\\u0432\\u0438\\u0447']\n"
],
[
"print \"---\".join(income)",
"Высокий---Средний---Высокий\n"
],
[
"features = ['Ivan Ivanovich', 'Medium', 500000, 12, True]\nprint features",
"['Ivan Ivanovich', 'Medium', 500000, 12, True]\n"
],
[
"print features[0]\nprint features[1]\nprint features[3]",
"Ivan Ivanovich\nMedium\n12\n"
],
[
"print features[0:5]",
"['Ivan Ivanovich', 'Medium', 500000, 12, True]\n"
],
[
"print features[:5]",
"['Ivan Ivanovich', 'Medium', 500000, 12, True]\n"
],
[
"print features[1:]",
"['Medium', 500000, 12, True]\n"
],
[
"print features[2:5]",
"[500000, 12, True]\n"
],
[
"print features[:-1]",
"['Ivan Ivanovich', 'Medium', 500000, 12]\n"
],
[
"features.append('One more element in list')\nprint features",
"['Ivan Ivanovich', 'Medium', 500000, 12, True, 'One more element in list']\n"
],
[
"del features[-2]",
"_____no_output_____"
],
[
"print features",
"['Ivan Ivanovich', 'Medium', 500000, 12, 'One more element in list']\n"
]
],
[
[
"### tuple",
"_____no_output_____"
]
],
[
[
"features_tuple = ('Ivan Ivanovich', 'Medium', 500000, 12, True)\nprint type(features_tuple)",
"<type 'tuple'>\n"
],
[
"features_tuple[2:5]",
"_____no_output_____"
],
[
"features_tuple.append('one more element')",
"_____no_output_____"
]
],
[
[
"## 4. Множества и словари",
"_____no_output_____"
],
[
"### set",
"_____no_output_____"
]
],
[
[
"names = {'Ivan', 'Petr', 'Konstantin'}",
"_____no_output_____"
],
[
"print type(names)",
"<type 'set'>\n"
],
[
"print 'Ivan' in names",
"True\n"
],
[
"print 'Mikhail' in names",
"False\n"
],
[
"names.add('Mikhail')\nprint names",
"set(['Ivan', 'Mikhail', 'Konstantin', 'Petr'])\n"
],
[
"names.add('Mikhail')\nprint names",
"set(['Ivan', 'Mikhail', 'Konstantin', 'Petr'])\n"
],
[
"names.remove('Mikhail')\nprint names",
"set(['Ivan', 'Konstantin', 'Petr'])\n"
],
[
"names.add(['Vladimir', 'Vladimirovich'])",
"_____no_output_____"
],
[
"names.add(('Vladimir', 'Vladimirovich'))\nprint names",
"set(['Ivan', ('Vladimir', 'Vladimirovich'), 'Konstantin', 'Petr'])\n"
],
[
"a = range(10000)\nb = range(10000)\nb = set(b)",
"_____no_output_____"
],
[
"print a[:5]\nprint a[-5:]",
"[0, 1, 2, 3, 4]\n[9995, 9996, 9997, 9998, 9999]\n"
],
[
"%%time\nprint 9999 in a",
"True\nCPU times: user 675 µs, sys: 70 µs, total: 745 µs\nWall time: 752 µs\n"
],
[
"%%time\nprint 9999 in b",
"True\nCPU times: user 49 µs, sys: 9 µs, total: 58 µs\nWall time: 55.1 µs\n"
]
],
[
[
"### dict",
"_____no_output_____"
]
],
[
[
"words_frequencies = dict()\nwords_frequencies['I'] = 1\nwords_frequencies['am'] = 1\nwords_frequencies['I'] += 1\n\nprint words_frequencies",
"{'I': 2, 'am': 1}\n"
],
[
"print words_frequencies['I']",
"2\n"
],
[
"words_frequencies = {'I': 2, 'am': 1}\nprint words_frequencies",
"{'I': 2, 'am': 1}\n"
],
[
"yet_another_dict = {'abc': 3.4, 5: 7.8, u'123': None}\nprint yet_another_dict",
"{u'123': None, 'abc': 3.4, 5: 7.8}\n"
],
[
"yet_another_dict[(1,2,5)] = [4, 5, 7]\nprint yet_another_dict",
"{u'123': None, 'abc': 3.4, 5: 7.8, (1, 2, 5): [4, 5, 7]}\n"
],
[
"yet_another_dict[[1,2,7]] = [4, 5]",
"_____no_output_____"
]
],
[
[
"## Где еще можно познакомиться с Python",
"_____no_output_____"
],
[
"* https://www.coursera.org/courses?query=Python\n* https://www.codeacademy.com\n* http://www.pythontutor.ru\n* http://www.learnpythonthehardway.org\n* http://snakify.org\n* https://www.checkio.org",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cbd42859b771b053962ef26651b347a41aea25cf
| 81,546 |
ipynb
|
Jupyter Notebook
|
GausianNB (1).ipynb
|
suley-bit/HealthAI
|
8b0e23c5a0405e5a4f92b7b16727b909d5c2515a
|
[
"MIT"
] | null | null | null |
GausianNB (1).ipynb
|
suley-bit/HealthAI
|
8b0e23c5a0405e5a4f92b7b16727b909d5c2515a
|
[
"MIT"
] | null | null | null |
GausianNB (1).ipynb
|
suley-bit/HealthAI
|
8b0e23c5a0405e5a4f92b7b16727b909d5c2515a
|
[
"MIT"
] | null | null | null | 82.203629 | 25,924 | 0.683688 |
[
[
[
"import numpy as np\nimport pylab as pl\nimport pandas as pd\nimport matplotlib.pyplot as plt \n%matplotlib inline\nimport seaborn as sns\nfrom sklearn.utils import shuffle\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import confusion_matrix,classification_report\nfrom sklearn.model_selection import cross_val_score, GridSearchCV\nfrom collections import Counter\nfrom matplotlib import pyplot\nfrom sklearn.model_selection import StratifiedKFold",
"_____no_output_____"
],
[
"final_df = pd.read_csv('final_Suleyman', index_col = 0) ",
"_____no_output_____"
],
[
"final_df",
"_____no_output_____"
],
[
"final_df = final_df.drop(['DOB', 'DOD','ADMITTIME'], axis = 1)",
"_____no_output_____"
],
[
"X = final_df.iloc[:,:-1]\ny = final_df.iloc[:,-1]\ncounter = Counter(y)\nfor k,v in counter.items():\n\tper = v / len(y) * 100\n\tprint('Class=%d, n=%d (%.3f%%)' % (k, v, per))\n# plot the distribution\npyplot.bar(counter.keys(), counter.values())\npyplot.show()",
"Class=1, n=597 (31.078%)\nClass=2, n=1048 (54.555%)\nClass=0, n=119 (6.195%)\nClass=3, n=157 (8.173%)\n"
],
[
"from imblearn.over_sampling import SMOTE\n# transform the dataset\noversample = SMOTE()\nX, y = oversample.fit_resample(X, y)\n# summarize distribution\ncounter = Counter(y)\nfor k,v in counter.items():\n\tper = v / len(y) * 100\n\tprint('Class=%d, n=%d (%.3f%%)' % (k, v, per))\n# plot the distribution\npyplot.bar(counter.keys(), counter.values())\npyplot.show()",
"Class=1, n=1048 (25.000%)\nClass=2, n=1048 (25.000%)\nClass=0, n=1048 (25.000%)\nClass=3, n=1048 (25.000%)\n"
],
[
"final_df = final_df.reset_index()",
"_____no_output_____"
],
[
"X = final_df.iloc[:,:-1]\ny = final_df.iloc[:,-1]",
"_____no_output_____"
],
[
"skf = StratifiedKFold(n_splits=2, shuffle = True, random_state = 3)\nfor train_index, test_index in skf.split(np.zeros(len(y)), y):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n train_X, test_X = X.loc[train_index], X.loc[test_index]\n train_y,test_y = y.loc[train_index],y.loc[test_index]",
"TRAIN: [ 1 4 5 6 8 11 14 16 18 24 26 27 29 30\n 32 42 43 47 48 49 50 51 55 60 61 64 68 74\n 75 77 78 79 81 83 85 86 89 90 91 92 93 94\n 95 96 97 101 102 103 104 105 108 109 110 113 115 120\n 124 125 127 130 131 134 135 136 137 138 139 140 141 143\n 144 146 147 148 150 152 153 156 158 160 161 163 164 165\n 169 171 174 175 176 178 179 180 181 183 185 186 188 190\n 191 192 193 195 197 198 199 203 208 211 217 218 220 222\n 226 227 229 230 231 233 241 242 247 249 251 253 254 256\n 258 260 261 263 264 265 268 269 270 272 273 274 277 278\n 282 283 285 286 289 292 296 298 299 300 308 310 315 320\n 322 323 325 331 332 334 335 338 341 343 346 348 351 353\n 354 355 356 357 362 363 364 366 367 369 370 372 373 374\n 375 378 379 382 383 384 385 388 390 391 392 400 401 403\n 406 409 413 415 416 417 418 420 421 423 426 428 429 430\n 433 439 440 442 444 445 448 449 450 451 452 453 454 455\n 459 460 464 465 466 467 469 470 472 474 475 476 477 478\n 480 481 484 486 489 490 491 495 496 498 499 503 504 505\n 507 508 510 513 514 524 526 529 530 531 532 539 540 541\n 543 547 548 549 551 552 556 557 561 564 567 568 569 570\n 571 572 575 576 577 579 580 582 583 584 586 587 588 589\n 590 591 592 593 598 600 601 603 606 607 612 613 614 615\n 617 618 620 624 627 628 629 630 631 632 634 635 636 637\n 640 641 642 643 645 646 648 649 650 651 656 659 660 661\n 667 668 670 672 678 679 681 682 687 690 692 697 698 700\n 701 705 709 710 711 712 714 715 718 722 725 728 733 734\n 735 736 737 738 739 740 742 743 745 748 750 752 761 762\n 763 764 767 770 771 773 774 775 776 779 782 784 790 792\n 793 794 802 803 805 806 807 808 813 815 816 821 822 823\n 825 827 831 833 834 837 842 843 845 846 848 849 852 853\n 855 857 860 862 864 867 871 873 876 878 879 880 881 883\n 884 885 886 887 889 893 894 895 896 899 902 903 904 906\n 908 911 912 913 914 916 919 924 925 926 927 929 934 937\n 938 939 941 944 945 946 948 949 950 951 953 954 955 956\n 958 959 960 963 966 968 969 970 972 973 976 977 978 979\n 982 984 990 992 993 995 1000 1001 1002 1003 1006 1007 1009 1013\n 1022 1025 1026 1027 1030 1031 1034 1035 1036 1037 1039 1042 1043 1044\n 1047 1048 1049 1051 1052 1053 1059 1061 1062 1063 1064 1068 1071 1072\n 1073 1075 1078 1081 1082 1083 1085 1090 1092 1094 1095 1101 1102 1108\n 1110 1113 1115 1116 1117 1118 1119 1126 1128 1129 1130 1131 1132 1135\n 1136 1138 1142 1145 1147 1148 1150 1151 1152 1155 1158 1160 1162 1164\n 1165 1168 1169 1170 1174 1176 1179 1182 1183 1184 1186 1188 1189 1191\n 1193 1194 1197 1198 1199 1202 1203 1204 1205 1207 1208 1209 1211 1212\n 1214 1216 1217 1220 1221 1223 1224 1226 1227 1229 1231 1236 1238 1241\n 1242 1247 1248 1251 1253 1254 1257 1258 1265 1268 1269 1270 1271 1272\n 1274 1275 1278 1281 1284 1285 1286 1287 1288 1289 1291 1300 1302 1303\n 1305 1309 1310 1311 1312 1313 1314 1316 1317 1319 1321 1323 1324 1329\n 1330 1334 1341 1342 1343 1344 1350 1352 1359 1361 1362 1364 1365 1367\n 1369 1371 1374 1377 1379 1381 1382 1384 1385 1391 1394 1395 1397 1401\n 1402 1407 1408 1409 1411 1413 1414 1415 1417 1419 1420 1423 1424 1428\n 1430 1431 1433 1434 1435 1436 1437 1439 1440 1442 1443 1445 1448 1450\n 1451 1453 1455 1456 1457 1458 1460 1464 1465 1467 1468 1470 1473 1474\n 1477 1478 1479 1481 1482 1483 1485 1487 1490 1493 1495 1496 1497 1499\n 1508 1510 1514 1517 1519 1522 1523 1524 1526 1529 1530 1531 1532 1533\n 1534 1537 1540 1541 1542 1545 1546 1547 1548 1550 1551 1555 1556 1558\n 1559 1560 1563 1564 1565 1567 1568 1570 1571 1573 1574 1575 1577 1579\n 1580 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1598 1599 1601\n 1602 1603 1604 1605 1608 1611 1612 1613 1616 1619 1622 1624 1625 1626\n 1627 1628 1631 1632 1633 1636 1638 1641 1643 1644 1645 1646 1647 1648\n 1651 1653 1654 1657 1659 1663 1664 1666 1667 1669 1671 1672 1674 1676\n 1678 1681 1682 1683 1684 1685 1690 1693 1694 1695 1697 1700 1702 1705\n 1706 1708 1709 1712 1715 1716 1717 1718 1720 1721 1722 1725 1727 1728\n 1731 1733 1734 1738 1739 1740 1743 1745 1747 1750 1753 1755 1758 1760\n 1764 1765 1770 1773 1774 1780 1781 1783 1784 1786 1788 1789 1792 1794\n 1795 1796 1802 1803 1805 1808 1811 1812 1813 1814 1815 1816 1817 1818\n 1819 1821 1822 1823 1824 1826 1831 1832 1833 1837 1838 1840 1844 1846\n 1851 1852 1853 1854 1856 1857 1860 1862 1866 1867 1869 1871 1874 1875\n 1880 1883 1885 1886 1888 1890 1893 1895 1898 1902 1903 1907 1908 1909\n 1911 1912 1913 1915 1916 1917 1918 1919] TEST: [ 0 2 3 7 9 10 12 13 15 17 19 20 21 22\n 23 25 28 31 33 34 35 36 37 38 39 40 41 44\n 45 46 52 53 54 56 57 58 59 62 63 65 66 67\n 69 70 71 72 73 76 80 82 84 87 88 98 99 100\n 106 107 111 112 114 116 117 118 119 121 122 123 126 128\n 129 132 133 142 145 149 151 154 155 157 159 162 166 167\n 168 170 172 173 177 182 184 187 189 194 196 200 201 202\n 204 205 206 207 209 210 212 213 214 215 216 219 221 223\n 224 225 228 232 234 235 236 237 238 239 240 243 244 245\n 246 248 250 252 255 257 259 262 266 267 271 275 276 279\n 280 281 284 287 288 290 291 293 294 295 297 301 302 303\n 304 305 306 307 309 311 312 313 314 316 317 318 319 321\n 324 326 327 328 329 330 333 336 337 339 340 342 344 345\n 347 349 350 352 358 359 360 361 365 368 371 376 377 380\n 381 386 387 389 393 394 395 396 397 398 399 402 404 405\n 407 408 410 411 412 414 419 422 424 425 427 431 432 434\n 435 436 437 438 441 443 446 447 456 457 458 461 462 463\n 468 471 473 479 482 483 485 487 488 492 493 494 497 500\n 501 502 506 509 511 512 515 516 517 518 519 520 521 522\n 523 525 527 528 533 534 535 536 537 538 542 544 545 546\n 550 553 554 555 558 559 560 562 563 565 566 573 574 578\n 581 585 594 595 596 597 599 602 604 605 608 609 610 611\n 616 619 621 622 623 625 626 633 638 639 644 647 652 653\n 654 655 657 658 662 663 664 665 666 669 671 673 674 675\n 676 677 680 683 684 685 686 688 689 691 693 694 695 696\n 699 702 703 704 706 707 708 713 716 717 719 720 721 723\n 724 726 727 729 730 731 732 741 744 746 747 749 751 753\n 754 755 756 757 758 759 760 765 766 768 769 772 777 778\n 780 781 783 785 786 787 788 789 791 795 796 797 798 799\n 800 801 804 809 810 811 812 814 817 818 819 820 824 826\n 828 829 830 832 835 836 838 839 840 841 844 847 850 851\n 854 856 858 859 861 863 865 866 868 869 870 872 874 875\n 877 882 888 890 891 892 897 898 900 901 905 907 909 910\n 915 917 918 920 921 922 923 928 930 931 932 933 935 936\n 940 942 943 947 952 957 961 962 964 965 967 971 974 975\n 980 981 983 985 986 987 988 989 991 994 996 997 998 999\n 1004 1005 1008 1010 1011 1012 1014 1015 1016 1017 1018 1019 1020 1021\n 1023 1024 1028 1029 1032 1033 1038 1040 1041 1045 1046 1050 1054 1055\n 1056 1057 1058 1060 1065 1066 1067 1069 1070 1074 1076 1077 1079 1080\n 1084 1086 1087 1088 1089 1091 1093 1096 1097 1098 1099 1100 1103 1104\n 1105 1106 1107 1109 1111 1112 1114 1120 1121 1122 1123 1124 1125 1127\n 1133 1134 1137 1139 1140 1141 1143 1144 1146 1149 1153 1154 1156 1157\n 1159 1161 1163 1166 1167 1171 1172 1173 1175 1177 1178 1180 1181 1185\n 1187 1190 1192 1195 1196 1200 1201 1206 1210 1213 1215 1218 1219 1222\n 1225 1228 1230 1232 1233 1234 1235 1237 1239 1240 1243 1244 1245 1246\n 1249 1250 1252 1255 1256 1259 1260 1261 1262 1263 1264 1266 1267 1273\n 1276 1277 1279 1280 1282 1283 1290 1292 1293 1294 1295 1296 1297 1298\n 1299 1301 1304 1306 1307 1308 1315 1318 1320 1322 1325 1326 1327 1328\n 1331 1332 1333 1335 1336 1337 1338 1339 1340 1345 1346 1347 1348 1349\n 1351 1353 1354 1355 1356 1357 1358 1360 1363 1366 1368 1370 1372 1373\n 1375 1376 1378 1380 1383 1386 1387 1388 1389 1390 1392 1393 1396 1398\n 1399 1400 1403 1404 1405 1406 1410 1412 1416 1418 1421 1422 1425 1426\n 1427 1429 1432 1438 1441 1444 1446 1447 1449 1452 1454 1459 1461 1462\n 1463 1466 1469 1471 1472 1475 1476 1480 1484 1486 1488 1489 1491 1492\n 1494 1498 1500 1501 1502 1503 1504 1505 1506 1507 1509 1511 1512 1513\n 1515 1516 1518 1520 1521 1525 1527 1528 1535 1536 1538 1539 1543 1544\n 1549 1552 1553 1554 1557 1561 1562 1566 1569 1572 1576 1578 1581 1582\n 1583 1584 1585 1596 1597 1600 1606 1607 1609 1610 1614 1615 1617 1618\n 1620 1621 1623 1629 1630 1634 1635 1637 1639 1640 1642 1649 1650 1652\n 1655 1656 1658 1660 1661 1662 1665 1668 1670 1673 1675 1677 1679 1680\n 1686 1687 1688 1689 1691 1692 1696 1698 1699 1701 1703 1704 1707 1710\n 1711 1713 1714 1719 1723 1724 1726 1729 1730 1732 1735 1736 1737 1741\n 1742 1744 1746 1748 1749 1751 1752 1754 1756 1757 1759 1761 1762 1763\n 1766 1767 1768 1769 1771 1772 1775 1776 1777 1778 1779 1782 1785 1787\n 1790 1791 1793 1797 1798 1799 1800 1801 1804 1806 1807 1809 1810 1820\n 1825 1827 1828 1829 1830 1834 1835 1836 1839 1841 1842 1843 1845 1847\n 1848 1849 1850 1855 1858 1859 1861 1863 1864 1865 1868 1870 1872 1873\n 1876 1877 1878 1879 1881 1882 1884 1887 1889 1891 1892 1894 1896 1897\n 1899 1900 1901 1904 1905 1906 1910 1914 1920]\nTRAIN: [ 0 2 3 7 9 10 12 13 15 17 19 20 21 22\n 23 25 28 31 33 34 35 36 37 38 39 40 41 44\n 45 46 52 53 54 56 57 58 59 62 63 65 66 67\n 69 70 71 72 73 76 80 82 84 87 88 98 99 100\n 106 107 111 112 114 116 117 118 119 121 122 123 126 128\n 129 132 133 142 145 149 151 154 155 157 159 162 166 167\n 168 170 172 173 177 182 184 187 189 194 196 200 201 202\n 204 205 206 207 209 210 212 213 214 215 216 219 221 223\n 224 225 228 232 234 235 236 237 238 239 240 243 244 245\n 246 248 250 252 255 257 259 262 266 267 271 275 276 279\n 280 281 284 287 288 290 291 293 294 295 297 301 302 303\n 304 305 306 307 309 311 312 313 314 316 317 318 319 321\n 324 326 327 328 329 330 333 336 337 339 340 342 344 345\n 347 349 350 352 358 359 360 361 365 368 371 376 377 380\n 381 386 387 389 393 394 395 396 397 398 399 402 404 405\n 407 408 410 411 412 414 419 422 424 425 427 431 432 434\n 435 436 437 438 441 443 446 447 456 457 458 461 462 463\n 468 471 473 479 482 483 485 487 488 492 493 494 497 500\n 501 502 506 509 511 512 515 516 517 518 519 520 521 522\n 523 525 527 528 533 534 535 536 537 538 542 544 545 546\n 550 553 554 555 558 559 560 562 563 565 566 573 574 578\n 581 585 594 595 596 597 599 602 604 605 608 609 610 611\n 616 619 621 622 623 625 626 633 638 639 644 647 652 653\n 654 655 657 658 662 663 664 665 666 669 671 673 674 675\n 676 677 680 683 684 685 686 688 689 691 693 694 695 696\n 699 702 703 704 706 707 708 713 716 717 719 720 721 723\n 724 726 727 729 730 731 732 741 744 746 747 749 751 753\n 754 755 756 757 758 759 760 765 766 768 769 772 777 778\n 780 781 783 785 786 787 788 789 791 795 796 797 798 799\n 800 801 804 809 810 811 812 814 817 818 819 820 824 826\n 828 829 830 832 835 836 838 839 840 841 844 847 850 851\n 854 856 858 859 861 863 865 866 868 869 870 872 874 875\n 877 882 888 890 891 892 897 898 900 901 905 907 909 910\n 915 917 918 920 921 922 923 928 930 931 932 933 935 936\n 940 942 943 947 952 957 961 962 964 965 967 971 974 975\n 980 981 983 985 986 987 988 989 991 994 996 997 998 999\n 1004 1005 1008 1010 1011 1012 1014 1015 1016 1017 1018 1019 1020 1021\n 1023 1024 1028 1029 1032 1033 1038 1040 1041 1045 1046 1050 1054 1055\n 1056 1057 1058 1060 1065 1066 1067 1069 1070 1074 1076 1077 1079 1080\n 1084 1086 1087 1088 1089 1091 1093 1096 1097 1098 1099 1100 1103 1104\n 1105 1106 1107 1109 1111 1112 1114 1120 1121 1122 1123 1124 1125 1127\n 1133 1134 1137 1139 1140 1141 1143 1144 1146 1149 1153 1154 1156 1157\n 1159 1161 1163 1166 1167 1171 1172 1173 1175 1177 1178 1180 1181 1185\n 1187 1190 1192 1195 1196 1200 1201 1206 1210 1213 1215 1218 1219 1222\n 1225 1228 1230 1232 1233 1234 1235 1237 1239 1240 1243 1244 1245 1246\n 1249 1250 1252 1255 1256 1259 1260 1261 1262 1263 1264 1266 1267 1273\n 1276 1277 1279 1280 1282 1283 1290 1292 1293 1294 1295 1296 1297 1298\n 1299 1301 1304 1306 1307 1308 1315 1318 1320 1322 1325 1326 1327 1328\n 1331 1332 1333 1335 1336 1337 1338 1339 1340 1345 1346 1347 1348 1349\n 1351 1353 1354 1355 1356 1357 1358 1360 1363 1366 1368 1370 1372 1373\n 1375 1376 1378 1380 1383 1386 1387 1388 1389 1390 1392 1393 1396 1398\n 1399 1400 1403 1404 1405 1406 1410 1412 1416 1418 1421 1422 1425 1426\n 1427 1429 1432 1438 1441 1444 1446 1447 1449 1452 1454 1459 1461 1462\n 1463 1466 1469 1471 1472 1475 1476 1480 1484 1486 1488 1489 1491 1492\n 1494 1498 1500 1501 1502 1503 1504 1505 1506 1507 1509 1511 1512 1513\n 1515 1516 1518 1520 1521 1525 1527 1528 1535 1536 1538 1539 1543 1544\n 1549 1552 1553 1554 1557 1561 1562 1566 1569 1572 1576 1578 1581 1582\n 1583 1584 1585 1596 1597 1600 1606 1607 1609 1610 1614 1615 1617 1618\n 1620 1621 1623 1629 1630 1634 1635 1637 1639 1640 1642 1649 1650 1652\n 1655 1656 1658 1660 1661 1662 1665 1668 1670 1673 1675 1677 1679 1680\n 1686 1687 1688 1689 1691 1692 1696 1698 1699 1701 1703 1704 1707 1710\n 1711 1713 1714 1719 1723 1724 1726 1729 1730 1732 1735 1736 1737 1741\n 1742 1744 1746 1748 1749 1751 1752 1754 1756 1757 1759 1761 1762 1763\n 1766 1767 1768 1769 1771 1772 1775 1776 1777 1778 1779 1782 1785 1787\n 1790 1791 1793 1797 1798 1799 1800 1801 1804 1806 1807 1809 1810 1820\n 1825 1827 1828 1829 1830 1834 1835 1836 1839 1841 1842 1843 1845 1847\n 1848 1849 1850 1855 1858 1859 1861 1863 1864 1865 1868 1870 1872 1873\n 1876 1877 1878 1879 1881 1882 1884 1887 1889 1891 1892 1894 1896 1897\n 1899 1900 1901 1904 1905 1906 1910 1914 1920] TEST: [ 1 4 5 6 8 11 14 16 18 24 26 27 29 30\n 32 42 43 47 48 49 50 51 55 60 61 64 68 74\n 75 77 78 79 81 83 85 86 89 90 91 92 93 94\n 95 96 97 101 102 103 104 105 108 109 110 113 115 120\n 124 125 127 130 131 134 135 136 137 138 139 140 141 143\n 144 146 147 148 150 152 153 156 158 160 161 163 164 165\n 169 171 174 175 176 178 179 180 181 183 185 186 188 190\n 191 192 193 195 197 198 199 203 208 211 217 218 220 222\n 226 227 229 230 231 233 241 242 247 249 251 253 254 256\n 258 260 261 263 264 265 268 269 270 272 273 274 277 278\n 282 283 285 286 289 292 296 298 299 300 308 310 315 320\n 322 323 325 331 332 334 335 338 341 343 346 348 351 353\n 354 355 356 357 362 363 364 366 367 369 370 372 373 374\n 375 378 379 382 383 384 385 388 390 391 392 400 401 403\n 406 409 413 415 416 417 418 420 421 423 426 428 429 430\n 433 439 440 442 444 445 448 449 450 451 452 453 454 455\n 459 460 464 465 466 467 469 470 472 474 475 476 477 478\n 480 481 484 486 489 490 491 495 496 498 499 503 504 505\n 507 508 510 513 514 524 526 529 530 531 532 539 540 541\n 543 547 548 549 551 552 556 557 561 564 567 568 569 570\n 571 572 575 576 577 579 580 582 583 584 586 587 588 589\n 590 591 592 593 598 600 601 603 606 607 612 613 614 615\n 617 618 620 624 627 628 629 630 631 632 634 635 636 637\n 640 641 642 643 645 646 648 649 650 651 656 659 660 661\n 667 668 670 672 678 679 681 682 687 690 692 697 698 700\n 701 705 709 710 711 712 714 715 718 722 725 728 733 734\n 735 736 737 738 739 740 742 743 745 748 750 752 761 762\n 763 764 767 770 771 773 774 775 776 779 782 784 790 792\n 793 794 802 803 805 806 807 808 813 815 816 821 822 823\n 825 827 831 833 834 837 842 843 845 846 848 849 852 853\n 855 857 860 862 864 867 871 873 876 878 879 880 881 883\n 884 885 886 887 889 893 894 895 896 899 902 903 904 906\n 908 911 912 913 914 916 919 924 925 926 927 929 934 937\n 938 939 941 944 945 946 948 949 950 951 953 954 955 956\n 958 959 960 963 966 968 969 970 972 973 976 977 978 979\n 982 984 990 992 993 995 1000 1001 1002 1003 1006 1007 1009 1013\n 1022 1025 1026 1027 1030 1031 1034 1035 1036 1037 1039 1042 1043 1044\n 1047 1048 1049 1051 1052 1053 1059 1061 1062 1063 1064 1068 1071 1072\n 1073 1075 1078 1081 1082 1083 1085 1090 1092 1094 1095 1101 1102 1108\n 1110 1113 1115 1116 1117 1118 1119 1126 1128 1129 1130 1131 1132 1135\n 1136 1138 1142 1145 1147 1148 1150 1151 1152 1155 1158 1160 1162 1164\n 1165 1168 1169 1170 1174 1176 1179 1182 1183 1184 1186 1188 1189 1191\n 1193 1194 1197 1198 1199 1202 1203 1204 1205 1207 1208 1209 1211 1212\n 1214 1216 1217 1220 1221 1223 1224 1226 1227 1229 1231 1236 1238 1241\n 1242 1247 1248 1251 1253 1254 1257 1258 1265 1268 1269 1270 1271 1272\n 1274 1275 1278 1281 1284 1285 1286 1287 1288 1289 1291 1300 1302 1303\n 1305 1309 1310 1311 1312 1313 1314 1316 1317 1319 1321 1323 1324 1329\n 1330 1334 1341 1342 1343 1344 1350 1352 1359 1361 1362 1364 1365 1367\n 1369 1371 1374 1377 1379 1381 1382 1384 1385 1391 1394 1395 1397 1401\n 1402 1407 1408 1409 1411 1413 1414 1415 1417 1419 1420 1423 1424 1428\n 1430 1431 1433 1434 1435 1436 1437 1439 1440 1442 1443 1445 1448 1450\n 1451 1453 1455 1456 1457 1458 1460 1464 1465 1467 1468 1470 1473 1474\n 1477 1478 1479 1481 1482 1483 1485 1487 1490 1493 1495 1496 1497 1499\n 1508 1510 1514 1517 1519 1522 1523 1524 1526 1529 1530 1531 1532 1533\n 1534 1537 1540 1541 1542 1545 1546 1547 1548 1550 1551 1555 1556 1558\n 1559 1560 1563 1564 1565 1567 1568 1570 1571 1573 1574 1575 1577 1579\n 1580 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1598 1599 1601\n 1602 1603 1604 1605 1608 1611 1612 1613 1616 1619 1622 1624 1625 1626\n 1627 1628 1631 1632 1633 1636 1638 1641 1643 1644 1645 1646 1647 1648\n 1651 1653 1654 1657 1659 1663 1664 1666 1667 1669 1671 1672 1674 1676\n 1678 1681 1682 1683 1684 1685 1690 1693 1694 1695 1697 1700 1702 1705\n 1706 1708 1709 1712 1715 1716 1717 1718 1720 1721 1722 1725 1727 1728\n 1731 1733 1734 1738 1739 1740 1743 1745 1747 1750 1753 1755 1758 1760\n 1764 1765 1770 1773 1774 1780 1781 1783 1784 1786 1788 1789 1792 1794\n 1795 1796 1802 1803 1805 1808 1811 1812 1813 1814 1815 1816 1817 1818\n 1819 1821 1822 1823 1824 1826 1831 1832 1833 1837 1838 1840 1844 1846\n 1851 1852 1853 1854 1856 1857 1860 1862 1866 1867 1869 1871 1874 1875\n 1880 1883 1885 1886 1888 1890 1893 1895 1898 1902 1903 1907 1908 1909\n 1911 1912 1913 1915 1916 1917 1918 1919]\n"
],
[
"# training a Naive Bayes classifier\nfrom sklearn.naive_bayes import GaussianNB\ngnb = GaussianNB()\nfrom yellowbrick.classifier import ClassificationReport\nvisualizer = ClassificationReport(gnb, classes=y.unique(), support=True)\nvisualizer.fit(train_X, train_y) # Fit the visualizer and the model\nvisualizer.score(test_X, test_y) # Evaluate the model on the test data\nvisualizer.show() # Plot the result",
"_____no_output_____"
],
[
"scores = cross_val_score(gnb, X, y, cv=10)",
"_____no_output_____"
],
[
"print(scores)",
"[0.59585492 0.578125 0.63541667 0.56770833 0.65625 0.65625\n 0.6875 0.625 0.67708333 0.61458333]\n"
],
[
"scores.mean()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd43737aba587ee82366025a5985292a0d84d91
| 6,153 |
ipynb
|
Jupyter Notebook
|
examples/notebooks/wrench.ipynb
|
dbt-ethz/compas_vol
|
d8faa22b4b782896837eac0fa10eefb9b2d7f928
|
[
"MIT"
] | 8 |
2020-02-13T11:51:03.000Z
|
2022-01-13T10:27:47.000Z
|
examples/notebooks/wrench.ipynb
|
dbt-ethz/compas_vol
|
d8faa22b4b782896837eac0fa10eefb9b2d7f928
|
[
"MIT"
] | 5 |
2019-12-04T19:48:40.000Z
|
2021-08-23T09:48:48.000Z
|
examples/notebooks/wrench.ipynb
|
dbt-ethz/compas_vol
|
d8faa22b4b782896837eac0fa10eefb9b2d7f928
|
[
"MIT"
] | 6 |
2020-02-12T18:19:23.000Z
|
2021-12-16T11:00:32.000Z
| 26.182979 | 438 | 0.569153 |
[
[
[
"## import libraries",
"_____no_output_____"
]
],
[
[
"from compas_vol.primitives import VolBox, VolCylinder, VolPlane\nfrom compas_vol.modifications import Overlay, Shell\nfrom compas_vol.combinations import Intersection, Union, Subtraction\nfrom compas_vol.microstructures import TPMS\nfrom compas.geometry import Box, Frame, Point, Plane, Cylinder, Circle",
"_____no_output_____"
],
[
"import numpy as np\nimport meshplot as mp\nfrom skimage.measure import marching_cubes\nfrom compas_vol.utilities import bbox_edges",
"_____no_output_____"
]
],
[
[
"## create volumetric object (CSG tree)",
"_____no_output_____"
]
],
[
[
"shaft = VolBox(Box(Frame.worldXY(), 250, 30, 10), 1.5)\ncyl_plane = Plane((125,0,0),(0,0,1))\nroundcap = VolCylinder(Cylinder(Circle(cyl_plane, 15), 10))\nhandle = Union(shaft, roundcap)\n\ngyroid = TPMS(tpmstype='Gyroid', wavelength=5.0)\nshell = Shell(gyroid, 2.0, 0.5)\n\nol_plane = VolPlane(Plane((0,0,0), (1,0,0)))\nthicken_tpms = Overlay(shell, ol_plane, 0.005)\ntaper = Overlay(handle, ol_plane, -0.01)\n\nporous_handle = Intersection(thicken_tpms, taper)\nsolid_outer = VolCylinder(Cylinder(Circle(cyl_plane, 12), 13))\nvoid_inner = VolCylinder(Cylinder(Circle(cyl_plane, 10), 20))\nhole_reinforce = Union(porous_handle, solid_outer)\nwrench = Subtraction(hole_reinforce, void_inner)\n",
"_____no_output_____"
]
],
[
[
"## workspace (dense grid)",
"_____no_output_____"
]
],
[
[
"#workspace initialization\n# lower and upper bounds\nlbx, ubx = -145.0, 145.0\nlby, uby = -18.0, 18.0\nlbz, ubz = -8.0, 8.0\n# resolution(s)\nnx, ny, nz = 580, 72, 32\nx, y, z = np.ogrid[lbx:ubx:nx*1j, lby:uby:ny*1j, lbz:ubz:nz*1j]\n#voxel dimensions\ngx = (ubx-lbx)/nx\ngy = (uby-lby)/ny\ngz = (ubz-lbz)/nz",
"_____no_output_____"
]
],
[
[
"## sample at discrete interval",
"_____no_output_____"
]
],
[
[
"dm = wrench.get_distance_numpy(x, y, z)",
"/Users/bernham/Dropbox/My Mac (staff-net-hix-1665.ethz.ch)/Documents/Resources/ProgrammingLibraries/compas-dev/compas_vol/src/compas_vol/primitives/vplane.py:59: 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 d = np.dot(np.array([x, y, z]), normal)\n"
]
],
[
[
"## generate isosurface (marching cube)",
"_____no_output_____"
]
],
[
[
"v, f, n, l = marching_cubes(dm, 0, spacing=(gx, gy, gz))\nv += [lbx,lby,lbz]",
"_____no_output_____"
]
],
[
[
"## display mesh",
"_____no_output_____"
]
],
[
[
"p = mp.plot(v, f, c=np.array([0,0.57,0.82]), shading={\"flat\":False, \"roughness\":0.4, \"metalness\":0.01, \"reflectivity\":1.0})\nvs,ve = bbox_edges(lbx,ubx,lby,uby,lbz,ubz)\np.add_lines(np.array(vs), np.array(ve))",
"/Users/bernham/anaconda3/envs/compasdev/lib/python3.9/site-packages/jupyter_client/session.py:716: UserWarning: Message serialization failed with:\nOut of range float values are not JSON compliant\nSupporting this message is deprecated in jupyter-client 7, please make sure your message is JSON-compliant\n content = self.pack(content)\n"
]
]
] |
[
"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"
]
] |
cbd43e48be7b9570189aa02bc66c1023b80fff91
| 14,729 |
ipynb
|
Jupyter Notebook
|
14_terminal_de_comandos_bash/bash.ipynb
|
Fcovalencia/python
|
8e4aa261da0b48ff6313df6670e43088d58c0313
|
[
"MIT"
] | 8 |
2016-04-05T17:33:14.000Z
|
2019-12-09T20:20:18.000Z
|
14_terminal_de_comandos_bash/bash.ipynb
|
Fcovalencia/python
|
8e4aa261da0b48ff6313df6670e43088d58c0313
|
[
"MIT"
] | null | null | null |
14_terminal_de_comandos_bash/bash.ipynb
|
Fcovalencia/python
|
8e4aa261da0b48ff6313df6670e43088d58c0313
|
[
"MIT"
] | 8 |
2016-05-13T20:20:23.000Z
|
2021-04-01T22:55:36.000Z
| 40.464286 | 430 | 0.640166 |
[
[
[
"<img src=\"images/utfsm.png\" alt=\"\" width=\"100px\" align=\"right\"/>\n# USM Numérica",
"_____no_output_____"
],
[
"## Licencia y configuración del laboratorio\nEjecutar la siguiente celda mediante *`Ctr-S`*.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nIPython Notebook v4.0 para python 3.0\nLibrerías adicionales: \nContenido bajo licencia CC-BY 4.0. Código bajo licencia MIT. \n(c) Sebastian Flores, Christopher Cooper, Alberto Rubio, Pablo Bunout.\n\"\"\"\n# Configuración para recargar módulos y librerías dinámicamente\n%reload_ext autoreload\n%autoreload 2\n\n# Configuración para graficos en línea\n%matplotlib inline\n\n# Configuración de estilo\nfrom IPython.core.display import HTML\nHTML(open(\"./style/style.css\", \"r\").read())",
"_____no_output_____"
]
],
[
[
"## Introducción a BASH",
"_____no_output_____"
],
[
"Antes de comenzar debemos saber que Bash es un programa informático usado como intérprete de comandos \no instrucciones dadas por un usuario, las cuales son escritas en alguna interfaz gráfica o comúnmente \nuna terminal. Esas instrucciones son interpretadas por Bash para luego enviar dichas órdenes al Núcleo \no Kernel del sistema operativo.\n\nCada sistema operativo se encuentra conformado por un Núcleo particular, que se encarga de interactuar \ncon la computadora siendo una especie de cerebro capaz de organizar, administrar y distribuir los recursos \nfísicos de esta, tales como memoria, procesador, forma de almacenamiento, entre otros.\n\n\n\n<img src=\"imbash.png\"width=\"700px\">\n\n\n\nBash (Bourne-Again-Shell) es un lenguaje de programación basado en Bourne-Shell, el cual fue creado para \nsistemas Unix en la década de los 70, siendo el sustituto natural y de acceso libre de este a partir del \naño 1987 siendo compatible con la mayoría de sistemas Unix, GNU/Linux y en algunos casos con Microsoft-Windows \ny Apple. \n",
"_____no_output_____"
],
[
"## Objetivos",
"_____no_output_____"
],
[
"1. Operaciones básicas para crear, abrir y cambiarse de directorio\n2. Operaciones para crear un archivo, copiar y cambiarlo de directorio\n3. Visualizador gráfico de directorios y archivos\n4. Visualizador de datos y editor de un archivo de texto\n5. Ejercicio de práctica\n\n",
"_____no_output_____"
],
[
"### 1. Operaciones para crear, abrir y cambiar de directorio\n",
"_____no_output_____"
],
[
"Este es el tipo de operaciones más básicas que un usuario ejecuta en un sistema operativo, los siguientes comandos nos permiten ubicarnos en alguna carpeta para tener acceso a algún archivo o material en específico, crear carpetas o directorios para almacenar información deseada entre otros.\n\nLa acción más simple para comenzar será ingresar a un directorio o carpeta deseada usando el comando *`cd`* como sigue:\n```\ncd <directorio>\n```\nUna extensión de este recurso es la posibilidad de colocar una secuencia de directorios para llegar a la ubicación deseada, separando los nombres por un slash del siguiente modo.\n```\ncd <directorio_1>/<subdirectorio_2>/<subdirectorio_3>\n```\nPodemos visualizar en la terminal el contenido de este directorio con el comando *`ls`* y luego crear un nuevo sub-directorio (o carpeta) dentro del directorio en el cual nos ubicamos con *`mkdir`*:\n```\nmkdir <subdirectorio>\n```\nMencionamos además una opción con el comando anterior, que nos permite crear varios sub-directorios a la vez escribiendo sus nombres respectivos uno al lado del otro, separados por un espacio.\n```\nmkdir <subdirectorio_1> <subdirectorio_2> ... <subdirectorio_N>\n```\n\nAdemás como detalle si el nombre de nuestro directorio se conforma por palabras separadas por espacio, entonces conviene por defecto escribir el nombre completo entre comillas, puesto que de lo contrario Bash considerará cada palabra separada por un espacio como un subdirectorio diferente.\n```\nmkdir <\"nombre subdirectorio\">\n```\n\n\nSi queremos regresar a una ubicación anterior basta los comandos *`cd ..`* o *`cd -`* y si queremos volver al directorio original desde donde se abrió la terminal usamos *`cd ~`*. \n\nEs posible borrar un directorio con su contenido al interior escribiendo el siguiente comando: \n```Bash\nrm -r <directorio>\n```\nFinalmente un comando que nos permite visualizar rápidamente nuestra ubicación actual y las precedentes es *`pwd`*.",
"_____no_output_____"
],
[
"### 2. Operaciones para crear, copiar y eliminar archivos",
"_____no_output_____"
],
[
"Un paso siguiente a lo visto en el punto anterior es la creación de algún tipo de archivo, realizando operaciones básicas como copiarlo de un directorio a otro, cambiarlo de ubicación o borrarlo.\n\nPara crear un archivo debemos ingresar al directorio en el cual deseamos guardarlo con el comando *`cd`* y luego de esto podemos crear el archivo con el argumento *`>`* de la siguiente manera.\n```\n> <archivo.tipo>\n``` \nPor defecto el archivo se crea en el directorio actual de nuestra ubicación, recordar que con pwd podemos visualizar la cadena de directorios y subdirectorios hasta la ubicación actual.\n\nDebemos hacer referencia al comando *`echo`*, este consiste en una función interna del intérprete de comandos que nos permite realizar más de una acción al combinarlo de distintas maneras con otros comandos o variables. Uno de los usos más comunes es para la impresión de algún texto en la terminal.\n```\necho <texto a imprimir>\n``` \nTambién nos permite imprimir un texto en un archivo específico agregando *`echo <texto a imprimir> < <archivo sobre el que se imprime>`*, entre muchas otras opciones que la función *`echo`* nos permite realizar y que es posible profundizar con la práctica, pero estas las postergaremos para la siguiente sección.\n\nContinuamos con el comando *`mv`*, que refiere a \"move\", el cual sirve para mover algún archivo ya creado a un nuevo directorio.\n```\nmv <archivo.tipo> <directorio>\n```\nTambién sirve para mover un directorio dentro de otro (mover *directorio_1* al *direcotorio_2*), para que el comando se ejecute correctamente ambos directorios deben estar en una misma ubicación.\n```\nmv <directorio_1> <directorio_2>\n```\nUna operación similar a la anterior es copiar un archivo y llevarlo a un directorio particular, con la diferencia que una vez realizada la acción se tendrán 2 copias del mismo archivo, una en el directorio original y la segunda en el nuevo directorio.\n```\ncp <archivo.tipo> <directorio>\n```\nSupongamos que queremos copiar un archivo existente en otro directorio y reemplazarlo por un archivo del directorio actual, podemos hacer esto de la siguiente manera.\n```\ncp ~/directorio_fuente/<archivo_fuente> <archivo_local>\n```\nLo anterior se hace desde el directorio al cual deseamos copiar el archivo fuente y *~/directoiro_fuente/* hace alusión al directorio en el cual se encuentra este archivo.\n\nSi por otra parte queremos copiar un archivo fuente y nos encontramos en el directorio en el cual este se encuentra, para realizar la copia en otro directorio, sin necesariamente hacer un reemplazo por otro archivo, se puede con:\n```\ncp <archivo_fuente_1> <archivo_fuente_2> ~/directorio_desitno/\n```\n\nDel mismo modo que para un directorio, si queremos borrar un archivo creado podemos hacerlo con el comando *`rm -r`*.\n```\nrm -r <archivo.tipo>\n```\nY si queremos borrar una serie de archivos lo hacemos escribiendo consecutivamente.\n```\nrm -r <archivo_1.tipo> <archivo_2.tipo> ... <archivo_N.tipo>\n```\n",
"_____no_output_____"
],
[
"### 3. Visualizador de estructura de directorios y archivos",
"_____no_output_____"
],
[
"El comando *`tree`* es una forma útil y rápida de visualizar gráficamente la estructura de directorios y archivo pudiendo ver claramente la relación entre estos. Solo debemos escribir el comando para que automáticamente aparezca esta información en pantalla (dentro de la terminal) apareciendo en orden alfabético, por defecto debe ejecutarse ubicándose en el directorio deseado visualizando la estructura dentro de este.\n\nEn caso de que este no se encuentre instalado en nuestro sistema operativo, a modo de ejercicio, primero debemos escribir los siguientes comandos.\n```\nsudo apt-get install <tree>\n```\n\n",
"_____no_output_____"
],
[
"### 4. Visualizar, editar y concatenar un archivo de texto",
"_____no_output_____"
],
[
"Para visualizar el contenido de un texto previamente creado, pudiendo hacerlo con el comando visto anteriormente, *`echo > arhcivo.tipo`*, utilizamos el comando *`cat`*.\n```\ncat <archivo.tipo>\n```\nLuego si queremos visualizar varios archivos en la terminal, lo hacemos agregando uno al lado del otro después del comando *`cat`*.\n```\ncat <archivo_1.tipo> <archivo_2.tipo> ... <archivo_N.tipo>\n```\nExisten muchos argumentos que nos permiten visualizar de distinta forma el contenido de un archivo en la terminal, por ejemplo enumerar las filas de algún texto, *`cat -n`*, otra opción sería que solo se enumerara las filas que tienen algún contenido, *`cat -b`*.\n\nEn caso de que queramos enumerar solo las filas con texto, pero este tiene demasiadas filas en blanco y buscamos reducirlas a una sola de modo de ahorrar espacio en la terminal, podemos hacerlo agregando el argumento *-s* como sigue.\n```\ncat -sb <archivo.tipo>\n```\nEditar o imprimir un texto en un archivo es posible hacerlo usando la función *`echo`* como sigue.\n```\necho <texto a imprimir> ./archivo.txt\n``` ",
"_____no_output_____"
],
[
"Similar a sudo, less es un programa usado como visualizador de archivos de texto que funciona como un comando interpretado desde la terminal. Este permite visualizar completamente el archivo de texto usando por defecto las flechas del teclado para avanzar o retroceder en el visualizador.\n\nUna de las ventajas de un programa como less, es que puede añadirse comandos para ejecutar acciones de forma rápida en modo de comandos que resulta por defecto al ejecutar less, a continuación presentamos algunos comandos básicos.\n```\nG: permite visualizar el final del texto \n```\n```\ng: permite visualizar el inicio del texto\n```\n```\nh: nos proporciona ayuda respecto a comandos posibles\n```\n```\nq: permite salir de la aplicación dentro del visualizador less\n```\nPara modificar el texto una de las formas es cargar algún editor de texto como por ejemplo el Visual.\n```\nv: ejecutar el editor de texto\n```",
"_____no_output_____"
],
[
"### 5. Ejercicio de práctica",
"_____no_output_____"
],
[
"Para redondear lo visto en este tutorial se dejara como ejercicio las siguientes instrucciones:\n\n * Crear una carpeta o directorio principal\n * En ella se debe copiar 2 archivos de textos provenientes de cualquier dirección\n * Crear un archivo de texto el cual tenga por nombre \"Texto Principal\" y se imprima \"concatenación de textos\"\n * Crear una segunda carpeta dentro de la principal \n * Concatenar los 2 archivos copiados con el archivo creado\n * Mover el archivo \"Texto Principal\" a la nueva carpeta \n * Eliminar las copias de los archivos concatenados\n * Visualizar con Tree la estructura y relación de archivos y directorios creados",
"_____no_output_____"
]
],
[
[
"%%bash",
"UsageError: %%bash is a cell magic, but the cell body is empty."
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
cbd442bcd84ec579f7c3bc7ca4ba6533e79fb0c4
| 68,379 |
ipynb
|
Jupyter Notebook
|
notes/reference/moocs/fast.ai/dl-2018/lesson04-prudential-life-insurance-assessment.ipynb
|
aav789/study-notes
|
34eca00cd48869ba7a79c0ea7d8948ee9bde72b9
|
[
"MIT"
] | 43 |
2015-06-10T14:48:00.000Z
|
2020-11-29T16:22:28.000Z
|
notes/reference/moocs/fast.ai/dl-2018/lesson04-prudential-life-insurance-assessment.ipynb
|
aav789/study-notes
|
34eca00cd48869ba7a79c0ea7d8948ee9bde72b9
|
[
"MIT"
] | 1 |
2021-11-01T12:01:44.000Z
|
2021-11-01T12:01:44.000Z
|
notes/reference/moocs/fast.ai/dl-2018/lesson04-prudential-life-insurance-assessment.ipynb
|
lextoumbourou/notes
|
5f94c59a467eb3eb387542bdce398abc0365e6a7
|
[
"MIT"
] | 40 |
2015-03-02T10:33:59.000Z
|
2020-05-24T12:17:05.000Z
| 42.603738 | 16,768 | 0.529212 |
[
[
[
"# Prudential Life Insurance Assessment\n\nAn example of the structured data lessons from Lesson 4 on another dataset.",
"_____no_output_____"
]
],
[
[
"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\n\nimport os\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom fastai import structured\nfrom fastai.column_data import ColumnarModelData\nfrom fastai.dataset import get_cv_idxs\nfrom sklearn.metrics import cohen_kappa_score\nfrom ml_metrics import quadratic_weighted_kappa\nfrom torch.nn.init import kaiming_uniform, kaiming_normal",
"_____no_output_____"
],
[
"PATH = Path('./data/prudential')\nPATH.mkdir(exist_ok=True)",
"_____no_output_____"
]
],
[
[
"## Download dataset",
"_____no_output_____"
]
],
[
[
"!kaggle competitions download -c prudential-life-insurance-assessment --path={PATH}",
"Warning: Looks like you're using an outdated API Version, please consider updating (server 1.4.4 / client 1.4.3)\nDownloading sample_submission.csv.zip to data/prudential\n 0%| | 0.00/24.9k [00:00<?, ?B/s]\n100%|███████████████████████████████████████| 24.9k/24.9k [00:00<00:00, 948kB/s]\nDownloading test.csv.zip to data/prudential\n 98%|█████████████████████████████████████ | 1.00M/1.02M [00:00<00:00, 1.40MB/s]\n100%|██████████████████████████████████████| 1.02M/1.02M [00:00<00:00, 1.40MB/s]\nDownloading train.csv.zip to data/prudential\n 97%|████████████████████████████████████▋ | 3.00M/3.10M [00:02<00:00, 1.46MB/s]\n100%|██████████████████████████████████████| 3.10M/3.10M [00:02<00:00, 1.47MB/s]\n"
],
[
"for file in os.listdir(PATH):\n if not file.endswith('zip'):\n continue\n \n !unzip -q -d {PATH} {PATH}/{file}",
"_____no_output_____"
],
[
"train_df = pd.read_csv(PATH/'train.csv')",
"_____no_output_____"
],
[
"train_df.head()",
"_____no_output_____"
]
],
[
[
"Extra feature engineering taken from the forum",
"_____no_output_____"
]
],
[
[
"train_df['Product_Info_2_char'] = train_df.Product_Info_2.str[0]\ntrain_df['Product_Info_2_num'] = train_df.Product_Info_2.str[1]\ntrain_df['BMI_Age'] = train_df['BMI'] * train_df['Ins_Age']\nmed_keyword_columns = train_df.columns[train_df.columns.str.startswith('Medical_Keyword_')]\ntrain_df['Med_Keywords_Count'] = train_df[med_keyword_columns].sum(axis=1)\ntrain_df['num_na'] = train_df.apply(lambda x: sum(x.isnull()), 1)",
"_____no_output_____"
],
[
"categorical_columns = 'Product_Info_1, Product_Info_2, Product_Info_3, Product_Info_5, Product_Info_6, Product_Info_7, Employment_Info_2, Employment_Info_3, Employment_Info_5, InsuredInfo_1, InsuredInfo_2, InsuredInfo_3, InsuredInfo_4, InsuredInfo_5, InsuredInfo_6, InsuredInfo_7, Insurance_History_1, Insurance_History_2, Insurance_History_3, Insurance_History_4, Insurance_History_7, Insurance_History_8, Insurance_History_9, Family_Hist_1, Medical_History_2, Medical_History_3, Medical_History_4, Medical_History_5, Medical_History_6, Medical_History_7, Medical_History_8, Medical_History_9, Medical_History_11, Medical_History_12, Medical_History_13, Medical_History_14, Medical_History_16, Medical_History_17, Medical_History_18, Medical_History_19, Medical_History_20, Medical_History_21, Medical_History_22, Medical_History_23, Medical_History_25, Medical_History_26, Medical_History_27, Medical_History_28, Medical_History_29, Medical_History_30, Medical_History_31, Medical_History_33, Medical_History_34, Medical_History_35, Medical_History_36, Medical_History_37, Medical_History_38, Medical_History_39, Medical_History_40, Medical_History_41'.split(', ')",
"_____no_output_____"
],
[
"categorical_columns += ['Product_Info_2_char', 'Product_Info_2_num']",
"_____no_output_____"
],
[
"cont_columns = 'Product_Info_4, Ins_Age, Ht, Wt, BMI, Employment_Info_1, Employment_Info_4, Employment_Info_6, Insurance_History_5, Family_Hist_2, Family_Hist_3, Family_Hist_4, Family_Hist_5, Medical_History_1, Medical_History_10, Medical_History_15, Medical_History_24, Medical_History_32'.split(', ')",
"_____no_output_____"
],
[
"cont_columns += [c for c in train_df.columns if c.startswith('Medical_Keyword_')] + ['BMI_Age', 'Med_Keywords_Count', 'num_na']",
"_____no_output_____"
],
[
"train_df[categorical_columns].head()",
"_____no_output_____"
],
[
"train_df[cont_columns].head()",
"_____no_output_____"
],
[
"train_df = train_df[categorical_columns + cont_columns + ['Response']]",
"_____no_output_____"
],
[
"len(train_df.columns)",
"_____no_output_____"
]
],
[
[
"### Convert to categorical",
"_____no_output_____"
]
],
[
[
"for col in categorical_columns:\n train_df[col] = train_df[col].astype('category').cat.as_ordered()",
"_____no_output_____"
],
[
"train_df['Product_Info_1'].dtype",
"_____no_output_____"
],
[
"train_df.shape",
"_____no_output_____"
]
],
[
[
"### Numericalise and process DataFrame",
"_____no_output_____"
]
],
[
[
"df, y, nas, mapper = structured.proc_df(train_df, 'Response', do_scale=True)\ny = y.astype('float')",
"_____no_output_____"
],
[
"num_targets = len(set(y))",
"_____no_output_____"
]
],
[
[
"### Create ColumnData object (instead of ImageClassifierData)",
"_____no_output_____"
]
],
[
[
"cv_idx = get_cv_idxs(len(df))",
"_____no_output_____"
],
[
"cv_idx",
"_____no_output_____"
],
[
"model_data = ColumnarModelData.from_data_frame(\n PATH, cv_idx, df, y, cat_flds=categorical_columns, is_reg=True)",
"_____no_output_____"
],
[
"model_data.trn_ds[0][0].shape[0] + model_data.trn_ds[0][1].shape[0]",
"_____no_output_____"
],
[
"model_data.trn_ds[0][1].shape",
"_____no_output_____"
]
],
[
[
"### Get embedding sizes\n\nThe formula Jeremy uses for getting embedding sizes is: cardinality / 2 (maxed out at 50).\n\nWe reproduce that below:",
"_____no_output_____"
]
],
[
[
"categorical_column_sizes = [\n (c, len(train_df[c].cat.categories) + 1) for c in categorical_columns]",
"_____no_output_____"
],
[
"categorical_column_sizes[:5]",
"_____no_output_____"
],
[
"embedding_sizes = [(c, min(50, (c+1)//2)) for _, c in categorical_column_sizes]",
"_____no_output_____"
],
[
"embedding_sizes[:5]",
"_____no_output_____"
],
[
"def emb_init(x):\n x = x.weight.data\n sc = 2/(x.size(1)+1)\n x.uniform_(-sc,sc)",
"_____no_output_____"
],
[
"class MixedInputModel(nn.Module):\n def __init__(self, emb_sizes, num_cont):\n super().__init__()\n \n embedding_layers = []\n for size, dim in emb_sizes:\n embedding_layers.append(\n nn.Embedding(\n num_embeddings=size, embedding_dim=dim))\n \n self.embeddings = nn.ModuleList(embedding_layers)\n for emb in self.embeddings: emb_init(emb)\n self.embedding_dropout = nn.Dropout(0.04)\n \n self.batch_norm_cont = nn.BatchNorm1d(num_cont)\n \n num_emb = sum(e.embedding_dim for e in self.embeddings)\n \n self.fc1 = nn.Linear(\n in_features=num_emb + num_cont,\n out_features=1000)\n kaiming_normal(self.fc1.weight.data)\n self.dropout_fc1 = nn.Dropout(p=0.01)\n self.batch_norm_fc1 = nn.BatchNorm1d(1000)\n \n self.fc2 = nn.Linear(\n in_features=1000,\n out_features=500)\n kaiming_normal(self.fc2.weight.data)\n self.dropout_fc2 = nn.Dropout(p=0.01)\n self.batch_norm_fc2 = nn.BatchNorm1d(500)\n \n self.output_fc = nn.Linear(\n in_features=500,\n out_features=1\n )\n kaiming_normal(self.output_fc.weight.data)\n self.sigmoid = nn.Sigmoid()\n \n \n def forward(self, categorical_input, continuous_input):\n # Add categorical embeddings together\n categorical_embeddings = [e(categorical_input[:,i]) for i, e in enumerate(self.embeddings)]\n categorical_embeddings = torch.cat(categorical_embeddings, 1)\n categorical_embeddings_dropout = self.embedding_dropout(categorical_embeddings)\n \n # Batch normalise continuos vars\n continuous_input_batch_norm = self.batch_norm_cont(continuous_input)\n \n # Create a single vector\n x = torch.cat([\n categorical_embeddings_dropout, continuous_input_batch_norm\n ], dim=1)\n \n # Fully-connected layer 1\n fc1_output = self.fc1(x)\n fc1_relu_output = F.relu(fc1_output)\n fc1_dropout_output = self.dropout_fc1(fc1_relu_output)\n fc1_batch_norm = self.batch_norm_fc1(fc1_dropout_output)\n \n # Fully-connected layer 2\n fc2_output = self.fc2(fc1_batch_norm)\n fc2_relu_output = F.relu(fc2_output)\n fc2_batch_norm = self.batch_norm_fc2(fc2_relu_output)\n fc2_dropout_output = self.dropout_fc2(fc2_batch_norm)\n \n output = self.output_fc(fc2_dropout_output)\n output = self.sigmoid(output)\n \n output = output * 7\n output = output + 1\n\n return output",
"_____no_output_____"
],
[
"num_cont = len(df.columns) - len(categorical_columns)\n\nmodel = MixedInputModel(\n embedding_sizes,\n num_cont\n)",
"_____no_output_____"
],
[
"model",
"_____no_output_____"
],
[
"from fastai.column_data import StructuredLearner",
"_____no_output_____"
],
[
"def weighted_kappa_metric(probs, y):\n return quadratic_weighted_kappa(probs[:,0], y[:,0])",
"_____no_output_____"
],
[
"learner = StructuredLearner.from_model_data(model, model_data, metrics=[weighted_kappa_metric])",
"_____no_output_____"
],
[
"learner.lr_find()",
"_____no_output_____"
],
[
"learner.sched.plot()",
"_____no_output_____"
],
[
"learner.fit(0.0001, 3, use_wd_sched=True)",
"fit() warning: use_wd_sched is set to True, but weight decay(s) passed are 0. Use wds to pass weight decay values.\n"
],
[
"learner.fit(0.0001, 5, cycle_len=1, cycle_mult=2, use_wd_sched=True)",
"fit() warning: use_wd_sched is set to True, but weight decay(s) passed are 0. Use wds to pass weight decay values.\n"
],
[
"learner.fit(0.00001, 3, cycle_len=1, cycle_mult=2, use_wd_sched=True)",
"fit() warning: use_wd_sched is set to True, but weight decay(s) passed are 0. Use wds to pass weight decay values.\n"
]
],
[
[
"There's either a bug in my implementation, or a NN doesn't do that well at this problem.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cbd451efd3128cc2e99f683b9f19bd291cd4eac9
| 328,037 |
ipynb
|
Jupyter Notebook
|
DS502-1704/MXNet-week2-part1/demo_test.ipynb
|
YunchuZhang/DS502-AI-Engineer
|
a2e4acab34e8b9b69c982915364cdc6e05f03b71
|
[
"Apache-2.0"
] | 1 |
2018-04-02T05:06:20.000Z
|
2018-04-02T05:06:20.000Z
|
DS502-1704/MXNet-week2-part1/demo_test.ipynb
|
StephenBin/DS502-AI-Engineer
|
fea17ecfd012172354392e3be72c4ff5a2ab7da5
|
[
"Apache-2.0"
] | null | null | null |
DS502-1704/MXNet-week2-part1/demo_test.ipynb
|
StephenBin/DS502-AI-Engineer
|
fea17ecfd012172354392e3be72c4ff5a2ab7da5
|
[
"Apache-2.0"
] | null | null | null | 1,491.077273 | 161,400 | 0.948756 |
[
[
[
"import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport numpy as np\nimport mxnet as mx \nfrom symbol import get_resnet_model\nfrom symbol import YOLO_loss\nfrom data_ulti import get_iterator",
"_____no_output_____"
],
[
"def decodeBox(yolobox, size, dscale):\n i, j, cx, cy, w, h = yolobox\n cxt = j*dscale + cx*dscale\n cyt = i*dscale + cy*dscale\n wt = w*size\n ht = h*size\n return [cxt, cyt, wt, ht]\n\ndef bboxdraw(img, label, dscale=32):\n assert label.shape == (7,7,5)\n size = img.shape[1]\n ilist, jlist = np.where(label[:,:,0]>0.2)\n \n # Create figure and axes\n fig,ax = plt.subplots(1)\n ax.imshow(np.uint8(img))\n for i,j in zip(ilist, jlist): \n cx,cy,w,h = label[i,j,1:]\n cxt, cyt, wt ,ht = decodeBox([i, j, cx,cy,w,h], size, dscale)\n # Create a Rectangle patch\n rect = patches.Rectangle((cxt-wt/2,cyt-ht/2), wt,ht,linewidth=1,edgecolor='r',facecolor='none')\n\n # Add the patch to the Axes\n ax.add_patch(rect)\n \n plt.plot(int(cxt), int(cyt), '*')\n plt.show()",
"_____no_output_____"
],
[
"data = mx.io.ImageRecordIter(path_imgrec='DATA_rec/cat_small.rec',\n data_shape=(3,224,224),\n label_width=7*7*5, \n batch_size=1,)",
"_____no_output_____"
],
[
"# get sym \nsym, args_params, aux_params = mx.model.load_checkpoint('cat_detect_full_scale', 448)\nlogit = sym.get_internals()['logit_output']\nmod = mx.mod.Module(symbol=logit, context=mx.gpu(0))\nmod.bind(data.provide_data)\nmod.init_params(allow_missing=False, arg_params=args_params, aux_params=aux_params, \n initializer=mx.init.Xavier(magnitude=2,rnd_type='gaussian',factor_type='in'))\nout = mod.predict(eval_data=data, num_batch=10)",
"/home/chuck/DLenv/MXNet/local/lib/python2.7/site-packages/mxnet/module/base_module.py:52: UserWarning: \u001b[91mYou created Module with Module(..., label_names=['softmax_label']) but input with name 'softmax_label' is not found in symbol.list_arguments(). Did you mean one of:\n\tdata\u001b[0m\n warnings.warn(msg)\n/home/chuck/DLenv/MXNet/local/lib/python2.7/site-packages/mxnet/module/base_module.py:64: UserWarning: Data provided by label_shapes don't match names specified by label_names ([] vs. ['softmax_label'])\n warnings.warn(msg)\n"
],
[
"data.reset()\nbatch = data.next()\nbatch = data.next()\nbatch = data.next()\nimg = batch.data[0].asnumpy()[0].transpose((1,2,0))\nlabel = batch.label[0].asnumpy().reshape((7,7,5))\npred = (out.asnumpy()[2]+1)/2\nprint pred.shape",
"(7, 7, 5)\n"
],
[
"print \"Prediction\"\nbboxdraw(img, pred)",
"Prediction\n"
],
[
"print \"Ground Truth\"\nbboxdraw(img, label)",
"Ground Truth\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd458f6e336c0a6b1691c3971af3c029b9153c2
| 510,165 |
ipynb
|
Jupyter Notebook
|
Notebooks/Python/Part02_filtering_sample3.ipynb
|
hds-sandbox/scRNASeq_course
|
21de29197979562e99ee2080ca41479b033384ee
|
[
"Apache-2.0"
] | null | null | null |
Notebooks/Python/Part02_filtering_sample3.ipynb
|
hds-sandbox/scRNASeq_course
|
21de29197979562e99ee2080ca41479b033384ee
|
[
"Apache-2.0"
] | 3 |
2022-03-24T14:50:49.000Z
|
2022-03-25T12:09:55.000Z
|
Notebooks/Python/Part02_filtering_sample3.ipynb
|
hds-sandbox/scRNASeq_course
|
21de29197979562e99ee2080ca41479b033384ee
|
[
"Apache-2.0"
] | 1 |
2022-03-02T13:18:52.000Z
|
2022-03-02T13:18:52.000Z
| 409.113873 | 126,604 | 0.937544 |
[
[
[
"# **Quality Control (QC) and filtering**\n\nThis notebooks serves for filtering of the second human testis sample. It is analogous to the filtering of the other sample, so feel free to go through it faster and just skimming through the text.\n\n---------------------\n\n**Motivation:**\n\nQuality control and filtering is the most important steps of single cell data analysis. Allowing low quality cells into your analysis will compromise/mislead your conclusions by adding hundreds of meaningless data points to your workflow.\nThe main sources of low quality cells are\n- broken cells for which some of their transcripts get lost\n- cells isolated together with too much ambient RNA\n- missing cell during isolation (e.g. empty droplet in microfluidic machines)\n- multiple cells isolated together (multiplets, usually only two cells - doublets)\n\n---------------------------\n\n**Learning objectives:**\n\n- Understand and discuss QC issues and measures from single cell data\n- Explore QC graphs and set filtering tools and thresholds\n- Analyze the results of QC filters and evaluate necessity for different filtering \n----------------\n**Execution time: 40 minutes**",
"_____no_output_____"
],
[
"------------------------------------",
"_____no_output_____"
],
[
"**Import the packages**",
"_____no_output_____"
]
],
[
[
"import scanpy as sc\nimport pandas as pd\nimport scvelo as scv\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport sklearn\nimport ipywidgets as widgets",
"_____no_output_____"
],
[
"sample_3 = sc.read_h5ad('../../Data/notebooks_data/sample_3.h5ad')",
"_____no_output_____"
]
],
[
[
"We calculate the percentage of mitocondrial genes into each cell. A high percentage denotes the possibility that material from broken cells has been captured during cell isolation, and then sequenced. Mitocondrial percentage is not usually calculated by `scanpy`, because there is need for an identifier for mitocondrial genes, and there is not a standard one. In our case, we look at genes that contain `MT-` into their ID, and calculate their transcript proportion into each cell. We save the result as an observation into `.obs['perc_mito']`",
"_____no_output_____"
]
],
[
[
"MT = ['MT' in i for i in sample_3.var_names]\nperc_mito = np.sum( sample_3[:,MT].X, 1 ) / np.sum( sample_3.X, 1 )\nsample_3.obs['perc_mito'] = perc_mito.copy()",
"_____no_output_____"
]
],
[
[
"## Visualize and evaluate quality measures\n\nWe can do some plots to have a look at quality measures combined together",
"_____no_output_____"
],
[
"**Counts vs Genes:** this is a typical plot, where you look at the total transcripts per cells (x axis) and detected genes per cell (y axis). Usually, those two measures grow together. Points with a lot of transcripts and genes might be multiplets (multiple cells sequenced together as one), while very few transcripts and genes denote the presence of only ambient RNA or very low quality sequencing of a cell. Below, the dots are coloured based on the percentage of mitocondrial transcripts. Note how a high proportion is often on cells with very low transcripts and genes (bottom left corner of the plot)",
"_____no_output_____"
]
],
[
[
"sc.pl.scatter(sample_3, x='total_counts', y='n_genes_by_counts', color='perc_mito', \n title ='Nr of transcripts vs Nr detected genes, coloured by mitocondrial content',\n size=50)",
"_____no_output_____"
]
],
[
[
"**Transcripts and Genes distribution:** Here we simply look at the distribution of transcripts per cells and detected genes per cell. Note how the distribution is bimodal. This usually denotes a cluster of low-quality cells and viable cells. Sometimes filtering out the data points on the left-most modes of those graphs removes a lot of cells from a dataset, but this is quite a normal thing not to be worried about. The right side of the distributions show a tail with few cells having a lot of transcripts and genes. It is also good to filter out some of those extreme values - for technical reasons, it will also help in having a better normalization of the data later on.",
"_____no_output_____"
]
],
[
[
"ax = sns.distplot(sample_3.obs['total_counts'], bins=50)\nax.set_title('Cells Transcripts distribution')",
"_____no_output_____"
],
[
"ax = sns.distplot(sample_3.obs['n_genes_by_counts'], bins=50)\nax.set_title('Distribution of detected genes per cell')",
"_____no_output_____"
]
],
[
[
"**Mitocondrial content**: In this dataset there are few cell with a high percentage of mitocondrial content. Those are precisely 245 if we set 0.1 (that is 10%) as a treshold. A value between 10% and 20% is the usual standard when filtering single cell datasets.",
"_____no_output_____"
]
],
[
[
"#subsetting to see how many cells have percentage of mitocondrial genes above 10%\nsample_3[ sample_3.obs['perc_mito']>0.1, : ].shape",
"_____no_output_____"
],
[
"ax = sns.distplot(sample_3.obs['perc_mito'], bins=50)\nax.set_title('Distribution of mitocondrial content per cell')",
"_____no_output_____"
]
],
[
[
"## Choosing thresholds",
"_____no_output_____"
],
[
"Let's establish some filtering values by looking at the plots above, and then apply filtering",
"_____no_output_____"
]
],
[
[
"MIN_COUNTS = 5000 #minimum number of transcripts per cell\nMAX_COUNTS = 40000 #maximum number of transcripts per cell\nMIN_GENES = 2000 #minimum number of genes per cell\nMAX_GENES = 6000 #maximum number of genes per cell\nMAX_MITO = .1 #mitocondrial percentage treshold)\n \n#plot cells filtered by max transcripts\na=sc.pl.scatter(sample_3[ sample_3.obs['total_counts']<MAX_COUNTS ], \n x='total_counts', y='n_genes_by_counts', color='perc_mito', size=50,\n title =f'Nr of transcripts vs Nr detected genes, coloured by mitocondrial content\\nsubsetting with threshold MAX_COUNTS={MAX_COUNTS}')\n#plot cells filtered by min genes\nb=sc.pl.scatter(sample_3[ sample_3.obs['n_genes_by_counts'] > MIN_GENES ], \n x='total_counts', y='n_genes_by_counts', color='perc_mito', size=50,\n title =f'Nr of transcripts vs Nr detected genes, coloured by mitocondrial content\\nsubsetting with treshold MIN_GENES={MIN_GENES}')\n ",
"_____no_output_____"
]
],
[
[
" \nThe following commands filter using the chosen tresholds. \nAgain, scanpy does not do the mitocondrial QC filtering, \nso we do that on our own by subsetting the data. \nNote for the last two filterings: the parameter `min_cells` remove \nall those cells showing transcripts for only 10 genes or less - \nstandard values for this parameter are usually between 3 and 10, \nand do not come from looking at the QC plots. ",
"_____no_output_____"
]
],
[
[
"sc.preprocessing.filter_cells(sample_3, max_counts=MAX_COUNTS)\n\nsc.preprocessing.filter_cells(sample_3, min_counts=MIN_COUNTS)\n\nsc.preprocessing.filter_cells(sample_3, min_genes=MIN_GENES)\n\nsc.preprocessing.filter_cells(sample_3, max_genes=MAX_GENES)\n\nsc.preprocessing.filter_genes(sample_3, min_cells=10)\n\nsample_3 = sample_3[sample_3.obs['perc_mito']<MAX_MITO].copy()",
"_____no_output_____"
]
],
[
[
"We have been reducing the data quite a lot from the original >8000 cells. Often, even more aggressive filterings are done. For example, one could have set the minimum number of genes detected to 3000. It would have been anyway in the area between the two modes of the QC plot.",
"_____no_output_____"
]
],
[
[
"print(f'Cells after filters: {sample_3.shape[0]}, Genes after filters: {sample_3.shape[1]}')",
"Cells after filters: 2690, Genes after filters: 23454\n"
]
],
[
[
"## Doublet filtering",
"_____no_output_____"
],
[
"Another important step consists in filtering out multiplets. Those are in the almost totality of the cases doublets, because triplets and above multiplets are extremely rare. Read [this more technical blog post](https://liorpachter.wordpress.com/2019/02/07/sub-poisson-loading-for-single-cell-rna-seq/) for more explanations about this.",
"_____no_output_____"
],
[
"The external tool `scrublet` simulates doublets by putting together the transcripts of random pairs of cells from the dataset. Then it assigns a score to each cell in the data, based on the similarity with the simulated doublets. An `expected_doublet_rate` of 0.06 (6%) is quite a typical value for single cell data, but if you have a better estimate from laboratory work, microscope imaging or a specific protocol/sequencing machine, you can also tweak the value. \n`random_state` is a number choosing how the simulations are done. using a specific random state means that you will always simulate the same doublets whenever you run this code. This allows you to reproduce exactly the same results every time and is a great thing for reproducibility in your own research.",
"_____no_output_____"
]
],
[
[
" sc.external.pp.scrublet(sample_3, \n expected_doublet_rate=0.06,\n random_state=12345)",
"Automatically set threshold at doublet score = 0.31\nDetected doublet rate = 1.7%\nEstimated detectable doublet fraction = 55.3%\nOverall doublet rate:\n\tExpected = 6.0%\n\tEstimated = 3.2%\n"
]
],
[
[
"It seems that the doublet rate is likely to be lower than 6%, meaning that in this regard the data has been produced pretty well. We now plot the doublet scores assigned to each cell by the algorithm. We can see that most cells have a low score (the score is a value between 0 and 1). Datasets with many doublets show a more bimodal distribution, while here we just have a light tail beyond 0.1. ",
"_____no_output_____"
]
],
[
[
"sns.distplot(sample_3.obs['doublet_score'])",
"_____no_output_____"
]
],
[
[
"We can choose 0.1 as filtering treshold for the few detected doublets or alternatively use the automatic selection of doublets by the algorithm. We will choose the last option and use the automatically chosen doublets.",
"_____no_output_____"
]
],
[
[
"sample_3 = sample_3[np.invert(sample_3.obs['predicted_doublet'])].copy()",
"_____no_output_____"
]
],
[
[
"## Evaluation of filtering",
"_____no_output_____"
],
[
"A quite basic but easy way to look at the results of our filtering is to normalize and plot the dataset on some projections. Here we use a standard normalization technique that consists of:\n- **TPM normalization**: the transcripts of each cell are normalized, so that their total amounts to the same value in each cell. This should make cells more comparable independently of how many transcripts has been retained during cell isolation.\n- **Logarithmization**: the logarithm of the normalized transcripts is calculated. This reduce the variability of transcripts values and highlights variations due to biological factors.\n- **Standardization**: Each gene is standardized across all cells. This is useful for example for projecting the data onto a PCA. ",
"_____no_output_____"
]
],
[
[
"# TPM normalization and storage of the matrix\nsc.pp.normalize_per_cell(sample_3)\nsample_3.layers['umi_tpm'] = sample_3.X.copy()\n\n# Logarithmization and storage\nsc.pp.log1p(sample_3)\nsample_3.layers['umi_log'] = sample_3.X.copy()\n\n# Select some of the most meaningful genes to calculate the PCA plot later\n# This must be done on logarithmized values\nsc.pp.highly_variable_genes(sample_3, n_top_genes=15000)\n\n# save the dataset\nsample_3.write('../../Data/notebooks_data/sample_3.filt.h5ad')\n\n# standardization and matrix storage\nsc.pp.scale(sample_3)\nsample_3.layers['umi_gauss'] = sample_3.X.copy()",
"_____no_output_____"
]
],
[
[
"Now we calculate the PCA projection",
"_____no_output_____"
]
],
[
[
"sc.preprocessing.pca(sample_3, svd_solver='arpack', random_state=12345)",
"_____no_output_____"
]
],
[
[
"We can look at the PCA plot and color it by some quality measure and gene expression. We can already see how the PCA has a clear structure with only a few dots sparsed around. It seems the filtering has got a good result.",
"_____no_output_____"
]
],
[
[
"sc.pl.pca(sample_3, color=['total_counts','SYCP1'])",
"_____no_output_____"
]
],
[
[
"We plot the variance ratio to see how each component of the PCA changes in variability. Small changes in variability denote that the components are mostly modeling noise in the data. We can choose a threshold (for example 15 PCA components) to be used in all algorithms that use PCA to calculate any quantity.",
"_____no_output_____"
]
],
[
[
"sc.plotting.pca_variance_ratio(sample_3)",
"_____no_output_____"
]
],
[
[
"We project the data using the UMAP algorithm. This is very good in preserving the structure of a dataset in low dimension, if any is present. We first calculate the neighbors of each cell (that is, its most similar cells), those are then used for the UMAP. The neighbors are calculated using the PCA matrix instead of the full data matrix, so we can choose the number of PCA components to use (parameter `n_pcs`). Many algorithms work on the PCA, so you will see the parameter used again in other places.",
"_____no_output_____"
]
],
[
[
"sc.pp.neighbors(sample_3, n_pcs=15, random_state=12345)",
"_____no_output_____"
],
[
"sc.tools.umap(sample_3, random_state=54321)",
"_____no_output_____"
]
],
[
[
"The UMAP plot gives a pretty well-structured output for this dataset. We will keep working further with this filtering.",
"_____no_output_____"
]
],
[
[
"sc.plotting.umap(sample_3, color=['total_counts','SYCP1'])",
"_____no_output_____"
]
],
[
[
"-------------------------------",
"_____no_output_____"
],
[
"## Wrapping up",
"_____no_output_____"
],
[
"The second human testis dataset is now filtered and you can proceed to the normalize and integration part of the analysis (Notebook `Part03_normalize_and_integrate`).",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cbd45af5325249a3809372dcc1b57e27a56a2070
| 653,745 |
ipynb
|
Jupyter Notebook
|
notebook/carbon_emission.ipynb
|
microsoft/Carbon-Insight
|
4cfd95809f0916a628a60de16f9487a6ec70fc7c
|
[
"MIT"
] | 6 |
2022-01-06T07:43:02.000Z
|
2022-03-16T19:14:46.000Z
|
notebook/carbon_emission.ipynb
|
microsoft/Carbon-Insight
|
4cfd95809f0916a628a60de16f9487a6ec70fc7c
|
[
"MIT"
] | null | null | null |
notebook/carbon_emission.ipynb
|
microsoft/Carbon-Insight
|
4cfd95809f0916a628a60de16f9487a6ec70fc7c
|
[
"MIT"
] | 1 |
2022-03-22T15:38:42.000Z
|
2022-03-22T15:38:42.000Z
| 378.105842 | 174,930 | 0.920221 |
[
[
[
"Carbon Insight: Carbon Emissions Visualization\n==============================================\n\nThis tutorial aims to showcase how to visualize anthropogenic CO2 emissions with a near-global coverage and track correlations between global carbon emissions and socioeconomic factors such as COVID-19 and GDP.",
"_____no_output_____"
]
],
[
[
"# Requirements\n%pip install numpy\n%pip install pandas\n%pip install matplotlib\n",
"_____no_output_____"
]
],
[
[
"# A. Process Carbon Emission Data\n\nThis notebook helps you to process and visualize carbon emission data provided by [Carbon-Monitor](https://carbonmonitor.org/), which records human-caused carbon emissions from different countries, sources, and timeframes that are of interest to you.\n\nOverview:\n- [Process carbon emission data](#a1)\n - [Download data from Carbon Monitor](#a11)\n - [Calculate the rate of change](#a12)\n - [Expand country regions](#a13)\n- [Visualize carbon emission data](#a2)\n - [Observe carbon emission data from the perspective of time](#a21)\n - [Compare carbon emission data of different sectors](#a22)\n- [Examples](#a3)\n - [World carbon emission data](#a31)\n - [US carbon emission data](#a32)",
"_____no_output_____"
]
],
[
[
"import io\nfrom urllib.request import urlopen\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import register_matplotlib_converters\n\nregister_matplotlib_converters()\n",
"_____no_output_____"
],
[
"import os\n\n# Optional Function: Export Data\ndef export_data(file_name: str, df: pd.DataFrame):\n # df = country_region_name_to_code(df)\n export_path = os.path.join('export_data', file_name)\n print(f'Export Data to {export_path}')\n if not os.path.exists('export_data'):\n os.mkdir('export_data')\n with open(export_path, 'w', encoding='utf-8') as f:\n f.write(df.to_csv(index=None, line_terminator='\\n', encoding='utf-8'))\n",
"_____no_output_____"
]
],
[
[
"## <a id=\"a1\"></a> 1. Process Data",
"_____no_output_____"
],
[
"### <a id=\"a11\"></a> 1.1. Download data from Carbon Monitor\nWe are going to download tabular carbon emission data and convert to Pandas Dataframe.\n\nSupported data types:\n\n- ```carbon_global``` includes carbon emission data of 11 countries and regions worldwide.\n- ```carbon_us``` includes carbon emission data of 51 states of the United States.\n- ```carbon_eu``` includes carbon emission data of 27 countries of the European Union.\n- ```carbon_china``` includes carbon emission data of 31 cities and provinces of China.",
"_____no_output_____"
]
],
[
[
"def get_data_from_carbon_monitor(data_type='carbon_global'):\n assert data_type in ['carbon_global', 'carbon_us', 'carbon_eu', 'carbon_china']\n data_url = f'https://datas.carbonmonitor.org/API/downloadFullDataset.php?source={data_type}'\n data = urlopen(data_url).read().decode('utf-8-sig')\n df = pd.read_csv(io.StringIO(data))\n df = df.drop(columns=['timestamp'])\n df = df.loc[pd.notna(df['date'])]\n df = df.rename(columns={'country': 'country_region'})\n df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y')\n if data_type == 'carbon_us':\n df = df.loc[df['state'] != 'United States']\n return df",
"_____no_output_____"
]
],
[
[
"### <a id=\"a12\"></a> 1.2. Calculate the rate of change\nThe rate of change $\\Delta(s, r, t)$ is defined as the ratio of current value and moving average of a certain window size:\n$$\\begin{aligned}\n\\Delta(s, r, t) = \\left\\{\\begin{aligned}\n&\\frac{TX(s, r, t)}{\\sum_{\\tau=t-T}^{t-1}X(\\tau)}, &t\\geq T\\\\\n&1, &0<t<T\n\\end{aligned}\\right.\n\\end{aligned}$$\nWhere $X(s, r, t)$ is the carbon emission value of sector $s$, region $r$ and date $t$; $T$ is the window size with default value $T=14$.",
"_____no_output_____"
]
],
[
[
"def calculate_rate_of_change(df, window_size=14):\n region_scope = 'state' if 'state' in df.columns else 'country_region'\n new_df = pd.DataFrame()\n for sector in set(df['sector']):\n sector_mask = df['sector'] == sector\n for region, values in df.loc[sector_mask].pivot(index='date', columns=region_scope, values='value').items():\n values.fillna(0)\n rates = values / values.rolling(window_size).mean()\n rates.fillna(value=1, inplace=True)\n tmp_df = pd.DataFrame(\n index=values.index,\n columns=['value', 'rate_of_change'],\n data=np.array([values.to_numpy(), rates.to_numpy()]).T\n )\n tmp_df['sector'] = sector\n tmp_df[region_scope] = region\n new_df = new_df.append(tmp_df.reset_index())\n return new_df",
"_____no_output_____"
]
],
[
[
"### <a id=\"a13\"></a> 1.3. Expand country regions\n*Note: This step applies only to the ```carbon_global``` dataset.*\n\nThe dataset ```carbon_global``` does not list all the countries/regions in the world. Instead, there are two groups which contains multiple countries/regions: ```ROW``` (i.e. the rest of the world) and ```EU27 & UK```.\n\nIn order to obtain the carbon emission data of countries/regions in these two groups, we can refer to [the EDGAR dataset](https://edgar.jrc.ec.europa.eu/dataset_ghg60) and use [the table of CO2 emissions of all world countries in 2019](./static_data/Baseline.csv) as the baseline.\n\nAssume the the carbon emission of each non-listed country/region is linearly related to the carbon emission of the group it belongs to, we have:\n$$\\begin{aligned}\nX(s, r, t) &= \\frac{\\sum_{r_i\\in R(r)}X(s, r_i, t)}{\\sum_{r_i\\in R(r)}X(s, r_i, t_0)}X(s, r, t_0)\\\\\n&= \\frac{X_{Raw}(s, R(r), t)}{\\sum_{r_i\\in R(r)}X_{Baseline}(s, r_i)}X_{Baseline}(s, r)\n\\end{aligned}$$\nWhere\n- $X(s, r, t)$ is the carbon emission value of sector $s$, country/region $r$ and date $t$.\n- $t_0$ is the date of the baseline table.\n- $R(r)$ is the group that contains country/region $r$.\n- $X_{Raw}(s, R, t)$ is the carbon emission value of sector $s$, country/region group $R$ and date $t$ in the ```carbon_global``` dataset.\n- $X_{Baseline}(s, r)$ is the carbon emission value of sector $s$ and country/region $r$ in the baseline table.\n\nNote that the baseline table does not contain the ```International Aviation``` sector. Therefore, the data for ```International Aviation``` is only available to countries listed in the ```carbon_global``` dataset. When we expand the ```ROW``` and the ```EU27 & UK``` groups to other countries/regions of the world, only the other five sectors are considered.",
"_____no_output_____"
]
],
[
[
"def expand_country_regions(df):\n\n sectors = set(df['sector'])\n assert 'country_region' in df.columns\n df = df.replace('US', 'United States')\n df = df.replace('UK', 'United Kingdom')\n original_country_regions = set(df['country_region'])\n\n country_region_df = pd.read_csv('static_data/CountryRegion.csv')\n base = {}\n name_to_code = {}\n for _, (name, code, source) in country_region_df.loc[:, ['Name', 'Code', 'DataSource']].iterrows():\n if source.startswith('Simulated') and name not in original_country_regions:\n name_to_code[name] = code\n base[code] = 'ROW' if source.endswith('ROW') else 'EU27 & UK'\n\n baseline = pd.read_csv('static_data/Baseline.csv')\n baseline = baseline.set_index('CountryRegionCode')\n baseline = baseline.loc[:, [sector for sector in baseline.columns if sector in sectors]]\n group_baseline = {}\n for group in original_country_regions & set(['ROW', 'EU27 & UK']):\n group_baseline[group] = baseline.loc[[code for code, base_group in base.items() if base_group == group], :].sum()\n\n new_df = pd.DataFrame()\n sector_masks = {sector: df['sector'] == sector for sector in sectors}\n for country_region in set(country_region_df['Name']):\n if country_region in name_to_code:\n code = name_to_code[country_region]\n group = base[code]\n group_mask = df['country_region'] == group\n for sector, sum_value in group_baseline[group].items():\n tmp_df = df.loc[sector_masks[sector] & group_mask, :].copy()\n tmp_df['value'] = tmp_df['value'] / sum_value * baseline.loc[code, sector]\n tmp_df['country_region'] = country_region\n new_df = new_df.append(tmp_df)\n elif country_region in original_country_regions:\n new_df = new_df.append(df.loc[df['country_region'] == country_region])\n\n return new_df\n",
"_____no_output_____"
]
],
[
[
"## 2. <a id=\"a2\"></a> Visualize Data\nThis is a auxiliary module for displaying data, which can be modified arbitrarily.",
"_____no_output_____"
],
[
"### <a id=\"a21\"></a> 2.1. Plot by date\nIn this part we are going to create a line chart, where the emission value and rate of change for given counties during the given time can be browsed.",
"_____no_output_____"
]
],
[
[
"def plot_by_date(df, start_date=None, end_date=None, sector=None, regions=None, title='Carbon Emission by Date'):\n if start_date is None:\n start_date = df['date'].min()\n if end_date is None:\n end_date = df['date'].max()\n tmp_df = df.loc[(df['date'] >= start_date) & (df['date'] <= end_date)]\n\n region_scope = 'state' if 'state' in tmp_df.columns else 'country_region'\n if regions is None or type(regions) == int:\n region_list = list(set(tmp_df[region_scope]))\n sector_mask = True if sector is None else tmp_df['sector'] == sector\n region_list.sort(key=lambda region: -tmp_df.loc[(tmp_df[region_scope] == region) & sector_mask, 'value'].sum())\n regions = region_list[:3 if regions is None else regions]\n tmp_df = pd.concat([tmp_df.loc[tmp_df[region_scope] == region] for region in regions])\n\n if sector not in set(tmp_df['sector']):\n tmp_df['rate_of_change'] = tmp_df['value'] / tmp_df['rate_of_change']\n tmp_df = tmp_df.groupby(['date', region_scope]).sum().reset_index()\n value_df = tmp_df.pivot(index='date', columns=region_scope, values='value')\n rate_df = tmp_df.pivot(index='date', columns=region_scope, values='rate_of_change')\n rate_df = value_df / rate_df\n else:\n tmp_df = tmp_df.loc[tmp_df['sector'] == sector, [region_scope, 'date', 'value', 'rate_of_change']]\n value_df = tmp_df.pivot(index='date', columns=region_scope, values='value')\n rate_df = tmp_df.pivot(index='date', columns=region_scope, values='rate_of_change')\n value_df = value_df.loc[:, regions]\n rate_df = rate_df.loc[:, regions]\n\n fig = plt.figure(figsize=(10, 8))\n fig.suptitle(title)\n\n plt.subplot(2, 1, 1)\n plt.plot(value_df)\n plt.ylabel('Carbon Emission Value / Mt CO2')\n plt.xticks(rotation=60)\n plt.legend(regions, loc='upper right')\n\n plt.subplot(2, 1, 2)\n plt.plot(rate_df)\n plt.ylabel('Rate of Change')\n plt.xticks(rotation=60)\n plt.legend(regions, loc='upper right')\n\n plt.subplots_adjust(hspace=0.3)\n",
"_____no_output_____"
]
],
[
[
"### <a id=\"a22\"></a> 2.2. Plot by sector\nGenerally, sources of emissions can be divided into five or six categories:\n- Domestic Aviation\n- Ground Transport\n- Industry\n- Power \n- Residential\n- International Aviation\n\nWhere the data of ```International Aviation``` are only available to ```carbon_global``` and ```carbon_us``` datasets. For ```carbon_global``` dataset, we can not expand the data for International Aviation of non-listed countries.\n\nLet's create a pie chart and a stacked column chart, where you can focus on details of specific countiy/regions’ emission data, including quantity and percentage breakdown by above sectors. ",
"_____no_output_____"
]
],
[
[
"def plot_by_sector(df, start_date=None, end_date=None, sectors=None, region=None, title='Carbon Emission Data by Sector'):\n if start_date is None:\n start_date = df['date'].min()\n if end_date is None:\n end_date = df['date'].max()\n tmp_df = df.loc[(df['date'] >= start_date) & (df['date'] <= end_date)]\n\n region_scope = 'state' if 'state' in df.columns else 'country_region'\n if region in set(tmp_df[region_scope]):\n tmp_df = tmp_df.loc[tmp_df[region_scope] == region]\n\n if sectors is None:\n sectors = list(set(tmp_df['sector']))\n sectors.sort(key=lambda sector: -tmp_df.loc[tmp_df['sector'] == sector, 'value'].sum())\n tmp_df = tmp_df.loc[[sector in sectors for sector in tmp_df['sector']]]\n\n fig = plt.figure(figsize=(10, 8))\n fig.suptitle(title)\n\n plt.subplot(2, 1, 1)\n data = np.array([tmp_df.loc[tmp_df['sector'] == sector, 'value'].sum() for sector in sectors])\n total = tmp_df['value'].sum()\n bbox_props = dict(boxstyle=\"square,pad=0.3\", fc=\"w\", ec=\"k\", lw=0.72)\n kw = dict(arrowprops=dict(arrowstyle=\"-\"),\n bbox=bbox_props, zorder=0, va=\"center\")\n wedges, texts = plt.pie(data, wedgeprops=dict(width=0.5), startangle=90)\n for i, p in enumerate(wedges):\n factor = data[i] / total * 100\n if factor > 5:\n ang = (p.theta2 - p.theta1)/2. + p.theta1\n y = np.sin(np.deg2rad(ang))\n x = np.cos(np.deg2rad(ang))\n horizontalalignment = {-1: \"right\", 1: \"left\"}[int(np.sign(x))]\n connectionstyle = \"angle,angleA=0,angleB={}\".format(ang)\n kw[\"arrowprops\"].update({\"connectionstyle\": connectionstyle})\n text = '{}\\n{:.1f} Mt CO2 ({:.1f}%)'.format(sectors[i], data[i], factor)\n plt.annotate(\n text,\n xy=(x, y),\n xytext=(1.35 * np.sign(x), 1.4 * y),\n horizontalalignment=horizontalalignment,\n **kw\n )\n plt.axis('equal')\n\n plt.subplot(2, 1, 2)\n labels = []\n data = [[] for _ in sectors]\n date = pd.to_datetime(start_date)\n delta = pd.DateOffset(months=1)\n while date <= pd.to_datetime(end_date):\n sub_df = tmp_df.loc[(tmp_df['date'] >= date) & (tmp_df['date'] < date + delta)]\n for i, sector in enumerate(sectors):\n data[i].append(sub_df.loc[sub_df['sector'] == sector, 'value'].sum())\n labels.append(date.strftime('%Y-%m'))\n date += delta\n data = np.array(data)\n for i, sector in enumerate(sectors):\n plt.bar(labels, data[i], bottom=data[:i].sum(axis=0), label=sector)\n plt.xticks(rotation=60)\n plt.legend()\n",
"_____no_output_____"
]
],
[
[
"## <a id=\"a3\"></a> 3. Examples",
"_____no_output_____"
],
[
"### <a id=\"a31\"></a> 3.1. World carbon emission data",
"_____no_output_____"
]
],
[
[
"data_type = 'carbon_global'\nprint(f'Download {data_type} data')\nglobal_df = get_data_from_carbon_monitor(data_type)\nprint('Calculate rate of change')\nglobal_df = calculate_rate_of_change(global_df)\nprint('Expand country / regions')\nglobal_df = expand_country_regions(global_df)\n\nexport_data('global_carbon_emission_data.csv', global_df)\nglobal_df",
"Download carbon_global data\nCalculate rate of change\nExpand country / regions\nExport Data to export_data\\global_carbon_emission_data.csv\n"
],
[
"plot_by_date(\n global_df,\n start_date='2019-01-01',\n end_date='2020-12-31',\n sector='Residential',\n regions=['China', 'United States'],\n title='Residential Carbon Emission, China v.s. United States, 2019-2020'\n)",
"_____no_output_____"
],
[
"plot_by_sector(\n global_df,\n start_date='2019-01-01',\n end_date='2020-12-31',\n sectors=None,\n region=None,\n title='World Carbon Emission by Sectors, 2019-2020',\n)",
"_____no_output_____"
]
],
[
[
"### <a id=\"a32\"></a> 3.2. US carbon emission data",
"_____no_output_____"
]
],
[
[
"data_type = 'carbon_us'\nprint(f'Download {data_type} data')\nus_df = get_data_from_carbon_monitor(data_type)\nprint('Calculate rate of change')\nus_df = calculate_rate_of_change(us_df)\nexport_data('us_carbon_emission_data.csv', us_df)\nus_df",
"Download carbon_us data\nCalculate rate of change\nExport Data to export_data\\us_carbon_emission_data.csv\n"
],
[
"plot_by_date(\n us_df,\n start_date='2019-01-01',\n end_date='2020-12-31',\n sector=None,\n regions=3,\n title='US Carbon Emission, Top 3 States, 2019-2020'\n)\n",
"_____no_output_____"
],
[
"plot_by_sector(\n us_df,\n start_date='2019-01-01',\n end_date='2020-12-31',\n sectors = None,\n region='California',\n title='California Carbon Emission by Sectors, 2019-2020',\n)",
"_____no_output_____"
]
],
[
[
"# B. Co-Analysis of Carbon Emission Data v.s. COVID-19 Data\n\nThis section will help you to visualize the relativity between carbon emissions in different countries and the trends of the COVID-19 pandemic since January 2020 provided by [Oxford COVID-19 Government Response Tracker](https://covidtracker.bsg.ox.ac.uk/). The severity of the epidemic can be shown in three aspects: the number of new diagnoses, the number of deaths and the stringency and policy indices of governments.\n\nOverview:\n- [Download data from Oxford COVID-19 Government Response Tracker](#b1)\n- [Visualize COVID-19 data and carbon emission data](#b2)\n- [Example: COVID-19 cases and stringency index v.s. carbon emission in US](#b3)",
"_____no_output_____"
]
],
[
[
"import json\nimport datetime\nfrom urllib.request import urlopen",
"_____no_output_____"
]
],
[
[
"## 1. <a id=\"b1\"></a> Download COVID-19 Data\n\nWe are going to download JSON-formatted COVID-19 data and convert to Pandas Dataframe. The Oxford COVID-19 Government Response Tracker dataset provides confirmed cases, deaths and stringency index data for all countries/regions since January 2020.\n\n- The ```confirmed``` measurement records the total number of confirmed COVID-19 cases since January 2020. We will convert it into incremental data.\n- The ```deaths``` measurement records the total number of patients who died due to infection with COVID-19 since January 2020. We will convert it into incremental data.\n- The ```stringency``` measurement means the Stringency Index, which is a float number from 0 to 100 that reflects how strict a country’s measures were, including lockdown, school closures, travel bans, etc. A higher score indicates a stricter response (i.e. 100 = strictest response). \n",
"_____no_output_____"
]
],
[
[
"def get_covid_data_from_oxford_covid_tracker(data_type='carbon_global'):\n data = json.loads(urlopen(\"https://covidtrackerapi.bsg.ox.ac.uk/api/v2/stringency/date-range/{}/{}\".format(\n \"2020-01-22\",\n datetime.datetime.now().strftime(\"%Y-%m-%d\")\n )).read().decode('utf-8-sig'))\n country_region_df = pd.read_csv('static_data/CountryRegion.csv')\n code_to_name = {code: name for _, (name, code) in country_region_df.loc[:, ['Name', 'Code']].iterrows()}\n last_df = 0\n df = pd.DataFrame()\n for date in sorted(data['data'].keys()):\n sum_df = pd.DataFrame({name: data['data'][date][code] for code, name in code_to_name.items() if code in data['data'][date]})\n sum_df = sum_df.T[['confirmed', 'deaths', 'stringency']].fillna(last_df).astype(np.float32)\n tmp_df = sum_df - last_df\n last_df = sum_df[['confirmed', 'deaths']]\n last_df['stringency'] = 0\n tmp_df = tmp_df.reset_index().rename(columns={'index': 'country_region'})\n tmp_df['date'] = pd.to_datetime(date)\n df = df.append(tmp_df)\n return df\n",
"_____no_output_____"
]
],
[
[
"## <a id=\"b2\"></a> 2. Visualize COVID-19 Data and Carbon Emission Data\n\nThis part will guide you to create a line-column chart, where you can view the specified COVID-19 measurement (```confirmed```, ```deaths``` or ```stringency```) and carbon emissions in the specified country/region throughout time. ",
"_____no_output_____"
]
],
[
[
"def plot_covid_data_vs_carbon_emission_data(\n covid_df, carbon_df, start_date=None, end_date=None,\n country_region=None, sector=None, covid_measurement='confirmed',\n title='Carbon Emission v.s. COVID-19 Confirmed Cases'\n):\n if start_date is None:\n start_date = max(covid_df['date'].min(), carbon_df['date'].min())\n if end_date is None:\n end_date = min(covid_df['date'].max(), carbon_df['date'].max())\n x = pd.to_datetime(start_date)\n dates = [x]\n while x <= pd.to_datetime(end_date):\n x = x.replace(year=x.year+1, month=1) if x.month == 12 else x.replace(month=x.month+1)\n dates.append(x)\n dates = [f'{x.year}-{x.month}' for x in dates]\n\n plt.figure(figsize=(10, 6))\n plt.title(title)\n plt.xticks(rotation=60)\n\n if sector in set(carbon_df['sector']):\n carbon_df = carbon_df[carbon_df['sector'] == sector]\n else:\n sector = 'All Sectors'\n if 'country_region' not in carbon_df.columns:\n raise ValueError('The carbon emission data need to be disaggregated by countries/regions.')\n if country_region in set(carbon_df['country_region']):\n carbon_df = carbon_df.loc[carbon_df['country_region'] == country_region]\n else:\n country_region = 'World'\n carbon_df = carbon_df[['date', 'value']]\n carbon_df = carbon_df.loc[(carbon_df['date'] >= f'{dates[0]}-01') & (carbon_df['date'] < f'{dates[-1]}-01')].set_index('date')\n carbon_df = carbon_df.groupby(carbon_df.index.year * 12 + carbon_df.index.month).sum()\n plt.bar(dates[:-1], carbon_df['value'], color='C1')\n plt.ylim(0)\n plt.legend([f'{country_region} {sector}\\nCarbon Emission / Mt CO2'], loc='upper left')\n\n plt.twinx()\n if country_region in set(covid_df['country_region']):\n covid_df = covid_df.loc[covid_df['country_region'] == country_region]\n covid_df = covid_df[['date', covid_measurement]]\n covid_df = covid_df.loc[(covid_df['date'] >= f'{dates[0]}-01') & (covid_df['date'] < f'{dates[-1]}-01')].set_index('date')\n covid_df = covid_df.groupby(covid_df.index.year * 12 + covid_df.index.month)\n covid_df = covid_df.mean() if covid_measurement == 'stringency' else covid_df.sum()\n plt.plot(dates[:-1], covid_df[covid_measurement])\n plt.ylim(0, 100 if covid_measurement == 'stringency' else None)\n plt.legend([f'COVID-19\\n{covid_measurement}'], loc='upper right')\n",
"_____no_output_____"
]
],
[
[
"## <a id=\"b3\"></a> 3. Examples",
"_____no_output_____"
]
],
[
[
"print(f'Download COVID-19 data')\ncovid_df = get_covid_data_from_oxford_covid_tracker(data_type)\nexport_data('covid_data.csv', covid_df)\ncovid_df",
"Download COVID-19 data\nExport Data to export_data\\covid_data.csv\n"
],
[
"plot_covid_data_vs_carbon_emission_data(\n covid_df,\n global_df,\n start_date=None,\n end_date=None,\n country_region='United States',\n sector=None,\n covid_measurement='confirmed',\n title = 'US Carbon Emission v.s. COVID-19 Confirmed Cases'\n)",
"_____no_output_____"
],
[
"plot_covid_data_vs_carbon_emission_data(\n covid_df,\n global_df,\n start_date=None,\n end_date=None,\n country_region='United States',\n sector=None,\n covid_measurement='stringency',\n title = 'US Carbon Emission v.s. COVID-19 Stringency Index'\n)",
"_____no_output_____"
]
],
[
[
"# C. Co-Analysis of Historical Carbon Emission Data v.s. Population & GDP Data\n\nThis section illustrates how to compare carbon intensity and per capita emissions of different countries/regions. Refer to [the EDGAR dataset](https://edgar.jrc.ec.europa.eu/dataset_ghg60) and [World Bank Open Data](https://data.worldbank.org/), carbon emissions, population and GDP data of countries/regions in the world from 1970 to 2018 are available. \n\nOverview:\n- [Process carbon emission & social economy data](#c1)\n - [Download data from EDGAR](#c11)\n - [Download data from World Bank](#c12)\n - [Merge datasets](#c13)\n- [Visualize carbon emission & social economy data](#c2)\n - [See how per capita emissions change over time in different countries/regions](#c21)\n - [Observe how *carbon intensity* reduced over time](#c22)\n- [Example: relationships of carbon emission and social economy in huge countries](#c3)\n\n*Carbon intensity* is the measure of CO2 produced per US dollar GDP. In other words, it’s a measure of how much CO2 we emit when we generate one dollar of domestic economy. A rapidly decreasing carbon intensity is beneficial for the environment and economy.",
"_____no_output_____"
]
],
[
[
"import zipfile\n",
"_____no_output_____"
]
],
[
[
"## <a id=\"c1\"></a> 1. Process Carbon Emission & Social Economy Data",
"_____no_output_____"
],
[
"### <a id=\"c11\"></a> 1.1. Download 1970-2018 yearly carbon emission data from the EDGAR dataset",
"_____no_output_____"
]
],
[
[
"def get_historical_carbon_emission_data_from_edgar():\n if not os.path.exists('download_data'):\n os.mkdir('download_data')\n site = 'https://cidportal.jrc.ec.europa.eu/ftp/jrc-opendata/EDGAR/datasets'\n dataset = 'v60_GHG/CO2_excl_short-cycle_org_C/v60_GHG_CO2_excl_short-cycle_org_C_1970_2018.zip'\n with open('download_data/historical_carbon_emission.zip', 'wb') as f:\n f.write(urlopen(f'{site}/{dataset}').read())\n with zipfile.ZipFile('download_data/historical_carbon_emission.zip', 'r') as zip_ref:\n zip_ref.extractall('download_data/historical_carbon_emission')\n hist_carbon_df = pd.read_excel(\n 'download_data/historical_carbon_emission/v60_CO2_excl_short-cycle_org_C_1970_2018.xls',\n sheet_name='TOTALS BY COUNTRY',\n index_col=2,\n header=9,\n ).iloc[:, 4:]\n hist_carbon_df.columns = hist_carbon_df.columns.map(lambda x: pd.to_datetime(f'{x[-4:]}-01-01'))\n hist_carbon_df.index = hist_carbon_df.index.rename('country_region')\n hist_carbon_df *= 1000\n return hist_carbon_df\n",
"_____no_output_____"
]
],
[
[
"### <a id=\"c12\"></a> 1.2. Download 1960-pressent yearly population and GDP data from World Bank",
"_____no_output_____"
]
],
[
[
"def read_worldbank_data(data_id):\n tmp_df = pd.read_excel(\n f'https://api.worldbank.org/v2/en/indicator/{data_id}?downloadformat=excel',\n sheet_name='Data',\n index_col=1,\n header=3,\n ).iloc[:, 3:]\n tmp_df.columns = tmp_df.columns.map(lambda x: pd.to_datetime(x, format='%Y'))\n tmp_df.index = tmp_df.index.rename('country_region')\n return tmp_df\n\ndef get_population_and_gdp_data_from_worldbank():\n return read_worldbank_data('SP.POP.TOTL'), read_worldbank_data('NY.GDP.MKTP.CD')\n",
"_____no_output_____"
]
],
[
[
"### <a id=\"c13\"></a> 1.3. Merge the three datasets",
"_____no_output_____"
]
],
[
[
"def melt_table_by_years(df, value_name, country_region_codes, code_to_name, years):\n return df.loc[country_region_codes, years].rename(index=code_to_name).reset_index().melt(\n id_vars=['country_region'],\n value_vars=years,\n var_name='date',\n value_name=value_name\n )\n\ndef merge_historical_data(hist_carbon_df, pop_df, gdp_df):\n country_region_df = pd.read_csv('static_data/CountryRegion.csv')\n code_to_name = {code: name for _, (name, code) in country_region_df.loc[:, ['Name', 'Code']].iterrows()}\n country_region_codes = sorted(set(pop_df.index) & set(gdp_df.index) & set(hist_carbon_df.index) & set(code_to_name.keys()))\n years = sorted(set(pop_df.columns) & set(gdp_df.columns) & set(hist_carbon_df.columns))\n pop_df = melt_table_by_years(pop_df, 'population', country_region_codes, code_to_name, years)\n gdp_df = melt_table_by_years(gdp_df, 'gdp', country_region_codes, code_to_name, years)\n hist_carbon_df = melt_table_by_years(hist_carbon_df, 'carbon_emission', country_region_codes, code_to_name, years)\n hist_carbon_df['population'] = pop_df['population']\n hist_carbon_df['gdp'] = gdp_df['gdp']\n return hist_carbon_df.fillna(0)",
"_____no_output_____"
]
],
[
[
"## <a id=\"c2\"></a> 2. Visualize Carbon Emission & Social Economy Data",
"_____no_output_____"
],
[
"## <a id=\"c21\"></a> 2.1. Plot changes in per capita emissions\nWe now will walk you through how to plot a bubble chart of per capita GDP and per capita emissions of different countries/regions for a given year. ",
"_____no_output_____"
]
],
[
[
"def plot_carbon_emission_data_vs_gdp(df, year=None, countries_regions=None, title='Carbon Emission per Capita v.s. GDP per Capita'):\n if year is None:\n date = df['date'].max()\n else:\n date = min(max(pd.to_datetime(year, format='%Y'), df['date'].min()), df['date'].max())\n df = df[df['date'] == date]\n\n if countries_regions is None or type(countries_regions) == int:\n country_region_list = list(set(df['country_region']))\n country_region_list.sort(key=lambda country_region: -df.loc[df['country_region'] == country_region, 'population'].to_numpy())\n countries_regions = country_region_list[:10 if countries_regions is None else countries_regions]\n\n plt.figure(figsize=(10, 6))\n plt.title(title)\n max_pop = df['population'].max()\n for country_region in countries_regions:\n row = df.loc[df['country_region'] == country_region]\n plt.scatter(\n x=row['gdp'] / row['population'],\n y=row['carbon_emission'] / row['population'],\n s=row['population'] / max_pop * 1000,\n )\n for lgnd in plt.legend(countries_regions).legendHandles:\n lgnd._sizes = [50]\n plt.xlabel('GDP per Capita (USD)')\n plt.ylabel('Carbon Emission per Capita (tCO2)')\n",
"_____no_output_____"
]
],
[
[
"## <a id=\"c22\"></a> 2.2. Plot changes in carbon intensity\nTo see changes in Carbon Intensity of different countries overtime, let’s plot a line chart.",
"_____no_output_____"
]
],
[
[
"def plot_carbon_indensity_data(df, start_year=None, end_year=None, countries_regions=None, title='Carbon Indensity'):\n start_date = df['date'].min() if start_year is None else pd.to_datetime(start_year, format='%Y')\n end_date = df['date'].max() if end_year is None else pd.to_datetime(end_year, format='%Y')\n df = df[(df['date'] >= start_date) & (df['date'] <= end_date)]\n\n if countries_regions is None or type(countries_regions) == int:\n country_region_list = list(set(df['country_region']))\n country_region_list.sort(key=lambda country_region: -df.loc[df['country_region'] == country_region, 'population'].sum())\n countries_regions = country_region_list[:3 if countries_regions is None else countries_regions]\n df = pd.concat([df[df['country_region'] == country_region] for country_region in countries_regions])\n df['carbon_indensity'] = df['carbon_emission'] / df['gdp']\n indensity_df = df.pivot(index='date', columns='country_region', values='carbon_indensity')[countries_regions]\n emission_df = df.pivot(index='date', columns='country_region', values='carbon_emission')[countries_regions]\n\n plt.figure(figsize=(10, 8))\n plt.subplot(211)\n plt.title(title)\n plt.plot(indensity_df)\n plt.legend(countries_regions)\n plt.ylabel('Carbon Emission (tCO2) per Dollar GDP')\n plt.subplot(212)\n plt.plot(emission_df)\n plt.legend(countries_regions)\n plt.ylabel('Carbon Emission (tCO2)')\n",
"_____no_output_____"
]
],
[
[
"## <a id=\"c3\"></a> 3. Examples",
"_____no_output_____"
]
],
[
[
"print('Download historical carbon emission data')\nhist_carbon_df = get_historical_carbon_emission_data_from_edgar()\nprint('Download population & GDP data')\npop_df, gdp_df = get_population_and_gdp_data_from_worldbank()\nprint('Merge data')\nhist_carbon_df = merge_historical_data(hist_carbon_df, pop_df, gdp_df)\nexport_data('historical_carbon_emission_data.csv', hist_carbon_df)\nhist_carbon_df",
"Download historical carbon emission data\nDownload population & GDP data\nMerge data\nExport Data to export_data\\historical_carbon_emission_data.csv\n"
],
[
"plot_carbon_emission_data_vs_gdp(\n hist_carbon_df,\n year=2018,\n countries_regions=10,\n title = 'Carbon Emission per Capita v.s. GDP per Capita, Top 10 Populous Countries/Regions, 2018'\n)",
"_____no_output_____"
],
[
"plot_carbon_indensity_data(\n hist_carbon_df,\n start_year=None,\n end_year=None,\n countries_regions=['United States', 'China'],\n title='Carbon Indensity & Carbon Emission, US v.s. China, 1970-2018'\n)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbd461799e771eadf45305fe4b20dcd9399106fb
| 3,487 |
ipynb
|
Jupyter Notebook
|
notebooks/train_classifier_plot.ipynb
|
bittremieux/drugs_epidermis
|
4dd5d4dd2c21cb3cce545c6b8ace0ca60f0892c2
|
[
"BSD-3-Clause"
] | 1 |
2020-12-10T19:43:47.000Z
|
2020-12-10T19:43:47.000Z
|
notebooks/train_classifier_plot.ipynb
|
bittremieux/drugs_epidermis
|
4dd5d4dd2c21cb3cce545c6b8ace0ca60f0892c2
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/train_classifier_plot.ipynb
|
bittremieux/drugs_epidermis
|
4dd5d4dd2c21cb3cce545c6b8ace0ca60f0892c2
|
[
"BSD-3-Clause"
] | null | null | null | 30.858407 | 86 | 0.537138 |
[
[
[
"import joblib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns",
"_____no_output_____"
],
[
"# Plot styling.\nplt.style.use(['seaborn-white', 'seaborn-paper'])\nplt.rc('font', family='sans-serif')\nsns.set_palette(['#6da7de', '#9e0059', '#dee000', '#d82222', '#5ea15d',\n '#943fa6', '#63c5b5', '#ff38ba', '#eb861e', '#ee266d'])\nsns.set_context('paper', font_scale=1.3)",
"_____no_output_____"
],
[
"rf_stats, *_ = joblib.load('../data/processed/train_classifier_rf.joblib')\nlr_stats, *_ = joblib.load('../data/processed/train_classifier_lr.joblib')\nsvm_stats, *_ = joblib.load('../data/processed/train_classifier_svm.joblib')",
"_____no_output_____"
],
[
"width = 7\nheight = width / 1.618 # Golden ratio.\nfig, ax = plt.subplots(figsize=(width, height))\n\ninterval = np.linspace(0, 1, 101)\ntpr_rf = rf_stats['tpr_mean_test']\ntpr_rf[0], tpr_rf[-1] = 0, 1\ntpr_lr = lr_stats['tpr_mean_test']\ntpr_lr[0], tpr_lr[-1] = 0, 1\ntpr_svm = svm_stats['tpr_mean_test']\ntpr_svm[0], tpr_svm[-1] = 0, 1\nax.plot(interval, tpr_rf,\n label=f'Random forest (AUC = {rf_stats[\"roc_auc_test\"]:.3f} '\n f'± {rf_stats[\"roc_auc_std_test\"]:.3f})')\nax.fill_between(interval, tpr_rf - rf_stats['tpr_std_test'],\n tpr_rf + rf_stats['tpr_std_test'], alpha=0.2)\nax.plot(interval, tpr_lr,\n label=f'Logistic regression (AUC = {lr_stats[\"roc_auc_test\"]:.3f} '\n f'± {lr_stats[\"roc_auc_std_test\"]:.3f})')\nax.fill_between(interval, tpr_lr - lr_stats['tpr_std_test'],\n tpr_lr + lr_stats['tpr_std_test'], alpha=0.2)\nax.plot(interval, tpr_svm,\n label=f'SVM (AUC = {svm_stats[\"roc_auc_test\"]:.3f} '\n f'± {svm_stats[\"roc_auc_std_test\"]:.3f})')\nax.fill_between(interval, tpr_svm - svm_stats['tpr_std_test'],\n tpr_svm + svm_stats['tpr_std_test'], alpha=0.2)\n \nax.plot([0, 1], [0, 1], c='black', ls='--')\n\nax.set_xlim(0, 1)\nax.set_ylim(0, 1)\n\nax.set_xlabel('False Positive Rate')\nax.set_ylabel('True Positive Rate')\n\nax.legend(loc='lower right', frameon=False)\n\nsns.despine()\n\nplt.savefig('train_classifier_roc.png', dpi=300, bbox_inches='tight')\nplt.show()\nplt.close()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
cbd4648121a23411022c9adebf78d5c3dec92cf0
| 3,626 |
ipynb
|
Jupyter Notebook
|
Module2/Python_Data_Analysis_code/Chapter 11/extracting_texture.ipynb
|
vijaysharmapc/Python-End-to-end-Data-Analysis
|
a00f2d5d1547993e000b2551ec6a1360240885ba
|
[
"MIT"
] | 119 |
2016-08-24T20:12:01.000Z
|
2022-03-23T03:59:30.000Z
|
Chapter 11/extracting_texture.ipynb
|
woaitianfa/PythonDataAnalysisCookbook
|
e41b5c1d097239d876ab64a4ce7ec2fb3f6a5c7b
|
[
"MIT"
] | 3 |
2016-10-18T03:49:11.000Z
|
2020-11-03T12:41:29.000Z
|
Chapter 11/extracting_texture.ipynb
|
woaitianfa/PythonDataAnalysisCookbook
|
e41b5c1d097239d876ab64a4ce7ec2fb3f6a5c7b
|
[
"MIT"
] | 110 |
2016-08-19T01:57:35.000Z
|
2022-02-18T17:02:17.000Z
| 26.467153 | 208 | 0.538334 |
[
[
[
"import mahotas as mh\nimport numpy as np\nfrom sklearn.datasets import load_digits\nimport matplotlib.pyplot as plt\nfrom tpot import TPOT\nfrom sklearn.cross_validation import train_test_split\nimport dautil as dl",
"_____no_output_____"
],
[
"context = dl.nb.Context('extracting_texture')\nlr = dl.nb.LatexRenderer(chapter=11, start=5, context=context)\nlr.render(r' C_{\\Delta x, \\Delta y}(i,j)=\\sum_{p=1}^n\\sum_{q=1}^m\\begin{cases} 1, & \\text{if }I(p,q)=i\\text{ and }I(p+\\Delta x,q+\\Delta y)=j \\\\ 0, & \\text{otherwise}\\end{cases}')\nlr.render(r'''\\begin{align}\n Angular \\text{ } 2nd \\text{ } Moment &= \\sum_{i} \\sum_{j} p[i,j]^{2}\\\\\n Contrast &= \\sum_{n=0}^{Ng-1} n^{2} \\left \\{ \\sum_{i=1}^{Ng} \\sum_{j=1}^{Ng} p[i,j] \\right \\} \\text{, where } |i-j|=n\\\\\n Correlation &= \\frac{\\sum_{i=1}^{Ng} \\sum_{j=1}^{Ng}(ij)p[i,j] - \\mu_x \\mu_y}{\\sigma_x \\sigma_y} \\\\\n Entropy &= -\\sum_{i}\\sum_{j} p[i,j] log(p[i,j])\\\\\n\\end{align}''')",
"_____no_output_____"
],
[
"digits = load_digits()\nX = digits.data.copy()\n\nfor i, img in enumerate(digits.images):\n np.append(X[i], mh.features.haralick(\n img.astype(np.uint8)).ravel())\n\nX_train, X_test, y_train, y_test = train_test_split(\n X, digits.target, train_size=0.75)",
"_____no_output_____"
],
[
"tpot = TPOT(generations=6, population_size=101,\n random_state=46, verbosity=2)\ntpot.fit(X_train, y_train)",
"_____no_output_____"
],
[
"%matplotlib inline\ncontext = dl.nb.Context('extracting_texture')\ndl.nb.RcWidget(context)",
"_____no_output_____"
],
[
"print('Score {:.2f}'.format(tpot.score(X_train, y_train, X_test, y_test)))\ndl.plotting.img_show(plt.gca(), digits.images[0])\nplt.title('Original Image')\n\nplt.figure()\ndl.plotting.img_show(plt.gca(), digits.data[0].reshape((8, 8)))\nplt.title('Core Features')\nplt.figure()\ndl.plotting.img_show(plt.gca(), mh.features.haralick(\n digits.images[0].astype(np.uint8)))\nplt.title('Haralick Features')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd469e6f669f0660b8b37f38abff5fb5b0fe761
| 504,505 |
ipynb
|
Jupyter Notebook
|
examples/Time_Series.ipynb
|
truongc2/data-describe
|
ed64a34587c7997e0c8a67938c2b9de996aaac11
|
[
"Apache-2.0"
] | 294 |
2020-10-18T06:18:35.000Z
|
2022-03-17T01:58:41.000Z
|
examples/Time_Series.ipynb
|
lenamax2355/data-describe
|
4e42a3de5b0dd776f78b78bd85f1ba6435b252eb
|
[
"Apache-2.0"
] | 127 |
2020-10-13T22:42:15.000Z
|
2022-03-31T05:07:23.000Z
|
examples/Time_Series.ipynb
|
lenamax2355/data-describe
|
4e42a3de5b0dd776f78b78bd85f1ba6435b252eb
|
[
"Apache-2.0"
] | 19 |
2020-10-18T06:21:26.000Z
|
2021-06-28T15:39:14.000Z
| 504,505 | 504,505 | 0.819379 |
[
[
[
"# Time Series",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\n\nimport data_describe as dd\nfrom data_describe.core.time import plot_autocorrelation, stationarity_test",
"_____no_output_____"
],
[
"df = pd.read_csv(\"https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-total-female-births.csv\")\ndf['Date'] = pd.to_datetime(df.Date, unit='ns')\ndf['Births_Multiplier'] = df['Births'] * 1.16\ndf.set_index(\"Date\", inplace=True)\ndf.head(2)",
"_____no_output_____"
]
],
[
[
"## Plot time series",
"_____no_output_____"
]
],
[
[
"dd.plot_time_series(df, col=\"Births\")",
"_____no_output_____"
]
],
[
[
"## Plot interactive time series",
"_____no_output_____"
]
],
[
[
"dd.plot_time_series(df, col=[\"Births\",\"Births_Multiplier\"], viz_backend=\"plotly\" )",
"C:\\workspace\\data-describe\\data_describe\\compat\\_notebook.py:32: JupyterPlotlyWarning:\n\nAre you running in Jupyter Lab? The extension \"jupyterlab-plotly\" was not found and is required for Plotly visualizations in Jupyter Lab.\n\n"
]
],
[
[
"## Plot decomposition",
"_____no_output_____"
]
],
[
[
"dd.plot_time_series(df, col=\"Births\", decompose=True)",
"_____no_output_____"
],
[
"dd.plot_time_series(df, col=\"Births\", decompose=True, viz_backend=\"plotly\")",
"_____no_output_____"
]
],
[
[
"## Perform Stationarity Tests",
"_____no_output_____"
]
],
[
[
"stationarity_test(df, col='Births', test=\"dickey-fuller\")",
"_____no_output_____"
]
],
[
[
"## Plot ACF ",
"_____no_output_____"
]
],
[
[
"# Use seaborn by default\nplot_autocorrelation(df, col='Births', plot_type=\"acf\")",
"_____no_output_____"
]
],
[
[
"## Plot PACF",
"_____no_output_____"
]
],
[
[
"plot_autocorrelation(df, col=\"Births\", plot_type=\"pacf\", n_lags=10, viz_backend=\"plotly\")",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd4794131cdad370938a3cd06d2669233adff82
| 59,696 |
ipynb
|
Jupyter Notebook
|
notebooks/Sentiment Analysis Example using BERT.ipynb
|
SophieNi/ATTESSA
|
d8aa5258e30deb113f66df9600926bf8c41c6c13
|
[
"FTL"
] | 1 |
2021-07-18T10:58:53.000Z
|
2021-07-18T10:58:53.000Z
|
notebooks/Sentiment Analysis Example using BERT.ipynb
|
SophieNi/ATTESSA
|
d8aa5258e30deb113f66df9600926bf8c41c6c13
|
[
"FTL"
] | null | null | null |
notebooks/Sentiment Analysis Example using BERT.ipynb
|
SophieNi/ATTESSA
|
d8aa5258e30deb113f66df9600926bf8c41c6c13
|
[
"FTL"
] | null | null | null | 45.639144 | 711 | 0.574913 |
[
[
[
"from sklearn.model_selection import train_test_split\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom datetime import datetime",
"_____no_output_____"
],
[
"import bert\nfrom bert import run_classifier\nfrom bert import optimization\nfrom bert import tokenization",
"_____no_output_____"
],
[
"from tensorflow import keras\nimport os\nimport re",
"_____no_output_____"
],
[
"# Set the output directory for saving model file\n# Optionally, set a GCP bucket location\n\nOUTPUT_DIR = '../models'\nDO_DELETE = False \nUSE_BUCKET = False \nBUCKET = 'BUCKET_NAME'\n\nif USE_BUCKET:\n OUTPUT_DIR = 'gs://{}/{}'.format(BUCKET, OUTPUT_DIR)\n from google.colab import auth\n auth.authenticate_user()\n\nif DO_DELETE:\n try:\n tf.gfile.DeleteRecursively(OUTPUT_DIR)\n except:\n pass\n\ntf.gfile.MakeDirs(OUTPUT_DIR)\nprint('***** Model output directory: {} *****'.format(OUTPUT_DIR))",
"***** Model output directory: ../models *****\n"
],
[
"# Load all files from a directory in a DataFrame.\ndef load_directory_data(directory):\n data = {}\n data[\"sentence\"] = []\n data[\"sentiment\"] = []\n \n for file_path in os.listdir(directory):\n with tf.gfile.GFile(os.path.join(directory, file_path), \"r\") as f:\n data[\"sentence\"].append(f.read())\n data[\"sentiment\"].append(re.match(\"\\d+_(\\d+)\\.txt\", file_path).group(1))\n \n return pd.DataFrame.from_dict(data)\n\n# Merge positive and negative examples, add a polarity column and shuffle.\ndef load_dataset(directory):\n pos_df = load_directory_data(os.path.join(directory, \"pos\"))\n neg_df = load_directory_data(os.path.join(directory, \"neg\"))\n pos_df[\"polarity\"] = 1\n neg_df[\"polarity\"] = 0\n return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)",
"_____no_output_____"
],
[
"train = load_dataset(os.path.join(\"../data/\", \"aclImdb\", \"train\"))\ntest = load_dataset(os.path.join(\"../data/\", \"aclImdb\", \"test\"))",
"_____no_output_____"
],
[
"train = train.sample(5000)\ntest = test.sample(5000)",
"_____no_output_____"
],
[
"DATA_COLUMN = 'sentence'\nLABEL_COLUMN = 'polarity'\nlabel_list = [0, 1]",
"_____no_output_____"
],
[
"# Use the InputExample class from BERT's run_classifier code to create examples from the data\ntrain_InputExamples = train.apply(lambda x: bert.run_classifier.InputExample(guid=None,\n text_a = x[DATA_COLUMN], \n text_b = None, \n label = x[LABEL_COLUMN]), axis = 1)\n\ntest_InputExamples = test.apply(lambda x: bert.run_classifier.InputExample(guid=None, \n text_a = x[DATA_COLUMN], \n text_b = None, \n label = x[LABEL_COLUMN]), axis = 1)",
"_____no_output_____"
],
[
"# This is a path to an uncased (all lowercase) version of BERT\nBERT_MODEL_HUB = \"https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1\"\n\ndef create_tokenizer_from_hub_module():\n \"\"\"Get the vocab file and casing info from the Hub module.\"\"\"\n with tf.Graph().as_default():\n bert_module = hub.Module(BERT_MODEL_HUB)\n tokenization_info = bert_module(signature=\"tokenization_info\", as_dict=True)\n with tf.Session() as sess:\n vocab_file, do_lower_case = sess.run([tokenization_info[\"vocab_file\"],\n tokenization_info[\"do_lower_case\"]])\n \n return bert.tokenization.FullTokenizer(vocab_file=vocab_file, do_lower_case=do_lower_case)\n\ntokenizer = create_tokenizer_from_hub_module()",
"INFO:tensorflow:Saver not created because there are no variables in the graph to restore\n"
],
[
"tokenizer.tokenize(\"This here's an example of using the BERT tokenizer\")",
"_____no_output_____"
],
[
"# We'll set sequences to be at most 128 tokens long.\nMAX_SEQ_LENGTH = 128\n# Convert our train and test features to InputFeatures that BERT understands.\ntrain_features = bert.run_classifier.convert_examples_to_features(train_InputExamples, \n label_list, \n MAX_SEQ_LENGTH, \n tokenizer)\n\ntest_features = bert.run_classifier.convert_examples_to_features(test_InputExamples, \n label_list, \n MAX_SEQ_LENGTH, \n tokenizer)",
"WARNING:tensorflow:From /Users/tingwei758/opt/anaconda3/envs/ATTESSA/lib/python3.7/site-packages/bert/run_classifier.py:774: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd47e91c7a7de94b3efbcf43901cbd57a9ea1e1
| 114,282 |
ipynb
|
Jupyter Notebook
|
DS_Methodology/DS0103EN-2-2-1-From-Requirements-to-Collection-v2.0.ipynb
|
ClaudiaCCordeiro/Curso_IBM
|
2123ebf48e0657f61998f38fe803203be51877ff
|
[
"MIT"
] | null | null | null |
DS_Methodology/DS0103EN-2-2-1-From-Requirements-to-Collection-v2.0.ipynb
|
ClaudiaCCordeiro/Curso_IBM
|
2123ebf48e0657f61998f38fe803203be51877ff
|
[
"MIT"
] | null | null | null |
DS_Methodology/DS0103EN-2-2-1-From-Requirements-to-Collection-v2.0.ipynb
|
ClaudiaCCordeiro/Curso_IBM
|
2123ebf48e0657f61998f38fe803203be51877ff
|
[
"MIT"
] | null | null | null | 34.810235 | 557 | 0.305079 |
[
[
[
"<a href=\"https://cognitiveclass.ai\"><img src = \"https://ibm.box.com/shared/static/9gegpsmnsoo25ikkbl4qzlvlyjbgxs5x.png\" width = 400> </a>\n\n<h1 align=center><font size = 5>From Requirements to Collection</font></h1>",
"_____no_output_____"
],
[
"## Introduction\n\nIn this lab, we will continue learning about the data science methodology, and focus on the **Data Requirements** and the **Data Collection** stages.",
"_____no_output_____"
],
[
"## Table of Contents\n\n<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n1. [Data Requirements](#0)<br>\n2. [Data Collection](#2)<br>\n</div>\n<hr>",
"_____no_output_____"
],
[
"# Data Requirements <a id=\"0\"></a>",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
],
[
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab2_fig1_flowchart_data_requirements.png\" width=500>",
"_____no_output_____"
],
[
"In the videos, we learned that the chosen analytic approach determines the data requirements. Specifically, the analytic methods to be used require certain data content, formats and representations, guided by domain knowledge.",
"_____no_output_____"
],
[
"In the **From Problem to Approach Lab**, we determined that automating the process of determining the cuisine of a given recipe or dish is potentially possible using the ingredients of the recipe or the dish. In order to build a model, we need extensive data of different cuisines and recipes.",
"_____no_output_____"
],
[
"Identifying the required data fulfills the data requirements stage of the data science methodology.\n\n-----------",
"_____no_output_____"
],
[
"# Data Collection <a id=\"2\"></a>",
"_____no_output_____"
],
[
"<img src = \"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab2_fig2_flowchart_data_collection.png\" width=500>",
"_____no_output_____"
],
[
"In the initial data collection stage, data scientists identify and gather the available data resources. These can be in the form of structured, unstructured, and even semi-structured data relevant to the problem domain.",
"_____no_output_____"
],
[
"#### Web Scraping of Online Food Recipes \n\nA researcher named Yong-Yeol Ahn scraped tens of thousands of food recipes (cuisines and ingredients) from three different websites, namely:",
"_____no_output_____"
],
[
"<img src = \"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab2_fig3_allrecipes.png\" width=500>\n\nwww.allrecipes.com\n\n<img src = \"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab2_fig4_epicurious.png\" width=500>\n\nwww.epicurious.com\n\n<img src = \"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/images/lab2_fig5_menupan.png\" width=500>\n\nwww.menupan.com",
"_____no_output_____"
],
[
"For more information on Yong-Yeol Ahn and his research, you can read his paper on [Flavor Network and the Principles of Food Pairing](http://yongyeol.com/papers/ahn-flavornet-2011.pdf).",
"_____no_output_____"
],
[
"Luckily, we will not need to carry out any data collection as the data that we need to meet the goal defined in the business understanding stage is readily available.",
"_____no_output_____"
],
[
"#### We have already acquired the data and placed it on an IBM server. Let's download the data and take a look at it.",
"_____no_output_____"
],
[
"<strong>Important note:</strong> Please note that you are not expected to know how to program in Python. The following code is meant to illustrate the stage of data collection, so it is totally fine if you do not understand the individual lines of code. We have a full course on programming in Python, <a href=\"http://cocl.us/PY0101EN_DS0103EN_LAB2_PYTHON_Coursera\"><strong>Python for Data Science</strong></a>, which is also offered on Coursera. So make sure to complete the Python course if you are interested in learning how to program in Python.",
"_____no_output_____"
],
[
"### Using this notebook:\n\nTo run any of the following cells of code, you can type **Shift + Enter** to excute the code in a cell.",
"_____no_output_____"
],
[
"Get the version of Python installed.",
"_____no_output_____"
]
],
[
[
"# check Python version\n!python -V",
"Python 3.6.8 :: Anaconda, Inc.\n"
]
],
[
[
"Read the data from the IBM server into a *pandas* dataframe.",
"_____no_output_____"
]
],
[
[
"import pandas as pd # download library to read data into dataframe\npd.set_option('display.max_columns', None)\n\nrecipes = pd.read_csv(\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DS0103EN/labs/data/recipes.csv\")\n\nprint(\"Data read into dataframe!\") # takes about 30 seconds",
"Data read into dataframe!\n"
]
],
[
[
"Show the first few rows.",
"_____no_output_____"
]
],
[
[
"recipes.head()",
"_____no_output_____"
]
],
[
[
"Get the dimensions of the dataframe.",
"_____no_output_____"
]
],
[
[
"recipes.shape",
"_____no_output_____"
]
],
[
[
"So our dataset consists of 57,691 recipes. Each row represents a recipe, and for each recipe, the corresponding cuisine is documented as well as whether 384 ingredients exist in the recipe or not beginning with almond and ending with zucchini.\n\n-----------",
"_____no_output_____"
],
[
"Now that the data collection stage is complete, data scientists typically use descriptive statistics and visualization techniques to better understand the data and get acquainted with it. Data scientists, essentially, explore the data to:\n\n* understand its content,\n* assess its quality,\n* discover any interesting preliminary insights, and,\n* determine whether additional data is necessary to fill any gaps in the data.",
"_____no_output_____"
],
[
"### Thank you for completing this lab!\n\nThis notebook was created by [Alex Aklson](https://www.linkedin.com/in/aklson/). I hope you found this lab session interesting. Feel free to contact me if you have any questions!",
"_____no_output_____"
],
[
"This notebook is part of a course on **Coursera** called *Data Science Methodology*. If you accessed this notebook outside the course, you can take this course, online by clicking [here](http://cocl.us/DS0103EN_Coursera_LAB2).",
"_____no_output_____"
],
[
"<hr>\n\nCopyright © 2019 [Cognitive Class](https://cognitiveclass.ai/?utm_source=bducopyrightlink&utm_medium=dswb&utm_campaign=bdu). This notebook and its source code are released under the terms of the [MIT License](https://bigdatauniversity.com/mit-license/).",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cbd4811d50b40e1f41657f0ff14ca321ac18d25b
| 10,363 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/3 . Lists and Dictionaries ..... [abhishek soni]-checkpoint.ipynb
|
abhishek201202/Machine-Learning
|
24edc24a716b840980ed16dc6f7d554a5b1ccea9
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/3 . Lists and Dictionaries ..... [abhishek soni]-checkpoint.ipynb
|
abhishek201202/Machine-Learning
|
24edc24a716b840980ed16dc6f7d554a5b1ccea9
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/3 . Lists and Dictionaries ..... [abhishek soni]-checkpoint.ipynb
|
abhishek201202/Machine-Learning
|
24edc24a716b840980ed16dc6f7d554a5b1ccea9
|
[
"MIT"
] | null | null | null | 20.767535 | 399 | 0.412911 |
[
[
[
"# # Lists\n### == > it is same as array in c++ , but it can also store multiple data types at the same time ",
"_____no_output_____"
]
],
[
[
"# creating lists\na = [1,2,3]\nprint(type(a))\n\na1 = list()\nprint(a1)\n\na2 = list(a)\nprint(a2)\n\na4 = [ i for i in range(10)] ## for range from 0 to 10 set i\nprint(a4)\n\na5 = [ i*i for i in range(10)]\nprint(a5)\n\na6 = [1,2,\"as\",True]\nprint(a6)\n",
"<class 'list'>\n[]\n[1, 2, 3]\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n[1, 2, 'as', True]\n"
],
[
"#how to access data\nprint(a[1])\nprint(a[-1])\n\n# len of array\nprint(\"len : \",len(a))",
"2\n3\nlen : 3\n"
]
],
[
[
"## 1) slicing and fast iteration in lists",
"_____no_output_____"
]
],
[
[
"# slicing of array\nprint(a[1:2])\n\n# fast iteration\nfor i in a :\n print(i)",
"[2]\n1\n2\n3\n"
]
],
[
[
"## 2) string spliting",
"_____no_output_____"
]
],
[
[
"## returns a list after the spliting that string on the basis of \" \"\nstr = \" a abc d ef ghf \"\nprint(str.split(\" \"))\n\nstr = \" a df d dsds \"\nprint(str.split())\n\nstr = \"a,bcd,dsd,dwd\"\nprint(str.split(\",\"))",
"['', 'a', 'abc', 'd', 'ef', 'ghf', '']\n['a', 'df', 'd', 'dsds']\n['a', 'bcd', 'dsd', 'dwd']\n"
]
],
[
[
"## 3) user input",
"_____no_output_____"
]
],
[
[
"########## 1st method ###########\nlist1 = input().strip().split()\nprint(list1)\nfor i in range(len(list1)):\n list1[i] = int(list1[i])\nprint(list1)\nprint()\n\n########## 2nd method ###########\nlist = input().split()\nprint(list)\nfor i in range(len(list)):\n list[i] = int(list[i])\nprint(list)\nprint()\n\n########## 3rd method ###########\n### one line for taking array input\n\narr = [int(x) for x in input().split()]\nprint(arr)\n",
"1 2 3 4 5 6\n['1', '2', '3', '4', '5', '6']\n[1, 2, 3, 4, 5, 6]\n\n1 2 3 4 5\n['1', '2', '3', '4', '5']\n[1, 2, 3, 4, 5]\n\n 1 2 4 5 6\n[1, 2, 4, 5, 6]\n"
]
],
[
[
"## 4) add elements in a lists ( append , insert , extend )",
"_____no_output_____"
]
],
[
[
"l = [1,2,3]\nl.append(9)\nprint(l)\nl.insert(1,243)\nprint(l)\n\nl2 = [2,3,4]\nl.extend(l2)\nprint(l)",
"[1, 2, 3, 9]\n[1, 243, 2, 3, 9]\n[1, 243, 2, 3, 9, 2, 3, 4]\n"
]
],
[
[
"## 5) deleting elements ( pop , remove , del )",
"_____no_output_____"
]
],
[
[
"print(l)\n\nl.pop() ## without arguments its going to remove the last element\nprint(l)\n\nl.pop(2) ## remove element at index 2\nprint(l)\n\nl.remove(2) ## remove first occurance of that elements\nprint(l)\n\ndel l[0:2] ## delete this range from the list\nprint(l)\n\n\n",
"[1, 243, 2, 3, 9, 2, 3, 4]\n[1, 243, 2, 3, 9, 2, 3]\n[1, 243, 3, 9, 2, 3]\n[1, 243, 3, 9, 3]\n[3, 9, 3]\n"
]
],
[
[
"## 6) concatenation of two lists",
"_____no_output_____"
]
],
[
[
"l = [1,2,3]\nl = l + l\n# l = l - l ## there is - operation possible\nprint(l)\nl*=3 \nprint(l)",
"[1, 2, 3, 1, 2, 3]\n[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]\n"
]
],
[
[
"## 7) some useful inbuild functions (sort , count , index , in , reverse , max , min , len)",
"_____no_output_____"
]
],
[
[
"#sorting \nl = [2,5,1,3,64,13,0,1]\nl.sort()\nprint(l)\nprint(len(l))\n\n# count , index , reverse\nprint(l.count(1)) ## count element 1 in the array\nprint(l.index(64)) ## find index of element \nl.reverse() ## reverse the array\nprint(l)\n\nif 64 in l: ## boolean function is present or not\n print(\"found\")\nelse:\n print(\"not_found\")\n \n \nprint(max(l)) ## find the maximum element in the list\nprint(min(l)) ## find the minimum element in the list",
"[0, 1, 1, 2, 3, 5, 13, 64]\n8\n2\n7\n[64, 13, 5, 3, 2, 1, 1, 0]\nfound\n64\n0\n"
]
],
[
[
"## 8) bubble sort",
"_____no_output_____"
]
],
[
[
"## bubble sort \nl = [int(x) for x in input().split()]\nprint(l)\n\nn = len(l)\nfor j in range(n-1):\n for i in range(0,n-1-j):\n if(l[i] > l[i+1]):\n l[i],l[i+1] = l[i+1],l[i]\nprint(l)",
"-9 0 -7 3 69 0 \n[-9, 0, -7, 3, 69, 0]\n[-9, -7, 0, 0, 3, 69]\n"
]
],
[
[
"# # Dictionaries\n### === > it is same as map in c++ , here we can store different types of keys and values but in c++ we have to create a different map for different type of keys and values . ex : map<pair<int,int> , int> mp ....... this will store pair as a key always and integer as value but in python we can store anything. keys are immutable therefore keys can be string , int ,float but it not be a list",
"_____no_output_____"
]
],
[
[
"d = {}\nd[23] = 34\nd[3 , 4] = 32\nd[\"str\"] = 31\nprint(d[23])\nprint(type(d[23]))\n\nd = {23 : 34 , \"str\" : 31}\nprint(d)\n\n\n### fast iteration on dictionaries\nprint(\"\\n\" , \"traversing on map\")\nfor i in d: ### in C++ i is pair of key and value but here it is key\n print(i , \":\" , d[i])\nprint(\"over\")\n### delete elements\n\ndel d[23]\nprint(d)\n\n",
"34\n<class 'int'>\n{23: 34, 'str': 31}\n\n traversing on map\n23 : 34\nstr : 31\nover\n{'str': 31}\n"
],
[
"# common functions in dictionaries\nd1 = {}\nd1[1] = 1\nd2 = {}\nd2[2] = 3\n\nprint(d1 == d2)\n\n\nprint(len(d1))\n\nd1.clear()\nprint(d1)\n\nprint(d2.keys()) ## behave like a list\nprint(d2.values()) ## behave like a list\n\nprint(23 in d2) ## is this key is present or not\n",
"False\n1\n{}\ndict_keys([2])\ndict_values([3])\nFalse\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbd4a5d459ab843e3633d235e2fae3e72ea52405
| 20,084 |
ipynb
|
Jupyter Notebook
|
nbs/002b_data.unwindowed.ipynb
|
xanderdunn/tsai
|
4ff0348767b3640cc4613441b673ed466eb96913
|
[
"Apache-2.0"
] | null | null | null |
nbs/002b_data.unwindowed.ipynb
|
xanderdunn/tsai
|
4ff0348767b3640cc4613441b673ed466eb96913
|
[
"Apache-2.0"
] | null | null | null |
nbs/002b_data.unwindowed.ipynb
|
xanderdunn/tsai
|
4ff0348767b3640cc4613441b673ed466eb96913
|
[
"Apache-2.0"
] | null | null | null | 41.929019 | 2,820 | 0.529277 |
[
[
[
"# default_exp data.unwindowed",
"_____no_output_____"
]
],
[
[
"# Unwindowed datasets\n\n> This functionality will allow you to create a dataset that applies sliding windows to the input data on the fly. This heavily reduces the size of the input data files, as only the original, unwindowed data needs to be stored.",
"_____no_output_____"
]
],
[
[
"#export\nfrom tsai.imports import *\nfrom tsai.utils import *\nfrom tsai.data.validation import *\nfrom tsai.data.core import *",
"_____no_output_____"
],
[
"#export\nclass TSUnwindowedDataset():\n _types = TSTensor, TSLabelTensor\n def __init__(self, X, y=None, y_func=None, window_size=1, stride=1, drop_start=0, drop_end=0, seq_first=True, **kwargs):\n store_attr()\n if X.ndim == 1: X = np.expand_dims(X, 1)\n shape = X.shape\n assert len(shape) == 2\n if seq_first: \n seq_len = shape[0]\n else: \n seq_len = shape[-1]\n max_time = seq_len - window_size + 1 - drop_end\n assert max_time > 0, 'you need to modify either window_size or drop_end as they are larger than seq_len'\n self.all_idxs = np.expand_dims(np.arange(drop_start, max_time, step=stride), 0).T\n self.window_idxs = np.expand_dims(np.arange(window_size), 0)\n if 'split' in kwargs: self.split = kwargs['split']\n else: self.split = None\n self.n_inp = 1\n if y is None: self.loss_func = MSELossFlat()\n else: \n _,yb=self[:2]\n if (is_listy(yb[0]) and isinstance(yb[0][0], Integral)) or isinstance(yb[0], Integral): self.loss_func = CrossEntropyLossFlat()\n else: self.loss_func = MSELossFlat()\n\n def __len__(self):\n if self.split is not None: \n return len(self.split)\n else: \n return len(self.all_idxs)\n\n def __getitem__(self, idxs):\n if self.split is not None:\n idxs = self.split[idxs]\n widxs = self.all_idxs[idxs] + self.window_idxs\n if self.seq_first:\n xb = self.X[widxs]\n if xb.ndim == 3: xb = xb.transpose(0,2,1)\n else: xb = np.expand_dims(xb, 1)\n else:\n xb = self.X[:, widxs].transpose(1,0,2)\n if self.y is None:\n return (self._types[0](xb),)\n else:\n yb = self.y[widxs]\n if self.y_func is not None: \n yb = self.y_func(yb)\n return (self._types[0](xb), self._types[1](yb))\n @property\n def vars(self):\n s = self[0][0] if not isinstance(self[0][0], tuple) else self[0][0][0]\n return s.shape[-2]\n @property\n def len(self): \n s = self[0][0] if not isinstance(self[0][0], tuple) else self[0][0][0]\n return s.shape[-1] \n\n\nclass TSUnwindowedDatasets(FilteredBase):\n def __init__(self, dataset, splits):\n store_attr()\n def subset(self, i):\n return type(self.dataset)(self.dataset.X, y=self.dataset.y, y_func=self.dataset.y_func, window_size=self.dataset.window_size,\n stride=self.dataset.stride, drop_start=self.dataset.drop_start, drop_end=self.dataset.drop_end, \n seq_first=self.dataset.seq_first, split=self.splits[i])\n @property\n def train(self): \n return self.subset(0)\n @property\n def valid(self): \n return self.subset(1)\n def __getitem__(self, i): return self.subset(i)",
"_____no_output_____"
],
[
"def y_func(y): return y.astype('float').mean(1)",
"_____no_output_____"
]
],
[
[
"This approach works with both univariate and multivariate data.\n\n* Univariate: we'll use a simple array with 20 values, one with the seq_len first (X0), the other with seq_len second (X1).\n* Multivariate: we'll use 2 time series arrays, one with the seq_len first (X2), the other with seq_len second (X3). No sliding window has been applied to them yet. ",
"_____no_output_____"
]
],
[
[
"# Univariate\nX0 = np.arange(20)\nX1 = np.arange(20).reshape(1, -1)\nX0.shape, X0, X1.shape, X1",
"_____no_output_____"
],
[
"# Multivariate\nX2 = np.arange(20).reshape(-1,1)*np.array([1, 10, 100]).reshape(1,-1)\nX3 = np.arange(20).reshape(1,-1)*np.array([1, 10, 100]).reshape(-1,1)\nX2.shape, X3.shape, X2, X3",
"_____no_output_____"
]
],
[
[
"Now, instead of applying SlidingWindow to create and save the time series that can be consumed by a time series model, we can use a dataset that creates the data on the fly. In this way we avoid the need to create and save large files. This approach is also useful when you want to test different sliding window sizes, as otherwise you would need to create files for every size you want to test.The dataset will create the samples correctly formatted and ready to be passed on to a time series architecture.",
"_____no_output_____"
]
],
[
[
"wds0 = TSUnwindowedDataset(X0, window_size=5, stride=2, seq_first=True)[:][0]\nwds1 = TSUnwindowedDataset(X1, window_size=5, stride=2, seq_first=False)[:][0]\ntest_eq(wds0, wds1)\nwds0, wds0.data, wds1, wds1.data",
"_____no_output_____"
],
[
"wds2 = TSUnwindowedDataset(X2, window_size=5, stride=2, seq_first=True)[:][0]\nwds3 = TSUnwindowedDataset(X3, window_size=5, stride=2, seq_first=False)[:][0]\ntest_eq(wds2, wds3)\nwds2, wds3, wds2.data, wds3.data",
"_____no_output_____"
],
[
"#hide\nout = create_scripts(); beep(out)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbd4a91dbd7a26ee0d8ab9f2e7396aa917fc090c
| 51,486 |
ipynb
|
Jupyter Notebook
|
C1_functional_API/C1_W1_Lab_2_multi-output.ipynb
|
abroy77/Advanced-TF-Course
|
70629da6f1be6fa2cc25a426dfd254ac701e31e2
|
[
"MIT"
] | null | null | null |
C1_functional_API/C1_W1_Lab_2_multi-output.ipynb
|
abroy77/Advanced-TF-Course
|
70629da6f1be6fa2cc25a426dfd254ac701e31e2
|
[
"MIT"
] | null | null | null |
C1_functional_API/C1_W1_Lab_2_multi-output.ipynb
|
abroy77/Advanced-TF-Course
|
70629da6f1be6fa2cc25a426dfd254ac701e31e2
|
[
"MIT"
] | null | null | null | 71.807531 | 8,066 | 0.729771 |
[
[
[
"# Ungraded Lab: Build a Multi-output Model\n\nIn this lab, we'll show how you can build models with more than one output. The dataset we will be working on is available from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Energy+efficiency). It is an Energy Efficiency dataset which uses the bulding features (e.g. wall area, roof area) as inputs and has two outputs: Cooling Load and Heating Load. Let's see how we can build a model to train on this data.",
"_____no_output_____"
],
[
"## Imports",
"_____no_output_____"
]
],
[
[
"try:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Input\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
]
],
[
[
"## Utilities\n\nWe define a few utilities for data conversion and visualization to make our code more neat.",
"_____no_output_____"
]
],
[
[
"def format_output(data):\n y1 = data.pop('Y1')\n y1 = np.array(y1)\n y2 = data.pop('Y2')\n y2 = np.array(y2)\n return y1, y2\n\n\ndef norm(x):\n return (x - train_stats['mean']) / train_stats['std']\n\n\ndef plot_diff(y_true, y_pred, title=''):\n plt.scatter(y_true, y_pred)\n plt.title(title)\n plt.xlabel('True Values')\n plt.ylabel('Predictions')\n plt.axis('equal')\n plt.axis('square')\n plt.xlim(plt.xlim())\n plt.ylim(plt.ylim())\n plt.plot([-100, 100], [-100, 100])\n plt.show()\n\n\ndef plot_metrics(metric_name, title, ylim=5):\n plt.title(title)\n plt.ylim(0, ylim)\n plt.plot(history.history[metric_name], color='blue', label=metric_name)\n plt.plot(history.history['val_' + metric_name], color='green', label='val_' + metric_name)\n plt.show()",
"_____no_output_____"
]
],
[
[
"## Prepare the Data\n\nWe download the dataset and format it for training.",
"_____no_output_____"
]
],
[
[
"# Specify data URI\nURI = 'local_data/ENB2012_data.xls'\n\n# link for dataset excel: https://archive.ics.uci.edu/ml/machine-learning-databases/00242/ENB2012_data.xlsx\n\n\n# Use pandas excel reader\ndf = pd.read_excel(URI)\n\n# df.drop(columns=['Unnamed: 10', 'Unnamed: 11'], inplace=True)\n",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"\ndf = df.sample(frac=1).reset_index(drop=True)\n\n# Split the data into train and test with 80 train / 20 test\ntrain, test = train_test_split(df, test_size=0.2)\ntrain_stats = train.describe()\n\n# Get Y1 and Y2 as the 2 outputs and format them as np arrays\ntrain_stats.pop('Y1')\ntrain_stats.pop('Y2')\ntrain_stats = train_stats.transpose()\ntrain_Y = format_output(train)\ntest_Y = format_output(test)\n\n# Normalize the training and test data\nnorm_train_X = norm(train)\nnorm_test_X = norm(test)",
"_____no_output_____"
],
[
"train",
"_____no_output_____"
]
],
[
[
"## Build the Model\n\nHere is how we'll build the model using the functional syntax. Notice that we can specify a list of outputs (i.e. `[y1_output, y2_output]`) when we instantiate the `Model()` class.",
"_____no_output_____"
]
],
[
[
"# Define model layers.\ninput_layer = Input(shape=(len(train .columns),))\nfirst_dense = Dense(units='128', activation='relu')(input_layer)\nsecond_dense = Dense(units='128', activation='relu')(first_dense)\n\n# Y1 output will be fed directly from the second dense\ny1_output = Dense(units='1', name='y1_output')(second_dense)\nthird_dense = Dense(units='64', activation='relu')(second_dense)\n\n# Y2 output will come via the third dense\ny2_output = Dense(units='1', name='y2_output')(third_dense)\n\n# Define the model with the input layer and a list of output layers\nmodel = Model(inputs=input_layer, outputs=[y1_output, y2_output])\n\nprint(model.summary())",
"Model: \"model_1\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_2 (InputLayer) [(None, 8)] 0 \n__________________________________________________________________________________________________\ndense_3 (Dense) (None, 128) 1152 input_2[0][0] \n__________________________________________________________________________________________________\ndense_4 (Dense) (None, 128) 16512 dense_3[0][0] \n__________________________________________________________________________________________________\ndense_5 (Dense) (None, 64) 8256 dense_4[0][0] \n__________________________________________________________________________________________________\ny1_output (Dense) (None, 1) 129 dense_4[0][0] \n__________________________________________________________________________________________________\ny2_output (Dense) (None, 1) 65 dense_5[0][0] \n==================================================================================================\nTotal params: 26,114\nTrainable params: 26,114\nNon-trainable params: 0\n__________________________________________________________________________________________________\nNone\n"
]
],
[
[
"## Configure parameters\n\nWe specify the optimizer as well as the loss and metrics for each output.",
"_____no_output_____"
]
],
[
[
"# Specify the optimizer, and compile the model with loss functions for both outputs\noptimizer = tf.keras.optimizers.SGD(lr=0.001)\nmodel.compile(optimizer=optimizer,\n loss={'y1_output': 'mse', 'y2_output': 'mse'},\n metrics={'y1_output': tf.keras.metrics.RootMeanSquaredError(),\n 'y2_output': tf.keras.metrics.RootMeanSquaredError()})",
"_____no_output_____"
]
],
[
[
"## Train the Model",
"_____no_output_____"
]
],
[
[
"# Train the model for 500 epochs\nhistory = model.fit(norm_train_X, train_Y,\n epochs=10, batch_size=10, validation_data=(norm_test_X, test_Y))",
"Epoch 1/10\n62/62 [==============================] - 1s 4ms/step - loss: 558.3519 - y1_output_loss: 261.8806 - y2_output_loss: 296.4713 - y1_output_root_mean_squared_error: 15.6448 - y2_output_root_mean_squared_error: 16.5897 - val_loss: 35.3501 - val_y1_output_loss: 17.6830 - val_y2_output_loss: 17.6671 - val_y1_output_root_mean_squared_error: 4.2051 - val_y2_output_root_mean_squared_error: 4.2032\nEpoch 2/10\n62/62 [==============================] - 0s 1ms/step - loss: 34.7343 - y1_output_loss: 12.9546 - y2_output_loss: 21.7797 - y1_output_root_mean_squared_error: 3.5948 - y2_output_root_mean_squared_error: 4.6486 - val_loss: 33.6444 - val_y1_output_loss: 15.4094 - val_y2_output_loss: 18.2350 - val_y1_output_root_mean_squared_error: 3.9255 - val_y2_output_root_mean_squared_error: 4.2702\nEpoch 3/10\n62/62 [==============================] - 0s 1ms/step - loss: 32.2030 - y1_output_loss: 11.5578 - y2_output_loss: 20.6452 - y1_output_root_mean_squared_error: 3.3915 - y2_output_root_mean_squared_error: 4.5233 - val_loss: 20.1393 - val_y1_output_loss: 9.5905 - val_y2_output_loss: 10.5488 - val_y1_output_root_mean_squared_error: 3.0969 - val_y2_output_root_mean_squared_error: 3.2479\nEpoch 4/10\n62/62 [==============================] - 0s 1ms/step - loss: 22.4620 - y1_output_loss: 9.4845 - y2_output_loss: 12.9775 - y1_output_root_mean_squared_error: 3.0761 - y2_output_root_mean_squared_error: 3.5828 - val_loss: 17.3932 - val_y1_output_loss: 8.5096 - val_y2_output_loss: 8.8836 - val_y1_output_root_mean_squared_error: 2.9171 - val_y2_output_root_mean_squared_error: 2.9805\nEpoch 5/10\n62/62 [==============================] - 0s 1ms/step - loss: 23.8997 - y1_output_loss: 9.8965 - y2_output_loss: 14.0032 - y1_output_root_mean_squared_error: 3.1370 - y2_output_root_mean_squared_error: 3.7365 - val_loss: 18.1755 - val_y1_output_loss: 7.9452 - val_y2_output_loss: 10.2303 - val_y1_output_root_mean_squared_error: 2.8187 - val_y2_output_root_mean_squared_error: 3.1985\nEpoch 6/10\n62/62 [==============================] - 0s 1ms/step - loss: 19.6691 - y1_output_loss: 8.1462 - y2_output_loss: 11.5230 - y1_output_root_mean_squared_error: 2.8422 - y2_output_root_mean_squared_error: 3.3749 - val_loss: 34.0948 - val_y1_output_loss: 11.0321 - val_y2_output_loss: 23.0627 - val_y1_output_root_mean_squared_error: 3.3215 - val_y2_output_root_mean_squared_error: 4.8024\nEpoch 7/10\n62/62 [==============================] - 0s 1ms/step - loss: 22.7110 - y1_output_loss: 9.3590 - y2_output_loss: 13.3520 - y1_output_root_mean_squared_error: 3.0542 - y2_output_root_mean_squared_error: 3.6461 - val_loss: 20.2864 - val_y1_output_loss: 7.4047 - val_y2_output_loss: 12.8816 - val_y1_output_root_mean_squared_error: 2.7212 - val_y2_output_root_mean_squared_error: 3.5891\nEpoch 8/10\n62/62 [==============================] - 0s 1ms/step - loss: 19.3140 - y1_output_loss: 8.0313 - y2_output_loss: 11.2827 - y1_output_root_mean_squared_error: 2.8326 - y2_output_root_mean_squared_error: 3.3527 - val_loss: 29.8413 - val_y1_output_loss: 9.0340 - val_y2_output_loss: 20.8072 - val_y1_output_root_mean_squared_error: 3.0057 - val_y2_output_root_mean_squared_error: 4.5615\nEpoch 9/10\n62/62 [==============================] - 0s 1ms/step - loss: 22.2228 - y1_output_loss: 8.3826 - y2_output_loss: 13.8402 - y1_output_root_mean_squared_error: 2.8916 - y2_output_root_mean_squared_error: 3.6942 - val_loss: 40.0338 - val_y1_output_loss: 17.1919 - val_y2_output_loss: 22.8419 - val_y1_output_root_mean_squared_error: 4.1463 - val_y2_output_root_mean_squared_error: 4.7793\nEpoch 10/10\n62/62 [==============================] - 0s 1ms/step - loss: 19.1284 - y1_output_loss: 7.4709 - y2_output_loss: 11.6576 - y1_output_root_mean_squared_error: 2.7284 - y2_output_root_mean_squared_error: 3.4032 - val_loss: 14.7133 - val_y1_output_loss: 6.6364 - val_y2_output_loss: 8.0769 - val_y1_output_root_mean_squared_error: 2.5761 - val_y2_output_root_mean_squared_error: 2.8420\n"
]
],
[
[
"## Evaluate the Model and Plot Metrics",
"_____no_output_____"
]
],
[
[
"# Test the model and print loss and mse for both outputs\nloss, Y1_loss, Y2_loss, Y1_rmse, Y2_rmse = model.evaluate(x=norm_test_X, y=test_Y)\nprint(\"Loss = {}, Y1_loss = {}, Y1_mse = {}, Y2_loss = {}, Y2_mse = {}\".format(loss, Y1_loss, Y1_rmse, Y2_loss, Y2_rmse))",
"9/9 [==============================] - 0s 1ms/step - loss: nan - y1_output_loss: nan - y2_output_loss: nan - y1_output_root_mean_squared_error: nan - y2_output_root_mean_squared_error: nan\nLoss = nan, Y1_loss = nan, Y1_mse = nan, Y2_loss = nan, Y2_mse = nan\n"
],
[
"# Plot the loss and mse\nY_pred = model.predict(norm_test_X)\nplot_diff(test_Y[0], Y_pred[0], title='Y1')\nplot_diff(test_Y[1], Y_pred[1], title='Y2')\nplot_metrics(metric_name='y1_output_root_mean_squared_error', title='Y1 RMSE', ylim=6)\nplot_metrics(metric_name='y2_output_root_mean_squared_error', title='Y2 RMSE', ylim=7)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbd4ad9eb7066353b4b04bb70060e0b8ae458605
| 6,732 |
ipynb
|
Jupyter Notebook
|
Python/2016-08-08/aula7-parte1-reacoes.ipynb
|
rubensfernando/mba-analytics-big-data
|
704653b070c872ad92a21b364ca5c4a708b85428
|
[
"MIT"
] | null | null | null |
Python/2016-08-08/aula7-parte1-reacoes.ipynb
|
rubensfernando/mba-analytics-big-data
|
704653b070c872ad92a21b364ca5c4a708b85428
|
[
"MIT"
] | null | null | null |
Python/2016-08-08/aula7-parte1-reacoes.ipynb
|
rubensfernando/mba-analytics-big-data
|
704653b070c872ad92a21b364ca5c4a708b85428
|
[
"MIT"
] | null | null | null | 21.0375 | 286 | 0.497178 |
[
[
[
"# Recuperando as reações de um post",
"_____no_output_____"
]
],
[
[
"import requests",
"_____no_output_____"
]
],
[
[
"Iremos definir a URL base para realizar as requisições.",
"_____no_output_____"
]
],
[
[
"url_base = 'https://graph.facebook.com/v2.7'",
"_____no_output_____"
]
],
[
[
"Agora, iremos utilizar um nó (post) que recuperamos na aula passada.",
"_____no_output_____"
]
],
[
[
"id_post = '/134488303306371_1056521637769695'",
"_____no_output_____"
],
[
"no = id_post",
"_____no_output_____"
]
],
[
[
"Vamos criar a parte da URL em que definimos os campos que queremos recuperar. No caso é o reactions.",
"_____no_output_____"
]
],
[
[
"campos = '/?fields=reactions'",
"_____no_output_____"
]
],
[
[
"Por fim, temos que criar a parte da URL que contém o token de acesso.",
"_____no_output_____"
]
],
[
[
"access_token = '&access_token=EAACEdEose0cBAKGD4DeJpEyS5Mvf0v4VZCooTJ8KgSKOwPojIjqej9pEsC6nG4EOVD0Bi6ripn04OP9CuxZAZCqAinpBh75fYCDEalZAcXDlgbbZCyq0IZBtZCgpQZCukscpAiVJFbQs1S1f3k8SCDYw3FWxzL2HBryYrP0MGNIk9QZDZD'",
"_____no_output_____"
],
[
"url_final = url_base+no+campos+access_token\nurl_final",
"_____no_output_____"
]
],
[
[
"Com a URL final, podemos fazer o requisição.",
"_____no_output_____"
]
],
[
[
"req = requests.get(url_final).json()",
"_____no_output_____"
],
[
"import simplejson as json",
"_____no_output_____"
],
[
"print(json.dumps(req, indent=2))",
"{\n \"reactions\": {\n \"data\": [\n {\n \"name\": \"Dino Magri\",\n \"id\": \"114873192193820\",\n \"type\": \"WOW\"\n },\n {\n \"name\": \"Olya Ostasheva\",\n \"id\": \"10153793518774056\",\n \"type\": \"LIKE\"\n },\n {\n \"name\": \"Huynh Ngoc Phu\",\n \"id\": \"1518973238357915\",\n \"type\": \"LIKE\"\n },\n {\n \"name\": \"Anna Matevosyan\",\n \"id\": \"677824635611754\",\n \"type\": \"LIKE\"\n },\n {\n \"name\": \"Frederic Moresmau\",\n \"id\": \"4835889712721\",\n \"type\": \"LIKE\"\n }\n ],\n \"paging\": {\n \"cursors\": {\n \"before\": \"TVRBd01ERXdNVE0wTVRnMU56UTRPakUwTnpBMU5EQTNNREk2TnpnNE5qUTRNRE0zT1RFek16RXkZD\",\n \"after\": \"TVRjMk1UQTNNRE14TURveE5EY3dOREkxTnpjeE9qSTFOREE1TmpFMk1UTT0ZD\"\n }\n }\n },\n \"id\": \"134488303306371_1056521637769695\"\n}\n"
]
],
[
[
"Ótimo! Dados foram recuperados!\n\nAgora podemos realizar a contagem das reações de um determinado post.",
"_____no_output_____"
]
],
[
[
"tipos_reacoes = ['LIKE','LOVE', 'WOW', 'HAHA', 'SAD', 'ANGRY']",
"_____no_output_____"
],
[
"dados = req['reactions']['data']",
"_____no_output_____"
],
[
"contagem = dict(zip(tipos_reacoes, [0,0,0,0,0,0]))",
"_____no_output_____"
],
[
"for reacao in dados:\n contagem[reacao['type']] += 1",
"_____no_output_____"
],
[
"contagem",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbd4af13b8ff45206d8a97484ec4a54dc536f583
| 481,679 |
ipynb
|
Jupyter Notebook
|
examples/02-fine-tuning.ipynb
|
BT123/caffe-test
|
c5610fc35974a0c91c8bf7a39807e12c9c81fbba
|
[
"Intel",
"BSD-2-Clause"
] | null | null | null |
examples/02-fine-tuning.ipynb
|
BT123/caffe-test
|
c5610fc35974a0c91c8bf7a39807e12c9c81fbba
|
[
"Intel",
"BSD-2-Clause"
] | null | null | null |
examples/02-fine-tuning.ipynb
|
BT123/caffe-test
|
c5610fc35974a0c91c8bf7a39807e12c9c81fbba
|
[
"Intel",
"BSD-2-Clause"
] | null | null | null | 409.590986 | 130,211 | 0.920893 |
[
[
[
"# Fine-tuning a Pretrained Network for Style Recognition\n\nIn this example, we'll explore a common approach that is particularly useful in real-world applications: take a pre-trained Caffe network and fine-tune the parameters on your custom data.\n\nThe advantage of this approach is that, since pre-trained networks are learned on a large set of images, the intermediate layers capture the \"semantics\" of the general visual appearance. Think of it as a very powerful generic visual feature that you can treat as a black box. On top of that, only a relatively small amount of data is needed for good performance on the target task.",
"_____no_output_____"
],
[
"First, we will need to prepare the data. This involves the following parts:\n(1) Get the ImageNet ilsvrc pretrained model with the provided shell scripts.\n(2) Download a subset of the overall Flickr style dataset for this demo.\n(3) Compile the downloaded Flickr dataset into a database that Caffe can then consume.",
"_____no_output_____"
]
],
[
[
"caffe_root = '../' # this file should be run from {caffe_root}/examples (otherwise change this line)\n\nimport sys\nsys.path.insert(0, caffe_root + 'python')\nimport caffe\n\ncaffe.set_device(0)\ncaffe.set_mode_gpu()\n\nimport numpy as np\nfrom pylab import *\n%matplotlib inline\nimport tempfile\n\n# Helper function for deprocessing preprocessed images, e.g., for display.\ndef deprocess_net_image(image):\n image = image.copy() # don't modify destructively\n image = image[::-1] # BGR -> RGB\n image = image.transpose(1, 2, 0) # CHW -> HWC\n image += [123, 117, 104] # (approximately) undo mean subtraction\n\n # clamp values in [0, 255]\n image[image < 0], image[image > 255] = 0, 255\n\n # round and cast from float32 to uint8\n image = np.round(image)\n image = np.require(image, dtype=np.uint8)\n\n return image",
"_____no_output_____"
]
],
[
[
"### 1. Setup and dataset download\n\nDownload data required for this exercise.\n\n- `get_ilsvrc_aux.sh` to download the ImageNet data mean, labels, etc.\n- `download_model_binary.py` to download the pretrained reference model\n- `finetune_flickr_style/assemble_data.py` downloads the style training and testing data\n\nWe'll download just a small subset of the full dataset for this exercise: just 2000 of the 80K images, from 5 of the 20 style categories. (To download the full dataset, set `full_dataset = True` in the cell below.)",
"_____no_output_____"
]
],
[
[
"# Download just a small subset of the data for this exercise.\n# (2000 of 80K images, 5 of 20 labels.)\n# To download the entire dataset, set `full_dataset = True`.\nfull_dataset = False\nif full_dataset:\n NUM_STYLE_IMAGES = NUM_STYLE_LABELS = -1\nelse:\n NUM_STYLE_IMAGES = 2000\n NUM_STYLE_LABELS = 5\n\n# This downloads the ilsvrc auxiliary data (mean file, etc),\n# and a subset of 2000 images for the style recognition task.\nimport os\nos.chdir(caffe_root) # run scripts from caffe root\n!data/ilsvrc12/get_ilsvrc_aux.sh\n!scripts/download_model_binary.py models/bvlc_reference_caffenet\n!python examples/finetune_flickr_style/assemble_data.py \\\n --workers=-1 --seed=1701 \\\n --images=$NUM_STYLE_IMAGES --label=$NUM_STYLE_LABELS\n# back to examples\nos.chdir('examples')",
"Downloading...\n--2016-02-24 00:28:36-- http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz\nResolving dl.caffe.berkeleyvision.org (dl.caffe.berkeleyvision.org)... 169.229.222.251\nConnecting to dl.caffe.berkeleyvision.org (dl.caffe.berkeleyvision.org)|169.229.222.251|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 17858008 (17M) [application/octet-stream]\nSaving to: ‘caffe_ilsvrc12.tar.gz’\n\n100%[======================================>] 17,858,008 112MB/s in 0.2s \n\n2016-02-24 00:28:36 (112 MB/s) - ‘caffe_ilsvrc12.tar.gz’ saved [17858008/17858008]\n\nUnzipping...\nDone.\nModel already exists.\nDownloading 2000 images with 7 workers...\nWriting train/val for 1996 successfully downloaded images.\n"
]
],
[
[
"Define `weights`, the path to the ImageNet pretrained weights we just downloaded, and make sure it exists.",
"_____no_output_____"
]
],
[
[
"import os\nweights = os.path.join(caffe_root, 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel')\nassert os.path.exists(weights)",
"_____no_output_____"
]
],
[
[
"Load the 1000 ImageNet labels from `ilsvrc12/synset_words.txt`, and the 5 style labels from `finetune_flickr_style/style_names.txt`.",
"_____no_output_____"
]
],
[
[
"# Load ImageNet labels to imagenet_labels\nimagenet_label_file = caffe_root + 'data/ilsvrc12/synset_words.txt'\nimagenet_labels = list(np.loadtxt(imagenet_label_file, str, delimiter='\\t'))\nassert len(imagenet_labels) == 1000\nprint 'Loaded ImageNet labels:\\n', '\\n'.join(imagenet_labels[:10] + ['...'])\n\n# Load style labels to style_labels\nstyle_label_file = caffe_root + 'examples/finetune_flickr_style/style_names.txt'\nstyle_labels = list(np.loadtxt(style_label_file, str, delimiter='\\n'))\nif NUM_STYLE_LABELS > 0:\n style_labels = style_labels[:NUM_STYLE_LABELS]\nprint '\\nLoaded style labels:\\n', ', '.join(style_labels)",
"Loaded ImageNet labels:\nn01440764 tench, Tinca tinca\nn01443537 goldfish, Carassius auratus\nn01484850 great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias\nn01491361 tiger shark, Galeocerdo cuvieri\nn01494475 hammerhead, hammerhead shark\nn01496331 electric ray, crampfish, numbfish, torpedo\nn01498041 stingray\nn01514668 cock\nn01514859 hen\nn01518878 ostrich, Struthio camelus\n...\n\nLoaded style labels:\nDetailed, Pastel, Melancholy, Noir, HDR\n"
]
],
[
[
"### 2. Defining and running the nets\n\nWe'll start by defining `caffenet`, a function which initializes the *CaffeNet* architecture (a minor variant on *AlexNet*), taking arguments specifying the data and number of output classes.",
"_____no_output_____"
]
],
[
[
"from caffe import layers as L\nfrom caffe import params as P\n\nweight_param = dict(lr_mult=1, decay_mult=1)\nbias_param = dict(lr_mult=2, decay_mult=0)\nlearned_param = [weight_param, bias_param]\n\nfrozen_param = [dict(lr_mult=0)] * 2\n\ndef conv_relu(bottom, ks, nout, stride=1, pad=0, group=1,\n param=learned_param,\n weight_filler=dict(type='gaussian', std=0.01),\n bias_filler=dict(type='constant', value=0.1)):\n conv = L.Convolution(bottom, kernel_size=ks, stride=stride,\n num_output=nout, pad=pad, group=group,\n param=param, weight_filler=weight_filler,\n bias_filler=bias_filler)\n return conv, L.ReLU(conv, in_place=True)\n\ndef fc_relu(bottom, nout, param=learned_param,\n weight_filler=dict(type='gaussian', std=0.005),\n bias_filler=dict(type='constant', value=0.1)):\n fc = L.InnerProduct(bottom, num_output=nout, param=param,\n weight_filler=weight_filler,\n bias_filler=bias_filler)\n return fc, L.ReLU(fc, in_place=True)\n\ndef max_pool(bottom, ks, stride=1):\n return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride)\n\ndef caffenet(data, label=None, train=True, num_classes=1000,\n classifier_name='fc8', learn_all=False):\n \"\"\"Returns a NetSpec specifying CaffeNet, following the original proto text\n specification (./models/bvlc_reference_caffenet/train_val.prototxt).\"\"\"\n n = caffe.NetSpec()\n n.data = data\n param = learned_param if learn_all else frozen_param\n n.conv1, n.relu1 = conv_relu(n.data, 11, 96, stride=4, param=param)\n n.pool1 = max_pool(n.relu1, 3, stride=2)\n n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75)\n n.conv2, n.relu2 = conv_relu(n.norm1, 5, 256, pad=2, group=2, param=param)\n n.pool2 = max_pool(n.relu2, 3, stride=2)\n n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75)\n n.conv3, n.relu3 = conv_relu(n.norm2, 3, 384, pad=1, param=param)\n n.conv4, n.relu4 = conv_relu(n.relu3, 3, 384, pad=1, group=2, param=param)\n n.conv5, n.relu5 = conv_relu(n.relu4, 3, 256, pad=1, group=2, param=param)\n n.pool5 = max_pool(n.relu5, 3, stride=2)\n n.fc6, n.relu6 = fc_relu(n.pool5, 4096, param=param)\n if train:\n n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True)\n else:\n fc7input = n.relu6\n n.fc7, n.relu7 = fc_relu(fc7input, 4096, param=param)\n if train:\n n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True)\n else:\n fc8input = n.relu7\n # always learn fc8 (param=learned_param)\n fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=learned_param)\n # give fc8 the name specified by argument `classifier_name`\n n.__setattr__(classifier_name, fc8)\n if not train:\n n.probs = L.Softmax(fc8)\n if label is not None:\n n.label = label\n n.loss = L.SoftmaxWithLoss(fc8, n.label)\n n.acc = L.Accuracy(fc8, n.label)\n # write the net to a temporary file and return its filename\n with tempfile.NamedTemporaryFile(delete=False) as f:\n f.write(str(n.to_proto()))\n return f.name",
"_____no_output_____"
]
],
[
[
"Now, let's create a *CaffeNet* that takes unlabeled \"dummy data\" as input, allowing us to set its input images externally and see what ImageNet classes it predicts.",
"_____no_output_____"
]
],
[
[
"dummy_data = L.DummyData(shape=dict(dim=[1, 3, 227, 227]))\nimagenet_net_filename = caffenet(data=dummy_data, train=False)\nimagenet_net = caffe.Net(imagenet_net_filename, weights, caffe.TEST)",
"_____no_output_____"
]
],
[
[
"Define a function `style_net` which calls `caffenet` on data from the Flickr style dataset.\n\nThe new network will also have the *CaffeNet* architecture, with differences in the input and output:\n\n- the input is the Flickr style data we downloaded, provided by an `ImageData` layer\n- the output is a distribution over 20 classes rather than the original 1000 ImageNet classes\n- the classification layer is renamed from `fc8` to `fc8_flickr` to tell Caffe not to load the original classifier (`fc8`) weights from the ImageNet-pretrained model",
"_____no_output_____"
]
],
[
[
"def style_net(train=True, learn_all=False, subset=None):\n if subset is None:\n subset = 'train' if train else 'test'\n source = caffe_root + 'data/flickr_style/%s.txt' % subset\n transform_param = dict(mirror=train, crop_size=227,\n mean_file=caffe_root + 'data/ilsvrc12/imagenet_mean.binaryproto')\n style_data, style_label = L.ImageData(\n transform_param=transform_param, source=source,\n batch_size=50, new_height=256, new_width=256, ntop=2)\n return caffenet(data=style_data, label=style_label, train=train,\n num_classes=NUM_STYLE_LABELS,\n classifier_name='fc8_flickr',\n learn_all=learn_all)",
"_____no_output_____"
]
],
[
[
"Use the `style_net` function defined above to initialize `untrained_style_net`, a *CaffeNet* with input images from the style dataset and weights from the pretrained ImageNet model.\n\n\nCall `forward` on `untrained_style_net` to get a batch of style training data.",
"_____no_output_____"
]
],
[
[
"untrained_style_net = caffe.Net(style_net(train=False, subset='train'),\n weights, caffe.TEST)\nuntrained_style_net.forward()\nstyle_data_batch = untrained_style_net.blobs['data'].data.copy()\nstyle_label_batch = np.array(untrained_style_net.blobs['label'].data, dtype=np.int32)",
"_____no_output_____"
]
],
[
[
"Pick one of the style net training images from the batch of 50 (we'll arbitrarily choose #8 here). Display it, then run it through `imagenet_net`, the ImageNet-pretrained network to view its top 5 predicted classes from the 1000 ImageNet classes.\n\nBelow we chose an image where the network's predictions happen to be reasonable, as the image is of a beach, and \"sandbar\" and \"seashore\" both happen to be ImageNet-1000 categories. For other images, the predictions won't be this good, sometimes due to the network actually failing to recognize the object(s) present in the image, but perhaps even more often due to the fact that not all images contain an object from the (somewhat arbitrarily chosen) 1000 ImageNet categories. Modify the `batch_index` variable by changing its default setting of 8 to another value from 0-49 (since the batch size is 50) to see predictions for other images in the batch. (To go beyond this batch of 50 images, first rerun the *above* cell to load a fresh batch of data into `style_net`.)",
"_____no_output_____"
]
],
[
[
"def disp_preds(net, image, labels, k=5, name='ImageNet'):\n input_blob = net.blobs['data']\n net.blobs['data'].data[0, ...] = image\n probs = net.forward(start='conv1')['probs'][0]\n top_k = (-probs).argsort()[:k]\n print 'top %d predicted %s labels =' % (k, name)\n print '\\n'.join('\\t(%d) %5.2f%% %s' % (i+1, 100*probs[p], labels[p])\n for i, p in enumerate(top_k))\n\ndef disp_imagenet_preds(net, image):\n disp_preds(net, image, imagenet_labels, name='ImageNet')\n\ndef disp_style_preds(net, image):\n disp_preds(net, image, style_labels, name='style')",
"_____no_output_____"
],
[
"batch_index = 8\nimage = style_data_batch[batch_index]\nplt.imshow(deprocess_net_image(image))\nprint 'actual label =', style_labels[style_label_batch[batch_index]]",
"actual label = Melancholy\n"
],
[
"disp_imagenet_preds(imagenet_net, image)",
"top 5 predicted ImageNet labels =\n\t(1) 69.89% n09421951 sandbar, sand bar\n\t(2) 21.76% n09428293 seashore, coast, seacoast, sea-coast\n\t(3) 3.22% n02894605 breakwater, groin, groyne, mole, bulwark, seawall, jetty\n\t(4) 1.89% n04592741 wing\n\t(5) 1.23% n09332890 lakeside, lakeshore\n"
]
],
[
[
"We can also look at `untrained_style_net`'s predictions, but we won't see anything interesting as its classifier hasn't been trained yet.\n\nIn fact, since we zero-initialized the classifier (see `caffenet` definition -- no `weight_filler` is passed to the final `InnerProduct` layer), the softmax inputs should be all zero and we should therefore see a predicted probability of 1/N for each label (for N labels). Since we set N = 5, we get a predicted probability of 20% for each class.",
"_____no_output_____"
]
],
[
[
"disp_style_preds(untrained_style_net, image)",
"top 5 predicted style labels =\n\t(1) 20.00% Detailed\n\t(2) 20.00% Pastel\n\t(3) 20.00% Melancholy\n\t(4) 20.00% Noir\n\t(5) 20.00% HDR\n"
]
],
[
[
"We can also verify that the activations in layer `fc7` immediately before the classification layer are the same as (or very close to) those in the ImageNet-pretrained model, since both models are using the same pretrained weights in the `conv1` through `fc7` layers.",
"_____no_output_____"
]
],
[
[
"diff = untrained_style_net.blobs['fc7'].data[0] - imagenet_net.blobs['fc7'].data[0]\nerror = (diff ** 2).sum()\nassert error < 1e-8",
"_____no_output_____"
]
],
[
[
"Delete `untrained_style_net` to save memory. (Hang on to `imagenet_net` as we'll use it again later.)",
"_____no_output_____"
]
],
[
[
"del untrained_style_net",
"_____no_output_____"
]
],
[
[
"### 3. Training the style classifier\n\nNow, we'll define a function `solver` to create our Caffe solvers, which are used to train the network (learn its weights). In this function we'll set values for various parameters used for learning, display, and \"snapshotting\" -- see the inline comments for explanations of what they mean. You may want to play with some of the learning parameters to see if you can improve on the results here!",
"_____no_output_____"
]
],
[
[
"from caffe.proto import caffe_pb2\n\ndef solver(train_net_path, test_net_path=None, base_lr=0.001):\n s = caffe_pb2.SolverParameter()\n\n # Specify locations of the train and (maybe) test networks.\n s.train_net = train_net_path\n if test_net_path is not None:\n s.test_net.append(test_net_path)\n s.test_interval = 1000 # Test after every 1000 training iterations.\n s.test_iter.append(100) # Test on 100 batches each time we test.\n\n # The number of iterations over which to average the gradient.\n # Effectively boosts the training batch size by the given factor, without\n # affecting memory utilization.\n s.iter_size = 1\n \n s.max_iter = 100000 # # of times to update the net (training iterations)\n \n # Solve using the stochastic gradient descent (SGD) algorithm.\n # Other choices include 'Adam' and 'RMSProp'.\n s.type = 'SGD'\n\n # Set the initial learning rate for SGD.\n s.base_lr = base_lr\n\n # Set `lr_policy` to define how the learning rate changes during training.\n # Here, we 'step' the learning rate by multiplying it by a factor `gamma`\n # every `stepsize` iterations.\n s.lr_policy = 'step'\n s.gamma = 0.1\n s.stepsize = 20000\n\n # Set other SGD hyperparameters. Setting a non-zero `momentum` takes a\n # weighted average of the current gradient and previous gradients to make\n # learning more stable. L2 weight decay regularizes learning, to help prevent\n # the model from overfitting.\n s.momentum = 0.9\n s.weight_decay = 5e-4\n\n # Display the current training loss and accuracy every 1000 iterations.\n s.display = 1000\n\n # Snapshots are files used to store networks we've trained. Here, we'll\n # snapshot every 10K iterations -- ten times during training.\n s.snapshot = 10000\n s.snapshot_prefix = caffe_root + 'models/finetune_flickr_style/finetune_flickr_style'\n \n # Train on the GPU. Using the CPU to train large networks is very slow.\n s.solver_mode = caffe_pb2.SolverParameter.GPU\n \n # Write the solver to a temporary file and return its filename.\n with tempfile.NamedTemporaryFile(delete=False) as f:\n f.write(str(s))\n return f.name",
"_____no_output_____"
]
],
[
[
"Now we'll invoke the solver to train the style net's classification layer.\n\nFor the record, if you want to train the network using only the command line tool, this is the command:\n\n<code>\nbuild/tools/caffe train \\\n -solver models/finetune_flickr_style/solver.prototxt \\\n -weights models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel \\\n -gpu 0\n</code>\n\nHowever, we will train using Python in this example.\n\nWe'll first define `run_solvers`, a function that takes a list of solvers and steps each one in a round robin manner, recording the accuracy and loss values each iteration. At the end, the learned weights are saved to a file.",
"_____no_output_____"
]
],
[
[
"def run_solvers(niter, solvers, disp_interval=10):\n \"\"\"Run solvers for niter iterations,\n returning the loss and accuracy recorded each iteration.\n `solvers` is a list of (name, solver) tuples.\"\"\"\n blobs = ('loss', 'acc')\n loss, acc = ({name: np.zeros(niter) for name, _ in solvers}\n for _ in blobs)\n for it in range(niter):\n for name, s in solvers:\n s.step(1) # run a single SGD step in Caffe\n loss[name][it], acc[name][it] = (s.net.blobs[b].data.copy()\n for b in blobs)\n if it % disp_interval == 0 or it + 1 == niter:\n loss_disp = '; '.join('%s: loss=%.3f, acc=%2d%%' %\n (n, loss[n][it], np.round(100*acc[n][it]))\n for n, _ in solvers)\n print '%3d) %s' % (it, loss_disp) \n # Save the learned weights from both nets.\n weight_dir = tempfile.mkdtemp()\n weights = {}\n for name, s in solvers:\n filename = 'weights.%s.caffemodel' % name\n weights[name] = os.path.join(weight_dir, filename)\n s.net.save(weights[name])\n return loss, acc, weights",
"_____no_output_____"
]
],
[
[
"Let's create and run solvers to train nets for the style recognition task. We'll create two solvers -- one (`style_solver`) will have its train net initialized to the ImageNet-pretrained weights (this is done by the call to the `copy_from` method), and the other (`scratch_style_solver`) will start from a *randomly* initialized net.\n\nDuring training, we should see that the ImageNet pretrained net is learning faster and attaining better accuracies than the scratch net.",
"_____no_output_____"
]
],
[
[
"niter = 200 # number of iterations to train\n\n# Reset style_solver as before.\nstyle_solver_filename = solver(style_net(train=True))\nstyle_solver = caffe.get_solver(style_solver_filename)\nstyle_solver.net.copy_from(weights)\n\n# For reference, we also create a solver that isn't initialized from\n# the pretrained ImageNet weights.\nscratch_style_solver_filename = solver(style_net(train=True))\nscratch_style_solver = caffe.get_solver(scratch_style_solver_filename)\n\nprint 'Running solvers for %d iterations...' % niter\nsolvers = [('pretrained', style_solver),\n ('scratch', scratch_style_solver)]\nloss, acc, weights = run_solvers(niter, solvers)\nprint 'Done.'\n\ntrain_loss, scratch_train_loss = loss['pretrained'], loss['scratch']\ntrain_acc, scratch_train_acc = acc['pretrained'], acc['scratch']\nstyle_weights, scratch_style_weights = weights['pretrained'], weights['scratch']\n\n# Delete solvers to save memory.\ndel style_solver, scratch_style_solver, solvers",
"Running solvers for 200 iterations...\n 0) pretrained: loss=1.609, acc=28%; scratch: loss=1.609, acc=28%\n 10) pretrained: loss=1.293, acc=52%; scratch: loss=1.626, acc=14%\n 20) pretrained: loss=1.110, acc=56%; scratch: loss=1.646, acc=10%\n 30) pretrained: loss=1.084, acc=60%; scratch: loss=1.616, acc=20%\n 40) pretrained: loss=0.898, acc=64%; scratch: loss=1.588, acc=26%\n 50) pretrained: loss=1.024, acc=54%; scratch: loss=1.607, acc=32%\n 60) pretrained: loss=0.925, acc=66%; scratch: loss=1.616, acc=20%\n 70) pretrained: loss=0.861, acc=74%; scratch: loss=1.598, acc=24%\n 80) pretrained: loss=0.967, acc=60%; scratch: loss=1.588, acc=30%\n 90) pretrained: loss=1.274, acc=52%; scratch: loss=1.608, acc=20%\n100) pretrained: loss=1.113, acc=62%; scratch: loss=1.588, acc=30%\n110) pretrained: loss=0.922, acc=62%; scratch: loss=1.578, acc=36%\n120) pretrained: loss=0.918, acc=62%; scratch: loss=1.599, acc=20%\n130) pretrained: loss=0.959, acc=58%; scratch: loss=1.594, acc=22%\n140) pretrained: loss=1.228, acc=50%; scratch: loss=1.608, acc=14%\n150) pretrained: loss=0.727, acc=76%; scratch: loss=1.623, acc=16%\n160) pretrained: loss=1.074, acc=66%; scratch: loss=1.607, acc=20%\n170) pretrained: loss=0.887, acc=60%; scratch: loss=1.614, acc=20%\n180) pretrained: loss=0.961, acc=62%; scratch: loss=1.614, acc=18%\n190) pretrained: loss=0.737, acc=76%; scratch: loss=1.613, acc=18%\n199) pretrained: loss=0.836, acc=70%; scratch: loss=1.614, acc=16%\nDone.\n"
]
],
[
[
"Let's look at the training loss and accuracy produced by the two training procedures. Notice how quickly the ImageNet pretrained model's loss value (blue) drops, and that the randomly initialized model's loss value (green) barely (if at all) improves from training only the classifier layer.",
"_____no_output_____"
]
],
[
[
"plot(np.vstack([train_loss, scratch_train_loss]).T)\nxlabel('Iteration #')\nylabel('Loss')",
"_____no_output_____"
],
[
"plot(np.vstack([train_acc, scratch_train_acc]).T)\nxlabel('Iteration #')\nylabel('Accuracy')",
"_____no_output_____"
]
],
[
[
"Let's take a look at the testing accuracy after running 200 iterations of training. Note that we're classifying among 5 classes, giving chance accuracy of 20%. We expect both results to be better than chance accuracy (20%), and we further expect the result from training using the ImageNet pretraining initialization to be much better than the one from training from scratch. Let's see.",
"_____no_output_____"
]
],
[
[
"def eval_style_net(weights, test_iters=10):\n test_net = caffe.Net(style_net(train=False), weights, caffe.TEST)\n accuracy = 0\n for it in xrange(test_iters):\n accuracy += test_net.forward()['acc']\n accuracy /= test_iters\n return test_net, accuracy",
"_____no_output_____"
],
[
"test_net, accuracy = eval_style_net(style_weights)\nprint 'Accuracy, trained from ImageNet initialization: %3.1f%%' % (100*accuracy, )\nscratch_test_net, scratch_accuracy = eval_style_net(scratch_style_weights)\nprint 'Accuracy, trained from random initialization: %3.1f%%' % (100*scratch_accuracy, )",
"Accuracy, trained from ImageNet initialization: 50.0%\nAccuracy, trained from random initialization: 23.6%\n"
]
],
[
[
"### 4. End-to-end finetuning for style\n\nFinally, we'll train both nets again, starting from the weights we just learned. The only difference this time is that we'll be learning the weights \"end-to-end\" by turning on learning in *all* layers of the network, starting from the RGB `conv1` filters directly applied to the input image. We pass the argument `learn_all=True` to the `style_net` function defined earlier in this notebook, which tells the function to apply a positive (non-zero) `lr_mult` value for all parameters. Under the default, `learn_all=False`, all parameters in the pretrained layers (`conv1` through `fc7`) are frozen (`lr_mult = 0`), and we learn only the classifier layer `fc8_flickr`.\n\nNote that both networks start at roughly the accuracy achieved at the end of the previous training session, and improve significantly with end-to-end training. To be more scientific, we'd also want to follow the same additional training procedure *without* the end-to-end training, to ensure that our results aren't better simply because we trained for twice as long. Feel free to try this yourself!",
"_____no_output_____"
]
],
[
[
"end_to_end_net = style_net(train=True, learn_all=True)\n\n# Set base_lr to 1e-3, the same as last time when learning only the classifier.\n# You may want to play around with different values of this or other\n# optimization parameters when fine-tuning. For example, if learning diverges\n# (e.g., the loss gets very large or goes to infinity/NaN), you should try\n# decreasing base_lr (e.g., to 1e-4, then 1e-5, etc., until you find a value\n# for which learning does not diverge).\nbase_lr = 0.001\n\nstyle_solver_filename = solver(end_to_end_net, base_lr=base_lr)\nstyle_solver = caffe.get_solver(style_solver_filename)\nstyle_solver.net.copy_from(style_weights)\n\nscratch_style_solver_filename = solver(end_to_end_net, base_lr=base_lr)\nscratch_style_solver = caffe.get_solver(scratch_style_solver_filename)\nscratch_style_solver.net.copy_from(scratch_style_weights)\n\nprint 'Running solvers for %d iterations...' % niter\nsolvers = [('pretrained, end-to-end', style_solver),\n ('scratch, end-to-end', scratch_style_solver)]\n_, _, finetuned_weights = run_solvers(niter, solvers)\nprint 'Done.'\n\nstyle_weights_ft = finetuned_weights['pretrained, end-to-end']\nscratch_style_weights_ft = finetuned_weights['scratch, end-to-end']\n\n# Delete solvers to save memory.\ndel style_solver, scratch_style_solver, solvers",
"Running solvers for 200 iterations...\n 0) pretrained, end-to-end: loss=0.781, acc=64%; scratch, end-to-end: loss=1.585, acc=28%\n 10) pretrained, end-to-end: loss=1.178, acc=62%; scratch, end-to-end: loss=1.638, acc=14%\n 20) pretrained, end-to-end: loss=1.084, acc=60%; scratch, end-to-end: loss=1.637, acc= 8%\n 30) pretrained, end-to-end: loss=0.902, acc=76%; scratch, end-to-end: loss=1.600, acc=20%\n 40) pretrained, end-to-end: loss=0.865, acc=64%; scratch, end-to-end: loss=1.574, acc=26%\n 50) pretrained, end-to-end: loss=0.888, acc=60%; scratch, end-to-end: loss=1.604, acc=26%\n 60) pretrained, end-to-end: loss=0.538, acc=78%; scratch, end-to-end: loss=1.555, acc=34%\n 70) pretrained, end-to-end: loss=0.717, acc=72%; scratch, end-to-end: loss=1.563, acc=30%\n 80) pretrained, end-to-end: loss=0.695, acc=74%; scratch, end-to-end: loss=1.502, acc=42%\n 90) pretrained, end-to-end: loss=0.708, acc=68%; scratch, end-to-end: loss=1.523, acc=26%\n100) pretrained, end-to-end: loss=0.432, acc=78%; scratch, end-to-end: loss=1.500, acc=38%\n110) pretrained, end-to-end: loss=0.611, acc=78%; scratch, end-to-end: loss=1.618, acc=18%\n120) pretrained, end-to-end: loss=0.610, acc=76%; scratch, end-to-end: loss=1.473, acc=30%\n130) pretrained, end-to-end: loss=0.471, acc=78%; scratch, end-to-end: loss=1.488, acc=26%\n140) pretrained, end-to-end: loss=0.500, acc=76%; scratch, end-to-end: loss=1.514, acc=38%\n150) pretrained, end-to-end: loss=0.476, acc=80%; scratch, end-to-end: loss=1.452, acc=46%\n160) pretrained, end-to-end: loss=0.368, acc=82%; scratch, end-to-end: loss=1.419, acc=34%\n170) pretrained, end-to-end: loss=0.556, acc=76%; scratch, end-to-end: loss=1.583, acc=36%\n180) pretrained, end-to-end: loss=0.574, acc=72%; scratch, end-to-end: loss=1.556, acc=22%\n190) pretrained, end-to-end: loss=0.360, acc=88%; scratch, end-to-end: loss=1.429, acc=44%\n199) pretrained, end-to-end: loss=0.458, acc=78%; scratch, end-to-end: loss=1.370, acc=44%\nDone.\n"
]
],
[
[
"Let's now test the end-to-end finetuned models. Since all layers have been optimized for the style recognition task at hand, we expect both nets to get better results than the ones above, which were achieved by nets with only their classifier layers trained for the style task (on top of either ImageNet pretrained or randomly initialized weights).",
"_____no_output_____"
]
],
[
[
"test_net, accuracy = eval_style_net(style_weights_ft)\nprint 'Accuracy, finetuned from ImageNet initialization: %3.1f%%' % (100*accuracy, )\nscratch_test_net, scratch_accuracy = eval_style_net(scratch_style_weights_ft)\nprint 'Accuracy, finetuned from random initialization: %3.1f%%' % (100*scratch_accuracy, )",
"Accuracy, finetuned from ImageNet initialization: 53.6%\nAccuracy, finetuned from random initialization: 39.2%\n"
]
],
[
[
"We'll first look back at the image we started with and check our end-to-end trained model's predictions.",
"_____no_output_____"
]
],
[
[
"plt.imshow(deprocess_net_image(image))\ndisp_style_preds(test_net, image)",
"top 5 predicted style labels =\n\t(1) 55.67% Melancholy\n\t(2) 27.21% HDR\n\t(3) 16.46% Pastel\n\t(4) 0.63% Detailed\n\t(5) 0.03% Noir\n"
]
],
[
[
"Whew, that looks a lot better than before! But note that this image was from the training set, so the net got to see its label at training time.\n\nFinally, we'll pick an image from the test set (an image the model hasn't seen) and look at our end-to-end finetuned style model's predictions for it.",
"_____no_output_____"
]
],
[
[
"batch_index = 1\nimage = test_net.blobs['data'].data[batch_index]\nplt.imshow(deprocess_net_image(image))\nprint 'actual label =', style_labels[int(test_net.blobs['label'].data[batch_index])]",
"actual label = Pastel\n"
],
[
"disp_style_preds(test_net, image)",
"top 5 predicted style labels =\n\t(1) 99.76% Pastel\n\t(2) 0.13% HDR\n\t(3) 0.11% Detailed\n\t(4) 0.00% Melancholy\n\t(5) 0.00% Noir\n"
]
],
[
[
"We can also look at the predictions of the network trained from scratch. We see that in this case, the scratch network also predicts the correct label for the image (*Pastel*), but is much less confident in its prediction than the pretrained net.",
"_____no_output_____"
]
],
[
[
"disp_style_preds(scratch_test_net, image)",
"top 5 predicted style labels =\n\t(1) 49.81% Pastel\n\t(2) 19.76% Detailed\n\t(3) 17.06% Melancholy\n\t(4) 11.66% HDR\n\t(5) 1.72% Noir\n"
]
],
[
[
"Of course, we can again look at the ImageNet model's predictions for the above image:",
"_____no_output_____"
]
],
[
[
"disp_imagenet_preds(imagenet_net, image)",
"top 5 predicted ImageNet labels =\n\t(1) 34.90% n07579787 plate\n\t(2) 21.63% n04263257 soup bowl\n\t(3) 17.75% n07875152 potpie\n\t(4) 5.72% n07711569 mashed potato\n\t(5) 5.27% n07584110 consomme\n"
]
],
[
[
"So we did finetuning and it is awesome. Let's take a look at what kind of results we are able to get with a longer, more complete run of the style recognition dataset. Note: the below URL might be occasionally down because it is run on a research machine.\n\nhttp://demo.vislab.berkeleyvision.org/",
"_____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"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbd4bd7d0b40633cbef2f21393728bc68a8679d4
| 2,067 |
ipynb
|
Jupyter Notebook
|
20-CLEAN.ipynb
|
danielmiodovnik/FrontDoorDataCollaboration
|
1a89143e64b329838bae76616ae147b6143d8557
|
[
"MIT"
] | 7 |
2020-01-30T18:18:08.000Z
|
2020-03-31T07:19:10.000Z
|
20-annexa-CLEAN.ipynb
|
CSCDP/AnnexA_CiNCensus_Cleaner
|
335ceeab69829214e94477bbc5ca072dc9462c99
|
[
"MIT"
] | 1 |
2020-01-30T18:21:53.000Z
|
2020-01-30T18:21:53.000Z
|
20-annexa-CLEAN.ipynb
|
CSCDP/AnnexA_CiNCensus_Cleaner
|
335ceeab69829214e94477bbc5ca072dc9462c99
|
[
"MIT"
] | 2 |
2019-12-22T13:21:10.000Z
|
2020-01-31T11:13:07.000Z
| 21.091837 | 113 | 0.538945 |
[
[
[
"# 20-CLEAN",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"import os\nimport sys\nimport logging\nfrom fddc.config import Config\nfrom fddc.annex_a.cleaner import clean",
"_____no_output_____"
],
[
"logger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nlogging.debug(\"This is just to get loggin to work - it seems to refuse to log unless you log something!\")",
"_____no_output_____"
],
[
"# Set paths\n\nconfig = Config(\"config/data-map.yml\")\n\n# Full path to the input file that should be cleaned\nconfig[\"input_file\"] = \"merged.xlsx\"\n\n# Full path to the output file that will hold the cleaned data\nconfig[\"output_file\"] = \"cleaned.xlsx\"\n\n# Full path to a file holding a report of how the matching was performed\nconfig[\"matching_report_file\"] = \"matching_report.xlsx\"",
"_____no_output_____"
],
[
"# Launch cleaning\n\nclean(**config)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbd4be17b6949f7d695c42e33de58046aa7629d6
| 391,434 |
ipynb
|
Jupyter Notebook
|
content/Homework/HW4/cs109a_HW4_solutions.ipynb
|
gurdeep101/2019-CS109A
|
46000db9e36c71534788ed00cca988305e8e3ee9
|
[
"MIT"
] | null | null | null |
content/Homework/HW4/cs109a_HW4_solutions.ipynb
|
gurdeep101/2019-CS109A
|
46000db9e36c71534788ed00cca988305e8e3ee9
|
[
"MIT"
] | null | null | null |
content/Homework/HW4/cs109a_HW4_solutions.ipynb
|
gurdeep101/2019-CS109A
|
46000db9e36c71534788ed00cca988305e8e3ee9
|
[
"MIT"
] | null | null | null | 117.406719 | 85,016 | 0.816255 |
[
[
[
"\n# <img style=\"float: left; padding-right: 10px; width: 45px\" src=\"https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/iacs.png\"> CS109A Introduction to Data Science\n\n## Homework 4: Logistic Regression\n\n**Harvard University**<br/>\n**Fall 2019**<br/>\n**Instructors**: Pavlos Protopapas, Kevin Rader, and Chris Tanner\n\n<hr style=\"height:2pt\">\n\n",
"_____no_output_____"
]
],
[
[
"#RUN THIS CELL \nimport requests\nfrom IPython.core.display import HTML\nstyles = requests.get(\"https://raw.githubusercontent.com/Harvard-IACS/2018-CS109A/master/content/styles/cs109.css\").text\nHTML(styles)",
"_____no_output_____"
]
],
[
[
"### INSTRUCTIONS\n\n- **This is an individual homework. No group collaboration.**\n- To submit your assignment, follow the instructions given in Canvas.\n- Restart the kernel and run the whole notebook again before you submit. \n- As much as possible, try and stick to the hints and functions we import at the top of the homework, as those are the ideas and tools the class supports and are aiming to teach. And if a problem specifies a particular library, you're required to use that library, and possibly others from the import list.\n- Please use .head() when viewing data. Do not submit a notebook that is excessively long because output was not suppressed or otherwise limited. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom sklearn.linear_model import LassoCV\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport zipfile\n\n\nimport seaborn as sns\nsns.set()\n\nfrom scipy.stats import ttest_ind",
"_____no_output_____"
]
],
[
[
"<div class='theme'> Cancer Classification from Gene Expressions </div>\n\nIn this problem, we will build a classification model to distinguish between two related classes of cancer, acute lymphoblastic leukemia (ALL) and acute myeloid leukemia (AML), using gene expression measurements. The dataset is provided in the file `data/dataset_hw4.csv`. Each row in this file corresponds to a tumor tissue sample from a patient with one of the two forms of Leukemia. The first column contains the cancer type, with **0 indicating the ALL** class and **1 indicating the AML** class. Columns 2-7130 contain expression levels of 7129 genes recorded from each tissue sample. \n\nIn the following questions, we will use linear and logistic regression to build classification models for this data set. \n",
"_____no_output_____"
],
[
"<div class='exercise'><b> Question 1 [20 pts]: Data Exploration </b></div>\n\nThe first step is to split the observations into an approximate 80-20 train-test split. Below is some code to do this for you (we want to make sure everyone has the same splits). Print dataset shape before splitting and after splitting. `Cancer_type` is our target column.\n\n\n**1.1** Take a peek at your training set: you should notice the severe differences in the measurements from one gene to the next (some are negative, some hover around zero, and some are well into the thousands). To account for these differences in scale and variability, normalize each predictor to vary between 0 and 1. **NOTE: for the entirety of this homework assignment, you will use these normalized values, not the original, raw values**.\n\n\n**1.2** The training set contains more predictors than observations. What problem(s) can this lead to in fitting a classification model to such a dataset? Explain in 3 or fewer sentences.\n\n\n**1.3** Determine which 10 genes individually discriminate between the two cancer classes the best (consider every gene in the dataset).\n\nPlot two histograms of best predictor -- one using the training set and another using the testing set. Each histogram should clearly distinguish two different `Cancer_type` classes.\n\n**Hint:** You may use t-testing to make this determination: #https://en.wikipedia.org/wiki/Welch%27s_t-test .\n\n\n**1.4** Using your most useful gene from the previous part, create a classification model by simply eye-balling a value for this gene that would discriminate the two classes the best (do not use an algorithm to determine for you the optimal coefficient or threshold; we are asking you to provide a rough estimate / model by manual inspection). Justify your choice in 1-2 sentences. Report the accuracy of your hand-chosen model on the test set (write code to implement and evaluate your hand-created model).\n\n<hr> <hr>",
"_____no_output_____"
],
[
"<hr>\n\n### Solutions",
"_____no_output_____"
],
[
"**The first step is to split the observations into an approximate 80-20 train-test split. Below is some code to do this for you (we want to make sure everyone has the same splits). Print dataset shape before splitting and after splitting. `Cancer_type` is our target column.**",
"_____no_output_____"
]
],
[
[
"np.random.seed(10)\ndf = pd.read_csv('data/hw4_enhance.csv', index_col=0)\nX_train, X_test, y_train, y_test = train_test_split(df.loc[:, df.columns != 'Cancer_type'], \n df.Cancer_type, test_size=0.2, \n random_state = 109, \n stratify = df.Cancer_type)",
"_____no_output_____"
],
[
"print(df.shape)\nprint(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\nprint(df.Cancer_type.value_counts(normalize=True))",
"(752, 7130)\n(601, 7129) (151, 7129) (601,) (151,)\n0.0 0.511968\n1.0 0.488032\nName: Cancer_type, dtype: float64\n"
]
],
[
[
"**1.1 Take a peek at your training set: you should notice the severe differences in the measurements from one gene to the next (some are negative, some hover around zero, and some are well into the thousands). To account for these differences in scale and variability, normalize each predictor to vary between 0 and 1. **NOTE: for the entirety of this homework assignment, you will use these normalized values, not the original, raw values.**\n",
"_____no_output_____"
]
],
[
[
"#your code here\nX_train.describe()",
"_____no_output_____"
],
[
"#your code here\nmin_vals = X_train.min()\nmax_vals = X_train.max()\n\nX_train = (X_train - min_vals)/(max_vals - min_vals)\nX_test = (X_test - min_vals)/(max_vals - min_vals)",
"_____no_output_____"
]
],
[
[
"**1.2 The training set contains more predictors than observations. What problem(s) can this lead to in fitting a classification model to such a dataset? Explain in 3 or fewer sentences.**",
"_____no_output_____"
],
[
"*your answer here*\n\n\np>>n - Linear Regression and Logisitic Regression does not work. We need to regularize or reduce dimensions. \n\nThe training set is improper as it contains many more columns compared to number of samples. If we fit models to the given dataset, they will be highly overfitted. This is called the curse of dimensionality.\n\nMulticollinearity",
"_____no_output_____"
],
[
"**1.3 Determine which 10 genes individually discriminate between the two cancer classes the best (consider every gene in the dataset).**\n\n**Plot two histograms of best predictor -- one using the training set and another using the testing set. Each histogram should clearly distinguish two different `Cancer_type` classes.**\n\n**Hint:** You may use t-testing to make this determination: #https://en.wikipedia.org/wiki/Welch%27s_t-test.",
"_____no_output_____"
]
],
[
[
"#your code here\npredictors = df.columns\npredictors = predictors.drop('Cancer_type');\nprint(predictors.shape) \n\nmeans_0 = X_train[y_train==0][predictors].mean()\nmeans_1 = X_train[y_train==1][predictors].mean()\nstds_0 = X_train[y_train==0][predictors].std()\nstds_1 = X_train[y_train==1][predictors].std()\nn1 = X_train[y_train==0].shape[0]\nn2 = X_train[y_train==1].shape[0]\n\nt_tests = np.abs(means_0-means_1)/np.sqrt( stds_0**2/n1 + stds_1**2/n2) \n#your code here\nbest_preds_idx = np.argsort(-t_tests.values)\nbest_preds = t_tests.index[best_preds_idx]\n\nprint(t_tests[best_preds_idx[0:10]])\nprint(t_tests.index[best_preds_idx[0:10]])\n\nbest_pred = t_tests.index[best_preds_idx[0]]\nprint(best_pred)",
"(7129,)\nM31523_at 12.537397\nX95735_at 12.435494\nM84526_at 11.870642\nX61587_at 11.458105\nU50136_rna1_at 10.986655\nX17042_at 10.666939\nU29175_at 10.487500\nY08612_at 10.299221\nZ11793_at 10.081967\nX76648_at 10.024521\ndtype: float64\nIndex(['M31523_at', 'X95735_at', 'M84526_at', 'X61587_at', 'U50136_rna1_at',\n 'X17042_at', 'U29175_at', 'Y08612_at', 'Z11793_at', 'X76648_at'],\n dtype='object')\nM31523_at\n"
],
[
"#your code here\nplt.figure(figsize=(12,8))\nplt.subplot(211)\nplt.hist( X_train[y_train==0][best_pred], bins=10, label='Class 0')\nplt.hist( X_train[y_train==1][best_pred],bins=30, label='Class 1')\nplt.title(best_pred + \" train\")\nplt.legend()\nplt.subplot(212)\nplt.hist( X_test[y_test==0][best_pred], bins=30,label='Class 0')\nplt.hist( X_test[y_test==1][best_pred], bins=30, label='Class 1')\nplt.title(best_pred + \" test\")\nplt.legend();",
"_____no_output_____"
],
[
"# #your code here\n# from scipy.stats import ttest_ind\n\n# predictors = df.columns\n# predictors = predictors.drop('Cancer_type');\n# print(predictors.shape) \n\n# t_tests = ttest_ind(X_train[y_train==0],X_train[y_train==1],equal_var=False)\n# best_preds_idx_t_tests = np.argsort(t_tests.pvalue)\n\n# predictors[best_preds_idx_t_tests][0:15]\n\n# # (7129,)\n# # Index(['M31523_at', 'X95735_at', 'M84526_at', 'X61587_at', 'U50136_rna1_at',\n# # 'X17042_at', 'U29175_at', 'Y08612_at', 'Z11793_at', 'J04615_at',\n# # 'X76648_at', 'U72936_s_at', 'M80254_at', 'M29551_at', 'X62320_at'],\n# # dtype='object')",
"_____no_output_____"
]
],
[
[
"**1.4 Using your most useful gene from the previous part, create a classification model by simply eye-balling a value for this gene that would discriminate the two classes the best (do not use an algorithm to determine for you the optimal coefficient or threshold; we are asking you to provide a rough estimate / model by manual inspection). Justify your choice in 1-2 sentences. Report the accuracy of your hand-chosen model on the test set (write code to implement and evaluate your hand-created model)**\n",
"_____no_output_____"
]
],
[
[
"#your code here\nthreshold = 0.45\n\ntrain_score = accuracy_score(y_train.values, X_train[best_pred]<=threshold) #Check this!\ntest_score = accuracy_score(y_test.values, X_test[best_pred]<=threshold)\nresults = [['naive train', train_score], ['naive test', test_score]] \n \n\ndf_res = pd.DataFrame.from_dict(results)\ndf_res",
"_____no_output_____"
]
],
[
[
"By observing the distribution of 'M31523_at' in the training histogram above, we roughly estimate that 0.45 distinguishes the two classes, so we use the threshold of 0.45. ",
"_____no_output_____"
],
[
"<div class='exercise'><b> Question 2 [25 pts]: Linear and Logistic Regression </b></div>\n\nIn class, we discussed how to use both linear regression and logistic regression for classification. For this question, you will explore these two models by working with the single gene that you identified above as being the best predictor.\n\n**2.1** Fit a simple linear regression model to the training set using the single gene predictor \"best_predictor\" to predict cancer type (use the normalized values of the gene). We could interpret the scores predicted by the regression model for a patient as being an estimate of the probability that the patient has Cancer_type=1 (AML). Is this a reasonable interpretation? If not, what is the problem with such?\n\nCreate a figure with the following items displayed on the same plot (Use training data):\n - the model's predicted value (the quantitative response from your linear regression model as a function of the normalized value of the best gene predictor)\n - the true binary response. \n\n**2.2** Use your estimated linear regression model to classify observations into 0 and 1 using the standard Bayes classifier. Evaluate the classification accuracy of this classification model on both the training and testing sets.\n\n**2.3** Next, fit a simple logistic regression model to the training set. How do the training and test classification accuracies of this model compare with the linear regression model? \n\nRemember, you need to set the regularization parameter for sklearn's logistic regression function to be a very large value in order to **not** regularize (use 'C=100000'). \n\n\n**2.4** \nPrint and interpret Logistic regression coefficient and intercept. \n\n\nCreate 2 plots (with training and testing data) with 4 items displayed on each plot.\n- the quantitative response from the linear regression model as a function of the best gene predictor.\n- the predicted probabilities of the logistic regression model as a function of the best gene predictor. \n- the true binary response. \n- a horizontal line at $y=0.5$. \n\nBased on these plots, does one of the models appear better suited for binary classification than the other? Explain in 3 sentences or fewer. \n\n",
"_____no_output_____"
],
[
"<hr>\n\n### Solutions",
"_____no_output_____"
],
[
"**2.1 Fit a simple linear regression model to the training set using the single gene predictor \"best_predictor\" to predict cancer type (use the normalized values of the gene). We could interpret the scores predicted by the regression model for a patient as being an estimate of the probability that the patient has Cancer_type=1 (AML). Is this a reasonable interpretation? If not, what is the problem with such?**\n\n**Create a figure with the following items displayed on the same plot (Use training data):**\n - the model's predicted value (the quantitative response from your linear regression model as a function of the normalized value of the best gene predictor)\n - the true binary response.",
"_____no_output_____"
]
],
[
[
"# your code here\nprint(best_pred)\n\nlinreg = LinearRegression()\nlinreg.fit(X_train[best_pred].values.reshape(-1,1), y_train)\n\ny_train_pred = linreg.predict(X_train[best_pred].values.reshape(-1,1))\ny_test_pred = linreg.predict(X_test[best_pred].values.reshape(-1,1))\n",
"M31523_at\n"
],
[
"# your code here\nfig = plt.figure();\nhost = fig.add_subplot(111)\npar1 = host.twinx()\n\nhost.set_ylabel(\"Probability\")\npar1.set_ylabel(\"Class\")\n\nhost.plot(X_train[best_pred], y_train_pred, '-');\nhost.plot(X_train[best_pred], y_train, 's');\nhost.set_xlabel('Normalized best_pred')\nhost.set_ylabel('Probability of being ALM')\n\nlabels = ['ALL', 'ALM'];\n\n# You can specify a rotation for the tick labels in degrees or with keywords.\npar1.set_yticks( [0.082, 0.81]);\npar1.set_yticklabels(labels);",
"_____no_output_____"
]
],
[
[
"*your answer here* \n\nYes there is a problem with interpretation - seems like our probabilities are <0 and >1. ",
"_____no_output_____"
],
[
"**2.2 Use your estimated linear regression model to classify observations into 0 and 1 using the standard Bayes classifier. Evaluate the classification accuracy of this classification model on both the training and testing sets.**",
"_____no_output_____"
]
],
[
[
"# your code here\ntrain_score = accuracy_score(y_train, y_train_pred>0.5)\ntest_score = accuracy_score(y_test, y_test_pred>0.5)\n\nprint(\"train score:\", train_score, \"test score:\", test_score)\ndf_res = df_res.append([['Linear Regression train', train_score], ['Linear Regression test', test_score]] )\ndf_res",
"train score: 0.7088186356073212 test score: 0.6887417218543046\n"
]
],
[
[
"\n**2.3** **Next, fit a simple logistic regression model to the training set. How do the training and test classification accuracies of this model compare with the linear regression model? Are the classifications substantially different? Explain why this is the case.**\n\n**Remember, you need to set the regularization parameter for sklearn's logistic regression function to be a very large value in order to **not** regularize (use 'C=100000').",
"_____no_output_____"
]
],
[
[
"# your code here\nlogreg = LogisticRegression(C=100000, solver='lbfgs')\nlogreg.fit(X_train[[best_pred]], y_train) \n\ny_train_pred_logreg = logreg.predict(X_train[[best_pred]])\ny_test_pred_logreg = logreg.predict(X_test[[best_pred]])\n\ny_train_pred_logreg_prob = logreg.predict_proba(X_train[[best_pred]])[:,1]\ny_test_pred_logreg_prob = logreg.predict_proba(X_test[[best_pred]])[:,1]\n\ntrain_score_logreg = accuracy_score(y_train, y_train_pred_logreg)\ntest_score_logreg = accuracy_score(y_test, y_test_pred_logreg)\n\nprint(\"train score:\", train_score_logreg, \"test score:\", test_score_logreg)\n\ndf_res = df_res.append([['Logistic Regression train', train_score_logreg], ['Logistic Regression test', test_score_logreg]] )\ndf_res",
"train score: 0.7071547420965059 test score: 0.7086092715231788\n"
]
],
[
[
"*your answer here* \n\nResults are not significantly different. ",
"_____no_output_____"
],
[
"**2.4 Print and interpret Logistic regression coefficient and intercept.**\n\n**Create 2 plots (with training and testing data) with 4 items displayed on each plot.**\n- the quantitative response from the linear regression model as a function of the best gene predictor.\n- the predicted probabilities of the logistic regression model as a function of the best gene predictor. \n- the true binary response. \n- a horizontal line at $y=0.5$. \n\n**Based on these plots, does one of the models appear better suited for binary classification than the other? Explain in 3 sentences or fewer.**\n",
"_____no_output_____"
],
[
"$ \\hat{p}(X) = \\frac{e^{\\hat{\\beta_0}+\\hat{\\beta_1}X_1 } }{1 + e^{\\hat{\\beta_0}+\\hat{\\beta_1}X_1 }} $",
"_____no_output_____"
]
],
[
[
"# your code here\nlogreg.intercept_, logreg.coef_, -logreg.intercept_/logreg.coef_",
"_____no_output_____"
]
],
[
[
"The slope is how steep is the sigmoid function is. Negative slope indicates probability of predicting y = 1 decreases as X gets larger. The intercept offers an indication of how much right or left shifted the curve (inflection point) is by -intercept/slope: the curve is approx 0.4656 to the right in this case.",
"_____no_output_____"
]
],
[
[
"print(\"Intercept:\",logreg.intercept_)\nprob = logreg.predict_proba(np.array([0]).reshape(-1,1))[0,1] #Predictions when best_pred = 0 \nprint(\"When %s is 0, log odds are %.5f \"%(best_pred,logreg.intercept_))\nprint(\"In other words, we predict `cancer_type` with %.5f probability \"%(prob))\n#np.exp(4.07730445)/(1+np.exp(4.07730445)) = 0.98333\n",
"Intercept: [4.07730445]\nWhen M31523_at is 0, log odds are 4.07730 \nIn other words, we predict `cancer_type` with 0.98333 probability \n"
],
[
"print(\"Coefficient: \",logreg.coef_) \n\nprint(\"A one-unit increase in coefficient (%s) is associated with an increase in the odds of `cancer_type` by %.5f\"%(best_pred,np.exp(logreg.coef_)))\n \n\n#print(\"A one-unit increase in coefficient (%s) is associated with an increase in the log odds of `cancer_type` by %.5f\"%(best_pred,logreg.coef_))\n#Explanation \n# #Assume best_pred = 0.48\n# prob = logreg.predict_proba(np.array([0.48]).reshape(-1,1))[0,1]\n# print(\"Prob. when best_pred is 0.48 = \",prob) \n# print(\"Log odds when best_pred is 0.48 = \", np.log(prob/(1-prob)))\n\n# #Increase best_pred by 1, best_pred = 1.48\n# prob1 = logreg.predict_proba(np.array([1.48]).reshape(-1,1))[0,1]\n# print(\"Prob. when best_pred is 1.48 = \",prob1) \n# print(\"Log odds when best_pred is 1.48 = \", np.log(prob1/(1-prob1)))\n\n# np.log(prob1/(1-prob1)) - (np.log(prob/(1-prob))) #coefficient",
"Coefficient: [[-8.75716206]]\nA one-unit increase in coefficient (M31523_at) is associated with an increase in the odds of `cancer_type` by 0.00016\n"
],
[
"# your code here \nfig, ax = plt.subplots(1,2, figsize=(16,5))\nsort_index = np.argsort(X_train[best_pred].values)\n\n# plotting true binary response\nax[0].scatter(X_train[best_pred].iloc[sort_index].values, y_train.iloc[sort_index].values, color='red', label = 'Train True Response')\n# plotting ols output\nax[0].plot(X_train[best_pred].iloc[sort_index].values, y_train_pred[sort_index], color='red', alpha=0.3, \\\n label = 'Linear Regression Predictions')\n# plotting logreg prob output\nax[0].plot(X_train[best_pred].iloc[sort_index].values, y_train_pred_logreg_prob[sort_index], alpha=0.3, \\\n color='green', label = 'Logistic Regression Predictions Prob')\n\nax[0].axhline(0.5, c='c')\nax[0].legend()\nax[0].set_title('Train - True response v/s obtained responses')\nax[0].set_xlabel('Gene predictor value')\nax[0].set_ylabel('Cancer type response');\n\n# Test\nsort_index = np.argsort(X_test[best_pred].values)\n\n# plotting true binary response\nax[1].scatter(X_test[best_pred].iloc[sort_index].values, y_test.iloc[sort_index].values, color='black', label = 'Test True Response')\n\n# plotting ols output\nax[1].plot(X_test[best_pred].iloc[sort_index].values, y_test_pred[sort_index], color='red', alpha=0.3, \\\n label = 'Linear Regression Predictions')\n\n# plotting logreg prob output\nax[1].plot(X_test[best_pred].iloc[sort_index].values, y_test_pred_logreg_prob[sort_index], alpha=0.3, \\\n color='green', label = 'Logistic Regression Predictions Prob')\n\nax[1].axhline(0.5, c='c')\nax[1].legend()\nax[1].set_title('Test - True response v/s obtained responses')\nax[1].set_xlabel('Gene predictor value')\nax[1].set_ylabel('Cancer type response');",
"_____no_output_____"
]
],
[
[
"Logistic Regression is better suited for this problem, our probabilities are within the range as expected. ",
"_____no_output_____"
],
[
"<div class='exercise'> <b> Question 3 [20pts]: Multiple Logistic Regression </b> </div>\n\n\n**3.1** Next, fit a multiple logistic regression model with **all** the gene predictors from the data set (reminder: for this assignment, we are always using the normalized values). How does the classification accuracy of this model compare with the models fitted in question 2 with a single gene (on both the training and test sets)? \n\n\n**3.2** How many of the coefficients estimated by this multiple logistic regression in the previous part (P3.1) are significantly different from zero at a *significance level of 5%*? Use the same value of C=100000 as before.\n\n**Hint:** To answer this question, use *bootstrapping* with 100 bootstrap samples/iterations. \n\n\n**3.3** Comment on the classification accuracy of both the training and testing set. Given the results above, how would you assess the generalization capacity of your trained model? What other tests would you suggest to better guard against possibly having a false sense of the overall efficacy/accuracy of the model as a whole?\n\n**3.4** Now let's use regularization to improve the predictions from the multiple logistic regression model. Specifically, use LASSO-like regularization and cross-validation to train the model on the training set. Report the classification accuracy on both the training and testing set.\n\n**3.5** Do the 10 best predictors from Q1 hold up as important features in this regularized model? If not, explain why this is the case (feel free to use the data to support your explanation).",
"_____no_output_____"
],
[
"<hr>\n### Solutions",
"_____no_output_____"
],
[
"**3.1 Next, fit a multiple logistic regression model with all the gene predictors from the data set (reminder: for this assignment, we are always using the normalized values). How does the classification accuracy of this model compare with the models fitted in question 2 with a single gene (on both the training and test sets)?** \n",
"_____no_output_____"
]
],
[
[
"# your code here\n# fitting multi regression model\nmulti_regr = LogisticRegression(C=100000, solver = \"lbfgs\", max_iter=10000, random_state=109)\nmulti_regr.fit(X_train, y_train)\n\n# predictions\ny_train_pred_multi = multi_regr.predict(X_train) \ny_test_pred_multi = multi_regr.predict(X_test)\n\n# accuracy\ntrain_score_multi = accuracy_score(y_train, y_train_pred_multi)\ntest_score_multi = accuracy_score(y_test, y_test_pred_multi)\n\nprint('Training set accuracy for multiple logistic regression = ', train_score_multi)\nprint('Test set accuracy for multiple logistic regression = ', test_score_multi)\n\ndf_res = df_res.append([['Multiple Logistic Regression train', train_score_multi],\n ['Multiple Logistic Regression test', test_score_multi]] )\ndf_res",
"Training set accuracy for multiple logistic regression = 1.0\nTest set accuracy for multiple logistic regression = 0.7682119205298014\n"
]
],
[
[
"*your answer here* \n\nBetter results, overfitted model.",
"_____no_output_____"
],
[
"**3.2** **How many of the coefficients estimated by this multiple logistic regression in the previous part (P3.1) are significantly different from zero at a *significance level of 5%*? Use the same value of C=100000 as before.**\n\n**Hint:** To answer this question, use *bootstrapping* with 100 bootstrap samples/iterations. ",
"_____no_output_____"
]
],
[
[
"# your code here\n# bootstrapping code\nn = 100 # Number of iterations\nboot_coefs = np.zeros((X_train.shape[1],n)) # Create empty storage array for later use\n\n# iteration for each sample\nfor i in range(n):\n \n # Sampling WITH replacement the indices of a resampled dataset \n sample_index = np.random.choice(range(y_train.shape[0]), size=y_train.shape[0], replace=True)\n\n # finding subset\n x_train_samples = X_train.values[sample_index]\n y_train_samples = y_train.values[sample_index]\n \n # finding logreg coefficient\n logistic_mod_boot = LogisticRegression(C=100000, fit_intercept=True, solver = \"lbfgs\", max_iter=10000) \n logistic_mod_boot.fit(x_train_samples, y_train_samples) \n boot_coefs[:,i] = logistic_mod_boot.coef_",
"_____no_output_____"
],
[
"# your code here\n\nci_upper = np.percentile(boot_coefs, 97.5, axis=1)\nci_lower = np.percentile(boot_coefs, 2.5, axis=1)\n\n# ct significant predictors\nsig_b_ct = 0\nsig_preds = []\ncols = list(X_train.columns)\n\n# if ci contains 0, then insignificant\nfor i in range(len(ci_upper)):\n if ci_upper[i]<0 or ci_lower[i]>0:\n sig_b_ct += 1\n sig_preds.append(cols[i])\n\nprint(\"Significant coefficents at 5pct level = %i / %i\" % (sig_b_ct, len(ci_upper)))\n# print('Number of significant columns: ', len(sig_preds))",
"Significant coefficents at 5pct level = 1194 / 7129\n"
]
],
[
[
"**3.3 Comment on the classification accuracy of both the training and testing set. Given the results above, how would you assess the generalization capacity of your trained model? What other tests would you suggest to better guard against possibly having a false sense of the overall efficacy/accuracy of the model as a whole?**",
"_____no_output_____"
],
[
"*your answer here*\n\nProper cross validation and/or regularization.",
"_____no_output_____"
],
[
"**3.4 Now let's use regularization to improve the predictions from the multiple logistic regression model. Specifically, use LASSO-like regularization and cross-validation to train the model on the training set. Report the classification accuracy on both the training and testing set.**",
"_____no_output_____"
]
],
[
[
"# your code here\n# fitting regularized multi regression model - L1 penalty\n# Any reason for using liblinear - Use 5 fold CV\nmulti_regr = LogisticRegressionCV( solver='liblinear', penalty='l1', cv=5)\nmulti_regr.fit(X_train, y_train)\n\n# predictions\ny_train_pred_multi = multi_regr.predict(X_train) \ny_test_pred_multi = multi_regr.predict(X_test)\n\n# accuracy\ntrain_score_multi = accuracy_score(y_train, y_train_pred_multi)\ntest_score_multi = accuracy_score(y_test, y_test_pred_multi)\n\nprint('Training set accuracy for multiple logistic regression = ', train_score_multi)\nprint('Test set accuracy for multiple logistic regression = ', test_score_multi)\n\ndf_res = df_res.append([['Reg-loR train', train_score_multi], ['Reg-loR val', test_score_multi]] )\ndf_res",
"Training set accuracy for multiple logistic regression = 0.9101497504159733\nTest set accuracy for multiple logistic regression = 0.8609271523178808\n"
]
],
[
[
"**3.5 Do the 10 best predictors from Q1 hold up as important features in this regularized model? If not, explain why this is the case (feel free to use the data to support your explanation).**",
"_____no_output_____"
]
],
[
[
"# your code here\nbest_pred_1_3 = set(t_tests.index[best_preds_idx[0:10]])\nprint(best_pred_1_3)",
"{'U50136_rna1_at', 'X17042_at', 'U29175_at', 'Y08612_at', 'M31523_at', 'Z11793_at', 'X61587_at', 'M84526_at', 'X76648_at', 'X95735_at'}\n"
],
[
"# your code here\nmulti_regr_coefs =multi_regr.coef_!=0\n#Followin is a list of Lasso coefficients and # of Log Reg L1 coefficients\npredictors[multi_regr_coefs[0]] , np.sum(multi_regr_coefs[0]) ",
"_____no_output_____"
],
[
"# your code here\nbest_pred_1_3.difference(predictors[multi_regr_coefs[0]]) \n#Following predictors were important using t-test, however not for Log Reg - L1.",
"_____no_output_____"
],
[
"# your code here\n#checking correlation between above list and best predictor\ndf[['X17042_at', 'X76648_at', 'Y08612_at','M31523_at']].corr().style.background_gradient(cmap='Blues')\n",
"_____no_output_____"
]
],
[
[
"*your answer here* \n\nIdea here is that the predictors that did not make it to the list of regularization ... are the ones strongly correlated with the the best predictor. Notice high (absolute) correlation values in last row / last column.\n",
"_____no_output_____"
],
[
"<div class='exercise'> <b> Question 4 [25pts]: Multiclass Logistic Regression </b> </div>",
"_____no_output_____"
],
[
"**4.1** Load the data `hw4_mc_enhance.csv.zip` and examine its structure. How many instances of each class are there in our dataset? \n\n**4.2** Split the dataset into train and test, 80-20 split, random_state = 8. \n\nWe are going to use two particular features/predictors -- 'M31523_at', 'X95735_at'. Create a scatter plot of these two features using training set. We should be able to discern from the plot which sample belongs to which `cancer_type`.\n\n**4.3** Fit the following two models using cross-validation: \n- Logistic Regression Multiclass model with linear features. \n- Logistic Regression Multiclass model with Polynomial features, degree = 2.\n\n**4.4** Plot the decision boundary and interpret results. **Hint:** You may utilize the function `overlay_decision_boundary` \n\n**4.5** Report and plot the CV scores for the two models and interpret the results.\n",
"_____no_output_____"
],
[
"<hr>\n### Solutions",
"_____no_output_____"
],
[
"**4.1 Load the data `hw4_mc_enhance.csv.zip` and examine its structure. How many instances of each class are there in our dataset?**",
"_____no_output_____"
]
],
[
[
"#your code here\nzf = zipfile.ZipFile('data/hw4_mc_enhance.csv.zip') \ndf = pd.read_csv(zf.open('hw4_mc_enhance.csv'))\ndisplay(df.describe())\ndisplay(df.head())\n",
"_____no_output_____"
],
[
"#your code here \nprint(df.columns)\n",
"Index(['Unnamed: 0', 'AFFX-BioB-5_at', 'AFFX-BioB-M_at', 'AFFX-BioB-3_at',\n 'AFFX-BioC-5_at', 'AFFX-BioC-3_at', 'AFFX-BioDn-5_at',\n 'AFFX-BioDn-3_at', 'AFFX-CreX-5_at', 'AFFX-CreX-3_at',\n ...\n 'U58516_at', 'U73738_at', 'X06956_at', 'X16699_at', 'X83863_at',\n 'Z17240_at', 'L49218_f_at', 'M71243_f_at', 'Z78285_f_at',\n 'cancer_type'],\n dtype='object', length=7131)\n"
],
[
"#How many instances of each class are there in our dataset ? \nprint(df.cancer_type.value_counts())",
"2.0 250\n1.0 250\n0.0 250\nName: cancer_type, dtype: int64\n"
]
],
[
[
"**4.2 Split the dataset into train and test, 80-20 split, random_state = 8.**\n\n**We are going to utilize these two features - 'M31523_at', 'X95735_at'. Create a scatter plot of these two features using training dataset. We should be able to discern from the plot which sample belongs to which `cancer_type`.** ",
"_____no_output_____"
]
],
[
[
"# your code here\n# Split data\nfrom sklearn.model_selection import train_test_split\nrandom_state = 8 \n\ndata_train, data_test = train_test_split(df, test_size=.2, random_state=random_state)\n\ndata_train_X = data_train[best_preds[0:2]]\ndata_train_Y = data_train['cancer_type']\n\n# your code here\nprint(best_preds[0:2])",
"Index(['M31523_at', 'X95735_at'], dtype='object')\n"
],
[
"# your code here\nX = data_train_X.values\ny = data_train_Y.values\n\npal = sns.utils.get_color_cycle()\nclass_colors = {0: pal[0], 1: pal[1], 2: pal[2]}\nclass_markers = {0: 'o', 1: '^', 2: 'v'}\nclass_names = {\"ClassA\": 0, \"ClassB\": 1, \"ClassC\": 2}\ndef plot_cancer_data(ax, X, y):\n for class_name, response in class_names.items():\n subset = X[y == response]\n ax.scatter(\n subset[:, 0],\n subset[:, 1], \n label=class_name,\n alpha=.9, color=class_colors[response],\n lw=.5, edgecolor='k', marker=class_markers[response])\n \n ax.set(xlabel='Biomarker 1', ylabel='Biomarker 2')\n ax.legend(loc=\"lower right\")\n\nfig, ax = plt.subplots(figsize=(10,6))\nax.set_title( 'M31523_at vs. X95735_at')\nplot_cancer_data(ax, X, y)",
"_____no_output_____"
]
],
[
[
"**4.3 Fit the following two models using crossvalidation:**\n\n**Logistic Regression Multiclass model with linear features.**\n\n**Logistic Regression Multiclass model with Polynomial features, degree = 2.**\n",
"_____no_output_____"
]
],
[
[
"# your code here\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.preprocessing import StandardScaler\n\npolynomial_logreg_estimator = make_pipeline(\n PolynomialFeatures(degree=2, include_bias=False),\n LogisticRegressionCV(multi_class=\"ovr\"))\n\n# Since this is a Pipeline, you can call `.fit` and `.predict` just as if it were any other estimator.\n#\n# Note that you can access the logistic regression classifier itself by\n# polynomial_logreg_estimator.named_steps['logisticregressioncv']",
"_____no_output_____"
],
[
"# your code here\nstandardize_before_logreg = True\nif not standardize_before_logreg:\n # without standardizing...\n logreg_ovr = LogisticRegressionCV(multi_class=\"ovr\", cv=5, max_iter=300).fit(X, y)\n polynomial_logreg_estimator = make_pipeline(\n PolynomialFeatures(degree=2, include_bias=False),\n LogisticRegressionCV(multi_class=\"ovr\", cv=5, max_iter=300)).fit(X, y);\n\nelse:\n # with standardizing... since we want to standardize all features, it's really this easy:\n logreg_ovr = make_pipeline(\n StandardScaler(),\n LogisticRegressionCV(multi_class=\"ovr\", cv=5, max_iter=300)).fit(X, y)\n polynomial_logreg_estimator = make_pipeline(\n PolynomialFeatures(degree=2, include_bias=False),\n StandardScaler(),\n LogisticRegressionCV(multi_class=\"ovr\", cv=5)).fit(X, y);",
"_____no_output_____"
]
],
[
[
"**4.4 Plot the decision boundary and interpret results. Hint: You may utilize the function `overlay_decision_boundary`** \n",
"_____no_output_____"
]
],
[
[
"def overlay_decision_boundary(ax, model, colors=None, nx=200, ny=200, desaturate=.5, xlim=None, ylim=None):\n \"\"\"\n A function that visualizes the decision boundaries of a classifier.\n \n ax: Matplotlib Axes to plot on\n model: Classifier to use.\n - if `model` has a `.predict` method, like an sklearn classifier, we call `model.predict(X)`\n - otherwise, we simply call `model(X)`\n colors: list or dict of colors to use. Use color `colors[i]` for class i.\n - If colors is not provided, uses the current color cycle\n nx, ny: number of mesh points to evaluated the classifier on\n desaturate: how much to desaturate each of the colors (for better contrast with the sample points)\n xlim, ylim: range to plot on. (If the default, None, is passed, the limits will be taken from `ax`.)\n \"\"\"\n # Create mesh.\n xmin, xmax = ax.get_xlim() if xlim is None else xlim\n ymin, ymax = ax.get_ylim() if ylim is None else ylim\n xx, yy = np.meshgrid(\n np.linspace(xmin, xmax, nx),\n np.linspace(ymin, ymax, ny))\n X = np.c_[xx.flatten(), yy.flatten()]\n\n # Predict on mesh of points.\n model = getattr(model, 'predict', model)\n y = model(X)\n #print(\"Do I predict\" , y)\n \n \n# y[np.where(y=='aml')]=3\n# y[np.where(y=='allT')]=2\n# y[np.where(y=='allB')]=1\n \n \n \n y = y.astype(int) # This may be necessary for 32-bit Python.\n y = y.reshape((nx, ny))\n\n # Generate colormap.\n if colors is None:\n # If colors not provided, use the current color cycle.\n # Shift the indices so that the lowest class actually predicted gets the first color.\n # ^ This is a bit magic, consider removing for next year.\n colors = (['white'] * np.min(y)) + sns.utils.get_color_cycle()\n\n if isinstance(colors, dict):\n missing_colors = [idx for idx in np.unique(y) if idx not in colors]\n assert len(missing_colors) == 0, f\"Color not specified for predictions {missing_colors}.\"\n\n # Make a list of colors, filling in items from the dict.\n color_list = ['white'] * (np.max(y) + 1)\n for idx, val in colors.items():\n color_list[idx] = val\n else:\n assert len(colors) >= np.max(y) + 1, \"Insufficient colors passed for all predictions.\"\n color_list = colors\n color_list = [sns.utils.desaturate(color, desaturate) for color in color_list]\n cmap = matplotlib.colors.ListedColormap(color_list)\n\n # Plot decision surface\n ax.pcolormesh(xx, yy, y, zorder=-2, cmap=cmap, norm=matplotlib.colors.NoNorm(), vmin=0, vmax=y.max() + 1)\n xx = xx.reshape(nx, ny)\n yy = yy.reshape(nx, ny)\n if len(np.unique(y)) > 1:\n ax.contour(xx, yy, y, colors=\"black\", linewidths=1, zorder=-1)\n else:\n print(\"Warning: only one class predicted, so not plotting contour lines.\")",
"_____no_output_____"
],
[
"# Your code here\ndef plot_decision_boundary(x, y, model, title, ax):\n plot_cancer_data(ax, x, y)\n overlay_decision_boundary(ax, model, colors=class_colors)\n ax.set_title(title)\n",
"_____no_output_____"
],
[
"# your code here\nfig, axs = plt.subplots(1, 2, figsize=(12, 5))\nnamed_classifiers = [\n (\"Linear\", logreg_ovr),\n (\"Polynomial\", polynomial_logreg_estimator)\n]\nfor ax, (name, clf) in zip(axs, named_classifiers):\n plot_decision_boundary(X, y, clf, name, ax)",
"_____no_output_____"
]
],
[
[
"**4.5 Report and plot the CV scores for the two models and interpret the results.**",
"_____no_output_____"
]
],
[
[
"# your code here\ncv_scores = [\n cross_val_score(model, X, y, cv=3)\n for name, model in named_classifiers]\n\nplt.boxplot(cv_scores);\nplt.xticks(np.arange(1, 4), [name for name, model in named_classifiers])\nplt.xlabel(\"Logistic Regression variant\")\nplt.ylabel(\"Validation-Set Accuracy\");",
"_____no_output_____"
],
[
"# your code here\nprint(\"Cross-validation accuracy:\")\npd.DataFrame(cv_scores, index=[name for name, model in named_classifiers]).T.aggregate(['mean', 'std']).T",
"Cross-validation accuracy:\n"
]
],
[
[
"We are looking for low standard deviations in cross validation scores. If standard deviation is low (like in this case), we expect accuracy on an unseen dataset/test datasets to be rougly equal to mean cross validation accuracy. ",
"_____no_output_____"
],
[
"<div class='exercise'><b> Question 5: [10 pts] Including an 'abstain' option </b></div>\n\nOne of the reasons a hospital might be hesitant to use your cancer classification model is that a misdiagnosis by the model on a patient can sometimes prove to be very costly (e.g., missing a diagnosis or wrongly diagnosing a condition, and subsequently, one may file a lawsuit seeking a compensation for damages). One way to mitigate this concern is to allow the model to 'abstain' from making a prediction whenever it is uncertain about the diagnosis for a patient. However, when the model abstains from making a prediction, the hospital will have to forward the patient to a specialist, which would incur additional cost. How could one design a cancer classification model with an abstain option, such that the cost to the hospital is minimized?\n\n**Hint:** Think of ways to build on top of the logistic regression model and have it abstain on patients who are difficult to classify.",
"_____no_output_____"
],
[
"**5.1** More specifically, suppose the cost incurred by a hospital when a model mis-predicts on a patient is $\\$5000$ , and the cost incurred when the model abstains from making a prediction is \\$1000. What is the average cost per patient for the OvR logistic regression model (without quadratic or interaction terms) from **Question 4**. Note that this needs to be evaluated on the patients in the testing set. ",
"_____no_output_____"
],
[
"**5.2** Design a classification strategy (into the 3 groups plus the *abstain* group) that has a low cost as possible per patient (certainly lower cost per patient than the logistic regression model). Give a justification for your approach.",
"_____no_output_____"
],
[
"<hr>\n### Solutions",
"_____no_output_____"
],
[
"**5.1 More specifically, suppose the cost incurred by a hospital when a model mis-predicts on a patient is $\\$5000$ , and the cost incurred when the model abstains from making a prediction is \\$1000. What is the average cost per patient for the OvR logistic regression model (without quadratic or interaction terms) from Question 4.** <br><bR> Note that this needs to be evaluated on the patients in the testing set. ",
"_____no_output_____"
],
[
"*your answer here* \n\n**Philosophy:** Assuming the OvR logistic regression model, we estimate $p_j$ for $j\\in \\{1,2,3\\}$, the marginal probability of being in each class. `sklearn` handles the normalization for us, although the normalization step is not necessary for the multinomial model since the softmax function is already constrained to sum to 1. \n\nFollowing the hint, we will proceed by using the trained OvR logistic regression model to estimate $\\hat{p}_j$ and then use the missclassifications to estimate the cost of them. \n",
"_____no_output_____"
]
],
[
[
"data_test.head()",
"_____no_output_____"
],
[
"# predict only in two best predictors\ndec = logreg_ovr.predict(data_test.loc[:,best_preds[0:2]].values) \ndec = pd.Series(dec).astype('category').cat.codes\n\n# true values in test, our y_test\nvl = np.array(data_test.cancer_type.astype('category').cat.codes)",
"_____no_output_____"
],
[
"# your code here\ndef cost(predictions, truth):\n ''' Counts the cost when we have missclassifications in the predictions vs. the truth set.\n Option = -1 is the abstain option and is only relevant when the values include the abstain option, \n otherwise initial cost defaults to 0 (for question 5.1). \n \n Arguments: prediction values and true values\n Returns: the numerical cost\n '''\n cost = 1000 * len(predictions[predictions == -1]) # defaults to 0 for 5.1\n true_vals = truth[predictions != -1] # defaults to truth for 5.1\n \n predicted_vals = predictions[predictions != -1] # defaults to predictions for 5.1\n \n cost += 5000 * np.sum(true_vals != predicted_vals)\n return cost",
"_____no_output_____"
],
[
"print(\"Cost incurred for OvR Logistic Regression Model without abstain: $\", cost(dec,vl)/len(vl))",
"Cost incurred for OvR Logistic Regression Model without abstain: $ 800.0\n"
]
],
[
[
"**5.2 Design a classification strategy (into the 3 groups plus the *abstain* group) that has a low cost as possible per patient (certainly lower cost per patient than the logistic regression model). Give a justification for your approach.**",
"_____no_output_____"
],
[
"Following 5.1, we make the decision to abstain or not based on minimizing the expected cost. \n<br><br>\nThe expected cost for abstaining is $\\$1000$. The expected cost for predicting is $ \\$5000 * P(\\text{misdiagnosis}) = 5000 * (1 - \\hat{p}_k)$ where $k$ is the label of the predicted class. \n\nSo our decision rule is if the cost of making a missdiagnosis is less than the cost of abstaining (expressed by the formula $5000 * (1 - \\hat{p}_k) < 1000$), then attempt a prediction. Otherwise, abstain.",
"_____no_output_____"
]
],
[
[
"# your code here\ndef decision_rule(lrm_mod,input_data):\n probs = lrm_mod.predict_proba(input_data)\n predicted_class = np.argmax(probs,axis = 1)\n conf = 1.0 - np.max(probs,axis = 1)\n predicted_class[5000*conf > 1000.0] = -1 #Abstain\n return predicted_class\n \ninp = data_test.loc[:,best_preds[0:2]].values\ndec2 = decision_rule(logreg_ovr,inp)\n\nprint(\"Cost incurred for new model: $\", cost(dec2,vl)/len(vl))",
"Cost incurred for new model: $ 653.3333333333334\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
cbd4c98b52400fdcb1a76acb065c18b615d90c67
| 7,134 |
ipynb
|
Jupyter Notebook
|
homeworks/Homework_2.ipynb
|
benedettaliberatori/DSSC_DL_2021
|
176ab914b53749d2caf53c531b1be9e1b6e14708
|
[
"MIT"
] | 1 |
2021-09-17T01:15:55.000Z
|
2021-09-17T01:15:55.000Z
|
homeworks/Homework_2.ipynb
|
benedettaliberatori/DSSC_DL_2021
|
176ab914b53749d2caf53c531b1be9e1b6e14708
|
[
"MIT"
] | null | null | null |
homeworks/Homework_2.ipynb
|
benedettaliberatori/DSSC_DL_2021
|
176ab914b53749d2caf53c531b1be9e1b6e14708
|
[
"MIT"
] | null | null | null | 32.724771 | 373 | 0.484441 |
[
[
[
"# Homework 2 - Deep Learning\n## Liberatori Benedetta\n\n",
"_____no_output_____"
]
],
[
[
"import torch\nimport numpy as np",
"_____no_output_____"
],
[
"# A class defining the model for the Multi Layer Perceptron\n\nclass MLP(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.layer1 = torch.nn.Linear(in_features=6, out_features=2, bias= True)\n self.layer2 = torch.nn.Linear(in_features=2, out_features=1, bias= True)\n\n def forward(self, X):\n out = self.layer1(X)\n out = self.layer2(out)\n out = torch.nn.functional.sigmoid(out)\n return out",
"_____no_output_____"
],
[
"# Initialization of weights: uniformly distributed between -0.3 and 0.3\n\nW = (0.3 + 0.3) * torch.rand(6, 1 ) - 0.3\n\n# Inizialization of Data: 50% symmetric randomly generated tensors\n# 50% not necessarily symmetric \n\nfirsthalf= torch.rand([32,3])\nsecondhalf=torch.zeros([32,3])\n\nsecondhalf[:, 2:3 ]=firsthalf[:, 0:1]\nsecondhalf[:, 1:2 ]=firsthalf[:, 1:2]\nsecondhalf[:, 0:1 ]=firsthalf[:, 2:3]\n\ny1=torch.ones([32,1])\ny0=torch.zeros([32,1])\nsimmetric = torch.cat((firsthalf, secondhalf, y1), dim=1)\nnotsimmetric = torch.rand([32,6])\nnotsimmetric= torch.cat((notsimmetric, y0), dim=1)\n\ndata= torch.cat((notsimmetric, simmetric), dim=0)\n\n# Permutation of the concatenated dataset\ndata= data[torch.randperm(data.size()[0])]\n",
"_____no_output_____"
],
[
"def train_epoch(model, data, loss_fn, optimizer):\n X=data[:,0:6]\n y=data[:,6]\n \n # 1. reset the gradients previously accumulated by the optimizer\n # this will avoid re-using gradients from previous loops\n optimizer.zero_grad() \n # 2. get the predictions from the current state of the model\n # this is the forward pass\n y_hat = model(X)\n # 3. calculate the loss on the current mini-batch\n loss = loss_fn(y_hat, y.unsqueeze(1))\n # 4. execute the backward pass given the current loss\n loss.backward()\n # 5. update the value of the params\n optimizer.step()\n return model\n\n ",
"_____no_output_____"
],
[
"def train_model(model, data, loss_fn, optimizer, num_epochs):\n model.train()\n for epoch in range(num_epochs):\n model=train_epoch(model, data, loss_fn, optimizer)\n \n for i in model.state_dict():\n print(model.state_dict()[i])\n",
"_____no_output_____"
],
[
"# Parameters set as defined in the paper\nlearn_rate = 0.1 \nnum_epochs = 1425\nbeta= 0.9\nmodel = MLP()\n\n# I have judged the loss function (3) reported in the paper paper a general one for the discussion\n# Since the problem of interest is a binary classification and that loss is mostly suited for \n# regression problems I have used instead a Binary Cross Entropy loss\n\nloss_fn = torch.nn.BCELoss()\n\n# Gradient descent optimizer with momentum\noptimizer = torch.optim.SGD(model.parameters(), lr=learn_rate, momentum=beta)",
"_____no_output_____"
],
[
"train_model(model, data, loss_fn, optimizer, num_epochs)",
"/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:1709: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\n warnings.warn(\"nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.\")\n"
]
],
[
[
"## Some conclusions:\n\nEven if the original protocol has been followed as deep as possible, the results obtained in the same number of epochs are fare from the ones stated in the paper. Not only the numbers, indeed those are not even near to be symmetric. I assume this could depend on the inizialization of the data, which was not reported and thus a completely autonomous choice. \n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cbd4d436fd03ac4768515fda9aafef05eda4a09b
| 355,784 |
ipynb
|
Jupyter Notebook
|
NeuralNetworksBasics/LogisticRegressionWithANeuralNetworkmindset.ipynb
|
FarmerCui/NeuralNetworksAndDeepLearning
|
504594f49d3ee298344fd384ce147a2dbfd570de
|
[
"MIT"
] | 1 |
2019-08-06T15:52:36.000Z
|
2019-08-06T15:52:36.000Z
|
NeuralNetworksBasics/LogisticRegressionWithANeuralNetworkmindset.ipynb
|
FarmerCui/NeuralNetworksAndDeepLearning
|
504594f49d3ee298344fd384ce147a2dbfd570de
|
[
"MIT"
] | null | null | null |
NeuralNetworksBasics/LogisticRegressionWithANeuralNetworkmindset.ipynb
|
FarmerCui/NeuralNetworksAndDeepLearning
|
504594f49d3ee298344fd384ce147a2dbfd570de
|
[
"MIT"
] | null | null | null | 272.006116 | 226,946 | 0.901235 |
[
[
[
"# Logistic Regression with a Neural Network mindset\n\nWelcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning.\n\n**Instructions:**\n- Do not use loops (for/while) in your code, unless the instructions explicitly ask you to do so.\n\n**You will learn to:**\n- Build the general architecture of a learning algorithm, including:\n - Initializing parameters\n - Calculating the cost function and its gradient\n - Using an optimization algorithm (gradient descent) \n- Gather all three functions above into a main model function, in the right order.",
"_____no_output_____"
],
[
"## 1 - Packages ##\n\nFirst, let's run the cell below to import all the packages that you will need during this assignment. \n- [numpy](https://www.numpy.org/) is the fundamental package for scientific computing with Python.\n- [h5py](http://www.h5py.org) is a common package to interact with a dataset that is stored on an H5 file.\n- [matplotlib](http://matplotlib.org) is a famous library to plot graphs in Python.\n- [PIL](http://www.pythonware.com/products/pil/) and [scipy](https://www.scipy.org/) are used here to test your model with your own picture at the end.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nfrom lr_utils import load_dataset\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## 2 - Overview of the Problem set ##\n\n**Problem Statement**: You are given a dataset (\"data.h5\") containing:\n - a training set of m_train images labeled as cat (y=1) or non-cat (y=0)\n - a test set of m_test images labeled as cat or non-cat\n - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB). Thus, each image is square (height = num_px) and (width = num_px).\n\nYou will build a simple image-recognition algorithm that can correctly classify pictures as cat or non-cat.\n\nLet's get more familiar with the dataset. Load the data by running the following code.",
"_____no_output_____"
]
],
[
[
"# Loading the data (cat/non-cat)\ntrain_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()",
"_____no_output_____"
]
],
[
[
"We added \"_orig\" at the end of image datasets (train and test) because we are going to preprocess them. After preprocessing, we will end up with train_set_x and test_set_x (the labels train_set_y and test_set_y don't need any preprocessing).\n\nEach line of your train_set_x_orig and test_set_x_orig is an array representing an image. You can visualize an example by running the following code. Feel free also to change the `index` value and re-run to see other images. ",
"_____no_output_____"
]
],
[
[
"# Example of a picture\nindex = 25\nplt.imshow(train_set_x_orig[index])\nprint (\"y = \" + str(train_set_y[:, index]) + \", it's a '\" + classes[np.squeeze(train_set_y[:, index])].decode(\"utf-8\") + \"' picture.\")",
"y = [1], it's a 'cat' picture.\n"
]
],
[
[
"Many software bugs in deep learning come from having matrix/vector dimensions that don't fit. If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating many bugs. \n\n**Exercise:** Find the values for:\n - m_train (number of training examples)\n - m_test (number of test examples)\n - num_px (= height = width of a training image)\nRemember that `train_set_x_orig` is a numpy-array of shape (m_train, num_px, num_px, 3). For instance, you can access `m_train` by writing `train_set_x_orig.shape[0]`.",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (≈ 3 lines of code)\nm_train = train_set_x_orig.shape[0]\nm_test = test_set_x_orig.shape[0]\nnum_px = train_set_x_orig.shape[1]\n### END CODE HERE ###\n\nprint (\"Number of training examples: m_train = \" + str(m_train))\nprint (\"Number of testing examples: m_test = \" + str(m_test))\nprint (\"Height/Width of each image: num_px = \" + str(num_px))\nprint (\"Each image is of size: (\" + str(num_px) + \", \" + str(num_px) + \", 3)\")\nprint (\"train_set_x shape: \" + str(train_set_x_orig.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x shape: \" + str(test_set_x_orig.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))",
"Number of training examples: m_train = 209\nNumber of testing examples: m_test = 50\nHeight/Width of each image: num_px = 64\nEach image is of size: (64, 64, 3)\ntrain_set_x shape: (209, 64, 64, 3)\ntrain_set_y shape: (1, 209)\ntest_set_x shape: (50, 64, 64, 3)\ntest_set_y shape: (1, 50)\n"
]
],
[
[
"**Expected Output for m_train, m_test and num_px**: \n<table style=\"width:15%\">\n <tr>\n <td>**m_train**</td>\n <td> 209 </td> \n </tr>\n \n <tr>\n <td>**m_test**</td>\n <td> 50 </td> \n </tr>\n \n <tr>\n <td>**num_px**</td>\n <td> 64 </td> \n </tr>\n \n</table>\n",
"_____no_output_____"
],
[
"For convenience, you should now reshape images of shape (num_px, num_px, 3) in a numpy-array of shape (num_px $*$ num_px $*$ 3, 1). After this, our training (and test) dataset is a numpy-array where each column represents a flattened image. There should be m_train (respectively m_test) columns.\n\n**Exercise:** Reshape the training and test data sets so that images of size (num_px, num_px, 3) are flattened into single vectors of shape (num\\_px $*$ num\\_px $*$ 3, 1).\n\nA trick when you want to flatten a matrix X of shape (a,b,c,d) to a matrix X_flatten of shape (b$*$c$*$d, a) is to use: \n```python\nX_flatten = X.reshape(X.shape[0], -1).T # X.T is the transpose of X\n```",
"_____no_output_____"
]
],
[
[
"# Reshape the training and test examples\n\n### START CODE HERE ### (≈ 2 lines of code)\ntrain_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T\ntest_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\n### END CODE HERE ###\n\nprint (\"train_set_x_flatten shape: \" + str(train_set_x_flatten.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x_flatten shape: \" + str(test_set_x_flatten.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))\nprint (\"sanity check after reshaping: \" + str(train_set_x_flatten[0:5,0]))",
"train_set_x_flatten shape: (12288, 209)\ntrain_set_y shape: (1, 209)\ntest_set_x_flatten shape: (12288, 50)\ntest_set_y shape: (1, 50)\nsanity check after reshaping: [17 31 56 22 33]\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:35%\">\n <tr>\n <td>**train_set_x_flatten shape**</td>\n <td> (12288, 209)</td> \n </tr>\n <tr>\n <td>**train_set_y shape**</td>\n <td>(1, 209)</td> \n </tr>\n <tr>\n <td>**test_set_x_flatten shape**</td>\n <td>(12288, 50)</td> \n </tr>\n <tr>\n <td>**test_set_y shape**</td>\n <td>(1, 50)</td> \n </tr>\n <tr>\n <td>**sanity check after reshaping**</td>\n <td>[17 31 56 22 33]</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"To represent color images, the red, green and blue channels (RGB) must be specified for each pixel, and so the pixel value is actually a vector of three numbers ranging from 0 to 255.\n\nOne common preprocessing step in machine learning is to center and standardize your dataset, meaning that you substract the mean of the whole numpy array from each example, and then divide each example by the standard deviation of the whole numpy array. But for picture datasets, it is simpler and more convenient and works almost as well to just divide every row of the dataset by 255 (the maximum value of a pixel channel).\n\n<!-- During the training of your model, you're going to multiply weights and add biases to some initial inputs in order to observe neuron activations. Then you backpropogate with the gradients to train the model. But, it is extremely important for each feature to have a similar range such that our gradients don't explode. You will see that more in detail later in the lectures. !--> \n\nLet's standardize our dataset.",
"_____no_output_____"
]
],
[
[
"train_set_x = train_set_x_flatten/255.\ntest_set_x = test_set_x_flatten/255.",
"_____no_output_____"
]
],
[
[
"<font color='blue'>\n**What you need to remember:**\n\nCommon steps for pre-processing a new dataset are:\n- Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...)\n- Reshape the datasets such that each example is now a vector of size (num_px \\* num_px \\* 3, 1)\n- \"Standardize\" the data",
"_____no_output_____"
],
[
"## 3 - General Architecture of the learning algorithm ##\n\nIt's time to design a simple algorithm to distinguish cat images from non-cat images.\n\nYou will build a Logistic Regression, using a Neural Network mindset. The following Figure explains why **Logistic Regression is actually a very simple Neural Network!**\n\n<img src=\"images/LogReg_kiank.png\" style=\"width:650px;height:400px;\">\n\n**Mathematical expression of the algorithm**:\n\nFor one example $x^{(i)}$:\n$$z^{(i)} = w^T x^{(i)} + b \\tag{1}$$\n$$\\hat{y}^{(i)} = a^{(i)} = sigmoid(z^{(i)})\\tag{2}$$ \n$$ \\mathcal{L}(a^{(i)}, y^{(i)}) = - y^{(i)} \\log(a^{(i)}) - (1-y^{(i)} ) \\log(1-a^{(i)})\\tag{3}$$\n\nThe cost is then computed by summing over all training examples:\n$$ J = \\frac{1}{m} \\sum_{i=1}^m \\mathcal{L}(a^{(i)}, y^{(i)})\\tag{6}$$\n\n**Key steps**:\nIn this exercise, you will carry out the following steps: \n - Initialize the parameters of the model\n - Learn the parameters for the model by minimizing the cost \n - Use the learned parameters to make predictions (on the test set)\n - Analyse the results and conclude",
"_____no_output_____"
],
[
"## 4 - Building the parts of our algorithm ## \n\nThe main steps for building a Neural Network are:\n1. Define the model structure (such as number of input features) \n2. Initialize the model's parameters\n3. Loop:\n - Calculate current loss (forward propagation)\n - Calculate current gradient (backward propagation)\n - Update parameters (gradient descent)\n\nYou often build 1-3 separately and integrate them into one function we call `model()`.\n\n### 4.1 - Helper functions\n\n**Exercise**: Using your code from \"Python Basics\", implement `sigmoid()`. As you've seen in the figure above, you need to compute $sigmoid( w^T x + b) = \\frac{1}{1 + e^{-(w^T x + b)}}$ to make predictions. Use np.exp().",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: sigmoid\n\ndef sigmoid(z):\n \"\"\"\n Compute the sigmoid of z\n\n Arguments:\n z -- A scalar or numpy array of any size.\n\n Return:\n s -- sigmoid(z)\n \"\"\"\n\n ### START CODE HERE ### (≈ 1 line of code)\n s = 1 / (1 + np.exp(-z))\n ### END CODE HERE ###\n \n return s",
"_____no_output_____"
],
[
"print (\"sigmoid([0, 2]) = \" + str(sigmoid(np.array([0,2]))))",
"sigmoid([0, 2]) = [ 0.5 0.88079708]\n"
]
],
[
[
"**Expected Output**: \n\n<table>\n <tr>\n <td>**sigmoid([0, 2])**</td>\n <td> [ 0.5 0.88079708]</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"### 4.2 - Initializing parameters\n\n**Exercise:** Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documentation.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: initialize_with_zeros\n\ndef initialize_with_zeros(dim):\n \"\"\"\n This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.\n \n Argument:\n dim -- size of the w vector we want (or number of parameters in this case)\n \n Returns:\n w -- initialized vector of shape (dim, 1)\n b -- initialized scalar (corresponds to the bias)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n w = np.zeros((dim,1))\n b = 0\n ### END CODE HERE ###\n\n assert(w.shape == (dim, 1))\n assert(isinstance(b, float) or isinstance(b, int))\n \n return w, b",
"_____no_output_____"
],
[
"dim = 2\nw, b = initialize_with_zeros(dim)\nprint (\"w = \" + str(w))\nprint (\"b = \" + str(b))",
"w = [[ 0.]\n [ 0.]]\nb = 0\n"
]
],
[
[
"**Expected Output**: \n\n\n<table style=\"width:15%\">\n <tr>\n <td> ** w ** </td>\n <td> [[ 0.]\n [ 0.]] </td>\n </tr>\n <tr>\n <td> ** b ** </td>\n <td> 0 </td>\n </tr>\n</table>\n\nFor image inputs, w will be of shape (num_px $\\times$ num_px $\\times$ 3, 1).",
"_____no_output_____"
],
[
"### 4.3 - Forward and Backward propagation\n\nNow that your parameters are initialized, you can do the \"forward\" and \"backward\" propagation steps for learning the parameters.\n\n**Exercise:** Implement a function `propagate()` that computes the cost function and its gradient.\n\n**Hints**:\n\nForward Propagation:\n- You get X\n- You compute $A = \\sigma(w^T X + b) = (a^{(1)}, a^{(2)}, ..., a^{(m-1)}, a^{(m)})$\n- You calculate the cost function: $J = -\\frac{1}{m}\\sum_{i=1}^{m}y^{(i)}\\log(a^{(i)})+(1-y^{(i)})\\log(1-a^{(i)})$\n\nHere are the two formulas you will be using: \n\n$$ \\frac{\\partial J}{\\partial w} = \\frac{1}{m}X(A-Y)^T\\tag{7}$$\n$$ \\frac{\\partial J}{\\partial b} = \\frac{1}{m} \\sum_{i=1}^m (a^{(i)}-y^{(i)})\\tag{8}$$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: propagate\n\ndef propagate(w, b, X, Y):\n \"\"\"\n Implement the cost function and its gradient for the propagation explained above\n\n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of size (num_px * num_px * 3, number of examples)\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)\n\n Return:\n cost -- negative log-likelihood cost for logistic regression\n dw -- gradient of the loss with respect to w, thus same shape as w\n db -- gradient of the loss with respect to b, thus same shape as b\n \n Tips:\n - Write your code step by step for the propagation. np.log(), np.dot()\n \"\"\"\n \n m = X.shape[1]\n \n # FORWARD PROPAGATION (FROM X TO COST)\n ### START CODE HERE ### (≈ 2 lines of code)\n A = 1 / (1 + np.exp(-(np.dot(w.T, X) + b))) # compute activation\n cost = -1 / m * np.sum(np.multiply(Y, np.log(A)) + np.multiply(1 - Y,np.log(1 - A))) # compute cost\n ### END CODE HERE ###\n \n # BACKWARD PROPAGATION (TO FIND GRAD)\n ### START CODE HERE ### (≈ 2 lines of code)\n dw = 1 / m * np.dot(X, (A - Y).T)\n db = 1 / m * np.sum(A - Y)\n ### END CODE HERE ###\n\n assert(dw.shape == w.shape)\n assert(db.dtype == float)\n cost = np.squeeze(cost)\n assert(cost.shape == ())\n \n grads = {\"dw\": dw,\n \"db\": db}\n \n return grads, cost",
"_____no_output_____"
],
[
"w, b, X, Y = np.array([[1.],[2.]]), 2., np.array([[1.,2.,-1.],[3.,4.,-3.2]]), np.array([[1,0,1]])\ngrads, cost = propagate(w, b, X, Y)\nprint (\"dw = \" + str(grads[\"dw\"]))\nprint (\"db = \" + str(grads[\"db\"]))\nprint (\"cost = \" + str(cost))",
"dw = [[ 0.99845601]\n [ 2.39507239]]\ndb = 0.00145557813678\ncost = 5.80154531939\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:50%\">\n <tr>\n <td> ** dw ** </td>\n <td> [[ 0.99845601]\n [ 2.39507239]]</td>\n </tr>\n <tr>\n <td> ** db ** </td>\n <td> 0.00145557813678 </td>\n </tr>\n <tr>\n <td> ** cost ** </td>\n <td> 5.801545319394553 </td>\n </tr>\n\n</table>",
"_____no_output_____"
],
[
"### 4.4 - Optimization\n- You have initialized your parameters.\n- You are also able to compute a cost function and its gradient.\n- Now, you want to update the parameters using gradient descent.\n\n**Exercise:** Write down the optimization function. The goal is to learn $w$ and $b$ by minimizing the cost function $J$. For a parameter $\\theta$, the update rule is $ \\theta = \\theta - \\alpha \\text{ } d\\theta$, where $\\alpha$ is the learning rate.",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: optimize\n\ndef optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):\n \"\"\"\n This function optimizes w and b by running a gradient descent algorithm\n \n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of shape (num_px * num_px * 3, number of examples)\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)\n num_iterations -- number of iterations of the optimization loop\n learning_rate -- learning rate of the gradient descent update rule\n print_cost -- True to print the loss every 100 steps\n \n Returns:\n params -- dictionary containing the weights w and bias b\n grads -- dictionary containing the gradients of the weights and bias with respect to the cost function\n costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.\n \n Tips:\n You basically need to write down two steps and iterate through them:\n 1) Calculate the cost and the gradient for the current parameters. Use propagate().\n 2) Update the parameters using gradient descent rule for w and b.\n \"\"\"\n \n costs = []\n \n for i in range(num_iterations):\n \n \n # Cost and gradient calculation (≈ 1-4 lines of code)\n ### START CODE HERE ### \n grads, cost = propagate(w, b, X, Y)\n ### END CODE HERE ###\n \n # Retrieve derivatives from grads\n dw = grads[\"dw\"]\n db = grads[\"db\"]\n \n # update rule (≈ 2 lines of code)\n ### START CODE HERE ###\n w = w - learning_rate * dw\n b = b - learning_rate * db\n ### END CODE HERE ###\n \n # Record the costs\n if i % 100 == 0:\n costs.append(cost)\n \n # Print the cost every 100 training iterations\n if print_cost and i % 100 == 0:\n print (\"Cost after iteration %i: %f\" %(i, cost))\n \n params = {\"w\": w,\n \"b\": b}\n \n grads = {\"dw\": dw,\n \"db\": db}\n \n return params, grads, costs",
"_____no_output_____"
],
[
"params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)\n\nprint (\"w = \" + str(params[\"w\"]))\nprint (\"b = \" + str(params[\"b\"]))\nprint (\"dw = \" + str(grads[\"dw\"]))\nprint (\"db = \" + str(grads[\"db\"]))",
"w = [[ 0.19033591]\n [ 0.12259159]]\nb = 1.92535983008\ndw = [[ 0.67752042]\n [ 1.41625495]]\ndb = 0.219194504541\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:40%\">\n <tr>\n <td> **w** </td>\n <td>[[ 0.19033591]\n [ 0.12259159]] </td>\n </tr>\n \n <tr>\n <td> **b** </td>\n <td> 1.92535983008 </td>\n </tr>\n <tr>\n <td> **dw** </td>\n <td> [[ 0.67752042]\n [ 1.41625495]] </td>\n </tr>\n <tr>\n <td> **db** </td>\n <td> 0.219194504541 </td>\n </tr>\n\n</table>",
"_____no_output_____"
],
[
"**Exercise:** The previous function will output the learned w and b. We are able to use w and b to predict the labels for a dataset X. Implement the `predict()` function. There are two steps to computing predictions:\n\n1. Calculate $\\hat{Y} = A = \\sigma(w^T X + b)$\n\n2. Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5), stores the predictions in a vector `Y_prediction`. If you wish, you can use an `if`/`else` statement in a `for` loop (though there is also a way to vectorize this). ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: predict\n\ndef predict(w, b, X):\n '''\n Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)\n \n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of size (num_px * num_px * 3, number of examples)\n \n Returns:\n Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X\n '''\n \n m = X.shape[1]\n Y_prediction = np.zeros((1,m))\n w = w.reshape(X.shape[0], 1)\n \n # Compute vector \"A\" predicting the probabilities of a cat being present in the picture\n ### START CODE HERE ### (≈ 1 line of code)\n A = sigmoid(np.dot(w.T, X) + b)\n ### END CODE HERE ###\n \n for i in range(A.shape[1]):\n \n # Convert probabilities A[0,i] to actual predictions p[0,i]\n ### START CODE HERE ### (≈ 4 lines of code)\n Y_prediction[0][i] = 1 if A[0][i] >= 0.5 else 0\n ### END CODE HERE ###\n \n assert(Y_prediction.shape == (1, m))\n \n return Y_prediction",
"_____no_output_____"
],
[
"w = np.array([[0.1124579],[0.23106775]])\nb = -0.3\nX = np.array([[1.,-1.1,-3.2],[1.2,2.,0.1]])\nprint (\"predictions = \" + str(predict(w, b, X)))",
"predictions = [[ 1. 1. 0.]]\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:30%\">\n <tr>\n <td>\n **predictions**\n </td>\n <td>\n [[ 1. 1. 0.]]\n </td> \n </tr>\n\n</table>\n",
"_____no_output_____"
],
[
"<font color='blue'>\n**What to remember:**\nYou've implemented several functions that:\n- Initialize (w,b)\n- Optimize the loss iteratively to learn parameters (w,b):\n - computing the cost and its gradient \n - updating the parameters using gradient descent\n- Use the learned (w,b) to predict the labels for a given set of examples",
"_____no_output_____"
],
[
"## 5 - Merge all functions into a model ##\n\nYou will now see how the overall model is structured by putting together all the building blocks (functions implemented in the previous parts) together, in the right order.\n\n**Exercise:** Implement the model function. Use the following notation:\n - Y_prediction_test for your predictions on the test set\n - Y_prediction_train for your predictions on the train set\n - w, costs, grads for the outputs of optimize()",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: model\n\ndef model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):\n \"\"\"\n Builds the logistic regression model by calling the function you've implemented previously\n \n Arguments:\n X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)\n Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)\n X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)\n Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)\n num_iterations -- hyperparameter representing the number of iterations to optimize the parameters\n learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()\n print_cost -- Set to true to print the cost every 100 iterations\n \n Returns:\n d -- dictionary containing information about the model.\n \"\"\"\n \n ### START CODE HERE ###\n \n # initialize parameters with zeros (≈ 1 line of code)\n w, b = initialize_with_zeros(X_train.shape[0])\n\n # Gradient descent (≈ 1 line of code)\n parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost = False)\n \n # Retrieve parameters w and b from dictionary \"parameters\"\n w = parameters[\"w\"]\n b = parameters[\"b\"]\n \n # Predict test/train set examples (≈ 2 lines of code)\n Y_prediction_test = predict(w, b, X_test)\n Y_prediction_train = predict(w, b, X_train)\n\n ### END CODE HERE ###\n\n # Print train/test Errors\n print(\"train accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))\n print(\"test accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))\n\n \n d = {\"costs\": costs,\n \"Y_prediction_test\": Y_prediction_test, \n \"Y_prediction_train\" : Y_prediction_train, \n \"w\" : w, \n \"b\" : b,\n \"learning_rate\" : learning_rate,\n \"num_iterations\": num_iterations}\n \n return d",
"_____no_output_____"
]
],
[
[
"Run the following cell to train your model.",
"_____no_output_____"
]
],
[
[
"d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)",
"train accuracy: 99.04306220095694 %\ntest accuracy: 70.0 %\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:40%\"> \n\n <tr>\n <td> **Cost after iteration 0 ** </td> \n <td> 0.693147 </td>\n </tr>\n <tr>\n <td> <center> $\\vdots$ </center> </td> \n <td> <center> $\\vdots$ </center> </td> \n </tr> \n <tr>\n <td> **Train Accuracy** </td> \n <td> 99.04306220095694 % </td>\n </tr>\n\n <tr>\n <td>**Test Accuracy** </td> \n <td> 70.0 % </td>\n </tr>\n</table> \n\n\n",
"_____no_output_____"
],
[
"**Comment**: Training accuracy is close to 100%. This is a good sanity check: your model is working and has high enough capacity to fit the training data. Test accuracy is 68%. It is actually not bad for this simple model, given the small dataset we used and that logistic regression is a linear classifier. But no worries, you'll build an even better classifier next week!\n\nAlso, you see that the model is clearly overfitting the training data. Later in this specialization you will learn how to reduce overfitting, for example by using regularization. Using the code below (and changing the `index` variable) you can look at predictions on pictures of the test set.",
"_____no_output_____"
]
],
[
[
"# Example of a picture that was wrongly classified.\nindex = 1\nplt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))\nprint (\"y = \" + str(test_set_y[0,index]) + \", you predicted that it is a \\\"\" + classes[d[\"Y_prediction_test\"][0,index]].decode(\"utf-8\") + \"\\\" picture.\")",
"y = 1, you predicted that it is a \"cat\" picture.\n"
]
],
[
[
"Let's also plot the cost function and the gradients.",
"_____no_output_____"
]
],
[
[
"# Plot learning curve (with costs)\ncosts = np.squeeze(d['costs'])\nplt.plot(costs)\nplt.ylabel('cost')\nplt.xlabel('iterations (per hundreds)')\nplt.title(\"Learning rate =\" + str(d[\"learning_rate\"]))\nplt.show()",
"_____no_output_____"
]
],
[
[
"**Interpretation**:\nYou can see the cost decreasing. It shows that the parameters are being learned. However, you see that you could train the model even more on the training set. Try to increase the number of iterations in the cell above and rerun the cells. You might see that the training set accuracy goes up, but the test set accuracy goes down. This is called overfitting. ",
"_____no_output_____"
],
[
"## 6 - Further analysis (optional/ungraded exercise) ##\n\nCongratulations on building your first image classification model. Let's analyze it further, and examine possible choices for the learning rate $\\alpha$. ",
"_____no_output_____"
],
[
"#### Choice of learning rate ####\n\n**Reminder**:\nIn order for Gradient Descent to work you must choose the learning rate wisely. The learning rate $\\alpha$ determines how rapidly we update the parameters. If the learning rate is too large we may \"overshoot\" the optimal value. Similarly, if it is too small we will need too many iterations to converge to the best values. That's why it is crucial to use a well-tuned learning rate.\n\nLet's compare the learning curve of our model with several choices of learning rates. Run the cell below. This should take about 1 minute. Feel free also to try different values than the three we have initialized the `learning_rates` variable to contain, and see what happens. ",
"_____no_output_____"
]
],
[
[
"learning_rates = [0.01, 0.001, 0.0001]\nmodels = {}\nfor i in learning_rates:\n print (\"learning rate is: \" + str(i))\n models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)\n print ('\\n' + \"-------------------------------------------------------\" + '\\n')\n\nfor i in learning_rates:\n plt.plot(np.squeeze(models[str(i)][\"costs\"]), label= str(models[str(i)][\"learning_rate\"]))\n\nplt.ylabel('cost')\nplt.xlabel('iterations (hundreds)')\n\nlegend = plt.legend(loc='upper center', shadow=True)\nframe = legend.get_frame()\nframe.set_facecolor('0.90')\nplt.show()",
"learning rate is: 0.01\ntrain accuracy: 99.52153110047847 %\ntest accuracy: 68.0 %\n\n-------------------------------------------------------\n\nlearning rate is: 0.001\ntrain accuracy: 88.99521531100478 %\ntest accuracy: 64.0 %\n\n-------------------------------------------------------\n\nlearning rate is: 0.0001\ntrain accuracy: 68.42105263157895 %\ntest accuracy: 36.0 %\n\n-------------------------------------------------------\n\n"
]
],
[
[
"**Interpretation**: \n- Different learning rates give different costs and thus different predictions results.\n- If the learning rate is too large (0.01), the cost may oscillate up and down. It may even diverge (though in this example, using 0.01 still eventually ends up at a good value for the cost). \n- A lower cost doesn't mean a better model. You have to check if there is possibly overfitting. It happens when the training accuracy is a lot higher than the test accuracy.\n- In deep learning, we usually recommend that you: \n - Choose the learning rate that better minimizes the cost function.\n - If your model overfits, use other techniques to reduce overfitting. (We'll talk about this in later videos.) \n",
"_____no_output_____"
],
[
"## 7 - Test with your own image (optional/ungraded exercise) ##\n\nCongratulations on finishing this assignment. You can use your own image and see the output of your model. To do that:\n 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n 3. Change your image's name in the following code\n 4. Run the code and check if the algorithm is right (1 = cat, 0 = non-cat)!",
"_____no_output_____"
]
],
[
[
"## START CODE HERE ## (PUT YOUR IMAGE NAME) \nmy_image = \"my_image.jpg\" # change this to the name of your image file \n## END CODE HERE ##\n\n# We preprocess the image to fit your algorithm.\nfname = \"images/\" + my_image\nimage = np.array(ndimage.imread(fname, flatten=False))\nimage = image/255.\nmy_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T\nmy_predicted_image = predict(d[\"w\"], d[\"b\"], my_image)\n\nplt.imshow(image)\nprint(\"y = \" + str(np.squeeze(my_predicted_image)) + \", your algorithm predicts a \\\"\" + classes[int(np.squeeze(my_predicted_image)),].decode(\"utf-8\") + \"\\\" picture.\")",
"y = 0.0, your algorithm predicts a \"non-cat\" picture.\n"
]
],
[
[
"<font color='blue'>\n**What to remember from this assignment:**\n1. Preprocessing the dataset is important.\n2. You implemented each function separately: initialize(), propagate(), optimize(). Then you built a model().\n3. Tuning the learning rate (which is an example of a \"hyperparameter\") can make a big difference to the algorithm. You will see more examples of this later in this course!",
"_____no_output_____"
],
[
"Finally, if you'd like, we invite you to try different things on this Notebook. Make sure you submit before trying anything. Once you submit, things you can play with include:\n - Play with the learning rate and the number of iterations\n - Try different initialization methods and compare the results\n - Test other preprocessings (center the data, or divide each row by its standard deviation)",
"_____no_output_____"
],
[
"Bibliography:\n- http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/\n- https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cbd50610d0b465a50a59cb8d06f930c2c971e5c3
| 479,747 |
ipynb
|
Jupyter Notebook
|
pca.ipynb
|
asantos-6/musicinformationretrieval.com
|
d7649adde62945ec327a3a550c68000284bbd591
|
[
"MIT"
] | 636 |
2018-07-02T09:33:08.000Z
|
2022-03-30T12:50:42.000Z
|
pca.ipynb
|
cheulyop/musicinformationretrieval.com
|
d7649adde62945ec327a3a550c68000284bbd591
|
[
"MIT"
] | 20 |
2016-01-14T14:22:58.000Z
|
2018-04-17T01:04:42.000Z
|
pca.ipynb
|
cheulyop/musicinformationretrieval.com
|
d7649adde62945ec327a3a550c68000284bbd591
|
[
"MIT"
] | 272 |
2018-07-01T15:37:07.000Z
|
2022-03-29T03:18:01.000Z
| 1,325.267956 | 451,736 | 0.910428 |
[
[
[
"import numpy, scipy, matplotlib.pyplot as plt, sklearn, urllib, stanford_mir, IPython.display\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (14, 5)",
"_____no_output_____"
]
],
[
[
"[← Back to Index](index.html)",
"_____no_output_____"
],
[
"# Principal Component Analysis ",
"_____no_output_____"
],
[
"Download a file:",
"_____no_output_____"
]
],
[
[
"filename = '125_bounce.wav'",
"_____no_output_____"
],
[
"url = 'http://audio.musicinformationretrieval.com/'\nurllib.urlretrieve(url + filename, filename=filename)",
"_____no_output_____"
]
],
[
[
"Load a file:",
"_____no_output_____"
]
],
[
[
"x, fs = librosa.load(filename)",
"_____no_output_____"
]
],
[
[
"Listen to the signal:",
"_____no_output_____"
]
],
[
[
"IPython.display.Audio(x, rate=fs)",
"_____no_output_____"
]
],
[
[
"Compute some features:",
"_____no_output_____"
]
],
[
[
"X = librosa.feature.mfcc(x, sr=fs)",
"_____no_output_____"
],
[
"print(X.shape)",
"(20, 331)\n"
]
],
[
[
"Scale the features to have zero mean and unit variance:",
"_____no_output_____"
]
],
[
[
"X = sklearn.preprocessing.scale(X)",
"_____no_output_____"
],
[
"X.mean()",
"_____no_output_____"
]
],
[
[
"Create a PCA model object.",
"_____no_output_____"
]
],
[
[
"model = sklearn.decomposition.PCA(n_components=2, whiten=True)",
"_____no_output_____"
]
],
[
[
"Apply PCA to the scaled features:",
"_____no_output_____"
]
],
[
[
"model.fit(X.T)",
"_____no_output_____"
],
[
"Y = model.transform(X.T)",
"_____no_output_____"
],
[
"print(Y.shape)",
"(331, 2)\n"
]
],
[
[
"Let's see how many principal components were returned:",
"_____no_output_____"
]
],
[
[
"model.components_.shape",
"_____no_output_____"
]
],
[
[
"Plot the two top principal components for each data point:",
"_____no_output_____"
]
],
[
[
"plt.scatter(Y[:,0], Y[:,1])",
"_____no_output_____"
]
],
[
[
"[← Back to Index](index.html)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbd5161ee47ddb1ab205dd8fa854bd1b5b4af864
| 170,229 |
ipynb
|
Jupyter Notebook
|
src/test/testData/ParserTests/40 puzzles.ipynb
|
ileasile/jupyter-notebooks-parser
|
660554f9f54cd7eb9e6436dbbbf476f1a364b093
|
[
"Apache-2.0"
] | null | null | null |
src/test/testData/ParserTests/40 puzzles.ipynb
|
ileasile/jupyter-notebooks-parser
|
660554f9f54cd7eb9e6436dbbbf476f1a364b093
|
[
"Apache-2.0"
] | null | null | null |
src/test/testData/ParserTests/40 puzzles.ipynb
|
ileasile/jupyter-notebooks-parser
|
660554f9f54cd7eb9e6436dbbbf476f1a364b093
|
[
"Apache-2.0"
] | null | null | null | 54.126868 | 2,008 | 0.464721 |
[
[
[
"# 40 kotlin-dataframe puzzles\ninspired by [100 pandas puzzles](https://github.com/ajcr/100-pandas-puzzles)",
"_____no_output_____"
],
[
"## Importing kotlin-dataframe\n### Getting started\nDifficulty: easy\n\n**1.** Import kotlin-dataframe",
"_____no_output_____"
]
],
[
[
"%use dataframe(0.8.0-dev-595-0.11.0.13)",
"_____no_output_____"
]
],
[
[
"## DataFrame Basics\n### A few of the fundamental routines for selecting, sorting, adding and aggregating data in DataFrames\nDifficulty: easy\n\nConsider the following columns:\n```[kotlin]\nval animal by column(\"cat\", \"cat\", \"snake\", \"dog\", \"dog\", \"cat\", \"snake\", \"cat\", \"dog\", \"dog\")\nval age by column(2.5, 3.0, 0.5, Double.NaN, 5.0, 2.0, 4.5, Double.NaN, 7, 3)\nval visits by column(1, 3, 2, 3, 2, 3, 1, 1, 2, 1)\nval priority by column(\"yes\", \"yes\", \"no\", \"yes\", \"no\", \"no\", \"no\", \"yes\", \"no\", \"no\")\n```\n**2.** Create a DataFrame df from this columns.",
"_____no_output_____"
]
],
[
[
"val animal by columnOf(\"cat\", \"cat\", \"snake\", \"dog\", \"dog\", \"cat\", \"snake\", \"cat\", \"dog\", \"dog\")\nval age by columnOf(2.5, 3.0, 0.5, Double.NaN, 5.0, 2.0, 4.5, Double.NaN, 7.0, 3.0)\nval visits by columnOf(1, 3, 2, 3, 2, 3, 1, 1, 2, 1)\nval priority by columnOf(\"yes\", \"yes\", \"no\", \"yes\", \"no\", \"no\", \"no\", \"yes\", \"no\", \"no\")\n\nvar df = dataFrameOf(animal, age, visits, priority)\ndf",
"_____no_output_____"
]
],
[
[
"**3.** Display a summary of the basic information about this DataFrame and its data.",
"_____no_output_____"
]
],
[
[
"df.schema()",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"**4.** Return the first 3 rows of the DataFrame df.",
"_____no_output_____"
]
],
[
[
"df[0 until 3] // df[0..2]\n\n// or equivalently\n\ndf.head(3)\n\n// or\n\ndf.take(3)",
"_____no_output_____"
]
],
[
[
"**5.** Select \"animal\" and \"age\" columns from the DataFrame df.",
"_____no_output_____"
]
],
[
[
"df[animal, age]",
"_____no_output_____"
]
],
[
[
"**6.** Select the data in rows [3, 4, 8] and in columns [\"animal\", \"age\"].",
"_____no_output_____"
]
],
[
[
"df[3, 4, 8][animal, age]",
"_____no_output_____"
]
],
[
[
"**7.** Select only the rows where the number of visits is grater than 2.",
"_____no_output_____"
]
],
[
[
"df.filter { visits > 2 }",
"_____no_output_____"
]
],
[
[
"**8.** Select the rows where the age is missing, i.e. it is NaN.",
"_____no_output_____"
]
],
[
[
"df.filter { age.isNaN() }",
"_____no_output_____"
]
],
[
[
"**9.** Select the rows where the animal is a cat and the age is less than 3.",
"_____no_output_____"
]
],
[
[
"df.filter { animal == \"cat\" && age < 3 }",
"_____no_output_____"
]
],
[
[
"**10.** Select the rows where age is between 2 and 4 (inclusive).",
"_____no_output_____"
]
],
[
[
"df.filter { age in 2.0..4.0 }",
"_____no_output_____"
]
],
[
[
"**11.** Change tha age in row 5 to 1.5",
"_____no_output_____"
]
],
[
[
"df.update { age }.at(5).withValue(1.5)",
"_____no_output_____"
]
],
[
[
"**12.** Calculate the sum of all visits in df (i.e. the total number of visits).",
"_____no_output_____"
]
],
[
[
"df.visits.sum()",
"_____no_output_____"
]
],
[
[
"**13.** Calculate the mean age for each different animal in df.",
"_____no_output_____"
]
],
[
[
"df.groupBy { animal }.mean { age }",
"_____no_output_____"
]
],
[
[
"**14.** Append a new row to df with your choice of values for each column. Then delete that row to return the original DataFrame.",
"_____no_output_____"
]
],
[
[
"val modifiedDf = df.append(\"dog\", 5.5, 2, \"no\")\nmodifiedDf.dropLast()",
"_____no_output_____"
]
],
[
[
"**15.** Count the number of each type of animal in df.",
"_____no_output_____"
]
],
[
[
"df.groupBy { animal }.count()",
"_____no_output_____"
]
],
[
[
"**16.** Sort df first by the values in the 'age' in decending order, then by the value in the 'visits' column in ascending order.",
"_____no_output_____"
]
],
[
[
"df.sortBy { age.desc() and visits }",
"_____no_output_____"
]
],
[
[
"**17.** The 'priority' column contains the values 'yes' and 'no'. Replace this column with a column of boolean values: 'yes' should be True and 'no' should be False.",
"_____no_output_____"
]
],
[
[
"df.convert { priority }.with { it == \"yes\" }",
"_____no_output_____"
]
],
[
[
"**18.** In the 'animal' column, change the 'dog' entries to 'corgi'.",
"_____no_output_____"
]
],
[
[
"df.update { animal }.where { it == \"dog\" }.with { \"corgi\" }",
"_____no_output_____"
]
],
[
[
"**19.** For each animal type and each number of visits, find the mean age. In other words, each row is an animal, each column is a number of visits and the values are the mean ages (hint: use a pivot table).",
"_____no_output_____"
]
],
[
[
"df.pivot(inward = false) { visits }.groupBy { animal }.mean(skipNA = true) { age }",
"_____no_output_____"
]
],
[
[
"## DataFrame: beyond the basics\n### Slightly trickier: you may need to combine two or more methods to get the right answer\nDifficulty: medium\n\nThe previous section was tour through some basic but essential DataFrame operations. Below are some ways that you might need to cut your data, but for which there is no single \"out of the box\" method.",
"_____no_output_____"
],
[
"**20.** You have a DataFrame df with a column 'A' of integers. For example:\n```kotlin\nval df = dataFrameOf(\"A\")(1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7)\n```\nHow do you filter out rows which contain the same integer as the row immediately above?\n\nYou should be left with a column containing the following values:\n```\n1, 2, 3, 4, 5, 6, 7\n```",
"_____no_output_____"
]
],
[
[
"val df = dataFrameOf(\"A\")(1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7)\ndf",
"_____no_output_____"
],
[
"df.filter { prev()?.A != A }",
"_____no_output_____"
],
[
"df.filter { diff { A } != 0 }",
"_____no_output_____"
]
],
[
[
"We could use `distinct()` here but it won't work as desired if A is [1, 1, 2, 2, 1, 1] for example.",
"_____no_output_____"
]
],
[
[
"df.distinct()",
"_____no_output_____"
]
],
[
[
"**21.** Given a DataFrame of random numetic values:\n```kotlin\nval df = dataFrameOf(\"a\", \"b\", \"c\").randomDouble(5) // this is a 5x3 DataFrame of double values\n```\n\nhow do you subtract the row mean from each element in the row?",
"_____no_output_____"
]
],
[
[
"val df = dataFrameOf(\"a\", \"b\", \"c\").randomDouble(5)\ndf",
"_____no_output_____"
],
[
"df.update { colsOf<Double>() }\n .with { it - rowMean() }",
"_____no_output_____"
]
],
[
[
"**22.** Suppose you have DataFrame with 10 columns of real numbers, for example:\n```kotlin\nval names = ('a'..'j').map { it.toString() }\nval df = dataFrameOf(names).randomDouble(5)\n```\n\nWhich column of number has the smallest sum? Return that column's label.",
"_____no_output_____"
]
],
[
[
"val names = ('a'..'j').map { it.toString() }\nval df = dataFrameOf(names).randomDouble(5)\ndf",
"_____no_output_____"
],
[
"df.sum().transpose().minBy(\"value\")[\"name\"]",
"_____no_output_____"
]
],
[
[
"**23.** How do you count how many unique rows a DataFrame has (i.e. ignore all rows that are duplicates)?",
"_____no_output_____"
]
],
[
[
"val df = dataFrameOf(\"a\", \"b\", \"c\").randomInt(30, 0..2)\ndf.distinct().nrow()",
"_____no_output_____"
]
],
[
[
"**24.** In the cell below, you have a DataFrame `df` that consists of 10 columns of floating-point numbers. Exactly 5 entries in each row are NaN values.\n\nFor each row of the DataFrame, find the *column* which contains the *third* NaN value.\n\nYou should return a Series of column labels: `e, c, d, h, d`",
"_____no_output_____"
]
],
[
[
"val nan = Double.NaN\nval names = ('a'..'j').map { it.toString() }\nval data = listOf(\n 0.04, nan, nan, 0.25, nan, 0.43, 0.71, 0.51, nan, nan,\n nan, nan, nan, 0.04, 0.76, nan, nan, 0.67, 0.76, 0.16,\n nan, nan, 0.5 , nan, 0.31, 0.4 , nan, nan, 0.24, 0.01,\n 0.49, nan, nan, 0.62, 0.73, 0.26, 0.85, nan, nan, nan,\n nan, nan, 0.41, nan, 0.05, nan, 0.61, nan, 0.48, 0.68\n)\nval df = dataFrameOf(names)(*data.toTypedArray())\ndf",
"_____no_output_____"
],
[
"df.map(\"res\") { \n namedValuesOf<Double>()\n .filter { it.value.isNaN() }.drop(2)\n .firstOrNull()?.name \n}",
"_____no_output_____"
]
],
[
[
"**25.** A DataFrame has a column of groups 'grps' and and column of integer values 'vals':\n```kotlin\nval grps by column(\"a\", \"a\", \"a\", \"b\", \"b\", \"c\", \"a\", \"a\", \"b\", \"c\", \"c\", \"c\", \"b\", \"b\", \"c\")\nval vals by column(12, 345, 3, 1, 45, 14, 4, 52, 54, 23, 235, 21, 57, 3, 87)\n\nval df = dataFrameOf(grps, vals)\n```\n\nFor each group, find the sum of the three greatest values. You should end up with the answer as follows:\n```\ngrps\na 409\nb 156\nc 345\n```",
"_____no_output_____"
]
],
[
[
"val grps by columnOf(\"a\", \"a\", \"a\", \"b\", \"b\", \"c\", \"a\", \"a\", \"b\", \"c\", \"c\", \"c\", \"b\", \"b\", \"c\")\nval vals by columnOf(12, 345, 3, 1, 45, 14, 4, 52, 54, 23, 235, 21, 57, 3, 87)\n\nval df = dataFrameOf(grps, vals)\ndf",
"_____no_output_____"
],
[
"df.groupBy { grps }.aggregate { \n vals.sortDesc().take(3).sum() into \"res\"\n}",
"_____no_output_____"
]
],
[
[
"**26.** The DataFrame `df` constructed below has two integer columns 'A' and 'B'. The values in 'A' are between 1 and 100 (inclusive).\n\nFor each group of 10 consecutive integers in 'A' (i.e. `(0, 10]`, `(10, 20]`, ...), calculate the sum of the corresponding values in column 'B'.\n\nThe answer as follows:\n\n```\nA\n(0, 10] 635\n(10, 20] 360\n(20, 30] 315\n(30, 40] 306\n(40, 50] 750\n(50, 60] 284\n(60, 70] 424\n(70, 80] 526\n(80, 90] 835\n(90, 100] 852\n```",
"_____no_output_____"
]
],
[
[
"import kotlin.random.Random\n\nval random = Random(42)\nval list = List(200) { random.nextInt(1, 101)}\nval df = dataFrameOf(\"A\", \"B\")(*list.toTypedArray())\ndf",
"_____no_output_____"
],
[
"df.groupBy { A.map { (it - 1) / 10 } }.sum { B }\n .sortBy { A }\n .convert { A }.with { \"(${it * 10}, ${it * 10 + 10}]\" }",
"_____no_output_____"
]
],
[
[
"## DataFrames: harder problems\n\n### These might require a bit of thinking outside the box...\n\nDifficulty: hard",
"_____no_output_____"
],
[
"**27.** Consider a DataFrame `df` where there is an integer column 'X':\n```kotlin\nval df = dataFrameOf(\"X\")(7, 2, 0, 3, 4, 2, 5, 0, 3 , 4)\n```\nFor each value, count the difference back to the previous zero (or the start of the column, whichever is closer). These values should therefore be\n\n```\n[1, 2, 0, 1, 2, 3, 4, 0, 1, 2]\n```\n\nMake this a new column 'Y'.",
"_____no_output_____"
]
],
[
[
"val df = dataFrameOf(\"X\")(7, 2, 0, 3, 4, 2, 5, 0, 3 , 4)\ndf",
"_____no_output_____"
],
[
"df.map(\"Y\") {\n if(it.X == 0) 0 else (prev()?.new() ?: 0) + 1\n}",
"_____no_output_____"
]
],
[
[
"**28.** Consider the DataFrame constructed below which contains rows and columns of numerical data.\n\nCreate a list of the column-row index locations of the 3 largest values in this DataFrame. In thi case, the answer should be:\n```\n[(0, d), (2, c), (3, f)]\n```",
"_____no_output_____"
]
],
[
[
"val names = ('a'..'h').map { it.toString() } // val names = (0..7).map { it.toString() }\nval random = Random(30)\nval list = List(64) { random.nextInt(1, 101) }\nval df = dataFrameOf(names)(*list.toTypedArray())\ndf",
"_____no_output_____"
],
[
"df.add(\"index\") { index() }\n .gather { dropLast() }.into(\"name\", \"vals\")\n .sortByDesc(\"vals\").take(3)[\"index\", \"name\"]",
"_____no_output_____"
]
],
[
[
"**29.** You are given the DataFrame below with a column of group IDs, 'grps', and a column of corresponding integer values, 'vals'.\n\n```kotlin\nval random = Random(31)\nval lab = listOf(\"A\", \"B\")\n\nval vals by columnOf(List(15) { random.nextInt(-30, 30) })\nval grps by columnOf(List(15) { lab[random.nextInt(0, 2)] })\n\nval df = dataFrameOf(vals, grps)\n```\n\nCreate a new column 'patched_values' which contains the same values as the 'vals' any negative values in 'vals' with the group mean:\n\n```\nvals grps patched_vals\n-17\tB\t21.000000\n-7\tB\t21.000000\n28\tB\t28.000000\n16\tB\t16.000000\n-21\tB\t21.000000\n19\tB\t19.000000\n-2\tB\t21.000000\n-19\tB\t21.000000\n16\tA\t16.000000\n9\tA\t9.000000\n-14\tA\t16.000000\n-19\tA\t16.000000\n-22\tA\t16.000000\n-1\tA\t16.000000\n23\tA\t23.000000\n```",
"_____no_output_____"
]
],
[
[
"val random = Random(31)\nval lab = listOf(\"A\", \"B\")\n\nval vals by columnOf(*Array(15) { random.nextInt(-30, 30) })\nval grps by columnOf(*Array(15) { lab[random.nextInt(0, 2)] })\n\nval df = dataFrameOf(vals, grps)\ndf",
"_____no_output_____"
],
[
"val means = df.filter { vals >= 0 }\n .groupBy { grps }.mean() \n .pivot { grps }.values { vals }\n\ndf.add(\"patched_values\") {\n if(vals < 0) means[grps] else vals\n}",
"_____no_output_____"
]
],
[
[
"**30.** Implement a rolling mean over groups with window size 3, which ignores NaN value. For example consider the following DataFrame:\n```kotlin\nval group by columnOf(\"a\", \"a\", \"b\", \"b\", \"a\", \"b\", \"b\", \"b\", \"a\", \"b\", \"a\", \"b\")\nval value by columnOf(1.0, 2.0, 3.0, Double.NaN, 2.0, 3.0, Double.NaN, 1.0, 7.0, 3.0, Double.NaN, 8.0)\n\nval df = dataFrameOf(group, value)\ndf\n\ngroup value\na 1.0\na 2.0\nb 3.0\nb NaN\na 2.0\nb 3.0\nb NaN\nb 1.0\na 7.0\nb 3.0\na NaN\nb 8.0\n```\nThe goal is:\n```\n1.000000\n1.500000\n3.000000\n3.000000\n1.666667\n3.000000\n3.000000\n2.000000\n3.666667\n2.000000\n4.500000\n4.000000\n```\nE.g. the first window of size three for group 'b' has values 3.0, NaN and 3.0 and occurs at row index 5. Instead of being NaN the value in the new column at this row index should be 3.0 (just the two non-NaN values are used to compute the mean (3+3)/2)",
"_____no_output_____"
]
],
[
[
"val groups by columnOf(\"a\", \"a\", \"b\", \"b\", \"a\", \"b\", \"b\", \"b\", \"a\", \"b\", \"a\", \"b\")\nval value by columnOf(1.0, 2.0, 3.0, Double.NaN, 2.0, 3.0, Double.NaN, 1.0, 7.0, 3.0, Double.NaN, 8.0)\n\nval df = dataFrameOf(groups, value)\ndf",
"_____no_output_____"
],
[
"df.add(\"id\"){ index() }\n .groupBy { groups }.add(\"res\") {\n near(-2..0).map { it.value }.filter { !it.isNaN() }.average()\n }.concat()\n .sortBy(\"id\")\n .remove(\"id\")",
"_____no_output_____"
]
],
[
[
"## Date\nDifficulty: easy/medium",
"_____no_output_____"
],
[
"**31.** Create a column Of LocalDate that contains each day of 2015 and column of random numbers.",
"_____no_output_____"
]
],
[
[
"@file:DependsOn(\"org.jetbrains.kotlinx:kotlinx-datetime-jvm:0.3.1\")",
"_____no_output_____"
],
[
"import kotlinx.datetime.*",
"_____no_output_____"
],
[
"class DateRangeIterator(first: LocalDate, last: LocalDate, val step: Int) : Iterator<LocalDate> {\n private val finalElement: LocalDate = last\n private var hasNext: Boolean = if (step > 0) first <= last else first >= last\n private var next: LocalDate = if (hasNext) first else finalElement\n\n override fun hasNext(): Boolean = hasNext\n\n override fun next(): LocalDate {\n val value = next\n if (value == finalElement) {\n if (!hasNext) throw kotlin.NoSuchElementException()\n hasNext = false\n }\n else {\n next = next.plus(step, DateTimeUnit.DayBased(1))\n }\n return value\n }\n}\n\noperator fun ClosedRange<LocalDate>.iterator() = DateRangeIterator(this.start, this.endInclusive, 1)\n\nfun ClosedRange<LocalDate>.toList(): List<LocalDate> {\n return when (val size = this.start.daysUntil(this.endInclusive)) {\n 0 -> emptyList()\n 1 -> listOf(iterator().next())\n else -> {\n val dest = ArrayList<LocalDate>(size)\n for (item in this) {\n dest.add(item)\n }\n dest\n }\n }\n}",
"_____no_output_____"
],
[
"val start = LocalDate(2015, 1, 1)\nval end = LocalDate(2016, 1, 1)\n\nval days = (start..end).toList()\n\nval dti = days.toColumn(\"dti\")\nval s = List(dti.size()) { Random.nextDouble() }.toColumn(\"s\")\nval df = dataFrameOf(dti, s)\ndf.head()",
"_____no_output_____"
]
],
[
[
"**32.** Find the sum of the values in s for every Wednesday.",
"_____no_output_____"
]
],
[
[
"df.filter { dti.dayOfWeek.ordinal == 2 }.sum { s }",
"_____no_output_____"
]
],
[
[
"**33.** For each calendar month in s, find the mean of values.",
"_____no_output_____"
]
],
[
[
"df.groupBy { dti.map { it.month } named \"month\" }.mean()",
"_____no_output_____"
]
],
[
[
"**34.** For each group of four consecutive calendar months in s, find the date on which the highest value occurred.",
"_____no_output_____"
]
],
[
[
"df.add(\"month4\") {\n when(dti.monthNumber) {\n in 1..4 -> 1\n in 5..8 -> 2\n else -> 3\n }\n}.groupBy(\"month4\").aggregate { maxBy(s) into \"max\" }.flatten()",
"_____no_output_____"
]
],
[
[
"**35.** Create a column consisting of the third Thursday in each month for the years 2015 and 2016.",
"_____no_output_____"
]
],
[
[
"import java.time.temporal.WeekFields\nimport java.util.*",
"_____no_output_____"
],
[
"val start = LocalDate(2015, 1, 1)\nval end = LocalDate(2016, 12, 31)\n\n(start..end).toList().toColumn(\"3thu\").filter { \n it.toJavaLocalDate()[WeekFields.of(Locale.ENGLISH).weekOfMonth()] == 3\n && it.dayOfWeek.value == 4\n }",
"_____no_output_____"
]
],
[
[
"## Cleaning Data\n### Making a DataFrame easier to work with\nDifficulty: *easy/medium*\n\nIt happens all the time: someone gives you data containing malformed strings, lists and missing data. How do you tidy it up so you can get on with the analysis?\n\nTake this monstrosity as the DataFrame to use in the following puzzles:\n```kotlin\nval fromTo = listOf(\"LoNDon_paris\", \"MAdrid_miLAN\", \"londON_StockhOlm\", \"Budapest_PaRis\", \"Brussels_londOn\").toColumn(\"From_To\")\nval flightNumber = listOf(10045.0, Double.NaN, 10065.0, Double.NaN, 10085.0).toColumn(\"FlightNumber\")\nval recentDelays = listOf(listOf(23, 47), listOf(), listOf(24, 43, 87), listOf(13), listOf(67, 32)).toColumn(\"RecentDelays\")\nval airline = listOf(\"KLM(!)\", \"<Air France> (12)\", \"(British Airways. )\", \"12. Air France\", \"'Swiss Air'\").toColumn(\"Airline\")\n\nval df = dataFrameOf(fromTo, flightNumber, recentDelays, airline)\n```\n\nIt looks like this:\n```\nFrom_To FlightNumber RecentDelays Airline\nLoNDon_paris 10045.000000 [23, 47] KLM(!)\nMAdrid_miLAN NaN [] {Air France} (12)\nlondON_StockhOlm 10065.000000 [24, 43, 87] (British Airways. )\nBudapest_PaRis NaN [13] 12. Air France\nBrussels_londOn 10085.000000 [67, 32] 'Swiss Air'\n```",
"_____no_output_____"
]
],
[
[
"val fromTo = listOf(\"LoNDon_paris\", \"MAdrid_miLAN\", \"londON_StockhOlm\", \"Budapest_PaRis\", \"Brussels_londOn\").toColumn(\"From_To\")\nval flightNumber = listOf(10045.0, Double.NaN, 10065.0, Double.NaN, 10085.0).toColumn(\"FlightNumber\")\nval recentDelays = listOf(listOf(23, 47), listOf(), listOf(24, 43, 87), listOf(13), listOf(67, 32)).toColumn(\"RecentDelays\")\nval airline = listOf(\"KLM(!)\", \"{Air France} (12)\", \"(British Airways. )\", \"12. Air France\", \"'Swiss Air'\").toColumn(\"Airline\")\n\nvar df = dataFrameOf(fromTo, flightNumber, recentDelays, airline)\ndf",
"_____no_output_____"
]
],
[
[
"**36.** Some values in the FlightNumber column are missing (they are NaN). These numbers are meant to increase by 10 with each row, so 10055 and 10075 need to be put in place. Modify df to fill in these missing numbers and make the column an integer column (instead of a float column).",
"_____no_output_____"
]
],
[
[
"val df1 = df.update { FlightNumber }\n .where { it.isNaN() }.with { prev()!!.FlightNumber + (next()!!.FlightNumber - prev()!!.FlightNumber) / 2 }\n .convert { FlightNumber }.toInt()\ndf1",
"_____no_output_____"
]
],
[
[
"**37.** The **From_To** column would be better as two separate columns! Split each string on the underscore delimiter **_** to give a new two columns. Assign the correct names 'From' and 'To' to this columns.",
"_____no_output_____"
]
],
[
[
"var df2 = df.split { From_To }.by(\"_\").into(\"From\", \"To\")\ndf2",
"_____no_output_____"
]
],
[
[
"**38.** Notice how the capitalisation of the city names is all mixed up in this temporary DataFrame 'temp'. Standardise the strings so that only the first letter is uppercase (e.g. \"londON\" should become \"London\".)",
"_____no_output_____"
]
],
[
[
"df2 = df2.update { From and To }.with { it.lowercase().replaceFirstChar(Char::uppercase) }\ndf2",
"_____no_output_____"
]
],
[
[
"**39.** In the **Airline** column, you can see some extra punctuation and symbols have appeared around the airline names. Pull out just the airline name. E.g. `'(British Airways. )'` should become `'British Airways'`.",
"_____no_output_____"
]
],
[
[
"df2 = df2.update { Airline }.with {\n \"([a-zA-Z\\\\s]+)\".toRegex().find(it)?.value ?: \"\"\n }\ndf2",
"_____no_output_____"
]
],
[
[
"**40.** In the **RecentDelays** column, the values have been entered into the DataFrame as a list. We would like each first value in its own column, each second value in its own column, and so on. If there isn't an Nth value, the value should be NaN.\n\nExpand the column of lists into columns named 'delays_' and replace the unwanted RecentDelays column in `df` with 'delays'.",
"_____no_output_____"
]
],
[
[
"val prep_df = df2\n .convert { RecentDelays }.with { it.map { it.toDouble() } }\n .split { RecentDelays }.default(Double.NaN).into { \"delay_$it\" }\nprep_df",
"_____no_output_____"
]
],
[
[
"The DataFrame should look much better now:\n\n|From |To |FlightNumber |delay_1 |delay_2 |delay_3 |Airline |\n|------------|----------|-----------------|---------------|---------------|---------------|----------------|\n|London |Paris |10045 |23.000000 |47.000000 |NaN |KLM |\n|Madrid |Milan |10055 |NaN |NaN |NaN |Air France |\n|London |Stockholm |10065 |24.000000 |43.000000 |87.000000 |British Airways |\n|Budapest |Paris |10075 |13.000000 |NaN |NaN | Air France |\n|Brussels |London |10085 |67.000000 |32.000000 |NaN |Swiss Air |",
"_____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"
] |
[
[
"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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbd51a31cbc6b2182ca174395e750b85afcd4c92
| 314,915 |
ipynb
|
Jupyter Notebook
|
1_ET/3_Olena_Analyze/VegET_validation-Copy1.ipynb
|
tonybutzer/etscrum
|
e36fb68c01e7ce8581a6d16cccc71cad369eca24
|
[
"MIT"
] | null | null | null |
1_ET/3_Olena_Analyze/VegET_validation-Copy1.ipynb
|
tonybutzer/etscrum
|
e36fb68c01e7ce8581a6d16cccc71cad369eca24
|
[
"MIT"
] | null | null | null |
1_ET/3_Olena_Analyze/VegET_validation-Copy1.ipynb
|
tonybutzer/etscrum
|
e36fb68c01e7ce8581a6d16cccc71cad369eca24
|
[
"MIT"
] | null | null | null | 99.625119 | 103,600 | 0.752619 |
[
[
[
"# Veg ET validation",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom time import time\nimport xarray as xr\nimport numpy as np",
"_____no_output_____"
],
[
"def _get_year_month(product, tif):\n fn = tif.split('/')[-1]\n fn = fn.replace(product,'')\n fn = fn.replace('.tif','')\n fn = fn.replace('_','')\n print(fn)\n return fn",
"_____no_output_____"
],
[
"def _file_object(bucket_prefix,product_name,year,day):\n if product_name == 'NDVI':\n decade = str(year)[:3]+'0'\n variable_prefix = bucket_prefix + 'NDVI_FORE_SCE_MED/delaware_basin_FS_'\n file_object = variable_prefix + str(decade) + '/' + 'FS_{0}_{1}_med_{2}.tif'.format(str(decade), product_name, day)\n elif product_name == 'ETo':\n decade = str(year)[:3]+'0'\n variable_prefix = bucket_prefix +'ETo_Moving_Average_byDOY/'\n file_object = variable_prefix + '{0}_{1}/'.format(str(decade), str(int(decade)+10)) + '{0}_DOY{1}.tif'.format(product_name,day)\n elif product_name == 'Tasavg' or product_name == 'Tasmax' or product_name == 'Tasmin':\n variable_prefix = bucket_prefix + 'Temp/' + product_name + '/'\n #variable_prefix = bucket_prefix + 'TempCelsius/' + product_name + '/'\n file_object = variable_prefix + str(year) + '/' + '{}_'.format(product_name) + str(year) + day + '.tif'\n elif product_name == 'PPT':\n variable_prefix = bucket_prefix + product_name + '/'\n file_object = variable_prefix + str(year) + '/' + '{}_'.format(product_name) + str(year) + day + '.tif'\n else:\n file_object = bucket_prefix + str(start_year) + '/' + f'{product_name}_' + str(start_year) + day + '.tif'\n return file_object",
"_____no_output_____"
],
[
"def create_s3_list_of_days_start_end(main_bucket_prefix, start_year,start_day, end_year, end_day, product_name):\n the_list = []\n years = []\n for year in (range(int(start_year),int(end_year)+1)):\n years.append(year)\n if len(years) == 1:\n for i in range(int(start_day),int(end_day)):\n day = f'{i:03d}'\n file_object = _file_object(main_bucket_prefix,product_name,start_year,day)\n the_list.append(file_object)\n elif len(years) == 2:\n for i in range(int(start_day),366):\n day = f'{i:03d}'\n file_object = _file_object(main_bucket_prefix,product_name,start_year,day)\n the_list.append(file_object)\n for i in range(1,int(end_day)):\n day = f'{i:03d}'\n file_object = _file_object(main_bucket_prefix,product_name,end_year,day)\n the_list.append(file_object)\n else:\n for i in range(int(start_day),366):\n day = f'{i:03d}'\n file_object = _file_object(main_bucket_prefix,product_name,start_year,day)\n the_list.append(file_object)\n for year in years[1:-1]:\n for i in range(1,366):\n day = f'{i:03d}'\n file_object = _file_object(main_bucket_prefix,product_name,year,day)\n the_list.append(file_object)\n for i in range(1,int(end_day)):\n day = f'{i:03d}'\n file_object = _file_object(main_bucket_prefix,product_name,end_year,day)\n the_list.append(file_object)\n return the_list",
"_____no_output_____"
],
[
"def xr_build_cube_concat_ds_one(tif_list, product, x, y):\n start = time()\n my_da_list =[]\n year_month_list = []\n for tif in tif_list:\n #tiffile = 's3://dev-et-data/' + tif\n tiffile = tif\n print(tiffile)\n da = xr.open_rasterio(tiffile)\n daSub = da.sel(x=x, y=y, method='nearest')\n #da = da.squeeze().drop(labels='band')\n #da.name=product\n my_da_list.append(daSub)\n tnow = time()\n elapsed = tnow - start\n print(tif, elapsed)\n year_month_list.append(_get_year_month(product, tif))\n\n da = xr.concat(my_da_list, dim='band')\n da = da.rename({'band':'year_month'})\n da = da.assign_coords(year_month=year_month_list)\n DS = da.to_dataset(name=product)\n return(DS)",
"_____no_output_____"
],
[
"main_bucket_prefix='s3://dev-et-data/in/DelawareRiverBasin/'\nstart_year = '1950'\nstart_day = '1'\nend_year = '1950'\nend_day = '11'\nx=-75\ny =41",
"_____no_output_____"
]
],
[
[
"## Step 1: Get pixel values for input variables",
"_____no_output_____"
]
],
[
[
"df_list=[]\nfor product in ['PPT','Tasavg', 'Tasmin', 'Tasmax', 'NDVI', 'ETo']:\n print(\"===\"*30)\n print(\"processing product\",product)\n tif_list = create_s3_list_of_days_start_end(main_bucket_prefix, start_year,start_day, end_year, end_day, product)\n print (tif_list)\n ds_pix=xr_build_cube_concat_ds_one(tif_list, product, x, y)\n my_index = ds_pix['year_month'].values\n my_array = ds_pix[product].values\n df = pd.DataFrame(my_array, columns=[product,], index=my_index)\n df_list.append(df)\n ",
"==========================================================================================\nprocessing product PPT\n['s3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950001.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950002.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950003.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950004.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950005.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950006.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950007.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950008.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950009.tif', 's3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950010.tif']\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950001.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950001.tif 0.47864317893981934\n1950001\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950002.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950002.tif 0.6047778129577637\n1950002\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950003.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950003.tif 0.7098016738891602\n1950003\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950004.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950004.tif 0.8149271011352539\n1950004\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950005.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950005.tif 0.9783620834350586\n1950005\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950006.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950006.tif 1.10514235496521\n1950006\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950007.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950007.tif 1.2305400371551514\n1950007\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950008.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950008.tif 1.3996870517730713\n1950008\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950009.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950009.tif 1.5080335140228271\n1950009\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950010.tif\ns3://dev-et-data/in/DelawareRiverBasin/PPT/1950/PPT_1950010.tif 1.6189475059509277\n1950010\n==========================================================================================\nprocessing product Tasavg\n['s3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950001.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950002.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950003.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950004.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950005.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950006.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950007.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950008.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950009.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950010.tif']\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950001.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950001.tif 0.1301119327545166\n1950001\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950002.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950002.tif 0.27252197265625\n1950002\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950003.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950003.tif 0.45270514488220215\n1950003\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950004.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950004.tif 0.5668902397155762\n1950004\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950005.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950005.tif 0.6805555820465088\n1950005\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950006.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950006.tif 0.7869186401367188\n1950006\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950007.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950007.tif 0.9000794887542725\n1950007\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950008.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950008.tif 1.0350134372711182\n1950008\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950009.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950009.tif 1.165743350982666\n1950009\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950010.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasavg/1950/Tasavg_1950010.tif 1.283900260925293\n1950010\n==========================================================================================\nprocessing product Tasmin\n['s3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950001.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950002.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950003.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950004.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950005.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950006.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950007.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950008.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950009.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950010.tif']\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950001.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950001.tif 0.1281726360321045\n1950001\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950002.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950002.tif 0.2673990726470947\n1950002\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950003.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950003.tif 0.4204387664794922\n1950003\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950004.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950004.tif 0.5597665309906006\n1950004\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950005.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950005.tif 0.6729238033294678\n1950005\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950006.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950006.tif 0.7960042953491211\n1950006\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950007.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950007.tif 0.917588472366333\n1950007\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950008.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950008.tif 1.0498933792114258\n1950008\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950009.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950009.tif 1.1947152614593506\n1950009\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950010.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmin/1950/Tasmin_1950010.tif 1.3310215473175049\n1950010\n==========================================================================================\nprocessing product Tasmax\n['s3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950001.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950002.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950003.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950004.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950005.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950006.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950007.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950008.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950009.tif', 's3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950010.tif']\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950001.tif\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950001.tif 0.11693382263183594\n1950001\ns3://dev-et-data/in/DelawareRiverBasin/Temp/Tasmax/1950/Tasmax_1950002.tif\n"
],
[
"df_reset_list = []\nfor dframe in df_list:\n print (dframe)\n df_reset = dframe.set_index(df_list[0].index)\n print (df_reset)\n df_reset_list.append(df_reset)\ndf_veget = pd.concat(df_reset_list, axis=1)\ndf_veget['NDVI'] *= 0.0001\ndf_veget['Tasavg'] -= 273.15\ndf_veget['Tasmin'] -= 273.15\ndf_veget['Tasmax'] -= 273.15\ndf_veget",
" PPT\n1950001 22.103655\n1950002 10.489694\n1950003 12.496798\n1950004 0.000000\n1950005 0.000000\n1950006 0.000000\n1950007 0.000000\n1950008 0.000000\n1950009 2.937698\n1950010 0.000000\n PPT\n1950001 22.103655\n1950002 10.489694\n1950003 12.496798\n1950004 0.000000\n1950005 0.000000\n1950006 0.000000\n1950007 0.000000\n1950008 0.000000\n1950009 2.937698\n1950010 0.000000\n Tasavg\n1950001 279.295715\n1950002 276.374756\n1950003 281.106750\n1950004 276.876587\n1950005 274.469666\n1950006 273.120117\n1950007 272.331268\n1950008 270.107239\n1950009 268.194641\n1950010 268.863678\n Tasavg\n1950001 279.295715\n1950002 276.374756\n1950003 281.106750\n1950004 276.876587\n1950005 274.469666\n1950006 273.120117\n1950007 272.331268\n1950008 270.107239\n1950009 268.194641\n1950010 268.863678\n Tasmin\n1950001 274.587250\n1950002 271.933441\n1950003 276.610107\n1950004 271.856262\n1950005 270.783295\n1950006 270.250427\n1950007 268.920105\n1950008 266.844452\n1950009 264.575745\n1950010 265.103790\n Tasmin\n1950001 274.587250\n1950002 271.933441\n1950003 276.610107\n1950004 271.856262\n1950005 270.783295\n1950006 270.250427\n1950007 268.920105\n1950008 266.844452\n1950009 264.575745\n1950010 265.103790\n Tasmax\n1950001 284.004181\n1950002 280.816101\n1950003 285.603394\n1950004 281.896881\n1950005 278.156067\n1950006 275.989807\n1950007 275.742432\n1950008 273.369995\n1950009 271.813538\n1950010 272.623566\n Tasmax\n1950001 284.004181\n1950002 280.816101\n1950003 285.603394\n1950004 281.896881\n1950005 278.156067\n1950006 275.989807\n1950007 275.742432\n1950008 273.369995\n1950009 271.813538\n1950010 272.623566\n NDVI\nFS1950med001 4113.0\nFS1950med002 4038.0\nFS1950med003 3970.0\nFS1950med004 3909.0\nFS1950med005 3855.0\nFS1950med006 3808.0\nFS1950med007 3766.0\nFS1950med008 3730.0\nFS1950med009 3698.0\nFS1950med010 3671.0\n NDVI\n1950001 4113.0\n1950002 4038.0\n1950003 3970.0\n1950004 3909.0\n1950005 3855.0\n1950006 3808.0\n1950007 3766.0\n1950008 3730.0\n1950009 3698.0\n1950010 3671.0\n ETo\nDOY001 0.54\nDOY002 1.03\nDOY003 0.83\nDOY004 1.03\nDOY005 0.89\nDOY006 1.03\nDOY007 0.96\nDOY008 0.87\nDOY009 1.16\nDOY010 1.17\n ETo\n1950001 0.54\n1950002 1.03\n1950003 0.83\n1950004 1.03\n1950005 0.89\n1950006 1.03\n1950007 0.96\n1950008 0.87\n1950009 1.16\n1950010 1.17\n"
],
[
"for static_product in ['awc', 'por', 'fc', 'intercept', 'water']:\n if static_product == 'awc' or static_product == 'por' or static_product == 'fc':\n file_object = ['s3://dev-et-data/in/NorthAmerica/Soil/' + '{}_NA_mosaic.tif'.format(static_product)]\n elif static_product == 'intercept':\n file_object = ['s3://dev-et-data/in/NorthAmerica/Soil/' + 'Intercept2016_nowater_int.tif']\n else:\n file_object = ['s3://dev-et-data/in/DelawareRiverBasin/' + 'DRB_water_mask_inland.tif']\n ds_pix=xr_build_cube_concat_ds_one(file_object, static_product, x, y)\n df_veget['{}'.format(static_product)] = ds_pix[static_product].values[0]\nprint (df_veget)\n",
"s3://dev-et-data/in/NorthAmerica/Soil/awc_NA_mosaic.tif\ns3://dev-et-data/in/NorthAmerica/Soil/awc_NA_mosaic.tif 0.5414783954620361\nNAmosaic\ns3://dev-et-data/in/NorthAmerica/Soil/por_NA_mosaic.tif\ns3://dev-et-data/in/NorthAmerica/Soil/por_NA_mosaic.tif 0.4496116638183594\nNAmosaic\ns3://dev-et-data/in/NorthAmerica/Soil/fc_NA_mosaic.tif\ns3://dev-et-data/in/NorthAmerica/Soil/fc_NA_mosaic.tif 0.5490615367889404\nNAmosaic\ns3://dev-et-data/in/NorthAmerica/Soil/Intercept2016_nowater_int.tif\ns3://dev-et-data/in/NorthAmerica/Soil/Intercept2016_nowater_int.tif 0.4282236099243164\nIntercept2016nowaterint\ns3://dev-et-data/in/DelawareRiverBasin/DRB_water_mask_inland.tif\ns3://dev-et-data/in/DelawareRiverBasin/DRB_water_mask_inland.tif 0.2876427173614502\nDRBmaskinland\n PPT Tasavg Tasmin Tasmax NDVI ETo awc \\\n1950001 22.103655 6.145721 1.437256 10.854187 0.4113 0.54 170.0 \n1950002 10.489694 3.224762 -1.216553 7.666107 0.4038 1.03 170.0 \n1950003 12.496798 7.956757 3.460114 12.453400 0.3970 0.83 170.0 \n1950004 0.000000 3.726593 -1.293732 8.746887 0.3909 1.03 170.0 \n1950005 0.000000 1.319672 -2.366699 5.006073 0.3855 0.89 170.0 \n1950006 0.000000 -0.029877 -2.899567 2.839813 0.3808 1.03 170.0 \n1950007 0.000000 -0.818726 -4.229889 2.592438 0.3766 0.96 170.0 \n1950008 0.000000 -3.042755 -6.305542 0.220001 0.3730 0.87 170.0 \n1950009 2.937698 -4.955353 -8.574249 -1.336456 0.3698 1.16 170.0 \n1950010 0.000000 -4.286316 -8.046204 -0.526428 0.3671 1.17 170.0 \n\n por fc intercept water \n1950001 437.73587 305.0 25 0 \n1950002 437.73587 305.0 25 0 \n1950003 437.73587 305.0 25 0 \n1950004 437.73587 305.0 25 0 \n1950005 437.73587 305.0 25 0 \n1950006 437.73587 305.0 25 0 \n1950007 437.73587 305.0 25 0 \n1950008 437.73587 305.0 25 0 \n1950009 437.73587 305.0 25 0 \n1950010 437.73587 305.0 25 0 \n"
],
[
"df_veget",
"_____no_output_____"
]
],
[
[
"## Step 2: Run Veg ET model for a selected pixel",
"_____no_output_____"
]
],
[
[
"pptcorr = 1\nrf_value = 0.167\nrf_low_thresh_temp = 0\nrf_high_thresh_temp = 6\nmelt_factor = 0.06\ndc_coeff: 0.65\nrf_coeff = 0.35\nk_factor = 1.25\nndvi_factor = 0.2\nwater_factor = 0.7\nbias_corr = 0.85\nalfa_factor = 1.25\n\n\ndf_veget['PPTcorr'] = df_veget['PPT']*pptcorr\ndf_veget['PPTeff'] = df_veget['PPTcorr']*(1-df_veget['intercept']/100)\ndf_veget['PPTinter'] = df_veget['PPTcorr']*(df_veget['intercept']/100)\ndf_veget['Tmin0'] = np.where(df_veget['Tasmin']<0,0,df_veget['Tasmin'])\ndf_veget['Tmax0'] = np.where(df_veget['Tasmax']<0,0,df_veget['Tasmax'])\n\nrain_frac_conditions = [(df_veget['Tasavg']<=rf_low_thresh_temp),\n (df_veget['Tasavg']>=rf_low_thresh_temp)&(df_veget['Tasavg']<=rf_high_thresh_temp),\n (df_veget['Tasavg']>=rf_high_thresh_temp)]\nrain_frac_values = [0,df_veget['Tasavg']*rf_value,1]\ndf_veget['rain_frac'] = np.select(rain_frac_conditions,rain_frac_values)\n\ndf_veget['melt_rate'] = melt_factor*(df_veget['Tmax0']**2 - df_veget['Tmax0']*df_veget['Tmin0'])\ndf_veget['snow_melt_rate'] = np.where(df_veget['Tasavg']<0,0,df_veget['melt_rate'])\n\ndf_veget['rain']=df_veget['PPTeff']*df_veget['rain_frac']\n",
"_____no_output_____"
],
[
"def _snow_water_equivalent(rain_frac, PPTeff):\n swe_value = (1-rain_frac)*PPTeff\n return swe_value\n\ndef _snow_melt(melt_rate,swe,snowpack):\n if melt_rate <= (swe + snowpack):\n snowmelt_value = melt_rate\n else:\n snowmelt_value = swe_value + snowpack\n return snowmelt_value\n\ndef _snow_pack(snowpack_prev,swe,snow_melt):\n if (snowpack_prev + swe - snow_melt) < 0:\n SNOW_pack_value = 0\n else:\n SNOW_pack_value = snowpack_prev + swe - snow_melt\n return SNOW_pack_value\n \ndef _runoff(snow_melt,awc,swi):\n if snow_melt<awc:\n rf_value = 0\n else:\n rf_value = swi-awc\n return rf_value\n\ndef _surface_runoff(rf, por,fc,rf_coeff):\n if rf <= por - fc:\n srf_value = rf*rf_coeff\n else:\n srf_value = (rf - (por - fc)) + rf_coeff*(por - fc)\n return srf_value\n\ndef _etasw_calc(k_factor, ndvi, ndvi_factor, eto, bias_corr, swi, awc, water, water_factor, alfa_factor):\n etasw1A_value = (k_factor*ndvi+ndvi_factor)*eto*bias_corr\n etasw1B_value = (k_factor*ndvi)*eto*bias_corr\n if ndvi > 0.4:\n etasw1_value = etasw1A_value\n else:\n etasw1_value = etasw1B_value\n etasw2_value = swi/(0.5*awc)*etasw1_value\n if swi>0.5*awc:\n etasw3_value = etasw1_value\n else:\n etasw3_value = etasw2_value\n if etasw3_value>swi:\n etasw4_value = swi\n else:\n etasw4_value = etasw3_value\n if etasw4_value> awc:\n etasw5_value = awc\n else:\n etasw5_value = etasw4_value\n etc_value = etasw1A_value\n if water == 0:\n etasw_value = etasw5_value\n else:\n etasw_value = water_factor*alfa_factor*bias_corr*eto\n if (etc_value - etasw_value)<0:\n netet_value = 0\n else:\n netet_value = etc_value - etasw_value\n return [etasw1A_value, etasw1B_value, etasw1_value, etasw2_value, etasw3_value, etasw4_value, etasw5_value, etasw_value, etc_value, netet_value]\n\ndef _soil_water_final(swi,awc,etasw5):\n if swi> awc:\n swf_value = awc - etasw5\n elif (swi> awc) & (swi-etasw5<0):\n swf_value = 0\n else:\n swf_value = swi-etasw5\n return swf_value",
"_____no_output_____"
],
[
"swe_list = []\nsnowmelt_list = []\nsnwpk_list = []\nswi_list = []\nrf_list = []\nsrf_list = []\ndd_list = []\netasw1A_list = []\netasw1B_list = []\netasw1_list = []\netasw2_list = []\netasw3_list = []\netasw4_list = []\netasw5_list = []\netasw_list = []\netc_list = []\nnetet_list = []\nswf_list = []\n\nfor index, row in df_veget.iterrows():\n if index == df_veget.index[0]:\n swe_value = 0\n swe_list.append(swe_value)\n snowmelt_value = swe_value\n snowmelt_list.append(snowmelt_value)\n snwpk_value = 0\n snwpk_list.append(snwpk_value)\n swi_value = 0.5*row['awc']+ row['PPTeff'] + snowmelt_value\n swi_list.append(swi_value)\n rf_value = _runoff(snowmelt_value,row['awc'],swi_value)\n rf_list.append(rf_value)\n srf_value = _surface_runoff(rf_value, row['por'],row['fc'],rf_coeff)\n srf_list.append(srf_value)\n dd_value = rf_value - srf_value\n dd_list.append(dd_value)\n eta_variables = _etasw_calc(k_factor, row['NDVI'], ndvi_factor, row['ETo'], bias_corr, swi_value, row['awc'], row['water'], water_factor, alfa_factor)\n etasw1A_list.append(eta_variables[0])\n etasw1B_list.append(eta_variables[1])\n etasw1_list.append(eta_variables[2])\n etasw2_list.append(eta_variables[3])\n etasw3_list.append(eta_variables[4])\n etasw4_list.append(eta_variables[5])\n etasw5_list.append(eta_variables[6])\n etasw_list.append(eta_variables[7])\n etc_list.append(eta_variables[8])\n netet_list.append(eta_variables[9])\n swf_value = _soil_water_final(swi_value,row['awc'],eta_variables[7])\n swf_list.append(swf_value) \n else:\n swe_value = _snow_water_equivalent(row['rain_frac'],row['PPTeff'])\n swe_list.append(swe_value)\n snowmelt_value = _snow_melt(row['melt_rate'],swe_value,snwpk_list[-1])\n snowmelt_list.append(snowmelt_value)\n snwpk_value = _snow_pack(snwpk_list[-1],swe_value,snowmelt_value)\n snwpk_list.append(snwpk_value)\n swi_value = swf_list[-1] + row['rain'] + snowmelt_value\n swi_list.append(swi_value)\n rf_value = _runoff(snowmelt_value,row['awc'],swi_value)\n rf_list.append(rf_value)\n srf_value = _surface_runoff(rf_value, row['por'],row['fc'],rf_coeff)\n srf_list.append(srf_value)\n dd_value = rf_value - srf_value\n dd_list.append(dd_value)\n eta_variables = _etasw_calc(k_factor, row['NDVI'], ndvi_factor, row['ETo'], bias_corr, swi_value, row['awc'], row['water'], water_factor, alfa_factor)\n etasw1A_list.append(eta_variables[0])\n etasw1B_list.append(eta_variables[1])\n etasw1_list.append(eta_variables[2])\n etasw2_list.append(eta_variables[3])\n etasw3_list.append(eta_variables[4])\n etasw4_list.append(eta_variables[5])\n etasw5_list.append(eta_variables[6])\n etasw_list.append(eta_variables[7])\n etc_list.append(eta_variables[8])\n netet_list.append(eta_variables[9])\n swf_value = _soil_water_final(swi_value,row['awc'],eta_variables[7])\n swf_list.append(swf_value)\n \ndf_veget['swe'] = swe_list \ndf_veget['snowmelt'] = snowmelt_list \ndf_veget['snwpk'] = snwpk_list\ndf_veget['swi'] = swi_list\ndf_veget['rf'] = rf_list\ndf_veget['srf'] = srf_list\ndf_veget['dd'] = dd_list\ndf_veget['etasw1A'] = etasw1A_list\ndf_veget['etasw1B'] = etasw1B_list\ndf_veget['etasw1'] = etasw1_list\ndf_veget['etasw2'] = etasw2_list\ndf_veget['etasw3'] = etasw3_list\ndf_veget['etasw4'] = etasw4_list\ndf_veget['etasw5'] = etasw5_list\ndf_veget['etasw'] = etasw_list\ndf_veget['etc'] = etc_list\ndf_veget['netet'] = netet_list\ndf_veget['swf'] = swf_list",
"_____no_output_____"
],
[
"pd.set_option('display.max_columns', None)\ndf_veget",
"_____no_output_____"
]
],
[
[
"## Step 3: Sample output data computed in the cloud",
"_____no_output_____"
]
],
[
[
"output_bucket_prefix='s3://dev-et-data/enduser/DelawareRiverBasin/r_01_29_2021_drb35pct/'\n#output_bucket_prefix = 's3://dev-et-data/out/DelawareRiverBasin/Run03_11_2021/run_drbcelsius_5yr_0311_chip39.84N-73.72E_o/'",
"_____no_output_____"
],
[
"df_list_cloud=[]\n\nfor product_out in ['rain', 'swe', 'snowmelt', 'snwpk','srf', 'dd', 'etasw5', 'etasw', 'netet', 'swf', 'etc']:\n print(\"===\"*30)\n print(\"processing product\",product_out)\n tif_list = create_s3_list_of_days_start_end(output_bucket_prefix, start_year,start_day, end_year, end_day, product_out)\n ds_pix=xr_build_cube_concat_ds_one(tif_list, product_out, x, y)\n \n my_index = ds_pix['year_month'].values\n my_array = ds_pix[product_out].values\n df = pd.DataFrame(my_array, columns=['{}_cloud'.format(product_out),], index=my_index)\n df_list_cloud.append(df)",
"==========================================================================================\nprocessing product rain\ns3://dev-et-data/enduser/DelawareRiverBasin/r_01_29_2021_drb35pct/1950/rain_1950001.tif\n"
],
[
"for dframe in df_list_cloud:\n print(dframe)",
" rain_cloud\n1950001 -0.0\n1950002 -0.0\n1950003 -0.0\n1950004 -0.0\n1950005 -0.0\n1950006 -0.0\n1950007 -0.0\n1950008 -0.0\n1950009 -0.0\n1950010 -0.0\n swe_cloud\n1950001 0.0\n1950002 -9999.0\n1950003 -9999.0\n1950004 -9999.0\n1950005 -9999.0\n1950006 -9999.0\n1950007 -9999.0\n1950008 -9999.0\n1950009 -9999.0\n1950010 -9999.0\n snowmelt_cloud\n1950001 0.0\n1950002 -9999.0\n1950003 -9999.0\n1950004 -9999.0\n1950005 -9999.0\n1950006 -9999.0\n1950007 -9999.0\n1950008 -9999.0\n1950009 -9999.0\n1950010 -9999.0\n snwpk_cloud\n1950001 0.0\n1950002 0.0\n1950003 0.0\n1950004 0.0\n1950005 0.0\n1950006 0.0\n1950007 0.0\n1950008 0.0\n1950009 0.0\n1950010 0.0\n srf_cloud\n1950001 NaN\n1950002 NaN\n1950003 NaN\n1950004 NaN\n1950005 NaN\n1950006 NaN\n1950007 NaN\n1950008 NaN\n1950009 NaN\n1950010 NaN\n dd_cloud\n1950001 NaN\n1950002 NaN\n1950003 NaN\n1950004 NaN\n1950005 NaN\n1950006 NaN\n1950007 NaN\n1950008 NaN\n1950009 NaN\n1950010 NaN\n etasw5_cloud\n1950001 NaN\n1950002 NaN\n1950003 NaN\n1950004 NaN\n1950005 NaN\n1950006 NaN\n1950007 NaN\n1950008 NaN\n1950009 NaN\n1950010 NaN\n etasw_cloud\n1950001 NaN\n1950002 NaN\n1950003 NaN\n1950004 NaN\n1950005 NaN\n1950006 NaN\n1950007 NaN\n1950008 NaN\n1950009 NaN\n1950010 NaN\n netet_cloud\n1950001 0.0\n1950002 0.0\n1950003 0.0\n1950004 0.0\n1950005 0.0\n1950006 0.0\n1950007 0.0\n1950008 0.0\n1950009 0.0\n1950010 0.0\n swf_cloud\n1950001 NaN\n1950002 NaN\n1950003 NaN\n1950004 NaN\n1950005 NaN\n1950006 NaN\n1950007 NaN\n1950008 NaN\n1950009 NaN\n1950010 NaN\n etc_cloud\n1950001 NaN\n1950002 NaN\n1950003 NaN\n1950004 NaN\n1950005 NaN\n1950006 NaN\n1950007 NaN\n1950008 NaN\n1950009 NaN\n1950010 NaN\n"
],
[
"df_veget_cloud = pd.concat(df_list_cloud, axis=1)",
"_____no_output_____"
],
[
"df_veget_cloud",
"_____no_output_____"
],
[
"df_validation = pd.concat([df_veget,df_veget_cloud], axis=1)\ndf_validation",
"_____no_output_____"
]
],
[
[
"## Step 4: Visualization of validation results",
"_____no_output_____"
],
[
"### Import Visualization libraries",
"_____no_output_____"
]
],
[
[
"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib.ticker as mtick\nfrom scipy import stats\nimport matplotlib.patches as mpatches",
"_____no_output_____"
]
],
[
[
"### Visualize Veg ET input variables",
"_____no_output_____"
]
],
[
[
"fig, axs = plt.subplots(3, 1, figsize=(15,12))\n\naxs[0].bar(df_validation.index, df_validation[\"PPT\"], color = 'lightskyblue', width = 0.1)\nax0 = axs[0].twinx()\nax0.plot(df_validation.index, df_validation[\"NDVI\"], color = 'seagreen')\naxs[0].set_ylabel(\"PPT, mm\")\nax0.set_ylabel(\"NDVI\")\nax0.set_ylim([0,1])\n\nlow_threshold = np.array([0 for i in range(len(df_validation))])\naxs[1].plot(df_validation.index, low_threshold, '--', color = 'dimgray', linewidth=0.8)\nhigh_threshold = np.array([6 for i in range(len(df_validation))])\naxs[1].plot(df_validation.index, high_threshold, '--', color = 'dimgray', linewidth=0.8)\naxs[1].plot(df_validation.index, df_validation[\"Tasmin\"], color = 'navy', linewidth=2.5)\naxs[1].plot(df_validation.index, df_validation[\"Tasavg\"], color = 'slategray', linewidth=2.5)\naxs[1].plot(df_validation.index, df_validation[\"Tasmax\"], color = 'red', linewidth=2.5)\naxs[1].set_ylabel(\"T, deg C\")\n\n\naxs[2].plot(df_validation.index, df_validation[\"ETo\"], color = 'goldenrod')\naxs[2].plot(df_validation.index, df_validation[\"etasw\"], color = 'royalblue')\naxs[2].set_ylabel(\"ET, mm\")\n\nppt = mpatches.Patch(color='lightskyblue', label='PPT')\nndvi = mpatches.Patch(color='seagreen', label='NDVI')\ntmax = mpatches.Patch(color='red', label='Tmax')\ntavg = mpatches.Patch(color='slategray', label='Tavg')\ntmin = mpatches.Patch(color='navy', label='Tmin')\neto = mpatches.Patch(color='goldenrod', label='ETo')\neta = mpatches.Patch(color='royalblue', label='ETa')\nplt.legend(handles=[ppt, ndvi, tmax, tavg, tmin, eto,eta])",
"_____no_output_____"
]
],
[
[
"### Compare Veg ET output variables computed with data frames vs output variables computed in the cloud",
"_____no_output_____"
]
],
[
[
"fig, axs = plt.subplots(5, 2, figsize=(20,25))\n\n\naxs[0, 0].bar(df_validation.index, df_validation[\"rain\"], color = 'skyblue')\naxs[0, 0].plot(df_validation.index, df_validation[\"rain_cloud\"], 'ro', color = 'crimson')\naxs[0, 0].set_title(\"Rain amount from precipitation (rain)\")\naxs[0, 0].set_ylabel(\"rain, mm/day\")\n\n\naxs[0, 1].bar(df_validation.index, df_validation[\"swe\"], color = 'skyblue')\naxs[0, 1].plot(df_validation.index, df_validation[\"swe_cloud\"], 'ro', color = 'crimson')\naxs[0, 1].set_title(\"Snow water equivalent from precipiation (swe)\")\naxs[0, 1].set_ylabel(\"swe, mm/day\")\n\naxs[1, 0].bar(df_validation.index, df_validation[\"snowmelt\"], color = 'skyblue')\naxs[1, 0].plot(df_validation.index, df_validation[\"snowmelt_cloud\"], 'ro', color = 'crimson')\naxs[1, 0].set_title(\"Amount of melted snow (snowmelt)\")\naxs[1, 0].set_ylabel(\"snowmelt, mm/day\")\n\n\naxs[1, 1].bar(df_validation.index, df_validation[\"snwpk\"], color = 'skyblue')\naxs[1, 1].plot(df_validation.index, df_validation[\"snwpk_cloud\"], 'ro', color = 'crimson')\naxs[1, 1].set_title(\"Snow pack amount (snwpk)\")\naxs[1, 1].set_ylabel(\"snpk, mm/day\")\n\n\naxs[2, 0].bar(df_validation.index, df_validation[\"srf\"], color = 'skyblue')\naxs[2, 0].plot(df_validation.index, df_validation[\"srf_cloud\"], 'ro', color = 'crimson')\naxs[2, 0].set_title(\"Surface runoff (srf)\")\naxs[2, 0].set_ylabel(\"srf, mm/day\")\n\naxs[2, 1].bar(df_validation.index, df_validation[\"dd\"], color = 'skyblue')\naxs[2, 1].plot(df_validation.index, df_validation[\"dd_cloud\"], 'ro', color = 'crimson')\naxs[2, 1].set_title(\"Deep drainage (dd)\")\naxs[2, 1].set_ylabel(\"dd, mm/day\")\n\n\naxs[3, 0].bar(df_validation.index, df_validation[\"etasw\"], color = 'skyblue')\naxs[3, 0].plot(df_validation.index, df_validation[\"etasw_cloud\"], 'ro', color = 'crimson')\naxs[3, 0].set_title(\"ETa value (etasw)\")\naxs[3, 0].set_ylabel(\"etasw, mm/day\")\n\n\n\naxs[3, 1].bar(df_validation.index, df_validation[\"etc\"], color = 'skyblue')\naxs[3, 1].plot(df_validation.index, df_validation[\"etc_cloud\"], 'ro', color = 'crimson')\naxs[3, 1].set_title(\"Optimal crop ETa value (etc)\")\naxs[3, 1].set_ylabel(\"etc, mm/day\")\n\n\n\naxs[4, 0].bar(df_validation.index, df_validation[\"netet\"], color = 'skyblue')\naxs[4, 0].plot(df_validation.index, df_validation[\"netet_cloud\"], 'ro', color = 'crimson')\naxs[4, 0].set_title(\"Additional ETa requirement for optimal crop condition (netet)\")\naxs[4, 0].set_ylabel(\"netet, mm/day\")\n\n\naxs[4, 1].plot(df_validation.index, df_validation[\"swf\"], color = 'skyblue')\naxs[4, 1].plot(df_validation.index, df_validation[\"swf_cloud\"], 'ro', color = 'crimson')\naxs[4, 1].set_title(\"Final soil water amount at the end of the day (swf)\")\naxs[4, 1].set_ylabel(\"swf, mm/m\")\n\nmanual = mpatches.Patch(color='skyblue', label='manual')\ncloud = mpatches.Patch(color='crimson', label='cloud')\nplt.legend(handles=[manual,cloud])",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd51b68d21db637bc73b1cc98d58e111a172996
| 7,359 |
ipynb
|
Jupyter Notebook
|
demo/PCA_SVM.ipynb
|
ZouJinying/XAI_loglizer
|
df3e9d91502c10b8c8d8871617b405cc0671308b
|
[
"MIT"
] | 1 |
2021-03-02T13:22:21.000Z
|
2021-03-02T13:22:21.000Z
|
demo/PCA_SVM.ipynb
|
ZouJinying/XAI_loglizer
|
df3e9d91502c10b8c8d8871617b405cc0671308b
|
[
"MIT"
] | null | null | null |
demo/PCA_SVM.ipynb
|
ZouJinying/XAI_loglizer
|
df3e9d91502c10b8c8d8871617b405cc0671308b
|
[
"MIT"
] | null | null | null | 37.166667 | 95 | 0.480364 |
[
[
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nsys.path.append('../')\nfrom loglizer.models import SVM\nfrom loglizer import dataloader, preprocessing\nimport numpy as np\n\nstruct_log = '../data/HDFS/HDFS_100k.log_structured.csv' # The structured log file\nlabel_file = '../data/HDFS/anomaly_label.csv' # The anomaly label file\n\nif __name__ == '__main__':\n (x_train, y_train), (x_test, y_test) = dataloader.load_HDFS(struct_log,\n label_file=label_file,\n window='session', \n train_ratio=0.5,\n split_type='uniform')\n\n feature_extractor = preprocessing.FeatureExtractor()\n x_train = feature_extractor.fit_transform(x_train, term_weighting='tf-idf')\n x_test = feature_extractor.transform(x_test)\n print(np.array(x_train).shape)\n \n model = SVM()\n model.fit(x_train, y_train)\n print(np.array(x_train).shape)\n\n# print('Train validation:')\n# precision, recall, f1 = model.evaluate(x_train, y_train)\n\n# print('Test validation:')\n# precision, recall, f1 = model.evaluate(x_test, y_test)",
"_____no_output_____"
],
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nsys.path.append('../')\nfrom loglizer.models import PCA\nfrom loglizer import dataloader, preprocessing\n\nstruct_log = '../data/HDFS/HDFS_100k.log_structured.csv' # The structured log file\nlabel_file = '../data/HDFS/anomaly_label.csv' # The anomaly label file\n\nif __name__ == '__main__':\n (x_train, y_train), (x_test, y_test) = dataloader.load_HDFS(struct_log,\n label_file=label_file,\n window='session', \n train_ratio=0.5,\n split_type='uniform')\n feature_extractor = preprocessing.FeatureExtractor()\n x_train = feature_extractor.fit_transform(x_train, term_weighting='tf-idf', \n normalization='zero-mean')\n x_test = feature_extractor.transform(x_test)\n \n# print(\"输入后的训练数据:\",x_train)\n# print(\"尺寸:\",x_train.shape)\n# print(\"输入后的测试数据:\",x_test)\n# print(\"尺寸:\",x_test.shape)\n model = PCA()\n model.fit(x_train)\n\n# print('Train validation:')\n# precision, recall, f1 = model.evaluate(x_train, y_train)\n \n# print('Test validation:')\n# precision, recall, f1 = model.evaluate(x_test, y_test)",
"====== Input data summary ======***\n====== Input data summary ======\nLoading ../data/HDFS/HDFS_100k.log_structured.csv\n BlockId \\\n0 blk_-1608999687919862906 \n1 blk_7503483334202473044 \n2 blk_-3544583377289625738 \n3 blk_-9073992586687739851 \n4 blk_7854771516489510256 \n... ... \n7935 blk_-1445970677921829671 \n7936 blk_-5943236831140622436 \n7937 blk_-5039164935117450945 \n7938 blk_7379833155074044619 \n7939 blk_8909107483987085802 \n\n EventSequence \n0 [E5, E22, E5, E5, E11, E11, E9, E9, E11, E9, E... \n1 [E5, E5, E22, E5, E11, E9, E11, E9, E11, E9, E... \n2 [E5, E22, E5, E5, E11, E9, E11, E9, E11, E9, E... \n3 [E5, E22, E5, E5, E11, E9, E11, E9, E11, E9, E... \n4 [E5, E5, E22, E5, E11, E9, E11, E9, E11, E9, E... \n... ... \n7935 [E22, E5, E5, E5, E11, E9, E11, E9, E26, E26, ... \n7936 [E22, E5, E5, E5, E26, E26, E26, E11, E9, E11,... \n7937 [E22, E5, E5, E5, E26, E26, E11, E9, E11, E9, ... \n7938 [E22, E5, E5, E5, E26, E26, E11, E9, E11, E9, ... \n7939 [E22, E5, E5, E5, E26, E26, E11, E9, E11, E9, ... \n\n[7940 rows x 2 columns]\n156 157\nTotal: 7940 instances, 313 anomaly, 7627 normal\nTrain: 3969 instances, 156 anomaly, 3813 normal\nTest: 3971 instances, 157 anomaly, 3814 normal\n\n====== Transformed train data summary ======\nTrain data shape: 3969-by-14\n\n====== Transformed test data summary ======\nTest data shape: 3971-by-14\n\n====== Model summary ======\nn_components: 1\nProject matrix shape: 14-by-14\nSPE threshold: 14.989659385477372\n\n输入后的训练数据: [[-4.88799673e-14 1.03801473e-25 5.87142581e-04 ... -8.35098961e-03\n -2.08774740e-03 -2.08774740e-03]\n [-4.88799673e-14 1.03801473e-25 5.87142581e-04 ... -8.35098961e-03\n -2.08774740e-03 -2.08774740e-03]\n [-4.88799673e-14 1.03801473e-25 5.87142581e-04 ... -8.35098961e-03\n -2.08774740e-03 -2.08774740e-03]\n ...\n [-4.88799673e-14 1.03801473e-25 5.87142581e-04 ... -8.35098961e-03\n -2.08774740e-03 -2.08774740e-03]\n [-4.88799673e-14 1.03801473e-25 5.87142581e-04 ... -8.35098961e-03\n -2.08774740e-03 -2.08774740e-03]\n [-4.88799673e-14 1.03801473e-25 5.87142581e-04 ... -8.35098961e-03\n -2.08774740e-03 -2.08774740e-03]]\n"
],
[
"help(model.fit())",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
cbd52cedaef5c23a33f8187319c334c02fa58e1c
| 262,548 |
ipynb
|
Jupyter Notebook
|
Bank.ipynb
|
varundineshan/BankMarketing
|
e672caaa774eb6ed99fe0d5eb07b7593d43d9c6e
|
[
"MIT"
] | 1 |
2021-03-05T06:01:24.000Z
|
2021-03-05T06:01:24.000Z
|
Bank.ipynb
|
varundineshan/BankMarketing
|
e672caaa774eb6ed99fe0d5eb07b7593d43d9c6e
|
[
"MIT"
] | null | null | null |
Bank.ipynb
|
varundineshan/BankMarketing
|
e672caaa774eb6ed99fe0d5eb07b7593d43d9c6e
|
[
"MIT"
] | null | null | null | 53.061439 | 27,968 | 0.537913 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ndata=pd.read_csv('F:\\\\bank-additional-full.csv',sep=';')",
"_____no_output_____"
],
[
"data.shape",
"_____no_output_____"
],
[
"tot=len(set(data.index))\nlast=data.shape[0]-tot\nlast",
"_____no_output_____"
],
[
"data.isnull().sum()",
"_____no_output_____"
],
[
"print(data.y.value_counts())\nsns.countplot(x='y', data=data)\nplt.show()",
"no 36548\nyes 4640\nName: y, dtype: int64\n"
],
[
"cat=data.select_dtypes(include=['object']).columns\ncat",
"_____no_output_____"
],
[
"for c in cat:\n print(c)\n print(\"-\"*50)\n print(data[c].value_counts())\n print(\"-\"*50)\n ",
"job\n--------------------------------------------------\nadmin. 10422\nblue-collar 9254\ntechnician 6743\nservices 3969\nmanagement 2924\nretired 1720\nentrepreneur 1456\nself-employed 1421\nhousemaid 1060\nunemployed 1014\nstudent 875\nunknown 330\nName: job, dtype: int64\n--------------------------------------------------\nmarital\n--------------------------------------------------\nmarried 24928\nsingle 11568\ndivorced 4612\nunknown 80\nName: marital, dtype: int64\n--------------------------------------------------\neducation\n--------------------------------------------------\nuniversity.degree 12168\nhigh.school 9515\nbasic.9y 6045\nprofessional.course 5243\nbasic.4y 4176\nbasic.6y 2292\nunknown 1731\nilliterate 18\nName: education, dtype: int64\n--------------------------------------------------\ndefault\n--------------------------------------------------\nno 32588\nunknown 8597\nyes 3\nName: default, dtype: int64\n--------------------------------------------------\nhousing\n--------------------------------------------------\nyes 21576\nno 18622\nunknown 990\nName: housing, dtype: int64\n--------------------------------------------------\nloan\n--------------------------------------------------\nno 33950\nyes 6248\nunknown 990\nName: loan, dtype: int64\n--------------------------------------------------\ncontact\n--------------------------------------------------\ncellular 26144\ntelephone 15044\nName: contact, dtype: int64\n--------------------------------------------------\nmonth\n--------------------------------------------------\nmay 13769\njul 7174\naug 6178\njun 5318\nnov 4101\napr 2632\noct 718\nsep 570\nmar 546\ndec 182\nName: month, dtype: int64\n--------------------------------------------------\nday_of_week\n--------------------------------------------------\nthu 8623\nmon 8514\nwed 8134\ntue 8090\nfri 7827\nName: day_of_week, dtype: int64\n--------------------------------------------------\npoutcome\n--------------------------------------------------\nnonexistent 35563\nfailure 4252\nsuccess 1373\nName: poutcome, dtype: int64\n--------------------------------------------------\ny\n--------------------------------------------------\nno 36548\nyes 4640\nName: y, dtype: int64\n--------------------------------------------------\n"
],
[
"from sklearn.preprocessing import LabelEncoder,OneHotEncoder\nle=LabelEncoder()\ndata['y']=le.fit_transform(data['y'])",
"_____no_output_____"
],
[
"data.drop('poutcome',axis=1,inplace=True)",
"_____no_output_____"
],
[
"print( data['age'].quantile(q = 0.75) + \n 1.5*(data['age'].quantile(q = 0.75) - data['age'].quantile(q = 0.25)))",
"69.5\n"
],
[
"data['age']=data[data['age']<69.6]\ndata['age'].fillna(int(data['age'].mean()),inplace=True)",
"_____no_output_____"
],
[
"data['age'].values",
"_____no_output_____"
],
[
"data[['age','y']].groupby(['age'],as_index=False).mean().sort_values(by='y', ascending=False)",
"_____no_output_____"
],
[
"# for x in data:\n# x['Sex'] = x['Sex'].map( {'female': 1, 'male': 0}).astype(int)",
"_____no_output_____"
],
[
"data['age_slice'] = pd.cut(data['age'],5)\ndata[['age_slice', 'y']].groupby(['age_slice'], as_index=False).mean().sort_values(by='age_slice', ascending=True)",
"_____no_output_____"
],
[
"data['age'] = data['age'].astype(int)\ndata.loc[(data['age'] >= 16) & (data['age'] <= 28), 'age'] = 1\ndata.loc[(data['age'] > 28) & (data['age'] <= 38), 'age'] = 2\ndata.loc[(data['age'] > 38) & (data['age'] <= 49), 'age'] = 3\ndata.loc[ (data['age'] > 49) & (data['age'] <= 59), 'age'] = 4\ndata.loc[ (data['age'] > 59 )& (data['age'] <= 69), 'age'] = 5\n",
"_____no_output_____"
],
[
"data.drop('age_slice',axis=1,inplace=True)",
"_____no_output_____"
],
[
"data['marital'].replace(['divorced' ,'married' , 'unknown' , 'single'] ,['single','married','unknown','single'], inplace=True)",
"_____no_output_____"
],
[
"data['marital']=le.fit_transform(data['marital'])",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"data['job'].replace(['student'] ,['unemployed'], inplace=True)",
"_____no_output_____"
],
[
"data[['education', 'y']].groupby(['education'], as_index=False).mean().sort_values(by='education', ascending=True)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nfig.set_size_inches(20, 5)\nsns.countplot(x = 'education', hue = 'loan', data = data)\nax.set_xlabel('Education', fontsize=15)\nax.set_ylabel('y', fontsize=15)\nax.set_title('Education Count Distribution', fontsize=15)\nax.tick_params(labelsize=15)\nsns.despine()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nfig.set_size_inches(20, 5)\nsns.countplot(x = 'job', hue = 'loan', data = data)\nax.set_xlabel('job', fontsize=17)\nax.set_ylabel('y', fontsize=17)\nax.set_title('Education Count Distribution', fontsize=17)\nax.tick_params(labelsize=17)\nsns.despine()",
"_____no_output_____"
],
[
"data['education'].replace(['basic.4y','basic.6y','basic.9y','professional.course'] ,['not_reach_highschool','not_reach_highschool','not_reach_highschool','university.degree'], inplace=True)",
"_____no_output_____"
],
[
"ohe=OneHotEncoder()\ndata['default']=le.fit_transform(data['default'])\ndata['housing']=le.fit_transform(data['housing'])\ndata['loan']=le.fit_transform(data['loan'])\ndata['month']=le.fit_transform(data['month'])\nohe=OneHotEncoder(categorical_features=data['month'])\ndata['contact']=le.fit_transform(data['contact'])\ndata['day_of_week']=le.fit_transform(data['day_of_week'])\ndata['job']=le.fit_transform(data['job'])\ndata['education']=le.fit_transform(data['education'])",
"_____no_output_____"
],
[
"cat=data.select_dtypes(include=['object']).columns\ncat",
"_____no_output_____"
],
[
"def outlier_detect(data,feature):\n q1 = data[feature].quantile(0.25)\n q3 = data[feature].quantile(0.75)\n iqr = q3-q1 #Interquartile range\n lower = q1-1.5*iqr\n upper = q3+1.5*iqr\n data = data.loc[(data[feature] > lower) & (data[feature] < upper)]\n print('lower IQR and upper IQR of',feature,\"are:\", lower, 'and', upper, 'respectively')\n return data\n",
"_____no_output_____"
],
[
"data.columns",
"_____no_output_____"
],
[
"data['pdays'].unique()",
"_____no_output_____"
],
[
"data['pdays'].replace([999] ,[0], inplace=True)",
"_____no_output_____"
],
[
"data['previous'].unique()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nfig.set_size_inches(15, 5)\nsns.countplot(x = 'campaign', palette=\"rocket\", data = data)\nax.set_xlabel('campaign', fontsize=25)\nax.set_ylabel('y', fontsize=25)\nax.set_title('campaign', fontsize=25)\nsns.despine()",
"_____no_output_____"
],
[
"sns.countplot(x = 'pdays', palette=\"rocket\", data = data)\nax.set_xlabel('pdays', fontsize=25)\nax.set_ylabel('y', fontsize=25)\nax.set_title('pdays', fontsize=25)\nsns.despine()",
"_____no_output_____"
],
[
"data[['pdays', 'y']].groupby(['pdays'], as_index=False).mean().sort_values(by='pdays', ascending=True)",
"_____no_output_____"
],
[
"sns.countplot(x = 'emp.var.rate', palette=\"rocket\", data = data)\nax.set_xlabel('emp.var.rate', fontsize=25)\nax.set_ylabel('y', fontsize=25)\nax.set_title('emp.var.rate', fontsize=25)\nsns.despine()",
"_____no_output_____"
],
[
"outlier_detect(data,'duration')\n#outlier_detect(data,'emp.var.rate')\noutlier_detect(data,'nr.employed')\n#outlier_detect(data,'euribor3m')",
"lower IQR and upper IQR of duration are: -223.5 and 644.5 respectively\nlower IQR and upper IQR of nr.employed are: 4905.6 and 5421.6 respectively\n"
],
[
"X = data.iloc[:,:-1]\nX = X.values\ny = data['y'].values",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier",
"c:\\users\\varlock^_^\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\sklearn\\ensemble\\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release.\n from numpy.core.umath_tests import inner1d\n"
],
[
"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)",
"_____no_output_____"
],
[
"algo = {'LR': LogisticRegression(), \n 'DT':DecisionTreeClassifier(), \n 'RFC':RandomForestClassifier(n_estimators=100), \n 'SVM':SVC(gamma=0.01),\n 'KNN':KNeighborsClassifier(n_neighbors=10)\n }\n\nfor k, v in algo.items():\n model = v\n model.fit(X_train, y_train)\n print('Acurracy of ' + k + ' is {0:.2f}'.format(model.score(X_test, y_test)*100))",
"Acurracy of LR is 91.22\nAcurracy of DT is 89.04\nAcurracy of RFC is 91.58\nAcurracy of SVM is 90.99\nAcurracy of KNN is 90.82\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd53bc306f87d709af20f5aca052ce97794612a
| 8,342 |
ipynb
|
Jupyter Notebook
|
code/pivotal-samples.ipynb
|
Hsingh2096/Hsingh2096
|
bf085c9b7d9b76739eb1ab17767d2db75b0b1c2f
|
[
"Apache-2.0"
] | null | null | null |
code/pivotal-samples.ipynb
|
Hsingh2096/Hsingh2096
|
bf085c9b7d9b76739eb1ab17767d2db75b0b1c2f
|
[
"Apache-2.0"
] | null | null | null |
code/pivotal-samples.ipynb
|
Hsingh2096/Hsingh2096
|
bf085c9b7d9b76739eb1ab17767d2db75b0b1c2f
|
[
"Apache-2.0"
] | null | null | null | 31.011152 | 143 | 0.499281 |
[
[
[
"# Requirements Documentation and Notes\n\n# SQL Samples\n\n\n2. Total monthly commits\n```sql\n SELECT\n date_trunc( 'month', commits.cmt_author_timestamp AT TIME ZONE'America/Chicago' ) AS DATE,\n repo_name,\n rg_name,\n cmt_author_name,\n cmt_author_email,\n COUNT ( cmt_author_email ) AS author_count \n FROM\n commits,\n repo,\n repo_groups \n WHERE\n commits.repo_id = repo.repo_id \n AND repo.repo_group_id = repo_groups.repo_group_id \n AND commits.cmt_author_timestamp AT TIME ZONE'America/Chicago' BETWEEN '2019-11-01' \n AND '2019-11-30' \n GROUP BY\n DATE,\n repo_name,\n rg_name,\n cmt_author_name,\n cmt_author_email \n ORDER BY\n DATE,\n cmt_author_name,\n cmt_author_email; \n\n```\n\n### Metrics: Lines of Code and Commit Summaries by Week, Month and Year\nThere are six summary tables : \n1. dm_repo_annual\n2. dm_repo_monthly\n3. dm_repo_weekly\n4. dm_repo_group_annual\n5. dm_repo_group_monthly\n6. dm_repo_group_weekly\n\n```sql\nSELECT\n repo.repo_id,\n repo.repo_name,\n repo_groups.rg_name,\n dm_repo_annual.YEAR,\n SUM ( dm_repo_annual.added ) AS lines_added,\n SUM ( dm_repo_annual.whitespace ) AS whitespace_added,\n SUM ( dm_repo_annual.removed ) AS lines_removed,\n SUM ( dm_repo_annual.files ) AS files,\n SUM ( dm_repo_annual.patches ) AS commits \nFROM\n dm_repo_annual,\n repo,\n repo_groups \nWHERE\n dm_repo_annual.repo_id = repo.repo_id \n AND repo.repo_group_id = repo_groups.repo_group_id \nGROUP BY\n repo.repo_id,\n repo.repo_name,\n repo_groups.rg_name,\nYEAR \nORDER BY\n YEAR,\n rg_name,\n repo_name\n\n```\n\n\n### Metrics: Value / Labor / Lines of Code (Total, NOT Commits)\n1. Total lines in a repository by language and line type. This is like software as an asset. Its lines of code, at a point in time, ++\n```sql \nSELECT\n repo.repo_id,\n repo.repo_name,\n programming_language,\n SUM ( total_lines ) AS repo_total_lines,\n SUM ( code_lines ) AS repo_code_lines,\n SUM ( comment_lines ) AS repo_comment_lines,\n SUM ( blank_lines ) AS repo_blank_lines,\n AVG ( code_complexity ) AS repo_lang_avg_code_complexity \nFROM\n repo_labor,\n repo,\n repo_groups \nWHERE\n repo.repo_group_id = repo_groups.repo_group_id \n and \n repo.repo_id = repo_labor.repo_id\nGROUP BY\n repo.repo_id,\n programming_language \nORDER BY\n repo_id\n\n\n--\n\n```\n\n#### Estimated Labor Hours by Repository \n```sql \nSELECT C\n .repo_id,\n C.repo_name,\n SUM ( estimated_labor_hours ) \nFROM\n (\n SELECT A\n .repo_id,\n b.repo_name,\n programming_language,\n SUM ( total_lines ) AS repo_total_lines,\n SUM ( code_lines ) AS repo_code_lines,\n SUM ( comment_lines ) AS repo_comment_lines,\n SUM ( blank_lines ) AS repo_blank_lines,\n AVG ( code_complexity ) AS repo_lang_avg_code_complexity,\n AVG ( code_complexity ) * SUM ( code_lines ) + 20 AS estimated_labor_hours \n FROM\n repo_labor A,\n repo b \n WHERE\n A.repo_id = b.repo_id \n GROUP BY\n A.repo_id,\n programming_language,\n repo_name \n ORDER BY\n repo_name,\n A.repo_id,\n programming_language \n ) C \nGROUP BY\n repo_id,\n repo_name;\n```\n\n#### Estimated Labor Hours by Language\n```sql\nSELECT C\n .repo_id,\n C.repo_name,\n programming_language,\n SUM ( estimated_labor_hours ) \nFROM\n (\n SELECT A\n .repo_id,\n b.repo_name,\n programming_language,\n SUM ( total_lines ) AS repo_total_lines,\n SUM ( code_lines ) AS repo_code_lines,\n SUM ( comment_lines ) AS repo_comment_lines,\n SUM ( blank_lines ) AS repo_blank_lines,\n AVG ( code_complexity ) AS repo_lang_avg_code_complexity,\n AVG ( code_complexity ) * SUM ( code_lines ) + 20 AS estimated_labor_hours \n FROM\n repo_labor A,\n repo b \n WHERE\n A.repo_id = b.repo_id \n GROUP BY\n A.repo_id,\n programming_language,\n repo_name \n ORDER BY\n repo_name,\n A.repo_id,\n programming_language \n ) C \nGROUP BY\n repo_id,\n repo_name,\n programming_language \nORDER BY\n programming_language;\n```\n\n\n\n## Issues\n### Issue Collection Status\n1. Currently 100% Complete\n```sql\nSELECT a.repo_id, a.repo_name, a.repo_git, \n b.issues_count,\n d.repo_id AS issue_repo_id,\n e.last_collected,\n COUNT ( * ) AS issues_collected_count,\n (\n b.issues_count - COUNT ( * )) AS issues_missing,\n ABS (\n CAST (( COUNT ( * )) AS DOUBLE PRECISION ) / CAST ( b.issues_count AS DOUBLE PRECISION )) AS ratio_abs,\n (\n CAST (( COUNT ( * )) AS DOUBLE PRECISION ) / CAST ( b.issues_count AS DOUBLE PRECISION )) AS ratio_issues \nFROM\n augur_data.repo a,\n augur_data.issues d,\n augur_data.repo_info b,\n ( SELECT repo_id, MAX ( data_collection_date ) AS last_collected FROM augur_data.repo_info GROUP BY repo_id ORDER BY repo_id ) e \nWHERE\n a.repo_id = b.repo_id \n AND a.repo_id = d.repo_id \n AND b.repo_id = d.repo_id \n AND e.repo_id = a.repo_id \n AND b.data_collection_date = e.last_collected \n AND d.pull_request_id IS NULL \nGROUP BY\n a.repo_id,\n d.repo_id,\n b.issues_count,\n e.last_collected, \n a.repo_git \nORDER BY\n repo_name, repo_id, ratio_abs;\n```\n\n### Repositories with GitHub Issue Tracking\n```sql \n \nselect repo_id, count(*) from repo_info where issues_count > 0\n group by repo_id; \n```",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
cbd53d55cad3b9aa3cf891ad7c735c949728e0ba
| 215,841 |
ipynb
|
Jupyter Notebook
|
diamonds_multivariate_exploration.ipynb
|
Meng-nanco/data_visualization_practice
|
524d8eafa3d5b3febdeeed26a182e28d3247f0fe
|
[
"MIT"
] | null | null | null |
diamonds_multivariate_exploration.ipynb
|
Meng-nanco/data_visualization_practice
|
524d8eafa3d5b3febdeeed26a182e28d3247f0fe
|
[
"MIT"
] | null | null | null |
diamonds_multivariate_exploration.ipynb
|
Meng-nanco/data_visualization_practice
|
524d8eafa3d5b3febdeeed26a182e28d3247f0fe
|
[
"MIT"
] | null | null | null | 726.737374 | 80,116 | 0.950125 |
[
[
[
"# import all packages and set plots to be embedded inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\n%matplotlib inline",
"_____no_output_____"
],
[
"# load in the dataset into a pandas dataframe\ndiamonds = pd.read_csv('./data/diamonds.csv')",
"_____no_output_____"
],
[
"# convert cut, color, and clarity into ordered categorical types\nordinal_var_dict = {'cut': ['Fair','Good','Very Good','Premium','Ideal'],\n 'color': ['J', 'I', 'H', 'G', 'F', 'E', 'D'],\n 'clarity': ['I1', 'SI2', 'SI1', 'VS2', 'VS1', 'VVS2', 'VVS1', 'IF']}\n\nfor var in ordinal_var_dict:\n pd_ver = pd.__version__.split(\".\")\n if (int(pd_ver[0]) > 0) or (int(pd_ver[1]) >= 21): # v0.21 or later\n ordered_var = pd.api.types.CategoricalDtype(ordered = True,\n categories = ordinal_var_dict[var])\n diamonds[var] = diamonds[var].astype(ordered_var)\n else: # pre-v0.21\n diamonds[var] = diamonds[var].astype('category', ordered = True,\n categories = ordinal_var_dict[var])",
"_____no_output_____"
]
],
[
[
"## Multivariate Exploration\n\nIn the previous workspace, you looked at various bivariate relationships. You saw that the log of price was approximately linearly related to the cube root of carat weight, as analogy to its length, width, and depth. You also saw that there was an unintuitive relationship between price and the categorical quality measures of cut, color, and clarity, that the median price decreased with increasing quality. Investigating the distributions more clearly and looking at the relationship between carat weight with the three categorical variables showed that this was due to carat size tending to be smaller for the diamonds with higher categorical grades.\n\nThe goal of this workspace will be to depict these interaction effects through the use of multivariate plots.\n\nTo start off with, create a plot of the relationship between price, carat, and clarity. In the previous workspace, you saw that clarity had the clearest interactions with price and carat. How clearly does this show up in a multivariate visualization?",
"_____no_output_____"
]
],
[
[
"def cube_trans(x, inverse=False):\n if not inverse:\n return np.cbrt(x)\n else:\n return x**3\n\ndiamonds['carat_cube'] = diamonds['carat'].apply(cube_trans)",
"_____no_output_____"
],
[
"# multivariate plot of price by carat weight, and clarity\ng = sb.FacetGrid(data=diamonds, hue='clarity', height=5)\ng = g.map(sb.regplot, 'carat_cube', 'price', fit_reg=False)\nplt.yscale('log')\ny_ticks = [300, 800, 2000, 4000, 10000, 20000]\nplt.yticks(y_ticks, y_ticks)\ng.add_legend();",
"_____no_output_____"
]
],
[
[
"Price by Carat and Clarity Comment 1: <span style=\"color:black\">With two numeric variables and one categorical variable, there are two main plot types that make sense. A scatterplot with points colored by clarity level makes sense on paper, but the sheer number of points causes overplotting that suggests a different plot type. A faceted scatterplot or heat map is a better choice in this case.</span>",
"_____no_output_____"
]
],
[
[
"g = sb.FacetGrid(data=diamonds, col='clarity')\ng.map(plt.scatter, 'carat_cube', 'price', alpha=1/5)\nplt.yscale('log');",
"_____no_output_____"
]
],
[
[
"Price by Carat and Clarity Comment 2: <span style=\"color:black\">You should see across facets the general movement of the points upwards and to the left, corresponding with smaller diamond sizes, but higher value for their sizes. As a final comment, did you remember to apply transformation functions to the price and carat values?</span>",
"_____no_output_____"
],
[
"Let's try a different plot, for diamond price against cut and color quality features. To avoid the trap of higher quality grades being associated with smaller diamonds, and thus lower prices, we should focus our visualization on only a small range of diamond weights. For this plot, select diamonds in a small range around 1 carat weight. Try to make it so that your plot shows the effect of each of these categorical variables on the price of diamonds.",
"_____no_output_____"
]
],
[
[
"diamonds_flag = (diamonds['carat'] >= 0.99) & (diamonds['carat'] <= 1.03)\ndiamonds_sub = diamonds.loc[diamonds_flag,:]",
"_____no_output_____"
],
[
"diamonds_sub['cut'].unique()",
"_____no_output_____"
],
[
"diamonds_sub['color'].unique()",
"_____no_output_____"
],
[
"sb.pointplot(data=diamonds_sub, x='color', y='price', hue='cut', palette='mako')\nplt.yscale('log')\nplt.yticks([3000, 4000, 6000], ['3K', '4K', '6K']);",
"_____no_output_____"
],
[
"# multivariate plot of price by cut and color, for approx. 1 carat diamonds\nplt.figure(figsize=(10,6))\nsb.boxplot(data=diamonds_sub, x='color', y='price', hue='cut', palette='mako')\nplt.yscale('log')\nplt.yticks([3000, 4000, 6000, 10000], ['3K', '4K', '6K', '10K']);",
"_____no_output_____"
]
],
[
[
"Price by Cut and Color Comment 1: <span style=\"color:black\">There's a lot of ways that you could plot one numeric variable against two categorical variables. I think that the clustered box plot or the clustered point plot are the best choices in this case. With the number of category combinations to be plotted (7x5 = 35), it's hard to make full sense of a violin plot's narrow areas; simplicity is better. A clustered bar chart could work, but considering that price should be on a log scale, there isn't really a nice baseline that would work well.</span>",
"_____no_output_____"
],
[
"Price by Cut and Color Comment 2: <span style=\"color:black\">Assuming you went with a clustered plot approach, you should see a gradual increase in price across the main x-value clusters, as well as generally upwards trends within each cluster for the third variable. Aesthetically, did you remember to choose a sequential color scheme for whichever variable you chose for your third variable, to override the default qualitative scheme? If you chose a point plot, did you set a dodge parameter to spread the clusters out? </span>",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cbd548b00ab928d3b0de19fd5da26f335359fb4c
| 403,673 |
ipynb
|
Jupyter Notebook
|
docs/source/examples/Revisiting Lambert's problem in Python.ipynb
|
newlawrence/Poliastro
|
941d99e4682cef58b37990cd072bdf0f52de2716
|
[
"MIT"
] | 1 |
2018-12-09T18:33:52.000Z
|
2018-12-09T18:33:52.000Z
|
docs/source/examples/Revisiting Lambert's problem in Python.ipynb
|
ggarrett13/poliastro
|
9cc569ed4421f1e05d69de5df260ea919fa83a30
|
[
"MIT"
] | null | null | null |
docs/source/examples/Revisiting Lambert's problem in Python.ipynb
|
ggarrett13/poliastro
|
9cc569ed4421f1e05d69de5df260ea919fa83a30
|
[
"MIT"
] | 1 |
2021-11-24T12:00:27.000Z
|
2021-11-24T12:00:27.000Z
| 989.394608 | 132,088 | 0.955442 |
[
[
[
"# Revisiting Lambert's problem in Python",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom cycler import cycler\n\nfrom poliastro.core import iod\nfrom poliastro.iod import izzo\n\nplt.ion()\nplt.rc('text', usetex=True)",
"_____no_output_____"
]
],
[
[
"## Part 1: Reproducing the original figure",
"_____no_output_____"
]
],
[
[
"x = np.linspace(-1, 2, num=1000)\nM_list = 0, 1, 2, 3\nll_list = 1, 0.9, 0.7, 0, -0.7, -0.9, -1",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(10, 8))\nax.set_prop_cycle(cycler('linestyle', ['-', '--']) *\n (cycler('color', ['black']) * len(ll_list)))\nfor M in M_list:\n for ll in ll_list:\n T_x0 = np.zeros_like(x)\n for ii in range(len(x)):\n y = iod._compute_y(x[ii], ll)\n T_x0[ii] = iod._tof_equation(x[ii], y, 0.0, ll, M)\n if M == 0 and ll == 1:\n T_x0[x > 0] = np.nan\n elif M > 0:\n # Mask meaningless solutions\n T_x0[x > 1] = np.nan\n l, = ax.plot(x, T_x0)\n\nax.set_ylim(0, 10)\n\nax.set_xticks((-1, 0, 1, 2))\nax.set_yticks((0, np.pi, 2 * np.pi, 3 * np.pi))\nax.set_yticklabels(('$0$', '$\\pi$', '$2 \\pi$', '$3 \\pi$'))\n\nax.vlines(1, 0, 10)\nax.text(0.65, 4.0, \"elliptic\")\nax.text(1.16, 4.0, \"hyperbolic\")\n\nax.text(0.05, 1.5, \"$M = 0$\", bbox=dict(facecolor='white'))\nax.text(0.05, 5, \"$M = 1$\", bbox=dict(facecolor='white'))\nax.text(0.05, 8, \"$M = 2$\", bbox=dict(facecolor='white'))\n\nax.annotate(\"$\\lambda = 1$\", xy=(-0.3, 1), xytext=(-0.75, 0.25), arrowprops=dict(arrowstyle=\"simple\", facecolor=\"black\"))\nax.annotate(\"$\\lambda = -1$\", xy=(0.3, 2.5), xytext=(0.65, 2.75), arrowprops=dict(arrowstyle=\"simple\", facecolor=\"black\"))\n\nax.grid()\nax.set_xlabel(\"$x$\")\nax.set_ylabel(\"$T$\");",
"_____no_output_____"
]
],
[
[
"## Part 2: Locating $T_{min}$",
"_____no_output_____"
]
],
[
[
"for M in M_list:\n for ll in ll_list:\n x_T_min, T_min = iod._compute_T_min(ll, M, 10, 1e-8)\n ax.plot(x_T_min, T_min, 'kx', mew=2)\n\nfig",
"_____no_output_____"
]
],
[
[
"## Part 3: Try out solution",
"_____no_output_____"
]
],
[
[
"T_ref = 1\nll_ref = 0\n\n(x_ref, _), = iod._find_xy(ll_ref, T_ref, 0, 10, 1e-8)\nx_ref",
"_____no_output_____"
],
[
"ax.plot(x_ref, T_ref, 'o', mew=2, mec='red', mfc='none')\n\nfig",
"_____no_output_____"
]
],
[
[
"## Part 4: Run some examples",
"_____no_output_____"
]
],
[
[
"from astropy import units as u\n\nfrom poliastro.bodies import Earth",
"_____no_output_____"
]
],
[
[
"### Single revolution",
"_____no_output_____"
]
],
[
[
"k = Earth.k\nr0 = [15945.34, 0.0, 0.0] * u.km\nr = [12214.83399, 10249.46731, 0.0] * u.km\ntof = 76.0 * u.min\n\nexpected_va = [2.058925, 2.915956, 0.0] * u.km / u.s\nexpected_vb = [-3.451569, 0.910301, 0.0] * u.km / u.s\n\n(v0, v), = izzo.lambert(k, r0, r, tof)\nv",
"_____no_output_____"
],
[
"k = Earth.k\nr0 = [5000.0, 10000.0, 2100.0] * u.km\nr = [-14600.0, 2500.0, 7000.0] * u.km\ntof = 1.0 * u.h\n\nexpected_va = [-5.9925, 1.9254, 3.2456] * u.km / u.s\nexpected_vb = [-3.3125, -4.1966, -0.38529] * u.km / u.s\n\n(v0, v), = izzo.lambert(k, r0, r, tof)\nv",
"_____no_output_____"
]
],
[
[
"### Multiple revolutions",
"_____no_output_____"
]
],
[
[
"k = Earth.k\nr0 = [22592.145603, -1599.915239, -19783.950506] * u.km\nr = [1922.067697, 4054.157051, -8925.727465] * u.km\ntof = 10 * u.h\n\nexpected_va = [2.000652697, 0.387688615, -2.666947760] * u.km / u.s\nexpected_vb = [-3.79246619, -1.77707641, 6.856814395] * u.km / u.s\n\nexpected_va_l = [0.50335770, 0.61869408, -1.57176904] * u.km / u.s\nexpected_vb_l = [-4.18334626, -1.13262727, 6.13307091] * u.km / u.s\n\nexpected_va_r = [-2.45759553, 1.16945801, 0.43161258] * u.km / u.s\nexpected_vb_r = [-5.53841370, 0.01822220, 5.49641054] * u.km / u.s",
"_____no_output_____"
],
[
"(v0, v), = izzo.lambert(k, r0, r, tof, M=0)\nv",
"_____no_output_____"
],
[
"(_, v_l), (_, v_r) = izzo.lambert(k, r0, r, tof, M=1)",
"_____no_output_____"
],
[
"v_l",
"_____no_output_____"
],
[
"v_r",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbd54d98ef221c813cadf325fbee7fe9ba8c6aaf
| 15,614 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/MVP (Single block)-checkpoint.ipynb
|
ChiaraDM/RainbowFood-Collaborative-Filtering-
|
0ef536609575db9c0eedce8666bcf1f1b7d280c1
|
[
"Apache-2.0"
] | null | null | null |
.ipynb_checkpoints/MVP (Single block)-checkpoint.ipynb
|
ChiaraDM/RainbowFood-Collaborative-Filtering-
|
0ef536609575db9c0eedce8666bcf1f1b7d280c1
|
[
"Apache-2.0"
] | null | null | null |
.ipynb_checkpoints/MVP (Single block)-checkpoint.ipynb
|
ChiaraDM/RainbowFood-Collaborative-Filtering-
|
0ef536609575db9c0eedce8666bcf1f1b7d280c1
|
[
"Apache-2.0"
] | null | null | null | 39.529114 | 401 | 0.557961 |
[
[
[
"# DATAFRAMES INITIALISATION\n\nimport os\nos.chdir('C:\\\\Users\\\\asus\\\\OneDrive\\\\Documenti\\\\University Docs\\\\MSc Computing\\\\Final Project\\\\RainbowFood(JN)\\\\Rainbow-Food-Collaborative-Filtering-')\n\nimport pandas as pd\n\n# vegetables file\ncol_list_veg = [\"Vegetables\", \"Serving\", \"Calories\"]\ndf_veg = pd.read_csv(\"Vegetables.csv\", usecols = col_list_veg)\n\n# allergies file\ncol_list_all = [\"Class\", \"Type\", \"Group\", \"Food\", \"Allergy\"]\ndf_all = pd.read_csv(\"FoodAllergies.csv\", usecols = col_list_all)\n\n# got rid of the Nan values because it considered as it was float instead of string (could not apply lower case)\ndf_all.dropna(inplace = True)\n\n# recipe file\ncol_list_rec = ['Link', 'Title', 'Total Time', 'Servings', 'Ingredients', 'Instructions']\ndf_rec = pd.read_csv(\"Recipes.csv\", usecols = col_list_rec)\n\n# ratings\ncol_list_rat = [\"userId\", \"recipeId\", \"rating\"]\ndf_rat = pd.read_csv(\"Ratings_small.csv\", usecols = col_list_rat)\n\n# NLP FOR CLEANING UP INPUTS\n# lemmatising\nimport nltk\nnltk.download('wordnet')\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\n\n# FUNCTIONS\n# function to extract lists from pandas columns\ndef list_maker(column):\n return column.tolist()\n\n# function to make lower case in lists\ndef lower_case(column_list):\n for x in range(len(column_list)):\n column_list[x] = column_list[x].lower()\n return column_list\n\n# function to cut duplicates from a list\ndef no_duplicates(column_list):\n no_duplicates_list = []\n for x in column_list:\n if x not in no_duplicates_list:\n no_duplicates_list.append(x)\n return no_duplicates_list\n\n# function to make dictionaries\ndef dictionary_maker(list1, list2):\n zip_iterator = zip(list1, list2)\n dictionary = dict(zip_iterator)\n return dictionary\n\n# function to lemmatise words in lists\ndef lemmatise(list_of_words):\n lemmatised_words = []\n for word in list_of_words:\n lemmatised_words.append(lemmatizer.lemmatize(word))\n return lemmatised_words\n\n# function user inputs veggies\nmylist = []\nmybasket = []\ndef user_inputs_veggies():\n print(\"Enter 3 veggies: \")\n for x in range(1,4):\n basket = input(\"%d \" % x)\n mylist.append(basket.lower())\n for veg in lemmatise(mylist):\n if veg in veg_list:\n print(veg, \"= got it\")\n mybasket.append(veg)\n else:\n print(veg, \"= we don't have it\")\n\n# function user inputs quantities (NOT USED FOR GETTING RECIPES YET)\nveg_quantity = {}\ndef user_input_quantity():\n for x in mybasket:\n # Ask for the quantity, until it's correct\n while True:\n # Quantity?\n quantity = input(\"%s grams \" % x)\n # Is it an integer?\n try:\n int(quantity)\n break\n # No...\n except ValueError:\n # Is it a float?\n try:\n float(quantity)\n break\n # No...\n except ValueError:\n print(\"Please, use numbers in grams only\")\n # If it's valid, add it\n veg_quantity[x] = quantity\n return veg_quantity\n\n# CODE\n# Extracting lists from pandas columns\nveg_list = list_maker(df_veg['Vegetables'])\nfood_list = list_maker(df_all[\"Food\"])\nallergy_list = list_maker(df_all[\"Allergy\"])\nrecipe_titles_list = list_maker(df_rec['Title'])\ningredients_list = list_maker(df_rec['Ingredients'])\nusers_id_list = list_maker(df_rat[\"userId\"])\nrecipes_id_list = list_maker(df_rat[\"recipeId\"])\nratings_list = list_maker(df_rat[\"rating\"])\n\n# Lower case in lists\nveg_list = lower_case(veg_list)\nfood_list = lower_case(food_list)\nallergy_list = lower_case(allergy_list)\n#recipe_titles_list = lower_case(recipe_titles_list)\ningredients_list = lower_case(ingredients_list)\n\n# Dictionaries\nfood_allergy_dictionary = dictionary_maker(food_list, allergy_list)\nrecipe_titles_ingredients_dictionary = dictionary_maker(recipe_titles_list, ingredients_list)\nrecipes_id_ratings_dictionary = dictionary_maker(recipes_id_list, ratings_list)\n\n# User inputs veggies\nuser_inputs_veggies() \nif mybasket == []:\n print(\"Your basket is empty\")\nelse:\n print(\"Here's what we have\", mybasket)\n\n# User inputs quantities\nuser_input_quantity() \n\n# REST OF THE CODE (Still to change...)\n# USER INPUTS ALLERGIES (NOT USED FOR GETTING RECIPES YET)\nprint(\"Any allergies or intolerances? Please enter them here or leave it blank. \\n\")\nprint(\"Please, specify if you have allergy or intolerance for generic terms \\n\")\nprint(\"(e.g. 'nut allergy', 'gluten allergy', but not for 'strawberry' or 'strawberries'): \")\n\n# add allergies in the list\nmyallergies = []\n\n# empty basket to break\nbasket = \" \"\n\n# indefinite iteration over not empty basket\nwhile basket != \"\":\n \n # over input\n basket = input()\n \n # if input = num\n if basket.isnumeric() == True:\n \n # then print you don't want num \n print(\"No numbers, please\")\n \n # otherwise if it's a word \n elif basket.isnumeric() == False: \n \n # and the basket is not empty\n if basket != \"\":\n \n # append allergies to my list\n myallergies.append(basket)\n\nmy_allergies = lower_case(myallergies) \nmy_allergies = lemmatise(myallergies)\nmy_allergies = no_duplicates(my_allergies)\n\nfor al in my_allergies:\n if al in food_allergy_dictionary.keys() or al in food_allergy_dictionary.values():\n print(\"You said: \", al)\n else:\n print(al, \", got it, I will update my database\")\n \n# OUTPUT = RECIPES BASED ON USER'S VEGGIES\n# RegEx to find matches\nimport re\nrecipe_titles_list = []\nrecipe_title_to_matched_ingredient_list_dict_with_duplicates = {}\nrecipes_ingredients = {}\nrecipes = []\n\n\ninput_vegetable_list = mybasket\nrecipe_title_to_ingredient_list_dict = recipe_titles_ingredients_dictionary\n\nfor input_vegetable in input_vegetable_list:\n for recipe_title in recipe_title_to_ingredient_list_dict:\n ingredient_list_string = recipe_title_to_ingredient_list_dict[ recipe_title ]\n \n # df not perfect, values looked like list but it was a string... \n # with eval is list of lists\n ingredient_list = eval(ingredient_list_string)\n \n for ingredient in ingredient_list:\n find = re.search(input_vegetable, ingredient) \n \n if find:\n recipe_titles_list.append( recipe_title )\n \n if recipe_title in recipe_title_to_matched_ingredient_list_dict_with_duplicates:\n \n recipe_title_to_matched_ingredient_list_dict_with_duplicates[recipe_title].append(input_vegetable)\n else:\n recipe_title_to_matched_ingredient_list_dict_with_duplicates[recipe_title] = [input_vegetable]\n \n# duplicates removed \nfor key, value in recipe_title_to_matched_ingredient_list_dict_with_duplicates.items():\n recipes_ingredients[key] = list(set(value)) \nprint(\"\\n\")\n\nfor recipe_title in recipe_titles_list:\n if recipe_title not in recipes:\n recipes.append(recipe_title)\n \nprint(\"These are all the recipes that contain : \", mybasket)\nprint(\"\\n\")\nindex = 1\nfor recipe in recipes:\n print(index, recipe)\n index += 1\n\nimport random \nrecipes_ingredients_items = list(recipes_ingredients.items())\nrandom.shuffle(recipes_ingredients_items)\nrecipes_ingredients = dict(recipes_ingredients_items)\n\nindex = 1\nfor recipe in recipes_ingredients.items():\n index += 1\n \nrecipes = {}\ni_have_processed_these_already = []\n\nfor vegetable in input_vegetable_list:\n for key, values in recipes_ingredients.items():\n if vegetable in values:\n if not key in i_have_processed_these_already:\n if not vegetable in recipes:\n i_have_processed_these_already.append(key)\n recipes[vegetable] = key\n \nimport pprint\nprint(\"\\n\")\nprint(\"I would recommend you to try these recipes: \\n\")\npprint.pprint(recipes)\nprint(\"\\n\")\nprint(\"Here you can see the ingredients for the recipes selected: \\n\")\nfor recipe in recipes.values():\n for recipeT, ingredient in recipe_title_to_ingredient_list_dict.items():\n if recipe in recipeT:\n print(recipeT, \"\\n\",ingredient, \"\\n\")",
"[nltk_data] Downloading package wordnet to\n[nltk_data] C:\\Users\\asus\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package wordnet is already up-to-date!\n"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
cbd54ed3c3a6b1808d8964a21b1c9ee666d7bc0a
| 754,177 |
ipynb
|
Jupyter Notebook
|
functional_data/fetch_data.ipynb
|
darribas/data_processing
|
2bbb5bc18e7c148189f1a3219868035e3e78f6e2
|
[
"BSD-3-Clause"
] | null | null | null |
functional_data/fetch_data.ipynb
|
darribas/data_processing
|
2bbb5bc18e7c148189f1a3219868035e3e78f6e2
|
[
"BSD-3-Clause"
] | 2 |
2020-07-24T09:56:09.000Z
|
2020-10-31T18:09:36.000Z
|
functional_data/fetch_data.ipynb
|
darribas/data_processing
|
2bbb5bc18e7c148189f1a3219868035e3e78f6e2
|
[
"BSD-3-Clause"
] | 4 |
2020-07-15T16:07:39.000Z
|
2021-05-13T08:03:54.000Z
| 194.726827 | 595,588 | 0.864455 |
[
[
[
"# Download data for a functional layer of Spatial Signatures\n\nThis notebook downloads and prepares data for a functional layer of Spatial Signatures.",
"_____no_output_____"
]
],
[
[
"from download import download\nimport geopandas as gpd\nimport pandas as pd\nimport osmnx as ox\nfrom tqdm import tqdm\nfrom glob import glob\nimport rioxarray as ra\nimport pyproj\nimport zipfile\nimport tarfile\nfrom shapely.geometry import box, mapping\nimport requests\nimport datetime",
"_____no_output_____"
]
],
[
[
"## Population estimates\n\nPopulation estimates for England, Scotland and Wales. England is split into regions.\n\n### ONS data",
"_____no_output_____"
]
],
[
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthesouthwestregionofengland%2fmid2019sape22dt10g/sape22dt10gmid2019southwest.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/south_west_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthesouthwestregionofengland%2fmid2019sape22dt10g/sape22dt10gmid2019southwest.zip (1 byte)\n\nfile_sizes: 17.4MB [00:00, 72.8MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/south_west_england\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesintheyorkshireandthehumberregionofengland%2fmid2019sape22dt10c/sape22dt10cmid2019yorkshireandthehumber.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/yorkshire_humber_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesintheyorkshireandthehumberregionofengland%2fmid2019sape22dt10c/sape22dt10cmid2019yorkshireandthehumber.zip (1 byte)\n\nfile_sizes: 16.9MB [00:00, 72.4MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/yorkshire_humber_england\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthesoutheastregionofengland%2fmid2019sape22dt10i/sape22dt10imid2019southeast.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/south_east_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthesoutheastregionofengland%2fmid2019sape22dt10i/sape22dt10imid2019southeast.zip (1 byte)\n\nfile_sizes: 27.6MB [00:00, 71.8MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/south_east_england\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesintheeastmidlandsregionofengland%2fmid2019sape22dt10f/sape22dt10fmid2019eastmidlands.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/east_midlands_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesintheeastmidlandsregionofengland%2fmid2019sape22dt10f/sape22dt10fmid2019eastmidlands.zip (1 byte)\n\nfile_sizes: 14.5MB [00:00, 104MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/east_midlands_england\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthenorthwestregionofengland%2fmid2019sape22dt10b/sape22dt10bmid2019northwest.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/north_west_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthenorthwestregionofengland%2fmid2019sape22dt10b/sape22dt10bmid2019northwest.zip (1 byte)\n\nfile_sizes: 23.0MB [00:00, 67.3MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/north_west_england\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesintheeastregionofengland%2fmid2019sape22dt10h/sape22dt10hmid2019east.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/east_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesintheeastregionofengland%2fmid2019sape22dt10h/sape22dt10hmid2019east.zip (1 byte)\n\nfile_sizes: 18.8MB [00:00, 111MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/east_england\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinwales%2fmid2019sape22dt10j/sape22dt10jmid2019wales.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/wales', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinwales%2fmid2019sape22dt10j/sape22dt10jmid2019wales.zip (1 byte)\n\nfile_sizes: 9.60MB [00:00, 97.4MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/wales\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthenortheastregionofengland%2fmid2019sape22dt10d/sape22dt10dmid2019northeast.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/north_east_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthenortheastregionofengland%2fmid2019sape22dt10d/sape22dt10dmid2019northeast.zip (1 byte)\n\nfile_sizes: 8.39MB [00:00, 68.0MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/north_east_england\n"
],
[
"download('https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthewestmidlandsregionofengland%2fmid2019sape22dt10e/sape22dt10emid2019westmidlands.zip',\n '../../urbangrammar_samba/functional_data/population_estimates/west_midlands_england', kind='zip')",
"Creating data folder...\nDownloading data from https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fpopulationandmigration%2fpopulationestimates%2fdatasets%2fcensusoutputareaestimatesinthewestmidlandsregionofengland%2fmid2019sape22dt10e/sape22dt10emid2019westmidlands.zip (1 byte)\n\nfile_sizes: 17.7MB [00:00, 69.1MB/s] \nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/west_midlands_england\n"
]
],
[
[
"### Geometries",
"_____no_output_____"
]
],
[
[
"download('https://borders.ukdataservice.ac.uk/ukborders/easy_download/prebuilt/shape/England_oa_2011.zip', '../../urbangrammar_samba/functional_data/population_estimates/oa_geometry_england', kind='zip')",
"Creating data folder...\nDownloading data from https://borders.ukdataservice.ac.uk/ukborders/easy_download/prebuilt/shape/England_oa_2011.zip (388.3 MB)\n\nfile_sizes: 100%|████████████████████████████| 407M/407M [00:08<00:00, 49.9MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/oa_geometry_england\n"
],
[
"download('https://borders.ukdataservice.ac.uk/ukborders/easy_download/prebuilt/shape/Wales_oac_2011.zip', '../../urbangrammar_samba/functional_data/population_estimates/oa_geometry_wales', kind='zip')",
"Creating data folder...\nDownloading data from https://borders.ukdataservice.ac.uk/ukborders/easy_download/prebuilt/shape/Wales_oac_2011.zip (30.0 MB)\n\nfile_sizes: 100%|██████████████████████████| 31.4M/31.4M [00:00<00:00, 32.5MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/oa_geometry_wales\n"
]
],
[
[
"### Data cleaning and processing",
"_____no_output_____"
]
],
[
[
"england = gpd.read_file('../../urbangrammar_samba/functional_data/population_estimates/oa_geometry_england/england_oa_2011.shp')",
"_____no_output_____"
],
[
"wales = gpd.read_file('../../urbangrammar_samba/functional_data/population_estimates/oa_geometry_wales/wales_oac_2011.shp')",
"_____no_output_____"
],
[
"oa = england.append(wales[['code', 'label', 'name', 'geometry']])",
"_____no_output_____"
],
[
"files = glob('../../urbangrammar_samba/functional_data/population_estimates/*/*.xlsx', recursive=True)",
"_____no_output_____"
],
[
"%time merged = pd.concat([pd.read_excel(f, sheet_name='Mid-2019 Persons', header=0, skiprows=4) for f in files])",
"CPU times: user 12min 2s, sys: 640 ms, total: 12min 2s\nWall time: 12min 5s\n"
],
[
"population_est = oa.merge(merged, left_on='code', right_on='OA11CD', how='left')",
"_____no_output_____"
]
],
[
[
"### Add Scotland\n\nScottish data are shipped differently.\n\n#### Data",
"_____no_output_____"
]
],
[
[
"download('http://statistics.gov.scot/downloads/file?id=438c9dc6-dca0-48d5-995c-e3bb1d34e29e%2FSAPE_2011DZ_2001-2019_Five_and_broad_age_groups.zip', '../../urbangrammar_samba/functional_data/population_estimates/scotland', kind='zip')",
"Creating data folder...\nDownloading data from https://scottish-government-files.s3.amazonaws.com/438c9dc6-dca0-48d5-995c-e3bb1d34e29e/SAPE_2011DZ_2001-2019_Five_and_broad_age_groups.zip (35.8 MB)\n\nfile_sizes: 100%|██████████████████████████| 37.5M/37.5M [00:02<00:00, 14.0MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/scotland\n"
],
[
"pop_scot = pd.read_csv('../../urbangrammar_samba/functional_data/population_estimates/scotland/data - statistics.gov.scot - SAPE_2011DZ_2019_Five.csv')",
"_____no_output_____"
],
[
"pop_scot = pop_scot[pop_scot.Sex == 'All']",
"_____no_output_____"
],
[
"counts = pop_scot[['GeographyCode', 'Value']].groupby('GeographyCode').sum()",
"_____no_output_____"
]
],
[
[
"#### Geometry",
"_____no_output_____"
]
],
[
[
"download('http://sedsh127.sedsh.gov.uk/Atom_data/ScotGov/ZippedShapefiles/SG_DataZoneBdry_2011.zip', '../../urbangrammar_samba/functional_data/population_estimates/dz_geometry_scotland', kind='zip')",
"Creating data folder...\nDownloading data from http://sedsh127.sedsh.gov.uk/Atom_data/ScotGov/ZippedShapefiles/SG_DataZoneBdry_2011.zip (18.2 MB)\n\nfile_sizes: 100%|██████████████████████████| 19.1M/19.1M [00:06<00:00, 3.05MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/population_estimates/dz_geometry_scotland\n"
],
[
"data_zones = gpd.read_file('../../urbangrammar_samba/functional_data/population_estimates/dz_geometry_scotland')",
"_____no_output_____"
],
[
"scotland = data_zones.merge(counts, left_on='DataZone', right_index=True)",
"_____no_output_____"
],
[
"scotland = scotland[['DataZone', 'Value', 'geometry']].rename(columns={'DataZone': 'code', 'Value': 'population'})",
"_____no_output_____"
],
[
"population_est = population_est[['code', 'All Ages', 'geometry']].rename(columns={'All Ages': 'population'}).append(scotland)",
"_____no_output_____"
],
[
"population_est.to_parquet('../../urbangrammar_samba/functional_data/population_estimates/gb_population_estimates.pq')",
"/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:1: UserWarning: this is an initial implementation of Parquet/Feather file support and associated metadata. This is tracking version 0.1.0 of the metadata specification at https://github.com/geopandas/geo-arrow-spec\n\nThis metadata specification does not yet make stability promises. We do not yet recommend using this in a production setting unless you are able to rewrite your Parquet/Feather files.\n\nTo further ignore this warning, you can do: \nimport warnings; warnings.filterwarnings('ignore', message='.*initial implementation of Parquet.*')\n \"\"\"Entry point for launching an IPython kernel.\n"
]
],
[
[
"## WorldPop\n\nData is dowloaded clipped to GB, so we only have to reproject to OSGB.",
"_____no_output_____"
]
],
[
[
"download('ftp://ftp.worldpop.org.uk/GIS/Population/Global_2000_2020_Constrained/2020/BSGM/GBR/gbr_ppp_2020_constrained.tif', '../../urbangrammar_samba/functional_data/population_estimates/world_pop/gbr_ppp_2020_constrained.tif')",
"Downloading data from ftp://ftp.worldpop.org.uk/GIS/Population/Global_2000_2020_Constrained/2020/BSGM/GBR/gbr_ppp_2020_constrained.tif (32.7 MB)\n\nfile_sizes: 100%|██████████████████████████| 34.3M/34.3M [00:01<00:00, 19.2MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/population_estimates/world_pop/gbr_ppp_2020_constrained.tif\n"
]
],
[
[
"### Reproject to OSGB",
"_____no_output_____"
]
],
[
[
"wp = ra.open_rasterio(\"../../urbangrammar_samba/functional_data/population_estimates/world_pop/gbr_ppp_2020_constrained.tif\")\nwp.rio.crs",
"_____no_output_____"
],
[
"%time wp_osgb = wp.rio.reproject(pyproj.CRS(27700).to_wkt())",
"CPU times: user 8.28 s, sys: 896 ms, total: 9.17 s\nWall time: 9.18 s\n"
],
[
"wp_osgb.rio.crs",
"_____no_output_____"
],
[
"wp_osgb.rio.to_raster(\"../../urbangrammar_samba/functional_data/population_estimates/world_pop/gbr_ppp_2020_constrained_osgb.tif\")",
"_____no_output_____"
]
],
[
[
"## POIs\n### Geolytix retail",
"_____no_output_____"
],
[
"Geolytix retail POIs: https://drive.google.com/u/0/uc?id=1B8M7m86rQg2sx2TsHhFa2d-x-dZ1DbSy (no idea how to get them programatically, so they were downloaded manually)",
"_____no_output_____"
]
],
[
[
"geolytix = pd.read_csv('../../urbangrammar_samba/functional_data/pois/GEOLYTIX - RetailPoints/geolytix_retailpoints_v17_202008.csv')\ngeolytix.head(2)",
"_____no_output_____"
]
],
[
[
"We already have coordinates in OSGB, no need to preprocess.",
"_____no_output_____"
],
[
"### Listed buildings\n\nWe have to merge English, Scottish and Welsh data.\n\nEngland downloaded manually from https://services.historicengland.org.uk/NMRDataDownload/OpenPages/Download.aspx",
"_____no_output_____"
]
],
[
[
"download('https://inspire.hes.scot/AtomService/DATA/lb_scotland.zip', '../../urbangrammar_samba/functional_data/pois/listed_buildings/scotland', kind='zip')",
"Creating data folder...\nDownloading data from https://inspire.hes.scot/AtomService/DATA/lb_scotland.zip (6.1 MB)\n\nfile_sizes: 100%|██████████████████████████| 6.41M/6.41M [00:01<00:00, 3.43MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/pois/listed_buildings/scotland\n"
],
[
"download('http://lle.gov.wales/catalogue/item/ListedBuildings.zip', '../../urbangrammar_samba/functional_data/pois/listed_buildings/wales', kind='zip')",
"Creating data folder...\nDownloading data from http://lle.gov.wales/catalogue/item/ListedBuildings.zip (2.5 MB)\n\nfile_sizes: 100%|██████████████████████████| 2.57M/2.57M [00:00<00:00, 13.3MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/pois/listed_buildings/wales\n"
]
],
[
[
"#### Processing",
"_____no_output_____"
]
],
[
[
"with zipfile.ZipFile(\"../../urbangrammar_samba/functional_data/pois/listed_buildings/Listed Buildings.zip\", 'r') as zip_ref:\n zip_ref.extractall(\"../../urbangrammar_samba/functional_data/pois/listed_buildings/england\")",
"_____no_output_____"
],
[
"england = gpd.read_file('../../urbangrammar_samba/functional_data/pois/listed_buildings/england/ListedBuildings_23Oct2020.shp')",
"_____no_output_____"
],
[
"england.head(2)",
"_____no_output_____"
],
[
"scotland = gpd.read_file('../../urbangrammar_samba/functional_data/pois/listed_buildings/scotland/Listed_Buildings.shp')",
"_____no_output_____"
],
[
"scotland.head(2)",
"_____no_output_____"
],
[
"wales = gpd.read_file('../../urbangrammar_samba/functional_data/pois/listed_buildings/wales/Cadw_ListedBuildingsMPoint.shp')",
"_____no_output_____"
],
[
"wales.head(2)",
"_____no_output_____"
],
[
"listed = pd.concat([england[['geometry']], scotland[['geometry']], wales[['geometry']]])\nlisted.reset_index(drop=True).to_parquet(\"../../urbangrammar_samba/functional_data/pois/listed_buildings/listed_buildings_gb.pq\")",
"<ipython-input-44-77ad3d860075>:2: UserWarning: this is an initial implementation of Parquet/Feather file support and associated metadata. This is tracking version 0.1.0 of the metadata specification at https://github.com/geopandas/geo-arrow-spec\n\nThis metadata specification does not yet make stability promises. We do not yet recommend using this in a production setting unless you are able to rewrite your Parquet/Feather files.\n\nTo further ignore this warning, you can do: \nimport warnings; warnings.filterwarnings('ignore', message='.*initial implementation of Parquet.*')\n listed.reset_index(drop=True).to_parquet(\"../../urbangrammar_samba/functional_data/pois/listed_buildings/listed_buildings_gb.pq\")\n"
]
],
[
[
"## Night lights\n\nWe need to clip it to the extent of GB (dataset has a global coverage) and reproject to OSGB.",
"_____no_output_____"
]
],
[
[
"with open('../../urbangrammar_samba/functional_data/employment/SVDNB_npp_20190301-20190331_75N060W_vcmcfg_v10_c201904071900.tgz', \"wb\") as down:\n down.write(requests.get('https://data.ngdc.noaa.gov/instruments/remote-sensing/passive/spectrometers-radiometers/imaging/viirs/dnb_composites/v10//201903/vcmcfg/SVDNB_npp_20190301-20190331_75N060W_vcmcfg_v10_c201904071900.tgz').content)\n down.close()",
"_____no_output_____"
],
[
"with tarfile.open('../../urbangrammar_samba/functional_data/employment/SVDNB_npp_20190301-20190331_75N060W_vcmcfg_v10_c201904071900.tgz', 'r') as zip_ref:\n zip_ref.extractall(\"../../urbangrammar_samba/functional_data/employment\")",
"_____no_output_____"
]
],
[
[
"### Clip and reproject",
"_____no_output_____"
]
],
[
[
"nl = ra.open_rasterio('../../urbangrammar_samba/functional_data/employment/SVDNB_npp_20190301-20190331_75N060W_vcmcfg_v10_c201904071900.avg_rade9h.tif')",
"_____no_output_____"
],
[
"nl.rio.crs",
"_____no_output_____"
],
[
"extent = gpd.read_parquet(\"../../urbangrammar_samba/spatial_signatures/local_auth_chunks.pq\")",
"_____no_output_____"
],
[
"extent = extent.to_crs(4326)",
"_____no_output_____"
],
[
"%time nl_clipped = nl.rio.clip([mapping(box(*extent.total_bounds))], all_touched=True)",
"CPU times: user 3.96 s, sys: 6.95 s, total: 10.9 s\nWall time: 29.5 s\n"
],
[
"%time nl_osgb = nl_clipped.rio.reproject(pyproj.CRS(27700).to_wkt())",
"CPU times: user 766 ms, sys: 50.2 ms, total: 816 ms\nWall time: 816 ms\n"
],
[
"nl_osgb.rio.to_raster(\"../../urbangrammar_samba/functional_data/employment/night_lights_osgb.tif\")",
"_____no_output_____"
],
[
"nl_osgb.plot(figsize=(12, 12), vmin=0, vmax=7)",
"_____no_output_____"
]
],
[
[
"## Postcodes\n\nKeeping only active postcodes, relevant columns and determining their age.",
"_____no_output_____"
]
],
[
[
"download('https://www.arcgis.com/sharing/rest/content/items/b6e6715fa1984648b5e690b6a8519e53/data', '../../urbangrammar_samba/functional_data/postcode/nhspd', kind='zip')",
"Creating data folder...\nDownloading data from https://ago-item-storage.s3.us-east-1.amazonaws.com/b6e6715fa1984648b5e690b6a8519e53/NHSPD_AUG_2020_UK_FULL.zip?X-Amz-Security-Token=IQoJb3JpZ2luX2VjEGcaCXVzLWVhc3QtMSJGMEQCIE1aY0Pvl6tQbhtVpUFLoDlgPOfnYQeua3PqJo%2BY4ha7AiBmEHPkSi6dk7cfbOMACbdFZIJkTemkkKYLzVaD5gPFnSq9Awi%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F8BEAAaDDYwNDc1ODEwMjY2NSIMqVOVkqTsT8bs3%2FTqKpEDPg1CUnhXrkkNksaeepovynl5NWDCyWb5iMjrMuss6PTKTyCod85tX1OfcgXIhUdARci%2FKYA5fOpfPJGJpuJ%2B1qoljKytKriAyaNU%2FRonRCgB%2FSti5aaQy8i7uK923IlQwx1tbNswcBs2eO6bAYQagoRIsiv%2FynfrVAoot0zgl9nxGomHFYugdHXKoqqHSmAkYf%2FzEZmuehv0hPDealY%2FPUFbopmmGro0XY1ETls52NzkUJKhaqdz9kofSWpRrrOuVi8N3%2Ft9ggvENoVnAhw62OpBKLIoGvKyUa8XVX4qD5uljNRB6N9fpbR2BcxDERzhYDR2zSd0z6XCWjAI6UBBLcZy%2FOd2NMcP5tTaQWeA2gVtIReskJPB2MF60srFTUl07eEFub41lxQQyEqJ05uNg5mp2iwokIr7mR3Nq7GJxrzIH80QgYMEXiqpUlzptwYumC0%2F3JdqsXpNlyr0m4PR5VdcskpyYnsEGpnetaz%2B0G4%2FVhRlB1n4DIFfdMvahSf%2F9h%2FkhDyq7ADtcGie%2Ba3V%2Bhcw3MyF%2FQU67AFvPcSHt9IlZ4h%2B3Ls3iBfbnynIjGG96K8W23RkCzosvVeEzqvBd7oHufO3LrcegBJN0rvK4jwLbzomgGjTfGrHvfUSpPl4gUSAZp1CY2rqbng8blAX5tyGwo7%2BnOSybr33uDiJb9sFd8InpfOeV7Yud%2BB3gIQEdyOnS5XgR7hth3AIJPRsXbCR2yWJrkx%2BFjj4nDsNlVG73RbjNUL%2FfV4nm3lAsT5oUBCbFDO72xiEW9f3%2BgLUiAmwWmapM83nlhYF4ZAx%2Fltl%2BPD5BsvsF8zGUhCFXketa%2Bh3nYgPST1MYpT7ANE68XXJEtA9AQ%3D%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20201103T145506Z&X-Amz-SignedHeaders=host&X-Amz-Expires=300&X-Amz-Credential=ASIAYZTTEKKETFSSP5W2%2F20201103%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=f290dd148c10a89a40b5ef7f3f0d15eda6abc484fac92116edba6a1c46205ac9 (104.8 MB)\n\nfile_sizes: 100%|████████████████████████████| 110M/110M [00:04<00:00, 24.2MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/postcode/nhspd\n"
],
[
"postcodes = pd.read_csv(\"../../urbangrammar_samba/functional_data/postcode/nhspd/Data/nhg20aug.csv\", header=None)",
"/opt/conda/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3146: DtypeWarning: Columns (7,10,11,17,20,26,35) have mixed types.Specify dtype option on import or set low_memory=False.\n has_raised = await self.run_ast_nodes(code_ast.body, cell_name,\n"
],
[
"postcodes = postcodes.iloc[:, :6]\nexisting = postcodes[postcodes[3].isna()]\nlocated = existing[existing[4].notna()]\nlocated = located.rename(columns={0: 'postcode', 1: 'postcode2', 2:'introduced', 3:'terminated', 4:'x', 5:'y'})\nlocated.introduced = pd.to_datetime(located.introduced, format=\"%Y%m\")\nlocated['age'] = (pd.to_datetime('today') - located.introduced).dt.days\nlocated.drop(columns=['postcode2', 'terminated']).to_parquet('../../urbangrammar_samba/functional_data/postcode/postcodes_gb.pq')",
"_____no_output_____"
]
],
[
[
"## Food hygiene rating scheme",
"_____no_output_____"
],
[
"FHRS https://data.cdrc.ac.uk/dataset/food-hygiene-rating-scheme-fhrs-ratings (requires login)",
"_____no_output_____"
]
],
[
[
"fhrs = pd.read_csv('../../urbangrammar_samba/functional_data/fhrs/Data/fhrs_location_20200528.csv')",
"_____no_output_____"
],
[
"fhrs",
"_____no_output_____"
]
],
[
[
"No need to preprocess at the moment. Contains OSGB coordinates for each point.",
"_____no_output_____"
],
[
"## Business census\n\nhttps://data.cdrc.ac.uk/dataset/business-census (requires login)\n`encoding = \"ISO-8859-1\"`\n\n- get gemetries\n - either geocode addresses (could be expensive\n - or link to postcode points",
"_____no_output_____"
],
[
"## Workplace density\n\nDowload workplace population data from scottish census and english census, combine together and link to geometry.",
"_____no_output_____"
]
],
[
[
"download('http://www.scotlandscensus.gov.uk/documents/additional_tables/WP605SCwz.csv', '../../urbangrammar_samba/functional_data/employment/workplace/scotland_industry.csv')",
"Downloading data from https://www.scotlandscensus.gov.uk/documents/additional_tables/WP605SCwz.csv (234 kB)\n\nfile_sizes: 100%|████████████████████████████| 239k/239k [00:00<00:00, 2.47MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/scotland_industry.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1314_1.bulk.csv?time=latest&measures=20100&geography=TYPE262', '../../urbangrammar_samba/functional_data/employment/workplace/england_wales_industry.csv', timeout=60)",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1314_1.bulk.csv?time=latest&measures=20100&geography=TYPE262 (5.1 MB)\n\nfile_sizes: 100%|██████████████████████████| 5.35M/5.35M [00:00<00:00, 7.41MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/england_wales_industry.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265922TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/north_west.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265922TYPE299 (781 kB)\n\nfile_sizes: 100%|████████████████████████████| 799k/799k [00:00<00:00, 6.92MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/north_west.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265926TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/east.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265926TYPE299 (636 kB)\n\nfile_sizes: 100%|████████████████████████████| 651k/651k [00:00<00:00, 6.86MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/east.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265924TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/east_midlands.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265924TYPE299 (492 kB)\n\nfile_sizes: 100%|████████████████████████████| 504k/504k [00:00<00:00, 6.91MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/east_midlands.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265927TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/london.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265927TYPE299 (839 kB)\n\nfile_sizes: 100%|████████████████████████████| 859k/859k [00:00<00:00, 6.74MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/london.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265921TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/north_east.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265921TYPE299 (294 kB)\n\nfile_sizes: 100%|████████████████████████████| 301k/301k [00:00<00:00, 5.98MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/north_east.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265928TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/south_east.csv', timeout=30)",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265928TYPE299 (926 kB)\n\nfile_sizes: 100%|████████████████████████████| 948k/948k [00:00<00:00, 7.44MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/south_east.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265929TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/south_west.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265929TYPE299 (591 kB)\n\nfile_sizes: 100%|████████████████████████████| 605k/605k [00:00<00:00, 7.05MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/south_west.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265925TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/west_midlands.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265925TYPE299 (599 kB)\n\nfile_sizes: 100%|████████████████████████████| 614k/614k [00:00<00:00, 6.14MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/west_midlands.csv\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265923TYPE299', '../../urbangrammar_samba/functional_data/employment/workplace/yorkshire.csv')",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_1300_1.bulk.csv?time=latest&measures=20100&geography=2013265923TYPE299 (578 kB)\n\nfile_sizes: 100%|████████████████████████████| 592k/592k [00:00<00:00, 6.67MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/yorkshire.csv\n"
],
[
"download('https://www.nrscotland.gov.uk/files/geography/output-area-2011-mhw.zip', '../../urbangrammar_samba/functional_data/employment/workplace/scotland_oa', kind='zip')",
"Creating data folder...\nDownloading data from https://www.nrscotland.gov.uk/files/geography/output-area-2011-mhw.zip (31.2 MB)\n\nfile_sizes: 100%|██████████████████████████| 32.7M/32.7M [00:00<00:00, 65.3MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/employment/workplace/scotland_oa\n"
],
[
"download('https://www.nomisweb.co.uk/api/v01/dataset/nm_155_1.bulk.csv?time=latest&measures=20100&geography=TYPE262', '../../urbangrammar_samba/functional_data/employment/workplace/wp_density_ew.csv', timeout=30)",
"Downloading data from https://www.nomisweb.co.uk/api/v01/dataset/nm_155_1.bulk.csv?time=latest&measures=20100&geography=TYPE262 (2.3 MB)\n\nfile_sizes: 100%|██████████████████████████| 2.46M/2.46M [00:00<00:00, 7.66MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/wp_density_ew.csv\n"
],
[
"download('https://www.nrscotland.gov.uk/files//geography/products/workplacezones2011scotland.zip', '../../urbangrammar_samba/functional_data/employment/workplace/wpz_scotland', kind='zip')",
"Creating data folder...\nDownloading data from https://www.nrscotland.gov.uk/files//geography/products/workplacezones2011scotland.zip (14.7 MB)\n\nfile_sizes: 100%|██████████████████████████| 15.4M/15.4M [00:00<00:00, 39.3MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/employment/workplace/wpz_scotland\n"
],
[
"download('http://www.scotlandscensus.gov.uk/documents/additional_tables/WP102SCca.csv', '../../urbangrammar_samba/functional_data/employment/workplace/wp_density_scotland.csv')",
"Downloading data from https://www.scotlandscensus.gov.uk/documents/additional_tables/WP102SCca.csv (3 kB)\n\nfile_sizes: 100%|███████████████████████████| 2.79k/2.79k [00:00<00:00, 184kB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/wp_density_scotland.csv\n"
],
[
"download('http://www.scotlandscensus.gov.uk/documents/additional_tables/WP103SCwz.csv', '../../urbangrammar_samba/functional_data/employment/workplace/wp_pop_scotland.csv')",
"Downloading data from https://www.scotlandscensus.gov.uk/documents/additional_tables/WP103SCwz.csv (462 kB)\n\nfile_sizes: 100%|████████████████████████████| 473k/473k [00:00<00:00, 4.64MB/s]\nSuccessfully downloaded file to ../../urbangrammar_samba/functional_data/employment/workplace/wp_pop_scotland.csv\n"
],
[
"with zipfile.ZipFile(\"../../urbangrammar_samba/functional_data/employment/workplace/wz2011ukbgcv2.zip\", 'r') as zip_ref:\n zip_ref.extractall(\"../../urbangrammar_samba/functional_data/employment/workplace/\")",
"_____no_output_____"
],
[
"wpz_geom = gpd.read_file('../../urbangrammar_samba/functional_data/employment/workplace/WZ_2011_UK_BGC_V2.shp')",
"_____no_output_____"
],
[
"wpz_geom",
"_____no_output_____"
],
[
"wpz_ew = pd.read_csv(\"../../urbangrammar_samba/functional_data/employment/workplace/wp_density_ew.csv\")",
"_____no_output_____"
],
[
"wpz_ew",
"_____no_output_____"
],
[
"wpz = wpz_geom[['WZ11CD', 'LAD_DCACD', 'geometry']].merge(wpz_ew[['geography code', 'Area/Population Density: All usual residents; measures: Value']], left_on='WZ11CD', right_on='geography code', how='left')",
"_____no_output_____"
],
[
"scot = pd.read_csv(\"../../urbangrammar_samba/functional_data/employment/workplace/wp_pop_scotland.csv\", header=5)",
"_____no_output_____"
],
[
"wpz = wpz.merge(scot[['Unnamed: 0', 'Total']], left_on='WZ11CD', right_on='Unnamed: 0', how='left')",
"_____no_output_____"
],
[
"wpz.Total = wpz.Total.astype(str).apply(lambda x: x.replace(',', '') if ',' in x else x).astype(float)",
"_____no_output_____"
],
[
"wpz['count'] = wpz['Area/Population Density: All usual residents; measures: Value'].astype(float).fillna(0) + wpz.Total.fillna(0)",
"_____no_output_____"
],
[
"wpz = wpz[~wpz.WZ11CD.str.startswith('N')]",
"_____no_output_____"
],
[
"wpz[['geography code', 'count', 'geometry']].to_parquet('../../urbangrammar_samba/functional_data/employment/workplace/workplace_population_gb.pq')",
"<ipython-input-144-0a3123e8e9c0>:1: UserWarning: this is an initial implementation of Parquet/Feather file support and associated metadata. This is tracking version 0.1.0 of the metadata specification at https://github.com/geopandas/geo-arrow-spec\n\nThis metadata specification does not yet make stability promises. We do not yet recommend using this in a production setting unless you are able to rewrite your Parquet/Feather files.\n\nTo further ignore this warning, you can do: \nimport warnings; warnings.filterwarnings('ignore', message='.*initial implementation of Parquet.*')\n wpz[['geography code', 'count', 'geometry']].to_parquet('../../urbangrammar_samba/functional_data/employment/workplace/workplace_population_gb.pq')\n"
],
[
"wpz_ind_s = pd.read_csv('../../urbangrammar_samba/functional_data/employment/workplace/scotland_industry.csv', skiprows=4)\nwpz_ind_s = wpz_ind_s.loc[4:5378].drop(columns=[c for c in wpz_ind_s.columns if 'Unnamed' in c])\nwpz_ind_s",
"_____no_output_____"
],
[
"wpz_ind_s.columns",
"_____no_output_____"
],
[
"wpz_ind_ew = pd.read_csv('../../urbangrammar_samba/functional_data/employment/workplace/england_wales_industry.csv')\nwpz_ind_ew.columns",
"_____no_output_____"
],
[
"wpz_ind_ew['A, B, D, E. Agriculture, energy and water'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['A', 'B', 'D', 'E']]].sum(axis=1)\nwpz_ind_ew['C. Manufacturing'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['C']]].sum(axis=1)\nwpz_ind_ew['F. Construction'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['F']]].sum(axis=1)\nwpz_ind_ew['G, I. Distribution, hotels and restaurants'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['G', 'I']]].sum(axis=1)\nwpz_ind_ew['H, J. Transport and communication'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['H', 'J']]].sum(axis=1)\nwpz_ind_ew['K, L, M, N. Financial, real estate, professional and administrative activities'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['K', 'L', 'M', 'N']]].sum(axis=1)\nwpz_ind_ew['O,P,Q. Public administration, education and health'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['O', 'P', 'Q']]].sum(axis=1)\nwpz_ind_ew['R, S, T, U. Other'] = wpz_ind_ew[[c for c in wpz_ind_ew.columns[4:] if c[10] in ['R', 'S', 'T', 'U']]].sum(axis=1)",
"_____no_output_____"
],
[
"wpz = wpz_ind_ew[['geography code'] + list(wpz_ind_ew.columns[-8:])].append(wpz_ind_s.rename(columns={'2011 Workplace Zone': 'geography code'}).drop(columns='All workplace population aged 16 to 74'))",
"_____no_output_____"
],
[
"wpz_merged = wpz_geom.merge(wpz, left_on='WZ11CD', right_on='geography code', how='left')\nwpz_merged = wpz_merged[~wpz_merged.WZ11CD.str.startswith('N')]",
"_____no_output_____"
],
[
"wpz_merged = wpz_merged.reset_index(drop=True)[list(wpz.columns) + ['geometry']]\nwpz_merged.columns",
"_____no_output_____"
],
[
"for c in wpz_merged.columns[1:-1]:\n wpz_merged[c] = wpz_merged[c].astype(str).apply(lambda x: x.replace(',', '') if ',' in x else x).astype(float)",
"_____no_output_____"
],
[
"wpz_merged",
"_____no_output_____"
],
[
"wpz_merged.to_parquet('../../urbangrammar_samba/functional_data/employment/workplace/workplace_by_industry_gb.pq')",
"_____no_output_____"
],
[
"%%time\npois = []\nfor i in tqdm(range(103), total=103):\n nodes = gpd.read_parquet(f'../../urbangrammar_samba/spatial_signatures/morphometrics/nodes/nodes_{i}.pq')\n poly = nodes.to_crs(4326).unary_union.convex_hull\n tags = {'amenity': ['cinema', 'theatre']}\n pois.append(ox.geometries.geometries_from_polygon(poly, tags))",
"100%|██████████| 103/103 [15:42<00:00, 9.15s/it]"
],
[
"pois_merged = pd.concat(pois)\npois_merged",
"/opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n and should_run_async(code)\n"
],
[
"pois_merged.drop_duplicates(subset='unique_id')[['amenity', 'name', 'geometry']].to_crs(27700).to_parquet('../../urbangrammar_samba/functional_data/pois/culture_gb.pq')",
"/opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n and should_run_async(code)\n<ipython-input-150-b737c023146a>:1: UserWarning: this is an initial implementation of Parquet/Feather file support and associated metadata. This is tracking version 0.1.0 of the metadata specification at https://github.com/geopandas/geo-arrow-spec\n\nThis metadata specification does not yet make stability promises. We do not yet recommend using this in a production setting unless you are able to rewrite your Parquet/Feather files.\n\nTo further ignore this warning, you can do: \nimport warnings; warnings.filterwarnings('ignore', message='.*initial implementation of Parquet.*')\n pois_merged.drop_duplicates(subset='unique_id')[['amenity', 'name', 'geometry']].to_parquet('../../urbangrammar_samba/functional_data/pois/culture_gb.pq')\n"
]
],
[
[
"## Corine land cover\n\nCorine - get link from https://land.copernicus.eu/pan-european/corine-land-cover\n\nWe need to extract data, clip to GB and reproject to OSGB.",
"_____no_output_____"
]
],
[
[
"download('https://land.copernicus.eu/land-files/afd643e4508e9dd7af7659c1fb1d75017ba6d9f4.zip', '../../urbangrammar_samba/functional_data/land_use/corine', kind='zip')",
"Creating data folder...\nDownloading data from https://land.copernicus.eu/land-files/afd643e4508e9dd7af7659c1fb1d75017ba6d9f4.zip (3.62 GB)\n\nfile_sizes: 100%|██████████████████████████| 3.89G/3.89G [01:11<00:00, 54.5MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/land_use/corine\n"
],
[
"with zipfile.ZipFile(\"../../urbangrammar_samba/functional_data/land_use/corine/u2018_clc2018_v2020_20u1_geoPackage.zip\", 'r') as zip_ref:\n zip_ref.extractall(\"../../urbangrammar_samba/functional_data/land_use/corine\")",
"/opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n and should_run_async(code)\n"
],
[
"extent = gpd.read_parquet(\"../../urbangrammar_samba/spatial_signatures/local_auth_chunks.pq\")\ncorine_gdf = gpd.read_file(\"../../urbangrammar_samba/functional_data/land_use/corine/u2018_clc2018_v2020_20u1_geoPackage/DATA/U2018_CLC2018_V2020_20u1.gpkg\", mask=extent)",
"/opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n and should_run_async(code)\n"
],
[
"corine_gdf.to_crs(27700).to_parquet(\"../../urbangrammar_samba/functional_data/land_use/corine/corine_gb.pq\")",
"/opt/conda/lib/python3.8/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.\n and should_run_async(code)\n<ipython-input-159-970263de7d63>:1: UserWarning: this is an initial implementation of Parquet/Feather file support and associated metadata. This is tracking version 0.1.0 of the metadata specification at https://github.com/geopandas/geo-arrow-spec\n\nThis metadata specification does not yet make stability promises. We do not yet recommend using this in a production setting unless you are able to rewrite your Parquet/Feather files.\n\nTo further ignore this warning, you can do: \nimport warnings; warnings.filterwarnings('ignore', message='.*initial implementation of Parquet.*')\n corine_gdf.to_crs(27700).to_parquet(\"../../urbangrammar_samba/functional_data/land_use/corine/corine_gb.pq\")\n"
]
],
[
[
"## Land cover classification\nLand cover classification - get link from https://cds.climate.copernicus.eu/cdsapp#!/dataset/satellite-land-cover?tab=form\n\nWe need to clip it to the extent of GB (dataset has a global coverage) and reproject to OSGB.",
"_____no_output_____"
]
],
[
[
"download('http://136.156.133.37/cache-compute-0011/cache/data0/dataset-satellite-land-cover-c20f5b30-2bdb-4f69-a21e-c8f2e696e715.zip', '../../urbangrammar_samba/functional_data/land_use/lcc', kind='zip' )",
"Creating data folder...\nDownloading data from http://136.156.133.37/cache-compute-0011/cache/data0/dataset-satellite-land-cover-c20f5b30-2bdb-4f69-a21e-c8f2e696e715.zip (2.17 GB)\n\nfile_sizes: 100%|██████████████████████████| 2.33G/2.33G [01:26<00:00, 27.1MB/s]\nExtracting zip file...\nSuccessfully downloaded / unzipped to ../../urbangrammar_samba/functional_data/land_use/lcc\n"
],
[
"lcc = ra.open_rasterio(\"../../urbangrammar_samba/functional_data/land_use/lcc/C3S-LC-L4-LCCS-Map-300m-P1Y-2018-v2.1.1.nc\")",
"/opt/conda/lib/python3.8/site-packages/rasterio/__init__.py:221: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.\n s = DatasetReader(path, driver=driver, sharing=sharing, **kwargs)\n/opt/conda/lib/python3.8/site-packages/rioxarray/_io.py:678: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.\n warnings.warn(str(rio_warning.message), type(rio_warning.message))\n/opt/conda/lib/python3.8/site-packages/rasterio/__init__.py:221: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.\n s = DatasetReader(path, driver=driver, sharing=sharing, **kwargs)\n/opt/conda/lib/python3.8/site-packages/rioxarray/_io.py:678: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.\n warnings.warn(str(rio_warning.message), type(rio_warning.message))\n/opt/conda/lib/python3.8/site-packages/rasterio/__init__.py:221: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.\n s = DatasetReader(path, driver=driver, sharing=sharing, **kwargs)\n/opt/conda/lib/python3.8/site-packages/rioxarray/_io.py:678: NotGeoreferencedWarning: Dataset has no geotransform set. The identity matrix may be returned.\n warnings.warn(str(rio_warning.message), type(rio_warning.message))\n"
],
[
"lccs = lcc[0].lccs_class",
"_____no_output_____"
],
[
"extent.total_bounds",
"_____no_output_____"
],
[
"lccs_gb = lccs.sel(x=slice(-9, 2), y=slice(61, 49))\nlccs_gb = lccs_gb.rio.set_crs(4326)",
"_____no_output_____"
],
[
"lccs_osgb = lccs_gb.rio.reproject(pyproj.CRS(27700).to_wkt())",
"_____no_output_____"
],
[
"lccs_osgb.rio.to_raster(\"../../urbangrammar_samba/functional_data/land_use/lcc/lccs_osgb.tif\")",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd5503ae1cb307207c4f9de09a74c118e65eb09
| 8,256 |
ipynb
|
Jupyter Notebook
|
AdventOfCode 2019/AOC.3.ipynb
|
BhasherBEL/ProgrammingChallenges
|
e697c7f7e3d8177b9ee615918f3c78b645b927d0
|
[
"MIT"
] | null | null | null |
AdventOfCode 2019/AOC.3.ipynb
|
BhasherBEL/ProgrammingChallenges
|
e697c7f7e3d8177b9ee615918f3c78b645b927d0
|
[
"MIT"
] | 1 |
2020-12-09T12:00:56.000Z
|
2020-12-09T12:00:56.000Z
|
AdventOfCode 2019/AOC.3.ipynb
|
BhasherBEL/ProgrammingChallenges
|
e697c7f7e3d8177b9ee615918f3c78b645b927d0
|
[
"MIT"
] | 1 |
2020-12-09T11:38:49.000Z
|
2020-12-09T11:38:49.000Z
| 30.131387 | 1,486 | 0.580184 |
[
[
[
"import sys\nimport os\nsys.path.append(os.path.abspath(\"../\"))\nsys.path.append(os.path.abspath(\"../AdventOfCode 2020/\"))\nfrom utils import *\nfrom aoc import *\nfrom personal import SESSION\nfrom datetime import datetime\nimport numpy as np",
"_____no_output_____"
],
[
"aoc = AOC(session=SESSION)",
"_____no_output_____"
],
[
"aoc.verify_session()",
"_____no_output_____"
],
[
"st = datetime.now()",
"_____no_output_____"
],
[
"data = aoc.get_file(year=2019, day=3).analyse().head().data",
"Local file found.\n0 empty line(s) found. Analyse as monline data.\n===== HEAD (5) =====\nR998,U367,R735,U926,R23,U457,R262,D473,L353,U242,L930,U895,R321,U683,L333,U623,R105,D527,R437,D473,L100,D251,L958,U384,R655,U543,L704,D759,R529,D176,R835,U797,R453,D650,L801,U437,L468,D841,R928,D747,L803,U677,R942,D851,R265,D684,L206,U763,L566,U774,L517,U337,L86,D585,R212,U656,L799,D953,L24,U388,L465,U656,L467,U649,R658,U519,L966,D290,L979,D819,R208,D907,R941,D458,L882,U408,R539,D939,R557,D771,L448,U460,L586,U148,R678,U360,R715,U312,L12,D746,L958,U216,R275,D278,L368,U663,L60,D543,L605,D991,L369,D599,R464,D387,L835,D876,L810,U377,L521,U113,L803,U680,L732,D449,R891,D558,L25,U249,L264,U643,L544,U504,R876,U403,R950,U19,L224,D287,R28,U914,R906,U970,R335,U295,R841,D810,R891,D596,R451,D79,R924,U823,L724,U968,R342,D349,R656,U373,R864,U374,L401,D102,L730,D886,R268,D188,R621,U258,L788,U408,L199,D422,R101,U368,L636,U543,R7,U722,L533,U242,L340,D195,R158,D291,L84,U936,L570,D937,L321,U947,L707,U32,L56,U650,L427,U490,L472,U258,R694,U87,L887,U575,R826,D398,R602,U794,R855,U225,R435,U591,L58,U281,L834,D400,R89,D201,L328,U278,L494,D70,L770,D182,L251,D44,R753,U431,R573,D71,R809,U983,L159,U26,R540,U516,R5,D23,L603,U65,L260,D187,R973,U877,R110,U49,L502,D68,R32,U153,R495,D315,R720,D439,R264,D603,R717,U586,R732,D111,R997,U578,L243,U256,R147,D425,L141,U758,R451,U779,R964,D219,L151,D789,L496,D484,R627,D431,R433,D761,R355,U975,L983,U364,L200,U578,L488,U668,L48,D774,R438,D456,L819,D927,R831,D598,L437,U979,R686,U930,L454,D553,L77,D955,L98,U201,L724,U211,R501,U492,L495,U732,L511\nL998,U949,R912,D186,R359,D694,L878,U542,L446,D118,L927,U175,R434,U473,R147,D54,R896,U890,R300,D537,R254,D322,R758,D690,R231,U269,R288,U968,R638,U192,L732,D355,R879,U451,R336,D872,L141,D842,L126,U584,L973,D940,R890,D75,L104,U340,L821,D590,R577,U859,L948,D199,L872,D751,L368,U506,L308,U827,R181,U94,R670,U901,R739,D48,L985,D801,R722,D597,R654,D606,R183,U646,R939,U677,R32,U936,L541,D934,R316,U354,L415,D930,R572,U571,R147,D609,L534,D406,R872,D527,L816,D960,R652,D429,L402,D858,R374,D930,L81,U106,R977,U251,R917,U966,R353,U732,L613,U280,L713,D937,R481,U52,R746,U203,L500,D557,L209,U249,R89,D58,L149,U872,R331,D460,R343,D423,R392,D160,L876,U981,L399,D642,R525,U515,L537,U113,R886,D516,L301,D680,L236,U399,R460,D869,L942,D280,R669,U476,R683,D97,R199,D444,R137,D489,L704,D120,R753,D100,L737,U375,L495,D325,R48,D269,R575,U895,L184,D10,L502,D610,R618,D744,R585,U861,R695,D775,L942,U64,L819,U161,L332,U513,L461,D366,R273,D493,L197,D97,L6,U63,L564,U59,L699,U30,L68,U861,R35,U564,R540,U371,L115,D595,L412,D781,L185,D41,R207,D264,R999,D799,R421,D117,R377,D571,R268,D947,R77,D2,R712,D600,L516,U389,L868,D762,L996,U205,L178,D339,L844,D629,R67,D732,R109,D858,R630,U470,L121,D542,L751,U353,L61,U770,R952,U703,R264,D537,L569,U55,L795,U389,R836,U166,R585,U275,L734,U966,L130,D357,L260,U719,L647,D606,R547,U575,R791,U686,L597,D486,L774,U386,L163,U912,L234,D238,L948,U279,R789,U300,R117,D28,L833,U835,L340,U693,R343,D573,R882,D241,L731,U812,R600,D663,R902,U402,R831,D802,L577,U920,L947,D538,L192\n====================\n"
]
],
[
[
"## First part",
"_____no_output_____"
]
],
[
[
"def gen_path(instructions):\n path = [np.array([0, 0])]\n for instruction in instructions:\n if instruction[0] == 'R':\n moving = np.array([1, 0])\n elif instruction[0] == 'L':\n moving = np.array([-1, 0])\n elif instruction[0] == 'U':\n moving = np.array([0, 1])\n else:\n moving = np.array([0, -1])\n \n for i in range(int(instruction[1:])):\n path.append(path[-1]+moving)\n \n return path",
"_____no_output_____"
],
[
"p1 = set([tuple(el) for el in gen_path(data[0].split(','))])",
"_____no_output_____"
],
[
"p2 =set([tuple(el) for el in gen_path(data[1].split(','))])",
"_____no_output_____"
],
[
"inter = p1 & p2",
"_____no_output_____"
],
[
"sorted([sum(map(abs, inter)) for inter in inter])[:5]",
"_____no_output_____"
],
[
"e1 = datetime.now()",
"_____no_output_____"
]
],
[
[
"## Second part",
"_____no_output_____"
]
],
[
[
"p1 = [tuple(el) for el in gen_path(data[0].split(','))]",
"_____no_output_____"
],
[
"p2 = [tuple(el) for el in gen_path(data[1].split(','))]",
"_____no_output_____"
],
[
"vals = []\nfor cross in inter:\n vals.append(p1.index(cross) + p2.index(cross))",
"_____no_output_____"
],
[
"sorted(vals)[:5]",
"_____no_output_____"
],
[
"e2 = datetime.now()",
"_____no_output_____"
],
[
"print(f'Première partie: {e1-st!s}')\nprint(f'Seconde partie: {e2-e1!s}')",
"Première partie: 0:12:14.935654\nSeconde partie: 0:05:09.666545\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd55e3dbb86551beca5778d99a84539d8d0ccbe
| 253,551 |
ipynb
|
Jupyter Notebook
|
docs/source/notebooks/GLM-negative-binomial-regression.ipynb
|
JvParidon/pymc3
|
f60dc1db74df3c54d707761e9dc054a7fdf0435c
|
[
"Apache-2.0"
] | 2 |
2020-05-29T07:10:45.000Z
|
2021-04-07T06:43:52.000Z
|
docs/source/notebooks/GLM-negative-binomial-regression.ipynb
|
nd1511/pymc3
|
4e33b323c35ccd0311b37686c12b56d0b4e8a957
|
[
"Apache-2.0"
] | 2 |
2017-03-02T05:56:13.000Z
|
2019-12-06T19:15:42.000Z
|
docs/source/notebooks/GLM-negative-binomial-regression.ipynb
|
nd1511/pymc3
|
4e33b323c35ccd0311b37686c12b56d0b4e8a957
|
[
"Apache-2.0"
] | 1 |
2019-01-02T09:02:18.000Z
|
2019-01-02T09:02:18.000Z
| 378.434328 | 210,244 | 0.927289 |
[
[
[
"# GLM: Negative Binomial Regression",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport pymc3 as pm\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-darkgrid')\nimport seaborn as sns\nimport re\nprint('Running on PyMC3 v{}'.format(pm.__version__))",
"Running on PyMC3 v3.4.1\n"
]
],
[
[
"This notebook demos negative binomial regression using the `glm` submodule. It closely follows the GLM Poisson regression example by [Jonathan Sedar](https://github.com/jonsedar) (which is in turn inspired by [a project by Ian Osvald](http://ianozsvald.com/2016/05/07/statistically-solving-sneezes-and-sniffles-a-work-in-progress-report-at-pydatalondon-2016/)) except the data here is negative binomially distributed instead of Poisson distributed.\n\nNegative binomial regression is used to model count data for which the variance is higher than the mean. The [negative binomial distribution](https://en.wikipedia.org/wiki/Negative_binomial_distribution) can be thought of as a Poisson distribution whose rate parameter is gamma distributed, so that rate parameter can be adjusted to account for the increased variance.",
"_____no_output_____"
],
[
"### Convenience Functions\n\nTaken from the Poisson regression example.",
"_____no_output_____"
]
],
[
[
"def plot_traces(trcs, varnames=None):\n '''Plot traces with overlaid means and values'''\n\n nrows = len(trcs.varnames)\n if varnames is not None:\n nrows = len(varnames)\n\n ax = pm.traceplot(trcs, varnames=varnames, figsize=(12,nrows*1.4),\n lines={k: v['mean'] for k, v in\n pm.summary(trcs,varnames=varnames).iterrows()})\n\n for i, mn in enumerate(pm.summary(trcs, varnames=varnames)['mean']):\n ax[i,0].annotate('{:.2f}'.format(mn), xy=(mn,0), xycoords='data',\n xytext=(5,10), textcoords='offset points', rotation=90,\n va='bottom', fontsize='large', color='#AA0022')\n \ndef strip_derived_rvs(rvs):\n '''Remove PyMC3-generated RVs from a list'''\n\n ret_rvs = []\n for rv in rvs:\n if not (re.search('_log',rv.name) or re.search('_interval',rv.name)):\n ret_rvs.append(rv)\n return ret_rvs",
"_____no_output_____"
]
],
[
[
"### Generate Data\n\nAs in the Poisson regression example, we assume that sneezing occurs at some baseline rate, and that consuming alcohol, not taking antihistamines, or doing both, increase its frequency.\n\n#### Poisson Data\n\nFirst, let's look at some Poisson distributed data from the Poisson regression example.",
"_____no_output_____"
]
],
[
[
"np.random.seed(123)",
"_____no_output_____"
],
[
"# Mean Poisson values\ntheta_noalcohol_meds = 1 # no alcohol, took an antihist\ntheta_alcohol_meds = 3 # alcohol, took an antihist\ntheta_noalcohol_nomeds = 6 # no alcohol, no antihist\ntheta_alcohol_nomeds = 36 # alcohol, no antihist\n\n# Create samples\nq = 1000\ndf_pois = pd.DataFrame({\n 'nsneeze': np.concatenate((np.random.poisson(theta_noalcohol_meds, q),\n np.random.poisson(theta_alcohol_meds, q),\n np.random.poisson(theta_noalcohol_nomeds, q), \n np.random.poisson(theta_alcohol_nomeds, q))),\n 'alcohol': np.concatenate((np.repeat(False, q),\n np.repeat(True, q),\n np.repeat(False, q),\n np.repeat(True, q))),\n 'nomeds': np.concatenate((np.repeat(False, q),\n np.repeat(False, q),\n np.repeat(True, q),\n np.repeat(True, q)))})",
"_____no_output_____"
],
[
"df_pois.groupby(['nomeds', 'alcohol'])['nsneeze'].agg(['mean', 'var'])",
"_____no_output_____"
]
],
[
[
"Since the mean and variance of a Poisson distributed random variable are equal, the sample means and variances are very close.\n\n#### Negative Binomial Data\n\nNow, suppose every subject in the dataset had the flu, increasing the variance of their sneezing (and causing an unfortunate few to sneeze over 70 times a day). If the mean number of sneezes stays the same but variance increases, the data might follow a negative binomial distribution.",
"_____no_output_____"
]
],
[
[
"# Gamma shape parameter\nalpha = 10\n\ndef get_nb_vals(mu, alpha, size):\n \"\"\"Generate negative binomially distributed samples by\n drawing a sample from a gamma distribution with mean `mu` and\n shape parameter `alpha', then drawing from a Poisson\n distribution whose rate parameter is given by the sampled\n gamma variable.\n\n \"\"\"\n\n g = stats.gamma.rvs(alpha, scale=mu / alpha, size=size)\n return stats.poisson.rvs(g)\n\n# Create samples\nn = 1000\ndf = pd.DataFrame({\n 'nsneeze': np.concatenate((get_nb_vals(theta_noalcohol_meds, alpha, n),\n get_nb_vals(theta_alcohol_meds, alpha, n),\n get_nb_vals(theta_noalcohol_nomeds, alpha, n),\n get_nb_vals(theta_alcohol_nomeds, alpha, n))),\n 'alcohol': np.concatenate((np.repeat(False, n),\n np.repeat(True, n),\n np.repeat(False, n),\n np.repeat(True, n))),\n 'nomeds': np.concatenate((np.repeat(False, n),\n np.repeat(False, n),\n np.repeat(True, n),\n np.repeat(True, n)))})",
"_____no_output_____"
],
[
"df.groupby(['nomeds', 'alcohol'])['nsneeze'].agg(['mean', 'var'])",
"_____no_output_____"
]
],
[
[
"As in the Poisson regression example, we see that drinking alcohol and/or not taking antihistamines increase the sneezing rate to varying degrees. Unlike in that example, for each combination of `alcohol` and `nomeds`, the variance of `nsneeze` is higher than the mean. This suggests that a Poisson distrubution would be a poor fit for the data since the mean and variance of a Poisson distribution are equal.",
"_____no_output_____"
],
[
"### Visualize the Data",
"_____no_output_____"
]
],
[
[
"g = sns.factorplot(x='nsneeze', row='nomeds', col='alcohol', data=df, kind='count', aspect=1.5)\n\n# Make x-axis ticklabels less crowded\nax = g.axes[1, 0]\nlabels = range(len(ax.get_xticklabels(which='both')))\nax.set_xticks(labels[::5])\nax.set_xticklabels(labels[::5]);",
"_____no_output_____"
]
],
[
[
"## Negative Binomial Regression",
"_____no_output_____"
],
[
"### Create GLM Model",
"_____no_output_____"
]
],
[
[
"fml = 'nsneeze ~ alcohol + nomeds + alcohol:nomeds'\n\nwith pm.Model() as model:\n pm.glm.GLM.from_formula(formula=fml, data=df, family=pm.glm.families.NegativeBinomial())\n \n # Old initialization\n # start = pm.find_MAP(fmin=optimize.fmin_powell)\n # C = pm.approx_hessian(start)\n # trace = pm.sample(4000, step=pm.NUTS(scaling=C))\n \n trace = pm.sample(1000, tune=2000, cores=2)",
"Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nMultiprocess sampling (2 chains in 2 jobs)\nNUTS: [alpha, mu, alcohol[T.True]:nomeds[T.True], nomeds[T.True], alcohol[T.True], Intercept]\nSampling 2 chains: 100%|██████████| 6000/6000 [03:15<00:00, 30.72draws/s]\n"
]
],
[
[
"### View Results",
"_____no_output_____"
]
],
[
[
"rvs = [rv.name for rv in strip_derived_rvs(model.unobserved_RVs)]\nplot_traces(trace, varnames=rvs);",
"_____no_output_____"
],
[
"# Transform coefficients to recover parameter values\nnp.exp(pm.summary(trace, varnames=rvs)[['mean','hpd_2.5','hpd_97.5']])",
"_____no_output_____"
]
],
[
[
"The mean values are close to the values we specified when generating the data:\n- The base rate is a constant 1.\n- Drinking alcohol triples the base rate.\n- Not taking antihistamines increases the base rate by 6 times.\n- Drinking alcohol and not taking antihistamines doubles the rate that would be expected if their rates were independent. If they were independent, then doing both would increase the base rate by 3\\*6=18 times, but instead the base rate is increased by 3\\*6\\*2=16 times.\n\nFinally, even though the sample for `mu` is highly skewed, its median value is close to the sample mean, and the mean of `alpha` is also quite close to its actual value of 10.",
"_____no_output_____"
]
],
[
[
"np.percentile(trace['mu'], [25,50,75])",
"_____no_output_____"
],
[
"df.nsneeze.mean()",
"_____no_output_____"
],
[
"trace['alpha'].mean()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbd561fc04801a666fb57133ef32140b1146f514
| 20,965 |
ipynb
|
Jupyter Notebook
|
qiskit_advocates/meetups/11_04_19-Hassi_Norlen-McLean/exercise_2_multiple_qubits_and_entanglement.ipynb
|
ordmoj/qiskit-community-tutorials
|
da70783eef36785326c07579e4c8906eda1cca49
|
[
"Apache-2.0"
] | 3 |
2020-09-12T01:50:58.000Z
|
2021-05-09T20:52:19.000Z
|
qiskit_advocates/meetups/11_04_19-Hassi_Norlen-McLean/exercise_2_multiple_qubits_and_entanglement.ipynb
|
ordmoj/qiskit-community-tutorials
|
da70783eef36785326c07579e4c8906eda1cca49
|
[
"Apache-2.0"
] | null | null | null |
qiskit_advocates/meetups/11_04_19-Hassi_Norlen-McLean/exercise_2_multiple_qubits_and_entanglement.ipynb
|
ordmoj/qiskit-community-tutorials
|
da70783eef36785326c07579e4c8906eda1cca49
|
[
"Apache-2.0"
] | 1 |
2020-09-12T01:51:12.000Z
|
2020-09-12T01:51:12.000Z
| 37.30427 | 4,531 | 0.677844 |
[
[
[
"# Multi-qubit quantum circuit\nIn this exercise we creates a two qubit circuit, with two qubits in superposition, and then measures the individual qubits, resulting in two coin toss results with the following possible outcomes with equal probability: $|00\\rangle$, $|01\\rangle$, $|10\\rangle$, and $|11\\rangle$. This is like tossing two coins.\n",
"_____no_output_____"
],
[
"Import the required libraries, including the IBM Q library for working with IBM Q hardware.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom qiskit import QuantumCircuit, execute, Aer\nfrom qiskit.tools.monitor import job_monitor\n\n# Import visualization\nfrom qiskit.visualization import plot_histogram, plot_bloch_multivector, iplot_bloch_multivector, plot_state_qsphere, iplot_state_qsphere\n\n# Add the state vector calculation function\ndef get_psi(circuit, vis): \n global psi\n backend = Aer.get_backend('statevector_simulator') \n psi = execute(circuit, backend).result().get_statevector(circuit)\n if vis==\"IQ\":\n display(iplot_state_qsphere(psi))\n elif vis==\"Q\":\n display(plot_state_qsphere(psi))\n elif vis==\"M\":\n print(psi)\n elif vis==\"B\":\n display(plot_bloch_multivector(psi))\n else: # vis=\"IB\"\n display(iplot_bloch_multivector(psi))\n \n vis=\"\"",
"_____no_output_____"
]
],
[
[
"How many qubits do we want to use. The notebook let's you set up multi-qubit circuits of various sizes. Keep in mind that the biggest publicly available IBM quantum computer is 14 qubits in size. ",
"_____no_output_____"
]
],
[
[
"#n_qubits=int(input(\"Enter number of qubits:\"))\nn_qubits=2",
"_____no_output_____"
]
],
[
[
"Create quantum circuit that includes the quantum register and the classic register. Then add a Hadamard (super position) gate to all the qubits. Add measurement gates.",
"_____no_output_____"
]
],
[
[
"qc1 = QuantumCircuit(n_qubits,n_qubits)\nqc_measure = QuantumCircuit(n_qubits,n_qubits)\nfor qubit in range (0,n_qubits):\n qc1.h(qubit) #A Hadamard gate that creates a superposition\nfor qubit in range (0,n_qubits):\n qc_measure.measure(qubit,qubit)\ndisplay(qc1.draw(output=\"mpl\"))\n",
"_____no_output_____"
]
],
[
[
"Now that we have more than one qubit it is starting to become a bit difficult to visualize the outcomes when running the circuit. To alleviate this we can instead have the get_psi return the statevector itself by by calling it with the vis parameter set to `\"M\"`. We can also have it display a Qiskit-unique visualization called a Q Sphere by passing the parameter `\"Q\"` or `\"q\"`. Big Q returns an interactive Q-sphere, and little q a static one.",
"_____no_output_____"
]
],
[
[
"get_psi(qc1,\"M\")\nprint (abs(np.square(psi))) \nget_psi(qc1,\"B\")",
"_____no_output_____"
]
],
[
[
"Now we see the statevector for multiple qubits, and can calculate the probabilities for the different outcomes by squaring the complex parameters in the vector.\n\nThe Q Sphere visualization provides the same informaton in a visual form, with |0..0> at the north pole, |1..1> at the bottom, and other combinations on latitude circles. In the dynamicc version, you can hover over the tips of the vectors to see the state, probability, and phase data. In the static version, the size of the vector tip represents the relative probability of getting that specific result, and the color represents the phase angle for that specific output. More on that later!",
"_____no_output_____"
],
[
"Now add your circuit with the measurement circuit and run a 1,000 shots to get statistics on the possible outcomes.\n ",
"_____no_output_____"
]
],
[
[
"backend = Aer.get_backend('qasm_simulator')\n\nqc_final=qc1+qc_measure\n\njob = execute(qc_final, backend, shots=1000)\ncounts1 = job.result().get_counts(qc_final)\nprint(counts1)\nplot_histogram(counts1)",
"_____no_output_____"
]
],
[
[
"As you might expect, with two independednt qubits ea h in a superposition, the resulting outcomes should be spread evenly accross th epossible outcomes, all the combinations of 0 and 1.\n\n**Time for you to do some work!** To get an understanding of the probable outcomes and how these are displayed on the interactive (or static) Q Sphere, change the `n_qubits=2` value in the cell above, and run the cells again for a different number of qubits. \n\nWhen you are done, set the value back to 2, and continue on.\n",
"_____no_output_____"
]
],
[
[
"n_qubits=2",
"_____no_output_____"
]
],
[
[
"# Entangled-qubit quantum circuit - The Bell state\n\nNow we are going to do something different. We will entangle the qubits.\n\nCreate quantum circuit that includes the quantum register and the classic register. Then add a Hadamard (super position) gate to the first qubit. Then add a controlled-NOT gate (cx) between the first and second qubit, entangling them. Add measurement gates. \n\nWe then take a look at using the CX (Controlled-NOT) gate to entangle the two qubits in a so called Bell state. This surprisingly results in the following possible outcomes with equal probability: $|00\\rangle$ and $|11\\rangle$. Two entangled qubits do not at all behave like two tossed coins.\n\nWe then run the circuit a large number of times to see what the statistical behavior of the qubits are.\nFinally, we run the circuit on real IBM Q hardware to see how real physical qubits behave.\n\nIn this exercise we introduce the CX gate, which creates entanglement between two qubits, by flipping the controlled qubit (q_1) if the controlling qubit (q_0) is 1.\n\n\n",
"_____no_output_____"
]
],
[
[
"qc2 = QuantumCircuit(n_qubits,n_qubits)\nqc2_measure = QuantumCircuit(n_qubits, n_qubits)\nfor qubit in range (0,n_qubits):\n qc2_measure.measure(qubit,qubit)\n\nqc2.h(0) # A Hadamard gate that puts the first qubit in superposition\ndisplay(qc2.draw(output=\"mpl\"))\nget_psi(qc2,\"M\")\nget_psi(qc2,\"B\")",
"_____no_output_____"
],
[
"for qubit in range (1,n_qubits):\n qc2.cx(0,qubit) #A controlled NOT gate that entangles the qubits.\n\ndisplay(qc2.draw(output=\"mpl\"))\nget_psi(qc2, \"B\")",
"_____no_output_____"
]
],
[
[
"Now we notice something peculiar; after we add the CX gate, entangling the qubits the Bloch spheres display nonsense. Why is that? It turns out that once your qubits are entangled they can no longer be described individually, but only as a combined object. Let's take a look at the state vector and Q sphere.",
"_____no_output_____"
]
],
[
[
"get_psi(qc2,\"M\")\n\nprint (abs(np.square(psi)))\n\nget_psi(qc2,\"Q\")",
"_____no_output_____"
]
],
[
[
"Set the backend to a local simulator. Then create a quantum job for the circuit, the selected backend, that runs just one shot to simulate a coin toss with two simultaneously tossed coins, then run the job. Display the result; either 0 for up (base) or 1 for down (excited) for each qubit. Display the result as a histogram. Either |00> or |11> with 100% probability.",
"_____no_output_____"
]
],
[
[
"backend = Aer.get_backend('qasm_simulator')\n\nqc2_final=qc2+qc2_measure\n\njob = execute(qc2_final, backend, shots=1)\ncounts2 = job.result().get_counts(qc2_final)\nprint(counts2)\nplot_histogram(counts2)",
"_____no_output_____"
]
],
[
[
"Note how the qubits completely agree. They are entangled.\n\n**Do some work..** Run the cell above a few times to verify that you only get the results 00 or 11.",
"_____no_output_____"
],
[
"Now, lets run quite a few more shots, and display the statistsics for the two results. This time, as we are no longer just talking about two qubits, but the amassed results of thousands of runs on these qubits.",
"_____no_output_____"
]
],
[
[
"job = execute(qc2_final, backend, shots=1000)\nresult = job.result() \ncounts = result.get_counts()\nprint(counts)\nplot_histogram(counts)",
"_____no_output_____"
]
],
[
[
"And look at that, we are back at our coin toss results, fifty-fifty. Every time one of the coins comes up heads (|0>) the other one follows suit. Tossing one coin we immediately know what the other one will come up as; the coins (qubits) are entangled.",
"_____no_output_____"
],
[
"# Run your entangled circuit on an IBM quantum computer\n**Important:** With the simulator we get perfect results, only |00> or |11>. On a real NISQ (Noisy Intermediate Scale Quantum computer) we do not expect perfect results like this. Let's run the Bell state once more, but on an actual IBM Q quantum computer.",
"_____no_output_____"
],
[
"**Time for some work!** Before you can run your program on IBM Q you must load your API key. If you are running this notebook in an IBM Qx environment, your API key is already stored in the system, but if you are running on your own machine you [must first store the key](https://qiskit.org/documentation/install.html#access-ibm-q-systems).",
"_____no_output_____"
]
],
[
[
"#Save and store API key locally.\nfrom qiskit import IBMQ\n#IBMQ.save_account('MY_API_TOKEN') <- Uncomment this line if you need to store your API key\n\n#Load account information \nIBMQ.load_account()\nprovider = IBMQ.get_provider()",
"_____no_output_____"
]
],
[
[
"Grab the least busy IBM Q backend.",
"_____no_output_____"
]
],
[
[
"from qiskit.providers.ibmq import least_busy\nbackend = least_busy(provider.backends(operational=True, simulator=False))\n#backend = provider.get_backend('ibmqx2')\nprint(\"Selected backend:\",backend.status().backend_name)\nprint(\"Number of qubits(n_qubits):\", backend.configuration().n_qubits)\nprint(\"Pending jobs:\", backend.status().pending_jobs)",
"_____no_output_____"
]
],
[
[
"Lets run a large number of shots, and display the statistsics for the two results: $|00\\rangle$ and $|11\\rangle$ on the real hardware. Monitor the job and display our place in the queue.",
"_____no_output_____"
]
],
[
[
"if n_qubits > backend.configuration().n_qubits:\n print(\"Your circuit contains too many qubits (\",n_qubits,\"). Start over!\")\nelse:\n job = execute(qc2_final, backend, shots=1000)\n job_monitor(job)",
"_____no_output_____"
]
],
[
[
"Get the results, and display in a histogram. Notice how we no longer just get the perfect entangled results, but also a few results that include non-entangled qubit results. At this stage, quantum computers are not perfect calculating machines, but pretty noisy. ",
"_____no_output_____"
]
],
[
[
"result = job.result()\ncounts = result.get_counts(qc2_final)\nprint(counts)\nplot_histogram(counts)",
"_____no_output_____"
]
],
[
[
"That was the simple readout. Let's take a look at the whole returned results:",
"_____no_output_____"
]
],
[
[
"print(result)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd58ba5137953c17f52e6007487ef9f947f505c
| 108,534 |
ipynb
|
Jupyter Notebook
|
archive/1_twitter_mining_func_scatter.ipynb
|
jhustles/project_1_team_zeta
|
bf0cf0ba973c1a20b18064685fe33fb86b51187b
|
[
"MIT"
] | 1 |
2020-04-02T17:31:22.000Z
|
2020-04-02T17:31:22.000Z
|
archive/1_twitter_mining_func_scatter.ipynb
|
jhustles/project1_twitter_api_google_apple_app_stores
|
bf0cf0ba973c1a20b18064685fe33fb86b51187b
|
[
"MIT"
] | null | null | null |
archive/1_twitter_mining_func_scatter.ipynb
|
jhustles/project1_twitter_api_google_apple_app_stores
|
bf0cf0ba973c1a20b18064685fe33fb86b51187b
|
[
"MIT"
] | null | null | null | 34.620096 | 245 | 0.618912 |
[
[
[
"# Twitter Mining Function & Scatter Plots\n---------------------------------------------------------------\n",
"_____no_output_____"
]
],
[
[
"# Import Dependencies\n%matplotlib notebook\nimport os\nimport csv\nimport json\nimport requests\nfrom pprint import pprint\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom twython import Twython\nimport simplejson\nimport sys\nimport string\nimport glob\nfrom pathlib import Path",
"_____no_output_____"
],
[
"# Import Twitter 'Keys' - MUST SET UP YOUR OWN 'config_twt.py' file\n# You will need to create your own \"config_twt.py\" file using each of the Twitter authentication codes\n# they provide you when you sign up for a developer account with your Twitter handle\nfrom config_twt import (app_key_twt, app_secret_twt, oauth_token_twt, oauth_token_secret_twt)",
"_____no_output_____"
],
[
"# Set Up Consumer Keys And Secret with Twitter Keys\nAPP_KEY = app_key_twt\nAPP_SECRET = app_secret_twt\n\n# Set up OAUTH Token and Secret With Twitter Keys\n\nOAUTH_TOKEN = oauth_token_twt\nOAUTH_TOKEN_SECRET = oauth_token_secret_twt\n\n# Load Keys In To a Twython Function And Call It \"twitter\"\ntwitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n\n# Setup Batch Counter For Phase 2\nbatch_counter = 0",
"_____no_output_____"
]
],
[
[
"___________________________\n## Twitter Mining Function '(TMF)'\n___________________________\n\n### INSTRUCTIONS:\n\n\nThis will Twitter Query Function will:\n- Perform searches for hastags (#)\n- Search for \"@twitter_user_acct\"\n- Provide mixed results of popular and most recent tweets from the last 7 days\n- 'remaining' 'search/tweets (allowance of 180) rate limit status' regenerates in 15 minutes after depletion\n\n### Final outputs are aggegrated queries in both:\n\n- Pandas DataFrame of queried tweets\n- CSV files saved in the same folder as this Jupyter Notebook\n\n\n### Phase 1 - Run Query and Store The Dictionary Into a List\n\n\n- Step 1) Run the 'Twitter Mining Function' cell below to begin program\n Note:\n - Limits have not been fully tested due to time constraint\n - Search up to 180 queries where and each query yields up to 100 tweets max\n - Running the TLC to see how many you have left after every csv outputs.\n\n- Step 2) When prompted, input in EITHER: #hashtag or @Twitter_user_account\n Examples: \"#thuglife\" or \"@beyonce\"\n\n- Step 3) TMF will query Twitter and store the tweets_data, a list called \"all_data\"\n\n- Step 4) Upon query search completion, it will prompt: \"Perform another search query:' ('y'/'n') \"\n - Input 'y' to query, and the program will append the results\n - Tip: Keep count of how many 'search tweets' you have, it should deduct 1 from 'remaining',\n which can produce up to 100 tweets of data\n \n- Step 5) End program by entering 'n' when prompted for 'search again'\n Output: printed list of all appended query data\n\n\n### Phase 2 - Converting to Pandas DataFrame and Produce a CSV Output\n\n- Step 6) Loop Through Queried Data \n\n- Step 7) Convert to Pandas DataFrame\n\n- Step 8) Convert from DataFrame to CSV\n\n### Addtional Considerations:\n\n- Current set up uses standard search api keys, not premium\n- TMF returns potentially 100 tweets at a time, and pulls from the last 7 days in random order\n- More than likely will have to run multiple searches and track line items count\n in each of the csv files output that will be created in the same folder\n",
"_____no_output_____"
],
[
"### Tweet Limit Counter (TLC)\n - Run cell to see how many search queries you have available\n - Your 'remaining' search tweets regenerates over 15 minutes.",
"_____no_output_____"
]
],
[
[
"# TLC - Run to Query Current Rate Limit on API Keys \ntwitter.get_application_rate_limit_status()['resources']['search']",
"_____no_output_____"
],
[
"#Twitter Mining Function (TMF)\n#RUN THIS CELL TO BEGIN PROGRAM!\nprint('-'*80)\nprint(\"TWITTER QUERY FUNCTION - BETA\")\nprint('-'*80)\nprint(\"INPUT PARAMETERS:\")\nprint(\"- @Twitter_handle e.g. @clashofclans\")\nprint(\"- Hashtags (#) e.g. #THUGLIFE\")\nprint(\"NOTE: SCROLL DOWN AFTER EACH QUERY FOR ENTER INPUT\")\nprint('-'*80)\n\ndef twitter_search(app_search):\n # Store the following Twython function and parameters into variable 't'\n t = Twython(app_key=APP_KEY,\n app_secret=APP_SECRET,\n oauth_token=OAUTH_TOKEN,\n oauth_token_secret=OAUTH_TOKEN_SECRET)\n # The Twitter Mining Function we will use to run searches is below\n # and we're asking for it to pull 100 tweets\n search = t.search(q=app_search, count=100)\n tweets = search['statuses']\n # This will be a list of dictionaries of each tweet where the loop below will append to\n all_data = []\n # From the tweets, go into each individual tweet and extract the following into a 'dictionary'\n # and append it to big bucket called 'all_data'\n for tweet in tweets:\n try:\n tweets_data = {\n \"Created At\":tweet['created_at'],\n \"Text (Tweet)\":tweet['text'],\n \"User ID\":tweet['user']['id'],\n \"User Followers Count\":tweet['user']['followers_count'],\n \"Screen Name\":tweet['user']['name'],\n \"ReTweet Count\":tweet['retweet_count'],\n \"Favorite Count\":tweet['favorite_count']}\n all_data.append(tweets_data)\n #print(tweets_data)\n except (KeyError, NameError, TypeError, AttributeError) as err: \n print(f\"{err} Skipping...\")\n #functions need to return something...\n return all_data\n# The On and Off Mechanisms:\nsearch_again = 'y'\nfinal_all_data = []\n# initialize the query counter\nquery_counter = 0\nwhile search_again == 'y':\n query_counter += 1\n start_program = str(input('Type the EXACT @twitter_acct or #hashtag to query: '))\n all_data = twitter_search(start_program)\n final_all_data += all_data\n #print(all_data)\n print(f\"Completed Collecting Search Results for {start_program} . Queries Completed: {query_counter} \")\n print('-'*80)\n search_again = input(\"Would you like to run another query? Enter 'y'. Otherwise, 'n' or another response will end query mode. \")\n print('-'*80)\n# When you exit the program, set the query counter back to zero\nquery_counter = 0\nprint()\nprint(f\"Phase 1 of 2 Queries Completed . Proceed to Phase 2 - Convert Collection to DF and CSV formats .\")\n#print(\"final Data\", final_all_data)\n#####################################################################################################\n# TIPS!: # If you're searching for the same hastag or twitter_handle,\n # consider copying and pasting it (e.g. @fruitninja)",
"_____no_output_____"
],
[
"# Display the total tweets the TMF successfully pulled:\nprint(len(final_all_data))",
"_____no_output_____"
]
],
[
[
"### Tweet Limit Counter (TLC)\n - Run cell to see how many search queries you have available\n - Your 'remaining' search tweets regenerates over 15 minutes.",
"_____no_output_____"
]
],
[
[
"# Run to view current rate limit status\ntwitter.get_application_rate_limit_status()['resources']['search']",
"_____no_output_____"
],
[
"#df = pd.DataFrame(final_all_data[0])\n#df\n\nfinal_all_data",
"_____no_output_____"
]
],
[
[
"### Step 6) Loop through the stored list of queried tweets from final_all_data and stores in designated lists",
"_____no_output_____"
]
],
[
[
"# Loop thru finall_all_data (list of dictionaries) and extract each item and store them into\n# the respective lists\n\n# BUCKETS\ncreated_at = []\ntweet_text = []\nuser_id = []\nuser_followers_count = []\nscreen_name = []\nretweet_count = []\nlikes_count = []\n\n# append tweets data to the buckets for each tweet\n#change to final_all_data\nfor data in final_all_data:\n #print(keys, data[keys])\n \n created_at.append(data[\"Created At\"]),\n tweet_text.append(data['Text (Tweet)']),\n user_id.append(data['User ID']),\n user_followers_count.append(data['User Followers Count']),\n screen_name.append(data['Screen Name']),\n retweet_count.append(data['ReTweet Count']),\n likes_count.append(data['Favorite Count'])\n\n\n#print(created_at, tweet_text, user_id, user_followers_count, screen_name, retweet_count, likes_count)\n\nprint(\"Run complete. Proceed to next cell.\")",
"_____no_output_____"
]
],
[
[
"### Step 7) Convert to Pandas DataFrame",
"_____no_output_____"
]
],
[
[
"# Setup DataFrame and run tweets_data_df\n\ntweets_data_df = pd.DataFrame({\n \"Created At\": created_at,\n \"Screen Name\": screen_name,\n \"User ID\": user_id,\n \"User Follower Count\": user_followers_count,\n \"Likes Counts\": likes_count,\n \"ReTweet Count\": retweet_count,\n \"Tweet Text\" : tweet_text\n})\ntweets_data_df.head()",
"_____no_output_____"
]
],
[
[
"### Step 8) Load into MySQL Database - later added this piece to display ETL potential of this project",
"_____no_output_____"
]
],
[
[
"# This section was added later after I reviewed and wanted to briefly reiterate on it\ntweets_data_df2 = tweets_data_df.copy()\n# Dropped Screen Name and Tweets Text bc would I would need to clean the 'Screen Name' and 'Tweet Text' Columns\ntweets_data_df2 = tweets_data_df2.drop([\"Screen Name\", \"Tweet Text\"], axis=1).sort_values(by=\"User Follower Count\")",
"_____no_output_____"
],
[
"# Import Dependencies 2/2:\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.sql import select\nfrom sqlalchemy_utils import database_exists, create_database, drop_database, has_index\nimport pymysql\n\nrds_connection_string = \"root:[email protected]/\"\n#db_name = input(\"What database would you like to search for?\")\ndb_name = 'twitterAPI_data_2019_db'\n# Setup engine connection string\nengine = create_engine(f'mysql://{rds_connection_string}{db_name}?charset=utf8', echo=True)",
"_____no_output_____"
],
[
"# Created a function incorproating SQL Alchemy to search, create, and or drop a database:\ndef search_create_drop_db(db_name):\n db_exist = database_exists(f'mysql://{rds_connection_string}{db_name}')\n db_url = f'mysql://{rds_connection_string}{db_name}'\n if db_exist == True:\n drop_table_y_or_n = input(f'\"{db_name}\" database already exists in MySQL. Do you want you drop the table? Enter exactly: \"y\" or \"n\". ')\n if drop_table_y_or_n == 'y':\n drop_database(db_url)\n print(f\"Database {db_name} was dropped\")\n create_new_db = input(f\"Do you want to create another database called: {db_name}? \")\n if create_new_db == 'y':\n create_database(db_url)\n return(f\"The database {db_name} was created. Next You will need to create tables for this database. \")\n else:\n return(\"No database was created. Goodbye! \")\n else:\n return(\"The database exists. No action was taken. Goodbye! \")\n else:\n create_database(db_url)\n return(f\"The queried database did not exist, and was created as: {db_name} . \")\nsearch_create_drop_db(db_name)",
"_____no_output_____"
],
[
"tweets_data_df2.to_sql('tweets', con=engine, if_exists='append')",
"_____no_output_____"
]
],
[
[
"### Step 9) Convert DataFrame to CSV File and save on local drive",
"_____no_output_____"
]
],
[
[
"# Save Tweets Data to a CSV File (Run Cell to input filename)\n# Streamline the saving of multiple queries (1 query = up to 100 tweets) into a csv file.\n\n# E.g. input = (#fruit_ninja) will save the file as \"fruit_ninja_batch1.csv\" as the file result\n# Note: first chracter will be slice off so you can just copy and paste\n# the hastag / @twitter_handle from steps above\nbatch_name = str(input(\"Enter in batch name.\"))\n\n# If you restart kernel, batch_counter resets to zero.\nbatch_counter = batch_counter +1\n\n# Check if the #hastag / @twitter_handle folder exists and create the folder if it does not\nPath(f\"./resources/{batch_name[1:]}\").mkdir(parents=True, exist_ok=True)\n\n# Save dataframe of all queries in a csv file to a folder in the resources folder csv using the \ntweets_data_df.to_csv(f\"./resources/{batch_name[1:]}/{batch_name[1:]}_batch{batch_counter}.csv\", encoding='utf-8')\nprint(f\"Output saved in current folder as: {batch_name[1:]}_batch{batch_counter}.csv \")",
"_____no_output_____"
]
],
[
[
"# PHASE 3 - CALCULATIONS USING API DATA\n",
"_____no_output_____"
]
],
[
[
"# This prints out all of the folder titles in \"resources\" folder\npath = './resources/*' # use your path\nresources = glob.glob(path)\n\nall_folders = []\nprint(\"All folders in the 'resources' folder:\")\nprint(\"=\"*40)\nfor foldername in resources:\n str(foldername)\n foldername = foldername[12:]\n all_folders.append(foldername)\n#print(li)\nprint(\"\")\nprint(F\"Total Folders: {len(all_folders)}\")",
"All folders in the 'resources' folder:\n========================================\n\nTotal Folders: 2\n"
],
[
"print(all_folders)",
"['angrybirds', 'bible']\n"
],
[
"all_TopApps_df_list = []\n\nfor foldername in all_folders:\n plug = foldername\n path = f'./resources\\\\{plug}'\n all_files = glob.glob(path + \"/*.csv\")\n counter = 0\n app_dataframes = []\n for filename in all_files:\n counter += 1\n df = pd.read_csv(filename, index_col=None, header=0)\n app_dataframes.append(df)\n output = pd.concat(app_dataframes, axis=0, ignore_index=True)\n all_TopApps_df_list.append(f\"{output}_{counter}\")\n counter = 0\n #fb_frame",
"_____no_output_____"
]
],
[
[
"##### Facebook Calculations\n",
"_____no_output_____"
]
],
[
[
"# Example Template of looping thru csvfiles, and concatenate all of the csv files we collected in each folder\nplug = 'facebook'\npath = f'./resources\\\\{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\n\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nfb_frame = pd.concat(li, axis=0, ignore_index=True)\nfb_frame",
"_____no_output_____"
],
[
"fb_frame.describe()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\nfb_frame.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nfacebook_filtered_df = fb_frame.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nfacebook_filtered_df.describe()",
"_____no_output_____"
],
[
"facebook_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nfacebook_total_tweets = len(facebook_filtered_df['Tweet Text'])\nfacebook_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\nfacebook_avg_followers_ct = facebook_filtered_df['User Follower Count'].mean()\nfacebook_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nfacebook_total_likes = facebook_filtered_df['Likes Counts'].sum()\n#facebook_avg_likes = facebook_filtered_df['Likes Counts'].mean()\nfacebook_total_likes\n#facebook_avg_likes",
"_____no_output_____"
],
[
"# Facebook Retweets Stats:\n#facebook_sum_retweets = facebook_filtered_df['ReTweet Count'].sum()\nfacebook_avg_retweets = facebook_filtered_df['ReTweet Count'].mean()\n#facebook_sum_retweets\nfacebook_avg_retweets",
"_____no_output_____"
]
],
[
[
"#### Instagram Calculations",
"_____no_output_____"
]
],
[
[
"plug = 'instagram'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\n\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\ninstagram_source_df = pd.concat(li, axis=0, ignore_index=True)\ninstagram_source_df",
"_____no_output_____"
],
[
"# Snapshot Statistics\ninstagram_source_df.describe()",
"_____no_output_____"
],
[
"instagram_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\ninstagram_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\ninstagram_filtered_df = instagram_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"instagram_filtered_df",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\ninstagram_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\ninstagram_total_tweets = len(instagram_filtered_df['Tweet Text'])\ninstagram_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\ninstagram_avg_followers_ct = instagram_filtered_df['User Follower Count'].mean()\ninstagram_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\ninstagram_total_likes = instagram_filtered_df['Likes Counts'].sum()\n#instagram_avg_likes = instagram_filtered_df['Likes Counts'].mean()\ninstagram_total_likes\n#instagram_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#instagram_sum_retweets = instagram_filtered_df['ReTweet Count'].sum()\ninstagram_avg_retweets = instagram_filtered_df['ReTweet Count'].mean()\n#instagram_sum_retweets\ninstagram_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Clash of Clans Calculations",
"_____no_output_____"
]
],
[
[
"plug = 'clashofclans'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\n\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\ncoc_source_df = pd.concat(li, axis=0, ignore_index=True)\ncoc_source_df\n\n# Snapshot Statistics\ncoc_source_df.describe()",
"_____no_output_____"
],
[
"coc_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\ncoc_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\ncoc_filtered_df = coc_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"coc_filtered_df.head()",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\ncoc_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\ncoc_total_tweets = len(coc_filtered_df['Tweet Text'])\ncoc_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\ncoc_avg_followers_ct = coc_filtered_df['User Follower Count'].mean()\ncoc_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\ncoc_total_likes = coc_filtered_df['Likes Counts'].sum()\n#coc_avg_likes = coc_filtered_df['Likes Counts'].mean()\ncoc_total_likes\n#coc_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#coc_sum_retweets = coc_filtered_df['ReTweet Count'].sum()\ncoc_avg_retweets = coc_filtered_df['ReTweet Count'].mean()\n#coc_sum_retweets\ncoc_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Temple Run Calculations\n",
"_____no_output_____"
]
],
[
[
"plug = 'templerun'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\ntemplerun_source_df = pd.concat(li, axis=0, ignore_index=True)\ntemplerun_source_df\n\n# Snapshot Statistics\ntemplerun_source_df.describe()",
"_____no_output_____"
],
[
"#templerun_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\ntemplerun_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\ntemplerun_filtered_df = templerun_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"#templerun_filtered_df",
"_____no_output_____"
],
[
"#templerun_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\ntemplerun_total_tweets = len(templerun_filtered_df['Tweet Text'])\ntemplerun_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\ntemplerun_avg_followers_ct = templerun_filtered_df['User Follower Count'].mean()\ntemplerun_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\ntemplerun_total_likes = templerun_filtered_df['Likes Counts'].sum()\n#templerun_avg_likes = templerun_filtered_df['Likes Counts'].mean()\ntemplerun_total_likes\n#instagram_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#templerun_sum_retweets = templerun_filtered_df['ReTweet Count'].sum()\ntemplerun_avg_retweets = templerun_filtered_df['ReTweet Count'].mean()\n#templerun_sum_retweets\ntemplerun_avg_retweets",
"_____no_output_____"
],
[
"templerun_total_tweets\ntemplerun_avg_retweets\ntemplerun_avg_followers_ct\ntemplerun_total_likes",
"_____no_output_____"
]
],
[
[
"### Pandora Calculations",
"_____no_output_____"
]
],
[
[
"plug = 'pandora'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\npandora_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\npandora_source_df.describe()",
"_____no_output_____"
],
[
"#pandora_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\npandora_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\npandora_filtered_df = pandora_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"pandora_filtered_df",
"_____no_output_____"
],
[
"pandora_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\npandora_total_tweets = len(pandora_filtered_df['Tweet Text'])\npandora_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\npandora_avg_followers_ct = pandora_filtered_df['User Follower Count'].mean()\npandora_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\n# use sum of likes.\npandora_total_likes = pandora_filtered_df['Likes Counts'].sum()\n#pandora_avg_likes = pandora_filtered_df['Likes Counts'].mean()\npandora_total_likes\n#pandora_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#pandora_sum_retweets = pandora_filtered_df['ReTweet Count'].sum()\npandora_avg_retweets = pandora_filtered_df['ReTweet Count'].mean()\n#pandora_sum_retweets\npandora_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Pinterest Calculations",
"_____no_output_____"
]
],
[
[
"# Concatenate them\nplug = 'pinterest'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\npinterest_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\npinterest_source_df.describe()",
"_____no_output_____"
],
[
"pinterest_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\npinterest_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\npinterest_filtered_df = pinterest_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"pinterest_filtered_df",
"_____no_output_____"
],
[
"pinterest_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\npinterest_total_tweets = len(pinterest_filtered_df['Tweet Text'])\npinterest_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\npinterest_avg_followers_ct = pinterest_filtered_df['User Follower Count'].mean()\npinterest_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\npinterest_total_likes = pinterest_filtered_df['Likes Counts'].sum()\n#pinterest_avg_likes = pinterest_filtered_df['Likes Counts'].mean()\npinterest_total_likes\n#pinterest_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#pinterest_sum_retweets = pinterest_filtered_df['ReTweet Count'].sum()\npinterest_avg_retweets = pinterest_filtered_df['ReTweet Count'].mean()\n#pinterest_sum_retweets\npinterest_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Bible (You Version) Calculations",
"_____no_output_____"
]
],
[
[
"plug = 'bible'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nbible_source_df = pd.concat(li, axis=0, ignore_index=True)\nbible_source_df\n# Snapshot Statistics\nbible_source_df.describe()",
"_____no_output_____"
],
[
"bible_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\nbible_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nbible_filtered_df = bible_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"bible_filtered_df",
"_____no_output_____"
],
[
"bible_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nbible_total_tweets = len(bible_filtered_df['Tweet Text'])\nbible_total_tweets",
"_____no_output_____"
],
[
"# Calculate Avg Followers - doesn't make sense to sum.\nbible_avg_followers_ct = bible_filtered_df['User Follower Count'].mean()\nbible_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nbible_total_likes = bible_filtered_df['Likes Counts'].sum()\n#bible_avg_likes = bible_filtered_df['Likes Counts'].mean()\nbible_total_likes\n#bible_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#bible_sum_retweets = bible_filtered_df['ReTweet Count'].sum()\nbible_avg_retweets = bible_filtered_df['ReTweet Count'].mean()\n#bible_sum_retweets\nbible_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Candy Crush Saga Calculations",
"_____no_output_____"
]
],
[
[
"plug = 'candycrushsaga'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nCandyCrushSaga_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nCandyCrushSaga_source_df.describe()",
"_____no_output_____"
],
[
"# has duplicates\nCandyCrushSaga_source_df.sort_values(by=['User ID','Created At'], ascending=False)\nCandyCrushSaga_source_df.head()",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nCandyCrushSaga_filtered_df = CandyCrushSaga_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nCandyCrushSaga_filtered_df.describe()",
"_____no_output_____"
],
[
"CandyCrushSaga_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\ncandycrushsaga_total_tweets = len(CandyCrushSaga_filtered_df['Tweet Text'])\ncandycrushsaga_total_tweets",
"_____no_output_____"
],
[
"# Calculate Avg Followers - doesn't make sense to sum.\ncandycrushsaga_avg_followers_ct = CandyCrushSaga_filtered_df['User Follower Count'].mean()\ncandycrushsaga_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\ncandycrushsaga_total_likes = CandyCrushSaga_filtered_df['Likes Counts'].sum()\n#facebook_avg_likes = facebook_filtered_df['Likes Counts'].mean()\ncandycrushsaga_total_likes\n#facebook_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#facebook_sum_retweets = facebook_filtered_df['ReTweet Count'].sum()\ncandycrushsaga_avg_retweets = CandyCrushSaga_filtered_df['ReTweet Count'].mean()\n#facebook_sum_retweets\ncandycrushsaga_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Spotify Music Caculations",
"_____no_output_____"
]
],
[
[
"plug = 'spotify'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nspotify_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nspotify_source_df.describe()\n",
"_____no_output_____"
],
[
"spotify_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\nspotify_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nspotify_filtered_df = spotify_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"spotify_filtered_df",
"_____no_output_____"
],
[
"spotify_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nspotify_total_tweets = len(spotify_filtered_df['Tweet Text'])\nspotify_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\nspotify_avg_followers_ct = spotify_filtered_df['User Follower Count'].mean()\nspotify_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nspotify_total_likes = spotify_filtered_df['Likes Counts'].sum()\n#spotify_avg_likes = spotify_filtered_df['Likes Counts'].mean()\nspotify_total_likes\n#spotify_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#spotify_sum_retweets = spotify_filtered_df['ReTweet Count'].sum()\nspotify_avg_retweets = spotify_filtered_df['ReTweet Count'].mean()\n#spotify_sum_retweets\nspotify_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Angry Birds Calculations\n",
"_____no_output_____"
]
],
[
[
"plug = 'angrybirds'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nangrybirds_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nangrybirds_source_df.describe()",
"_____no_output_____"
],
[
"angrybirds_source_df.head()",
"_____no_output_____"
],
[
"# Sort to set up removal of duplicates\nangrybirds_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nangrybirds_filtered_df = angrybirds_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"angrybirds_filtered_df",
"_____no_output_____"
],
[
"angrybirds_filtered_df.describe()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nangrybirds_total_tweets = len(angrybirds_filtered_df['Tweet Text'])\nangrybirds_total_tweets",
"_____no_output_____"
],
[
"# Calculate angrybirds Avg Followers - doesn't make sense to sum.\nangrybirds_avg_followers_ct = angrybirds_filtered_df['User Follower Count'].mean()\nangrybirds_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nangrybirds_total_likes = angrybirds_filtered_df['Likes Counts'].sum()\n#angrybirds_avg_likes = angrybirds_filtered_df['Likes Counts'].mean()\nangrybirds_total_likes\n#angrybirds_avg_likes",
"_____no_output_____"
],
[
"# Retweets Stats:\n#angrybirds_sum_retweets = angrybirds_filtered_df['ReTweet Count'].sum()\nangrybirds_avg_retweets = angrybirds_filtered_df['ReTweet Count'].mean()\n#angrybirds_sum_retweets\nangrybirds_avg_retweets",
"_____no_output_____"
]
],
[
[
"### YouTube Calculations",
"_____no_output_____"
]
],
[
[
"plug = 'youtube'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nyoutube_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nyoutube_source_df.describe()",
"_____no_output_____"
],
[
"youtube_source_df.head()",
"_____no_output_____"
],
[
"# Sort\nyoutube_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nyoutube_filtered_df = youtube_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nyoutube_filtered_df.describe()",
"_____no_output_____"
],
[
"youtube_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nyoutube_total_tweets = len(youtube_filtered_df['Tweet Text'])\nyoutube_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\nyoutube_avg_followers_ct = youtube_filtered_df['User Follower Count'].mean()\nyoutube_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\n# use sum of likes.\nyoutube_total_likes = youtube_filtered_df['Likes Counts'].sum()\n#youtube_avg_likes = youtube_filtered_df['Likes Counts'].mean()\nyoutube_total_likes\n#youtube_avg_likes",
"_____no_output_____"
],
[
"# You Tube Retweets Stats:\n#youtube_sum_retweets = facebook_filtered_df['ReTweet Count'].sum()\nyoutube_avg_retweets = youtube_filtered_df['ReTweet Count'].mean()\n#youtube_sum_retweets\nyoutube_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Subway Surfers",
"_____no_output_____"
]
],
[
[
"plug = 'subwaysurfer'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nSubwaySurfers_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nSubwaySurfers_source_df.describe()",
"_____no_output_____"
],
[
"SubwaySurfers_source_df.head()",
"_____no_output_____"
],
[
"# Sort\nSubwaySurfers_source_df.sort_values(by=['User ID','Created At'], ascending=False)\nSubwaySurfers_source_df.head()",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nSubwaySurfers_filtered_df = SubwaySurfers_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nSubwaySurfers_filtered_df.describe()",
"_____no_output_____"
],
[
"SubwaySurfers_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nSubwaySurfers_total_tweets = len(SubwaySurfers_filtered_df['Tweet Text'])\nSubwaySurfers_total_tweets",
"_____no_output_____"
],
[
"# Calculate Avg Followers - doesn't make sense to sum.\nSubwaySurfers_avg_followers_ct = SubwaySurfers_filtered_df['User Follower Count'].mean()\nSubwaySurfers_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nSubwaySurfers_total_likes = SubwaySurfers_filtered_df['Likes Counts'].sum()\n#SubwaySurfers_avg_likes = SubwaySurfers_filtered_df['Likes Counts'].mean()\nSubwaySurfers_total_likes\n#SubwaySurfers_avg_likes",
"_____no_output_____"
],
[
"# Subway Surfer Retweets Stats:\n#SubwaySurfers_sum_retweets = SubwaySurfers_filtered_df['ReTweet Count'].sum()\nSubwaySurfers_avg_retweets = SubwaySurfers_filtered_df['ReTweet Count'].mean()\n#SubwaySurfers_sum_retweets\nSubwaySurfers_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Security Master - Antivirus, VPN",
"_____no_output_____"
]
],
[
[
"# Cheetah Mobile owns Security Master\nplug = 'cheetah'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nSecurityMaster_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nSecurityMaster_source_df.describe()",
"_____no_output_____"
],
[
"SecurityMaster_source_df.head()",
"_____no_output_____"
],
[
"# has duplicates\nSecurityMaster_source_df.sort_values(by=['User ID','Created At'], ascending=False)\nSecurityMaster_source_df.head()",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nSecurityMaster_filtered_df = SecurityMaster_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nSecurityMaster_filtered_df.describe()",
"_____no_output_____"
],
[
"SecurityMaster_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nSecurityMaster_total_tweets = len(SecurityMaster_filtered_df['Tweet Text'])\nSecurityMaster_total_tweets",
"_____no_output_____"
],
[
"# Calculate Avg Followers - doesn't make sense to sum.\nSecurityMaster_avg_followers_ct = SecurityMaster_filtered_df['User Follower Count'].mean()\nSecurityMaster_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nSecurityMaster_total_likes = SecurityMaster_filtered_df['Likes Counts'].sum()\n#SecurityMaster_avg_likes = SecurityMaster_filtered_df['Likes Counts'].mean()\nSecurityMaster_total_likes\n#SecurityMaster_avg_likes",
"_____no_output_____"
],
[
"# Security Master Retweets Stats:\n#SecurityMaster_sum_retweets = SecurityMaster_filtered_df['ReTweet Count'].sum()\nSecurityMaster_avg_retweets = SecurityMaster_filtered_df['ReTweet Count'].mean()\n#SecurityMaster_sum_retweets\nSecurityMaster_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Clash Royale",
"_____no_output_____"
]
],
[
[
"plug = 'clashroyale'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nClashRoyale_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nClashRoyale_source_df.describe()",
"_____no_output_____"
],
[
"ClashRoyale_source_df.head()",
"_____no_output_____"
],
[
"# has duplicates\nClashRoyale_source_df.sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nClashRoyale_filtered_df = ClashRoyale_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nClashRoyale_filtered_df.describe()",
"_____no_output_____"
],
[
"ClashRoyale_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nClashRoyale_total_tweets = len(ClashRoyale_filtered_df['Tweet Text'])\nClashRoyale_total_tweets",
"_____no_output_____"
],
[
"# Calculate Avg Followers - doesn't make sense to sum.\nClashRoyale_avg_followers_ct = ClashRoyale_filtered_df['User Follower Count'].mean()\nClashRoyale_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nClashRoyale_total_likes = ClashRoyale_filtered_df['Likes Counts'].sum()\n#ClashRoyale_avg_likes = ClashRoyale_filtered_df['Likes Counts'].mean()\nClashRoyale_total_likes\n#ClashRoyale_avg_likes",
"_____no_output_____"
],
[
"# ClashRoyale Retweets Stats:\n#ClashRoyale_sum_retweets = ClashRoyale_filtered_df['ReTweet Count'].sum()\nClashRoyale_avg_retweets = ClashRoyale_filtered_df['ReTweet Count'].mean()\n#facebook_sum_retweets\nClashRoyale_avg_retweets",
"_____no_output_____"
]
],
[
[
"### Clean Master - Space Cleaner",
"_____no_output_____"
]
],
[
[
"plug = 'cleanmaster'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nCleanMaster_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nCleanMaster_source_df.describe()",
"_____no_output_____"
],
[
"CleanMaster_source_df.head()\n",
"_____no_output_____"
],
[
"# has duplicates\nCleanMaster_source_df.sort_values(by=['User ID','Created At'], ascending=False)\nCleanMaster_source_df.head()",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nCleanMaster_filtered_df = CleanMaster_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nCleanMaster_filtered_df.describe()",
"_____no_output_____"
],
[
"CleanMaster_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nCleanMaster_total_tweets = len(CleanMaster_filtered_df['Tweet Text'])\nCleanMaster_total_tweets",
"_____no_output_____"
],
[
"# Calculate Avg Followers - doesn't make sense to sum.\nCleanMaster_avg_followers_ct = CleanMaster_filtered_df['User Follower Count'].mean()\nCleanMaster_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets\nCleanMaster_total_likes = CleanMaster_filtered_df['Likes Counts'].sum()\n#facebook_avg_likes = facebook_filtered_df['Likes Counts'].mean()\nCleanMaster_total_likes\n#facebook_avg_likes",
"_____no_output_____"
],
[
"# Clean MasterRetweets Stats:\n#CleanMaster_sum_retweets = CleanMaster_filtered_df['ReTweet Count'].sum()\nCleanMaster_avg_retweets = CleanMaster_filtered_df['ReTweet Count'].mean()\n#facebook_sum_retweets\nCleanMaster_avg_retweets",
"_____no_output_____"
]
],
[
[
"### What's App",
"_____no_output_____"
]
],
[
[
"plug = 'whatsapp'\npath = f'./resources/{plug}'\nall_files = glob.glob(path + \"/*.csv\")\nli = []\nfor filename in all_files:\n df = pd.read_csv(filename, index_col=None, header=0)\n li.append(df)\nwhatsapp_source_df = pd.concat(li, axis=0, ignore_index=True)\n\n# Snapshot Statistics\nwhatsapp_source_df.describe()",
"_____no_output_____"
],
[
"whatsapp_source_df.head()",
"_____no_output_____"
],
[
"# has duplicates\nwhatsapp_source_df.sort_values(by=['User ID','Created At'], ascending=False)\nwhatsapp_source_df.head()",
"_____no_output_____"
],
[
"# Drop Duplicates only for matching columns omitting the index\nwhatsapp_filtered_df = whatsapp_source_df.drop_duplicates(['Created At', 'Screen Name', 'User ID', 'User Follower Count', 'Likes Counts', 'ReTweet Count', 'Tweet Text']).sort_values(by=['User ID','Created At'], ascending=False)",
"_____no_output_____"
],
[
"# Get New Snap Shot Statistics\nwhatsapp_filtered_df.describe()",
"_____no_output_____"
],
[
"whatsapp_filtered_df.head()",
"_____no_output_____"
],
[
"# Count total out of Unique Tweets\nwhatsapp_total_tweets = len(whatsapp_filtered_df['Tweet Text'])\nwhatsapp_total_tweets",
"_____no_output_____"
],
[
"# Calculate Facebook Avg Followers - doesn't make sense to sum.\nwhatsapp_avg_followers_ct = whatsapp_filtered_df['User Follower Count'].mean()\nwhatsapp_avg_followers_ct",
"_____no_output_____"
],
[
"# Total Likes of all tweets.\nwhatsapp_total_likes = whatsapp_filtered_df['Likes Counts'].sum()\n#whatsapp_avg_likes = whatsapp_filtered_df['Likes Counts'].mean()\nwhatsapp_total_likes\n#whatsapp_avg_likes",
"_____no_output_____"
],
[
"# Whatsapp Retweets Stats:\n#whatsapp_sum_retweets = whatsapp_filtered_df['ReTweet Count'].sum()\nwhatsapp_avg_retweets = whatsapp_filtered_df['ReTweet Count'].mean()\n#whatsapp_sum_retweets\nwhatsapp_avg_retweets",
"_____no_output_____"
]
],
[
[
"# Charts and Plots\n",
"_____no_output_____"
],
[
"#### Scatter plot - Twitter Average Followers to Tweets",
"_____no_output_____"
]
],
[
[
"# Scatter Plot 1 - Tweets vs Average Followers vs Total Likes of the Top 10 Apps for both Google and Apple App Stores\n\nfig, ax = plt.subplots(figsize=(11,11))\n\n\n# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(facebook_total_tweets, facebook_avg_followers_ct, s=facebook_total_likes*15, color='sandybrown', label='Facebook', edgecolors='black', alpha=0.75)\ninstagram_plot= ax.scatter(instagram_total_tweets, instagram_avg_followers_ct, s=instagram_total_likes*15, color='saddlebrown', label='Instagram', edgecolors='black', alpha=0.5)\ncoc_plot= ax.scatter(coc_total_tweets, coc_avg_followers_ct, s=coc_total_likes*10, color='springgreen', label='Clash Of Clans', edgecolors='black', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(candycrushsaga_total_tweets, candycrushsaga_avg_followers_ct, s=candycrushsaga_total_likes*5, color='limegreen', label='Candy Crush Saga', edgecolors='black')#, alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(CleanMaster_total_tweets, CleanMaster_avg_followers_ct, s=CleanMaster_total_likes*5, color='m', label='Clean Master Space Cleaner', edgecolors='black', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(SubwaySurfers_total_tweets, SubwaySurfers_avg_followers_ct, s=SubwaySurfers_total_likes*5, color='lime', label='Subway Surfers', edgecolors='black', alpha=0.75)\nyoutube_plot= ax.scatter(youtube_total_tweets, youtube_avg_followers_ct, s=youtube_total_likes*5, color='red', label='You Tube', edgecolors='black', alpha=0.75)\nSecurityMaster_plot= ax.scatter(SecurityMaster_total_tweets, SecurityMaster_avg_followers_ct, s=SecurityMaster_total_likes*5, color='blueviolet', label='Security Master, Antivirus VPN', edgecolors='black', alpha=0.75)\nClashRoyale_plot= ax.scatter(ClashRoyale_total_tweets, ClashRoyale_avg_followers_ct, s=ClashRoyale_total_likes*5, color='darkolivegreen', label='Clash Royale', edgecolors='black', alpha=0.75)\nwhatsapp_plot= ax.scatter(whatsapp_total_tweets, whatsapp_avg_followers_ct, s=whatsapp_total_likes*5, color='tan', label='Whats App', edgecolors='black', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(templerun_total_tweets, templerun_avg_followers_ct, s=templerun_total_likes*5, color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(pandora_total_tweets, pandora_avg_followers_ct, s=pandora_total_likes*5, color='coral', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(pinterest_total_tweets, pinterest_avg_followers_ct, s=pinterest_total_likes*5, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(bible_total_tweets, bible_avg_followers_ct, s=bible_total_likes*5, color='tomato', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(spotify_total_tweets, spotify_avg_followers_ct, s=spotify_total_likes*5, color='orangered', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(angrybirds_total_tweets, angrybirds_avg_followers_ct, s=angrybirds_total_likes*5, color='forestgreen', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs Average Followers (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Total Tweets \\n Note: Circle sizes correlate with Total Likes\" )\nplt.ylabel(\"Average Number of Followers per Twitter User \\n\")\n\n# set and format the legend\nlgnd = plt.legend(title='Legend', loc=\"best\")\n \n\nlgnd.legendHandles[0]._sizes = [30]\nlgnd.legendHandles[1]._sizes = [30]\nlgnd.legendHandles[2]._sizes = [30]\nlgnd.legendHandles[3]._sizes = [30]\nlgnd.legendHandles[4]._sizes = [30]\nlgnd.legendHandles[5]._sizes = [30]\nlgnd.legendHandles[6]._sizes = [30]\nlgnd.legendHandles[7]._sizes = [30]\nlgnd.legendHandles[8]._sizes = [30]\nlgnd.legendHandles[9]._sizes = [30]\nlgnd.legendHandles[10]._sizes = [30]\nlgnd.legendHandles[11]._sizes = [30]\nlgnd.legendHandles[12]._sizes = [30]\nlgnd.legendHandles[13]._sizes = [30]\nlgnd.legendHandles[14]._sizes = [30]\nlgnd.legendHandles[15]._sizes = [30]\n\n\n#grid lines and show\nplt.grid()\nplt.show()\n#plt.savefig(\"./TWEETS_vs__AVG_followers_Scatter.png\")",
"_____no_output_____"
],
[
"# Test Cell: Tried to automate plot, but was unable to beause for the size (s), JG wanted to scale the\n# the size by multiplying by a unique scale depending on the number of likes to emphasize data points\n# Conclusion: was to stick with brute force method\n\nSubwaySurfers_total_tweets, \nx = [facebook_total_tweets, instagram_total_tweets, coc_total_tweets,\n candycrushsaga_total_tweets, CleanMaster_total_tweets,\n youtube_total_tweets, SecurityMaster_total_tweets,\n ClashRoyale_total_tweets, whatsapp_total_tweets, templerun_total_tweets,\n pandora_total_tweets, pinterest_total_tweets, bible_total_tweets, spotify_total_tweets,\n angrybirds_total_tweets]\nSubwaySurfers_avg_followers_ct, \ny = [facebook_avg_followers_ct, instagram_avg_followers_ct, coc_avg_followers_ct,\n candycrushsaga_avg_followers_ct, CleanMaster_avg_followers_ct,\n youtube_avg_followers_ct, SecurityMaster_avg_followers_ct,\n ClashRoyale_avg_followers_ct, whatsapp_avg_followers_ct, templerun_avg_followers_ct,\n pandora_avg_followers_ct, pinterest_avg_followers_ct, bible_avg_followers_ct, spotify_avg_followers_ct,\n angrybirds_avg_followers_ct]\n\n\"\"\"\n# Below this method doesn't work. Will go with brute force method.\ns = [(facebook_total_likes*15), (instagram_total_likes*15), (coc_total_likes*10), (candycrushsaga_total_likes*5),\n (CleanMaster_total_likes*5), (SubwaySurfers_total_likes*5), (youtube_total_likes*5), (SecurityMaster_total_likes*5)\n (ClashRoyale_total_likes*5), (whatsapp_total_likes*5), (templerun_total_likes*5), (pandora_total_likes*5),\n (pinterest_total_likes*5), (bible_total_likes*5), (spotify_total_likes*5), (angrybirds_total_likes*5)]\n\"\"\"\ns = [facebook_total_likes, instagram_total_likes, coc_total_likes, candycrushsaga_total_likes,\n CleanMaster_total_likes, SubwaySurfers_total_likes, youtube_total_likes, SecurityMaster_total_likes,\n ClashRoyale_total_likes, whatsapp_total_likes, templerun_total_likes, pandora_total_likes,\n pinterest_total_likes, bible_total_likes, spotify_total_likes, angrybirds_total_likes]\n\ncolors = np.random.rand(16)\n\n\n\nlabel = []\nedgecolors = []\nalpha = []\n\nfig, ax = plt.subplots(figsize=(11,11))\nax.scatter(x, y, s)\nplt.grid()\nplt.show()\n\n\"\"\"# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(, , , color='sandybrown', label='Facebook', edgecolors='black', alpha=0.75)\ninstagram_plot= ax.scatter(, , , color='saddlebrown', label='Instagram', edgecolors='black', alpha=0.5)\ncoc_plot= ax.scatter(,, , color='springgreen', label='Clash Of Clans', edgecolors='black', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(,, , color='limegreen', label='Candy Crush Saga', edgecolors='black')#, alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(,, , color='m', label='Clean Master Space Cleaner', edgecolors='black', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(,, , color='lime', label='Subway Surfers', edgecolors='black', alpha=0.75)\nyoutube_plot= ax.scatter(,, , color='red', label='You Tube', edgecolors='black', alpha=0.75)\nSecurityMaster_plot= ax.scatter(,, , color='blueviolet', label='Security Master, Antivirus VPN', edgecolors='black', alpha=0.75)\nClashRoyale_plot= ax.scatter(,, , color='darkolivegreen', label='Clash Royale', edgecolors='black', alpha=0.75)\nwhatsapp_plot= ax.scatter(,, , color='tan', label='Whats App', edgecolors='black', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(, , , color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(, ,, color='coral', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(, ,, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(, , color='tomato', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(, , color='orangered', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(,,, color='forestgreen', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs Average Followers (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Total Tweets \\n Note: Circle sizes correlate with Total Likes\" )\nplt.ylabel(\"Average Number of Followers per Twitter User \\n\")\n\n\"\"\"\n",
"_____no_output_____"
],
[
"# Scatter Plot 2 - Tweets vs ReTweets vs Likes\n\nfig, ax = plt.subplots(figsize=(11,11))\n\n\n# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(facebook_total_tweets, facebook_avg_retweets, s=facebook_total_likes*5, color='sandybrown', label='Facebook', edgecolors='black', alpha=0.75)\ninstagram_plot= ax.scatter(instagram_total_tweets, instagram_avg_retweets, s=instagram_total_likes*5, color='saddlebrown', label='Instagram', edgecolors='black', alpha=0.75)\ncoc_plot= ax.scatter(coc_total_tweets, coc_avg_retweets, s=coc_total_likes*5, color='springgreen', label='Clash Of Clans', edgecolors='black', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(candycrushsaga_total_tweets, candycrushsaga_avg_retweets, s=candycrushsaga_total_likes*5, color='limegreen', label='Candy Crush Saga', edgecolors='black')#, alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(CleanMaster_total_tweets, CleanMaster_avg_retweets, s=CleanMaster_total_likes*5, color='m', label='Clean Master Space Cleaner', edgecolors='black', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(SubwaySurfers_total_tweets, SubwaySurfers_avg_retweets, s=SubwaySurfers_total_likes*5, color='lime', label='Subway Surfers', edgecolors='black', alpha=0.75)\nyoutube_plot= ax.scatter(youtube_total_tweets, youtube_avg_retweets, s=youtube_total_likes*5, color='red', label='You Tube', edgecolors='black', alpha=0.75)\nSecurityMaster_plot= ax.scatter(SecurityMaster_total_tweets, SecurityMaster_avg_retweets, s=SecurityMaster_total_likes*5, color='blueviolet', label='Security Master, Antivirus VPN', edgecolors='black', alpha=0.75)\nClashRoyale_plot= ax.scatter(ClashRoyale_total_tweets, ClashRoyale_avg_retweets, s=ClashRoyale_total_likes*5, color='darkolivegreen', label='Clash Royale', edgecolors='black', alpha=0.75)\nwhatsapp_plot= ax.scatter(whatsapp_total_tweets, whatsapp_avg_retweets, s=whatsapp_total_likes*5, color='tan', label='Whats App', edgecolors='black', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(templerun_total_tweets, templerun_avg_retweets, s=templerun_total_likes*5, color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(pandora_total_tweets, pandora_avg_retweets, s=pandora_total_likes*5, color='coral', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(pinterest_total_tweets, pinterest_avg_retweets, s=pinterest_total_likes*5, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(bible_total_tweets, bible_avg_retweets, s=bible_total_likes*5, color='tomato', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(spotify_total_tweets, spotify_avg_retweets, s=spotify_total_likes*5, color='orangered', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(angrybirds_total_tweets, angrybirds_avg_retweets, s=angrybirds_total_likes*5, color='forestgreen', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs ReTweets (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Total Tweets \\n Note: Circle sizes correlate with Total Likes \\n\" )\nplt.ylabel(\"Average Number of ReTweets per Twitter User \\n\")\n\n# set and format the legend\nlgnd = plt.legend(title='Legend', loc=\"best\")\n\nlgnd.legendHandles[0]._sizes = [30]\nlgnd.legendHandles[1]._sizes = [30]\nlgnd.legendHandles[2]._sizes = [30]\nlgnd.legendHandles[3]._sizes = [30]\nlgnd.legendHandles[4]._sizes = [30]\nlgnd.legendHandles[5]._sizes = [30]\nlgnd.legendHandles[6]._sizes = [30]\nlgnd.legendHandles[7]._sizes = [30]\nlgnd.legendHandles[8]._sizes = [30]\nlgnd.legendHandles[9]._sizes = [30]\nlgnd.legendHandles[10]._sizes = [30]\nlgnd.legendHandles[11]._sizes = [30]\nlgnd.legendHandles[12]._sizes = [30]\nlgnd.legendHandles[13]._sizes = [30]\nlgnd.legendHandles[14]._sizes = [30]\nlgnd.legendHandles[15]._sizes = [30]\n\n\n#grid lines and show\nplt.grid()\nplt.show()\n#plt.savefig('./TWEETS_VS_RETWEETS_vs_LIKES_Scatter.png')",
"_____no_output_____"
],
[
"# Scatter Plot 3 - Will not use this plot\n\nfig, ax = plt.subplots(figsize=(8,8))\n\n\n# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(facebook_avg_retweets, facebook_total_tweets, s=facebook_total_likes*5, color='blue', label='Facebook', edgecolors='red', alpha=0.75)\ninstagram_plot= ax.scatter(instagram_avg_retweets, instagram_total_tweets, s=instagram_total_likes*5, color='fuchsia', label='Instagram', edgecolors='red', alpha=0.75)\ncoc_plot= ax.scatter(coc_avg_retweets, coc_total_tweets, s=coc_total_likes*5, color='springgreen', label='Clash Of Clans', edgecolors='red', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(candycrushsaga_avg_retweets, candycrushsaga_total_tweets, s=candycrushsaga_total_likes*5, color='black', label='Candy Crush Saga', edgecolors='red')#, alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(CleanMaster_avg_retweets, CleanMaster_total_tweets, s=CleanMaster_total_likes*5, color='olive', label='Clean Master Space Cleaner', edgecolors='lime', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(SubwaySurfers_avg_retweets, SubwaySurfers_total_tweets, s=SubwaySurfers_total_likes*5, color='plum', label='Subway Surfers', edgecolors='lime', alpha=0.75)\nyoutube_plot= ax.scatter(youtube_avg_retweets, youtube_total_tweets, s=youtube_total_likes*5, color='grey', label='You Tube', edgecolors='lime', alpha=0.75)\nSecurityMaster_plot= ax.scatter(SecurityMaster_avg_retweets, SecurityMaster_total_tweets, s=SecurityMaster_total_likes*5, color='coral', label='Security Master, Antivirus VPN', edgecolors='lime', alpha=0.75)\nClashRoyale_plot= ax.scatter(ClashRoyale_avg_retweets, ClashRoyale_total_tweets, s=ClashRoyale_total_likes*5, color='orange', label='Clash Royale', edgecolors='lime', alpha=0.75)\nwhatsapp_plot= ax.scatter(whatsapp_avg_retweets, whatsapp_total_tweets, s=whatsapp_total_likes*5, color='green', label='Whats App', edgecolors='lime', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(templerun_avg_retweets, templerun_total_tweets, s=templerun_total_likes*5, color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(pandora_avg_retweets, pandora_total_tweets, s=pandora_total_likes*5, color='cornflowerblue', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(pinterest_avg_retweets, pinterest_total_tweets, s=pinterest_total_likes*5, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(bible_avg_retweets, bible_total_tweets, s=bible_total_likes*5, color='brown', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(spotify_avg_retweets, spotify_total_tweets, s=spotify_total_likes*5, color='darkgreen', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(angrybirds_avg_retweets, angrybirds_total_tweets, s=angrybirds_total_likes*5, color='salmon', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs ReTweets (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Total Tweets \\n Note: Circle sizes correlate with Total Likes \\n\" )\nplt.ylabel(\"Average Number of ReTweets per Twitter User \\n\")\n\n# set and format the legend\nlgnd = plt.legend(title='Legend', loc=\"best\")\n\nlgnd.legendHandles[0]._sizes = [30]\nlgnd.legendHandles[1]._sizes = [30]\nlgnd.legendHandles[2]._sizes = [30]\nlgnd.legendHandles[3]._sizes = [30]\nlgnd.legendHandles[4]._sizes = [30]\nlgnd.legendHandles[5]._sizes = [30]\nlgnd.legendHandles[6]._sizes = [30]\nlgnd.legendHandles[7]._sizes = [30]\nlgnd.legendHandles[8]._sizes = [30]\nlgnd.legendHandles[9]._sizes = [30]\nlgnd.legendHandles[10]._sizes = [30]\nlgnd.legendHandles[11]._sizes = [30]\nlgnd.legendHandles[12]._sizes = [30]\nlgnd.legendHandles[13]._sizes = [30]\nlgnd.legendHandles[14]._sizes = [30]\nlgnd.legendHandles[15]._sizes = [30]\n\n\n#grid lines and show\nplt.grid()\nplt.show()\n#plt.savefig('./tweets_vs__avgfollowers_Scatter.png')",
"_____no_output_____"
],
[
"# Hardcoding numbers from analysis done in Apple and Google Play Store Final Code Notebooks\n# Avergage Apple, Google Ratings\nfacebook_avg_rating = (3.5 + 4.1)/2\ninstagram_avg_rating = (4.5 + 4.5)/2\ncoc_avg_rating = (4.5 + 4.6)/2\ncandycrushsaga_avg_rating = (4.5 + 4.4)/2\n\n# Avergage Apple, Google Reviews\nfacebook_reviews = (2974676 + 78158306)/2\ninstagram_reviews = (2161558 + 66577446)/2\ncoc_reviews = (2130805 + 44893888)/2\ncandycrushsaga_reviews = (961794 + 22430188)/2\n\n# Apple App Ratings\ntemplerun_rating = 4.5\npandora_rating = 4.5\npinterest_rating = 4.5\nbible_rating = 4.5\nspotify_rating = 4.5\nangrybirds_rating = 4.5\n\n# Apple App Reviews\ntemplerun_reviews = 1724546\npandora_reviews = 1126879\npinterest_reviews = 1061624\nbible_reviews = 985920\nspotify_reviews = 878563\nangrybirds_reviews = 824451\n\n\n# Google App Ratings\nwhatsapp_rating = 4.4\nclean_master_rating = 4.7\nsubway_surfers_rating = 4.5\nyou_tube_rating = 4.3\nsecurity_master_rating = 4.7\nclash_royale_rating = 4.6\n\n# Google App Reviews\nwhatsapp_reviews = 69119316\nclean_master_reviews = 42916526\nsubway_surfers_reviews = 27725352\nyou_tube_reviews = 25655305\nsecurity_master_reviews = 24900999\nclash_royale_reviews = 23136735\n",
"_____no_output_____"
],
[
"# Scatter Plot 5 - Tweets vs Ratings vs Likes - USE THIS ONE\n\nfig, ax = plt.subplots(figsize=(11,11))\n\n\n# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(facebook_total_tweets, facebook_avg_rating, s=facebook_total_likes*5, color='sandybrown', label='Facebook', edgecolors='black', alpha=0.75)\ninstagram_plot= ax.scatter(instagram_total_tweets, instagram_avg_rating, s=instagram_total_likes*5, color='saddlebrown', label='Instagram', edgecolors='black', alpha=0.75)\ncoc_plot= ax.scatter(coc_total_tweets, coc_avg_rating, s=coc_total_likes*5, color='springgreen', label='Clash Of Clans', edgecolors='black', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(candycrushsaga_total_tweets, candycrushsaga_avg_rating, s=candycrushsaga_total_likes*5, color='limegreen', label='Candy Crush Saga', edgecolors='black')#, alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(CleanMaster_total_tweets, clean_master_rating, s=CleanMaster_total_likes*5, color='m', label='Clean Master Space Cleaner', edgecolors='black', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(SubwaySurfers_total_tweets, subway_surfers_rating, s=SubwaySurfers_total_likes*5, color='lime', label='Subway Surfers', edgecolors='black', alpha=0.75)\nyoutube_plot= ax.scatter(youtube_total_tweets, you_tube_rating, s=youtube_total_likes*5, color='red', label='You Tube', edgecolors='black', alpha=0.75)\nSecurityMaster_plot= ax.scatter(SecurityMaster_total_tweets, security_master_rating, s=SecurityMaster_total_likes*5, color='blueviolet', label='Security Master, Antivirus VPN', edgecolors='black', alpha=0.75)\nClashRoyale_plot= ax.scatter(ClashRoyale_total_tweets, clash_royale_rating, s=ClashRoyale_total_likes*5, color='darkolivegreen', label='Clash Royale', edgecolors='black', alpha=0.75)\nwhatsapp_plot= ax.scatter(whatsapp_total_tweets, whatsapp_rating, s=whatsapp_total_likes*5, color='tan', label='Whats App', edgecolors='black', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(templerun_total_tweets,templerun_rating, s=templerun_total_likes*5, color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(pandora_total_tweets, pandora_rating, s=pandora_total_likes*5, color='coral', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(pinterest_total_tweets, pinterest_rating, s=pinterest_total_likes*5, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(bible_total_tweets, bible_rating, s=bible_total_likes*5, color='tomato', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(spotify_total_tweets, spotify_rating, s=spotify_total_likes*5, color='orangered', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(angrybirds_total_tweets, angrybirds_rating, s=angrybirds_total_likes*5, color='forestgreen', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs Ratings (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Total Tweets \\n Note: Circle sizes correlate with Total Likes \\n\" )\nplt.ylabel(\"App Store User Ratings (Out of 5) \\n\")\n\n# set and format the legend\nlgnd = plt.legend(title='Legend', loc=\"best\")\n\nlgnd.legendHandles[0]._sizes = [30]\nlgnd.legendHandles[1]._sizes = [30]\nlgnd.legendHandles[2]._sizes = [30]\nlgnd.legendHandles[3]._sizes = [30]\nlgnd.legendHandles[4]._sizes = [30]\nlgnd.legendHandles[5]._sizes = [30]\nlgnd.legendHandles[6]._sizes = [30]\nlgnd.legendHandles[7]._sizes = [30]\nlgnd.legendHandles[8]._sizes = [30]\nlgnd.legendHandles[9]._sizes = [30]\nlgnd.legendHandles[10]._sizes = [30]\nlgnd.legendHandles[11]._sizes = [30]\nlgnd.legendHandles[12]._sizes = [30]\nlgnd.legendHandles[13]._sizes = [30]\nlgnd.legendHandles[14]._sizes = [30]\nlgnd.legendHandles[15]._sizes = [30]\n\n\n#grid lines and show\nplt.grid()\nplt.show()\n#plt.savefig('./TWEETS_VS_RATINGSVS LIKES_Scatter.png')",
"_____no_output_____"
],
[
"# Scatter Plot 5 - Tweets vs Reviews vs Ratings (size) - DO NOT USE\n\nfig, ax = plt.subplots(figsize=(11,11))\n\n\n\n# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(facebook_total_tweets, facebook_reviews, s=facebook_avg_rating*105, color='sandybrown', label='Facebook', edgecolors='black', alpha=0.75)\ninstagram_plot= ax.scatter(instagram_total_tweets, instagram_reviews, s=instagram_avg_rating*105, color='saddlebrown', label='Instagram', edgecolors='black', alpha=0.75)\ncoc_plot= ax.scatter(coc_total_tweets, coc_reviews, s=coc_avg_rating*105, color='springgreen', label='Clash Of Clans', edgecolors='black', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(candycrushsaga_total_tweets, candycrushsaga_reviews, s=candycrushsaga_avg_rating*105, color='limegreen', label='Candy Crush Saga', edgecolors='black', alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(CleanMaster_total_tweets, clean_master_reviews, s=clean_master_rating*105, color='m', label='Clean Master Space Cleaner', edgecolors='black', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(SubwaySurfers_total_tweets, subway_surfers_reviews, s=subway_surfers_rating*105, color='lime', label='Subway Surfers', edgecolors='black', alpha=0.75)\nyoutube_plot= ax.scatter(youtube_total_tweets, you_tube_reviews, s=you_tube_rating*105, color='red', label='You Tube', edgecolors='black', alpha=0.75)\nSecurityMaster_plot= ax.scatter(SecurityMaster_total_tweets, security_master_reviews, s=security_master_rating*105, color='blueviolet', label='Security Master, Antivirus VPN', edgecolors='black', alpha=0.75)\nClashRoyale_plot= ax.scatter(ClashRoyale_total_tweets, clash_royale_reviews, s=clash_royale_rating*105, color='darkolivegreen', label='Clash Royale', edgecolors='black', alpha=0.75)\nwhatsapp_plot= ax.scatter(whatsapp_total_tweets, whatsapp_reviews, s=whatsapp_rating*105, color='tan', label='Whats App', edgecolors='lime', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(templerun_total_tweets,templerun_reviews, s=templerun_rating*105, color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(pandora_total_tweets, pandora_reviews, s=pandora_rating*105, color='coral', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(pinterest_total_tweets, pinterest_reviews, s=pinterest_rating*105, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(bible_total_tweets, bible_reviews, s=bible_rating*105, color='tomato', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(spotify_total_tweets, spotify_reviews, s=spotify_rating*105, color='orangered', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(angrybirds_total_tweets, angrybirds_reviews, s=angrybirds_rating*105, color='forestgreen', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs Reviews (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Total Tweets \\n Note: Circle sizes correlate with App Ratings \\n\" )\nplt.ylabel(\"App Store Reviews in Millions \\n\")\n\n# set and format the legend\nlgnd = plt.legend(title='Legend', loc=\"best\")\n\nlgnd.legendHandles[0]._sizes = [30]\nlgnd.legendHandles[1]._sizes = [30]\nlgnd.legendHandles[2]._sizes = [30]\nlgnd.legendHandles[3]._sizes = [30]\nlgnd.legendHandles[4]._sizes = [30]\nlgnd.legendHandles[5]._sizes = [30]\nlgnd.legendHandles[6]._sizes = [30]\nlgnd.legendHandles[7]._sizes = [30]\nlgnd.legendHandles[8]._sizes = [30]\nlgnd.legendHandles[9]._sizes = [30]\nlgnd.legendHandles[10]._sizes = [30]\nlgnd.legendHandles[11]._sizes = [30]\nlgnd.legendHandles[12]._sizes = [30]\nlgnd.legendHandles[13]._sizes = [30]\nlgnd.legendHandles[14]._sizes = [30]\nlgnd.legendHandles[15]._sizes = [30]\n\n\n#grid lines and show\nplt.grid()\nplt.show()\n#plt.savefig('./tweets_vs__avgfollowers_Scatter.png')",
"_____no_output_____"
],
[
"# Scatter Plot 6 - Tweets vs Reviews vs Likes (size) -USE THIS ONE\n\nfig, ax = plt.subplots(figsize=(11,11))\n\n\n\n# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(facebook_total_tweets, facebook_reviews, s=facebook_total_likes*5, color='sandybrown', label='Facebook', edgecolors='black', alpha=0.75)\ninstagram_plot= ax.scatter(instagram_total_tweets, instagram_reviews, s=instagram_total_likes*5, color='saddlebrown', label='Instagram', edgecolors='black', alpha=0.75)\ncoc_plot= ax.scatter(coc_total_tweets, coc_reviews, s=coc_total_likes*5, color='springgreen', label='Clash Of Clans', edgecolors='black', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(candycrushsaga_total_tweets, candycrushsaga_reviews, s=candycrushsaga_total_likes*5, color='limegreen', label='Candy Crush Saga', edgecolors='black', alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(CleanMaster_total_tweets, clean_master_reviews, s=CleanMaster_total_likes*5, color='m', label='Clean Master Space Cleaner', edgecolors='black', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(SubwaySurfers_total_tweets, subway_surfers_reviews, s=SubwaySurfers_total_likes*5, color='lime', label='Subway Surfers', edgecolors='black', alpha=0.75)\nyoutube_plot= ax.scatter(youtube_total_tweets, you_tube_reviews, s=youtube_total_likes*5, color='red', label='You Tube', edgecolors='black', alpha=0.75)\nSecurityMaster_plot= ax.scatter(SecurityMaster_total_tweets, security_master_reviews, s=SecurityMaster_total_likes*5, color='blueviolet', label='Security Master, Antivirus VPN', edgecolors='black', alpha=0.75)\nClashRoyale_plot= ax.scatter(ClashRoyale_total_tweets, clash_royale_reviews, s=ClashRoyale_total_likes*5, color='darkolivegreen', label='Clash Royale', edgecolors='black', alpha=0.75)\nwhatsapp_plot= ax.scatter(whatsapp_total_tweets, whatsapp_reviews, s=whatsapp_total_likes*5, color='tan', label='Whats App', edgecolors='black', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(templerun_total_tweets, templerun_reviews, s=templerun_total_likes*5, color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(pandora_total_tweets, pandora_reviews, s=pandora_total_likes*5, color='coral', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(pinterest_total_tweets, pinterest_reviews, s=pinterest_total_likes*5, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(bible_total_tweets, bible_reviews, s=bible_total_likes*5, color='tomato', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(spotify_total_tweets, spotify_reviews, s=spotify_total_likes*5, color='orangered', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(angrybirds_total_tweets, angrybirds_reviews, s=angrybirds_total_likes*5, color='forestgreen', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs Reviews (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Total Tweets \\n Note: Circle sizes correlate with Likes \\n\" )\nplt.ylabel(\"App Store Reviews in Millions \\n\")\n\n# set and format the legend\nlgnd = plt.legend(title='Legend', loc=\"best\")\n\nlgnd.legendHandles[0]._sizes = [30]\nlgnd.legendHandles[1]._sizes = [30]\nlgnd.legendHandles[2]._sizes = [30]\nlgnd.legendHandles[3]._sizes = [30]\nlgnd.legendHandles[4]._sizes = [30]\nlgnd.legendHandles[5]._sizes = [30]\nlgnd.legendHandles[6]._sizes = [30]\nlgnd.legendHandles[7]._sizes = [30]\nlgnd.legendHandles[8]._sizes = [30]\nlgnd.legendHandles[9]._sizes = [30]\nlgnd.legendHandles[10]._sizes = [30]\nlgnd.legendHandles[11]._sizes = [30]\nlgnd.legendHandles[12]._sizes = [30]\nlgnd.legendHandles[13]._sizes = [30]\nlgnd.legendHandles[14]._sizes = [30]\nlgnd.legendHandles[15]._sizes = [30]\n\n\n#grid lines and show\nplt.grid()\nplt.show()\n#plt.savefig('./TWEETS_VS_REVIEWS_VSLIKES_Scatter.png')",
"_____no_output_____"
],
[
"# Scatter Plot 5 - Tweets vs Reviews vs Likes (size) - Need to do\n\nfig, ax = plt.subplots(figsize=(8,8))\n\n\n# Apps both on Google Play Store and Apple - 4 apps\nfacebook_plot = ax.scatter(facebook_avg_retweets, facebook_total_tweets, s=facebook_total_likes*5, color='blue', label='Facebook', edgecolors='red', alpha=0.75)\ninstagram_plot= ax.scatter(instagram_avg_retweets, instagram_total_tweets, s=instagram_total_likes*5, color='fuchsia', label='Instagram', edgecolors='red', alpha=0.75)\ncoc_plot= ax.scatter(coc_avg_retweets, coc_total_tweets, s=coc_total_likes*5, color='springgreen', label='Clash Of Clans', edgecolors='red', alpha=0.75)\ncandycrushsaga_plot= ax.scatter(candycrushsaga_avg_retweets, candycrushsaga_total_tweets, s=candycrushsaga_total_likes*5, color='black', label='Candy Crush Saga', edgecolors='red')#, alpha=0.75)\n\n# Google Play Store - 6 apps:\nCleanMaster_plot= ax.scatter(CleanMaster_avg_retweets, CleanMaster_total_tweets, s=CleanMaster_total_likes*5, color='olive', label='Clean Master Space Cleaner', edgecolors='lime', alpha=0.75)\nSubwaySurfers_plot= ax.scatter(SubwaySurfers_avg_retweets, SubwaySurfers_total_tweets, s=SubwaySurfers_total_likes*5, color='plum', label='Subway Surfers', edgecolors='lime', alpha=0.75)\nyoutube_plot= ax.scatter(youtube_avg_retweets, youtube_total_tweets, s=youtube_total_likes*5, color='grey', label='You Tube', edgecolors='lime', alpha=0.75)\nSecurityMaster_plot= ax.scatter(SecurityMaster_avg_retweets, SecurityMaster_total_tweets, s=SecurityMaster_total_likes*5, color='coral', label='Security Master, Antivirus VPN', edgecolors='lime', alpha=0.75)\nClashRoyale_plot= ax.scatter(ClashRoyale_avg_retweets, ClashRoyale_total_tweets, s=ClashRoyale_total_likes*5, color='orange', label='Clash Royale', edgecolors='lime', alpha=0.75)\nwhatsapp_plot= ax.scatter(whatsapp_avg_retweets, whatsapp_total_tweets, s=whatsapp_total_likes*5, color='green', label='Whats App', edgecolors='lime', alpha=0.75)\n\n# Apple Apps Store - 6 apps\ntemplerun_plot= ax.scatter(templerun_avg_retweets, templerun_total_tweets, s=templerun_total_likes*5, color='lawngreen', label='Temple Run', edgecolors='black', alpha=0.75)\npandora_plot= ax.scatter(pandora_avg_retweets, pandora_total_tweets, s=pandora_total_likes*5, color='cornflowerblue', label='Pandora', edgecolors='black', alpha=0.75)\npinterest_plot= ax.scatter(pinterest_avg_retweets, pinterest_total_tweets, s=pinterest_total_likes*5, color='firebrick', label='Pinterest', edgecolors='black', alpha=0.75)\nbible_plot= ax.scatter(bible_avg_retweets, bible_total_tweets, s=bible_total_likes*5, color='brown', label='Bible', edgecolors='black', alpha=0.75)\nspotify_plot= ax.scatter(spotify_avg_retweets, spotify_total_tweets, s=spotify_total_likes*5, color='darkgreen', label='Spotify', edgecolors='black', alpha=0.75)\nangrybirds_plot= ax.scatter(angrybirds_avg_retweets, angrybirds_total_tweets, s=angrybirds_total_likes*5, color='salmon', label='Angry Birds', edgecolors='black', alpha=0.75)\n\n# title and labels\nplt.title(\"Tweets vs ReTweets (Mar 27 - Apr 3, 2019) \\n\")\nplt.xlabel(\"Avg ReTweets \\n Note: Circle sizes correlate with Total Likes \\n\" )\nplt.ylabel(\"Total Tweets \\n\")\n\n# set and format the legend\nlgnd = plt.legend(title='Legend', loc=\"best\")\n\nlgnd.legendHandles[0]._sizes = [30]\nlgnd.legendHandles[1]._sizes = [30]\nlgnd.legendHandles[2]._sizes = [30]\nlgnd.legendHandles[3]._sizes = [30]\nlgnd.legendHandles[4]._sizes = [30]\nlgnd.legendHandles[5]._sizes = [30]\nlgnd.legendHandles[6]._sizes = [30]\nlgnd.legendHandles[7]._sizes = [30]\nlgnd.legendHandles[8]._sizes = [30]\nlgnd.legendHandles[9]._sizes = [30]\nlgnd.legendHandles[10]._sizes = [30]\nlgnd.legendHandles[11]._sizes = [30]\nlgnd.legendHandles[12]._sizes = [30]\nlgnd.legendHandles[13]._sizes = [30]\nlgnd.legendHandles[14]._sizes = [30]\nlgnd.legendHandles[15]._sizes = [30]\n\n\n#grid lines and show\nplt.grid()\nplt.show()\n#plt.savefig('./tweets_vs__avgfollowers_Scatter.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",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd59eeee1b5a4e990b19f03ecd8ce56befc1f1c
| 105,208 |
ipynb
|
Jupyter Notebook
|
notebooks/3-Sims-Generation.ipynb
|
voytekresearch/BandRatios
|
ce06cdd3066c45730bff7f48e82835bd4c0e0fdc
|
[
"MIT"
] | 6 |
2021-03-29T20:58:32.000Z
|
2022-03-20T10:38:35.000Z
|
notebooks/3-Sims-Generation.ipynb
|
voytekresearch/BandRatios
|
ce06cdd3066c45730bff7f48e82835bd4c0e0fdc
|
[
"MIT"
] | 1 |
2020-01-11T05:30:38.000Z
|
2020-01-11T05:30:39.000Z
|
notebooks/3-Sims-Generation.ipynb
|
voytekresearch/BandRatios
|
ce06cdd3066c45730bff7f48e82835bd4c0e0fdc
|
[
"MIT"
] | 7 |
2020-03-18T13:22:38.000Z
|
2022-02-06T12:05:11.000Z
| 304.950725 | 65,400 | 0.929796 |
[
[
[
"# Simulating Power Spectra\n\nIn this notebook we will explore how to simulate the data that we will use to investigate how different spectral parameters can influence band ratios. \n\nSimulated power spectra will be created with varying aperiodic and periodic parameters, and are created using the [FOOOF](https://github.com/fooof-tools/fooof) tool.\n\nIn the first set of simulations, each set of simulated spectra will vary across a single parameter while the remaining parameters remain constant. In a secondary set of simulated power spectra, we will simulate pairs of parameters changing together.\n\nFor this part of the project, this notebook demonstrates the simulations with some examples, but does not create the actual set simulations used in the project. The full set of simulations for the project are created by the standalone scripts, available in the `scripts` folder. ",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom fooof.sim import *\nfrom fooof.plts import plot_spectra",
"_____no_output_____"
],
[
"# Import custom project code\nimport sys\nsys.path.append('../bratios')\nfrom settings import *\nfrom paths import DATA_PATHS as dp",
"_____no_output_____"
],
[
"# Settings\nFREQ_RANGE = [1, 40]\nLO_BAND = [4, 8]\nHI_BAND = [13, 30]\n\n# Define default parameters\nEXP_DEF = [0, 1]\nCF_LO_DEF = np.mean(LO_BAND)\nCF_HI_DEF = np.mean(HI_BAND)\nPW_DEF = 0.4\nBW_DEF = 1\n\n# Set a range of values for the band power to take\nPW_START = 0\nPW_END = 1\nW_INC = .1\n\n# Set a range of values for the aperiodic exponent to take\nEXP_START = .25\nEXP_END = 3\nEXP_INC = .25",
"_____no_output_____"
]
],
[
[
"## Simulate power spectra with one parameter varying\n\nFirst we will make several power spectra with varying band power. \n\nTo do so, we will continue to use the example of the theta beta ratio, and vary the power of the higher (beta) band.",
"_____no_output_____"
]
],
[
[
"# The Stepper object iterates through a range of values\npw_step = Stepper(PW_START, PW_END, PW_INC)\nnum_spectra = len(pw_step)\n\n# `param_iter` creates a generator can be used to step across ranges of parameters\npw_iter = param_iter([[CF_LO_DEF, PW_DEF, BW_DEF], [CF_HI_DEF, pw_step, BW_DEF]])",
"_____no_output_____"
],
[
"# Simulate power spectra\npw_fs, pw_ps, pw_syns = gen_group_power_spectra(num_spectra, FREQ_RANGE, EXP_DEF, pw_iter)\n\n# Collect together simulated data\npw_data = [pw_fs, pw_ps, pw_syns]\n\n# Save out data, to access from other notebooks\nnp.save(dp.make_file_path(dp.demo, 'PW_DEMO', 'npy'), pw_data)",
"_____no_output_____"
],
[
"# Plot our series of generated power spectra, with varying high-band power\nplot_spectra(pw_fs, pw_ps, log_powers=True)",
"_____no_output_____"
]
],
[
[
"Above, we can see each of the spectra we generated plotted, with the same properties for all parameters, except for beta power.\n\nThe same approach can be used to simulate data that vary only in one parameter, for each isolated spectral feature.",
"_____no_output_____"
],
[
"## Simulate power spectra with two parameters varying\n\nIn this section we will explore generating data in which two parameters vary simultaneously.\n\nSpecifically, we will simulate the case in which the aperiodic exponent varies while power for a higher band oscillation also varies.\n\nThe total number of trials will be: `(n_pw_changes) * (n_exp_changes)`.",
"_____no_output_____"
]
],
[
[
"data = []\n\nexp_step = Stepper(EXP_START, EXP_END, EXP_INC)\nfor exp in exp_step:\n \n # Low band sweeps through power range\n pw_step = Stepper(PW_START, PW_END, PW_INC)\n pw_iter = param_iter([[CF_LO_DEF, PW_DEF, BW_DEF],\n [CF_HIGH_DEF, pw_step, BW_DEF]])\n \n # Generates data\n pw_apc_fs, pw_apc_ps, pw_apc_syns = gen_group_power_spectra(\n len(pw_step), FREQ_RANGE, [0, exp], pw_iter)\n \n # Collect together all simulated data\n data.append(np.array([exp, pw_apc_fs, pw_apc_ps], dtype=object))\n\n# Save out data, to access from other notebooks\nnp.save(dp.make_file_path(dp.demo, 'EXP_PW_DEMO', 'npy'), data)",
"_____no_output_____"
],
[
"# Extract some example power spectra, sub-sampling ones that vary in both exp & power\n# Note: this is just a shortcut to step across the diagonal of the matrix of simulated spectra\nplot_psds = [data[ii][2][ii, :] for ii in range(min(len(exp_step), len(pw_step)))]",
"_____no_output_____"
],
[
"# Plot a selection of power spectra in the paired parameter simulations\nplot_spectra(pw_apc_fs, plot_psds, log_powers=True)",
"_____no_output_____"
]
],
[
[
"In the plot above, we can see a selection of the data we just simulated, selecting a group of power spectra that vary across both exponent and beta power.\n\nIn the next notebook we will calculate band ratios and see how changing these parameters affects ratio measures.",
"_____no_output_____"
],
[
"### Simulating the full set of data\n\nHere we just simulated example data, to show how the simulations work. \n\nThe full set of simulations for this project are re-created with scripts, available in the `scripts` folder.\n\nTo simulate full set of single parameter simulation for this project, run this script:\n\n`python gen_single_param_sims.py`\n\nTo simulate full set of interacting parameter simulation for this project, run this script:\n\n`python gen_interacting_param_sims.py`\n\nThese scripts will automatically save all the regenerated data into the `data` folder. ",
"_____no_output_____"
]
],
[
[
"# Check all the available data files for the single parameter simulations\ndp.list_files('sims_single')",
"Files in the sims_single directory:\n 1f_data.npy\n bw_alpha.npy\n bw_beta.npy\n bw_theta.npy\n cf_alpha.npy\n cf_beta.npy\n cf_theta.npy\n exp_data.npy\n offset_data.npy\n pw_alpha.npy\n pw_beta.npy\n pw_theta.npy\n shifting_alpha.npy\n"
],
[
"# Check all the available data files for the interacting parameter simulations\ndp.list_files('sims_interacting')",
"Files in the sims_interacting directory:\n EXP_highBW.npy\n EXP_highCF.npy\n EXP_highPW.npy\n EXP_lowBW.npy\n EXP_lowCF.npy\n EXP_lowPW.npy\n highCF_highBW.npy\n highCF_highPW.npy\n highCF_lowBW.npy\n highCF_lowPW.npy\n highPW_highBW.npy\n highPW_lowBW.npy\n lowBW_highBW.npy\n lowCF_highBW.npy\n lowCF_highCF.npy\n lowCF_highPW.npy\n lowCF_lowBW.npy\n lowCF_lowPW.npy\n lowPW_highBW.npy\n lowPW_highPW.npy\n lowPW_lowBW.npy\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cbd5af02db2080c091c19f408b20fbb455fbbb05
| 334,864 |
ipynb
|
Jupyter Notebook
|
notebooks/usage.ipynb
|
amitg7/markovian-dynamics
|
91d2cc9ea2700d9210ff3140a1c72ee11184450d
|
[
"MIT"
] | 2 |
2019-03-05T13:23:16.000Z
|
2022-02-03T22:57:03.000Z
|
notebooks/usage.ipynb
|
amitg7/markovian-dynamics
|
91d2cc9ea2700d9210ff3140a1c72ee11184450d
|
[
"MIT"
] | null | null | null |
notebooks/usage.ipynb
|
amitg7/markovian-dynamics
|
91d2cc9ea2700d9210ff3140a1c72ee11184450d
|
[
"MIT"
] | 1 |
2022-02-03T22:57:13.000Z
|
2022-02-03T22:57:13.000Z
| 269.399839 | 73,080 | 0.930521 |
[
[
[
"# Symbolic System",
"_____no_output_____"
],
[
"Create a symbolic three-state system:",
"_____no_output_____"
]
],
[
[
"import markoviandynamics as md\nsym_system = md.SymbolicDiscreteSystem(3)",
"_____no_output_____"
]
],
[
[
"Get the symbolic equilibrium distribution:",
"_____no_output_____"
]
],
[
[
"sym_system.equilibrium()",
"_____no_output_____"
]
],
[
[
"Create a symbolic three-state system with potential energy barriers:",
"_____no_output_____"
]
],
[
[
"sym_system = md.SymbolicDiscreteSystemArrhenius(3)",
"_____no_output_____"
]
],
[
[
"It's the same object as the previous one, only with additional symbolic barriers:",
"_____no_output_____"
]
],
[
[
"sym_system.B_ij",
"_____no_output_____"
]
],
[
[
"We can assing values to the free parameters in the equilibrium distribution:",
"_____no_output_____"
]
],
[
[
"sym_system.equilibrium(energies=[0, 0.1, 1])",
"_____no_output_____"
],
[
"sym_system.equilibrium(energies=[0, 0.1, 1], temperature=1.5)",
"_____no_output_____"
]
],
[
[
"and create multiple equilibrium points by assigning temperature sequence:",
"_____no_output_____"
]
],
[
[
"import numpy as np\ntemperature_range = np.linspace(0.01, 10, 300)",
"_____no_output_____"
],
[
"equilibrium_line = sym_system.equilibrium([0, 0.1, 1], temperature_range)\n\nequilibrium_line.shape",
"_____no_output_____"
]
],
[
[
"# Symbolic rate matrix",
"_____no_output_____"
],
[
"Create a symbolic rate matrix with Arrhenius process transitions:",
"_____no_output_____"
]
],
[
[
"sym_rate_matrix = md.SymbolicRateMatrixArrhenius(3)\n\nsym_rate_matrix",
"_____no_output_____"
]
],
[
[
"Energies and barriers can be substituted at once:",
"_____no_output_____"
]
],
[
[
"energies = [0, 0.1, 1]\nbarriers = [[0, 0.11, 1.1], \n [0.11, 0, 10], \n [1.1, 10, 0]]\n\nsym_rate_matrix.subs_symbols(energies, barriers)",
"_____no_output_____"
],
[
"sym_rate_matrix.subs_symbols(energies, barriers, temperature=2.5)",
"_____no_output_____"
]
],
[
[
"A symbolic rate matrix can be also lambdified (transform to lambda function):",
"_____no_output_____"
]
],
[
[
"rate_matrix_lambdified = sym_rate_matrix.lambdify()",
"_____no_output_____"
]
],
[
[
"The parameters of this function are the free symbols in the rate matrix:",
"_____no_output_____"
]
],
[
[
"rate_matrix_lambdified.__code__.co_varnames",
"_____no_output_____"
]
],
[
[
"They are positioned in ascending order. First the temperature, then the energies and the barriers. Sequence of rate matrices can be created by calling this function with a sequence for each parameter.",
"_____no_output_____"
],
[
"# Dynamics",
"_____no_output_____"
],
[
"We start by computing an initial probability distribution by assigning the energies and temperature:",
"_____no_output_____"
]
],
[
[
"p_initial = sym_system.equilibrium(energies, 0.5)\n\np_initial",
"_____no_output_____"
]
],
[
[
"## Trajectory - evolve by a fixed rate matrix",
"_____no_output_____"
],
[
"Compute the rate matrix by substituting free symbols:",
"_____no_output_____"
]
],
[
[
"rate_matrix = md.rate_matrix_arrhenius(energies, barriers, 1.2)\n\nrate_matrix",
"_____no_output_____"
]
],
[
[
"Create trajectory of probability distributions in time:",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n# Create time sequence\nt_range = np.linspace(0, 5, 100)\n\ntrajectory = md.evolve(p_initial, rate_matrix, t_range)\n\ntrajectory.shape",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n\nfor i in [0, 1, 2]:\n plt.plot(t_range, trajectory[i,0,:], label='$p_{}(t)$'.format(i + 1))\nplt.xlabel('$t$')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"## Trajectory - evolve by a time-dependent rate matrix",
"_____no_output_____"
],
[
"Create a temperature sequence in time:",
"_____no_output_____"
]
],
[
[
"temperature_time = 1.4 + np.sin(4. * t_range)",
"_____no_output_____"
]
],
[
[
"Create a rate matrix as a function of the temperature sequence:",
"_____no_output_____"
]
],
[
[
"# Array of stacked rate matrices that corresponds to ``temperature_time``\nrate_matrix_time = md.rate_matrix_arrhenius(energies, barriers, temperature_time)\n\nrate_matrix_time.shape",
"_____no_output_____"
],
[
"crazy_trajectory = md.evolve(p_initial, rate_matrix_time, t_range)\n\ncrazy_trajectory.shape",
"_____no_output_____"
],
[
"for i in [0, 1, 2]:\n plt.plot(t_range, crazy_trajectory[i,0,:], label='$p_{}(t)$'.format(i + 1))\nplt.xlabel('$t$')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"# Diagonalize the rate matrix",
"_____no_output_____"
],
[
"Calculate the eigenvalues, left and right eigenvectors:",
"_____no_output_____"
]
],
[
[
"U, eigenvalues, V = md.eigensystem(rate_matrix)\n\nU.shape, eigenvalues.shape, V.shape",
"_____no_output_____"
]
],
[
[
"The eigenvalues are in descending order (the eigenvectors are ordered accordingly):",
"_____no_output_____"
]
],
[
[
"eigenvalues",
"_____no_output_____"
]
],
[
[
"We can also compute the eigensystem for multiple rate matrices at once (or evolution of a rate matrix, i.e., `rate_matrix_time`):",
"_____no_output_____"
]
],
[
[
"U, eigenvalues, V = md.eigensystem(rate_matrix_time)\n\nU.shape, eigenvalues.shape, V.shape",
"_____no_output_____"
]
],
[
[
"# Decompose to rate matrix eigenvectors",
"_____no_output_____"
],
[
"A probability distribution, in general, can be decomposed to the right eigenvectors of the rate matrix:\n\n$$\\left|p\\right\\rangle = a_1\\left|v_1\\right\\rangle + a_2\\left|v_2\\right\\rangle + a_3\\left|v_3\\right\\rangle$$\n\nwhere $a_i$ is the coefficient of the i'th right eigenvector $\\left|v_i\\right\\rangle$. A rate matrix that satisfies detailed balance has its first eigenvector as the equilibrium distribution $\\left|\\pi\\right\\rangle$. Therefore, *markovian-dynamics* normalizes $a_1$ to $1$ and decompose a probability distribution to \n\n$$\\left|p\\right\\rangle = \\left|\\pi\\right\\rangle + a_2\\left|v_2\\right\\rangle + a_3\\left|v_3\\right\\rangle$$",
"_____no_output_____"
],
[
"Decompose ``p_initial``:",
"_____no_output_____"
]
],
[
[
"md.decompose(p_initial, rate_matrix)",
"_____no_output_____"
]
],
[
[
"We can decompose also multiple points and/or by multiple rate matrices. For example, decompose multiple points:",
"_____no_output_____"
]
],
[
[
"first_decomposition = md.decompose(equilibrium_line, rate_matrix)\n\nfirst_decomposition.shape",
"_____no_output_____"
],
[
"for i in [0, 1, 2]:\n plt.plot(temperature_range, first_decomposition[i,:], label='$a_{}(T)$'.format(i + 1))\nplt.xlabel('$T$')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"or decompose a trajectory:",
"_____no_output_____"
]
],
[
[
"second_decomposition = md.decompose(trajectory, rate_matrix)\n\nsecond_decomposition.shape",
"_____no_output_____"
],
[
"for i in [0, 1, 2]:\n plt.plot(t_range, second_decomposition[i,0,:], label='$a_{}(t)$'.format(i + 1))\nplt.xlabel('$t$')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"Decompose single point using multiple rate matrices:",
"_____no_output_____"
]
],
[
[
"third_decomposition = md.decompose(p_initial, rate_matrix_time)\n\nthird_decomposition.shape",
"_____no_output_____"
],
[
"for i in [0, 1, 2]:\n plt.plot(t_range, third_decomposition[i,0,:], label='$a_{}(t)$'.format(i + 1))\nplt.legend()",
"_____no_output_____"
]
],
[
[
"Decompose, for every time $t$, the corresponding point $\\left|p(t)\\right\\rangle$ using the temporal rate matrix $R(t)$",
"_____no_output_____"
]
],
[
[
"fourth_decomposition = md.decompose(trajectory, rate_matrix_time)\n\nfourth_decomposition.shape",
"_____no_output_____"
],
[
"for i in [0, 1, 2]:\n plt.plot(t_range, fourth_decomposition[i,0,:], label='$a_{}(t)$'.format(i + 1))\nplt.legend()",
"_____no_output_____"
]
],
[
[
"# Plotting the 2D probability simplex for three-state system",
"_____no_output_____"
],
[
"The probability space of a three-state system is a three dimensional space. However, the normalization constraint $\\sum_{i}p_i=1$ together with $0 < p_i \\le 1$, form a 2D triangular plane in which all of the possible probability points reside.",
"_____no_output_____"
],
[
"We'll start by importing the plotting module:",
"_____no_output_____"
]
],
[
[
"import markoviandynamics.plotting.plotting2d as plt2d\n\n# Use latex rendering\nplt2d.latex()",
"_____no_output_____"
]
],
[
[
"Plot the probability plane:",
"_____no_output_____"
]
],
[
[
"plt2d.figure(figsize=(7, 5.5))\nplt2d.equilibrium_line(equilibrium_line)\nplt2d.legend()",
"_____no_output_____"
]
],
[
[
"We can plot many objects on the probability plane, such as trajectories, points, and eigenvectors of the rate matrix:",
"_____no_output_____"
]
],
[
[
"# Final equilibrium point\np_final = sym_system.equilibrium(energies, 1.2)",
"_____no_output_____"
],
[
"plt2d.figure(focus=True, figsize=(7, 5.5))\nplt2d.equilibrium_line(equilibrium_line)\n\n# Plot trajectory\nplt2d.plot(trajectory, c='r', label=r'$\\left|p(t)\\right>$')\n\n# Initial & final points\nplt2d.point(p_initial, c='k', label=r'$\\left|p_0\\right>$')\nplt2d.point(p_final, c='r', label=r'$\\left|\\pi\\right>$')\n\n# Eigenvectors\nplt2d.eigenvectors(md.eigensystem(rate_matrix), kwargs_arrow={'zorder': 1})\n\nplt2d.legend()",
"_____no_output_____"
]
],
[
[
"Plot multiple trajectories at once:",
"_____no_output_____"
]
],
[
[
"# Create temperature sequence\ntemperature_range = np.logspace(np.log10(0.01), np.log10(10), 50)\n\n# Create the equilibrium line points\nequilibrium_line = sym_system.equilibrium(energies, temperature_range)\n\n# Create a trajectory for every point on ``equilibrium_line``\nequilibrium_line_trajectory = md.evolve(equilibrium_line, rate_matrix, t_range)",
"_____no_output_____"
],
[
"plt2d.figure(focus=True, figsize=(7, 5))\nplt2d.equilibrium_line(equilibrium_line)\nplt2d.plot(equilibrium_line_trajectory, c='g', alpha=0.2)\nplt2d.point(p_final, c='r', label=r'$\\left|\\pi\\right>$')\nplt2d.legend()",
"_____no_output_____"
],
[
"# Create a trajectory for every point on ``equilibrium_line``\nequilibrium_line_crazy_trajectory = md.evolve(equilibrium_line, rate_matrix_time, t_range)",
"_____no_output_____"
],
[
"plt2d.figure(focus=True, figsize=(7, 5))\nplt2d.equilibrium_line(equilibrium_line)\nplt2d.plot(equilibrium_line_crazy_trajectory, c='r', alpha=0.1)\nplt2d.text(p_final, r'Text $\\alpha$', delta_x=0.05)\nplt2d.legend()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cbd5c910df9040e9459e43776a71ffbffb52122a
| 7,674 |
ipynb
|
Jupyter Notebook
|
tutorials_jupyter/01-basics/logistic_regression/main.ipynb
|
AlxGeek/pytorch-tutorial
|
fb42c9880d95fe58cbff9734eb7f3fc6fcf8ab02
|
[
"MIT"
] | null | null | null |
tutorials_jupyter/01-basics/logistic_regression/main.ipynb
|
AlxGeek/pytorch-tutorial
|
fb42c9880d95fe58cbff9734eb7f3fc6fcf8ab02
|
[
"MIT"
] | null | null | null |
tutorials_jupyter/01-basics/logistic_regression/main.ipynb
|
AlxGeek/pytorch-tutorial
|
fb42c9880d95fe58cbff9734eb7f3fc6fcf8ab02
|
[
"MIT"
] | null | null | null | 26.738676 | 101 | 0.486839 |
[
[
[
"# Logistic Regression",
"_____no_output_____"
],
[
"Modules",
"_____no_output_____"
]
],
[
[
"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms",
"_____no_output_____"
]
],
[
[
"Hyper-parameters ",
"_____no_output_____"
]
],
[
[
"input_size = 784\nnum_classes = 10\nnum_epochs = 5\nbatch_size = 100\nlearning_rate = 0.001",
"_____no_output_____"
]
],
[
[
"MNIST dataset (images and labels)",
"_____no_output_____"
]
],
[
[
"train_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())",
"Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\nDownloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\nDownloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\nDownloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\nProcessing...\nDone!\n"
]
],
[
[
"Data loader (input pipeline)",
"_____no_output_____"
]
],
[
[
"train_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)",
"_____no_output_____"
]
],
[
[
"Logistic regression model",
"_____no_output_____"
]
],
[
[
"model = nn.Linear(input_size, num_classes)",
"_____no_output_____"
]
],
[
[
"Loss and optimizer\n\n`nn.CrossEntropyLoss()` computes softmax internally",
"_____no_output_____"
]
],
[
[
"criterion = nn.CrossEntropyLoss() \noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) ",
"_____no_output_____"
]
],
[
[
"Train the model",
"_____no_output_____"
]
],
[
[
"total_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n # Reshape images to (batch_size, input_size)\n images = images.reshape(-1, 28*28)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 100 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))",
"Epoch [1/5], Step [100/600], Loss: 2.2122\nEpoch [1/5], Step [200/600], Loss: 2.0889\nEpoch [1/5], Step [300/600], Loss: 2.0165\nEpoch [1/5], Step [400/600], Loss: 1.9407\nEpoch [1/5], Step [500/600], Loss: 1.8564\nEpoch [1/5], Step [600/600], Loss: 1.8237\nEpoch [2/5], Step [100/600], Loss: 1.7188\nEpoch [2/5], Step [200/600], Loss: 1.6249\nEpoch [2/5], Step [300/600], Loss: 1.5657\nEpoch [2/5], Step [400/600], Loss: 1.5601\nEpoch [2/5], Step [500/600], Loss: 1.4386\nEpoch [2/5], Step [600/600], Loss: 1.5124\nEpoch [3/5], Step [100/600], Loss: 1.4313\nEpoch [3/5], Step [200/600], Loss: 1.3220\nEpoch [3/5], Step [300/600], Loss: 1.4177\nEpoch [3/5], Step [400/600], Loss: 1.2768\nEpoch [3/5], Step [500/600], Loss: 1.2609\nEpoch [3/5], Step [600/600], Loss: 1.3218\nEpoch [4/5], Step [100/600], Loss: 1.2181\nEpoch [4/5], Step [200/600], Loss: 1.1998\nEpoch [4/5], Step [300/600], Loss: 1.2113\nEpoch [4/5], Step [400/600], Loss: 1.1474\nEpoch [4/5], Step [500/600], Loss: 1.2270\nEpoch [4/5], Step [600/600], Loss: 1.1559\nEpoch [5/5], Step [100/600], Loss: 1.0965\nEpoch [5/5], Step [200/600], Loss: 1.1190\nEpoch [5/5], Step [300/600], Loss: 1.0574\nEpoch [5/5], Step [400/600], Loss: 0.9847\nEpoch [5/5], Step [500/600], Loss: 1.0934\nEpoch [5/5], Step [600/600], Loss: 0.9374\n"
]
],
[
[
"Test the model\n\nIn test phase, we don't need to compute gradients (for memory efficiency)",
"_____no_output_____"
]
],
[
[
"with torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.reshape(-1, 28*28)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n\n print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))",
"Accuracy of the model on the 10000 test images: 83 %\n"
]
],
[
[
"Save the model checkpoint",
"_____no_output_____"
]
],
[
[
"torch.save(model.state_dict(), 'model.ckpt')",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd5d00b2ce808247ebfd0eed2d5c315d7be435b
| 1,296 |
ipynb
|
Jupyter Notebook
|
jupyter/examples/instrumentControl/HP3458A.ipynb
|
PhilippCo/meas_rpi
|
46f1c4eb72baab79957bbb7294079a722d198b43
|
[
"MIT"
] | 3 |
2021-08-25T15:15:48.000Z
|
2022-02-07T10:21:47.000Z
|
jupyter/examples/instrumentControl/HP3458A.ipynb
|
PhilippCo/meas_rpi
|
46f1c4eb72baab79957bbb7294079a722d198b43
|
[
"MIT"
] | null | null | null |
jupyter/examples/instrumentControl/HP3458A.ipynb
|
PhilippCo/meas_rpi
|
46f1c4eb72baab79957bbb7294079a722d198b43
|
[
"MIT"
] | null | null | null | 17.513514 | 48 | 0.516975 |
[
[
[
"import testgear",
"_____no_output_____"
],
[
"inst = testgear.HPAK.HP3458A(gpib=22)",
"_____no_output_____"
],
[
"inst",
"_____no_output_____"
],
[
"inst.get_reading()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
cbd5d2d2a70faa56136a87c3ec5004533e6195da
| 349,762 |
ipynb
|
Jupyter Notebook
|
Tutorials/tuto_Machine.ipynb
|
stephane-eisen/pyleecan
|
8444b8131c9eff11a616da8277fb1f280c8f70e5
|
[
"Apache-2.0"
] | 95 |
2019-01-23T04:19:45.000Z
|
2022-03-17T18:22:10.000Z
|
Tutorials/tuto_Machine.ipynb
|
ecs-kev/pyleecan
|
1faedde4b24acc6361fa1fdd4e980eaec4ca3a62
|
[
"Apache-2.0"
] | 366 |
2019-02-20T07:15:08.000Z
|
2022-03-31T13:37:23.000Z
|
Tutorials/tuto_Machine.ipynb
|
ecs-kev/pyleecan
|
1faedde4b24acc6361fa1fdd4e980eaec4ca3a62
|
[
"Apache-2.0"
] | 74 |
2019-01-24T01:47:31.000Z
|
2022-02-25T05:44:42.000Z
| 120.151838 | 82,661 | 0.796985 |
[
[
[
"# Version information",
"_____no_output_____"
]
],
[
[
"from datetime import date\nprint(\"Running date:\", date.today().strftime(\"%B %d, %Y\"))\nimport pyleecan\nprint(\"Pyleecan version:\" + pyleecan.__version__)\nimport SciDataTool\nprint(\"SciDataTool version:\" + SciDataTool.__version__)",
"_____no_output_____"
]
],
[
[
"\n# How to define a machine\n\nThis tutorial shows the different ways to define electrical machine. To do so, it presents the definition of the **Toyota Prius 2004** interior magnet with distributed winding \\[1\\].\n\nThe notebook related to this tutorial is available on [GitHub](https://github.com/Eomys/pyleecan/tree/master/Tutorials/tuto_Machine.ipynb).\n\n## Type of machines Pyleecan can model\nPyleecan handles the geometrical modelling of main 2D radial flux machines such as: \n- surface or interior permanent magnet machines (SPMSM, IPMSM) \n- synchronous reluctance machines (SynRM) \n- squirrel-cage induction machines and doubly-fed induction machines (SCIM, DFIM) \n- would rotor synchronous machines and salient pole synchronous machines (WSRM) \n- switched reluctance machines (SRM) \n\nThe architecture of Pyleecan also enables to define other kinds of machines (with more than two laminations for instance). More information in our ICEM 2020 pyblication \\[2\\]\n\nEvery machine can be defined by using the **Graphical User Interface** or directly in **Python script**.\n\n## Defining machine with Pyleecan GUI \nThe GUI is the easiest way to define machine in Pyleecan. Its purpose is to create or load a machine and save it in JSON format to be loaded in a python script. The interface enables to define step by step in a user-friendly way every characteristics of the machine such as: \n- topology \n- dimensions \n- materials \n- winding \n\nEach parameter is explained by a tooltip and the machine can be previewed at each stage of the design.\n",
"_____no_output_____"
],
[
"## Start the GUI\nThe GUI can be started by running the following command in a notebook:\n```python\n# Start Pyleecan GUI from the Jupyter Notebook\n%run -m pyleecan\n```\nTo use it on Anaconda you may need to create the system variable:\n\nQT_QPA_PLATFORM_PLUGIN_PATH : path\\to\\anaconda3\\Lib\\site-packages\\PySide2\\plugins\\platforms\n\nThe GUI can also be launched in a terminal by calling one of the following commands in a terminal:\n```\nPath/to/python.exe -m pyleecan\nPath/to/python3.exe -m pyleecan\n```",
"_____no_output_____"
],
[
"## load a machine\nOnce the machine defined in the GUI it can be loaded with the following commands:",
"_____no_output_____"
]
],
[
[
"%matplotlib notebook\n\n# Load the machine\nfrom os.path import join\nfrom pyleecan.Functions.load import load\nfrom pyleecan.definitions import DATA_DIR\n\nIPMSM_A = load(join(DATA_DIR, \"Machine\", \"Toyota_Prius.json\"))\nIPMSM_A.plot()",
"_____no_output_____"
]
],
[
[
"## Defining Machine in scripting mode \nPyleecan also enables to define the machine in scripting mode, using different classes. Each class is defined from a csv file in the folder _pyleecan/Generator/ClasseRef_ and the documentation of every class is available on the dedicated [webpage](https://www.pyleecan.org/pyleecan.Classes.html).\nThe following image shows the machine classes organization : \n\n\n\nEvery rotor and stator can be created with the **Lamination** class or one of its daughters. \n\n\n\nThe scripting enables to define some complex and exotic machine that can't be defined in the GUI such as this one:",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.MachineUD import MachineUD\nfrom pyleecan.Classes.LamSlotWind import LamSlotWind\nfrom pyleecan.Classes.LamSlot import LamSlot\nfrom pyleecan.Classes.WindingCW2LT import WindingCW2LT\nfrom pyleecan.Classes.SlotW10 import SlotW10\nfrom pyleecan.Classes.SlotW22 import SlotW22\nfrom numpy import pi\n\nmachine = MachineUD(name=\"4 laminations machine\")\n\n# Main geometry parameter\nRext = 170e-3 # Exterior radius of outter lamination\nW1 = 30e-3 # Width of first lamination\nA1 = 2.5e-3 # Width of the first airgap\nW2 = 20e-3\nA2 = 10e-3\nW3 = 20e-3\nA3 = 2.5e-3\nW4 = 60e-3\n\n# Outer stator\nlam1 = LamSlotWind(Rext=Rext, Rint=Rext - W1, is_internal=False, is_stator=True)\nlam1.slot = SlotW22(\n Zs=12, W0=2 * pi / 12 * 0.75, W2=2 * pi / 12 * 0.75, H0=0, H2=W1 * 0.65\n)\nlam1.winding = WindingCW2LT(qs=3, p=3)\n# Outer rotor\nlam2 = LamSlot(\n Rext=lam1.Rint - A1, Rint=lam1.Rint - A1 - W2, is_internal=True, is_stator=False\n)\nlam2.slot = SlotW10(Zs=22, W0=25e-3, W1=25e-3, W2=15e-3, H0=0, H1=0, H2=W2 * 0.75)\n# Inner rotor\nlam3 = LamSlot(\n Rext=lam2.Rint - A2,\n Rint=lam2.Rint - A2 - W3,\n is_internal=False,\n is_stator=False,\n)\nlam3.slot = SlotW10(\n Zs=22, W0=17.5e-3, W1=17.5e-3, W2=12.5e-3, H0=0, H1=0, H2=W3 * 0.75\n)\n# Inner stator\nlam4 = LamSlotWind(\n Rext=lam3.Rint - A3, Rint=lam3.Rint - A3 - W4, is_internal=True, is_stator=True\n)\nlam4.slot = SlotW10(Zs=12, W0=25e-3, W1=25e-3, W2=1e-3, H0=0, H1=0, H2=W4 * 0.75)\nlam4.winding = WindingCW2LT(qs=3, p=3)\n# Machine definition\nmachine.lam_list = [lam1, lam2, lam3, lam4]\n\n# Plot, check and save\nmachine.plot()",
"_____no_output_____"
]
],
[
[
"## Stator definition\nTo define the stator, we initialize a [**LamSlotWind**](http://pyleecan.org/pyleecan.Classes.LamSlotWind.html) object with the different parameters. In pyleecan, all the parameters must be set in SI units.",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.LamSlotWind import LamSlotWind\nmm = 1e-3 # Millimeter\n\n\n# Lamination setup\nstator = LamSlotWind(\n Rint=80.95 * mm, # internal radius [m]\n Rext=134.62 * mm, # external radius [m]\n L1=83.82 * mm, # Lamination stack active length [m] without radial ventilation airducts \n # but including insulation layers between lamination sheets\n Nrvd=0, # Number of radial air ventilation duct\n Kf1=0.95, # Lamination stacking / packing factor\n is_internal=False,\n is_stator=True, \n)",
"_____no_output_____"
]
],
[
[
"Then we add 48 slots using [**SlotW11**](http://pyleecan.org/pyleecan.Classes.SlotW11.html) which is one of the 25 Slot classes: ",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.SlotW11 import SlotW11\n\n# Slot setup\nstator.slot = SlotW11(\n Zs=48, # Slot number\n H0=1.0 * mm, # Slot isthmus height\n H1=0, # Height\n H2=33.3 * mm, # Slot height below wedge \n W0=1.93 * mm, # Slot isthmus width\n W1=5 * mm, # Slot top width\n W2=8 * mm, # Slot bottom width\n R1=4 * mm # Slot bottom radius\n)",
"_____no_output_____"
]
],
[
[
"As for the slot, we can define the winding and its conductor with [**WindingDW1L**](http://pyleecan.org/pyleecan.Classes.WindingDW1L.html) and [**CondType11**](http://pyleecan.org/pyleecan.Classes.CondType11.html). The conventions for winding are further explained on [pyleecan website](https://pyleecan.org/winding.convention.html)",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.WindingDW1L import WindingDW1L\nfrom pyleecan.Classes.CondType11 import CondType11\n# Winding setup\nstator.winding = WindingDW1L(\n qs=3, # number of phases\n Lewout=0, # staight length of conductor outside lamination before EW-bend\n p=4, # number of pole pairs\n Ntcoil=9, # number of turns per coil\n Npcp=1, # number of parallel circuits per phase\n Nslot_shift_wind=0, # 0 not to change the stator winding connection matrix built by pyleecan number \n # of slots to shift the coils obtained with pyleecan winding algorithm \n # (a, b, c becomes b, c, a with Nslot_shift_wind1=1)\n is_reverse_wind=False # True to reverse the default winding algorithm along the airgap \n # (c, b, a instead of a, b, c along the trigonometric direction)\n)\n\n# Conductor setup\nstator.winding.conductor = CondType11(\n Nwppc_tan=1, # stator winding number of preformed wires (strands) \n # in parallel per coil along tangential (horizontal) direction\n Nwppc_rad=1, # stator winding number of preformed wires (strands) \n # in parallel per coil along radial (vertical) direction\n Wwire=0.000912, # single wire width without insulation [m]\n Hwire=2e-3, # single wire height without insulation [m]\n Wins_wire=1e-6, # winding strand insulation thickness [m]\n type_winding_shape=0, # type of winding shape for end winding length calculation\n # 0 for hairpin windings\n # 1 for normal windings\n)",
"_____no_output_____"
]
],
[
[
"## Rotor definition\n\nFor this example, we use the [**LamHole**](http://www.pyleecan.org/pyleecan.Classes.LamHole.html) class to define the rotor as a lamination with holes to contain magnet.\n\nIn the same way as for the stator, we start by defining the lamination:",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.LamHole import LamHole\n\n# Rotor setup\nrotor = LamHole(\n Rint=55.32 * mm, # Internal radius\n Rext=80.2 * mm, # external radius\n is_internal=True, \n is_stator=False,\n L1=stator.L1 # Lamination stack active length [m] \n # without radial ventilation airducts but including insulation layers between lamination sheets\n)",
"_____no_output_____"
]
],
[
[
"After that, we can add holes with magnets to the rotor using the class [**HoleM50**](http://www.pyleecan.org/pyleecan.Classes.HoleM50.html): ",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.HoleM50 import HoleM50\nrotor.hole = list()\nrotor.hole.append(\n HoleM50(\n Zh=8, # Number of Hole around the circumference\n W0=42.0 * mm, # Slot opening\n W1=0, # Tooth width (at V bottom)\n W2=0, # Distance Magnet to bottom of the V\n W3=14.0 * mm, # Tooth width (at V top)\n W4=18.9 * mm, # Magnet Width\n H0=10.96 * mm, # Slot Depth\n H1=1.5 * mm, # Distance from the lamination Bore\n H2=1 * mm, # Additional depth for the magnet\n H3=6.5 * mm, # Magnet Height\n H4=0, # Slot top height\n )\n)",
"_____no_output_____"
]
],
[
[
"The holes are defined as a list to enable to create several layers of holes and/or to combine different kinds of holes\n\n## Create a shaft and a frame\n\nThe classes [**Shaft**](http://www.pyleecan.org/pyleecan.Classes.Shaft.html) and [**Frame**](http://www.pyleecan.org/pyleecan.Classes.Frame.html) enable to add a shaft and a frame to the machine. For this example there is no frame:",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.Shaft import Shaft\nfrom pyleecan.Classes.Frame import Frame\n\n# Set shaft\nshaft = Shaft(Drsh=rotor.Rint * 2, # Diamater of the rotor shaft [m]\n # used to estimate bearing diameter for friction losses\n Lshaft=1.2 # length of the rotor shaft [m] \n )\nframe = None",
"_____no_output_____"
]
],
[
[
"## Set materials and magnets\n\nEvery Pyleecan object can be saved in JSON using the method `save` and can be loaded with the `load` function.\nIn this example, the materials *M400_50A* and *Copper1* are loaded and set in the corresponding properties.",
"_____no_output_____"
]
],
[
[
"# Loading Materials \nM400_50A = load(join(DATA_DIR, \"Material\", \"M400-50A.json\"))\nCopper1 = load(join(DATA_DIR, \"Material\", \"Copper1.json\"))\n\n# Set Materials\nstator.mat_type = M400_50A # Stator Lamination material\nrotor.mat_type = M400_50A # Rotor Lamination material\nstator.winding.conductor.cond_mat = Copper1 # Stator winding conductor material",
"_____no_output_____"
]
],
[
[
"A material can also be defined in scripting as any other Pyleecan object. The material *Magnet_prius* is created with the classes [**Material**](http://www.pyleecan.org/pyleecan.Classes.Material.html) and [**MatMagnetics**](http://www.pyleecan.org/pyleecan.Classes.MatMagnetics.html).",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.Material import Material\nfrom pyleecan.Classes.MatMagnetics import MatMagnetics\n\n# Defining magnets\nMagnet_prius = Material(name=\"Magnet_prius\")\n\n# Definition of the magnetic properties of the material\nMagnet_prius.mag = MatMagnetics(\n mur_lin = 1.05, # Relative magnetic permeability\n Hc = 902181.163126629, # Coercitivity field [A/m]\n alpha_Br = -0.001, # temperature coefficient for remanent flux density /°C compared to 20°C\n Brm20 = 1.24, # magnet remanence induction at 20°C [T]\n Wlam = 0, # lamination sheet width without insulation [m] (0 == not laminated)\n)\n\n# Definition of the electric properties of the material \nMagnet_prius.elec.rho = 1.6e-06 # Resistivity at 20°C\n\n# Definition of the structural properties of the material\nMagnet_prius.struct.rho = 7500.0 # mass per unit volume [kg/m3]",
"_____no_output_____"
]
],
[
[
"The magnet materials are set with the \"magnet_X\" property. Pyleecan enables to define different magnetization or material for each magnets of the holes. Here both magnets are defined identical.",
"_____no_output_____"
]
],
[
[
"# Set magnets in the rotor hole\nrotor.hole[0].magnet_0.mat_type = Magnet_prius\nrotor.hole[0].magnet_1.mat_type = Magnet_prius\nrotor.hole[0].magnet_0.type_magnetization = 1\nrotor.hole[0].magnet_1.type_magnetization = 1",
"_____no_output_____"
]
],
[
[
"## Create, save and plot the machine\nFinally, the Machine object can be created with [**MachineIPMSM**](http://www.pyleecan.org/pyleecan.Classes.MachineIPMSM.html) and saved using the `save` method.",
"_____no_output_____"
]
],
[
[
"from pyleecan.Classes.MachineIPMSM import MachineIPMSM\n\n%matplotlib notebook\nIPMSM_Prius_2004 = MachineIPMSM(\n name=\"Toyota Prius 2004\", \n stator=stator, \n rotor=rotor, \n shaft=shaft, \n frame=frame # None\n)\nIPMSM_Prius_2004.save('IPMSM_Toyota_Prius_2004.json')\n\nim=IPMSM_Prius_2004.plot()",
"[13:59:25] Saving in IPMSM_Toyota_Prius_2004.json\n"
]
],
[
[
"Note that Pyleecan also handles ventilation duct thanks to the classes : \n- [**VentilationCirc**](http://www.pyleecan.org/pyleecan.Classes.VentilationCirc.html) \n- [**VentilationPolar**](http://www.pyleecan.org/pyleecan.Classes.VentilationPolar.html) \n- [**VentilationTrap**](http://www.pyleecan.org/pyleecan.Classes.VentilationTrap.html) ",
"_____no_output_____"
],
[
"[1] Z. Yang, M. Krishnamurthy and I. P. Brown, \"Electromagnetic and vibrational characteristic of IPM over full torque-speed range\", *2013 International Electric Machines & Drives Conference*, Chicago, IL, 2013, pp. 295-302.\n\n[2] P. Bonneel, J. Le Besnerais, E. Devillers, C. Marinel, and R. Pile, “Design Optimization of Innovative Electrical Machines Topologies Based on Pyleecan Opensource Object-Oriented Software,” in 24th International Conference on Electrical Machines (ICEM), 2020.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbd5d770b01ee83ceb671ac7fcab1b14db1860d3
| 6,602 |
ipynb
|
Jupyter Notebook
|
chapter1/homework/localization/3-22/201611680049(3).ipynb
|
hpishacker/python_tutorial
|
9005f0db9dae10bdc1d1c3e9e5cf2268036cd5bd
|
[
"MIT"
] | 76 |
2017-09-26T01:07:26.000Z
|
2021-02-23T03:06:25.000Z
|
chapter1/homework/localization/3-22/201611680049(3).ipynb
|
hpishacker/python_tutorial
|
9005f0db9dae10bdc1d1c3e9e5cf2268036cd5bd
|
[
"MIT"
] | 5 |
2017-12-10T08:40:11.000Z
|
2020-01-10T03:39:21.000Z
|
chapter1/homework/localization/3-22/201611680049(3).ipynb
|
hacker-14/python_tutorial
|
4a110b12aaab1313ded253f5207ff263d85e1b56
|
[
"MIT"
] | 112 |
2017-09-26T01:07:30.000Z
|
2021-11-25T19:46:51.000Z
| 23.748201 | 128 | 0.425326 |
[
[
[
"## 练习 1:写程序,可由键盘读入用户姓名例如Mr. right,让用户输入出生的月份与日期,判断用户星座,假设用户是金牛座,则输出,Mr. right,你是非常有性格的金牛座!。",
"_____no_output_____"
]
],
[
[
"name = input('请输入你的姓名')\nprint('你好',name)\nprint('请输入出生的月份与日期')\nmonth = int(input('月份:'))\ndate = int(input('日期:'))\n\nif month == 4:\n if date < 20:\n print(name, '你是白羊座')\n else:\n print(name,'你是非常有性格的金牛座')\n \nif month == 5:\n if date < 21:\n print(name, '你是非常有性格的金牛座')\n else:\n print(name,'你是双子座')\n \nif month == 6:\n if date < 22:\n print(name, '你是双子座')\n else:\n print(name,'你是巨蟹座')\n\nif month == 7:\n if date < 23:\n print(name, '你是巨蟹座')\n else:\n print(name,'你是狮子座')\n \nif month == 8:\n if date < 23:\n print(name, '你是狮子座')\n else:\n print(name,'你是处女座')\n \nif month == 9:\n if date < 24:\n print(name, '你是处女座')\n else:\n print(name,'你是天秤座')\n\nif month == 10:\n if date < 24:\n print(name, '你是天秤座')\n else:\n print(name,'你是天蝎座')\n \nif month == 11:\n if date < 23:\n print(name, '你是天蝎座')\n else:\n print(name,'你是射手座')\n \nif month == 12:\n if date < 22:\n print(name, '你是射手座')\n else:\n print(name,'你是摩羯座')\n \nif month == 1:\n if date < 20:\n print(name, '你是摩羯座')\n else:\n print(name,'你是水瓶座')\n \nif month == 2:\n if date < 19:\n print(name, '你是水瓶座')\n else:\n print(name,'你是双鱼座')\n \nif month == 3:\n if date < 22:\n print(name, '你是双鱼座')\n else:\n print(name,'你是白羊座')",
"_____no_output_____"
]
],
[
[
"## 练习 2:写程序,可由键盘读入两个整数m与n(n不等于0),询问用户意图,如果要求和则计算从m到n的和输出,如果要乘积则计算从m到n的积并输出,如果要求余数则计算m除以n的余数的值并输出,否则则计算m整除n的值并输出。",
"_____no_output_____"
]
],
[
[
"m = int(input('请输入一个整数,回车结束'))\nn = int(input('请输入一个整数,不为零'))\nintend = input('请输入计算意图,如 + * %')\nif m<n:\n min_number = m\nelse:\n min_number = n\ntotal = min_number\n\nif intend == '+':\n if m<n:\n while m<n:\n m = m + 1\n total = total + m\n print(total)\n else:\n while m > n:\n n = n + 1\n total = total + n\n print(total)\nelif intend == '*':\n if m<n:\n while m<n:\n m = m + 1\n total = total * m\n print(total)\n else:\n while m > n:\n n = n + 1\n total = total * n\n print(total)\nelif intend == '%':\n print(m % n)\nelse:\n print(m // n)",
"_____no_output_____"
]
],
[
[
"## 练习 3:写程序,能够根据北京雾霾PM2.5数值给出对应的防护建议。如当PM2.5数值大于500,则应该打开空气净化器,戴防雾霾口罩等。",
"_____no_output_____"
]
],
[
[
"number = int(input('现在北京的PM2.5指数是多少?请输入整数'))\n\nif number > 500:\n print('应该打开空气净化器,戴防雾霾口罩')\nelif 300 < number < 500:\n print('尽量呆在室内不出门,出门佩戴防雾霾口罩')\nelif 200 < number < 300:\n print('尽量不要进行户外活动')\nelif 100 < number < 200:\n print('轻度污染,可进行户外活动,可不佩戴口罩')\nelse:\n print('无须特别注意')",
"_____no_output_____"
]
],
[
[
"## 尝试性练习:写程序,能够在屏幕上显示空行。",
"_____no_output_____"
]
],
[
[
"print('空行是我')\nprint('空行是我')\nprint('空行是我')\nprint( )\nprint('我是空行')",
"_____no_output_____"
]
],
[
[
"## 练习 4:英文单词单数转复数,要求输入一个英文动词(单数形式),能够得到其复数形式,或给出单数转复数形式的建议",
"_____no_output_____"
]
],
[
[
"word = input('请输入一个单词,回车结束')\n\nif word.endswith('s') or word.endswith('sh') or word.endswith('ch') or word.endswith('x'):\n print(word,'es',sep = '')\n \nelif word.endswith('y'):\n if word.endswith('ay') or word.endswith('ey') or word.endswith('iy') or word.endswith('oy') or word.endswith('uy'):\n print(word,'s',sep = '')\n else:\n word = word[:-1]\n print(word,'ies',sep = '')\n \nelif word.endswith('f'):\n word = word[:-1]\n print(word,'ves',sep = '')\n \nelif word.endswith('fe'):\n word = word[:-2]\n print(word,'ves',sep = '')\n\nelif word.endswith('o'):\n print('词尾加s或者es')\n \nelse:\n print(word,'s',sep = '')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd5d7eaf148e76ab5007e1a4d6ad2f3244980e8
| 143,591 |
ipynb
|
Jupyter Notebook
|
projeto1/proj1-busca-supervisionada.ipynb
|
luizcartolano2/mc906
|
21ae809442bfd51f3f2e3cade6198287dd428232
|
[
"MIT"
] | null | null | null |
projeto1/proj1-busca-supervisionada.ipynb
|
luizcartolano2/mc906
|
21ae809442bfd51f3f2e3cade6198287dd428232
|
[
"MIT"
] | null | null | null |
projeto1/proj1-busca-supervisionada.ipynb
|
luizcartolano2/mc906
|
21ae809442bfd51f3f2e3cade6198287dd428232
|
[
"MIT"
] | null | null | null | 87.608908 | 23,400 | 0.769596 |
[
[
[
"# Buscas supervisionadas",
"_____no_output_____"
],
[
"## Imports",
"_____no_output_____"
]
],
[
[
"# imports necessarios\nfrom search import *\nfrom notebook import psource, heatmap, gaussian_kernel, show_map, final_path_colors, display_visual, plot_NQueens\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\nimport time\nfrom statistics import mean, stdev\nfrom math import sqrt\nfrom memory_profiler import memory_usage\n\n# Needed to hide warnings in the matplotlib sections\nimport warnings\nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
]
],
[
[
"## Criação do mapa e do grafo",
"_____no_output_____"
]
],
[
[
"# make the dict where the key is associated with his neighbors\nmapa = {}\nfor i in range(0,60):\n for j in range(0,60):\n mapa[(i,j)] = {(i+1,j):1, (i-1,j):1, (i,j+1):1, (i,j-1):1}\n \ngrafo = UndirectedGraph(mapa)",
"_____no_output_____"
]
],
[
[
"## Modelagem da classe problema",
"_____no_output_____"
]
],
[
[
"class RobotProblem(Problem):\n\n \"\"\"Problema para encontrar o goal saindo de uma posicao (x,y) com um robo.\"\"\"\n\n def __init__(self, initial, goal, mapa, graph):\n Problem.__init__(self, initial, goal)\n self.mapa = mapa\n self.graph = graph\n\n def actions(self, actual_pos):\n \"\"\"The actions at a graph node are just its neighbors.\"\"\"\n neighbors = list(self.graph.get(actual_pos).keys())\n valid_actions = []\n for act in neighbors:\n if act[0] == 0 or act[0] == 60 or act[1] == 0 or act[1] == 60:\n i = 1\n elif (act[0] == 20 and (0<= act[1] <= 40)):\n i = 2\n elif (act[0] == 40 and (20<= act[1] <= 60)):\n i = 3\n else:\n valid_actions.append(act)\n \n return valid_actions\n\n def result(self, state, action):\n \"\"\"The result of going to a neighbor is just that neighbor.\"\"\"\n return action\n\n def path_cost(self, cost_so_far, state1, action, state2):\n return cost_so_far + 1\n\n def goal_test(self, state):\n if state[0] == self.goal[0] and state[1] == self.goal[1]:\n return True\n else:\n return False\n \n def heuristic_1(self, node):\n \"\"\"h function is straight-line distance from a node's state to goal.\"\"\"\n locs = getattr(self.graph, 'locations', None)\n if locs:\n if type(node) is str:\n return int(distance(locs[node], locs[self.goal]))\n\n return int(distance(locs[node.state], locs[self.goal]))\n else:\n return infinity\n \n def heuristic_2(self,node):\n \"\"\" Manhattan Heuristic Function \"\"\"\n x1,y1 = node.state[0], node.state[1]\n x2,y2 = self.goal[0], self.goal[1]\n \n return abs(x2 - x1) + abs(y2 - y1)",
"_____no_output_____"
]
],
[
[
"## Busca supervisionada A*: Heuristica 1",
"_____no_output_____"
],
[
"### Calculo do consumo de memoria",
"_____no_output_____"
]
],
[
[
"def calc_memory_a_h1():\n init_pos = (10,10)\n goal_pos = (50,50)\n\n robot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\n node = astar_search(robot_problem, h=robot_problem.heuristic_1)",
"_____no_output_____"
],
[
"mem_usage = memory_usage(calc_memory_a_h1)",
"_____no_output_____"
],
[
"print('Memória usada (em intervalos de .1 segundos): %s' % mem_usage)\nprint('Maximo de memoria usada: %s' % max(mem_usage))",
"Memória usada (em intervalos de .1 segundos): [45.5390625, 45.6875, 45.9375, 46.11328125, 46.515625, 48.71484375, 54.1875, 60.69921875, 64.99609375, 78.73046875, 89.4375, 94.87109375, 97.34765625, 98.2578125, 98.234375]\nMaximo de memoria usada: 98.2578125\n"
]
],
[
[
"### Calculo do custo da busca e o caminho percorrido",
"_____no_output_____"
]
],
[
[
"init_pos = (10,10)\ngoal_pos = (50,50)\n\nrobot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\nnode = astar_search(robot_problem, h=robot_problem.heuristic_1)\nprint(\"Custo da busca A* com a primeira heuristica: \" + str(node.path_cost))",
"Custo da busca A* com a primeira heuristica: 142\n"
],
[
"list_nodes = []\nfor n in node.path():\n list_nodes.append(n.state)",
"_____no_output_____"
],
[
"x = []\ny = []\nfor nod in list_nodes:\n x.append(nod[0])\n y.append(nod[1])",
"_____no_output_____"
],
[
"fig = plt.figure()\nplt.xlim(0,60)\nplt.ylim(0,60)\nplt.title('Caminho percorrido pelo robo na busca A* com a primeira heuristica')\nplt.annotate(\"\",\n xy=(0,0), xycoords='data',\n xytext=(0, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.annotate(\"\",\n xy=(0,0), xycoords='data',\n xytext=(60, 0), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\n\nplt.annotate(\"\",\n xy=(60,0), xycoords='data',\n xytext=(60, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\n\nplt.annotate(\"\",\n xy=(0,60), xycoords='data',\n xytext=(60, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.annotate(\"\",\n xy=(40,20), xycoords='data',\n xytext=(40, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.annotate(\"\",\n xy=(20,0), xycoords='data',\n xytext=(20, 40), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.scatter(x,y)\nplt.scatter(10,10,color='r')\nplt.scatter(50,50,color='r')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Calculo do tempo gasto pelo A* com inicio em (10,10) e fim em (50,50) usando a heuristica 1",
"_____no_output_____"
]
],
[
[
"init_pos = (10,10)\ngoal_pos = (50,50)\n\nrobot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\n\ntimes = []\nfor i in range(0,1000):\n start = time.time()\n node = astar_search(robot_problem, h=robot_problem.heuristic_1)\n end = time.time()\n times.append(end - start)",
"_____no_output_____"
],
[
"media_a_1 = mean(times)\ndesvio_a_1 = stdev(times)\nintervalo_conf = '(' + str( media_a_1 - 1.96 * (desvio_a_1 / (len(times)) ** (1/2)) ) + ',' + str( media_a_1 + 1.96 * (desvio_a_1 / (len(times)) ** (1/2)) ) + ')'\nprint(\"Media do tempo gasto para a busca A* com a primeira heuristica: \" + str(media_a_1))\nprint(\"Desvio padrao do tempo gasto para a busca A* com a primeira heuristica: \" + str(desvio_a_1))\nprint(\"Intervalo de confiança para a busca A* com a primeira heuristica: \" + intervalo_conf)\nfig = plt.figure()\nplt.hist(times,bins=50)\nplt.title('Histograma para o tempo de execucao do A* com a primeira heuristica')\nplt.show()",
"Media do tempo gasto para a busca A* com a primeira heuristica: 0.29269154953956605\nDesvio padrao do tempo gasto para a busca A* com a primeira heuristica: 0.024914598492101866\nIntervalo de confiança para a busca A* com a primeira heuristica: (0.2911473267263827,0.2942357723527494)\n"
]
],
[
[
"### Projecao da relacao entre distancia em linha reta e tempo para o A* com a primeira heuristica",
"_____no_output_____"
]
],
[
[
"goal_pos = (50,50)\nx = []\ny = []\nfor i in range(5,50):\n for j in range(5,50):\n if i != 20 and i != 40:\n init_pos = (i,i)\n distancia_linha_reta = sqrt( (goal_pos[0] - init_pos[0]) ** 2 + (goal_pos[1] - init_pos[1]) ** 2)\n robot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\n start = time.time()\n node = astar_search(robot_problem, h=robot_problem.heuristic_1)\n end = time.time()\n x.append(distancia_linha_reta)\n y.append(end - start)",
"_____no_output_____"
],
[
"import pandas as pd\ndata = {'x':[], 'y':[]}\ndf = pd.DataFrame(data)\ndf['x'] = x\ndf['y'] = y\ndf",
"_____no_output_____"
],
[
"fig = plt.figure()\nplt.scatter(x,y)\nplt.ylim(0.2, 1)\nplt.title(\"Distancia em linha reta x Tempo A*-heuristica1\")\nplt.xlabel(\"Distancia em linha reta entre os pontos inicial e final\")\nplt.ylabel(\"Tempo da busca A* com a primeira heuristica\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Busca supervisionada A*: Heuristica 2",
"_____no_output_____"
],
[
"### Calculo do consumo de memoria",
"_____no_output_____"
]
],
[
[
"def calc_memory_a_h2():\n init_pos = (10,10)\n goal_pos = (50,50)\n\n robot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\n node = astar_search(robot_problem, h=robot_problem.heuristic_2)",
"_____no_output_____"
],
[
"mem_usage = memory_usage(calc_memory_a_h2)",
"_____no_output_____"
],
[
"print('Memória usada (em intervalos de .1 segundos): %s' % mem_usage)\nprint('Maximo de memoria usada: %s' % max(mem_usage))",
"Memória usada (em intervalos de .1 segundos): [98.23828125, 98.23828125, 98.23828125, 98.23828125, 98.36328125, 98.36328125]\nMaximo de memoria usada: 98.36328125\n"
]
],
[
[
"### Calculo do custo da busca e o caminho percorrido",
"_____no_output_____"
]
],
[
[
"init_pos = (10,10)\ngoal_pos = (50,50)\n\nrobot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\nnode = astar_search(robot_problem, h=robot_problem.heuristic_2)\nprint(\"Custo da busca A* com a segunda heuristica: \" + str(node.path_cost))",
"Custo da busca A* com a segunda heuristica: 124\n"
],
[
"list_nodes = []\nfor n in node.path():\n list_nodes.append(n.state)",
"_____no_output_____"
],
[
"x = []\ny = []\nfor nod in list_nodes:\n x.append(nod[0])\n y.append(nod[1])",
"_____no_output_____"
],
[
"fig = plt.figure()\nplt.xlim(0,60)\nplt.ylim(0,60)\nplt.title('Caminho percorrido pelo robo na busca A* com a segunda heuristica')\nplt.annotate(\"\",\n xy=(0,0), xycoords='data',\n xytext=(0, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.annotate(\"\",\n xy=(0,0), xycoords='data',\n xytext=(60, 0), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\n\nplt.annotate(\"\",\n xy=(60,0), xycoords='data',\n xytext=(60, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\n\nplt.annotate(\"\",\n xy=(0,60), xycoords='data',\n xytext=(60, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.annotate(\"\",\n xy=(40,20), xycoords='data',\n xytext=(40, 60), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.annotate(\"\",\n xy=(20,0), xycoords='data',\n xytext=(20, 40), textcoords='data',\n arrowprops=dict(arrowstyle=\"-\",\n edgecolor = \"black\",\n linewidth=5,\n alpha=0.65,\n connectionstyle=\"arc3,rad=0.\"),\n )\nplt.scatter(x,y)\nplt.scatter(10,10,color='r')\nplt.scatter(50,50,color='r')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Calculo do tempo gasto pelo A* com inicio em (10,10) e fim em (50,50) usando a heuristica 2",
"_____no_output_____"
]
],
[
[
"init_pos = (10,10)\ngoal_pos = (50,50)\n\nrobot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\n\ntimes = []\nfor i in range(0,1000):\n start = time.time()\n node = astar_search(robot_problem, h=robot_problem.heuristic_2)\n end = time.time()\n times.append(end - start)",
"_____no_output_____"
],
[
"media_a_2 = mean(times)\ndesvio_a_2 = stdev(times)\nintervalo_conf = '(' + str( media_a_2 - 1.96 * (desvio_a_2 / (len(times)) ** (1/2)) ) + ',' + str( media_a_2 + 1.96 * (desvio_a_2 / (len(times)) ** (1/2)) ) + ')'\nprint(\"Media do tempo gasto para a busca A* com a segunda heuristica: \" + str(media_a_2))\nprint(\"Desvio padrao do tempo gasto para a busca A* com a segunda heuristica: \" + str(desvio_a_2))\nprint(\"Intervalo de confiança para a busca A* com a segunda heuristica: \" + intervalo_conf)\nfig = plt.figure()\nplt.hist(times,bins=50)\nplt.title('Histograma para o tempo de execucao do A* com a segunda heuristica')\nplt.show()",
"Media do tempo gasto para a busca A* com a segunda heuristica: 0.3358131620883942\nDesvio padrao do tempo gasto para a busca A* com a segunda heuristica: 0.055225639891942596\nIntervalo de confiança para a busca A* com a segunda heuristica: (0.3323902414653378,0.33923608271145056)\n"
]
],
[
[
"### Projecao da relacao entre distancia em linha reta e tempo para o A* com a segunda heuristica",
"_____no_output_____"
]
],
[
[
"goal_pos = (50,50)\nx = []\ny = []\nfor i in range(5,50):\n for j in range(5,50):\n if i != 20 and i != 40:\n init_pos = (i,i)\n distancia_linha_reta = sqrt( (goal_pos[0] - init_pos[0]) ** 2 + (goal_pos[1] - init_pos[1]) ** 2)\n robot_problem = RobotProblem(init_pos, goal_pos, mapa, grafo)\n start = time.time()\n node = astar_search(robot_problem, h=robot_problem.heuristic_2)\n end = time.time()\n x.append(distancia_linha_reta)\n y.append(end - start)",
"_____no_output_____"
],
[
"import pandas as pd\ndata = {'x':[], 'y':[]}\ndf = pd.DataFrame(data)\ndf['x'] = x\ndf['y'] = y\ndf",
"_____no_output_____"
],
[
"fig = plt.figure()\nplt.scatter(x,y)\nplt.ylim(-0.05, 0.45)\nplt.title(\"Distancia em linha reta x Tempo A*-heuristica2\")\nplt.xlabel(\"Distancia em linha reta entre os pontos inicial e final\")\nplt.ylabel(\"Tempo da busca A* com a segunda heuristica\")\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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbd5e83237ac3d12c612760a395751dac3ed6461
| 3,106 |
ipynb
|
Jupyter Notebook
|
python3.6/Assignment01.ipynb
|
JJBong/python-link-e-learning
|
ecb281e70237f720c793dd49b1feb854456b37bf
|
[
"MIT"
] | null | null | null |
python3.6/Assignment01.ipynb
|
JJBong/python-link-e-learning
|
ecb281e70237f720c793dd49b1feb854456b37bf
|
[
"MIT"
] | null | null | null |
python3.6/Assignment01.ipynb
|
JJBong/python-link-e-learning
|
ecb281e70237f720c793dd49b1feb854456b37bf
|
[
"MIT"
] | 6 |
2020-09-04T10:16:59.000Z
|
2020-12-03T01:47:03.000Z
| 20.03871 | 159 | 0.467804 |
[
[
[
"***\n### Q1\n***",
"_____no_output_____"
],
[
"1000 ~ 9999 까지(1000과 9999도 계산에 포함)의 네 자리 숫자 가운데에 '10'을 포함하는 숫자의 갯수는?",
"_____no_output_____"
],
[
"#### Answer1",
"_____no_output_____"
],
[
"***\n### Q2\n***",
"_____no_output_____"
],
[
"10 ~ 99999 까지(10과 99999도 계산에 포함)의 숫자 가운데에 20의 배수이며 '080'을 포함하는 숫자의 갯수는?",
"_____no_output_____"
],
[
"#### Answer2",
"_____no_output_____"
],
[
"***\n### Q3\n***",
"_____no_output_____"
],
[
"d = {'Hospital':0, 'PostOffice':1, 'Phamacy':2, 'School':3, 'Home':4, 'Convenience':5, 'DepartmentStore':6, 'BeautySalon':7, 'Lotteria':8}는 사전 자료형이며, \n각 element의 key는 건물 이름을 의미하고 value는 아래 'map'에서 건물의 위치를 의미한다.\n'철수'는 매일 집에서 09:00에 나와서 정확히 30분마다 인접한 건물로 이동한다고 했을 때, 18:00에 'Hospital'에 있을 확률 p(0.0 <= p <= 1.0)는 얼마인가? \n'철수'는 30분마다 꼭 인접한 건물로 이동해야하며(같은 건물에 30분을 초과하여 체류할 수 없음) 대각선에 위치한 건물로는 이동할 수 없다고 가정한다.",
"_____no_output_____"
],
[
"| |map| |\n|:--:|:--:|:--:|\n|0 |1 |2 |\n|3 |4 |5 |\n|6 |7 |8 |",
"_____no_output_____"
]
],
[
[
"d = {'Hospital':0, 'PostOffice':1, 'Phamacy':2, 'School':3, 'Home':4, 'Convenience':5, 'DepartmentStore':6, 'BeautySalon':7, 'Lotteria':8}\nprint(d)",
"{'Hospital': 0, 'PostOffice': 1, 'Phamacy': 2, 'School': 3, 'Home': 4, 'Convenience': 5, 'DepartmentStore': 6, 'BeautySalon': 7, 'Lotteria': 8}\n"
]
],
[
[
"#### Answer3",
"_____no_output_____"
],
[
" 2020.09.10 Q1 ~ Q3 by Jubong Kim",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbd5f017fbe9a7576d967d96d401de7a09e9f6d5
| 472,240 |
ipynb
|
Jupyter Notebook
|
Models/RFCN.ipynb
|
alifiaharmd/Malaria-Detection
|
846b2d50d483b27e32c07f742277227d50d97500
|
[
"Unlicense"
] | null | null | null |
Models/RFCN.ipynb
|
alifiaharmd/Malaria-Detection
|
846b2d50d483b27e32c07f742277227d50d97500
|
[
"Unlicense"
] | null | null | null |
Models/RFCN.ipynb
|
alifiaharmd/Malaria-Detection
|
846b2d50d483b27e32c07f742277227d50d97500
|
[
"Unlicense"
] | null | null | null | 472,240 | 472,240 | 0.801667 |
[
[
[
"\"\"\"The file needed to run this notebook can be accessed from the following folder using a UTS email account:\nhttps://drive.google.com/drive/folders/1y6e1Z2SbLDKkmvK3-tyQ6INO5rrzT3jp\n\"\"\"",
"_____no_output_____"
]
],
[
[
"# Object Detection Using RFCN\n\n## Tutorial:\n1. Image annotation using LabelImg\n2. Conversion of annotation & images into tfrecords\n3. Configuration of SSD config model file\n4. Training the model\n5. Using trained model for inference\n\n## Tasks for this week:\n\n1. installation of Google Object Detection API and required packages\n2. Conversion of images and xml into tfrecord. i.e. train tfrecord, test tfrecord\n3. Training: Transfer learning from already trained models\n4. Freezing a trained model and export it for inference\n",
"_____no_output_____"
],
[
"##Task-1: Installation of Google Object Detection API and required packages\n\n\n",
"_____no_output_____"
],
[
"### Step 1: Import packages\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"%tensorflow_version 1.x \n!pip install numpy==1.17.4",
"TensorFlow 1.x selected.\nRequirement already satisfied: numpy==1.17.4 in /usr/local/lib/python3.6/dist-packages (1.17.4)\n"
],
[
"import os\nimport re\nimport tensorflow as tf",
"_____no_output_____"
],
[
"print(tf.__version__)",
"1.15.2\n"
],
[
"pip install --upgrade tf_slim",
"Collecting tf_slim\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)\n\r\u001b[K |█ | 10kB 25.6MB/s eta 0:00:01\r\u001b[K |█▉ | 20kB 1.7MB/s eta 0:00:01\r\u001b[K |██▉ | 30kB 2.3MB/s eta 0:00:01\r\u001b[K |███▊ | 40kB 2.5MB/s eta 0:00:01\r\u001b[K |████▋ | 51kB 2.0MB/s eta 0:00:01\r\u001b[K |█████▋ | 61kB 2.3MB/s eta 0:00:01\r\u001b[K |██████▌ | 71kB 2.5MB/s eta 0:00:01\r\u001b[K |███████▌ | 81kB 2.7MB/s eta 0:00:01\r\u001b[K |████████▍ | 92kB 2.9MB/s eta 0:00:01\r\u001b[K |█████████▎ | 102kB 2.8MB/s eta 0:00:01\r\u001b[K |██████████▎ | 112kB 2.8MB/s eta 0:00:01\r\u001b[K |███████████▏ | 122kB 2.8MB/s eta 0:00:01\r\u001b[K |████████████ | 133kB 2.8MB/s eta 0:00:01\r\u001b[K |█████████████ | 143kB 2.8MB/s eta 0:00:01\r\u001b[K |██████████████ | 153kB 2.8MB/s eta 0:00:01\r\u001b[K |███████████████ | 163kB 2.8MB/s eta 0:00:01\r\u001b[K |███████████████▉ | 174kB 2.8MB/s eta 0:00:01\r\u001b[K |████████████████▊ | 184kB 2.8MB/s eta 0:00:01\r\u001b[K |█████████████████▊ | 194kB 2.8MB/s eta 0:00:01\r\u001b[K |██████████████████▋ | 204kB 2.8MB/s eta 0:00:01\r\u001b[K |███████████████████▌ | 215kB 2.8MB/s eta 0:00:01\r\u001b[K |████████████████████▌ | 225kB 2.8MB/s eta 0:00:01\r\u001b[K |█████████████████████▍ | 235kB 2.8MB/s eta 0:00:01\r\u001b[K |██████████████████████▍ | 245kB 2.8MB/s eta 0:00:01\r\u001b[K |███████████████████████▎ | 256kB 2.8MB/s eta 0:00:01\r\u001b[K |████████████████████████▏ | 266kB 2.8MB/s eta 0:00:01\r\u001b[K |█████████████████████████▏ | 276kB 2.8MB/s eta 0:00:01\r\u001b[K |██████████████████████████ | 286kB 2.8MB/s eta 0:00:01\r\u001b[K |███████████████████████████ | 296kB 2.8MB/s eta 0:00:01\r\u001b[K |████████████████████████████ | 307kB 2.8MB/s eta 0:00:01\r\u001b[K |████████████████████████████▉ | 317kB 2.8MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▉ | 327kB 2.8MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▊ | 337kB 2.8MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▋| 348kB 2.8MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 358kB 2.8MB/s \n\u001b[?25hRequirement already satisfied, skipping upgrade: absl-py>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from tf_slim) (0.9.0)\nRequirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from absl-py>=0.2.2->tf_slim) (1.12.0)\nInstalling collected packages: tf-slim\nSuccessfully installed tf-slim-1.1.0\n"
]
],
[
[
"### Step 2: Initial Configuration to Select model config file and selection of other hyperparameters",
"_____no_output_____"
]
],
[
[
"# If you forked the repository, you can replace the link.\nrepo_url = 'https://github.com/Tony607/object_detection_demo'\n\n# Number of training steps.\nnum_steps = 7000\n\n# Number of evaluation steps.\nnum_eval_steps = 100\n\nMODELS_CONFIG = {\n 'rfcn_resnet101': {\n 'model_name': 'rfcn_resnet101_coco_2018_01_28',\n 'pipeline_file': 'rfcn_resnet101_pets.config',\n 'batch_size': 8\n }\n}\n\n# Pick the model you want to use\n\nselected_model = 'rfcn_resnet101'\n\n# Name of the object detection model to use.\nMODEL = MODELS_CONFIG[selected_model]['model_name']\n\n# Name of the pipline file in tensorflow object detection API.\npipeline_file = MODELS_CONFIG[selected_model]['pipeline_file']\n\n# Training batch size fits in Colabe's Tesla K80 GPU memory for selected model.\nbatch_size = MODELS_CONFIG[selected_model]['batch_size']",
"_____no_output_____"
],
[
"%cd /content\n\nrepo_dir_path = os.path.abspath(os.path.join('.', os.path.basename(repo_url)))\n\n!git clone {repo_url}\n%cd {repo_dir_path}\n!git pull",
"/content\nCloning into 'object_detection_demo'...\nremote: Enumerating objects: 124, done.\u001b[K\nremote: Total 124 (delta 0), reused 0 (delta 0), pack-reused 124\u001b[K\nReceiving objects: 100% (124/124), 11.16 MiB | 36.39 MiB/s, done.\nResolving deltas: 100% (45/45), done.\n/content/object_detection_demo\nAlready up to date.\n"
]
],
[
[
"### Step 3: Download Google Object Detection API and other dependencies",
"_____no_output_____"
]
],
[
[
"%cd /content\n\n#!git clone --quiet https://github.com/tensorflow/models.git\n\n!git clone --branch r1.13.0 --depth 1 https://github.com/tensorflow/models.git\n\n!apt-get install -qq protobuf-compiler python-pil python-lxml python-tk\n\n!pip install -q Cython contextlib2 pillow lxml matplotlib\n\n!pip install -q pycocotools\n\n%cd /content/models/research\n!protoc object_detection/protos/*.proto --python_out=.\n\nimport os\nos.environ['PYTHONPATH'] += ':/content/models/research/:/content/models/research/slim/'\n\n!python object_detection/builders/model_builder_test.py",
"/content\nCloning into 'models'...\nremote: Enumerating objects: 2927, done.\u001b[K\nremote: Counting objects: 100% (2927/2927), done.\u001b[K\nremote: Compressing objects: 100% (2449/2449), done.\u001b[K\nremote: Total 2927 (delta 509), reused 2035 (delta 403), pack-reused 0\u001b[K\nReceiving objects: 100% (2927/2927), 369.04 MiB | 40.73 MiB/s, done.\nResolving deltas: 100% (509/509), done.\nChecking out files: 100% (2768/2768), done.\nSelecting previously unselected package python-bs4.\n(Reading database ... 144328 files and directories currently installed.)\nPreparing to unpack .../0-python-bs4_4.6.0-1_all.deb ...\nUnpacking python-bs4 (4.6.0-1) ...\nSelecting previously unselected package python-pkg-resources.\nPreparing to unpack .../1-python-pkg-resources_39.0.1-2_all.deb ...\nUnpacking python-pkg-resources (39.0.1-2) ...\nSelecting previously unselected package python-chardet.\nPreparing to unpack .../2-python-chardet_3.0.4-1_all.deb ...\nUnpacking python-chardet (3.0.4-1) ...\nSelecting previously unselected package python-six.\nPreparing to unpack .../3-python-six_1.11.0-2_all.deb ...\nUnpacking python-six (1.11.0-2) ...\nSelecting previously unselected package python-webencodings.\nPreparing to unpack .../4-python-webencodings_0.5-2_all.deb ...\nUnpacking python-webencodings (0.5-2) ...\nSelecting previously unselected package python-html5lib.\nPreparing to unpack .../5-python-html5lib_0.999999999-1_all.deb ...\nUnpacking python-html5lib (0.999999999-1) ...\nSelecting previously unselected package python-lxml:amd64.\nPreparing to unpack .../6-python-lxml_4.2.1-1ubuntu0.1_amd64.deb ...\nUnpacking python-lxml:amd64 (4.2.1-1ubuntu0.1) ...\nSelecting previously unselected package python-olefile.\nPreparing to unpack .../7-python-olefile_0.45.1-1_all.deb ...\nUnpacking python-olefile (0.45.1-1) ...\nSelecting previously unselected package python-pil:amd64.\nPreparing to unpack .../8-python-pil_5.1.0-1ubuntu0.2_amd64.deb ...\nUnpacking python-pil:amd64 (5.1.0-1ubuntu0.2) ...\nSetting up python-pkg-resources (39.0.1-2) ...\nSetting up python-six (1.11.0-2) ...\nSetting up python-bs4 (4.6.0-1) ...\nSetting up python-lxml:amd64 (4.2.1-1ubuntu0.1) ...\nSetting up python-olefile (0.45.1-1) ...\nSetting up python-pil:amd64 (5.1.0-1ubuntu0.2) ...\nSetting up python-webencodings (0.5-2) ...\nSetting up python-chardet (3.0.4-1) ...\nSetting up python-html5lib (0.999999999-1) ...\nProcessing triggers for man-db (2.8.3-2ubuntu0.1) ...\n/content/models/research\nWARNING: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\nWARNING:tensorflow:From /content/models/research/slim/nets/inception_resnet_v2.py:373: The name tf.GraphKeys is deprecated. Please use tf.compat.v1.GraphKeys instead.\n\nWARNING:tensorflow:From /content/models/research/slim/nets/mobilenet/mobilenet.py:389: The name tf.nn.avg_pool is deprecated. Please use tf.nn.avg_pool2d instead.\n\nRunning tests under Python 3.6.9: /usr/bin/python3\n[ RUN ] ModelBuilderTest.test_create_embedded_ssd_mobilenet_v1_model_from_config\n[ OK ] ModelBuilderTest.test_create_embedded_ssd_mobilenet_v1_model_from_config\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_inception_resnet_v2_model_from_config\nWARNING:tensorflow:From /content/models/research/object_detection/anchor_generators/grid_anchor_generator.py:59: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nW0617 08:24:17.768357 139871265372032 deprecation.py:323] From /content/models/research/object_detection/anchor_generators/grid_anchor_generator.py:59: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_inception_resnet_v2_model_from_config\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_inception_v2_model_from_config\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_inception_v2_model_from_config\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_model_from_config_with_example_miner\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_model_from_config_with_example_miner\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_nas_model_from_config\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_nas_model_from_config\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_pnas_model_from_config\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_pnas_model_from_config\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_resnet101_with_mask_prediction_enabled(use_matmul_crop_and_resize=False)\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_resnet101_with_mask_prediction_enabled(use_matmul_crop_and_resize=False)\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_resnet101_with_mask_prediction_enabled(use_matmul_crop_and_resize=True)\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_resnet101_with_mask_prediction_enabled(use_matmul_crop_and_resize=True)\n[ RUN ] ModelBuilderTest.test_create_faster_rcnn_resnet_v1_models_from_config\n[ OK ] ModelBuilderTest.test_create_faster_rcnn_resnet_v1_models_from_config\n[ RUN ] ModelBuilderTest.test_create_rfcn_resnet_v1_model_from_config\n[ OK ] ModelBuilderTest.test_create_rfcn_resnet_v1_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_inception_v2_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_inception_v2_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_inception_v3_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_inception_v3_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_mobilenet_v1_fpn_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_mobilenet_v1_fpn_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_mobilenet_v1_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_mobilenet_v1_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_mobilenet_v1_ppn_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_mobilenet_v1_ppn_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_mobilenet_v2_fpn_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_mobilenet_v2_fpn_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_mobilenet_v2_fpnlite_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_mobilenet_v2_fpnlite_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_mobilenet_v2_keras_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_mobilenet_v2_keras_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_mobilenet_v2_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_mobilenet_v2_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_resnet_v1_fpn_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_resnet_v1_fpn_model_from_config\n[ RUN ] ModelBuilderTest.test_create_ssd_resnet_v1_ppn_model_from_config\n[ OK ] ModelBuilderTest.test_create_ssd_resnet_v1_ppn_model_from_config\n[ RUN ] ModelBuilderTest.test_session\n[ SKIPPED ] ModelBuilderTest.test_session\n----------------------------------------------------------------------\nRan 22 tests in 0.101s\n\nOK (skipped=1)\n"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/gdrive')",
"Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/gdrive\n"
]
],
[
[
"##Task-2: Conversion of XML annotations and images into tfrecords for training and testing datasets",
"_____no_output_____"
],
[
"### Step 4: Prepare `tfrecord` files\n\nUse the following scripts to generate the `tfrecord` files.\n```bash\n# Convert train folder annotation xml files to a single csv file,\n# generate the `label_map.pbtxt` file to `data/` directory as well.\npython xml_to_csv.py -i data/images/train -o data/annotations/train_labels.csv -l data/annotations\n\n# Convert test folder annotation xml files to a single csv.\npython xml_to_csv.py -i data/images/test -o data/annotations/test_labels.csv\n\n# Generate `train.record`\npython generate_tfrecord.py --csv_input=data/annotations/train_labels.csv --output_path=data/annotations/train.record --img_path=data/images/train --label_map data/annotations/label_map.pbtxt\n\n# Generate `test.record`\npython generate_tfrecord.py --csv_input=data/annotations/test_labels.csv --output_path=data/annotations/test.record --img_path=data/images/test --label_map data/annotations/label_map.pbtxt\n```",
"_____no_output_____"
]
],
[
[
"#create the annotation directory\n%cd /content/object_detection_demo/data\nannotation_dir = 'annotations/'\nos.makedirs(annotation_dir, exist_ok=True)\n",
"/content/object_detection_demo/data\n"
],
[
"\"\"\"Need to manually upload the label_pbtxt file and the train_labels.csv and test_labels.csv\ninto the annotation folder using the link here\nhttps://drive.google.com/drive/folders/1NqKz2tC8I5eL5Qo4YzZiEph8W-dtI44d\n\"\"\"",
"_____no_output_____"
],
[
"%cd /content/gdrive/My Drive/A3 test\n# Generate `train.record`\n!python generate_tfrecord.py --csv_input=train_csv/train_labels.csv --output_path=annotations/train.record --img_path=train --label_map annotations/label_map.pbtxt",
"/content/gdrive/My Drive/A3 test\nWARNING:tensorflow:From generate_tfrecord.py:134: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n\nWARNING:tensorflow:From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nW0615 11:30:48.504616 140182534674304 module_wrapper.py:139] From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/utils/label_map_util.py:132: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nW0615 11:30:49.260015 140182534674304 module_wrapper.py:139] From /content/models/research/object_detection/utils/label_map_util.py:132: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nSuccessfully created the TFRecords: /content/gdrive/My Drive/A3 test/annotations/train.record\n"
],
[
"%cd /content/gdrive/My Drive/A3 test\n# Generate `test.record`\n!python generate_tfrecord.py --csv_input=test_csv/test_labels.csv --output_path=annotations/test.record --img_path=test --label_map annotations/label_map.pbtxt",
"/content/gdrive/My Drive/A3 test\nWARNING:tensorflow:From generate_tfrecord.py:134: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n\nWARNING:tensorflow:From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nW0615 13:17:13.488225 140325260527488 module_wrapper.py:139] From generate_tfrecord.py:107: The name tf.python_io.TFRecordWriter is deprecated. Please use tf.io.TFRecordWriter instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/utils/label_map_util.py:132: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nW0615 13:17:15.261747 140325260527488 module_wrapper.py:139] From /content/models/research/object_detection/utils/label_map_util.py:132: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nSuccessfully created the TFRecords: /content/gdrive/My Drive/A3 test/annotations/test.record\n"
],
[
"test_record_fname = '/content/gdrive/My Drive/A3 test/annotations/test.record'\ntrain_record_fname = '/content/gdrive/My Drive/A3 test/annotations/train.record'\nlabel_map_pbtxt_fname = '/content/gdrive/My Drive/A3 test/annotations/label_map.pbtxt'",
"_____no_output_____"
]
],
[
[
"### Step 5. Download the base model for transfer learning",
"_____no_output_____"
]
],
[
[
"%cd /content/models/research\n\nimport os\nimport shutil\nimport glob\nimport urllib.request\nimport tarfile\nMODEL_FILE = MODEL + '.tar.gz'\nDOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\nDEST_DIR = '/content/models/research/pretrained_model'\n\nif not (os.path.exists(MODEL_FILE)):\n urllib.request.urlretrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\n\ntar = tarfile.open(MODEL_FILE)\ntar.extractall()\ntar.close()\n\nos.remove(MODEL_FILE)\nif (os.path.exists(DEST_DIR)):\n shutil.rmtree(DEST_DIR)\nos.rename(MODEL, DEST_DIR)",
"/content/models/research\n"
],
[
"!echo {DEST_DIR}\n!ls -alh {DEST_DIR}",
"/content/models/research/pretrained_model\ntotal 476M\ndrwxr-xr-x 3 345018 5000 4.0K Feb 1 2018 .\ndrwxr-xr-x 70 root root 4.0K Jun 17 08:25 ..\n-rw-r--r-- 1 345018 5000 77 Feb 1 2018 checkpoint\n-rw-r--r-- 1 345018 5000 208M Feb 1 2018 frozen_inference_graph.pb\n-rw-r--r-- 1 345018 5000 262M Feb 1 2018 model.ckpt.data-00000-of-00001\n-rw-r--r-- 1 345018 5000 26K Feb 1 2018 model.ckpt.index\n-rw-r--r-- 1 345018 5000 6.4M Feb 1 2018 model.ckpt.meta\n-rw-r--r-- 1 345018 5000 3.1K Feb 1 2018 pipeline.config\ndrwxr-xr-x 3 345018 5000 4.0K Feb 1 2018 saved_model\n"
],
[
"fine_tune_checkpoint = os.path.join(DEST_DIR, \"model.ckpt\")\nfine_tune_checkpoint",
"_____no_output_____"
]
],
[
[
"##Task-3: Training: Transfer learning from already trained models\n\n",
"_____no_output_____"
],
[
"###Step 6: configuring a training pipeline",
"_____no_output_____"
]
],
[
[
"import os\npipeline_fname = os.path.join('/content/models/research/object_detection/samples/configs/', pipeline_file)\n\nassert os.path.isfile(pipeline_fname), '`{}` not exist'.format(pipeline_fname)",
"_____no_output_____"
],
[
"def get_num_classes(pbtxt_fname):\n from object_detection.utils import label_map_util\n label_map = label_map_util.load_labelmap(pbtxt_fname)\n categories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=90, use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n return len(category_index.keys())",
"_____no_output_____"
],
[
"\nnum_classes = get_num_classes(label_map_pbtxt_fname)\nwith open(pipeline_fname) as f:\n s = f.read()\nwith open(pipeline_fname, 'w') as f:\n \n # fine_tune_checkpoint\n s = re.sub('fine_tune_checkpoint: \".*?\"',\n 'fine_tune_checkpoint: \"{}\"'.format(fine_tune_checkpoint), s)\n \n # tfrecord files train and test.\n s = re.sub(\n '(input_path: \".*?)(train.record)(.*?\")', 'input_path: \"{}\"'.format(train_record_fname), s)\n s = re.sub(\n '(input_path: \".*?)(val.record)(.*?\")', 'input_path: \"{}\"'.format(test_record_fname), s)\n\n # label_map_path\n s = re.sub(\n 'label_map_path: \".*?\"', 'label_map_path: \"{}\"'.format(label_map_pbtxt_fname), s)\n\n # Set training batch_size.\n s = re.sub('batch_size: [0-9]+',\n 'batch_size: {}'.format(batch_size), s)\n\n # Set training steps, num_steps\n s = re.sub('num_steps: [0-9]+',\n 'num_steps: {}'.format(num_steps), s)\n \n # Set number of classes num_classes.\n s = re.sub('num_classes: [0-9]+',\n 'num_classes: {}'.format(num_classes), s)\n f.write(s)",
"WARNING:tensorflow:From /content/models/research/object_detection/utils/label_map_util.py:132: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\n"
],
[
"!cat {pipeline_fname}",
"# R-FCN with Resnet-101 (v1), configured for Oxford-IIIT Pets Dataset.\n# Users should configure the fine_tune_checkpoint field in the train config as\n# well as the label_map_path and input_path fields in the train_input_reader and\n# eval_input_reader. Search for \"PATH_TO_BE_CONFIGURED\" to find the fields that\n# should be configured.\n\nmodel {\n faster_rcnn {\n num_classes: 1\n image_resizer {\n keep_aspect_ratio_resizer {\n min_dimension: 600\n max_dimension: 1024\n }\n }\n feature_extractor {\n type: 'faster_rcnn_resnet101'\n first_stage_features_stride: 16\n }\n first_stage_anchor_generator {\n grid_anchor_generator {\n scales: [0.25, 0.5, 1.0, 2.0]\n aspect_ratios: [0.5, 1.0, 2.0]\n height_stride: 16\n width_stride: 16\n }\n }\n first_stage_box_predictor_conv_hyperparams {\n op: CONV\n regularizer {\n l2_regularizer {\n weight: 0.0\n }\n }\n initializer {\n truncated_normal_initializer {\n stddev: 0.01\n }\n }\n }\n first_stage_nms_score_threshold: 0.0\n first_stage_nms_iou_threshold: 0.7\n first_stage_max_proposals: 300\n first_stage_localization_loss_weight: 2.0\n first_stage_objectness_loss_weight: 1.0\n second_stage_box_predictor {\n rfcn_box_predictor {\n conv_hyperparams {\n op: CONV\n regularizer {\n l2_regularizer {\n weight: 0.0\n }\n }\n initializer {\n truncated_normal_initializer {\n stddev: 0.01\n }\n }\n }\n crop_height: 18\n crop_width: 18\n num_spatial_bins_height: 3\n num_spatial_bins_width: 3\n }\n }\n second_stage_post_processing {\n batch_non_max_suppression {\n score_threshold: 0.0\n iou_threshold: 0.6\n max_detections_per_class: 100\n max_total_detections: 300\n }\n score_converter: SOFTMAX\n }\n second_stage_localization_loss_weight: 2.0\n second_stage_classification_loss_weight: 1.0\n }\n}\n\ntrain_config: {\n batch_size: 8\n optimizer {\n momentum_optimizer: {\n learning_rate: {\n manual_step_learning_rate {\n initial_learning_rate: 0.0003\n schedule {\n step: 900000\n learning_rate: .00003\n }\n schedule {\n step: 1200000\n learning_rate: .000003\n }\n }\n }\n momentum_optimizer_value: 0.9\n }\n use_moving_average: false\n }\n gradient_clipping_by_norm: 10.0\n fine_tune_checkpoint: \"/content/models/research/pretrained_model/model.ckpt\"\n from_detection_checkpoint: true\n load_all_detection_checkpoint_vars: true\n # Note: The below line limits the training process to 200K steps, which we\n # empirically found to be sufficient enough to train the pets dataset. This\n # effectively bypasses the learning rate schedule (the learning rate will\n # never decay). Remove the below line to train indefinitely.\n num_steps: 1000\n data_augmentation_options {\n random_horizontal_flip {\n }\n }\n}\n\ntrain_input_reader: {\n tf_record_input_reader {\n input_path: \"/content/gdrive/My Drive/A3 test/annotations/train.record\"\n }\n label_map_path: \"/content/gdrive/My Drive/A3 test/annotations/label_map.pbtxt\"\n}\n\neval_config: {\n metrics_set: \"coco_detection_metrics\"\n num_examples: 1101\n}\n\neval_input_reader: {\n tf_record_input_reader {\n input_path: \"/content/gdrive/My Drive/A3 test/annotations/test.record\"\n }\n label_map_path: \"/content/gdrive/My Drive/A3 test/annotations/label_map.pbtxt\"\n shuffle: false\n num_readers: 1\n}\n"
],
[
"model_dir = 'training/'\n# Optionally remove content in output model directory to fresh start.\n!rm -rf {model_dir}\nos.makedirs(model_dir, exist_ok=True)",
"_____no_output_____"
]
],
[
[
"### Step 7. Install Tensorboard to visualize the progress of training process",
"_____no_output_____"
]
],
[
[
"!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n!unzip -o ngrok-stable-linux-amd64.zip",
"--2020-06-17 08:58:59-- https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\nResolving bin.equinox.io (bin.equinox.io)... 54.164.74.108, 54.161.19.10, 34.233.91.203, ...\nConnecting to bin.equinox.io (bin.equinox.io)|54.164.74.108|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 13773305 (13M) [application/octet-stream]\nSaving to: ‘ngrok-stable-linux-amd64.zip’\n\n\r ngrok-sta 0%[ ] 0 --.-KB/s \r ngrok-stab 43%[=======> ] 5.66M 27.6MB/s \rngrok-stable-linux- 100%[===================>] 13.13M 42.5MB/s in 0.3s \n\n2020-06-17 08:58:59 (42.5 MB/s) - ‘ngrok-stable-linux-amd64.zip’ saved [13773305/13773305]\n\nArchive: ngrok-stable-linux-amd64.zip\n inflating: ngrok \n"
],
[
"LOG_DIR = model_dir\nget_ipython().system_raw(\n 'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'\n .format(LOG_DIR)\n)",
"_____no_output_____"
],
[
"get_ipython().system_raw('./ngrok http 6006 &')\n",
"_____no_output_____"
]
],
[
[
"### Step: 8 Get tensorboard link",
"_____no_output_____"
]
],
[
[
"! curl -s http://localhost:4040/api/tunnels | python3 -c \\\n \"import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])\"",
"https://19e630cb7971.ngrok.io\n"
]
],
[
[
"### Step 9. Training the model",
"_____no_output_____"
]
],
[
[
"!python /content/models/research/object_detection/model_main.py \\\n --pipeline_config_path={pipeline_fname} \\\n --model_dir={model_dir} \\\n --alsologtostderr \\\n --num_train_steps={num_steps} \\\n --num_eval_steps={num_eval_steps}",
"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\nWARNING:tensorflow:From /content/models/research/slim/nets/inception_resnet_v2.py:373: The name tf.GraphKeys is deprecated. Please use tf.compat.v1.GraphKeys instead.\n\nWARNING:tensorflow:From /content/models/research/slim/nets/mobilenet/mobilenet.py:389: The name tf.nn.avg_pool is deprecated. Please use tf.nn.avg_pool2d instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_main.py:109: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/utils/config_util.py:94: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nW0617 08:59:21.863340 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/utils/config_util.py:94: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:573: The name tf.logging.warning is deprecated. Please use tf.compat.v1.logging.warning instead.\n\nW0617 08:59:21.865852 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:573: The name tf.logging.warning is deprecated. Please use tf.compat.v1.logging.warning instead.\n\nWARNING:tensorflow:Forced number of epochs for all eval validations to be 1.\nW0617 08:59:21.866010 140626870351744 model_lib.py:574] Forced number of epochs for all eval validations to be 1.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/config_util.py:480: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n\nW0617 08:59:21.866147 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/utils/config_util.py:480: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n\nINFO:tensorflow:Maybe overwriting train_steps: 7000\nI0617 08:59:21.866232 140626870351744 config_util.py:480] Maybe overwriting train_steps: 7000\nINFO:tensorflow:Maybe overwriting sample_1_of_n_eval_examples: 1\nI0617 08:59:21.866317 140626870351744 config_util.py:480] Maybe overwriting sample_1_of_n_eval_examples: 1\nINFO:tensorflow:Maybe overwriting eval_num_epochs: 1\nI0617 08:59:21.866399 140626870351744 config_util.py:480] Maybe overwriting eval_num_epochs: 1\nINFO:tensorflow:Maybe overwriting load_pretrained: True\nI0617 08:59:21.866472 140626870351744 config_util.py:480] Maybe overwriting load_pretrained: True\nINFO:tensorflow:Ignoring config override key: load_pretrained\nI0617 08:59:21.866549 140626870351744 config_util.py:490] Ignoring config override key: load_pretrained\nWARNING:tensorflow:Expected number of evaluation epochs is 1, but instead encountered `eval_on_train_input_config.num_epochs` = 0. Overwriting `num_epochs` to 1.\nW0617 08:59:21.867143 140626870351744 model_lib.py:590] Expected number of evaluation epochs is 1, but instead encountered `eval_on_train_input_config.num_epochs` = 0. Overwriting `num_epochs` to 1.\nINFO:tensorflow:create_estimator_and_inputs: use_tpu False, export_to_tpu False\nI0617 08:59:21.867240 140626870351744 model_lib.py:623] create_estimator_and_inputs: use_tpu False, export_to_tpu False\nINFO:tensorflow:Using config: {'_model_dir': 'training/', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true\ngraph_options {\n rewrite_options {\n meta_optimizer_iterations: ONE\n }\n}\n, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fe5d6895588>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}\nI0617 08:59:21.867614 140626870351744 estimator.py:212] Using config: {'_model_dir': 'training/', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true\ngraph_options {\n rewrite_options {\n meta_optimizer_iterations: ONE\n }\n}\n, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7fe5d6895588>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}\nWARNING:tensorflow:Estimator's model_fn (<function create_model_fn.<locals>.model_fn at 0x7fe5d68a50d0>) includes params argument, but params are not passed to Estimator.\nW0617 08:59:21.867815 140626870351744 model_fn.py:630] Estimator's model_fn (<function create_model_fn.<locals>.model_fn at 0x7fe5d68a50d0>) includes params argument, but params are not passed to Estimator.\nINFO:tensorflow:Not using Distribute Coordinator.\nI0617 08:59:21.868472 140626870351744 estimator_training.py:186] Not using Distribute Coordinator.\nINFO:tensorflow:Running training and evaluation locally (non-distributed).\nI0617 08:59:21.868666 140626870351744 training.py:612] Running training and evaluation locally (non-distributed).\nINFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600.\nI0617 08:59:21.868875 140626870351744 training.py:700] Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps None or save_checkpoints_secs 600.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\nW0617 08:59:21.873651 140626870351744 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\nWARNING:tensorflow:From /content/models/research/object_detection/data_decoders/tf_example_decoder.py:167: The name tf.FixedLenFeature is deprecated. Please use tf.io.FixedLenFeature instead.\n\nW0617 08:59:21.882289 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/data_decoders/tf_example_decoder.py:167: The name tf.FixedLenFeature is deprecated. Please use tf.io.FixedLenFeature instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/data_decoders/tf_example_decoder.py:182: The name tf.VarLenFeature is deprecated. Please use tf.io.VarLenFeature instead.\n\nW0617 08:59:21.882538 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/data_decoders/tf_example_decoder.py:182: The name tf.VarLenFeature is deprecated. Please use tf.io.VarLenFeature instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/builders/dataset_builder.py:61: The name tf.gfile.Glob is deprecated. Please use tf.io.gfile.glob instead.\n\nW0617 08:59:21.904967 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/builders/dataset_builder.py:61: The name tf.gfile.Glob is deprecated. Please use tf.io.gfile.glob instead.\n\nWARNING:tensorflow:num_readers has been reduced to 1 to match input file shards.\nW0617 08:59:21.906369 140626870351744 dataset_builder.py:66] num_readers has been reduced to 1 to match input file shards.\nWARNING:tensorflow:From /content/models/research/object_detection/builders/dataset_builder.py:80: parallel_interleave (from tensorflow.contrib.data.python.ops.interleave_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.experimental.parallel_interleave(...)`.\nW0617 08:59:21.912718 140626870351744 deprecation.py:323] From /content/models/research/object_detection/builders/dataset_builder.py:80: parallel_interleave (from tensorflow.contrib.data.python.ops.interleave_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.experimental.parallel_interleave(...)`.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/contrib/data/python/ops/interleave_ops.py:77: parallel_interleave (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.experimental.AUTOTUNE)` instead. If sloppy execution is desired, use `tf.data.Options.experimental_determinstic`.\nW0617 08:59:21.912866 140626870351744 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/contrib/data/python/ops/interleave_ops.py:77: parallel_interleave (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.experimental.AUTOTUNE)` instead. If sloppy execution is desired, use `tf.data.Options.experimental_determinstic`.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe600046ae8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 08:59:21.950588 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe600046ae8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\n2020-06-17 08:59:21.976817: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n2020-06-17 08:59:21.982922: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:21.983375: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 08:59:21.983664: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 08:59:21.985343: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 08:59:21.987073: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 08:59:21.987377: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 08:59:21.989398: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 08:59:21.990572: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 08:59:21.994203: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 08:59:21.994336: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:21.994838: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:21.995264: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\nWARNING:tensorflow:From /content/models/research/object_detection/anchor_generators/grid_anchor_generator.py:59: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nW0617 08:59:22.080037 140626870351744 deprecation.py:323] From /content/models/research/object_detection/anchor_generators/grid_anchor_generator.py:59: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/ops.py:466: The name tf.is_nan is deprecated. Please use tf.math.is_nan instead.\n\nW0617 08:59:22.082286 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/utils/ops.py:466: The name tf.is_nan is deprecated. Please use tf.math.is_nan instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/utils/ops.py:466: 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.\nW0617 08:59:22.082828 140626870351744 deprecation.py:323] From /content/models/research/object_detection/utils/ops.py:466: 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.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/ops.py:468: 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\nW0617 08:59:22.085090 140626870351744 deprecation.py:323] From /content/models/research/object_detection/utils/ops.py:468: 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 /content/models/research/object_detection/core/preprocessor.py:512: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.\n\nW0617 08:59:22.100084 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/core/preprocessor.py:512: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/core/preprocessor.py:2236: The name tf.image.resize_images is deprecated. Please use tf.image.resize instead.\n\nW0617 08:59:22.145589 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/core/preprocessor.py:2236: The name tf.image.resize_images is deprecated. Please use tf.image.resize instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/inputs.py:374: The name tf.string_to_hash_bucket_fast is deprecated. Please use tf.strings.to_hash_bucket_fast instead.\n\nW0617 08:59:22.338199 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/inputs.py:374: The name tf.string_to_hash_bucket_fast is deprecated. Please use tf.strings.to_hash_bucket_fast instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/builders/dataset_builder.py:148: batch_and_drop_remainder (from tensorflow.contrib.data.python.ops.batching) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.batch(..., drop_remainder=True)`.\nW0617 08:59:22.362221 140626870351744 deprecation.py:323] From /content/models/research/object_detection/builders/dataset_builder.py:148: batch_and_drop_remainder (from tensorflow.contrib.data.python.ops.batching) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.data.Dataset.batch(..., drop_remainder=True)`.\nINFO:tensorflow:Calling model_fn.\nI0617 08:59:22.373571 140626870351744 estimator.py:1148] Calling model_fn.\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:162: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n\nW0617 08:59:22.472047 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:162: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:59:22.479800 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/contrib/layers/python/layers/layers.py:1057: 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.\nW0617 08:59:22.482516 140626870351744 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/contrib/layers/python/layers/layers.py:1057: 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 /content/models/research/object_detection/core/anchor_generator.py:149: The name tf.assert_equal is deprecated. Please use tf.compat.v1.assert_equal instead.\n\nW0617 08:59:25.302015 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/core/anchor_generator.py:149: The name tf.assert_equal is deprecated. Please use tf.compat.v1.assert_equal instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:59:25.308074 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:986: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n\nW0617 08:59:25.308407 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:986: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:59:25.320410 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 08:59:25.320721 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nWARNING:tensorflow:From /content/models/research/object_detection/box_coders/faster_rcnn_box_coder.py:82: The name tf.log is deprecated. Please use tf.math.log instead.\n\nW0617 08:59:25.953444 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/box_coders/faster_rcnn_box_coder.py:82: The name tf.log is deprecated. Please use tf.math.log instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/core/minibatch_sampler.py:81: The name tf.random_shuffle is deprecated. Please use tf.random.shuffle instead.\n\nW0617 08:59:25.994459 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/core/minibatch_sampler.py:81: The name tf.random_shuffle is deprecated. Please use tf.random.shuffle instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:185: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n\nW0617 08:59:27.708463 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:185: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:59:27.708845 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 08:59:27.955544 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/ops.py:712: calling crop_and_resize_v1 (from tensorflow.python.ops.image_ops_impl) with box_ind is deprecated and will be removed in a future version.\nInstructions for updating:\nbox_ind is deprecated, use box_indices instead\nW0617 08:59:28.062154 140626870351744 deprecation.py:506] From /content/models/research/object_detection/utils/ops.py:712: calling crop_and_resize_v1 (from tensorflow.python.ops.image_ops_impl) with box_ind is deprecated and will be removed in a future version.\nInstructions for updating:\nbox_ind is deprecated, use box_indices instead\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/util/dispatch.py:180: calling squeeze (from tensorflow.python.ops.array_ops) with squeeze_dims is deprecated and will be removed in a future version.\nInstructions for updating:\nUse the `axis` argument instead\nW0617 08:59:28.965998 140626870351744 deprecation.py:506] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/util/dispatch.py:180: calling squeeze (from tensorflow.python.ops.array_ops) with squeeze_dims is deprecated and will be removed in a future version.\nInstructions for updating:\nUse the `axis` argument instead\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:2235: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n\nW0617 08:59:30.017379 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:2235: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:2236: get_or_create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease switch to tf.train.get_or_create_global_step\nW0617 08:59:30.017659 140626870351744 deprecation.py:323] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:2236: get_or_create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease switch to tf.train.get_or_create_global_step\nWARNING:tensorflow:From /content/models/research/object_detection/utils/variables_helper.py:126: The name tf.train.NewCheckpointReader is deprecated. Please use tf.compat.v1.train.NewCheckpointReader instead.\n\nW0617 08:59:30.019203 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/utils/variables_helper.py:126: The name tf.train.NewCheckpointReader is deprecated. Please use tf.compat.v1.train.NewCheckpointReader instead.\n\nW0617 08:59:30.025380 140626870351744 variables_helper.py:141] Variable [SecondStageBoxPredictor/class_predictions/biases] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[819]], model variable shape: [[18]]. This variable will not be initialized from the checkpoint.\nW0617 08:59:30.025501 140626870351744 variables_helper.py:141] Variable [SecondStageBoxPredictor/class_predictions/weights] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[1, 1, 1024, 819]], model variable shape: [[1, 1, 1024, 18]]. This variable will not be initialized from the checkpoint.\nW0617 08:59:30.025596 140626870351744 variables_helper.py:141] Variable [SecondStageBoxPredictor/refined_locations/biases] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[3240]], model variable shape: [[36]]. This variable will not be initialized from the checkpoint.\nW0617 08:59:30.025660 140626870351744 variables_helper.py:141] Variable [SecondStageBoxPredictor/refined_locations/weights] is available in checkpoint, but has an incompatible shape with model variable. Checkpoint shape: [[1, 1, 1024, 3240]], model variable shape: [[1, 1, 1024, 36]]. This variable will not be initialized from the checkpoint.\nW0617 08:59:30.026115 140626870351744 variables_helper.py:144] Variable [global_step] is not available in checkpoint\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:317: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n\nW0617 08:59:30.026358 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:317: The name tf.train.init_from_checkpoint is deprecated. Please use tf.compat.v1.train.init_from_checkpoint instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/core/losses.py:174: The name tf.losses.huber_loss is deprecated. Please use tf.compat.v1.losses.huber_loss instead.\n\nW0617 08:59:33.014684 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/core/losses.py:174: The name tf.losses.huber_loss is deprecated. Please use tf.compat.v1.losses.huber_loss instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/core/losses.py:180: The name tf.losses.Reduction is deprecated. Please use tf.compat.v1.losses.Reduction instead.\n\nW0617 08:59:33.015892 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/core/losses.py:180: The name tf.losses.Reduction is deprecated. Please use tf.compat.v1.losses.Reduction instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/core/losses.py:345: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\n\nFuture major versions of TensorFlow will allow gradients to flow\ninto the labels input on backprop by default.\n\nSee `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\nW0617 08:59:33.055978 140626870351744 deprecation.py:323] From /content/models/research/object_detection/core/losses.py:345: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\n\nFuture major versions of TensorFlow will allow gradients to flow\ninto the labels input on backprop by default.\n\nSee `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:2202: The name tf.get_collection is deprecated. Please use tf.compat.v1.get_collection instead.\n\nW0617 08:59:33.974540 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:2202: The name tf.get_collection is deprecated. Please use tf.compat.v1.get_collection instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:341: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n\nW0617 08:59:33.975373 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:341: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/builders/optimizer_builder.py:52: The name tf.train.MomentumOptimizer is deprecated. Please use tf.compat.v1.train.MomentumOptimizer instead.\n\nW0617 08:59:33.981831 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/builders/optimizer_builder.py:52: The name tf.train.MomentumOptimizer is deprecated. Please use tf.compat.v1.train.MomentumOptimizer instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:359: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n\nW0617 08:59:33.982042 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:359: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:369: The name tf.summary.scalar is deprecated. Please use tf.compat.v1.summary.scalar instead.\n\nW0617 08:59:33.982224 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:369: The name tf.summary.scalar is deprecated. Please use tf.compat.v1.summary.scalar instead.\n\n/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/indexed_slices.py:424: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\n/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/indexed_slices.py:424: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:472: The name tf.train.Saver is deprecated. Please use tf.compat.v1.train.Saver instead.\n\nW0617 08:59:46.443725 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:472: The name tf.train.Saver is deprecated. Please use tf.compat.v1.train.Saver instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:476: The name tf.add_to_collection is deprecated. Please use tf.compat.v1.add_to_collection instead.\n\nW0617 08:59:47.040690 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:476: The name tf.add_to_collection is deprecated. Please use tf.compat.v1.add_to_collection instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:477: The name tf.train.Scaffold is deprecated. Please use tf.compat.v1.train.Scaffold instead.\n\nW0617 08:59:47.040978 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:477: The name tf.train.Scaffold is deprecated. Please use tf.compat.v1.train.Scaffold instead.\n\nINFO:tensorflow:Done calling model_fn.\nI0617 08:59:47.041309 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Create CheckpointSaverHook.\nI0617 08:59:47.042503 140626870351744 basic_session_run_hooks.py:541] Create CheckpointSaverHook.\nINFO:tensorflow:Graph was finalized.\nI0617 08:59:51.798773 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 08:59:51.803382: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300000000 Hz\n2020-06-17 08:59:51.803574: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x23cfe140 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n2020-06-17 08:59:51.803617: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version\n2020-06-17 08:59:51.893444: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:51.894035: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x23cfdf80 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n2020-06-17 08:59:51.894065: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Tesla P100-PCIE-16GB, Compute Capability 6.0\n2020-06-17 08:59:51.894280: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:51.894685: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 08:59:51.894770: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 08:59:51.894800: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 08:59:51.894823: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 08:59:51.894848: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 08:59:51.894875: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 08:59:51.894956: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 08:59:51.894981: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 08:59:51.895093: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:51.895573: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:51.895989: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 08:59:51.896077: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 08:59:51.897216: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 08:59:51.897244: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 08:59:51.897260: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 08:59:51.897399: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:51.897884: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 08:59:51.898306: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.\n2020-06-17 08:59:51.898347: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\n2020-06-17 08:59:53.257361: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 18874368 exceeds 10% of system memory.\n2020-06-17 08:59:53.489043: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 18874368 exceeds 10% of system memory.\n2020-06-17 08:59:53.590403: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 18874368 exceeds 10% of system memory.\n2020-06-17 08:59:53.733096: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 18874368 exceeds 10% of system memory.\n2020-06-17 08:59:53.885851: W tensorflow/core/framework/cpu_allocator_impl.cc:81] Allocation of 18874368 exceeds 10% of system memory.\nINFO:tensorflow:Running local_init_op.\nI0617 09:00:00.900222 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:00:01.451279 140626870351744 session_manager.py:502] Done running local_init_op.\nINFO:tensorflow:Saving checkpoints for 0 into training/model.ckpt.\nI0617 09:00:15.509456 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 0 into training/model.ckpt.\n2020-06-17 09:00:31.189864: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:00:32.338569: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:00:33.547223: W tensorflow/core/common_runtime/bfc_allocator.cc:239] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.24GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available.\nINFO:tensorflow:loss = 1.2842872, step = 0\nI0617 09:00:34.836959 140626870351744 basic_session_run_hooks.py:262] loss = 1.2842872, step = 0\nINFO:tensorflow:global_step/sec: 1.15895\nI0617 09:02:01.121223 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.15895\nINFO:tensorflow:loss = 1.0294284, step = 100 (86.285 sec)\nI0617 09:02:01.122241 140626870351744 basic_session_run_hooks.py:260] loss = 1.0294284, step = 100 (86.285 sec)\nINFO:tensorflow:global_step/sec: 1.27762\nI0617 09:03:19.391921 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27762\nINFO:tensorflow:loss = 0.6777348, step = 200 (78.271 sec)\nI0617 09:03:19.393183 140626870351744 basic_session_run_hooks.py:260] loss = 0.6777348, step = 200 (78.271 sec)\nINFO:tensorflow:global_step/sec: 1.28119\nI0617 09:04:37.444211 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28119\nINFO:tensorflow:loss = 0.98728716, step = 300 (78.052 sec)\nI0617 09:04:37.445399 140626870351744 basic_session_run_hooks.py:260] loss = 0.98728716, step = 300 (78.052 sec)\nINFO:tensorflow:global_step/sec: 1.28246\nI0617 09:05:55.419322 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28246\nINFO:tensorflow:loss = 0.5429901, step = 400 (77.975 sec)\nI0617 09:05:55.420380 140626870351744 basic_session_run_hooks.py:260] loss = 0.5429901, step = 400 (77.975 sec)\nINFO:tensorflow:global_step/sec: 1.27961\nI0617 09:07:13.567983 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27961\nINFO:tensorflow:loss = 0.5978362, step = 500 (78.149 sec)\nI0617 09:07:13.569166 140626870351744 basic_session_run_hooks.py:260] loss = 0.5978362, step = 500 (78.149 sec)\nINFO:tensorflow:global_step/sec: 1.27349\nI0617 09:08:32.092286 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27349\nINFO:tensorflow:loss = 0.8104238, step = 600 (78.524 sec)\nI0617 09:08:32.093363 140626870351744 basic_session_run_hooks.py:260] loss = 0.8104238, step = 600 (78.524 sec)\nINFO:tensorflow:global_step/sec: 1.27917\nI0617 09:09:50.268033 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27917\nINFO:tensorflow:loss = 0.67875326, step = 700 (78.176 sec)\nI0617 09:09:50.269144 140626870351744 basic_session_run_hooks.py:260] loss = 0.67875326, step = 700 (78.176 sec)\nINFO:tensorflow:Saving checkpoints for 740 into training/model.ckpt.\nI0617 09:10:20.747971 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 740 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe5777c3d90> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:10:24.390253 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe5777c3d90> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:10:24.820141 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:10:24.846549 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:10:27.646597 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:10:27.658954 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:10:27.659282 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:10:28.101971 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:10:28.369542 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/eval_util.py:750: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nW0617 09:10:29.632938 140626870351744 deprecation.py:323] From /content/models/research/object_detection/eval_util.py:750: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/visualization_utils.py:429: py_func (from tensorflow.python.ops.script_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\ntf.py_func is deprecated in TF V2. Instead, there are two\n options available in V2.\n - tf.py_function takes a python function which manipulates tf eager\n tensors instead of numpy arrays. It's easy to convert a tf eager tensor to\n an ndarray (just call tensor.numpy()) but having access to eager tensors\n means `tf.py_function`s can use accelerators such as GPUs as well as\n being differentiable using a gradient tape.\n - tf.numpy_function maintains the semantics of the deprecated tf.py_func\n (it is not differentiable, and manipulates numpy arrays). It drops the\n stateful argument making all functions stateful.\n \nW0617 09:10:29.776114 140626870351744 deprecation.py:323] From /content/models/research/object_detection/utils/visualization_utils.py:429: py_func (from tensorflow.python.ops.script_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\ntf.py_func is deprecated in TF V2. Instead, there are two\n options available in V2.\n - tf.py_function takes a python function which manipulates tf eager\n tensors instead of numpy arrays. It's easy to convert a tf eager tensor to\n an ndarray (just call tensor.numpy()) but having access to eager tensors\n means `tf.py_function`s can use accelerators such as GPUs as well as\n being differentiable using a gradient tape.\n - tf.numpy_function maintains the semantics of the deprecated tf.py_func\n (it is not differentiable, and manipulates numpy arrays). It drops the\n stateful argument making all functions stateful.\n \nWARNING:tensorflow:From /content/models/research/object_detection/utils/visualization_utils.py:924: The name tf.summary.image is deprecated. Please use tf.compat.v1.summary.image instead.\n\nW0617 09:10:29.903468 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/utils/visualization_utils.py:924: The name tf.summary.image is deprecated. Please use tf.compat.v1.summary.image instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:441: The name tf.metrics.mean is deprecated. Please use tf.compat.v1.metrics.mean instead.\n\nW0617 09:10:29.985230 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:441: The name tf.metrics.mean is deprecated. Please use tf.compat.v1.metrics.mean instead.\n\nINFO:tensorflow:Done calling model_fn.\nI0617 09:10:30.435026 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:10:30Z\nI0617 09:10:30.450091 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T09:10:30Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:10:31.096575 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:10:31.097829: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:10:31.098147: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 09:10:31.098243: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:10:31.098275: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:10:31.098298: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:10:31.098321: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:10:31.098350: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:10:31.098370: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:10:31.098391: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:10:31.098507: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:10:31.098810: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:10:31.099041: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:10:31.099087: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:10:31.099101: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:10:31.099110: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:10:31.099237: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:10:31.099534: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:10:31.099766: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-740\nI0617 09:10:31.100923 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-740\nINFO:tensorflow:Running local_init_op.\nI0617 09:10:32.668555 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:10:32.844949 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:13:44.367871 140623421343488 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.41s)\nI0617 09:13:44.781075 140623421343488 coco_tools.py:131] DONE (t=0.41s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.79s).\nAccumulating evaluation results...\nDONE (t=2.61s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.352\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.726\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.283\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.365\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.274\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.004\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.271\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.507\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.548\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.543\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.583\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.593\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:14:04\nI0617 09:14:04.979043 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-09:14:04\nINFO:tensorflow:Saving dict for global step 740: DetectionBoxes_Precision/mAP = 0.3520298, DetectionBoxes_Precision/mAP (large) = 0.0037690396, DetectionBoxes_Precision/mAP (medium) = 0.27408546, DetectionBoxes_Precision/mAP (small) = 0.3652042, DetectionBoxes_Precision/[email protected] = 0.72577006, DetectionBoxes_Precision/[email protected] = 0.28301588, DetectionBoxes_Recall/AR@1 = 0.27051204, DetectionBoxes_Recall/AR@10 = 0.5068205, DetectionBoxes_Recall/AR@100 = 0.54826957, DetectionBoxes_Recall/AR@100 (large) = 0.5933333, DetectionBoxes_Recall/AR@100 (medium) = 0.5827011, DetectionBoxes_Recall/AR@100 (small) = 0.5427835, Loss/BoxClassifierLoss/classification_loss = 0.16743542, Loss/BoxClassifierLoss/localization_loss = 0.12594679, Loss/RPNLoss/localization_loss = 0.030730719, Loss/RPNLoss/objectness_loss = 0.048275594, Loss/total_loss = 0.3723893, global_step = 740, learning_rate = 0.0003, loss = 0.3723893\nI0617 09:14:04.979321 140626870351744 estimator.py:2049] Saving dict for global step 740: DetectionBoxes_Precision/mAP = 0.3520298, DetectionBoxes_Precision/mAP (large) = 0.0037690396, DetectionBoxes_Precision/mAP (medium) = 0.27408546, DetectionBoxes_Precision/mAP (small) = 0.3652042, DetectionBoxes_Precision/[email protected] = 0.72577006, DetectionBoxes_Precision/[email protected] = 0.28301588, DetectionBoxes_Recall/AR@1 = 0.27051204, DetectionBoxes_Recall/AR@10 = 0.5068205, DetectionBoxes_Recall/AR@100 = 0.54826957, DetectionBoxes_Recall/AR@100 (large) = 0.5933333, DetectionBoxes_Recall/AR@100 (medium) = 0.5827011, DetectionBoxes_Recall/AR@100 (small) = 0.5427835, Loss/BoxClassifierLoss/classification_loss = 0.16743542, Loss/BoxClassifierLoss/localization_loss = 0.12594679, Loss/RPNLoss/localization_loss = 0.030730719, Loss/RPNLoss/objectness_loss = 0.048275594, Loss/total_loss = 0.3723893, global_step = 740, learning_rate = 0.0003, loss = 0.3723893\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 740: training/model.ckpt-740\nI0617 09:14:06.360345 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 740: training/model.ckpt-740\nINFO:tensorflow:global_step/sec: 0.329217\nI0617 09:14:54.018674 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.329217\nINFO:tensorflow:loss = 0.56714493, step = 800 (303.751 sec)\nI0617 09:14:54.019799 140626870351744 basic_session_run_hooks.py:260] loss = 0.56714493, step = 800 (303.751 sec)\nINFO:tensorflow:global_step/sec: 1.27726\nI0617 09:16:12.311033 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27726\nINFO:tensorflow:loss = 0.8179549, step = 900 (78.292 sec)\nI0617 09:16:12.311942 140626870351744 basic_session_run_hooks.py:260] loss = 0.8179549, step = 900 (78.292 sec)\nINFO:tensorflow:global_step/sec: 1.27734\nI0617 09:17:30.598580 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27734\nINFO:tensorflow:loss = 0.86686635, step = 1000 (78.288 sec)\nI0617 09:17:30.599659 140626870351744 basic_session_run_hooks.py:260] loss = 0.86686635, step = 1000 (78.288 sec)\nINFO:tensorflow:global_step/sec: 1.28232\nI0617 09:18:48.582268 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28232\nINFO:tensorflow:loss = 0.84696764, step = 1100 (77.984 sec)\nI0617 09:18:48.583457 140626870351744 basic_session_run_hooks.py:260] loss = 0.84696764, step = 1100 (77.984 sec)\nINFO:tensorflow:global_step/sec: 1.27999\nI0617 09:20:06.707943 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27999\nINFO:tensorflow:loss = 0.71004313, step = 1200 (78.126 sec)\nI0617 09:20:06.709124 140626870351744 basic_session_run_hooks.py:260] loss = 0.71004313, step = 1200 (78.126 sec)\nINFO:tensorflow:Saving checkpoints for 1220 into training/model.ckpt.\nI0617 09:20:21.487435 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 1220 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe544d691e0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:20:24.906744 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe544d691e0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:20:25.324669 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:20:25.350851 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:20:28.106223 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:20:28.118914 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:20:28.119272 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:20:28.579399 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:20:28.852126 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:20:30.655715 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:20:30Z\nI0617 09:20:30.671284 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T09:20:30Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:20:31.329827 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:20:31.330490: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:20:31.330830: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 09:20:31.334350: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:20:31.334425: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:20:31.334451: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:20:31.334472: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:20:31.334497: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:20:31.334516: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:20:31.334537: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:20:31.334656: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:20:31.335003: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:20:31.335233: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:20:31.335273: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:20:31.335286: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:20:31.335297: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:20:31.335410: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:20:31.335758: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:20:31.336045: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1220\nI0617 09:20:31.337135 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-1220\nINFO:tensorflow:Running local_init_op.\nI0617 09:20:32.873651 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:20:33.051122 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:23:43.933980 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.42s)\nI0617 09:23:44.351923 140623412950784 coco_tools.py:131] DONE (t=0.42s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=17.07s).\nAccumulating evaluation results...\nDONE (t=2.45s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.357\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.737\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.282\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.366\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.302\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.009\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.274\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.515\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.555\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.548\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.603\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.647\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:24:04\nI0617 09:24:04.661056 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-09:24:04\nINFO:tensorflow:Saving dict for global step 1220: DetectionBoxes_Precision/mAP = 0.35685897, DetectionBoxes_Precision/mAP (large) = 0.008658241, DetectionBoxes_Precision/mAP (medium) = 0.30155215, DetectionBoxes_Precision/mAP (small) = 0.366362, DetectionBoxes_Precision/[email protected] = 0.7372937, DetectionBoxes_Precision/[email protected] = 0.28186038, DetectionBoxes_Recall/AR@1 = 0.2738717, DetectionBoxes_Recall/AR@10 = 0.51471364, DetectionBoxes_Recall/AR@100 = 0.55549484, DetectionBoxes_Recall/AR@100 (large) = 0.64666665, DetectionBoxes_Recall/AR@100 (medium) = 0.60257965, DetectionBoxes_Recall/AR@100 (small) = 0.54789126, Loss/BoxClassifierLoss/classification_loss = 0.15842967, Loss/BoxClassifierLoss/localization_loss = 0.12616444, Loss/RPNLoss/localization_loss = 0.03001606, Loss/RPNLoss/objectness_loss = 0.047681384, Loss/total_loss = 0.36229149, global_step = 1220, learning_rate = 0.0003, loss = 0.36229149\nI0617 09:24:04.661330 140626870351744 estimator.py:2049] Saving dict for global step 1220: DetectionBoxes_Precision/mAP = 0.35685897, DetectionBoxes_Precision/mAP (large) = 0.008658241, DetectionBoxes_Precision/mAP (medium) = 0.30155215, DetectionBoxes_Precision/mAP (small) = 0.366362, DetectionBoxes_Precision/[email protected] = 0.7372937, DetectionBoxes_Precision/[email protected] = 0.28186038, DetectionBoxes_Recall/AR@1 = 0.2738717, DetectionBoxes_Recall/AR@10 = 0.51471364, DetectionBoxes_Recall/AR@100 = 0.55549484, DetectionBoxes_Recall/AR@100 (large) = 0.64666665, DetectionBoxes_Recall/AR@100 (medium) = 0.60257965, DetectionBoxes_Recall/AR@100 (small) = 0.54789126, Loss/BoxClassifierLoss/classification_loss = 0.15842967, Loss/BoxClassifierLoss/localization_loss = 0.12616444, Loss/RPNLoss/localization_loss = 0.03001606, Loss/RPNLoss/objectness_loss = 0.047681384, Loss/total_loss = 0.36229149, global_step = 1220, learning_rate = 0.0003, loss = 0.36229149\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1220: training/model.ckpt-1220\nI0617 09:24:04.662253 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1220: training/model.ckpt-1220\nINFO:tensorflow:global_step/sec: 0.331985\nI0617 09:25:07.926794 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.331985\nINFO:tensorflow:loss = 0.8144297, step = 1300 (301.219 sec)\nI0617 09:25:07.928003 140626870351744 basic_session_run_hooks.py:260] loss = 0.8144297, step = 1300 (301.219 sec)\nINFO:tensorflow:global_step/sec: 1.27764\nI0617 09:26:26.195883 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27764\nINFO:tensorflow:loss = 0.6396644, step = 1400 (78.269 sec)\nI0617 09:26:26.196999 140626870351744 basic_session_run_hooks.py:260] loss = 0.6396644, step = 1400 (78.269 sec)\nINFO:tensorflow:global_step/sec: 1.27942\nI0617 09:27:44.356273 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27942\nINFO:tensorflow:loss = 0.6347585, step = 1500 (78.161 sec)\nI0617 09:27:44.357638 140626870351744 basic_session_run_hooks.py:260] loss = 0.6347585, step = 1500 (78.161 sec)\nINFO:tensorflow:global_step/sec: 1.28446\nI0617 09:29:02.209960 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28446\nINFO:tensorflow:loss = 0.5337739, step = 1600 (77.854 sec)\nI0617 09:29:02.211152 140626870351744 basic_session_run_hooks.py:260] loss = 0.5337739, step = 1600 (77.854 sec)\nINFO:tensorflow:global_step/sec: 1.2822\nI0617 09:30:20.200606 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.2822\nINFO:tensorflow:loss = 0.58396643, step = 1700 (77.991 sec)\nI0617 09:30:20.201816 140626870351744 basic_session_run_hooks.py:260] loss = 0.58396643, step = 1700 (77.991 sec)\nINFO:tensorflow:Saving checkpoints for 1703 into training/model.ckpt.\nI0617 09:30:21.796528 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 1703 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe287ca58c8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:30:25.373097 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe287ca58c8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:30:25.799632 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:30:25.826008 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:30:28.565258 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:30:28.577458 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:30:28.577781 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:30:29.031926 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:30:29.280940 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:30:31.076331 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:30:31Z\nI0617 09:30:31.091609 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T09:30:31Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:30:31.744259 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:30:31.744969: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:30:31.745268: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 09:30:31.745364: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:30:31.745387: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:30:31.745428: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:30:31.745448: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:30:31.745468: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:30:31.745491: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:30:31.745515: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:30:31.745640: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:30:31.745967: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:30:31.746252: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:30:31.746351: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:30:31.746365: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:30:31.746374: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:30:31.746512: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:30:31.746860: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:30:31.747126: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-1703\nI0617 09:30:31.748381 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-1703\nINFO:tensorflow:Running local_init_op.\nI0617 09:30:33.341835 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:30:33.520303 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:33:46.702319 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.39s)\nI0617 09:33:47.091455 140623412950784 coco_tools.py:131] DONE (t=0.39s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.78s).\nAccumulating evaluation results...\nDONE (t=2.49s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.350\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.738\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.254\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.359\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.293\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.004\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.267\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.505\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.547\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.541\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.586\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.607\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:34:07\nI0617 09:34:07.117709 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-09:34:07\nINFO:tensorflow:Saving dict for global step 1703: DetectionBoxes_Precision/mAP = 0.35026354, DetectionBoxes_Precision/mAP (large) = 0.004158835, DetectionBoxes_Precision/mAP (medium) = 0.29302272, DetectionBoxes_Precision/mAP (small) = 0.3594482, DetectionBoxes_Precision/[email protected] = 0.7376348, DetectionBoxes_Precision/[email protected] = 0.25429454, DetectionBoxes_Recall/AR@1 = 0.26711193, DetectionBoxes_Recall/AR@10 = 0.5049788, DetectionBoxes_Recall/AR@100 = 0.54691356, DetectionBoxes_Recall/AR@100 (large) = 0.6066667, DetectionBoxes_Recall/AR@100 (medium) = 0.5861912, DetectionBoxes_Recall/AR@100 (small) = 0.5406514, Loss/BoxClassifierLoss/classification_loss = 0.15746221, Loss/BoxClassifierLoss/localization_loss = 0.13000645, Loss/RPNLoss/localization_loss = 0.029511813, Loss/RPNLoss/objectness_loss = 0.04767628, Loss/total_loss = 0.36465728, global_step = 1703, learning_rate = 0.0003, loss = 0.36465728\nI0617 09:34:07.118010 140626870351744 estimator.py:2049] Saving dict for global step 1703: DetectionBoxes_Precision/mAP = 0.35026354, DetectionBoxes_Precision/mAP (large) = 0.004158835, DetectionBoxes_Precision/mAP (medium) = 0.29302272, DetectionBoxes_Precision/mAP (small) = 0.3594482, DetectionBoxes_Precision/[email protected] = 0.7376348, DetectionBoxes_Precision/[email protected] = 0.25429454, DetectionBoxes_Recall/AR@1 = 0.26711193, DetectionBoxes_Recall/AR@10 = 0.5049788, DetectionBoxes_Recall/AR@100 = 0.54691356, DetectionBoxes_Recall/AR@100 (large) = 0.6066667, DetectionBoxes_Recall/AR@100 (medium) = 0.5861912, DetectionBoxes_Recall/AR@100 (small) = 0.5406514, Loss/BoxClassifierLoss/classification_loss = 0.15746221, Loss/BoxClassifierLoss/localization_loss = 0.13000645, Loss/RPNLoss/localization_loss = 0.029511813, Loss/RPNLoss/objectness_loss = 0.04767628, Loss/total_loss = 0.36465728, global_step = 1703, learning_rate = 0.0003, loss = 0.36465728\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 1703: training/model.ckpt-1703\nI0617 09:34:07.118947 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 1703: training/model.ckpt-1703\nINFO:tensorflow:global_step/sec: 0.329614\nI0617 09:35:23.585869 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.329614\nINFO:tensorflow:loss = 0.39880756, step = 1800 (303.385 sec)\nI0617 09:35:23.587078 140626870351744 basic_session_run_hooks.py:260] loss = 0.39880756, step = 1800 (303.385 sec)\nINFO:tensorflow:global_step/sec: 1.2803\nI0617 09:36:41.692876 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.2803\nINFO:tensorflow:loss = 0.6437082, step = 1900 (78.107 sec)\nI0617 09:36:41.693930 140626870351744 basic_session_run_hooks.py:260] loss = 0.6437082, step = 1900 (78.107 sec)\nINFO:tensorflow:global_step/sec: 1.28162\nI0617 09:37:59.719313 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28162\nINFO:tensorflow:loss = 0.52580047, step = 2000 (78.027 sec)\nI0617 09:37:59.720531 140626870351744 basic_session_run_hooks.py:260] loss = 0.52580047, step = 2000 (78.027 sec)\nINFO:tensorflow:global_step/sec: 1.28054\nI0617 09:39:17.811200 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28054\nINFO:tensorflow:loss = 0.47870368, step = 2100 (78.092 sec)\nI0617 09:39:17.812336 140626870351744 basic_session_run_hooks.py:260] loss = 0.47870368, step = 2100 (78.092 sec)\nINFO:tensorflow:Saving checkpoints for 2183 into training/model.ckpt.\nI0617 09:40:21.879032 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 2183 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe544d691e0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:40:25.486286 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe544d691e0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:40:25.908287 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:40:25.934057 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:40:28.676135 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:40:28.689437 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:40:28.689810 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:40:29.132376 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:40:29.388623 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:40:31.149473 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:40:31Z\nI0617 09:40:31.164891 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T09:40:31Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:40:31.828331 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:40:31.829034: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:40:31.829340: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 09:40:31.829435: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:40:31.829464: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:40:31.829486: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:40:31.829511: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:40:31.829532: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:40:31.829551: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:40:31.829594: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:40:31.829711: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:40:31.830050: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:40:31.830281: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:40:31.830322: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:40:31.830336: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:40:31.830345: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:40:31.830476: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:40:31.830789: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:40:31.831030: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2183\nI0617 09:40:31.832103 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-2183\nINFO:tensorflow:Running local_init_op.\nI0617 09:40:33.404684 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:40:33.591391 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:43:45.055660 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.41s)\nI0617 09:43:45.467858 140623412950784 coco_tools.py:131] DONE (t=0.41s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=17.05s).\nAccumulating evaluation results...\nDONE (t=2.48s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.360\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.742\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.288\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.370\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.303\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.011\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.271\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.511\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.554\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.547\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.602\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.613\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:44:05\nI0617 09:44:05.756256 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-09:44:05\nINFO:tensorflow:Saving dict for global step 2183: DetectionBoxes_Precision/mAP = 0.3604455, DetectionBoxes_Precision/mAP (large) = 0.011444105, DetectionBoxes_Precision/mAP (medium) = 0.30338308, DetectionBoxes_Precision/mAP (small) = 0.36952958, DetectionBoxes_Precision/[email protected] = 0.74166983, DetectionBoxes_Precision/[email protected] = 0.2879663, DetectionBoxes_Recall/AR@1 = 0.2714835, DetectionBoxes_Recall/AR@10 = 0.51096946, DetectionBoxes_Recall/AR@100 = 0.5541591, DetectionBoxes_Recall/AR@100 (large) = 0.61333334, DetectionBoxes_Recall/AR@100 (medium) = 0.6019727, DetectionBoxes_Recall/AR@100 (small) = 0.54653233, Loss/BoxClassifierLoss/classification_loss = 0.16684356, Loss/BoxClassifierLoss/localization_loss = 0.12683329, Loss/RPNLoss/localization_loss = 0.02912238, Loss/RPNLoss/objectness_loss = 0.045558438, Loss/total_loss = 0.36835736, global_step = 2183, learning_rate = 0.0003, loss = 0.36835736\nI0617 09:44:05.756548 140626870351744 estimator.py:2049] Saving dict for global step 2183: DetectionBoxes_Precision/mAP = 0.3604455, DetectionBoxes_Precision/mAP (large) = 0.011444105, DetectionBoxes_Precision/mAP (medium) = 0.30338308, DetectionBoxes_Precision/mAP (small) = 0.36952958, DetectionBoxes_Precision/[email protected] = 0.74166983, DetectionBoxes_Precision/[email protected] = 0.2879663, DetectionBoxes_Recall/AR@1 = 0.2714835, DetectionBoxes_Recall/AR@10 = 0.51096946, DetectionBoxes_Recall/AR@100 = 0.5541591, DetectionBoxes_Recall/AR@100 (large) = 0.61333334, DetectionBoxes_Recall/AR@100 (medium) = 0.6019727, DetectionBoxes_Recall/AR@100 (small) = 0.54653233, Loss/BoxClassifierLoss/classification_loss = 0.16684356, Loss/BoxClassifierLoss/localization_loss = 0.12683329, Loss/RPNLoss/localization_loss = 0.02912238, Loss/RPNLoss/objectness_loss = 0.045558438, Loss/total_loss = 0.36835736, global_step = 2183, learning_rate = 0.0003, loss = 0.36835736\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 2183: training/model.ckpt-2183\nI0617 09:44:05.757560 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 2183: training/model.ckpt-2183\nINFO:tensorflow:global_step/sec: 0.331151\nI0617 09:44:19.788629 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.331151\nINFO:tensorflow:loss = 0.59743804, step = 2200 (301.977 sec)\nI0617 09:44:19.789802 140626870351744 basic_session_run_hooks.py:260] loss = 0.59743804, step = 2200 (301.977 sec)\nINFO:tensorflow:global_step/sec: 1.27972\nI0617 09:45:37.930451 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27972\nINFO:tensorflow:loss = 0.60676545, step = 2300 (78.142 sec)\nI0617 09:45:37.931393 140626870351744 basic_session_run_hooks.py:260] loss = 0.60676545, step = 2300 (78.142 sec)\nINFO:tensorflow:global_step/sec: 1.27968\nI0617 09:46:56.075233 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27968\nINFO:tensorflow:loss = 0.641906, step = 2400 (78.145 sec)\nI0617 09:46:56.076241 140626870351744 basic_session_run_hooks.py:260] loss = 0.641906, step = 2400 (78.145 sec)\nINFO:tensorflow:global_step/sec: 1.28074\nI0617 09:48:14.155119 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28074\nINFO:tensorflow:loss = 0.6851827, step = 2500 (78.080 sec)\nI0617 09:48:14.156183 140626870351744 basic_session_run_hooks.py:260] loss = 0.6851827, step = 2500 (78.080 sec)\nINFO:tensorflow:global_step/sec: 1.28008\nI0617 09:49:32.275528 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28008\nINFO:tensorflow:loss = 0.41374606, step = 2600 (78.120 sec)\nI0617 09:49:32.276667 140626870351744 basic_session_run_hooks.py:260] loss = 0.41374606, step = 2600 (78.120 sec)\nINFO:tensorflow:Saving checkpoints for 2665 into training/model.ckpt.\nI0617 09:50:22.164527 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 2665 into training/model.ckpt.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/saver.py:963: remove_checkpoint (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to delete files with this prefix.\nW0617 09:50:23.534569 140626870351744 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/saver.py:963: remove_checkpoint (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to delete files with this prefix.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe26c4d90d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 09:50:25.864950 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe26c4d90d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 09:50:26.298575 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:50:26.324813 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:50:29.084936 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:50:29.097719 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 09:50:29.098061 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:50:29.540470 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 09:50:29.797441 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 09:50:31.547474 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T09:50:31Z\nI0617 09:50:31.566509 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T09:50:31Z\nINFO:tensorflow:Graph was finalized.\nI0617 09:50:32.219486 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 09:50:32.220193: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:50:32.220496: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 09:50:32.220599: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 09:50:32.220631: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 09:50:32.220654: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 09:50:32.220681: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 09:50:32.220703: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 09:50:32.220723: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 09:50:32.220743: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 09:50:32.220855: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:50:32.221186: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:50:32.221404: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 09:50:32.221488: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 09:50:32.221503: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 09:50:32.221511: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 09:50:32.221651: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:50:32.221981: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 09:50:32.222213: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-2665\nI0617 09:50:32.223447 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-2665\nINFO:tensorflow:Running local_init_op.\nI0617 09:50:33.810696 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 09:50:33.996209 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 09:53:45.822856 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.38s)\nI0617 09:53:46.203857 140623412950784 coco_tools.py:131] DONE (t=0.38s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.84s).\nAccumulating evaluation results...\nDONE (t=2.47s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.355\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.733\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.277\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.364\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.305\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.018\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.272\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.509\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.552\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.546\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.592\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.647\nINFO:tensorflow:Finished evaluation at 2020-06-17-09:54:06\nI0617 09:54:06.279713 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-09:54:06\nINFO:tensorflow:Saving dict for global step 2665: DetectionBoxes_Precision/mAP = 0.35454267, DetectionBoxes_Precision/mAP (large) = 0.017795753, DetectionBoxes_Precision/mAP (medium) = 0.30537555, DetectionBoxes_Precision/mAP (small) = 0.3638684, DetectionBoxes_Precision/[email protected] = 0.733447, DetectionBoxes_Precision/[email protected] = 0.27683026, DetectionBoxes_Recall/AR@1 = 0.27227283, DetectionBoxes_Recall/AR@10 = 0.5094313, DetectionBoxes_Recall/AR@100 = 0.5523578, DetectionBoxes_Recall/AR@100 (large) = 0.64666665, DetectionBoxes_Recall/AR@100 (medium) = 0.59180576, DetectionBoxes_Recall/AR@100 (small) = 0.5459232, Loss/BoxClassifierLoss/classification_loss = 0.16357653, Loss/BoxClassifierLoss/localization_loss = 0.13031381, Loss/RPNLoss/localization_loss = 0.029621221, Loss/RPNLoss/objectness_loss = 0.04932744, Loss/total_loss = 0.3728393, global_step = 2665, learning_rate = 0.0003, loss = 0.3728393\nI0617 09:54:06.280013 140626870351744 estimator.py:2049] Saving dict for global step 2665: DetectionBoxes_Precision/mAP = 0.35454267, DetectionBoxes_Precision/mAP (large) = 0.017795753, DetectionBoxes_Precision/mAP (medium) = 0.30537555, DetectionBoxes_Precision/mAP (small) = 0.3638684, DetectionBoxes_Precision/[email protected] = 0.733447, DetectionBoxes_Precision/[email protected] = 0.27683026, DetectionBoxes_Recall/AR@1 = 0.27227283, DetectionBoxes_Recall/AR@10 = 0.5094313, DetectionBoxes_Recall/AR@100 = 0.5523578, DetectionBoxes_Recall/AR@100 (large) = 0.64666665, DetectionBoxes_Recall/AR@100 (medium) = 0.59180576, DetectionBoxes_Recall/AR@100 (small) = 0.5459232, Loss/BoxClassifierLoss/classification_loss = 0.16357653, Loss/BoxClassifierLoss/localization_loss = 0.13031381, Loss/RPNLoss/localization_loss = 0.029621221, Loss/RPNLoss/objectness_loss = 0.04932744, Loss/total_loss = 0.3728393, global_step = 2665, learning_rate = 0.0003, loss = 0.3728393\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 2665: training/model.ckpt-2665\nI0617 09:54:06.280923 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 2665: training/model.ckpt-2665\nINFO:tensorflow:global_step/sec: 0.330943\nI0617 09:54:34.442787 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.330943\nINFO:tensorflow:loss = 0.5714846, step = 2700 (302.167 sec)\nI0617 09:54:34.444084 140626870351744 basic_session_run_hooks.py:260] loss = 0.5714846, step = 2700 (302.167 sec)\nINFO:tensorflow:global_step/sec: 1.28397\nI0617 09:55:52.325942 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28397\nINFO:tensorflow:loss = 0.67150706, step = 2800 (77.883 sec)\nI0617 09:55:52.327135 140626870351744 basic_session_run_hooks.py:260] loss = 0.67150706, step = 2800 (77.883 sec)\nINFO:tensorflow:global_step/sec: 1.2833\nI0617 09:57:10.250084 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.2833\nINFO:tensorflow:loss = 0.5609437, step = 2900 (77.924 sec)\nI0617 09:57:10.251349 140626870351744 basic_session_run_hooks.py:260] loss = 0.5609437, step = 2900 (77.924 sec)\nINFO:tensorflow:global_step/sec: 1.2776\nI0617 09:58:28.521588 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.2776\nINFO:tensorflow:loss = 0.6144182, step = 3000 (78.271 sec)\nI0617 09:58:28.522636 140626870351744 basic_session_run_hooks.py:260] loss = 0.6144182, step = 3000 (78.271 sec)\nINFO:tensorflow:global_step/sec: 1.28354\nI0617 09:59:46.431192 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28354\nINFO:tensorflow:loss = 0.56862134, step = 3100 (77.910 sec)\nI0617 09:59:46.432426 140626870351744 basic_session_run_hooks.py:260] loss = 0.56862134, step = 3100 (77.910 sec)\nINFO:tensorflow:Saving checkpoints for 3147 into training/model.ckpt.\nI0617 10:00:22.338126 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 3147 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe277b8d1e0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:00:26.053051 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe277b8d1e0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:00:26.477441 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:00:26.503793 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:00:29.624325 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:00:29.636837 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:00:29.637178 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:00:30.079743 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:00:30.332455 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:00:32.130332 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:00:32Z\nI0617 10:00:32.145547 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T10:00:32Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:00:32.796365 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:00:32.797106: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:00:32.797396: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 10:00:32.797491: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:00:32.797516: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:00:32.797539: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:00:32.797561: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:00:32.797587: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:00:32.797607: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:00:32.797627: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:00:32.797741: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:00:32.798095: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:00:32.798326: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:00:32.798370: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:00:32.798384: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:00:32.798393: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:00:32.798525: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:00:32.798823: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:00:32.799062: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-3147\nI0617 10:00:32.800132 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-3147\nINFO:tensorflow:Running local_init_op.\nI0617 10:00:34.455596 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:00:34.650031 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:03:45.577576 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.41s)\nI0617 10:03:45.988713 140623412950784 coco_tools.py:131] DONE (t=0.41s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.81s).\nAccumulating evaluation results...\nDONE (t=2.52s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.354\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.734\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.284\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.361\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.308\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.012\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.273\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.510\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.553\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.545\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.600\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.680\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:04:06\nI0617 10:04:06.074697 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-10:04:06\nINFO:tensorflow:Saving dict for global step 3147: DetectionBoxes_Precision/mAP = 0.3537408, DetectionBoxes_Precision/mAP (large) = 0.011778688, DetectionBoxes_Precision/mAP (medium) = 0.30830944, DetectionBoxes_Precision/mAP (small) = 0.36135313, DetectionBoxes_Precision/[email protected] = 0.734487, DetectionBoxes_Precision/[email protected] = 0.28439647, DetectionBoxes_Recall/AR@1 = 0.27308238, DetectionBoxes_Recall/AR@10 = 0.51036227, DetectionBoxes_Recall/AR@100 = 0.5526007, DetectionBoxes_Recall/AR@100 (large) = 0.68, DetectionBoxes_Recall/AR@100 (medium) = 0.5996965, DetectionBoxes_Recall/AR@100 (small) = 0.5448922, Loss/BoxClassifierLoss/classification_loss = 0.16500027, Loss/BoxClassifierLoss/localization_loss = 0.12706405, Loss/RPNLoss/localization_loss = 0.029571334, Loss/RPNLoss/objectness_loss = 0.048917245, Loss/total_loss = 0.37055334, global_step = 3147, learning_rate = 0.0003, loss = 0.37055334\nI0617 10:04:06.074999 140626870351744 estimator.py:2049] Saving dict for global step 3147: DetectionBoxes_Precision/mAP = 0.3537408, DetectionBoxes_Precision/mAP (large) = 0.011778688, DetectionBoxes_Precision/mAP (medium) = 0.30830944, DetectionBoxes_Precision/mAP (small) = 0.36135313, DetectionBoxes_Precision/[email protected] = 0.734487, DetectionBoxes_Precision/[email protected] = 0.28439647, DetectionBoxes_Recall/AR@1 = 0.27308238, DetectionBoxes_Recall/AR@10 = 0.51036227, DetectionBoxes_Recall/AR@100 = 0.5526007, DetectionBoxes_Recall/AR@100 (large) = 0.68, DetectionBoxes_Recall/AR@100 (medium) = 0.5996965, DetectionBoxes_Recall/AR@100 (small) = 0.5448922, Loss/BoxClassifierLoss/classification_loss = 0.16500027, Loss/BoxClassifierLoss/localization_loss = 0.12706405, Loss/RPNLoss/localization_loss = 0.029571334, Loss/RPNLoss/objectness_loss = 0.048917245, Loss/total_loss = 0.37055334, global_step = 3147, learning_rate = 0.0003, loss = 0.37055334\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 3147: training/model.ckpt-3147\nI0617 10:04:06.075951 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 3147: training/model.ckpt-3147\nINFO:tensorflow:global_step/sec: 0.331294\nI0617 10:04:48.278002 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.331294\nINFO:tensorflow:loss = 0.61747855, step = 3200 (301.847 sec)\nI0617 10:04:48.279203 140626870351744 basic_session_run_hooks.py:260] loss = 0.61747855, step = 3200 (301.847 sec)\nINFO:tensorflow:global_step/sec: 1.27739\nI0617 10:06:06.562511 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27739\nINFO:tensorflow:loss = 0.5374551, step = 3300 (78.284 sec)\nI0617 10:06:06.563679 140626870351744 basic_session_run_hooks.py:260] loss = 0.5374551, step = 3300 (78.284 sec)\nINFO:tensorflow:global_step/sec: 1.28219\nI0617 10:07:24.553790 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28219\nINFO:tensorflow:loss = 0.56191707, step = 3400 (77.991 sec)\nI0617 10:07:24.555084 140626870351744 basic_session_run_hooks.py:260] loss = 0.56191707, step = 3400 (77.991 sec)\nINFO:tensorflow:global_step/sec: 1.28136\nI0617 10:08:42.595657 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28136\nINFO:tensorflow:loss = 0.49502504, step = 3500 (78.042 sec)\nI0617 10:08:42.596651 140626870351744 basic_session_run_hooks.py:260] loss = 0.49502504, step = 3500 (78.042 sec)\nINFO:tensorflow:global_step/sec: 1.27936\nI0617 10:10:00.759872 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27936\nINFO:tensorflow:loss = 0.53125226, step = 3600 (78.165 sec)\nI0617 10:10:00.761362 140626870351744 basic_session_run_hooks.py:260] loss = 0.53125226, step = 3600 (78.165 sec)\nINFO:tensorflow:Saving checkpoints for 3629 into training/model.ckpt.\nI0617 10:10:22.562315 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 3629 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe26ab708c8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:10:26.255181 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe26ab708c8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:10:26.678377 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:10:26.705323 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:10:29.449012 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:10:29.461740 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:10:29.462078 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:10:29.904796 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:10:30.162547 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:10:31.939446 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:10:31Z\nI0617 10:10:31.954478 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T10:10:31Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:10:32.598667 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:10:32.599411: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:10:32.599721: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 10:10:32.599812: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:10:32.599837: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:10:32.599859: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:10:32.599882: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:10:32.599916: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:10:32.599938: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:10:32.599960: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:10:32.600069: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:10:32.600370: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:10:32.600584: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:10:32.600664: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:10:32.600678: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:10:32.600687: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:10:32.600825: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:10:32.601145: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:10:32.601417: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-3629\nI0617 10:10:32.602469 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-3629\nINFO:tensorflow:Running local_init_op.\nI0617 10:10:34.208880 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:10:34.396227 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:13:47.877571 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.39s)\nI0617 10:13:48.270335 140623412950784 coco_tools.py:131] DONE (t=0.39s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.86s).\nAccumulating evaluation results...\nDONE (t=2.50s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.359\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.749\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.272\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.366\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.307\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.023\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.273\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.506\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.547\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.538\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.598\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.633\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:14:08\nI0617 10:14:08.428132 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-10:14:08\nINFO:tensorflow:Saving dict for global step 3629: DetectionBoxes_Precision/mAP = 0.35865676, DetectionBoxes_Precision/mAP (large) = 0.023248209, DetectionBoxes_Precision/mAP (medium) = 0.30749446, DetectionBoxes_Precision/mAP (small) = 0.36647624, DetectionBoxes_Precision/[email protected] = 0.7485957, DetectionBoxes_Precision/[email protected] = 0.2722362, DetectionBoxes_Recall/AR@1 = 0.27296093, DetectionBoxes_Recall/AR@10 = 0.5058895, DetectionBoxes_Recall/AR@100 = 0.54669094, DetectionBoxes_Recall/AR@100 (large) = 0.6333333, DetectionBoxes_Recall/AR@100 (medium) = 0.59817904, DetectionBoxes_Recall/AR@100 (small) = 0.5384255, Loss/BoxClassifierLoss/classification_loss = 0.15685257, Loss/BoxClassifierLoss/localization_loss = 0.13080662, Loss/RPNLoss/localization_loss = 0.028862972, Loss/RPNLoss/objectness_loss = 0.046564173, Loss/total_loss = 0.3630861, global_step = 3629, learning_rate = 0.0003, loss = 0.3630861\nI0617 10:14:08.428433 140626870351744 estimator.py:2049] Saving dict for global step 3629: DetectionBoxes_Precision/mAP = 0.35865676, DetectionBoxes_Precision/mAP (large) = 0.023248209, DetectionBoxes_Precision/mAP (medium) = 0.30749446, DetectionBoxes_Precision/mAP (small) = 0.36647624, DetectionBoxes_Precision/[email protected] = 0.7485957, DetectionBoxes_Precision/[email protected] = 0.2722362, DetectionBoxes_Recall/AR@1 = 0.27296093, DetectionBoxes_Recall/AR@10 = 0.5058895, DetectionBoxes_Recall/AR@100 = 0.54669094, DetectionBoxes_Recall/AR@100 (large) = 0.6333333, DetectionBoxes_Recall/AR@100 (medium) = 0.59817904, DetectionBoxes_Recall/AR@100 (small) = 0.5384255, Loss/BoxClassifierLoss/classification_loss = 0.15685257, Loss/BoxClassifierLoss/localization_loss = 0.13080662, Loss/RPNLoss/localization_loss = 0.028862972, Loss/RPNLoss/objectness_loss = 0.046564173, Loss/total_loss = 0.3630861, global_step = 3629, learning_rate = 0.0003, loss = 0.3630861\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 3629: training/model.ckpt-3629\nI0617 10:14:08.429383 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 3629: training/model.ckpt-3629\nINFO:tensorflow:global_step/sec: 0.328863\nI0617 10:15:04.837471 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.328863\nINFO:tensorflow:loss = 0.6161774, step = 3700 (304.077 sec)\nI0617 10:15:04.838436 140626870351744 basic_session_run_hooks.py:260] loss = 0.6161774, step = 3700 (304.077 sec)\nINFO:tensorflow:global_step/sec: 1.27882\nI0617 10:16:23.034434 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27882\nINFO:tensorflow:loss = 0.49155244, step = 3800 (78.197 sec)\nI0617 10:16:23.035412 140626870351744 basic_session_run_hooks.py:260] loss = 0.49155244, step = 3800 (78.197 sec)\nINFO:tensorflow:global_step/sec: 1.2786\nI0617 10:17:41.245131 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.2786\nINFO:tensorflow:loss = 0.73171675, step = 3900 (78.211 sec)\nI0617 10:17:41.246343 140626870351744 basic_session_run_hooks.py:260] loss = 0.73171675, step = 3900 (78.211 sec)\nINFO:tensorflow:global_step/sec: 1.27776\nI0617 10:18:59.506954 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27776\nINFO:tensorflow:loss = 0.9302973, step = 4000 (78.262 sec)\nI0617 10:18:59.508074 140626870351744 basic_session_run_hooks.py:260] loss = 0.9302973, step = 4000 (78.262 sec)\nINFO:tensorflow:global_step/sec: 1.27948\nI0617 10:20:17.664002 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27948\nINFO:tensorflow:loss = 0.6789362, step = 4100 (78.157 sec)\nI0617 10:20:17.665114 140626870351744 basic_session_run_hooks.py:260] loss = 0.6789362, step = 4100 (78.157 sec)\nINFO:tensorflow:Saving checkpoints for 4108 into training/model.ckpt.\nI0617 10:20:23.124977 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 4108 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe26ab700d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:20:26.877270 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe26ab700d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:20:27.303912 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:20:27.330389 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:20:30.077683 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:20:30.090431 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:20:30.090771 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:20:30.531064 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:20:30.797829 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:20:32.558160 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:20:32Z\nI0617 10:20:32.572999 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T10:20:32Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:20:33.220927 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:20:33.221646: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:20:33.222047: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 10:20:33.222160: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:20:33.222198: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:20:33.222223: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:20:33.222243: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:20:33.222262: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:20:33.222281: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:20:33.222301: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:20:33.222412: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:20:33.222734: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:20:33.222970: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:20:33.223015: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:20:33.223028: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:20:33.223037: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:20:33.223164: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:20:33.223462: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:20:33.223694: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-4108\nI0617 10:20:33.224827 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-4108\nINFO:tensorflow:Running local_init_op.\nI0617 10:20:34.833998 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:20:35.022238 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:23:46.675792 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.40s)\nI0617 10:23:47.072021 140623412950784 coco_tools.py:131] DONE (t=0.40s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.78s).\nAccumulating evaluation results...\nDONE (t=2.50s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.370\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.753\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.303\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.380\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.316\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.031\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.279\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.520\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.559\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.552\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.601\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.693\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:24:07\nI0617 10:24:07.125383 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-10:24:07\nINFO:tensorflow:Saving dict for global step 4108: DetectionBoxes_Precision/mAP = 0.3700234, DetectionBoxes_Precision/mAP (large) = 0.030702423, DetectionBoxes_Precision/mAP (medium) = 0.3162931, DetectionBoxes_Precision/mAP (small) = 0.37966132, DetectionBoxes_Precision/[email protected] = 0.75278336, DetectionBoxes_Precision/[email protected] = 0.30342102, DetectionBoxes_Recall/AR@1 = 0.2791945, DetectionBoxes_Recall/AR@10 = 0.5203805, DetectionBoxes_Recall/AR@100 = 0.5591783, DetectionBoxes_Recall/AR@100 (large) = 0.6933333, DetectionBoxes_Recall/AR@100 (medium) = 0.600607, DetectionBoxes_Recall/AR@100 (small) = 0.5523196, Loss/BoxClassifierLoss/classification_loss = 0.15474711, Loss/BoxClassifierLoss/localization_loss = 0.12742703, Loss/RPNLoss/localization_loss = 0.02939345, Loss/RPNLoss/objectness_loss = 0.048543077, Loss/total_loss = 0.36011076, global_step = 4108, learning_rate = 0.0003, loss = 0.36011076\nI0617 10:24:07.125662 140626870351744 estimator.py:2049] Saving dict for global step 4108: DetectionBoxes_Precision/mAP = 0.3700234, DetectionBoxes_Precision/mAP (large) = 0.030702423, DetectionBoxes_Precision/mAP (medium) = 0.3162931, DetectionBoxes_Precision/mAP (small) = 0.37966132, DetectionBoxes_Precision/[email protected] = 0.75278336, DetectionBoxes_Precision/[email protected] = 0.30342102, DetectionBoxes_Recall/AR@1 = 0.2791945, DetectionBoxes_Recall/AR@10 = 0.5203805, DetectionBoxes_Recall/AR@100 = 0.5591783, DetectionBoxes_Recall/AR@100 (large) = 0.6933333, DetectionBoxes_Recall/AR@100 (medium) = 0.600607, DetectionBoxes_Recall/AR@100 (small) = 0.5523196, Loss/BoxClassifierLoss/classification_loss = 0.15474711, Loss/BoxClassifierLoss/localization_loss = 0.12742703, Loss/RPNLoss/localization_loss = 0.02939345, Loss/RPNLoss/objectness_loss = 0.048543077, Loss/total_loss = 0.36011076, global_step = 4108, learning_rate = 0.0003, loss = 0.36011076\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 4108: training/model.ckpt-4108\nI0617 10:24:07.126700 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 4108: training/model.ckpt-4108\nINFO:tensorflow:global_step/sec: 0.330912\nI0617 10:25:19.859094 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.330912\nINFO:tensorflow:loss = 0.6541584, step = 4200 (302.195 sec)\nI0617 10:25:19.860203 140626870351744 basic_session_run_hooks.py:260] loss = 0.6541584, step = 4200 (302.195 sec)\nINFO:tensorflow:global_step/sec: 1.282\nI0617 10:26:37.861953 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.282\nINFO:tensorflow:loss = 0.5348252, step = 4300 (78.003 sec)\nI0617 10:26:37.863142 140626870351744 basic_session_run_hooks.py:260] loss = 0.5348252, step = 4300 (78.003 sec)\nINFO:tensorflow:global_step/sec: 1.27723\nI0617 10:27:56.156102 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27723\nINFO:tensorflow:loss = 0.3457889, step = 4400 (78.294 sec)\nI0617 10:27:56.157269 140626870351744 basic_session_run_hooks.py:260] loss = 0.3457889, step = 4400 (78.294 sec)\nINFO:tensorflow:global_step/sec: 1.28118\nI0617 10:29:14.208870 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28118\nINFO:tensorflow:loss = 0.4076098, step = 4500 (78.053 sec)\nI0617 10:29:14.209923 140626870351744 basic_session_run_hooks.py:260] loss = 0.4076098, step = 4500 (78.053 sec)\nINFO:tensorflow:Saving checkpoints for 4590 into training/model.ckpt.\nI0617 10:30:23.713011 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 4590 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe26bfa22f0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:30:27.452865 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe26bfa22f0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:30:27.885601 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:30:27.912102 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:30:30.652158 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:30:30.664421 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:30:30.664748 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:30:31.111496 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:30:31.370558 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:30:33.134457 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:30:33Z\nI0617 10:30:33.149610 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T10:30:33Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:30:33.797358 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:30:33.798072: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:30:33.798377: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 10:30:33.798488: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:30:33.798513: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:30:33.798536: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:30:33.798558: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:30:33.798586: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:30:33.798613: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:30:33.798633: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:30:33.798747: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:30:33.799131: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:30:33.799343: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:30:33.799437: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:30:33.799451: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:30:33.799460: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:30:33.799589: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:30:33.799889: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:30:33.800142: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-4590\nI0617 10:30:33.801277 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-4590\nINFO:tensorflow:Running local_init_op.\nI0617 10:30:35.429614 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:30:35.614787 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:33:46.699657 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.39s)\nI0617 10:33:47.091320 140623412950784 coco_tools.py:131] DONE (t=0.39s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.83s).\nAccumulating evaluation results...\nDONE (t=2.48s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.366\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.751\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.293\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.374\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.317\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.025\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.278\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.520\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.559\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.552\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.600\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.660\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:34:07\nI0617 10:34:07.166863 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-10:34:07\nINFO:tensorflow:Saving dict for global step 4590: DetectionBoxes_Precision/mAP = 0.36588943, DetectionBoxes_Precision/mAP (large) = 0.02467807, DetectionBoxes_Precision/mAP (medium) = 0.31734407, DetectionBoxes_Precision/mAP (small) = 0.37371987, DetectionBoxes_Precision/[email protected] = 0.75083137, DetectionBoxes_Precision/[email protected] = 0.29280156, DetectionBoxes_Recall/AR@1 = 0.2781016, DetectionBoxes_Recall/AR@10 = 0.51969236, DetectionBoxes_Recall/AR@100 = 0.55883425, DetectionBoxes_Recall/AR@100 (large) = 0.66, DetectionBoxes_Recall/AR@100 (medium) = 0.6003035, DetectionBoxes_Recall/AR@100 (small) = 0.5520853, Loss/BoxClassifierLoss/classification_loss = 0.1614168, Loss/BoxClassifierLoss/localization_loss = 0.12654638, Loss/RPNLoss/localization_loss = 0.028816273, Loss/RPNLoss/objectness_loss = 0.047004834, Loss/total_loss = 0.36378407, global_step = 4590, learning_rate = 0.0003, loss = 0.36378407\nI0617 10:34:07.167186 140626870351744 estimator.py:2049] Saving dict for global step 4590: DetectionBoxes_Precision/mAP = 0.36588943, DetectionBoxes_Precision/mAP (large) = 0.02467807, DetectionBoxes_Precision/mAP (medium) = 0.31734407, DetectionBoxes_Precision/mAP (small) = 0.37371987, DetectionBoxes_Precision/[email protected] = 0.75083137, DetectionBoxes_Precision/[email protected] = 0.29280156, DetectionBoxes_Recall/AR@1 = 0.2781016, DetectionBoxes_Recall/AR@10 = 0.51969236, DetectionBoxes_Recall/AR@100 = 0.55883425, DetectionBoxes_Recall/AR@100 (large) = 0.66, DetectionBoxes_Recall/AR@100 (medium) = 0.6003035, DetectionBoxes_Recall/AR@100 (small) = 0.5520853, Loss/BoxClassifierLoss/classification_loss = 0.1614168, Loss/BoxClassifierLoss/localization_loss = 0.12654638, Loss/RPNLoss/localization_loss = 0.028816273, Loss/RPNLoss/objectness_loss = 0.047004834, Loss/total_loss = 0.36378407, global_step = 4590, learning_rate = 0.0003, loss = 0.36378407\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 4590: training/model.ckpt-4590\nI0617 10:34:07.168081 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 4590: training/model.ckpt-4590\nINFO:tensorflow:global_step/sec: 0.331629\nI0617 10:34:15.750813 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.331629\nINFO:tensorflow:loss = 0.7082207, step = 4600 (301.542 sec)\nI0617 10:34:15.751995 140626870351744 basic_session_run_hooks.py:260] loss = 0.7082207, step = 4600 (301.542 sec)\nINFO:tensorflow:global_step/sec: 1.27843\nI0617 10:35:33.972025 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27843\nINFO:tensorflow:loss = 0.5735248, step = 4700 (78.221 sec)\nI0617 10:35:33.972986 140626870351744 basic_session_run_hooks.py:260] loss = 0.5735248, step = 4700 (78.221 sec)\nINFO:tensorflow:global_step/sec: 1.28212\nI0617 10:36:51.967699 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28212\nINFO:tensorflow:loss = 0.42972475, step = 4800 (77.996 sec)\nI0617 10:36:51.968835 140626870351744 basic_session_run_hooks.py:260] loss = 0.42972475, step = 4800 (77.996 sec)\nINFO:tensorflow:global_step/sec: 1.28166\nI0617 10:38:09.991439 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28166\nINFO:tensorflow:loss = 0.67952955, step = 4900 (78.024 sec)\nI0617 10:38:09.992465 140626870351744 basic_session_run_hooks.py:260] loss = 0.67952955, step = 4900 (78.024 sec)\nINFO:tensorflow:global_step/sec: 1.2836\nI0617 10:39:27.897501 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.2836\nINFO:tensorflow:loss = 0.83128893, step = 5000 (77.906 sec)\nI0617 10:39:27.898498 140626870351744 basic_session_run_hooks.py:260] loss = 0.83128893, step = 5000 (77.906 sec)\nINFO:tensorflow:Saving checkpoints for 5073 into training/model.ckpt.\nI0617 10:40:24.179537 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 5073 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe278c06158> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:40:27.863570 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe278c06158> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:40:28.299134 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:40:28.324838 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:40:31.056787 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:40:31.068925 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:40:31.069242 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:40:31.507144 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:40:31.761714 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:40:33.513671 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:40:33Z\nI0617 10:40:33.529868 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T10:40:33Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:40:34.194325 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:40:34.195068: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:40:34.195404: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 10:40:34.195504: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:40:34.195529: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:40:34.195551: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:40:34.195572: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:40:34.195593: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:40:34.195616: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:40:34.195639: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:40:34.195747: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:40:34.196175: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:40:34.196407: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:40:34.196447: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:40:34.196460: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:40:34.196468: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:40:34.196587: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:40:34.196943: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:40:34.197201: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-5073\nI0617 10:40:34.198258 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-5073\nINFO:tensorflow:Running local_init_op.\nI0617 10:40:35.824695 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:40:36.010998 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:43:47.224718 140623421343488 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.40s)\nI0617 10:43:47.625650 140623421343488 coco_tools.py:131] DONE (t=0.40s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=17.18s).\nAccumulating evaluation results...\nDONE (t=2.46s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.378\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.756\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.320\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.385\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.328\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.051\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.281\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.531\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.569\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.561\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.621\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.647\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:44:08\nI0617 10:44:08.006761 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-10:44:08\nINFO:tensorflow:Saving dict for global step 5073: DetectionBoxes_Precision/mAP = 0.3775027, DetectionBoxes_Precision/mAP (large) = 0.050679274, DetectionBoxes_Precision/mAP (medium) = 0.32801136, DetectionBoxes_Precision/mAP (small) = 0.38512984, DetectionBoxes_Precision/[email protected] = 0.7562433, DetectionBoxes_Precision/[email protected] = 0.3196513, DetectionBoxes_Recall/AR@1 = 0.28053024, DetectionBoxes_Recall/AR@10 = 0.53141063, DetectionBoxes_Recall/AR@100 = 0.5691965, DetectionBoxes_Recall/AR@100 (large) = 0.64666665, DetectionBoxes_Recall/AR@100 (medium) = 0.62139606, DetectionBoxes_Recall/AR@100 (small) = 0.5608482, Loss/BoxClassifierLoss/classification_loss = 0.15752065, Loss/BoxClassifierLoss/localization_loss = 0.12370388, Loss/RPNLoss/localization_loss = 0.028634785, Loss/RPNLoss/objectness_loss = 0.047720816, Loss/total_loss = 0.3575807, global_step = 5073, learning_rate = 0.0003, loss = 0.3575807\nI0617 10:44:08.007064 140626870351744 estimator.py:2049] Saving dict for global step 5073: DetectionBoxes_Precision/mAP = 0.3775027, DetectionBoxes_Precision/mAP (large) = 0.050679274, DetectionBoxes_Precision/mAP (medium) = 0.32801136, DetectionBoxes_Precision/mAP (small) = 0.38512984, DetectionBoxes_Precision/[email protected] = 0.7562433, DetectionBoxes_Precision/[email protected] = 0.3196513, DetectionBoxes_Recall/AR@1 = 0.28053024, DetectionBoxes_Recall/AR@10 = 0.53141063, DetectionBoxes_Recall/AR@100 = 0.5691965, DetectionBoxes_Recall/AR@100 (large) = 0.64666665, DetectionBoxes_Recall/AR@100 (medium) = 0.62139606, DetectionBoxes_Recall/AR@100 (small) = 0.5608482, Loss/BoxClassifierLoss/classification_loss = 0.15752065, Loss/BoxClassifierLoss/localization_loss = 0.12370388, Loss/RPNLoss/localization_loss = 0.028634785, Loss/RPNLoss/objectness_loss = 0.047720816, Loss/total_loss = 0.3575807, global_step = 5073, learning_rate = 0.0003, loss = 0.3575807\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 5073: training/model.ckpt-5073\nI0617 10:44:08.007982 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 5073: training/model.ckpt-5073\nINFO:tensorflow:global_step/sec: 0.331098\nI0617 10:44:29.922966 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.331098\nINFO:tensorflow:loss = 0.3686535, step = 5100 (302.025 sec)\nI0617 10:44:29.923841 140626870351744 basic_session_run_hooks.py:260] loss = 0.3686535, step = 5100 (302.025 sec)\nINFO:tensorflow:global_step/sec: 1.28241\nI0617 10:45:47.901190 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28241\nINFO:tensorflow:loss = 0.6603526, step = 5200 (77.978 sec)\nI0617 10:45:47.902219 140626870351744 basic_session_run_hooks.py:260] loss = 0.6603526, step = 5200 (77.978 sec)\nINFO:tensorflow:global_step/sec: 1.28096\nI0617 10:47:05.967815 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28096\nINFO:tensorflow:loss = 0.5303992, step = 5300 (78.067 sec)\nI0617 10:47:05.969085 140626870351744 basic_session_run_hooks.py:260] loss = 0.5303992, step = 5300 (78.067 sec)\nINFO:tensorflow:global_step/sec: 1.28065\nI0617 10:48:24.053293 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28065\nINFO:tensorflow:loss = 0.6947307, step = 5400 (78.085 sec)\nI0617 10:48:24.054181 140626870351744 basic_session_run_hooks.py:260] loss = 0.6947307, step = 5400 (78.085 sec)\nINFO:tensorflow:global_step/sec: 1.27622\nI0617 10:49:42.409462 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27622\nINFO:tensorflow:loss = 0.8008859, step = 5500 (78.357 sec)\nI0617 10:49:42.410718 140626870351744 basic_session_run_hooks.py:260] loss = 0.8008859, step = 5500 (78.357 sec)\nINFO:tensorflow:Saving checkpoints for 5555 into training/model.ckpt.\nI0617 10:50:24.458422 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 5555 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe287d240d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 10:50:28.140138 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe287d240d0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 10:50:28.566371 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:50:28.592549 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:50:31.344924 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:50:31.357505 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 10:50:31.357836 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:50:31.791820 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 10:50:32.041673 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 10:50:33.802592 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T10:50:33Z\nI0617 10:50:33.817805 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T10:50:33Z\nINFO:tensorflow:Graph was finalized.\nI0617 10:50:34.462670 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 10:50:34.463378: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:50:34.463665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 10:50:34.463753: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 10:50:34.463777: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 10:50:34.463800: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 10:50:34.463821: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 10:50:34.463842: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 10:50:34.463867: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 10:50:34.463888: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 10:50:34.464025: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:50:34.464364: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:50:34.464595: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 10:50:34.464682: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 10:50:34.464700: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 10:50:34.464709: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 10:50:34.464841: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:50:34.465163: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 10:50:34.465405: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-5555\nI0617 10:50:34.466624 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-5555\nINFO:tensorflow:Running local_init_op.\nI0617 10:50:36.083552 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 10:50:36.289159 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 10:53:47.699677 140623421343488 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.42s)\nI0617 10:53:48.120084 140623421343488 coco_tools.py:131] DONE (t=0.42s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.61s).\nAccumulating evaluation results...\nDONE (t=2.44s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.368\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.751\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.295\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.377\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.313\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.041\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.279\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.522\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.560\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.553\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.598\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.620\nINFO:tensorflow:Finished evaluation at 2020-06-17-10:54:07\nI0617 10:54:07.912842 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-10:54:07\nINFO:tensorflow:Saving dict for global step 5555: DetectionBoxes_Precision/mAP = 0.36846098, DetectionBoxes_Precision/mAP (large) = 0.04111025, DetectionBoxes_Precision/mAP (medium) = 0.31309694, DetectionBoxes_Precision/mAP (small) = 0.3770236, DetectionBoxes_Precision/[email protected] = 0.75070286, DetectionBoxes_Precision/[email protected] = 0.29450706, DetectionBoxes_Recall/AR@1 = 0.27907306, DetectionBoxes_Recall/AR@10 = 0.52206033, DetectionBoxes_Recall/AR@100 = 0.5595021, DetectionBoxes_Recall/AR@100 (large) = 0.62, DetectionBoxes_Recall/AR@100 (medium) = 0.5980273, DetectionBoxes_Recall/AR@100 (small) = 0.5533271, Loss/BoxClassifierLoss/classification_loss = 0.1670357, Loss/BoxClassifierLoss/localization_loss = 0.12627587, Loss/RPNLoss/localization_loss = 0.029111363, Loss/RPNLoss/objectness_loss = 0.05003918, Loss/total_loss = 0.37246218, global_step = 5555, learning_rate = 0.0003, loss = 0.37246218\nI0617 10:54:07.913162 140626870351744 estimator.py:2049] Saving dict for global step 5555: DetectionBoxes_Precision/mAP = 0.36846098, DetectionBoxes_Precision/mAP (large) = 0.04111025, DetectionBoxes_Precision/mAP (medium) = 0.31309694, DetectionBoxes_Precision/mAP (small) = 0.3770236, DetectionBoxes_Precision/[email protected] = 0.75070286, DetectionBoxes_Precision/[email protected] = 0.29450706, DetectionBoxes_Recall/AR@1 = 0.27907306, DetectionBoxes_Recall/AR@10 = 0.52206033, DetectionBoxes_Recall/AR@100 = 0.5595021, DetectionBoxes_Recall/AR@100 (large) = 0.62, DetectionBoxes_Recall/AR@100 (medium) = 0.5980273, DetectionBoxes_Recall/AR@100 (small) = 0.5533271, Loss/BoxClassifierLoss/classification_loss = 0.1670357, Loss/BoxClassifierLoss/localization_loss = 0.12627587, Loss/RPNLoss/localization_loss = 0.029111363, Loss/RPNLoss/objectness_loss = 0.05003918, Loss/total_loss = 0.37246218, global_step = 5555, learning_rate = 0.0003, loss = 0.37246218\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 5555: training/model.ckpt-5555\nI0617 10:54:07.914063 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 5555: training/model.ckpt-5555\nINFO:tensorflow:global_step/sec: 0.331604\nI0617 10:54:43.974407 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.331604\nINFO:tensorflow:loss = 0.53352386, step = 5600 (301.565 sec)\nI0617 10:54:43.975546 140626870351744 basic_session_run_hooks.py:260] loss = 0.53352386, step = 5600 (301.565 sec)\nINFO:tensorflow:global_step/sec: 1.28045\nI0617 10:56:02.072215 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.28045\nINFO:tensorflow:loss = 0.5648789, step = 5700 (78.098 sec)\nI0617 10:56:02.073129 140626870351744 basic_session_run_hooks.py:260] loss = 0.5648789, step = 5700 (78.098 sec)\nINFO:tensorflow:global_step/sec: 1.27811\nI0617 10:57:20.312947 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27811\nINFO:tensorflow:loss = 0.63451624, step = 5800 (78.241 sec)\nI0617 10:57:20.314349 140626870351744 basic_session_run_hooks.py:260] loss = 0.63451624, step = 5800 (78.241 sec)\nINFO:tensorflow:global_step/sec: 1.27549\nI0617 10:58:38.714401 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27549\nINFO:tensorflow:loss = 0.47773698, step = 5900 (78.401 sec)\nI0617 10:58:38.715467 140626870351744 basic_session_run_hooks.py:260] loss = 0.47773698, step = 5900 (78.401 sec)\nINFO:tensorflow:global_step/sec: 1.27865\nI0617 10:59:56.921827 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27865\nINFO:tensorflow:loss = 0.91164, step = 6000 (78.208 sec)\nI0617 10:59:56.923107 140626870351744 basic_session_run_hooks.py:260] loss = 0.91164, step = 6000 (78.208 sec)\nINFO:tensorflow:Saving checkpoints for 6037 into training/model.ckpt.\nI0617 11:00:25.098789 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 6037 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe277e7a2f0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:00:28.855424 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe277e7a2f0> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:00:29.297623 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:00:29.328012 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:00:32.116540 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:00:32.128872 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:00:32.129200 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:00:32.584873 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:00:32.843135 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:00:34.629465 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:00:34Z\nI0617 11:00:34.644524 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T11:00:34Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:00:35.304953 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:00:35.305617: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:00:35.305922: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:00:35.306023: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:00:35.306049: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:00:35.306071: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:00:35.306091: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:00:35.306111: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:00:35.306130: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:00:35.306150: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:00:35.306271: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:00:35.306580: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:00:35.306795: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:00:35.306835: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:00:35.306849: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:00:35.306858: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:00:35.306997: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:00:35.307308: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:00:35.307538: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-6037\nI0617 11:00:35.308426 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-6037\nINFO:tensorflow:Running local_init_op.\nI0617 11:00:36.930932 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:00:37.119377 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:03:49.821595 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.40s)\nI0617 11:03:50.224916 140623412950784 coco_tools.py:131] DONE (t=0.40s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.86s).\nAccumulating evaluation results...\nDONE (t=2.47s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.366\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.755\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.295\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.373\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.325\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.019\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.274\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.522\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.558\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.550\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.612\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.673\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:04:10\nI0617 11:04:10.349214 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-11:04:10\nINFO:tensorflow:Saving dict for global step 6037: DetectionBoxes_Precision/mAP = 0.36628962, DetectionBoxes_Precision/mAP (large) = 0.0186822, DetectionBoxes_Precision/mAP (medium) = 0.3246763, DetectionBoxes_Precision/mAP (small) = 0.3728835, DetectionBoxes_Precision/[email protected] = 0.7551322, DetectionBoxes_Precision/[email protected] = 0.2948928, DetectionBoxes_Recall/AR@1 = 0.27427647, DetectionBoxes_Recall/AR@10 = 0.52155435, DetectionBoxes_Recall/AR@100 = 0.55846995, DetectionBoxes_Recall/AR@100 (large) = 0.67333335, DetectionBoxes_Recall/AR@100 (medium) = 0.61183614, DetectionBoxes_Recall/AR@100 (small) = 0.54981256, Loss/BoxClassifierLoss/classification_loss = 0.1610607, Loss/BoxClassifierLoss/localization_loss = 0.12631583, Loss/RPNLoss/localization_loss = 0.028940981, Loss/RPNLoss/objectness_loss = 0.046191916, Loss/total_loss = 0.36250928, global_step = 6037, learning_rate = 0.0003, loss = 0.36250928\nI0617 11:04:10.349525 140626870351744 estimator.py:2049] Saving dict for global step 6037: DetectionBoxes_Precision/mAP = 0.36628962, DetectionBoxes_Precision/mAP (large) = 0.0186822, DetectionBoxes_Precision/mAP (medium) = 0.3246763, DetectionBoxes_Precision/mAP (small) = 0.3728835, DetectionBoxes_Precision/[email protected] = 0.7551322, DetectionBoxes_Precision/[email protected] = 0.2948928, DetectionBoxes_Recall/AR@1 = 0.27427647, DetectionBoxes_Recall/AR@10 = 0.52155435, DetectionBoxes_Recall/AR@100 = 0.55846995, DetectionBoxes_Recall/AR@100 (large) = 0.67333335, DetectionBoxes_Recall/AR@100 (medium) = 0.61183614, DetectionBoxes_Recall/AR@100 (small) = 0.54981256, Loss/BoxClassifierLoss/classification_loss = 0.1610607, Loss/BoxClassifierLoss/localization_loss = 0.12631583, Loss/RPNLoss/localization_loss = 0.028940981, Loss/RPNLoss/objectness_loss = 0.046191916, Loss/total_loss = 0.36250928, global_step = 6037, learning_rate = 0.0003, loss = 0.36250928\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 6037: training/model.ckpt-6037\nI0617 11:04:10.350543 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 6037: training/model.ckpt-6037\nINFO:tensorflow:global_step/sec: 0.329603\nI0617 11:05:00.317078 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.329603\nINFO:tensorflow:loss = 0.4680398, step = 6100 (303.395 sec)\nI0617 11:05:00.317953 140626870351744 basic_session_run_hooks.py:260] loss = 0.4680398, step = 6100 (303.395 sec)\nINFO:tensorflow:global_step/sec: 1.27484\nI0617 11:06:18.757988 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27484\nINFO:tensorflow:loss = 0.55177665, step = 6200 (78.441 sec)\nI0617 11:06:18.758997 140626870351744 basic_session_run_hooks.py:260] loss = 0.55177665, step = 6200 (78.441 sec)\nINFO:tensorflow:global_step/sec: 1.27422\nI0617 11:07:37.237650 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27422\nINFO:tensorflow:loss = 0.47819647, step = 6300 (78.480 sec)\nI0617 11:07:37.238792 140626870351744 basic_session_run_hooks.py:260] loss = 0.47819647, step = 6300 (78.480 sec)\nINFO:tensorflow:global_step/sec: 1.27281\nI0617 11:08:55.804207 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27281\nINFO:tensorflow:loss = 0.63258326, step = 6400 (78.566 sec)\nI0617 11:08:55.805294 140626870351744 basic_session_run_hooks.py:260] loss = 0.63258326, step = 6400 (78.566 sec)\nINFO:tensorflow:global_step/sec: 1.27425\nI0617 11:10:14.281913 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27425\nINFO:tensorflow:loss = 0.44437832, step = 6500 (78.478 sec)\nI0617 11:10:14.283145 140626870351744 basic_session_run_hooks.py:260] loss = 0.44437832, step = 6500 (78.478 sec)\nINFO:tensorflow:Saving checkpoints for 6515 into training/model.ckpt.\nI0617 11:10:25.319551 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 6515 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe26bca3048> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:10:29.052318 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe26bca3048> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:10:29.486775 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:10:29.513396 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:10:32.283288 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:10:32.295691 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:10:32.296026 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:10:32.749828 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:10:33.011844 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:10:34.789821 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:10:34Z\nI0617 11:10:34.805153 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T11:10:34Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:10:35.449528 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:10:35.450359: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:10:35.450795: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:10:35.450950: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:10:35.450998: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:10:35.451029: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:10:35.451056: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:10:35.451080: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:10:35.451104: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:10:35.451130: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:10:35.451275: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:10:35.451738: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:10:35.452343: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:10:35.452462: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:10:35.452487: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:10:35.452500: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:10:35.452678: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:10:35.453146: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:10:35.453499: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-6515\nI0617 11:10:35.457295 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-6515\nINFO:tensorflow:Running local_init_op.\nI0617 11:10:37.182027 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:10:37.395977 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:13:53.924344 140623412950784 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.41s)\nI0617 11:13:54.337912 140623412950784 coco_tools.py:131] DONE (t=0.41s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=16.97s).\nAccumulating evaluation results...\nDONE (t=2.58s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.370\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.750\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.304\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.377\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.317\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.039\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.278\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.522\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.560\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.552\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.613\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.713\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:14:14\nI0617 11:14:14.663850 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-11:14:14\nINFO:tensorflow:Saving dict for global step 6515: DetectionBoxes_Precision/mAP = 0.3695197, DetectionBoxes_Precision/mAP (large) = 0.038734496, DetectionBoxes_Precision/mAP (medium) = 0.31747302, DetectionBoxes_Precision/mAP (small) = 0.3767664, DetectionBoxes_Precision/[email protected] = 0.7503083, DetectionBoxes_Precision/[email protected] = 0.30404285, DetectionBoxes_Recall/AR@1 = 0.27828375, DetectionBoxes_Recall/AR@10 = 0.5215341, DetectionBoxes_Recall/AR@100 = 0.5604331, DetectionBoxes_Recall/AR@100 (large) = 0.7133333, DetectionBoxes_Recall/AR@100 (medium) = 0.61259484, DetectionBoxes_Recall/AR@100 (small) = 0.551851, Loss/BoxClassifierLoss/classification_loss = 0.15888306, Loss/BoxClassifierLoss/localization_loss = 0.12651473, Loss/RPNLoss/localization_loss = 0.028911384, Loss/RPNLoss/objectness_loss = 0.04832301, Loss/total_loss = 0.3626322, global_step = 6515, learning_rate = 0.0003, loss = 0.3626322\nI0617 11:14:14.664211 140626870351744 estimator.py:2049] Saving dict for global step 6515: DetectionBoxes_Precision/mAP = 0.3695197, DetectionBoxes_Precision/mAP (large) = 0.038734496, DetectionBoxes_Precision/mAP (medium) = 0.31747302, DetectionBoxes_Precision/mAP (small) = 0.3767664, DetectionBoxes_Precision/[email protected] = 0.7503083, DetectionBoxes_Precision/[email protected] = 0.30404285, DetectionBoxes_Recall/AR@1 = 0.27828375, DetectionBoxes_Recall/AR@10 = 0.5215341, DetectionBoxes_Recall/AR@100 = 0.5604331, DetectionBoxes_Recall/AR@100 (large) = 0.7133333, DetectionBoxes_Recall/AR@100 (medium) = 0.61259484, DetectionBoxes_Recall/AR@100 (small) = 0.551851, Loss/BoxClassifierLoss/classification_loss = 0.15888306, Loss/BoxClassifierLoss/localization_loss = 0.12651473, Loss/RPNLoss/localization_loss = 0.028911384, Loss/RPNLoss/objectness_loss = 0.04832301, Loss/total_loss = 0.3626322, global_step = 6515, learning_rate = 0.0003, loss = 0.3626322\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 6515: training/model.ckpt-6515\nI0617 11:14:14.665198 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 6515: training/model.ckpt-6515\nINFO:tensorflow:global_step/sec: 0.324793\nI0617 11:15:22.170605 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 0.324793\nINFO:tensorflow:loss = 0.578318, step = 6600 (307.889 sec)\nI0617 11:15:22.171716 140626870351744 basic_session_run_hooks.py:260] loss = 0.578318, step = 6600 (307.889 sec)\nINFO:tensorflow:global_step/sec: 1.27739\nI0617 11:16:40.455049 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27739\nINFO:tensorflow:loss = 0.6535774, step = 6700 (78.284 sec)\nI0617 11:16:40.456211 140626870351744 basic_session_run_hooks.py:260] loss = 0.6535774, step = 6700 (78.284 sec)\nINFO:tensorflow:global_step/sec: 1.27458\nI0617 11:17:58.911979 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27458\nINFO:tensorflow:loss = 0.4986852, step = 6800 (78.457 sec)\nI0617 11:17:58.913001 140626870351744 basic_session_run_hooks.py:260] loss = 0.4986852, step = 6800 (78.457 sec)\nINFO:tensorflow:global_step/sec: 1.27527\nI0617 11:19:17.326742 140626870351744 basic_session_run_hooks.py:692] global_step/sec: 1.27527\nINFO:tensorflow:loss = 0.65695316, step = 6900 (78.415 sec)\nI0617 11:19:17.327841 140626870351744 basic_session_run_hooks.py:260] loss = 0.65695316, step = 6900 (78.415 sec)\nINFO:tensorflow:Saving checkpoints for 6988 into training/model.ckpt.\nI0617 11:20:25.545233 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 6988 into training/model.ckpt.\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe2763b19d8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:20:29.309710 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe2763b19d8> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:20:29.759766 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:20:29.786705 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:20:32.586834 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:20:32.600023 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:20:32.600435 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:20:33.055932 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:20:33.321021 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:20:35.126188 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:20:35Z\nI0617 11:20:35.141174 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T11:20:35Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:20:35.804460 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:20:35.805264: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:20:35.805609: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:20:35.805702: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:20:35.805736: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:20:35.805771: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:20:35.805800: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:20:35.805825: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:20:35.805848: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:20:35.805871: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:20:35.806021: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:20:35.806371: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:20:35.806593: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:20:35.806635: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:20:35.806648: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:20:35.806657: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:20:35.806774: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:20:35.807082: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:20:35.807316: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-6988\nI0617 11:20:35.808543 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-6988\nINFO:tensorflow:Running local_init_op.\nI0617 11:20:37.506978 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:20:37.719384 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:23:54.009078 140623421343488 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.41s)\nI0617 11:23:54.422712 140623421343488 coco_tools.py:131] DONE (t=0.41s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=17.09s).\nAccumulating evaluation results...\nDONE (t=2.55s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.369\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.757\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.288\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.376\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.325\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.025\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.277\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.519\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.557\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.549\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.612\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.667\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:24:14\nI0617 11:24:14.831433 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-11:24:14\nINFO:tensorflow:Saving dict for global step 6988: DetectionBoxes_Precision/mAP = 0.36909318, DetectionBoxes_Precision/mAP (large) = 0.024864854, DetectionBoxes_Precision/mAP (medium) = 0.32504582, DetectionBoxes_Precision/mAP (small) = 0.3763382, DetectionBoxes_Precision/[email protected] = 0.75744766, DetectionBoxes_Precision/[email protected] = 0.28782046, DetectionBoxes_Recall/AR@1 = 0.27704918, DetectionBoxes_Recall/AR@10 = 0.5191459, DetectionBoxes_Recall/AR@100 = 0.55733657, DetectionBoxes_Recall/AR@100 (large) = 0.6666667, DetectionBoxes_Recall/AR@100 (medium) = 0.61183614, DetectionBoxes_Recall/AR@100 (small) = 0.5485239, Loss/BoxClassifierLoss/classification_loss = 0.15668108, Loss/BoxClassifierLoss/localization_loss = 0.1314576, Loss/RPNLoss/localization_loss = 0.029021006, Loss/RPNLoss/objectness_loss = 0.047359753, Loss/total_loss = 0.3645192, global_step = 6988, learning_rate = 0.0003, loss = 0.3645192\nI0617 11:24:14.831731 140626870351744 estimator.py:2049] Saving dict for global step 6988: DetectionBoxes_Precision/mAP = 0.36909318, DetectionBoxes_Precision/mAP (large) = 0.024864854, DetectionBoxes_Precision/mAP (medium) = 0.32504582, DetectionBoxes_Precision/mAP (small) = 0.3763382, DetectionBoxes_Precision/[email protected] = 0.75744766, DetectionBoxes_Precision/[email protected] = 0.28782046, DetectionBoxes_Recall/AR@1 = 0.27704918, DetectionBoxes_Recall/AR@10 = 0.5191459, DetectionBoxes_Recall/AR@100 = 0.55733657, DetectionBoxes_Recall/AR@100 (large) = 0.6666667, DetectionBoxes_Recall/AR@100 (medium) = 0.61183614, DetectionBoxes_Recall/AR@100 (small) = 0.5485239, Loss/BoxClassifierLoss/classification_loss = 0.15668108, Loss/BoxClassifierLoss/localization_loss = 0.1314576, Loss/RPNLoss/localization_loss = 0.029021006, Loss/RPNLoss/objectness_loss = 0.047359753, Loss/total_loss = 0.3645192, global_step = 6988, learning_rate = 0.0003, loss = 0.3645192\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 6988: training/model.ckpt-6988\nI0617 11:24:14.832724 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 6988: training/model.ckpt-6988\nINFO:tensorflow:Saving checkpoints for 7000 into training/model.ckpt.\nI0617 11:24:24.250965 140626870351744 basic_session_run_hooks.py:606] Saving checkpoints for 7000 into training/model.ckpt.\nINFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).\nI0617 11:24:27.978397 140626870351744 training.py:527] Skip the current checkpoint eval due to throttle secs (600 secs).\nWARNING:tensorflow:Entity <function build.<locals>.process_fn at 0x7fe26d72e268> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nW0617 11:24:28.037600 140626870351744 ag_logging.py:146] Entity <function build.<locals>.process_fn at 0x7fe26d72e268> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: Bad argument number for Name: 3, expecting 4\nINFO:tensorflow:Calling model_fn.\nI0617 11:24:28.470584 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:24:28.497128 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:24:31.687450 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:24:31.700921 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:24:31.701327 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:24:32.145251 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:24:32.402846 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Done calling model_fn.\nI0617 11:24:34.222533 140626870351744 estimator.py:1150] Done calling model_fn.\nINFO:tensorflow:Starting evaluation at 2020-06-17T11:24:34Z\nI0617 11:24:34.238128 140626870351744 evaluation.py:255] Starting evaluation at 2020-06-17T11:24:34Z\nINFO:tensorflow:Graph was finalized.\nI0617 11:24:34.903126 140626870351744 monitored_session.py:240] Graph was finalized.\n2020-06-17 11:24:34.903951: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:24:34.904442: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:24:34.904564: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:24:34.904606: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:24:34.904645: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:24:34.904677: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:24:34.904709: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:24:34.904735: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:24:34.904762: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:24:34.904940: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:24:34.905490: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:24:34.905911: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:24:34.905963: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:24:34.905983: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:24:34.905997: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:24:34.906173: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:24:34.906695: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:24:34.907059: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-7000\nI0617 11:24:34.908281 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-7000\nINFO:tensorflow:Running local_init_op.\nI0617 11:24:36.677967 140626870351744 session_manager.py:500] Running local_init_op.\nINFO:tensorflow:Done running local_init_op.\nI0617 11:24:36.908327 140626870351744 session_manager.py:502] Done running local_init_op.\ncreating index...\nindex created!\nINFO:tensorflow:Loading and preparing annotation results...\nI0617 11:27:52.567077 140623421343488 coco_tools.py:109] Loading and preparing annotation results...\nINFO:tensorflow:DONE (t=0.40s)\nI0617 11:27:52.969794 140623421343488 coco_tools.py:131] DONE (t=0.40s)\ncreating index...\nindex created!\nRunning per image evaluation...\nEvaluate annotation type *bbox*\nDONE (t=17.06s).\nAccumulating evaluation results...\nDONE (t=2.54s).\n Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.325\n Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.729\n Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.213\n Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.333\n Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.283\n Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.030\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.249\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.491\n Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.535\n Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.528\n Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.574\n Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.633\nINFO:tensorflow:Finished evaluation at 2020-06-17-11:28:13\nI0617 11:28:13.336186 140626870351744 evaluation.py:275] Finished evaluation at 2020-06-17-11:28:13\nINFO:tensorflow:Saving dict for global step 7000: DetectionBoxes_Precision/mAP = 0.32500675, DetectionBoxes_Precision/mAP (large) = 0.030233093, DetectionBoxes_Precision/mAP (medium) = 0.28287673, DetectionBoxes_Precision/mAP (small) = 0.33251557, DetectionBoxes_Precision/[email protected] = 0.7287303, DetectionBoxes_Precision/[email protected] = 0.21318778, DetectionBoxes_Recall/AR@1 = 0.24948391, DetectionBoxes_Recall/AR@10 = 0.49069014, DetectionBoxes_Recall/AR@100 = 0.5347703, DetectionBoxes_Recall/AR@100 (large) = 0.6333333, DetectionBoxes_Recall/AR@100 (medium) = 0.5742033, DetectionBoxes_Recall/AR@100 (small) = 0.5283271, Loss/BoxClassifierLoss/classification_loss = 0.15551552, Loss/BoxClassifierLoss/localization_loss = 0.1428248, Loss/RPNLoss/localization_loss = 0.029262757, Loss/RPNLoss/objectness_loss = 0.048093494, Loss/total_loss = 0.37569618, global_step = 7000, learning_rate = 0.0003, loss = 0.37569618\nI0617 11:28:13.336463 140626870351744 estimator.py:2049] Saving dict for global step 7000: DetectionBoxes_Precision/mAP = 0.32500675, DetectionBoxes_Precision/mAP (large) = 0.030233093, DetectionBoxes_Precision/mAP (medium) = 0.28287673, DetectionBoxes_Precision/mAP (small) = 0.33251557, DetectionBoxes_Precision/[email protected] = 0.7287303, DetectionBoxes_Precision/[email protected] = 0.21318778, DetectionBoxes_Recall/AR@1 = 0.24948391, DetectionBoxes_Recall/AR@10 = 0.49069014, DetectionBoxes_Recall/AR@100 = 0.5347703, DetectionBoxes_Recall/AR@100 (large) = 0.6333333, DetectionBoxes_Recall/AR@100 (medium) = 0.5742033, DetectionBoxes_Recall/AR@100 (small) = 0.5283271, Loss/BoxClassifierLoss/classification_loss = 0.15551552, Loss/BoxClassifierLoss/localization_loss = 0.1428248, Loss/RPNLoss/localization_loss = 0.029262757, Loss/RPNLoss/objectness_loss = 0.048093494, Loss/total_loss = 0.37569618, global_step = 7000, learning_rate = 0.0003, loss = 0.37569618\nINFO:tensorflow:Saving 'checkpoint_path' summary for global step 7000: training/model.ckpt-7000\nI0617 11:28:13.337459 140626870351744 estimator.py:2109] Saving 'checkpoint_path' summary for global step 7000: training/model.ckpt-7000\nINFO:tensorflow:Performing the final export in the end of training.\nI0617 11:28:13.338137 140626870351744 exporter.py:410] Performing the final export in the end of training.\nWARNING:tensorflow:From /content/models/research/object_detection/inputs.py:606: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n\nW0617 11:28:13.345140 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/inputs.py:606: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n\nINFO:tensorflow:Calling model_fn.\nI0617 11:28:13.506196 140626870351744 estimator.py:1148] Calling model_fn.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:28:13.517227 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:28:16.295150 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:28:16.309286 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:28:16.309785 140626870351744 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:28:16.744073 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:28:16.995217 140626870351744 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/model_lib.py:387: The name tf.saved_model.signature_constants.PREDICT_METHOD_NAME is deprecated. Please use tf.saved_model.PREDICT_METHOD_NAME instead.\n\nW0617 11:28:17.558674 140626870351744 module_wrapper.py:139] From /content/models/research/object_detection/model_lib.py:387: The name tf.saved_model.signature_constants.PREDICT_METHOD_NAME is deprecated. Please use tf.saved_model.PREDICT_METHOD_NAME instead.\n\nINFO:tensorflow:Done calling model_fn.\nI0617 11:28:17.955934 140626870351744 estimator.py:1150] Done calling model_fn.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/saved_model/signature_def_utils_impl.py:201: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.\nW0617 11:28:17.956218 140626870351744 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/saved_model/signature_def_utils_impl.py:201: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.\nINFO:tensorflow:Signatures INCLUDED in export for Classify: None\nI0617 11:28:17.956687 140626870351744 export_utils.py:170] Signatures INCLUDED in export for Classify: None\nINFO:tensorflow:Signatures INCLUDED in export for Regress: None\nI0617 11:28:17.956816 140626870351744 export_utils.py:170] Signatures INCLUDED in export for Regress: None\nINFO:tensorflow:Signatures INCLUDED in export for Predict: ['tensorflow/serving/predict', 'serving_default']\nI0617 11:28:17.956911 140626870351744 export_utils.py:170] Signatures INCLUDED in export for Predict: ['tensorflow/serving/predict', 'serving_default']\nINFO:tensorflow:Signatures INCLUDED in export for Train: None\nI0617 11:28:17.956981 140626870351744 export_utils.py:170] Signatures INCLUDED in export for Train: None\nINFO:tensorflow:Signatures INCLUDED in export for Eval: None\nI0617 11:28:17.957047 140626870351744 export_utils.py:170] Signatures INCLUDED in export for Eval: None\n2020-06-17 11:28:17.957605: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:28:17.957976: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:28:17.958066: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:28:17.958096: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:28:17.958118: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:28:17.958142: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:28:17.958162: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:28:17.958181: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:28:17.958202: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:28:17.958317: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:28:17.958633: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:28:17.958879: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:28:17.958935: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:28:17.958950: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:28:17.958959: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:28:17.959090: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:28:17.959389: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:28:17.959619: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-7000\nI0617 11:28:17.962056 140626870351744 saver.py:1284] Restoring parameters from training/model.ckpt-7000\nINFO:tensorflow:Assets added to graph.\nI0617 11:28:18.884246 140626870351744 builder_impl.py:665] Assets added to graph.\nINFO:tensorflow:No assets to write.\nI0617 11:28:18.884480 140626870351744 builder_impl.py:460] No assets to write.\nINFO:tensorflow:SavedModel written to: training/export/Servo/temp-b'1592393293'/saved_model.pb\nI0617 11:28:20.679733 140626870351744 builder_impl.py:425] SavedModel written to: training/export/Servo/temp-b'1592393293'/saved_model.pb\nINFO:tensorflow:Loss for final step: 0.8255045.\nI0617 11:28:21.186152 140626870351744 estimator.py:371] Loss for final step: 0.8255045.\n"
],
[
"!ls {model_dir}",
"checkpoint\neval_0\nevents.out.tfevents.1592384388.db6e00fb63e1\nexport\ngraph.pbtxt\nmodel.ckpt-5555.data-00000-of-00001\nmodel.ckpt-5555.index\nmodel.ckpt-5555.meta\nmodel.ckpt-6037.data-00000-of-00001\nmodel.ckpt-6037.index\nmodel.ckpt-6037.meta\nmodel.ckpt-6515.data-00000-of-00001\nmodel.ckpt-6515.index\nmodel.ckpt-6515.meta\nmodel.ckpt-6988.data-00000-of-00001\nmodel.ckpt-6988.index\nmodel.ckpt-6988.meta\nmodel.ckpt-7000.data-00000-of-00001\nmodel.ckpt-7000.index\nmodel.ckpt-7000.meta\n"
]
],
[
[
"##Task-4: Freezing a trained model and export it for inference\n",
"_____no_output_____"
],
[
"### Step: 10 Exporting a Trained Inference Graph",
"_____no_output_____"
]
],
[
[
"import re\nimport numpy as np\n\noutput_directory = './fine_tuned_model'\n\nlst = os.listdir(model_dir)\nlst = [l for l in lst if 'model.ckpt-' in l and '.meta' in l]\nsteps=np.array([int(re.findall('\\d+', l)[0]) for l in lst])\nlast_model = lst[steps.argmax()].replace('.meta', '')\n\nlast_model_path = os.path.join(model_dir, last_model)\nprint(last_model_path)\n!python /content/models/research/object_detection/export_inference_graph.py \\\n --input_type=image_tensor \\\n --pipeline_config_path={pipeline_fname} \\\n --output_directory={output_directory} \\\n --trained_checkpoint_prefix={last_model_path}",
"training/model.ckpt-7000\nWARNING: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\nWARNING:tensorflow:From /content/models/research/slim/nets/inception_resnet_v2.py:373: The name tf.GraphKeys is deprecated. Please use tf.compat.v1.GraphKeys instead.\n\nWARNING:tensorflow:From /content/models/research/slim/nets/mobilenet/mobilenet.py:389: The name tf.nn.avg_pool is deprecated. Please use tf.nn.avg_pool2d instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/export_inference_graph.py:150: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/export_inference_graph.py:133: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nW0617 11:54:04.371880 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/export_inference_graph.py:133: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/anchor_generators/grid_anchor_generator.py:59: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nW0617 11:54:04.379477 140158920451968 deprecation.py:323] From /content/models/research/object_detection/anchor_generators/grid_anchor_generator.py:59: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:348: The name tf.gfile.MakeDirs is deprecated. Please use tf.io.gfile.makedirs instead.\n\nW0617 11:54:04.382447 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:348: The name tf.gfile.MakeDirs is deprecated. Please use tf.io.gfile.makedirs instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:113: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n\nW0617 11:54:04.382739 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:113: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/core/preprocessor.py:2154: 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.\nW0617 11:54:04.422861 140158920451968 deprecation.py:323] From /content/models/research/object_detection/core/preprocessor.py:2154: 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.\nWARNING:tensorflow:From /content/models/research/object_detection/core/preprocessor.py:2236: The name tf.image.resize_images is deprecated. Please use tf.image.resize instead.\n\nW0617 11:54:04.438835 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/core/preprocessor.py:2236: The name tf.image.resize_images is deprecated. Please use tf.image.resize instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:162: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n\nW0617 11:54:04.460829 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:162: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:54:04.470107 140158920451968 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/contrib/layers/python/layers/layers.py:1057: 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.\nW0617 11:54:04.472759 140158920451968 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/contrib/layers/python/layers/layers.py:1057: 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 /content/models/research/object_detection/core/anchor_generator.py:149: The name tf.assert_equal is deprecated. Please use tf.compat.v1.assert_equal instead.\n\nW0617 11:54:07.432069 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/core/anchor_generator.py:149: The name tf.assert_equal is deprecated. Please use tf.compat.v1.assert_equal instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:54:07.438727 140158920451968 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:986: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n\nW0617 11:54:07.439115 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:986: The name tf.get_variable_scope is deprecated. Please use tf.compat.v1.get_variable_scope instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:54:07.452192 140158920451968 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/predictors/convolutional_box_predictor.py:147: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n\nW0617 11:54:07.452548 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/predictors/convolutional_box_predictor.py:147: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n\nINFO:tensorflow:depth of additional conv before box predictor: 0\nI0617 11:54:07.452667 140158920451968 convolutional_box_predictor.py:148] depth of additional conv before box predictor: 0\nWARNING:tensorflow:From /content/models/research/object_detection/core/box_list_ops.py:136: 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\nW0617 11:54:07.502345 140158920451968 deprecation.py:323] From /content/models/research/object_detection/core/box_list_ops.py:136: 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 /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:185: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n\nW0617 11:54:07.935282 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py:185: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:54:07.935662 140158920451968 regularizers.py:98] Scale of 0 disables regularizer.\nINFO:tensorflow:Scale of 0 disables regularizer.\nI0617 11:54:08.197104 140158920451968 regularizers.py:98] Scale of 0 disables regularizer.\nWARNING:tensorflow:From /content/models/research/object_detection/utils/ops.py:712: calling crop_and_resize_v1 (from tensorflow.python.ops.image_ops_impl) with box_ind is deprecated and will be removed in a future version.\nInstructions for updating:\nbox_ind is deprecated, use box_indices instead\nW0617 11:54:08.337769 140158920451968 deprecation.py:506] From /content/models/research/object_detection/utils/ops.py:712: calling crop_and_resize_v1 (from tensorflow.python.ops.image_ops_impl) with box_ind is deprecated and will be removed in a future version.\nInstructions for updating:\nbox_ind is deprecated, use box_indices instead\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/util/dispatch.py:180: calling squeeze (from tensorflow.python.ops.array_ops) with squeeze_dims is deprecated and will be removed in a future version.\nInstructions for updating:\nUse the `axis` argument instead\nW0617 11:54:08.405458 140158920451968 deprecation.py:506] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/util/dispatch.py:180: calling squeeze (from tensorflow.python.ops.array_ops) with squeeze_dims is deprecated and will be removed in a future version.\nInstructions for updating:\nUse the `axis` argument instead\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:231: The name tf.add_to_collection is deprecated. Please use tf.compat.v1.add_to_collection instead.\n\nW0617 11:54:09.048885 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:231: The name tf.add_to_collection is deprecated. Please use tf.compat.v1.add_to_collection instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:330: get_or_create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease switch to tf.train.get_or_create_global_step\nW0617 11:54:09.049160 140158920451968 deprecation.py:323] From /content/models/research/object_detection/exporter.py:330: get_or_create_global_step (from tensorflow.contrib.framework.python.ops.variables) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease switch to tf.train.get_or_create_global_step\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:361: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n\nW0617 11:54:09.052310 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:361: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:484: print_model_analysis (from tensorflow.contrib.tfprof.model_analyzer) is deprecated and will be removed after 2018-01-01.\nInstructions for updating:\nUse `tf.profiler.profile(graph, run_meta, op_log, cmd, options)`. Build `options` with `tf.profiler.ProfileOptionBuilder`. See README.md for details\nW0617 11:54:09.052496 140158920451968 deprecation.py:323] From /content/models/research/object_detection/exporter.py:484: print_model_analysis (from tensorflow.contrib.tfprof.model_analyzer) is deprecated and will be removed after 2018-01-01.\nInstructions for updating:\nUse `tf.profiler.profile(graph, run_meta, op_log, cmd, options)`. Build `options` with `tf.profiler.ProfileOptionBuilder`. See README.md for details\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/profiler/internal/flops_registry.py:142: tensor_shape_from_node_def_name (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.tensor_shape_from_node_def_name`\nW0617 11:54:09.053572 140158920451968 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/profiler/internal/flops_registry.py:142: tensor_shape_from_node_def_name (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.tensor_shape_from_node_def_name`\n232 ops no flops stats due to incomplete shapes.\nParsing Inputs...\nIncomplete shape.\n\n=========================Options=============================\n-max_depth 10000\n-min_bytes 0\n-min_peak_bytes 0\n-min_residual_bytes 0\n-min_output_bytes 0\n-min_micros 0\n-min_accelerator_micros 0\n-min_cpu_micros 0\n-min_params 0\n-min_float_ops 0\n-min_occurrence 0\n-step -1\n-order_by name\n-account_type_regexes _trainable_variables\n-start_name_regexes .*\n-trim_name_regexes .*BatchNorm.*\n-show_name_regexes .*\n-hide_name_regexes \n-account_displayed_op_only true\n-select params\n-output stdout:\n\n==================Model Analysis Report======================\nIncomplete shape.\n\nDoc:\nscope: The nodes in the model graph are organized by their names, which is hierarchical like filesystem.\nparam: Number of parameters (in the Variable).\n\nProfile:\nnode name | # parameters\n_TFProfRoot (--/64.25m params)\n Conv (--/4.72m params)\n Conv/biases (512, 512/512 params)\n Conv/weights (3x3x1024x512, 4.72m/4.72m params)\n FirstStageBoxPredictor (--/36.94k params)\n FirstStageBoxPredictor/BoxEncodingPredictor (--/24.62k params)\n FirstStageBoxPredictor/BoxEncodingPredictor/biases (48, 48/48 params)\n FirstStageBoxPredictor/BoxEncodingPredictor/weights (1x1x512x48, 24.58k/24.58k params)\n FirstStageBoxPredictor/ClassPredictor (--/12.31k params)\n FirstStageBoxPredictor/ClassPredictor/biases (24, 24/24 params)\n FirstStageBoxPredictor/ClassPredictor/weights (1x1x512x24, 12.29k/12.29k params)\n FirstStageFeatureExtractor (--/42.39m params)\n FirstStageFeatureExtractor/resnet_v1_101 (--/42.39m params)\n FirstStageFeatureExtractor/resnet_v1_101/block1 (--/212.99k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1 (--/73.73k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1 (--/73.73k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1 (--/4.10k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv1/weights (1x1x64x64, 4.10k/4.10k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2 (--/36.86k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv2/weights (3x3x64x64, 36.86k/36.86k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3 (--/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/conv3/weights (1x1x64x256, 16.38k/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut (--/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_1/bottleneck_v1/shortcut/weights (1x1x64x256, 16.38k/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2 (--/69.63k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1 (--/69.63k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv1 (--/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv1/weights (1x1x256x64, 16.38k/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv2 (--/36.86k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv2/weights (3x3x64x64, 36.86k/36.86k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv3 (--/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_2/bottleneck_v1/conv3/weights (1x1x64x256, 16.38k/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3 (--/69.63k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1 (--/69.63k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv1 (--/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv1/weights (1x1x256x64, 16.38k/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv2 (--/36.86k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv2/weights (3x3x64x64, 36.86k/36.86k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv3 (--/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block1/unit_3/bottleneck_v1/conv3/weights (1x1x64x256, 16.38k/16.38k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2 (--/1.21m params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1 (--/376.83k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1 (--/376.83k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv1 (--/32.77k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv1/weights (1x1x256x128, 32.77k/32.77k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv2 (--/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv2/weights (3x3x128x128, 147.46k/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv3 (--/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/conv3/weights (1x1x128x512, 65.54k/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/shortcut (--/131.07k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/shortcut/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_1/bottleneck_v1/shortcut/weights (1x1x256x512, 131.07k/131.07k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2 (--/278.53k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1 (--/278.53k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv1 (--/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv1/weights (1x1x512x128, 65.54k/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv2 (--/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv2/weights (3x3x128x128, 147.46k/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv3 (--/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_2/bottleneck_v1/conv3/weights (1x1x128x512, 65.54k/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3 (--/278.53k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1 (--/278.53k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv1 (--/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv1/weights (1x1x512x128, 65.54k/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv2 (--/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv2/weights (3x3x128x128, 147.46k/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv3 (--/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_3/bottleneck_v1/conv3/weights (1x1x128x512, 65.54k/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4 (--/278.53k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1 (--/278.53k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv1 (--/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv1/weights (1x1x512x128, 65.54k/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv2 (--/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv2/weights (3x3x128x128, 147.46k/147.46k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv3 (--/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block2/unit_4/bottleneck_v1/conv3/weights (1x1x128x512, 65.54k/65.54k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3 (--/26.02m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1 (--/1.51m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1 (--/1.51m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv1 (--/131.07k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv1/weights (1x1x512x256, 131.07k/131.07k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/shortcut (--/524.29k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/shortcut/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_1/bottleneck_v1/shortcut/weights (1x1x512x1024, 524.29k/524.29k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_10/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_11/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_12/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_13/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_14/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_15/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_16/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_17/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_18/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_19/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_2/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_20/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_21/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_22/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_23/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_3/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_4/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_5/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_6/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_7/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_8/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1 (--/1.11m params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv1 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv1/weights (1x1x1024x256, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv2 (--/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv2/weights (3x3x256x256, 589.82k/589.82k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv3 (--/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block3/unit_9/bottleneck_v1/conv3/weights (1x1x256x1024, 262.14k/262.14k params)\n FirstStageFeatureExtractor/resnet_v1_101/block4 (--/14.94m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1 (--/6.03m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1 (--/6.03m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv1 (--/524.29k params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv1/weights (1x1x1024x512, 524.29k/524.29k params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv2 (--/2.36m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv2/weights (3x3x512x512, 2.36m/2.36m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv3 (--/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv3/weights (1x1x512x2048, 1.05m/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/shortcut (--/2.10m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/shortcut/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/shortcut/weights (1x1x1024x2048, 2.10m/2.10m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2 (--/4.46m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1 (--/4.46m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv1 (--/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv1/weights (1x1x2048x512, 1.05m/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv2 (--/2.36m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv2/weights (3x3x512x512, 2.36m/2.36m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv3 (--/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv3/weights (1x1x512x2048, 1.05m/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3 (--/4.46m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1 (--/4.46m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv1 (--/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv1/weights (1x1x2048x512, 1.05m/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv2 (--/2.36m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv2/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv2/weights (3x3x512x512, 2.36m/2.36m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3 (--/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3/weights (1x1x512x2048, 1.05m/1.05m params)\n FirstStageFeatureExtractor/resnet_v1_101/conv1 (--/9.41k params)\n FirstStageFeatureExtractor/resnet_v1_101/conv1/BatchNorm (--/0 params)\n FirstStageFeatureExtractor/resnet_v1_101/conv1/weights (7x7x3x64, 9.41k/9.41k params)\n SecondStageBoxPredictor (--/2.15m params)\n SecondStageBoxPredictor/class_predictions (--/18.45k params)\n SecondStageBoxPredictor/class_predictions/biases (18, 18/18 params)\n SecondStageBoxPredictor/class_predictions/weights (1x1x1024x18, 18.43k/18.43k params)\n SecondStageBoxPredictor/reduce_depth (--/2.10m params)\n SecondStageBoxPredictor/reduce_depth/biases (1024, 1.02k/1.02k params)\n SecondStageBoxPredictor/reduce_depth/weights (1x1x2048x1024, 2.10m/2.10m params)\n SecondStageBoxPredictor/refined_locations (--/36.90k params)\n SecondStageBoxPredictor/refined_locations/biases (36, 36/36 params)\n SecondStageBoxPredictor/refined_locations/weights (1x1x1024x36, 36.86k/36.86k params)\n SecondStageFeatureExtractor (--/14.94m params)\n SecondStageFeatureExtractor/resnet_v1_101 (--/14.94m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4 (--/14.94m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1 (--/6.03m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1 (--/6.03m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv1 (--/524.29k params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv1/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv1/weights (1x1x1024x512, 524.29k/524.29k params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv2 (--/2.36m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv2/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv2/weights (3x3x512x512, 2.36m/2.36m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv3 (--/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv3/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/conv3/weights (1x1x512x2048, 1.05m/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/shortcut (--/2.10m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/shortcut/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_1/bottleneck_v1/shortcut/weights (1x1x1024x2048, 2.10m/2.10m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2 (--/4.46m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1 (--/4.46m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv1 (--/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv1/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv1/weights (1x1x2048x512, 1.05m/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv2 (--/2.36m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv2/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv2/weights (3x3x512x512, 2.36m/2.36m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv3 (--/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv3/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_2/bottleneck_v1/conv3/weights (1x1x512x2048, 1.05m/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3 (--/4.46m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1 (--/4.46m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv1 (--/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv1/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv1/weights (1x1x2048x512, 1.05m/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv2 (--/2.36m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv2/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv2/weights (3x3x512x512, 2.36m/2.36m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3 (--/1.05m params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3/BatchNorm (--/0 params)\n SecondStageFeatureExtractor/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3/weights (1x1x512x2048, 1.05m/1.05m params)\n\n======================End of Report==========================\n232 ops no flops stats due to incomplete shapes.\nParsing Inputs...\nIncomplete shape.\n\n=========================Options=============================\n-max_depth 10000\n-min_bytes 0\n-min_peak_bytes 0\n-min_residual_bytes 0\n-min_output_bytes 0\n-min_micros 0\n-min_accelerator_micros 0\n-min_cpu_micros 0\n-min_params 0\n-min_float_ops 1\n-min_occurrence 0\n-step -1\n-order_by float_ops\n-account_type_regexes .*\n-start_name_regexes .*\n-trim_name_regexes .*BatchNorm.*,.*Initializer.*,.*Regularizer.*,.*BiasAdd.*\n-show_name_regexes .*\n-hide_name_regexes \n-account_displayed_op_only true\n-select float_ops\n-output stdout:\n\n==================Model Analysis Report======================\nIncomplete shape.\n\nDoc:\nscope: The nodes in the model graph are organized by their names, which is hierarchical like filesystem.\nflops: Number of float operations. Note: Please read the implementation for the math behind it.\n\nProfile:\nnode name | # float_ops\n_TFProfRoot (--/686.55k flops)\n SecondStageBoxPredictor/map/while/AddN (345.60k/345.60k flops)\n SecondStageBoxPredictor/map_1/while/AddN (172.80k/172.80k flops)\n SecondStageBoxPredictor/map/while/Mean (43.20k/43.20k flops)\n SecondStageBoxPredictor/map/while/truediv_12 (43.20k/43.20k flops)\n SecondStageBoxPredictor/map_1/while/Mean (21.60k/21.60k flops)\n SecondStageBoxPredictor/map_1/while/truediv_12 (21.60k/21.60k flops)\n SecondStageBoxPredictor/map_1/while/mul_18 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_1 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_10 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_11 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_12 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_13 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_14 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_15 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_16 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_17 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_27 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_19 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_2 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_20 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_21 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_22 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_23 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_24 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_25 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_26 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_28 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_10 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_11 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_2 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_3 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_4 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_5 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_6 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_7 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_8 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_9 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_1 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_10 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_11 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_2 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_3 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_4 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_5 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_6 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_8 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_9 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_6 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_7 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_8 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_9 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_1 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_10 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_11 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_2 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_3 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_4 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_5 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_6 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_7 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_8 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/truediv_9 (300/300 flops)\n map/while/ToNormalizedCoordinates/Scale/mul (300/300 flops)\n map/while/ToNormalizedCoordinates/Scale/mul_1 (300/300 flops)\n map/while/ToNormalizedCoordinates/Scale/mul_2 (300/300 flops)\n map/while/ToNormalizedCoordinates/Scale/mul_3 (300/300 flops)\n map_1/while/mul (300/300 flops)\n map_1/while/mul_1 (300/300 flops)\n map_1/while/mul_2 (300/300 flops)\n map_1/while/mul_3 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_7 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_29 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_3 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_30 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_31 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_32 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_33 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_34 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_35 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_4 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_5 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_6 (300/300 flops)\n SecondStageBoxPredictor/map/while/truediv_7 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_8 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/mul_9 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_1 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_10 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_11 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_2 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_3 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_4 (300/300 flops)\n SecondStageBoxPredictor/map_1/while/sub_5 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_17 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub_1 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_24 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_23 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_22 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_21 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_20 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_2 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_19 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_18 (300/300 flops)\n SecondStageBoxPredictor/map/while/sub (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_16 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_15 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_14 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_13 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_12 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_11 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_10 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_1 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_26 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_9 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_8 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_7 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_6 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_5 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_4 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_35 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_34 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_33 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_31 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_30 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_3 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_29 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_25 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_28 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_27 (300/300 flops)\n SecondStageBoxPredictor/map/while/mul_32 (300/300 flops)\n GridAnchorGenerator/truediv (12/12 flops)\n GridAnchorGenerator/mul_2 (12/12 flops)\n GridAnchorGenerator/mul_1 (12/12 flops)\n GridAnchorGenerator/mul (12/12 flops)\n FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block4/unit_1/bottleneck_v1/conv2/required_space_to_batch_paddings/sub (2/2 flops)\n FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block4/unit_3/bottleneck_v1/conv2/required_space_to_batch_paddings/sub (2/2 flops)\n FirstStageFeatureExtractor/resnet_v1_101/resnet_v1_101/block4/unit_2/bottleneck_v1/conv2/required_space_to_batch_paddings/sub (2/2 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_1 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_11 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_6 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_5 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_10 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_4 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_3 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_2 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_1 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/sub (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/SortByField_1/Equal (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/SortByField/Equal (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Minimum_1 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Minimum (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Greater (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/truediv_1 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/truediv (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/sub_1 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/Less_1 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/ChangeCoordinateFrame/sub (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/Less_1 (1/1 flops)\n map/while/Less_1 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Greater (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Minimum (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/Minimum_1 (1/1 flops)\n map_1/while/Less_1 (1/1 flops)\n map_1/while/Less (1/1 flops)\n map/while/ToNormalizedCoordinates/truediv_1 (1/1 flops)\n map/while/ToNormalizedCoordinates/truediv (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/SortByField/Equal (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/SortByField_1/Equal (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/MultiClassNonMaxSuppression/sub (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_12 (1/1 flops)\n map/while/Less (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_9 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_8 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_7 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_6 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_5 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_4 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_3 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_2 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_13 (1/1 flops)\n Preprocessor/map/while/ResizeToRange/mul (1/1 flops)\n FirstStageFeatureExtractor/GreaterEqual (1/1 flops)\n FirstStageFeatureExtractor/GreaterEqual_1 (1/1 flops)\n GridAnchorGenerator/assert_equal_1/Equal (1/1 flops)\n GridAnchorGenerator/mul_7 (1/1 flops)\n GridAnchorGenerator/mul_8 (1/1 flops)\n GridAnchorGenerator/zeros/Less (1/1 flops)\n Preprocessor/map/while/Less (1/1 flops)\n Preprocessor/map/while/Less_1 (1/1 flops)\n Preprocessor/map/while/ResizeToRange/Greater (1/1 flops)\n Preprocessor/map/while/ResizeToRange/Maximum (1/1 flops)\n Preprocessor/map/while/ResizeToRange/Minimum (1/1 flops)\n BatchMultiClassNonMaxSuppression/ones/Less (1/1 flops)\n Preprocessor/map/while/ResizeToRange/mul_1 (1/1 flops)\n Preprocessor/map/while/ResizeToRange/mul_2 (1/1 flops)\n Preprocessor/map/while/ResizeToRange/mul_3 (1/1 flops)\n Preprocessor/map/while/ResizeToRange/truediv (1/1 flops)\n Preprocessor/map/while/ResizeToRange/truediv_1 (1/1 flops)\n SecondStageBoxPredictor/map/while/Less (1/1 flops)\n SecondStageBoxPredictor/map/while/Less_1 (1/1 flops)\n SecondStageBoxPredictor/map_1/while/Less_1 (1/1 flops)\n SecondStageBoxPredictor/map_1/while/Less (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/Less (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_11 (1/1 flops)\n SecondStageBoxPredictor/mul_1 (1/1 flops)\n SecondStageBoxPredictor/mul (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_1 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_2 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_3 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_4 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_5 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/Greater_6 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_1 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_10 (1/1 flops)\n SecondStagePostprocessor/BatchMultiClassNonMaxSuppression/map/while/Less (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_12 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_13 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_2 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_3 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_4 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_5 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_6 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_7 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_8 (1/1 flops)\n BatchMultiClassNonMaxSuppression/map/while/PadOrClipBoxList/sub_9 (1/1 flops)\n\n======================End of Report==========================\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:377: The name tf.train.Saver is deprecated. Please use tf.compat.v1.train.Saver instead.\n\nW0617 11:54:10.712829 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:377: The name tf.train.Saver is deprecated. Please use tf.compat.v1.train.Saver instead.\n\n2020-06-17 11:54:11.943492: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1\n2020-06-17 11:54:11.950469: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:11.950940: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:54:11.954910: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:54:11.960871: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:54:11.962800: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:54:11.963172: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:54:11.968465: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:54:11.973618: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:54:11.978670: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:54:11.978812: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:11.979334: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:11.979736: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:54:11.985135: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300000000 Hz\n2020-06-17 11:54:11.985344: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x320b2c0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:\n2020-06-17 11:54:11.985375: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version\n2020-06-17 11:54:12.084795: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:12.085463: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x320af40 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n2020-06-17 11:54:12.085495: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Tesla P100-PCIE-16GB, Compute Capability 6.0\n2020-06-17 11:54:12.085786: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:12.086329: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:54:12.086414: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:54:12.086442: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:54:12.086475: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:54:12.086497: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:54:12.086522: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:54:12.086548: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:54:12.086578: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:54:12.086693: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:12.087227: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:12.087619: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:54:12.087685: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:54:12.088758: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:54:12.088785: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:54:12.088796: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:54:12.088958: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:12.089447: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:12.089920: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.\n2020-06-17 11:54:12.089970: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-7000\nI0617 11:54:12.091634 140158920451968 saver.py:1284] Restoring parameters from training/model.ckpt-7000\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:127: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to check for files with this prefix.\nW0617 11:54:15.275730 140158920451968 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:127: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse standard file APIs to check for files with this prefix.\n2020-06-17 11:54:15.985182: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:15.985715: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:54:15.985801: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:54:15.985826: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:54:15.985850: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:54:15.985872: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:54:15.985893: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:54:15.985930: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:54:15.985951: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:54:15.986070: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:15.986547: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:15.986942: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:54:15.986983: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:54:15.986997: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:54:15.987006: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:54:15.987131: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:15.987632: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:15.988040: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nINFO:tensorflow:Restoring parameters from training/model.ckpt-7000\nI0617 11:54:15.989352 140158920451968 saver.py:1284] Restoring parameters from training/model.ckpt-7000\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:233: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.convert_variables_to_constants`\nW0617 11:54:17.091264 140158920451968 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/tools/freeze_graph.py:233: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.convert_variables_to_constants`\nWARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.extract_sub_graph`\nW0617 11:54:17.091529 140158920451968 deprecation.py:323] From /tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.extract_sub_graph`\nINFO:tensorflow:Froze 532 variables.\nI0617 11:54:17.663572 140158920451968 graph_util_impl.py:334] Froze 532 variables.\nINFO:tensorflow:Converted 532 variables to const ops.\nI0617 11:54:17.938369 140158920451968 graph_util_impl.py:394] Converted 532 variables to const ops.\n2020-06-17 11:54:18.572772: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:18.573298: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1639] Found device 0 with properties: \nname: Tesla P100-PCIE-16GB major: 6 minor: 0 memoryClockRate(GHz): 1.3285\npciBusID: 0000:00:04.0\n2020-06-17 11:54:18.573416: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1\n2020-06-17 11:54:18.573445: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10\n2020-06-17 11:54:18.573473: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10\n2020-06-17 11:54:18.573515: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10\n2020-06-17 11:54:18.573540: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10\n2020-06-17 11:54:18.573563: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10\n2020-06-17 11:54:18.573587: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7\n2020-06-17 11:54:18.573699: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:18.574382: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:18.574984: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1767] Adding visible gpu devices: 0\n2020-06-17 11:54:18.575040: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1180] Device interconnect StreamExecutor with strength 1 edge matrix:\n2020-06-17 11:54:18.575057: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1186] 0 \n2020-06-17 11:54:18.575070: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1199] 0: N \n2020-06-17 11:54:18.575283: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:18.576088: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:983] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero\n2020-06-17 11:54:18.576729: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1325] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10329 MB memory) -> physical GPU (device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0)\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:259: The name tf.saved_model.builder.SavedModelBuilder is deprecated. Please use tf.compat.v1.saved_model.builder.SavedModelBuilder instead.\n\nW0617 11:54:19.516744 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:259: The name tf.saved_model.builder.SavedModelBuilder is deprecated. Please use tf.compat.v1.saved_model.builder.SavedModelBuilder instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:262: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.\nW0617 11:54:19.517249 140158920451968 deprecation.py:323] From /content/models/research/object_detection/exporter.py:262: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:268: The name tf.saved_model.signature_def_utils.build_signature_def is deprecated. Please use tf.compat.v1.saved_model.signature_def_utils.build_signature_def instead.\n\nW0617 11:54:19.517635 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:268: The name tf.saved_model.signature_def_utils.build_signature_def is deprecated. Please use tf.compat.v1.saved_model.signature_def_utils.build_signature_def instead.\n\nWARNING:tensorflow:From /content/models/research/object_detection/exporter.py:274: The name tf.saved_model.tag_constants.SERVING is deprecated. Please use tf.saved_model.SERVING instead.\n\nW0617 11:54:19.517863 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/exporter.py:274: The name tf.saved_model.tag_constants.SERVING is deprecated. Please use tf.saved_model.SERVING instead.\n\nINFO:tensorflow:No assets to save.\nI0617 11:54:19.518169 140158920451968 builder_impl.py:640] No assets to save.\nINFO:tensorflow:No assets to write.\nI0617 11:54:19.518273 140158920451968 builder_impl.py:460] No assets to write.\nINFO:tensorflow:SavedModel written to: ./fine_tuned_model/saved_model/saved_model.pb\nI0617 11:54:20.448054 140158920451968 builder_impl.py:425] SavedModel written to: ./fine_tuned_model/saved_model/saved_model.pb\nWARNING:tensorflow:From /content/models/research/object_detection/utils/config_util.py:180: The name tf.gfile.Open is deprecated. Please use tf.io.gfile.GFile instead.\n\nW0617 11:54:20.571968 140158920451968 module_wrapper.py:139] From /content/models/research/object_detection/utils/config_util.py:180: The name tf.gfile.Open is deprecated. Please use tf.io.gfile.GFile instead.\n\nINFO:tensorflow:Writing pipeline config file to ./fine_tuned_model/pipeline.config\nI0617 11:54:20.572267 140158920451968 config_util.py:182] Writing pipeline config file to ./fine_tuned_model/pipeline.config\n"
],
[
"!ls {output_directory}",
"checkpoint\t\t\tmodel.ckpt.index saved_model\nfrozen_inference_graph.pb\tmodel.ckpt.meta\nmodel.ckpt.data-00000-of-00001\tpipeline.config\n"
]
],
[
[
"### Step 11: Use frozen model for inference.",
"_____no_output_____"
]
],
[
[
"import os\n\npb_fname = os.path.join(os.path.abspath(output_directory), \"frozen_inference_graph.pb\")\nassert os.path.isfile(pb_fname), '`{}` not exist'.format(pb_fname)",
"_____no_output_____"
],
[
"!ls -alh {pb_fname}",
"-rw-r--r-- 1 root root 190M Jun 17 11:54 /content/models/research/object_detection/fine_tuned_model/frozen_inference_graph.pb\n"
],
[
"import os\nimport glob\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = pb_fname\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = label_map_pbtxt_fname\n\n# If you want to test the code with your images, just add images files to the PATH_TO_TEST_IMAGES_DIR.\nPATH_TO_TEST_IMAGES_DIR = '/content/gdrive/My Drive/A3 test/img'\n\nassert os.path.isfile(pb_fname)\nassert os.path.isfile(PATH_TO_LABELS)\nTEST_IMAGE_PATHS = glob.glob(os.path.join(PATH_TO_TEST_IMAGES_DIR, \"*.*\"))\nassert len(TEST_IMAGE_PATHS) > 0, 'No image found in `{}`.'.format(PATH_TO_TEST_IMAGES_DIR)\nprint(TEST_IMAGE_PATHS)",
"['/content/gdrive/My Drive/A3 test/img/resized_C59P20thinF_IMG_20150803_111244_cell_188.png', '/content/gdrive/My Drive/A3 test/img/resized_C39P4thinF_original_IMG_20150622_110900_cell_19.png', '/content/gdrive/My Drive/A3 test/img/resized_C39P4thinF_original_IMG_20150622_110115_cell_118.png']\n"
],
[
"%cd /content/models/research/object_detection\n\nimport numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\n# This is needed since the notebook is stored in the object_detection folder.\nsys.path.append(\"..\")\nfrom object_detection.utils import ops as utils_ops\n\n\n# This is needed to display the images.\n%matplotlib inline\n\n\nfrom object_detection.utils import label_map_util\n\nfrom object_detection.utils import visualization_utils as vis_util\n\nnum_classes = 1\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=num_classes, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n# Size, in inches, of the output images.\nIMAGE_SIZE = (12, 8)\n\n\ndef run_inference_for_single_image(image, graph):\n with graph.as_default():\n with tf.Session() as sess:\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {\n output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n tensor_name)\n if 'detection_masks' in tensor_dict:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(\n tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(\n tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(\n tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [\n real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [\n real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(\n detection_masks_reframed, 0)\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # Run inference\n output_dict = sess.run(tensor_dict,\n feed_dict={image_tensor: np.expand_dims(image, 0)})\n\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(\n output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict[\n 'detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n return output_dict\n\n\nfor image_path in TEST_IMAGE_PATHS:\n #load images\n image = Image.open(image_path)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n output_dict = run_inference_for_single_image(image_np, detection_graph)\n\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=8)\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)",
"/content/models/research/object_detection\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbd5ff7156738df3e41fee2e0414aadb621dff3b
| 8,978 |
ipynb
|
Jupyter Notebook
|
python-intro-exercises.ipynb
|
jamesaslack/digiskillstest
|
25e93fe322c41aab548396443bc95649fba30f48
|
[
"MIT"
] | null | null | null |
python-intro-exercises.ipynb
|
jamesaslack/digiskillstest
|
25e93fe322c41aab548396443bc95649fba30f48
|
[
"MIT"
] | null | null | null |
python-intro-exercises.ipynb
|
jamesaslack/digiskillstest
|
25e93fe322c41aab548396443bc95649fba30f48
|
[
"MIT"
] | null | null | null | 31.28223 | 280 | 0.511807 |
[
[
[
"# 1. Enumerate sentence\nCreate a function that prints words within a sentence along with their index in front of the word itself.\n\nFor example if we give the function the argument \"This is a sentence\" it should print\n\n```\n1 This\n2 is\n3 a\n4 sentence\n```",
"_____no_output_____"
]
],
[
[
"def enumWords(sentence):\n #Complete this method.\n ",
"_____no_output_____"
]
],
[
[
"# 2. Fibonacci\nCreate a function `fibonacci()` which takes an integer `num` as an input and returns the first `num` fibonacci numbers.\n\nEg.\n\nInput: `8`\n\nOutput: `[1, 1, 2, 3, 5, 8, 13, 21]`\n\n*Hint: You might want to recall [fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)*",
"_____no_output_____"
]
],
[
[
"def fibonacci(num):\n #Complete this method.\n\n################ Checking code ########################\n# Please don't edit this code\nnewList = fibonacci(10)\nif newList == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]:\n print(\"Success!\")\nelse:\n print(\"Error! Your function returned\")\n print(newList)\n ",
"_____no_output_____"
]
],
[
[
"# 3. Guessing game 2\nAsk the user to input a number and then have the program guess it. After each guess, the user must input whether it was too high, too low or the correct number. In the end, the program must always guess the users number and it must print out the number of guesses it needed.",
"_____no_output_____"
],
[
"# 4. Find word\nCreate a function that searches for a word within a provided lists of words. Inputs to the function should be a list of words and a word to search for\n\nThe function should return `True` if the word is contained within the list and `False` otherwise.",
"_____no_output_____"
]
],
[
[
"fruits = [\"banana\", \"orange\", \"grapefruit\", \"lime\", \"lemon\"]\n\ndef findWord(wordList, word):\n #Complete this method.\n \n################ Checking code ########################\n# Please don't edit this code\n\nif findWord(fruits, \"lime\"):\n print(\"Success!\")\nelse:\n print(\"Try again!\")",
"_____no_output_____"
]
],
[
[
"# 5. Powers of 2\nUse a while loop to find the largest power of 2 which is less than 30 million.",
"_____no_output_____"
],
[
"# 6. Making a better school\nThis exercise is on defining classes. This topic is covered in the optional notebook python-intro-3-extra-classes.\n\nBelow is a copy of the `School`, `Student` and `Exam` classes, together with a copy of the code needed to populate an object of that class with students and exam results. Edit the `School` class to add in the following functions:\n\n* `.resits()` : this should return the list of exams that each student should resit if they get a \"F\" or \"U\" grade.\n* `.prizeStudent()` : this should return the name of the student who scored the highest average percent across all of the exams.\n* `.reviseCourse(threshold)` : this should return the name of the exam that gets the lowest average score across all students, if the average score is below `threshold`.\n\nUse these functions to find out which students need to resit which exams, which student should be awarded the annual school prize, and which courses should be revised as the average mark is less than 50%.",
"_____no_output_____"
]
],
[
[
"class School:\n def __init__(self):\n self._students = {}\n self._exams = []\n\n def addStudent(self, name):\n self._students[name] = Student(name)\n\n def addExam(self, exam, max_score):\n self._exams.append(exam)\n \n for key in self._students.keys():\n self._students[key].addExam(exam, Exam(max_score))\n \n def addResult(self, name, exam, score):\n self._students[name].addResult(exam, score)\n \n def grades(self):\n grades = {}\n for name in self._students.keys():\n grades[name] = self._students[name].grades()\n return grades\n \n# NOTE: This is not a class method\ndef addResults(school, exam, results):\n for student in results.keys():\n school.addResult(student, exam, results[student])\n\n\nclass Student:\n def __init__(self, name):\n self._exams = {}\n self._name = name\n \n def addExam(self, name, exam):\n self._exams[name] = exam\n \n def addResult(self, name, score):\n self._exams[name].setResult(score)\n \n def result(self, exam):\n return self._exams[exam].percent()\n \n def grade(self, exam):\n return self._exams[exam].grade()\n \n def grades(self):\n g = {}\n for exam in self._exams.keys():\n g[exam] = self.grade(exam)\n return g\n \n\nclass Exam:\n def __init__(self, max_score=100):\n self._max_score = max_score\n self._actual_score = 0\n \n def percent(self):\n return 100.0 * self._actual_score / self._max_score\n \n def setResult(self, score):\n if score < 0:\n self._actual_score = 0\n elif score > self._max_score:\n self._actual_score = self._max_score\n else:\n self._actual_score = score\n \n def grade(self):\n if self._actual_score == 0:\n return \"U\"\n elif self.percent() > 70.0:\n return \"A\"\n elif self.percent() > 60.0:\n return \"B\"\n elif self.percent() > 50.0:\n return \"C\"\n else:\n return \"F\"\n \n# NOTE: This si not a class method\ndef addResults(school, exam, results):\n for student in results.keys():\n school.addResult(student, exam, results[student])",
"_____no_output_____"
],
[
"school = School()\n\nschool.grades()\n\nstudents = [\"Andrew\", \"James\", \"Laura\"]\nexams = { \"Maths\" : 20, \"Physics\" : 50, \"English\": 30}\nresults = {\"Maths\" : {\"Andrew\" : 13, \"James\" : 17, \"Laura\" : 14},\n \"Physics\" : {\"Andrew\" : 34, \"James\" : 44, \"Laura\" : 27},\n \"English\" : {\"Andrew\" : 26, \"James\" : 14, \"Laura\" : 29}}\n\nfor student in students:\n school.addStudent(student)\n \nfor exam in exams.keys():\n school.addExam(exam, exams[exam])\n \nfor result in results.keys():\n addResults(school, result, results[result])\n \nschool.grades()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cbd6079278de1a0639c3bd52552e6a1ea87e27a7
| 45,545 |
ipynb
|
Jupyter Notebook
|
p1_navigation/Navigation.ipynb
|
kinsella333/deepreinforcement_nanodegree
|
f1840c548820a9daeba475a68d02623625883c18
|
[
"MIT"
] | null | null | null |
p1_navigation/Navigation.ipynb
|
kinsella333/deepreinforcement_nanodegree
|
f1840c548820a9daeba475a68d02623625883c18
|
[
"MIT"
] | null | null | null |
p1_navigation/Navigation.ipynb
|
kinsella333/deepreinforcement_nanodegree
|
f1840c548820a9daeba475a68d02623625883c18
|
[
"MIT"
] | null | null | null | 114.14787 | 29,444 | 0.82806 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbd622b7ed44fadb89c43ca17dfb6f74fde6b704
| 49,746 |
ipynb
|
Jupyter Notebook
|
test/indexing.ipynb
|
BhavyaGulati/datamart
|
7cc346fd1315bafceeea6128d158cf787e3012ab
|
[
"MIT"
] | null | null | null |
test/indexing.ipynb
|
BhavyaGulati/datamart
|
7cc346fd1315bafceeea6128d158cf787e3012ab
|
[
"MIT"
] | null | null | null |
test/indexing.ipynb
|
BhavyaGulati/datamart
|
7cc346fd1315bafceeea6128d158cf787e3012ab
|
[
"MIT"
] | null | null | null | 318.884615 | 45,980 | 0.401138 |
[
[
[
"create index and document",
"_____no_output_____"
]
],
[
[
"import sys, os, json\nsys.path.append(sys.path.append(os.path.join(os.getcwd(), '..')))\nfrom datamart.query_manager import QueryManager\nfrom datamart.index_builder import IndexBuilder\n\nes_index = \"datamart_tmp\" # es index for your metadata, make sure you change to your own\n\nindex_builder = IndexBuilder()",
"_____no_output_____"
],
[
"tmp_description_dir = \"tmp\" # dataset schema json file\ntmp_description = \"tmp/tmp.json\" # dir of all dataset schema json files\ntmp_out = \"tmp/tmp.metadata\" # output of metadata\n",
"_____no_output_____"
]
],
[
[
"Indexing single dataset",
"_____no_output_____"
]
],
[
[
"this_metadata = index_builder.indexing(description_path=tmp_description,\n es_index=es_index,\n data_path=None,\n query_data_for_indexing=True,\n save_to_file=tmp_out,\n save_to_file_mode=\"w\",\n delete_old_es_index=True)\n",
"_____no_output_____"
]
],
[
[
"Take a look at the last metadata generated",
"_____no_output_____"
]
],
[
[
"print(json.dumps(this_metadata, indent=2))",
"{\n \"datamart_id\": 10000,\n \"title\": \"TAVG\",\n \"description\": \"Average temperature (tenths of degrees C)[Note that TAVG from source 'S' corresponds to an average for the period ending at 2400 UTC rather than local midnight]\",\n \"url\": \"https://www1.ncdc.noaa.gov/pub/data/ghcn/daily/readme.txt\",\n \"keywords\": [\n \"Average Temperature.\"\n ],\n \"date_updated\": \"2018-09-28T00:00:00\",\n \"provenance\": \"noaa.org\",\n \"materialization\": {\n \"python_path\": \"noaa_materializer\",\n \"arguments\": {\n \"type\": \"TAVG\"\n }\n },\n \"variables\": [\n {\n \"datamart_id\": 10001,\n \"name\": \"date\",\n \"description\": \"the date of data\",\n \"semantic_type\": [\n \"https://metadata.datadrivendiscovery.org/types/Time\"\n ],\n \"temporal_coverage\": {\n \"start\": \"1874-10-13T00:00:00\",\n \"end\": \"2018-10-01T00:00:00\"\n }\n },\n {\n \"datamart_id\": 10002,\n \"name\": \"stationId\",\n \"description\": \"the id of station which has this data\",\n \"semantic_type\": [\n \"https://metadata.datadrivendiscovery.org/types/CategoricalData\"\n ]\n },\n {\n \"datamart_id\": 10003,\n \"name\": \"city\",\n \"description\": \"the city data belongs to\",\n \"semantic_type\": [\n \"https://metadata.datadrivendiscovery.org/types/Location\"\n ],\n \"named_entity\": [\n \"abu dhabi\",\n \"ajman\",\n \"dubai\",\n \"sharjah\",\n \"kabul\",\n \"kandahar\",\n \"algiers\",\n \"annaba\",\n \"batna\",\n \"bechar\",\n \"bejaia\",\n \"constantine\",\n \"guelma\",\n \"laghouat\",\n \"medea\",\n \"mostaganem\",\n \"oran\",\n \"oum el bouaghi\",\n \"saida\",\n \"sidi-bel-abbes\",\n \"skikda\",\n \"tamanrasset\",\n \"tlemcen\",\n \"baku\",\n \"naxcivian\",\n \"durres\",\n \"shkoder\",\n \"tirana\",\n \"yerevan\",\n \"luanda\",\n \"lubango\",\n \"namibe\",\n \"bahia blanca\",\n \"buenos aires\",\n \"catamarca\",\n \"comodoro rivadavia\",\n \"cordoba\",\n \"corrientes\",\n \"formosa\",\n \"la plata\",\n \"la rioja\",\n \"mendoza\",\n \"neuquen\",\n \"parana\",\n \"posadas\",\n \"resistencia\",\n \"rio gallegos\",\n \"rosario\",\n \"salta\",\n \"san juan\",\n \"san luis\",\n \"san miguel de tucuman\",\n \"santa rosa\",\n \"santiago del estero\",\n \"ushuaia\",\n \"adelaide\",\n \"brisbane\",\n \"cairns\",\n \"canberra\",\n \"darwin\",\n \"melbourne\",\n \"newcastle\",\n \"perth\",\n \"rockhampton\",\n \"sydney\",\n \"townsville\",\n \"graz\",\n \"innsbruck\",\n \"klagenfurt\",\n \"salzburg\",\n \"vienna\",\n \"al-muharraq\",\n \"manama\",\n \"bridgetown\",\n \"francistown\",\n \"gaborone\",\n \"molepolole\",\n \"brussels\",\n \"gent\",\n \"hasselt\",\n \"liege\",\n \"nassau\",\n \"barisal\",\n \"chittagong\",\n \"dhaka\",\n \"rajshahi\",\n \"belize\",\n \"sarajevo\",\n \"cochabamba\",\n \"la paz\",\n \"oruro\",\n \"potosi\",\n \"santa cruz de la sierra\",\n \"sucre\",\n \"tarija\",\n \"trinidad\",\n \"mandalay\",\n \"myitkyina\",\n \"rangoon\",\n \"sagaing\",\n \"sittwe\",\n \"abomey\",\n \"cotonou\",\n \"lokossa\",\n \"natitingou\",\n \"parakou\",\n \"brest\",\n \"homyel'\",\n \"hrodna\",\n \"mahilyow\",\n \"minsk\",\n \"vitsyebsk\",\n \"honiara\",\n \"aracaju\",\n \"belem\",\n \"belo horizonte\",\n \"boa vista\",\n \"brasilia\",\n \"campo grande\",\n \"cuiaba\",\n \"curitiba\",\n \"florianopolis\",\n \"fortaleza\",\n \"goiania\",\n \"joao pessoa\",\n \"macapa\",\n \"maceio\",\n \"manaus\",\n \"natal\",\n \"niteroi\",\n \"palmas\",\n \"porto alegre\",\n \"porto velho\",\n \"recife\",\n \"rio branco\",\n \"rio de janeiro\",\n \"salvador\",\n \"santarem\",\n \"santos\",\n \"sao luis\",\n \"sao paulo\",\n \"teresina\",\n \"vitoria\",\n \"sofia\",\n \"varna\",\n \"bandar seri begawan\",\n \"bujumbura\",\n \"muyinga\",\n \"calgary\",\n \"edmonton\",\n \"fredericton\",\n \"halifax\",\n \"montreal\",\n \"ottawa\",\n \"quebec\",\n \"regina\",\n \"saint john\",\n \"saskatoon\",\n \"toronto\",\n \"vancouver\",\n \"victoria\",\n \"winnipeg\",\n \"phnom penh\",\n \"abeche\",\n \"moundou\",\n \"ndjamena\",\n \"sarh\",\n \"colombo\",\n \"trincomalee\",\n \"brazzaville\",\n \"loubomo\",\n \"pointe noire\",\n \"bandundu\",\n \"kananga\",\n \"kinshasa\",\n \"lumumbashi\",\n \"matadi\",\n \"mbandaka\",\n \"mbuji-mayi\",\n \"beijing\",\n \"changchun\",\n \"changsha\",\n \"chengdu\",\n \"chongqing\",\n \"dalian\",\n \"fushun\",\n \"fuzhou\",\n \"guangzhou\",\n \"guiyang\",\n \"hangzhou\",\n \"harbin\",\n \"hefei\",\n \"hong kong\",\n \"huhot\",\n \"jinan\",\n \"kashi\",\n \"kunming\",\n \"lanzhou\",\n \"lhasa\",\n \"macau\",\n \"nanchang\",\n \"nanjing\",\n \"nanning\",\n \"qingdao\",\n \"qiqihar\",\n \"shanghai\",\n \"shenyang\",\n \"shijiazhuang\",\n \"taiyuan\",\n \"tianjin\",\n \"urumqi\",\n \"wuhan\",\n \"xi'an\",\n \"xining\",\n \"yinchuan\",\n \"zhengzhou\",\n \"antofagasta\",\n \"concepcion\",\n \"copiapo\",\n \"coquimbo\",\n \"la serena\",\n \"puerto montt\",\n \"punta arenas\",\n \"santiago\",\n \"temuco\",\n \"bertoua\",\n \"douala\",\n \"garoua\",\n \"maroua\",\n \"ngaoundere\",\n \"arauca\",\n \"armenia\",\n \"barranquilla\",\n \"bogota\",\n \"bucaramanga\",\n \"cali\",\n \"cartagena\",\n \"cucuta\",\n \"ibague\",\n \"medellin\",\n \"monteria\",\n \"neiva\",\n \"pasto\",\n \"pereira\",\n \"quibdo\",\n \"riohacha\",\n \"san andres\",\n \"santa marta\",\n \"valledupar\",\n \"villavicencio\",\n \"puerto limon\",\n \"san jose\",\n \"bangui\",\n \"berberati\",\n \"camaguey\",\n \"havana\",\n \"matanzas\",\n \"praia\",\n \"lemesos\",\n \"nicosia\",\n \"alborg\",\n \"copenhagen\",\n \"santo domingo\",\n \"babahoyo\",\n \"loja\",\n \"portoviejo\",\n \"quito\",\n \"al ghurdaqah\",\n \"alexandria\",\n \"aswan\",\n \"cairo\",\n \"giza\",\n \"ismailia\",\n \"marsa matruh\",\n \"qena\",\n \"suez\",\n \"cork\",\n \"dublin\",\n \"galway\",\n \"bata\",\n \"malabo\",\n \"tallinn\",\n \"asmara\",\n \"nueva san salvador\",\n \"san salvador\",\n \"sonsonate\",\n \"addis ababa\",\n \"arba minch\",\n \"awasa\",\n \"debre markos\",\n \"dese\",\n \"gonder\",\n \"jima\",\n \"brno\",\n \"ostrava\",\n \"prague\",\n \"usti nad labem\",\n \"cayenne\",\n \"helsinki\",\n \"joensuu\",\n \"jyvaskyla\",\n \"kuopio\",\n \"oulu\",\n \"turku\",\n \"suva\",\n \"ajaccio\",\n \"amiens\",\n \"besancon\",\n \"caen\",\n \"clermont-ferrand\",\n \"dijon\",\n \"le havre\",\n \"lille\",\n \"limoges\",\n \"lyon\",\n \"marseille\",\n \"montpellier\",\n \"nancy\",\n \"nantes\",\n \"orleans\",\n \"paris\",\n \"poitiers\",\n \"reims\",\n \"rennes\",\n \"rouen\",\n \"strasbourg\",\n \"toulouse\",\n \"brikama\",\n \"libreville\",\n \"port gentil\",\n \"bat'umi\",\n \"sokhumi\",\n \"t'bilisi\",\n \"accra\",\n \"ho\",\n \"koforidua\",\n \"kumasi\",\n \"sekondi\",\n \"sunyani\",\n \"tamale\",\n \"wa\",\n \"berlin\",\n \"bonn\",\n \"bremen\",\n \"bremerhaven\",\n \"cologne\",\n \"dortmund\",\n \"dresden\",\n \"duisburg\",\n \"dusseldorf\",\n \"erfurt\",\n \"essen\",\n \"frankfurt\",\n \"hamburg\",\n \"hannover\",\n \"kiel\",\n \"leipzig\",\n \"magdeburg\",\n \"mainz\",\n \"munich\",\n \"potsdam\",\n \"saarbrucken\",\n \"schwerin\",\n \"stuttgart\",\n \"wiesbaden\",\n \"athens\",\n \"ioannina\",\n \"iraklion\",\n \"larisa\",\n \"piraeus\",\n \"thessaloniki\",\n \"guatemala\",\n \"conakry\",\n \"kankan\",\n \"kindia\",\n \"nzerekore\",\n \"georgetown\",\n \"la ceiba\",\n \"san pedro sula\",\n \"tegucigalpa\",\n \"rijeka\",\n \"zagreb\",\n \"budapest\",\n \"debrecen\",\n \"miskolc\",\n \"pecs\",\n \"szeged\",\n \"szombathely\",\n \"reykjavik\",\n \"ambon\",\n \"balikpapan\",\n \"banda aceh\",\n \"bandjermasin\",\n \"bengkulu\",\n \"denpasar\",\n \"jakarta\",\n \"jambi\",\n \"jayapura\",\n \"kupang\",\n \"makassar\",\n \"manado\",\n \"mataram\",\n \"medan\",\n \"padang\",\n \"palembang\",\n \"palu\",\n \"pontianak\",\n \"samarinda\",\n \"semarang\",\n \"surabaja\",\n \"tanjungkarang-telukbetung\",\n \"agartala\",\n \"ahmadabad\",\n \"aizawl\",\n \"amritsar\",\n \"bangalore\",\n \"bhopal\",\n \"bhubaneshwar\",\n \"chandigarh\",\n \"chennai\",\n \"cochin\",\n \"delhi\",\n \"hyderabad\",\n \"imphal\",\n \"jaipur\",\n \"kanpur\",\n \"kohima\",\n \"kolkata\",\n \"lucknow\",\n \"madurai\",\n \"mangalore\",\n \"mumbai\",\n \"nagpur\",\n \"new delhi\",\n \"panaji\",\n \"patna\",\n \"pondicherry\",\n \"port blair\",\n \"pune\",\n \"shillong\",\n \"simla\",\n \"trivandrum\",\n \"varanasi\",\n \"vishakhapatnam\",\n \"ahvaz\",\n \"arak\",\n \"esfahan\",\n \"hamadan\",\n \"ilam\",\n \"kerman\",\n \"kermanshah\",\n \"khorramabad\",\n \"mashhad\",\n \"rasht\",\n \"sanandaj\",\n \"semnan\",\n \"shahr-e kord\",\n \"shiraz\",\n \"tabriz\",\n \"tehran\",\n \"yazd\",\n \"zahedan\",\n \"zanjan\",\n \"beersheba\",\n \"jerusalem\",\n \"ramla\",\n \"tel aviv-yafo\",\n \"bologna\",\n \"cagliari\",\n \"campobasso\",\n \"genoa\",\n \"milan\",\n \"naples\",\n \"palermo\",\n \"rome\",\n \"trento\",\n \"trieste\",\n \"turin\",\n \"abidjan\",\n \"bondoukou\",\n \"bouake\",\n \"daloa\",\n \"dimbokro\",\n \"ferkessedougou\",\n \"gagnoa\",\n \"korhogo\",\n \"man\",\n \"yamoussoukro\",\n \"al basrah\",\n \"aomori\",\n \"fukuoka\",\n \"gifu\",\n \"hiroshima\",\n \"kawasaki\",\n \"kita kyushu\",\n \"kobe\",\n \"kyoto\",\n \"nagasaki\",\n \"nagoya\",\n \"naha\",\n \"osaka\",\n \"sapporo\",\n \"sendai\",\n \"shimonoseki\",\n \"tokyo\",\n \"yokohama\",\n \"kingston\",\n \"montego bay\",\n \"spanish town\",\n \"al mafraq\",\n \"az zarqa'\",\n \"irbid\",\n \"mombasa\",\n \"nairobi\",\n \"bishkek\",\n \"karakol\",\n \"osh\",\n \"haeju\",\n \"hyesan\",\n \"kaesong\",\n \"p'yongyang\",\n \"sariwon\",\n \"sinuiju\",\n \"wonsan\",\n \"ch'unch'on\",\n \"ch'ungju\",\n \"cheju\",\n \"chonju\",\n \"inch`on\",\n \"kwangju\",\n \"pusan\",\n \"seoul\",\n \"taegu\",\n \"taejon\",\n \"kuwait\",\n \"aktyubinsk\",\n \"almaty\",\n \"astana\",\n \"atyrau\",\n \"dzhambul\",\n \"karaganda\",\n \"kokshetau\",\n \"kostanay\",\n \"kyzylorda\",\n \"pavlodar\",\n \"petropavlovsk\",\n \"semipalatinsk\",\n \"shymkent\",\n \"taldykorgan\",\n \"ural'sk\",\n \"ust'-kamenogorsk\",\n \"zhezkazgan\",\n \"savannakhet\",\n \"vientiane\",\n \"beirut\",\n \"tripoli\",\n \"zahle\",\n \"riga\",\n \"vilnius\",\n \"monrovia\",\n \"banska bystrica\",\n \"kosice\",\n \"mafeteng\",\n \"maseru\",\n \"luxembourg\",\n \"ajdabiya\",\n \"al khums\",\n \"benghazi\",\n \"darnah\",\n \"misratah\",\n \"antananarivo\",\n \"antsiranana\",\n \"fianarantsoa\",\n \"mahajanga\",\n \"toamasina\",\n \"toliara\",\n \"fort-de-france\",\n \"chisinau\",\n \"mamoutzou\",\n \"ulaanbaatar\",\n \"blantyre\",\n \"lilongwe\",\n \"podgorica\",\n \"skopje\",\n \"bamako\",\n \"gao\",\n \"kayes\",\n \"mopti\",\n \"segou\",\n \"sikasso\",\n \"casablanca\",\n \"marrakech\",\n \"meknes\",\n \"oujda\",\n \"rabat\",\n \"port louis\",\n \"nouadhibou\",\n \"nouakchott\",\n \"muscat\",\n \"acapulco\",\n \"aguascalientes\",\n \"campeche\",\n \"chetumal\",\n \"chihuahua\",\n \"chilpancingo de los bravo\",\n \"ciudad victoria\",\n \"colima\",\n \"cuernavaca\",\n \"culiacan\",\n \"durango\",\n \"guadalajara\",\n \"guanajuato\",\n \"hermosillo\",\n \"jalapa\",\n \"mazatlan\",\n \"merida\",\n \"mexicali\",\n \"mexico\",\n \"monterrey\",\n \"morelia\",\n \"oaxaca\",\n \"pachuca\",\n \"puebla\",\n \"queretaro\",\n \"saltillo\",\n \"san luis potosi\",\n \"tampico\",\n \"tepic\",\n \"tlaxcala\",\n \"toluca\",\n \"tuxtla gutierrez\",\n \"veracruz\",\n \"villahermosa\",\n \"zacatecas\",\n \"johor baharu\",\n \"kota baharu\",\n \"kota kinabalu\",\n \"kuala lumpur\",\n \"kuantan new port\",\n \"kuching\",\n \"melaka\",\n \"pinang\",\n \"shah alam\",\n \"beira\",\n \"chimoio\",\n \"inhambane\",\n \"lichinga\",\n \"maputo\",\n \"nampula\",\n \"pemba\",\n \"quelimane\",\n \"tete\",\n \"xai-xai\",\n \"maradi\",\n \"niamey\",\n \"tahoua\",\n \"zinder\",\n \"enugu\",\n \"ilorin\",\n \"jos\",\n \"kano\",\n \"lagos\",\n \"maiduguri\",\n \"makurdi\",\n \"minna\",\n \"port harcourt\",\n \"yola\",\n \"'s-hertogenbosch\",\n \"amsterdam\",\n \"arnhem\",\n \"assen\",\n \"groningen\",\n \"haarlem\",\n \"leeuwarden\",\n \"maastricht\",\n \"rotterdam\",\n \"the hague\",\n \"utrecht\",\n \"zwolle\",\n \"bergen\",\n \"drammen\",\n \"kristiansand\",\n \"oslo\",\n \"stavanger\",\n \"tromso\",\n \"trondheim\",\n \"bhairawa\",\n \"biratnagar\",\n \"kathmandu\",\n \"willemstad\",\n \"chinandega\",\n \"esteli\",\n \"jinotega\",\n \"juigalpa\",\n \"managua\",\n \"masaya\",\n \"matagalpa\",\n \"auckland\",\n \"christchurch\",\n \"wellington\",\n \"asuncion\",\n \"coronel oviedo\",\n \"encarnacion\",\n \"arequipa\",\n \"ayacucho\",\n \"cajamarca\",\n \"callao\",\n \"chiclayo\",\n \"cuzco\",\n \"huanuco\",\n \"huaraz\",\n \"iquitos\",\n \"lima\",\n \"piura\",\n \"pucallpa\",\n \"tacna\",\n \"trujillo\",\n \"tumbes\",\n \"islamabad\",\n \"karachi\",\n \"lahore\",\n \"peshawar\",\n \"quetta\",\n \"rawalpindi\",\n \"bialystok\",\n \"elblag\",\n \"krakow\",\n \"poznan\",\n \"siedlce\",\n \"szczecin\",\n \"warsaw\",\n \"wroclaw\",\n \"colon\",\n \"panama\",\n \"aveiro\",\n \"braga\",\n \"coimbra\",\n \"evora\",\n \"funchal\",\n \"lisbon\",\n \"porto\",\n \"port moresby\",\n \"bissau\",\n \"doha\",\n \"belgrade\",\n \"saint-denis\",\n \"arad\",\n \"bacau\",\n \"baia mare\",\n \"bistrita\",\n \"botosani\",\n \"braila\",\n \"bucharest\",\n \"buzau\",\n \"calarasi\",\n \"cluj-napoca\",\n \"constanta\",\n \"craiova\",\n \"deva\",\n \"drobeta- turmu sererin\",\n \"galati\",\n \"iasi\",\n \"rimnicu vilcea\",\n \"sibiu\",\n \"suceava\",\n \"targu jiu\",\n \"timisoara\",\n \"tulcea\",\n \"manila\",\n \"mayaguez\",\n \"ponce\",\n \"abakan\",\n \"arkangel'sk\",\n \"astrakhan\",\n \"barnaul\",\n \"belgorod\",\n \"birobidzhan\",\n \"blagoveshchensk\",\n \"ceboksary\",\n \"chelyabinsk\",\n \"chita\",\n \"elista\",\n \"gor'kiy\",\n \"gorno-altaysk\",\n \"groznyy\",\n \"irkutsk\",\n \"ivanovo\",\n \"izevsk\",\n \"kaliningrad\",\n \"kaluga\",\n \"kazan'\",\n \"kemerovo\",\n \"khabarovsk\",\n \"khanty-mansiysk\",\n \"klintsy\",\n \"kostroma\",\n \"kotlas\",\n \"krasnodar\",\n \"krasnoyarsk\",\n \"kurgan\",\n \"kursk\",\n \"kuybyskev\",\n \"kyzyl\",\n \"lipetsk\",\n \"machackala\",\n \"magadan\",\n \"majkop\",\n \"moscow\",\n \"murmansk\",\n \"nazran\",\n \"novgorod\",\n \"novokuznetsk\",\n \"novosibirsk\",\n \"omsk\",\n \"orel\",\n \"orenburg\",\n \"penza\",\n \"perm'\",\n \"petropavloski-kamchatskiy\",\n \"petrozavodsk\",\n \"pskov\",\n \"rostov-on-don\",\n \"ryazan\",\n \"saint petersburg\",\n \"saransk\",\n \"saratov\",\n \"smolensk\",\n \"stavropol\",\n \"sverdlovsk\",\n \"syktyvkar\",\n \"tambov\",\n \"tomsk\",\n \"tula\",\n \"tver\",\n \"tyumen\",\n \"ufa\",\n \"ul'yanovsk\",\n \"ulan ude\",\n \"vladikavkaz\",\n \"vladimir\",\n \"vladivostok\",\n \"volgograd\",\n \"vologda\",\n \"vorkuta\",\n \"voronezh\",\n \"vyatka\",\n \"yakutsk\",\n \"yaroslavl\",\n \"yuzhno-sakhalinsk\",\n \"kigali\",\n \"abha\",\n \"jeddah\",\n \"mecca\",\n \"medina\",\n \"riyadh\",\n \"sakakah\",\n \"tabuk\",\n \"bisho\",\n \"bloemfontein\",\n \"cape town\",\n \"durban\",\n \"johannesburg\",\n \"kimberley\",\n \"mmabatho (mafikeng)\",\n \"nelspruit\",\n \"pietermaritzburg (ulundi)\",\n \"pietersburg (polokwane)\",\n \"port elizabeth\",\n \"pretoria\",\n \"richards bay\",\n \"dakar\",\n \"kolda\",\n \"thies\",\n \"ziguinchor\",\n \"ljubljana\",\n \"freetown\",\n \"singapore\",\n \"barcelona\",\n \"bilbao\",\n \"ceuta\",\n \"logrono\",\n \"madrid\",\n \"melilla\",\n \"murcia\",\n \"oviedo\",\n \"palma de mallorca\",\n \"pamplona\",\n \"santa cruz de tenerife\",\n \"santander\",\n \"santiago de compostela\",\n \"seville\",\n \"toledo\",\n \"valencia\",\n \"valladolid\",\n \"zaragoza\",\n \"el fasher\",\n \"el obeid\",\n \"khartoum\",\n \"malakal\",\n \"omdurman\",\n \"port sudan\",\n \"wau\",\n \"gavle\",\n \"goteborg\",\n \"halmstad\",\n \"jonkoping\",\n \"karlstad\",\n \"linkoping\",\n \"malmo\",\n \"orebro\",\n \"stockholm\",\n \"umea\",\n \"uppsala\",\n \"vasteras\",\n \"vaxjo\",\n \"aleppo\",\n \"damascus\",\n \"dayr az zawr\",\n \"hamah\",\n \"homs\",\n \"tartus\",\n \"basel\",\n \"geneva\",\n \"saint gallen\",\n \"zurich\",\n \"bangkok\",\n \"chang rai\",\n \"chanthaburi\",\n \"chiang mai\",\n \"chon buri\",\n \"chumphon\",\n \"kanchanaburi\",\n \"khon kaen\",\n \"lampang\",\n \"nakhon ratchasima\",\n \"nakhon si thammarat\",\n \"nong khai\",\n \"phetchabun\",\n \"phitsanulok\",\n \"phuket\",\n \"sakon nakhon\",\n \"samut prakan\",\n \"supham buri\",\n \"surat thani\",\n \"trang\",\n \"ubon ratchathani\",\n \"udon thani\",\n \"uttaradit\",\n \"dushanbe\",\n \"kulob\",\n \"leninobod\",\n \"qurghonteppa\",\n \"lome\",\n \"bizerte\",\n \"gabes\",\n \"gafsa\",\n \"jendouba\",\n \"kairouan\",\n \"sfax\",\n \"tunis\",\n \"adiyaman\",\n \"agri\",\n \"aintab\",\n \"ankara\",\n \"antalya\",\n \"aydin\",\n \"balikesir\",\n \"bingol\",\n \"bolu\",\n \"burdur\",\n \"bursa\",\n \"canakkale\",\n \"cankiri\",\n \"corum\",\n \"denizli\",\n \"diyarbakir\",\n \"edirne\",\n \"elazig\",\n \"erzincan\",\n \"erzurum\",\n \"giresun\",\n \"hakkari\",\n \"isparta\",\n \"istanbul\",\n \"izmir\",\n \"kahramanmaras\",\n \"kars\",\n \"kastamonu\",\n \"kirsehir\",\n \"konya\",\n \"kutahya\",\n \"malatya\",\n \"mersin\",\n \"mus\",\n \"nevsehir\",\n \"nigde\",\n \"rize\",\n \"sakarya\",\n \"samsun\",\n \"siirt\",\n \"sivas\",\n \"tekirdag\",\n \"tokat\",\n \"usak\",\n \"van\",\n \"yozgat\",\n \"zonguldak\",\n \"ashgabat\",\n \"mary\",\n \"turkmenbashi\",\n \"arusha\",\n \"bukoba\",\n \"dar es salaam\",\n \"dodoma\",\n \"iringa\",\n \"moshi\",\n \"mtwara\",\n \"musoma\",\n \"mwanza\",\n \"songea\",\n \"tabora\",\n \"zanzibar\",\n \"arua\",\n \"gulu\",\n \"jinja\",\n \"belfast\",\n \"birmingham\",\n \"dundee\",\n \"edinburgh\",\n \"glasgow\",\n \"leeds\",\n \"liverpool\",\n \"london\",\n \"manchester\",\n \"sheffield\",\n \"southampton\",\n \"cherkasy\",\n \"chernihiv\",\n \"chernivtsi\",\n \"dnipropetrovs'k\",\n \"donets'k\",\n \"ivano-frankivs'k\",\n \"kharkiv\",\n \"kherson\",\n \"khmel'nyts'kyz\",\n \"kirovohrad\",\n \"kovel'\",\n \"kyiv\",\n \"l'viv\",\n \"luhans'k\",\n \"mykolayiv\",\n \"odesa\",\n \"poltava\",\n \"rivne\",\n \"simferopol'\",\n \"sumy\",\n \"ternopil'\",\n \"uzhhorod\",\n \"vinnytsya\",\n \"zaporiyhzhya\",\n \"zhytomyra\",\n \"washington d.c.\",\n \"alexander\",\n \"anniston\",\n \"auburn\",\n \"cullman\",\n \"dothan\",\n \"enterprise\",\n \"eufaula\",\n \"florence\",\n \"fort payne\",\n \"gadsden\",\n \"huntsville\",\n \"jasper\",\n \"mobile\",\n \"montgomery\",\n \"selma\",\n \"talladega\",\n \"troy\",\n \"tuscaloosa\",\n \"anchorage\",\n \"fairbanks\",\n \"juneau\",\n \"nome\",\n \"seward\",\n \"bullhead\",\n \"casa grande\",\n \"douglas\",\n \"flagstaff\",\n \"green valley\",\n \"kingman\",\n \"lake havasu\",\n \"mesa\",\n \"nogales\",\n \"payson\",\n \"phoenix\",\n \"prescott\",\n \"sierra vista\",\n \"tucson\",\n \"yuma\",\n \"arkadelphia\",\n \"blytheville\",\n \"camden\",\n \"conway\",\n \"el dorado\",\n \"fayetteville\",\n \"forrest\",\n \"fort smith\",\n \"harrison\",\n \"hope\",\n \"hot springs\",\n \"jonesboro\",\n \"little rock\",\n \"magnolia\",\n \"mountain home\",\n \"paragould\",\n \"pine bluff\",\n \"russellville\",\n \"searcy\",\n \"siloam springs\",\n \"anaheim\",\n \"bakersfield\",\n \"barstow\",\n \"blythe\",\n \"chico\",\n \"clearlake\",\n \"coalinga\",\n \"el centro\",\n \"eureka\",\n \"fresno\",\n \"grass valley\",\n \"long beach\",\n \"los angeles\",\n \"merced\",\n \"modesto\",\n \"monterey\",\n \"napa\",\n \"oakland\",\n \"oceanside\",\n \"oxnard\",\n \"palm springs\",\n \"red bluff\",\n \"redding\",\n \"ridgecrest\",\n \"riverside\",\n \"rosamond\",\n \"sacramento\",\n \"salinas\",\n \"san bernardino\",\n \"san diego\",\n \"san francisco\",\n \"san jose\",\n \"san luis obispo\",\n \"santa ana\",\n \"santa barbara\",\n \"santa clarita\",\n \"santa cruz\",\n \"santa maria\",\n \"santa rosa\",\n \"simi valley\",\n \"soledad\",\n \"stockton\",\n \"susanville\",\n \"ukiah\",\n \"vallejo\",\n \"visalia\",\n \"yuba\",\n \"yucca valley\",\n \"boulder\",\n \"canon\",\n \"colorado springs\",\n \"denver\",\n \"durango\",\n \"fort collins\",\n \"fort morgan\",\n \"grand junction\",\n \"montrose\",\n \"pueblo\",\n \"sterling\",\n \"bridgeport\",\n \"danbury\",\n \"hartford\",\n \"new haven\",\n \"new london\",\n \"norwalk\",\n \"norwich\",\n \"stamford\",\n \"torrington\",\n \"waterbury\",\n \"willimantic\",\n \"dover\",\n \"newark\",\n \"belle glade\",\n \"boca raton\",\n \"boynton beach\",\n \"bradenton\",\n \"cape coral\",\n \"cocoa\",\n \"coral springs\",\n \"crestview\",\n \"daytona beach\",\n \"deltona\",\n \"destin\",\n \"fort lauderdale\",\n \"fort myers\",\n \"fort walton beach\",\n \"gainesville\",\n \"homosassa springs\",\n \"immokalee\",\n \"jacksonville\",\n \"jupiter\",\n \"key largo\",\n \"key west\",\n \"kissimmee\",\n \"marathon\",\n \"melbourne\",\n \"miami\",\n \"naples\",\n \"ocala\",\n \"orlando\",\n \"palatka\",\n \"palm coast\",\n \"panama\",\n \"pensacola\",\n \"pompano beach\",\n \"port charlotte\",\n \"port st. lucie\",\n \"sarasota\",\n \"spring hill\",\n \"st. augustine\",\n \"st. petersburg\",\n \"tallahassee\",\n \"tampa\",\n \"titusville\",\n \"west palm beach\",\n \"albany\",\n \"americus\",\n \"athens\",\n \"atlanta\",\n \"augusta\",\n \"bainbridge\",\n \"brunswick\",\n \"carrollton\",\n \"columbus\",\n \"dalton\",\n \"dublin\",\n \"fort benning south\",\n \"griffin\",\n \"hinesville\",\n \"lagrange\",\n \"macon\",\n \"milledgeville\",\n \"peachtree\",\n \"rome\",\n \"savannah\",\n \"st. marys\",\n \"statesboro\",\n \"thomasville\",\n \"tifton\",\n \"valdosta\",\n \"vidalia\",\n \"waycross\",\n \"hilo\",\n \"honolulu\",\n \"kahului\",\n \"boise\",\n \"coeur d'alene\",\n \"idaho falls\",\n \"lewiston\",\n \"moscow\",\n \"nampa\",\n \"pocatello\",\n \"twin falls\",\n \"aurora\",\n \"bloomington\",\n \"carbondale\",\n \"champaign\",\n \"charleston\",\n \"chicago\",\n \"crystal lake\",\n \"danville\",\n \"dekalb\",\n \"decatur\",\n \"dixon\",\n \"effingham\",\n \"elgin\",\n \"freeport\",\n \"galesburg\",\n \"joliet\",\n \"kankakee\",\n \"kewanee\",\n \"lincoln\",\n \"macomb\",\n \"mount vernon\",\n \"naperville\",\n \"ottawa\",\n \"peoria\",\n \"pontiac\",\n \"quincy\",\n \"rockford\",\n \"springfield\",\n \"streator\",\n \"waukegan\",\n \"evansville\",\n \"fort wayne\",\n \"indianapolis\",\n \"kokomo\",\n \"lafayette\",\n \"madison\",\n \"michigan\",\n \"muncie\",\n \"richmond\",\n \"shelbyville\",\n \"south bend\",\n \"terre haute\",\n \"vincennes\",\n \"ames\",\n \"burlington\",\n \"carroll\",\n \"cedar falls\",\n \"cedar rapids\",\n \"clinton\",\n \"davenport\",\n \"des moines\",\n \"dubuque\",\n \"fort dodge\",\n \"iowa\",\n \"keokuk\",\n \"marshalltown\",\n \"mason\",\n \"oskaloosa\",\n \"ottumwa\",\n \"sioux\",\n \"spencer\",\n \"storm lake\",\n \"waterloo\",\n \"coffeyville\",\n \"dodge\",\n \"emporia\",\n \"garden\",\n \"great bend\",\n \"hays\",\n \"hutchinson\",\n \"lawrence\",\n \"leavenworth\",\n \"liberal\",\n \"manhattan\",\n \"pittsburg\",\n \"salina\",\n \"topeka\",\n \"wichita\",\n \"winfield\",\n \"bowling green\",\n \"campbellsville\",\n \"elizabethtown\",\n \"fort knox\",\n \"frankfort\",\n \"hopkinsville\",\n \"lexington\",\n \"louisville\",\n \"madisonville\",\n \"middlesborough\",\n \"murray\",\n \"owensboro\",\n \"paducah\",\n \"somerset\",\n \"alexandria\",\n \"bastrop\",\n \"baton rouge\",\n \"bogalusa\",\n \"fort polk south\",\n \"hammond\",\n \"houma\",\n \"jennings\",\n \"lake charles\",\n \"minden\",\n \"monroe\",\n \"morgan\",\n \"natchitoches\",\n \"new iberia\",\n \"new orleans\",\n \"opelousas\",\n \"ruston\",\n \"shreveport\",\n \"thibodaux\",\n \"bangor\",\n \"portland\",\n \"waterville\",\n \"annapolis\",\n \"baltimore\",\n \"cambridge\",\n \"cumberland\",\n \"easton\",\n \"frederick\",\n \"hagerstown\",\n \"ocean pines\",\n \"salisbury\",\n \"westminster\",\n \"barnstable town\",\n \"boston\",\n \"brockton\",\n \"fall river\",\n \"gloucester\",\n \"greenfield\",\n \"leominster\",\n \"lowell\",\n \"new bedford\",\n \"north adams\",\n \"northampton\",\n \"pittsfield\",\n \"worcester\",\n \"alpena\",\n \"ann arbor\",\n \"benton harbor\",\n \"big rapids\",\n \"cadillac\",\n \"detroit\",\n \"escanaba\",\n \"flint\",\n \"grand rapids\",\n \"holland\",\n \"jackson\",\n \"kalamazoo\",\n \"lansing\",\n \"marquette\",\n \"midland\",\n \"mount pleasant\",\n \"muskegon\",\n \"owosso\",\n \"port huron\",\n \"saginaw\",\n \"sault ste. marie\",\n \"sturgis\",\n \"traverse\",\n \"austin\",\n \"bemidji\",\n \"brainerd\",\n \"buffalo\",\n \"duluth\",\n \"fairmont\",\n \"faribault\",\n \"fergus falls\",\n \"hibbing\",\n \"mankato\",\n \"marshall\",\n \"minneapolis\",\n \"new ulm\",\n \"owatonna\",\n \"rochester\",\n \"saint paul\",\n \"st. cloud\",\n \"willmar\",\n \"worthington\",\n \"biloxi\",\n \"clarksdale\",\n \"cleveland\",\n \"corinth\",\n \"greenville\",\n \"greenwood\",\n \"grenada\",\n \"gulfport\",\n \"hattiesburg\",\n \"laurel\",\n \"mccomb\",\n \"meridian\",\n \"natchez\",\n \"oxford\",\n \"picayune\",\n \"tupelo\",\n \"vicksburg\",\n \"yazoo\",\n \"cape girardeau\",\n \"columbia\",\n \"excelsior springs\",\n \"farmington\",\n \"fort leonard wood\",\n \"jefferson\",\n \"joplin\",\n \"kansas\",\n \"kennett\",\n \"kirksville\",\n \"lebanon\",\n \"maryville\",\n \"moberly\",\n \"poplar bluff\",\n \"rolla\",\n \"sedalia\",\n \"sikeston\",\n \"st. joseph\",\n \"st. louis\",\n \"warrensburg\",\n \"washington\",\n \"west plains\",\n \"billings\",\n \"bozeman\",\n \"butte\",\n \"great falls\",\n \"helena\",\n \"kalispell\",\n \"missoula\",\n \"beatrice\",\n \"fremont\",\n \"grand island\",\n \"hastings\",\n \"kearney\",\n \"norfolk\",\n \"north platte\",\n \"omaha\",\n \"scottsbluff\",\n \"boulder\",\n \"carson\",\n \"elko\",\n \"las vegas\",\n \"pahrump\",\n \"reno\",\n \"berlin\",\n \"claremont\",\n \"concord\",\n \"keene\",\n \"laconia\",\n \"nashua\",\n \"portsmouth\",\n \"jersey\",\n \"lakewood\",\n \"pleasantville\",\n \"toms river\",\n \"trenton\",\n \"vineland\",\n \"alamogordo\",\n \"albuquerque\",\n \"carlsbad\",\n \"clovis\",\n \"deming\",\n \"gallup\",\n \"las cruces\",\n \"roswell\",\n \"santa fe\",\n \"silver\",\n \"amsterdam\",\n \"binghamton\",\n \"brentwood\",\n \"brooklyn\",\n \"commack\",\n \"coram\",\n \"elmira\",\n \"hempstead\",\n \"huntington station\",\n \"ithaca\",\n \"jamestown\",\n \"kingston\",\n \"levittown\",\n \"massena\",\n \"middletown\",\n \"new\",\n \"new york\",\n \"niagara falls\",\n \"ogdensburg\",\n \"oneonta\",\n \"oswego\",\n \"plattsburgh\",\n \"poughkeepsie\",\n \"saratoga springs\",\n \"syracuse\",\n \"utica\",\n \"watertown\",\n \"yonkers\",\n \"asheboro\",\n \"asheville\",\n \"boone\",\n \"charlotte\",\n \"durham\",\n \"elizabeth\",\n \"fort bragg\",\n \"gastonia\",\n \"greensboro\",\n \"hendersonville\",\n \"hickory\",\n \"new bern\",\n \"raleigh\",\n \"roanoke rapids\",\n \"rocky mount\",\n \"statesville\",\n \"wilmington\",\n \"winston-salem\",\n \"bismarck\",\n \"dickinson\",\n \"fargo\",\n \"grand forks\",\n \"minot\",\n \"williston\",\n \"akron\",\n \"ashland\",\n \"ashtabula\",\n \"canton\",\n \"chillicothe\",\n \"cincinnati\",\n \"dayton\",\n \"defiance\",\n \"delaware\",\n \"lima\",\n \"mansfield\",\n \"marion\",\n \"mentor\",\n \"new philadelphia\",\n \"salem\",\n \"sandusky\",\n \"steubenville\",\n \"toledo\",\n \"urbana\",\n \"wooster\",\n \"youngstown\",\n \"zanesville\",\n \"ada\",\n \"altus\",\n \"ardmore\",\n \"bartlesville\",\n \"chickasha\",\n \"durant\",\n \"elk\",\n \"enid\",\n \"guymon\",\n \"lawton\",\n \"mcalester\",\n \"muskogee\",\n \"oklahoma\",\n \"okmulgee\",\n \"ponca\",\n \"shawnee\",\n \"stillwater\",\n \"tahlequah\",\n \"tulsa\",\n \"woodward\",\n \"bend\",\n \"coos bay\",\n \"corvallis\",\n \"eugene\",\n \"grants pass\",\n \"hermiston\",\n \"hillsboro\",\n \"klamath falls\",\n \"la grande\",\n \"medford\",\n \"ontario\",\n \"pendleton\",\n \"roseburg\",\n \"st. helens\",\n \"allentown\",\n \"altoona\",\n \"bethlehem\",\n \"bloomsburg\",\n \"chambersburg\",\n \"chester\",\n \"erie\",\n \"hanover\",\n \"harrisburg\",\n \"hazleton\",\n \"johnstown\",\n \"lancaster\",\n \"meadville\",\n \"philadelphia\",\n \"pittsburgh\",\n \"reading\",\n \"scranton\",\n \"state college\",\n \"uniontown\",\n \"wilkes-barre\",\n \"williamsport\",\n \"york\",\n \"newport\",\n \"providence\",\n \"westerly\",\n \"clemson\",\n \"hilton head island\",\n \"myrtle beach\",\n \"orangeburg\",\n \"rock hill\",\n \"spartanburg\",\n \"sumter\",\n \"aberdeen\",\n \"brookings\",\n \"huron\",\n \"mitchell\",\n \"pierre\",\n \"rapid\",\n \"sioux falls\",\n \"yankton\",\n \"bristol\",\n \"chattanooga\",\n \"clarksville\",\n \"cookeville\",\n \"dyersburg\",\n \"johnson\",\n \"kingsport\",\n \"knoxville\",\n \"mcminnville\",\n \"memphis\",\n \"morristown\",\n \"murfreesboro\",\n \"nashville\",\n \"union\",\n \"abilene\",\n \"amarillo\",\n \"arlington\",\n \"bay\",\n \"beaumont\",\n \"beeville\",\n \"brenham\",\n \"brownsville\",\n \"bryan\",\n \"college station\",\n \"conroe\",\n \"corpus christi\",\n \"corsicana\",\n \"dallas\",\n \"del rio\",\n \"denton\",\n \"eagle pass\",\n \"el campo\",\n \"el paso\",\n \"fort hood\",\n \"fort worth\",\n \"galveston\",\n \"gatesville\",\n \"harlingen\",\n \"henderson\",\n \"houston\",\n \"irving\",\n \"katy\",\n \"kerrville\",\n \"killeen\",\n \"kingsville\",\n \"lake jackson\",\n \"laredo\",\n \"longview\",\n \"lubbock\",\n \"lufkin\",\n \"mcallen\",\n \"mineral wells\",\n \"nacogdoches\",\n \"new braunfels\",\n \"odessa\",\n \"palestine\",\n \"paris\",\n \"plano\",\n \"port arthur\",\n \"rio grande\",\n \"round rock\",\n \"san antonio\",\n \"san marcos\",\n \"sherman\",\n \"stephenville\",\n \"sulphur springs\",\n \"texarkana\",\n \"the woodlands\",\n \"tyler\",\n \"uvalde\",\n \"vernon\",\n \"victoria\",\n \"waco\",\n \"waxahachie\",\n \"wichita falls\",\n \"brigham\",\n \"cedar\",\n \"logan\",\n \"ogden\",\n \"provo\",\n \"salt lake\",\n \"st. george\",\n \"montpelier\",\n \"rutland\",\n \"blacksburg\",\n \"centreville\",\n \"charlottesville\",\n \"chesapeake\",\n \"fredericksburg\",\n \"hampton\",\n \"harrisonburg\",\n \"leesburg\",\n \"lynchburg\",\n \"newport news\",\n \"roanoke\",\n \"virginia beach\",\n \"winchester\",\n \"anacortes\",\n \"bellevue\",\n \"bellingham\",\n \"bremerton\",\n \"centralia\",\n \"ellensburg\",\n \"everett\",\n \"federal way\",\n \"kennewick\",\n \"moses lake\",\n \"oak harbor\",\n \"olympia\",\n \"port angeles\",\n \"pullman\",\n \"redmond\",\n \"seattle\",\n \"spokane\",\n \"sunnyside\",\n \"tacoma\",\n \"vancouver\",\n \"walla walla\",\n \"wenatchee\",\n \"yakima\",\n \"beckley\",\n \"bluefield\",\n \"huntington\",\n \"martinsburg\",\n \"morgantown\",\n \"parkersburg\",\n \"wheeling\",\n \"eau claire\",\n \"green bay\",\n \"janesville\",\n \"kenosha\",\n \"la crosse\",\n \"manitowoc\",\n \"marinette\",\n \"milwaukee\",\n \"oshkosh\",\n \"racine\",\n \"river falls\",\n \"sheboygan\",\n \"wausau\",\n \"casper\",\n \"cheyenne\",\n \"evanston\",\n \"gillette\",\n \"laramie\",\n \"rock springs\",\n \"sheridan\",\n \"bobo dioulasso\",\n \"ouagadougou\",\n \"ouahigouya\",\n \"melo\",\n \"montevideo\",\n \"paysandu\",\n \"rivera\",\n \"salto\",\n \"tacuarembo\",\n \"andizhan\",\n \"bukhara\",\n \"dzhizak\",\n \"fergana\",\n \"gulistan\",\n \"karshi\",\n \"namangan\",\n \"navoi\",\n \"nukus\",\n \"samarkand\",\n \"tashkent\",\n \"termez\",\n \"urgench\",\n \"barcelona\",\n \"barquisimeto\",\n \"caracas\",\n \"ciudad bolivar\",\n \"coro\",\n \"cumana\",\n \"guanare\",\n \"maracaibo\",\n \"maturin\",\n \"merida\",\n \"puerto ayacucho\",\n \"puerto la cruz\",\n \"san carlos\",\n \"san cristobal\",\n \"san felipe\",\n \"san juan de los morros\",\n \"valencia\",\n \"bien hoa\",\n \"buon me thuot\",\n \"can tho\",\n \"da lat\",\n \"da nang\",\n \"haiphong\",\n \"hanoi\",\n \"ho chi minh\",\n \"hue\",\n \"my tho\",\n \"nha trang\",\n \"phan thiet\",\n \"play cu\",\n \"qui nhon\",\n \"soc trang\",\n \"tan an\",\n \"thanh hoa\",\n \"truc giang\",\n \"tuy hoa\",\n \"vinh long\",\n \"walvis bay\",\n \"windhoek\",\n \"manzini\",\n \"mbabane\",\n \"chipata\",\n \"kabwe\",\n \"kasama\",\n \"livingstone\",\n \"lusaka\",\n \"mongu\",\n \"ndola\",\n \"bulawayo\",\n \"gweru\",\n \"harare\",\n \"masvingo\"\n ]\n },\n {\n \"datamart_id\": 10004,\n \"name\": \"TAVG\",\n \"description\": \"Average temperature (tenths of degrees C)[Note that TAVG from source 'S' corresponds to an average for the period ending at 2400 UTC rather than local midnight]\",\n \"semantic_type\": [\n \"http://schema.org/Float\"\n ]\n }\n ]\n}\n"
]
],
[
[
"Bulk indexing multiple dataset",
"_____no_output_____"
]
],
[
[
"index_builder.bulk_indexing(description_dir=tmp_description_dir,\n es_index=es_index,\n data_dir=None,\n query_data_for_indexing=True,\n save_to_file=tmp_out,\n save_to_file_mode=\"w\",\n delete_old_es_index=True)\n",
"==== Creating metadata and indexing for tmp.json\n"
]
],
[
[
"Index is built in elasticsearch, check it here: http://dsbox02.isi.edu:9200/_cat/indices?v\n\nTry some query through Kibana: http://dsbox02.isi.edu:5601/app/kibana#/dev_tools/console?_g=()",
"_____no_output_____"
],
[
"Output metadata is written to `save_to_file` in indexing",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbd64ff08fa35f80d9e6047107f42b318b856dba
| 248,517 |
ipynb
|
Jupyter Notebook
|
01_math_and_python/06_optimizations.ipynb
|
pkuderov/mlda-course
|
ceb81afbc91b9f13cf68ab2503c53d3e8bf615c1
|
[
"MIT"
] | 2 |
2019-02-28T02:25:34.000Z
|
2021-02-15T19:22:22.000Z
|
01_math_and_python/06_optimizations.ipynb
|
pkuderov/mlda-course
|
ceb81afbc91b9f13cf68ab2503c53d3e8bf615c1
|
[
"MIT"
] | null | null | null |
01_math_and_python/06_optimizations.ipynb
|
pkuderov/mlda-course
|
ceb81afbc91b9f13cf68ab2503c53d3e8bf615c1
|
[
"MIT"
] | null | null | null | 370.920896 | 81,564 | 0.934274 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport scipy.stats as sts\nimport seaborn as sns\n\nsns.set()\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"# 01. Smooth function optimization\n\nРассмотрим все ту же функцию из задания по линейной алгебре:\n$ f(x) = \\sin{\\frac{x}{5}} * e^{\\frac{x}{10}} + 5 * e^{-\\frac{x}{2}} $\n, но теперь уже на промежутке `[1, 30]`.\n\nВ первом задании будем искать минимум этой функции на заданном промежутке с помощью `scipy.optimize`. Разумеется, в дальнейшем вы будете использовать методы оптимизации для более сложных функций, а `f(x)` мы рассмотрим как удобный учебный пример.",
"_____no_output_____"
],
[
"Напишите на Питоне функцию, вычисляющую значение `f(x)` по известному `x`. Будьте внимательны: не забывайте про то, что по умолчанию в питоне целые числа делятся нацело, и о том, что функции `sin` и `exp` нужно импортировать из модуля `math`.",
"_____no_output_____"
]
],
[
[
"from math import sin, exp, sqrt\n\ndef f(x):\n return sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2)\n\nf(10)",
"_____no_output_____"
],
[
"xs = np.arange(41, 60, 0.1)\nys = np.array([f(x) for x in xs])\n\nplt.plot(xs, ys)",
"_____no_output_____"
]
],
[
[
"Изучите примеры использования `scipy.optimize.minimize` в документации `Scipy` (см. \"Материалы\").\n\nПопробуйте найти минимум, используя стандартные параметры в функции `scipy.optimize.minimize` (т.е. задав только функцию и начальное приближение). Попробуйте менять начальное приближение и изучить, меняется ли результат.",
"_____no_output_____"
]
],
[
[
"from scipy.optimize import minimize, rosen, rosen_der, differential_evolution",
"_____no_output_____"
],
[
"x0 = 60\nminimize(f, x0)",
"_____no_output_____"
],
[
"# поиграемся с розенброком\nx0 = [1., 10.]\nminimize(rosen, x0, method='BFGS')",
"_____no_output_____"
]
],
[
[
"___\n\n## Submission #1\n\nУкажите в `scipy.optimize.minimize` в качестве метода `BFGS` (один из самых точных в большинстве случаев градиентных методов оптимизации), запустите из начального приближения $ x = 2 $. Градиент функции при этом указывать не нужно – он будет оценен численно. Полученное значение функции в точке минимума - ваш первый ответ по заданию 1, его надо записать с точностью до 2 знака после запятой.",
"_____no_output_____"
],
[
"Теперь измените начальное приближение на x=30. Значение функции в точке минимума - ваш второй ответ по заданию 1, его надо записать через пробел после первого, с точностью до 2 знака после запятой.\nСтоит обдумать полученный результат. Почему ответ отличается в зависимости от начального приближения? Если нарисовать график функции (например, как это делалось в видео, где мы знакомились с Numpy, Scipy и Matplotlib), можно увидеть, в какие именно минимумы мы попали. В самом деле, градиентные методы обычно не решают задачу глобальной оптимизации, поэтому результаты работы ожидаемые и вполне корректные.",
"_____no_output_____"
]
],
[
[
"# 1. x0 = 2\nx0 = 2\nres1 = minimize(f, x0, method='BFGS')\n\n# 2. x0 = 30\nx0 = 30\nres2 = minimize(f, x0, method='BFGS')\n\nwith open('out/06. submission1.txt', 'w') as f_out: \n output = '{0:.2f} {1:.2f}'.format(res1.fun, res2.fun)\n print(output)\n f_out.write(output)",
"1.75 -11.90\n"
]
],
[
[
"# 02. Глобальная оптимизация\n\nТеперь попробуем применить к той же функции $ f(x) $ метод глобальной оптимизации — дифференциальную эволюцию.\nИзучите документацию и примеры использования функции `scipy.optimize.differential_evolution`.\n\nОбратите внимание, что границы значений аргументов функции представляют собой список кортежей (list, в который помещены объекты типа tuple). Даже если у вас функция одного аргумента, возьмите границы его значений в квадратные скобки, чтобы передавать в этом параметре список из одного кортежа, т.к. в реализации `scipy.optimize.differential_evolution` длина этого списка используется чтобы определить количество аргументов функции.\n\nЗапустите поиск минимума функции f(x) с помощью дифференциальной эволюции на промежутке [1, 30]. Полученное значение функции в точке минимума - ответ в задаче 2. Запишите его с точностью до второго знака после запятой. В этой задаче ответ - только одно число.\nЗаметьте, дифференциальная эволюция справилась с задачей поиска глобального минимума на отрезке, т.к. по своему устройству она предполагает борьбу с попаданием в локальные минимумы.\n\nСравните количество итераций, потребовавшихся BFGS для нахождения минимума при хорошем начальном приближении, с количеством итераций, потребовавшихся дифференциальной эволюции. При повторных запусках дифференциальной эволюции количество итераций будет меняться, но в этом примере, скорее всего, оно всегда будет сравнимым с количеством итераций BFGS. Однако в дифференциальной эволюции за одну итерацию требуется выполнить гораздо больше действий, чем в BFGS. Например, можно обратить внимание на количество вычислений значения функции (nfev) и увидеть, что у BFGS оно значительно меньше. Кроме того, время работы дифференциальной эволюции очень быстро растет с увеличением числа аргументов функции.",
"_____no_output_____"
]
],
[
[
"res = differential_evolution(f, [(1, 30)])\nres",
"_____no_output_____"
]
],
[
[
"___\n\n## Submission #2",
"_____no_output_____"
]
],
[
[
"res = differential_evolution(f, [(1, 30)])\n\nwith open('out/06. submission2.txt', 'w') as f_out: \n output = '{0:.2f}'.format(res.fun)\n print(output)\n f_out.write(output)",
"-11.90\n"
]
],
[
[
"# 03. Минимизация негладкой функции\n\nТеперь рассмотрим функцию $ h(x) = int(f(x)) $ на том же отрезке `[1, 30]`, т.е. теперь каждое значение $ f(x) $ приводится к типу int и функция принимает только целые значения.\n\nТакая функция будет негладкой и даже разрывной, а ее график будет иметь ступенчатый вид. Убедитесь в этом, построив график $ h(x) $ с помощью `matplotlib`.",
"_____no_output_____"
]
],
[
[
"def h(x):\n return int(f(x))\n\nxs = np.arange(0, 70, 1)\nys = [h(x) for x in xs]\nplt.plot(xs, ys)",
"_____no_output_____"
],
[
"minimize(h, 40.3)",
"_____no_output_____"
]
],
[
[
"Попробуйте найти минимум функции $ h(x) $ с помощью BFGS, взяв в качестве начального приближения $ x = 30 $. Получившееся значение функции – ваш первый ответ в этой задаче.",
"_____no_output_____"
]
],
[
[
"res_bfgs = minimize(h, 30)\nres_bfgs",
"_____no_output_____"
]
],
[
[
"Теперь попробуйте найти минимум $ h(x) $ на отрезке `[1, 30]` с помощью дифференциальной эволюции. Значение функции $ h(x) $ в точке минимума – это ваш второй ответ в этом задании. Запишите его через пробел после предыдущего.",
"_____no_output_____"
]
],
[
[
"res_diff_evol = differential_evolution(h, [(1, 30)])\nres_diff_evol",
"_____no_output_____"
]
],
[
[
"Обратите внимание на то, что полученные ответы различаются. Это ожидаемый результат, ведь BFGS использует градиент (в одномерном случае – производную) и явно не пригоден для минимизации рассмотренной нами разрывной функции. Попробуйте понять, почему минимум, найденный BFGS, именно такой (возможно в этом вам поможет выбор разных начальных приближений).\n\nВыполнив это задание, вы увидели на практике, чем поиск минимума функции отличается от глобальной оптимизации, и когда может быть полезно применить вместо градиентного метода оптимизации метод, не использующий градиент. Кроме того, вы попрактиковались в использовании библиотеки SciPy для решения оптимизационных задач, и теперь знаете, насколько это просто и удобно.",
"_____no_output_____"
],
[
"___\n\n## Submission #3",
"_____no_output_____"
]
],
[
[
"with open('out/06. submission3.txt', 'w') as f_out: \n output = '{0:.2f} {1:.2f}'.format(res_bfgs.fun, res_diff_evol.fun)\n print(output)\n f_out.write(output)",
"-5.00 -11.00\n"
]
],
[
[
"___\n\nДальше играюсь с визуализацией ф-ии розенброка",
"_____no_output_____"
]
],
[
[
"lb = -10\nrb = 10\nstep = 0.2\ngen_xs = np.arange(lb, rb, step)\n\nxs = np.meshgrid(np.arange(-1, 1, 0.1), np.arange(-10, 10, 0.1))\nys = rosen(xs)\nprint(xs[0].shape, xs[1].shape, ys.shape)",
"(200, 20) (200, 20) (200, 20)\n"
],
[
"plt.contour(xs[0], xs[1], ys, 30)",
"_____no_output_____"
],
[
"lb = 0\nrb = 4\nstep = 0.3\ngen_xs = np.arange(lb, rb, step)\n\n#xs = np.meshgrid(gen_xs, gen_xs)\n#ys = (xs[0]**2 + xs[1]**2)**0.5\nxs = np.meshgrid(np.arange(-2, 2, 0.1), np.arange(-10, 10, 0.1))\nys = rosen(xs)\nprint(xs[0].shape, xs[1].shape, ys.shape)\n\ncmap = sns.cubehelix_palette(light=1, as_cmap=True)\nplt.contour(xs[0], xs[1], ys, 30, cmap=cmap)\n#plt.plot(xs[0], xs[1], marker='.', color='k', linestyle='none', alpha=0.1)\nplt.show()",
"(200, 40) (200, 40) (200, 40)\n"
],
[
"from mpl_toolkits.mplot3d import Axes3D\n\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\nsurf = ax.plot_surface(xs[0], xs[1], ys, cmap=cmap, linewidth=0, antialiased=False)\n\nplt.show()",
"_____no_output_____"
],
[
"x0 = [1.3, 0.7, 0.8, 1.9, 1.2]\n\n\nres = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6)\nres.x",
"_____no_output_____"
]
]
] |
[
"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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbd6647f54cbc6ce2046d4ca505d59f2a4471079
| 6,474 |
ipynb
|
Jupyter Notebook
|
assignment_2/update_github.ipynb
|
jaleeli413/Harvard_BAI
|
989403b479b8c7f89758fa0c6cd8914facea5adc
|
[
"MIT"
] | null | null | null |
assignment_2/update_github.ipynb
|
jaleeli413/Harvard_BAI
|
989403b479b8c7f89758fa0c6cd8914facea5adc
|
[
"MIT"
] | null | null | null |
assignment_2/update_github.ipynb
|
jaleeli413/Harvard_BAI
|
989403b479b8c7f89758fa0c6cd8914facea5adc
|
[
"MIT"
] | null | null | null | 6,474 | 6,474 | 0.71177 |
[
[
[
"<a href=\"https://colab.research.google.com/github/Spandan-Madan/Harvard_BAI/blob/main/assignment_1/colab_test.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"from google.colab import 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"
],
[
"import os\nos.chdir('/content/drive/MyDrive/Harvard_BAI')",
"_____no_output_____"
],
[
"### CREATE A PERSONAL ACCESS TOKEN FROM YOUR GITHUB ACCOUNT ####\n\n# Go to Settings ---> Developer Settings ---> Generate new access token\n# For scope just select the checkbox \"repo\".\n# Copy the access token.\n# Create a file (OUTSIDE YOUR GITHUB REPO) in your google drive access_token.txt and paste your access token to this file.\n# I made mine at /content/drive/MyDrive/access_token.txt, which is the path below. If you make your file at another path, use that path below.",
"_____no_output_____"
],
[
"with open('/content/drive/MyDrive/access_token.txt','r') as F:\n contents = F.readlines()",
"_____no_output_____"
],
[
"token = contents[0]",
"_____no_output_____"
],
[
"!git config --global user.email \"[email protected]\"\n!git config --global user.name \"jaleeli413\"",
"_____no_output_____"
],
[
"!git add assignment_2/\n#!git add assignment_2/update_github.ipynb\n#!git add assignment_2/todos.md",
"_____no_output_____"
],
[
"!git commit -m \"Updating Assignment2 + Todos\"",
"[main 1d7e1f9] Updating Assignment2 + Todos\n 2 files changed, 18 insertions(+), 1 deletion(-)\n rewrite assignment_2/Assignment2.ipynb (90%)\n create mode 100644 assignment_2/todos.md\n"
],
[
"",
"_____no_output_____"
],
[
"# THE FIRST TIME YOU RUN THIS CODE, UNCOMMENT LINES BELOW. AFTER THAT COMMENT THEM BACK.\n# !git remote rm origin\n# !git remote add origin https://Spandan-Madan:[email protected]/Spandan-Madan/Harvard_BAI.git",
"_____no_output_____"
],
[
"!git push -u origin main",
"Counting objects: 5, done.\nDelta compression using up to 2 threads.\nCompressing objects: 20% (1/5) \rCompressing objects: 40% (2/5) \rCompressing objects: 60% (3/5) \rCompressing objects: 80% (4/5) \rCompressing objects: 100% (5/5) \rCompressing objects: 100% (5/5), done.\nWriting objects: 20% (1/5) \rWriting objects: 40% (2/5) \rWriting objects: 60% (3/5) \rWriting objects: 80% (4/5) \rWriting objects: 100% (5/5) \rWriting objects: 100% (5/5), 1.61 KiB | 205.00 KiB/s, done.\nTotal 5 (delta 2), reused 0 (delta 0)\nremote: Resolving deltas: 100% (2/2), completed with 2 local objects.\u001b[K\nTo https://github.com/Spandan-Madan/Harvard_BAI.git\n 13ede99..1d7e1f9 main -> main\nBranch 'main' set up to track remote branch 'main' from 'origin'.\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd672676f9b2045e8f03532ba17a671547a8340
| 245,613 |
ipynb
|
Jupyter Notebook
|
notebooks/WeightImprintingSoftmax/WeightImprintingSoftmax_LFW.ipynb
|
PAL-ML/CLIPPER
|
c971c89a9315d27ddb007082ff209153859f5906
|
[
"MIT"
] | 3 |
2021-06-05T05:00:54.000Z
|
2021-06-16T21:17:52.000Z
|
notebooks/WeightImprintingSoftmax/WeightImprintingSoftmax_LFW.ipynb
|
PAL-ML/CLIPPER
|
c971c89a9315d27ddb007082ff209153859f5906
|
[
"MIT"
] | null | null | null |
notebooks/WeightImprintingSoftmax/WeightImprintingSoftmax_LFW.ipynb
|
PAL-ML/CLIPPER
|
c971c89a9315d27ddb007082ff209153859f5906
|
[
"MIT"
] | null | null | null | 79.357997 | 100,331 | 0.613893 |
[
[
[
"# Mount Drive",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
],
[
"!pip install -U -q PyDrive\n!pip install httplib2==0.15.0\nimport os\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nfrom pydrive.files import GoogleDriveFileList\nfrom google.colab import auth\nfrom oauth2client.client import GoogleCredentials\n\nfrom getpass import getpass\nimport urllib\n\n# 1. Authenticate and create the PyDrive client.\nauth.authenticate_user()\ngauth = GoogleAuth()\ngauth.credentials = GoogleCredentials.get_application_default()\ndrive = GoogleDrive(gauth)\n\n# Cloning PAL_2021 to access modules.\n# Need password to access private repo.\n\nif 'CLIPPER' not in os.listdir():\n cmd_string = 'git clone https://github.com/PAL-ML/CLIPPER.git'\n os.system(cmd_string)",
"Collecting httplib2==0.15.0\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/be/83/5e006e25403871ffbbf587c7aa4650158c947d46e89f2d50dcaf018464de/httplib2-0.15.0-py3-none-any.whl (94kB)\n\r\u001b[K |███▌ | 10kB 16.6MB/s eta 0:00:01\r\u001b[K |███████ | 20kB 21.4MB/s eta 0:00:01\r\u001b[K |██████████▍ | 30kB 22.2MB/s eta 0:00:01\r\u001b[K |█████████████▉ | 40kB 18.0MB/s eta 0:00:01\r\u001b[K |█████████████████▎ | 51kB 13.4MB/s eta 0:00:01\r\u001b[K |████████████████████▊ | 61kB 10.6MB/s eta 0:00:01\r\u001b[K |████████████████████████▏ | 71kB 11.6MB/s eta 0:00:01\r\u001b[K |███████████████████████████▋ | 81kB 12.5MB/s eta 0:00:01\r\u001b[K |███████████████████████████████ | 92kB 13.5MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 102kB 7.0MB/s \n\u001b[?25hInstalling collected packages: httplib2\n Found existing installation: httplib2 0.17.4\n Uninstalling httplib2-0.17.4:\n Successfully uninstalled httplib2-0.17.4\nSuccessfully installed httplib2-0.15.0\n"
]
],
[
[
"# Installation",
"_____no_output_____"
],
[
"## Install multi label metrics dependencies",
"_____no_output_____"
]
],
[
[
"! pip install scikit-learn==0.24",
"Collecting scikit-learn==0.24\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/b1/ed/ab51a8da34d2b3f4524b21093081e7f9e2ddf1c9eac9f795dcf68ad0a57d/scikit_learn-0.24.0-cp37-cp37m-manylinux2010_x86_64.whl (22.3MB)\n\u001b[K |████████████████████████████████| 22.3MB 1.5MB/s \n\u001b[?25hRequirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.7/dist-packages (from scikit-learn==0.24) (1.4.1)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn==0.24) (1.0.1)\nRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from scikit-learn==0.24) (1.19.5)\nCollecting threadpoolctl>=2.0.0\n Downloading https://files.pythonhosted.org/packages/f7/12/ec3f2e203afa394a149911729357aa48affc59c20e2c1c8297a60f33f133/threadpoolctl-2.1.0-py3-none-any.whl\nInstalling collected packages: threadpoolctl, scikit-learn\n Found existing installation: scikit-learn 0.22.2.post1\n Uninstalling scikit-learn-0.22.2.post1:\n Successfully uninstalled scikit-learn-0.22.2.post1\nSuccessfully installed scikit-learn-0.24.0 threadpoolctl-2.1.0\n"
]
],
[
[
"## Install CLIP dependencies",
"_____no_output_____"
]
],
[
[
"import subprocess\n\nCUDA_version = [s for s in subprocess.check_output([\"nvcc\", \"--version\"]).decode(\"UTF-8\").split(\", \") if s.startswith(\"release\")][0].split(\" \")[-1]\nprint(\"CUDA version:\", CUDA_version)\n\nif CUDA_version == \"10.0\":\n torch_version_suffix = \"+cu100\"\nelif CUDA_version == \"10.1\":\n torch_version_suffix = \"+cu101\"\nelif CUDA_version == \"10.2\":\n torch_version_suffix = \"\"\nelse:\n torch_version_suffix = \"+cu110\"",
"CUDA version: 11.0\n"
],
[
"! pip install torch==1.7.1{torch_version_suffix} torchvision==0.8.2{torch_version_suffix} -f https://download.pytorch.org/whl/torch_stable.html ftfy regex",
"Looking in links: https://download.pytorch.org/whl/torch_stable.html\nCollecting torch==1.7.1+cu110\n\u001b[?25l Downloading https://download.pytorch.org/whl/cu110/torch-1.7.1%2Bcu110-cp37-cp37m-linux_x86_64.whl (1156.8MB)\n\u001b[K |███████████████████████ | 834.1MB 1.5MB/s eta 0:03:38tcmalloc: large alloc 1147494400 bytes == 0x561d282c4000 @ 0x7f8b16cf4615 0x561cee453cdc 0x561cee53352a 0x561cee456afd 0x561cee547fed 0x561cee4ca988 0x561cee4c54ae 0x561cee4583ea 0x561cee4ca7f0 0x561cee4c54ae 0x561cee4583ea 0x561cee4c732a 0x561cee548e36 0x561cee4c6853 0x561cee548e36 0x561cee4c6853 0x561cee548e36 0x561cee4c6853 0x561cee548e36 0x561cee5cb3e1 0x561cee52b6a9 0x561cee496cc4 0x561cee457559 0x561cee4cb4f8 0x561cee45830a 0x561cee4c63b5 0x561cee4c57ad 0x561cee4583ea 0x561cee4c63b5 0x561cee45830a 0x561cee4c63b5\n\u001b[K |█████████████████████████████▏ | 1055.7MB 1.5MB/s eta 0:01:08tcmalloc: large alloc 1434370048 bytes == 0x561d6c91a000 @ 0x7f8b16cf4615 0x561cee453cdc 0x561cee53352a 0x561cee456afd 0x561cee547fed 0x561cee4ca988 0x561cee4c54ae 0x561cee4583ea 0x561cee4ca7f0 0x561cee4c54ae 0x561cee4583ea 0x561cee4c732a 0x561cee548e36 0x561cee4c6853 0x561cee548e36 0x561cee4c6853 0x561cee548e36 0x561cee4c6853 0x561cee548e36 0x561cee5cb3e1 0x561cee52b6a9 0x561cee496cc4 0x561cee457559 0x561cee4cb4f8 0x561cee45830a 0x561cee4c63b5 0x561cee4c57ad 0x561cee4583ea 0x561cee4c63b5 0x561cee45830a 0x561cee4c63b5\n\u001b[K |████████████████████████████████| 1156.7MB 1.5MB/s eta 0:00:01tcmalloc: large alloc 1445945344 bytes == 0x561dc2106000 @ 0x7f8b16cf4615 0x561cee453cdc 0x561cee53352a 0x561cee456afd 0x561cee547fed 0x561cee4ca988 0x561cee4c54ae 0x561cee4583ea 0x561cee4c660e 0x561cee4c54ae 0x561cee4583ea 0x561cee4c660e 0x561cee4c54ae 0x561cee4583ea 0x561cee4c660e 0x561cee4c54ae 0x561cee4583ea 0x561cee4c660e 0x561cee4c54ae 0x561cee4583ea 0x561cee4c660e 0x561cee45830a 0x561cee4c660e 0x561cee4c54ae 0x561cee4583ea 0x561cee4c732a 0x561cee4c54ae 0x561cee4583ea 0x561cee4c732a 0x561cee4c54ae 0x561cee458a81\n\u001b[K |████████████████████████████████| 1156.8MB 16kB/s \n\u001b[?25hCollecting torchvision==0.8.2+cu110\n\u001b[?25l Downloading https://download.pytorch.org/whl/cu110/torchvision-0.8.2%2Bcu110-cp37-cp37m-linux_x86_64.whl (12.9MB)\n\u001b[K |████████████████████████████████| 12.9MB 203kB/s \n\u001b[?25hCollecting ftfy\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/ce/b5/5da463f9c7823e0e575e9908d004e2af4b36efa8d02d3d6dad57094fcb11/ftfy-6.0.1.tar.gz (63kB)\n\u001b[K |████████████████████████████████| 71kB 3.3MB/s \n\u001b[?25hRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (2019.12.20)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch==1.7.1+cu110) (3.7.4.3)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch==1.7.1+cu110) (1.19.5)\nRequirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.7/dist-packages (from torchvision==0.8.2+cu110) (7.1.2)\nRequirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from ftfy) (0.2.5)\nBuilding wheels for collected packages: ftfy\n Building wheel for ftfy (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for ftfy: filename=ftfy-6.0.1-cp37-none-any.whl size=41573 sha256=0e69a343f49b5c44652ea7fb8e6ff182c4a0d14fb22c5a1fcdbfb57ea05ca5f6\n Stored in directory: /root/.cache/pip/wheels/ae/73/c7/9056e14b04919e5c262fe80b54133b1a88d73683d05d7ac65c\nSuccessfully built ftfy\n\u001b[31mERROR: torchtext 0.9.1 has requirement torch==1.8.1, but you'll have torch 1.7.1+cu110 which is incompatible.\u001b[0m\nInstalling collected packages: torch, torchvision, ftfy\n Found existing installation: torch 1.8.1+cu101\n Uninstalling torch-1.8.1+cu101:\n Successfully uninstalled torch-1.8.1+cu101\n Found existing installation: torchvision 0.9.1+cu101\n Uninstalling torchvision-0.9.1+cu101:\n Successfully uninstalled torchvision-0.9.1+cu101\nSuccessfully installed ftfy-6.0.1 torch-1.7.1+cu110 torchvision-0.8.2+cu110\n"
],
[
"! pip install ftfy regex\n! wget https://openaipublic.azureedge.net/clip/bpe_simple_vocab_16e6.txt.gz -O bpe_simple_vocab_16e6.txt.gz",
"Requirement already satisfied: ftfy in /usr/local/lib/python3.7/dist-packages (6.0.1)\nRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (2019.12.20)\nRequirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from ftfy) (0.2.5)\n--2021-05-17 16:12:33-- https://openaipublic.azureedge.net/clip/bpe_simple_vocab_16e6.txt.gz\nResolving openaipublic.azureedge.net (openaipublic.azureedge.net)... 13.107.246.39, 13.107.213.39, 2620:1ec:bdf::39, ...\nConnecting to openaipublic.azureedge.net (openaipublic.azureedge.net)|13.107.246.39|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 1356917 (1.3M) [application/octet-stream]\nSaving to: ‘bpe_simple_vocab_16e6.txt.gz’\n\nbpe_simple_vocab_16 100%[===================>] 1.29M --.-KB/s in 0.08s \n\n2021-05-17 16:12:34 (16.5 MB/s) - ‘bpe_simple_vocab_16e6.txt.gz’ saved [1356917/1356917]\n\n"
],
[
"!pip install git+https://github.com/Sri-vatsa/CLIP # using this fork because of visualization capabilities",
"Collecting git+https://github.com/Sri-vatsa/CLIP\n Cloning https://github.com/Sri-vatsa/CLIP to /tmp/pip-req-build-r5ufba0x\n Running command git clone -q https://github.com/Sri-vatsa/CLIP /tmp/pip-req-build-r5ufba0x\nRequirement already satisfied: ftfy in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (6.0.1)\nRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (2019.12.20)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (4.41.1)\nRequirement already satisfied: torch~=1.7.1 in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (1.7.1+cu110)\nRequirement already satisfied: torchvision~=0.8.2 in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (0.8.2+cu110)\nRequirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from ftfy->clip==1.0) (0.2.5)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch~=1.7.1->clip==1.0) (1.19.5)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch~=1.7.1->clip==1.0) (3.7.4.3)\nRequirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.7/dist-packages (from torchvision~=0.8.2->clip==1.0) (7.1.2)\nBuilding wheels for collected packages: clip\n Building wheel for clip (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for clip: filename=clip-1.0-cp37-none-any.whl size=1368623 sha256=163cf33cf5161cf5eae29c5c5a5e34233fba491af6b24bd357b8d0dc5b9cef62\n Stored in directory: /tmp/pip-ephem-wheel-cache-mrooc3wn/wheels/cc/55/69/0d411dabbd5009fd069d47b47cf7839c54e595dc61725b307b\nSuccessfully built clip\nInstalling collected packages: clip\nSuccessfully installed clip-1.0\n"
]
],
[
[
"## Install clustering dependencies",
"_____no_output_____"
]
],
[
[
"!pip -q install umap-learn>=0.3.7",
"_____no_output_____"
]
],
[
[
"## Install dataset manager dependencies",
"_____no_output_____"
]
],
[
[
"!pip install wget",
"Collecting wget\n Downloading https://files.pythonhosted.org/packages/47/6a/62e288da7bcda82b935ff0c6cfe542970f04e29c756b0e147251b2fb251f/wget-3.2.zip\nBuilding wheels for collected packages: wget\n Building wheel for wget (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for wget: filename=wget-3.2-cp37-none-any.whl size=9681 sha256=7e448148860d1b41d62b774c386fbe77d8e420e73ce2e586a33d801733510a7f\n Stored in directory: /root/.cache/pip/wheels/40/15/30/7d8f7cea2902b4db79e3fea550d7d7b85ecb27ef992b618f3f\nSuccessfully built wget\nInstalling collected packages: wget\nSuccessfully installed wget-3.2\n"
]
],
[
[
"# Imports",
"_____no_output_____"
]
],
[
[
"# ML Libraries\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nimport keras\n\n# Data processing\nimport PIL\nimport base64\nimport imageio\nimport pandas as pd\nimport numpy as np\nimport json\n\nfrom PIL import Image\nimport cv2\nfrom sklearn.feature_extraction.image import extract_patches_2d\n\n# Plotting\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\nfrom IPython.core.display import display, HTML\nfrom matplotlib import cm\nimport matplotlib.image as mpimg\n\n# Models\nimport clip\n\n# Datasets\nimport tensorflow_datasets as tfds\n\n# Clustering\n# import umap\n\nfrom sklearn import metrics\nfrom sklearn.cluster import KMeans\n#from yellowbrick.cluster import KElbowVisualizer\n\n# Misc\nimport progressbar\nimport logging\nfrom abc import ABC, abstractmethod\nimport time\nimport urllib.request\nimport os\nfrom sklearn.metrics import jaccard_score, hamming_loss, accuracy_score, f1_score\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\n\n# Modules\nfrom CLIPPER.code.ExperimentModules import embedding_models\nfrom CLIPPER.code.ExperimentModules.dataset_manager import DatasetManager\nfrom CLIPPER.code.ExperimentModules.weight_imprinting_classifier import WeightImprintingClassifier\nfrom CLIPPER.code.ExperimentModules import simclr_data_augmentations\nfrom CLIPPER.code.ExperimentModules.utils import (save_npy, load_npy, \n get_folder_id, \n create_expt_dir, \n save_to_drive, \n load_all_from_drive_folder, \n download_file_by_name, \n delete_file_by_name)\n\nlogging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR)",
"_____no_output_____"
]
],
[
[
"# Initialization & Constants",
"_____no_output_____"
],
[
"## Dataset details",
"_____no_output_____"
]
],
[
[
"dataset_name = \"LFW\"\nfolder_name = \"LFW-Embeddings-28-02-21\"\n\n# Change parentid to match that of experiments root folder in gdrive\nparentid = '1bK72W-Um20EQDEyChNhNJthUNbmoSEjD'\n\n# Filepaths\ntrain_labels_filename = \"train_labels.npz\"\n\ntrain_embeddings_filename_suffix = \"_embeddings_train.npz\"\n\n# Initialize sepcific experiment folder in drive\nfolderid = create_expt_dir(drive, parentid, folder_name)",
"title: LFW-Embeddings-28-02-21, id: 18CcWLV0mDi9Iuk7rFquHa1jRQ5VI0BSx\nExperiment folder already exists. WARNING: Following with this run might overwrite existing results stored.\n"
]
],
[
[
"## Few shot learning parameters",
"_____no_output_____"
]
],
[
[
"num_ways = 5 # [5, 20]\nnum_shot = 5 # [5, 1]\nnum_eval = 15 # [5, 10, 15, 19]\nnum_episodes = 100\nshuffle = False",
"_____no_output_____"
]
],
[
[
"## Image embedding and augmentations",
"_____no_output_____"
]
],
[
[
"embedding_model = embedding_models.CLIPEmbeddingWrapper()\nnum_augmentations = 0 # [0, 5, 10]\ntrivial=False # [True, False]",
"_____no_output_____"
]
],
[
[
"## Training parameters",
"_____no_output_____"
]
],
[
[
"# List of number of epochs to train over, e.g. [5, 10, 15, 20]. [0] indicates no training.\ntrain_epochs_arr = [0] \n\n# Single label (softmax) parameters\nmulti_label= False # [True, False] i.e. sigmoid or softmax\nmetrics_val = ['accuracy', 'ap', 'map', 'c_f1', 'o_f1', 'c_precision', 'o_precision', 'c_recall', 'o_recall', 'top1_accuracy', 'top5_accuracy', 'classwise_accuracy', 'c_accuracy']",
"_____no_output_____"
]
],
[
[
"# Load data",
"_____no_output_____"
]
],
[
[
"def get_ndarray_from_drive(drive, folderid, filename):\n download_file_by_name(drive, folderid, filename)\n return np.load(filename)['data']\n\ntrain_labels = get_ndarray_from_drive(drive, folderid, train_labels_filename)",
"Downloading train_labels.npz from GDrive\nDownloading train_labels.npz from GDrive\n"
],
[
"train_labels = train_labels.astype(str)",
"_____no_output_____"
],
[
"dm = DatasetManager()\n\ntest_data_generator = dm.load_dataset('lfw', split='train')\n\nclass_names = dm.get_class_names()\nprint(class_names)",
"\u001b[1mDownloading and preparing dataset lfw/0.1.0 (download: 172.20 MiB, generated: Unknown size, total: 172.20 MiB) to /root/tensorflow_datasets/lfw/0.1.0...\u001b[0m\n"
]
],
[
[
"# Create label dictionary",
"_____no_output_____"
]
],
[
[
"unique_labels = np.unique(train_labels)\nprint(len(unique_labels))",
"5749\n"
],
[
"label_dictionary = {la:[] for la in unique_labels}\n\nfor i in range(len(train_labels)):\n la = train_labels[i]\n\n label_dictionary[la].append(i)",
"_____no_output_____"
]
],
[
[
"# Weight Imprinting models on train data embeddings",
"_____no_output_____"
],
[
"## Function definitions",
"_____no_output_____"
]
],
[
[
"def start_progress_bar(bar_len):\n widgets = [\n ' [', \n progressbar.Timer(format= 'elapsed time: %(elapsed)s'), \n '] ', \n progressbar.Bar('*'),' (', \n progressbar.ETA(), ') ', \n ]\n pbar = progressbar.ProgressBar(\n max_value=bar_len, widgets=widgets\n ).start()\n\n return pbar",
"_____no_output_____"
],
[
"def prepare_indices(\n num_ways,\n num_shot,\n num_eval,\n num_episodes,\n label_dictionary,\n labels,\n shuffle=False\n):\n eval_indices = []\n train_indices = []\n wi_y = []\n eval_y = []\n\n label_dictionary = {la:label_dictionary[la] for la in label_dictionary if len(label_dictionary[la]) >= (num_shot+num_eval)}\n unique_labels = list(label_dictionary.keys())\n\n pbar = start_progress_bar(num_episodes)\n\n for s in range(num_episodes):\n # Setting random seed for replicability\n np.random.seed(s)\n\n _train_indices = []\n _eval_indices = []\n\n selected_labels = np.random.choice(unique_labels, size=num_ways, replace=False)\n for la in selected_labels:\n la_indices = label_dictionary[la]\n select = np.random.choice(la_indices, size = num_shot+num_eval, replace=False)\n tr_idx = list(select[:num_shot])\n ev_idx = list(select[num_shot:])\n\n _train_indices = _train_indices + tr_idx\n _eval_indices = _eval_indices + ev_idx\n\n if shuffle:\n np.random.shuffle(_train_indices)\n np.random.shuffle(_eval_indices)\n\n train_indices.append(_train_indices)\n eval_indices.append(_eval_indices)\n\n _wi_y = labels[_train_indices]\n _eval_y = labels[_eval_indices]\n\n wi_y.append(_wi_y)\n eval_y.append(_eval_y)\n\n pbar.update(s+1)\n \n return train_indices, eval_indices, wi_y, eval_y",
"_____no_output_____"
],
[
"def embed_images(\n embedding_model, \n train_indices, \n num_augmentations,\n trivial=False\n ):\n\n def augment_image(image, num_augmentations, trivial):\n \"\"\" Perform SimCLR augmentations on the image\n \"\"\"\n\n if np.max(image) > 1:\n image = image/255\n\n augmented_images = [image]\n\n def _run_filters(image):\n width = image.shape[1]\n height = image.shape[0]\n image_aug = simclr_data_augmentations.random_crop_with_resize(\n image,\n height,\n width\n )\n image_aug = tf.image.random_flip_left_right(image_aug)\n image_aug = simclr_data_augmentations.random_color_jitter(image_aug)\n image_aug = simclr_data_augmentations.random_blur(\n image_aug,\n height,\n width\n )\n image_aug = tf.reshape(image_aug, [image.shape[0], image.shape[1], 3])\n image_aug = tf.clip_by_value(image_aug, 0., 1.)\n\n return image_aug.numpy()\n\n for _ in range(num_augmentations):\n if trivial:\n aug_image = image\n else:\n aug_image = _run_filters(image)\n augmented_images.append(aug_image)\n\n augmented_images = np.stack(augmented_images)\n return augmented_images\n\n embedding_model.load_model()\n\n unique_indices = np.unique(np.array(train_indices))\n\n ds = dm.load_dataset('lfw', split='train')\n embeddings = []\n IMAGE_IDX = 'image'\n pbar = start_progress_bar(unique_indices.size+1)\n num_done=0\n for idx, item in enumerate(ds):\n if idx in unique_indices:\n image = item[IMAGE_IDX]\n if num_augmentations > 0:\n aug_images = augment_image(image, num_augmentations, trivial)\n else:\n aug_images = image\n \n processed_images = embedding_model.preprocess_data(aug_images)\n embedding = embedding_model.embed_images(processed_images)\n embeddings.append(embedding)\n \n num_done += 1\n pbar.update(num_done+1)\n\n if idx == unique_indices[-1]:\n break\n\n embeddings = np.stack(embeddings)\n\n return unique_indices, embeddings",
"_____no_output_____"
],
[
"def train_model_for_episode(\n indices_and_embeddings,\n train_indices,\n wi_y,\n num_augmentations,\n train_epochs=None,\n train_batch_size=5,\n multi_label=True\n):\n\n train_embeddings = []\n train_labels = []\n ind = indices_and_embeddings[0]\n emb = indices_and_embeddings[1]\n\n for idx, tr_idx in enumerate(train_indices):\n train_embeddings.append(emb[np.argwhere(ind==tr_idx)[0][0]])\n train_labels += [wi_y[idx] for _ in range(num_augmentations+1)]\n train_embeddings = np.concatenate(train_embeddings)\n train_labels = np.array(train_labels)\n\n train_embeddings = WeightImprintingClassifier.preprocess_input(train_embeddings)\n\n wi_weights, label_mapping = WeightImprintingClassifier.get_imprinting_weights(\n train_embeddings, train_labels, False, multi_label\n )\n\n wi_parameters = {\n \"num_classes\": num_ways,\n \"input_dims\": train_embeddings.shape[-1],\n \"scale\": False,\n \"dense_layer_weights\": wi_weights,\n \"multi_label\": multi_label\n }\n\n wi_cls = WeightImprintingClassifier(wi_parameters)\n\n if train_epochs:\n # ep_y = train_labels\n rev_label_mapping = {label_mapping[val]:val for val in label_mapping}\n train_y = np.zeros((len(train_labels), num_ways))\n for idx_y, l in enumerate(train_labels):\n if multi_label:\n for _l in l:\n train_y[idx_y, rev_label_mapping[_l]] = 1\n else:\n train_y[idx_y, rev_label_mapping[l]] = 1\n\n wi_cls.train(train_embeddings, train_y, train_epochs, train_batch_size)\n\n return wi_cls, label_mapping",
"_____no_output_____"
],
[
"def evaluate_model_for_episode(\n model,\n eval_x,\n eval_y,\n label_mapping,\n metrics=['hamming', 'jaccard', 'subset_accuracy', 'ap', 'map', 'c_f1', 'o_f1', 'c_precision', 'o_precision', 'c_recall', 'o_recall', 'top1_accuracy', 'top5_accuracy', 'classwise_accuracy', 'c_accuracy'],\n threshold=0.7,\n multi_label=True\n):\n eval_x = WeightImprintingClassifier.preprocess_input(eval_x)\n logits = model.predict_scores(eval_x).tolist()\n\n if multi_label:\n pred_y = model.predict_multi_label(eval_x, threshold)\n pred_y = [[label_mapping[v] for v in l] for l in pred_y]\n\n met = model.evaluate_multi_label_metrics(\n eval_x, eval_y, label_mapping, threshold, metrics\n )\n else:\n pred_y = model.predict_single_label(eval_x)\n pred_y = [label_mapping[l] for l in pred_y]\n\n met = model.evaluate_single_label_metrics(\n eval_x, eval_y, label_mapping, metrics\n )\n return pred_y, met, logits",
"_____no_output_____"
],
[
"def run_episode_through_model(\n indices_and_embeddings,\n train_indices, \n eval_indices, \n wi_y, \n eval_y,\n thresholds=None,\n num_augmentations=0,\n train_epochs=None,\n train_batch_size=5,\n metrics=['hamming', 'jaccard', 'subset_accuracy', 'ap', 'map', 'c_f1', 'o_f1', 'c_precision', 'o_precision', 'c_recall', 'o_recall', 'top1_accuracy', 'top5_accuracy', 'classwise_accuracy', 'c_accuracy'],\n embeddings=None,\n multi_label=True\n):\n metrics_values = {m:[] for m in metrics}\n\n wi_cls, label_mapping = train_model_for_episode(\n indices_and_embeddings,\n train_indices,\n wi_y,\n num_augmentations,\n train_epochs,\n train_batch_size,\n multi_label=multi_label\n )\n\n eval_x = embeddings[eval_indices]\n ep_logits = []\n\n if multi_label:\n for t in thresholds:\n pred_labels, met, logits = evaluate_model_for_episode(\n wi_cls,\n eval_x,\n eval_y,\n label_mapping,\n threshold=t,\n metrics=metrics,\n multi_label=True\n )\n ep_logits.append(logits)\n for m in metrics:\n metrics_values[m].append(met[m])\n else:\n pred_labels, metrics_values, logits = evaluate_model_for_episode(\n wi_cls,\n eval_x,\n eval_y,\n label_mapping,\n metrics=metrics,\n multi_label=False\n )\n ep_logits = logits\n return metrics_values, ep_logits",
"_____no_output_____"
],
[
"def run_evaluations(\n indices_and_embeddings,\n train_indices, \n eval_indices, \n wi_y, \n eval_y, \n num_episodes, \n num_ways,\n thresholds,\n verbose=True,\n normalize=True,\n train_epochs=None,\n train_batch_size=5,\n metrics=['hamming', 'jaccard', 'subset_accuracy', 'ap', 'map', 'c_f1', 'o_f1', 'c_precision', 'o_precision', 'c_recall', 'o_recall', 'top1_accuracy', 'top5_accuracy', 'classwise_accuracy', 'c_accuracy'],\n embeddings=None,\n num_augmentations=0,\n multi_label=True\n):\n metrics_values = {m:[] for m in metrics}\n\n all_logits = []\n\n if verbose:\n pbar = start_progress_bar(num_episodes)\n\n for idx_ep in range(num_episodes):\n _train_indices = train_indices[idx_ep]\n _eval_indices = eval_indices[idx_ep]\n if multi_label:\n _wi_y = [[label] for label in wi_y[idx_ep]]\n _eval_y = [[label] for label in eval_y[idx_ep]]\n else:\n _wi_y = wi_y[idx_ep]\n _eval_y = eval_y[idx_ep]\n\n met, ep_logits = run_episode_through_model(\n indices_and_embeddings,\n _train_indices, \n _eval_indices, \n _wi_y, \n _eval_y,\n num_augmentations=num_augmentations,\n train_epochs=train_epochs,\n train_batch_size=train_batch_size,\n embeddings=embeddings,\n thresholds=thresholds,\n metrics=metrics,\n multi_label=multi_label\n )\n\n all_logits.append(ep_logits)\n\n for m in metrics:\n metrics_values[m].append(met[m])\n\n if verbose:\n pbar.update(idx_ep+1)\n return metrics_values, all_logits",
"_____no_output_____"
],
[
"def get_max_mean_jaccard_index_by_threshold(metrics_thresholds):\n max_mean_jaccard = np.max([np.mean(mt['jaccard']) for mt in metrics_thresholds])\n return max_mean_jaccard",
"_____no_output_____"
],
[
"def get_max_mean_jaccard_index_with_threshold(metrics_thresholds):\n arr = np.array(metrics_thresholds['jaccard'])\n max_mean_jaccard = np.max(np.mean(arr, 0))\n threshold = np.argmax(np.mean(arr, 0))\n return max_mean_jaccard, threshold\n\ndef get_max_mean_f1_score_with_threshold(metrics_thresholds):\n arr = np.array(metrics_thresholds['f1_score'])\n max_mean_jaccard = np.max(np.mean(arr, 0))\n threshold = np.argmax(np.mean(arr, 0))\n return max_mean_jaccard, threshold",
"_____no_output_____"
],
[
"def get_mean_max_jaccard_index_by_episode(metrics_thresholds):\n mean_max_jaccard = np.mean(np.max(np.array([mt['jaccard'] for mt in metrics_thresholds]), axis=0))\n return mean_max_jaccard",
"_____no_output_____"
],
[
"def plot_metrics_by_threshold(\n metrics_thresholds, \n thresholds, \n metrics=['hamming', 'jaccard', 'subset_accuracy', 'ap', 'map', 'c_f1', 'o_f1', 'c_precision', 'o_precision', 'c_recall', 'o_recall', 'top1_accuracy', 'top5_accuracy', 'classwise_accuracy', 'c_accuracy'],\n title_suffix=\"\"\n):\n legend = []\n\n fig = plt.figure(figsize=(10,10))\n if 'jaccard' in metrics:\n mean_jaccard_threshold = np.mean(np.array(metrics_thresholds['jaccard']), axis=0)\n opt_threshold_jaccard = thresholds[np.argmax(mean_jaccard_threshold)]\n plt.plot(thresholds, mean_jaccard_threshold, c='blue')\n plt.axvline(opt_threshold_jaccard, ls=\"--\", c='blue')\n legend.append(\"Jaccard Index\")\n legend.append(opt_threshold_jaccard)\n if 'hamming' in metrics:\n mean_hamming_threshold = np.mean(np.array(metrics_thresholds['hamming']), axis=0)\n opt_threshold_hamming = thresholds[np.argmin(mean_hamming_threshold)]\n plt.plot(thresholds, mean_hamming_threshold, c='green')\n plt.axvline(opt_threshold_hamming, ls=\"--\", c='green')\n legend.append(\"Hamming Score\")\n legend.append(opt_threshold_hamming)\n if 'map' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['map']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='red')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='red')\n legend.append(\"mAP\")\n legend.append(opt_threshold_f1_score)\n if 'o_f1' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['o_f1']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='yellow')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='yellow')\n legend.append(\"OF1\")\n legend.append(opt_threshold_f1_score)\n if 'c_f1' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['c_f1']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='orange')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='orange')\n legend.append(\"CF1\")\n legend.append(opt_threshold_f1_score)\n if 'o_precision' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['o_precision']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='purple')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='purple')\n legend.append(\"OP\")\n legend.append(opt_threshold_f1_score)\n if 'c_precision' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['c_precision']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='cyan')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='cyan')\n legend.append(\"CP\")\n legend.append(opt_threshold_f1_score)\n if 'o_recall' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['o_recall']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='brown')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='brown')\n legend.append(\"OR\")\n legend.append(opt_threshold_f1_score)\n if 'c_recall' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['c_recall']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='pink')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='pink')\n legend.append(\"CR\")\n legend.append(opt_threshold_f1_score)\n if 'c_accuracy' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['c_accuracy']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='maroon')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='maroon')\n legend.append(\"CACC\")\n legend.append(opt_threshold_f1_score)\n if 'top1_accuracy' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['top1_accuracy']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='magenta')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='magenta')\n legend.append(\"TOP1\")\n legend.append(opt_threshold_f1_score)\n if 'top5_accuracy' in metrics:\n mean_f1_score_threshold = np.mean(np.array(metrics_thresholds['top5_accuracy']), axis=0)\n opt_threshold_f1_score = thresholds[np.argmax(mean_f1_score_threshold)]\n plt.plot(thresholds, mean_f1_score_threshold, c='slategray')\n plt.axvline(opt_threshold_f1_score, ls=\"--\", c='slategray')\n legend.append(\"TOP5\")\n legend.append(opt_threshold_f1_score)\n \n plt.xlabel('Threshold')\n plt.ylabel('Value')\n plt.legend(legend)\n title = title_suffix+\"\\nMulti label metrics by threshold\"\n plt.title(title)\n plt.grid()\n\n fname = os.path.join(PLOT_DIR, title_suffix)\n plt.savefig(fname)\n \n plt.show()\n ",
"_____no_output_____"
]
],
[
[
"## Setting multiple thresholds",
"_____no_output_____"
]
],
[
[
"# No threshold for softmax\nthresholds = None",
"_____no_output_____"
]
],
[
[
"# Main",
"_____no_output_____"
],
[
"## Picking indices",
"_____no_output_____"
]
],
[
[
"train_indices, eval_indices, wi_y, eval_y = prepare_indices(\n num_ways, num_shot, num_eval, num_episodes, label_dictionary, train_labels, shuffle\n)",
"\r \r\r [elapsed time: 0:00:00] | | (ETA: --:--:--) "
],
[
"indices, embeddings = embed_images(\n embedding_model, \n train_indices, \n num_augmentations,\n trivial=trivial\n )",
"100%|███████████████████████████████████████| 354M/354M [00:05<00:00, 69.6MiB/s]\n [elapsed time: 0:01:27] |**********************************| (ETA: 00:00:00) "
]
],
[
[
"## CLIP",
"_____no_output_____"
]
],
[
[
"clip_embeddings_train_fn = \"clip\" + train_embeddings_filename_suffix\nclip_embeddings_train = get_ndarray_from_drive(drive, folderid, clip_embeddings_train_fn)",
"Downloading clip_embeddings_train.npz from GDrive\n"
],
[
"import warnings\n\nwarnings.filterwarnings('ignore')\n\nif train_epochs_arr == [0]:\n if trivial:\n results_filename = \"new_metrics\"+dataset_name+\"_softmax_0t\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_trivial_metrics_with_logits.json\"\n else:\n results_filename = \"new_metrics\"+dataset_name+\"_softmax_0t\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_metrics_with_logits.json\"\nelse:\n if trivial:\n results_filename = \"new_metrics\"+dataset_name+\"_softmax_\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_trivial_metrics_with_logits.json\"\n else:\n results_filename = \"new_metrics\"+dataset_name+\"_softmax_\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_metrics_with_logits.json\"\n\nauth.authenticate_user()\ngauth = GoogleAuth()\ngauth.credentials = GoogleCredentials.get_application_default()\ndrive = GoogleDrive(gauth)\ndownload_file_by_name(drive, folderid, results_filename)\nif results_filename in os.listdir():\n with open(results_filename, 'r') as f:\n json_loaded = json.load(f)\n clip_metrics_over_train_epochs = json_loaded['metrics']\n logits_over_train_epochs = json_loaded[\"logits\"]\nelse:\n clip_metrics_over_train_epochs = [] \n logits_over_train_epochs = [] \n\nfor idx, train_epochs in enumerate(train_epochs_arr):\n if idx < len(clip_metrics_over_train_epochs):\n continue\n print(train_epochs)\n clip_metrics_thresholds, all_logits = run_evaluations(\n (indices, embeddings),\n train_indices,\n eval_indices,\n wi_y,\n eval_y,\n num_episodes,\n num_ways,\n thresholds,\n train_epochs=train_epochs,\n num_augmentations=num_augmentations,\n embeddings=clip_embeddings_train,\n multi_label=multi_label,\n metrics=metrics_val\n )\n clip_metrics_over_train_epochs.append(clip_metrics_thresholds)\n logits_over_train_epochs.append(all_logits)\n\n fin_list = []\n for a1 in wi_y:\n fin_a1_list = []\n for a2 in a1:\n new_val = a2.decode(\"utf-8\")\n fin_a1_list.append(new_val)\n fin_list.append(fin_a1_list)\n\n with open(results_filename, 'w') as f:\n results = {'metrics': clip_metrics_over_train_epochs,\n \"logits\": logits_over_train_epochs,\n \"true_labels\": fin_list}\n json.dump(results, f)\n auth.authenticate_user()\n gauth = GoogleAuth()\n gauth.credentials = GoogleCredentials.get_application_default()\n drive = GoogleDrive(gauth)\n delete_file_by_name(drive, folderid, results_filename)\n save_to_drive(drive, folderid, results_filename)",
"WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.7/dist-packages/googleapiclient/discovery_cache/file_cache.py\", line 33, in <module>\n from oauth2client.contrib.locked_file import LockedFile\nModuleNotFoundError: No module named 'oauth2client.contrib.locked_file'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.7/dist-packages/googleapiclient/discovery_cache/file_cache.py\", line 37, in <module>\n from oauth2client.locked_file import LockedFile\nModuleNotFoundError: No module named 'oauth2client.locked_file'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.7/dist-packages/googleapiclient/discovery_cache/__init__.py\", line 44, in autodetect\n from . import file_cache\n File \"/usr/local/lib/python3.7/dist-packages/googleapiclient/discovery_cache/file_cache.py\", line 41, in <module>\n \"file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth\"\nImportError: file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth\n [elapsed time: 0:00:00] | | (ETA: --:--:--) "
],
[
"def get_best_metric_and_threshold(mt, metric_name, thresholds, optimal='max'):\n if optimal=='max':\n opt_value = np.max(np.mean(np.array(mt[metric_name]), axis=0))\n opt_threshold = thresholds[np.argmax(np.mean(np.array(mt[metric_name]), axis=0))]\n if optimal=='min':\n opt_value = np.min(np.mean(np.array(mt[metric_name]), axis=0))\n opt_threshold = thresholds[np.argmin(np.mean(np.array(mt[metric_name]), axis=0))]\n\n return opt_value, opt_threshold\n\ndef get_avg_metric(mt, metric_name):\n opt_value = np.mean(np.array(mt[metric_name]), axis=0)\n \n return opt_value",
"_____no_output_____"
],
[
"all_metrics = ['accuracy', 'map', 'c_f1', 'o_f1', 'c_precision', 'o_precision', 'c_recall', 'o_recall', 'top1_accuracy', 'top5_accuracy', 'c_accuracy']\n\nf1_vals = []\nf1_t_vals = []\njaccard_vals = []\njaccard_t_vals = []\n\nfinal_dict = {}\nfor ind_metric in all_metrics:\n vals = []\n t_vals = []\n final_array = []\n for mt in clip_metrics_over_train_epochs:\n ret_val = get_avg_metric(mt,ind_metric)\n vals.append(ret_val)\n\n final_array.append(vals)\n final_dict[ind_metric] = final_array\n\nif train_epochs_arr == [0]:\n if trivial:\n graph_filename = \"new_metrics\"+dataset_name+\"_softmax_0t\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_trivial_metrics_graphs.json\"\n else:\n graph_filename = \"new_metrics\"+dataset_name+\"_softmax_0t\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_metrics_graphs.json\"\nelse:\n if trivial:\n graph_filename = \"new_metrics\"+dataset_name+\"_softmax_\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_trivial_metrics_graphs.json\"\n else:\n graph_filename = \"new_metrics\"+dataset_name+\"_softmax_\"+str(num_ways)+\"w\"+str(num_shot)+\"s\"+str(num_augmentations)+\"a_metrics_graphs.json\"\n\nwith open(graph_filename, 'w') as f:\n json.dump(final_dict, f)\n\nauth.authenticate_user()\ngauth = GoogleAuth()\ngauth.credentials = GoogleCredentials.get_application_default()\ndrive = GoogleDrive(gauth)\ndelete_file_by_name(drive, folderid, graph_filename)\nsave_to_drive(drive, folderid, graph_filename)",
"_____no_output_____"
],
[
"final_dict",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbd67c0d3179f90e40e39c534cdfd9eaa0722f45
| 74,390 |
ipynb
|
Jupyter Notebook
|
Project_ML_STCET/GTZAN_MGD/Keras_reg_30sec_5.ipynb
|
AnirbanPal4341/FinalYear_ML_Project
|
b49427b58cf1df6c380227937605b9d6627b4c9b
|
[
"MIT"
] | null | null | null |
Project_ML_STCET/GTZAN_MGD/Keras_reg_30sec_5.ipynb
|
AnirbanPal4341/FinalYear_ML_Project
|
b49427b58cf1df6c380227937605b9d6627b4c9b
|
[
"MIT"
] | null | null | null |
Project_ML_STCET/GTZAN_MGD/Keras_reg_30sec_5.ipynb
|
AnirbanPal4341/FinalYear_ML_Project
|
b49427b58cf1df6c380227937605b9d6627b4c9b
|
[
"MIT"
] | null | null | null | 65.773652 | 14,036 | 0.641766 |
[
[
[
"import pandas as pd\nimport numpy as np",
"_____no_output_____"
],
[
"data = pd.read_csv('features_30_sec.csv')",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"dataset = data[data['label'].isin(['blues', 'classical', 'jazz', 'metal', 'pop'])].drop(['filename','length'],axis=1)\ndataset.iloc[:, :-15].head()",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler ,MinMaxScaler\nfrom sklearn import preprocessing",
"_____no_output_____"
],
[
"encode = LabelEncoder().fit(dataset.iloc[:,-1])\ny= LabelEncoder().fit_transform(dataset.iloc[:,-1])",
"_____no_output_____"
],
[
"scaler1 = MinMaxScaler().fit(np.array(dataset.iloc[:, :-15], dtype = float))\nscaler2 = StandardScaler().fit(np.array(dataset.iloc[:, :-15], dtype = float))\nX = StandardScaler().fit_transform(np.array(dataset.iloc[:, :-15], dtype = float))\nX.shape",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.30,random_state=42)\nprint ('Train set:', X_train.shape, y_train.shape)\nprint ('Test set:', X_test.shape, y_test.shape)",
"Train set: (350, 43) (350,)\nTest set: (150, 43) (150,)\n"
],
[
"import tensorflow.keras as keras",
"_____no_output_____"
],
[
"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout, BatchNormalization",
"_____no_output_____"
],
[
"# defining our regression model \nn_cols = dataset.iloc[:, :-15].shape[1]\ndef regression_model_1():\n # structure of our model\n model = Sequential()\n model.add(Dense(256, activation='relu', input_shape=(n_cols,)))\n model.add(BatchNormalization())\n model.add(Dropout(0.2))\n model.add(Dense(128, activation='relu'))\n model.add(BatchNormalization())\n model.add(Dropout(0.2))\n model.add(Dense(64, activation='relu',))\n model.add(BatchNormalization())\n model.add(Dropout(0.2))\n model.add(Dense(32, activation='relu'))\n model.add(BatchNormalization())\n model.add(Dropout(0.2))\n model.add(Dense(5,activation='softmax'))\n \n # compile model\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n return model",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_11 (Dense) (None, 256) 11264 \n_________________________________________________________________\nbatch_normalization_9 (Batch (None, 256) 1024 \n_________________________________________________________________\ndropout_9 (Dropout) (None, 256) 0 \n_________________________________________________________________\ndense_12 (Dense) (None, 128) 32896 \n_________________________________________________________________\nbatch_normalization_10 (Batc (None, 128) 512 \n_________________________________________________________________\ndropout_10 (Dropout) (None, 128) 0 \n_________________________________________________________________\ndense_13 (Dense) (None, 64) 8256 \n_________________________________________________________________\nbatch_normalization_11 (Batc (None, 64) 256 \n_________________________________________________________________\ndropout_11 (Dropout) (None, 64) 0 \n_________________________________________________________________\ndense_14 (Dense) (None, 32) 2080 \n_________________________________________________________________\nbatch_normalization_12 (Batc (None, 32) 128 \n_________________________________________________________________\ndropout_12 (Dropout) (None, 32) 0 \n_________________________________________________________________\ndense_15 (Dense) (None, 5) 165 \n=================================================================\nTotal params: 56,581\nTrainable params: 55,621\nNon-trainable params: 960\n_________________________________________________________________\n"
],
[
"from keras.callbacks import EarlyStopping, ReduceLROnPlateau\nearlystop = EarlyStopping(patience=10)\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', \n patience=10, \n verbose=1, \n )\nCallbacks = [earlystop, learning_rate_reduction]",
"_____no_output_____"
],
[
"#build the model\n# model_1 = regression_model_1()\n\n#fit the model\n# model_1.fit(X_train,y_train, callbacks=Callbacks , validation_data=(X_test,y_test) ,epochs=100,batch_size=150)",
"WARNING:tensorflow:From C:\\Users\\user1\\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.\nWARNING:tensorflow:From C:\\Users\\user1\\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.\nTrain on 350 samples, validate on 150 samples\nEpoch 1/100\n350/350 [==============================] - 1s 4ms/step - loss: 2.0630 - accuracy: 0.2143 - val_loss: 1.5512 - val_accuracy: 0.4067\nEpoch 2/100\n350/350 [==============================] - 0s 94us/step - loss: 1.4828 - accuracy: 0.4457 - val_loss: 1.4632 - val_accuracy: 0.5133\nEpoch 3/100\n350/350 [==============================] - 0s 94us/step - loss: 1.1352 - accuracy: 0.5829 - val_loss: 1.3778 - val_accuracy: 0.5733\nEpoch 4/100\n350/350 [==============================] - 0s 88us/step - loss: 1.0223 - accuracy: 0.6000 - val_loss: 1.3066 - val_accuracy: 0.6467\nEpoch 5/100\n350/350 [==============================] - 0s 94us/step - loss: 0.8530 - accuracy: 0.6914 - val_loss: 1.2449 - val_accuracy: 0.6600\nEpoch 6/100\n350/350 [==============================] - 0s 91us/step - loss: 0.7757 - accuracy: 0.7343 - val_loss: 1.1917 - val_accuracy: 0.7133\nEpoch 7/100\n350/350 [==============================] - 0s 97us/step - loss: 0.7184 - accuracy: 0.7600 - val_loss: 1.1436 - val_accuracy: 0.7400\nEpoch 8/100\n350/350 [==============================] - 0s 100us/step - loss: 0.6350 - accuracy: 0.7943 - val_loss: 1.1005 - val_accuracy: 0.7600\nEpoch 9/100\n350/350 [==============================] - 0s 94us/step - loss: 0.6211 - accuracy: 0.7829 - val_loss: 1.0601 - val_accuracy: 0.7867\nEpoch 10/100\n350/350 [==============================] - 0s 97us/step - loss: 0.5631 - accuracy: 0.8000 - val_loss: 1.0227 - val_accuracy: 0.7800\nEpoch 11/100\n350/350 [==============================] - 0s 91us/step - loss: 0.5404 - accuracy: 0.8200 - val_loss: 0.9885 - val_accuracy: 0.7867\nEpoch 12/100\n350/350 [==============================] - 0s 97us/step - loss: 0.4609 - accuracy: 0.8571 - val_loss: 0.9570 - val_accuracy: 0.7867\nEpoch 13/100\n350/350 [==============================] - 0s 94us/step - loss: 0.4287 - accuracy: 0.8743 - val_loss: 0.9252 - val_accuracy: 0.7933\nEpoch 14/100\n350/350 [==============================] - 0s 103us/step - loss: 0.4282 - accuracy: 0.8657 - val_loss: 0.8964 - val_accuracy: 0.8067\nEpoch 15/100\n350/350 [==============================] - 0s 91us/step - loss: 0.3613 - accuracy: 0.8943 - val_loss: 0.8697 - val_accuracy: 0.8133\nEpoch 16/100\n350/350 [==============================] - 0s 91us/step - loss: 0.3892 - accuracy: 0.8886 - val_loss: 0.8434 - val_accuracy: 0.8133\nEpoch 17/100\n350/350 [==============================] - 0s 97us/step - loss: 0.3527 - accuracy: 0.8800 - val_loss: 0.8171 - val_accuracy: 0.8267\nEpoch 18/100\n350/350 [==============================] - 0s 85us/step - loss: 0.3385 - accuracy: 0.9086 - val_loss: 0.7902 - val_accuracy: 0.8333\nEpoch 19/100\n350/350 [==============================] - 0s 100us/step - loss: 0.3053 - accuracy: 0.9143 - val_loss: 0.7670 - val_accuracy: 0.8333\nEpoch 20/100\n350/350 [==============================] - 0s 108us/step - loss: 0.2928 - accuracy: 0.9143 - val_loss: 0.7451 - val_accuracy: 0.8400\nEpoch 21/100\n350/350 [==============================] - 0s 103us/step - loss: 0.2888 - accuracy: 0.9200 - val_loss: 0.7217 - val_accuracy: 0.8400\nEpoch 22/100\n350/350 [==============================] - 0s 111us/step - loss: 0.2947 - accuracy: 0.9057 - val_loss: 0.7008 - val_accuracy: 0.8400\nEpoch 23/100\n350/350 [==============================] - 0s 105us/step - loss: 0.2740 - accuracy: 0.9257 - val_loss: 0.6795 - val_accuracy: 0.8400\nEpoch 24/100\n350/350 [==============================] - 0s 100us/step - loss: 0.2711 - accuracy: 0.9029 - val_loss: 0.6588 - val_accuracy: 0.8400\nEpoch 25/100\n350/350 [==============================] - 0s 105us/step - loss: 0.2654 - accuracy: 0.9257 - val_loss: 0.6407 - val_accuracy: 0.8467\nEpoch 26/100\n350/350 [==============================] - 0s 97us/step - loss: 0.2448 - accuracy: 0.9286 - val_loss: 0.6200 - val_accuracy: 0.8533\nEpoch 27/100\n350/350 [==============================] - 0s 105us/step - loss: 0.2159 - accuracy: 0.9429 - val_loss: 0.5993 - val_accuracy: 0.8467\nEpoch 28/100\n350/350 [==============================] - 0s 100us/step - loss: 0.2314 - accuracy: 0.9343 - val_loss: 0.5798 - val_accuracy: 0.8533\nEpoch 29/100\n350/350 [==============================] - 0s 111us/step - loss: 0.2088 - accuracy: 0.9400 - val_loss: 0.5601 - val_accuracy: 0.8600\nEpoch 30/100\n350/350 [==============================] - 0s 105us/step - loss: 0.1829 - accuracy: 0.9629 - val_loss: 0.5412 - val_accuracy: 0.8733\nEpoch 31/100\n350/350 [==============================] - 0s 105us/step - loss: 0.1772 - accuracy: 0.9543 - val_loss: 0.5228 - val_accuracy: 0.8800\nEpoch 32/100\n350/350 [==============================] - 0s 97us/step - loss: 0.1878 - accuracy: 0.9514 - val_loss: 0.5060 - val_accuracy: 0.8867\nEpoch 33/100\n350/350 [==============================] - 0s 120us/step - loss: 0.1869 - accuracy: 0.9486 - val_loss: 0.4894 - val_accuracy: 0.8933\nEpoch 34/100\n350/350 [==============================] - 0s 97us/step - loss: 0.1669 - accuracy: 0.9600 - val_loss: 0.4745 - val_accuracy: 0.8933\nEpoch 35/100\n350/350 [==============================] - 0s 83us/step - loss: 0.1510 - accuracy: 0.9714 - val_loss: 0.4629 - val_accuracy: 0.8867\nEpoch 36/100\n350/350 [==============================] - 0s 83us/step - loss: 0.1919 - accuracy: 0.9486 - val_loss: 0.4529 - val_accuracy: 0.8867\nEpoch 37/100\n350/350 [==============================] - 0s 83us/step - loss: 0.1500 - accuracy: 0.9657 - val_loss: 0.4442 - val_accuracy: 0.8867\nEpoch 38/100\n350/350 [==============================] - 0s 91us/step - loss: 0.1499 - accuracy: 0.9629 - val_loss: 0.4343 - val_accuracy: 0.8800\nEpoch 39/100\n350/350 [==============================] - 0s 91us/step - loss: 0.1365 - accuracy: 0.9657 - val_loss: 0.4257 - val_accuracy: 0.8800\nEpoch 40/100\n350/350 [==============================] - 0s 83us/step - loss: 0.1491 - accuracy: 0.9686 - val_loss: 0.4170 - val_accuracy: 0.8800\nEpoch 41/100\n350/350 [==============================] - 0s 85us/step - loss: 0.1329 - accuracy: 0.9629 - val_loss: 0.4086 - val_accuracy: 0.8933\nEpoch 42/100\n350/350 [==============================] - 0s 88us/step - loss: 0.1228 - accuracy: 0.9686 - val_loss: 0.4016 - val_accuracy: 0.8867\nEpoch 43/100\n350/350 [==============================] - 0s 85us/step - loss: 0.1254 - accuracy: 0.9714 - val_loss: 0.3951 - val_accuracy: 0.8800\n\nEpoch 00043: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.\nEpoch 44/100\n350/350 [==============================] - 0s 113us/step - loss: 0.1174 - accuracy: 0.9800 - val_loss: 0.3911 - val_accuracy: 0.8800\nEpoch 45/100\n350/350 [==============================] - 0s 94us/step - loss: 0.1224 - accuracy: 0.9771 - val_loss: 0.3879 - val_accuracy: 0.8867\nEpoch 46/100\n350/350 [==============================] - 0s 97us/step - loss: 0.1156 - accuracy: 0.9657 - val_loss: 0.3841 - val_accuracy: 0.8867\nEpoch 47/100\n350/350 [==============================] - 0s 83us/step - loss: 0.1024 - accuracy: 0.9771 - val_loss: 0.3802 - val_accuracy: 0.8867\nEpoch 48/100\n350/350 [==============================] - 0s 94us/step - loss: 0.1096 - accuracy: 0.9800 - val_loss: 0.3760 - val_accuracy: 0.8867\nEpoch 49/100\n350/350 [==============================] - 0s 85us/step - loss: 0.1202 - accuracy: 0.9714 - val_loss: 0.3720 - val_accuracy: 0.8867\nEpoch 50/100\n350/350 [==============================] - 0s 85us/step - loss: 0.1323 - accuracy: 0.9714 - val_loss: 0.3684 - val_accuracy: 0.8800\nEpoch 51/100\n350/350 [==============================] - 0s 91us/step - loss: 0.1218 - accuracy: 0.9743 - val_loss: 0.3655 - val_accuracy: 0.8800\nEpoch 52/100\n350/350 [==============================] - 0s 94us/step - loss: 0.1151 - accuracy: 0.9743 - val_loss: 0.3617 - val_accuracy: 0.8800\n"
],
[
"# model_1.save('Keras_reg_30sec_5.h5')",
"_____no_output_____"
],
[
"from keras.models import load_model\nmodel = load_model('Keras_reg_30sec_5.h5')\npredictions = model.predict_classes(X_test)\nscore = model.evaluate(X_test,y_test, verbose=0)\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], score[1]*100))",
"accuracy: 88.00%\n"
],
[
"print(y_test)\nprint(predictions)",
"[3 0 3 1 1 3 3 1 0 4 0 1 4 0 3 3 4 0 3 4 4 4 2 3 0 4 4 2 1 3 4 3 4 1 0 3 4\n 0 2 0 3 0 4 1 0 0 0 0 4 0 0 1 1 4 1 0 1 0 2 0 4 2 3 4 0 0 4 0 2 3 3 3 2 2\n 3 3 2 0 4 4 1 0 4 1 3 0 1 4 3 2 3 4 3 3 4 3 0 0 4 0 2 4 0 3 3 0 3 2 3 1 1\n 4 3 0 4 2 2 2 1 0 2 1 3 1 2 2 4 2 1 3 0 1 4 2 1 0 1 0 0 2 0 2 4 0 2 2 0 2\n 2 4]\n[3 0 3 1 1 3 3 1 0 4 0 1 2 0 3 0 4 0 3 4 4 4 2 3 0 4 4 2 1 3 4 3 4 1 0 3 4\n 0 1 0 3 2 4 1 0 0 0 0 4 0 0 1 1 4 1 0 2 2 2 0 4 2 3 4 3 0 4 0 2 0 3 3 2 2\n 3 3 2 0 4 4 2 0 4 1 3 0 2 3 3 2 3 4 3 3 4 3 0 0 4 0 0 4 0 0 3 0 3 2 3 1 1\n 4 3 0 4 2 2 2 1 0 2 1 3 1 2 2 4 1 1 3 0 1 4 2 1 0 1 0 0 2 0 0 2 0 2 1 2 2\n 2 4]\n"
],
[
"from sklearn.metrics import confusion_matrix",
"_____no_output_____"
],
[
"cf_matrix = confusion_matrix(y_test,predictions)",
"_____no_output_____"
],
[
"print(cf_matrix)",
"[[35 0 3 1 0]\n [ 0 20 3 0 0]\n [ 2 3 21 0 0]\n [ 3 0 0 28 0]\n [ 0 0 2 1 28]]\n"
],
[
"import seaborn as sns\n%matplotlib inline\nclasses=['blues', 'classical', 'jazz', 'metal', 'pop']\nsns.heatmap(cf_matrix, annot=True , cmap='Blues',xticklabels=classes,yticklabels=classes)",
"_____no_output_____"
],
[
"data_test = pd.read_csv('test_30_sec.csv')\ndataset_test= data_test.drop(['filename','length'],axis=1)\nX__test=scaler2.transform(np.array(dataset_test.iloc[:, :-15], dtype = float))\nactual = encode.transform(dataset_test.iloc[:,-1])\npred = model.predict_classes(X__test)",
"_____no_output_____"
],
[
"# blues[0],classical[1],jazz[2],metal[3],pop[4]\nprint(actual)\nprint(pred)",
"[3 2 4 1 1 0 3 4 4 1 4 4 4 0 4 0 0 2 2 1 3 0 2 3 2 2 4 4 1]\n[3 3 4 1 1 0 3 4 4 1 4 2 4 4 4 0 0 2 2 1 3 2 2 4 2 2 2 4 2]\n"
],
[
"cf_matrix_test = confusion_matrix(actual,pred)\nclasses=['blues', 'classical','jazz', 'metal', 'pop']\nsns.heatmap(cf_matrix_test, annot=True , cmap='Blues',xticklabels=classes,yticklabels=classes)",
"_____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"
]
] |
cbd68308d7531a6e9c6f6a7e0d226170ebff2464
| 2,929 |
ipynb
|
Jupyter Notebook
|
Chapter5_Functions/Functions/args.ipynb
|
kernbeisser/UdemyPythonPro
|
000d5e66031bcc22b2d8f115edfbd5ef0e80d5b9
|
[
"MIT"
] | 4 |
2020-12-28T23:43:35.000Z
|
2022-01-01T18:34:18.000Z
|
Chapter5_Functions/Functions/args.ipynb
|
kernbeisser/UdemyPythonPro
|
000d5e66031bcc22b2d8f115edfbd5ef0e80d5b9
|
[
"MIT"
] | null | null | null |
Chapter5_Functions/Functions/args.ipynb
|
kernbeisser/UdemyPythonPro
|
000d5e66031bcc22b2d8f115edfbd5ef0e80d5b9
|
[
"MIT"
] | 9 |
2020-09-26T19:29:28.000Z
|
2022-02-07T06:41:00.000Z
| 23.813008 | 320 | 0.505975 |
[
[
[
"def my_function(a, b, c=10, d=12, e=13):\n print('a: {}, b: {}, c: {}, d: {}, e:{}'.format(a, b, c, d, e))",
"_____no_output_____"
],
[
"my_function(1, 2)",
"a: 1, b: 2, c: 10, d: 12, e:13\n"
],
[
"# *args: variable number of pos. arguments",
"_____no_output_____"
],
[
"def my_function2(a, b, *args):\n print(*args, type(args))\n print('a: {}, b: {}, args: {}'.format(a, b, args))\n\nmy_function2(1, 2, 3, 4)",
"3 4 <class 'tuple'>\na: 1, b: 2, args: (3, 4)\n"
],
[
"def my_function3(*args):\n print(*args, type(args))\n print('args: {}'.format(args))\n\nmy_function2(1, 2, 3, 4)",
"3 4 <class 'tuple'>\na: 1, b: 2, args: (3, 4)\n"
],
[
"# NORMAL ARGS; *ARGS; DEFAULT ARGS\ndef my_function4(a, *args, b=None):\n print(*args, type(args))\n print('a: {}, b: {}, args: {}'.format(a, b, args))\n\nmy_function4(1, b=2, 3, 4)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd686aee09da543c1108271e6336bb0a5a71a37
| 3,234 |
ipynb
|
Jupyter Notebook
|
Range Function.ipynb
|
himanshu-1205/Python-Tutorial
|
2e7d6d7a42bfc8619effca7d685174a4feeae93b
|
[
"Apache-2.0"
] | 1 |
2020-12-02T07:19:05.000Z
|
2020-12-02T07:19:05.000Z
|
Range Function.ipynb
|
himanshu-1205/Python-Tutorial
|
2e7d6d7a42bfc8619effca7d685174a4feeae93b
|
[
"Apache-2.0"
] | null | null | null |
Range Function.ipynb
|
himanshu-1205/Python-Tutorial
|
2e7d6d7a42bfc8619effca7d685174a4feeae93b
|
[
"Apache-2.0"
] | null | null | null | 18.912281 | 269 | 0.452999 |
[
[
[
"# Range\nIt is an in-built function in Python which returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number. The most common use of range function is to iterate sequence type. It is most commonly used in for and while loops.\n",
"_____no_output_____"
]
],
[
[
"# Syntax\n# range(start, stop, step)",
"_____no_output_____"
],
[
"# Range With For Loop\n\nfor i in range(2,20,2):\n print(i)",
"2\n4\n6\n8\n10\n12\n14\n16\n18\n"
],
[
"# Increment With Positive And Negative Step\n\nfor i in range(2, 20, 5):\n print(i, end=\", \")\nfor j in range(25, 0 , -5):\n print(j , end=\", \")",
"2, 7, 12, 17, 25, 20, 15, 10, 5, "
],
[
"# Concatenating Two Range Functions\n\nfrom itertools import chain \n \nres = chain(range(10) , range(10, 15))\nfor i in res:\n print(i , end=\", \")",
"0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, "
],
[
"# Accessing Range Using Index Values\n\na = range(0,10)[3]\nb = range(0,10)[5]\nprint(a)\nprint(b)",
"3\n5\n"
],
[
"# Converting Range To List\n\na = range(0,10)\nb = list(a)\nc = list(range(0,5))\nprint(b)\nprint(c)",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n[0, 1, 2, 3, 4]\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd68c55f87cbb528297e82df18be5808bb4d623
| 178,871 |
ipynb
|
Jupyter Notebook
|
Training_LDA.ipynb
|
datascisteven/NYCODW-STEW-MAP-Project
|
5b847e6bdfc86df6abcc9e2139b2dc71a3c6e4b1
|
[
"MIT"
] | null | null | null |
Training_LDA.ipynb
|
datascisteven/NYCODW-STEW-MAP-Project
|
5b847e6bdfc86df6abcc9e2139b2dc71a3c6e4b1
|
[
"MIT"
] | null | null | null |
Training_LDA.ipynb
|
datascisteven/NYCODW-STEW-MAP-Project
|
5b847e6bdfc86df6abcc9e2139b2dc71a3c6e4b1
|
[
"MIT"
] | null | null | null | 111.031037 | 38,514 | 0.60216 |
[
[
[
"## Importing Packages",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport tqdm\nimport pickle\nfrom pprint import pprint\nimport os\n\nimport warnings\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\n\n#sklearn\nfrom sklearn.manifold import TSNE\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.model_selection import train_test_split\n\nimport gensim\nfrom gensim import corpora, models\nfrom gensim.corpora import Dictionary\nfrom gensim.models.coherencemodel import CoherenceModel\nfrom gensim.models.ldamodel import LdaModel\n\n",
"_____no_output_____"
],
[
"! pip install pyLDAvis",
"Collecting pyLDAvis\n Downloading pyLDAvis-3.3.1.tar.gz (1.7 MB)\n\u001b[K |████████████████████████████████| 1.7 MB 3.9 MB/s \n\u001b[?25h Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n Installing backend dependencies ... \u001b[?25l\u001b[?25hdone\n Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\nRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (0.16.0)\nRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (1.1.0)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (2.11.3)\nRequirement already satisfied: numexpr in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (2.8.1)\nCollecting funcy\n Downloading funcy-1.17-py2.py3-none-any.whl (33 kB)\nRequirement already satisfied: sklearn in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (0.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (57.4.0)\nRequirement already satisfied: pandas>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (1.3.5)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (1.4.1)\nRequirement already satisfied: gensim in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (3.6.0)\nRequirement already satisfied: numpy>=1.20.0 in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (1.21.5)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from pyLDAvis) (1.0.2)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.2.0->pyLDAvis) (2.8.2)\nRequirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.2.0->pyLDAvis) (2018.9)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=1.2.0->pyLDAvis) (1.15.0)\nRequirement already satisfied: smart-open>=1.2.1 in /usr/local/lib/python3.7/dist-packages (from gensim->pyLDAvis) (5.2.1)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->pyLDAvis) (2.0.1)\nRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from numexpr->pyLDAvis) (21.3)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->numexpr->pyLDAvis) (3.0.7)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->pyLDAvis) (3.1.0)\nBuilding wheels for collected packages: pyLDAvis\n Building wheel for pyLDAvis (PEP 517) ... \u001b[?25l\u001b[?25hdone\n Created wheel for pyLDAvis: filename=pyLDAvis-3.3.1-py2.py3-none-any.whl size=136898 sha256=949a43551ff78b995340bc3acad21a2cb08f7b3b4005c32b9b03415d74dc9789\n Stored in directory: /root/.cache/pip/wheels/c9/21/f6/17bcf2667e8a68532ba2fbf6d5c72fdf4c7f7d9abfa4852d2f\nSuccessfully built pyLDAvis\nInstalling collected packages: funcy, pyLDAvis\nSuccessfully installed funcy-1.17 pyLDAvis-3.3.1\n"
],
[
"import pyLDAvis\nimport pyLDAvis.sklearn\nimport pyLDAvis.gensim_models as gensimvis",
"_____no_output_____"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
],
[
"with open('processed_tweets.pickle', 'rb') as read_file:\n df = pickle.load(read_file)",
"_____no_output_____"
]
],
[
[
"## Train-Test Split",
"_____no_output_____"
]
],
[
[
"X_train, X_test = train_test_split(df.tweet, test_size=0.2, random_state=42)\nX_train",
"_____no_output_____"
],
[
"X_test",
"_____no_output_____"
],
[
"train_list_of_lists = list(X_train.values)",
"_____no_output_____"
]
],
[
[
"## Bigram-Trigram Models\n\n(I did not incorporate bigrams and trigrams into the model yet)",
"_____no_output_____"
]
],
[
[
"# Build the bigram and trigram models\nbigram = gensim.models.Phrases(train_list_of_lists, min_count=5, threshold=100) # higher threshold fewer phrases.\ntrigram = gensim.models.Phrases(bigram[train_list_of_lists], threshold=100)\n# Faster way to get a sentence clubbed as a trigram/bigram\nbigram_mod = gensim.models.phrases.Phraser(bigram)\ntrigram_mod = gensim.models.phrases.Phraser(trigram)",
"_____no_output_____"
],
[
"def make_bigrams(texts):\n return [bigram_mod[doc] for doc in texts]",
"_____no_output_____"
],
[
"data_words_bigrams = make_bigrams(train_list_of_lists)",
"_____no_output_____"
]
],
[
[
"## Bag of Words",
"_____no_output_____"
]
],
[
[
"id2word = Dictionary(train_list_of_lists)\ncorpus = [id2word.doc2bow(text) for text in train_list_of_lists]",
"_____no_output_____"
],
[
"sample = corpus[3000]\n\nfor i in range(len(sample)):\n print(\"Word {} (\\\"{}\\\") appears {} time(s).\".format(sample[i][0], \n id2word[sample[i][0]], \n sample[i][1]))",
"Word 173 (\"class\") appears 1 time(s).\nWord 572 (\"get_repost\") appears 1 time(s).\nWord 660 (\"wine\") appears 1 time(s).\nWord 692 (\"january\") appears 1 time(s).\nWord 715 (\"pizza\") appears 1 time(s).\nWord 732 (\"february\") appears 1 time(s).\nWord 833 (\"thursday\") appears 2 time(s).\nWord 1022 (\"month\") appears 1 time(s).\nWord 1091 (\"dd\") appears 1 time(s).\nWord 3509 (\"pair\") appears 2 time(s).\n"
]
],
[
[
"## LDA with Bag of Words",
"_____no_output_____"
]
],
[
[
"# Build LDA model\nlda_model = LdaModel(corpus=corpus,\n id2word=id2word,\n num_topics=4, \n random_state=42,\n chunksize=100,\n passes=100,\n update_every=5,\n alpha='auto',\n per_word_topics=True)\n\npprint(lda_model.print_topics())\ndoc_lda = lda_model[corpus]\n",
"[(0,\n '0.019*\"water\" + 0.010*\"river\" + 0.008*\"protect\" + 0.008*\"new\" + '\n '0.008*\"clean\" + 0.006*\"state\" + 0.006*\"hudson\" + 0.006*\"environmental\" + '\n '0.006*\"society\" + 0.006*\"littoral\"'),\n (1,\n '0.014*\"us\" + 0.011*\"new\" + 0.011*\"thank\" + 0.010*\"join\" + 0.009*\"today\" + '\n '0.009*\"get\" + 0.008*\"day\" + 0.008*\"make\" + 0.008*\"help\" + 0.008*\"learn\"'),\n (2,\n '0.025*\"park\" + 0.016*\"brooklyn\" + 0.012*\"st\" + 0.010*\"come\" + '\n '0.009*\"get_repost\" + 0.008*\"slope\" + 0.008*\"good\" + 0.008*\"corner\" + '\n '0.007*\"amaze\" + 0.007*\"house\"'),\n (3,\n '0.011*\"high\" + 0.010*\"line\" + 0.009*\"june\" + 0.008*\"friday\" + '\n '0.008*\"ticket\" + 0.007*\"april\" + 0.006*\"bio\" + 0.006*\"business\" + '\n '0.006*\"update\" + 0.006*\"staff\"')]\n"
],
[
"pyLDAvis.enable_notebook()\nLDAvis_prepared = gensimvis.prepare(lda_model, corpus, id2word)\nLDAvis_prepared",
"_____no_output_____"
],
[
"# Compute Coherence Score\ncoherence_model_lda = CoherenceModel(model=lda_model, texts=train_list_of_lists, dictionary=id2word, coherence='c_v')\ncoherence_lda = coherence_model_lda.get_coherence()\nprint('Coherence Score: ', coherence_lda)",
"Coherence Score: 0.2907941943446717\n"
],
[
"lda_model_bow = gensim.models.LdaMulticore(corpus, num_topics=4, id2word=id2word, passes=100, workers=2)\n\nfor idx, topic in lda_model_bow.print_topics(-1):\n print('Topic: {} \\nWords: {}'.format(idx, topic))",
"Topic: 0 \nWords: 0.009*\"park\" + 0.008*\"brooklyn\" + 0.008*\"open\" + 0.008*\"st\" + 0.007*\"come\" + 0.007*\"order\" + 0.007*\"get\" + 0.007*\"us\" + 0.006*\"day\" + 0.005*\"today\"\nTopic: 1 \nWords: 0.012*\"thank\" + 0.011*\"us\" + 0.010*\"community\" + 0.009*\"new\" + 0.009*\"learn\" + 0.007*\"help\" + 0.007*\"support\" + 0.007*\"program\" + 0.006*\"make\" + 0.006*\"please\"\nTopic: 2 \nWords: 0.008*\"gowanus\" + 0.008*\"get\" + 0.007*\"park\" + 0.006*\"join\" + 0.006*\"one\" + 0.005*\"link\" + 0.005*\"small\" + 0.005*\"bio\" + 0.005*\"today\" + 0.005*\"support\"\nTopic: 3 \nWords: 0.013*\"water\" + 0.011*\"new\" + 0.008*\"river\" + 0.006*\"protect\" + 0.005*\"clean\" + 0.005*\"join\" + 0.005*\"state\" + 0.004*\"change\" + 0.004*\"littoral\" + 0.004*\"hudson\"\n"
],
[
"LDAvis_prepared_2 = gensimvis.prepare(lda_model_bow, corpus, id2word)\nLDAvis_prepared_2",
"_____no_output_____"
],
[
"for index, score in sorted(lda_model_bow[corpus[3000]], key=lambda tup: -1*tup[1]):\n print(\"\\nScore: {}\\t \\nTopic: {}\".format(score, lda_model_bow.print_topic(index, 4)))",
"\nScore: 0.49821075797080994\t \nTopic: 0.016*\"park\" + 0.012*\"us\" + 0.012*\"join\" + 0.008*\"thank\"\n\nScore: 0.46301236748695374\t \nTopic: 0.010*\"get\" + 0.009*\"order\" + 0.008*\"open\" + 0.008*\"day\"\n\nScore: 0.019508961588144302\t \nTopic: 0.018*\"new\" + 0.008*\"york\" + 0.008*\"grant\" + 0.006*\"congratulations\"\n\nScore: 0.01926790364086628\t \nTopic: 0.015*\"water\" + 0.008*\"river\" + 0.006*\"new\" + 0.006*\"protect\"\n"
],
[
"# Compute Coherence Score\ncoherence_model_lda_2 = CoherenceModel(model=lda_model_bow, texts=train_list_of_lists, dictionary=id2word, coherence='c_v')\ncoherence_lda_2 = coherence_model_lda_2.get_coherence()\nprint('Coherence Score: ', coherence_lda_2)",
"Coherence Score: 0.2938788565098576\n"
]
],
[
[
"## LDA with TF-IDF",
"_____no_output_____"
]
],
[
[
"tfidf = models.TfidfModel(corpus)\ncorpus_tfidf = tfidf[corpus]\n\nfor doc in corpus_tfidf:\n pprint(doc)\n break",
"[(0, 0.42466773753051157),\n (1, 0.1766020120629213),\n (2, 0.23014024341235387),\n (3, 0.2832750364803111),\n (4, 0.2366724011621648),\n (5, 0.2832750364803111),\n (6, 0.18979599067454203),\n (7, 0.2143401059677086),\n (8, 0.24462258623808159),\n (9, 0.33186344059309086),\n (10, 0.29674778220154957),\n (11, 0.19428450256362492),\n (12, 0.19638562074430463),\n (13, 0.24300529787323882),\n (14, 0.2088991128043566)]\n"
],
[
"lda_model_tfidf = gensim.models.LdaMulticore(corpus_tfidf, num_topics=4, id2word=id2word, passes=100, workers=4)\n\nfor idx, topic in lda_model_tfidf.print_topics(-1):\n print('Topic: {} Word: {}'.format(idx, topic))",
"Topic: 0 Word: 0.004*\"st\" + 0.004*\"corner\" + 0.004*\"open\" + 0.003*\"wine\" + 0.003*\"come\" + 0.003*\"get_repost\" + 0.002*\"brooklyn\" + 0.002*\"gowanus\" + 0.002*\"order\" + 0.002*\"union\"\nTopic: 1 Word: 0.003*\"park\" + 0.003*\"post\" + 0.003*\"slope\" + 0.003*\"photo\" + 0.002*\"le\" + 0.002*\"restaurant\" + 0.002*\"see\" + 0.002*\"grill\" + 0.002*\"get\" + 0.002*\"start\"\nTopic: 2 Word: 0.005*\"thank\" + 0.004*\"water\" + 0.004*\"new\" + 0.004*\"join\" + 0.003*\"support\" + 0.003*\"us\" + 0.003*\"learn\" + 0.003*\"community\" + 0.003*\"help\" + 0.003*\"work\"\nTopic: 3 Word: 0.004*\"happy\" + 0.004*\"open\" + 0.004*\"please\" + 0.003*\"get\" + 0.003*\"line\" + 0.003*\"us\" + 0.003*\"day\" + 0.003*\"high\" + 0.003*\"today\" + 0.003*\"park\"\n"
],
[
"LDAvis_prepared_3 = gensimvis.prepare(lda_model_tfidf, corpus_tfidf, id2word)\nLDAvis_prepared_3",
"_____no_output_____"
],
[
"for index, score in sorted(lda_model_tfidf[corpus[3000]], key=lambda tup: -1*tup[1]):\n print(\"\\nScore: {}\\t \\nTopic: {}\".format(score, lda_model_tfidf.print_topic(index, 4)))",
"\nScore: 0.528406023979187\t \nTopic: 0.004*\"order\" + 0.004*\"open\" + 0.004*\"st\" + 0.003*\"delivery\"\n\nScore: 0.4327649474143982\t \nTopic: 0.004*\"park\" + 0.004*\"us\" + 0.004*\"join\" + 0.004*\"today\"\n\nScore: 0.01952865533530712\t \nTopic: 0.005*\"new\" + 0.005*\"water\" + 0.003*\"protect\" + 0.003*\"thank\"\n\nScore: 0.01930043287575245\t \nTopic: 0.004*\"thank\" + 0.002*\"early\" + 0.002*\"khcc\" + 0.002*\"el\"\n"
],
[
"# Compute Coherence Score\ncoherence_model_lda_3 = CoherenceModel(model=lda_model_tfidf, texts=train_list_of_lists, dictionary=id2word, coherence='c_v')\ncoherence_lda_3 = coherence_model_lda_3.get_coherence()\nprint('Coherence Score: ', coherence_lda_3)",
"Coherence Score: 0.30371951254730767\n"
],
[
"# supporting function\ndef compute_coherence_values(corpus, dictionary, k, a, b):\n \n lda_model = gensim.models.LdaMulticore(corpus=corpus,\n id2word=dictionary,\n num_topics=k, \n random_state=42,\n chunksize=100,\n passes=10,\n alpha=a,\n eta=b)\n \n coherence_model_lda = CoherenceModel(model=lda_model, texts=train_list_of_lists, dictionary=id2word, coherence='c_v')\n \n return coherence_model_lda.get_coherence()",
"_____no_output_____"
],
[
"grid = {}\ngrid['Validation_Set'] = {}\n\n# Topics range\nmin_topics = 2\nmax_topics = 11\nstep_size = 1\ntopics_range = range(min_topics, max_topics, step_size)\n\n# Alpha parameter\nalpha = list(np.arange(0.01, 1, 0.1))\nalpha.append('symmetric')\nalpha.append('asymmetric')\n\n# Beta parameter\nbeta = list(np.arange(0.01, 1, 0.1))\nbeta.append('symmetric')\n\n# Validation sets\nnum_of_docs = len(corpus)\ncorpus_sets = [# gensim.utils.ClippedCorpus(corpus, num_of_docs*0.25), \n # gensim.utils.ClippedCorpus(corpus, num_of_docs*0.5), \n gensim.utils.ClippedCorpus(corpus, int(num_of_docs*0.75)), \n corpus]\ncorpus_title = ['75% Corpus', '100% Corpus']\nmodel_results = {'Validation_Set': [],\n 'Topics': [],\n 'Alpha': [],\n 'Beta': [],\n 'Coherence': []\n }\n# Can take a long time to run\nif 1 == 1:\n pbar = tqdm.tqdm(total=540)\n \n # iterate through validation corpuses\n for i in range(len(corpus_sets)):\n # iterate through number of topics\n for k in topics_range:\n # iterate through alpha values\n for a in alpha:\n # iterare through beta values\n for b in beta:\n # get the coherence score for the given parameters\n cv = compute_coherence_values(corpus=corpus_sets[i], dictionary=id2word, \n k=k, a=a, b=b)\n # Save the model results\n model_results['Validation_Set'].append(corpus_title[i])\n model_results['Topics'].append(k)\n model_results['Alpha'].append(a)\n model_results['Beta'].append(b)\n model_results['Coherence'].append(cv)\n \n pbar.update(1)\n pd.DataFrame(model_results).to_csv('lda_tuning_results_2.csv', index=False)\n pbar.close()",
"\n 0%| | 0/540 [00:16<?, ?it/s]\n\n 0%| | 1/540 [01:15<11:20:50, 75.79s/it]\u001b[A\n 0%| | 2/540 [02:33<11:28:21, 76.77s/it]\u001b[A\n 1%| | 3/540 [03:51<11:33:01, 77.43s/it]\u001b[A\n 1%| | 4/540 [05:16<11:58:54, 80.48s/it]\u001b[A\n 1%| | 5/540 [06:44<12:22:58, 83.32s/it]\u001b[A\n 1%| | 6/540 [08:15<12:42:42, 85.70s/it]\u001b[A\n 1%|▏ | 7/540 [09:48<13:03:54, 88.24s/it]\u001b[A\n 1%|▏ | 8/540 [11:25<13:27:43, 91.10s/it]\u001b[A\n 2%|▏ | 9/540 [13:06<13:53:31, 94.18s/it]\u001b[A\n 2%|▏ | 10/540 [14:50<14:16:39, 96.98s/it]\u001b[A\n 2%|▏ | 11/540 [16:24<14:08:12, 96.21s/it]\u001b[A\n 2%|▏ | 12/540 [17:38<13:08:06, 89.56s/it]\u001b[A\n 2%|▏ | 13/540 [18:54<12:28:50, 85.26s/it]\u001b[A\n 3%|▎ | 14/540 [20:11<12:04:57, 82.70s/it]\u001b[A\n 3%|▎ | 15/540 [21:34<12:05:23, 82.90s/it]\u001b[A\n 3%|▎ | 16/540 [23:08<12:34:15, 86.37s/it]\u001b[A\n 3%|▎ | 17/540 [24:38<12:41:53, 87.41s/it]\u001b[A\n 3%|▎ | 18/540 [26:10<12:51:02, 88.63s/it]\u001b[A\n 4%|▎ | 19/540 [27:44<13:04:43, 90.37s/it]\u001b[A\n 4%|▎ | 20/540 [29:19<13:16:06, 91.86s/it]\u001b[A\n 4%|▍ | 21/540 [30:54<13:20:59, 92.60s/it]\u001b[A\n 4%|▍ | 22/540 [32:24<13:12:36, 91.81s/it]\u001b[A\n 4%|▍ | 23/540 [33:37<12:23:52, 86.33s/it]\u001b[A\n 4%|▍ | 24/540 [34:54<11:56:59, 83.37s/it]\u001b[A\n 5%|▍ | 25/540 [36:12<11:42:12, 81.81s/it]\u001b[A\n 5%|▍ | 26/540 [37:38<11:51:23, 83.04s/it]\u001b[A\n 5%|▌ | 27/540 [39:08<12:07:56, 85.14s/it]\u001b[A\n 5%|▌ | 28/540 [40:40<12:25:35, 87.37s/it]\u001b[A\n 5%|▌ | 29/540 [42:15<12:42:02, 89.48s/it]\u001b[A\n 6%|▌ | 30/540 [44:02<13:24:29, 94.65s/it]\u001b[A\n 6%|▌ | 31/540 [45:42<13:36:27, 96.24s/it]\u001b[A\n 6%|▌ | 32/540 [47:19<13:38:14, 96.64s/it]\u001b[A\n 6%|▌ | 33/540 [48:51<13:24:40, 95.23s/it]\u001b[A\n 6%|▋ | 34/540 [50:03<12:24:14, 88.25s/it]\u001b[A\n 6%|▋ | 35/540 [51:26<12:08:53, 86.60s/it]\u001b[A\n 7%|▋ | 36/540 [52:49<11:57:47, 85.45s/it]\u001b[A\n 7%|▋ | 37/540 [54:15<11:57:37, 85.60s/it]\u001b[A\n 7%|▋ | 38/540 [55:47<12:14:30, 87.79s/it]\u001b[A\n 7%|▋ | 39/540 [57:23<12:32:45, 90.15s/it]\u001b[A\n 7%|▋ | 40/540 [59:00<12:49:04, 92.29s/it]\u001b[A\n 8%|▊ | 41/540 [1:00:40<13:06:26, 94.56s/it]\u001b[A\n 8%|▊ | 42/540 [1:02:20<13:18:06, 96.16s/it]\u001b[A\n 8%|▊ | 43/540 [1:04:03<13:34:01, 98.27s/it]\u001b[A\n 8%|▊ | 44/540 [1:05:39<13:26:14, 97.53s/it]\u001b[A\n 8%|▊ | 45/540 [1:06:48<12:13:32, 88.91s/it]\u001b[A\n 9%|▊ | 46/540 [1:08:05<11:43:16, 85.42s/it]\u001b[A\n 9%|▊ | 47/540 [1:09:26<11:30:31, 84.04s/it]\u001b[A\n 9%|▉ | 48/540 [1:10:50<11:28:31, 83.97s/it]\u001b[A\n 9%|▉ | 49/540 [1:12:20<11:43:28, 85.96s/it]\u001b[A\n 9%|▉ | 50/540 [1:13:55<12:02:57, 88.52s/it]\u001b[A\n 9%|▉ | 51/540 [1:15:31<12:20:38, 90.88s/it]\u001b[A\n 10%|▉ | 52/540 [1:17:09<12:36:08, 92.97s/it]\u001b[A\n 10%|▉ | 53/540 [1:18:50<12:54:29, 95.42s/it]\u001b[A\n 10%|█ | 54/540 [1:20:31<13:06:26, 97.09s/it]\u001b[A\n 10%|█ | 55/540 [1:22:03<12:52:09, 95.52s/it]\u001b[A"
],
[
"pd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\npd.set_option('display.max_colwidth', None)",
"_____no_output_____"
],
[
"results = pd.read_csv('lda_tuning_results.csv')\nresults.head(20)",
"_____no_output_____"
],
[
"sorted.tail(1)",
"_____no_output_____"
],
[
"plt.plot(kind='scatter', x='Topics', y='Coherence')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd6ac7714ee4d7032d8dbd57c68cc5edd11fed4
| 6,558 |
ipynb
|
Jupyter Notebook
|
dask-sql/dask-sql.ipynb
|
pavithraes/notebooks
|
efe8cf6f1d0a67daca2acec19e8c3e0ae305f218
|
[
"BSD-3-Clause"
] | 3 |
2020-09-29T22:28:08.000Z
|
2022-02-24T07:58:17.000Z
|
dask-sql/dask-sql.ipynb
|
pavithraes/notebooks
|
efe8cf6f1d0a67daca2acec19e8c3e0ae305f218
|
[
"BSD-3-Clause"
] | 13 |
2020-10-26T02:52:51.000Z
|
2021-12-03T14:10:11.000Z
|
dask-sql/dask-sql.ipynb
|
pavithraes/notebooks
|
efe8cf6f1d0a67daca2acec19e8c3e0ae305f218
|
[
"BSD-3-Clause"
] | 4 |
2021-03-12T00:15:27.000Z
|
2021-06-21T05:50:38.000Z
| 26.877049 | 264 | 0.572278 |
[
[
[
"# Analyzing data with Dask, SQL, and Coiled\n\nIn this notebook, we look at using [Dask-SQL](https://dask-sql.readthedocs.io/en/latest/), an exciting new open-source library which adds a SQL query layer on top of Dask. This allows you to query and transform Dask DataFrames using common SQL operations.\n\n## Launch a cluster\n\nLet's first start by creating a Coiled cluster which uses the `examples/dask-sql` software environment, which has `dask`, `pandas`, `s3fs`, and a few other libraries installed.",
"_____no_output_____"
]
],
[
[
"import coiled\n\ncluster = coiled.Cluster(\n n_workers=10,\n worker_cpu=4,\n worker_memory=\"30GiB\",\n software=\"examples/dask-sql\",\n)\ncluster",
"_____no_output_____"
]
],
[
[
"and then connect Dask to our remote Coiled cluster",
"_____no_output_____"
]
],
[
[
"from dask.distributed import Client\n\nclient = Client(cluster)\nclient.wait_for_workers(10)\nclient",
"_____no_output_____"
]
],
[
[
"## Getting started with Dask-SQL\n\nInternally, Dask-SQL uses a well-established Java library, Apache Calcite, to parse SQL and perform some initial work on your query. To help Dask-SQL locate JVM shared libraries, we set the `JAVA_HOME` environment variable. ",
"_____no_output_____"
]
],
[
[
"import os\n\nos.environ[\"JAVA_HOME\"] = os.environ[\"CONDA_DIR\"]",
"_____no_output_____"
]
],
[
[
"The main interface for interacting with Dask-SQL is the `dask_sql.Context` object. It allows your to register Dask DataFrames as data sources and can convert SQL queries to Dask DataFrame operations.",
"_____no_output_____"
]
],
[
[
"from dask_sql import Context\n\nc = Context()",
"_____no_output_____"
]
],
[
[
"For this notebook, we'll use the NYC taxi dataset, which is publically accessible on AWS S3, as our data source",
"_____no_output_____"
]
],
[
[
"import dask.dataframe as dd\nfrom distributed import wait\n\ndf = dd.read_csv(\n \"s3://nyc-tlc/trip data/yellow_tripdata_2019-*.csv\",\n dtype={\n \"payment_type\": \"UInt8\",\n \"VendorID\": \"UInt8\",\n \"passenger_count\": \"UInt8\",\n \"RatecodeID\": \"UInt8\",\n },\n storage_options={\"anon\": True}\n)\n\n# Load datasest into the cluster's distributed memory.\n# This isn't strictly necessary, but does allow us to\n# avoid repeated running the same I/O operations. \ndf = df.persist()\nwait(df);",
"_____no_output_____"
]
],
[
[
"We can then use our `dask_sql.Context` to assign a table name to this DataFrame, and then use that table name within SQL queries",
"_____no_output_____"
]
],
[
[
"# Registers our Dask DataFrame df as a table with the name \"taxi\"\nc.register_dask_table(df, \"taxi\")\n\n# Perform a SQL operation on the \"taxi\" table\nresult = c.sql(\"SELECT count(1) FROM taxi\")\nresult",
"_____no_output_____"
]
],
[
[
"Note that this returned another Dask DataFrame and no computation has been run yet. This is similar to other Dask DataFrame operations, which are lazily evaluated. We can call `.compute()` to run the computation on our cluster.",
"_____no_output_____"
]
],
[
[
"result.compute()",
"_____no_output_____"
]
],
[
[
"Hooray, we've run our first SQL query with Dask-SQL! Let's try out some more complex queries.\n\n## More complex SQL examples\n\nWith Dask-SQL we can run more complex SQL statements like, for example, a groupby-aggregation:",
"_____no_output_____"
]
],
[
[
"c.sql('SELECT avg(tip_amount) FROM taxi GROUP BY passenger_count').compute()",
"_____no_output_____"
]
],
[
[
"NOTE: that the equivalent operatation using the Dask DataFrame API would be:\n\n```python\ndf.groupby(\"passenger_count\").tip_amount.mean().compute()\n```",
"_____no_output_____"
],
[
"We can even make plots of our SQL query results for near-real-time interactive data exploration and visualization.",
"_____no_output_____"
]
],
[
[
"c.sql(\"\"\"\n SELECT floor(trip_distance) AS dist, avg(fare_amount) as fare\n FROM taxi \n WHERE trip_distance < 50 AND trip_distance >= 0 \n GROUP BY floor(trip_distance)\n\"\"\").compute().plot(x=\"dist\", y=\"fare\");",
"_____no_output_____"
]
],
[
[
"If you would like to learn more about Dask-SQL check out the [Dask-SQL docs](https://dask-sql.readthedocs.io/) or [source code](https://github.com/nils-braun/dask-sql) on GitHub.",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbd6bb722e86bfeab644e97e06e20307cc79ae3e
| 1,373 |
ipynb
|
Jupyter Notebook
|
date/date_test.ipynb
|
gusman/text_processing
|
1e0f841fc590b459768cbe3f9926f9452d957ca3
|
[
"MIT"
] | null | null | null |
date/date_test.ipynb
|
gusman/text_processing
|
1e0f841fc590b459768cbe3f9926f9452d957ca3
|
[
"MIT"
] | null | null | null |
date/date_test.ipynb
|
gusman/text_processing
|
1e0f841fc590b459768cbe3f9926f9452d957ca3
|
[
"MIT"
] | null | null | null | 19.614286 | 140 | 0.525856 |
[
[
[
"from date_tool import dt_search",
"_____no_output_____"
],
[
"text = '2020-03-19 Jumat, 12 Februari 2016 14:57, 13 Februari 2016, january 31, 2020, january 1, 2020, 2020/09/01, 2020\\\\09\\\\02'\n",
"_____no_output_____"
],
[
"dt_search.find_date(text)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
cbd6bf608d9f04618fae980bc87c1ed68fffaa03
| 8,757 |
ipynb
|
Jupyter Notebook
|
Data_PreProcessing.ipynb
|
JonWeber0328/100-Days-Of-ML-Code
|
850db261f6cf13b09907b6fe5858a35859942291
|
[
"MIT"
] | null | null | null |
Data_PreProcessing.ipynb
|
JonWeber0328/100-Days-Of-ML-Code
|
850db261f6cf13b09907b6fe5858a35859942291
|
[
"MIT"
] | null | null | null |
Data_PreProcessing.ipynb
|
JonWeber0328/100-Days-Of-ML-Code
|
850db261f6cf13b09907b6fe5858a35859942291
|
[
"MIT"
] | null | null | null | 23.105541 | 98 | 0.462601 |
[
[
[
"# 100 Days of Machine Learning\nThis code and lesson plan comes from: https://github.com/Avik-Jain/100-Days-Of-ML-Code",
"_____no_output_____"
]
],
[
[
"# Import needed libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler",
"_____no_output_____"
],
[
"# Import the data into pandas dataframe\n# Set variable for dependent and independent data\ndataset = pd.read_csv('datasets/Data.csv')\nX = dataset.iloc[ : , :-1].values\nY = dataset.iloc[ : , 3].values\nX",
"_____no_output_____"
],
[
"Y",
"_____no_output_____"
],
[
"# Handle the missing values using simpleimputer from scikit learn\nimputer = SimpleImputer(missing_values = np.nan, strategy = \"mean\")\nimputer = imputer.fit(X[ : , 1:3])\nX[ : , 1:3] = imputer.transform(X[ : , 1:3])\nX",
"_____no_output_____"
],
[
"# Encode the X categorical data using labelencoder from scikit learn.\nlabelencoder_X = LabelEncoder()\nX[ : , 0] = labelencoder_X.fit_transform(X[ : , 0])\nX",
"_____no_output_____"
],
[
"Y",
"_____no_output_____"
],
[
"# Encode the Y data using labelencoder from scikit learn\nlabelencoder_Y = LabelEncoder()\nY = labelencoder_Y.fit_transform(Y)\nY",
"_____no_output_____"
],
[
"# Split the datasets into training sets and test sets\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)",
"_____no_output_____"
],
[
"X_train",
"_____no_output_____"
],
[
"X_test",
"_____no_output_____"
],
[
"Y_train",
"_____no_output_____"
],
[
"Y_test",
"_____no_output_____"
],
[
"# Scale the features using standardscaler from scikit learn\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.fit_transform(X_test)",
"_____no_output_____"
],
[
"X_train",
"_____no_output_____"
],
[
"X_test",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd6c20a1d6404f9ade4a206c9caa665e06d6c06
| 29,628 |
ipynb
|
Jupyter Notebook
|
meta_learning_without_memorization/sinusoid/MR_MAML.ipynb
|
ojInc/google-research
|
9929c88b664800a25b8716c22068dd77d80bd5ee
|
[
"Apache-2.0"
] | 23,901 |
2018-10-04T19:48:53.000Z
|
2022-03-31T21:27:42.000Z
|
meta_learning_without_memorization/sinusoid/MR_MAML.ipynb
|
ojInc/google-research
|
9929c88b664800a25b8716c22068dd77d80bd5ee
|
[
"Apache-2.0"
] | 891 |
2018-11-10T06:16:13.000Z
|
2022-03-31T10:42:34.000Z
|
meta_learning_without_memorization/sinusoid/MR_MAML.ipynb
|
ojInc/google-research
|
9929c88b664800a25b8716c22068dd77d80bd5ee
|
[
"Apache-2.0"
] | 6,047 |
2018-10-12T06:31:02.000Z
|
2022-03-31T13:59:28.000Z
| 41.729577 | 155 | 0.495173 |
[
[
[
"# Copyright 2019 Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras import layers\nimport tensorflow.keras.backend as keras_backend\ntf.keras.backend.set_floatx('float32')\nimport tensorflow_probability as tfp\nfrom tensorflow_probability.python.layers import util as tfp_layers_util\n\nimport random\nimport sys\nimport time\nimport os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nprint(tf.__version__) # use tensorflow version >= 2.0.0\n#pip install tensorflow=2.0.0\n#pip install --upgrade tensorflow-probability\n\nexp_type = 'MAML' # choose from 'MAML', 'MR-MAML-W', 'MR-MAML-A'",
"2.0.0\n"
],
[
"class SinusoidGenerator():\n def __init__(self, K=10, width=5, K_amp=20, phase=0, amps = None, amp_ind=None, amplitude =None, seed = None):\n '''\n Args:\n K: batch size. Number of values sampled at every batch.\n amplitude: Sine wave amplitude.\n pahse: Sine wave phase.\n '''\n self.K = K\n self.width = width\n self.K_amp = K_amp\n self.phase = phase\n self.seed = seed\n self.x = self._sample_x()\n self.amp_ind = amp_ind if amp_ind is not None else random.randint(0,self.K_amp-5)\n self.amps = amps if amps is not None else np.linspace(0.1,4,self.K_amp)\n self.amplitude = amplitude if amplitude is not None else self.amps[self.amp_ind]\n\n def _sample_x(self):\n if self.seed is not None:\n np.random.seed(self.seed)\n return np.random.uniform(-self.width, self.width, self.K)\n\n\n def batch(self, noise_scale, x = None):\n '''return xa is [K, d_x+d_a], y is [K, d_y]'''\n if x is None:\n x = self._sample_x()\n x = x[:, None]\n amp = np.zeros([1, self.K_amp])\n amp[0,self.amp_ind] = 1\n amp = np.tile(amp, x.shape)\n xa = np.concatenate([x, amp], axis = 1)\n y = self.amplitude * np.sin(x - self.phase) + np.random.normal(scale = noise_scale, size = x.shape)\n return xa, y\n\n def equally_spaced_samples(self, K=None, width=None):\n '''Returns K equally spaced samples.'''\n if K is None:\n K = self.K\n if width is None:\n width = self.width\n return self.batch(noise_scale = 0, x=np.linspace(-width+0.5, width-0.5, K))",
"_____no_output_____"
],
[
"noise_scale = 0.1 #@param {type:\"number\"}\nn_obs = 20 #@param {type:\"number\"}\nn_context = 10 #@param {type:\"number\"}\nK_amp = 20 #@param {type:\"number\"}\nx_width = 5 #@param {type:\"number\"}\nn_iter = 20000 #@param {type:\"number\"}\namps = np.linspace(0.1,4,K_amp)\nlr_inner = 0.01 #@param {type:\"number\"}\ndim_w = 5 #@param {type:\"number\"}\ntrain_ds = [SinusoidGenerator(K=n_context, width = x_width, \\\n K_amp = K_amp, amps = amps) \\\n for _ in range(n_iter)]",
"_____no_output_____"
],
[
"\nclass SineModel(keras.Model):\n def __init__(self):\n super(SineModel, self).__init__() # python 2 syntax\n # super().__init__() # python 3 syntax\n self.hidden1 = keras.layers.Dense(40)\n self.hidden2 = keras.layers.Dense(40)\n self.out = keras.layers.Dense(1)\n\n def call(self, x):\n x = keras.activations.relu(self.hidden1(x))\n x = keras.activations.relu(self.hidden2(x))\n x = self.out(x)\n return x\n\n\ndef kl_qp_gaussian(mu_q, sigma_q, mu_p, sigma_p):\n \"\"\"Kullback-Leibler KL(N(mu_q), Diag(sigma_q^2) || N(mu_p), Diag(sigma_p^2))\"\"\"\n sigma2_q = tf.square(sigma_q) + 1e-16\n sigma2_p = tf.square(sigma_p) + 1e-16\n temp = tf.math.log(sigma2_p) - tf.math.log(sigma2_q) - 1.0 + \\\n sigma2_q / sigma2_p + tf.square(mu_q - mu_p) / sigma2_p #n_target * d_w\n kl = 0.5 * tf.reduce_mean(temp, axis = 1)\n return tf.reduce_mean(kl)\n\ndef copy_model(model, x=None, input_shape=None):\n '''\n Copy model weights to a new model.\n Args:\n model: model to be copied.\n x: An input example.\n '''\n copied_model = SineModel()\n if x is not None:\n copied_model.call(tf.convert_to_tensor(x))\n if input_shape is not None:\n copied_model.build(tf.TensorShape([None,input_shape]))\n copied_model.set_weights(model.get_weights())\n return copied_model\n\ndef np_to_tensor(list_of_numpy_objs):\n return (tf.convert_to_tensor(obj, dtype=tf.float32) for obj in list_of_numpy_objs)\n\n\ndef compute_loss(model, xa, y):\n y_hat = model.call(xa)\n loss = keras_backend.mean(keras.losses.mean_squared_error(y, y_hat))\n return loss, y_hat\n\n\n",
"_____no_output_____"
],
[
"def train_batch(xa, y, model, optimizer, encoder=None):\n tensor_xa, tensor_y = np_to_tensor((xa, y))\n if exp_type == 'MAML':\n with tf.GradientTape() as tape:\n loss, _ = compute_loss(model, tensor_xa, tensor_y)\n if exp_type == 'MR-MAML-W':\n w = encoder(tensor_xa)\n with tf.GradientTape() as tape:\n y_hat = model.call(w)\n loss = keras_backend.mean(keras.losses.mean_squared_error(tensor_y, y_hat))\n if exp_type == 'MR-MAML-A':\n _, w, _ = encoder(tensor_xa)\n with tf.GradientTape() as tape:\n y_hat = model.call(w)\n loss = keras_backend.mean(keras.losses.mean_squared_error(y, y_hat))\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n return loss\n\n\ndef test_inner_loop(model, optimizer, xa_context, y_context, xa_target, y_target, num_steps, encoder=None):\n inner_record = []\n tensor_xa_target, tensor_y_target = np_to_tensor((xa_target, y_target))\n if exp_type == 'MAML':\n w_target = tensor_xa_target\n if exp_type == 'MR-MAML-W':\n w_target = encoder(tensor_xa_target)\n if exp_type == 'MR-MAML-A':\n _, w_target, _ = encoder(tensor_xa_target)\n\n for step in range(0, np.max(num_steps) + 1):\n if step in num_steps:\n if exp_type == 'MAML':\n loss, y_hat = compute_loss(model, w_target, tensor_y_target)\n else:\n y_hat = model.call(w_target)\n loss = keras_backend.mean(keras.losses.mean_squared_error(tensor_y_target, y_hat))\n inner_record.append((step, y_hat, loss))\n loss = train_batch(xa_context, y_context, model, optimizer, encoder)\n return inner_record\n\n\ndef eval_sinewave_for_test(model, sinusoid_generator, num_steps=(0, 1, 10), encoder=None, learning_rate = lr_inner, ax = None, legend= False):\n # data for training\n xa_context, y_context = sinusoid_generator.batch(noise_scale = noise_scale)\n y_context = y_context + np.random.normal(scale = noise_scale, size = y_context.shape)\n # data for validation\n xa_target, y_target = sinusoid_generator.equally_spaced_samples(K = 200, width = 5)\n y_target = y_target + np.random.normal(scale = noise_scale, size = y_target.shape)\n\n # copy model so we can use the same model multiple times\n if exp_type == 'MAML':\n copied_model = copy_model(model, x = xa_context)\n else:\n copied_model = copy_model(model, input_shape=dim_w)\n optimizer = keras.optimizers.SGD(learning_rate=learning_rate)\n inner_record = test_inner_loop(copied_model, optimizer, xa_context, y_context, xa_target, y_target, num_steps, encoder)\n\n # plot\n if ax is not None:\n plt.sca(ax)\n x_context = xa_context[:,0,None]\n x_target = xa_target[:,0,None]\n train, = plt.plot(x_context, y_context, '^')\n ground_truth, = plt.plot(x_target, y_target0, linewidth=2.0)\n plots = [train, ground_truth]\n legends = ['Context Points', 'True Function']\n for n, y_hat, loss in inner_record:\n cur, = plt.plot(x_target, y_hat[:, 0], '--')\n plots.append(cur)\n legends.append('After {} Steps'.format(n))\n if legend:\n plt.legend(plots, legends, loc='center left', bbox_to_anchor=(1, 0.5))\n plt.ylim(-6, 6)\n plt.axvline(x=-sinusoid_generator.width, linestyle='--')\n plt.axvline(x=sinusoid_generator.width,linestyle='--')\n return inner_record",
"_____no_output_____"
],
[
"exp_type = 'MAML'\nif exp_type == 'MAML':\n model = SineModel()\n model.build((None, K_amp+1))\n\n dataset = train_ds\n optimizer = keras.optimizers.Adam()\n total_loss = 0\n n_iter = 15000\n losses = []\n\n for i, t in enumerate(random.sample(dataset, n_iter)):\n xa_train, y_train = np_to_tensor(t.batch(noise_scale = noise_scale))\n\n with tf.GradientTape(watch_accessed_variables=False) as test_tape:\n test_tape.watch(model.trainable_variables)\n with tf.GradientTape() as train_tape:\n train_loss, _ = compute_loss(model, xa_train, y_train)\n model_copy = copy_model(model, xa_train)\n gradients_inner = train_tape.gradient(train_loss, model.trainable_variables) # \\nabla_{\\theta}\n\n k = 0\n for j in range(len(model_copy.layers)):\n model_copy.layers[j].kernel = tf.subtract(model.layers[j].kernel, # \\phi_t = T(\\theta, \\nabla_{\\theta})\n tf.multiply(lr_inner, gradients_inner[k]))\n model_copy.layers[j].bias = tf.subtract(model.layers[j].bias,\n tf.multiply(lr_inner, gradients_inner[k+1]))\n k += 2\n xa_validation, y_validation = np_to_tensor(t.batch(noise_scale = noise_scale))\n test_loss, y_hat = compute_loss(model_copy, xa_validation, y_validation) # test_loss\n gradients_outer = test_tape.gradient(test_loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients_outer, model.trainable_variables))\n\n\n total_loss += test_loss\n loss = total_loss / (i+1.0)\n if i % 1000 == 0:\n print('Step {}: loss = {}'.format(i, loss))",
"Step 0: loss = 0.5836441516876221\nStep 1000: loss = 0.7144132256507874\nStep 2000: loss = 0.4053805470466614\nStep 3000: loss = 0.2834143042564392\nStep 4000: loss = 0.2200154811143875\nStep 5000: loss = 0.18113426864147186\nStep 6000: loss = 0.154592826962471\nStep 7000: loss = 0.1353120058774948\nStep 8000: loss = 0.12070710957050323\nStep 9000: loss = 0.1094995066523552\nStep 10000: loss = 0.1004406288266182\nStep 11000: loss = 0.09283847361803055\nStep 12000: loss = 0.08659099042415619\nStep 13000: loss = 0.08126141875982285\nStep 14000: loss = 0.07664626091718674\n"
],
[
"if exp_type == 'MAML':\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n n_context = 5\n n_test_task = 100\n errs = []\n for ii in range(n_test_task):\n np.random.seed(ii)\n A = np.random.uniform(low = amps[0], high = amps[-1])\n test_ds = SinusoidGenerator(K=n_context, seed = ii, amplitude = A, amp_ind= random.randint(0,K_amp-5))\n inner_record = eval_sinewave_for_test(model, test_ds, num_steps=(0, 1, 5, 100));\n errs.append(inner_record[-1][2].numpy())\n\n print('Model is', exp_type, 'meta-test MSE is', np.mean(errs) )",
"Model is MAML meta-test MSE is 0.51450217\n"
]
],
[
[
"# Training & Testing for MR-MAML(W)",
"_____no_output_____"
]
],
[
[
"if exp_type == 'MR-MAML-W':\n\n model = SineModel()\n dataset = train_ds\n optimizer = keras.optimizers.Adam()\n\n Beta = 5e-5\n learning_rate = 1e-3\n n_iter = 15000\n model.build((None, dim_w))\n\n kernel_posterior_fn=tfp_layers_util.default_mean_field_normal_fn(untransformed_scale_initializer=tf.compat.v1.initializers.random_normal(\n mean=-50., stddev=0.1))\n\n encoder_w = tf.keras.Sequential([\n tfp.layers.DenseReparameterization(100, activation=tf.nn.relu, kernel_posterior_fn=kernel_posterior_fn,input_shape=(1 + K_amp,)),\n tfp.layers.DenseReparameterization(dim_w,kernel_posterior_fn=kernel_posterior_fn),\n ])\n\n total_loss = 0\n losses = []\n start = time.time()\n\n for i, t in enumerate(random.sample(dataset, n_iter)):\n xa_train, y_train = np_to_tensor(t.batch(noise_scale = noise_scale)) #[K, 1]\n\n x_validation = np.random.uniform(-x_width, x_width, n_obs - n_context)\n xa_validation, y_validation = np_to_tensor(t.batch(noise_scale = noise_scale, x = x_validation))\n\n all_var = encoder_w.trainable_variables + model.trainable_variables\n with tf.GradientTape(watch_accessed_variables=False) as test_tape:\n test_tape.watch(all_var)\n with tf.GradientTape() as train_tape:\n w_train = encoder_w(xa_train)\n y_hat_train = model.call(w_train)\n train_loss = keras_backend.mean(keras.losses.mean_squared_error(y_train, y_hat_train)) # K*1\n gradients_inner = train_tape.gradient(train_loss, model.trainable_variables) # \\nabla_{\\theta}\n model_copy = copy_model(model, x = w_train)\n k = 0\n for j in range(len(model_copy.layers)):\n model_copy.layers[j].kernel = tf.subtract(model.layers[j].kernel, # \\phi_t = T(\\theta, \\nabla_{\\theta})\n tf.multiply(lr_inner, gradients_inner[k]))\n model_copy.layers[j].bias = tf.subtract(model.layers[j].bias,\n tf.multiply(lr_inner, gradients_inner[k+1]))\n k += 2\n\n w_validation = encoder_w(xa_validation)\n y_hat_validation = model_copy.call(w_validation)\n mse_loss = keras_backend.mean(keras.losses.mean_squared_error(y_validation, y_hat_validation))\n kl_loss = Beta * sum(encoder_w.losses)\n validation_loss = mse_loss + kl_loss\n\n gradients_outer = test_tape.gradient(validation_loss,all_var)\n keras.optimizers.Adam(learning_rate=learning_rate).apply_gradients(zip(gradients_outer, all_var))\n\n losses.append(validation_loss.numpy())\n\n if i % 1000 == 0 and i > 0:\n print('Step {}:'.format(i), 'loss=', np.mean(losses))\n losses = []",
"Step 1000: loss= 2.6914458\nStep 2000: loss= 2.4870665\nStep 3000: loss= 2.4284792\nStep 4000: loss= 2.3726428\nStep 5000: loss= 2.3125937\nStep 6000: loss= 2.228668\nStep 7000: loss= 2.1762276\nStep 8000: loss= 2.1387603\nStep 9000: loss= 2.112448\nStep 10000: loss= 2.1087198\nStep 11000: loss= 2.10187\nStep 12000: loss= 2.102722\nStep 13000: loss= 2.1002984\nStep 14000: loss= 2.0911772\n"
],
[
"if exp_type == 'MR-MAML-W':\n n_context = 5\n n_test_task = 100\n errs = []\n for ii in range(n_test_task):\n np.random.seed(ii)\n A = np.random.uniform(low = amps[0], high = amps[-1])\n test_ds = SinusoidGenerator(K=n_context, seed = ii, amplitude = A, amp_ind= random.randint(0,K_amp-5))\n inner_record = eval_sinewave_for_test(model, test_ds, num_steps=(0, 1, 5, 100), encoder=encoder_w);\n errs.append(inner_record[-1][2].numpy())\n\n print('Model is', exp_type, ', meta-test MSE is', np.mean(errs) )",
"Model is MR-MAML-W , meta-test MSE is 0.16159104\n"
]
],
[
[
"#Training & Testing for MR-MAML(A)",
"_____no_output_____"
]
],
[
[
"\nif exp_type == 'MR-MAML-A':\n class Encoder(keras.Model):\n def __init__(self, dim_w=5, name='encoder', **kwargs):\n # super().__init__(name = name)\n super(Encoder, self).__init__(name = name)\n self.dense_proj = layers.Dense(80, activation='relu')\n self.dense_mu = layers.Dense(dim_w)\n self.dense_sigma_w = layers.Dense(dim_w)\n\n def call(self, inputs):\n h = self.dense_proj(inputs)\n mu_w = self.dense_mu(h)\n sigma_w = self.dense_sigma_w(h)\n sigma_w = tf.nn.softplus(sigma_w)\n ws = mu_w + tf.random.normal(tf.shape(mu_w)) * sigma_w\n return ws, mu_w, sigma_w\n\n model = SineModel()\n model.build((None, dim_w))\n encoder_w = Encoder(dim_w = dim_w)\n encoder_w.build((None, K_amp+1))\n Beta = 5.0\n n_iter = 10000\n dataset = train_ds\n optimizer = keras.optimizers.Adam()\n losses = [];\n\n for i, t in enumerate(random.sample(dataset, n_iter)):\n xa_train, y_train = np_to_tensor(t.batch(noise_scale = noise_scale)) #[K, 1]\n\n with tf.GradientTape(watch_accessed_variables=False) as test_tape, tf.GradientTape(watch_accessed_variables=False) as encoder_test_tape:\n test_tape.watch(model.trainable_variables)\n encoder_test_tape.watch(encoder_w.trainable_variables)\n with tf.GradientTape() as train_tape:\n w_train, _, _ = encoder_w(xa_train)\n y_hat = model.call(w_train)\n train_loss = keras_backend.mean(keras.losses.mean_squared_error(y_train, y_hat))\n model_copy = copy_model(model, x=w_train)\n gradients_inner = train_tape.gradient(train_loss, model.trainable_variables) # \\nabla_{\\theta}\n k = 0\n for j in range(len(model_copy.layers)):\n model_copy.layers[j].kernel = tf.subtract(model.layers[j].kernel, # \\phi_t = T(\\theta, \\nabla_{\\theta})\n tf.multiply(lr_inner, gradients_inner[k]))\n model_copy.layers[j].bias = tf.subtract(model.layers[j].bias,\n tf.multiply(lr_inner, gradients_inner[k+1]))\n k += 2\n x_validation = np.random.uniform(-x_width, x_width, n_obs - n_context)\n xa_validation, y_validation = np_to_tensor(t.batch(noise_scale = noise_scale, x = x_validation))\n\n w_validation, w_mu_validation, w_sigma_validation = encoder_w(xa_validation)\n test_mse, _ = compute_loss(model_copy, w_validation, y_validation)\n kl_ib = kl_qp_gaussian(w_mu_validation, w_sigma_validation,\n tf.zeros(tf.shape(w_mu_validation)), tf.ones(tf.shape(w_sigma_validation)))\n test_loss = test_mse + Beta * kl_ib\n\n gradients_outer = test_tape.gradient(test_mse, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients_outer, model.trainable_variables))\n\n gradients = encoder_test_tape.gradient(test_loss,encoder_w.trainable_variables)\n keras.optimizers.Adam(learning_rate=0.001).apply_gradients(zip(gradients, encoder_w.trainable_variables))\n\n losses.append(test_loss)\n\n if i % 1000 == 0 and i > 0:\n print('Step {}:'.format(i), 'loss = ', np.mean(losses))",
"Step 1000: loss = 1.9501201\nStep 2000: loss = 1.9419937\nStep 3000: loss = 1.8764127\nStep 4000: loss = 1.8179001\nStep 5000: loss = 1.7535788\nStep 6000: loss = 1.6897625\nStep 7000: loss = 1.632552\nStep 8000: loss = 1.57314\nStep 9000: loss = 1.5216928\n"
],
[
"if exp_type == 'MR-MAML-A':\n n_context = 5\n n_test_task = 100\n errs = []\n for ii in range(n_test_task):\n np.random.seed(ii)\n A = np.random.uniform(low = amps[0], high = amps[-1])\n test_ds = SinusoidGenerator(K=n_context, seed = ii, amplitude = A, amp_ind= random.randint(0,K_amp-5))\n inner_record = eval_sinewave_for_test(model, test_ds, num_steps=(0, 1, 5, 100), encoder=encoder_w);\n errs.append(inner_record[-1][2].numpy())\n\n print('Model is', exp_type, ', meta-test MSE is', np.mean(errs) )",
"Model is MR-MAML-A , meta-test MSE is 0.14966752\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbd6dc74ac1c89b24f52479b2590bb305cd5a619
| 325,145 |
ipynb
|
Jupyter Notebook
|
Custom_Resnet_1.ipynb
|
gpdsec/ResNet
|
79d54609144bf075789c0556064038a8cbf0d63b
|
[
"MIT"
] | 2 |
2021-07-12T05:51:22.000Z
|
2022-02-04T10:12:47.000Z
|
Custom_Resnet_1.ipynb
|
gpdsec/Residual-Neural-Network
|
79d54609144bf075789c0556064038a8cbf0d63b
|
[
"MIT"
] | null | null | null |
Custom_Resnet_1.ipynb
|
gpdsec/Residual-Neural-Network
|
79d54609144bf075789c0556064038a8cbf0d63b
|
[
"MIT"
] | null | null | null | 41.34075 | 22,370 | 0.555398 |
[
[
[
"<a href=\"https://colab.research.google.com/github/gpdsec/Residual-Neural-Network/blob/main/Custom_Resnet_1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"*It's custom ResNet trained demonstration purpose, not for accuracy.\nDataset used is cats_vs_dogs dataset from tensorflow_dataset with **Custom Augmentatior** for data augmentation*\n\n---\n",
"_____no_output_____"
]
],
[
[
"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"
]
],
[
[
"### **1. Importing Libraries**\n\n\n\n",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Input, GlobalMaxPooling2D, add, ReLU\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Sequential\nimport tensorflow_datasets as tfds\nimport pandas as pd\nimport numpy as np\nfrom tensorflow.keras import Model\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nfrom PIL import Image\nfrom tqdm.notebook import tqdm\nimport os\nimport time\n%matplotlib inline\n",
"_____no_output_____"
]
],
[
[
"### **2. Loading & Processing Data**\n\n\n\n",
"_____no_output_____"
],
[
"##### **Loading Data**",
"_____no_output_____"
]
],
[
[
"(train_ds, val_ds, test_ds), info = tfds.load(\n 'cats_vs_dogs',\n split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],\n with_info=True,\n as_supervised=True)\n",
"_____no_output_____"
],
[
"## Image preprocessing function\ndef preprocess(img, lbl):\n image = tf.image.resize_with_pad(img, target_height=224, target_width=224)\n image = tf.divide(image, 255)\n label = [0,0]\n if int(lbl) == 1:\n label[1]=1\n else:\n label[0]=1\n return image, tf.cast(label, tf.float32)",
"_____no_output_____"
],
[
"train_ds = train_ds.map(preprocess)\ntest_ds = test_ds.map(preprocess)\nval_ds = val_ds.map(preprocess)\n",
"_____no_output_____"
],
[
"info",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"#### **Data Augmentation layer**\n\n\n\n",
"_____no_output_____"
]
],
[
[
"###### Important Variables\n\nbatch_size = 32\nshape = (224, 224, 3)\ntraining_steps = int(18610/batch_size)\nvalidation_steps = int(2326/batch_size)\npath = '/content/drive/MyDrive/Colab Notebooks/cats_v_dogs.h5' ",
"_____no_output_____"
],
[
"####### Data agumentation layer\n# RandomFlip and RandomRotation Suits my need for Data Agumentation\n\n\naugmentation=Sequential([\n layers.experimental.preprocessing.RandomFlip(\"horizontal_and_vertical\"),\n layers.experimental.preprocessing.RandomRotation(0.2),\n ])\n\n####### Data Shuffle and batch Function\ndef shufle_batch(train_set, val_set, batch_size): \n train_set=(train_set.shuffle(1000).batch(batch_size))\n train_set = train_set.map(lambda x, y: (augmentation(x, training=True), y))\n val_set = (val_set.shuffle(1000).batch(batch_size))\n val_set = val_set.map(lambda x, y: (augmentation(x, training=True), y))\n return train_set, val_set\n\n\ntrain_set, val_set = shufle_batch(train_ds, val_ds, batch_size)\n",
"_____no_output_____"
]
],
[
[
"## **3. Creating Model**",
"_____no_output_____"
],
[
"##### **Creating Residual block**",
"_____no_output_____"
]
],
[
[
"def residual_block(x, feature_map, filter=(3,3) , _strides=(1,1), _network_shortcut=False):\n shortcut = x\n x = Conv2D(feature_map, filter, strides=_strides, activation='relu', padding='same')(x)\n x = BatchNormalization()(x)\n\n x = Conv2D(feature_map, filter, strides=_strides, activation='relu', padding='same')(x)\n x = BatchNormalization()(x)\n\n \n if _network_shortcut :\n shortcut = Conv2D(feature_map, filter, strides=_strides, activation='relu', padding='same')(shortcut)\n shortcut = BatchNormalization()(shortcut)\n\n x = add([shortcut, x])\n x = ReLU()(x)\n\n return x",
"_____no_output_____"
],
[
"# Build the model using the functional API\ni = Input(shape)\n\nx = Conv2D(32, (3, 3), activation='relu', padding='same')(i)\nx = BatchNormalization()(x)\nx = residual_block(x, 32, filter=(3,3) , _strides=(1,1), _network_shortcut=False)\n#x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n#x = BatchNormalization()(x)\nx = MaxPooling2D((2, 2))(x)\nx = Conv2D(64, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = residual_block(x,64, filter=(3,3) , _strides=(1,1), _network_shortcut=False)\nx = MaxPooling2D((2, 2))(x)\nx = Conv2D(64, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D((2, 2))(x)\nx = Conv2D(128, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(128, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D((2, 2))(x)\nx = Flatten()(x)\nx = Dropout(0.2)(x)\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.2)(x)\nx = Dense(2, activation='sigmoid')(x)\n\nmodel = Model(i, x)",
"_____no_output_____"
],
[
"model.compile()\nmodel.summary()",
"Model: \"model\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) [(None, 224, 224, 3) 0 \n__________________________________________________________________________________________________\nconv2d (Conv2D) (None, 224, 224, 32) 896 input_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization (BatchNorma (None, 224, 224, 32) 128 conv2d[0][0] \n__________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 224, 224, 32) 9248 batch_normalization[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_1 (BatchNor (None, 224, 224, 32) 128 conv2d_1[0][0] \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 224, 224, 32) 9248 batch_normalization_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_2 (BatchNor (None, 224, 224, 32) 128 conv2d_2[0][0] \n__________________________________________________________________________________________________\nadd (Add) (None, 224, 224, 32) 0 batch_normalization[0][0] \n batch_normalization_2[0][0] \n__________________________________________________________________________________________________\nre_lu (ReLU) (None, 224, 224, 32) 0 add[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 112, 112, 32) 0 re_lu[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 112, 112, 64) 18496 max_pooling2d[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_3 (BatchNor (None, 112, 112, 64) 256 conv2d_3[0][0] \n__________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 112, 112, 64) 36928 batch_normalization_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_4 (BatchNor (None, 112, 112, 64) 256 conv2d_4[0][0] \n__________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 112, 112, 64) 36928 batch_normalization_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_5 (BatchNor (None, 112, 112, 64) 256 conv2d_5[0][0] \n__________________________________________________________________________________________________\nadd_1 (Add) (None, 112, 112, 64) 0 batch_normalization_3[0][0] \n batch_normalization_5[0][0] \n__________________________________________________________________________________________________\nre_lu_1 (ReLU) (None, 112, 112, 64) 0 add_1[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 56, 56, 64) 0 re_lu_1[0][0] \n__________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 56, 56, 64) 36928 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_6 (BatchNor (None, 56, 56, 64) 256 conv2d_6[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_2 (MaxPooling2D) (None, 28, 28, 64) 0 batch_normalization_6[0][0] \n__________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 28, 28, 128) 73856 max_pooling2d_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_7 (BatchNor (None, 28, 28, 128) 512 conv2d_7[0][0] \n__________________________________________________________________________________________________\nconv2d_8 (Conv2D) (None, 28, 28, 128) 147584 batch_normalization_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_8 (BatchNor (None, 28, 28, 128) 512 conv2d_8[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_3 (MaxPooling2D) (None, 14, 14, 128) 0 batch_normalization_8[0][0] \n__________________________________________________________________________________________________\nflatten (Flatten) (None, 25088) 0 max_pooling2d_3[0][0] \n__________________________________________________________________________________________________\ndropout (Dropout) (None, 25088) 0 flatten[0][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 512) 12845568 dropout[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 512) 0 dense[0][0] \n__________________________________________________________________________________________________\ndense_1 (Dense) (None, 2) 1026 dropout_1[0][0] \n==================================================================================================\nTotal params: 13,219,138\nTrainable params: 13,217,922\nNon-trainable params: 1,216\n__________________________________________________________________________________________________\n"
]
],
[
[
"### **4. Optimizer and loss Function** ",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"loss_object = tf.keras.losses.BinaryCrossentropy(from_logits=False)\nOptimiser = tf.keras.optimizers.Adam()",
"_____no_output_____"
]
],
[
[
"### **5. Metrics For Loss and Acuracy**",
"_____no_output_____"
]
],
[
[
"train_loss = tf.keras.metrics.Mean(name='train_loss')\ntrain_accuracy = tf.keras.metrics.BinaryAccuracy(name='train_accuracy')\ntest_loss = tf.keras.metrics.Mean(name=\"test_loss\")\ntest_accuracy = tf.keras.metrics.BinaryAccuracy(name='test_accuracy')",
"_____no_output_____"
]
],
[
[
"### **6. Function for training and Testing**",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef train_step(images, labels):\n with tf.GradientTape() as tape:\n prediction = model(images, training=True)\n loss = loss_object(labels,prediction)\n gradient = tape.gradient(loss, model.trainable_variables)\n Optimiser.apply_gradients(zip(gradient, model.trainable_variables))\n train_loss(loss)\n train_accuracy(labels, prediction)",
"_____no_output_____"
],
[
"@tf.function\ndef test_step(images, labels):\n prediction = model(images, training = False)\n t_loss = loss_object(labels, prediction)\n test_loss(t_loss)\n test_accuracy(labels, prediction)",
"_____no_output_____"
]
],
[
[
"### **7. Training Model**",
"_____no_output_____"
]
],
[
[
"EPOCHS = 25\nTrain_LOSS = []\nTRain_Accuracy = []\nTest_LOSS = []\nTest_Accuracy = [] \n\nfor epoch in range(EPOCHS):\n train_loss.reset_states()\n train_accuracy.reset_states()\n test_loss.reset_states()\n test_accuracy.reset_states()\n print(f'Epoch : {epoch+1}')\n\n count = 0 # variable to keep tab how much data steps of training\n desc = \"EPOCHS {:0>4d}\".format(epoch+1)\n\n\n for images, labels in tqdm(train_set, total=training_steps, desc=desc):\n train_step(images, labels)\n \n for test_images, test_labels in val_set:\n test_step(test_images, test_labels)\n \n \n \n \n\n print(\n f'Loss: {train_loss.result()}, '\n f'Accuracy: {train_accuracy.result()*100}, '\n f'Test Loss: {test_loss.result()}, '\n f'Test Accuracy: {test_accuracy.result()*100}'\n )\n\n Train_LOSS.append(train_loss.result())\n TRain_Accuracy.append(train_accuracy.result()*100)\n Test_LOSS.append(test_loss.result())\n Test_Accuracy.append(test_accuracy.result()*100)\n\n ### Saving BestModel\n\n if epoch==0:\n min_Loss = test_loss.result()\n min_Accuracy = test_accuracy.result()*100\n elif (min_Loss>test_loss.result()):\n if (min_Accuracy <= test_accuracy.result()*100) :\n min_Loss = test_loss.result()\n min_Accuracy = ( test_accuracy.result()*100)\n print(f\"Saving Best Model {epoch+1}\")\n model.save_weights(path) # Saving Model To drive\n ",
"Epoch : 1\n"
]
],
[
[
"### **8. Ploting Loss and Accuracy Per Iteration**",
"_____no_output_____"
]
],
[
[
"# Plot loss per iteration\nplt.plot(Train_LOSS, label='loss')\nplt.plot(Test_LOSS, label='val_loss')\nplt.title('Plot loss per iteration')\nplt.legend()",
"_____no_output_____"
],
[
"# Plot Accuracy per iteration\nplt.plot(TRain_Accuracy, label='loss')\nplt.plot(Test_Accuracy, label='val_loss')\nplt.title('Plot Accuracy per iteration')\nplt.legend()",
"_____no_output_____"
]
],
[
[
"## 9. Evoluting model",
"_____no_output_____"
],
[
"##### **Note-**\nTesting Accuracy of Model with Complete Unseen DataSet.",
"_____no_output_____"
]
],
[
[
"model.load_weights(path)",
"_____no_output_____"
],
[
"len(test_ds)",
"_____no_output_____"
],
[
"test_set = test_ds.shuffle(50).batch(2326)",
"_____no_output_____"
],
[
"for images, labels in test_set:\n prediction = model.predict(images)\n break\n## Function For Accuracy\ndef accuracy(prediction, labels):\n corect =0\n for i in range(len(prediction)):\n pred = prediction[i]\n labe = labels[i]\n if pred[0]>pred[1] and labe[0]>labe[1]:\n corect+=1\n elif pred[0]<pred[1] and labe[0]<labe[1]:\n corect+=1\n \n return (corect/len(prediction))*100\n ",
"_____no_output_____"
],
[
"print(accuracy(prediction, labels))\n",
"93.50816852966466\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd6e30f8bb518ce338cda0073d284d5fdbab020
| 214,251 |
ipynb
|
Jupyter Notebook
|
notebooks/SA-Gravity.ipynb
|
RichardScottOZ/australia-gravity-data
|
8f8da7831795f63b542ade32fa00d52b9b85ab6d
|
[
"MIT"
] | 2 |
2020-10-29T22:17:08.000Z
|
2021-06-10T14:40:56.000Z
|
notebooks/SA-Gravity.ipynb
|
RichardScottOZ/australia-gravity-data
|
8f8da7831795f63b542ade32fa00d52b9b85ab6d
|
[
"MIT"
] | null | null | null |
notebooks/SA-Gravity.ipynb
|
RichardScottOZ/australia-gravity-data
|
8f8da7831795f63b542ade32fa00d52b9b85ab6d
|
[
"MIT"
] | 2 |
2021-04-28T00:49:37.000Z
|
2022-03-02T09:27:06.000Z
| 53.045556 | 26,496 | 0.632618 |
[
[
[
"import geopandas as gpd\nimport pandas as pd\n\nimport os\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport tarfile\n\nfrom discretize import TensorMesh\n\nfrom SimPEG.utils import plot2Ddata, surface2ind_topo\nfrom SimPEG.potential_fields import gravity\nfrom SimPEG import (\n maps,\n data,\n data_misfit,\n inverse_problem,\n regularization,\n optimization,\n directives,\n inversion,\n utils,\n)\n\n",
"_____no_output_____"
],
[
"#sagrav = gpd.read_file(r'C:\\users\\rscott\\Downloads\\gravity_stations_shp\\gravity_stations.shp') #test ",
"_____no_output_____"
],
[
"print(sagrav['MGA_ZONE'].unique())\nsagrav.head()",
"[54 53 52]\n"
],
[
"#survey_array = sagrav[['LONGITUDE','LATITUDE','AHD_ELEVAT','BA_1984_UM']].to_numpy()\nsurvey_array = sagrav[['MGA_EAST','MGA_NORTH','AHD_ELEVAT','BA_1984_UM']].to_numpy()",
"_____no_output_____"
],
[
"dobs = survey_array",
"_____no_output_____"
],
[
"survey_array.shape",
"_____no_output_____"
],
[
"dobs.shape",
"_____no_output_____"
],
[
"#dobs_total_bounds = [sagrav['MGA_EAST'].min(),sagrav['MGA_NORTH'].min(),sagrav['MGA_EAST'].max(),sagrav['MGA_NORTH'].max()]\ndobs_total_bounds = sagrav.total_bounds\nprint(dobs_total_bounds)\nsa54 = sagrav.loc[sagrav['MGA_ZONE'] == 54]",
"[128.50132321 -39.99733438 141.49972995 -25.50001403]\n"
],
[
"dobs_total_bounds\nminx, miny, maxx, maxy = dobs_total_bounds\nminx = sa54['MGA_EAST'].min()\nmaxx = sa54['MGA_EAST'].max()\nminy = sa54['MGA_NORTH'].min()\nmaxy = sa54['MGA_NORTH'].max()\n\nminxtest = maxx - 0.045\nminxtest = maxx - 5000\nmaxxtest = maxx\nminytest = maxy - 0.045\nminytest = maxy - 5000\nmaxytest = maxy\n\nprint(minxtest, maxxtest, minytest, maxytest)\n",
"544587.6900000001 549587.6900000001 7174103.37 7179103.37\n"
],
[
"# Define receiver locations and observed data\nreceiver_locations = dobs[:, 0:3]\ndobs = dobs[:, -1]",
"_____no_output_____"
],
[
"#sagrav_test = sagrav.loc[(sagrav['MGA_EAST'] >= minxtest) & (sagrav['MGA_EAST'] <= maxxtest) & (sagrav['MGA_NORTH'] >= minytest) & (sagrav['MGA_NORTH'] <= maxytest) ]\nfrom tqdm import tqdm\nfrom time import sleep\n\n#print(minxtest, minytest, maxxtest, maxytest)\nprint(minx, miny, maxx, maxy)\n#maxrangey = (maxy - miny)//0.045\n#maxrangex = (maxx - minx)//0.045\n\nmaxrangey = (maxy - miny)//5000\nmaxrangex = (maxx - minx)//5000\n\nprint(maxrangex, maxrangey)\n#with tqdm(total=maxrangey) as pbar:\nfor i in range(int(maxrangey)):\n print(i)\n for j in range(int(maxrangex)):\n\n #xmin, ymin, xmax, ymax = sagrav_test.total_bounds\n #xmin = minx + j*0.045\n #ymin = miny + i*0.045\n #xmax = minx + (j+1)*0.045\n #ymax = miny + (i+1)*0.045\n \n xmin = minx + j*5000\n ymin = miny + i*5000\n xmax = minx + (j+1)*5000\n ymax = miny + (i+1)*5000\n print(xmin, ymin, xmax, ymax)\n\n #sagrav_test = sagrav.loc[(sagrav['LONGITUDE'] >= xmin) & (sagrav['LATITUDE'] >= ymin) & (sagrav['LONGITUDE'] <= xmax) & (sagrav['LATITUDE'] <= ymax) ]\n sagrav_test = sa54.loc[(sa54['MGA_EAST'] >= xmin) & (sa54['MGA_NORTH'] >= ymin) & (sa54['MGA_EAST'] <= xmax) & (sa54['MGA_NORTH'] <= ymax) ]\n \n #sac_sussex = sagrav.cx[xmin:xmax, ymin:ymax] \n #print(sagrav_test.shape)\n if (sagrav_test.shape[0] > 0):\n #print(sagrav_test)\n break\n if (sagrav_test.shape[0] > 3):\n print(sagrav_test)\n break\n\nprint(minx, miny, maxx, maxy, sagrav_test.shape)\nprint(sagrav_test.total_bounds)\n\nprint(xmin, xmax, ymin, ymax)\nncx = 10\nncy = 10\nncz = 5\n#dx = 0.0045*2\n#dy = 0.0045*2\ndx = 500\ndy = 500\ndz = 200\n\nx0 = xmin\ny0 = ymin\nz0 = -1000\nhx = dx*np.ones(ncx)\nhy = dy*np.ones(ncy)\nhz = dz*np.ones(ncz)\n\nmesh2 = TensorMesh([hx, hx, hz], x0 = [x0,y0,z0])\nmesh2\n",
"198845.79 5568582.51 549587.6900000001 7179103.37\n70.0 322.0\n0\n198845.79 5568582.51 203845.79 5573582.51\n203845.79 5568582.51 208845.79 5573582.51\n208845.79 5568582.51 213845.79 5573582.51\n213845.79 5568582.51 218845.79 5573582.51\n218845.79 5568582.51 223845.79 5573582.51\n223845.79 5568582.51 228845.79 5573582.51\n228845.79 5568582.51 233845.79 5573582.51\n233845.79 5568582.51 238845.79 5573582.51\n238845.79 5568582.51 243845.79 5573582.51\n243845.79 5568582.51 248845.79 5573582.51\n1\n198845.79 5573582.51 203845.79 5578582.51\n203845.79 5573582.51 208845.79 5578582.51\n208845.79 5573582.51 213845.79 5578582.51\n213845.79 5573582.51 218845.79 5578582.51\n218845.79 5573582.51 223845.79 5578582.51\n223845.79 5573582.51 228845.79 5578582.51\n228845.79 5573582.51 233845.79 5578582.51\n233845.79 5573582.51 238845.79 5578582.51\n238845.79 5573582.51 243845.79 5578582.51\n243845.79 5573582.51 248845.79 5578582.51\n248845.79 5573582.51 253845.79 5578582.51\n253845.79 5573582.51 258845.79 5578582.51\n258845.79 5573582.51 263845.79000000004 5578582.51\n263845.79000000004 5573582.51 268845.79000000004 5578582.51\n268845.79000000004 5573582.51 273845.79000000004 5578582.51\n273845.79000000004 5573582.51 278845.79000000004 5578582.51\n278845.79000000004 5573582.51 283845.79000000004 5578582.51\n283845.79000000004 5573582.51 288845.79000000004 5578582.51\n288845.79000000004 5573582.51 293845.79000000004 5578582.51\n293845.79000000004 5573582.51 298845.79000000004 5578582.51\n298845.79000000004 5573582.51 303845.79000000004 5578582.51\n303845.79000000004 5573582.51 308845.79000000004 5578582.51\n308845.79000000004 5573582.51 313845.79000000004 5578582.51\n313845.79000000004 5573582.51 318845.79000000004 5578582.51\n318845.79000000004 5573582.51 323845.79000000004 5578582.51\n323845.79000000004 5573582.51 328845.79000000004 5578582.51\n328845.79000000004 5573582.51 333845.79000000004 5578582.51\n333845.79000000004 5573582.51 338845.79000000004 5578582.51\n338845.79000000004 5573582.51 343845.79000000004 5578582.51\n343845.79000000004 5573582.51 348845.79000000004 5578582.51\n348845.79000000004 5573582.51 353845.79000000004 5578582.51\n353845.79000000004 5573582.51 358845.79000000004 5578582.51\n358845.79000000004 5573582.51 363845.79000000004 5578582.51\n363845.79000000004 5573582.51 368845.79000000004 5578582.51\n368845.79000000004 5573582.51 373845.79000000004 5578582.51\n373845.79000000004 5573582.51 378845.79000000004 5578582.51\n378845.79000000004 5573582.51 383845.79000000004 5578582.51\n2\n198845.79 5578582.51 203845.79 5583582.51\n203845.79 5578582.51 208845.79 5583582.51\n208845.79 5578582.51 213845.79 5583582.51\n213845.79 5578582.51 218845.79 5583582.51\n218845.79 5578582.51 223845.79 5583582.51\n223845.79 5578582.51 228845.79 5583582.51\n228845.79 5578582.51 233845.79 5583582.51\n233845.79 5578582.51 238845.79 5583582.51\n238845.79 5578582.51 243845.79 5583582.51\n243845.79 5578582.51 248845.79 5583582.51\n248845.79 5578582.51 253845.79 5583582.51\n253845.79 5578582.51 258845.79 5583582.51\n258845.79 5578582.51 263845.79000000004 5583582.51\n263845.79000000004 5578582.51 268845.79000000004 5583582.51\n268845.79000000004 5578582.51 273845.79000000004 5583582.51\n273845.79000000004 5578582.51 278845.79000000004 5583582.51\n278845.79000000004 5578582.51 283845.79000000004 5583582.51\n283845.79000000004 5578582.51 288845.79000000004 5583582.51\n288845.79000000004 5578582.51 293845.79000000004 5583582.51\n293845.79000000004 5578582.51 298845.79000000004 5583582.51\n298845.79000000004 5578582.51 303845.79000000004 5583582.51\n303845.79000000004 5578582.51 308845.79000000004 5583582.51\n308845.79000000004 5578582.51 313845.79000000004 5583582.51\n313845.79000000004 5578582.51 318845.79000000004 5583582.51\n318845.79000000004 5578582.51 323845.79000000004 5583582.51\n323845.79000000004 5578582.51 328845.79000000004 5583582.51\n328845.79000000004 5578582.51 333845.79000000004 5583582.51\n333845.79000000004 5578582.51 338845.79000000004 5583582.51\n338845.79000000004 5578582.51 343845.79000000004 5583582.51\n343845.79000000004 5578582.51 348845.79000000004 5583582.51\n348845.79000000004 5578582.51 353845.79000000004 5583582.51\n353845.79000000004 5578582.51 358845.79000000004 5583582.51\n358845.79000000004 5578582.51 363845.79000000004 5583582.51\n363845.79000000004 5578582.51 368845.79000000004 5583582.51\n368845.79000000004 5578582.51 373845.79000000004 5583582.51\n373845.79000000004 5578582.51 378845.79000000004 5583582.51\n378845.79000000004 5578582.51 383845.79000000004 5583582.51\n383845.79000000004 5578582.51 388845.79000000004 5583582.51\n3\n198845.79 5583582.51 203845.79 5588582.51\n203845.79 5583582.51 208845.79 5588582.51\n208845.79 5583582.51 213845.79 5588582.51\n213845.79 5583582.51 218845.79 5588582.51\n218845.79 5583582.51 223845.79 5588582.51\n223845.79 5583582.51 228845.79 5588582.51\n228845.79 5583582.51 233845.79 5588582.51\n233845.79 5583582.51 238845.79 5588582.51\n238845.79 5583582.51 243845.79 5588582.51\n243845.79 5583582.51 248845.79 5588582.51\n248845.79 5583582.51 253845.79 5588582.51\n253845.79 5583582.51 258845.79 5588582.51\n258845.79 5583582.51 263845.79000000004 5588582.51\n263845.79000000004 5583582.51 268845.79000000004 5588582.51\n268845.79000000004 5583582.51 273845.79000000004 5588582.51\n273845.79000000004 5583582.51 278845.79000000004 5588582.51\n278845.79000000004 5583582.51 283845.79000000004 5588582.51\n283845.79000000004 5583582.51 288845.79000000004 5588582.51\n288845.79000000004 5583582.51 293845.79000000004 5588582.51\n293845.79000000004 5583582.51 298845.79000000004 5588582.51\n298845.79000000004 5583582.51 303845.79000000004 5588582.51\n303845.79000000004 5583582.51 308845.79000000004 5588582.51\n308845.79000000004 5583582.51 313845.79000000004 5588582.51\n313845.79000000004 5583582.51 318845.79000000004 5588582.51\n318845.79000000004 5583582.51 323845.79000000004 5588582.51\n323845.79000000004 5583582.51 328845.79000000004 5588582.51\n328845.79000000004 5583582.51 333845.79000000004 5588582.51\n333845.79000000004 5583582.51 338845.79000000004 5588582.51\n338845.79000000004 5583582.51 343845.79000000004 5588582.51\n343845.79000000004 5583582.51 348845.79000000004 5588582.51\n348845.79000000004 5583582.51 353845.79000000004 5588582.51\n353845.79000000004 5583582.51 358845.79000000004 5588582.51\n358845.79000000004 5583582.51 363845.79000000004 5588582.51\n363845.79000000004 5583582.51 368845.79000000004 5588582.51\n368845.79000000004 5583582.51 373845.79000000004 5588582.51\n373845.79000000004 5583582.51 378845.79000000004 5588582.51\n378845.79000000004 5583582.51 383845.79000000004 5588582.51\n383845.79000000004 5583582.51 388845.79000000004 5588582.51\n388845.79000000004 5583582.51 393845.79000000004 5588582.51\n4\n198845.79 5588582.51 203845.79 5593582.51\n203845.79 5588582.51 208845.79 5593582.51\n208845.79 5588582.51 213845.79 5593582.51\n213845.79 5588582.51 218845.79 5593582.51\n218845.79 5588582.51 223845.79 5593582.51\n223845.79 5588582.51 228845.79 5593582.51\n228845.79 5588582.51 233845.79 5593582.51\n233845.79 5588582.51 238845.79 5593582.51\n238845.79 5588582.51 243845.79 5593582.51\n243845.79 5588582.51 248845.79 5593582.51\n248845.79 5588582.51 253845.79 5593582.51\n253845.79 5588582.51 258845.79 5593582.51\n258845.79 5588582.51 263845.79000000004 5593582.51\n263845.79000000004 5588582.51 268845.79000000004 5593582.51\n268845.79000000004 5588582.51 273845.79000000004 5593582.51\n273845.79000000004 5588582.51 278845.79000000004 5593582.51\n278845.79000000004 5588582.51 283845.79000000004 5593582.51\n283845.79000000004 5588582.51 288845.79000000004 5593582.51\n288845.79000000004 5588582.51 293845.79000000004 5593582.51\n293845.79000000004 5588582.51 298845.79000000004 5593582.51\n298845.79000000004 5588582.51 303845.79000000004 5593582.51\n303845.79000000004 5588582.51 308845.79000000004 5593582.51\n308845.79000000004 5588582.51 313845.79000000004 5593582.51\n313845.79000000004 5588582.51 318845.79000000004 5593582.51\n318845.79000000004 5588582.51 323845.79000000004 5593582.51\n323845.79000000004 5588582.51 328845.79000000004 5593582.51\n328845.79000000004 5588582.51 333845.79000000004 5593582.51\n333845.79000000004 5588582.51 338845.79000000004 5593582.51\n338845.79000000004 5588582.51 343845.79000000004 5593582.51\n343845.79000000004 5588582.51 348845.79000000004 5593582.51\n348845.79000000004 5588582.51 353845.79000000004 5593582.51\n353845.79000000004 5588582.51 358845.79000000004 5593582.51\n358845.79000000004 5588582.51 363845.79000000004 5593582.51\n363845.79000000004 5588582.51 368845.79000000004 5593582.51\n368845.79000000004 5588582.51 373845.79000000004 5593582.51\n373845.79000000004 5588582.51 378845.79000000004 5593582.51\n378845.79000000004 5588582.51 383845.79000000004 5593582.51\n383845.79000000004 5588582.51 388845.79000000004 5593582.51\n388845.79000000004 5588582.51 393845.79000000004 5593582.51\n393845.79000000004 5588582.51 398845.79000000004 5593582.51\n5\n198845.79 5593582.51 203845.79 5598582.51\n203845.79 5593582.51 208845.79 5598582.51\n208845.79 5593582.51 213845.79 5598582.51\n213845.79 5593582.51 218845.79 5598582.51\n218845.79 5593582.51 223845.79 5598582.51\n223845.79 5593582.51 228845.79 5598582.51\n228845.79 5593582.51 233845.79 5598582.51\n233845.79 5593582.51 238845.79 5598582.51\n238845.79 5593582.51 243845.79 5598582.51\n243845.79 5593582.51 248845.79 5598582.51\n248845.79 5593582.51 253845.79 5598582.51\n253845.79 5593582.51 258845.79 5598582.51\n258845.79 5593582.51 263845.79000000004 5598582.51\n263845.79000000004 5593582.51 268845.79000000004 5598582.51\n268845.79000000004 5593582.51 273845.79000000004 5598582.51\n273845.79000000004 5593582.51 278845.79000000004 5598582.51\n278845.79000000004 5593582.51 283845.79000000004 5598582.51\n283845.79000000004 5593582.51 288845.79000000004 5598582.51\n288845.79000000004 5593582.51 293845.79000000004 5598582.51\n293845.79000000004 5593582.51 298845.79000000004 5598582.51\n298845.79000000004 5593582.51 303845.79000000004 5598582.51\n303845.79000000004 5593582.51 308845.79000000004 5598582.51\n308845.79000000004 5593582.51 313845.79000000004 5598582.51\n313845.79000000004 5593582.51 318845.79000000004 5598582.51\n318845.79000000004 5593582.51 323845.79000000004 5598582.51\n323845.79000000004 5593582.51 328845.79000000004 5598582.51\n328845.79000000004 5593582.51 333845.79000000004 5598582.51\n333845.79000000004 5593582.51 338845.79000000004 5598582.51\n338845.79000000004 5593582.51 343845.79000000004 5598582.51\n343845.79000000004 5593582.51 348845.79000000004 5598582.51\n348845.79000000004 5593582.51 353845.79000000004 5598582.51\n353845.79000000004 5593582.51 358845.79000000004 5598582.51\n358845.79000000004 5593582.51 363845.79000000004 5598582.51\n363845.79000000004 5593582.51 368845.79000000004 5598582.51\n368845.79000000004 5593582.51 373845.79000000004 5598582.51\n"
],
[
"sagrav_test",
"_____no_output_____"
],
[
"survey_array_test = sagrav_test[['LONGITUDE','LATITUDE','AHD_ELEVAT','BA_1984_UM']].to_numpy()\nprint(survey_array_test.shape)\ndobs_test = survey_array_test\nreceiver_locations_test = dobs_test[:, 0:3]\ndobs_test = dobs_test[:, -1]",
"(4, 4)\n"
],
[
"# Plot\nmpl.rcParams.update({\"font.size\": 12})\nfig = plt.figure(figsize=(7, 5))\n\nax1 = fig.add_axes([0.1, 0.1, 0.73, 0.85])\nplot2Ddata(receiver_locations_test, dobs_test, ax=ax1, contourOpts={\"cmap\": \"bwr\"})\nax1.set_title(\"Gravity Anomaly\")\nax1.set_xlabel(\"x (m)\")\nax1.set_ylabel(\"y (m)\")\n\nax2 = fig.add_axes([0.8, 0.1, 0.03, 0.85])\nnorm = mpl.colors.Normalize(vmin=-np.max(np.abs(dobs_test)), vmax=np.max(np.abs(dobs_test)))\ncbar = mpl.colorbar.ColorbarBase(\n ax2, norm=norm, orientation=\"vertical\", cmap=mpl.cm.bwr, format=\"%.1e\"\n)\ncbar.set_label(\"$mgal$\", rotation=270, labelpad=15, size=12)\n\nplt.show()",
"_____no_output_____"
],
[
"dobs_test.shape",
"_____no_output_____"
],
[
"sagrav_test",
"_____no_output_____"
],
[
"maximum_anomaly = np.max(np.abs(dobs_test))\n\nuncertainties = 0.01 * maximum_anomaly * np.ones(np.shape(dobs_test)) ",
"_____no_output_____"
],
[
"print(i)",
"90\n"
],
[
"# Define the receivers. The data consist of vertical gravity anomaly measurements.\n# The set of receivers must be defined as a list.\nreceiver_list = gravity.receivers.Point(receiver_locations_test, components=\"gz\")\n\nreceiver_list = [receiver_list]\n\n# Define the source field\nsource_field = gravity.sources.SourceField(receiver_list=receiver_list)\n\n# Define the survey\nsurvey = gravity.survey.Survey(source_field)",
"_____no_output_____"
],
[
"receiver_list",
"_____no_output_____"
],
[
"data_object = data.Data(survey, dobs=dobs_test, standard_deviation=uncertainties)",
"_____no_output_____"
],
[
"data_object",
"_____no_output_____"
],
[
"mesh2\n#source_field",
"_____no_output_____"
],
[
"# Define density contrast values for each unit in g/cc. Don't make this 0!\n# Otherwise the gradient for the 1st iteration is zero and the inversion will\n# not converge.\nbackground_density = 1e-6\n\n# Find the indecies of the active cells in forward model (ones below surface)\n#ind_active = surface2ind_topo(mesh, xyz_topo)\ntopo_fake = receiver_locations_test + 399\nprint(receiver_locations_test)\nprint(topo_fake)\nind_active = surface2ind_topo(mesh2, receiver_locations_test)\n#ind_active = surface2ind_topo(mesh2, topo_fake)\n#ind_active = surface2ind_topo(mesh2, topo_fake)\n\n# Define mapping from model to active cells\nnC = int(ind_active.sum())\nmodel_map = maps.IdentityMap(nP=nC) # model consists of a value for each active cell\n\n# Define and plot starting model\nstarting_model = background_density * np.ones(nC)",
"[[138.0431963 -35.8991295 39.99000168]\n [138.0314963 -35.8999395 41.97000122]\n [138.0331963 -35.9009295 44.84000015]\n [138.0350963 -35.9004395 40.36000061]]\n[[537.0431963 363.1008705 438.99000168]\n [537.0314963 363.1000605 440.97000122]\n [537.0331963 363.0990705 443.84000015]\n [537.0350963 363.0995605 439.36000061]]\n"
],
[
"nC",
"_____no_output_____"
],
[
"model_map",
"_____no_output_____"
],
[
"ind_active",
"_____no_output_____"
],
[
"starting_model",
"_____no_output_____"
],
[
"simulation = gravity.simulation.Simulation3DIntegral(\n survey=survey, mesh=mesh2, rhoMap=model_map, actInd=ind_active\n)",
"_____no_output_____"
],
[
"# Define the data misfit. Here the data misfit is the L2 norm of the weighted\n# residual between the observed data and the data predicted for a given model.\n# Within the data misfit, the residual between predicted and observed data are\n# normalized by the data's standard deviation.\ndmis = data_misfit.L2DataMisfit(data=data_object, simulation=simulation)\n\n# Define the regularization (model objective function).\nreg = regularization.Simple(mesh2, indActive=ind_active, mapping=model_map)\n\n# Define how the optimization problem is solved. Here we will use a projected\n# Gauss-Newton approach that employs the conjugate gradient solver.\nopt = optimization.ProjectedGNCG(\n maxIter=10, lower=-1.0, upper=1.0, maxIterLS=20, maxIterCG=10, tolCG=1e-3\n)\n\n# Here we define the inverse problem that is to be solved\ninv_prob = inverse_problem.BaseInvProblem(dmis, reg, opt)",
"_____no_output_____"
],
[
"dmis.nD",
"_____no_output_____"
],
[
"# Defining a starting value for the trade-off parameter (beta) between the data\n# misfit and the regularization.\nstarting_beta = directives.BetaEstimate_ByEig(beta0_ratio=1e0)\n\n# Defining the fractional decrease in beta and the number of Gauss-Newton solves\n# for each beta value.\nbeta_schedule = directives.BetaSchedule(coolingFactor=5, coolingRate=1)\n\n# Options for outputting recovered models and predicted data for each beta.\nsave_iteration = directives.SaveOutputEveryIteration(save_txt=False)\n\n# Updating the preconditionner if it is model dependent.\nupdate_jacobi = directives.UpdatePreconditioner()\n\n# Setting a stopping criteria for the inversion.\ntarget_misfit = directives.TargetMisfit(chifact=1)\n\n# Add sensitivity weights\nsensitivity_weights = directives.UpdateSensitivityWeights(everyIter=False)\n\n# The directives are defined as a list.\ndirectives_list = [\n sensitivity_weights,\n starting_beta,\n beta_schedule,\n save_iteration,\n update_jacobi,\n target_misfit,\n] ",
"_____no_output_____"
],
[
"# Here we combine the inverse problem and the set of directives\ninv = inversion.BaseInversion(inv_prob, directives_list)\n\n# Run inversion\nrecovered_model = inv.run(starting_model)",
"SimPEG.InvProblem will set Regularization.mref to m0.\n\n SimPEG.InvProblem is setting bfgsH0 to the inverse of the eval2Deriv.\n ***Done using same Solver and solverOpts as the problem***\nmodel has any nan: 0\n=============================== Projected GNCG ===============================\n # beta phi_d phi_m f |proj(x-g)-x| LS Comment \n-----------------------------------------------------------------------------\nx0 has any nan: 0\n 0 4.81e-21 1.91e+04 0.00e+00 1.91e+04 4.18e-07 0 \n------------------------- STOP! -------------------------\n0 : |fc-fOld| = 1.0000e+00 <= tolF*(1+|f0|) = 0.0000e+00\n0 : |xc-x_last| = 1.0000e+00 <= tolX*(1+|x0|) = 0.0000e+00\n1 : |proj(x-g)-x| = 4.1762e-07 <= tolG = 1.0000e-01\n1 : |proj(x-g)-x| = 4.1762e-07 <= 1e3*eps = 1.0000e-02\n0 : maxIter = 10 <= iter = 0\n------------------------- DONE! -------------------------\n"
],
[
"\n# Plot Recovered Model\nfig = plt.figure(figsize=(9, 4))\nplotting_map = maps.InjectActiveCells(mesh2, ind_active, np.nan)\n\nax1 = fig.add_axes([0.1, 0.1, 0.73, 0.8])\n#ax1 = fig.add_axes([10.1, 10.1, 73.73, 80.8])\nmesh2.plotSlice(\n plotting_map * recovered_model,\n normal=\"Y\",\n ax=ax1,\n ind=int(mesh2.nCy / 2),\n grid=True,\n clim=(np.min(recovered_model), np.max(recovered_model)),\n pcolorOpts={\"cmap\": \"viridis\"},\n)\nax1.set_title(\"Model slice at y = 0 m\")\n\nax2 = fig.add_axes([0.85, 0.1, 0.05, 0.8])\nnorm = mpl.colors.Normalize(vmin=np.min(recovered_model), vmax=np.max(recovered_model))\ncbar = mpl.colorbar.ColorbarBase(\n ax2, norm=norm, orientation=\"vertical\", cmap=mpl.cm.viridis\n)\ncbar.set_label(\"$g/cm^3$\", rotation=270, labelpad=15, size=12)\n\nplt.show()",
"_____no_output_____"
],
[
"dpred = inv_prob.dpred\n\n# Observed data | Predicted data | Normalized data misfit\ndata_array = np.c_[dobs_test, dpred, (dobs_test - dpred) / uncertainties]\n\nfig = plt.figure(figsize=(17, 4))\nplot_title = [\"Observed\", \"Predicted\", \"Normalized Misfit\"]\nplot_units = [\"mgal\", \"mgal\", \"\"]\n\nax1 = 3 * [None]\nax2 = 3 * [None]\nnorm = 3 * [None]\ncbar = 3 * [None]\ncplot = 3 * [None]\nv_lim = [np.max(np.abs(dobs)), np.max(np.abs(dobs)), np.max(np.abs(data_array[:, 2]))]\n\nfor ii in range(0, 3):\n\n ax1[ii] = fig.add_axes([0.33 * ii + 0.03, 0.11, 0.23, 0.84])\n cplot[ii] = plot2Ddata(\n receiver_list[0].locations,\n data_array[:, ii],\n ax=ax1[ii],\n ncontour=30,\n clim=(-v_lim[ii], v_lim[ii]),\n contourOpts={\"cmap\": \"bwr\"},\n )\n ax1[ii].set_title(plot_title[ii])\n ax1[ii].set_xlabel(\"x (m)\")\n ax1[ii].set_ylabel(\"y (m)\")\n\n ax2[ii] = fig.add_axes([0.33 * ii + 0.25, 0.11, 0.01, 0.85])\n norm[ii] = mpl.colors.Normalize(vmin=-v_lim[ii], vmax=v_lim[ii])\n cbar[ii] = mpl.colorbar.ColorbarBase(\n ax2[ii], norm=norm[ii], orientation=\"vertical\", cmap=mpl.cm.bwr\n )\n cbar[ii].set_label(plot_units[ii], rotation=270, labelpad=15, size=12)\n\nplt.show()\n",
"_____no_output_____"
],
[
"dpred",
"_____no_output_____"
],
[
"data_source = \"https://storage.googleapis.com/simpeg/doc-assets/gravity.tar.gz\"\n\n# download the data\ndownloaded_data = utils.download(data_source, overwrite=True)\n\n# unzip the tarfile\ntar = tarfile.open(downloaded_data, \"r\")\ntar.extractall()\ntar.close()\n\n# path to the directory containing our data\ndir_path = downloaded_data.split(\".\")[0] + os.path.sep\n\n# files to work with\ntopo_filename = dir_path + \"gravity_topo.txt\"\ndata_filename = dir_path + \"gravity_data.obs\"\nmodel_filename = dir_path + \"true_model.txt\"",
"Downloading https://storage.googleapis.com/simpeg/doc-assets/gravity.tar.gz\n saved to: C:\\Users\\rscott\\OneDrive - OZ Minerals\\Exploration2021\\Invert-the-Gawler\\gravity.tar.gz\nDownload completed!\n"
],
[
"xyz_topo = np.loadtxt(str(topo_filename))\n",
"_____no_output_____"
],
[
"xyz_topo.shape",
"_____no_output_____"
],
[
"xyzdobs = np.loadtxt(str(data_filename))",
"_____no_output_____"
],
[
"xyzdobs.shape",
"_____no_output_____"
],
[
"xyz_topo[1]",
"_____no_output_____"
],
[
"xyzdobs[0]",
"_____no_output_____"
],
[
"xyzdobs",
"_____no_output_____"
],
[
"sagrav_test",
"_____no_output_____"
],
[
"dobs_test",
"_____no_output_____"
],
[
"survey_array_test[0]",
"_____no_output_____"
],
[
"receiver_locations_test[0]",
"_____no_output_____"
],
[
"print(survey)",
"<SimPEG.potential_fields.gravity.survey.Survey object at 0x00000229CADFAA88>\n"
],
[
"survey.nD",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"data.noise_floor",
"_____no_output_____"
],
[
"mesh2",
"_____no_output_____"
],
[
"xyzdobs",
"_____no_output_____"
],
[
"recovered_model",
"_____no_output_____"
],
[
"from SimPEG.utils import plot2Ddata, surface2ind_topo",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd6e5b73d83a050da270e5e986faa3c6bd3030e
| 2,489 |
ipynb
|
Jupyter Notebook
|
archive/Untitled5.ipynb
|
KailongPeng/rtSynth
|
e0d45dc68cba259a1308842a584435e04b77858a
|
[
"Apache-2.0"
] | null | null | null |
archive/Untitled5.ipynb
|
KailongPeng/rtSynth
|
e0d45dc68cba259a1308842a584435e04b77858a
|
[
"Apache-2.0"
] | null | null | null |
archive/Untitled5.ipynb
|
KailongPeng/rtSynth
|
e0d45dc68cba259a1308842a584435e04b77858a
|
[
"Apache-2.0"
] | null | null | null | 19.294574 | 73 | 0.522298 |
[
[
[
"import os\nos.chdir(\"/gpfs/milgram/project/turk-browne/projects/rtTest/\")\n!pwd\nimport subprocess",
"/gpfs/milgram/pi/turk-browne/projects/rtTest\r\n"
],
[
"# call(f\"sbatch class.sh {tmpFile}\",shell=True)\n\n\nproc = subprocess.Popen(['sbatch class.sh'],shell=True)\n# proc.wait()\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cbd6eae04e4c927d9022a4e25a181174f15cef5a
| 140,595 |
ipynb
|
Jupyter Notebook
|
movie_recommender/movie_recommendation_using_KNN.ipynb
|
KevinLiao159/ApiForDataScience
|
daf35dd650142edb73bcdd62d66f75e8d0f1b296
|
[
"MIT"
] | 320 |
2018-09-29T18:36:44.000Z
|
2022-03-28T22:25:46.000Z
|
movie_recommender/movie_recommendation_using_KNN.ipynb
|
KevinLiao159/ApiForDataScience
|
daf35dd650142edb73bcdd62d66f75e8d0f1b296
|
[
"MIT"
] | 3 |
2019-01-24T15:24:21.000Z
|
2020-03-31T05:58:28.000Z
|
movie_recommender/movie_recommendation_using_KNN.ipynb
|
KevinLiao159/ApiForDataScience
|
daf35dd650142edb73bcdd62d66f75e8d0f1b296
|
[
"MIT"
] | 258 |
2018-11-12T00:32:12.000Z
|
2022-03-13T22:55:50.000Z
| 87.981852 | 29,332 | 0.80064 |
[
[
[
"# Overview\n\nIn this project, I will build an item-based collaborative filtering system using [MovieLens Datasets](https://grouplens.org/datasets/movielens/latest/). Specically, I will train a KNN models to cluster similar movies based on user's ratings and make movie recommendation based on similarity score of previous rated movies. \n\n\n## [Recommender system](https://en.wikipedia.org/wiki/Recommender_system)\nA recommendation system is basically an information filtering system that seeks to predict the \"rating\" or \"preference\" a user would give to an item. It is widely used in different internet / online business such as Amazon, Netflix, Spotify, or social media like Facebook and Youtube. By using recommender systems, those companies are able to provide better or more suited products/services/contents that are personalized to a user based on his/her historical consumer behaviors\n\nRecommender systems typically produce a list of recommendations through collaborative filtering or through content-based filtering\n\nThis project will focus on collaborative filtering and use item-based collaborative filtering systems make movie recommendation\n\n\n## [Item-based Collaborative Filtering](https://beckernick.github.io/music_recommender/)\nCollaborative filtering based systems use the actions of users to recommend other items. In general, they can either be user based or item based. User based collaborating filtering uses the patterns of users similar to me to recommend a product (users like me also looked at these other items). Item based collaborative filtering uses the patterns of users who browsed the same item as me to recommend me a product (users who looked at my item also looked at these other items). Item-based approach is usually prefered than user-based approach. User-based approach is often harder to scale because of the dynamic nature of users, whereas items usually don't change much, so item-based approach often can be computed offline.\n\n\n## Data Sets\nI use [MovieLens Datasets](https://grouplens.org/datasets/movielens/latest/).\nThis dataset (ml-latest.zip) describes 5-star rating and free-text tagging activity from [MovieLens](http://movielens.org), a movie recommendation service. It contains 27753444 ratings and 1108997 tag applications across 58098 movies. These data were created by 283228 users between January 09, 1995 and September 26, 2018. This dataset was generated on September 26, 2018.\n\nUsers were selected at random for inclusion. All selected users had rated at least 1 movies. No demographic information is included. Each user is represented by an id, and no other information is provided.\n\nThe data are contained in the files `genome-scores.csv`, `genome-tags.csv`, `links.csv`, `movies.csv`, `ratings.csv` and `tags.csv`.\n\n## Project Content\n1. Load data\n2. Exploratory data analysis\n3. Train KNN model for item-based collaborative filtering\n4. Use this trained model to make movie recommendations to myself\n5. Deep dive into the bottleneck of item-based collaborative filtering.\n - cold start problem\n - data sparsity problem\n - popular bias (how to recommend products from the tail of product distribution)\n - scalability bottleneck\n6. Further study",
"_____no_output_____"
]
],
[
[
"import os\nimport time\n\n# data science imports\nimport math\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse import csr_matrix\nfrom sklearn.neighbors import NearestNeighbors\n\n# utils import\nfrom fuzzywuzzy import fuzz\n\n# visualization imports\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\n%matplotlib inline",
"/opt/conda/lib/python3.6/site-packages/fuzzywuzzy/fuzz.py:11: UserWarning: Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning\n warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning')\n"
],
[
"# path config\ndata_path = os.path.join(os.environ['DATA_PATH'], 'MovieLens')\nmovies_filename = 'movies.csv'\nratings_filename = 'ratings.csv'",
"_____no_output_____"
]
],
[
[
"## 1. Load Data",
"_____no_output_____"
]
],
[
[
"df_movies = pd.read_csv(\n os.path.join(data_path, movies_filename),\n usecols=['movieId', 'title'],\n dtype={'movieId': 'int32', 'title': 'str'})\n\ndf_ratings = pd.read_csv(\n os.path.join(data_path, ratings_filename),\n usecols=['userId', 'movieId', 'rating'],\n dtype={'userId': 'int32', 'movieId': 'int32', 'rating': 'float32'})",
"_____no_output_____"
],
[
"df_movies.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 58098 entries, 0 to 58097\nData columns (total 2 columns):\nmovieId 58098 non-null int32\ntitle 58098 non-null object\ndtypes: int32(1), object(1)\nmemory usage: 680.9+ KB\n"
],
[
"df_ratings.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 27753444 entries, 0 to 27753443\nData columns (total 3 columns):\nuserId int32\nmovieId int32\nrating float32\ndtypes: float32(1), int32(2)\nmemory usage: 317.6 MB\n"
],
[
"df_movies.head()",
"_____no_output_____"
],
[
"df_ratings.head()",
"_____no_output_____"
],
[
"num_users = len(df_ratings.userId.unique())\nnum_items = len(df_ratings.movieId.unique())\nprint('There are {} unique users and {} unique movies in this data set'.format(num_users, num_items))",
"There are 283228 unique users and 53889 unique movies in this data set\n"
]
],
[
[
"## 2. Exploratory data analysis\n - Plot the counts of each rating\n - Plot rating frequency of each movie",
"_____no_output_____"
],
[
"#### 1. Plot the counts of each rating",
"_____no_output_____"
],
[
"we first need to get the counts of each rating from ratings data",
"_____no_output_____"
]
],
[
[
"# get count\ndf_ratings_cnt_tmp = pd.DataFrame(df_ratings.groupby('rating').size(), columns=['count'])\ndf_ratings_cnt_tmp",
"_____no_output_____"
]
],
[
[
"We can see that above table does not include counts of zero rating score. So we need to add that in rating count dataframe as well",
"_____no_output_____"
]
],
[
[
"# there are a lot more counts in rating of zero\ntotal_cnt = num_users * num_items\nrating_zero_cnt = total_cnt - df_ratings.shape[0]\n# append counts of zero rating to df_ratings_cnt\ndf_ratings_cnt = df_ratings_cnt_tmp.append(\n pd.DataFrame({'count': rating_zero_cnt}, index=[0.0]),\n verify_integrity=True,\n).sort_index()\ndf_ratings_cnt",
"_____no_output_____"
]
],
[
[
"The count for zero rating score is too big to compare with others. So let's take log transform for count values and then we can plot them to compare",
"_____no_output_____"
]
],
[
[
"# add log count\ndf_ratings_cnt['log_count'] = np.log(df_ratings_cnt['count'])\ndf_ratings_cnt",
"_____no_output_____"
],
[
"ax = df_ratings_cnt[['count']].reset_index().rename(columns={'index': 'rating score'}).plot(\n x='rating score',\n y='count',\n kind='bar',\n figsize=(12, 8),\n title='Count for Each Rating Score (in Log Scale)',\n logy=True,\n fontsize=12,\n)\nax.set_xlabel(\"movie rating score\")\nax.set_ylabel(\"number of ratings\")",
"_____no_output_____"
]
],
[
[
"It's interesting that there are more people giving rating score of 3 and 4 than other scores ",
"_____no_output_____"
],
[
"#### 2. Plot rating frequency of all movies",
"_____no_output_____"
]
],
[
[
"df_ratings.head()",
"_____no_output_____"
],
[
"# get rating frequency\ndf_movies_cnt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count'])\ndf_movies_cnt.head()",
"_____no_output_____"
],
[
"# plot rating frequency of all movies\nax = df_movies_cnt \\\n .sort_values('count', ascending=False) \\\n .reset_index(drop=True) \\\n .plot(\n figsize=(12, 8),\n title='Rating Frequency of All Movies',\n fontsize=12\n )\nax.set_xlabel(\"movie Id\")\nax.set_ylabel(\"number of ratings\")",
"_____no_output_____"
]
],
[
[
"The distribution of ratings among movies often satisfies a property in real-world settings,\nwhich is referred to as the long-tail property. According to this property, only a small\nfraction of the items are rated frequently. Such items are referred to as popular items. The\nvast majority of items are rated rarely. This results in a highly skewed distribution of the\nunderlying ratings.",
"_____no_output_____"
],
[
"Let's plot the same distribution but with log scale",
"_____no_output_____"
]
],
[
[
"# plot rating frequency of all movies in log scale\nax = df_movies_cnt \\\n .sort_values('count', ascending=False) \\\n .reset_index(drop=True) \\\n .plot(\n figsize=(12, 8),\n title='Rating Frequency of All Movies (in Log Scale)',\n fontsize=12,\n logy=True\n )\nax.set_xlabel(\"movie Id\")\nax.set_ylabel(\"number of ratings (log scale)\")",
"_____no_output_____"
]
],
[
[
"We can see that roughly 10,000 out of 53,889 movies are rated more than 100 times. More interestingly, roughly 20,000 out of 53,889 movies are rated less than only 10 times. Let's look closer by displaying top quantiles of rating counts",
"_____no_output_____"
]
],
[
[
"df_movies_cnt['count'].quantile(np.arange(1, 0.6, -0.05))",
"_____no_output_____"
]
],
[
[
"So about 1% of movies have roughly 97,999 or more ratings, 5% have 1,855 or more, and 20% have 100 or more. Since we have so many movies, we'll limit it to the top 25%. This is arbitrary threshold for popularity, but it gives us about 13,500 different movies. We still have pretty good amount of movies for modeling. There are two reasons why we want to filter to roughly 13,500 movies in our dataset.\n - Memory issue: we don't want to run into the “MemoryError” during model training\n - Improve KNN performance: lesser known movies have ratings from fewer viewers, making the pattern more noisy. Droping out less known movies can improve recommendation quality",
"_____no_output_____"
]
],
[
[
"# filter data\npopularity_thres = 50\npopular_movies = list(set(df_movies_cnt.query('count >= @popularity_thres').index))\ndf_ratings_drop_movies = df_ratings[df_ratings.movieId.isin(popular_movies)]\nprint('shape of original ratings data: ', df_ratings.shape)\nprint('shape of ratings data after dropping unpopular movies: ', df_ratings_drop_movies.shape)",
"shape of original ratings data: (27753444, 3)\nshape of ratings data after dropping unpopular movies: (27430748, 3)\n"
]
],
[
[
"After dropping 75% of movies in our dataset, we still have a very large dataset. So next we can filter users to further reduce the size of data",
"_____no_output_____"
]
],
[
[
"# get number of ratings given by every user\ndf_users_cnt = pd.DataFrame(df_ratings_drop_movies.groupby('userId').size(), columns=['count'])\ndf_users_cnt.head()",
"_____no_output_____"
],
[
"# plot rating frequency of all movies\nax = df_users_cnt \\\n .sort_values('count', ascending=False) \\\n .reset_index(drop=True) \\\n .plot(\n figsize=(12, 8),\n title='Rating Frequency of All Users',\n fontsize=12\n )\nax.set_xlabel(\"user Id\")\nax.set_ylabel(\"number of ratings\")",
"_____no_output_____"
],
[
"df_users_cnt['count'].quantile(np.arange(1, 0.5, -0.05))",
"_____no_output_____"
]
],
[
[
"We can see that the distribution of ratings by users is very similar to the distribution of ratings among movies. They both have long-tail property. Only a very small fraction of users are very actively engaged with rating movies that they watched. Vast majority of users aren't interested in rating movies. So we can limit users to the top 40%, which is about 113,291 users.",
"_____no_output_____"
]
],
[
[
"# filter data\nratings_thres = 50\nactive_users = list(set(df_users_cnt.query('count >= @ratings_thres').index))\ndf_ratings_drop_users = df_ratings_drop_movies[df_ratings_drop_movies.userId.isin(active_users)]\nprint('shape of original ratings data: ', df_ratings.shape)\nprint('shape of ratings data after dropping both unpopular movies and inactive users: ', df_ratings_drop_users.shape)",
"shape of original ratings data: (27753444, 3)\nshape of ratings data after dropping both unpopular movies and inactive users: (24178982, 3)\n"
]
],
[
[
"## 3. Train KNN model for item-based collaborative filtering\n - Reshaping the Data\n - Fitting the Model",
"_____no_output_____"
],
[
"#### 1. Reshaping the Data\nFor K-Nearest Neighbors, we want the data to be in an (artist, user) array, where each row is a movie and each column is a different user. To reshape the dataframe, we'll pivot the dataframe to the wide format with movies as rows and users as columns. Then we'll fill the missing observations with 0s since we're going to be performing linear algebra operations (calculating distances between vectors). Finally, we transform the values of the dataframe into a scipy sparse matrix for more efficient calculations.",
"_____no_output_____"
]
],
[
[
"# pivot and create movie-user matrix\nmovie_user_mat = df_ratings_drop_users.pivot(index='movieId', columns='userId', values='rating').fillna(0)\n# create mapper from movie title to index\nmovie_to_idx = {\n movie: i for i, movie in \n enumerate(list(df_movies.set_index('movieId').loc[movie_user_mat.index].title))\n}\n# transform matrix to scipy sparse matrix\nmovie_user_mat_sparse = csr_matrix(movie_user_mat.values)",
"_____no_output_____"
]
],
[
[
"#### 2. Fitting the Model\nTime to implement the model. We'll initialize the NearestNeighbors class as model_knn and fit our sparse matrix to the instance. By specifying the metric = cosine, the model will measure similarity bectween artist vectors by using cosine similarity.",
"_____no_output_____"
]
],
[
[
"%env JOBLIB_TEMP_FOLDER=/tmp\n# define model\nmodel_knn = NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=20, n_jobs=-1)\n# fit\nmodel_knn.fit(movie_user_mat_sparse)",
"env: JOBLIB_TEMP_FOLDER=/tmp\n"
]
],
[
[
"## 4. Use this trained model to make movie recommendations to myself\nAnd we're finally ready to make some recommendations!",
"_____no_output_____"
]
],
[
[
"def fuzzy_matching(mapper, fav_movie, verbose=True):\n \"\"\"\n return the closest match via fuzzy ratio. If no match found, return None\n \n Parameters\n ---------- \n mapper: dict, map movie title name to index of the movie in data\n\n fav_movie: str, name of user input movie\n \n verbose: bool, print log if True\n\n Return\n ------\n index of the closest match\n \"\"\"\n match_tuple = []\n # get match\n for title, idx in mapper.items():\n ratio = fuzz.ratio(title.lower(), fav_movie.lower())\n if ratio >= 60:\n match_tuple.append((title, idx, ratio))\n # sort\n match_tuple = sorted(match_tuple, key=lambda x: x[2])[::-1]\n if not match_tuple:\n print('Oops! No match is found')\n return\n if verbose:\n print('Found possible matches in our database: {0}\\n'.format([x[0] for x in match_tuple]))\n return match_tuple[0][1]\n\n\n\ndef make_recommendation(model_knn, data, mapper, fav_movie, n_recommendations):\n \"\"\"\n return top n similar movie recommendations based on user's input movie\n\n\n Parameters\n ----------\n model_knn: sklearn model, knn model\n\n data: movie-user matrix\n\n mapper: dict, map movie title name to index of the movie in data\n\n fav_movie: str, name of user input movie\n\n n_recommendations: int, top n recommendations\n\n Return\n ------\n list of top n similar movie recommendations\n \"\"\"\n # fit\n model_knn.fit(data)\n # get input movie index\n print('You have input movie:', fav_movie)\n idx = fuzzy_matching(mapper, fav_movie, verbose=True)\n # inference\n print('Recommendation system start to make inference')\n print('......\\n')\n distances, indices = model_knn.kneighbors(data[idx], n_neighbors=n_recommendations+1)\n # get list of raw idx of recommendations\n raw_recommends = \\\n sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1]\n # get reverse mapper\n reverse_mapper = {v: k for k, v in mapper.items()}\n # print recommendations\n print('Recommendations for {}:'.format(fav_movie))\n for i, (idx, dist) in enumerate(raw_recommends):\n print('{0}: {1}, with distance of {2}'.format(i+1, reverse_mapper[idx], dist))",
"_____no_output_____"
],
[
"my_favorite = 'Iron Man'\n\nmake_recommendation(\n model_knn=model_knn,\n data=movie_user_mat_sparse,\n fav_movie=my_favorite,\n mapper=movie_to_idx,\n n_recommendations=10)",
"You have input movie: Iron Man\nFound possible matches in our database: ['Iron Man (2008)', 'Iron Man 3 (2013)', 'Iron Man 2 (2010)']\n\nRecommendation system start to make inference\n......\n\nRecommendations for Iron Man:\n1: Bourne Ultimatum, The (2007), with distance of 0.4217848777770996\n2: Sherlock Holmes (2009), with distance of 0.4190899133682251\n3: Inception (2010), with distance of 0.39293038845062256\n4: Avatar (2009), with distance of 0.38322633504867554\n5: WALL·E (2008), with distance of 0.38314002752304077\n6: Star Trek (2009), with distance of 0.37503182888031006\n7: Batman Begins (2005), with distance of 0.3701704144477844\n8: Iron Man 2 (2010), with distance of 0.37011009454727173\n9: Avengers, The (2012), with distance of 0.3579972982406616\n10: Dark Knight, The (2008), with distance of 0.3010351061820984\n"
]
],
[
[
"This is very interesting that my **KNN** model recommends movies that were also produced in very similar years. However, the cosine distance of all those recommendations are actually quite small. This is probabily because there is too many zero values in our movie-user matrix. With too many zero values in our data, the data sparsity becomes a real issue for **KNN** model and the distance in **KNN** model starts to fall apart. So I'd like to dig deeper and look closer inside our data.",
"_____no_output_____"
],
[
"#### (extra inspection) \nLet's now look at how sparse the movie-user matrix is by calculating percentage of zero values in the data.",
"_____no_output_____"
]
],
[
[
"# calcuate total number of entries in the movie-user matrix\nnum_entries = movie_user_mat.shape[0] * movie_user_mat.shape[1]\n# calculate total number of entries with zero values\nnum_zeros = (movie_user_mat==0).sum(axis=1).sum()\n# calculate ratio of number of zeros to number of entries\nratio_zeros = num_zeros / num_entries\nprint('There is about {:.2%} of ratings in our data is missing'.format(ratio_zeros))",
"There is about 98.35% of ratings in our data is missing\n"
]
],
[
[
"This result confirms my hypothesis. The vast majority of entries in our data is zero. This explains why the distance between similar items or opposite items are both pretty large.",
"_____no_output_____"
],
[
"## 5. Deep dive into the bottleneck of item-based collaborative filtering.\n - cold start problem\n - data sparsity problem\n - popular bias (how to recommend products from the tail of product distribution)\n - scalability bottleneck",
"_____no_output_____"
],
[
"We saw there is 98.35% of user-movie interactions are not yet recorded, even after I filtered out less-known movies and inactive users. Apparently, we don't even have sufficient information for the system to make reliable inferences for users or items. This is called **Cold Start** problem in recommender system.\n\nThere are three cases of cold start:\n\n1. New community: refers to the start-up of the recommender, when, although a catalogue of items might exist, almost no users are present and the lack of user interaction makes very hard to provide reliable recommendations\n2. New item: a new item is added to the system, it might have some content information but no interactions are present\n3. New user: a new user registers and has not provided any interaction yet, therefore it is not possible to provide personalized recommendations\n\nWe are not concerned with the last one because we can use item-based filtering to make recommendations for new user. In our case, we are more concerned with the first two cases, especially the second case.\n\nThe item cold-start problem refers to when items added to the catalogue have either none or very little interactions. This constitutes a problem mainly for collaborative filtering algorithms due to the fact that they rely on the item's interactions to make recommendations. If no interactions are available then a pure collaborative algorithm cannot recommend the item. In case only a few interactions are available, although a collaborative algorithm will be able to recommend it, the quality of those recommendations will be poor. This arises another issue, which is not anymore related to new items, but rather to unpopular items. In some cases (e.g. movie recommendations) it might happen that a handful of items receive an extremely high number of iteractions, while most of the items only receive a fraction of them. This is also referred to as popularity bias. Please recall previous long-tail skewed distribution of movie rating frequency plot.\n\nIn addtition to that, scalability is also a big issue in KNN model too. Its time complexity is O(nd + kn), where n is the cardinality of the training set and d the dimension of each sample. And KNN takes more time in making inference than training, which increase the prediction latency",
"_____no_output_____"
],
[
"## 6. Further study\n\nUse spark's ALS to solve above problems",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cbd6f99b5a25904ffd4ec32889843917c7634ca6
| 4,766 |
ipynb
|
Jupyter Notebook
|
Notebook/TFLite.ipynb
|
deepchecks/url_classification_dl
|
029fddb78e019cf288adcc2fd46be3435536d469
|
[
"CC0-1.0"
] | 3 |
2021-05-22T09:20:54.000Z
|
2022-03-14T15:58:17.000Z
|
Notebook/TFLite.ipynb
|
deepchecks/url_classification_dl
|
029fddb78e019cf288adcc2fd46be3435536d469
|
[
"CC0-1.0"
] | 1 |
2021-11-15T11:22:48.000Z
|
2021-12-11T13:32:19.000Z
|
Notebook/TFLite.ipynb
|
deepchecks/url_classification_dl
|
029fddb78e019cf288adcc2fd46be3435536d469
|
[
"CC0-1.0"
] | 6 |
2021-05-15T17:46:22.000Z
|
2022-03-24T11:24:59.000Z
| 29.060976 | 428 | 0.596937 |
[
[
[
"import os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\nimport tensorflow as tf\nimport pickle\nos.chdir('../')\nos.chdir('scripts')\nimport data_creation_v3 as d",
"_____no_output_____"
],
[
"os.chdir('../')\nos.chdir('models')",
"_____no_output_____"
],
[
"order = ['bodyLength', 'bscr', 'dse', 'dsr', 'entropy', 'hasHttp', 'hasHttps',\n 'has_ip', 'numDigits', 'numImages', 'numLinks', 'numParams',\n 'numTitles', 'num_%20', 'num_@', 'sbr', 'scriptLength', 'specialChars',\n 'sscr', 'urlIsLive', 'urlLength']",
"_____no_output_____"
],
[
"a = d.UrlFeaturizer('http://astore.amazon.co.uk/allezvinsfrenchr/detail/1904010202/026-8324244-9330038').run()\ntest = []\nfor i in order:\n test.append(a[i])\nencoder = LabelEncoder()\nencoder.classes_ = np.load('lblenc.npy',allow_pickle=True)\nscalerfile = 'scaler.sav'\nscaler = pickle.load(open(scalerfile, 'rb'))",
"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/sklearn/utils/deprecation.py:143: FutureWarning: The sklearn.preprocessing.data module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.preprocessing. Anything that cannot be imported from sklearn.preprocessing is now part of the private API.\n warnings.warn(message, FutureWarning)\n/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/sklearn/base.py:329: UserWarning: Trying to unpickle estimator MinMaxScaler from version 0.21.3 when using version 0.23.2. This might lead to breaking code or invalid results. Use at your own risk.\n warnings.warn(\n"
],
[
"test = pd.DataFrame(test).replace(True,1).replace(False,0).to_numpy(dtype=\"float32\").reshape(1,-1)\ntest = scaler.transform(test)",
"_____no_output_____"
],
[
"# Load the TFLite model and allocate tensors.\ninterpreter = tf.lite.Interpreter(model_path=\"tflite_quant_model.tflite\")\ninterpreter.allocate_tensors()\n\n# Get input and output tensors.\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\ninterpreter.set_tensor(input_details[0]['index'], test)\n\ninterpreter.invoke()\n\n# The function `get_tensor()` returns a copy of the tensor data.\n# Use `tensor()` in order to get a pointer to the tensor.\noutput_data = interpreter.get_tensor(output_details[0]['index'])\npredicted = np.argmax(output_data,axis=1)",
"_____no_output_____"
],
[
"print(encoder.inverse_transform(predicted)[0])",
"Malware_dataset\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd6ffa61ab85a0905916b8c375058433bc198ef
| 1,024,357 |
ipynb
|
Jupyter Notebook
|
notebooks/pascal-fastai-object-classification.ipynb
|
aaronlelevier/pytorch-practice
|
8b8abe832106d3054460bb4996d23a8be2e1bc5e
|
[
"MIT"
] | null | null | null |
notebooks/pascal-fastai-object-classification.ipynb
|
aaronlelevier/pytorch-practice
|
8b8abe832106d3054460bb4996d23a8be2e1bc5e
|
[
"MIT"
] | null | null | null |
notebooks/pascal-fastai-object-classification.ipynb
|
aaronlelevier/pytorch-practice
|
8b8abe832106d3054460bb4996d23a8be2e1bc5e
|
[
"MIT"
] | null | null | null | 522.098369 | 148,392 | 0.946364 |
[
[
[
"import json\nimport os\nfrom pathlib import Path\nimport time\nimport copy\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch import nn, optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import models\nfrom fastai.dataset import open_image\nimport json\nfrom PIL import ImageDraw, ImageFont\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches, patheffects\nimport cv2\nfrom tqdm import tqdm",
"/home/paperspace/anaconda3/envs/fastai/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n return f(*args, **kwds)\n/home/paperspace/anaconda3/envs/fastai/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n return f(*args, **kwds)\n/home/paperspace/anaconda3/envs/fastai/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n return f(*args, **kwds)\n/home/paperspace/anaconda3/envs/fastai/lib/python3.6/site-packages/sklearn/ensemble/weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release.\n from numpy.core.umath_tests import inner1d\n"
],
[
"SIZE = 224\nIMAGES = 'images'\nANNOTATIONS = 'annotations'\nCATEGORIES = 'categories'\nID = 'id'\nNAME = 'name'\nIMAGE_ID = 'image_id'\nBBOX = 'bbox'\nCATEGORY_ID = 'category_id'\nFILE_NAME = 'file_name'",
"_____no_output_____"
],
[
"!pwd",
"/home/paperspace/pytorch-practice/notebooks\r\n"
],
[
"!ls $HOME/data/pascal",
"Annotations models\t\t pascal_train2012.json SegmentationClass\r\nImageSets pascal_test2007.json pascal_val2007.json SegmentationObject\r\nJPEGImages pascal_train2007.json pascal_val2012.json tmp\r\n"
],
[
"!ls ../input/pascal/pascal",
"ls: cannot access '../input/pascal/pascal': No such file or directory\r\n"
],
[
"PATH = Path('/home/paperspace/data/pascal')\nlist(PATH.iterdir())",
"_____no_output_____"
],
[
"train_data = json.load((PATH/'pascal_train2007.json').open())\nval_data = json.load((PATH/'pascal_val2007.json').open())\ntest_data = json.load((PATH/'pascal_test2007.json').open())\n\nprint('train:', train_data.keys())\nprint('val:', val_data.keys())\nprint('test:', test_data.keys())",
"train: dict_keys(['images', 'type', 'annotations', 'categories'])\nval: dict_keys(['images', 'type', 'annotations', 'categories'])\ntest: dict_keys(['images', 'type', 'annotations', 'categories'])\n"
],
[
"train_data[ANNOTATIONS][:1]",
"_____no_output_____"
],
[
"train_data[IMAGES][:2]",
"_____no_output_____"
],
[
"len(train_data[CATEGORIES])",
"_____no_output_____"
],
[
"next(iter(train_data[CATEGORIES]))",
"_____no_output_____"
]
],
[
[
"## Categories - 1th indexed",
"_____no_output_____"
]
],
[
[
"categories = {c[ID]:c[NAME] for c in train_data[CATEGORIES]}\ncategories",
"_____no_output_____"
],
[
"len(categories)",
"_____no_output_____"
],
[
"IMAGE_PATH = Path(PATH/'JPEGImages/')\nlist(IMAGE_PATH.iterdir())[:2]",
"_____no_output_____"
],
[
"train_filenames = {o[ID]:o[FILE_NAME] for o in train_data[IMAGES]}\nprint('length:', len(train_filenames))\nimage1_id, image1_fn = next(iter(train_filenames.items()))\nimage1_id, image1_fn",
"length: 2501\n"
],
[
"train_image_ids = [o[ID] for o in train_data[IMAGES]]\nprint('length:', len(train_image_ids))\ntrain_image_ids[:5]",
"length: 2501\n"
],
[
"IMAGE_PATH",
"_____no_output_____"
],
[
"image1_path = IMAGE_PATH/image1_fn\nimage1_path",
"_____no_output_____"
],
[
"str(image1_path)",
"_____no_output_____"
],
[
"im = open_image(str(IMAGE_PATH/image1_fn))\nprint(type(im))",
"<class 'numpy.ndarray'>\n"
],
[
"im.shape",
"_____no_output_____"
],
[
"len(train_data[ANNOTATIONS])",
"_____no_output_____"
],
[
"# get the biggest object label per image",
"_____no_output_____"
],
[
"train_data[ANNOTATIONS][0]",
"_____no_output_____"
],
[
"bbox = train_data[ANNOTATIONS][0][BBOX]\nbbox",
"_____no_output_____"
],
[
"def fastai_bb(bb):\n return np.array([bb[1], bb[0], bb[3]+bb[1]-1, bb[2]+bb[0]-1])\n\nprint(bbox)\nprint(fastai_bb(bbox))",
"[155, 96, 196, 174]\n[ 96 155 269 350]\n"
],
[
"fbb = fastai_bb(bbox)\nfbb",
"_____no_output_____"
],
[
"def fastai_bb_hw(bb):\n h= bb[3]-bb[1]+1\n w = bb[2]-bb[0]+1\n return [h,w]\n\nfastai_bb_hw(fbb)",
"_____no_output_____"
],
[
"def pascal_bb_hw(bb):\n return bb[2:]\n\npascal_bb_hw(bbox)",
"_____no_output_____"
],
[
"train_image_w_area = {i:None for i in train_image_ids}\nprint(image1_id, train_image_w_area[image1_id])",
"12 None\n"
],
[
"for x in train_data[ANNOTATIONS]:\n bbox = x[BBOX]\n new_category_id = x[CATEGORY_ID]\n image_id = x[IMAGE_ID]\n h, w = pascal_bb_hw(bbox)\n new_area = h*w\n cat_id_area = train_image_w_area[image_id]\n if not cat_id_area:\n train_image_w_area[image_id] = (new_category_id, new_area)\n else:\n category_id, area = cat_id_area\n if new_area > area:\n train_image_w_area[image_id] = (new_category_id, new_area)",
"_____no_output_____"
],
[
"train_image_w_area[image1_id]",
"_____no_output_____"
],
[
"plt.imshow(im)",
"_____no_output_____"
],
[
"def show_img(im, figsize=None, ax=None):\n if not ax:\n fig,ax = plt.subplots(figsize=figsize)\n ax.imshow(im)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n return ax\n\nshow_img(im)",
"_____no_output_____"
],
[
"# show_img(im)\n# b = bb_hw(im0_a[0])\n# draw_rect(ax, b)\nimage1_fn",
"_____no_output_____"
],
[
"def draw_rect(ax, b):\n patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor='white', lw=2))\n draw_outline(patch, 4)",
"_____no_output_____"
],
[
"image1_id",
"_____no_output_____"
],
[
"image1_path",
"_____no_output_____"
],
[
"plt.imshow(open_image(str(image1_path)))",
"_____no_output_____"
],
[
"train_data[ANNOTATIONS][0]",
"_____no_output_____"
],
[
"im = open_image(str(image1_path))\nax = show_img(im)",
"_____no_output_____"
],
[
"def draw_outline(o, lw):\n o.set_path_effects([patheffects.Stroke(\n linewidth=lw, foreground='black'), patheffects.Normal()])",
"_____no_output_____"
],
[
"image1_ann = train_data[ANNOTATIONS][0]\nb = fastai_bb(image1_ann[BBOX])\nb",
"_____no_output_____"
],
[
"def draw_text(ax, xy, txt, sz=14):\n text = ax.text(*xy, txt,\n verticalalignment='top', color='white', fontsize=sz, weight='bold')\n draw_outline(text, 1)",
"_____no_output_____"
],
[
"ax = show_img(im)\nb = image1_ann[BBOX]\nprint(b)\ndraw_rect(ax, b)\ndraw_text(ax, b[:2], categories[image1_ann[CATEGORY_ID]])",
"[155, 96, 196, 174]\n"
],
[
"# create a Pandas dataframe for: image_id, filename, category\nBIGGEST_OBJECT_CSV = '../input/pascal/pascal/tmp/biggest-object.csv'\nIMAGE = 'image'\nCATEGORY = 'category'\n\ntrain_df = pd.DataFrame({\n IMAGE_ID: image_id,\n IMAGE: str(IMAGE_PATH/image_fn),\n CATEGORY: train_image_w_area[image_id][0]\n} for image_id, image_fn in train_filenames.items())\n\ntrain_df.head()",
"_____no_output_____"
],
[
"# NOTE: won't work in Kaggle Kernal b/c read-only file system\n# train_df.to_csv(BIGGEST_OBJECT_CSV, index=False)",
"_____no_output_____"
],
[
"train_df.iloc[0]",
"_____no_output_____"
],
[
"len(train_df)",
"_____no_output_____"
],
[
"class BiggestObjectDataset(Dataset):\n def __init__(self, df):\n self.df = df\n\n def __len__(self):\n return len(self.df)\n \n def __getitem__(self, idx):\n im = open_image(self.df.iloc[idx][IMAGE]) # HW\n resized_image = cv2.resize(im, (SIZE, SIZE)) # HW\n image = np.transpose(resized_image, (2, 0, 1)) # CHW\n \n category = self.df.iloc[idx][CATEGORY]\n\n return image, category\n \ndataset = BiggestObjectDataset(train_df)\ninputs, label = dataset[0]",
"_____no_output_____"
],
[
"label",
"_____no_output_____"
],
[
"inputs.shape",
"_____no_output_____"
],
[
"hwc_image = np.transpose(inputs, (1, 2, 0))\nplt.imshow(hwc_image)",
"_____no_output_____"
]
],
[
[
"# DataLoader",
"_____no_output_____"
]
],
[
[
"BATCH_SIZE = 64\nNUM_WORKERS = 4\n\ndataloader = DataLoader(dataset, batch_size=BATCH_SIZE,\n shuffle=True, num_workers=NUM_WORKERS)\n\nbatch_inputs, batch_labels = next(iter(dataloader))",
"_____no_output_____"
],
[
"batch_inputs.size()",
"_____no_output_____"
],
[
"batch_labels",
"_____no_output_____"
],
[
"np_batch_inputs = batch_inputs.numpy()\ni = np.random.randint(0,20)\nprint(categories[batch_labels[i].item()])\nchw_image = np_batch_inputs[i]\nprint(chw_image.shape)\nhwc_image = np.transpose(chw_image, (1, 2, 0))\nplt.imshow(hwc_image)",
"diningtable\n(3, 224, 224)\n"
],
[
"NUM_CATEGORIES = len(categories)\nNUM_CATEGORIES",
"_____no_output_____"
]
],
[
[
"## train the model",
"_____no_output_____"
]
],
[
[
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# device = torch.device('cpu')\nprint('device:', device)\n\nmodel_ft = models.resnet18(pretrained=True)\n\n# freeze pretrained model\nfor layer in model_ft.parameters():\n layer.requires_grad = False\n \nnum_ftrs = model_ft.fc.in_features\nprint('final layer in/out:', num_ftrs, NUM_CATEGORIES)\n\nmodel_ft.fc = nn.Linear(num_ftrs, NUM_CATEGORIES)\n\nmodel_ft = model_ft.to(device)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Observe that all parameters are being optimized\noptimizer = optim.SGD(model_ft.parameters(), lr=0.01, momentum=0.9)",
"device: cuda:0\nfinal layer in/out: 512 20\n"
],
[
"EPOCHS = 10\n\nepoch_losses = []\nepoch_accuracies = []\n\nfor epoch in range(EPOCHS):\n print('epoch:', epoch)\n running_loss = 0.0\n running_correct = 0\n\n for inputs, labels in tqdm(dataloader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # clear gradients\n optimizer.zero_grad()\n \n # forward pass\n outputs = model_ft(inputs)\n _, preds = torch.max(outputs, dim=1)\n labels_0_indexed = labels-1\n loss = criterion(outputs, labels_0_indexed)\n \n # backwards pass\n loss.backward()\n optimizer.step()\n \n # step stats\n running_loss += loss.item() * inputs.size(0)\n running_correct += torch.sum(preds == labels_0_indexed)\n \n # epoch stats\n epoch_loss = running_loss / len(dataset)\n epoch_acc = running_correct.double().item() / len(dataset)\n epoch_losses.append(epoch_loss)\n epoch_accuracies.append(epoch_acc)\n print('loss:', epoch_loss, 'acc:', epoch_acc)",
"\r 0%| | 0/40 [00:00<?, ?it/s]"
],
[
"epoch_losses",
"_____no_output_____"
],
[
"epoch_accuracies",
"_____no_output_____"
],
[
"plt.plot(epoch_losses)",
"_____no_output_____"
],
[
"plt.plot(epoch_accuracies)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd70684156aa60ed5cf6c1f1be78c5cfb0b29cc
| 88,148 |
ipynb
|
Jupyter Notebook
|
notebook_v1.ipynb
|
peddrogomes/Hackaton_dados
|
d0fe4bafcb29b36183fdfa646614611ce3f4b714
|
[
"Apache-2.0"
] | null | null | null |
notebook_v1.ipynb
|
peddrogomes/Hackaton_dados
|
d0fe4bafcb29b36183fdfa646614611ce3f4b714
|
[
"Apache-2.0"
] | null | null | null |
notebook_v1.ipynb
|
peddrogomes/Hackaton_dados
|
d0fe4bafcb29b36183fdfa646614611ce3f4b714
|
[
"Apache-2.0"
] | null | null | null | 39.599281 | 1,314 | 0.471412 |
[
[
[
"## Bibliotecas:",
"_____no_output_____"
]
],
[
[
"#importanto bibliotecas\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn import datasets, linear_model, preprocessing\n\nimport statsmodels.api as sm\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nfrom sklearn.preprocessing import StandardScaler\nfrom datetime import datetime\n\nfrom sklearn.linear_model import Lasso, LassoCV\nfrom sklearn.impute import SimpleImputer\n\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import mean_squared_error as MSE\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
]
],
[
[
"#### Lendo csv e removendo algumas colunas redundantes:",
"_____no_output_____"
]
],
[
[
"Y_train=pd.read_csv('shared/bases_budokai_ufpr/produtividade_soja_modelagem.csv')\ndf=pd.read_csv('shared/bases_budokai_ufpr/agroclimatology_budokai.csv')",
"_____no_output_____"
],
[
"Y_train.head()",
"_____no_output_____"
],
[
"Y_train['nivel'].unique()",
"_____no_output_____"
],
[
"#Y_codigo=Y_train['codigo_ibge']\n\nY_train=Y_train.drop(columns=['nivel', 'name'])",
"_____no_output_____"
],
[
"Y_train.head()",
"_____no_output_____"
]
],
[
[
"### De acordo com as respostas esperadas temos:",
"_____no_output_____"
]
],
[
[
"codigo_saida=[4102000,4104303,4104428,4104808,4104907,4109401,4113205,4113700,4113734,4114005,4114401,4117701,4117909,4119608,4119905,4127007,4127403,4127502,4127700,4128005\n]",
"_____no_output_____"
],
[
"dataset=pd.DataFrame(columns=df.keys())\n#dataset.loc[dataset['codigo_ibge']==codigo_saida[j]]\n\nfor k in codigo_saida:\n dataset=pd.concat([df.loc[df['codigo_ibge']==k],dataset])\n\ndataset=dataset.reset_index(drop=True)",
"_____no_output_____"
],
[
"dataset.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 131500 entries, 0 to 131499\nData columns (total 38 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 data 131500 non-null object \n 1 codigo_ibge 131500 non-null object \n 2 latitude 131500 non-null float64\n 3 longitude 131500 non-null float64\n 4 T2M_RANGE 131500 non-null float64\n 5 TS 131500 non-null float64\n 6 T2MDEW 131500 non-null float64\n 7 T2MWET 131500 non-null float64\n 8 T2M_MAX 131500 non-null float64\n 9 T2M_MIN 131500 non-null float64\n 10 T2M 131500 non-null float64\n 11 QV2M 131500 non-null float64\n 12 RH2M 131500 non-null float64\n 13 PRECTOTCORR 131500 non-null float64\n 14 PS 131500 non-null float64\n 15 WS2M 131500 non-null float64\n 16 WS2M_MAX 131500 non-null float64\n 17 WS2M_MIN 131500 non-null float64\n 18 WS2M_RANGE 131500 non-null float64\n 19 WS10M 131500 non-null float64\n 20 WS10M_MAX 131500 non-null float64\n 21 WS10M_MIN 131500 non-null float64\n 22 WS10M_RANGE 131500 non-null float64\n 23 WS50M 131500 non-null float64\n 24 WS50M_MAX 131500 non-null float64\n 25 WS50M_MIN 131500 non-null float64\n 26 WS50M_RANGE 131500 non-null float64\n 27 GWETTOP 131500 non-null float64\n 28 GWETROOT 131500 non-null float64\n 29 GWETPROF 131500 non-null float64\n 30 ALLSKY_SFC_SW_DWN 131500 non-null float64\n 31 CLRSKY_SFC_SW_DWN 131500 non-null float64\n 32 TOA_SW_DWN 131500 non-null float64\n 33 ALLSKY_SFC_PAR_TOT 131500 non-null float64\n 34 CLRSKY_SFC_PAR_TOT 131500 non-null float64\n 35 ALLSKY_SFC_UVA 131500 non-null float64\n 36 ALLSKY_SFC_UVB 131500 non-null float64\n 37 ALLSKY_SFC_UV_INDEX 131500 non-null float64\ndtypes: float64(36), object(2)\nmemory usage: 38.1+ MB\n"
],
[
"dataset['codigo_ibge']=list(map(int,dataset['codigo_ibge']))\n#transformar o codigo em inteiro novamente\n#df.loc[df['codigo_ibge']==codigo_saida[0]]",
"_____no_output_____"
]
],
[
[
"### Vamos começar transformando os dados de data em 'datetime' para melhor agrupar em semanas, meses ou anos.",
"_____no_output_____"
]
],
[
[
"def t_data_day(data):\n data=str(data)\n data=datetime.strptime(data,\"%Y%m%d\")\n return data.day\n\ndef t_data_month(data):\n data=str(data)\n data=datetime.strptime(data,\"%Y%m%d\")\n return data.month\n\ndef t_data_year(data):\n data=str(data)\n data=datetime.strptime(data,\"%Y%m%d\")\n return data.year\n #return data.day, data.month, data.year",
"_____no_output_____"
],
[
"dataset['day']=list(map(t_data_day, dataset['data']))\ndataset['month']=list(map(t_data_month, dataset['data']))\ndataset['year']=list(map(t_data_year, dataset['data']))",
"_____no_output_____"
],
[
"dataset.head()",
"_____no_output_____"
]
],
[
[
"## *Uma feature importante é o valor da produção do ano passado, inserir depois.",
"_____no_output_____"
]
],
[
[
"dataset=dataset.drop(dataset.loc[dataset['year']==2003].index).reset_index(drop=True)",
"_____no_output_____"
]
],
[
[
"#### A ideia posteriormente aqui é fazer um algoritmo de pesos para cada mês (media ponderada)",
"_____no_output_____"
],
[
"### A titulo de teste do sistema podemos implementar um algoritmo rápido para previsões baseado na média dos valores anuais.",
"_____no_output_____"
]
],
[
[
"dataset=dataset.drop(columns=['data','latitude','longitude','day','month'])",
"_____no_output_____"
]
],
[
[
"#### Para cada codigo postal agrupamos os dados anuais pela média.",
"_____no_output_____"
]
],
[
[
"codigos=dataset['codigo_ibge'].unique()\n\ndatanew=pd.DataFrame(columns=dataset.keys())\n\nfor i in codigos:\n \n aux = dataset.loc[dataset['codigo_ibge']==i].groupby(by='year').agg('mean').reset_index()\n \n datanew=pd.concat([datanew,aux])\n \ndatanew=datanew.reset_index(drop=True)",
"_____no_output_____"
],
[
"datanew.head()",
"_____no_output_____"
],
[
"X_train=datanew.loc[datanew['year']<2018]\nX_test=datanew.loc[datanew['year']>2017]\n",
"_____no_output_____"
]
],
[
[
"#### Scalando os dados:",
"_____no_output_____"
]
],
[
[
"colunas_=list(X_train.keys())\n\ncolunas_.remove('year')\ncolunas_.remove('codigo_ibge')\n#removendo os dados que não serão escalados",
"_____no_output_____"
],
[
"scaler=StandardScaler()\n\n\nX_train_scaled=scaler.fit_transform(X_train[colunas_])\nX_train_scaled=pd.DataFrame(X_train_scaled, columns=colunas_)\n\n\nX_test_scaled=scaler.transform(X_test[colunas_])\nX_test_scaled=pd.DataFrame(X_test_scaled, columns=colunas_)",
"_____no_output_____"
]
],
[
[
"### Precisamos reinserir o codigo e ano e resetar o indice.",
"_____no_output_____"
]
],
[
[
"X_train_scaled[['codigo_ibge','year']]=X_train[['codigo_ibge','year']].reset_index(drop=True)\nX_test_scaled[['codigo_ibge','year']]=X_test[['codigo_ibge','year']].reset_index(drop=True)",
"_____no_output_____"
],
[
"X_train_scaled",
"_____no_output_____"
],
[
"#k-fold para achar melhor valor de alpha\nmodel = LassoCV(cv=5, random_state=0, max_iter=10000)",
"_____no_output_____"
],
[
"\n\ndf_out=pd.DataFrame(columns=['codigo_ibge','2018','2019','2020'])\n\nfor i in codigo_saida:\n \n X_train_menor=X_train_scaled.loc[X_train_scaled['codigo_ibge']==i].drop(columns=['codigo_ibge','year'])\n Y_train_menor=Y_train[Y_train['codigo_ibge']==i].drop(columns='codigo_ibge').T\n \n model.fit(X_train_menor, Y_train_menor)\n ##########################\n # Teste com árvore de decisão\n dt = DecisionTreeRegressor(max_depth=4, min_samples_leaf=0.1, random_state=3)\n dt.fit(X_train_menor,Y_train_menor)\n ##############################################3\n lasso_t= Lasso(alpha=model.alpha_, max_iter= 10000).fit(X_train_menor,Y_train_menor)\n \n print(f'\\n Alpha usado: {model.alpha_}')\n print('Features non-zero para {}: {}'.format(i, np.sum(lasso_t.coef_ != 0)))\n print('Features com valores non-zero (ordenados pela magnitude absoluta):')\n\n for e in sorted (list(zip(list(X_train), lasso_t.coef_)), key = lambda e: -abs(e[1])):\n if e[1] != 0:\n print('\\t{}, {:.3f}'.format(e[0], e[1]))\n \n \n X_test_menor=X_test_scaled.loc[X_test_scaled['codigo_ibge']==i].drop(columns=['codigo_ibge','year'])\n ##################\n Y_prd = dt.predict(X_test_menor)\n predicoes = Y_prd\n #Analisando a acuracia\n ##################\n #predicoes=lasso_t.predict(X_test_menor)\n\n data_saida={'codigo_ibge':i, '2018':predicoes[0], '2019':predicoes[1], '2020':predicoes[2]}\n \n data_saida=pd.DataFrame([data_saida])\n \n df_out=pd.concat([df_out,data_saida])",
"/opt/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_coordinate_descent.py:1088: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n/opt/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_coordinate_descent.py:1088: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n"
],
[
"df_out=df_out.reset_index(drop=True)",
"_____no_output_____"
],
[
"df_out",
"_____no_output_____"
],
[
"df_out.to_csv('submission.csv',index=False)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd717c1bbbb0ef8efa8a8fd54593f0044cfbec9
| 17,264 |
ipynb
|
Jupyter Notebook
|
intro-to-pytorch/Part 1 - Tensors in PyTorch (Exercises).ipynb
|
jvce92/deep-learning-v2-pytorch
|
cf770f3837d82b0883fcb4f27e617776757722be
|
[
"MIT"
] | null | null | null |
intro-to-pytorch/Part 1 - Tensors in PyTorch (Exercises).ipynb
|
jvce92/deep-learning-v2-pytorch
|
cf770f3837d82b0883fcb4f27e617776757722be
|
[
"MIT"
] | null | null | null |
intro-to-pytorch/Part 1 - Tensors in PyTorch (Exercises).ipynb
|
jvce92/deep-learning-v2-pytorch
|
cf770f3837d82b0883fcb4f27e617776757722be
|
[
"MIT"
] | 1 |
2021-01-09T15:58:44.000Z
|
2021-01-09T15:58:44.000Z
| 38.19469 | 674 | 0.598355 |
[
[
[
"# Introduction to Deep Learning with PyTorch\n\nIn this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation!) and another module specifically for building neural networks. All together, PyTorch ends up being more coherent with Python and the Numpy/Scipy stack compared to TensorFlow and other frameworks.\n\n",
"_____no_output_____"
],
[
"## Neural Networks\n\nDeep Learning is based on artificial neural networks which have been around in some form since the late 1950s. The networks are built from individual parts approximating neurons, typically called units or simply \"neurons.\" Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit's output.\n\n<img src=\"assets/simple_neuron.png\" width=400px>\n\nMathematically this looks like: \n\n$$\n\\begin{align}\ny &= f(w_1 x_1 + w_2 x_2 + b) \\\\\ny &= f\\left(\\sum_i w_i x_i +b \\right)\n\\end{align}\n$$\n\nWith vectors this is the dot/inner product of two vectors:\n\n$$\nh = \\begin{bmatrix}\nx_1 \\, x_2 \\cdots x_n\n\\end{bmatrix}\n\\cdot \n\\begin{bmatrix}\n w_1 \\\\\n w_2 \\\\\n \\vdots \\\\\n w_n\n\\end{bmatrix}\n$$",
"_____no_output_____"
],
[
"## Tensors\n\nIt turns out neural network computations are just a bunch of linear algebra operations on *tensors*, a generalization of matrices. A vector is a 1-dimensional tensor, a matrix is a 2-dimensional tensor, an array with three indices is a 3-dimensional tensor (RGB color images for example). The fundamental data structure for neural networks are tensors and PyTorch (as well as pretty much every other deep learning framework) is built around tensors.\n\n<img src=\"assets/tensor_examples.svg\" width=600px>\n\nWith the basics covered, it's time to explore how we can use PyTorch to build a simple neural network.",
"_____no_output_____"
]
],
[
[
"# First, import PyTorch\nimport torch",
"_____no_output_____"
],
[
"def activation(x):\n \"\"\" Sigmoid activation function \n \n Arguments\n ---------\n x: torch.Tensor\n \"\"\"\n return 1/(1+torch.exp(-x))",
"_____no_output_____"
],
[
"### Generate some data\ntorch.manual_seed(7) # Set the random seed so things are predictable\n\n# Features are 3 random normal variables\nfeatures = torch.randn((1, 5))\n# True weights for our data, random normal variables again\nweights = torch.randn_like(features)\n# and a true bias term\nbias = torch.randn((1, 1))",
"_____no_output_____"
]
],
[
[
"Above I generated data we can use to get the output of our simple network. This is all just random for now, going forward we'll start using normal data. Going through each relevant line:\n\n`features = torch.randn((1, 5))` creates a tensor with shape `(1, 5)`, one row and five columns, that contains values randomly distributed according to the normal distribution with a mean of zero and standard deviation of one. \n\n`weights = torch.randn_like(features)` creates another tensor with the same shape as `features`, again containing values from a normal distribution.\n\nFinally, `bias = torch.randn((1, 1))` creates a single value from a normal distribution.\n\nPyTorch tensors can be added, multiplied, subtracted, etc, just like Numpy arrays. In general, you'll use PyTorch tensors pretty much the same way you'd use Numpy arrays. They come with some nice benefits though such as GPU acceleration which we'll get to later. For now, use the generated data to calculate the output of this simple single layer network. \n> **Exercise**: Calculate the output of the network with input features `features`, weights `weights`, and bias `bias`. Similar to Numpy, PyTorch has a [`torch.sum()`](https://pytorch.org/docs/stable/torch.html#torch.sum) function, as well as a `.sum()` method on tensors, for taking sums. Use the function `activation` defined above as the activation function.",
"_____no_output_____"
]
],
[
[
"## Calculate the output of this network using the weights and bias tensors\nactivation(torch.sum(weights * features) + bias)",
"_____no_output_____"
]
],
[
[
"You can do the multiplication and sum in the same operation using a matrix multiplication. In general, you'll want to use matrix multiplications since they are more efficient and accelerated using modern libraries and high-performance computing on GPUs.\n\nHere, we want to do a matrix multiplication of the features and the weights. For this we can use [`torch.mm()`](https://pytorch.org/docs/stable/torch.html#torch.mm) or [`torch.matmul()`](https://pytorch.org/docs/stable/torch.html#torch.matmul) which is somewhat more complicated and supports broadcasting. If we try to do it with `features` and `weights` as they are, we'll get an error\n\n```python\n>> torch.mm(features, weights)\n\n---------------------------------------------------------------------------\nRuntimeError Traceback (most recent call last)\n<ipython-input-13-15d592eb5279> in <module>()\n----> 1 torch.mm(features, weights)\n\nRuntimeError: size mismatch, m1: [1 x 5], m2: [1 x 5] at /Users/soumith/minicondabuild3/conda-bld/pytorch_1524590658547/work/aten/src/TH/generic/THTensorMath.c:2033\n```\n\nAs you're building neural networks in any framework, you'll see this often. Really often. What's happening here is our tensors aren't the correct shapes to perform a matrix multiplication. Remember that for matrix multiplications, the number of columns in the first tensor must equal to the number of rows in the second column. Both `features` and `weights` have the same shape, `(1, 5)`. This means we need to change the shape of `weights` to get the matrix multiplication to work.\n\n**Note:** To see the shape of a tensor called `tensor`, use `tensor.shape`. If you're building neural networks, you'll be using this method often.\n\nThere are a few options here: [`weights.reshape()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.reshape), [`weights.resize_()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.resize_), and [`weights.view()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.view).\n\n* `weights.reshape(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)` sometimes, and sometimes a clone, as in it copies the data to another part of memory.\n* `weights.resize_(a, b)` returns the same tensor with a different shape. However, if the new shape results in fewer elements than the original tensor, some elements will be removed from the tensor (but not from memory). If the new shape results in more elements than the original tensor, new elements will be uninitialized in memory. Here I should note that the underscore at the end of the method denotes that this method is performed **in-place**. Here is a great forum thread to [read more about in-place operations](https://discuss.pytorch.org/t/what-is-in-place-operation/16244) in PyTorch.\n* `weights.view(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)`.\n\nI usually use `.view()`, but any of the three methods will work for this. So, now we can reshape `weights` to have five rows and one column with something like `weights.view(5, 1)`.\n\n> **Exercise**: Calculate the output of our little network using matrix multiplication.",
"_____no_output_____"
]
],
[
[
"## Calculate the output of this network using matrix multiplication\nactivation(torch.matmul(weights, features.t()) + bias)",
"_____no_output_____"
]
],
[
[
"### Stack them up!\n\nThat's how you can calculate the output for a single neuron. The real power of this algorithm happens when you start stacking these individual units into layers and stacks of layers, into a network of neurons. The output of one layer of neurons becomes the input for the next layer. With multiple input units and output units, we now need to express the weights as a matrix.\n\n<img src='assets/multilayer_diagram_weights.png' width=450px>\n\nThe first layer shown on the bottom here are the inputs, understandably called the **input layer**. The middle layer is called the **hidden layer**, and the final layer (on the right) is the **output layer**. We can express this network mathematically with matrices again and use matrix multiplication to get linear combinations for each unit in one operation. For example, the hidden layer ($h_1$ and $h_2$ here) can be calculated \n\n$$\n\\vec{h} = [h_1 \\, h_2] = \n\\begin{bmatrix}\nx_1 \\, x_2 \\cdots \\, x_n\n\\end{bmatrix}\n\\cdot \n\\begin{bmatrix}\n w_{11} & w_{12} \\\\\n w_{21} &w_{22} \\\\\n \\vdots &\\vdots \\\\\n w_{n1} &w_{n2}\n\\end{bmatrix}\n$$\n\nThe output for this small network is found by treating the hidden layer as inputs for the output unit. The network output is expressed simply\n\n$$\ny = f_2 \\! \\left(\\, f_1 \\! \\left(\\vec{x} \\, \\mathbf{W_1}\\right) \\mathbf{W_2} \\right)\n$$",
"_____no_output_____"
]
],
[
[
"### Generate some data\ntorch.manual_seed(7) # Set the random seed so things are predictable\n\n# Features are 3 random normal variables\nfeatures = torch.randn((1, 3))\n\n# Define the size of each layer in our network\nn_input = features.shape[1] # Number of input units, must match number of input features\nn_hidden = 2 # Number of hidden units \nn_output = 1 # Number of output units\n\n# Weights for inputs to hidden layer\nW1 = torch.randn(n_input, n_hidden)\n# Weights for hidden layer to output layer\nW2 = torch.randn(n_hidden, n_output)\n\n# and bias terms for hidden and output layers\nB1 = torch.randn((1, n_hidden))\nB2 = torch.randn((1, n_output))",
"_____no_output_____"
]
],
[
[
"> **Exercise:** Calculate the output for this multi-layer network using the weights `W1` & `W2`, and the biases, `B1` & `B2`. ",
"_____no_output_____"
]
],
[
[
"## Your solution here\nactivation(torch.mm(activation(torch.mm(features, W1) + B1), W2) + B2)",
"_____no_output_____"
]
],
[
[
"If you did this correctly, you should see the output `tensor([[ 0.3171]])`.\n\nThe number of hidden units a parameter of the network, often called a **hyperparameter** to differentiate it from the weights and biases parameters. As you'll see later when we discuss training a neural network, the more hidden units a network has, and the more layers, the better able it is to learn from data and make accurate predictions.",
"_____no_output_____"
],
[
"## Numpy to Torch and back\n\nSpecial bonus section! PyTorch has a great feature for converting between Numpy arrays and Torch tensors. To create a tensor from a Numpy array, use `torch.from_numpy()`. To convert a tensor to a Numpy array, use the `.numpy()` method.",
"_____no_output_____"
]
],
[
[
"import numpy as np\na = np.random.rand(4,3)\na",
"_____no_output_____"
],
[
"b = torch.from_numpy(a)\nb",
"_____no_output_____"
],
[
"b.numpy()",
"_____no_output_____"
]
],
[
[
"The memory is shared between the Numpy array and Torch tensor, so if you change the values in-place of one object, the other will change as well.",
"_____no_output_____"
]
],
[
[
"# Multiply PyTorch Tensor by 2, in place\nb.mul_(2)",
"_____no_output_____"
],
[
"# Numpy array matches new values from Tensor\na",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbd71a6b88f8d2915886df6e99307dc56f08597b
| 460,245 |
ipynb
|
Jupyter Notebook
|
ipynb/2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb
|
RobertRosca/oscovida.github.io
|
d609949076e3f881e38ec674ecbf0887e9a2ec25
|
[
"CC-BY-4.0"
] | 2 |
2020-06-19T09:16:14.000Z
|
2021-01-24T17:47:56.000Z
|
ipynb/2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb
|
RobertRosca/oscovida.github.io
|
d609949076e3f881e38ec674ecbf0887e9a2ec25
|
[
"CC-BY-4.0"
] | 8 |
2020-04-20T16:49:49.000Z
|
2021-12-25T16:54:19.000Z
|
ipynb/2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb
|
RobertRosca/oscovida.github.io
|
d609949076e3f881e38ec674ecbf0887e9a2ec25
|
[
"CC-BY-4.0"
] | 4 |
2020-04-20T13:24:45.000Z
|
2021-01-29T11:12:12.000Z
| 52.744098 | 235 | 0.504573 |
[
[
[
"Quick study to investigate oscillations in reported infections in Germany. Here is the plot of the data in question: ",
"_____no_output_____"
]
],
[
[
"import coronavirus\nimport numpy as np\nimport matplotlib.pyplot as plt\n%config InlineBackend.figure_formats = ['svg']\n\ncoronavirus.display_binder_link(\"2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb\")",
"_____no_output_____"
],
[
"# get data\ncases, deaths, country_label = coronavirus.get_country_data(\"Germany\")\n\n# plot daily changes\nfig, ax = plt.subplots(figsize=(8, 4))\ncoronavirus.plot_daily_change(ax, cases, 'C1')",
"_____no_output_____"
]
],
[
[
"The working assumption is that during the weekend fewer numbers are captured or reported. The analysis below seems to confirm this.\n\nWe compute a discrete Fourier transform of the data, and expect a peak at a frequency corresponding to a period of 7 days.",
"_____no_output_____"
],
[
"## Data selection\n\nWe start with data from 1st March as numbers before were small. It is convenient to take a number of days that can be divided by seven (for alignment of the freuency axis in Fourier space, so we choose 63 days from 1st of March):",
"_____no_output_____"
]
],
[
[
"data = cases['2020-03-01':'2020-05-03']\n# compute daily change\ndiff = data.diff().dropna()\n# plot data points (corresponding to bars in figure above:)\nfig, ax = plt.subplots()\nax.plot(diff.index, diff, '-C1', \n label='daily new cases Germany')\n\nfig.autofmt_xdate() # avoid x-labels overlap\n# How many data points (=days) have we got?\ndiff.size",
"_____no_output_____"
],
[
"diff2 = diff.resample(\"24h\").asfreq() # ensure we have one data point every day\ndiff2.size",
"_____no_output_____"
]
],
[
[
"## Compute the frequency spectrum",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots()\n# compute power density spectrum \nchange_F = abs(np.fft.fft(diff2))**2\n# determine appropriate frequencies\nn = change_F.size\nfreq = np.fft.fftfreq(n, d=1)\n# We skip values at indices 0, 1 and 2: these are large because we have a finite \n# sequence and not substracted the mean from the data set\n# We also only plot the the first n/2 frequencies as for high n, we get negative\n# frequencies with the same data content as the positive ones.\nax.plot(freq[3:n//2], change_F[3:n//2], 'o-C3')\nax.set_xlabel('frequency [cycles per day]');\n",
"_____no_output_____"
]
],
[
[
"A signal with oscillations on a weekly basis would correspond to a frequency of 1/7 as frequency is measured in `per day`. We thus expect the peak above to be at 1/7 $\\approx 0.1428$. \n\nWe can show this more easily by changing the frequency scale from cycles per day to cycles per week:\n",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots()\nax.plot(freq[3:n//2] * 7, change_F[3:n//2], 'o-C3')\nax.set_xlabel('frequency [cycles per week]');",
"_____no_output_____"
]
],
[
[
"In other words: there as a strong component of the data with a frequency corresponding to one week.\n\n\nThis is the end of the notebook.",
"_____no_output_____"
],
[
"# Fourier transform basics\n\nA little playground to explore properties of discrete Fourier transforms.",
"_____no_output_____"
]
],
[
[
"time = np.linspace(0, 4, 1000)\nsignal_frequency = 3 # choose this freely\nsignal = np.sin(time * 2 * np.pi * signal_frequency)\nfourier = np.abs(np.fft.fft(signal))\n\n# compute frequencies in fourier spectrum\nn = signal.size\ntimestep = time[1] - time[0]\nfreqs = np.fft.fftfreq(n, d=timestep)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nax.plot(time, signal, 'oC9', label=f'signal, frequency={signal_frequency}')\nax.set_xlabel('time')\nax.legend()\nfig, ax = plt.subplots()\nax.plot(freqs[0:n//2][:20], fourier[0:n//2][0:20], 'o-C8', label=\"Fourier transform\")\nax.legend()\nax.set_xlabel('frequency');\n",
"_____no_output_____"
],
[
"coronavirus.display_binder_link(\"2020-05-10-notebook-weekly-fluctuations-in-data-from-germany.ipynb\")",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbd73b4093edc74fc3ea83b68e8505b8824ae1cb
| 154,124 |
ipynb
|
Jupyter Notebook
|
Final_Submission_Hackerearth - Copy.ipynb
|
ssunwalka01/HE
|
d0a3ae60f43e0bda002ae2f38e6a09a072637fda
|
[
"Apache-2.0"
] | null | null | null |
Final_Submission_Hackerearth - Copy.ipynb
|
ssunwalka01/HE
|
d0a3ae60f43e0bda002ae2f38e6a09a072637fda
|
[
"Apache-2.0"
] | null | null | null |
Final_Submission_Hackerearth - Copy.ipynb
|
ssunwalka01/HE
|
d0a3ae60f43e0bda002ae2f38e6a09a072637fda
|
[
"Apache-2.0"
] | null | null | null | 97.856508 | 45,872 | 0.803665 |
[
[
[
"# Predict Happiness Source",
"_____no_output_____"
],
[
"- Importing the Packages",
"_____no_output_____"
]
],
[
[
"# importing packages\nimport pandas as pd \nimport numpy as np # For mathematical calculations \nimport seaborn as sns # For data visualization \nimport matplotlib.pyplot as plt # For plotting graphs \n%matplotlib inline \nimport warnings # To ignore any warnings warnings.filterwarnings(\"ignore\")\n\nimport seaborn as sns\nfrom sklearn.preprocessing import MinMaxScaler\n#from sklearn.cross_validation import train_test_split\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import f1_score\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom nltk.stem.porter import PorterStemmer\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import cross_val_score\nimport nltk\nimport re\nimport codecs\nimport seaborn as sns\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n#from sklearn.cross_validation import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import f1_score",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\n#import xgboost as xgb\nfrom tqdm import tqdm\nfrom sklearn.svm import SVC\nfrom keras.models import Sequential\nfrom keras.layers.recurrent import LSTM, GRU\nfrom keras.layers.core import Dense, Activation, Dropout\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils import np_utils\nfrom sklearn import preprocessing, decomposition, model_selection, metrics, pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom keras.layers import GlobalMaxPooling1D, Conv1D, MaxPooling1D, Flatten, Bidirectional, SpatialDropout1D\nfrom keras.preprocessing import sequence, text\nfrom keras.callbacks import EarlyStopping\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords\nstop_words = stopwords.words('english')",
"_____no_output_____"
]
],
[
[
"- Reading the data",
"_____no_output_____"
]
],
[
[
"train=pd.read_csv('hm_train.csv')\ntest=pd.read_csv('hm_test.csv')\nsubmission=pd.read_csv('sample_submission.csv')",
"_____no_output_____"
],
[
"print(train.columns,test.columns,submission.columns)\nprint(train.head(),test.head(),submission.head())\nprint(train.shape,test.shape,submission.shape)",
"Index(['hmid', 'reflection_period', 'cleaned_hm', 'num_sentence',\n 'predicted_category'],\n dtype='object') Index(['hmid', 'reflection_period', 'cleaned_hm', 'num_sentence'], dtype='object') Index(['hmid', 'predicted_category'], dtype='object')\n hmid reflection_period cleaned_hm \\\n0 27673 24h I went on a successful date with someone I fel... \n1 27674 24h I was happy when my son got 90% marks in his e... \n2 27675 24h I went to the gym this morning and did yoga. \n3 27676 24h We had a serious talk with some friends of our... \n4 27677 24h I went with grandchildren to butterfly display... \n\n num_sentence predicted_category \n0 1 affection \n1 1 affection \n2 1 exercise \n3 2 bonding \n4 1 affection hmid reflection_period cleaned_hm \\\n0 88305 3m I spent the weekend in Chicago with my friends. \n1 88306 3m We moved back into our house after a remodel. ... \n2 88307 3m My fiance proposed to me in front of my family... \n3 88308 3m I ate lobster at a fancy restaurant with some ... \n4 88309 3m I went out to a nice restaurant on a date with... \n\n num_sentence \n0 1 \n1 2 \n2 1 \n3 1 \n4 5 hmid predicted_category\n0 88305 bonding\n1 88306 achievement\n2 88307 affection\n3 88308 bonding\n4 88309 affection\n(60321, 5) (40213, 4) (5, 2)\n"
]
],
[
[
"- Let’s make a copy of train and test data so that even if we have to make any changes in these datasets we would not lose the original datasets.\n\n",
"_____no_output_____"
]
],
[
[
"train_copy=pd.read_csv('hm_train.csv').copy()\ntest_copy=pd.read_csv('hm_test.csv').copy()\nsubmission_copy=pd.read_csv('sample_submission.csv').copy()",
"_____no_output_____"
]
],
[
[
"# Univariate Analysis",
"_____no_output_____"
]
],
[
[
"print(train.dtypes,test.dtypes,submission.dtypes)",
"hmid int64\nreflection_period object\ncleaned_hm object\nnum_sentence int64\npredicted_category object\ndtype: object hmid int64\nreflection_period object\ncleaned_hm object\nnum_sentence int64\ndtype: object hmid int64\npredicted_category object\ndtype: object\n"
],
[
"train['predicted_category'].value_counts(normalize=True)\n# Read as percentage after multiplying by 100",
"_____no_output_____"
],
[
"train['predicted_category'].value_counts(normalize=True).plot.bar()",
"_____no_output_____"
]
],
[
[
"- exercise featurescontributes approx 2%, nature contributes 3.5 %, leisure contributes 7.5%, enjoy_the_moment does 10%, bonding does 10%, achievement does 34%, and affection does34.5 % to the population sample.",
"_____no_output_____"
],
[
"On Looking at the datsets, we identified that there are 3 Data Types:\n\n- Continuous : reflection_period, cleaned_hm ,num_sentence\n\n- Categorical :Category\n\n- Text : cleaned_hm",
"_____no_output_____"
],
[
"Let's go for Continuous Data Type Exploration. We know that we use BarGraphs for Categorical variable, Histogram or ScatterPlot for continuous variables.",
"_____no_output_____"
]
],
[
[
"# reflection_period\nplt.figure(figsize=(6, 6))\nsns.countplot(train[\"reflection_period\"])\nplt.title('reflection_period')\nplt.show()",
"_____no_output_____"
],
[
"# num_sentence\nplt.figure(figsize=(10, 6))\nsns.countplot(train[\"num_sentence\"])\nplt.title('num_sentence')\nplt.show()",
"_____no_output_____"
],
[
"# predicted_category\nplt.figure(figsize=(13, 6))\nsns.countplot(train[\"predicted_category\"])\nplt.title('predicted_category')\nplt.show()\n",
"_____no_output_____"
],
[
"# Pairplot for cross visualisation of continuous variables\nplt.figure(figsize=(30,30))\nsns.pairplot(train, diag_kind='kde');",
"_____no_output_____"
]
],
[
[
"Data Preprocessing",
"_____no_output_____"
],
[
"- Checking Missing Values",
"_____no_output_____"
]
],
[
[
"def missing_value(df):\n total = df.isnull().sum().sort_values(ascending = False)\n percent = (df.isnull().sum()/df.isnull().count()*100).sort_values(ascending=False)\n missing_df = pd.concat([total, percent], axis=1, keys = ['Total', 'Percent'])\n return missing_df",
"_____no_output_____"
],
[
"mis_train = missing_value(train)\nmis_train",
"_____no_output_____"
],
[
"mis_test = missing_value(test)\nmis_test",
"_____no_output_____"
]
],
[
[
"Text Preprocessing",
"_____no_output_____"
],
[
"- Let's try to understand the writing style if possible :)",
"_____no_output_____"
]
],
[
[
"grouped_df = train.groupby('predicted_category')\nfor name, group in grouped_df:\n print(\"Text : \", name)\n cnt = 0\n for ind, row in group.iterrows():\n print(row[\"cleaned_hm\"])\n cnt += 1\n if cnt == 5:\n break\n print(\"\\n\")",
"Text : achievement\nI made a new recipe for peasant bread, and it came out spectacular!\nI was shorting Gold and made $200 from the trade.\nManaged to get the final trophy in a game I was playing. \nGot A in class.\nThe cake I made today came out amazing. It tasted amazing as well.\n\n\nText : affection\nI went on a successful date with someone I felt sympathy and connection with.\nI was happy when my son got 90% marks in his examination \nI went with grandchildren to butterfly display at Crohn Conservatory\n\nI got gift from my elder brother which was really surprising me\nWatching cupcake wars with my three teen children\n\n\nText : bonding\nWe had a serious talk with some friends of ours who have been flaky lately. They understood and we had a good evening hanging out.\nwent to movies with my friends it was fun \nI helped my neighbour to fix their car damages. \nA hot kiss with my girl friend last night made my day\nWe were competing against another team in a online game, I was playing with my friends most of them were my childhood friends, \nwe grew up together and went to the same school since we're just kids. We've been playing this game together for almost 2 years \nnow and we kinda formed a team for ourselves for this game. The game started smoothly and everyone was being hyped about the fight. \nSlowly, things started to become interesting and exciting then before we know it it became a close fight where the score was 2-2, \n1 more point\nand the winner will be declared. Everyone was looking up to me since they knew I was the best within my friends in\nthis particular game. I started commanding them to what to do and what to expect against our enemies. This game,\n It was a team based game, 5 vs 5. My team was starting to fail and demoralization ensues \nbut I tried and did my best, before I knew it, we won! I maneuvered through each attack of the enemy and with skill\nand with some luck I dodged and countered them.\n\n\nText : enjoy_the_moment\nYESTERDAY MY MOMS BIRTHDAY SO I ENJOYED\nHearing Songs It can be nearly impossible to go from angry to happy, so you're just looking for the thought that eases you out of your angry feeling and moves you in the direction of happiness. It may take a while, but as long as you're headed in a more positive direction youall be doing yourself a world of good.\nThere are two types of people in the world: those who choose to be happy, and those who choose to be unhappy. Contrary to popular belief, happiness doesn't come from fame, fortune, other people, or material possessions\nI cooked and ate a wonderful sausage and cheese omelet.\nThe phone that I have ordered in a local online store was delivered this morning. I like the phone so much!\n\n\nText : exercise\nI went to the gym this morning and did yoga.\nI completed my 5 miles run without break. It makes me feel strong.\nGoing for some running and exercising after three days break.\nAfter taking some off at the gym(due to illness) I was able to wake up early and complete my normal squat workout at the same weight I had done prior to my break. \nI went to sports club and did running and exercise that's why I feel very fresh and happy.\n\n\nText : leisure\nI meditated last night.\nI came in 3rd place in my Call of Duty video game.\nMy co-woker started playing a Carley Rae Jepsen song from her phone while ringing out customers.\nI went shopping \nWe booked our beach vacation for May of this year.\n\n\nText : nature\nGoing to the mountains and hiking the trail to the top.\nI went for a run in the neighborhood. I enjoyed the perfect weather.\n\nI remember yesterday as being totally different from many of my Mondays. It felt like Spring finally, the sun was bright, the temperatures were warm.\nI saw a rainbow and it made me to feel very happy since i have never seen rainbow in reality.\nAfter 3 long weeks of deep snow covered ground we finally had enough warm days in the Northeast for the snow to melt and I was able to start my day with a fantastic hike up the Appalachian trail that runs nearby my home. I felt as though my entire life suddenly came back into balance after being held back for weeks due to the enormous amount of snowfall :)\n\n\n"
]
],
[
[
"Though, there are not very special Characters but some are present like expression of emoji's i.e. :), vs, etc",
"_____no_output_____"
],
[
"### Feature Engineering:",
"_____no_output_____"
],
[
"Now let us come try to do some feature engineering. This consists of two main parts.\n\n- Meta features - features that are extracted from the text like number of words, number of stop words, number of punctuations etc\n- Text based features - features directly based on the text / words like frequency, svd, word2vec etc.\n",
"_____no_output_____"
],
[
"#### Meta Features:",
"_____no_output_____"
],
[
"We will start with creating meta featues and see how good are they at predicting the happiness source. The feature list is as follows:\n\n - Number of words in the text\n - Number of unique words in the text\n - Number of characters in the text\n - Number of stopwords\n - Number of punctuations\n - Number of upper case words\n - Number of title case words\n - Average length of the words\n",
"_____no_output_____"
],
[
"Feature Engineering function",
"_____no_output_____"
]
],
[
[
"import string",
"_____no_output_____"
],
[
"def feature_engineering(df):\n \n ## Number of words in the text ##\n df[\"num_words\"] = df['cleaned_hm'].apply(lambda x: len(str(x).split()))\n \n ## Number of unique words in the text ##\n df[\"num_unique_words\"] = df['cleaned_hm'].apply(lambda x: len(set(str(x).split())))\n \n ## Number of characters in the text ##\n df[\"num_chars\"] = df['cleaned_hm'].apply(lambda x: len(str(x)))\n \n ## Number of stopwords in the text ##\n from nltk.corpus import stopwords\n eng_stopwords = stopwords.words('english')\n df[\"num_stopwords\"] = df['cleaned_hm'].apply(lambda x: len([w for w in str(x).lower().split() if w in eng_stopwords]))\n \n ## Number of punctuations in the text ##\n df[\"num_punctuations\"] =df['cleaned_hm'].apply(lambda x: len([c for c in str(x) if c in string.punctuation]))\n \n ## Number of title case words in the text ##\n df[\"num_words_upper\"] = df['cleaned_hm'].apply(lambda x: len([w for w in str(x).split() if w.isupper()]))\n \n ## Number of title case words in the text ##\n df[\"num_words_title\"] = df['cleaned_hm'].apply(lambda x: len([w for w in str(x).split() if w.istitle()]))\n \n ## Average length of the words in the text ##\n df[\"mean_word_len\"] = df['cleaned_hm'].apply(lambda x: np.mean([len(w) for w in str(x).split()]))\n \n df = pd.concat([df, df[\"num_words\"],df[\"num_unique_words\"],df[\"num_chars\"],df[\"num_stopwords\"],df[\"num_punctuations\"],\n df[\"num_words_upper\"],df[\"num_words_title\"],df[\"mean_word_len\"]],axis=1)\n \n #X = dataset.loc[:,['Transaction-Type','Complaint-reason','Company-response','Consumer-disputes','delayed','converted_text','convertion_language']]\n \n return df",
"_____no_output_____"
],
[
"train = feature_engineering(train)\ntest = feature_engineering(test)",
"_____no_output_____"
],
[
"train.head()",
"_____no_output_____"
]
],
[
[
"Let us now plot some of our new variables to see of they will be helpful in predictions.",
"_____no_output_____"
],
[
"CLEANING THE TEXT !!!",
"_____no_output_____"
]
],
[
[
"def preprocess_text(df):\n \n \"\"\" Here, The function preprocesses the text. It performs stemming, lemmatization\n , stopwords removal, common words and rare words removal and removal of unwanted chractaers. \"\"\"\n \n #removing non-letter symbols and converting text in 'cleaned_hm' to lowercase \n df = df.apply(lambda x: \"\".join(re.sub(r\"[^A-Za-z\\s]\", '',str(x))))\n \n # lower casing the Text\n df = df.apply(lambda x: \" \".join(x.lower() for x in x.split()))\n \n #Removing punctuations\n #adding characters list which needs to remove that is PUNCTUATION\n punc = ['.', ',', '\"', \"'\", '?','#', '!', ':','vs',':)', ';', '(', ')', '[', ']', '{', '}',\"%\",'/','<','>','br','�','^','XX','XXXX','xxxx','xx']\n #removing extra characters\n df = df.apply(lambda x: \" \".join(x for x in x.split() if x not in punc))\n \n import nltk\n nltk.download('stopwords')\n \n #removal of stopwords\n from nltk.corpus import stopwords\n stop = stopwords.words('english')\n df = df.apply(lambda x: \" \".join(x for x in x.split() if x not in stop))\n \n #common words removal\n freq_df = pd.Series(' '.join(df).split()).value_counts()[:10]\n freq_df = list(freq_df.index)\n df = df.apply(lambda x: \" \".join(x for x in x.split() if x not in freq_df))\n \n #rare words removal\n freq_df_rare = pd.Series(' '.join(df).split()).value_counts()[-10:]\n freq_df_rare = list(freq_df_rare.index)\n df = df.apply(lambda x: \" \".join(x for x in x.split() if x not in freq_df_rare))\n \n #STEMMING\n st = PorterStemmer()\n df=df.apply(lambda x: \" \".join([st.stem(w) for w in x.split()]))\n \n # WordNet lexical database for lemmatization\n #from nltk.stem import WordNetLemmatizer\n #lem = WordNetLemmatizer()\n #df=df.apply(lambda x: \" \".join([lem.lemmatize(w) for w in x.split()]))\n \n return df ",
"_____no_output_____"
],
[
"train['cleaned_hm'] = preprocess_text(train['cleaned_hm'])\ntest['cleaned_hm'] = preprocess_text(test['cleaned_hm'])",
"[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\harsh\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n[nltk_data] Downloading package stopwords to\n[nltk_data] C:\\Users\\harsh\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n"
],
[
"# Removing 'h or m extension\ntrain['reflection_period'] = train['reflection_period'].str.rstrip('h | m')\ntest['reflection_period'] = test['reflection_period'].str.rstrip('h | m')",
"_____no_output_____"
],
[
"train['reflection_period'].fillna(train['reflection_period'].mode()[0], inplace=True)\ntrain['cleaned_hm'].fillna(train['cleaned_hm'].mode()[0], inplace=True)\ntrain['num_sentence'].fillna(train['num_sentence'].mode()[0], inplace=True)\ntrain['predicted_category'].fillna(train['predicted_category'].mode()[0], inplace=True)",
"D:\\Anaconda3\\lib\\site-packages\\pandas\\core\\generic.py:6130: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n self._update_inplace(new_data)\n"
],
[
"test['reflection_period'].fillna(test['reflection_period'].mode()[0], inplace=True)\ntest['cleaned_hm'].fillna(test['cleaned_hm'].mode()[0], inplace=True)\ntest['num_sentence'].fillna(test['num_sentence'].mode()[0], inplace=True)",
"_____no_output_____"
],
[
"#NOw We will convert the target variable into LabelEncoder\ny_train = train.loc[:,['predicted_category']]\nlabelencoder1 = LabelEncoder()\nlabelencoder1.fit(y_train.values)\ny_train=labelencoder1.transform(y_train)",
"D:\\Anaconda3\\lib\\site-packages\\sklearn\\preprocessing\\label.py:219: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\nD:\\Anaconda3\\lib\\site-packages\\sklearn\\preprocessing\\label.py:252: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().\n y = column_or_1d(y, warn=True)\n"
],
[
"train.columns",
"_____no_output_____"
],
[
"x = train.loc[:,[\"num_sentence\",\"reflection_period\",'num_sentence',\n 'num_words', 'num_unique_words', 'num_chars',\n 'num_stopwords', 'num_punctuations', 'num_words_upper',\n 'num_words_title', 'mean_word_len', 'num_words', 'num_unique_words',\n 'num_chars', 'num_stopwords', 'num_punctuations', 'num_words_upper',\n 'num_words_title', 'mean_word_len']]\n\nx1 = test.loc[:,[\"num_sentence\",\"reflection_period\",'num_sentence',\n 'num_words', 'num_unique_words', 'num_chars',\n 'num_stopwords', 'num_punctuations', 'num_words_upper',\n 'num_words_title', 'mean_word_len', 'num_words', 'num_unique_words',\n 'num_chars', 'num_stopwords', 'num_punctuations', 'num_words_upper',\n 'num_words_title', 'mean_word_len']]",
"_____no_output_____"
],
[
"from sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import TfidfTransformer",
"_____no_output_____"
],
[
"import gensim",
"_____no_output_____"
],
[
"from gensim.models import Word2Vec\n\nwv = gensim.models.KeyedVectors.load_word2vec_format(\"GoogleNews-vectors-negative300.bin.gz\",limit=50000, binary=True)\nwv.init_sims(replace=True)",
"D:\\Anaconda3\\lib\\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"
],
[
"from itertools import islice\nlist(islice(wv.vocab, 13030, 13050))",
"_____no_output_____"
],
[
"def word_averaging(wv, words):\n all_words, mean = set(), []\n \n for word in words:\n if isinstance(word, np.ndarray):\n mean.append(word)\n elif word in wv.vocab:\n mean.append(wv.syn0norm[wv.vocab[word].index])\n all_words.add(wv.vocab[word].index)\n\n if not mean:\n logging.warning(\"cannot compute similarity with no input %s\", words)\n # FIXME: remove these examples in pre-processing\n return np.zeros(wv.vector_size,)\n\n mean = gensim.matutils.unitvec(np.array(mean).mean(axis=0)).astype(np.float32)\n return mean\n\ndef word_averaging_list(wv, text_list):\n return np.vstack([word_averaging(wv, post) for post in text_list ])",
"_____no_output_____"
],
[
"def w2v_tokenize_text(text):\n tokens = []\n for sent in nltk.sent_tokenize(text, language='english'):\n for word in nltk.word_tokenize(sent, language='english'):\n if len(word) < 2:\n continue\n tokens.append(word)\n return tokens",
"_____no_output_____"
],
[
"nltk.download('punkt')",
"[nltk_data] Downloading package punkt to\n[nltk_data] C:\\Users\\harsh\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n"
],
[
"alldata = pd.concat([train, test], axis=1)",
"_____no_output_____"
],
[
"# initialise the functions - we'll create separate models for each type.\ncountvec = CountVectorizer(analyzer='word', ngram_range = (1,2), max_features=500)\ntfidfvec = TfidfVectorizer(analyzer='word', ngram_range = (1,2), max_features=500)",
"_____no_output_____"
],
[
"# create features\nbagofwords = countvec.fit_transform(alldata['cleaned_hm'])\ntfidfdata = tfidfvec.fit_transform(alldata['cleaned_hm'])",
"_____no_output_____"
],
[
"# create dataframe for features\nbow_df = pd.DataFrame(bagofwords.todense())\ntfidf_df = pd.DataFrame(tfidfdata.todense())",
"_____no_output_____"
],
[
"# set column names\nbow_df.columns = ['col'+ str(x) for x in bow_df.columns]\ntfidf_df.columns = ['col' + str(x) for x in tfidf_df.columns]",
"_____no_output_____"
],
[
"# create separate data frame for bag of words and tf-idf\n\nbow_df_train = bow_df[:len(train)]\nbow_df_test = bow_df[len(train):]\n\ntfid_df_train = tfidf_df[:len(train)]\ntfid_df_test = tfidf_df[len(train):]",
"_____no_output_____"
],
[
"# split the merged data file into train and test respectively\ntrain_feats = alldata[~pd.isnull(alldata.predicted_category)]\ntest_feats = alldata[pd.isnull(alldata.predicted_category)]",
"_____no_output_____"
],
[
"# merge count (bag of word) features into train\nx_train = pd.concat([x, bow_df_train], axis = 1)\nx_test = pd.concat([x1, bow_df_test], axis=1)\n\n\nx_test.reset_index(drop=True, inplace=True)",
"_____no_output_____"
],
[
"from sklearn.linear_model import LogisticRegression\nlogreg = LogisticRegression(n_jobs=-1, penalty = 'l1',C=1.0,random_state = 0)\nlogreg = logreg.fit(x_train, train['cleaned_hm'])\ny_pred = logreg.predict(x_test)",
"D:\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\logistic.py:433: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.\n FutureWarning)\n"
],
[
"ans = labelencoder1.inverse_transform(y_pred)\ntype(ans)\nans = pd.DataFrame(ans)",
"_____no_output_____"
],
[
"id1=test.loc[:,['hmid']]\nfinal_ans = [id1, ans]\nfinal_ans = pd.concat(final_ans, axis=1)\nfinal_ans.columns = ['hmid', 'predicted_category']\nfinal_ans.to_csv('vdemo_HK.csv',index=False)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"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"
]
] |
cbd741ea276424f1fb1119a39859bd8d2562a0ad
| 344,459 |
ipynb
|
Jupyter Notebook
|
Max/MNIST-ORBM-Inference.ipynb
|
garibaldu/multicauseRBM
|
f64f54435f23d04682ac7c15f895a1cf470c51e8
|
[
"MIT"
] | null | null | null |
Max/MNIST-ORBM-Inference.ipynb
|
garibaldu/multicauseRBM
|
f64f54435f23d04682ac7c15f895a1cf470c51e8
|
[
"MIT"
] | null | null | null |
Max/MNIST-ORBM-Inference.ipynb
|
garibaldu/multicauseRBM
|
f64f54435f23d04682ac7c15f895a1cf470c51e8
|
[
"MIT"
] | null | null | null | 122.670584 | 8,698 | 0.856154 |
[
[
[
"from scipy.special import expit\nfrom rbm import RBM\nfrom sampler import VanillaSampler, PartitionedSampler\nfrom trainer import VanillaTrainier\nfrom performance import Result\nimport numpy as np\nimport datasets, performance, plotter, mnist, pickle, rbm, os, logging\n\nlogger = logging.getLogger()\n# Set the logging level to logging.DEBUG to \nlogger.setLevel(logging.INFO)\n\n\n%matplotlib inline\n\nmodels_names = [\n \"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\", \"eight\", \"nine\", \"bar\",\"two_three\"]\n# RBM's keyed by a label of what they were trained on\nmodels = datasets.load_models(models_names)",
"_____no_output_____"
],
[
"data_set_size = 40\nnumber_gibbs_alternations = 1000\n# the model we will be `corrupting` the others with, in this case we are adding bars to the digit models\ncorruption_model_name = \"bar\"\n\ndef result_key(data_set_size, num_gibbs_alternations, model_name, corruption_name):\n return '{}Size_{}nGibbs_{}Model_{}Corruption'.format(data_set_size, number_gibbs_alternations, model_name, corruption_name)\n\ndef results_for_models(models, corruption_model_name, data_set_size, num_gibbs_alternations):\n \n results = {}\n for model_name in models:\n if model_name is not corruption_model_name:\n key = result_key(data_set_size, number_gibbs_alternations, model_name, corruption_model_name)\n logging.info(\"Getting result for {}\".format(model_name))\n model_a = models[model_name] \n model_b = models[corruption_model_name]\n model_a_data = model_a.visible[:data_set_size]#visibles that model_a was fit to. \n model_b_data = model_b.visible[:data_set_size]#visibles that model_b was fit to. \n r = Result(data_set_size, num_gibbs_alternations, model_a, model_b,model_a_data, model_b_data)\n r.calculate_result()\n results[key] = r\n return results\n \nresults = results_for_models(models, corruption_model_name, data_set_size, number_gibbs_alternations)",
"INFO:root:Getting result for nine\n"
],
[
"for key in models:\n# plotter.plot(results[key].composite)\n# plotter.plot(results[key].visibles_for_stored_hidden(9)[0])\n# plotter.plot(results[key].vis_van_a)\n plotter.plot(models[key].visible[:40])\n",
"_____no_output_____"
]
],
[
[
"#In the cell below #\n\nI have calculated in the previous cell the loglikelyhood score of the partitioned sampling and vanilla sampling technique image-wise. So I have a score for each image. I have done this for all the MNIST digits that have been 'corrupted' by the bar images. That is RBM's trained models 1 - 9 and an RBM trained on 2's and 3's\n\nThe `wins` for a given model are where the partitioned scored better than the vanilla sampling technique\n\nConversly, `losses` are images where the vanilla score better.\n\nIntuitively, `ties` is where they scored the same, which could only really occur when the correction would be zero, or ultimately cancelled out.",
"_____no_output_____"
]
],
[
[
"for key in results:\n logging.info(\"Plotting, win, lose and tie images for the {}\".format(key))\n results[key].plot_various_images()",
"INFO:root:Plotting, win, lose and tie images for the 400Size_100nGibbs_fiveModel_barCorruption\n"
]
],
[
[
"#Thoughts#\n\nSo on a dataset of size 50, with 100 gibbs alterations we see in all cases that for the digit model, 1,2,3,..,9 that the partitioned sampling technique does either better or the same more often than the vanilla does. Let's try some different configurations.",
"_____no_output_____"
]
],
[
[
"results.update(results_for_models(models, corruption_model_name, 400, 500))",
"INFO:root:Getting result for four\n"
]
],
[
[
"results.update(results_for_models(models, corruption_model_name, 10, 1))",
"_____no_output_____"
]
],
[
[
"results",
"_____no_output_____"
],
[
"# with open('results_dict', 'wb') as f3le:\n# pickle.dump(results,f3le, protocol = None)\nwith open('results_dict', 'rb') as f4le:\n results = pickle.load(f4le)",
"_____no_output_____"
],
[
"# for key in results:\n# if key.startswith('400'):\n# logging.info(\"Results for hiddens\")\n# r = results[key].stored_hiddens\n# for i in range(len(r)):\n# print(results[key].imagewise_score())\n ",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbd74204c55d5f3968a162fdbee30d2b131e512e
| 12,657 |
ipynb
|
Jupyter Notebook
|
08_Multithreading_Basics.ipynb
|
tuanvo-git/2022-rwth-julia-workshop
|
0b10ede0d49b4121adb9f6932a10623f7eef7015
|
[
"MIT"
] | null | null | null |
08_Multithreading_Basics.ipynb
|
tuanvo-git/2022-rwth-julia-workshop
|
0b10ede0d49b4121adb9f6932a10623f7eef7015
|
[
"MIT"
] | null | null | null |
08_Multithreading_Basics.ipynb
|
tuanvo-git/2022-rwth-julia-workshop
|
0b10ede0d49b4121adb9f6932a10623f7eef7015
|
[
"MIT"
] | null | null | null | 25.936475 | 511 | 0.558584 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbd754b96eafc66c266eff2bdc2b321ea6fd6076
| 677,160 |
ipynb
|
Jupyter Notebook
|
examples/ode_demo.ipynb
|
rollervan/torchdiffeq
|
676c1869388beb7d5d093c065cb4e72f81c76562
|
[
"MIT"
] | null | null | null |
examples/ode_demo.ipynb
|
rollervan/torchdiffeq
|
676c1869388beb7d5d093c065cb4e72f81c76562
|
[
"MIT"
] | null | null | null |
examples/ode_demo.ipynb
|
rollervan/torchdiffeq
|
676c1869388beb7d5d093c065cb4e72f81c76562
|
[
"MIT"
] | null | null | null | 1,525.135135 | 159,672 | 0.954525 |
[
[
[
"!pip install matplotlib\nimport os\nimport argparse\nimport time\nimport numpy as np",
"_____no_output_____"
],
[
"import torch\nimport torch.nn as nn\nimport torch.optim as optim",
"_____no_output_____"
],
[
"class Args:\n method = 'dopri5' # choices=['dopri5', 'adams']\n data_size = 1000\n batch_time = 10\n batch_size = 20\n niters = 2000\n test_freq = 20\n viz = True\n gpu = True\n adjoint = False\n\nargs=Args()",
"_____no_output_____"
],
[
"if args.adjoint:\n from torchdiffeq import odeint_adjoint as odeint\nelse:\n from torchdiffeq import odeint",
"_____no_output_____"
],
[
"device = torch.device('cuda:' + str(args.gpu) if torch.cuda.is_available() else 'cpu')",
"_____no_output_____"
],
[
"true_y0 = torch.tensor([[2., 0.]])\nt = torch.linspace(0., 25., args.data_size)\ntrue_A = torch.tensor([[-0.1, 2.0], [-2.0, -0.1]])",
"_____no_output_____"
],
[
"class Lambda(nn.Module):\n\n def forward(self, t, y):\n return torch.mm(y**3, true_A)",
"_____no_output_____"
],
[
"with torch.no_grad():\n true_y = odeint(Lambda(), true_y0, t, method='dopri5')",
"_____no_output_____"
],
[
"def get_batch():\n s = torch.from_numpy(np.random.choice(np.arange(args.data_size - args.batch_time, dtype=np.int64), args.batch_size, replace=False))\n batch_y0 = true_y[s] # (M, D)\n batch_t = t[:args.batch_time] # (T)\n batch_y = torch.stack([true_y[s + i] for i in range(args.batch_time)], dim=0) # (T, M, D)\n return batch_y0, batch_t, batch_y",
"_____no_output_____"
],
[
"def makedirs(dirname):\n if not os.path.exists(dirname):\n os.makedirs(dirname)",
"_____no_output_____"
],
[
"def visualize(true_y, pred_y, odefunc, itr):\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize=(12, 4), facecolor='white')\n ax_traj = fig.add_subplot(131, frameon=False)\n ax_phase = fig.add_subplot(132, frameon=False)\n ax_vecfield = fig.add_subplot(133, frameon=False)\n makedirs('png')\n\n if args.viz:\n \n\n\n ax_traj.cla()\n ax_traj.set_title('Trajectories')\n ax_traj.set_xlabel('t')\n ax_traj.set_ylabel('x,y')\n ax_traj.plot(t.numpy(), true_y.numpy()[:, 0, 0], t.numpy(), true_y.numpy()[:, 0, 1], 'g-')\n ax_traj.plot(t.numpy(), pred_y.numpy()[:, 0, 0], '--', t.numpy(), pred_y.numpy()[:, 0, 1], 'b--')\n ax_traj.set_xlim(t.min(), t.max())\n ax_traj.set_ylim(-2, 2)\n ax_traj.legend()\n\n ax_phase.cla()\n ax_phase.set_title('Phase Portrait')\n ax_phase.set_xlabel('x')\n ax_phase.set_ylabel('y')\n ax_phase.plot(true_y.numpy()[:, 0, 0], true_y.numpy()[:, 0, 1], 'g-')\n ax_phase.plot(pred_y.numpy()[:, 0, 0], pred_y.numpy()[:, 0, 1], 'b--')\n ax_phase.set_xlim(-2, 2)\n ax_phase.set_ylim(-2, 2)\n\n ax_vecfield.cla()\n ax_vecfield.set_title('Learned Vector Field')\n ax_vecfield.set_xlabel('x')\n ax_vecfield.set_ylabel('y')\n\n y, x = np.mgrid[-2:2:21j, -2:2:21j]\n dydt = odefunc(0, torch.Tensor(np.stack([x, y], -1).reshape(21 * 21, 2))).cpu().detach().numpy()\n mag = np.sqrt(dydt[:, 0]**2 + dydt[:, 1]**2).reshape(-1, 1)\n dydt = (dydt / mag)\n dydt = dydt.reshape(21, 21, 2)\n\n ax_vecfield.streamplot(x, y, dydt[:, :, 0], dydt[:, :, 1], color=\"black\")\n ax_vecfield.set_xlim(-2, 2)\n ax_vecfield.set_ylim(-2, 2)\n\n fig.tight_layout()\n plt.savefig('png/{:03d}'.format(itr))\n plt.draw()\n plt.pause(0.001);\n ",
"_____no_output_____"
],
[
"class ODEFunc(nn.Module):\n\n def __init__(self):\n super(ODEFunc, self).__init__()\n\n self.net = nn.Sequential(\n nn.Linear(2, 50),\n nn.Tanh(),\n nn.Linear(50, 2),\n )\n\n for m in self.net.modules():\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0, std=0.1)\n nn.init.constant_(m.bias, val=0)\n\n def forward(self, t, y):\n return self.net(y**3)",
"_____no_output_____"
],
[
"class RunningAverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self, momentum=0.99):\n self.momentum = momentum\n self.reset()\n\n def reset(self):\n self.val = None\n self.avg = 0\n\n def update(self, val):\n if self.val is None:\n self.avg = val\n else:\n self.avg = self.avg * self.momentum + val * (1 - self.momentum)\n self.val = val",
"_____no_output_____"
],
[
"%matplotlib inline\nii = 0\n\nfunc = ODEFunc()\noptimizer = optim.RMSprop(func.parameters(), lr=1e-3)\nend = time.time()\n\ntime_meter = RunningAverageMeter(0.97)\nloss_meter = RunningAverageMeter(0.97)\n\nfor itr in range(1, args.niters + 1):\n optimizer.zero_grad()\n batch_y0, batch_t, batch_y = get_batch()\n pred_y = odeint(func, batch_y0, batch_t)\n loss = torch.mean(torch.abs(pred_y - batch_y))\n loss.backward()\n optimizer.step()\n\n time_meter.update(time.time() - end)\n loss_meter.update(loss.item())\n\n if itr % args.test_freq == 0:\n with torch.no_grad():\n pred_y = odeint(func, true_y0, t)\n loss = torch.mean(torch.abs(pred_y - true_y))\n print('Iter {:04d} | Total Loss {:.6f}'.format(itr, loss.item()))\n visualize(true_y, pred_y, func, ii)\n ii += 1\n\n end = time.time()",
"No handles with labels found to put in legend.\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd75a17839dd014d85cdb2a6252c3dafd2b0fd7
| 3,031 |
ipynb
|
Jupyter Notebook
|
2020/Day 02.ipynb
|
AwesomeGitHubRepos/adventofcode
|
84ba7963a5d7905973f14bb1c2e3a59165f8b398
|
[
"MIT"
] | 96 |
2018-04-21T07:53:34.000Z
|
2022-03-15T11:00:02.000Z
|
2020/Day 02.ipynb
|
AwesomeGitHubRepos/adventofcode
|
84ba7963a5d7905973f14bb1c2e3a59165f8b398
|
[
"MIT"
] | 17 |
2019-02-07T05:14:47.000Z
|
2021-12-27T12:11:04.000Z
|
2020/Day 02.ipynb
|
AwesomeGitHubRepos/adventofcode
|
84ba7963a5d7905973f14bb1c2e3a59165f8b398
|
[
"MIT"
] | 14 |
2019-02-05T06:34:15.000Z
|
2022-01-24T17:35:00.000Z
| 24.248 | 163 | 0.511052 |
[
[
[
"# Counting letters\n\n* https://adventofcode.com/2020/day/2\n\nI like to use a dataclass for parsing tasks like these. A single regex to read out each line, and methods on the class to implement the password rule checks.",
"_____no_output_____"
]
],
[
[
"import re\nfrom dataclasses import dataclass\n\n_line = re.compile(r'^(?P<min_>\\d+)-(?P<max_>\\d+) (?P<letter>[a-z]):\\s*(?P<password>[a-z]+)$')\n\n@dataclass\nclass PWRule:\n min_: int\n max_: int\n letter: str\n password: str\n\n @classmethod\n def from_line(cls, line: str) -> 'PWRule':\n match = _line.search(line)\n min_, max_ = int(match['min_']), int(match['max_'])\n return cls(min_, max_, match['letter'], match['password'])\n\n def is_valid(self) -> bool:\n return self.min_ <= self.password.count(self.letter) <= self.max_\n\n def is_valid_toboggan_policy(self) -> bool:\n return (self.password[self.min_ - 1], self.password[self.max_ - 1]).count(self.letter) == 1\n\n\ndef read_passwords(lines):\n return [PWRule.from_line(l) for l in lines]\n\n\ntest = read_passwords('''\\\n1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc\n'''.splitlines())\n\nassert sum(pwr.is_valid() for pwr in test) == 2\nassert sum(pwr.is_valid_toboggan_policy() for pwr in test) == 1",
"_____no_output_____"
],
[
" import aocd\n rules = read_passwords(aocd.get_data(day=2, year=2020).splitlines())",
"_____no_output_____"
],
[
"print('Part 1:', sum(pwr.is_valid() for pwr in rules))",
"Part 1: 591\n"
],
[
"print('Part 2:', sum(pwr.is_valid_toboggan_policy() for pwr in rules))",
"Part 2: 335\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cbd7633f387e6ac70b9523c22c2e5e1f0f74f1c3
| 31,987 |
ipynb
|
Jupyter Notebook
|
Codes/Results_For_PPT-Pareto/NPB_EP_physical_all_models_except_dnn.ipynb
|
rajatgupta1234/Evaluating-Machine-Learning-Models-for-Disparate-Computer-Systems-Performance-Prediction
|
f338ee90d31a2358a136d01268c8b1172ed41d0b
|
[
"MIT"
] | 1 |
2021-01-11T16:29:48.000Z
|
2021-01-11T16:29:48.000Z
|
Codes/Results_For_PPT-Pareto/NPB_EP_physical_all_models_except_dnn.ipynb
|
rajatgupta1234/Evaluating-Machine-Learning-Models-for-Disparate-Computer-Systems-Performance-Prediction
|
f338ee90d31a2358a136d01268c8b1172ed41d0b
|
[
"MIT"
] | null | null | null |
Codes/Results_For_PPT-Pareto/NPB_EP_physical_all_models_except_dnn.ipynb
|
rajatgupta1234/Evaluating-Machine-Learning-Models-for-Disparate-Computer-Systems-Performance-Prediction
|
f338ee90d31a2358a136d01268c8b1172ed41d0b
|
[
"MIT"
] | null | null | null | 58.264117 | 336 | 0.614781 |
[
[
[
"from sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import GridSearchCV \nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.metrics import accuracy_score\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.optimizers import SGD\nfrom matplotlib import pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport category_encoders as ce\nimport os\nimport pickle\nimport gc\nfrom tqdm import tqdm\nimport pickle\nfrom sklearn.svm import SVR\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import linear_model\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn import ensemble\nimport xgboost as xgb",
"Using TensorFlow backend.\n"
],
[
"def encode_text_features(encode_decode, data_frame, encoder_isa=None, encoder_mem_type=None):\n # Implement Categorical OneHot encoding for ISA and mem-type\n if encode_decode == 'encode':\n encoder_isa = ce.one_hot.OneHotEncoder(cols=['isa'])\n encoder_mem_type = ce.one_hot.OneHotEncoder(cols=['mem-type'])\n encoder_isa.fit(data_frame, verbose=1)\n df_new1 = encoder_isa.transform(data_frame)\n encoder_mem_type.fit(df_new1, verbose=1)\n df_new = encoder_mem_type.transform(df_new1)\n encoded_data_frame = df_new\n else:\n df_new1 = encoder_isa.transform(data_frame)\n df_new = encoder_mem_type.transform(df_new1)\n encoded_data_frame = df_new\n \n return encoded_data_frame, encoder_isa, encoder_mem_type",
"_____no_output_____"
],
[
"def absolute_percentage_error(Y_test, Y_pred):\n error = 0\n for i in range(len(Y_test)):\n if(Y_test[i]!= 0 ):\n error = error + (abs(Y_test[i] - Y_pred[i]))/Y_test[i]\n \n error = error/ len(Y_test)\n return error",
"_____no_output_____"
],
[
"def process_all(dataset_path, dataset_name, path_for_saving_data):\n \n ################## Data Preprocessing ######################\n df = pd.read_csv(dataset_path)\n encoded_data_frame, encoder_isa, encoder_mem_type = encode_text_features('encode', df, \n encoder_isa = None, encoder_mem_type=None)\n # total_data = encoded_data_frame.drop(columns = ['arch', 'arch1'])\n \n total_data = encoded_data_frame.drop(columns = ['arch', 'sys','sysname','executable','PS'])\n total_data = total_data.fillna(0)\n X_columns = total_data.drop(columns = 'runtime').columns\n X = total_data.drop(columns = ['runtime']).to_numpy()\n Y = total_data['runtime'].to_numpy()\n # X_columns = total_data.drop(columns = 'PS').columns\n # X = total_data.drop(columns = ['runtime','PS']).to_numpy()\n # Y = total_data['runtime'].to_numpy()\n print('Data X and Y shape', X.shape, Y.shape)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)\n print('Train Test Split:', X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)\n scaler = StandardScaler()\n X_train = scaler.fit_transform(X_train)\n X_test = scaler.fit_transform(X_test)\n ################## Data Preprocessing ######################\n \n # Put best models here using grid search\n \n # 1. SVR \n best_svr =SVR(C=1000, cache_size=200, coef0=0.0, degree=3, epsilon=0.1, gamma=0.1,\n kernel='rbf', max_iter=-1, shrinking=True, tol=0.001, verbose=False)\n\n \n # 2. LR\n best_lr = LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=True)\n \n # 3. RR\n best_rr = linear_model.Ridge(alpha=10, copy_X=True, fit_intercept=True, max_iter=None, normalize=False,\n random_state=None, solver='svd', tol=0.001)\n \n # 4. KNN\n best_knn = KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',\n metric_params=None, n_jobs=None, n_neighbors=2, p=1,\n weights='distance')\n \n # 5. GPR\n best_gpr = GaussianProcessRegressor(alpha=0.01, copy_X_train=True, kernel=None,\n n_restarts_optimizer=0, normalize_y=True,\n optimizer='fmin_l_bfgs_b', random_state=None)\n # 6. Decision Tree\n best_dt = DecisionTreeRegressor(criterion='mse', max_depth=7, max_features='auto',\n max_leaf_nodes=None, min_impurity_decrease=0.0,\n min_impurity_split=None, min_samples_leaf=1,\n min_samples_split=2, min_weight_fraction_leaf=0.0,\n presort=False, random_state=None, splitter='best')\n \n # 7. Random Forest \n best_rf = RandomForestRegressor(bootstrap=True, criterion='friedman_mse', max_depth=7,\n max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=10,\n n_jobs=None, oob_score=False, random_state=None,\n verbose=0, warm_start='False')\n \n # 8. Extra Trees Regressor\n best_etr = ExtraTreesRegressor(bootstrap=False, criterion='friedman_mse', max_depth=15,\n max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=200, n_jobs=None,\n oob_score=False, random_state=None, verbose=0,\n warm_start='True')\n \n # 9. GBR\n best_gbr = ensemble.GradientBoostingRegressor(alpha=0.9, criterion='mae', init=None,\n learning_rate=0.1, loss='lad', max_depth=None,\n max_features=None, max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_iter_no_change=None, presort='auto',\n random_state=42, subsample=1.0, tol=0.0001,\n validation_fraction=0.1, verbose=0, warm_start=False)\n \n # 10. XGB\n best_xgb = xgb.XGBRegressor(alpha=10, base_score=0.5, booster='gbtree', colsample_bylevel=1,\n colsample_bynode=1, colsample_bytree=0.3, gamma=0,\n importance_type='gain', learning_rate=0.5, max_delta_step=0,\n max_depth=10, min_child_weight=1, missing=None, n_estimators=100,\n n_jobs=1, nthread=None, objective='reg:linear', random_state=0,\n reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,\n silent=None, subsample=1, validate_parameters=False, verbosity=1)\n \n best_models = [best_svr, best_lr, best_rr, best_knn, best_gpr, best_dt, best_rf, best_etr, best_gbr, best_xgb]\n best_models_name = ['best_svr', 'best_lr', 'best_rr', 'best_knn', 'best_gpr', 'best_dt', 'best_rf', 'best_etr'\n , 'best_gbr', 'best_xgb']\n k = 0\n \n df = pd.DataFrame(columns = ['model_name', 'dataset_name', 'r2', 'mse', 'mape', 'mae' ])\n \n for model in best_models:\n \n print('Running model number:', k+1, 'with Model Name: ', best_models_name[k])\n r2_scores = []\n mse_scores = []\n mape_scores = []\n mae_scores = []\n\n # cv = KFold(n_splits = 10, random_state = 42, shuffle = True)\n cv = ShuffleSplit(n_splits=10, random_state=0, test_size = 0.4)\n # print(cv)\n \n fold = 1\n for train_index, test_index in cv.split(X):\n model_orig = model\n # print(\"Train Index: \", train_index, \"\\n\")\n # print(\"Test Index: \", test_index)\n\n X_train_fold, X_test_fold, Y_train_fold, Y_test_fold = X[train_index], X[test_index], Y[train_index], Y[test_index]\n # print(X_train_fold.shape, X_test_fold.shape, Y_train_fold.shape, Y_test_fold.shape)\n model_orig.fit(X_train_fold, Y_train_fold)\n Y_pred_fold = model_orig.predict(X_test_fold)\n \n # save the folds to disk\n data = [X_train_fold, X_test_fold, Y_train_fold, Y_test_fold]\n filename = path_for_saving_data + '/folds_data/' + best_models_name[k] +'_'+ str(fold) + '.pickle'\n # pickle.dump(data, open(filename, 'wb'))\n \n \n # save the model to disk\n # filename = path_for_saving_data + '/models_data/' + best_models_name[k] + '_' + str(fold) + '.sav'\n fold = fold + 1\n # pickle.dump(model_orig, open(filename, 'wb'))\n\n # some time later...\n '''\n # load the model from disk\n loaded_model = pickle.load(open(filename, 'rb'))\n result = loaded_model.score(X_test, Y_test)\n print(result)\n '''\n # scores.append(best_svr.score(X_test, y_test))\n '''\n plt.figure()\n plt.plot(Y_test_fold, 'b')\n plt.plot(Y_pred_fold, 'r')\n '''\n # print('Accuracy =',accuracy_score(Y_test, Y_pred))\n r2_scores.append(r2_score(Y_test_fold, Y_pred_fold))\n mse_scores.append(mean_squared_error(Y_test_fold, Y_pred_fold))\n mape_scores.append(absolute_percentage_error(Y_test_fold, Y_pred_fold))\n mae_scores.append(mean_absolute_error(Y_test_fold, Y_pred_fold))\n \n df = df.append({'model_name': best_models_name[k], 'dataset_name': dataset_name\n , 'r2': r2_scores, 'mse': mse_scores, 'mape': mape_scores, 'mae': mae_scores }, ignore_index=True)\n k = k + 1 \n print(df.head())\n df.to_csv(r'runtimes_final_npb_ep_60.csv')\n",
"_____no_output_____"
],
[
"dataset_name = 'runtimes_final_npb_ep'\ndataset_path = 'C:\\\\Users\\\\Rajat\\\\Desktop\\\\DESKTOP_15_05_2020\\\\Evaluating-Machine-Learning-Models-for-Disparate-Computer-Systems-Performance-Prediction\\\\Dataset_CSV\\\\PhysicalSystems\\\\runtimes_final_npb_ep.csv'\npath_for_saving_data = 'data\\\\' + dataset_name\nprocess_all(dataset_path, dataset_name, path_for_saving_data)",
"Data X and Y shape (108, 21) (108,)\nTrain Test Split: (86, 21) (22, 21) (86,) (22,)\nRunning model number: 1 with Model Name: best_svr\nRunning model number: 2 with Model Name: best_lr\nRunning model number: 3 with Model Name: best_rr\nRunning model number: 4 with Model Name: best_knn\nRunning model number: 5 with Model Name: best_gpr\nRunning model number: 6 with Model Name: best_dt\n"
],
[
"df = pd.DataFrame(columns = ['model_name', 'dataset_name', 'r2', 'mse', 'mape', 'mae' ])",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd766953422f789c0b042f0eea15f7ab8e10f80
| 20,035 |
ipynb
|
Jupyter Notebook
|
Assignment/Assignment+2.ipynb
|
Hassanchatouani/Applied-Text-Mining-in-Python
|
ad9905e6f5406211da3a7147babd8e3e3ac61bbb
|
[
"MIT"
] | 3 |
2020-12-20T16:54:06.000Z
|
2021-11-20T14:01:03.000Z
|
Assignment/Assignment+2.ipynb
|
Hassanchatouani/Applied-Text-Mining-in-Python
|
ad9905e6f5406211da3a7147babd8e3e3ac61bbb
|
[
"MIT"
] | null | null | null |
Assignment/Assignment+2.ipynb
|
Hassanchatouani/Applied-Text-Mining-in-Python
|
ad9905e6f5406211da3a7147babd8e3e3ac61bbb
|
[
"MIT"
] | 2 |
2020-09-12T09:46:43.000Z
|
2021-11-03T00:18:45.000Z
| 25.489822 | 294 | 0.51989 |
[
[
[
"---\n\n_You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._\n\n---",
"_____no_output_____"
],
[
"# Assignment 2 - Introduction to NLTK\n\nIn part 1 of this assignment you will use nltk to explore the Herman Melville novel Moby Dick. Then in part 2 you will create a spelling recommender function that uses nltk to find words similar to the misspelling. ",
"_____no_output_____"
],
[
"## Part 1 - Analyzing Moby Dick",
"_____no_output_____"
]
],
[
[
"import nltk\nimport pandas as pd\nimport numpy as np\n\nimport nltk\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('averaged_perceptron_tagger')\n# If you would like to work with the raw text you can use 'moby_raw'\nwith open('moby.txt', 'r') as f:\n moby_raw = f.read()\n \n# If you would like to work with the novel in nltk.Text format you can use 'text1'\nmoby_tokens = nltk.word_tokenize(moby_raw)\ntext1 = nltk.Text(moby_tokens)",
"[nltk_data] Downloading package punkt to /home/jovyan/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n[nltk_data] Downloading package wordnet to /home/jovyan/nltk_data...\n[nltk_data] Package wordnet is already up-to-date!\n[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] /home/jovyan/nltk_data...\n[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n"
]
],
[
[
"### Example 1\n\nHow many tokens (words and punctuation symbols) are in text1?\n\n*This function should return an integer.*",
"_____no_output_____"
]
],
[
[
"def example_one():\n \n return len(nltk.word_tokenize(moby_raw)) # or alternatively len(text1)\n\nexample_one()",
"_____no_output_____"
]
],
[
[
"### Example 2\n\nHow many unique tokens (unique words and punctuation) does text1 have?\n\n*This function should return an integer.*",
"_____no_output_____"
]
],
[
[
"def example_two():\n \n return len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1))\n\nexample_two()",
"_____no_output_____"
]
],
[
[
"### Example 3\n\nAfter lemmatizing the verbs, how many unique tokens does text1 have?\n\n*This function should return an integer.*",
"_____no_output_____"
]
],
[
[
"from nltk.stem import WordNetLemmatizer\n\ndef example_three():\n\n lemmatizer = WordNetLemmatizer()\n lemmatized = [lemmatizer.lemmatize(w,'v') for w in text1]\n\n return len(set(lemmatized))\n\nexample_three()",
"_____no_output_____"
]
],
[
[
"### Question 1\n\nWhat is the lexical diversity of the given text input? (i.e. ratio of unique tokens to the total number of tokens)\n\n*This function should return a float.*",
"_____no_output_____"
]
],
[
[
"def answer_one():\n \n unique = len(set(nltk.word_tokenize(moby_raw))) # or alternatively len(set(text1))\n tot = len(nltk.word_tokenize(moby_raw))\n return unique/tot\n\nanswer_one()",
"_____no_output_____"
]
],
[
[
"### Question 2\n\nWhat percentage of tokens is 'whale'or 'Whale'?\n\n*This function should return a float.*",
"_____no_output_____"
]
],
[
[
"def answer_two():\n\n tot = nltk.word_tokenize(moby_raw)\n count = [w for w in tot if w == \"Whale\" or w == \"whale\"]\n \n return 100*len(count)/len(tot)\n\nanswer_two()",
"_____no_output_____"
]
],
[
[
"### Question 3\n\nWhat are the 20 most frequently occurring (unique) tokens in the text? What is their frequency?\n\n*This function should return a list of 20 tuples where each tuple is of the form `(token, frequency)`. The list should be sorted in descending order of frequency.*",
"_____no_output_____"
]
],
[
[
"def answer_three():\n tot = nltk.word_tokenize(moby_raw)\n dist = nltk.FreqDist(tot)\n return dist.most_common(20)\n\nanswer_three()",
"_____no_output_____"
]
],
[
[
"### Question 4\n\nWhat tokens have a length of greater than 5 and frequency of more than 150?\n\n*This function should return an alphabetically sorted list of the tokens that match the above constraints. To sort your list, use `sorted()`*",
"_____no_output_____"
]
],
[
[
"def answer_four():\n tot = nltk.word_tokenize(moby_raw)\n dist = nltk.FreqDist(tot)\n count = [w for w in dist if len(w)>5 and dist[w]>150]\n return sorted(count)\n\nanswer_four()",
"_____no_output_____"
]
],
[
[
"### Question 5\n\nFind the longest word in text1 and that word's length.\n\n*This function should return a tuple `(longest_word, length)`.*",
"_____no_output_____"
]
],
[
[
"def answer_five():\n tot = nltk.word_tokenize(moby_raw)\n dist = nltk.FreqDist(tot)\n max_length = max([len(w) for w in dist])\n word = [w for w in dist if len(w)==max_length]\n return (word[0],max_length)\n\nanswer_five()",
"_____no_output_____"
]
],
[
[
"### Question 6\n\nWhat unique words have a frequency of more than 2000? What is their frequency?\n\n\"Hint: you may want to use `isalpha()` to check if the token is a word and not punctuation.\"\n\n*This function should return a list of tuples of the form `(frequency, word)` sorted in descending order of frequency.*",
"_____no_output_____"
]
],
[
[
"def answer_six():\n tot = nltk.word_tokenize(moby_raw)\n dist = nltk.FreqDist(tot)\n words = [w for w in dist if dist[w]>2000 and w.isalpha()]\n words_count = [dist[w] for w in words]\n ans = list(zip(words_count,words))\n ans.sort(key=lambda tup: tup[0],reverse=True) \n return ans\n\nanswer_six()\n\n",
"_____no_output_____"
]
],
[
[
"### Question 7\n\nWhat is the average number of tokens per sentence?\n\n*This function should return a float.*",
"_____no_output_____"
]
],
[
[
"def answer_seven():\n tot = nltk.sent_tokenize(moby_raw)\n dist = nltk.FreqDist(tot)\n tot1 = nltk.word_tokenize(moby_raw)\n return len(tot1)/len(tot)\n\nanswer_seven()",
"_____no_output_____"
]
],
[
[
"### Question 8\n\nWhat are the 5 most frequent parts of speech in this text? What is their frequency?\n\n*This function should return a list of tuples of the form `(part_of_speech, frequency)` sorted in descending order of frequency.*",
"_____no_output_____"
]
],
[
[
"def answer_eight():\n tot = nltk.word_tokenize(moby_raw)\n dist1 = nltk.pos_tag(tot)\n frequencies = nltk.FreqDist([tag for (word, tag) in dist1])\n \n return frequencies.most_common(5)\n\nanswer_eight()",
"_____no_output_____"
]
],
[
[
"## Part 2 - Spelling Recommender\n\nFor this part of the assignment you will create three different spelling recommenders, that each take a list of misspelled words and recommends a correctly spelled word for every word in the list.\n\nFor every misspelled word, the recommender should find find the word in `correct_spellings` that has the shortest distance*, and starts with the same letter as the misspelled word, and return that word as a recommendation.\n\n*Each of the three different recommenders will use a different distance measure (outlined below).\n\nEach of the recommenders should provide recommendations for the three default words provided: `['cormulent', 'incendenece', 'validrate']`.",
"_____no_output_____"
]
],
[
[
"import pandas\nfrom nltk.corpus import words\nnltk.download('words')\nfrom nltk.metrics.distance import (\n edit_distance,\n jaccard_distance,\n )\nfrom nltk.util import ngrams\n\ncorrect_spellings = words.words()\nspellings_series = pandas.Series(correct_spellings)\n#spellings_series",
"[nltk_data] Downloading package words to /home/jovyan/nltk_data...\n[nltk_data] Package words is already up-to-date!\n"
]
],
[
[
"### Question 9\n\nFor this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n\n**[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the trigrams of the two words.**\n\n*This function should return a list of length three:\n`['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*",
"_____no_output_____"
]
],
[
[
"def Jaccard(words, n_grams):\n outcomes = []\n for word in words:\n spellings = spellings_series[spellings_series.str.startswith(word[0])]\n distances = ((jaccard_distance(set(ngrams(word, n_grams)), set(ngrams(k, n_grams))), k) for k in spellings)\n closest = min(distances)\n outcomes.append(closest[1]) \n return outcomes\n\ndef answer_nine(entries=['cormulent', 'incendenece', 'validrate']):\n \n return Jaccard(entries,3)\n \nanswer_nine()",
"/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:5: DeprecationWarning: generator 'ngrams' raised StopIteration\n \"\"\"\n"
]
],
[
[
"### Question 10\n\nFor this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n\n**[Jaccard distance](https://en.wikipedia.org/wiki/Jaccard_index) on the 4-grams of the two words.**\n\n*This function should return a list of length three:\n`['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*",
"_____no_output_____"
]
],
[
[
"def answer_ten(entries=['cormulent', 'incendenece', 'validrate']):\n \n \n return Jaccard(entries,4)\n \nanswer_ten()",
"/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:5: DeprecationWarning: generator 'ngrams' raised StopIteration\n \"\"\"\n"
]
],
[
[
"### Question 11\n\nFor this recommender, your function should provide recommendations for the three default words provided above using the following distance metric:\n\n**[Edit distance on the two words with transpositions.](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)**\n\n*This function should return a list of length three:\n`['cormulent_reccomendation', 'incendenece_reccomendation', 'validrate_reccomendation']`.*",
"_____no_output_____"
]
],
[
[
"def Edit(words):\n outcomes = []\n for word in words:\n spellings = spellings_series[spellings_series.str.startswith(word[0])]\n distances = ((edit_distance(word,k),k) for k in spellings)\n closest = min(distances)\n outcomes.append(closest[1]) \n return outcomes\n\n\ndef answer_eleven(entries=['cormulent', 'incendenece', 'validrate']):\n \n \n return Edit(entries) \n \nanswer_eleven()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd783b80e725c4f5c0509da1f8208a1b54c89e6
| 74,841 |
ipynb
|
Jupyter Notebook
|
other/ged-lev/P1-ged-lev.ipynb
|
eyeonechi/waht-kinda-typoz-do-poeple-mak
|
33a6c898c5f88e5380da086872257ad2184c9e82
|
[
"MIT"
] | null | null | null |
other/ged-lev/P1-ged-lev.ipynb
|
eyeonechi/waht-kinda-typoz-do-poeple-mak
|
33a6c898c5f88e5380da086872257ad2184c9e82
|
[
"MIT"
] | null | null | null |
other/ged-lev/P1-ged-lev.ipynb
|
eyeonechi/waht-kinda-typoz-do-poeple-mak
|
33a6c898c5f88e5380da086872257ad2184c9e82
|
[
"MIT"
] | null | null | null | 32.738845 | 1,278 | 0.601462 |
[
[
[
"This is a simple iPython notebook which uses the \"editdistance\" package to find the best match for a string within the dictionary.\n(NJ, Aug 2018)",
"_____no_output_____"
]
],
[
[
"import editdistance",
"_____no_output_____"
]
],
[
[
"We'll load the entire dictionary into a list. This doesn't actually use much memory.",
"_____no_output_____"
]
],
[
[
"f = open(\"./dict.txt\")\nmy_dict = f.readlines()\nf.close()",
"_____no_output_____"
]
],
[
[
"Now we compare each dictionary entry with a string; we'll keep track of the best entry we've seen so far:",
"_____no_output_____"
]
],
[
[
"f = open('wiki_misspell.txt','r')\nfor line in f:\n string = line.strip()\n bestv = 10000000 # This is intentionally overkill\n bests = \"\"\n for entry in my_dict:\n thisv = editdistance.eval(string,entry.strip())\n if (thisv < bestv):\n # Note that this script only updates the best entry when it is better than all of the previous ones\n # It turns out that this is actually a really bad strategy\n bests = entry.strip()\n bestv = thisv\n \n print(string,bests,bestv)",
"abandonned abandoned 1\nabbout abbot 1\naberation aberration 1\nabilityes abilities 1\nabilties abilities 1\nabilty ability 1\nabondon abandon 1\nabondoned abandoned 1\nabondoning abandoning 1\nabondons abandons 1\naborigene aborigine 1\nabortificant abortifacient 3\nabotu abote 1\nabreviate abbreviate 1\nabreviated abbreviated 1\nabreviation abbreviation 1\nabritrary arbitrary 2\nabsail abseil 1\nabsailing abseiling 1\nabscence absconce 1\nabsense absence 1\nabsolutly absolutely 1\nabsorbsion absorbtion 1\nabsorbtion absorbtion 0\nabudance abidance 1\nabundacies abundances 2\nabundancies abundances 1\nabundunt abundant 1\nabutts abuts 1\nacadamy academy 1\nacadmic academic 1\naccademic academic 1\naccademy academy 1\nacccused accused 1\naccelleration acceleration 1\naccension accension 0\naccension accension 0\nacceptence acceptance 1\nacceptible acceptable 1\naccesories accessories 1\naccessable accessable 0\naccidant accident 1\naccidentaly accidental 1\naccidently accidently 0\nacclimitization acclimatization 1\naccomadate accomodate 1\naccomadated accommodated 2\naccomadates accommodates 2\naccomadating accommodating 2\naccomadation accommodation 2\naccomadations accommodations 2\naccomdate accomodate 1\naccomodate accomodate 0\naccomodated accommodated 1\naccomodates accommodates 1\naccomodating accommodating 1\naccomodation accommodation 1\naccomodations accommodations 1\naccompanyed accompanied 1\naccordeon accordion 1\naccordian accordion 1\naccoring accoying 1\naccoustic acoustic 1\naccquainted acquainted 1\naccrediation accreditation 1\naccredidation accreditation 1\naccross across 1\naccussed accessed 1\nacedemic academic 1\nacheive aceite 2\nacheived acheweed 2\nacheivement achievement 2\nacheivements achievements 2\nacheives acheirus 2\nacheiving achieving 2\nacheivment achievement 3\nacheivments achievements 3\nachievment achievement 1\nachievments achievements 1\nachive achieve 1\nachive achieve 1\nachived achieved 1\nachived achieved 1\nachivement achievement 1\nachivements achievements 1\nacident accident 1\nacknowldeged acknowledged 2\nacknowledgeing acknowledging 1\nackward awkward 1\nackward awkward 1\nacommodate accommodate 1\nacomplish accomplish 1\nacomplished accomplished 1\nacomplishment accomplishment 1\nacomplishments accomplishments 1\nacording according 1\nacordingly accordingly 1\nacquaintence acquaintance 1\nacquaintences acquaintances 1\nacquiantence acquaintance 3\nacquiantences acquaintances 3\nacquited acquired 1\nactivites activates 1\nactivly actively 1\nactualy actual 1\nacuracy accuracy 1\nacused abused 1\nacustom acustom 0\nacustommed accustomed 2\nadavanced advanced 1\nadbandon abandon 1\naddional actional 2\naddionally additionally 2\nadditinally additionally 1\nadditionaly additional 1\nadditonal additional 1\nadditonally additionally 1\naddmission admission 1\naddopt adopt 1\naddopted adopted 1\naddoptive adoptive 1\naddres addles 1\naddres addles 1\naddresable addressable 1\naddresed addressed 1\naddresing addressing 1\naddressess addressees 1\naddtion addition 1\naddtional additional 1\nadecuate adequate 1\nadequit acequia 2\nadhearing adhering 1\nadherance adherence 1\nadmendment amendment 1\nadmininistrative administrative 2\nadminstered administered 1\nadminstrate administrate 1\nadminstration adminstration 0\nadminstrative administrative 1\nadminstrator administrator 1\nadmissability admissability 0\nadmissable admissable 0\nadmited admired 1\nadmitedly admiredly 1\nadn abn 1\nadolecent adolescent 1\nadquire acquire 1\nadquired acquired 1\nadquires acquires 1\nadquiring acquiring 1\nadres acres 1\nadresable acreable 2\nadresing abrasing 2\nadress address 1\nadressable addressable 1\nadressed addressed 1\nadressing addressing 1\nadressing addressing 1\nadventrous adventurous 1\nadvertisment advertisement 1\nadvertisments advertisements 1\nadvesary adversary 1\nadviced advice 1\naeriel aerial 1\naeriels aerials 1\nafair afar 1\nafficianados afficionado 2\nafficionado afficionado 0\nafficionados afficionado 1\naffilate affiliate 1\naffilliate affiliate 1\naffort afford 1\naffort afford 1\naforememtioned aforementioned 1\nagainnst against 1\nagains again 1\nagaisnt afaint 2\naganist agamist 1\naggaravates aggravates 1\naggreed agreed 1\naggreement agreement 1\naggregious egregious 2\naggresive aggressive 1\nagian aghan 1\nagianst against 2\nagin agin 0\nagina aegina 1\nagina aegina 1\naginst against 1\nagravate aggravate 1\nagre agre 0\nagred acred 1\nagreeement agreement 1\nagreemnt agreement 1\nagregate aggregate 1\nagregates aggregates 1\nagreing agreing 0\nagression aggression 1\nagressive aggressive 1\nagressively aggressively 1\nagressor aggressor 1\nagricultue agriculture 1\nagriculure agriculture 1\nagricuture agriculture 1\nagrieved aggrieved 1\nahev ahey 1\nahppen alpeen 2\nahve ave 1\naicraft adcraft 1\naiport airport 1\nairbourne airborne 1\naircaft aircraft 1\naircrafts aircrafts 0\nairporta airport 1\nairrcraft aircraft 1\naisian asian 1\nalbiet aliet 1\nalchohol alcohol 1\nalchoholic alcoholic 1\nalchol alcohol 1\nalcholic acholic 1\nalcohal alcohol 1\nalcoholical alcoholic 2\naledge abedge 1\naledged fledged 1\naledges fledges 1\nalege alee 1\naleged aleger 1\nalegience allegiance 2\nalgebraical algebraical 0\nalgorhitms algorisms 2\nalgoritm algorism 1\nalgoritms algorisms 1\nalientating alienating 1\nalledge allege 1\nalledged alleged 1\nalledgedly allegedly 1\nalledges alleges 1\nallegedely allegedly 1\nallegedy alleged 1\nallegely allegedly 1\nallegence allegiance 2\nallegience allegiance 1\nallign align 1\nalligned aligned 1\nalliviate alleviate 1\nallopone allophone 1\nallopones allophones 1\nallready already 1\nallthough although 1\nalltogether altogether 1\nalmsot alepot 2\nalochol alcohol 2\nalomst acost 2\nalot alit 1\nalotted allotted 1\nalowed allowed 1\nalowing allowing 1\nalreayd adread 2\nalse alae 1\nalsot allot 1\nalternitives alternatives 1\naltho altho 0\nalthought although 1\naltough although 1\nalusion abusion 1\nalusion abusion 1\nalwasy alway 1\nalwyas aliyas 1\namalgomated amalgamated 1\namatuer abater 2\namature abature 1\namature abature 1\namendmant amendment 1\namercia aberia 2\namerliorate ameliorate 1\namke ake 1\namking aking 1\nammend amend 1\nammended amended 1\nammendment amendment 1\nammendments amendments 1\nammount amount 1\nammused amused 1\namoung among 1\namoungst amongst 1\namung amang 1\namunition ammunition 1\nanalagous analagous 0\nanalitic anaclitic 1\nanalogeous analogous 1\nanarchim anarchic 1\nanarchistm anarchism 1\nanbd abd 1\nancestory ancestor 1\nancilliary ancillary 1\nandd add 1\nandrogenous androgenous 0\nandrogeny androgen 1\nanihilation annihilation 1\naniversary anniversary 1\nannoint anoint 1\nannointed anointed 1\nannointing anointing 1\nannoints anoints 1\nannouced announced 1\nannualy annaly 1\nannuled annule 1\nanohter aborter 2\nanomolies anomalies 1\nanomolous anomalous 1\nanomoly anomaly 1\nanonimity anonymity 1\nanounced announced 1\nanouncement announcement 1\nansalisation alkalisation 2\nansalization alkalization 2\nansestors ancestors 1\nantartic antarctic 1\nanthromorphization anthropomorphization 2\nanthropolgist anthropologist 1\nanthropolgy anthropology 1\nanual anal 1\nanulled annulled 1\nanwsered angered 2\nanyhwere anywhere 2\nanytying anything 1\naparent apparent 1\naparment apartment 1\napenines adenines 1\naplication amplication 1\naplied allied 1\napolegetics apologetics 1\napon adon 1\napon adon 1\napparant apparat 1\napparantly apparently 1\nappart apart 1\nappartment apartment 1\nappartments apartments 1\nappealling appalling 1\nappealling appalling 1\nappeareance appearance 1\nappearence apparence 1\nappearences appearances 1\nappenines adenines 2\napperance apparance 1\napperances appearances 1\nappereance apparance 2\nappereances appearances 2\napplicaiton application 2\napplicaitons applications 2\nappologies apiologies 1\nappology apiology 1\napprearance appearance 1\napprieciate appreciate 1\napproachs approach 1\nappropiate appropriate 1\nappropraite appropriate 2\nappropropiate appropriate 2\napproproximate appropriate 3\napproxamately approximately 1\napproxiately approximately 1\napproximitely approximately 1\naprehensive apprehensive 1\napropriate appropriate 1\naproval approval 1\naproximate approximate 1\naproximately approximately 1\naquaduct aquaduct 0\naquaintance acquaintance 1\naquainted acquainted 1\naquiantance acquaintance 3\naquire acquire 1\naquired acquired 1\naquiring acquiring 1\naquisition acquisition 1\naquitted acquitted 1\naranged arranged 1\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd783bd217a1d168cf9af9581b03b48f51144ab
| 23,278 |
ipynb
|
Jupyter Notebook
|
Notebooks/ASSIGNMENT-4.ipynb
|
JeongJaeWook/python-for-text-analysis
|
ec1711f07b8f8656f857878956d4d4bc0557f61c
|
[
"Apache-2.0"
] | null | null | null |
Notebooks/ASSIGNMENT-4.ipynb
|
JeongJaeWook/python-for-text-analysis
|
ec1711f07b8f8656f857878956d4d4bc0557f61c
|
[
"Apache-2.0"
] | null | null | null |
Notebooks/ASSIGNMENT-4.ipynb
|
JeongJaeWook/python-for-text-analysis
|
ec1711f07b8f8656f857878956d4d4bc0557f61c
|
[
"Apache-2.0"
] | null | null | null | 30.872679 | 486 | 0.540596 |
[
[
[
"# Assignment 4: Word Sense Disambiguation: from start to finish\n\n## Due: Tuesday 6 December 2016 15:00 p.m.\n\nPlease name your Jupyter notebook using the following naming convention: ASSIGNMENT_4_FIRSTNAME_LASTNAME.ipynb \n\nPlease send your assignment to `[email protected]`. ",
"_____no_output_____"
],
[
"A well-known NLP task is [Word Sense Disambiguation (WSD)](https://en.wikipedia.org/wiki/Word-sense_disambiguation). The goal is to identify the sense of a word in a sentence. Here is an example of the output of one of the best systems, called [Babelfy](http://babelfy.org/index). ",
"_____no_output_____"
],
[
"Since 1998, there have been WSD competitions: [Senseval and SemEval](https://en.wikipedia.org/wiki/SemEval). The idea is very simple. A few people annotate words in a sentence with the correct meaning and systems try to the do same. Because we have the manual annotations, we can score how well each system performs. In this exercise, we are going to compete in [SemEval-2013 task 12: Multilingual Word Sense Disambiguation](https://www.cs.york.ac.uk/semeval-2013/task12.html).\n\nThe main steps in this exercise are:\n* Introduction of the data and goals\n* Performing WSD\n* Loading manual annotations (which we will call **gold data**)\n* System output \n* Write an XML file containing both the gold data and our system output\n* Read the XML file and evaluate our performance\n * please only use **xpath** if you are comfortable with using it. It is not needed to complete the assignment.",
"_____no_output_____"
],
[
"## Introduction of the data and goals",
"_____no_output_____"
],
[
"We will use the following data (originating from [SemEval-2013 task 12 test data](https://www.cs.york.ac.uk/semeval-2013/task12/data/uploads/datasets/semeval-2013-task12-test-data.zip)):",
"_____no_output_____"
],
[
"* **system input**: data/multilingual-all-words.en.xml \n* **gold data**: data/sem2013-aw.key",
"_____no_output_____"
],
[
"Given a word in a sentence, the goal of our system is to determine the corect meaning of that word. For example, look at the **system input** file (data/multilingual-all-words.en.xml) at lines 1724-1740.\nAll the *instance* elements are the ones we have to provide a meaning for. Please note that the *sentence* element has *wf* and *instance* children. The *instance* elements are the ones for which we have to provide a meaning.",
"_____no_output_____"
],
[
"\n```xml\n<sentence id=\"d003.s005\">\n <wf lemma=\"frankly\" pos=\"RB\">Frankly</wf>\n <wf lemma=\",\" pos=\",\">,</wf>\n <wf lemma=\"the\" pos=\"DT\">the</wf>\n <instance id=\"d003.s005.t001\" lemma=\"market\" pos=\"NN\">market</instance>\n <wf lemma=\"be\" pos=\"VBZ\">is</wf>\n <wf lemma=\"very\" pos=\"RB\">very</wf>\n <wf lemma=\"calm\" pos=\"JJ\">calm</wf>\n <wf lemma=\",\" pos=\",\">,</wf>\n <wf lemma=\"observe\" pos=\"VVZ\">observes</wf>\n <wf lemma=\"Mace\" pos=\"NP\">Mace</wf>\n <wf lemma=\"Blicksilver\" pos=\"NP\">Blicksilver</wf>\n <wf lemma=\"of\" pos=\"IN\">of</wf>\n <wf lemma=\"Marblehead\" pos=\"NP\">Marblehead</wf>\n <instance id=\"d003.s005.t002\" lemma=\"asset_management\" pos=\"NE\">Asset_Management</instance>\n <wf lemma=\".\" pos=\"SENT\">.</wf>\n </sentence>\n```",
"_____no_output_____"
],
[
"As a way to determine the possible meanings of a word, we will use [WordNet](https://wordnet.princeton.edu/). For example, for the lemma **market**, Wordnet lists the following meanings:",
"_____no_output_____"
]
],
[
[
"from nltk.corpus import wordnet as wn",
"_____no_output_____"
],
[
"for synset in wn.synsets('market', pos='n'):\n print(synset, synset.definition())",
"_____no_output_____"
]
],
[
[
"In order to know which meaning the manual annotators chose, we go to the **gold data** (data/sem2013-aw.key). For the identifier *d003.s005.t001*, we find:",
"_____no_output_____"
],
[
"d003 d003.s005.t001 market%1:14:01:: ",
"_____no_output_____"
],
[
"In order to know to which synset *market%1:14:01::* belongs, we can do the following:",
"_____no_output_____"
]
],
[
[
"lemma = wn.lemma_from_key('market%1:14:01::')\nsynset = lemma.synset()\nprint(synset, synset.definition())",
"_____no_output_____"
]
],
[
[
"Hence, the manual annotators chose **market.n.04**. ",
"_____no_output_____"
],
[
"## Performing WSD\nAs a first step, we will perform WSD. For this, we will use the [**lesk** WSD algorithm](http://www.d.umn.edu/~tpederse/Pubs/banerjee.pdf) as implemented in the [NLTK](http://www.nltk.org/howto/wsd.html). One of the applications of the Lesk algorithm is to determine which senses of words are related. Imagine that **cone** has three senses, and **pine** has three senses (example from [paper](http://www.d.umn.edu/~tpederse/Pubs/banerjee.pdf)):\n\n**Cone**\n* Sense 1: kind of *evergreen tree* with needle–shaped leaves\n* Sense 2: waste away through sorrow or illness.\n\n**Pine**\n* Sense 1: solid body which narrows to a point\n* Sense 2: something of this shape whether solid or hollow\n* Sense 3: fruit of certain *evergreen tree*\n\nAs you can see, **sense 1 of cone** and **sense 3 of pine** have an overlap in their definitions and hence indicate that these senses are related. This idea can then be used to perform WSD. The words in the sentence of a word are compared against the definition of each sense of word. The word sense that has the highest number of overlapping words between the sentence and the definition of the word sense is chosen as the correct sense according to the algorithm.",
"_____no_output_____"
]
],
[
[
"from nltk.wsd import lesk",
"_____no_output_____"
]
],
[
[
"Given is a function that allows you to perform WSD on a sentence. The output is a **WordNet sensekey**, hence an identifier of a sense.\n#### the function is given, but it is important that you understand how to call it.",
"_____no_output_____"
]
],
[
[
"def perform_wsd(sent, lemma, pos):\n '''\n perform WSD using the lesk algorithm as implemented in the nltk\n \n :param list sent: list of words\n :param str lemma: a lemma\n :param str pos: a pos (n | v | a | r)\n \n :rtype: str\n :return: wordnet sensekey or not_found\n '''\n sensekey = 'not_found'\n wsd_result = lesk(sent, lemma, pos)\n \n if wsd_result is not None:\n for lemma_obj in wsd_result.lemmas():\n if lemma_obj.name() == lemma:\n sensekey = lemma_obj.key()\n \n return sensekey\n\n\nsent = ['I', 'went', 'to', 'the', 'bank', 'to', 'deposit', 'money', '.']\nassert perform_wsd(sent, 'bank', 'n') == 'bank%1:06:01::', 'key is %s' % perform_wsd(sent, 'bank', 'n')\nassert perform_wsd(sent, 'dfsdf', 'n') == 'not_found', 'key is %s' % perform_wsd(sent, 'money', 'n')\nprint(perform_wsd(sent, 'bank', 'n'))",
"_____no_output_____"
]
],
[
[
"## Loading manual annotations\nYour job now is to load the manual annotations from 'data/sem2013-aw.key'.\n* Tip, you can use [**repr**](https://docs.python.org/3/library/functions.html#repr) to check which delimiter (space, tab, etc) was used.\n* sometimes there is more than one sensekey given for an identifier (see line 25 for example)",
"_____no_output_____"
],
[
"You can use the **set** function to convert a list to a set",
"_____no_output_____"
]
],
[
[
"a_list = [1, 1, 2, 1, 3]\na_set = set(a_list)\nprint(a_set)",
"_____no_output_____"
],
[
"def load_gold_data(path_to_gold_key):\n '''\n given the path to gold data of semeval2013 task 12,\n this function creates a dictionary mapping the identifier to the\n gold answers\n \n HINT: sometimes, there is more than one sensekey for identifier\n \n :param str path_to_gold_key: path to where gold data file is stored\n \n :rtype: dict\n :return: identifier (str) -> goldkeys (set)\n '''\n gold = {} \n with open(path_to_gold_key) as infile:\n for line in infile:\n # find the identifier and the goldkeys\n \n # add them to the dictionary\n # gold[identifier] = goldkeys\n \n return gold",
"_____no_output_____"
]
],
[
[
"Please check if your functions works correctly by running the cell below.",
"_____no_output_____"
]
],
[
[
"gold = load_gold_data('data/sem2013-aw.key')\nassert len(gold) == 1644, 'number of gold items is %s' % len(gold)",
"_____no_output_____"
]
],
[
[
"## Combining system input + system output + gold data\nWe are going to create a dictionary that looks like this:\n```python\n{10: {'sent_id' : 1\n 'text': 'banks',\n 'lemma' : 'bank',\n 'pos' : 'n',\n 'instance_id' : 'd003.s005.t001',\n 'gold_keys' : {'bank%1:14:00::'},\n 'system_key' : 'bank%1:14:00::'}\n }\n```\n\nThis dictionary maps a number (int) to a dictionary. Combining all relevant information in one dictionary will help us to create the NAF XML file. In order to do this, we will write several functions. To work with XML, we will first import the lxml module.",
"_____no_output_____"
]
],
[
[
"from lxml import etree",
"_____no_output_____"
],
[
"def load_sentences(semeval_2013_input):\n '''\n given the path to the semeval input xml,\n this function creates a dictionary mapping sentence identfier\n to the sentence (list of words)\n \n HINT: you need the text of both:\n text/sentence/instance and text/sentence/wf elements\n \n :param str semeval_2013_input: path to semeval 2013 input xml\n \n :rtype: dict\n :return: mapping sentence identifier -> list of words\n '''\n sentences = dict()\n \n doc = etree.parse(semeval_2013_input)\n \n # insert code here\n \n return sentences",
"_____no_output_____"
]
],
[
[
"please check that your function works by running the cell below.",
"_____no_output_____"
]
],
[
[
"sentences = load_sentences('data/multilingual-all-words.en.xml')\nassert len(sentences) == 306, 'number of sentences is different from needed 306: namely %s' % len(sentences)",
"_____no_output_____"
],
[
"def load_input_data(semeval_2013_input):\n '''\n given the path to input xml file, we will create a dictionary that looks like this:\n \n :rtype: dict\n :return: {10: {\n 'sent_id' : 1\n 'text': 'banks',\n 'lemma' : 'bank',\n 'pos' : 'n',\n 'instance_id' : 'd003.s005.t001',\n 'gold_keys' : {},\n 'system_key' : ''}\n }\n '''\n data = dict()\n doc = etree.parse(semeval_2013_input)\n identifier = 1\n \n for sent_el in doc.findall('text/sentence'):\n # insert code here\n \n for child_el in sent_el.getchildren():\n # insert code here\n \n info = {\n 'sent_id' : # to fill, \n 'text': # to fill, \n 'lemma' : # to fill,\n 'pos' : # to fill, \n 'instance_id' : # to fill if instance element else empty string,\n 'gold_keys' : set(), # this is ok for now\n 'system_key' : '' # this is ok for now\n }\n \n data[identifier] = info\n identifier += 1\n \n return data\n",
"_____no_output_____"
],
[
"data = load_input_data('data/multilingual-all-words.en.xml')\nassert len(data) == 8142, 'number of token is not the needed 8142: namely %s' % len(data)",
"_____no_output_____"
],
[
"def add_gold_and_wsd_output(data, gold, sentences): \n '''\n the goal of this function is to fill the keys 'system_key'\n and 'gold_keys' for the entries in which the 'instance_id' is not an empty string.\n \n :param dict data: see output function 'load_input_data'\n :param dict gold: see output function 'load_gold_data' \n :param dict sentences: see output function 'load_sentences' \n \n NOTE: not all instance_ids have a gold answer! \n \n :rtype: dict\n :return: {10: {'sent_id' : 1\n 'text': 'banks',\n 'lemma' : 'bank',\n 'pos' : 'n',\n 'instance_id' : 'd003.s005.t001',\n 'gold_keys' : {'bank%1:14:00::'},\n 'system_key' : 'bank%1:14:00::'}\n }\n '''\n for identifier, info in data.items():\n # get the instance id\n \n if instance_id:\n # perform wsd and get sensekey that lesk proposes\n \n # add system key to our dictionary\n # info['system_key'] = sensekey\n \n if instance_id in gold:\n info['gold_keys'] = gold[instance_id]",
"_____no_output_____"
]
],
[
[
"Call the function to combine all information.",
"_____no_output_____"
]
],
[
[
"add_gold_and_wsd_output(data, gold, sentences)",
"_____no_output_____"
]
],
[
[
"## Create NAF with system run and gold information\nWe are going to create one [NAF XML](http://www.newsreader-project.eu/files/2013/01/techreport.pdf) containing both the gold information and our system run. In order to do this, we will guide you through the process of doing this.",
"_____no_output_____"
],
[
"### [CODE IS GIVEN] Step a: create an xml object\n**NAF** will be our root element.",
"_____no_output_____"
]
],
[
[
"new_root = etree.Element('NAF')\nnew_tree = etree.ElementTree(new_root)\nnew_root = new_tree.getroot()",
"_____no_output_____"
]
],
[
[
"We can inspect what we have created by using the **etree.dump** method. As you can see, we only have the root node **NAF** currently in our document.",
"_____no_output_____"
]
],
[
[
"etree.dump(new_root)",
"_____no_output_____"
]
],
[
[
"### [CODE IS GIVEN] Step b: add children\nWe will now add the elements in which we will place the **wf** and **term** elements.",
"_____no_output_____"
]
],
[
[
"text_el = etree.Element('text')\nterms_el = etree.Element('terms')\n\nnew_root.append(text_el)\nnew_root.append(terms_el)",
"_____no_output_____"
],
[
"etree.dump(new_root)",
"_____no_output_____"
]
],
[
[
"### Step c: functions to create wf and term elements\nFor this step, the code is not given. Please complete the functions.\n#### TIP: check the subsection *Creating your own XML* from Topic 5",
"_____no_output_____"
]
],
[
[
"def create_wf_element(identifier, sent_id, text):\n '''\n create NAF wf element, such as:\n <wf id=\"11\" sent_id=\"d001.s002\">conference</wf>\n \n :param int identifier: our own identifier (convert this to string)\n :param str sent_id: the sentence id of the competition\n :param str text: the text\n '''\n # complete from here\n wf_el = etree.Element(\n \n return wf_el",
"_____no_output_____"
]
],
[
[
"#### TIP: **externalRef** elements are children of **term** elements",
"_____no_output_____"
]
],
[
[
"def create_term_element(identifier, instance_id, system_key, gold_keys):\n '''\n create NAF xml element, such as:\n <term id=\"3885\">\n <externalRef instance_id=\"d007.s013.t004\" provenance=\"lesk\" wordnetkey=\"player%1:18:04::\"/>\n <externalRef instance_id=\"d007.s013.t004\" provenance=\"gold\" wordnetkey=\"player%1:18:01::\"/>\n </term>\n \n :param int identifier: our own identifier (convert this to string)\n :param str system_key: system output\n :param set gold_keys: goldkeys\n '''\n # complete code here\n term_el = etree.Element(\n \n return term_el",
"_____no_output_____"
]
],
[
[
"### [CODE IS GIVEN] Step d: add wf and term elements ",
"_____no_output_____"
]
],
[
[
"counter = 0\nfor identifier, info in data.items():\n wf_el = create_wf_element(identifier, info['sent_id'], info['text'])\n text_el.append(wf_el)\n \n term_el = create_term_element(identifier, \n info['instance_id'],\n info['system_key'], \n info['gold_keys'])\n terms_el.append(term_el)\n",
"_____no_output_____"
]
],
[
[
"### [CODE IS GIVEN]: write to file",
"_____no_output_____"
]
],
[
[
"with open('semeval2013_run1.naf', 'wb') as outfile:\n new_tree.write(outfile,\n pretty_print=True,\n xml_declaration=True,\n encoding='utf-8')",
"_____no_output_____"
]
],
[
[
"## Score our system run\nRead the NAF file and extract relevant statistics, such as:\n* overall performance (how many are correct?)\n* [optional]: anything that you find interesting",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbd7933ccb915341cc109449500a72bbd29994c5
| 22,818 |
ipynb
|
Jupyter Notebook
|
LousyFairytaleGenerator_Assemblage_Project1_.ipynb
|
sarahalyahya/SoftwareArt-Text
|
e3044e90c5d4831986eb6c940f446de2ea998325
|
[
"MIT"
] | null | null | null |
LousyFairytaleGenerator_Assemblage_Project1_.ipynb
|
sarahalyahya/SoftwareArt-Text
|
e3044e90c5d4831986eb6c940f446de2ea998325
|
[
"MIT"
] | null | null | null |
LousyFairytaleGenerator_Assemblage_Project1_.ipynb
|
sarahalyahya/SoftwareArt-Text
|
e3044e90c5d4831986eb6c940f446de2ea998325
|
[
"MIT"
] | null | null | null | 51.04698 | 828 | 0.572793 |
[
[
[
"<a href=\"https://colab.research.google.com/github/sarahalyahya/SoftwareArt-Text/blob/main/LousyFairytaleGenerator_Assemblage_Project1_.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"#Lousy Fairytale Plot Generator | Sarah Al-Yahya\n*scroll to the end and click run to check the presentation first!*\n##Idea\nFor this project, I spent a lot of time browsing through project gutenberg. While I was doing that, I got a an urge to look up what kind of children's books are on the website, inspired by a phone call with my niece. My niece is a very curious child, and I can only imagine that by the time she starts getting interested in stories and fairytales, her curiosity will mean that her parents will run out of made-up stories to tell her. So, I wanted to create a tool that helps them, well kind of...I wanted to capture that confused tone that parents have sometimes when they make up a story as they go. \n##Research\nWhat makes a fairytale? A google search led to Missouri Southern State University's [website](https://libguides.mssu.edu/c.php?g=185298&p=1223898#:~:text=The%20basic%20structure%20of%20a,a%20solution%20can%20be%20found.). To summarize, the page explains that a fairy tale's main elements are:\n\n\n* Characters\n* The Moral Lesson\n* Obstacles\n* Magic\n* A Happily Ever After\n\nSo, these elements formed the structure of my output. \n\n##Elements\n*(More specific comments are in the code)*\n####Characters\nFor the characters, I scraped a few pages from a website called World of Tales. I chose it over Project Gutenberg as I found the HTML easier to work with. The program picks a random fairytale from the ones I have in an array, parses the HTML, finds all paragraphs and cleans them from new line and trailing characters before appending them to a list. Afterwards, to extract the main character's name I used NLTK and a function that counts proper nouns to find the most repeated proper noun which becomes my main character. As you can imagine, this isn't a perfect method since we could get \"I\" or \"King's\". I tried to do my best to limit such results, but it isn't perfect. \n###The Moral Lesson\nHere, I scraped a random blog post that lists 101 valuable life lessons. I thought this would add a humorous tone to the work as some of the lessons are completely unrelated to the fairytale world, e.g. \"Don’t go into bad debt (debt taken on for consumption)\". Then, I parsed and cleaned the text, and sliced the results to remove any paragraph elements that weren't part of the list. For this part I also used Regular Expressions to remove list numbers (\"1.\"). Unfortunately, there's a bit of hardcoded replacements and removals in this part. I found it difficult to figure out the pronouns, such as turning all you's into a neutral they resulting in \"theyself\"...etc. I left some of the failed RegEx attempts commented if anyone has any suggestions! This part picks a random lesson from the list everytime. \n###Obstacle\nMy obstacle was basically a villain the main character needs to fight. Which I got from a webpage that lists 10 fairytale villains. The process was similar, I parsed the page and cleaned the strings using replace() and regEx then randomly chose one of the villains listed. \n###Magic\nUsing an approach almost identical to the one for villains. I scraped a webpage that lists a bunch of superpowers and magical ability, and made a list out of them to pick a random one when the program runs. I relied on random web pages to compliment that \"confused\" \"humorous\" tone of scrambling to make up a random story on the spot!\n###The Happily Ever After\nI made sure to end the text generation with a reference to the happily ever after and the fact that the hero beats the villain using the specific superpower. \n\n##Presentation\nI made use of the Sleep() function to create a rhythm for the conversation. I embedded my generated text into human sounding text to really make it feel like you're talking to someone. Obviously, some outputs make it very obvious that this is a bot, such as when the main character is called \"I\", but I think the general feel is quite natural. \n\n##Impact\nI would say the impact is more entertaining and maybe humorous than functional, although it is quite functional sometimes and suggests ideas that could make great fairytales!\n\n##Final Reflection\nWhile working I realized that RegEx really need a lot of practice, and that the more I do it the more it'll make sense...so I'm excited to do that! However,\nThis was a really fun assignment to work on! It was very rewarding to gradually go through my ideas and realize that there's something in our \"toolbox\" that can help me achieve what I have in mind. \n",
"_____no_output_____"
]
],
[
[
"import requests\nfrom bs4 import BeautifulSoup\nimport random\nimport nltk\nimport re\nfrom time import sleep\nnltk.download('averaged_perceptron_tagger')\nfrom nltk.tag import pos_tag",
"[nltk_data] Downloading package averaged_perceptron_tagger to\n[nltk_data] /root/nltk_data...\n[nltk_data] Package averaged_perceptron_tagger is already up-to-\n[nltk_data] date!\n"
],
[
"fairytaleLinks = [\"Charles_Perrault/Little_Thumb.html#gsc.tab=0\",\"Brothers_Grimm/Margaret_Hunt/The_Story_of_the_Youth_who_Went_Forth_to_Learn_What_Fear_Was.html#gsc.tab=0\",\n \"Charles_Perrault/THE_FAIRY.html#gsc.tab=0\",\"Hans_Christian_Andersen/Andersen_fairy_tale_17.html#gsc.tab=0\",\"Brothers_Grimm/Grimm_fairy_stories/Cinderella.html#gsc.tab=0\"\n \"Brothers_Grimm/Margaret_Hunt/Little_Snow-white.html#gsc.tab=0\",\n \"Hans_Christian_Andersen/Andersen_fairy_tale_17.html#gsc.tab=0\",\"Charles_Perrault/THE_MASTER_CAT,_OR_PUSS_IN_BOOTS.html#gsc.tab=0\",\n \"Brothers_Grimm/Grimm_household_tales/The_Sleeping_Beauty.html#gsc.tab=0\", \"Hans_Christian_Andersen/Andersen_fairy_tale_31.html#gsc.tab=0\",\n \"Hans_Christian_Andersen/Andersen_fairy_tale_47.html#gsc.tab=0\",\"Brothers_Grimm/Grimm_fairy_stories/Snow-White_And_Rose-Red.html#gsc.tab=0\"\n \"Brothers_Grimm/Margaret_Hunt/Hansel_and_Grethel.html#gsc.tab=0\",\"Brothers_Grimm/RUMPELSTILTSKIN.html#gsc.tab=0\"\n \"Brothers_Grimm/THE%20ELVES%20AND%20THE%20SHOEMAKER.html#gsc.tab=0\",\"Brothers_Grimm/THE%20JUNIPER-TREE.html#gsc.tab=0\",\"Brothers_Grimm/THE%20GOLDEN%20GOOSE.html#gsc.tab=0\",\n \"Brothers_Grimm/Margaret_Hunt/The_Frog-King,_or_Iron_Henry.html#gsc.tab=0\",\"Brothers_Grimm/Grimm_fairy_stories/Snow-White_And_Rose-Red.html#gsc.tab=0\"]\nfairytaleIndex = random.randint(0,(len(fairytaleLinks))-1)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"fairytaleTargetUrl = \"https://www.worldoftales.com/fairy_tales/\" + fairytaleLinks[fairytaleIndex]\nreqFairytale = requests.get(fairytaleTargetUrl)\n\nmoralLessonTargetUrl = \"https://daringtolivefully.com/life-lessons\"\nreqMoralLesson = requests.get(moralLessonTargetUrl)\n\nsuperpowerTargetUrl = \"http://www.superheronation.com/2007/12/30/list-of-superpowers/\"\nreqSuperpower = requests.get(superpowerTargetUrl)\n\nvillainTargetUrl = \"https://beat102103.com/life/top-10-fairytale-villains-ranked/\"\nreqVillain = requests.get(villainTargetUrl)\n\n",
"_____no_output_____"
],
[
"#FOR CHARACTER\nsoupFairytale = BeautifulSoup(reqFairytale.content, 'html.parser')\nstory = soupFairytale.find_all(\"p\")\nparagraphs = []\nfor i in story:\n content = str(i.text)\n content = content.replace(\"\\r\",\" \")\n content = content.replace(\"\\n\",\"\")\n paragraphs.append(content)\n \n\n#print(paragraphs)\n\nstory = \" \"\nstory = story.join(paragraphs)\n#print(story)\n#Code from StackOverflow: https://stackoverflow.com/questions/17669952/finding-proper-nouns-using-nltk-wordnet\ntagged_sent = pos_tag(story.split())\npropernouns = [word for word,pos in tagged_sent if pos == 'NNP']\n\n#print(propernouns)\nhighestCount = 0\n#A loop that looks for the most repeated proper noun\nfor i in propernouns:\n currentCount = propernouns.count(i)\n if currentCount > highestCount:\n highestCount = currentCount\n \n\ncountDictionary = {i:propernouns.count(i) for i in propernouns}\n\n\n\n#Had an issue with this at first as there's no direct function to get the key using the value, so I researched solutions and used this page:\n# https://www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/\ndef get_key(val):\n for key, value in countDictionary.items():\n if val == value:\n return key\n\n \n \ncharacterName = get_key(highestCount)\n#to eliminate instances like \"king's\"\ncharacterName = characterName.replace(\"'\", \"\")\ncharacterName = characterName.replace('\"', \"\")\n#print(characterName)\n\n\n\n",
"_____no_output_____"
],
[
"#FOR MORAL LESSON\nsoupLesson = BeautifulSoup(reqMoralLesson.content, 'html.parser')\nlessonsHTML = soupLesson.find_all(\"p\")\nlessons = []\nfor i in lessonsHTML:\n content = str(i.text)\n content = content.replace(\"\\r\",\" \")\n content = content.replace(\"\\n\",\"\")\n lessons.append(content)\n\n\n#used .index() to figure out the slicing here: \ndel lessons[0]\ndel lessons[101:len(lessons)+1]\n\n# to make things more convenient :)\ntoRemove = ['2. Don’t postpone joy.',\n'8. Pay yourself first: save 10% of what you earn.',\n'10. Don’t go into bad debt (debt taken on for consumption).',\n'15. Remember Henry Ford’s admonishment: “Whether you think you can or whether you think you can’t, you’re right.”',\n'19. Don’t smoke. Don’t abuse alcohol. Don’t do drugs.',\n'36. Don’t take action when you’re angry. Take a moment to calm down and ask yourself if what you’re thinking of doing is really in your best interest.',\n'38. Worry is a waste of time; it’s a misuse of your imagination.',\n'44. Don’t gossip. Remember the following quote by Eleanor Roosevelt: “Great minds discuss ideas, average minds discuss events, small minds discuss people.”',\n'52. Don’t procrastinate; procrastination is the thief of time.',\n '61. Don’t take yourself too seriously.',\n'62. During difficult times remember this: “And this too shall pass.”',\n'63. When things go wrong remember that few things are as bad as they first seem.',\n'64. Keep in mind that mistakes are stepping stones to success. Success and failure are a team; success is the hero and failure is the sidekick. Don’t be afraid to fail.',\n'70. If you don’t know the answer, say so; then go and find the answer.',\n'77. Don’t renege on your promises, whether to others or to yourself.',\n'80. Don’t worry about what other people think.',\n'89. Every time you fall simply get back up again.',\n'95. Don’t argue for your limitations.',\n '97. Listen to Eleanor Roosevelt’s advice: “No one can make you feel inferior without your consent.”',\n'99. Remember the motto: “You catch more flies with honey.”']\n\nfor i in toRemove:\n lessons.remove(i)\n\n#print(lessons)\nx = 0\nstrippedLessons = []\n\nfor i in lessons:\n lessons[x] = lessons[x].strip()\n #remove any digits + the period after the digits \n lessons[x] = re.sub(\"\\d+\"\"[.]\", \"\", i)\n\n #lessons[x] = re.sub(\"n'^Dot\", \"not to\", lessons[x]) // attempt to turn all don't(s) at the beginning of the sentence to \"not to\"\n\n #remove periods ONLY at the end\n lessons[x] = re.sub(\"\\.$\", \" \", lessons[x])\n \n lessons[x] = lessons[x].replace(\"theirs\",\"others'\").replace(\"your\",\"their\").replace(\"you\",\"they\").replace(\"theyself\",\"themselves\").lower()\n strippedLessons.append(lessons[x])\n\n x+=1\n\n\n\n#specifics = {\"you've\":\"they've\",\"theirself\":\"themself\",\"theirs\":\"others'\"} // #an attempt to fix any awkward results due to the replace function above\n\n#y = 0\n#for word in strippedLessons[y]:\n # if word.lower() in specifics:\n # srippedLessons = text.replace(word, specifics[word.lower()])\n # y+=1\n\n\nrandomLessonIndex = random.randint(0, len(strippedLessons)-1)\nchosenMoralLesson = strippedLessons[randomLessonIndex]\n#print(chosenMoralLesson)\n\n",
"_____no_output_____"
],
[
"#FOR SUPERPOWER\nsoupSuperpower = BeautifulSoup(reqSuperpower.content, 'html.parser')\nsuperpowers = soupSuperpower.find_all(\"li\")\nallSuperpowers = []\nfor i in superpowers:\n content = (str(i.text)).strip()\n content = content.replace(\"\\r\",\" \")\n content = content.replace(\"\\n\",\" \")\n content = content.replace(\"\\t\",\"\")\n allSuperpowers.append(content)\n\n#allSuperpowers.index('Superstrength')\n#removing all non-Superpower elements\ndel allSuperpowers[67:len(allSuperpowers)+1]\ndel allSuperpowers[0:5]\ntoRemove2 = ['Skills and/or knowledge Popular categories: science, mechanical, computer/electronics, weapons-handling/military, driving, occult/magical.',\n 'Popular categories: science, mechanical, computer/electronics, weapons-handling/military, driving, occult/magical.',\n 'Resourcefulness (“I’m never more than a carton of baking soda away from a doomsday device”)']\n\nfor i in toRemove2:\n allSuperpowers.remove(i)\n\nrandomSuperpowerIndex = random.randint(0, len(allSuperpowers)-1)\nchosenSuperpower = allSuperpowers[randomSuperpowerIndex].lower()\n#print(chosenSuperpower)\n",
"_____no_output_____"
],
[
"#FOR VILLAIN:\nsoupVillain = BeautifulSoup(reqVillain.content, 'html.parser')\nvillainsHTML = soupVillain.find_all(\"strong\")\n\nvillains = []\nfor i in villainsHTML:\n content = str(i.text)\n content = content.replace(\"\\r\",\" \")\n content = content.replace(\"\\n\",\"\")\n content = content.replace(\"\\xa0\",\" \")\n villains.append(content)\n\nx = 0\nfor v in villains:\n villains[x] = re.sub(\"\\d+\"\"[.]\", \"\", v)\n villains[x].strip()\n x+=1\n\nrandomVillainIndex = random.randint(0, len(villains)-1)\nchosenVillain = villains[randomVillainIndex].lower()\n#print(chosenVillain)",
"_____no_output_____"
],
[
"print(u\"\\U0001F5E8\"+ \" \" +\"Oh? You're out of bedtime stories to tell?\")\nsleep(1.5)\nprint(u\"\\U0001F5E8\"+ \" \" +\"hmmm...\")\nsleep(2)\nprint(u\"\\U0001F5E8\"+ \" \" +\"how about you tell a story about\")\nsleep(1)\nprint(u\"\\U0001F5E8\"+ \" \" +\".....\")\nsleep(3)\nprint(u\"\\U0001F5E8\"+ \" \" +characterName+\"?\")\nsleep(2)\nprint(u\"\\U0001F5E8\"+ \" \" +\"yeah...yeah, tell a story about \" + characterName +\" \" + \"and how they learnt to...\")\nsleep(1.5)\nprint(u\"\\U0001F5E8\"+ \" \" +\"I don't know...like..\")\nsleep(3)\nprint(u\"\\U0001F5E8\"+ \" \" +\"how they learnt to...\" + chosenMoralLesson)\nsleep(1.5)\nprint(u\"\\U0001F5E8\"+ \" \" +\"Yes! that sounds good I guess.\")\nsleep(2)\nprint(u\"\\U0001F5E8\"+ \" \" +\"and of course it isn't that easy...it isn't all rainbows and sunshine you know?\")\nsleep(3)\nprint(u\"\\U0001F5E8\"+ \" \" +\"I don't know... maybe talk about their struggles with...\")\nsleep(4)\nprint(u\"\\U0001F5E8\"+ \" \" +\"with\" + chosenVillain + \"...yikes\")\nsleep(4)\nprint(u\"\\U0001F5E8\"+ \" \" +\"but we need a happily ever after, so maybe say that \" + characterName + \" was able to defeat\" + chosenVillain + \" somehow...\")\nsleep(5)\nprint(u\"\\U0001F5E8\"+ \" \" +\"like by \" + chosenSuperpower + \" or something...does that make sense?\")\nsleep(2)\nprint(u\"\\U0001F5E8\"+ \" \" +\"I mean even if it doesn't...that's all I can give you tonight\")\nsleep(3)\nprint(u\"\\U0001F5E8\"+ \" \" +\"you should practice being imaginative or something...\")\nsleep(2)\nprint(u\"\\U0001F5E8\"+ \" \" +\"anyways, it's way past bedtime. Go tell your story!\")\nprint(\"\\n\\n\\nERROR:chat disconnected\")",
"🗨 Oh? You're out of bedtime stories to tell?\n🗨 hmmm...\n🗨 how about you tell a story about\n🗨 .....\n🗨 Gerda?\n🗨 yeah...yeah, tell a story about Gerda and how they learnt to...\n🗨 I don't know...like..\n🗨 how they learnt to... develop their listening skills \n🗨 Yes! that sounds good I guess.\n🗨 and of course it isn't that easy...it isn't all rainbows and sunshine you know?\n🗨 I don't know... maybe talk about their struggles with...\n🗨 with the evil queen from snow white...yikes\n🗨 but we need a happily ever after, so maybe say that Gerda was able to defeat the evil queen from snow white somehow...\n🗨 like by supersenses sight/hearing/smell/taste/touch sensing danger (spider-sense) sensing other types of events (dishonesty, murder, etc.) or something...does that make sense?\n🗨 I mean even if it doesn't...that's all I can give you tonight\n🗨 you should practice being imaginative or something...\n🗨 anyways, it's way past bedtime. Go tell your story!\n\n\n\nERROR:chat disconnected\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd793b498a5dc257115d3299cce8210afd651d2
| 480,205 |
ipynb
|
Jupyter Notebook
|
notebooks/experiments/icews/Granger_casuality_analysis.ipynb
|
omid55/dynamic_sparse_balance_theory
|
b9de708e9f1e9be6f1a3f7d80e60b4716858a35f
|
[
"MIT"
] | null | null | null |
notebooks/experiments/icews/Granger_casuality_analysis.ipynb
|
omid55/dynamic_sparse_balance_theory
|
b9de708e9f1e9be6f1a3f7d80e60b4716858a35f
|
[
"MIT"
] | null | null | null |
notebooks/experiments/icews/Granger_casuality_analysis.ipynb
|
omid55/dynamic_sparse_balance_theory
|
b9de708e9f1e9be6f1a3f7d80e60b4716858a35f
|
[
"MIT"
] | null | null | null | 493.530319 | 272,156 | 0.923358 |
[
[
[
"# Imports",
"_____no_output_____"
]
],
[
[
"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport cvxpy as cp\nimport time\nimport collections\nfrom typing import Dict\nfrom typing import List\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport networkx as nx\nimport imp\nimport os\nimport pickle as pk\nimport scipy as sp\nfrom statsmodels.tsa.stattools import grangercausalitytests\n%matplotlib inline\n\nimport sys\nsys.path.insert(0, '../../../src/')\n\nimport network_utils\nimport utils",
"/home/omid/.local/lib/python3.5/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.\n from pandas.core import datetools\n"
]
],
[
[
"# Loading the preprocessed data",
"_____no_output_____"
]
],
[
[
"loaded_d = utils.load_it('/home/omid/Downloads/DT/cvx_data.pk')\nobs = loaded_d['obs']\nT = loaded_d['T']\n\nperiods = [['1995-01-01', '1995-03-26'],\n ['1995-03-26', '1995-06-18'],\n ['1995-06-18', '1995-09-10'],\n ['1995-09-10', '1995-12-03'],\n ['1995-12-03', '1996-02-25'],\n ['1996-02-25', '1996-05-19'],\n ['1996-05-19', '1996-08-11'],\n ['1996-08-11', '1996-11-03'],\n ['1996-11-03', '1997-01-26'],\n ['1997-01-26', '1997-04-20'],\n ['1997-04-20', '1997-07-13'],\n ['1997-07-13', '1997-10-05'],\n ['1997-10-05', '1997-12-28'],\n ['1997-12-28', '1998-03-22'],\n ['1998-03-22', '1998-06-14'],\n ['1998-06-14', '1998-09-06'],\n ['1998-09-06', '1998-11-29'],\n ['1998-11-29', '1999-02-21'],\n ['1999-02-21', '1999-05-16'],\n ['1999-05-16', '1999-08-08'],\n ['1999-08-08', '1999-10-31'],\n ['1999-10-31', '2000-01-23'],\n ['2000-01-23', '2000-04-16'],\n ['2000-04-16', '2000-07-09'],\n ['2000-07-09', '2000-10-01'],\n ['2000-10-01', '2000-12-24'],\n ['2000-12-24', '2001-03-18'],\n ['2001-03-18', '2001-06-10'],\n ['2001-06-10', '2001-09-02'],\n ['2001-09-02', '2001-11-25'],\n ['2001-11-25', '2002-02-17'],\n ['2002-02-17', '2002-05-12'],\n ['2002-05-12', '2002-08-04'],\n ['2002-08-04', '2002-10-27'],\n ['2002-10-27', '2003-01-19'],\n ['2003-01-19', '2003-04-13'],\n ['2003-04-13', '2003-07-06'],\n ['2003-07-06', '2003-09-28'],\n ['2003-09-28', '2003-12-21'],\n ['2003-12-21', '2004-03-14'],\n ['2004-03-14', '2004-06-06'],\n ['2004-06-06', '2004-08-29'],\n ['2004-08-29', '2004-11-21'],\n ['2004-11-21', '2005-02-13'],\n ['2005-02-13', '2005-05-08'],\n ['2005-05-08', '2005-07-31'],\n ['2005-07-31', '2005-10-23'],\n ['2005-10-23', '2006-01-15'],\n ['2006-01-15', '2006-04-09'],\n ['2006-04-09', '2006-07-02'],\n ['2006-07-02', '2006-09-24'],\n ['2006-09-24', '2006-12-17'],\n ['2006-12-17', '2007-03-11'],\n ['2007-03-11', '2007-06-03'],\n ['2007-06-03', '2007-08-26'],\n ['2007-08-26', '2007-11-18'],\n ['2007-11-18', '2008-02-10'],\n ['2008-02-10', '2008-05-04'],\n ['2008-05-04', '2008-07-27'],\n ['2008-07-27', '2008-10-19'],\n ['2008-10-19', '2009-01-11'],\n ['2009-01-11', '2009-04-05'],\n ['2009-04-05', '2009-06-28'],\n ['2009-06-28', '2009-09-20'],\n ['2009-09-20', '2009-12-13'],\n ['2009-12-13', '2010-03-07'],\n ['2010-03-07', '2010-05-30'],\n ['2010-05-30', '2010-08-22'],\n ['2010-08-22', '2010-11-14'],\n ['2010-11-14', '2011-02-06'],\n ['2011-02-06', '2011-05-01'],\n ['2011-05-01', '2011-07-24'],\n ['2011-07-24', '2011-10-16'],\n ['2011-10-16', '2012-01-08'],\n ['2012-01-08', '2012-04-01'],\n ['2012-04-01', '2012-06-24'],\n ['2012-06-24', '2012-09-16'],\n ['2012-09-16', '2012-12-09'],\n ['2012-12-09', '2013-03-03'],\n ['2013-03-03', '2013-05-26'],\n ['2013-05-26', '2013-08-18'],\n ['2013-08-18', '2013-11-10'],\n ['2013-11-10', '2014-02-02'],\n ['2014-02-02', '2014-04-27'],\n ['2014-04-27', '2014-07-20'],\n ['2014-07-20', '2014-10-12'],\n ['2014-10-12', '2015-01-04'],\n ['2015-01-04', '2015-03-29'],\n ['2015-03-29', '2015-06-21'],\n ['2015-06-21', '2015-09-13'],\n ['2015-09-13', '2015-12-06'],\n ['2015-12-06', '2016-02-28'],\n ['2016-02-28', '2016-05-22'],\n ['2016-05-22', '2016-08-14'],\n ['2016-08-14', '2016-11-06'],\n ['2016-11-06', '2017-01-29'],\n ['2017-01-29', '2017-04-23'],\n ['2017-04-23', '2017-07-16'],\n ['2017-07-16', '2017-10-08'],\n ['2017-10-08', '2017-12-31'],\n ['2017-12-31', '2018-03-25'],\n ['2018-03-25', '2018-06-17'],\n ['2018-06-17', '2018-09-09']]",
"_____no_output_____"
],
[
"sns.set(rc={'figure.figsize': (30, 8)})\nacc_from_prev_l2norm_dists = []\nn = len(T)\nfor i in range(1, n):\n current = T[i]\n prev = T[i-1]\n acc_from_prev_l2norm_dists.append(np.linalg.norm(prev - current))\nplt.plot(acc_from_prev_l2norm_dists)\nplt.ylabel('Frobenius-norm Difference of Consecutive Matrices.')\n# seting xticks\nax = plt.axes()\nnumber_of_periods = len(periods)\nax.set_xticks(list(range(number_of_periods)))\nlabels = ['[{}, {}] to [{}, {}]'.format(periods[i][0][:7], periods[i][1][:7], periods[i+1][0][:7], periods[i+1][1][:7]) for i in range(number_of_periods-1)]\nax.set_xticklabels(labels, rotation=45);\nfor tick in ax.xaxis.get_majorticklabels():\n tick.set_horizontalalignment(\"right\")",
"/home/omid/.local/lib/python3.5/site-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.\n warnings.warn(message, mplDeprecation, stacklevel=1)\n"
]
],
[
[
"# Death data analysis",
"_____no_output_____"
]
],
[
[
"all_death_data = pd.read_csv(\n '/home/omid/Datasets/deaths/battle-related-deaths-in-state-based-conflicts-since-1946-by-world-region.csv')\nall_death_data.drop(columns=['Code'], inplace=True)",
"_____no_output_____"
],
[
"all_death_data.head()",
"_____no_output_____"
],
[
"all_death_data.Entity.unique()",
"_____no_output_____"
],
[
"# death_data = all_death_data[all_death_data['Entity'] == 'Asia and Oceania']\ndeath_data = all_death_data",
"_____no_output_____"
],
[
"ad = death_data.groupby('Year').sum()\nannual_deaths = np.array(ad['Battle-related deaths'])\nyears = death_data.Year.unique()",
"_____no_output_____"
],
[
"indices = np.where(years >= 1995)[0]\nyears = years[indices]\nannual_deaths = annual_deaths[indices]",
"_____no_output_____"
],
[
"years",
"_____no_output_____"
],
[
"sns.set(rc={'figure.figsize': (8, 6)})\nplt.plot(annual_deaths);",
"_____no_output_____"
],
[
"len(years)",
"_____no_output_____"
],
[
"frob_norms = []\nfor i in range(len(years)):\n index = i * 4\n frob_norms.append(np.linalg.norm(T[index+1] - T[index]))",
"_____no_output_____"
],
[
"sns.set(rc={'figure.figsize': (8, 6)})\nplt.plot(frob_norms);",
"_____no_output_____"
],
[
"# It tests whether the time series in the second column Granger causes the time series in the first column.\ngrangercausalitytests(\n np.column_stack((frob_norms, annual_deaths)),\n maxlag=4)",
"\nGranger Causality\nnumber of lags (no zero) 1\nssr based F test: F=0.2713 , p=0.6088 , df_denom=18, df_num=1\nssr based chi2 test: chi2=0.3165 , p=0.5737 , df=1\nlikelihood ratio test: chi2=0.3141 , p=0.5752 , df=1\nparameter F test: F=0.2713 , p=0.6088 , df_denom=18, df_num=1\n\nGranger Causality\nnumber of lags (no zero) 2\nssr based F test: F=1.1877 , p=0.3320 , df_denom=15, df_num=2\nssr based chi2 test: chi2=3.1672 , p=0.2052 , df=2\nlikelihood ratio test: chi2=2.9401 , p=0.2299 , df=2\nparameter F test: F=1.1877 , p=0.3320 , df_denom=15, df_num=2\n\nGranger Causality\nnumber of lags (no zero) 3\nssr based F test: F=1.7629 , p=0.2076 , df_denom=12, df_num=3\nssr based chi2 test: chi2=8.3739 , p=0.0389 , df=3\nlikelihood ratio test: chi2=6.9379 , p=0.0739 , df=3\nparameter F test: F=1.7629 , p=0.2076 , df_denom=12, df_num=3\n\nGranger Causality\nnumber of lags (no zero) 4\nssr based F test: F=2.5466 , p=0.1124 , df_denom=9, df_num=4\nssr based chi2 test: chi2=20.3729 , p=0.0004 , df=4\nlikelihood ratio test: chi2=13.6256 , p=0.0086 , df=4\nparameter F test: F=2.5466 , p=0.1124 , df_denom=9, df_num=4\n"
],
[
"sp.stats.pearsonr(frob_norms, annual_deaths)",
"_____no_output_____"
]
],
[
[
"# Relationship with trade (similar to Jackson's pnas paper)",
"_____no_output_____"
]
],
[
[
"# 1995 to 2017.\ntrade_in_percent_of_gdp = np.array(\n [43.403, 43.661, 45.613, 46.034, 46.552,\n 51.156, 50.012, 49.66, 50.797, 54.085,\n 56.169, 58.412, 58.975, 60.826, 52.31,\n 56.82, 60.427, 60.474, 60.021, 59.703, 57.798, 56.096, 57.85])",
"_____no_output_____"
],
[
"frob_norms = []\nfor i in range(len(trade_in_percent_of_gdp)):\n index = i * 4\n frob_norms.append(np.linalg.norm(T[index+1] - T[index]))",
"_____no_output_____"
],
[
"# It tests whether the time series in the second column Granger causes the time series in the first column.\ngrangercausalitytests(\n np.column_stack((frob_norms, trade_in_percent_of_gdp)),\n maxlag=4)",
"\nGranger Causality\nnumber of lags (no zero) 1\nssr based F test: F=10.1735 , p=0.0048 , df_denom=19, df_num=1\nssr based chi2 test: chi2=11.7798 , p=0.0006 , df=1\nlikelihood ratio test: chi2=9.4341 , p=0.0021 , df=1\nparameter F test: F=10.1735 , p=0.0048 , df_denom=19, df_num=1\n\nGranger Causality\nnumber of lags (no zero) 2\nssr based F test: F=1.6357 , p=0.2258 , df_denom=16, df_num=2\nssr based chi2 test: chi2=4.2936 , p=0.1169 , df=2\nlikelihood ratio test: chi2=3.9066 , p=0.1418 , df=2\nparameter F test: F=1.6357 , p=0.2258 , df_denom=16, df_num=2\n\nGranger Causality\nnumber of lags (no zero) 3\nssr based F test: F=0.5014 , p=0.6878 , df_denom=13, df_num=3\nssr based chi2 test: chi2=2.3143 , p=0.5098 , df=3\nlikelihood ratio test: chi2=2.1899 , p=0.5339 , df=3\nparameter F test: F=0.5014 , p=0.6878 , df_denom=13, df_num=3\n\nGranger Causality\nnumber of lags (no zero) 4\nssr based F test: F=0.4621 , p=0.7623 , df_denom=10, df_num=4\nssr based chi2 test: chi2=3.5119 , p=0.4761 , df=4\nlikelihood ratio test: chi2=3.2225 , p=0.5213 , df=4\nparameter F test: F=0.4621 , p=0.7623 , df_denom=10, df_num=4\n"
],
[
"# It tests whether the time series in the second column Granger causes the time series in the first column.\ngrangercausalitytests(\n np.column_stack((trade_in_percent_of_gdp, frob_norms)),\n maxlag=4)",
"\nGranger Causality\nnumber of lags (no zero) 1\nssr based F test: F=5.7792 , p=0.0266 , df_denom=19, df_num=1\nssr based chi2 test: chi2=6.6917 , p=0.0097 , df=1\nlikelihood ratio test: chi2=5.8424 , p=0.0156 , df=1\nparameter F test: F=5.7792 , p=0.0266 , df_denom=19, df_num=1\n\nGranger Causality\nnumber of lags (no zero) 2\nssr based F test: F=1.9345 , p=0.1768 , df_denom=16, df_num=2\nssr based chi2 test: chi2=5.0781 , p=0.0789 , df=2\nlikelihood ratio test: chi2=4.5480 , p=0.1029 , df=2\nparameter F test: F=1.9345 , p=0.1768 , df_denom=16, df_num=2\n\nGranger Causality\nnumber of lags (no zero) 3\nssr based F test: F=2.4357 , p=0.1113 , df_denom=13, df_num=3\nssr based chi2 test: chi2=11.2416 , p=0.0105 , df=3\nlikelihood ratio test: chi2=8.9204 , p=0.0304 , df=3\nparameter F test: F=2.4357 , p=0.1113 , df_denom=13, df_num=3\n\nGranger Causality\nnumber of lags (no zero) 4\nssr based F test: F=1.3279 , p=0.3249 , df_denom=10, df_num=4\nssr based chi2 test: chi2=10.0918 , p=0.0389 , df=4\nlikelihood ratio test: chi2=8.0944 , p=0.0882 , df=4\nparameter F test: F=1.3279 , p=0.3249 , df_denom=10, df_num=4\n"
],
[
"sp.stats.pearsonr(frob_norms, trade_in_percent_of_gdp)",
"_____no_output_____"
],
[
"sp.stats.pearsonr(frob_norms, 1/trade_in_percent_of_gdp)",
"_____no_output_____"
],
[
"sp.stats.spearmanr(frob_norms, trade_in_percent_of_gdp)",
"_____no_output_____"
],
[
"sns.set(rc={'figure.figsize': (8, 6)})\nfig, ax1 = plt.subplots()\n\ncolor = 'tab:blue'\n# ax1.set_xlabel('time (s)')\nax1.set_ylabel('Frobenius-norm Difference of Consecutive Matrices', color=color)\nax1.plot(frob_norms, '-p', color=color)\nax1.tick_params(axis='y', labelcolor=color)\n# ax|1.legend(['Distance of matrices'])\n\nax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n\ncolor = 'tab:red'\nax2.set_ylabel('Global Trade (% of GDP)', color=color) # we already handled the x-label with ax1\nax2.plot(trade_in_percent_of_gdp, '-x', color=color, linestyle='--')\nax2.tick_params(axis='y', labelcolor=color)\n# ax2.legend(['Trades'], loc='center')\n\n# seting xticks\nlabels = [year for year in range(1995, 2018)]\nax1.set_xticks(list(range(len(labels))))\nax1.set_xticklabels(labels, rotation=45);\nfor tick in ax1.xaxis.get_majorticklabels():\n tick.set_horizontalalignment(\"right\")\n\nfig.tight_layout() # otherwise the right y-label is slightly clipped\nplt.savefig('frobenius_vs_trade.pdf', bbox_inches='tight')",
"_____no_output_____"
],
[
"sns.set(rc={'figure.figsize': (8, 6)})\nfig, ax1 = plt.subplots()\n\ncolor = 'tab:blue'\n# ax1.set_xlabel('time (s)')\nax1.set_ylabel('Frobenius-norm Difference of Consecutive Matrices', color=color)\nax1.plot(frob_norms, '-p', color=color)\nax1.tick_params(axis='y', labelcolor=color)\n\nax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n\ncolor = 'tab:red'\nax2.set_ylabel('Inverse Global Trade (% of GDP)', color=color) # we already handled the x-label with ax1\nax2.plot(1/trade_in_percent_of_gdp, '-x', color=color, linestyle='--')\nax2.tick_params(axis='y', labelcolor=color)\n\n# seting xticks\nlabels = [year for year in range(1995, 2018)]\nax1.set_xticks(list(range(len(labels))))\nax1.set_xticklabels(labels, rotation=45);\nfor tick in ax1.xaxis.get_majorticklabels():\n tick.set_horizontalalignment(\"right\")\n\nfig.tight_layout() # otherwise the right y-label is slightly clipped\nplt.savefig('frobenius_vs_inversetrade.pdf', bbox_inches='tight')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd7aa57160f547aa189c93d6584f77cc06bc7f1
| 40,188 |
ipynb
|
Jupyter Notebook
|
Improved_anime_recommender copy.ipynb
|
DFatade/Anime-Recommender
|
313407ddbbb9ac54e292cef5b4dc49711dd8c0f8
|
[
"MIT"
] | null | null | null |
Improved_anime_recommender copy.ipynb
|
DFatade/Anime-Recommender
|
313407ddbbb9ac54e292cef5b4dc49711dd8c0f8
|
[
"MIT"
] | null | null | null |
Improved_anime_recommender copy.ipynb
|
DFatade/Anime-Recommender
|
313407ddbbb9ac54e292cef5b4dc49711dd8c0f8
|
[
"MIT"
] | null | null | null | 33.295775 | 130 | 0.356723 |
[
[
[
"import seaborn as sb\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"from sklearn.neighbors import NearestNeighbors",
"_____no_output_____"
],
[
"link='/Users/afatade/Downloads/anime_cleaned.csv'\ndata=pd.read_csv(link)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"len(data)",
"_____no_output_____"
],
[
"#We have a lot of data. Lets see what we can do about our type and genre columns.",
"_____no_output_____"
],
[
"#Now we want to make use of our genres and type columns. These are very important when considering the type of anime one \n#wishes to make use of. We can call the pd.get_dummies function to generate a one hot encoded dataset.\n\n#For the genres column, we will call str.get_dummies() and set our seperator to ','. This was we can\n#do the dame for the genres column.",
"_____no_output_____"
],
[
"data.isnull().sum()",
"_____no_output_____"
],
[
"#We see we're missing some entrie for certain variables, but thats okay. We wont be using these variables.\n#Lets isolate type, source,episodes and genre. These are really important features for recommending\n#similar anime. Lets keep it simple.",
"_____no_output_____"
],
[
"#We need to generate one hot encoded columns for type, source and tv. Lets go\n\ntype_encoded=pd.get_dummies(data['type'])",
"_____no_output_____"
],
[
"type_encoded.head()",
"_____no_output_____"
],
[
"source_encoded=pd.get_dummies(data['source'])",
"_____no_output_____"
],
[
"source_encoded.head()",
"_____no_output_____"
],
[
"#The type column has a lot of factors that the typical anime fanatic doesn't look into.\n#Typically we only look at manga for the most part. However, we will consider using these features later.\n\n#There are a lot of values per row in the genres column. It would be logical to make use of a \n#one hot encoding mechanism that makes use of a seperator.\n\ngenre_encoded=data['genre'].str.get_dummies(sep=',')",
"_____no_output_____"
],
[
"genre_encoded.head().values",
"_____no_output_____"
],
[
"#We see our values have been encoded successfully.\n\n#Lets create a new data frame with our episodes list and our encoded values\n\nfeatures=pd.concat([genre_encoded, type_encoded,data['episodes']],axis=1)",
"_____no_output_____"
],
[
"features.head()",
"_____no_output_____"
],
[
"#Now we know our data has features with differing magnitudes. It would be logical to scale this data.\n\nfeatures_scaled=MinMaxScaler().fit_transform(features)",
"_____no_output_____"
],
[
"features_scaled[0]",
"_____no_output_____"
],
[
"#This is just one feature element that we are going to chuck into our KNN algorithm\n\ncollaborative_filter=NearestNeighbors().fit(features_scaled)",
"_____no_output_____"
],
[
"collaborative_filter.kneighbors([features_scaled[0]])",
"_____no_output_____"
],
[
"data['title'].iloc[[0, 4893, 2668, 3943, 4664],].values",
"_____no_output_____"
],
[
"#Okay. We see that this filtering mechanism works very well!\n#Lets see if we can generate a function such that when a user enters a name, a new anime is recommended",
"_____no_output_____"
],
[
"#Lets create some functions so this data looks neater overall.\n\ndef preprocess_data():\n link='/Users/afatade/Downloads/anime_cleaned.csv'\n data=pd.read_csv(link)\n type_encoded=pd.get_dummies(data['type'])\n source_encoded=pd.get_dummies(data['source'])\n genre_encoded=data['genre'].str.get_dummies(sep=',')\n features=pd.concat([genre_encoded, type_encoded,data['episodes']],axis=1)\n features_scaled=MinMaxScaler().fit_transform(features)\n return features_scaled",
"_____no_output_____"
],
[
"#This function will return the name of the anime in the dataset even if it is entered partially\n\ndef get_partial_names(title):\n names=list(data.title.values)\n for name in names:\n if title in name:\n return [name, names.index(name)]\n \n#This function will return features for recommendation\ndef get_features(title):\n values=get_partial_names(title)\n return values[1]\n\ndef get_vector(title):\n index=get_features(title)\n data=preprocess_data()\n return data[index]\n\ndef collaborative_filter():\n data=preprocess_data()\n filtering=NearestNeighbors().fit(data)\n return filtering\n \n\ndef get_recommendations(title):\n vectorized_input=get_vector(title)\n filter_model=collaborative_filter()\n indices=filter_model.kneighbors([vectorized_input])[1]\n recommendations=data['title'].iloc[indices[0],].values\n return recommendations",
"_____no_output_____"
],
[
"get_recommendations(\"One Piece\")",
"_____no_output_____"
],
[
"#Lovely! We'll work on the user interface later.",
"_____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"
]
] |
cbd7c041d039990892965b9d2721b3a73b74fd2c
| 30,796 |
ipynb
|
Jupyter Notebook
|
Cap06 - Machine Learning em Python/Machine Learning em Python - Regressão/Processo-Machine-Learning-Parte2.ipynb
|
FelipeChristanelli/BigData_Real-Time_Analytics_Python_e_Spark
|
9699e67a7ef5fc6db3844c299d91e6a39feb78fe
|
[
"MIT"
] | null | null | null |
Cap06 - Machine Learning em Python/Machine Learning em Python - Regressão/Processo-Machine-Learning-Parte2.ipynb
|
FelipeChristanelli/BigData_Real-Time_Analytics_Python_e_Spark
|
9699e67a7ef5fc6db3844c299d91e6a39feb78fe
|
[
"MIT"
] | null | null | null |
Cap06 - Machine Learning em Python/Machine Learning em Python - Regressão/Processo-Machine-Learning-Parte2.ipynb
|
FelipeChristanelli/BigData_Real-Time_Analytics_Python_e_Spark
|
9699e67a7ef5fc6db3844c299d91e6a39feb78fe
|
[
"MIT"
] | null | null | null | 28.620818 | 498 | 0.567152 |
[
[
[
"# <font color='blue'>Data Science Academy</font>\n# <font color='blue'>Big Data Real-Time Analytics com Python e Spark</font>\n\n# <font color='blue'>Capítulo 6</font>",
"_____no_output_____"
],
[
"# Machine Learning em Python - Parte 2 - Regressão",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image\nImage(url = 'images/processo.png')",
"_____no_output_____"
],
[
"import sklearn as sl\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nsl.__version__",
"_____no_output_____"
]
],
[
[
"## Definição do Problema de Negócio",
"_____no_output_____"
],
[
"Vamos criar um modelo preditivo que seja capaz de prever o preço de casas com base em uma série de variáveis (características) sobre diversas casas em um bairro de Boston, cidade dos EUA.\n\nDataset: https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html",
"_____no_output_____"
],
[
"## Avaliando a Performance",
"_____no_output_____"
],
[
"https://scikit-learn.org/stable/modules/model_evaluation.html",
"_____no_output_____"
],
[
"As métricas que você escolhe para avaliar a performance do modelo vão influenciar a forma como a performance é medida e comparada com modelos criados com outros algoritmos.",
"_____no_output_____"
],
[
"### Métricas para Algoritmos de Regressão",
"_____no_output_____"
],
[
"Métricas Para Avaliar Modelos de Regressão\n\n- Mean Squared Error (MSE)\n- Root Mean Squared Error (RMSE)\n- Mean Absolute Error (MAE)\n- R Squared (R²)\n- Adjusted R Squared (R²)\n- Mean Square Percentage Error (MSPE)\n- Mean Absolute Percentage Error (MAPE)\n- Root Mean Squared Logarithmic Error (RMSLE)\n",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image\nImage(url = 'images/mse.png')",
"_____no_output_____"
],
[
"from IPython.display import Image\nImage(url = 'images/rmse.png')",
"_____no_output_____"
],
[
"from IPython.display import Image\nImage(url = 'images/mae.png')",
"_____no_output_____"
],
[
"from IPython.display import Image\nImage(url = 'images/r2.png')",
"_____no_output_____"
]
],
[
[
"Como vamos agora estudar as métricas para regressão, usaremos outro dataset, o Boston Houses.",
"_____no_output_____"
],
[
"#### MSE\n\nÉ talvez a métrica mais simples e comum para a avaliação de regressão, mas também provavelmente a menos útil. O MSE basicamente mede o erro quadrado médio de nossas previsões. Para cada ponto, calcula a diferença quadrada entre as previsões e o valor real da variável alvo e, em seguida, calcula a média desses valores.\n\nQuanto maior esse valor, pior é o modelo. Esse valor nunca será negativo, já que estamos elevando ao quadrado os erros individuais de previsão, mas seria zero para um modelo perfeito.",
"_____no_output_____"
]
],
[
[
"# MSE - Mean Squared Error\n# Similar ao MAE, fornece a magnitude do erro do modelo.\n# Quanto maior, pior é o modelo!\n# Ao extrairmos a raiz quadrada do MSE convertemos as unidades de volta ao original, \n# o que pode ser útil para descrição e apresentação. Isso é chamado RMSE (Root Mean Squared Error)\n\n# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = LinearRegression()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 28.530458765974707\n"
]
],
[
[
"#### MAE",
"_____no_output_____"
]
],
[
[
"# MAE\n# Mean Absolute Error\n# É a soma da diferença absoluta entre previsões e valores reais.\n# Fornece uma ideia de quão erradas estão nossas previsões.\n# Valor igual a 0 indica que não há erro, sendo a previsão perfeita.\n\n# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.linear_model import LinearRegression\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = LinearRegression()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmae = mean_absolute_error(Y_test, Y_pred)\nprint(\"O MAE do modelo é:\", mae)",
"O MAE do modelo é: 3.455034932248345\n"
]
],
[
[
"### R^2",
"_____no_output_____"
]
],
[
[
"# R^2\n# Essa métrica fornece uma indicação do nível de precisão das previsões em relação aos valores observados.\n# Também chamado de coeficiente de determinação.\n# Valores entre 0 e 1, sendo 0 o valor ideal.\n\n# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nfrom sklearn.linear_model import LinearRegression\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = LinearRegression()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nr2 = r2_score(Y_test, Y_pred)\nprint(\"O R2 do modelo é:\", r2)",
"O R2 do modelo é: 0.6956551656111594\n"
]
],
[
[
"# Algoritmos de Regressão",
"_____no_output_____"
],
[
"## Regressão Linear",
"_____no_output_____"
],
[
"Assume que os dados estão em Distribuição Normal e também assume que as variáveis são relevantes para a construção do modelo e que não sejam colineares, ou seja, variáveis com alta correlação (cabe a você, Cientista de Dados, entregar ao algoritmo as variáveis realmente relevantes).",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = LinearRegression()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 28.530458765974707\n"
]
],
[
[
"## Ridge Regression",
"_____no_output_____"
],
[
"Extensão para a regressão linear onde a loss function é modificada para minimizar a complexidade do modelo.",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import Ridge\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = Ridge()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 29.294062013485007\n"
]
],
[
[
"## Lasso Regression",
"_____no_output_____"
],
[
"Lasso (Least Absolute Shrinkage and Selection Operator) Regression é uma modificação da regressão linear e assim como a Ridge Regression, a loss function é modificada para minimizar a complexidade do modelo.",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import Lasso\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = Lasso()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 33.394514390049885\n"
]
],
[
[
"## ElasticNet Regression",
"_____no_output_____"
],
[
"ElasticNet é uma forma de regularização da regressão que combina as propriedades da regressão Ridge e LASSO. O objetivo é minimizar a complexidade do modelo, penalizando o modelo usando a soma dos quadrados dos coeficientes.",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import ElasticNet\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = ElasticNet()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 33.27255150876938\n"
]
],
[
[
"## KNN",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.neighbors import KNeighborsRegressor\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = KNeighborsRegressor()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 47.70591377245509\n"
]
],
[
[
"## CART",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.tree import DecisionTreeRegressor\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = DecisionTreeRegressor()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 30.630958083832336\n"
]
],
[
[
"## SVM",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.svm import SVR\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Divide os dados em treino e teste\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.33, random_state = 5)\n\n# Criando o modelo\nmodelo = SVR()\n\n# Treinando o modelo\nmodelo.fit(X_train, Y_train)\n\n# Fazendo previsões\nY_pred = modelo.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"O MSE do modelo é: 93.21909995717193\n"
]
],
[
[
"## Otimização do Modelo - Ajuste de Parâmetros",
"_____no_output_____"
],
[
"Todos os algoritmos de Machine Learning são parametrizados, o que significa que você pode ajustar a performance do seu modelo preditivo, através do tuning (ajuste fino) dos parâmetros. Seu trabalho é encontrar a melhor combinação entre os parâmetros em cada algoritmo de Machine Learning. Esse processo também é chamado de Otimização Hyperparâmetro. O scikit-learn oferece dois métodos para otimização automática dos parâmetros: Grid Search Parameter Tuning e Random Search Parameter Tuning. ",
"_____no_output_____"
],
[
"### Grid Search Parameter Tuning",
"_____no_output_____"
],
[
"Este método realiza metodicamente combinações entre todos os parâmetros do algoritmo, criando um grid. Vamos experimentar este método utilizando o algoritmo de Regressão Ridge. No exemplo abaixo veremos que o valor 1 para o parâmetro alpha atingiu a melhor performance.",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nimport numpy as np\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import Ridge\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:8]\nY = array[:,8]\n\n# Definindo os valores que serão testados\nvalores_alphas = np.array([1,0.1,0.01,0.001,0.0001,0])\nvalores_grid = dict(alpha = valores_alphas)\n\n# Criando o modelo\nmodelo = Ridge()\n\n# Criando o grid\ngrid = GridSearchCV(estimator = modelo, param_grid = valores_grid)\ngrid.fit(X, Y)\n\n# Print do resultado\nprint(\"Melhores Parâmetros do Modelo:\\n\", grid.best_estimator_)",
"Melhores Parâmetros do Modelo:\n Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,\n normalize=False, random_state=None, solver='auto', tol=0.001)\n"
]
],
[
[
"### Random Search Parameter Tuning",
"_____no_output_____"
],
[
"Este método gera amostras dos parâmetros dos algoritmos a partir de uma distribuição randômica uniforme para um número fixo de interações. Um modelo é construído e testado para cada combinação de parâmetros. Neste exemplo veremos que o valor muito próximo de 1 para o parâmetro alpha é o que vai apresentar os melhores resultados.",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nimport numpy as np\nfrom scipy.stats import uniform\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import RandomizedSearchCV\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:8]\nY = array[:,8]\n\n# Definindo os valores que serão testados\nvalores_grid = {'alpha': uniform()}\nseed = 7\n\n# Criando o modelo\nmodelo = Ridge()\niterations = 100\nrsearch = RandomizedSearchCV(estimator = modelo, \n param_distributions = valores_grid, \n n_iter = iterations, \n random_state = seed)\nrsearch.fit(X, Y)\n\n# Print do resultado\nprint(\"Melhores Parâmetros do Modelo:\\n\", rsearch.best_estimator_)",
"Melhores Parâmetros do Modelo:\n Ridge(alpha=0.9779895119966027, copy_X=True, fit_intercept=True,\n max_iter=None, normalize=False, random_state=None, solver='auto',\n tol=0.001)\n"
]
],
[
[
"# Salvando o resultado do seu trabalho",
"_____no_output_____"
]
],
[
[
"# Import dos módulos\nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import Ridge\nimport pickle\n\n# Carregando os dados\narquivo = 'data/boston-houses.csv'\ncolunas = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO','B', 'LSTAT', 'MEDV']\ndados = read_csv(arquivo, delim_whitespace = True, names = colunas)\narray = dados.values\n\n# Separando o array em componentes de input e output\nX = array[:,0:13]\nY = array[:,13]\n\n# Definindo os valores para o número de folds\nteste_size = 0.35\nseed = 7\n\n# Criando o dataset de treino e de teste\nX_treino, X_teste, Y_treino, Y_teste = train_test_split(X, Y, test_size = teste_size, random_state = seed)\n\n# Criando o modelo\nmodelo = Ridge()\n\n# Treinando o modelo\nmodelo.fit(X_treino, Y_treino)\n\n# Salvando o modelo\narquivo = 'modelos/modelo_regressor_final.sav'\npickle.dump(modelo, open(arquivo, 'wb'))\nprint(\"Modelo salvo!\")\n\n# Carregando o arquivo\nmodelo_regressor_final = pickle.load(open(arquivo, 'rb'))\nprint(\"Modelo carregado!\")\n\n# Print do resultado\n# Fazendo previsões\nY_pred = modelo_regressor_final.predict(X_test)\n\n# Resultado\nmse = mean_squared_error(Y_test, Y_pred)\nprint(\"O MSE do modelo é:\", mse)",
"Modelo salvo!\nModelo carregado!\nO MSE do modelo é: 27.323167137174902\n"
]
],
[
[
"# Fim",
"_____no_output_____"
],
[
"### Obrigado - Data Science Academy - <a href=\"http://facebook.com/dsacademybr\">facebook.com/dsacademybr</a>",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbd7e0b392c8f07c788a67edc28102853dccb2e4
| 161,662 |
ipynb
|
Jupyter Notebook
|
notebooks/ResultExploration/Result_plot.ipynb
|
Bertinus/causal_cell_embedding
|
417b55749130fc7b7832fd3ee4c49feff4a04593
|
[
"MIT"
] | null | null | null |
notebooks/ResultExploration/Result_plot.ipynb
|
Bertinus/causal_cell_embedding
|
417b55749130fc7b7832fd3ee4c49feff4a04593
|
[
"MIT"
] | null | null | null |
notebooks/ResultExploration/Result_plot.ipynb
|
Bertinus/causal_cell_embedding
|
417b55749130fc7b7832fd3ee4c49feff4a04593
|
[
"MIT"
] | null | null | null | 575.309609 | 123,584 | 0.946345 |
[
[
[
"## Plotting Results",
"_____no_output_____"
]
],
[
[
"experiment_name = ['l1000_AE','l1000_cond_VAE','l1000_VAE','l1000_env_prior_VAE']",
"_____no_output_____"
],
[
"import numpy as np\nfrom scipy.spatial.distance import cosine\nfrom scipy.linalg import svd, inv\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport dill as pickle\nimport os\nimport pdb\nimport torch\nimport ai.causalcell\nfrom ai.causalcell.training import set_seed\nfrom ai.causalcell.utils import configuration\nos.chdir(os.path.join(os.path.dirname(ai.__file__), \"..\"))\nprint(\"Working in\", os.getcwd()) ",
"Working in /home/user/Documents/2020_medical/projects/causal_cell_embedding\n"
],
[
"def load_all_losses(res, name='recon_loss'):\n all_train_loss = []\n for epoch in range(len(res['losses']['train'])):\n train_loss = np.mean([res['losses']['train'][epoch][name]\n ])\n all_train_loss.append(train_loss)\n all_valid_loss = []\n for epoch in range(len(res['losses']['valid'])):\n valid_loss = np.mean([res['losses']['valid'][epoch][name]\n ])\n all_valid_loss.append(valid_loss)\n return all_train_loss, all_valid_loss",
"_____no_output_____"
],
[
"def epoch_length(i):\n return results[i]['n_samples_in_split']['train']",
"_____no_output_____"
],
[
"def get_tube(x_coord, valid_loss1, valid_loss2, valid_loss3):\n min_length = min(len(valid_loss1), len(valid_loss2), len(valid_loss3))\n concat_lists = np.array([valid_loss1[:min_length], valid_loss2[:min_length], valid_loss3[:min_length]])\n st_dev_list = np.std(concat_lists, 0)\n mean_list = np.mean(concat_lists, 0)\n return x_coord[:min_length], mean_list, st_dev_list",
"_____no_output_____"
],
[
"result_dir = os.path.join(os.getcwd(), \"results\", experiment_name[1])",
"_____no_output_____"
],
[
"results = []\nfor exp_id in range(1,4):\n with open(os.path.join(result_dir,'results_' \n + str(exp_id) + '.pkl'), 'rb') as f:\n results.append(pickle.load(f))",
"_____no_output_____"
]
],
[
[
"### Reconstruction Loss",
"_____no_output_____"
]
],
[
[
"all_train_loss, all_valid_loss = load_all_losses(results[1])",
"_____no_output_____"
],
[
"plt.plot(all_train_loss, label=\"train\")\nplt.plot(all_valid_loss, label=\"valid\")\nplt.title(\"reconstruction loss\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Reconstruction Loss log scale",
"_____no_output_____"
]
],
[
[
"plt.yscale(\"log\")\nplt.plot(all_train_loss, label=\"train\")\nplt.plot(all_valid_loss, label=\"valid\")\nplt.title(\"reconstruction loss log scale\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Reconstruction Loss with std deviation",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(6,4), dpi=200)\n\nfor exp in experiment_name:\n results = []\n all_exp_losses = []\n result_dir = os.path.join(os.getcwd(), \"results\", exp)\n \n for exp_id in range(1,4):\n with open(os.path.join(result_dir,'results_' \n + str(exp_id) + '.pkl'), 'rb') as f:\n results.append(pickle.load(f))\n \n for exp_id in range(3):\n all_exp_losses.append(load_all_losses(results[exp_id]))\n \n exp_id =0\n valid_loss1 = all_exp_losses[exp_id][1]\n valid_loss2 = all_exp_losses[exp_id+1][1]\n valid_loss3 = all_exp_losses[exp_id+2][1]\n x_coord = [epoch_length(exp_id)*i for i in range(len(valid_loss1))]\n x_coord_tube, mean_list, st_dev_list = get_tube(x_coord, valid_loss1, valid_loss2, valid_loss3)\n plt.fill_between(x_coord_tube, mean_list - st_dev_list, mean_list + st_dev_list, alpha=.2)\n label = list(results[exp_id]['config']['model'].keys())[0] \\\n + \" with \" + str(results[exp_id]['n_envs_in_split']['train']) + \" envs\"\n plt.plot(x_coord_tube, mean_list, label=label)\nplt.title(\"reconstruction losses\")\n#plt.yscale(\"log\")\n#plt.xlim((0,3000000))\nplt.legend()\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbd7f330226f1668abb725ab34a53e51ed8b3a3a
| 68,714 |
ipynb
|
Jupyter Notebook
|
Collaborative Filtering.ipynb
|
Adi8885/RecommenderSystems
|
0ab3df3ef5a22f0bf63e1f94aae0affbcd6d4dba
|
[
"MIT"
] | null | null | null |
Collaborative Filtering.ipynb
|
Adi8885/RecommenderSystems
|
0ab3df3ef5a22f0bf63e1f94aae0affbcd6d4dba
|
[
"MIT"
] | null | null | null |
Collaborative Filtering.ipynb
|
Adi8885/RecommenderSystems
|
0ab3df3ef5a22f0bf63e1f94aae0affbcd6d4dba
|
[
"MIT"
] | null | null | null | 39.310069 | 174 | 0.486931 |
[
[
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.autograd.variable as Variable\nimport torch.utils.data as data\nimport torchvision\nfrom torchvision import transforms",
"_____no_output_____"
],
[
"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import sparse\nimport lightfm\n\n%matplotlib inline",
"c:\\python\\python37\\lib\\site-packages\\lightfm\\_lightfm_fast.py:9: UserWarning: LightFM was compiled without OpenMP support. Only a single thread will be used.\n warnings.warn('LightFM was compiled without OpenMP support. '\n"
],
[
"filepath = 'D:/Data_Science/Recommender systems/the-movies-dataset/'\nfilename = 'movies.csv'\ndata_movie_names = pd.read_csv(filepath + filename)\ndata_movie_names = data_movie_names[['movieId','title']]\ndata_movie_names.head()",
"_____no_output_____"
],
[
"movie_names_dict = data_movie_names.set_index('movieId').to_dict()['title']\nmovie_names_dict",
"_____no_output_____"
],
[
"filepath = 'D:/Data_Science/Recommender systems/the-movies-dataset/'\nfilename = 'ratings_small.csv'\ndata = pd.read_csv(filepath + filename)\ndata.head()",
"_____no_output_____"
],
[
"data.shape",
"_____no_output_____"
],
[
"#make interaction dictionary\n\ninteraction_dict = {}\ncid_to_idx = {}\nidx_to_cid = {}\nuid_to_idx ={}\nidx_to_uid = {}\ncidx = 0\nuidx = 0\n\ninput_file = filepath + filename\nwith open(input_file) as fp:\n next(fp)\n for line in fp:\n row = line.split(',') \n uid = int(row[0])\n cid = int(row[1])\n rating = float(row[2])\n if uid_to_idx.get(uid) == None :\n uid_to_idx[uid] = uidx\n idx_to_uid[uidx] = uid\n interaction_dict[uid] = {}\n uidx+=1\n \n if cid_to_idx.get(cid) == None :\n cid_to_idx[cid] = cidx\n idx_to_cid[cidx] = cid\n cidx+=1\n \n interaction_dict[uid][cid] = rating\n\nfp.close()",
"_____no_output_____"
],
[
"print(\"unique users : {}\".format(data.userId.nunique()))\nprint(\"unique movies : {}\".format(data.movieId.nunique()))",
"unique users : 671\nunique movies : 9066\n"
],
[
"#interaction_dict",
"_____no_output_____"
],
[
"row = []\ncolumn = []\ndata_1 = []\n\nfor uid in interaction_dict.keys():\n for cid in interaction_dict[uid].keys():\n row.append(cid_to_idx[cid])\n column.append(uid_to_idx[uid])\n data_1.append(interaction_dict[uid][cid])",
"_____no_output_____"
],
[
"item_user_data = sparse.csr_matrix((data_1,(column,row)))\nitem_user_data",
"_____no_output_____"
],
[
"item_user_data.shape",
"_____no_output_____"
],
[
"torch.tensor(item_user_data[0].todense())[0]",
"_____no_output_____"
],
[
"input_dim = len(cid_to_idx)\nh_layer_2 = int(round(len(cid_to_idx) / 4))\nh_layer_3 = int(round(h_layer_2 / 4))\nh_layer_3",
"_____no_output_____"
],
[
"class AutoEncoder(nn.Module):\n def __init__(self): #Class contructor\n super(AutoEncoder,self).__init__() #Caal parent constructor\n self.fc1 = nn.Linear(in_features = input_dim , out_features = h_layer_2) #out_features = size of output tensor. This is rank1 tensor\n self.fc2 = nn.Linear(in_features = h_layer_2 , out_features = h_layer_3)\n self.fc3 = nn.Linear(in_features = h_layer_3 , out_features = h_layer_2)\n self.out = nn.Linear(in_features = h_layer_2 , out_features = input_dim)\n \n def forward(self,t):\n #implement forward pass\n \n #1. Input layer \n t = self.fc1(t)\n t = F.relu(t)\n \n #2. Hidden Linear Layer\n t = self.fc2(t)\n t = F.relu(t)\n \n #3. Hidden Linear Layer\n t = self.fc3(t)\n t = F.relu(t)\n \n #3. Output layer\n t = self.out(t)\n t = F.relu(t)\n \n return t",
"_____no_output_____"
],
[
"self_ae = AutoEncoder() #Runs the class contructor\nself_ae.double().cuda()",
"_____no_output_____"
],
[
"#torchvision.datasets.DatasetFolder('')\n#train_data_loader = data.DataLoader(item_user_data, 256)",
"_____no_output_____"
],
[
"#next(iter(train_data_loader))",
"_____no_output_____"
],
[
"#item_user_data[batch]",
"_____no_output_____"
],
[
"learning_rate = 0.001\noptimizer = torch.optim.Adam(self_ae.parameters(), lr=learning_rate)\ncriterion = F.mse_loss\nepochs = 10\n\nfor epoch in range(1,epochs):\n for batch in range(0,item_user_data.shape[0]):\n if batch % 100 == 0:\n print('processing epoch :{} , batch : {}'.format(epoch , batch+1))\n inputs = torch.tensor(np.array(item_user_data[batch].todense())[0])\n inputs = inputs.cuda()\n target = inputs\n # zero the parameter gradients\n optimizer.zero_grad()\n y_pred = self_ae(inputs.double())\n loss = criterion(y_pred, target)\n loss.backward()\n optimizer.step()\n print(\"epoch : {}\\t batch : {}\\t loss : {}\".format(epoch,batch+1,loss.item()))\n torch.save(self_ae.state_dict(), ('model'+str(epoch)))\n \ntorch.save(self_ae.state_dict(), 'model.final')",
"processing epoch :1 , batch : 1\nprocessing epoch :1 , batch : 101\nprocessing epoch :1 , batch : 201\nprocessing epoch :1 , batch : 301\nprocessing epoch :1 , batch : 401\nprocessing epoch :1 , batch : 501\nprocessing epoch :1 , batch : 601\nepoch : 1\t batch : 671\t loss : 0.18930687729219048\nprocessing epoch :2 , batch : 1\nprocessing epoch :2 , batch : 101\nprocessing epoch :2 , batch : 201\nprocessing epoch :2 , batch : 301\nprocessing epoch :2 , batch : 401\nprocessing epoch :2 , batch : 501\nprocessing epoch :2 , batch : 601\nepoch : 2\t batch : 671\t loss : 0.17599580324836142\nprocessing epoch :3 , batch : 1\nprocessing epoch :3 , batch : 101\nprocessing epoch :3 , batch : 201\nprocessing epoch :3 , batch : 301\nprocessing epoch :3 , batch : 401\nprocessing epoch :3 , batch : 501\nprocessing epoch :3 , batch : 601\nepoch : 3\t batch : 671\t loss : 0.16079334422014396\nprocessing epoch :4 , batch : 1\nprocessing epoch :4 , batch : 101\nprocessing epoch :4 , batch : 201\nprocessing epoch :4 , batch : 301\nprocessing epoch :4 , batch : 401\nprocessing epoch :4 , batch : 501\nprocessing epoch :4 , batch : 601\nepoch : 4\t batch : 671\t loss : 0.1599691675068887\nprocessing epoch :5 , batch : 1\nprocessing epoch :5 , batch : 101\nprocessing epoch :5 , batch : 201\nprocessing epoch :5 , batch : 301\nprocessing epoch :5 , batch : 401\nprocessing epoch :5 , batch : 501\nprocessing epoch :5 , batch : 601\nepoch : 5\t batch : 671\t loss : 0.16615026283120088\nprocessing epoch :6 , batch : 1\nprocessing epoch :6 , batch : 101\nprocessing epoch :6 , batch : 201\nprocessing epoch :6 , batch : 301\nprocessing epoch :6 , batch : 401\nprocessing epoch :6 , batch : 501\nprocessing epoch :6 , batch : 601\nepoch : 6\t batch : 671\t loss : 0.15816243276791184\nprocessing epoch :7 , batch : 1\nprocessing epoch :7 , batch : 101\nprocessing epoch :7 , batch : 201\nprocessing epoch :7 , batch : 301\nprocessing epoch :7 , batch : 401\nprocessing epoch :7 , batch : 501\nprocessing epoch :7 , batch : 601\nepoch : 7\t batch : 671\t loss : 0.16822628104517304\nprocessing epoch :8 , batch : 1\nprocessing epoch :8 , batch : 101\nprocessing epoch :8 , batch : 201\nprocessing epoch :8 , batch : 301\nprocessing epoch :8 , batch : 401\nprocessing epoch :8 , batch : 501\nprocessing epoch :8 , batch : 601\nepoch : 8\t batch : 671\t loss : 0.15829044630762978\nprocessing epoch :9 , batch : 1\nprocessing epoch :9 , batch : 101\nprocessing epoch :9 , batch : 201\nprocessing epoch :9 , batch : 301\nprocessing epoch :9 , batch : 401\nprocessing epoch :9 , batch : 501\nprocessing epoch :9 , batch : 601\nepoch : 9\t batch : 671\t loss : 0.14542658786504323\n"
],
[
"self_ae.eval().cpu()",
"_____no_output_____"
],
[
"idx = uid_to_idx[24]\ninputs = np.array(item_user_data[idx].todense())[0]\nwatched_movie_idx = np.argsort(inputs)[-10:][::-1]\ninputs = torch.tensor(inputs)\n\n\nprint('WATCHED MOVIES :')\nfor i in watched_movie_idx:\n movie_id = idx_to_cid[i]\n try :\n name = movie_names_dict[movie_id]\n except :\n name = 'unknown'\n print('index : {}\\t id : {}\\t name : {}'.format(i,movie_id,name))\n \ny_pred = self_ae(inputs)\ny_pred = y_pred.detach().numpy()\npred_idx = np.argsort(y_pred)[-10:][::-1]\n \nprint('PREDICTED MOVIES')\nfor i in pred_idx: #reverse list\n movid_id = idx_to_cid[i]\n try :\n name = movie_names_dict[movid_id]\n except :\n name = 'unknown'\n print('index : {}\\t id : {}\\t name : {}'.format(i,movid_id,name))",
"WATCHED MOVIES :\nindex : 49\t id : 296\t name : Pulp Fiction (1994)\nindex : 652\t id : 6\t name : Heat (1995)\nindex : 57\t id : 356\t name : Forrest Gump (1994)\nindex : 69\t id : 457\t name : Fugitive, The (1993)\nindex : 433\t id : 786\t name : Eraser (1996)\nindex : 432\t id : 780\t name : Independence Day (a.k.a. ID4) (1996)\nindex : 32\t id : 165\t name : Die Hard: With a Vengeance (1995)\nindex : 146\t id : 380\t name : True Lies (1994)\nindex : 2067\t id : 81\t name : Things to Do in Denver When You're Dead (1995)\nindex : 90\t id : 590\t name : Dances with Wolves (1990)\nPREDICTED MOVIES\nindex : 29\t id : 150\t name : Apollo 13 (1995)\nindex : 99\t id : 318\t name : Shawshank Redemption, The (1994)\nindex : 92\t id : 593\t name : Silence of the Lambs, The (1991)\nindex : 57\t id : 356\t name : Forrest Gump (1994)\nindex : 49\t id : 296\t name : Pulp Fiction (1994)\nindex : 72\t id : 480\t name : Jurassic Park (1993)\nindex : 69\t id : 457\t name : Fugitive, The (1993)\nindex : 323\t id : 344\t name : Ace Ventura: Pet Detective (1994)\nindex : 90\t id : 590\t name : Dances with Wolves (1990)\nindex : 88\t id : 588\t name : Aladdin (1992)\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd7f600302259942c1dd50f79366fefa6c59758
| 8,772 |
ipynb
|
Jupyter Notebook
|
message_reader.ipynb
|
jarrettdev/YT-Livechat-Bot
|
92c7fdbbc6599b8e5d4822c2cd5273d811b4b1a3
|
[
"MIT"
] | null | null | null |
message_reader.ipynb
|
jarrettdev/YT-Livechat-Bot
|
92c7fdbbc6599b8e5d4822c2cd5273d811b4b1a3
|
[
"MIT"
] | null | null | null |
message_reader.ipynb
|
jarrettdev/YT-Livechat-Bot
|
92c7fdbbc6599b8e5d4822c2cd5273d811b4b1a3
|
[
"MIT"
] | null | null | null | 34.671937 | 138 | 0.515846 |
[
[
[
"#\n# This small example shows you how to access JS-based requests via Selenium\n# Like this, one can access raw data for scraping, \n# for example on many JS-intensive/React-based websites\n#\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.common.exceptions import ElementClickInterceptedException\nfrom selenium.common.exceptions import ElementNotInteractableException\nfrom selenium.common.exceptions import WebDriverException\nimport json\nfrom datetime import datetime\nimport pandas as pd",
"_____no_output_____"
],
[
"def process_browser_log_entry(entry):\n response = json.loads(entry['message'])['message']\n return response\n\ndef log_filter(log_):\n return (\n # is an actual response\n log_[\"method\"] == \"Network.responseReceived\"\n # and json\n and \"json\" in log_[\"params\"][\"response\"][\"mimeType\"]\n )",
"_____no_output_____"
],
[
"def init_page():\n #fetch a site that does xhr requests\n driver.get(\"https://www.youtube.com/watch?v=DWcJFNfaw9c\")\n\n main_content_wait = WebDriverWait(driver, 20).until(\n EC.presence_of_element_located((By.XPATH, '//iframe[@id=\"chatframe\"]'))\n )\n time.sleep(3)\n video_box = driver.find_element_by_xpath('//div[@id=\"movie_player\"]')\n video_box.click()\n\n frame = driver.find_elements_by_xpath('//iframe[@id=\"chatframe\"]')\n # switch the webdriver object to the iframe.\n driver.switch_to.frame(frame[0])\n\n try:\n #enable 'all' livechat\n try:\n driver.find_element_by_xpath('//div[@id=\"label-text\"][@class=\"style-scope yt-dropdown-menu\"]').click()\n except ElementNotInteractableException:\n init_page()\n time.sleep(2.1)\n driver.find_element_by_xpath('//a[@class=\"yt-simple-endpoint style-scope yt-dropdown-menu\"][@tabindex=\"-1\"]').click()\n except ElementClickInterceptedException:\n print('let\\'s try again...')\n init_page()",
"_____no_output_____"
],
[
"# make chrome log requests\ncapabilities = DesiredCapabilities.CHROME\ncapabilities[\"goog:loggingPrefs\"] = {\"performance\": \"ALL\"} # newer: goog:loggingPrefs\ndriver = webdriver.Chrome(\n desired_capabilities=capabilities\n)",
"_____no_output_____"
],
[
"init_page()",
"_____no_output_____"
],
[
"iter_num = 0\nwhile True:\n iter_num += 1\n if iter_num >= 100:\n iter_num = 0\n init_page()\n # extract requests from logs\n logs_raw = driver.get_log(\"performance\")\n logs = [json.loads(lr[\"message\"])[\"message\"] for lr in logs_raw]\n\n json_list = []\n for log in filter(log_filter, logs):\n request_id = log[\"params\"][\"requestId\"]\n resp_url = log[\"params\"][\"response\"][\"url\"]\n #print(f\"Caught {resp_url}\")\n try:\n if 'https://www.youtube.com/youtubei/v1/live_chat/get_live_chat?key=' in resp_url:\n body = driver.execute_cdp_cmd(\"Network.getResponseBody\", {\"requestId\": request_id})\n json_list.append(body)\n except WebDriverException:\n print('web driver exception!!!')\n continue\n '''\n with open('look.txt', 'a', encoding='utf-8') as text_file:\n body = driver.execute_cdp_cmd(\"Network.getResponseBody\", {\"requestId\": request_id})\n text_file.write(str(body))\n json_list.append(body)\n '''\n\n #print(len(json_list))\n\n message_list = []\n self_message_list = []\n\n for i in range(len(json_list)):\n json_data = json.loads(json_list[i]['body'].replace('\\n','').strip())\n try:\n actions = (json_data['continuationContents']['liveChatContinuation']['actions'])\n except:\n continue\n for j in range(len(actions)):\n try:\n item = actions[j]['addChatItemAction']['item']['liveChatTextMessageRenderer']\n author_channel_id = item['authorExternalChannelId']\n author_name = item['authorName']['simpleText']\n text = item['message']['runs'][0]['text']\n post_time = item['timestampUsec']\n post_time = post_time[0:10]\n post_time = int(post_time)\n author_photo = item['authorPhoto']['thumbnails'][0]['url']\n post_time = datetime.utcfromtimestamp(post_time)\n\n post_item = {\n \"Author\" : author_name,\n \"Message\" : text,\n \"Date\" : post_time,\n \"Channel ID\" : author_channel_id,\n \"Channel\" : f'https://youtube.com/channel/{author_channel_id}'\n }\n message_list.append(post_item)\n if 'biss' in text.lower():\n self_message_list.append(post_item)\n #print(post_item)\n except Exception as e:\n print(str(e))\n continue\n\n #message_list = list(set(message_list))\n df = pd.DataFrame(message_list)\n df = df.drop_duplicates()\n #print(df)\n\n df.to_csv('./data/youtube_lofi/test_run.csv', index=False, mode='a')\n reply_df = pd.DataFrame(self_message_list)\n reply_df = reply_df.drop_duplicates()\n if len(self_message_list) > 0 :\n reply_df.to_csv('./data/youtube_lofi/reply_runs_cumulative.csv', index=False, mode='a')\n reply_df.to_csv('./data/youtube_lofi/reply_runs.csv', index=False, mode='a')\n if len(message_list) < 1:\n print('The world is ending!')\n time.sleep(30)",
"'addChatItemAction'\n'text'\n'liveChatTextMessageRenderer'\n'text'\n'addChatItemAction'\n'addChatItemAction'\n'addChatItemAction'\n'addChatItemAction'\n'text'\n'addChatItemAction'\n'addChatItemAction'\n'text'\n'text'\n'text'\n'text'\n'text'\n'addChatItemAction'\n'addChatItemAction'\n'text'\n'text'\n'text'\n'text'\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbd7f8f1a75999c777da2a0754bd37dbaf43d842
| 9,687 |
ipynb
|
Jupyter Notebook
|
tests/test_fft.ipynb
|
sajid-ali-nu/multislice
|
1e36e067ff53809f4cc6286562b221c4bddbcb60
|
[
"MIT"
] | 1 |
2019-01-12T22:41:21.000Z
|
2019-01-12T22:41:21.000Z
|
tests/test_fft.ipynb
|
s-sajid-ali/multislice
|
1e36e067ff53809f4cc6286562b221c4bddbcb60
|
[
"MIT"
] | null | null | null |
tests/test_fft.ipynb
|
s-sajid-ali/multislice
|
1e36e067ff53809f4cc6286562b221c4bddbcb60
|
[
"MIT"
] | null | null | null | 22.58042 | 185 | 0.523175 |
[
[
[
"Evaluating performance of FFT2 and IFFT2 and checking for accuracy. <br><br>\nNote that the ffts from fft_utils perform the transformation in place to save memory.<br><br>\nAs a rule of thumb, it's good to increase the number of threads as the size of the transform increases until one hits a limit <br><br>\npyFFTW uses lower memory and is slightly slower.(using icc to compile fftw might fix this, haven't tried it)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n#from multislice import fft_utils\nimport pyfftw,os\nimport scipy.fftpack as sfft",
"_____no_output_____"
],
[
"%load_ext memory_profiler\n%run obj_fft",
"_____no_output_____"
]
],
[
[
"Loading libraries and the profiler to be used",
"_____no_output_____"
]
],
[
[
"N = 15000 #size of transform\nt = 12 #number of threads.",
"_____no_output_____"
]
],
[
[
"Creating a test signal to perform on which we will perform 2D FFT ",
"_____no_output_____"
]
],
[
[
"a= np.random.random((N,N))+1j*np.random.random((N,N))\nprint('time for numpy forward')\n%timeit np.fft.fft2(a)\ndel(a)",
"time for numpy forward\n2.25 s ± 170 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('time for scipy forward')\n%timeit sfft.fft2(a,overwrite_x='True')\ndel(a)",
"time for scipy forward\n2.34 s ± 426 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nfft_obj = FFT_2d_Obj(np.shape(a),direction='FORWARD',flag='PATIENT',threads=t)\nprint('time for pyFFTW forward')\n%timeit fft_obj.run_fft2(a)\ndel(a)",
"time for pyFFTW forward\n3.19 s ± 447 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('Memory for numpy forward')\n%memit np.fft.fft2(a)\ndel(a)",
"Memory for numpy forward\npeak memory: 10442.64 MiB, increment: 3433.73 MiB\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('Memory for scipy forward')\n%memit sfft.fft2(a,overwrite_x='True')\ndel(a)",
"Memory for scipy forward\npeak memory: 10442.66 MiB, increment: 3433.24 MiB\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('Memory for pyFFTW forward')\n%memit fft_obj.run_fft2(a)\ndel(a)",
"Memory for pyFFTW forward\npeak memory: 7009.44 MiB, increment: 0.01 MiB\n"
]
],
[
[
"The results depend on how the libraries are complied. mkl linked scipy is fast but the fftw uses less memory. Also note that the fftw used in this test wasn't installed using icc.",
"_____no_output_____"
],
[
"Creating a test signal to perform on which we will perform 2D IFFT.",
"_____no_output_____"
]
],
[
[
"a= np.random.random((N,N))+1j*np.random.random((N,N))\nprint('time for numpy backward')\n%timeit np.fft.ifft2(a)\ndel(a)",
"time for numpy backward\n1.22 s ± 48.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('time for scipy backward')\n%timeit sfft.ifft2(a,overwrite_x='True')\ndel(a)",
"time for scipy backward\n1.25 s ± 41.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\ndel fft_obj\nfft_obj = FFT_2d_Obj(np.shape(a),direction='BACKWARD',flag='PATIENT',threads=t)\nprint('time for pyFFTW backward')\n%timeit fft_obj.run_ifft2(a)\ndel(a)",
"time for pyFFTW backward\n2.6 s ± 90.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('Memory for numpy forward')\n%memit np.fft.ifft2(a)\ndel(a)",
"Memory for numpy forward\npeak memory: 10442.72 MiB, increment: 3433.24 MiB\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('Memory for scipy forward')\n%memit sfft.ifft2(a,overwrite_x='True')\ndel(a)",
"Memory for scipy forward\npeak memory: 10442.72 MiB, increment: 3433.23 MiB\n"
],
[
"a = np.random.random((N,N))+1j*np.random.random((N,N))\nprint('Memory for pyFFTW backward')\n%memit fft_obj.run_ifft2(a)\ndel(a)",
"Memory for pyFFTW backward\npeak memory: 7009.49 MiB, increment: 0.00 MiB\n"
]
],
[
[
"The results depend on how the libraries are complied. mkl linked scipy is fast but the fftw uses less memory. Also note that the fftw used in this test wasn't installed using icc.",
"_____no_output_____"
],
[
"Testing for accuracy of 2D FFT: ",
"_____no_output_____"
]
],
[
[
"N = 5000\na = np.random.random((N,N)) + 1j*np.random.random((N,N))\nfft_obj = FFT_2d_Obj(np.shape(a),threads=t)\nA1 = np.fft.fft2(a)\nfft_obj.run_fft2(a)\nnp.allclose(A1,a)",
"_____no_output_____"
]
],
[
[
"Testing for accuracy of 2D IFFT: ",
"_____no_output_____"
]
],
[
[
"N = 5000\na = np.random.random((N,N)) + 1j*np.random.random((N,N))\nA1 = np.fft.ifft2(a)\nfft_obj.run_ifft2(a)\nnp.allclose(A1,a)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.